Commit e0420b3e authored by Denis Salem's avatar Denis Salem
Browse files

almost done with pattern processor testing + small refactorisation

parent 4f897b81
......@@ -150,7 +150,7 @@
DONE | Fix pattern (i.e .:GetEntryTitle:.) access in template's metadata.
DONE | Infinite scroll use html anchor instead of harcoded indexing.
DONE | Prevent Infinite scroll to block when ressource isn't available.
WIP | Rewrite unit tests.
WIP | Rewrite pattern processor unit tests.
TODO | Open with navigator manual.
TODO | Client-side search engine.
TODO | Reorganize themes dependencies in setup (adding default templates, scripts, and pages to include).
......@@ -176,3 +176,4 @@
TODO | Print out what's going on while FTP transfert.
TODO | Fix gvim / -ex.
TODO | Warn about entry title duplicates.
TODO | Handle missing args in case of unknown number of args
......@@ -25,6 +25,7 @@ from venc2.helpers import die
from venc2.helpers import notify
from venc2.l10n import messages
""" Need to handle missing args in case of unknown number of args """
class CodeHighlight:
def __init__(self, override):
self._override = override
......
......@@ -20,11 +20,20 @@
import random
from venc2.patterns.exceptions import PatternInvalidArgument
from venc2.patterns.exceptions import PatternMissingArguments
from venc2.l10n import messages
arg_names=["min","max","decimal_number"]
def get_random_number(in_argv):
arg_names=["min","max","decimal_number"]
try:
mn, mx, precision = in_argv
except ValueError as e:
raise PatternMissingArguments(e)
argv = []
for i in range(0,3):
try:
argv.append(int(in_argv[i]))
......@@ -32,8 +41,8 @@ def get_random_number(in_argv):
except ValueError:
raise PatternInvalidArgument(arg_names[i],in_argv[i], messages.pattern_argument_must_be_integer)
v = argv[0] + random.random() * (argv[1] - argv[0] + 1)
return str(int(v)) if argv[2] == 0 else str(round(v, argv[2]))
v = mn + random.random() * (mx - mn + 1)
return str(int(v)) if precision == 0 else str(round(v, precision))
extra_contextual_pattern_names = {
"GetRandomNumber" : get_random_number
......
......@@ -37,10 +37,12 @@ class PatternInvalidArgument(Exception):
class PatternMissingArguments(Exception):
def __init__(self, e=messages.not_enough_args.format(1,0)):
if type(e) != str():
if type(e) != str:
v = e.args[0].replace(',',' ').replace(')',' ').split()
l = [int(s) for s in v if s.isdigit()]
self.info = messages.not_enough_args.format(l[0],l[1])
self.expected, self.got = tuple([int(s) for s in v if s.isdigit()])
self.info = messages.not_enough_args.format(self.expected, self.got)
else:
else:
self.expected = 1
self.got = 0
self.info = e
......@@ -21,12 +21,16 @@ import latex2mathml.converter
from venc2.l10n import messages
from venc2.patterns.exceptions import PatternInvalidArgument
from venc2.patterns.exceptions import PatternMissingArguments
def Latex2MathML(argv):
tex_math_string = argv[0]
try:
tex_math_string = argv[0]
return latex2mathml.converter.convert(tex_math_string)
except IndexError:
raise PatternMissingArguments()
except Exception as e:
print(e)
raise PatternInvalidArgument(
......
......@@ -24,6 +24,7 @@ import requests
from venc2 import venc_version
from venc2.l10n import messages
from venc2.patterns.exceptions import PatternInvalidArgument
from venc2.patterns.exceptions import PatternMissingArguments
from venc2.helpers import GenericMessage
from venc2.helpers import notify
from urllib.parse import urlparse
......@@ -64,12 +65,18 @@ def try_oembed(providers, url):
return html
def get_embed_content(providers, argv):
url = urlparse(argv[0])
try:
url = urlparse(argv[0])
except IndexError:
raise PatternMissingArguments()
return try_oembed(providers, url)
def get_venc_version(argv):
return venc_version
""" Need to handle missing args in case of unknown number of args """
def set_color(argv):
return "<span style=\"color: "+('::'.join(argv[1:]))+";\">"+argv[0]+"</span>"
......@@ -78,7 +85,10 @@ def include_file(argv):
filename = argv[0]
include_string = open("includes/"+filename, 'r').read()
return include_string
except IndexError:
raise PatternMissingArguments()
except PermissionError:
raise PatternInvalidArgument("path", filename, messages.wrong_permissions.format(argv[0]))
......
......@@ -32,6 +32,9 @@ from venc2.helpers import remove_by_value
from venc2.l10n import messages
from venc2.patterns.exceptions import MalformedPatterns
from venc2.patterns.exceptions import UnknownContextual
from venc2.patterns.exceptions import PatternMissingArguments
from venc2.patterns.exceptions import PatternInvalidArgument
from venc2.helpers import GenericMessage
markup_language_errors = []
......@@ -274,6 +277,7 @@ class Processor():
error_origin = [".:"+pattern+"::"+"::".join(argv)+":."]
)
# might be removed
except FileNotFoundError as e:
output = self.handle_error(
e,
......
......@@ -3,26 +3,62 @@
from venc2.patterns.processor import ProcessedString # The object holding the string and its states
from venc2.patterns.processor import Processor # The actual string processor, holding binded methods.
from venc2.patterns.exceptions import MalformedPatterns
from venc2.patterns.exceptions import PatternMissingArguments
from venc2.patterns.exceptions import PatternInvalidArgument
from venc2.helpers import GenericMessage
from test_engine import run_tests
def add(argv):
a, b = tuple(argv)
try:
a, b = tuple(argv)
except Exception as e:
raise PatternMissingArguments(e)
return str( int(a) + int(b) )
def mul(argv):
a, b = tuple(argv)
try:
a, b = tuple(argv)
except Exception as e:
raise PatternMissingArguments(e)
return str( int(a) * int(b) )
def greater(argv):
a, b = tuple(argv)
try:
a, b = tuple(argv)
except Exception as e:
raise PatternMissingArguments(e)
return a if float(a) > float(b) else b
def upper(argv):
try:
a = argv[0]
except:
raise PatternMissingArguments()
return a.upper()
def trigger_generic_message_exception(argv):
raise GenericMessage("lol il will never work")
def trigger_pattern_invalid_argument_exception(argv):
raise PatternInvalidArgument("some field", "some value", "some message")
processor = Processor()
processor.debug = True
processor.set_function("add", add)
processor.set_function("mul", mul)
processor.set_function("greater", greater)
processor.set_function("upper", upper)
processor.set_function("trigger_generic_message_exception", trigger_generic_message_exception)
processor.set_function("trigger_pattern_invalid_argument_exception", trigger_pattern_invalid_argument_exception)
processor.blacklist.append("blacklisted")
def test_pattern_processor(args, test_name):
......@@ -60,8 +96,8 @@ tests = [
),
(
"Recursive Patterns plus extra trailing pattern.",
("moo .:mul::3::3:. .:greater:: .:add::1::1:. :: .:mul::2::2:. :. foo .:greater::1::2:. bar", False),
"moo 9 4 foo 2 bar",
("moo .:mul::3::3:. .:greater:: .:add::1::1:. :: .:mul::2::2:. :. foo .:upper::lower:. bar", False),
"moo 9 4 foo LOWER bar",
test_pattern_processor
),
(
......@@ -145,10 +181,27 @@ tests = [
(
"Missing pattern args.",
("moo .:mul::2:. foo .:add::3::3:.", True),
True,
(PatternMissingArguments, [("expected",2), ("got",1)]),
test_pattern_processor
),
(
"Missing unique and single pattern arg.",
("moo .:upper:. foo", True),
(PatternMissingArguments, [("expected",1), ("got",0)]),
test_pattern_processor
),
(
"Trigger GenericMessage.",
("moo .:trigger_generic_message_exception:. foo", True),
(GenericMessage, [("message","lol il will never work")]),
test_pattern_processor
),
(
"Trigger PatternInvalidArgument.",
("moo .:trigger_pattern_invalid_argument_exception:. foo", True),
(PatternInvalidArgument, [("message","some message"), ("name", "some field"), ("value", "some value")]),
test_pattern_processor
),
]
run_tests("Testing patterns processor...", tests)
......@@ -13,16 +13,27 @@ def run_tests(tests_name, tests):
except AssertionError as e:
print(get_formatted_message("\t"+test_name+" "+str(e), color="RED", prompt=""))
except Exception as e:
except Exception as venc_defined_exception:
try:
err, args = o
assert type(e) == err
for arg in args:
assert type(venc_defined_exception) == err
except AssertionError:
print(get_formatted_message("\t"+test_name+" "+str(err)+" != "+str(type(venc_defined_exception)), color="RED", prompt=""))
continue
params_okay = True
for arg in args:
try:
attr, value = arg
assert getattr(e, attr) == value, attr+" != "+str(value)
assert getattr(venc_defined_exception, attr) == value, attr+" != "+str(value)
except AssertionError as e:
print(get_formatted_message("\t"+test_name+" "+str(e), color="RED", prompt=""))
params_okay = False
if params_okay:
print(get_formatted_message("\t"+test_name+" Pass", prompt=""))
except AssertionError as e:
print(get_formatted_message("\t"+test_name+" "+str(e), color="RED", prompt=""))
print("Done.")
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment