Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Topotato: Regex Json Compare Directive #134

Open
wants to merge 3 commits into
base: topotato-base
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion topotato/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@
from .base import TestBase, topotatofunc
from .fixtures import *
from .assertions import *
from .utils import JSONCompareIgnoreContent
from .utils import JSONCompareIgnoreContent, JSONCompareRegex

del os
35 changes: 35 additions & 0 deletions topotato/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,32 @@ class JSONCompareDirective(dict):
"""




class JSONCompareRegex(JSONCompareDirective):
"""
Compare this value with a regular expression.

:Example:

JsonCompareRegex(r"\s+")
JsonCompareRegex(r"\d+")
JsonCompareRegex("[A-Z]")
JsonCompareRegex(r"^%?FRRouting/")

"""
regex: re.Pattern

def __init__(self, regex: str):
super().__init__()

self.regex = re.compile(regex)

def match(self, string):
return self.regex.match(string)



class JSONCompareIgnoreContent(JSONCompareDirective):
"""
Ignore list/dict content in JSON compare.
Expand Down Expand Up @@ -333,6 +359,15 @@ def json_cmp(d1, d2):
raise JSONCompareDirectiveWrongSide(nd1[key])

if isinstance(nd2[key], JSONCompareDirective):
if isinstance(nd2[key], JSONCompareRegex):
if not nd2[key].match(str(nd1[key])):
eznix86 marked this conversation as resolved.
Show resolved Hide resolved
result.add_error(
'{}["{}"] dict value is different (\n{} vs regex {})'.format(
parent, key, nd1[key], repr(nd2[key].regex.pattern)
)
)
continue

if isinstance(nd2[key], JSONCompareIgnoreContent):
continue

Expand Down
1 change: 1 addition & 0 deletions topotato/v1.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
JSONCompareIgnoreContent,
JSONCompareIgnoreExtraListitems,
JSONCompareListKeyedDict,
JSONCompareRegex
)
from .network import (
TopotatoNetwork,
Expand Down