Exemple #1
0
def test_output_indentation(gallery_conf):
    """Test whether indentation of code output is retained."""
    compiler = codeop.Compile()

    test_string = r"\n".join([
        "  A B",
        "A 1 2",
        "B 3 4"
    ])
    code = "print('" + test_string + "')"
    code_block = ("code", code, 1)

    script_vars = {
        "execute_script": True,
        "image_path_iterator": ImagePathIterator("temp.png"),
        "src_file": __file__,
        "memory_delta": [],
    }

    output = sg.execute_code_block(
        compiler, code_block, {}, script_vars, gallery_conf
    )
    output_test_string = "\n".join(
        [line[4:] for line in output.strip().split("\n")[-3:]]
    )
    assert output_test_string == test_string.replace(r"\n", "\n")
Exemple #2
0
def test_ignore_repr_types(gallery_conf, req_mpl, req_pil, script_vars):
    """Tests output capturing with various capture_repr settings."""
    compiler = codeop.Compile()
    code_block = ('code', 'a=2\na', 1)
    gallery_conf['ignore_repr_types'] = r'int'
    output = sg.execute_code_block(compiler, code_block, None, script_vars,
                                   gallery_conf)
    assert _clean_output(output) == ''
Exemple #3
0
def test_capture_repr(gallery_conf, capture_repr, code, expected_out, req_mpl,
                      req_pil, script_vars):
    """Tests output capturing with various capture_repr settings."""
    compiler = codeop.Compile()
    code_block = ('code', code, 1)
    gallery_conf['capture_repr'] = capture_repr
    output = sg.execute_code_block(compiler, code_block, None, script_vars,
                                   gallery_conf)
    assert _clean_output(output) == expected_out
Exemple #4
0
def test_empty_output_box(gallery_conf, script_vars):
    """Tests that `print(__doc__)` doesn't produce an empty output box."""
    gallery_conf.update(image_scrapers=())
    compiler = codeop.Compile()

    code_block = ("code", "print(__doc__)", 1)

    output = sg.execute_code_block(compiler, code_block, None, script_vars,
                                   gallery_conf)
    assert output.isspace()
def test_per_file_capture_repr(gallery_conf, caprepr_gallery, caprepr_file,
                               expected_out, req_mpl, req_pil, script_vars):
    """Tests that per file capture_repr overrides gallery_conf."""
    compiler = codeop.Compile()
    code_block = ('code', 'a=2\n2', 1)
    gallery_conf['capture_repr'] = caprepr_gallery
    file_conf = {'capture_repr': caprepr_file}
    output = sg.execute_code_block(compiler, code_block, None, script_vars,
                                   gallery_conf, file_conf)
    assert _clean_output(output) == expected_out
Exemple #6
0
def _create_tutorial_section(fname, src_dir, target_dir):
    if not os.path.exists(target_dir):
        os.makedirs(target_dir)

    src_file = os.path.normpath(os.path.join(src_dir, fname))
    # Check if the same tutorial script has been already run
    md5_file = os.path.join(target_dir, f"{fname}.md5")
    if _md5sum_is_current(src_file, md5_file):
        return

    file_conf, script_blocks = parser.split_code_and_text_blocks(src_file)

    # Remove *.py suffix
    base_image_name = os.path.splitext(fname)[0]
    image_path_template = os.path.join(target_dir,
                                       base_image_name + "_{0:02}.png")

    script_vars = {
        "execute_script": True,
        "image_path_iterator": scrapers.ImagePathIterator(image_path_template),
        "src_file": src_file,
        "memory_delta": [],
    }
    tutorial_globals = {"__doc__": "", "__name__": "__main__"}
    compiler = codeop.Compile()

    content_rst = ""
    for block_label, block_content, line_no in script_blocks:
        if block_label == "code":
            # Run code and save output images
            code_output = genrst.execute_code_block(
                compiler=compiler,
                block=(block_label, block_content, line_no),
                example_globals=tutorial_globals,
                script_vars=script_vars,
                gallery_conf={
                    "abort_on_example_error": True,
                    "src_dir": ".",
                    "execute_script": True,
                    "show_memory": False,
                    "image_scrapers": (scrapers.matplotlib_scraper, ),
                })
            content_rst += genrst.codestr2rst(block_content,
                                              lineno=None) + "\n"
            content_rst += code_output

        else:
            content_rst += block_content + "\n\n"

    with open(os.path.join(target_dir, f"{base_image_name}.rst"), "w") as file:
        file.write(content_rst)

    # Write checksum of file to avoid unnecessary rerun
    with open(md5_file, "w") as file:
        file.write(genrst.get_md5sum(src_file))
Exemple #7
0
def test_output_indentation(gallery_conf, script_vars):
    """Test whether indentation of code output is retained."""
    gallery_conf.update(image_scrapers=())
    compiler = codeop.Compile()

    test_string = r"\n".join(["  A B", "A 1 2", "B 3 4"])
    code = "print('" + test_string + "')"
    code_block = ("code", code, 1)
    output = sg.execute_code_block(compiler, code_block, None, script_vars,
                                   gallery_conf)
    output_test_string = "\n".join(
        [line[4:] for line in output.strip().split("\n")[-3:]])
    assert output_test_string == test_string.replace(r"\n", "\n")
Exemple #8
0
def _create_tutorial_section(fname, src_dir, target_dir):
    if not os.path.exists(target_dir):
        os.makedirs(target_dir)

    src_file = os.path.normpath(os.path.join(src_dir, fname))
    # Check if the same tutorial script has been already run
    md5_file = os.path.join(target_dir, f"{fname}.md5")
    if _md5sum_is_current(src_file, md5_file):
        return

    file_conf, script_blocks = parser.split_code_and_text_blocks(src_file)

    # Remove *.py suffix
    base_image_name = os.path.splitext(fname)[0]
    image_path_template = os.path.join(target_dir,
                                       base_image_name+"_{0:02}.png")

    block_vars = {'execute_script': True, 'fig_count': 0,
                  'image_path': image_path_template, 'src_file': src_file}
    tutorial_globals = {
        "__doc__": "",
        "__name__": "__main__"
    }
    compiler = codeop.Compile()

    content_rst = ""
    for block_label, block_content, line_no in script_blocks:
        if block_label == 'code':
            # Run code and save output images
            code_output, rtime = genrst.execute_code_block(
                compiler=compiler, src_file=src_file, code_block=block_content,
                lineno=line_no, example_globals=tutorial_globals,
                block_vars=block_vars,
                gallery_conf = {"abort_on_example_error": True, "src_dir":"."}
            )
            content_rst += genrst.codestr2rst(
                block_content, lineno=None
            ) + "\n"
            content_rst += code_output

        else:
            content_rst += block_content + "\n\n"

    with open(os.path.join(target_dir, f"{base_image_name}.rst"), "w") as file:
        file.write(content_rst)
    
    # Write checksum of file to avoid unnecessary rerun
    with open(md5_file, "w") as file:
        file.write(genrst.get_md5sum(src_file))
def test_capture_repr(gallery_conf, capture_repr, code, expected_out):
    """Tests output capturing with various capture_repr settings."""
    compiler = codeop.Compile()
    code_block = ('code', code, 1)
    script_vars = {
        "execute_script": True,
        "image_path_iterator": ImagePathIterator("temp.png"),
        "src_file": __file__,
        "memory_delta": [],
    }

    gallery_conf['capture_repr'] = capture_repr
    output = sg.execute_code_block(compiler, code_block, {}, script_vars,
                                   gallery_conf)
    assert _clean_output(output) == expected_out
Exemple #10
0
def test_output_no_ansi(gallery_conf, script_vars):
    """Test ANSI characters are removed.

    See: https://en.wikipedia.org/wiki/ANSI_escape_code
    """
    gallery_conf.update(image_scrapers=())
    compiler = codeop.Compile()

    code = 'print("\033[94m0.25")'
    code_block = ("code", code, 1)
    output = sg.execute_code_block(compiler, code_block, None, script_vars,
                                   gallery_conf)
    output_test_string = "\n".join(
        [line[4:] for line in output.strip().split("\n")[-3:]])

    assert output_test_string.split('\n')[-1] == "0.25"
def test_empty_output_box(gallery_conf):
    """Tests that `print(__doc__)` doesn't produce an empty output box."""
    compiler = codeop.Compile()

    code_block = ("code", "print(__doc__)", 1)

    script_vars = {
        "execute_script": True,
        "image_path_iterator": ImagePathIterator("temp.png"),
        "src_file": __file__,
        "memory_delta": [],
    }

    example_globals = {'__doc__': ''}

    output = sg.execute_code_block(compiler, code_block, example_globals,
                                   script_vars, gallery_conf)
    assert output.isspace()
Exemple #12
0
def _create_tutorial_section(fname, src_dir, target_dir):
    if not os.path.exists(target_dir):
        os.makedirs(target_dir)

    src_file = os.path.normpath(os.path.join(src_dir, fname))
    # Check if the same tutorial script has been already run
    md5_file = os.path.join(target_dir, f"{fname}.md5")
    if _md5sum_is_current(src_file, md5_file):
        return

    file_conf, script_blocks = parser.split_code_and_text_blocks(src_file)

    # Remove *.py suffix
    base_image_name = os.path.splitext(fname)[0]
    # Locate file in tutorial target directory
    abs_base_image_name = os.path.join(os.getcwd(), "tutorial", "target",
                                       base_image_name)
    image_path_template = abs_base_image_name + "_{0:02}.png"

    fake_main = module_from_spec(spec_from_loader('__main__', None))
    script_vars = {
        "execute_script": True,
        "image_path_iterator": scrapers.ImagePathIterator(image_path_template),
        "src_file": src_file,
        "memory_delta": [],
        "fake_main": fake_main
    }
    tutorial_globals = fake_main.__dict__
    tutorial_globals.update({
        "__doc__": "",
    })
    gallery_conf = copy.deepcopy(DEFAULT_GALLERY_CONF)
    gallery_conf.update({
        "abort_on_example_error": True,
        "src_dir": os.getcwd(),
        "execute_script": True,
        "inspect_global_variables": False,
        "call_memory": (lambda func: (0., func())),
        "image_scrapers": (scrapers.matplotlib_scraper, ),
    })
    compiler = codeop.Compile()

    content_rst = ""
    for block_label, block_content, line_no in script_blocks:
        if block_label == "code":
            # Run code and save output images
            code_output = genrst.execute_code_block(
                compiler=compiler,
                block=(block_label, block_content, line_no),
                example_globals=tutorial_globals,
                script_vars=script_vars,
                gallery_conf=gallery_conf)
            content_rst += genrst.codestr2rst(block_content,
                                              lineno=None) + "\n"
            content_rst += code_output

        else:
            content_rst += block_content + "\n\n"

    with open(os.path.join(target_dir, f"{base_image_name}.rst"), "w") as file:
        file.write(content_rst)

    # Write checksum of file to avoid unnecessary rerun
    with open(md5_file, "w") as file:
        file.write(genrst.get_md5sum(src_file))