Skip to main content
 首页 » 编程设计

python之使用 mock.patch 装饰器和 nose2 这样的 DSL

2025年05月04日7JustinYoung

Nose2 有这个很棒的 Such DSL其工作方式类似于 RSpec。我曾经直接使用 unittests 并用类似 mock.patch 的东西装饰函数.我想知道 should 装饰函数与常规 unittest 函数有何不同,以及如何将其他装饰器用于 unittest 函数。

我可以让它像这样工作,但似乎失去了 passing in the unittest instance in the arguments 的能力.任何建议将不胜感激。谢谢!

@it.should('do something') 
@mock.patch('my.package.lib.b')                                                                 
@mock.patch('my.package.lib.a')                                                                    
def test(a, b): 
    pass 

请您参考如下方法:

所以我们知道装饰器顺序很重要,但这些都不起作用:

@it.should('do something') 
@mock.patch('datetime.date') 
@mock.patch('datetime.time') 
def test_1(date, time, case): 
    pass 
 
@mock.patch('datetime.time') 
@mock.patch('datetime.date') 
@it.should('do something') 
def test_2(case, date, time): 
    pass 

因为 patch 和 should 的实现方式。这两个库都对生成的装饰函数是什么做出了一些假设,因此不可能直接将装饰结果从一个库传递到另一个库。

但我们可以使用“适配器”装饰器从外部修复它:

import mock 
import nose2.tools 
 
def fix_case(f): 
    def test(case): 
        f(case=case) 
    return test 
 
with nose2.tools.such.A('system') as it: 
 
    @it.should('do something') 
    @fix_case 
    @mock.patch('datetime.time') 
    @mock.patch('datetime.date') 
    def test_3(date, time, case=None): 
        print(date, time, case) 
 
it.createTests(globals()) 

现在这有效并导致:

$ nose2 -v 
test 0000: should do something (tests.test_nose2_such.A system) ... 
(<MagicMock name='date' id='4334752592'>, <MagicMock name='time' id='4334762000'>, 
<tests.test_nose2_such.A system testMethod=test 0000: should do something>) 
ok 
 
---------------------------------------------------------------------- 
Ran 1 test in 0.001s 
 
OK 

这是相当快速和肮脏的,但完成了工作。我会看看是否可以对此进行改进并使其变得更好。