简体   繁体   中英

create users before running tests DRF

i want to run django tests, but i want to create some users before i run the test and the users' username will be attribute of the class and can be shared in all tests somthing like this:

class DoSomeTests(TestCase):


    def setup_createusers(self):
             self.usr1 = create_user1()
             self.usr2 = create_user1()
             self.usr3 = create_user1()
    def test_number_one(self):
               use self.user1/2/3
    def test_number_two(self):
               use self.user1/2/3
    def test_number_three(self):
               use self.user1/2/3


how can i do it becuase every time i tried the test dont recognize the self's attributes ive tried use setupclass and setUp but nothing happend

cretae users before running tests

Generally (and personally) since setUpTestData was introduced I use this one but you can use setUp also based on your approach and what you need. In order to use setUpTestData you need to put a class decorator and approach it with cls instead of self since you want to set up data for the whole TestCase, something like:

class TestViews(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.user1 = User.objects.create_user(........)
        cls.user2 = User.objects.create_user(........)
        cls.user3 = User.objects.create_user(........)

Then in your tests, in order to access (and log in) each user you can use this:

   def test_number_one(self):
        test_user = self.user1
        self.client.force_login(test_user)

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