Merge pull request #15422 from artfulrobot/queue-parallel
[civicrm-core.git] / tests / phpunit / CRM / Utils / JSTest.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 * Tests for linking to resource files
14 * @group headless
15 */
16 class CRM_Utils_JSTest extends CiviUnitTestCase {
17
18 /**
19 * @return array
20 */
21 public function translateExamples() {
22 $cases = [];
23 $cases[] = [
24 '',
25 [],
26 ];
27 // missing ts
28 $cases[] = [
29 'alert("Hello world")',
30 [],
31 ];
32 // basic function call
33 $cases[] = [
34 'alert(ts("Hello world"));',
35 ['Hello world'],
36 ];
37 // with arg
38 $cases[] = [
39 'alert(ts("Hello world", {1: "whiz"}));',
40 ['Hello world'],
41 ];
42 // not really ts()
43 $cases[] = [
44 'alert(clients("Hello world"));',
45 [],
46 ];
47 // not really ts()
48 $cases[] = [
49 'alert(clients("Hello world", {1: "whiz"}));',
50 [],
51 ];
52 // with arg
53 $cases[] = [
54 "\n" .
55 "public function whits() {\n" .
56 " for (a in b) {\n" .
57 " mitts(\"wallaby\", function(zoo) {\n" .
58 " alert(zoo + ts(\"Hello\"))\n" .
59 " });\n" .
60 " }\n" .
61 "}\n",
62 ['Hello'],
63 ];
64 // duplicate
65 $cases[] = [
66 'alert(ts("Hello world") + "-" + ts("Hello world"));',
67 ['Hello world'],
68 ];
69 // two strings, addition
70 $cases[] = [
71 'alert(ts("Hello world") + "-" + ts("How do you do?"));',
72 ['Hello world', 'How do you do?'],
73 ];
74 // two strings, separate calls
75 $cases[] = [
76 'alert(ts("Hello world");\nalert(ts("How do you do?"));',
77 ['Hello world', 'How do you do?'],
78 ];
79 $cases[] = [
80 'alert(ts(\'Single quoted\'));',
81 ['Single quoted'],
82 ];
83 // unclear string
84 $cases[] = [
85 'alert(ts(message));',
86 [],
87 ];
88 // ts() within a string
89 $cases[] = [
90 'alert(ts("Does the ts(\'example\') notation work?"));',
91 ['Does the ts(\'example\') notation work?'],
92 ];
93 return $cases;
94 }
95
96 /**
97 * @param string $jsCode
98 * @param array $expectedStrings
99 * @dataProvider translateExamples
100 */
101 public function testParseStrings($jsCode, $expectedStrings) {
102 $actualStrings = CRM_Utils_JS::parseStrings($jsCode);
103 sort($expectedStrings);
104 sort($actualStrings);
105 $this->assertEquals($expectedStrings, $actualStrings);
106 }
107
108 public function dedupeClosureExamples() {
109 // Each example string here is named for its body, eg the body of $a calls "a()".
110 $a = "(function (angular, $, _) {\na();\n})(angular, CRM.$, CRM._);";
111 $b = "(function(angular,$,_){\nb();\n})(angular,CRM.$,CRM._);";
112 $c = "(function( angular, $,_) {\nc();\n})(angular,CRM.$, CRM._);";
113 $d = "(function (angular, $, _, whiz) {\nd();\n})(angular, CRM.$, CRM._, CRM.whizbang);";
114 $m = "alert('i is the trickster (function( angular, $,_) {\nm();\n})(angular,CRM.$, CRM._);)'";
115 // Note: $d has a fundamentally different closure.
116
117 // Each example string here is a deduped combination of others,
118 // eg "$ab" is the deduping of $a+$b.
119 $ab = "(function (angular, $, _) {\na();\n\nb();\n})(angular,CRM.$,CRM._);";
120 $abc = "(function (angular, $, _) {\na();\n\nb();\n\nc();\n})(angular,CRM.$, CRM._);";
121 $cb = "(function( angular, $,_) {\nc();\n\nb();\n})(angular,CRM.$,CRM._);";
122
123 $cases = [];
124 $cases[] = [[$a], "$a"];
125 $cases[] = [[$b], "$b"];
126 $cases[] = [[$c], "$c"];
127 $cases[] = [[$d], "$d"];
128 $cases[] = [[$m], "$m"];
129 $cases[] = [[$a, $b], "$ab"];
130 $cases[] = [[$a, $m, $b], "$a$m$b"];
131 $cases[] = [[$a, $d], "$a$d"];
132 $cases[] = [[$a, $d, $b], "$a$d$b"];
133 $cases[] = [[$a, $b, $c], "$abc"];
134 $cases[] = [[$a, $b, $d, $c, $b], "$ab$d$cb"];
135 return $cases;
136 }
137
138 /**
139 * @param array $scripts
140 * @param string $expectedOutput
141 * @dataProvider dedupeClosureExamples
142 */
143 public function testDedupeClosure($scripts, $expectedOutput) {
144 $actualOutput = CRM_Utils_JS::dedupeClosures(
145 $scripts,
146 ['angular', '$', '_'],
147 ['angular', 'CRM.$', 'CRM._']
148 );
149 $this->assertEquals($expectedOutput, implode("", $actualOutput));
150 }
151
152 public function stripCommentsExamples() {
153 $cases = [];
154 $cases[] = [
155 "a();\n//# sourceMappingURL=../foo/bar/baz.js\nb();",
156 "a();\n\nb();",
157 ];
158 $cases[] = [
159 "// foo\na();",
160 "\na();",
161 ];
162 $cases[] = [
163 "b();\n // foo",
164 "b();\n",
165 ];
166 $cases[] = [
167 "/// foo\na();\n\t \t//bar\nb();\n// whiz",
168 "\na();\n\nb();\n",
169 ];
170 $cases[] = [
171 "alert('//# sourceMappingURL=../foo/bar/baz.js');\n//zoop\na();",
172 "alert('//# sourceMappingURL=../foo/bar/baz.js');\n\na();",
173 ];
174 return $cases;
175 }
176
177 /**
178 * @param string $input
179 * @param string $expectedOutput
180 * @dataProvider stripCommentsExamples
181 */
182 public function testStripComments($input, $expectedOutput) {
183 $this->assertEquals($expectedOutput, CRM_Utils_JS::stripComments($input));
184 }
185
186 public static function decodeExamples() {
187 return [
188 ['{a: \'Apple\', \'b\': "Banana", c: [1, 2, 3]}', ['a' => 'Apple', 'b' => 'Banana', 'c' => [1, 2, 3]]],
189 ['true', TRUE],
190 [' ', NULL],
191 ['false', FALSE],
192 ['null', NULL],
193 ['"true"', 'true'],
194 ['0.5', 0.5],
195 [" {}", []],
196 ["[]", []],
197 ["{ }", []],
198 [" [ ]", []],
199 [" [ 2 ]", [2]],
200 [
201 '{a: "parse error no closing bracket"',
202 NULL,
203 ],
204 [
205 '{a: ["foo", \'bar\'], "b": {a: [\'foo\', "bar"], b: {\'a\': ["foo", "bar"], b: {}}}}',
206 ['a' => ['foo', 'bar'], 'b' => ['a' => ['foo', 'bar'], 'b' => ['a' => ['foo', 'bar'], 'b' => []]]],
207 ],
208 [
209 ' [{a: {aa: true}, b: [false, null, {x: 1, y: 2, z: 3}] , "c": -1}, ["fee", "fie", \'foe\']]',
210 [['a' => ['aa' => TRUE], 'b' => [FALSE, NULL, ['x' => 1, 'y' => 2, 'z' => 3]], "c" => -1], ["fee", "fie", "foe"]],
211 ],
212 ];
213 }
214
215 /**
216 * @param string $input
217 * @param string $expectedOutput
218 * @dataProvider decodeExamples
219 */
220 public function testDecode($input, $expectedOutput) {
221 $this->assertEquals($expectedOutput, CRM_Utils_JS::decode($input));
222 }
223
224 public static function encodeExamples() {
225 return [
226 [
227 ['a' => 'Apple', 'b' => 'Banana', 'c' => [0, -2, 3.15]],
228 "{a: 'Apple', b: 'Banana', c: [0, -2, 3.15]}",
229 ],
230 [
231 ['a' => ['foo', 'bar'], 'b' => ["'a'" => ['foo/bar&', 'bar(foo)'], 'b' => ['a' => ["fo\\\\'oo", '"bar"'], 'b' => []]]],
232 "{a: ['foo', 'bar'], b: {\"'a'\": ['foo/bar&', 'bar(foo)'], b: {a: ['fo\\\\\\\\\\'oo', '\"bar\"'], b: {}}}}",
233 ],
234 [TRUE, 'true'],
235 [' ', "' '"],
236 [FALSE, 'false'],
237 [NULL, 'null'],
238 ['true', "'true'"],
239 ['"false"', "'\"false\"'"],
240 ['0.5', "'0.5'"],
241 [0.5, '0.5'],
242 [[], "{}"],
243 ];
244 }
245
246 /**
247 * @param string $input
248 * @param string $expectedOutput
249 * @dataProvider encodeExamples
250 */
251 public function testEncode($input, $expectedOutput) {
252 $result = CRM_Utils_JS::encode($input);
253 $this->assertEquals($expectedOutput, $result);
254 $this->assertEquals($input, CRM_Utils_JS::decode($result));
255 }
256
257 /**
258 * @return array
259 */
260 public static function objectExamples() {
261 return [
262 [
263 '{a: \'Apple\', \'b\': "Banana", "c ": [1,2,3]}',
264 ['a' => "'Apple'", 'b' => '"Banana"', 'c ' => '[1,2,3]'],
265 '{a: \'Apple\', b: "Banana", \'c \': [1,2,3]}',
266 ],
267 [
268 " {}",
269 [],
270 "{}",
271 ],
272 [
273 " [ ] ",
274 [],
275 "{}",
276 ],
277 [
278 " {'fn' : function (foo, bar, baz) { return \"One, two, three\"; }, esc: /[1-9]\\\\/.test('5\\\\') , number : 55.5/2 } ",
279 ['fn' => 'function (foo, bar, baz) { return "One, two, three"; }', 'esc' => "/[1-9]\\\\/.test('5\\\\')", 'number' => '55.5/2'],
280 "{fn: function (foo, bar, baz) { return \"One, two, three\"; }, esc: /[1-9]\\\\/.test('5\\\\'), number: 55.5/2}",
281 ],
282 [
283 "{ string :
284 'this, has(some : weird, \\'stuff [{}!' ,
285 expr: sum(1, 2, 3) / 2 + 1, ' notes ' : [Do, re mi],
286 }",
287 ['string' => "'this, has(some : weird, \\'stuff [{}!'", 'expr' => 'sum(1, 2, 3) / 2 + 1', ' notes ' => "[Do, re mi]"],
288 "{string: 'this, has(some : weird, \\'stuff [{}!', expr: sum(1, 2, 3) / 2 + 1, ' notes ': [Do, re mi]}",
289 ],
290 [
291 '{status: /^http:\/\/civicrm\.com/.test(url) ? \'good\' : \'bad\' , \'foo\&\': getFoo("Some \"quoted\" thing"), "ba\'[(r": function() {return "bar"}}',
292 ['status' => '/^http:\/\/civicrm\.com/.test(url) ? \'good\' : \'bad\'', 'foo&' => 'getFoo("Some \"quoted\" thing")', "ba'[(r" => 'function() {return "bar"}'],
293 '{status: /^http:\/\/civicrm\.com/.test(url) ? \'good\' : \'bad\', "foo&": getFoo("Some \"quoted\" thing"), "ba\'[(r": function() {return "bar"}}',
294 ],
295 [
296 '{"some\"key": typeof foo === \'number\' ? true : false , "O\'Really?": ",((,", \'A"quote"\': 1 + 1 , "\\\\\\&\\/" : 0}',
297 ['some"key' => 'typeof foo === \'number\' ? true : false', "O'Really?" => '",((,"', 'A"quote"' => '1 + 1', '\\&/' => '0'],
298 '{\'some"key\': typeof foo === \'number\' ? true : false, "O\'Really?": ",((,", \'A"quote"\': 1 + 1, "\\\\&/": 0}',
299 ],
300 [
301 '[foo ? 1 : 2 , 3 , function() {return 1 + 1;}, /^http:\/\/civicrm\.com/.test(url) ? \'good\' : \'bad\' , 3.14 ]',
302 ['foo ? 1 : 2', '3', 'function() {return 1 + 1;}', '/^http:\/\/civicrm\.com/.test(url) ? \'good\' : \'bad\'', '3.14'],
303 '[foo ? 1 : 2, 3, function() {return 1 + 1;}, /^http:\/\/civicrm\.com/.test(url) ? \'good\' : \'bad\', 3.14]',
304 ],
305 ];
306 }
307
308 /**
309 * Test converting a js string to a php array and back again.
310 *
311 * @param string $input
312 * @param string $expectedPHP
313 * @param $expectedJS
314 * @dataProvider objectExamples
315 */
316 public function testObjectToAndFromString($input, $expectedPHP, $expectedJS) {
317 $objectProps = CRM_Utils_JS::getRawProps($input);
318 $this->assertEquals($expectedPHP, $objectProps);
319 $reformattedJS = CRM_Utils_JS::writeObject($objectProps);
320 $this->assertEquals($expectedJS, $reformattedJS);
321 $this->assertEquals($expectedPHP, CRM_Utils_JS::getRawProps($reformattedJS));
322 }
323
324 }