简体   繁体   中英

Using mock.patch in Python

How can I patch a variable used by foo() and which is imported from another file?

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() . How can I achieve that using 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. I'd just use import f2 in "f file" instead, and refer to some_var as 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

You don't necessarily need patch.object for modifying values in the case you've given. You can just do:

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.

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.

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

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

f2.py

def some_fn():         
    print 'stuff'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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