在python单元测试期间打开配置或文件的好方法是什么?

在python单元测试期间打开配置或文件的好方法是什么?,python,unit-testing,python-unittest,Python,Unit Testing,Python Unittest,我想知道在单元测试期间读取配置文件或本地文件的好方法是什么 我认为可以在测试期间编写测试配置文件。例如: def setUp(self): self.config = ConfigParser.RawConfigParser() self.config.add_section('TestingSection') self.config.set('TestingSection', 'x', '1') with open('local_file.txt', 'w')

我想知道在单元测试期间读取配置文件或本地文件的好方法是什么

我认为可以在测试期间编写测试配置文件。例如:

def setUp(self):
    self.config = ConfigParser.RawConfigParser()
    self.config.add_section('TestingSection')
    self.config.set('TestingSection', 'x', '1')

    with open('local_file.txt', 'w') as f:
        f.write('testing_value')
def setUp(self):
    self.config = ConfigParser.RawConfigParser()
    self.config('local_config_file_path')

    with open('local_file.txt', 'r') as f:
        self.testing_value = f.read()
或者可以在测试之前准备好文件,我们只需在测试期间打开它们,例如:

def setUp(self):
    self.config = ConfigParser.RawConfigParser()
    self.config.add_section('TestingSection')
    self.config.set('TestingSection', 'x', '1')

    with open('local_file.txt', 'w') as f:
        f.write('testing_value')
def setUp(self):
    self.config = ConfigParser.RawConfigParser()
    self.config('local_config_file_path')

    with open('local_file.txt', 'r') as f:
        self.testing_value = f.read()
在单元测试期间,我不确定哪种读取文件的方式更好,希望一些专家能帮助我

如果你有更好的方法,请与我分享


谢谢。

一个好方法是根本不必打开它们

对于依赖配置文件的函数,可以创建一个伪对象,该对象实现特定函数所依赖的必需方法。它可能只是一个支持获取“节”的
get
方法

这是剥削。您的python函数不关心它们得到的实际对象是什么,只要它实现了它所期望的配置解析器方法

在某些时候,您必须测试应用程序的“边缘”,即入口点。我猜执行了入口点函数,它从文件系统加载并解析配置文件。由于配置解析器已经在python核心中进行了测试,所以应该可以通过一个测试来测试这一点


在这个测试中,我将创建一个文件路径,并使用该文件路径作为主函数的输入,以确保它至少可以无错误地执行。这在技术上可能是一个集成测试,因为它与文件系统交互ConfigParser实现的方法。