| 1 |
"""In this file, we test to ensure that the output of |
| 2 |
exec_code is as expected. The tests we do here |
| 3 |
are almost identical to those for check_syntax, |
| 4 |
found in test_check_syntax.py |
| 5 |
|
| 6 |
We also test to ensure that exec_code does not accidentally |
| 7 |
change any existing error handling settings. |
| 8 |
|
| 9 |
""" |
| 10 |
|
| 11 |
import friendly_traceback as ft |
| 12 |
|
| 13 |
|
| 14 |
def test_exec_code(): |
| 15 |
|
| 16 |
bad_code_syntax = "True = 1" |
| 17 |
bad_code_exec = "a = b" |
| 18 |
good_code = "c = 1" |
| 19 |
|
| 20 |
ft.set_stream("capture") |
| 21 |
original_include = ft.get_include() |
| 22 |
installed = ft.is_installed() |
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
assert not ft.editors_helpers.exec_code(source=bad_code_syntax) |
| 27 |
result = ft.get_output() |
| 28 |
assert "SyntaxError" in result |
| 29 |
|
| 30 |
assert not ft.get_output() |
| 31 |
|
| 32 |
ft.editors_helpers.exec_code(source=bad_code_exec) |
| 33 |
result = ft.get_output() |
| 34 |
assert "NameError" in result |
| 35 |
|
| 36 |
assert ft.editors_helpers.exec_code(source=good_code) |
| 37 |
assert not ft.get_output() |
| 38 |
|
| 39 |
try: |
| 40 |
exec(bad_code_syntax, {}) |
| 41 |
except Exception: |
| 42 |
assert not ft.get_output() |
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
ft.uninstall() |
| 47 |
ft.editors_helpers.exec_code(source=bad_code_syntax) |
| 48 |
assert not ft.is_installed() |
| 49 |
ft.editors_helpers.exec_code(source=bad_code_syntax, include="no_tb") |
| 50 |
assert not ft.is_installed() |
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
ft.install(redirect="capture") |
| 55 |
|
| 56 |
ft.set_include("friendly_tb") |
| 57 |
ft.editors_helpers.exec_code(source=bad_code_syntax) |
| 58 |
assert ft.get_include() == "friendly_tb" |
| 59 |
ft.editors_helpers.exec_code(source=bad_code_syntax, include="no_tb") |
| 60 |
assert ft.get_include() == "friendly_tb" |
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
ft.set_lang("en") |
| 65 |
ft.editors_helpers.exec_code(source=bad_code_exec, lang="fr", include="explain") |
| 66 |
result = ft.get_output() |
| •67 |
assert "NameError" in result |
| 68 |
assert ft.get_lang() == "en" |
| 69 |
|
| 70 |
|
| 71 |
ft.get_output() |
| 72 |
ft.set_stream(None) |
| 73 |
if installed: |
| 74 |
ft.uninstall() |
| 75 |
ft.set_include(original_include) |
| 76 |
|
| 77 |
|
| 78 |
def test_source_cache(): |
| 79 |
""" |
| 80 |
Test that all relevant caches are updated by `source_cache.cache.add`. |
| 81 |
This test would fail without the clearing of the stack_data cache. |
| 82 |
""" |
| 83 |
|
| 84 |
ft.set_stream("capture") |
| 85 |
try: |
| 86 |
for n in range(5): |
| 87 |
source = f"{n}/0" |
| 88 |
ft.editors_helpers.exec_code(source=source) |
| 89 |
result = ft.get_output() |
| 90 |
assert source in result |
| 91 |
finally: |
| 92 |
ft.set_stream(None) |
| 93 |
|
| 94 |
|
| 95 |
if __name__ == "__main__": |
| 96 |
test_exec_code() |
| 97 |
test_source_cache() |
| 98 |
print("Success!") |