test_regexremove.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. """
  2. Module with tests for the RegexRemovePreprocessor.
  3. """
  4. # Copyright (c) IPython Development Team.
  5. # Distributed under the terms of the Modified BSD License.
  6. import re
  7. from nbformat import v4 as nbformat, from_dict
  8. from .base import PreprocessorTestsBase
  9. from ..regexremove import RegexRemovePreprocessor
  10. class TestRegexRemove(PreprocessorTestsBase):
  11. """Contains test functions for regexremove.py"""
  12. def build_notebook(self):
  13. notebook = super(TestRegexRemove, self).build_notebook()
  14. # Add a few empty cells
  15. notebook.cells.extend([
  16. nbformat.new_code_cell(''),
  17. nbformat.new_markdown_cell(' '),
  18. nbformat.new_raw_cell('\n'),
  19. nbformat.new_raw_cell('\t'),
  20. ])
  21. return notebook
  22. def build_preprocessor(self):
  23. """Make an instance of a preprocessor"""
  24. preprocessor = RegexRemovePreprocessor()
  25. preprocessor.enabled = True
  26. return preprocessor
  27. def test_constructor(self):
  28. """Can a RegexRemovePreprocessor be constructed?"""
  29. self.build_preprocessor()
  30. def test_output(self):
  31. """Test the output of the RegexRemovePreprocessor"""
  32. pattern_lookup = {
  33. 'disallow_whitespace': [r'\s*\Z'],
  34. 'disallow_tab_newline': [r'\t\Z', r'\n\Z']
  35. }
  36. expected_cell_count = {
  37. 'default': 6, # nothing is removed
  38. 'disallow_whitespace': 2, # all "empty" cells are removed
  39. 'disallow_tab_newline': 4, # cells with tab and newline are removed
  40. 'none': 6,
  41. }
  42. for method in ['default', 'disallow_whitespace', 'disallow_tab_newline', 'none']:
  43. nb = self.build_notebook()
  44. res = self.build_resources()
  45. # Build the preprocessor and extend the list of patterns or use an empty list
  46. preprocessor = self.build_preprocessor()
  47. if method == 'none':
  48. preprocessor.patterns = []
  49. else:
  50. preprocessor.patterns.extend(pattern_lookup.get(method, []))
  51. nb, res = preprocessor(nb, res)
  52. self.assertEqual(len(nb.cells), expected_cell_count[method])
  53. # Make sure none of the cells match the pattern
  54. patterns = list(map(re.compile, preprocessor.patterns))
  55. for cell in nb.cells:
  56. for pattern in patterns:
  57. self.assertFalse(pattern.match(cell.source))