Users in initial data fixture

后端 未结 6 1674
臣服心动
臣服心动 2021-01-31 01:50

I\'m creating a few users by default in my fixtures/initial_data.json so as to have some testing \"subjects.\" The problem I\'m experiencing is password generation.

6条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-31 02:00

    I came across the same problem while writing fixtures for tests. Here's how I'm handling this in unit tests.

    Creating data from admin and dumping them into fixture works but I don't quite like being dependent on manually doing it. So here's what I do -

    Create the fixture just as you've done and then in the setUp method, set_passwords for the users.

    user_fixture.json

    [
        { "model": "auth.user",
            "pk": 1,
            "fields": {
                "username": "user1",
                "password": "password"
            }
        }
    ]
    

    test_user.py

    def setUp(self):
        self.User = get_user_model()
    
        # Fix the passwords of fixtures
        for user in self.User.objects.all():
            user.set_password(user.password)
            user.save()
    

    This way I can cleanly write the passwords in fixture and refer back to them when I need to and create more fixtures simply by editing the fixture file.

提交回复
热议问题