首页 > 解决方案 > 如何在 python 测试中修改内置开放路径?

问题描述

我有一个写入特定文件的函数。我想模拟文件名,以便我可以测试该函数如何在不同的位置工作。下面是我写的代码:

import pytest

@pytest.fixture
def change_output_file(mocker):
    orig =builtins.open

    def fake(file_name):
        return orig('xml_test_file.xml','wb')

    mocker.patch('builtins.open', new=fake)


class SomeClass():
    def run(self):
        output_file ="xml_initial_file.xml"
        print("Output file= ",output_file)
        f = open(output_file,'wb')
        # print("Output file= ",f)

def test_change_name(change_output_file):
    class_instance = SomeClass()
    print(class_instance.run()) #to change xml_initial_file.xml with xml_test_file.xml

但是这个测试给了我以下错误:

TypeError: change_name() takes 1 positional argument but 2 were given

我认为这是因为 'wb' 参数,但我怎样才能更改模拟方法以用于写入与初始位置不同的位置?

标签: pythontestingmockingpytestfixtures

解决方案


推荐阅读