简体   繁体   English

在Python中使用mock.patch

[英]Using mock.patch in Python

How can I patch a variable used by foo() and which is imported from another file? 如何修补foo()使用的变量,该变量是从另一个文件导入的?

test file:
from f import foo

def test():
  foo()


f file:
from f2 import some_var

def foo():
  print some_var

Even if some_var in f file is 10, I might want it to have another value, when foo() is called from test() . 即使f文件中的some_var为10,当从test()调用foo()时,我仍可能希望它具有另一个值。 How can I achieve that using mock.patch.object ? 我如何使用mock.patch.object来实现?

Without trying it myself: 我自己不尝试:

#test file
import f2
import mock

def test():
    with mock.patch('f2.some_var', 'your-new-value-for-somevar'):
        # your test code

as you are importing some_var using from f2 import some_var in your "f file" then you'll need to make sure that the patch is in place when from f2 import some_var runs. 如要导入some_var使用from f2 import some_var在“F文件”,那么你就需要确保该补丁的地方,当from f2 import some_var运行。 I'd just use import f2 in "f file" instead, and refer to some_var as f2.some_var . 我只是在“ f文件”中使用import f2 ,并将some_var称为f2.some_var

---edit--- Gah, you can of course just do this in your test class: ---编辑---加,您当然可以在测试班级中这样做:

#test file
import f
import mock

def test():
    with mock.patch('f.some_var', 'your-new-value-for-somevar'):

This will patch the value of some_var that has been copied into f by from f2 import some_var 这将修补的价值some_var已复制到f通过from f2 import some_var

You don't necessarily need patch.object for modifying values in the case you've given. 在给出的情况下,不一定需要使用patch.object来修改值。 You can just do: 您可以这样做:

test.py: test.py:

from f import foo
import f

f.some_var = 'test-val'

def test():
  foo()

Foo will then print out 'test-val' in the case you've given. Foo将在您给出的情况下打印出“ test-val”。

If instead you have a function that needs to be mocked, you can use patch.object as a decorator in addition to Steve's example. 相反,如果您有一个需要模拟的函数,则可以在Steve的示例之外将patch.object用作装饰器。

test.py test.py

from mock import patch
from f import foo  
import f    

@patch.object(f, 'some_fn')               
def test(some_fn_mock):     
    some_fn_mock.return_value = 'new-stuff'    
    f.foo() 


test()

f.py py

from f2 import some_fn
def foo():              
    print some_fn()

f2.py f2.py

def some_fn():         
    print 'stuff'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM