Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to patch a constant in python

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?

like image 797
d.a.d.a Avatar asked Dec 02 '14 15:12

d.a.d.a


People also ask

How do I apply a patch in Python?

The library also provides a function, called patch() , which replaces the real objects in your code with Mock instances. You can use patch() as either a decorator or a context manager, giving you control over the scope in which the object will be mocked.

How do you mock a class constant?

If the constant class is not static and you can add a method to your class, add a non-static method that returns the value of your constant and mock that method to return the value you need for testing.


2 Answers

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_connector     if LOGGING_ACTIVATED:         amqp_connector = Connector()  main() 

or produce an object with attributes even.

like image 50
Martijn Pieters Avatar answered Oct 05 '22 13:10

Martijn Pieters


The problem you are facing is that you are mocking where it is defined, and you should patch where is it used.

Mock an item where it is used, not where it came from.

I leave you some example code, so you can catch the idea.

project1/constants.py

INPUT_DIRECTORY="/input_folder" 

project1/module1.py

from project1.constants import INPUT_DIRECTORY import os  def clean_directories():     for filename in os.listdir(INPUT_DIRECTORY):         filepath = os.path.join(directory, filename)         os.remove(filepath) 

project1/tests/test_module1.py

import mock, pytest  def test_clean_directories(tmpdir_factory):     """Test that folders supposed to be emptied, are effectively emptied"""      # Mock folder and one file in it     in_folder = tmpdir_factory.mktemp("in")     in_file = in_folder.join("name2.json")     in_file.write("{'asd': 3}")      # Check there is one file in the folder     assert len([name for name in os.listdir(in_folder.strpath) if os.path.isfile(os.path.join(path, name))]) == 1      # As this folder is not a parameter of the function, mock it.     with mock.patch('project1.module1.INPUT_DIRECTORY', in_folder.strpath):         clean_directories()      # Check there is no file in the folder     assert len([name for name in os.listdir(in_folder.strpath) if os.path.isfile(os.path.join(path, name))]) == 0 

So the importan line would be this one:

with mock.patch('project1.module1.INPUT_DIRECTORY', in_folder.strpath): 

See, value is mocked where it is used, and not in constants.py (where it is defined)

like image 40
Gonzalo Avatar answered Oct 05 '22 14:10

Gonzalo