Skip to content

Commit 6e673c7

Browse files
committed
TST: switch to automated TestCase discovery.
Avoid need to maintain a list of test modules. Also add `pattern` argument to testsuite() for filtering test cases.
1 parent e7c2c15 commit 6e673c7

File tree

1 file changed

+35
-20
lines changed

1 file changed

+35
-20
lines changed

pyobjcryst/tests/__init__.py

Lines changed: 35 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -16,36 +16,51 @@
1616
"""Unit tests for pyobjcryst.
1717
"""
1818

19+
import unittest
1920

20-
def testsuite():
21-
'''Build a unit tests suite for the pyobjcryst package.
2221

23-
Return a unittest.TestSuite object.
22+
def testsuite(pattern=''):
23+
'''Create a unit tests suite for the pyobjcryst package.
24+
25+
Parameters
26+
----------
27+
pattern : str, optional
28+
Regular expression pattern for selecting test cases.
29+
Select all tests when empty.
30+
31+
Returns
32+
-------
33+
suite : `unittest.TestSuite`
34+
The TestSuite object containing the matching tests.
2435
'''
25-
import unittest
26-
modulenames = '''
27-
pyobjcryst.tests.testcif
28-
pyobjcryst.tests.testclocks
29-
pyobjcryst.tests.testconverters
30-
pyobjcryst.tests.testcrystal
31-
pyobjcryst.tests.testmolecule
32-
pyobjcryst.tests.testrefinableobj
33-
pyobjcryst.tests.testutils
34-
'''.split()
35-
suite = unittest.TestSuite()
36+
import re
37+
from itertools import chain
38+
from pkg_resources import resource_filename
3639
loader = unittest.defaultTestLoader
37-
mobj = None
38-
for mname in modulenames:
39-
exec ('import %s as mobj' % mname)
40-
suite.addTests(loader.loadTestsFromModule(mobj))
40+
thisdir = resource_filename(__name__, '')
41+
suite_all = loader.discover(thisdir)
42+
# shortcut when pattern is not specified
43+
if not pattern:
44+
return suite_all
45+
# here we need to filter the suite by pattern
46+
suite = unittest.TestSuite()
47+
rx = re.compile(pattern)
48+
tcases = chain.from_iterable(chain.from_iterable(suite_all))
49+
for tc in tcases:
50+
tcwords = tc.id().rsplit('.', 2)
51+
shortname = '.'.join(tcwords[-2:])
52+
if rx.search(shortname):
53+
suite.addTest(tc)
4154
return suite
4255

4356

4457
def test():
4558
'''Execute all unit tests for the pyobjcryst package.
46-
Return a unittest TestResult object.
59+
60+
Returns
61+
-------
62+
result : `unittest.TestResult`
4763
'''
48-
import unittest
4964
suite = testsuite()
5065
runner = unittest.TextTestRunner()
5166
result = runner.run(suite)

0 commit comments

Comments
 (0)