测试设置的继承

时间:2015-04-19 21:57:53

标签: python unit-testing python-3.x python-unittest

我目前有几个具有相同setup / tearDown代码的TestCase。我认为以下设置可以删除重复。

clientsetup.py

class BaseClientTestCase(unittest.TestCase):

    def setUp(self):
        #Do setup    
    def tearDown(self):
        #Do tear down

test_myothertestcase.py

class MyOtherTestCase(BaseClientTestCase):

    def setUp(self):
        super(BaseClientTestCase, self).setUp()
        pass

    def tearDown(self):
        super(BaseClientTestCase, self).tearDown()
        pass

这允许我删除重复,然后能够在需要时添加一些特定的设置/拆卸。想到我遇到的问题, 是我的Testloader停止工作。

unittest.TestLoader().loadTestsFromName('tests.test_myothertestcase')

返回的错误如下:

AttributeError: 'module' object has no attribute 'test_myothertestcase'

测试加载器将从命令行中获取名称,因此它必须是一个字符串。出于某种原因,它不再认可MyOtherTestCase,就好像继承不像我期望的那样工作。

我该如何做到这一点?

扩展信息

结构

app/
  ...
manage.py
tests/
    __init__.py
    test_myothertestcase.py

manage.py

@manager.command
def test(coverage=False,testcase=None):
    """Run the unit tests."""

    suite = None
    if testcase:
        suite = unittest.TestLoader().loadTestsFromName("tests.%s" % testcase)
    else:
        suite = unittest.TestLoader().discover('tests')

    unittest.TextTestRunner(verbosity=2).run(suite)

堆栈跟踪:

  File "./manage.py", line 46, in <module>
    manager.run()
  File "/path/v_env/lib/python3.4/site-packages/flask_script/__init__.py", line 412, in run
    result = self.handle(sys.argv[0], sys.argv[1:])
  File "/path/v_env/lib/python3.4/site-packages/flask_script/__init__.py", line 383, in handle
    res = handle(*args, **config)
  File "/path/v_env/lib/python3.4/site-packages/flask_script/commands.py", line 216, in __call__
    return self.run(*args, **kwargs)
  File "./manage.py", line 30, in test
    suite = unittest.TestLoader().loadTestsFromName("tests.%s" % testcase)
  File "/usr/lib/python3.4/unittest/loader.py", line 114, in loadTestsFromName
    parent, obj = obj, getattr(obj, part)
AttributeError: 'module' object has no attribute 'test_myothertestcase'

1 个答案:

答案 0 :(得分:1)

如聊天所述,替换

suite = unittest.TestLoader().loadTestsFromName()

import importlib
test_module = importlib.import_module("tests.%s" % testcase)
suite = unittest.TestLoader().loadTestsFromModule(test_module)

的工作原理。它似乎是loadTestsFromName中的一个错误,但也许其他人知道它为什么会发生。

相关问题