Skip to content

Commit 37be3f8

Browse files
committed
NF: assert_re_in helper to check if any line matches the re
1 parent 2f613fb commit 37be3f8

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

nibabel/testing/__init__.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
''' Utilities for testing '''
1010
from __future__ import division, print_function
1111

12+
import re
1213
import os
1314
import sys
1415
import warnings
@@ -59,6 +60,17 @@ def assert_allclose_safely(a, b, match_nans=True):
5960
assert_true(np.allclose(a, b))
6061

6162

63+
def assert_re_in(regex, c, flags=0):
64+
"""Assert that container (list, str, etc) contains entry matching the regex
65+
"""
66+
if not isinstance(c, (list, tuple)):
67+
c = [c]
68+
for e in c:
69+
if re.match(regex, e, flags=flags):
70+
return
71+
raise AssertionError("Not a single entry matched %r in %r" % (regex, c))
72+
73+
6274
def get_fresh_mod(mod_name=__name__):
6375
# Get this module, with warning registry empty
6476
my_mod = sys.modules[mod_name]

nibabel/tests/test_testing.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from nose.tools import assert_true, assert_equal, assert_raises
1111
from ..testing import (error_warnings, suppress_warnings,
1212
clear_and_catch_warnings, assert_allclose_safely,
13-
get_fresh_mod)
13+
get_fresh_mod, assert_re_in)
1414

1515

1616
def assert_warn_len_equal(mod, n_in_context):
@@ -142,3 +142,24 @@ def f():
142142
with suppress_warnings():
143143
raise ValueError('An error')
144144
assert_raises(ValueError, f)
145+
146+
147+
def test_assert_re_in():
148+
assert_re_in(".*", "")
149+
assert_re_in(".*", ["any"])
150+
151+
# should do match not search
152+
assert_re_in("ab", "abc")
153+
assert_raises(AssertionError, assert_re_in, "ab", "cab")
154+
assert_raises(AssertionError, assert_re_in, "ab$", "abc")
155+
156+
# Sufficient to have one entry matching
157+
assert_re_in("ab", ["", "abc", "laskdjf"])
158+
assert_raises(AssertionError, assert_re_in, "ab$", ["ddd", ""])
159+
160+
# Tuples should be ok too
161+
assert_re_in("ab", ("", "abc", "laskdjf"))
162+
assert_raises(AssertionError, assert_re_in, "ab$", ("ddd", ""))
163+
164+
# shouldn't "match" the emty list
165+
assert_raises(AssertionError, assert_re_in, "", [])

0 commit comments

Comments
 (0)