Python unittest:在不同模块中具有重复代码的外部函数

Gio*_*lia 1 python unit-testing

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

ServA 做了几件事(有不同的观点),但所有的观点产生了一个类似的请求日志.

这些测试应该检查ServA不同情况下的日志,因此这些单元测试有很多重复的代码(日志的结构总是相同的).

我的想法是编写一个通用函数来避免重复代码,我发现了另一个问题,解决了在unittest类中创建泛型方法的问题.

但是,如果我有另一个Web服务ServB和另一组测试,我需要做同样的事情呢?

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

我应该简单地使用方法创建一个测试类来检查日志,如下所示:

class MyMetaTestClass(unittest.TestCase):
    def check_logs(self, log_list, **kwargs):
       #several self.assertEqual
Run Code Online (Sandbox Code Playgroud)

然后ServA和ServB的测试继承这个类,如下所示:

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

有另一种(更好的)方式吗?

bru*_*ers 7

你可以像你一样从一个公共基类继承,但是基类本身不一定是一个TestCase子类 - 你可以把它变成一个mixin类:

# 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')
Run Code Online (Sandbox Code Playgroud)

或者您可以将其设为普通函数并从测试中调用它:

# 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')
Run Code Online (Sandbox Code Playgroud)