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.
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.
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.
The Python Import Mocker provides an easy way to import a module and mock its dependencies in an isolated way.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With