MCPcopy Create free account
hub / github.com/RustPython/RustPython / TestSourcePositions

Class TestSourcePositions

Lib/test/test_compile.py:1871–2390  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1869
1870@requires_debug_ranges()
1871class TestSourcePositions(unittest.TestCase):
1872 # Ensure that compiled code snippets have correct line and column numbers
1873 # in `co_positions()`.
1874
1875 def check_positions_against_ast(self, snippet):
1876 # Basic check that makes sure each line and column is at least present
1877 # in one of the AST nodes of the source code.
1878 code = compile(snippet, 'test_compile.py', 'exec')
1879 ast_tree = compile(snippet, 'test_compile.py', 'exec', _ast.PyCF_ONLY_AST)
1880 self.assertTrue(type(ast_tree) == _ast.Module)
1881
1882 # Use an AST visitor that notes all the offsets.
1883 lines, end_lines, columns, end_columns = set(), set(), set(), set()
1884 class SourceOffsetVisitor(ast.NodeVisitor):
1885 def generic_visit(self, node):
1886 super().generic_visit(node)
1887 if not isinstance(node, (ast.expr, ast.stmt, ast.pattern)):
1888 return
1889 lines.add(node.lineno)
1890 end_lines.add(node.end_lineno)
1891 columns.add(node.col_offset)
1892 end_columns.add(node.end_col_offset)
1893
1894 SourceOffsetVisitor().visit(ast_tree)
1895
1896 # Check against the positions in the code object.
1897 for (line, end_line, col, end_col) in code.co_positions():
1898 if line == 0:
1899 continue # This is an artificial module-start line
1900 # If the offset is not None (indicating missing data), ensure that
1901 # it was part of one of the AST nodes.
1902 if line is not None:
1903 self.assertIn(line, lines)
1904 if end_line is not None:
1905 self.assertIn(end_line, end_lines)
1906 if col is not None:
1907 self.assertIn(col, columns)
1908 if end_col is not None:
1909 self.assertIn(end_col, end_columns)
1910
1911 return code, ast_tree
1912
1913 def assertOpcodeSourcePositionIs(self, code, opcode,
1914 line, end_line, column, end_column, occurrence=1):
1915
1916 for instr, position in instructions_with_positions(
1917 dis.Bytecode(code), code.co_positions()
1918 ):
1919 if instr.opname == opcode:
1920 occurrence -= 1
1921 if not occurrence:
1922 self.assertEqual(position[0], line)
1923 self.assertEqual(position[1], end_line)
1924 self.assertEqual(position[2], column)
1925 self.assertEqual(position[3], end_column)
1926 return
1927
1928 self.fail(f"Opcode {opcode} not found in code")

Callers

nothing calls this directly

Calls 3

bazFunction · 0.70
filesFunction · 0.50
setdefaultMethod · 0.45

Tested by

no test coverage detected