]> jfr.im git - yt-dlp.git/blame - test/test_jsinterp.py
[cleanup] Misc
[yt-dlp.git] / test / test_jsinterp.py
CommitLineData
cc52de43 1#!/usr/bin/env python3
54007a45 2
9e3f1991
PH
3# Allow direct execution
4import os
5import sys
6import unittest
f8271158 7
9e3f1991
PH
8sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
9
be13a6e5 10import math
54007a45 11
be13a6e5 12from yt_dlp.jsinterp import JS_Undefined, JSInterpreter
9e3f1991
PH
13
14
ad54c913 15class NaN:
16 pass
17
18
9e3f1991 19class TestJSInterpreter(unittest.TestCase):
ad54c913 20 def _test(self, jsi_or_code, expected, func='f', args=()):
21 if isinstance(jsi_or_code, str):
22 jsi_or_code = JSInterpreter(jsi_or_code)
23 got = jsi_or_code.call_function(func, *args)
24 if expected is NaN:
25 self.assertTrue(math.isnan(got), f'{got} is not NaN')
26 else:
27 self.assertEqual(got, expected)
9e3f1991 28
6f2287cb 29 def test_basic(self):
30 jsi = JSInterpreter('function f(){;}')
31 self.assertEqual(repr(jsi.extract_function('f')), 'F<f>')
ad54c913 32 self._test(jsi, None)
8f53dc44 33
6f2287cb 34 self._test('function f(){return 42;}', 42)
35 self._test('function f(){42}', None)
36 self._test('var f = function(){return 42;}', 42)
ff29bf81 37
b4a252fb 38 def test_div(self):
39 jsi = JSInterpreter('function f(a, b){return a / b;}')
ad54c913 40 self._test(jsi, NaN, args=(0, 0))
41 self._test(jsi, NaN, args=(JS_Undefined, 1))
42 self._test(jsi, float('inf'), args=(2, 0))
43 self._test(jsi, 0, args=(0, 3))
44
45 def test_calc(self):
46 self._test('function f(a){return 2*a+1;}', 7, args=[3])
b4a252fb 47
9e3f1991 48 def test_empty_return(self):
6f2287cb 49 self._test('function f(){return; y()}', None)
9e3f1991
PH
50
51 def test_morespace(self):
6f2287cb 52 self._test('function f (a) { return 2 * a + 1 ; }', 7, args=[3])
53 self._test('function f () { x = 2 ; return x; }', 2)
9e3f1991
PH
54
55 def test_strange_chars(self):
6f2287cb 56 self._test('function $_xY1 ($_axY1) { var $_axY2 = $_axY1 + 1; return $_axY2; }',
57 21, args=[20], func='$_xY1')
9e3f1991
PH
58
59 def test_operators(self):
6f2287cb 60 self._test('function f(){return 1 << 5;}', 32)
61 self._test('function f(){return 2 ** 5}', 32)
62 self._test('function f(){return 19 & 21;}', 17)
63 self._test('function f(){return 11 >> 2;}', 2)
64 self._test('function f(){return []? 2+3: 4;}', 5)
65 self._test('function f(){return 1 == 2}', False)
66 self._test('function f(){return 0 && 1 || 2;}', 2)
67 self._test('function f(){return 0 ?? 42;}', 0)
68 self._test('function f(){return "life, the universe and everything" < 42;}', False)
1ac7f461 69
9e3f1991 70 def test_array_access(self):
6f2287cb 71 self._test('function f(){var x = [1,2,3]; x[0] = 4; x[0] = 5; x[2.0] = 7; return x;}', [5, 2, 7])
9e3f1991
PH
72
73 def test_parens(self):
6f2287cb 74 self._test('function f(){return (1) + (2) * ((( (( (((((3)))))) )) ));}', 7)
75 self._test('function f(){return (1 + 2) * 3;}', 9)
9e3f1991 76
8f53dc44 77 def test_quotes(self):
6f2287cb 78 self._test(R'function f(){return "a\"\\("}', R'a"\(')
8f53dc44 79
9e3f1991 80 def test_assignments(self):
6f2287cb 81 self._test('function f(){var x = 20; x = 30 + 1; return x;}', 31)
82 self._test('function f(){var x = 20; x += 30 + 1; return x;}', 51)
83 self._test('function f(){var x = 20; x -= 30 + 1; return x;}', -11)
9e3f1991 84
4823ec9f 85 @unittest.skip('Not implemented')
9e3f1991 86 def test_comments(self):
6f2287cb 87 self._test('''
88 function f() {
89 var x = /* 1 + */ 2;
90 var y = /* 30
91 * 40 */ 50;
92 return x + y;
93 }
94 ''', 52)
95
96 self._test('''
97 function f() {
98 var x = "/*";
99 var y = 1 /* comment */ + 2;
100 return y;
101 }
102 ''', 3)
3eff81fb 103
9e3f1991 104 def test_precedence(self):
6f2287cb 105 self._test('''
106 function f() {
107 var a = [10, 20, 30, 40, 50];
108 var b = 6;
109 a[0]=a[b%a.length];
110 return a;
111 }
112 ''', [20, 20, 30, 40, 50])
9e3f1991 113
49b4ceae 114 def test_builtins(self):
ad54c913 115 self._test('function f() { return NaN }', NaN)
d81ba7d4 116
4823ec9f 117 def test_date(self):
118 self._test('function f() { return new Date("Wednesday 31 December 1969 18:01:26 MDT") - 0; }', 86000)
119
120 jsi = JSInterpreter('function f(dt) { return new Date(dt) - 0; }')
ad54c913 121 self._test(jsi, 86000, args=['Wednesday 31 December 1969 18:01:26 MDT'])
122 self._test(jsi, 86000, args=['12/31/1969 18:01:26 MDT']) # m/d/y
123 self._test(jsi, 0, args=['1 January 1970 00:00:00 UTC'])
49b4ceae 124
189935f1
KM
125 def test_call(self):
126 jsi = JSInterpreter('''
6f2287cb 127 function x() { return 2; }
128 function y(a) { return x() + (a?a:0); }
129 function z() { return y(3); }
189935f1 130 ''')
ad54c913 131 self._test(jsi, 5, func='z')
132 self._test(jsi, 2, func='y')
9e3f1991 133
8b008d62 134 def test_if(self):
6f2287cb 135 self._test('''
136 function f() {
137 let a = 9;
138 if (0==0) {a++}
139 return a
140 }
141 ''', 10)
142
143 self._test('''
144 function f() {
145 if (0==0) {return 10}
146 }
147 ''', 10)
148
149 self._test('''
150 function f() {
151 if (0!=0) {return 1}
152 else {return 10}
153 }
154 ''', 10)
8b008d62 155
156 """ # Unsupported
6f2287cb 157 self._test('''
158 function f() {
159 if (0!=0) {return 1}
160 else if (1==0) {return 2}
161 else {return 10}
162 }
163 ''', 10)
8b008d62 164 """
165
404f611f 166 def test_for_loop(self):
6f2287cb 167 self._test('function f() { a=0; for (i=0; i-10; i++) {a++} return a }', 10)
404f611f 168
169 def test_switch(self):
170 jsi = JSInterpreter('''
6f2287cb 171 function f(x) { switch(x){
172 case 1:x+=1;
173 case 2:x+=2;
174 case 3:x+=3;break;
175 case 4:x+=4;
176 default:x=0;
177 } return x }
404f611f 178 ''')
ad54c913 179 self._test(jsi, 7, args=[1])
180 self._test(jsi, 6, args=[3])
181 self._test(jsi, 0, args=[5])
404f611f 182
a1fc7ca0 183 def test_switch_default(self):
184 jsi = JSInterpreter('''
6f2287cb 185 function f(x) { switch(x){
186 case 2: x+=2;
187 default: x-=1;
188 case 5:
189 case 6: x+=6;
190 case 0: break;
191 case 1: x+=1;
192 } return x }
a1fc7ca0 193 ''')
ad54c913 194 self._test(jsi, 2, args=[1])
195 self._test(jsi, 11, args=[5])
196 self._test(jsi, 14, args=[9])
a1fc7ca0 197
404f611f 198 def test_try(self):
6f2287cb 199 self._test('function f() { try{return 10} catch(e){return 5} }', 10)
404f611f 200
1ac7f461 201 def test_catch(self):
6f2287cb 202 self._test('function f() { try{throw 10} catch(e){return 5} }', 5)
1ac7f461 203
204 def test_finally(self):
6f2287cb 205 self._test('function f() { try{throw 10} finally {return 42} }', 42)
206 self._test('function f() { try{throw 10} catch(e){return 5} finally {return 42} }', 42)
1ac7f461 207
208 def test_nested_try(self):
6f2287cb 209 self._test('''
210 function f() {try {
211 try{throw 10} finally {throw 42}
212 } catch(e){return 5} }
213 ''', 5)
1ac7f461 214
404f611f 215 def test_for_loop_continue(self):
6f2287cb 216 self._test('function f() { a=0; for (i=0; i-10; i++) { continue; a++ } return a }', 0)
404f611f 217
218 def test_for_loop_break(self):
6f2287cb 219 self._test('function f() { a=0; for (i=0; i-10; i++) { break; a++ } return a }', 0)
404f611f 220
1ac7f461 221 def test_for_loop_try(self):
6f2287cb 222 self._test('''
223 function f() {
224 for (i=0; i-10; i++) { try { if (i == 5) throw i} catch {return 10} finally {break} };
225 return 42 }
226 ''', 42)
1ac7f461 227
404f611f 228 def test_literal_list(self):
6f2287cb 229 self._test('function f() { return [1, 2, "asdf", [5, 6, 7]][3] }', [5, 6, 7])
404f611f 230
231 def test_comma(self):
6f2287cb 232 self._test('function f() { a=5; a -= 1, a+=3; return a }', 7)
233 self._test('function f() { a=5; return (a -= 1, a+=3, a); }', 7)
234 self._test('function f() { return (l=[0,1,2,3], function(a, b){return a+b})((l[1], l[2]), l[3]) }', 5)
6d3e7424 235
49b4ceae 236 def test_void(self):
6f2287cb 237 self._test('function f() { return void 42; }', None)
49b4ceae 238
8f53dc44 239 def test_return_function(self):
240 jsi = JSInterpreter('''
6f2287cb 241 function f() { return [1, function(){return 1}][1] }
8f53dc44 242 ''')
6f2287cb 243 self.assertEqual(jsi.call_function('f')([]), 1)
8f53dc44 244
be13a6e5 245 def test_null(self):
6f2287cb 246 self._test('function f() { return null; }', None)
247 self._test('function f() { return [null > 0, null < 0, null == 0, null === 0]; }',
248 [False, False, False, False])
249 self._test('function f() { return [null >= 0, null <= 0]; }', [True, True])
be13a6e5 250
251 def test_undefined(self):
6f2287cb 252 self._test('function f() { return undefined === undefined; }', True)
253 self._test('function f() { return undefined; }', JS_Undefined)
254 self._test('function f() {return undefined ?? 42; }', 42)
255 self._test('function f() { let v; return v; }', JS_Undefined)
256 self._test('function f() { let v; return v**0; }', 1)
257 self._test('function f() { let v; return [v>42, v<=42, v&&42, 42&&v]; }',
258 [False, False, JS_Undefined, JS_Undefined])
259
260 self._test('''
261 function f() { return [
262 undefined === undefined,
263 undefined == undefined,
264 undefined == null,
265 undefined < undefined,
266 undefined > undefined,
267 undefined === 0,
268 undefined == 0,
269 undefined < 0,
270 undefined > 0,
271 undefined >= 0,
272 undefined <= 0,
273 undefined > null,
274 undefined < null,
275 undefined === null
276 ]; }
277 ''', list(map(bool, (1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))))
278
279 jsi = JSInterpreter('''
280 function f() { let v; return [42+v, v+42, v**42, 42**v, 0**v]; }
281 ''')
282 for y in jsi.call_function('f'):
be13a6e5 283 self.assertTrue(math.isnan(y))
284
be13a6e5 285 def test_object(self):
6f2287cb 286 self._test('function f() { return {}; }', {})
287 self._test('function f() { let a = {m1: 42, m2: 0 }; return [a["m1"], a.m2]; }', [42, 0])
288 self._test('function f() { let a; return a?.qq; }', JS_Undefined)
289 self._test('function f() { let a = {m1: 42, m2: 0 }; return a?.qq; }', JS_Undefined)
be13a6e5 290
291 def test_regex(self):
6f2287cb 292 self._test('function f() { let a=/,,[/,913,/](,)}/; }', None)
7aeda6cc 293 self._test('function f() { let a=/,,[/,913,/](,)}/; return a; }', R'/,,[/,913,/](,)}/0')
be13a6e5 294
7aeda6cc 295 R''' # We are not compiling regex
6f2287cb 296 jsi = JSInterpreter('function f() { let a=/,,[/,913,/](,)}/; return a; }')
297 self.assertIsInstance(jsi.call_function('f'), re.Pattern)
be13a6e5 298
6f2287cb 299 jsi = JSInterpreter('function f() { let a=/,,[/,913,/](,)}/i; return a; }')
300 self.assertEqual(jsi.call_function('f').flags & re.I, re.I)
be13a6e5 301
6f2287cb 302 jsi = JSInterpreter(R'function f() { let a=/,][}",],()}(\[)/; return a; }')
303 self.assertEqual(jsi.call_function('f').pattern, r',][}",],()}(\[)')
05deb747 304
6f2287cb 305 jsi = JSInterpreter(R'function f() { let a=[/[)\\]/]; return a[0]; }')
306 self.assertEqual(jsi.call_function('f').pattern, r'[)\\]')
7aeda6cc 307 '''
0468a3b3 308
4823ec9f 309 @unittest.skip('Not implemented')
310 def test_replace(self):
311 self._test('function f() { let a="data-name".replace("data-", ""); return a }',
312 'name')
313 self._test('function f() { let a="data-name".replace(new RegExp("^.+-"), ""); return a; }',
314 'name')
315 self._test('function f() { let a="data-name".replace(/^.+-/, ""); return a; }',
316 'name')
317 self._test('function f() { let a="data-name".replace(/a/g, "o"); return a; }',
318 'doto-nome')
319 self._test('function f() { let a="data-name".replaceAll("a", "o"); return a; }',
320 'doto-nome')
321
f26af78a 322 def test_char_code_at(self):
6f2287cb 323 jsi = JSInterpreter('function f(i){return "test".charCodeAt(i)}')
ad54c913 324 self._test(jsi, 116, args=[0])
325 self._test(jsi, 101, args=[1])
326 self._test(jsi, 115, args=[2])
327 self._test(jsi, 116, args=[3])
328 self._test(jsi, None, args=[4])
329 self._test(jsi, 116, args=['not_a_number'])
f26af78a
E
330
331 def test_bitwise_operators_overflow(self):
6f2287cb 332 self._test('function f(){return -524999584 << 5}', 379882496)
333 self._test('function f(){return 1236566549 << 5}', 915423904)
f26af78a 334
1d765618 335 def test_bitwise_operators_typecast(self):
6f2287cb 336 self._test('function f(){return null << 5}', 0)
337 self._test('function f(){return undefined >> 5}', 0)
338 self._test('function f(){return 42 << NaN}', 42)
1d765618 339
7cf51f21 340 def test_negative(self):
6f2287cb 341 self._test('function f(){return 2 * -2.0 ;}', -4)
342 self._test('function f(){return 2 - - -2 ;}', 0)
343 self._test('function f(){return 2 - - - -2 ;}', 4)
344 self._test('function f(){return 2 - + + - -2;}', 0)
345 self._test('function f(){return 2 + - + - -2;}', 0)
7cf51f21 346
4823ec9f 347 @unittest.skip('Not implemented')
348 def test_packed(self):
349 jsi = JSInterpreter('''function f(p,a,c,k,e,d){while(c--)if(k[c])p=p.replace(new RegExp('\\b'+c.toString(a)+'\\b','g'),k[c]);return p}''')
350 self.assertEqual(jsi.call_function('f', '''h 7=g("1j");7.7h({7g:[{33:"w://7f-7e-7d-7c.v.7b/7a/79/78/77/76.74?t=73&s=2s&e=72&f=2t&71=70.0.0.1&6z=6y&6x=6w"}],6v:"w://32.v.u/6u.31",16:"r%",15:"r%",6t:"6s",6r:"",6q:"l",6p:"l",6o:"6n",6m:\'6l\',6k:"6j",9:[{33:"/2u?b=6i&n=50&6h=w://32.v.u/6g.31",6f:"6e"}],1y:{6d:1,6c:\'#6b\',6a:\'#69\',68:"67",66:30,65:r,},"64":{63:"%62 2m%m%61%5z%5y%5x.u%5w%5v%5u.2y%22 2k%m%1o%22 5t%m%1o%22 5s%m%1o%22 2j%m%5r%22 16%m%5q%22 15%m%5p%22 5o%2z%5n%5m%2z",5l:"w://v.u/d/1k/5k.2y",5j:[]},\'5i\':{"5h":"5g"},5f:"5e",5d:"w://v.u",5c:{},5b:l,1x:[0.25,0.50,0.75,1,1.25,1.5,2]});h 1m,1n,5a;h 59=0,58=0;h 7=g("1j");h 2x=0,57=0,56=0;$.55({54:{\'53-52\':\'2i-51\'}});7.j(\'4z\',6(x){c(5>0&&x.1l>=5&&1n!=1){1n=1;$(\'q.4y\').4x(\'4w\')}});7.j(\'13\',6(x){2x=x.1l});7.j(\'2g\',6(x){2w(x)});7.j(\'4v\',6(){$(\'q.2v\').4u()});6 2w(x){$(\'q.2v\').4t();c(1m)19;1m=1;17=0;c(4s.4r===l){17=1}$.4q(\'/2u?b=4p&2l=1k&4o=2t-4n-4m-2s-4l&4k=&4j=&4i=&17=\'+17,6(2r){$(\'#4h\').4g(2r)});$(\'.3-8-4f-4e:4d("4c")\').2h(6(e){2q();g().4b(0);g().4a(l)});6 2q(){h $14=$("<q />").2p({1l:"49",16:"r%",15:"r%",48:0,2n:0,2o:47,46:"45(10%, 10%, 10%, 0.4)","44-43":"42"});$("<41 />").2p({16:"60%",15:"60%",2o:40,"3z-2n":"3y"}).3x({\'2m\':\'/?b=3w&2l=1k\',\'2k\':\'0\',\'2j\':\'2i\'}).2f($14);$14.2h(6(){$(3v).3u();g().2g()});$14.2f($(\'#1j\'))}g().13(0);}6 3t(){h 9=7.1b(2e);2d.2c(9);c(9.n>1){1r(i=0;i<9.n;i++){c(9[i].1a==2e){2d.2c(\'!!=\'+i);7.1p(i)}}}}7.j(\'3s\',6(){g().1h("/2a/3r.29","3q 10 28",6(){g().13(g().27()+10)},"2b");$("q[26=2b]").23().21(\'.3-20-1z\');g().1h("/2a/3p.29","3o 10 28",6(){h 12=g().27()-10;c(12<0)12=0;g().13(12)},"24");$("q[26=24]").23().21(\'.3-20-1z\');});6 1i(){}7.j(\'3n\',6(){1i()});7.j(\'3m\',6(){1i()});7.j("k",6(y){h 9=7.1b();c(9.n<2)19;$(\'.3-8-3l-3k\').3j(6(){$(\'#3-8-a-k\').1e(\'3-8-a-z\');$(\'.3-a-k\').p(\'o-1f\',\'11\')});7.1h("/3i/3h.3g","3f 3e",6(){$(\'.3-1w\').3d(\'3-8-1v\');$(\'.3-8-1y, .3-8-1x\').p(\'o-1g\',\'11\');c($(\'.3-1w\').3c(\'3-8-1v\')){$(\'.3-a-k\').p(\'o-1g\',\'l\');$(\'.3-a-k\').p(\'o-1f\',\'l\');$(\'.3-8-a\').1e(\'3-8-a-z\');$(\'.3-8-a:1u\').3b(\'3-8-a-z\')}3a{$(\'.3-a-k\').p(\'o-1g\',\'11\');$(\'.3-a-k\').p(\'o-1f\',\'11\');$(\'.3-8-a:1u\').1e(\'3-8-a-z\')}},"39");7.j("38",6(y){1d.37(\'1c\',y.9[y.36].1a)});c(1d.1t(\'1c\')){35("1s(1d.1t(\'1c\'));",34)}});h 18;6 1s(1q){h 9=7.1b();c(9.n>1){1r(i=0;i<9.n;i++){c(9[i].1a==1q){c(i==18){19}18=i;7.1p(i)}}}}',36,270,'|||jw|||function|player|settings|tracks|submenu||if||||jwplayer|var||on|audioTracks|true|3D|length|aria|attr|div|100|||sx|filemoon|https||event|active||false|tt|seek|dd|height|width|adb|current_audio|return|name|getAudioTracks|default_audio|localStorage|removeClass|expanded|checked|addButton|callMeMaybe|vplayer|0fxcyc2ajhp1|position|vvplay|vvad|220|setCurrentAudioTrack|audio_name|for|audio_set|getItem|last|open|controls|playbackRates|captions|rewind|icon|insertAfter||detach|ff00||button|getPosition|sec|png|player8|ff11|log|console|track_name|appendTo|play|click|no|scrolling|frameborder|file_code|src|top|zIndex|css|showCCform|data|1662367683|383371|dl|video_ad|doPlay|prevt|mp4|3E||jpg|thumbs|file|300|setTimeout|currentTrack|setItem|audioTrackChanged|dualSound|else|addClass|hasClass|toggleClass|Track|Audio|svg|dualy|images|mousedown|buttons|topbar|playAttemptFailed|beforePlay|Rewind|fr|Forward|ff|ready|set_audio_track|remove|this|upload_srt|prop|50px|margin|1000001|iframe|center|align|text|rgba|background|1000000|left|absolute|pause|setCurrentCaptions|Upload|contains|item|content|html|fviews|referer|prem|embed|3e57249ef633e0d03bf76ceb8d8a4b65|216|83|hash|view|get|TokenZir|window|hide|show|complete|slow|fadeIn|video_ad_fadein|time||cache|Cache|Content|headers|ajaxSetup|v2done|tott|vastdone2|vastdone1|vvbefore|playbackRateControls|cast|aboutlink|FileMoon|abouttext|UHD|1870|qualityLabels|sites|GNOME_POWER|link|2Fiframe|3C|allowfullscreen|22360|22640|22no|marginheight|marginwidth|2FGNOME_POWER|2F0fxcyc2ajhp1|2Fe|2Ffilemoon|2F|3A||22https|3Ciframe|code|sharing|fontOpacity|backgroundOpacity|Tahoma|fontFamily|303030|backgroundColor|FFFFFF|color|userFontScale|thumbnails|kind|0fxcyc2ajhp10000|url|get_slides|start|startparam|none|preload|html5|primary|hlshtml|androidhls|duration|uniform|stretching|0fxcyc2ajhp1_xt|image|2048|sp|6871|asn|127|srv|43200|_g3XlBcu2lmD9oDexD2NLWSmah2Nu3XcDrl93m9PwXY|m3u8||master|0fxcyc2ajhp1_x|00076|01|hls2|to|s01|delivery|storage|moon|sources|setup'''.split('|')))
351
582be358 352
9e3f1991
PH
353if __name__ == '__main__':
354 unittest.main()