简体   繁体   中英

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

[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

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:

  • Parsing
  • Reading config values

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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