1 方法一

通过 http server 调用 api,优点是与真实调时环境一致。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from rest_framework.test import APITestCase, APIClient
from django.contrib.auth.models import User

class MyAPIViewTestCase(APITestCase):
def setUp(self):
self.user = User.objects.create_user(username='testuser', password='testpassword')
self.client = APIClient()
if True: # 登录具体用户
self.token = AuthToken.objects.create(self.user)[1]
self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token)
else: # 跳过用户验证
self.client.force_authenticate(user=self.user)

def test_1(self):
response = self.client.get(f'/api/entry/data/')
self.assertEqual(response.status_code, 200)
print(response)

注意:force_authenticate 会跳过测试过程,如果明确使用 TokenAuthentication,就必须提供验证信息。

2 方法二

不需要启动后端服务,它构造一个 request 直接调用 view 接口,缺点与真实环境有差异,且与函数定义强相关,内部函数改了测试代码也需要修改。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import unittest
from django.contrib.auth.models import User
from rest_framework.test import APIRequestFactory
from knox.models import AuthToken
from app_dataforge.views import StoreEntryViewSet

class RecordTestCase(unittest.TestCase):
def setUp(self):
self.factory = APIRequestFactory()
try:
self.user = User.objects.get(username='testuser')
except User.DoesNotExist:
self.user = User.objects.create_user(username='testuser', password='123456')
self.token = AuthToken.objects.create(self.user)[1]

def test_1(self):
request = self.factory.get('/api/entry/data/', {'etype': 'record'})
request.META['HTTP_AUTHORIZATION'] = f"Token {self.token}"
response = StoreEntryViewSet.as_view({'get': 'list'})(request)
self.assertEqual(response.status_code, 200)
print(response)

3 上传文件

1
2
3
4
5
6
7
8
from django.core.files.uploadedfile import SimpleUploadedFile

filename = 'xxx'
with open(path, 'rb') as f:
file_data = SimpleUploadedFile(path, f.read())
response = self.client.post('/api/entry/data/',
{'files':file_data, 'filepaths':filename},
format='multipart')