| 1 |
|
| 2 |
import glob |
| 3 |
import importlib.util |
| 4 |
import io |
| 5 |
import os |
| 6 |
import sys |
| 7 |
import traceback |
| 8 |
|
| 9 |
from codecs import utf_8_encode |
| 10 |
from functools import reduce |
| 11 |
from optparse import OptionParser |
| 12 |
from subprocess import Popen, PIPE |
| 13 |
|
| 14 |
from citeproc import CitationStylesStyle, CitationStylesBibliography |
| 15 |
from citeproc.source import Citation, CitationItem, Locator |
| 16 |
from citeproc.source.json import CiteProcJSON |
| 17 |
|
| 18 |
|
| 19 |
CITEPROC_TEST_REPOSITORY = 'https://github.com/citation-style-language/test-suite.git' |
| 20 |
CITEPROC_TEST_COMMIT = '6eefc5b07c6969ab8999e48542acbcc131cba864' |
| 21 |
|
| 22 |
CITEPROC_TEST_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), |
| 23 |
'test-suite')) |
| 24 |
TEST_PARSER_PATH = os.path.join(CITEPROC_TEST_PATH, 'processor.py') |
| 25 |
TESTS_PATH = os.path.join(CITEPROC_TEST_PATH, 'processor-tests', 'humans') |
| 26 |
LOCAL_TESTS_PATH = os.path.join(os.path.dirname(__file__), "local") |
| 27 |
|
| 28 |
FAILING_TESTS_FILE = 'failing_tests.txt' |
| 29 |
|
| 30 |
|
| 31 |
# The results of the following tests are ignored, since they don't test CSL |
| 32 |
# features, but citeproc-js specific features |
| 33 |
|
| 34 |
IGNORED_RESULS = { |
| 35 |
'date_Accessed': 'raw date', |
| 36 |
'date_LopsidedDataYearSuffixCollapse': 'raw date', |
| 37 |
'date_SeasonRange1': 'raw date', |
| 38 |
'date_SeasonRange2': 'raw date', |
| 39 |
'date_SeasonRange3': 'raw date', |
| 40 |
'date_String': 'raw date', |
| 41 |
} |
| 42 |
|
| 43 |
|
| 44 |
class ProcessorTest(object): |
| 45 |
"""Parses atest fixture and provides a method for processing the tests |
| 46 |
defined in it.""" |
| 47 |
bib_prefix = '<div class="csl-bib-body">' |
| 48 |
bib_suffix = '</div>' |
| 49 |
item_prefix = ' <div class="csl-entry">' |
| 50 |
item_suffix = '</div>' |
| 51 |
|
| 52 |
def __init__(self, filename): |
| 53 |
self.csl_test = CslTest({}, None, (filename, ), |
| 54 |
os.path.basename(filename)) |
| 55 |
self.csl_test.parse() |
| 56 |
csl_io = io.BytesIO(utf_8_encode(self.data['csl'])[0]) |
| 57 |
self.style = CitationStylesStyle(csl_io) |
| 58 |
self._fix_input(self.data['input']) |
| 59 |
self.references = [item['id'] for item in self.data['input']] |
| 60 |
self.references_dict = CiteProcJSON(self.data['input']) |
| 61 |
self.bibliography = CitationStylesBibliography(self.style, |
| 62 |
self.references_dict) |
| 63 |
self.expected = self.data['result'].splitlines() |
| 64 |
|
| 65 |
@property |
| 66 |
def data(self): |
| 67 |
return self.csl_test.data |
| 68 |
|
| 69 |
@staticmethod |
| 70 |
def _fix_input(input_data): |
| 71 |
for i, ref in enumerate(input_data): |
| 72 |
if 'id' not in ref: |
| 73 |
ref['id'] = i |
| 74 |
if 'type' not in ref: |
| 75 |
ref['type'] = 'book' |
| 76 |
|
| 77 |
def execute(self): |
| 78 |
if self.data['citation_items']: |
| 79 |
citations = [self.parse_citation(item) |
| 80 |
for item in self.data['citation_items']] |
| 81 |
elif self.data['citations']: |
| 82 |
citations = [] |
| 83 |
for cit in self.data['citations']: |
| 84 |
cit = cit[0] |
| 85 |
citation_items = [self.parse_citation_item(cititem) |
| 86 |
for cititem in cit['citationItems']] |
| 87 |
citation = Citation(citation_items) |
| 88 |
citation.key = cit['citationID'] |
| 89 |
citation.note_index = cit['properties']['noteIndex'] |
| 90 |
citations.append(citation) |
| 91 |
elif self.data['bibentries']: |
| 92 |
citation_items = [self.parse_citation_item({'id': entry}) |
| 93 |
for entry in self.data['bibentries'][-1]] |
| 94 |
citations = [Citation(citation_items)] |
| 95 |
else: |
| 96 |
citation_items = [self.parse_citation_item({'id': ref}) |
| 97 |
for ref in self.references] |
| 98 |
citations = [Citation(citation_items)] |
| 99 |
|
| 100 |
for citation in citations: |
| 101 |
self.bibliography.register(citation) |
| 102 |
|
| 103 |
if self.style.has_bibliography(): |
| 104 |
self.bibliography.sort() |
| 105 |
|
| 106 |
results = [] |
| 107 |
do_nothing = lambda x: None # callback passed to cite() |
| 108 |
if self.data['mode'] == 'citation': |
| 109 |
if self.data['citations']: |
| 110 |
for i, citation in enumerate(citations): |
| 111 |
if i == len(citations) - 1: |
| 112 |
dots_or_other = '>>' |
| 113 |
else: |
| 114 |
dots_or_other = '..' |
| 115 |
results.append('{}[{}] '.format(dots_or_other, i) + |
| 116 |
self.bibliography.cite(citation, do_nothing)) |
| 117 |
else: |
| 118 |
for citation in citations: |
| 119 |
results.append(self.bibliography.cite(citation, do_nothing)) |
| 120 |
elif self.data['mode'] in ('bibliography', 'bibliography-nosort'): |
| 121 |
results.append(self.bib_prefix) |
| 122 |
for entry in self.bibliography.bibliography(): |
| 123 |
text = self.item_prefix + str(entry) + self.item_suffix |
| 124 |
results.append(text) |
| 125 |
results.append(self.bib_suffix) |
| 126 |
return results |
| 127 |
|
| 128 |
def parse_citation(self, citation_data): |
| 129 |
citation_items = [] |
| 130 |
for item in citation_data: |
| 131 |
citation_item = self.parse_citation_item(item) |
| 132 |
citation_items.append(citation_item) |
| 133 |
return Citation(citation_items) |
| 134 |
|
| 135 |
def parse_citation_item(self, citation_item_data): |
| 136 |
options = {} |
| 137 |
for key, value in citation_item_data.items(): |
| 138 |
python_key = key.replace('-', '_') |
| 139 |
if python_key == 'id': |
| 140 |
reference_key = str(value) |
| 141 |
continue |
| 142 |
elif python_key == 'locator': |
| 143 |
try: |
| 144 |
options['locator'] = Locator(citation_item_data['label'], |
| 145 |
value) |
| 146 |
except KeyError: |
| 147 |
# some tests don't specify the label |
| 148 |
options['locator'] = Locator('page', value) |
| 149 |
elif python_key == 'label': |
| 150 |
pass |
| 151 |
else: |
| 152 |
options[python_key] = value |
| 153 |
return CitationItem(reference_key, **options) |
| 154 |
|
| 155 |
|
| 156 |
class FailedTests(object): |
| 157 |
"""Read the known failed tests from a file and update the file with the |
| 158 |
results from a new test run.""" |
| 159 |
def __init__(self, filename): |
| 160 |
self.filename = filename |
| 161 |
with open(filename, 'r') as file: |
| 162 |
self.lines = file.readlines() |
| 163 |
self.now_failing = {} |
| 164 |
self.updated_lines = [] |
| 165 |
|
| 166 |
def mark_failure(self, test_name, reason=None): |
| 167 |
self.now_failing[test_name] = reason |
| 168 |
|
| 169 |
def compare(self): |
| 170 |
assert not self.updated_lines |
| 171 |
was_failing = set() |
| 172 |
new_failing_tests = [] |
| 173 |
new_fixed_tests = [] |
| 174 |
for line in self.lines: |
| 175 |
test_name, comment = (line.split('#') if '#' in line |
| 176 |
else (line, None)) |
| 177 |
test_name = test_name.strip() |
| 178 |
if test_name and test_name not in self.now_failing: |
| 179 |
new_fixed_tests.append(test_name) |
| 180 |
continue |
| 181 |
was_failing.add(test_name) |
| 182 |
self.updated_lines.append(line) |
| 183 |
for test_name in sorted(self.now_failing.keys()): |
| 184 |
if test_name not in was_failing: |
| 185 |
reason = self.now_failing[test_name] |
| 186 |
line = ('{:<66} # {}'.format(test_name, reason) if reason |
| 187 |
else test_name) |
| 188 |
self.updated_lines.append(line + '\n') |
| 189 |
new_failing_tests.append(test_name) |
| 190 |
return new_failing_tests, new_fixed_tests |
| 191 |
|
| 192 |
def update_file(self): |
| 193 |
assert self.updated_lines |
| 194 |
with open(self.filename, 'w') as file: |
| 195 |
file.writelines(self.updated_lines) |
| 196 |
|
| 197 |
|
| 198 |
def execute_git_command(args, echo=False): |
| 199 |
"""Execute a git command, exiting this script when it returns a |
| 200 |
non-zero error code.""" |
| 201 |
command = ['git'] + args |
| 202 |
if echo: |
| 203 |
print(' '.join(command)) |
| 204 |
process = Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE) |
| 205 |
out, err = process.communicate() |
| 206 |
if process.returncode: |
| 207 |
print('Calling git failed. Make sure git is installed. Aborting.') |
| 208 |
sys.exit(1) |
| 209 |
return out, err |
| 210 |
|
| 211 |
|
| 212 |
def clone_test_suite(): |
| 213 |
"""Clone the citeproc-test repository if it is not present. Otherwise, check |
| 214 |
whether the correct commit is checked out.""" |
| 215 |
if not os.path.exists(CITEPROC_TEST_PATH): |
| 216 |
git_clone = ['clone', CITEPROC_TEST_REPOSITORY, CITEPROC_TEST_PATH] |
| 217 |
print('Cloning the test-suite repository...') |
| 218 |
execute_git_command(git_clone, echo=True) |
| 219 |
git_checkout = ['-C', CITEPROC_TEST_PATH, 'checkout', |
| 220 |
CITEPROC_TEST_COMMIT] |
| 221 |
print('Checking out the specified commit...') |
| 222 |
execute_git_command(git_checkout) |
| 223 |
else: |
| 224 |
git_ref = ['-C', CITEPROC_TEST_PATH, 'rev-parse', 'HEAD'] |
| 225 |
commit_ref, _ = execute_git_command(git_ref) |
| 226 |
if commit_ref.strip() != CITEPROC_TEST_COMMIT.encode('ascii'): |
| 227 |
print('The checked-out commit of test-suite does not match \n' |
| 228 |
'the one recorded in this test script. Aborting.') |
| 229 |
sys.exit(1) |
| 230 |
git_fetch = ['-C', CITEPROC_TEST_PATH, 'fetch'] |
| 231 |
execute_git_command(git_fetch) |
| 232 |
git_ref = ['-C', CITEPROC_TEST_PATH, 'rev-parse', 'origin/master'] |
| 233 |
commit_ref, _ = execute_git_command(git_ref) |
| 234 |
has_updates = commit_ref.strip() != CITEPROC_TEST_COMMIT.encode('ascii') |
| 235 |
return has_updates |
| 236 |
|
| 237 |
|
| 238 |
RED = '\033[91m' |
| 239 |
GREEN = '\033[92m' |
| 240 |
BOLD = '\033[1m' |
| 241 |
END = '\033[0m' |
| 242 |
|
| 243 |
|
| 244 |
if __name__ == '__main__': |
| 245 |
usage = ('usage: %prog [options] glob_pattern\n\n' |
| 246 |
'glob_pattern limits the tests that are executed, for example:\n' |
| 247 |
' %prog *Sort*\n' |
| 248 |
'runs only test fixtures that have "Sort" in the filename') |
| 249 |
parser = OptionParser(usage) |
| 250 |
parser.add_option('-m', '--max', dest='max', default=-1, |
| 251 |
help='run up to MAX tests', metavar='MAX') |
| 252 |
parser.add_option('-v', '--verbose', dest='verbose', action='store_true', |
| 253 |
default=False, help='print results for each test') |
| 254 |
parser.add_option('-r', '--raise', dest='catch_exceptions', default=True, |
| 255 |
action='store_false', |
| 256 |
help='do not catch exceptions (aborts program)') |
| 257 |
parser.add_option('-s', '--summary', dest='summary', action='store_true', |
| 258 |
default=False, help='print a summary of the test results') |
| 259 |
parser.add_option('-n', '--no-update', dest='update', action='store_false', |
| 260 |
default=True, help='do not update {}' |
| 261 |
.format(FAILING_TESTS_FILE)) |
| 262 |
parser.add_option('-f', '--file', dest='file', default=None, |
| 263 |
help='write output to FILE', metavar='FILE') |
| 264 |
(options, args) = parser.parse_args() |
| 265 |
|
| 266 |
max_tests = int(options.max) |
| 267 |
try: |
| 268 |
destination = open(options.file, 'wt', encoding='utf-8') |
| 269 |
class UnicodeWriter(object): |
| 270 |
def write(self, s): |
| 271 |
destination.write(str(s)) |
| 272 |
sys.stderr = UnicodeWriter() |
| 273 |
except TypeError: |
| 274 |
destination = sys.stdout |
| 275 |
|
| 276 |
def out(*args): |
| 277 |
if not args: |
| 278 |
destination.write('\n') |
| 279 |
else: |
| 280 |
print(*args, file=destination) |
| 281 |
|
| 282 |
def print_result(name, passed, total): |
| 283 |
out(' {:<13} {:>3} / {:>3} ({:>4.0%})'.format(name, passed, total, |
| 284 |
passed / total)) |
| 285 |
|
| 286 |
try: |
| 287 |
glob_pattern = args[0] |
| 288 |
run_all_tests = False |
| 289 |
except IndexError: |
| 290 |
glob_pattern = '*' |
| 291 |
run_all_tests = True |
| 292 |
|
| 293 |
test_repo_has_updates = clone_test_suite() |
| 294 |
|
| 295 |
# import the text fixture parser included with citeproc-test |
| 296 |
spec = importlib.util.spec_from_file_location('processor', TEST_PARSER_PATH) |
| 297 |
processor = importlib.util.module_from_spec(spec) |
| 298 |
sys.modules['processor'] = processor |
| 299 |
spec.loader.exec_module(processor) |
| 300 |
CslTest = processor.CslTest |
| 301 |
|
| 302 |
total_count = {} |
| 303 |
passed_count = {} |
| 304 |
failed_tests = FailedTests(os.path.join(os.path.dirname(__file__), |
| 305 |
FAILING_TESTS_FILE)) |
| 306 |
count = 0 |
| 307 |
test_files = list(glob.glob(os.path.join(TESTS_PATH, '{}.txt'.format(glob_pattern)))) |
| 308 |
test_files += list(glob.glob(os.path.join(LOCAL_TESTS_PATH, '{}.txt'.format(glob_pattern)))) |
| 309 |
for filename in sorted(test_files): |
| 310 |
test_name, _ = os.path.basename(filename).split('.txt') |
| 311 |
category, _ = os.path.basename(filename).split('_') |
| 312 |
passed_count.setdefault(category, 0) |
| 313 |
if count == max_tests: |
| 314 |
break |
| 315 |
|
| 316 |
reason = None |
| 317 |
try: |
| 318 |
if test_name not in IGNORED_RESULS: |
| 319 |
total_count[category] = total_count.get(category, 0) + 1 |
| 320 |
count += 1 |
| 321 |
t = ProcessorTest(filename) |
| 322 |
if run_all_tests and (t.data['mode'] == 'bibliography-header' or |
| 323 |
t.data['bibsection']): |
| 324 |
continue |
| 325 |
if options.verbose: |
| 326 |
out('>>> Testing {}'.format(os.path.basename(filename))) |
| 327 |
out('EXP: ' + '\n '.join(t.expected)) |
| 328 |
|
| 329 |
results = t.execute() |
| 330 |
results = reduce(lambda x, y: x+y, |
| 331 |
[item.split('\n') for item in results]) |
| 332 |
results = [item.replace('&', '&') |
| 333 |
for item in results] |
| 334 |
if options.verbose: |
| 335 |
out('RES: ' + '\n '.join(results)) |
| 336 |
if results == t.expected: |
| 337 |
if test_name not in IGNORED_RESULS: |
| 338 |
passed_count[category] += 1 |
| 339 |
if options.verbose: |
| 340 |
out('<<< SUCCESS\n') |
| 341 |
continue |
| 342 |
else: |
| 343 |
if options.verbose: |
| 344 |
out('<<< FAILED\n') |
| 345 |
del t |
| 346 |
except Exception as e: |
| 347 |
if not options.catch_exceptions: |
| 348 |
raise |
| 349 |
if options.verbose: |
| 350 |
out('Exception in', os.path.basename(filename)) |
| 351 |
traceback.print_exc() |
| 352 |
out('<<< FAILED\n') |
| 353 |
reason = 'uncaught exception' |
| 354 |
if test_name not in IGNORED_RESULS: |
| 355 |
failed_tests.mark_failure(test_name, reason) |
| 356 |
|
| 357 |
success = False |
| 358 |
if sum(total_count.values()) == 0: |
| 359 |
print('<no tests found>: check README.md file for instructions') |
| 360 |
else: |
| 361 |
if run_all_tests: |
| 362 |
new_failing, new_fixed = failed_tests.compare() |
| 363 |
success = not (new_failing or new_fixed) |
| 364 |
if options.update: |
| 365 |
failed_tests.update_file() |
| 366 |
|
| 367 |
if new_failing: |
| 368 |
out(BOLD + 'New failing tests:' + END) |
| 369 |
for test_name in new_failing: |
| 370 |
out(' ' + RED + test_name + END) |
| 371 |
if new_failing or new_fixed: |
| 372 |
out() |
| 373 |
else: |
| 374 |
out('All is well.') |
| 375 |
if new_fixed: |
| 376 |
out(BOLD + 'Fixed tests:' + END) |
| 377 |
for test_name in new_fixed: |
| 378 |
out(' ' + GREEN + test_name + END) |
| 379 |
out() |
| 380 |
out('You need to fix the newly failing tests and may commit the \n' |
| 381 |
'removal of the fixed tests from {}'.format(FAILING_TESTS_FILE)) |
| 382 |
|
| 383 |
if test_repo_has_updates: |
| 384 |
out() |
| 385 |
out(BOLD + 'The test-suite repository has updates! Consider ' |
| 386 |
'updating the test script.' + END) |
| 387 |
else: |
| 388 |
failing = sorted(failed_tests.now_failing.keys()) |
| 389 |
success = not failing |
| 390 |
out(BOLD + 'Failing tests:' + END) |
| 391 |
for test_name in failing: |
| 392 |
out(' ' + RED + test_name + END) |
| 393 |
if options.summary: |
| 394 |
out() |
| 395 |
out(BOLD + 'Summary:' + END) |
| 396 |
for category in sorted(total_count.keys()): |
| 397 |
print_result(category, passed_count[category], |
| 398 |
total_count[category]) |
| 399 |
out() |
| 400 |
print_result('total', sum(passed_count.values()), |
| 401 |
sum(total_count.values())) |
| 402 |
try: |
| 403 |
destination.close() |
| 404 |
except AttributeError: |
| 405 |
pass |
| 406 |
sys.exit(0 if success else 1) |