1

Consider the code below...

Singleton config class

# config.py

class SomeConfigObject:
    thing = True

CONFIG = SomeConfigObject()

A module that utilizes the config object

# some_module.py
from config import CONFIG

def somefn():
    return CONFIG.thing

The main program that uses the module

# main_program.py
import some_module

def main():
    return some_module.somefn()

A test for the main program

# test_main_program.py
from main_program import main

def test_main():
    assert main() == True

This is a very simplistic example of a singleton 'config' object. In a more complicated codebase, there are many many many files (often nested) that would have from config import CONFIG so many modules could use that particular config. So, my question is:

Is there a simple way to patch an object globally through out a code base?

I've found that using mock would work:

# test main_program
from unittest import mock
from main_program import main

class TestConfig:
    thing=True

@mock.patch('main_program.some_module.CONFIG', new=TestConfig())
def test_main():
    assert main() == True

But ultimately, the above is not scalable and is very painful if there are tens/hundreds of places it is used.

M Leonard
  • 581
  • 1
  • 7
  • 23

0 Answers0