-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathtest_main.py
More file actions
688 lines (613 loc) · 23.4 KB
/
Copy pathtest_main.py
File metadata and controls
688 lines (613 loc) · 23.4 KB
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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
# SPDX-Copyright: Copyright (c) Capital One Services, LLC
# SPDX-License-Identifier: Apache-2.0
# Copyright 2020 Capital One Services, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and limitations under the License.
"""
Pure Python implementation of CEL.
Test the main CLI.
Python >= 3.9 preserves order of arguments defined in :mod:`argparse`.
Python < 3.9 alphabetizes the arguments. This makes string comparisons
challenging in expected results.
"""
import argparse
import datetime
import io
import stat as os_stat
from pathlib import Path
import sys
from unittest.mock import Mock, call, sentinel, ANY
import pytest
import celpy
import celpy.__main__
from celpy import celtypes
@pytest.fixture
def mock_os_environ(monkeypatch):
monkeypatch.setitem(celpy.__main__.os.environ, "OS_ENV_VAR", "3.14")
def test_arg_type_value(mock_os_environ):
"""GIVEN arg values; WHEN parsing; THEN correct interpretation."""
assert celpy.__main__.arg_type_value("name:int=42") == (
"name",
celtypes.IntType,
42,
)
assert celpy.__main__.arg_type_value("OS_ENV_VAR") == (
"OS_ENV_VAR",
celtypes.StringType,
"3.14",
)
assert celpy.__main__.arg_type_value("OS_ENV_VAR:double") == (
"OS_ENV_VAR",
celtypes.DoubleType,
3.14,
)
with pytest.raises(argparse.ArgumentTypeError):
celpy.__main__.arg_type_value("name:type:value")
def test_get_options():
"""GIVEN verbose settings; WHEN parsing; THEN correct interpretation."""
options = celpy.__main__.get_options(["--arg", "name:int=42", "-n", "355./113."])
assert options.arg == [("name", celtypes.IntType, 42)]
assert options.null_input
assert options.expr == "355./113."
assert options.verbose == 0
options = celpy.__main__.get_options(["-v", "-n", '"hello world"'])
assert options.null_input
assert options.expr == '"hello world"'
assert options.verbose == 1
options = celpy.__main__.get_options(["-vv", ".doc.field * 42"])
assert not options.null_input
assert options.expr == ".doc.field * 42"
assert options.verbose == 2
def test_arg_type_bad(capsys, monkeypatch):
"""GIVEN invalid arg values; WHEN parsing; THEN correct interpretation."""
monkeypatch.setenv("COLUMNS", "80")
with pytest.raises(SystemExit) as exc_info:
options = celpy.__main__.get_options(
["--arg", "name:nope=42", "-n", "355./113."]
)
assert exc_info.value.args == (2,)
out, err = capsys.readouterr()
assert err.splitlines() == [
"usage: celpy [-h] [-v] [-a ARG] [-n] [-s] [-i] [--json-package NAME]",
" [--json-document NAME] [-b] [-f FORMAT]",
" [expr]",
"celpy: error: argument -a/--arg: arg name:nope=42 type name not in ['int', "
"'uint', 'double', 'bool', 'string', 'bytes', 'list', 'map', 'null_type', "
"'single_duration', 'single_timestamp', 'int64_value', 'uint64_value', "
"'double_value', 'bool_value', 'string_value', 'bytes_value', 'number_value', "
"'null_value']",
]
def test_arg_value_bad(capsys, monkeypatch):
"""GIVEN invalid arg values; WHEN parsing; THEN correct interpretation."""
monkeypatch.setenv("COLUMNS", "80")
with pytest.raises(SystemExit) as exc_info:
options = celpy.__main__.get_options(
["--arg", "name:int=nope", "-n", "355./113."]
)
assert exc_info.value.args == (2,)
out, err = capsys.readouterr()
assert err.splitlines() == [
"usage: celpy [-h] [-v] [-a ARG] [-n] [-s] [-i] [--json-package NAME]",
" [--json-document NAME] [-b] [-f FORMAT]",
" [expr]",
"celpy: error: argument -a/--arg: arg name:int=nope value invalid for the supplied type",
]
def test_arg_combo_bad(capsys, monkeypatch):
"""GIVEN invalid arg combinations; WHEN parsing; THEN correct interpretation."""
monkeypatch.setenv("COLUMNS", "80")
error_prefix = [
"usage: celpy [-h] [-v] [-a ARG] [-n] [-s] [-i] [--json-package NAME]",
" [--json-document NAME] [-b] [-f FORMAT]",
" [expr]",
]
with pytest.raises(SystemExit) as exc_info:
options = celpy.__main__.get_options(["-i", "-n", "355./113."])
assert exc_info.value.args == (2,)
out, err = capsys.readouterr()
assert err.splitlines() == error_prefix + [
"celpy: error: Interactive mode and an expression provided",
]
with pytest.raises(SystemExit) as exc_info:
options = celpy.__main__.get_options(["-n"])
assert exc_info.value.args == (2,)
out, err = capsys.readouterr()
assert err.splitlines() == error_prefix + [
"celpy: error: No expression provided",
]
with pytest.raises(SystemExit) as exc_info:
options = celpy.__main__.get_options(
["-n", "--json-document=_", "--json-package=_"]
)
assert exc_info.value.args == (2,)
out, err = capsys.readouterr()
assert err.splitlines() == error_prefix + [
"celpy: error: Either use --json-package or --json-document, not both",
]
@pytest.fixture
def mock_cel_environment(monkeypatch):
mock_runner = Mock(evaluate=Mock(return_value=str(sentinel.OUTPUT)))
mock_env = Mock(
compile=Mock(return_value=sentinel.AST), program=Mock(return_value=mock_runner)
)
mock_env_class = Mock(return_value=mock_env)
monkeypatch.setattr(celpy.__main__, "Environment", mock_env_class)
return mock_env_class
def test_main_0(mock_cel_environment, caplog, capsys):
"""GIVEN null-input AND expression; WHEN eval; THEN correct internal object use."""
argv = ["--null-input", '"Hello world! I\'m " + name + "."']
status = celpy.__main__.main(argv)
assert status == 0
assert mock_cel_environment.mock_calls == [
call(package=None, annotations={"stat": celpy.celtypes.FunctionType})
]
env = mock_cel_environment.return_value
assert env.compile.mock_calls == [call('"Hello world! I\'m " + name + "."')]
assert env.program.mock_calls == [call(sentinel.AST, functions={"stat": ANY})]
prgm = env.program.return_value
assert prgm.evaluate.mock_calls == [call({})]
assert caplog.messages == []
out, err = capsys.readouterr()
assert out == '"sentinel.OUTPUT"\n'
assert err == ""
def test_main_1(mock_cel_environment, caplog, capsys):
"""GIVEN null-input AND arg AND expression; WHEN eval; THEN correct internal object use."""
argv = [
"--arg",
"name:string=CEL",
"--null-input",
'"Hello world! I\'m " + name + "."',
]
status = celpy.__main__.main(argv)
assert status == 0
assert mock_cel_environment.mock_calls == [
call(
package=None,
annotations={
"name": celtypes.StringType,
"stat": celpy.celtypes.FunctionType,
},
)
]
env = mock_cel_environment.return_value
assert env.compile.mock_calls == [call('"Hello world! I\'m " + name + "."')]
assert env.program.mock_calls == [call(sentinel.AST, functions={"stat": ANY})]
prgm = env.program.return_value
assert prgm.evaluate.mock_calls == [call({"name": "CEL"})]
assert caplog.messages == []
out, err = capsys.readouterr()
assert out == '"sentinel.OUTPUT"\n'
assert err == ""
def test_main_pipe(mock_cel_environment, caplog, capsys):
"""GIVEN JSON AND expression; WHEN eval; THEN correct internal object use."""
argv = ['"Hello world! I\'m " + name + "."']
sys.stdin = io.StringIO('{"name": "CEL"}\n')
status = celpy.__main__.main(argv)
sys.stdin = sys.__stdin__
assert status == 0
assert mock_cel_environment.mock_calls == [
call(package="jq", annotations={"stat": celpy.celtypes.FunctionType})
]
env = mock_cel_environment.return_value
assert env.compile.mock_calls == [call('"Hello world! I\'m " + name + "."')]
assert env.program.mock_calls == [call(sentinel.AST, functions={"stat": ANY})]
prgm = env.program.return_value
assert prgm.evaluate.mock_calls == [
call(
{
"jq": celtypes.MapType(
{celtypes.StringType("name"): celtypes.StringType("CEL")}
)
}
)
]
assert caplog.messages == []
out, err = capsys.readouterr()
assert out == '"sentinel.OUTPUT"\n'
assert err == ""
def test_main_0_non_boolean(mock_cel_environment, caplog, capsys):
"""
GIVEN null-input AND boolean option and AND non-bool expr
WHEN eval
THEN correct internal object use.
"""
argv = ["-bn", '"Hello world! I\'m " + name + "."']
status = celpy.__main__.main(argv)
assert status == 2
assert mock_cel_environment.mock_calls == [
call(package=None, annotations={"stat": celpy.celtypes.FunctionType})
]
env = mock_cel_environment.return_value
assert env.compile.mock_calls == [call('"Hello world! I\'m " + name + "."')]
assert env.program.mock_calls == [call(sentinel.AST, functions={"stat": ANY})]
prgm = env.program.return_value
assert prgm.evaluate.mock_calls == [call({})]
assert caplog.messages == [
"Expected celtypes.BoolType, got <class 'str'> = 'sentinel.OUTPUT'"
]
out, err = capsys.readouterr()
assert out == ""
assert err == ""
@pytest.fixture
def mock_cel_environment_false(monkeypatch):
mock_runner = Mock(evaluate=Mock(return_value=celtypes.BoolType(False)))
mock_env = Mock(
compile=Mock(return_value=sentinel.AST), program=Mock(return_value=mock_runner)
)
mock_env_class = Mock(return_value=mock_env)
monkeypatch.setattr(celpy.__main__, "Environment", mock_env_class)
return mock_env_class
def test_main_0_boolean(mock_cel_environment_false, caplog, capsys):
"""
GIVEN null-input AND boolean option AND false expr
WHEN eval
THEN correct internal object use.
"""
argv = ["-bn", "2 == 1"]
status = celpy.__main__.main(argv)
assert status == 1
assert mock_cel_environment_false.mock_calls == [
call(package=None, annotations={"stat": celpy.celtypes.FunctionType})
]
env = mock_cel_environment_false.return_value
assert env.compile.mock_calls == [call("2 == 1")]
assert env.program.mock_calls == [call(sentinel.AST, functions={"stat": ANY})]
prgm = env.program.return_value
assert prgm.evaluate.mock_calls == [call({})]
assert caplog.messages == []
out, err = capsys.readouterr()
assert out == ""
assert err == ""
@pytest.fixture
def mock_cel_environment_integer(monkeypatch):
mock_runner = Mock(evaluate=Mock(return_value=celtypes.IntType(3735928559)))
mock_env = Mock(
compile=Mock(return_value=sentinel.AST), program=Mock(return_value=mock_runner)
)
mock_env_class = Mock(return_value=mock_env)
monkeypatch.setattr(celpy.__main__, "Environment", mock_env_class)
return mock_env_class
def test_main_slurp_int_format(mock_cel_environment_integer, caplog, capsys):
"""
GIVEN JSON AND slurp option AND formatted output AND int expr
WHEN eval
THEN correct internal object use.
"""
argv = ["-s", "-f", "#8x", "339629869*11"]
sys.stdin = io.StringIO('{"name": "CEL"}\n')
status = celpy.__main__.main(argv)
sys.stdin = sys.__stdin__
assert status == 0
assert mock_cel_environment_integer.mock_calls == [
call(package="jq", annotations={"stat": celpy.celtypes.FunctionType})
]
env = mock_cel_environment_integer.return_value
assert env.compile.mock_calls == [call("339629869*11")]
assert env.program.mock_calls == [call(sentinel.AST, functions={"stat": ANY})]
prgm = env.program.return_value
assert prgm.evaluate.mock_calls == [
call(
{
"jq": celtypes.MapType(
{celtypes.StringType("name"): celtypes.StringType("CEL")}
)
}
)
]
assert caplog.messages == []
out, err = capsys.readouterr()
assert out == "0xdeadbeef\n"
assert err == ""
@pytest.fixture
def mock_cel_environment_bool(monkeypatch):
mock_runner = Mock(evaluate=Mock(return_value=celtypes.BoolType(False)))
mock_env = Mock(
compile=Mock(return_value=sentinel.AST), program=Mock(return_value=mock_runner)
)
mock_env_class = Mock(return_value=mock_env)
monkeypatch.setattr(celpy.__main__, "Environment", mock_env_class)
return mock_env_class
def test_main_slurp_bool_status(mock_cel_environment_bool, caplog, capsys):
"""
GIVEN JSON AND slurp option AND formatted output AND int expr
WHEN eval
THEN correct internal object use.
"""
argv = ["-s", "-b", '.name == "not CEL"']
sys.stdin = io.StringIO('{"name": "CEL"}\n')
status = celpy.__main__.main(argv)
sys.stdin = sys.__stdin__
assert status == 1
assert mock_cel_environment_bool.mock_calls == [
call(package="jq", annotations={"stat": celpy.celtypes.FunctionType})
]
env = mock_cel_environment_bool.return_value
assert env.compile.mock_calls == [call('.name == "not CEL"')]
assert env.program.mock_calls == [call(sentinel.AST, functions={"stat": ANY})]
prgm = env.program.return_value
assert prgm.evaluate.mock_calls == [
call(
{
"jq": celtypes.MapType(
{celtypes.StringType("name"): celtypes.StringType("CEL")}
)
}
)
]
assert caplog.messages == []
out, err = capsys.readouterr()
assert out == "false\n"
assert err == ""
def test_main_0_int_format(mock_cel_environment_integer, caplog, capsys):
"""
GIVEN slurp option AND formatted output AND int expr
WHEN eval
THEN correct internal object use.
"""
argv = ["-n", "-f", "#8x", "339629869*11"]
status = celpy.__main__.main(argv)
assert status == 0
assert mock_cel_environment_integer.mock_calls == [
call(package=None, annotations={"stat": celpy.celtypes.FunctionType})
]
env = mock_cel_environment_integer.return_value
assert env.compile.mock_calls == [call("339629869*11")]
assert env.program.mock_calls == [call(sentinel.AST, functions={"stat": ANY})]
prgm = env.program.return_value
assert prgm.evaluate.mock_calls == [call({})]
assert caplog.messages == []
out, err = capsys.readouterr()
assert out == "0xdeadbeef\n"
assert err == ""
def test_main_verbose(mock_cel_environment, caplog, capsys):
"""GIVEN verbose AND expression; WHEN eval; THEN correct log output."""
argv = ["-v", "[2, 4, 5].map(x, x/2)"]
status = celpy.__main__.main(argv)
assert status == 0
assert mock_cel_environment.mock_calls == [
call(package="jq", annotations={"stat": celpy.celtypes.FunctionType})
]
assert caplog.messages == ["Expr: '[2, 4, 5].map(x, x/2)'"]
out, err = capsys.readouterr()
assert out == ""
assert err == ""
def test_main_very_verbose(mock_cel_environment, caplog, capsys):
"""GIVEN very verbose AND expression; WHEN eval; THEN correct log output."""
argv = ["-vv", "[2, 4, 5].map(x, x/2)"]
status = celpy.__main__.main(argv)
assert status == 0
assert mock_cel_environment.mock_calls == [
call(package="jq", annotations={"stat": celpy.celtypes.FunctionType})
]
expected_namespace = argparse.Namespace(
verbose=2,
arg=None,
null_input=False,
slurp=False,
interactive=False,
package="jq",
document=None,
boolean=False,
format=None,
expr="[2, 4, 5].map(x, x/2)",
)
assert caplog.messages == [
str(expected_namespace),
"Expr: '[2, 4, 5].map(x, x/2)'",
]
out, err = capsys.readouterr()
assert out == ""
assert err == ""
@pytest.fixture
def mock_cel_environment_syntax_error(monkeypatch):
mock_runner = Mock(evaluate=Mock(return_value=str(sentinel.OUTPUT)))
mock_env = Mock(
compile=Mock(side_effect=celpy.CELParseError((sentinel.arg0, sentinel.arg1))),
cel_parser=Mock(error_text=Mock(return_value=sentinel.Formatted_Error)),
)
mock_env_class = Mock(return_value=mock_env)
monkeypatch.setattr(celpy.__main__, "Environment", mock_env_class)
return mock_env_class
def test_main_parse_error(mock_cel_environment_syntax_error, caplog, capsys):
"""GIVEN syntax error; WHEN eval; THEN correct stderr output."""
argv = ["-n", "[nope++]"]
status = celpy.__main__.main(argv)
assert status == 1
assert mock_cel_environment_syntax_error.mock_calls == [
call(package=None, annotations={"stat": celpy.celtypes.FunctionType})
]
expected_namespace = argparse.Namespace(
verbose=0,
arg=None,
null_input=True,
slurp=False,
interactive=False,
package="jq",
document=None,
boolean=False,
format=None,
expr="[nope++]",
)
assert caplog.messages == [
str(expected_namespace),
"Expr: '[nope++]'",
]
out, err = capsys.readouterr()
assert out == ""
assert err == "sentinel.Formatted_Error\n"
@pytest.fixture
def mock_cel_environment_eval_error(monkeypatch):
mock_runner = Mock(
evaluate=Mock(side_effect=celpy.CELEvalError((sentinel.arg0, sentinel.arg1)))
)
mock_env = Mock(
compile=Mock(return_value=sentinel.AST),
program=Mock(return_value=mock_runner),
cel_parser=Mock(error_text=Mock(return_value=sentinel.Formatted_Error)),
)
mock_env_class = Mock(return_value=mock_env)
monkeypatch.setattr(celpy.__main__, "Environment", mock_env_class)
return mock_env_class
def test_main_0_eval_error(mock_cel_environment_eval_error, caplog, capsys):
"""GIVEN null input AND bad expression; WHEN eval; THEN correct stderr output."""
argv = ["-n", "2 / 0"]
status = celpy.__main__.main(argv)
assert status == 2
assert mock_cel_environment_eval_error.mock_calls == [
call(package=None, annotations={"stat": celpy.celtypes.FunctionType})
]
expected_namespace = argparse.Namespace(
verbose=0,
arg=None,
null_input=True,
slurp=False,
interactive=False,
package="jq",
document=None,
boolean=False,
format=None,
expr="2 / 0",
)
assert caplog.messages == [
str(expected_namespace),
"Expr: '2 / 0'",
]
out, err = capsys.readouterr()
assert out == ""
assert err == "sentinel.Formatted_Error\n"
def test_main_pipe_eval_error(mock_cel_environment_eval_error, caplog, capsys):
"""GIVEN piped input AND bad expression; WHEN eval; THEN correct stderr output."""
argv = [".json.field / 0"]
sys.stdin = io.StringIO('{"name": "CEL"}\n')
status = celpy.__main__.main(argv)
sys.stdin = sys.__stdin__
assert status == 0
assert mock_cel_environment_eval_error.mock_calls == [
call(package="jq", annotations={"stat": celpy.celtypes.FunctionType})
]
expected_namespace = argparse.Namespace(
verbose=0,
arg=None,
null_input=False,
slurp=False,
interactive=False,
package="jq",
document=None,
boolean=False,
format=None,
expr=".json.field / 0",
)
assert caplog.messages == [
str(expected_namespace),
"Expr: '.json.field / 0'",
'Encountered (sentinel.arg0, sentinel.arg1) on document \'{"name": "CEL"}\\n\'',
]
out, err = capsys.readouterr()
assert out == "null\n"
assert err == ""
def test_main_pipe_json_error(mock_cel_environment_eval_error, caplog, capsys):
"""GIVEN piped input AND bad expression; WHEN eval; THEN correct stderr output."""
argv = [".json.field / 0"]
sys.stdin = io.StringIO("nope, not json\n")
status = celpy.__main__.main(argv)
sys.stdin = sys.__stdin__
assert status == 3
assert mock_cel_environment_eval_error.mock_calls == [
call(package="jq", annotations={"stat": celpy.celtypes.FunctionType})
]
expected_namespace = argparse.Namespace(
verbose=0,
arg=None,
null_input=False,
slurp=False,
interactive=False,
package="jq",
document=None,
boolean=False,
format=None,
expr=".json.field / 0",
)
assert caplog.messages == [
str(expected_namespace),
"Expr: '.json.field / 0'",
"Expecting value: line 1 column 1 (char 0) on document 'nope, not json\\n'",
]
out, err = capsys.readouterr()
assert out == ""
assert err == ""
def test_main_repl(monkeypatch, capsys):
mock_repl = Mock()
mock_repl_class = Mock(return_value=mock_repl)
monkeypatch.setattr(celpy.__main__, "CEL_REPL", mock_repl_class)
argv = ["-i"]
status = celpy.__main__.main(argv)
assert status == 0
assert mock_repl_class.mock_calls == [call()]
assert mock_repl.cmdloop.mock_calls == [call()]
def test_repl_class_good_interaction(capsys):
"""
If any print() is added for debugging, this test will break.
"""
c = celpy.__main__.CEL_REPL()
c.preloop()
assert c.state == {}
r_0 = c.onecmd("set pi 355./113.")
assert not r_0
r_1 = c.onecmd("show")
assert not r_1
r_2 = c.onecmd("pi * 2.")
assert not r_2
r_2 = c.onecmd("quit")
assert r_2
out, err = capsys.readouterr()
print(out) # Needed to reveal debugging print() output.
lines = out.splitlines()
assert lines[0].startswith("3.14159")
assert lines[1].startswith("{'pi': DoubleType(3.14159")
assert lines[2].startswith("6.28318")
assert c.state == {"pi": celpy.celtypes.DoubleType(355.0 / 113.0)}
def test_repl_class_bad_interaction(capsys):
c = celpy.__main__.CEL_REPL()
c.preloop()
c.onecmd("set a pi ++ nope | not & proper \\ CEL")
c.onecmd("this! isn't! valid!!")
out, err = capsys.readouterr()
lines = err.splitlines()
assert lines[0] == "ERROR: <input>:1:5 pi ++ nope | not & proper \ CEL"
assert lines[4] == " | ....^"
assert c.state == {}
def test_stat_good():
cwd = Path.cwd()
doc = celpy.__main__.stat(str(cwd))
assert doc["st_atime"] == celtypes.TimestampType(
datetime.datetime.fromtimestamp(cwd.stat().st_atime)
)
assert doc["st_ctime"] == celtypes.TimestampType(
datetime.datetime.fromtimestamp(cwd.stat().st_ctime)
)
assert doc["st_mtime"] == celtypes.TimestampType(
datetime.datetime.fromtimestamp(cwd.stat().st_mtime)
)
# Not on all versions of Python.
# assert doc['st_birthtime'] == celtypes.TimestampType(
# datetime.datetime.fromtimestamp(
# cwd.stat().st_birthtime))
assert doc["st_ino"] == celtypes.IntType(cwd.stat().st_ino)
assert doc["st_size"] == celtypes.IntType(cwd.stat().st_size)
assert doc["st_nlink"] == celtypes.IntType(cwd.stat().st_nlink)
assert doc["kind"] == "d"
assert doc["setuid"] == celtypes.BoolType(os_stat.S_ISUID & cwd.stat().st_mode != 0)
assert doc["setgid"] == celtypes.BoolType(os_stat.S_ISGID & cwd.stat().st_mode != 0)
assert doc["sticky"] == celtypes.BoolType(os_stat.S_ISVTX & cwd.stat().st_mode != 0)
def test_stat_does_not_exist():
path = Path.cwd() / "does_not_exist.tmp"
doc = celpy.__main__.stat(str(path))
assert doc is None