Debian Codegraph @

tests/test_syntax.py

raw
1 """Test extension syntax."""
2 import os
3 import markdown
4 import difflib
5 import pytest
6 import copy
7 from . import util
8 import warnings
9
10 warnings.simplefilter('ignore', DeprecationWarning)
11
12 CURRENT_DIR = os.path.abspath(os.path.dirname(__file__))
13
14 CSS_LINK = '<link rel="stylesheet" type="text/css" href="%s"/>'
15 WRAPPER = '''<!DOCTYPE html>
16 <head>
17 <meta charset="utf-8">
18 %s
19 </head>
20 <body>
21 <div class="markdown-body">
22 %%s
23 </div>
24 </body>
25 '''
26
27 target_file = None
28
29
30 def set_target_file(file_name):
31 """Set target test file name."""
32
33 global target_file
34 target_file = file_name
35
36
37 def compare_results(cfg, testfile, update=False):
38 """Compare test results."""
39
40 extension = []
41 extension_config = {}
42 wrapper = "%s"
43 for k, v in cfg['extensions'].items():
44 extension.append(k)
45 if v:
46 extension_config[k] = v
47 if 'css' in cfg and len(cfg['css']):
48 wrapper = WRAPPER % '\n'.join([CSS_LINK % css for css in cfg['css']])
49
50 check_markdown(testfile, extension, extension_config, wrapper, update)
51
52
53 def check_markdown(testfile, extension, extension_config, wrapper, update=False):
54 """Check the markdown."""
55
56 expected_html = os.path.splitext(testfile)[0] + '.html'
57 with open(testfile, 'r', encoding='utf-8') as f:
58 source = f.read()
59
60 results = wrapper % markdown.Markdown(
61 extensions=extension, extension_configs=extension_config
62 ).convert(source)
63
64 try:
65 with open(expected_html, 'r', encoding='utf-8') as f:
66 expected = f.read().replace("\r\n", "\n")
67 except Exception:
68 expected = ''
69
70 diff = list(
71 difflib.unified_diff(
72 expected.splitlines(True),
73 results.splitlines(True),
74 expected_html,
75 os.path.join(os.path.dirname(testfile), 'results.html'),
76 n=3
77 )
78 )
79 if diff:
80 if update:
81 print('Updated: %s' % expected_html)
82 with open(expected_html, 'w', encoding='utf-8') as f:
83 f.write(results)
84 else:
85 raise Exception(
86 'Output from "%s" failed to match expected '
87 'output.\n\n%s' % (testfile, ''.join(diff))
88 )
89 elif update:
90 print('Skipped: %s' % expected_html)
91
92
93 def gather_test_params():
94 """Gather the test parameters."""
95
96 for base, dirs, files in os.walk(CURRENT_DIR):
97 [dirs.remove(d) for d in dirs[:] if d.startswith('_')]
98 cfg_path = os.path.join(base, 'tests.yml')
99 if os.path.exists(cfg_path):
100 files.remove('tests.yml')
101 [files.remove(file) for file in files[:] if not file.endswith('.txt')]
102 with open(cfg_path, 'r', encoding='utf-8') as f:
103 cfg = util.yaml_load(f.read())
104 for testfile in files:
105 key = os.path.splitext(testfile)[0]
106 test_cfg = copy.deepcopy(cfg['__default__'])
107 if 'extensions' not in test_cfg:
108 test_cfg['extensions'] = util.OrderedDict()
109 if 'css' not in test_cfg:
110 test_cfg['css'] = []
111 for k, v in cfg.get(key, util.OrderedDict()).items():
112 if k == 'css':
113 for css in v:
114 test_cfg[k].append(css)
115 continue
116 for k1, v1 in v.items():
117 if v1 is not None:
118 for k2, v2 in v1.items():
119 if isinstance(v2, str):
120 v1[k2] = v2.replace(
121 '{{BASE}}', base
122 ).replace(
123 '{{RELATIVE}}', CURRENT_DIR
124 )
125 elif k2 == 'base_path' and isinstance(v2, list):
126 for i, v3 in enumerate(v2, 0):
127 v1[k2][i] = v3.replace(
128 '{{BASE}}', base
129 ).replace(
130 '{{RELATIVE}}', CURRENT_DIR
131 )
132 test_cfg[k][k1] = v1
133 target = os.path.join(base, testfile)
134 if target_file is not None and target != target_file:
135 continue
136 yield test_cfg, os.path.join(base, testfile)
137
138
139 def pytest_generate_tests(metafunc):
140 """Generate tests."""
141
142 if "compare" in metafunc.fixturenames:
143 metafunc.parametrize("compare", gather_test_params())
144
145
146 def test_extensions(compare):
147 """Test extensions."""
148
149 compare_results(*compare)
150
151
152 def run():
153 """Run pytest."""
154
155 pytest.main(
156 [
157 'tests/test_syntax.py',
158 '-p', 'no:pytest_cov'
159 ]
160 )