我有一个对象,下面是一个to_json方法,我想为它写一个测试。
import networkx as nx
class Example:
def __init__(self, graph):
self.graph = graph
def to_json(self):
data = nx.readwrite.node_link_data(self.graph)
filepath = os.path.join('~/.cache/product', 'some_file_name.txt')
with open(filepath, "w") as outfile:
json.dump(data, outfile)
return filepath在运行to_json的单元测试时,我不希望将输出文件写入~/.cache/product目录,而希望将其写入/tmp/product目录。我如何使用mocking/patching来实现这一点?
我当前的测试设置类似于:
def test_example_to_json():
ex = Example(graph={}) # Some graph
filepath = ex.to_json() # This is the problematic step since the file is being written to ~/.cache/product
with open(filepath, "r") as infile:
assert json.load(infile) == {}这里的任何建议都将不胜感激。
发布于 2021-07-22 02:55:30
不可能更改filepath变量,然后让函数通过模拟/修补继续其余的计算。
这里一个对我有效的解决方案如下:我定义了一个名为CACHE_DIR的环境变量,并使用它来获取缓存目录。Monkeypatch确实允许您使用monkeypatch.setenv("CACHE_DIR", "/tmp/product")。
import networkx as nx
class Example:
def __init__(self, graph):
self.graph = graph
def to_json(self):
data = nx.readwrite.node_link_data(self.graph)
filepath = os.path.join(os.getenv('CACHE_DIR'), 'some_file_name.txt')
with open(filepath, "w") as outfile:
json.dump(data, outfile)
return filepath使用以下单元测试:
import pytest
def test_example_to_json(monkeypatch):
ex = Example(graph={})
monkeypatch.setenv("CACHE_DIR", "/tmp/product")
filepath = ex.to_json()
with open(filepath, "r") as infile:
assert json.load(infile) == {}https://stackoverflow.com/questions/68463934
复制相似问题