Python regex validation using py.test

Regexes are still a bit of dark art for me, but I think one of those things that just do the practice. So I'm more interested in being able to create py.test functions that show me where my regular expressions fail. My current code looks something like this:

my_regex = re.compile("<this is where the magic (doesn't)? happen(s)?>")

def test_my_regex():
    tests = ["an easy test that I'm sure will pass",
             "a few things that may trip me up",
             "a really pathological, contrived example",
             "something from the real world?"]

    test_matches = [my_regex.match(test) for test in tests]

    for i in range(len(tests)):
        print("{}: {!r}".format(i, tests[i]))
        assert test_matches[i] is not None

for which the output, when I run py.test myfile.py, is similar to

0: "an easy..."
1: "a few things..."
2: "a really pathological..."

where is the last - the first (only?) that failed the test.

I suppose I could do something like

assertSequenceEqual(test_matches, [not None]*len(test_matches))

but it seems rude, and I got the impression that it <object> is not Noneis the preferred way to verify that the object is not None, not <object> != None.

+4
2

- parametrize.

my_regex = re.compile("<this is where the magic (doesn't)? happen(s)?>")

@pytest.mark.parametrize('test_str', [
    "an easy test that I'm sure will pass",
    "a few things that may trip me up",
    "a really pathological, contrived example",
    "something from the real world?",
])
def test_my_regex(test_str):
     assert my_regex.match(test_str) is not None

. IMO , , , test_str , .

+12

all:

assert all([my_regex.match(test) for test in goodinputs])

, , , any.

assert not any([my_regex.match(test) for test in badinputs])

, , , :

for test in tests:
    assert my_regex.match(test), test

test, .

.

, :

failures = [test for test in tests if not my_regex.match(test)]
assert len(failures) == 0, failures
+2

Source: https://habr.com/ru/post/1534698/


All Articles