27

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.

Samuel Dion-Girardeau
  • 2,790
  • 1
  • 29
  • 37
James Lin
  • 25,028
  • 36
  • 133
  • 233
  • Possible duplicate of [How to Unit test with different settings in Django?](https://stackoverflow.com/questions/913549/how-to-unit-test-with-different-settings-in-django) – Peter Thomassen Nov 13 '19 at 13:31

2 Answers2

40

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

KePe
  • 531
  • 7
  • 7
20

You can also use the following decorator on your individual test functions or test class as a whole. For example:

from django.test import override_settings

@override_settings(BASE_URL='http://localhost')
def test_case()
    ...
Joep
  • 788
  • 2
  • 8
  • 23
Farhan Haider
  • 1,244
  • 1
  • 13
  • 22