Djangoのテストでsettingsの値をモックする

定期的に忘れるのでメモ

settingsの値をモックしたいときは、 django.test.utils.override_settingsTestCase.settings を使う。

override_settingsを使う場合

参考: https://gist.github.com/blaix/2294982#gistcomment-1318400

👆に書いてある通り。

from django.test.utils import override_settings

をインポートして、デコレーターとして使う。

@override_settings(DEBUG=False)

これだけ。

TestCase.settingsを使う場合

参考: https://stackoverflow.com/questions/36611393/how-to-mock-django-settings-attribute-used-in-another-module

with句で使う。withの範囲中だけsettingsのモックが有効になる。

class TestSample(TestCase):
    def test_1(self):
        try:
            val = settings.AA
        except AttributeError:
            print('AAはないよ!')

        with self.settings(AA='hogedayo'):
            print('AA='+settings.AA)

        try:
            val = settings.AA
        except AttributeError:
            print('withを抜けたからAAはないよ!')

    def test_2(self):
        try:
            val = settings.AA
        except AttributeError:
            print('AAはなくなったよ!')

出力

AAはないよ!
AA=hogedayo
withを抜けたからAAはないよ!
AAはなくなったよ!

デコレーターでやったほうがテストコードの見通しが良い気がする。わかりやすい。
お好みでお使いください。