Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
nedbat committed Jun 17, 2024
1 parent 9d36e16 commit 9ddb464
Show file tree
Hide file tree
Showing 5 changed files with 56 additions and 21 deletions.
29 changes: 18 additions & 11 deletions coverage/instrument.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def decode_branch(lineno):
class FakeBranchLineTransformer(ast.NodeTransformer):

def _mark_branch(self, from_lineno: int, to_lineno: int) -> list[ast.stmt]:
mark = ast.Expr(ast.Constant(1))
mark = ast.Expr(ast.Constant(1723))
#assert sys.version_info[0:2] >= (3,12)
for node in ast.walk(mark):
node.lineno = node.end_lineno = encode_branch(from_lineno, to_lineno)
Expand Down Expand Up @@ -85,8 +85,10 @@ def visit_Match(self, node: ast.Match) -> ast.Match:
for case in node.cases:
case.body = self._mark_branch(node.lineno, case.body[0].lineno) + case.body

has_wildcard = isinstance(node.cases[-1].pattern, ast.MatchAs) and \
node.cases[-1].pattern.pattern is None
pattern = node.cases[-1].pattern
while isinstance(pattern, ast.MatchOr):
pattern = pattern.patterns[-1]
has_wildcard = isinstance(pattern, ast.MatchAs)

if not has_wildcard:
to_line = node.next_node.lineno if node.next_node else 0 # exit
Expand Down Expand Up @@ -148,13 +150,18 @@ def compile_instrumented(source: str, filename: str): # -> code object

tree = FakeBranchLineTransformer().visit(tree)
ast.fix_missing_locations(tree)
import contextlib, os
with open("/tmp/foo.out", "a") as f:
with contextlib.redirect_stdout(f):
print("=" * 80)
print(f"--- test: {os.getenv('PYTEST_CURRENT_TEST')}")
print(f"--- {filename} -------")
print(ast.dump(tree, indent=4))
code = compile(tree, filename, "exec", dont_inherit=True)
# import contextlib, os
# with open("/tmp/foo.out", "a") as f:
# with contextlib.redirect_stdout(f):
# import dis
# print("=" * 80)
# print(f"--- test: {os.getenv('PYTEST_CURRENT_TEST')}")
# print(f"--- {filename} -------")
# dis.dis(code)
import contextlib, os
with open("/tmp/foo.out", "a") as f:
with contextlib.redirect_stdout(f):
import dis
print("----------------------------")
dis.dis(code)
return code
8 changes: 8 additions & 0 deletions coverage/pytracer.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,10 @@ def _trace(
flineno: TLineNo = frame.f_lineno

if self.trace_arcs:
import contextlib, os
with open("/tmp/foo.out", "a") as f:
with contextlib.redirect_stdout(f):
print(f"pytrace: add {(self.last_line, flineno)}")
cast(Set[TArc], self.cur_file_data).add((self.last_line, flineno))
else:
cast(Set[TLineNo], self.cur_file_data).add(flineno)
Expand Down Expand Up @@ -278,6 +282,10 @@ def _trace(
real_return = True
if real_return:
first = frame.f_code.co_firstlineno
import contextlib
with open("/tmp/foo.out", "a") as f:
with contextlib.redirect_stdout(f):
print(f"pytrace: add {(self.last_line, -first)}")
cast(Set[TArc], self.cur_file_data).add((self.last_line, -first))

# Leaving this function, pop the filename stack.
Expand Down
4 changes: 4 additions & 0 deletions coverage/results.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,8 @@ def missing_branch_arcs(self) -> dict[TLineNo, list[TLineNo]]:
branch_lines = set(self._branch_lines())
mba = collections.defaultdict(list)
for l1, l2 in missing:
if l1 == l2:
continue
if l1 in branch_lines:
mba[l1].append(l2)
return mba
Expand All @@ -211,6 +213,8 @@ def executed_branch_arcs(self) -> dict[TLineNo, list[TLineNo]]:
branch_lines = set(self._branch_lines())
eba = collections.defaultdict(list)
for l1, l2 in self.arcs_executed:
if l1 == l2:
continue
if l1 in branch_lines:
eba[l1].append(l2)
return eba
Expand Down
22 changes: 16 additions & 6 deletions coverage/sysmon.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,10 @@ def sysmon_py_return_arcs(
last_line = self.last_lines.get(frame)
if last_line is not None:
arc = (last_line, -code.co_firstlineno)
import contextlib
with open("/tmp/foo.out", "a") as f:
with contextlib.redirect_stdout(f):
print(f"sysmon adding {arc = } (return)")
# log(f"adding {arc=}")
cast(Set[TArc], code_info.file_data).add(arc)

Expand Down Expand Up @@ -429,16 +433,22 @@ def sysmon_line_arcs(self, code: CodeType, line_number: int) -> MonitorReturn:
"""Handle sys.monitoring.events.LINE events for branch coverage."""
code_info = self.code_infos[id(code)]
if code_info.file_data is not None:
was_branch = is_branch(line_number)
if is_branch(line_number):
from_no, to_no = decode_branch(line_number)
if to_no == 0:
to_no = -code.co_firstlineno
arc = (from_no, to_no)
else:
from_no = to_no = line_number
arc = (from_no, to_no)
cast(Set[TArc], code_info.file_data).add(arc)
import contextlib
# with open("/tmp/foo.out", "a") as f:
# with contextlib.redirect_stdout(f):
# print(f"adding {arc = }")
arc = None
arc = (from_no, to_no)
if arc is not None:
cast(Set[TArc], code_info.file_data).add(arc)
import contextlib
with open("/tmp/foo.out", "a") as f:
with contextlib.redirect_stdout(f):
print(f"sysmon adding {arc = } was_branch: {was_branch}")
# log(f"adding {arc=}")
#self.last_lines[frame] = line_number
return sys.monitoring.DISABLE
14 changes: 10 additions & 4 deletions tests/test_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,13 @@ def _assert_expected_json_report(
self.make_file("a.py", """\
a = {'b': 1}
if a.get('a'):
b = 1
b = 3
elif a.get('b'):
b = 2
b = 5
else:
b = 3
b = 7
if not a:
b = 4
b = 9
""")
a = self.start_import_stop(cov, "a")
output_path = os.path.join(self.temp_dir, "a.json")
Expand All @@ -49,6 +49,12 @@ def _assert_expected_json_report(
self.assert_recent_datetime(
datetime.strptime(parsed_result['meta']['timestamp'], "%Y-%m-%dT%H:%M:%S.%f"),
)
import contextlib
with open("/tmp/foo.out", "a") as f:
with contextlib.redirect_stdout(f):
print("=" * 120)
print(f'running {os.getenv("PYTEST_CURRENT_TEST")}')
print(json.dumps(parsed_result, indent=4))
del (parsed_result['meta']['timestamp'])
expected_result["meta"].update({
"format": FORMAT_VERSION,
Expand Down

0 comments on commit 9ddb464

Please sign in to comment.