This repository has been archived by the owner on May 3, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
Initial work on a regex implementation. #13
Open
deontologician
wants to merge
1
commit into
uri-templates:master
Choose a base branch
from
deontologician:regex
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,175 @@ | ||
''' | ||
Tests related to the as_regex function. Uses the same testcases as the | ||
expand function, but repurposes them to ensure the regex created | ||
produces the right output. | ||
''' | ||
import sys | ||
from os.path import join, dirname | ||
try: | ||
import json | ||
except ImportError: | ||
import simplejson as json | ||
import urllib | ||
import traceback | ||
import pdb | ||
|
||
import uritemplate | ||
|
||
TESTFILES = [ | ||
'spec-examples.json', | ||
'spec-examples-by-section.json', | ||
'extended-tests.json', | ||
] | ||
|
||
|
||
def correct_answers(var): | ||
'''Take a variable and produce a list of possibly correct | ||
answers''' | ||
safe = ":/?#[]@!$&'()*+,;=" | ||
def quote(v): | ||
v = '' if v is None else v | ||
return urllib.quote(str(v), '') | ||
|
||
def restrictquote(v): | ||
v = '' if v is None else v | ||
return urllib.quote(str(v), safe) | ||
|
||
if isinstance(var, list): | ||
return [','.join(map(restrictquote, var)), | ||
','.join(map(quote, var))] | ||
elif isinstance(var, dict): | ||
return [urllib.urlencode(var, safe), | ||
','.join(restrictquote(v) | ||
for item in var.iteritems() for v in item), | ||
','.join(quote(v) for item in var.iteritems() for v in item), | ||
] | ||
else: | ||
return [restrictquote(var), quote(var)] | ||
|
||
def _print_level(level, prefix): | ||
def _print_method(self, tpl, *args, **kwargs): | ||
if self.verbosity >= level: | ||
print prefix, tpl.format(*args, **kwargs) | ||
return _print_method | ||
|
||
|
||
class TestRunner(object): | ||
def __init__(self, verbosity=0, one_failure=False, fail_into_pdb=False): | ||
self.verbosity = verbosity | ||
self.one_failure = one_failure | ||
self.fail_into_pdb = fail_into_pdb | ||
|
||
self.failures = 0 | ||
self.successes = 0 | ||
|
||
print1 = _print_level(1, '||') | ||
print2 = _print_level(2, ';;') | ||
print3 = _print_level(3, ',,') | ||
print4 = _print_level(4, '. ') | ||
|
||
def main(self): | ||
cases_dir = join(dirname(__file__), 'cases') | ||
for testfile in TESTFILES: | ||
self.print2('Running Testfile: {0}', testfile) | ||
self.print2('=' * 80) | ||
with open(join(cases_dir, testfile), 'r') as tf: | ||
self.test_document(json.load(tf)) | ||
self.finish() | ||
|
||
def test_document(self, test_doc): | ||
for testname, testdef in sorted(test_doc.iteritems()): | ||
fails, succeeds = 0, 0 | ||
self.print2('{0}:', testname) | ||
variables = testdef['variables'] | ||
testcases = testdef['testcases'] | ||
for major_num, (template, inputs) in enumerate(testcases, 1): | ||
if not isinstance(inputs, list): | ||
# Correct for multiple 'expected' | ||
inputs = [inputs] | ||
for minor_num, to_match in enumerate(inputs, 1): | ||
self.print3(' Case # {0}.{1}', major_num, minor_num) | ||
if not self.test(variables, template, to_match): | ||
fails += 1 | ||
self.failures += 1 | ||
if self.one_failure: | ||
self.finish() | ||
else: | ||
self.successes += 1 | ||
succeeds += 1 | ||
self.print2(" {0} Successes, {1} Failures", succeeds, fails) | ||
|
||
def finish(self, final=False): | ||
self.print1('{0} tests succeeded.', self.successes) | ||
self.print1('{0} tests failed', self.failures) | ||
sys.exit(self.failures) | ||
|
||
def test(self, variables, template, to_match): | ||
# Normalize url escaping since mixed quoting is not what the | ||
# regex will be used for | ||
self.print4("'{0}' matching '{1}'", template, to_match) | ||
try: | ||
testvars = uritemplate.variables(template) | ||
regex = uritemplate.as_regex(template) | ||
except Exception as e: | ||
if self.fail_into_pdb: | ||
pdb.post_mortem() | ||
self.print4(traceback.format_exc()) | ||
self.print3(' Failed with: ' + repr(e)) | ||
return False | ||
self.print4('Regex is: {0}', regex.pattern) | ||
|
||
try: | ||
matchvars = regex.match(to_match).groupdict() | ||
except AttributeError: | ||
if self.fail_into_pdb: | ||
pdb.post_mortem() | ||
self.print3(' Failed with: Regex did not match expected') | ||
return False | ||
|
||
for var in testvars: | ||
match_var = matchvars.get(var) | ||
if not self.matches(match_var, variables[var], var): | ||
if self.fail_into_pdb: | ||
pdb.set_trace() | ||
return False | ||
return True | ||
|
||
def matches(self, match_var, expect_var, varname): | ||
possible_correct = correct_answers(expect_var) | ||
for answer in possible_correct: | ||
if answer.startswith(match_var): | ||
result = True | ||
break | ||
else: | ||
result = False | ||
self.print3_expectation(match_var, possible_correct, varname) | ||
return result | ||
|
||
def print3_expectation(self, match_var, answers, var): | ||
if len(set(answers)) == 1: | ||
outstring = " For '{var}' expected '{varU}',"\ | ||
" got '{match_var}'" | ||
else: | ||
outstring = " For '{var}' expected one of {answers!r}"\ | ||
", got '{match_var}'" | ||
self.print3( | ||
outstring, var=var, match_var=match_var, answers=answers) | ||
|
||
|
||
if __name__ == "__main__": | ||
verbosity, one_failure = 0, False | ||
if '-1' in sys.argv: | ||
verbosity = 1 | ||
if '-2' in sys.argv: | ||
verbosity = 2 | ||
if '-3' in sys.argv: | ||
verbosity = 3 | ||
if '-4' in sys.argv: | ||
verbosity = 4 | ||
TR = TestRunner( | ||
verbosity=verbosity, | ||
one_failure='-x' in sys.argv, | ||
fail_into_pdb='-pdb' in sys.argv, | ||
) | ||
TR.main() | ||
|
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,4 @@ | ||
|
||
from uritemplate import expand, variables | ||
from uritemplate import expand, variables, as_regex | ||
|
||
__version__ = "0.5.2" |
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
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Bit of a strange way to run the tests? Does the project not have a test runner?