I have a function that uses information from a config file. How do I test the function? Ideally, I'd want to inject my own version of the config file and test from there, but I'm not using dependency injection.
You have to write a test that works independent of the config file, so you can test that depending on the "simulated configuration" the output of the function or behavior of that function is correct.
You would need to inject the configuration file, or the value that you are trying to simulate on your function under test. This is the only way to guarantee that whenever you have that value, your function behavior is the indicated by the configuration file.
Ideally, you would also isolate the class that contains and dictates the behavior of the configuration file to the class/function that reads this file. When writing testing one of the goals should be isolation of the code under test.
Depends on how you load data from your config file.
Ideally, write your program to be easily testable and reduce unnecessary dependencies. So make sure that if you change the location or format of your config file, that this affects as little code as possible. Then make sure that code can also deal with the testing.
If you have a single object or class or file or set of functions that deal(s) with the loading from the config file, change that so it can take a different config file or even just stub variables programmatically without needing a config file.
If you load the config file in multiple places and its path is hardcoded, it's a bit more difficult (you're also in a not so ideal situation). You could try to:
- Before the test, save your actual config file to a different location (config.back or something)
- Create a new config file with the values you want
- After the test, delete your newly created config file and restore the old one. Make sure to take exceptions into account!
If you just define a bunch of values in a python file and that is your config, refactor: adapt your config file so that you can change which values it returns. For example, you could create a bunch of functions to return your config values that default to your hardcoded config, but could be edited for a test program.
Well, dependency injection comes to mind as a default sort of boxed approach to config testing.
However, there are other ways, specifically designing your code to eliminate the dependency on config file all together.
You can find more details in a canonical example of dependency elimination by Brian Geihsler that talks specifically about config files.