Created
August 9, 2014 13:18
-
-
Save prophile/fb31271a8a722de1a490 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function | |
from collections import namedtuple, defaultdict | |
Check = namedtuple('Check', 'description check') | |
Condition = namedtuple('Condition', 'severity format') | |
Failure = namedtuple('Failure', 'type severity message data') | |
class Validator(object): | |
def __init__(self): | |
self.checks = [] | |
self.conditions = {} | |
def condition(self, name, severity, format): | |
if severity not in ('error', 'warning'): | |
raise ValueError() | |
self.conditions[name] = Condition(severity=severity, | |
format=format) | |
def check(self, description): | |
def wrapper(fn): | |
self.checks.append(Check(description = description, | |
check = fn)) | |
return fn | |
return wrapper | |
def suppress(self, condition): | |
self.conditions[condition] = \ | |
self.conditions[condition]._replace(severity='warning') | |
def validate(self, value, suppress=[]): | |
failures = [] | |
severity_counts = defaultdict(lambda: 0) | |
def notify(condition, **kwargs): | |
if condition in suppress: | |
return | |
cnd = self.conditions.get(condition) | |
if cnd.severity is None: | |
raise KeyError("Unknown failure mode: {}".format(condition)) | |
severity_counts[cnd.severity] += 1 | |
failures.append(Failure(type = condition, | |
severity = cnd.severity, | |
message = cnd.format.format(**kwargs), | |
data = kwargs)) | |
for check in self.checks: | |
check.check(value, notify) | |
return severity_counts['error'] == 0, failures | |
# Example, very-reduced compstate | |
compstate_validator = Validator() | |
compstate_validator.condition('match-non-existent-team', | |
'error', | |
'Match {match} contains non-existent team {team}.') | |
@compstate_validator.check('all matches are populated with extant teams') | |
def check_extant_teams(state, notify): | |
for match_number, match in enumerate(state['matches']): | |
for team in match: | |
if team is not None and team not in state['teams']: | |
notify('match-non-existent-team', | |
match=match_number, | |
team=team) | |
compstate = {'teams': ['RWD', 'RGS'], | |
'matches': [['RWD', 'RGS', None, 'TTN']]} | |
test_result, failures = compstate_validator.validate(compstate) | |
print("Validation {}".format("PASSED" if test_result else "FAILED")) | |
for failure in failures: | |
print("[{}]: {}".format(failure.severity, failure.message)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment