Example #1
0
def test_rst(path):
    with open(path) as f:
        rst = f.read()
        doctree = publish_doctree(rst)

    ast_parts = []
    for block in doctree.traverse(condition=is_code_block):
        raw_text = block.astext()
        num_lines = raw_text.count("\n") + 1
        node = ast.parse(raw_text, path)
        ast.increment_lineno(node, block.line - num_lines - 1)
        ast_parts.extend(node.body)

    if sys.version_info >= (3, 8):
        mod = ast.Module(body=ast_parts, type_ignores=[])
    else:
        mod = ast.Module(body=ast_parts)

    # Pytest 5 is Python 3 only and there are some API differences we need to
    # consider
    if get_pytest_version_info() < (5,):
        rewrite_asserts(mod, None)
    else:
        rewrite_asserts(mod, rst)
    exec(compile(mod, path, "exec"), {})
Example #2
0
    def rewrite_asserts(self, line, cell):
        """Rewrite asserts with pytest.

        Usage::

            %%rewrite_asserts

            ...

            # new cell:
            from ipytest import run_pytest
            run_pytest()
        """
        emit_deprecation_warning(
            "Assertion rewriting via magics is deprecated. "
            "Use iyptest.config.rewrite_asserts = True instead."
        )

        # follow InteractiveShell._run_cell
        cell_name = self.shell.compile.cache(cell, self.shell.execution_count)
        mod = self.shell.compile.ast_parse(cell, filename=cell_name)

        # rewrite assert statements
        from _pytest.assertion.rewrite import rewrite_asserts

        rewrite_asserts(mod)

        # follow InteractiveShell.run_ast_nodes
        code = self.shell.compile(mod, cell_name, "exec")
        self.shell.run_code(code)
Example #3
0
def _rewrite_test(config, name):
    """Try to read and rewrite *fn* and return the code object."""
    state = config._assertstate

    source = importer.get_source(name)
    if source is None:
        return None

    path = importer.get_filename(name)

    try:
        tree = ast.parse(source, filename=path)
    except SyntaxError:
        # Let this pop up again in the real import.
        state.trace("failed to parse: %r" % (path, ))
        return None
    rewrite.rewrite_asserts(tree, path, config)
    try:
        co = compile(tree, path, "exec", dont_inherit=True)
    except SyntaxError:
        # It's possible that this error is from some bug in the
        # assertion rewriting, but I don't know of a fast way to tell.
        state.trace("failed to compile: %r" % (path, ))
        return None
    return co
Example #4
0
def pytest_rewrite_asserts(code,
                           module_name=reserved_prefix + "_pytest_module"):
    """Uses pytest to rewrite the assert statements in the given code."""
    from _pytest.assertion.rewrite import rewrite_asserts  # hidden since it's not always available

    module_name = module_name.encode("utf-8")
    tree = ast.parse(code)
    rewrite_asserts(tree, module_name)
    fixed_tree = ast.fix_missing_locations(FixPytestNames().visit(tree))
    return ast.unparse(fixed_tree)
Example #5
0
def pytest_pycollect_makemodule(module_path: pathlib.Path, path: Any,
                                parent: Any) -> None:
    source = module_path.read_bytes()
    strfn = str(module_path)
    tree = ast.parse(source, filename=strfn)
    ORIGINAL_MODULE_ASTS[strfn] = tree
    tree2 = deepcopy(tree)
    rewrite_asserts(tree2, source, strfn, REWRITE_CONFIG)
    REWRITTEN_MODULE_ASTS[strfn] = tree2
    orig_pytest_pycollect_makemodule(module_path, parent)
Example #6
0
    def visit(self, node):
        from _pytest.assertion.rewrite import rewrite_asserts

        pytest_version = get_pytest_version()
        if pytest_version.release[0] >= 5:
            # TODO: re-create a pseudo code to include the asserts?
            rewrite_asserts(node, b"")

        else:
            rewrite_asserts(node)
        return node
Example #7
0
def before_module_import(mod):
    if mod.config._assertstate.mode != "on":
        return
    # Some deep magic: load the source, rewrite the asserts, and write a
    # fake pyc, so that it'll be loaded when the module is imported.
    source = mod.fspath.read()
    try:
        tree = ast.parse(source)
    except SyntaxError:
        # Let this pop up again in the real import.
        mod.config._assertstate.trace("failed to parse: %r" % (mod.fspath,))
        return
    rewrite_asserts(tree)
    try:
        co = compile(tree, str(mod.fspath), "exec")
    except SyntaxError:
        # It's possible that this error is from some bug in the assertion
        # rewriting, but I don't know of a fast way to tell.
        mod.config._assertstate.trace("failed to compile: %r" % (mod.fspath,))
        return
    mod._pyc = _write_pyc(co, mod.fspath)
    mod.config._assertstate.trace("wrote pyc: %r" % (mod._pyc,))
Example #8
0
def before_module_import(mod):
    if mod.config._assertstate.mode != "on":
        return
    # Some deep magic: load the source, rewrite the asserts, and write a
    # fake pyc, so that it'll be loaded when the module is imported.
    source = mod.fspath.read()
    try:
        tree = ast.parse(source)
    except SyntaxError:
        # Let this pop up again in the real import.
        mod.config._assertstate.trace("failed to parse: %r" % (mod.fspath, ))
        return
    rewrite_asserts(tree)
    try:
        co = compile(tree, str(mod.fspath), "exec")
    except SyntaxError:
        # It's possible that this error is from some bug in the assertion
        # rewriting, but I don't know of a fast way to tell.
        mod.config._assertstate.trace("failed to compile: %r" % (mod.fspath, ))
        return
    mod._pyc = _write_pyc(co, mod.fspath)
    mod.config._assertstate.trace("wrote pyc: %r" % (mod._pyc, ))
Example #9
0
def create_pytest_module(name, path, source, config):
    """Return a Module from source string with its assertions rewritten"""
    try:
        tree = ast.parse(source)
    except SyntaxError:
        return None

    rewrite_asserts(tree, py.path.local(path), config)

    try:
        co = compile(tree, path, "exec", dont_inherit=True)
    except SyntaxError:
        return

    mod = types.ModuleType(name)
    exec(co, mod.__dict__)

    # Also, seed the line cache, so pytest can show source code
    def getsource():
        return source

    cache[path] = (getsource, )

    return mod
Example #10
0
    def visit(self, node):
        from _pytest.assertion.rewrite import rewrite_asserts

        rewrite_asserts(node)
        return node
Example #11
0
def rewrite(src):
    tree = ast.parse(src)
    rewrite_asserts(tree)
    return tree
Example #12
0
def rewrite(src: str) -> ast.Module:
    tree = ast.parse(src)
    rewrite_asserts(tree, src.encode())
    return tree
 def replacement_rewrite_asserts(mod, module_path=None, config=None):
     rewrite_asserts(mod, module_path, config)
     store.append(codegen.to_source(mod))
Example #14
0
from _pytest.assertion.rewrite import rewrite_asserts
import ast, astunparse, sys

with open(sys.argv[1], 'r') as open_file:
    ast_tree = ast.parse(open_file.read())
rewrite_asserts(ast_tree)
print astunparse.unparse(ast_tree)
 def replacement_rewrite_asserts(tree):
     rewrite_asserts(tree)
     store.append(codegen.to_source(tree))
Example #16
0
def rewrite(src):
    tree = ast.parse(src)
    rewrite_asserts(tree)
    return tree
 def replacement_rewrite_asserts(mod, *args, **kwargs):
     rewrite_asserts(mod, *args, **kwargs)
     store.append(codegen.to_source(mod))
Example #18
0
def rewrite(src):
    tree = ast.parse(src)
    rewrite_asserts(tree, src.encode())
    return tree
Example #19
0
 def transform_ast(self, node: ast.AST) -> ast.AST:
     rewrite_asserts(node, self.source, self.filename, _PYTEST_CONFIG)
     return node