首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用mocking/patching更改类方法中的本地目录变量,以避免将测试输出文件写入其中?

如何使用mocking/patching更改类方法中的本地目录变量,以避免将测试输出文件写入其中?
EN

Stack Overflow用户
提问于 2021-07-21 12:17:54
回答 1查看 17关注 0票数 0

我有一个对象,下面是一个to_json方法,我想为它写一个测试。

代码语言:javascript
复制
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来实现这一点?

我当前的测试设置类似于:

代码语言:javascript
复制
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) == {}

这里的任何建议都将不胜感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-22 02:55:30

不可能更改filepath变量,然后让函数通过模拟/修补继续其余的计算。

这里一个对我有效的解决方案如下:我定义了一个名为CACHE_DIR的环境变量,并使用它来获取缓存目录。Monkeypatch确实允许您使用monkeypatch.setenv("CACHE_DIR", "/tmp/product")

代码语言:javascript
复制
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

使用以下单元测试:

代码语言:javascript
复制
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) == {}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68463934

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档