Skip to content

Commit

Permalink
Switch from nose to unittest
Browse files Browse the repository at this point in the history
All file-based tests are now defined as unittest test cases via a
metaclass which walks a directory and builds a unittest for each pair
of test files.

To run the tests just run `python -m unittest discover tests`. Or use
tox as the tox config has been updated to run the new tests and all nose
specific code has been removed.

The test generator tools have been removed as well. If any changes or
additions need to be made to tests, they should be implemented using
the new framework rather than with the file-based tests. Eventually,
only the PHP and pl tests should remain as file-based tests.
  • Loading branch information
waylan committed Jan 9, 2018
1 parent 76e0a63 commit 49249b3
Show file tree
Hide file tree
Showing 19 changed files with 342 additions and 593 deletions.
3 changes: 1 addition & 2 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
recursive-include markdown *.py
recursive-include docs *
recursive-include tests *.txt *.html *.cfg *.py
recursive-include tests *.txt *.html *.py
include setup.py
include setup.cfg
include run-tests.py
include tox.ini
include makefile
include LICENSE.md
Expand Down
8 changes: 2 additions & 6 deletions makefile
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ help:
@echo ' build-win Build a Windows exe distribution'
@echo ' docs Build documentation'
@echo ' test Run all tests'
@echo ' update-tests Generate html files for updated text files in tests'
@echo ' clean Clean up the source directories'

.PHONY : install
Expand All @@ -38,11 +37,8 @@ docs:

.PHONY : test
test:
tox

.PHONY : update-tests
update-tests:
python run-tests.py update
coverage run --source=markdown -m unittest discover tests
coverage report --show-missing

.PHONY : clean
clean:
Expand Down
125 changes: 124 additions & 1 deletion markdown/test_tools.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
from __future__ import absolute_import
import os
import io
import unittest
import textwrap
from markdown import markdown
from . import markdown

try:
import tidylib
except ImportError:
tidylib = None

__all__ = ['TestCase', 'LegacyTestCase', 'Kwargs']


class TestCase(unittest.TestCase):
Expand Down Expand Up @@ -42,3 +52,116 @@ def dedent(self, text):
# TODO: If/when actual output ends with a newline, then use:
# return textwrap.dedent(text.strip('/n'))
return textwrap.dedent(text).strip()


#########################
# Legacy Test Framework #
#########################


class Kwargs(dict):
""" A dict like class for holding keyword arguments. """
pass


def _normalize_whitespace(text):
""" Normalize whitespace for a string of html using tidylib. """
output, errors = tidylib.tidy_fragment(text, options={
'drop_empty_paras': 0,
'fix_backslash': 0,
'fix_bad_comments': 0,
'fix_uri': 0,
'join_styles': 0,
'lower_literals': 0,
'merge_divs': 0,
'output_xhtml': 1,
'quote_ampersand': 0,
'newline': 'LF'
})
return output


class LegacyTestMeta(type):
def __new__(cls, name, bases, dct):

def generate_test(infile, outfile, normalize, kwargs):
def test(self):
with io.open(infile, encoding="utf-8") as f:
input = f.read()
with io.open(outfile, encoding="utf-8") as f:
# Normalize line endings
# (on Windows, git may have altered line endings).
expected = f.read().replace("\r\n", "\n")
output = markdown(input, **kwargs)
if tidylib and normalize:
expected = _normalize_whitespace(expected)
output = _normalize_whitespace(output)
elif normalize:
self.skipTest('Tidylib not available.')
self.assertMultiLineEqual(output, expected)
return test

location = dct.get('location', '')
exclude = dct.get('exclude', [])
normalize = dct.get('normalize', False)
input_ext = dct.get('input_ext', '.txt')
output_ext = dct.get('output_ext', '.html')
kwargs = dct.get('default_kwargs', Kwargs())

if os.path.isdir(location):
for file in os.listdir(location):
infile = os.path.join(location, file)
if os.path.isfile(infile):
tname, ext = os.path.splitext(file)
if ext == input_ext:
outfile = os.path.join(location, tname + output_ext)
tname = tname.replace(' ', '_').replace('-', '_')
kws = kwargs.copy()
if tname in dct:
kws.update(dct[tname])
test_name = 'test_%s' % tname
if tname not in exclude:
dct[test_name] = generate_test(infile, outfile, normalize, kws)
else:
dct[test_name] = unittest.skip('Excluded')(lambda: None)

return type.__new__(cls, name, bases, dct)


# Define LegacyTestCase class with metaclass in Py2 & Py3 compatable way.
# See https://stackoverflow.com/a/38668373/866026
# TODO: If/when py2 support is dropped change to:
# class LegacyTestCase(unittest.Testcase, metaclass=LegacyTestMeta)


class LegacyTestCase(LegacyTestMeta('LegacyTestCase', (unittest.TestCase,), {'__slots__': ()})):
"""
A `unittest.TestCase` subclass for running Markdown's legacy file-based tests.
A subclass should define various properties which point to a directory of
text-based test files and define various behaviors/defaults for those tests.
The following properties are supported:
location: A path to the directory fo test files. An absolute path is prefered.
exclude: A list of tests to exclude. Each test name should comprise the filename
without an extension.
normalize: A boolean value indicating if the HTML should be normalized.
Default: `False`.
input_ext: A string containing the file extension of input files. Default: `.txt`.
ouput_ext: A string containing the file extension of expected output files.
Default: `html`.
default_kwargs: A `Kwargs` instance which stores the default set of keyword
arguments for all test files in the directory.
In addition, properties can be defined for each individual set of test files within
the directory. The property should be given the name of the file wihtout the file
extension. Any spaces and dashes in the filename should be replaced with
underscores. The value of the property should be a `Kwargs` instance which
contains the keyword arguments that should be passed to `Markdown` for that
test file. The keyword arguments will "update" the `default_kwargs`.
When the class instance is created, it will walk the given directory and create
a seperate unitttest for each set of test files using the naming scheme:
`test_filename`. One unittest will be run for each set of input and output files.
"""
pass
23 changes: 0 additions & 23 deletions run-tests.py

This file was deleted.

2 changes: 0 additions & 2 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
[nosetests]

[bdist_wheel]
universal=1

Expand Down
1 change: 0 additions & 1 deletion test-requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
nose
coverage<4.0
pyyaml
pytidylib
Expand Down
189 changes: 0 additions & 189 deletions tests/__init__.py
Original file line number Diff line number Diff line change
@@ -1,189 +0,0 @@
import os
import markdown
import codecs
import difflib
import warnings
try:
import nose
except ImportError as e:
msg = e.args[0]
msg = msg + ". The nose testing framework is required to run the Python-" \
"Markdown tests. Run `pip install nose` to install the latest version."
e.args = (msg,) + e.args[1:]
raise
from .plugins import HtmlOutput, Markdown, MarkdownSyntaxError
try:
import tidylib
except ImportError:
tidylib = None
try:
import yaml
except ImportError as e:
msg = e.args[0]
msg = msg + ". A YAML library is required to run the Python-Markdown " \
"tests. Run `pip install pyyaml` to install the latest version."
e.args = (msg,) + e.args[1:]
raise

test_dir = os.path.abspath(os.path.dirname(__file__))


class YamlConfig():
def __init__(self, defaults, filename):
""" Set defaults and load config file if it exists. """
self.DEFAULT_SECTION = 'DEFAULT'
self._defaults = defaults
self._config = {}
if os.path.exists(filename):
with codecs.open(filename, encoding="utf-8") as f:
self._config = yaml.load(f)

def get(self, section, option):
""" Get config value for given section and option key. """
if section in self._config and option in self._config[section]:
return self._config[section][option]
return self._defaults[option]

def get_section(self, file):
""" Get name of config section for given file. """
filename = os.path.basename(file)
if filename in self._config:
return filename
else:
return self.DEFAULT_SECTION

def get_args(self, file):
""" Get args to pass to markdown from config for a given file. """
args = {}
section = self.get_section(file)
if section in self._config:
for key in self._config[section].keys():
# Filter out args unique to testing framework
if key not in self._defaults.keys():
args[key] = self.get(section, key)
return args


def get_config(dir_name):
""" Get config for given directory name. """
defaults = {
'normalize': False,
'skip': False,
'input_ext': '.txt',
'output_ext': '.html'
}
config = YamlConfig(defaults, os.path.join(dir_name, 'test.cfg'))
return config


def normalize(text):
""" Normalize whitespace for a string of html using tidylib. """
output, errors = tidylib.tidy_fragment(text, options={
'drop_empty_paras': 0,
'fix_backslash': 0,
'fix_bad_comments': 0,
'fix_uri': 0,
'join_styles': 0,
'lower_literals': 0,
'merge_divs': 0,
'output_xhtml': 1,
'quote_ampersand': 0,
'newline': 'LF'
})
return output


class CheckSyntax(object):
def __init__(self, description=None):
if description:
self.description = 'TestSyntax: "%s"' % description

def __call__(self, file, config):
""" Compare expected output to actual output and report result. """
cfg_section = config.get_section(file)
if config.get(cfg_section, 'skip'):
raise nose.plugins.skip.SkipTest('Test skipped per config.')
input_file = file + config.get(cfg_section, 'input_ext')
with codecs.open(input_file, encoding="utf-8") as f:
input = f.read()
output_file = file + config.get(cfg_section, 'output_ext')
with codecs.open(output_file, encoding="utf-8") as f:
# Normalize line endings
# (on windows, git may have altered line endings).
expected_output = f.read().replace("\r\n", "\n")
output = markdown.markdown(input, **config.get_args(file))
if tidylib and config.get(cfg_section, 'normalize'):
# Normalize whitespace with tidylib before comparing.
expected_output = normalize(expected_output)
output = normalize(output)
elif config.get(cfg_section, 'normalize'):
# Tidylib is not available. Skip this test.
raise nose.plugins.skip.SkipTest(
'Test skipped. Tidylib not available on system.'
)
diff = [l for l in difflib.unified_diff(
expected_output.splitlines(True),
output.splitlines(True),
output_file,
'actual_output.html',
n=3
)]
if diff:
raise MarkdownSyntaxError(
'Output from "%s" failed to match expected '
'output.\n\n%s' % (input_file, ''.join(diff))
)


def TestSyntax():
for dir_name, sub_dirs, files in os.walk(test_dir):
# Get dir specific config settings.
config = get_config(dir_name)
# Loop through files and generate tests.
for file in files:
root, ext = os.path.splitext(file)
if ext == config.get(config.get_section(file), 'input_ext'):
path = os.path.join(dir_name, root)
check_syntax = CheckSyntax(
description=os.path.relpath(path, test_dir)
)
yield check_syntax, path, config


def generate(file, config):
""" Write expected output file for given input. """
cfg_section = config.get_section(file)
if config.get(cfg_section, 'skip') or config.get(cfg_section, 'normalize'):
print('Skipping:', file)
return None
input_file = file + config.get(cfg_section, 'input_ext')
output_file = file + config.get(cfg_section, 'output_ext')
if not os.path.isfile(output_file) or \
os.path.getmtime(output_file) < os.path.getmtime(input_file):
print('Generating:', file)
markdown.markdownFromFile(input=input_file, output=output_file,
encoding='utf-8', **config.get_args(file))
else:
print('Already up-to-date:', file)


def generate_all():
""" Generate expected output for all outdated tests. """
for dir_name, sub_dirs, files in os.walk(test_dir):
# Get dir specific config settings.
config = get_config(dir_name)
# Loop through files and generate tests.
for file in files:
root, ext = os.path.splitext(file)
if ext == config.get(config.get_section(file), 'input_ext'):
generate(os.path.join(dir_name, root), config)


def run():
# Warnings should cause tests to fail...
warnings.simplefilter('error')
# Except for the warnings that shouldn't
warnings.filterwarnings('default', category=PendingDeprecationWarning)
warnings.filterwarnings('default', category=DeprecationWarning, module='markdown')

nose.main(addplugins=[HtmlOutput(), Markdown()])
Loading

0 comments on commit 49249b3

Please sign in to comment.