Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock django settings attribute used in another module?

Tags:

python

mocking

Lets say module a code:

from django.conf import settings
print settings.BASE_URL # prints http://example.com

In tests.py I want to mock the BASE_URL to http://localhost

I have tried the following:

with mock.patch('django.conf.settings.BASE_URL', 'http://localhost'):
    pass

with mock.patch('a.settings.BASE_URL', 'http://localhost'):
    pass

from a import settings

with mock.patch.object(settings, 'BASE_URL', 'http://localhost'):
    pass

import a

with mock.patch.object(a.settings, 'BASE_URL', 'http://localhost'):
    pass

None of the above worked.

like image 712
James Lin Avatar asked Apr 13 '16 23:04

James Lin


People also ask

How do you mock a global variable?

If you need to mock a global variable for all of your tests, you can use the setupFiles in your Jest config and point it to a file that mocks the necessary variables. This way, you will have the global variable mocked globally for all test suites.

How do you mock a variable in unit test Python?

If you are using pytest-mock (see https://pypi.org/project/pytest-mock/), then all you need to do is use the built in fixture. def test_my_function(mocker): # Mock the value of global variable `MY_NUMBER` as 10 mocker. patch("path.to. file.

Can you mock an import in Python?

The Python Import Mocker provides an easy way to import a module and mock its dependencies in an isolated way.


1 Answers

Try to use context manager settings() built-in django.

with self.settings(BASE_URL='http://localhost'):
    # perform your test

https://docs.djangoproject.com/en/dev/topics/testing/tools/#django.test.SimpleTestCase.settings

like image 80
KePe Avatar answered Sep 20 '22 19:09

KePe