Unittest 多进程+装饰器+额外传参

一、给Unittest测试类添加参数
调用unittest.main()时无法传入额外的参数给我们的测试类时,可以使用如下工具给我们的测试类添加额外的参数:

unittest_utils.py代码:

import unittest

class ParametrizedTestCase(unittest.TestCase):
""" TestCase classes that want to be parametrized should
inherit from this class.
"""

def __init__(self, method_name='runTest', param=None):
    super(ParametrizedTestCase, self).__init__(method_name)
    self.param = param

@staticmethod
def parametrize(test_case_class, param=None):
    """ Create a suite containing all tests taken from the given
        subclass, passing them the parameter 'param'.
    """
    test_loader = unittest.TestLoader()
    test_names = test_loader.getTestCaseNames(test_case_class)
    suite = unittest.TestSuite()
    for name in test_names:
        suite.addTest(test_case_class(name, param=param))
    return suite

使用时:

(1)需要让测试类继承自ParametrizedTestCase
(2)添加额外参数

suite = unittest.TestSuite()
suite.addTest(ParametrizedTestCase.parametrize(TestAndroid, param=data))
runner = unittest.TextTestRunner()
runner.run(suite)

二、使用多进程执行测试
run.py代码:

import unittest
from multiprocessing import Process
from demo.test_demo import TestAndroid
from utils.unittest_utils import ParametrizedTestCase

class MyProcess(Process):

def __init__(self, data):
    Process.__init__(self)
    self.data = data
    self.suite = None

def run(self):
    ParametrizedTestCase.data = self.data
    self.suite = unittest.TestSuite()
    # 此处param即为给测试类额外传入的参数
    self.suite.addTest(ParametrizedTestCase.parametrize(TestAndroid, param=self.data))
    runner = unittest.TextTestRunner()
    runner.run(self.suite)

def create_process_monkey(data):
process_instances = []
for d in data:
instance = MyProcess(d)
process_instances.append(instance)
for instance in process_instances:
instance.start()

if name == "main":

process01 = {
    'calculate': '20+30',
    "value": "50"
}
process02 = {
    'calculate': '3*2',
    "value": "6"
}
create_process_monkey([process01, process02])

三、使用装饰器格式化日志输出
logger.py代码:

def add_log(func):
def wrapper(*args, *kwargs):
# 获取用例名称
case = func.name
print(case + " : start ...")
print("")
# 执行测试用例
func(
args)
print(case + " : end ...")
print("")

return wrapper

test_demo.py代码示例:

import os

from utils.logger import add_log
from utils.unittest_utils import ParametrizedTestCase

class TestAndroid(ParametrizedTestCase):

def setUp(self):
    pass

# 格式化输出装饰器
@add_log
def test_calculate(self):
    print("当前进程的pid是: " + str(os.getpid()))
    self.assertTrue(eval(self.param["calculate"]) == int(self.param["value"]))
    
def tearDown(self):
    pass

原文链接:https://blog.csdn.net/qq_27525737/article/details/108561368

你可能感兴趣的:(Unittest 多进程+装饰器+额外传参)