How to patch a constant in python

2024/11/20 3:24:52

I have two different modules in my project. One is a config file which contains

LOGGING_ACTIVATED = False

This constant is used in the second module (lets call it main) like the following:

if LOGGING_ACTIVATED:amqp_connector = Connector()

In my test class for the main module i would like to patch this constant with the value

True

Unfortunately the following doesn't work

@patch("config.LOGGING_ACTIVATED", True)

nor does this work:

@patch.object("config.LOGGING_ACTIVATED", True)

Does anybody know how to patch a constant from different modules?

Answer

If the if LOGGING_ACTIVATED: test happens at the module level, you need to make sure that that module is not yet imported first. Module-level code runs just once (the first time the module is imported anywhere), you cannot test code that won't run again.

If the test is in a function, note that the global name used is LOGGING_ACTIVATED, not config.LOGGING_ACTIVATED. As such you need to patch out main.LOGGING_ACTIVATED here:

@patch("main.LOGGING_ACTIVATED", True)

as that's the actual reference you wanted to replace.

Also see the Where to patch section of the mock documentation.

You should consider refactoring module-level code to something more testable. Although you can force a reload of module code by deleting the module object from the sys.modules mapping, it is plain cleaner to move code you want to be testable into a function.

So if your code now looks something like this:

if LOGGING_ACTIVATED:amqp_connector = Connector()

consider using a function instead:

def main():global amqp_connectorif LOGGING_ACTIVATED:amqp_connector = Connector()main()

or produce an object with attributes even.

https://en.xdnf.cn/q/26365.html

Related Q&A

Python script for minifying CSS? [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.We don’t allow questi…

Saving numpy array to txt file row wise

I have an numpy array of forma = [1,2,3]which I want to save to a .txt file such that the file looks like:1 2 3If I use numpy.savetxt then I get a file like:1 2 3There should be a easy solution to this…

I want Python argparse to throw an exception rather than usage

I dont think this is possible, but I want to handle exceptions from argparse myself.For example:import argparse parser = argparse.ArgumentParser() parser.add_argument(--foo, help=foo help, required=Tru…

Pass Variable from python (flask) to HTML in render template?

The web server works (python flask) but when I go to the website, where the value of animal should be (dog) it shows the variable name animal. (There is more to the code but this is the most simplistic…

How to clear console in sublime text editor

How to clear console in sublime text editor. I have searched on internet too..But cant find proper shortcut for that. Please provide info

YAML loads 5e-6 as string and not a number

When I load a number with e form a JSON dump with YAML, the number is loaded as a string and not a float.I think this simple example can explain my problem.import json import yamlIn [1]: import jsonIn …

How to get rid of grid lines when plotting with Seaborn + Pandas with secondary_y

Im plotting two data series with Pandas with seaborn imported. Ideally I would like the horizontal grid lines shared between both the left and the right y-axis, but Im under the impression that this is…

How to set the line width of error bar caps

How can the line width of the error bar caps in Matplotlib be changed?I tried the following code:(_, caplines, _) = matplotlib.pyplot.errorbar(data[distance], data[energy], yerr=data[energy sigma],cap…

Where is Pythons shutdown procedure setting module globals to None documented?

CPython has a strange behaviour where it sets modules to None during shutdown. This screws up error logging during shutdown of some multithreading code Ive written.I cant find any documentation of this…

Save a dictionary to a file (alternative to pickle) in Python?

Answered I ended up going with pickle at the end anywayOk so with some advice on another question I asked I was told to use pickle to save a dictionary to a file. The dictionary that I was trying to sa…