Python 模拟文件中的变量
我有一个文件名为Python 模拟文件中的变量,python,mocking,Python,Mocking,我有一个文件名为 a.py file = "/home/test/abc.txt" 我正在为另一个文件创建一个unittest,它从a.py中获取这个文件变量的值 例如,如何将此变量名模拟到任何虚拟文件 file = "/tmp/a.txt" 在您的特定情况下,为什么不导入一个,然后导入一个a.file=“/tmp/a.txt” 您使用的是哪个版本的Python?Python3.x有一个 无论如何,如果您试图创建特定于上下文的模拟: >>> from mock import
a.py
file = "/home/test/abc.txt"
我正在为另一个文件创建一个unittest,它从a.py中获取这个文件变量的值
例如,如何将此变量名模拟到任何虚拟文件
file = "/tmp/a.txt"
在您的特定情况下,为什么不导入一个,然后导入一个
a.file=“/tmp/a.txt”
您使用的是哪个版本的Python?Python3.x有一个
无论如何,如果您试图创建特定于上下文的模拟:
>>> 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
您是否试图在导入时模拟它?基于:
使用mock.patch:
import mock
@mock.patch('a.file', '/tmp/a.txt')
def test_a():
assert thing_that_uses_a_file == '/tmp/a.txt'
@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")
]
文件a.py
from config import SERVICE_REQUIRED
def demo_func():
for name, state in SERVICE_REQUIRED:
print name, state
...
测试文件
...
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
您要做的是创建一个“假”
文件
变量,您可以对其进行测试?我使用的是python 2.6.6这里的第一个模拟解决方案仅声明可以测试模拟对象,它对测试使用文件变量的代码没有任何帮助。大概OP想要模拟file变量来声明其使用条件,而不是简单地更改它。
...
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