0

Assume we have two files some_module.py and some_config_file.py. The latter is a file that contains paths to files, parameters for functions, etc. The former has now functions that use these parameters, e.g.

# some_module.py
import some_config_file as config

def func():
    path = config.path_to_some_data
    # do some logic that involves `path`

I would like to write some tests to ensure that func does what it is supposed to do. To do this, I would need to prepare some data in a specific file to be able to predict what func will do with it. I see two way of doing this:

  1. I write a specific test_config_file.py that points to data and parameters specific for tests. This would be my preferred way of doing it, but I don't really know how to let some_module.py know that I'm running unittest on it...
  2. I modify my functions, i.e. in the above example we would have something like

.

# some module
import some_config_file as config

def func(test: bool = False):
    path = config.path_to_some_data
    if test:
        path = "path/to/test_data"
    # do some logic that involves `path`

This works but is somewhat cumbersome since I need to effectively change every function in the project in a very repetitive way...

Is it possible to use method 1., can method 2. be achieved more elegantly, or is there a completely different way?

Sito
  • 494
  • 10
  • 29
  • What about the test function replacing "config" with "test config"? Then have 2 tests for the 2 cases (which you should have anyway) – DeepSpace Nov 16 '21 at 20:37
  • Alternatively, you can have `func` accept a path with a default value of `None` which will overwrite the value in the config. This way the tests can run `func` with the correct path – DeepSpace Nov 16 '21 at 20:38
  • @DeepSpace Regarding the first comment: `some_module.py` imports `some_config_file.py` at the beginning of the file... I don't think you can overwrite that in the test function, or can you? – Sito Nov 16 '21 at 20:41
  • 2
    You can quite easily with mock. A good starting point: https://stackoverflow.com/questions/41220803/mock-an-entire-module-in-python – DeepSpace Nov 16 '21 at 20:42
  • @DeepSpace I'm not familiar with that part of `unittest`, will take a look at it. Thanks for the suggestion! – Sito Nov 16 '21 at 20:43

0 Answers0