Reputation: 53
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
[SECTION1]
key1 = value1
key2 = value2
key3 = value3
fuction_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.
I could mock the CFG_PATH and CFG_SECTION for isolating and don't need to read the config file. but i confused how achieve the value returned and Keyerror testing. Is this the correct way to test the function or Am I wrong?. May anyone help me or share some code?
By the way i'm using python 3.6
Upvotes: 1
Views: 445
Reputation: 55962
I commonly use integration tests to validate functions like 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:
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:
The function below takes an already parsed config file and attempts to retrieve the sections value:
def read_config(cfg, CFG_SECTION):
try:
return cfg.[CFG_SECTION].get('key1')
except KeyError:
return " "
This method is trivial to unit test.
Upvotes: 1