在单元测试中将日志分隔符添加到所有固定装置 [英] Add log separators to all fixtures in unittests

查看:84
本文介绍了在单元测试中将日志分隔符添加到所有固定装置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用unittest模块.我需要将setUp,setUpClass,teardown和teardownClass日志与unittests日志分开.输出应类似于:

I'm using unittest module. I need to separate setUp, setUpClass, teardown and teardownClass logs from unittests logs. Output should look something like:

**************setting things up**************
INFO: preparing database
INFO: create new users
**************end of setup****************
INFO: starting test one
INFO: ...
**************Cleaning things**************
INFO: delete users
...

我试图覆盖unittest.suite中的某些函数(_handleClassSetUp,_handleModuleFixtures,_tearDownPreviousClass)以记录分隔符被调用之前和之后的情况.结果,即使测试用例不包含setUpClass和tearDownClass,也会记录分隔符.仍然没有设置和拆卸的分隔符.

I tried to override some functions in unittest.suite (_handleClassSetUp, _handleModuleFixtures, _tearDownPreviousClass) to log separators before and after they are called. As a result separators are logged even if test case does not contain setUpClass and tearDownClass. And still, there is no separator for setup and teardown.

怎么办?

推荐答案

您可以使用元类来实现此功能.它所做的只是查找您提供的函数名称列表,然后将修饰符应用于这些函数.装饰器处理打印的进入和退出语句.

You could use a metaclass to achieve this functionality. All it's doing is looking for a list of function names that you provide, and then applying a decorator to those functions. The decorator handles printing entry and exit statements.

import functools
import unittest

FUNCTIONS_TO_LOG = ('setUp', 'tearDown')


def log_start_and_end(f):
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        print '********** start {}'.format(f.__name__)
        f(*args, **kwargs)
        print '********** end {}'.format(f.__name__)
    return wrapper


class LoggingMeta(type):
    def __new__(cls, name, bases, namespace):
        for attr, obj in namespace.items():
            if attr in FUNCTIONS_TO_LOG:
                namespace[attr] = log_start_and_end(obj)
        return super(LoggingMeta, cls).__new__(cls, name, bases, namespace)


class BaseTest(unittest.TestCase):
    __metaclass__ = LoggingMeta

    def setUp(self):
        print 'inside setup'

    def tearDown(self):
        print 'inside teardown'

    def test_test(self):
        print 'inside test'

if __name__ == '__main__':
    unittest.main()

这将导致输出:

********** start setUp
inside setup
********** end setUp
inside test
********** start tearDown
inside teardown
********** end tearDown
.


Ran 1 test in 0.000s

OK

这篇关于在单元测试中将日志分隔符添加到所有固定装置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆