![](/img/trans.png)
[英]Invoking Test Methods with a Method for a unittest.TestCase Subclass Python
[英]Is it possible to run a single test method from a python unittest.TestCase with a reference to the method?
假設我有以下TestCase
class TestSomething(unittest.TestCase):
def test_a(self):
# Do some testing
def test_b(self):
# Do some other testing
如果我有該測試的參考,我是否可以運行TestSomething.test_a
? 我想做的是:
def run_test(test):
# Somehow runs the test
# HERE IS THE PART I AM REALLY STUCK ON
run_test(TestSomething.test_a)
我知道對於正常的單元測試來說這是一件很尷尬的事情。 我想要做的是提供一個測試作為函數裝飾器的參數運行。 本質上:
@corresponding_test(TestSomething.test_a)
def my_function_a():
# Something here
然后在裝飾器中基本上檢查該函數的測試是否在運行該函數之前通過。
OP 明確表示現實世界的用例涉及更多,但這仍然需要說明:
免責聲明:這不是運行單元測試的好標准方法。 如果您使用此代碼運行單元測試,您 [可能] 做錯了。
也就是說,你的問題引起了我的興趣,所以我繼續為你寫了一個工作演示:
"""
The `only_if_test_passes` decorator can be used to run a function if and
only if the argument test (unbound `TestCase` method) passes.
"""
import inspect
from unittest import TestCase, TestResult
class TestError(Exception):
pass
class MyTests(TestCase):
def test_pass(self):
# This passes because nothing went wrong
pass
def test_fail(self):
self.fail('This test will always fail')
def only_if_test_passes(test_method):
# Comments are computed values when passed MyTests.test_pass
test_case_class = inspect._findclass(test_method) # MyTests
test_case_name = test_case_class.__name__ # 'MyTests'
test_name = test_method.__name__ # 'test_pass'
# Introspection for Python 2:
# test_case_class = test_method.im_class
# test_case_name = test_case_class.__name__ # Same as for Python 3
# test_name = test_method.if_func.func_name
def decorator(fn):
def decorated(*args, **kwargs):
test_result = TestResult()
case = test_case_class(test_name) # MyTests('test_pass')
case(test_result)
if test_result.wasSuccessful():
return fn(*args, **kwargs)
else:
raise TestError('Unit test failed: {}.{}'.format(
test_case_name, test_name))
return decorated
return decorator
@only_if_test_passes(MyTests.test_pass)
def this_will_run():
print('This should output')
@only_if_test_passes(MyTests.test_fail)
def this_wont_ever_run():
print("Don't bother; you'll never see this.")
if __name__ == "__main__":
this_will_run()
this_wont_ever_run()
Python 2 中的內省會有所不同。
另請參閱: unittest.TestCase
文檔
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.