Skip to content

Commit

Permalink
Reformating a notebook with black should preserve the outputs #154
Browse files Browse the repository at this point in the history
  • Loading branch information
mwouts committed Jan 23, 2019
1 parent 4c74d60 commit aec50f7
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 11 deletions.
12 changes: 8 additions & 4 deletions jupytext/combine.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,15 @@
_BLANK_LINE = re.compile(r'^\s*$')


def black_invariant(text, chars=[' ', '\n', ',', "'", '"']):
for char in chars:
text = text.replace(char, '')
return text


def same_content(ref, test):
"""Is the content of two cells the same, except for blank lines?"""
ref = [line for line in ref.splitlines() if not _BLANK_LINE.match(line)]
test = [line for line in test.splitlines() if not _BLANK_LINE.match(line)]
return ref == test
"""Is the content of two cells the same, up to reformating by black"""
return black_invariant(ref) == black_invariant(test)


def combine_inputs_with_outputs(nb_source, nb_outputs, fmt=None):
Expand Down
13 changes: 6 additions & 7 deletions tests/test_black.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from .utils import list_notebooks
from jupytext import readf
from jupytext.cli import system, jupytext
from jupytext.combine import black_invariant


def black_version():
Expand All @@ -16,12 +17,6 @@ def black_version():
requires_black = pytest.mark.skipif(not black_version(), reason='black not found')


def remove_spaces_and_commas(text, chars=[' ', '\n', ',', "'", '"']):
for char in chars:
text = text.replace(char, '')
return text


@requires_black
@pytest.mark.parametrize('nb_file', list_notebooks('ipynb_py'))
def test_apply_black_on_python_notebooks(nb_file, tmpdir):
Expand All @@ -39,8 +34,12 @@ def test_apply_black_on_python_notebooks(nb_file, tmpdir):
assert len(nb1.cells) == len(nb2.cells)
for c1, c2 in zip(nb1.cells, nb2.cells):
# same content (almost)
assert remove_spaces_and_commas(c1.source) == remove_spaces_and_commas(c2.source)
assert black_invariant(c1.source) == black_invariant(c2.source)
# python representation is pep8
assert 'lines_to_next_cell' not in c2.metadata
# outputs are preserved
assert c1.cell_type == c2.cell_type
if c1.cell_type == 'code':
compare(c1.outputs, c2.outputs)

compare(nb1.metadata, nb2.metadata)

0 comments on commit aec50f7

Please sign in to comment.