简体   繁体   中英

pytest-django: Mock settings.DEBUG

To make manual testing easy, I want to create users when the login page gets shown.

class LalaLoginView(LoginView):
    def get(self, request, *args, **kwargs):
        self.create_users()
        return super().get(request, *args, **kwargs)

    @classmethod
    def create_users(cls):
        if not settings.DEBUG:
            return
        admin = User.objects.update_or_create(username='admin', defaults=dict(
            is_superuser=True, is_staff=True))[0]
        admin.set_password('admin')
        admin.save()

My Test:

@pytest.mark.django_db
def test_create_users_prod(settings):
    settings.DEBUG=False
    LalaLoginView.create_users()
    assert not User.objects.all().exists()

But the mocking of settings.DEBUG does not work. In create_users() DEBUG is "True".

How to mock settings.DEBUG with pytest-django?

You need to uses override_settings decorator:

@override_settings(DEBUG=False)
@pytest.mark.django_db
def test_create_users_prod(settings):
    LalaLoginView.create_users()
    assert not User.objects.all().exists()

The problem was between keyboard and chair:-)

This code does work:

@pytest.mark.django_db
def test_create_users_prod(settings):
    settings.DEBUG=False
    LalaLoginView.create_users()
    assert not User.objects.all().exists()

But in my production code I imported settings from mysite .

After changing this to from django.conf import settings the pytest fixture "settings" worked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM