|
| 1 | +# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 |
| 2 | +# For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt |
| 3 | + |
| 4 | +"""Tests for coverage.py's bytecode analysis.""" |
| 5 | + |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +import dis |
| 9 | + |
| 10 | +from textwrap import dedent |
| 11 | + |
| 12 | +from tests.coveragetest import CoverageTest |
| 13 | + |
| 14 | +from coverage import env |
| 15 | +from coverage.bytecode import code_objects, op_set |
| 16 | + |
| 17 | + |
| 18 | +class BytecodeTest(CoverageTest): |
| 19 | + """Tests for bytecode.py""" |
| 20 | + |
| 21 | + def test_code_objects(self) -> None: |
| 22 | + code = compile( |
| 23 | + dedent("""\ |
| 24 | + def f(x): |
| 25 | + def g(y): |
| 26 | + return {z for z in range(10)} |
| 27 | + def j(): |
| 28 | + return [z for z in range(10)] |
| 29 | + return g(x) |
| 30 | + def h(x): |
| 31 | + return x+1 |
| 32 | + """), |
| 33 | + "<string>", |
| 34 | + "exec" |
| 35 | + ) |
| 36 | + |
| 37 | + objs = list(code_objects(code)) |
| 38 | + assert code in objs |
| 39 | + |
| 40 | + expected = {"<module>", "f", "g", "j", "h"} |
| 41 | + if env.PYVERSION < (3, 12): |
| 42 | + # Comprehensions were compiled as implicit functions in earlier |
| 43 | + # versions of Python. |
| 44 | + expected.update({"<setcomp>", "<listcomp>"}) |
| 45 | + assert {c.co_name for c in objs} == expected |
| 46 | + |
| 47 | + def test_op_set(self) -> None: |
| 48 | + opcodes = op_set("LOAD_CONST", "NON_EXISTENT_OPCODE", "RETURN_VALUE") |
| 49 | + assert opcodes == {dis.opmap["LOAD_CONST"], dis.opmap["RETURN_VALUE"]} |
0 commit comments