1

i am using the ConfigParser to read a INI File in a Python (2.7) Project. Now i want to write a Unittest and i am not sure what is the cleanest way to test it.

i already tried to adapt the init-method of the class which is reading the INI file, so i can pass the file which should be used as a parameter. like this:

def __ini__(self, config_file='/src/config/my_conf.ini'):
    self.conf = ConfigParser.SafeConfigParser()
    self.conf.read(config_file)

it works fine in production. However i do not manage to run it in a unittest. The config file is never available. It doesn't matter if i use the default value or change it to '/test/config/my_conf.ini'. I would prefer to use relative paths.

Could someone tell me what i am doing wrong with the path in the unittest. Or does someone have a much better idea how to handle this?

Thanks a lot!

1 Answer 1

1

A common solution for this kind of problem is, that during unit-testing you simply do not really access a real file. Instead, you 'mock' the functionality that reads the file content. This mock is then controlled by the test, such for each test case your mocked functionality returns data as if it was read from a file.

This does not necessarily have to be done on file access level. In your example you could also mock the ConfigParser.SafeConfigParser(). That is, during testing your code would not access the true config parser, but only some mock that just behaves as one and is in fact controlled by the test code.

In your code, however, this would require a bit of trickery: The way the __init__ function is written makes it difficult to take control from the unit-test code. Thus, it is advisable to change the code such that test code has more control of the file access or the config parser. Search for 'inversion of control' to learn more about how this can be done.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.