/
test_handlers.py
615 lines (525 loc) · 18.3 KB
/
test_handlers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
import json
import typing as t
import pkg_resources
import pytest
from jsonschema import validate
from tornado.httpclient import HTTPResponse
from jupyterlab_code_formatter.formatters import SERVER_FORMATTERS
def _generate_list_formaters_entry_json_schema(
formatter_name: str,
) -> t.Dict[str, t.Any]:
return {
"type": "object",
"required": [formatter_name],
"properties": {
formatter_name: {
"type": "object",
"required": ["enabled", "label"],
"properties": {
"enabled": {"type": "boolean"},
"label": {"type": "string"},
},
}
},
}
EXPECTED_VERSION_SCHEMA = {
"type": "object",
"required": ["version"],
"properties": {
"version": {
"type": "string",
}
},
}
EXPECTED_LIST_FORMATTERS_SCHEMA = {
"type": "object",
"required": ["formatters"],
"properties": {
"formatters": {
formatter_name: _generate_list_formaters_entry_json_schema(formatter_name)
for formatter_name in SERVER_FORMATTERS
}
},
}
EXPECTED_FROMAT_SCHEMA = {
"type": "object",
"required": ["code"],
"properties": {
"code": {
"type": "array",
"items": {
"type": "object",
"oneOf": [
{
"additionalProperties": False,
"properties": {"code": {"type": "string"}},
},
{
"additionalProperties": False,
"properties": {"error": {"type": "string"}},
},
],
},
}
},
}
SIMPLE_VALID_PYTHON_CODE = "x= 22; e =1"
def _create_headers(plugin_version: t.Optional[str] = None) -> t.Dict[str, str]:
return {
"Plugin-Version": plugin_version
if plugin_version is not None
else pkg_resources.get_distribution("jupyterlab_code_formatter").version
}
def _check_http_code_and_schema(
response: HTTPResponse, expected_code: int, expected_schema: t.Dict[str, t.Any]
) -> t.Dict[str, t.Any]:
assert response.code == expected_code
json_result: t.Dict[str, t.Any] = json.loads(response.body)
validate(instance=json_result, schema=expected_schema)
return json_result
async def test_list_formatters(request_list_formatters): # type: ignore[no-untyped-def]
"""Check if the formatters list route works."""
response: HTTPResponse = await request_list_formatters(headers=_create_headers())
_check_http_code_and_schema(
response=response,
expected_code=200,
expected_schema=EXPECTED_LIST_FORMATTERS_SCHEMA,
)
async def test_404_on_unknown(request_format): # type: ignore[no-untyped-def]
"""Check that it 404 correctly if formatter name is bad."""
response: HTTPResponse = await request_format(
formatter="UNKNOWN",
code=[SIMPLE_VALID_PYTHON_CODE],
options={},
headers=_create_headers(),
raise_error=False,
)
assert response.code == 404
async def test_can_apply_python_formatter(request_format): # type: ignore[no-untyped-def]
"""Check that it can apply black with simple config."""
response: HTTPResponse = await request_format(
formatter="black",
code=[SIMPLE_VALID_PYTHON_CODE],
options={"line_length": 88},
headers=_create_headers(),
)
json_result = _check_http_code_and_schema(
response=response,
expected_code=200,
expected_schema=EXPECTED_FROMAT_SCHEMA,
)
assert json_result["code"][0]["code"] == "x = 22\ne = 1"
async def test_can_use_black_config(request_format): # type: ignore[no-untyped-def]
"""Check that it can apply black with advanced config."""
given = "some_string='abc'"
expected = "some_string = 'abc'"
response: HTTPResponse = await request_format(
formatter="black",
code=[given],
options={"line_length": 123, "string_normalization": False},
headers=_create_headers(),
)
json_result = _check_http_code_and_schema(
response=response,
expected_code=200,
expected_schema=EXPECTED_FROMAT_SCHEMA,
)
assert json_result["code"][0]["code"] == expected
async def test_return_error_if_any(request_format): # type: ignore[no-untyped-def]
"""Check that it returns the error if any."""
bad_python = "this_is_bad = 'hihi"
response: HTTPResponse = await request_format(
formatter="black",
code=[bad_python],
options={"line_length": 123, "string_normalization": False},
headers=_create_headers(),
)
json_result = _check_http_code_and_schema(
response=response,
expected_code=200,
expected_schema=EXPECTED_FROMAT_SCHEMA,
)
assert json_result["code"][0]["error"] == "Cannot parse: 1:13: this_is_bad = 'hihi"
@pytest.mark.parametrize("formatter", ("black", "yapf", "isort"))
async def test_can_handle_magic(request_format, formatter): # type: ignore[no-untyped-def]
"""Check that it's fine to run formatters for code with magic."""
given = '%%timeit\nsome_string = "abc"'
expected = '%%timeit\nsome_string = "abc"'
response: HTTPResponse = await request_format(
formatter=formatter,
code=[given],
options={},
headers=_create_headers(),
)
json_result = _check_http_code_and_schema(
response=response,
expected_code=200,
expected_schema=EXPECTED_FROMAT_SCHEMA,
)
assert json_result["code"][0]["code"] == expected
@pytest.mark.parametrize("formatter", ("black", "yapf", "isort"))
async def test_can_handle_shell_cmd(request_format, formatter): # type: ignore[no-untyped-def]
"""Check that it's fine to run formatters for code with shell cmd."""
given = '%%timeit\nsome_string = "abc"\n!pwd'
expected = '%%timeit\nsome_string = "abc"\n!pwd'
response: HTTPResponse = await request_format(
formatter=formatter,
code=[given],
options={},
headers=_create_headers(),
)
json_result = _check_http_code_and_schema(
response=response,
expected_code=200,
expected_schema=EXPECTED_FROMAT_SCHEMA,
)
assert json_result["code"][0]["code"] == expected
@pytest.mark.parametrize("formatter", ("black", "yapf", "isort"))
async def test_can_handle_incompatible_magic_language(request_format, formatter): # type: ignore[no-untyped-def]
"""Check that it will ignore incompatible magic language cellblock."""
given = "%%html\n<h1>Hi</h1>"
expected = "%%html\n<h1>Hi</h1>"
response: HTTPResponse = await request_format(
formatter=formatter,
code=[given],
options={},
headers=_create_headers(),
)
json_result = _check_http_code_and_schema(
response=response,
expected_code=200,
expected_schema=EXPECTED_FROMAT_SCHEMA,
)
assert json_result["code"][0]["code"] == expected
@pytest.mark.parametrize("formatter", ("black", "yapf", "isort"))
async def test_can_handle_incompatible_magic_language_single(request_format, formatter): # type: ignore[no-untyped-def]
"""Check that it will ignore incompatible magic language cellblock with single %."""
given = "%html <h1>Hi</h1>"
expected = "%html <h1>Hi</h1>"
response: HTTPResponse = await request_format(
formatter=formatter,
code=[given],
options={},
headers=_create_headers(),
)
json_result = _check_http_code_and_schema(
response=response,
expected_code=200,
expected_schema=EXPECTED_FROMAT_SCHEMA,
)
assert json_result["code"][0]["code"] == expected
async def test_can_ipython_help_signle(request_format): # type: ignore[no-untyped-def]
"""Check that it will ignore single question mark interactive help lines on the fly."""
given = " bruh?\nprint('test')\n#test?"
expected = ' bruh?\nprint("test")\n# test?'
response: HTTPResponse = await request_format(
formatter="black",
code=[given],
options={},
headers=_create_headers(),
)
json_result = _check_http_code_and_schema(
response=response,
expected_code=200,
expected_schema=EXPECTED_FROMAT_SCHEMA,
)
assert json_result["code"][0]["code"] == expected
async def test_can_ipython_help_double(request_format): # type: ignore[no-untyped-def]
"""Check that it will ignore double question mark interactive help lines on the fly."""
given = " bruh??\nprint('test')\n#test?"
expected = ' bruh??\nprint("test")\n# test?'
response: HTTPResponse = await request_format(
formatter="black",
code=[given],
options={},
headers=_create_headers(),
)
json_result = _check_http_code_and_schema(
response=response,
expected_code=200,
expected_schema=EXPECTED_FROMAT_SCHEMA,
)
assert json_result["code"][0]["code"] == expected
async def test_can_ipython_help_signle_leading(request_format): # type: ignore[no-untyped-def]
"""Check that it will ignore leading single question mark interactive help lines on the fly."""
given = " ?bruh\nprint('test')\n#test?"
expected = ' ?bruh\nprint("test")\n# test?'
response: HTTPResponse = await request_format(
formatter="black",
code=[given],
options={},
headers=_create_headers(),
)
json_result = _check_http_code_and_schema(
response=response,
expected_code=200,
expected_schema=EXPECTED_FROMAT_SCHEMA,
)
assert json_result["code"][0]["code"] == expected
async def test_can_ipython_help_double_leading(request_format): # type: ignore[no-untyped-def]
"""Check that it will ignore leading double question mark interactive help lines on the fly."""
given = " ??bruh\nprint('test')\n#test?"
expected = ' ??bruh\nprint("test")\n# test?'
response: HTTPResponse = await request_format(
formatter="black",
code=[given],
options={},
headers=_create_headers(),
)
json_result = _check_http_code_and_schema(
response=response,
expected_code=200,
expected_schema=EXPECTED_FROMAT_SCHEMA,
)
assert json_result["code"][0]["code"] == expected
async def test_will_ignore_quarto_comments(request_format): # type: ignore[no-untyped-def]
"""Check that it will ignore Quarto's comments at the top of a block."""
given = """#| eval: false
1 + 1"""
response: HTTPResponse = await request_format(
formatter="black",
code=[given],
options={},
headers=_create_headers(),
)
json_result = _check_http_code_and_schema(
response=response,
expected_code=200,
expected_schema=EXPECTED_FROMAT_SCHEMA,
)
assert json_result["code"][0]["code"] == given
async def test_will_ignore_run_command(request_format): # type: ignore[no-untyped-def]
"""Check that it will ignore run command."""
given = " run some_script.py"
response: HTTPResponse = await request_format(
formatter="black",
code=[given],
options={},
headers=_create_headers(),
)
json_result = _check_http_code_and_schema(
response=response,
expected_code=200,
expected_schema=EXPECTED_FROMAT_SCHEMA,
)
assert json_result["code"][0]["code"] == given
async def test_will_ignore_question_mark(request_format): # type: ignore[no-untyped-def]
"""Check that it will ignore single question mark in comments."""
given = """def f():
# bruh what?
# again bruh? really
# a ? b
print('hi')
x = '?'"""
expected = """def f():
# bruh what?
# again bruh? really
# a ? b
print("hi")
x = "?\""""
response: HTTPResponse = await request_format(
formatter="black",
code=[given],
options={},
headers=_create_headers(),
)
json_result = _check_http_code_and_schema(
response=response,
expected_code=200,
expected_schema=EXPECTED_FROMAT_SCHEMA,
)
assert json_result["code"][0]["code"] == expected
async def test_will_ignore_question_mark2(request_format): # type: ignore[no-untyped-def]
"""Check that it will ignore double question mark in comments."""
given = """def f():
# bruh what??
# again bruh?? really
# a ? b ? c
print('hi')"""
expected = """def f():
# bruh what??
# again bruh?? really
# a ? b ? c
print("hi")"""
response: HTTPResponse = await request_format(
formatter="black",
code=[given],
options={},
headers=_create_headers(),
)
json_result = _check_http_code_and_schema(
response=response,
expected_code=200,
expected_schema=EXPECTED_FROMAT_SCHEMA,
)
assert json_result["code"][0]["code"] == expected
async def test_will_ignore_question_weird(request_format): # type: ignore[no-untyped-def]
given = """wat
wat??"""
expected = """wat
wat??"""
response: HTTPResponse = await request_format(
formatter="black",
code=[given],
options={},
headers=_create_headers(),
)
json_result = _check_http_code_and_schema(
response=response,
expected_code=200,
expected_schema=EXPECTED_FROMAT_SCHEMA,
)
assert json_result["code"][0]["code"] == expected
async def test_can_use_styler(request_format): # type: ignore[no-untyped-def]
given = "a = 3; 2"
expected = "a <- 3\n2"
response: HTTPResponse = await request_format(
formatter="styler",
code=[given],
options={"scope": "tokens"},
headers=_create_headers(),
)
json_result = _check_http_code_and_schema(
response=response,
expected_code=200,
expected_schema=EXPECTED_FROMAT_SCHEMA,
)
assert json_result["code"][0]["code"] == expected
async def test_can_use_styler2(request_format): # type: ignore[no-untyped-def]
given = """data_frame(
small = 2 ,
medium = 4,#comment without space
large =6
)"""
expected = """data_frame(
small = 2,
medium = 4, # comment without space
large = 6
)"""
response: HTTPResponse = await request_format(
formatter="styler",
code=[given],
options={"strict": False},
headers=_create_headers(),
)
json_result = _check_http_code_and_schema(
response=response,
expected_code=200,
expected_schema=EXPECTED_FROMAT_SCHEMA,
)
assert json_result["code"][0]["code"] == expected
async def test_can_use_styler3(request_format): # type: ignore[no-untyped-def]
given = "1++1/2*2^2"
expected = "1 + +1/2*2^2"
response: HTTPResponse = await request_format(
formatter="styler",
code=[given],
options={
"math_token_spacing": {
"one": ["'+'", "'-'"],
"zero": ["'/'", "'*'", "'^'"],
}
},
headers=_create_headers(),
)
json_result = _check_http_code_and_schema(
response=response,
expected_code=200,
expected_schema=EXPECTED_FROMAT_SCHEMA,
)
assert json_result["code"][0]["code"] == expected
async def test_can_use_styler4(request_format): # type: ignore[no-untyped-def]
given = """a <- function() {
### not to be indented
# indent normally
33
}"""
expected = """a <- function() {
### not to be indented
# indent normally
33
}"""
response: HTTPResponse = await request_format(
formatter="styler",
code=[given],
options={
"reindention": {
"regex_pattern": "^###",
"indention": 0,
"comments_only": True,
}
},
headers=_create_headers(),
)
json_result = _check_http_code_and_schema(
response=response,
expected_code=200,
expected_schema=EXPECTED_FROMAT_SCHEMA,
)
assert json_result["code"][0]["code"] == expected
async def test_can_use_styler5(request_format): # type: ignore[no-untyped-def]
given = """call(
# SHOULD BE ONE SPACE BEFORE
1,2)
"""
expected = """call(
# SHOULD BE ONE SPACE BEFORE
1, 2
)"""
response: HTTPResponse = await request_format(
formatter="styler",
code=[given],
options={"indent_by": 4, "start_comments_with_one_space": True},
headers=_create_headers(),
)
json_result = _check_http_code_and_schema(
response=response,
expected_code=200,
expected_schema=EXPECTED_FROMAT_SCHEMA,
)
assert json_result["code"][0]["code"] == expected
async def test_can_use_styler6(request_format): # type: ignore[no-untyped-def]
given = "1+1-3"
expected = "1 + 1 - 3"
response: HTTPResponse = await request_format(
formatter="styler",
code=[given],
options={
"math_token_spacing": "tidyverse_math_token_spacing",
"reindention": "tidyverse_reindention",
},
headers=_create_headers(),
)
json_result = _check_http_code_and_schema(
response=response,
expected_code=200,
expected_schema=EXPECTED_FROMAT_SCHEMA,
)
assert json_result["code"][0]["code"] == expected
async def test_422_on_mismatch_version_1(request_list_formatters): # type: ignore[no-untyped-def]
response: HTTPResponse = await request_list_formatters(
headers=_create_headers("0.0.0"),
raise_error=False,
)
assert response.code == 422
async def test_200_on_version_without_header(request_version): # type: ignore[no-untyped-def]
response: HTTPResponse = await request_version()
_check_http_code_and_schema(
response=response,
expected_code=200,
expected_schema=EXPECTED_VERSION_SCHEMA,
)
async def test_200_on_version_with_wrong_header(request_version): # type: ignore[no-untyped-def]
response: HTTPResponse = await request_version(headers=_create_headers("0.0.0"))
_check_http_code_and_schema(
response=response,
expected_code=200,
expected_schema=EXPECTED_VERSION_SCHEMA,
)
async def test_200_on_version_with_correct_header(request_version): # type: ignore[no-untyped-def]
response: HTTPResponse = await request_version(headers=_create_headers())
_check_http_code_and_schema(
response=response,
expected_code=200,
expected_schema=EXPECTED_VERSION_SCHEMA,
)