]> dreyeck.freedombox.rocks Git - topic-maps.git/blob - scripts/check-dates.py
Canonicalize DateTime timezone offsets with explicit baseline discrepancies
[topic-maps.git] / scripts / check-dates.py
1 #!/usr/bin/env python3
2 """Independent date grammar/calendar arithmetic and unchanged baseline/model evidence.
3 Uses Python arbitrary-precision integers and calendar.isleap, never datetime/localtime.
4 """
5 import calendar
6 import json
7 import pathlib
8 import re
9 import sys
10 import xml.etree.ElementTree as ET
11
12 if hasattr(sys, 'set_int_max_str_digits'):
13 sys.set_int_max_str_digits(0)
14 root = pathlib.Path(__file__).resolve().parent.parent
15 report = json.loads(pathlib.Path(sys.argv[1]).read_text())
16 assert report['kind'] == 'date-semantic-and-cxtm-evidence' and report['failed'] == 0
17 assert report['passed'] == len(report['checks']) == len(set(report['checks']))
18 names = ['occurrence-date', 'occurrence-date2', 'occurrence-date3', 'occurrence-date-negative', 'occurrence-date-another-century']
19 values = [['1976-09-19'], ['1976-10-09'], ['0001-12-02', '0011-12-02', '0111-12-02', '1111-12-02'], ['-1976-09-19'], ['191976-09-19']]
20 dt = 'http://www.w3.org/2001/XMLSchema#date'
21 assert [c['id'] for c in report['cases']] == ['ctm/in/' + n + '.ctm' for n in names]
22 for c, expected in zip(report['cases'], values):
23 doc = c['documentIRI']; model = c['actualObjects']
24 assert doc == 'https://ctm-tests.example.invalid/cd165b150176c1d6842b37be9cc9051b40d4996b/' + c['id']
25 assert c['ctmSource'].encode() == (root / 'vendor/cxtm' / c['id']).read_bytes()
26 assert model['topicCount'] == len(expected) + 1 and model['occurrenceCount'] == len(expected)
27 assert model['nameCount'] == model['associationCount'] == 0
28 for i, t in enumerate(model['topics']):
29 local = 'topic' if i == 0 else 'occtype' if len(expected) == 1 else 'o' + str(i)
30 assert t['itemIdentifiers'] == [doc + '#' + local]
31 assert t['subjectIdentifiers'] == t['subjectLocators'] == []
32 if i:
33 assert t['occurrences'] == []
34 assert model['topics'][0]['occurrences'] == [dict(value=v, datatype=dt, parentTopicOrdinal=1,
35 typeTopicOrdinal=i+2, itemIdentifiers=[]) for i, v in enumerate(expected)]
36 negative = ['date-invalid-day', 'date-invalid-month', 'date-invalid-year', 'date-invalid-year2', 'date-invalid-year3']
37 assert [c['id'] for c in report['negativeCases']] == ['ctm/invalid/' + n + '.ctm' for n in negative]
38 for c, code in zip(report['negativeCases'], ['INVALID-DATE-DAY', 'INVALID-DATE-MONTH'] + ['INVALID-DATE-YEAR']*3):
39 assert c['ctmSource'].encode() == (root / 'vendor/cxtm' / c['id']).read_bytes()
40 assert c['status'] == 'pass' and c['conditionClass'] == 'CTM-REJECTION' and c['code'] == code
41 assert c['line'] == c['ctmSource'][:c['position']].count('\n') + 1
42 assert c['column'] == c['position'] - c['ctmSource'].rfind('\n', 0, c['position']) == 14
43
44
45 def valid_date(text):
46 match = re.fullmatch(r'(-?)([0-9]{4,})-([0-9]{2})-([0-9]{2})', text)
47 if not match:
48 return False
49 sign, digits, month, day = match.groups()
50 if len(digits) > 4 and digits.startswith('0'):
51 return False
52 year, month, day = int(sign + digits), int(month), int(day)
53 if year == 0 or not 1 <= month <= 12:
54 return False
55 days = [31, 29 if calendar.isleap(year) else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month-1]
56 return 1 <= day <= days
57
58
59 assert len(report['calendarDecisions']) == 15
60 for c in report['calendarDecisions']:
61 assert valid_date(c['input']) == (c['expected'] == 'valid'), c
62 for p in report['lexicalProbes']:
63 lexical = p['input'].strip(' \r\t\n')
64 assert valid_date(lexical), lexical
65 assert p['storedValue'] == p['input'] and p['datatype'] == dt
66 xml = ET.fromstring(p['actualCXTM'])
67 items = xml.findall('topic/occurrence')
68 assert len(items) == 1 and items[0].findtext('value') == lexical and items[0].findtext('datatype') == dt
69 print(f"DATE-INDEPENDENT-PASS: 5 original sources/model observations; 5 specific rejections; {len(report['lexicalProbes'])} arbitrary-precision calendar probes; 15 century decisions")