Skip to main content
 首页 » 编程设计

Python 单元测试 : having an external function for repetitive code in different modules

2025年05月04日16sky-heaven

假设我有一个用 python 编写的网络服务 ServA,我想编写一些单元测试。

ServA 做几件事(使用不同的 View ),但所有 View 都会生成类似的请求日志。

这些测试在不同的情况下要检查ServA的日志,所以这些单元测试有很多重复的代码(日志的结构总是一样的)。

我的想法是编写一个通用函数来避免代码重复,我找到了 this other question这解决了在 unittest 类中创建通用方法的问题。

但是现在如果我有另一个 Web 服务 ServB 和另一组测试并且我需要做同样的事情怎么办?

有没有办法重用泛型函数?

我是否应该像这样简单地创建一个测试类来检查日志:

class MyMetaTestClass(unittest.TestCase): 
    def check_logs(self, log_list, **kwargs): 
       #several self.assertEqual 

然后 ServA 和 ServB 的测试像这样继承这个类:

class TestServA(MyMetaTestClass): 
    def test_log1(self): 
       logs = extract_the_logs() 
       self.check_logs(logs, log_1=1, log2='foo') 

还有其他(更好的)方法吗?

请您参考如下方法:

您可以像以前一样从公共(public)基类继承,但基类本身不必是 TestCase 子类 - 您可以将其设为混合类:

# testutils.py 
class LogCheckerMixin(object): 
    """ this class adds log checking abilities to a TestCase. 
    """   
    def check_logs(self, logs, **kw): 
       self.assertWhatever(something) 
 
 
# myserver/tests.py 
import unittest 
from testutils import LogCheckerMixin 
 
class MyServerTest(unittest.TestCase, LogCheckerMixin): 
    def test_log1(self): 
        logs = extract_the_logs() 
        self.check_logs(logs, log_1=1, log2='foo') 

或者你可以把它变成一个简单的函数并从你的测试中调用它:

# testutils.py 
def check_logs(testcase, logs, **kw): 
    testcase.assertWhatever(something) 
 
 
# myserver/tests.py 
import unittest 
from testutils import check_logs 
 
class MyServerTest(unittest.TestCase): 
    def test_log1(self): 
        logs = extract_the_logs() 
        check_logs(self, logs, log_1=1, log2='foo')