[英]How could I unittest Configparser
Hello i got a simple config file, let's call it config.cfg, and a fuction reading the file using configparser, passing two parameters, one for the config file path, and other for the config file's name section.您好,我有一个简单的配置文件,我们称之为 config.cfg,以及一个使用 configparser 读取文件的函数,传递两个参数,一个用于配置文件路径,另一个用于配置文件的名称部分。
config.cfg配置文件
[SECTION1]
key1 = value1
key2 = value2
key3 = value3
fuction_to_test function_to_test
def read_config_file(CFG_PATH, CFG_SECTION):
try:
cf = configparser.ConfigParser()
cf.read(CFG_PATH)
return cf.[CFG_SECTION].get('key1')
except KeyError:
return " "
I would like to unittest the code but i no have a clue how to do it, I would test a assertequal for the value returned when section and key names are ok, and test the rise KeyError when a section name doesn't exists in the config file.我想对代码进行单元测试,但我不知道该怎么做,我会在节名和键名正常时为返回的值测试一个 assertequal,并在节名不存在时测试上升 KeyError配置文件。
I could mock the CFG_PATH and CFG_SECTION for isolating and don't need to read the config file.我可以模拟 CFG_PATH 和 CFG_SECTION 进行隔离,并且不需要读取配置文件。 but i confused how achieve the value returned and Keyerror testing.但我很困惑如何实现返回值和 Keyerror 测试。 Is this the correct way to test the function or Am I wrong?.这是测试 function 的正确方法还是我错了? May anyone help me or share some code?有人可以帮助我或分享一些代码吗?
By the way i'm using python 3.6顺便说一句,我正在使用 python 3.6
I commonly use integration tests to validate functions like read_config_file
.我通常使用集成测试来验证read_config_file
类的函数。 The integration test would store a fixture file with a known config like:集成测试将存储具有已知配置的夹具文件,例如:
# tests/fixtures/config.has_key.cfg
[SECTION1]
key1 = value1
key2 = value2
key3 = value3
Then you need 2 test cases to fully exercise your method:然后你需要 2 个测试用例来充分练习你的方法:
def test_read_config_file_contains_section(self):
self.assertEqual(
'value1',
read_config_file('tests/fixtures/config.has_key.cfg', 'SECTION1')
)
def test_read_config_file_missing_section(self):
with self.assertRaises(KeyError):
read_config_file('tests/fixtures/config.has_key.cfg', 'MISSING_SECTION')
Another option could be to break out your function into 2 distinct components:另一种选择可能是将您的 function 分解为 2 个不同的组件:
The function below takes an already parsed config file and attempts to retrieve the sections value:下面的 function 采用已解析的配置文件并尝试检索部分值:
def read_config(cfg, CFG_SECTION):
try:
return cfg.[CFG_SECTION].get('key1')
except KeyError:
return " "
This method is trivial to unit test.这种方法对于单元测试来说是微不足道的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.