Beispiel #1
0
def test_split_code_and_text_blocks():
    """Test if a known example file gets properly split"""

    blocks = sg.split_code_and_text_blocks('examples/just_code.py')

    assert_equal(blocks[0][0], 'text')
    assert_equal(blocks[1][0], 'code')
def test_rst_block_after_docstring(gallery_conf, tmpdir):
    """Assert there is a blank line between the docstring and rst blocks."""
    filename = str(tmpdir.join('temp.py'))
    with open(filename, 'w') as f:
        f.write('\n'.join(['"Docstring"',
                           '####################',
                           '# Paragraph 1',
                           '',
                           '####################',
                           '# Paragraph 2',
                           '']))
    file_conf, blocks = sg.split_code_and_text_blocks(filename)

    assert file_conf == {}
    assert blocks[0][0] == 'text'
    assert blocks[1][0] == 'text'
    assert blocks[2][0] == 'text'

    script_vars = {'execute_script': ''}

    output_blocks, time_elapsed = sg.execute_script(blocks,
                                                    script_vars,
                                                    gallery_conf)

    example_rst = sg.rst_blocks(blocks, output_blocks, file_conf, gallery_conf)
    assert example_rst == '\n'.join([
        'Docstring',
        '',
        'Paragraph 1',
        '',
        'Paragraph 2',
        '',
        ''])
def test_rst_block_after_docstring(gallery_conf, tmpdir):
    """Assert there is a blank line between the docstring and rst blocks."""
    filename = str(tmpdir.join('temp.py'))
    with open(filename, 'w') as f:
        f.write('\n'.join([
            '"Docstring"', '####################', '# Paragraph 1', '', '#%%',
            '# Paragraph 2', '', '# %%', '# Paragraph 3', ''
        ]))
    file_conf, blocks = sg.split_code_and_text_blocks(filename)

    assert file_conf == {}
    assert len(blocks) == 4
    assert blocks[0][0] == 'text'
    assert blocks[1][0] == 'text'
    assert blocks[2][0] == 'text'
    assert blocks[3][0] == 'text'

    script_vars = {'execute_script': ''}

    output_blocks, time_elapsed = sg.execute_script(blocks, script_vars,
                                                    gallery_conf)

    example_rst = sg.rst_blocks(blocks, output_blocks, file_conf, gallery_conf)
    assert example_rst == '\n'.join([
        'Docstring', '', 'Paragraph 1', '', 'Paragraph 2', '', 'Paragraph 3',
        '', ''
    ])
def test_jupyter_notebook(gallery_conf):
    """Test that written ipython notebook file corresponds to python object"""
    file_conf, blocks = sg.split_code_and_text_blocks('tutorials/plot_parse.py')
    example_nb = jupyter_notebook(blocks, gallery_conf)

    with tempfile.NamedTemporaryFile('w', delete=False) as f:
        save_notebook(example_nb, f.name)
    try:
        with open(f.name, "r") as fname:
            assert json.load(fname) == example_nb
    finally:
        os.remove(f.name)
    assert example_nb.get('cells')[0]['source'][0] == "%matplotlib inline"

    # Test custom first cell text
    test_text = '# testing\n%matplotlib notebook'
    gallery_conf['first_notebook_cell'] = test_text
    example_nb = jupyter_notebook(blocks, gallery_conf)
    assert example_nb.get('cells')[0]['source'][0] == test_text

    # Test empty first cell text
    test_text = None
    gallery_conf['first_notebook_cell'] = test_text
    example_nb = jupyter_notebook(blocks, gallery_conf)
    assert example_nb.get('cells')[0]['source'][0].startswith('\nThe Header Docstring')
def test_rst_empty_code_block(gallery_conf, tmpdir):
    """Test that we can "execute" a code block containing only comments."""
    filename = str(tmpdir.join('temp.py'))
    with open(filename, 'w') as f:
        f.write('\n'.join([
            '"Docstring"', '####################', '# Paragraph 1', '',
            '# just a comment'
            ''
        ]))
    file_conf, blocks = sg.split_code_and_text_blocks(filename)

    assert file_conf == {}
    assert len(blocks) == 3
    assert blocks[0][0] == 'text'
    assert blocks[1][0] == 'text'
    assert blocks[2][0] == 'code'

    gallery_conf['abort_on_example_error'] = True
    script_vars = dict(execute_script=True,
                       src_file=filename,
                       image_path_iterator=[],
                       target_file=filename)

    output_blocks, time_elapsed = sg.execute_script(blocks, script_vars,
                                                    gallery_conf)

    example_rst = sg.rst_blocks(blocks, output_blocks, file_conf, gallery_conf)
    assert example_rst.rstrip('\n') == """Docstring
Beispiel #6
0
def test_split_code_and_text_blocks():
    """Test if a known example file gets properly split"""

    blocks = sg.split_code_and_text_blocks('examples/no_output/just_code.py')

    assert blocks[0][0] == 'text'
    assert blocks[1][0] == 'code'
def test_script_vars_globals(gallery_conf, tmpdir):
    """Assert the global vars get stored."""
    filename = str(tmpdir.join('temp.py'))
    with open(filename, 'w') as f:
        f.write("""
'''
My example
----------

This is it.
'''
a = 1.
b = 'foo'
""")
    file_conf, blocks = sg.split_code_and_text_blocks(filename)
    assert len(blocks) == 2
    assert blocks[0][0] == 'text'
    assert blocks[1][0] == 'code'
    assert file_conf == {}
    script_vars = {
        'execute_script': True,
        'src_file': filename,
        'image_path_iterator': [],
        'target_file': filename
    }
    output_blocks, time_elapsed = sg.execute_script(blocks, script_vars,
                                                    gallery_conf)
    assert 'example_globals' in script_vars
    assert script_vars['example_globals']['a'] == 1.
    assert script_vars['example_globals']['b'] == 'foo'
def test_split_code_and_text_blocks():
    """Test if a known example file gets properly split"""

    blocks = sg.split_code_and_text_blocks('examples/just_code.py')

    assert_equal(blocks[0][0], 'text')
    assert_equal(blocks[1][0], 'code')
Beispiel #9
0
def test_jupyter_notebook(gallery_conf):
    """Test that written ipython notebook file corresponds to python object"""
    file_conf, blocks = sg.split_code_and_text_blocks(
        'tutorials/plot_parse.py')
    example_nb = jupyter_notebook(blocks, gallery_conf)

    with tempfile.NamedTemporaryFile('w', delete=False) as f:
        save_notebook(example_nb, f.name)
    try:
        with open(f.name, "r") as fname:
            assert json.load(fname) == example_nb
    finally:
        os.remove(f.name)
    assert example_nb.get('cells')[0]['source'][0] == "%matplotlib inline"

    # Test custom first cell text
    test_text = '# testing\n%matplotlib notebook'
    gallery_conf['first_notebook_cell'] = test_text
    example_nb = jupyter_notebook(blocks, gallery_conf)
    assert example_nb.get('cells')[0]['source'][0] == test_text

    # Test empty first cell text
    test_text = None
    gallery_conf['first_notebook_cell'] = test_text
    example_nb = jupyter_notebook(blocks, gallery_conf)
    assert example_nb.get('cells')[0]['source'][0].startswith(
        '\nThe Header Docstring')
Beispiel #10
0
def test_split_code_and_text_blocks():
    """Test if a known example file gets properly split"""

    file_conf, blocks = sg.split_code_and_text_blocks(
        'examples/no_output/just_code.py')

    assert file_conf == {}
    assert blocks[0][0] == 'text'
    assert blocks[1][0] == 'code'
Beispiel #11
0
def test_bug_cases_of_notebook_syntax():
    """Test over the known requirements of supported syntax in the
    notebook styled comments"""

    with open('sphinx_gallery/tests/reference_parse.txt') as reference:
        ref_blocks = ast.literal_eval(reference.read())
        blocks = sg.split_code_and_text_blocks('tutorials/plot_parse.py')

        assert_equal(blocks, ref_blocks)
def test_bug_cases_of_notebook_syntax():
    """Test over the known requirements of supported syntax in the
    notebook styled comments"""

    with open('sphinx_gallery/tests/reference_parse.txt') as reference:
        ref_blocks = ast.literal_eval(reference.read())
        blocks = sg.split_code_and_text_blocks('tutorials/plot_parse.py')

        assert_equal(blocks, ref_blocks)
def test_thumbnail_number(test_str):
    # which plot to show as the thumbnail image
    with tempfile.NamedTemporaryFile('w', delete=False) as f:
        f.write('\n'.join(['"Docstring"', test_str]))
    try:
        file_conf, blocks = sg.split_code_and_text_blocks(f.name)
    finally:
        os.remove(f.name)
    assert file_conf == {'thumbnail_number': 2}
Beispiel #14
0
def test_thumbnail_number(test_str):
    # which plot to show as the thumbnail image
    with tempfile.NamedTemporaryFile('w', delete=False) as f:
        f.write('\n'.join(['"Docstring"',
                           test_str]))
    try:
        file_conf, blocks = sg.split_code_and_text_blocks(f.name)
    finally:
        os.remove(f.name)
    assert file_conf == {'thumbnail_number': 2}
def test_bug_cases_of_notebook_syntax():
    """Test over the known requirements of supported syntax in the
    notebook styled comments. Use both '#'s' and '# %%' as cell
    separators"""

    with open('sphinx_gallery/tests/reference_parse.txt') as reference:
        ref_blocks = ast.literal_eval(reference.read())
        file_conf, blocks = sg.split_code_and_text_blocks(
            'tutorials/plot_parse.py')

        assert file_conf == {}
        assert blocks == ref_blocks
Beispiel #16
0
def test_jupyter_notebook():
    """Test that written ipython notebook file corresponds to python object"""
    blocks = sg.split_code_and_text_blocks('tutorials/plot_parse.py')
    example_nb = jupyter_notebook(blocks)

    with tempfile.NamedTemporaryFile('w', delete=False) as f:
        save_notebook(example_nb, f.name)
    try:
        with open(f.name, "r") as fname:
            assert json.load(fname) == example_nb
    finally:
        os.remove(f.name)
def test_final_rst_last_word(tmpdir):
    """Tests last word in final rst block included as text"""
    filename = str(tmpdir.join('temp.py'))
    with open(filename, 'w') as f:
        f.write('\n'.join([
            '"Docstring"', '# comment only code block', '#%%',
            '# Include this whole sentence.'
        ]))

    file_conf, result = sg.split_code_and_text_blocks(f.name)

    assert file_conf == {}
    expected_result = [('text', 'Docstring', 1),
                       ('code', '# comment only code block\n', 2),
                       ('text', 'Include this whole sentence.', 4)]
    assert result == expected_result
Beispiel #18
0
def test_ipy_notebook():
    """Test that written ipython notebook file corresponds to python object"""
    with tempfile.NamedTemporaryFile('w+') as f:
        example_nb = notebook.Notebook(f.name, os.path.dirname(f.name))
        blocks = sg.split_code_and_text_blocks('tutorials/plot_parse.py')

        for blabel, bcontent in blocks:
            if blabel == 'code':
                example_nb.add_code_cell(bcontent)
            else:
                example_nb.add_markdown_cell(sg.text2string(bcontent))

        example_nb.save_file()

        f.flush()
        assert_equal(json.load(f), example_nb.work_notebook)
Beispiel #19
0
def test_ipy_notebook():
    """Test that written ipython notebook file corresponds to python object"""
    with tempfile.NamedTemporaryFile('w+') as f:
        example_nb = notebook.Notebook(f.name, os.path.dirname(f.name))
        blocks = sg.split_code_and_text_blocks('tutorials/plot_parse.py')

        for blabel, bcontent in blocks:
            if blabel == 'code':
                example_nb.add_code_cell(bcontent)
            else:
                example_nb.add_markdown_cell(sg.text2string(bcontent))

        example_nb.save_file()

        f.flush()
        assert_equal(json.load(f), example_nb.work_notebook)
Beispiel #20
0
def test_direct_comment_after_docstring():
    # For more details see
    # https://github.com/sphinx-gallery/sphinx-gallery/pull/49
    with tempfile.NamedTemporaryFile('w') as f:
        f.write('\n'.join([
            '"Docstring"', '# and now comes the module code',
            '# with a second line of comment', 'x, y = 1, 2', ''
        ]))
        f.flush()
        result = sg.split_code_and_text_blocks(f.name)

    expected_result = [('text', 'Docstring'),
                       ('code', '\n'.join([
                           '# and now comes the module code',
                           '# with a second line of comment', 'x, y = 1, 2', ''
                       ]))]
    assert_equal(result, expected_result)
def test_rst_block_after_docstring(gallery_conf, tmpdir):
    """Assert there is a blank line between the docstring and rst blocks."""
    filename = str(tmpdir.join('temp.py'))
    with open(filename, 'w') as f:
        f.write('\n'.join([
            '"Docstring"', '####################', '# Paragraph 1',
            '# is long.', '', '#%%', '# Paragraph 2', '', '# %%',
            '# Paragraph 3', ''
        ]))
    file_conf, blocks = sg.split_code_and_text_blocks(filename)

    assert file_conf == {}
    assert len(blocks) == 4
    assert blocks[0][0] == 'text'
    assert blocks[1][0] == 'text'
    assert blocks[2][0] == 'text'
    assert blocks[3][0] == 'text'

    script_vars = {'execute_script': ''}
    file_conf = {}

    output_blocks, time_elapsed = sg.execute_script(blocks, script_vars,
                                                    gallery_conf, file_conf)

    example_rst = sg.rst_blocks(blocks, output_blocks, file_conf, gallery_conf)
    want_rst = """\
Docstring

.. GENERATED FROM PYTHON SOURCE LINES 3-5

Paragraph 1
is long.

.. GENERATED FROM PYTHON SOURCE LINES 7-8

Paragraph 2

.. GENERATED FROM PYTHON SOURCE LINES 10-11

Paragraph 3

"""
    assert example_rst == want_rst
def test_direct_comment_after_docstring():
    # For more details see
    # https://github.com/sphinx-gallery/sphinx-gallery/pull/49
    with tempfile.NamedTemporaryFile('w') as f:
        f.write('\n'.join(['"Docstring"',
                           '# and now comes the module code',
                           '# with a second line of comment',
                           'x, y = 1, 2',
                           '']))
        f.flush()
        result = sg.split_code_and_text_blocks(f.name)

    expected_result = [
        ('text', 'Docstring'),
        ('code', '\n'.join(['# and now comes the module code',
                            '# with a second line of comment',
                            'x, y = 1, 2',
                            '']))]
    assert_equal(result, expected_result)
def test_direct_comment_after_docstring():
    # For more details see
    # https://github.com/sphinx-gallery/sphinx-gallery/pull/49
    with tempfile.NamedTemporaryFile('w', delete=False) as f:
        f.write('\n'.join([
            '"Docstring"', '# and now comes the module code',
            '# with a second line of comment', 'x, y = 1, 2', ''
        ]))
    try:
        file_conf, result = sg.split_code_and_text_blocks(f.name)
    finally:
        os.remove(f.name)

    assert file_conf == {}
    expected_result = [('text', 'Docstring', 1),
                       ('code', '\n'.join([
                           '# and now comes the module code',
                           '# with a second line of comment', 'x, y = 1, 2', ''
                       ]), 2)]
    assert result == expected_result
Beispiel #24
0
def test_jupyter_notebook(gallery_conf):
    """Test that written ipython notebook file corresponds to python object."""
    file_conf, blocks = sg.split_code_and_text_blocks(
        'tutorials/plot_parse.py')
    target_dir = 'tutorials'
    example_nb = jupyter_notebook(blocks, gallery_conf, target_dir)

    with tempfile.NamedTemporaryFile('w', delete=False) as f:
        save_notebook(example_nb, f.name)
    try:
        with open(f.name, "r") as fname:
            assert json.load(fname) == example_nb
    finally:
        os.remove(f.name)
    assert example_nb.get('cells')[0]['source'][0] == "%matplotlib inline"

    # Test custom first cell text
    test_text = '# testing\n%matplotlib notebook'
    gallery_conf['first_notebook_cell'] = test_text
    example_nb = jupyter_notebook(blocks, gallery_conf, target_dir)
    assert example_nb.get('cells')[0]['source'][0] == test_text

    # Test empty first cell text
    test_text = None
    gallery_conf['first_notebook_cell'] = test_text
    example_nb = jupyter_notebook(blocks, gallery_conf, target_dir)
    cell_src = example_nb.get('cells')[0]['source'][0]
    assert re.match('^[\n]?# Alternating text and code', cell_src)

    # Test custom last cell text
    test_text = '# testing last cell'
    gallery_conf['last_notebook_cell'] = test_text
    example_nb = jupyter_notebook(blocks, gallery_conf, target_dir)
    assert example_nb.get('cells')[-1]['source'][0] == test_text

    # Test empty first cell text
    test_text = None
    gallery_conf['last_notebook_cell'] = test_text
    example_nb = jupyter_notebook(blocks, gallery_conf, target_dir)
    cell_src = example_nb.get('cells')[-1]['source'][0]
    assert re.match("^Last text block.\n\nThat[\\\\]?'s all folks !", cell_src)
Beispiel #25
0
def test_direct_comment_after_docstring():
    # For more details see
    # https://github.com/sphinx-gallery/sphinx-gallery/pull/49
    with tempfile.NamedTemporaryFile('w', delete=False) as f:
        f.write('\n'.join(['"Docstring"',
                           '# and now comes the module code',
                           '# with a second line of comment',
                           'x, y = 1, 2',
                           '']))
    try:
        file_conf, result = sg.split_code_and_text_blocks(f.name)
    finally:
        os.remove(f.name)

    assert file_conf == {}
    expected_result = [
        ('text', 'Docstring', 1),
        ('code', '\n'.join(['# and now comes the module code',
                            '# with a second line of comment',
                            'x, y = 1, 2',
                            '']), 2)]
    assert result == expected_result