django - 测试中的初始数据

时间:2017-05-25 10:30:09

标签: django testing django-rest-framework

这是我的UserTestCase(APITestCase)类中的两个函数。资本变量是不变的。有没有办法测试api而不是在test_create_user函数中创建太多的常量和dumd数据,如“data”?哪个是django初始数据测试的最佳实践?

def setUp(self):
    self.client = APIClient()
    # create staff
    self.admin = User.objects.create_user(email=ADMIN, password=PASSWORD)
    self.admin.is_staff = True
    self.admin.is_active = True
    self.admin.save()

    self.user = User.objects.create_user(email=ADMIN, password=PASSWORD)
    self.user.is_active = True
    self.user.save()

def test_create_user(self):

    login = self.client.login(email=ADMIN, password=PASSWORD)
    self.assertTrue(login)

    data = {
         'email': EMAIL,
         'password': PASSWORD,
         'first_name': FIRSTNAME,
         'last_name': LASTNAME,
         'nationality': NATIONALITY,
         'is_active': True,
    }

    # configure urls
    url = reverse('apiv2:user-list')
    # url1 = reverse('apiv2:user-detail', args=[self.user.id])

    # create new user
    user = self.client.post(url, data, format='json')
    self.assertEqual(user.status_code, 201)

    # login after create
    login = self.client.login(email=string_normalize(
        self.data.email),
        password=PASSWORD
    )
    self.assertTrue(login)

    self.client.logout()

1 个答案:

答案 0 :(得分:3)

我建议使用一些模拟库,例如Model Mommy,根据Django Model声明轻松创建你的灯具。并且很可能您将在测试的setUp方法中加载初始数据。