For instance, I want these to run in the order they appear in the file.
import unittest
class Test_MyTests(unittest.TestCase):
def test_run_me_first(self): pass
def test_2nd_run_me(self): pass
def test_and_me_last(self): pass
class Test_AnotherClass(unittest.TestCase):
def test_first(self): pass
def test_after_first(self): pass
def test_de_last_ding(self): pass
if __name__ == "__main__":
unittest.main(verbosity=2)
Running this gives
test_after_first (__main__.Test_AnotherClass) ... ok
test_de_last_ding (__main__.Test_AnotherClass) ... ok
test_first (__main__.Test_AnotherClass) ... ok
test_2nd_run_me (__main__.Test_MyTests) ... ok
test_and_me_last (__main__.Test_MyTests) ... ok
test_run_me_first (__main__.Test_MyTests) ... ok
Not what I want.
The answers I've found here on SO after searching all either dance around and avoid the issue by calling / grouping tests or saying
"don't do it, just write your tests differently" or
"name your tests lexicographically!"
...except for one, which does what I want:
loader = unittest.TestLoader()
ln = lambda f: getattr(MyTestCase, f).im_func.func_code.co_firstlineno
lncmp = lambda a, b: cmp(ln(a), ln(b))
loader.sortTestMethodsUsing = lncmp
unittest.main(testLoader=loader, verbosity=2)
but only for one TestCase class, and only in Python 2.
I want to run all my Python 3 unittest.TestCase
subclasses, and I'd like to be able to specify the exact algorithm to use for ordering.
Can I do this in unittest
?