我有一个名为
的文件a.py
file = "/home/test/abc.txt"
我正在为另一个文件创建一个unittest,它从a.py
获取该文件变量的值如何将此变量名称模拟为任何虚拟文件,例如?
file = "/tmp/a.txt"
答案 0 :(得分:0)
使用模拟补丁:
import mock
@mock.patch('a.file', '/tmp/a.txt')
def test_a():
assert thing_that_uses_a_file == '/tmp/a.txt'
答案 1 :(得分:0)
@tbm的答案对我有用,在python 2.7上
config.py
SERVICE_REQUIRED = [
("lrc:/etc/rc2_d/S47pppd", "legacy_run"),
("lrc:/etc/rc2_d/S89PRESERVE", "legacy_run"),
("lrc:/etc/rc2_d/S99sysinfo", "legacy_run"),
("lrc:/etc/rc2_d/S99tcpwindow", "legacy_run"),
("lrc:/etc/rc3_d/S99cpupool", "legacy_run"),
("lrc:/etc/rc3_d/S99logparse", "legacy_run"),
("lrc:/etc/rc3_d/S99nicmon", "legacy_run"),
("lrc:/etc/rc3_d/S99nwmond", "legacy_run")
]
file_a.py
from config import SERVICE_REQUIRED
def demo_func():
for name, state in SERVICE_REQUIRED:
print name, state
...
test_file_a.py
...
class TestFileA(unittest.TestCase):
@mock.patch('file_a.SERVICE_REQUIRED', [
('svc:/system/console-login:vt2', 'online'),
('svc:/system/system-log:rsyslog', 'online'),
('svc:/network/socket-config:default', 'disabled'),
('dump', 'legacy_run'),
('firewall', 'disabled'),
("/'; echo hello;'", 'online')
])
def test_demo_func(self):
print SERVICE_REQUIRED
答案 2 :(得分:-1)
在您的具体情况下,为什么不只是import a
然后a.file = "/tmp/a.txt"
?
您使用的是哪个版本的Python? Python 3.x的unittest.mock
为backported to 2.x on pypi。
无论如何,如果您正在尝试创建特定于上下文的模拟:
>>> from mock import Mock
>>>
>>> # applies to module imports but doing it as a class here
... class A(object):
... file = 'xyz'
...
>>> some_a = Mock(file='abc')
>>> some_a.file
'abc'
>>>
>>> actual_a = A()
>>> actual_a.file
'xyz'
>>>
>>>
>>> def some_test():
... A = Mock(file='abc')
... assert A.file == 'abc'
... assert A.file != 'xyz'
...
>>> some_test()
>>> # no assertion error
你是否想在导入时嘲笑它?基于another SO answer:
>>> import sys
>>> sys.modules['A'] = Mock(file='abc')
>>> import A
>>>
>>> A.file
'abc'
>>> mocked_a = A
>>> mocked_a.file
'abc'
>>>