如何使用 mocking/patching 更改 class 方法中的本地目录变量以避免将测试输出文件写入其中?
How can I use mocking/patching for changing the local directory variable inside a class method to avoid writing test output files into it?
我有一个如下所示的对象,其中包含一个 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) == {}
如有任何建议,我们将不胜感激。
无法更改 filepath
变量然后让函数通过 mocking/patching 继续进行其余计算。
此处对我有用的一个解决方案如下:我定义了一个名为 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) == {}
我有一个如下所示的对象,其中包含一个 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) == {}
如有任何建议,我们将不胜感激。
无法更改 filepath
变量然后让函数通过 mocking/patching 继续进行其余计算。
此处对我有用的一个解决方案如下:我定义了一个名为 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) == {}