繁体   English   中英

Python Configparser在单元测试下找不到部分?

[英]Python Configparser cannot find section under Unittest?

所以我必须测试一个配置文件。 在此配置文件中,将初始化ConfigParser实例,然后加载配置文件。

在单元测试中,我导入了此解析器文件,然后尝试读取此ConfigParse实例的节点。 但是随后引发了一个错误,即找不到该节。

怎么会? 有办法解决吗?

编辑:所以单元测试只是导入配置文件。 配置文件的名称称为config。 该实例称为p_config。在一个测试案例中,该实例的名称如下:

config.p_config.get('section1','a')

配置文件看起来很标准。

import ConfigParser
p_config = ConfigParser.SafeConfigParser()
p_config.read("xxx.cfg")

所以我的配置文件看起来很像普通的Windows配置:

[section1]
a = 1
b = 2
[section2]
c = 2
d = 4

它引发的错误只是表明找不到部分:

ConfigParser.NoSectionError: No section: 'section1'

UnitTest的内容:

class TestConfigFile(TestCase):

    def setUp(self):
        pass

    def tearDown(self):
        pass


    def test_example(self):
        print global_path_config.get('section1', 'a')

听起来您正在设置测试配置对象,而没有实际提供配置文件供测试读取。

我假设您正在使用python unittest模块。

您的命令行与运行项目和运行测试有何不同? 命令行可能是个问题。

例如,如果您使用python /path/to/file.py <--options> config.ini启动程序,并使用python -m unittest /path/to/config/unittest -v启动单元测试,则您的配置文件永远不会被读取。

setUp(self):您将需要使用配置文件位置来初始化对象。 我喜欢写在很短的,假的配置文件setUp ,所以我可以很容易去除tearDown ,知道它究竟是如何与我的测试,不污染我的工作配置文件。

如果可以的话,我建议您放弃ConfigParser。 使用json文件进行配置

import json
from collections import OrderedDict

def read_config(file_json):
    with open(file_json, 'r') as filename:
        config = filename.read()
    return json.loads(config, object_pairs_hook=OrderedDict)

def write_config(config, file_json):
     data = json.dumps(config, indent=4)
     with open(file_json, 'w') as filename:
         filename.write(data)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM