django单元测试
django test
测试用例放于django app的tests.py中
class PlanTest(TestCase): fixtures = FIXTURES def setUp(self): super(PlanTest, self).setUp() def test_add_plan(self): response = self.client.post(path, request_param, 'raw') response_ret = json.loads(response.content.decode('utf-8')) self.assertEqual(response_ret['success'], True)
启动
python manage.py test # 执行全部的测试 python manage.py test app.tests # 执行app下的全部测试 python manage.py test app.tests.PlanTest # 执行app下的PlanTest 额外的参数 -k 使用已存在的测试数据库(加速测试) -parallel n 指定用n的进程去跑(加速测试)
还有可用脚本看每个测试的执行时间
git地址:https://github.com/yaosir0317/showEachTestRuntime
fixtures
是json格式的数据,你可以预先从数据库中导出一部分数据供你的测试使用,fixtures的体积会影响测试的速度
./manage.py dumpdata --pks 8 User > user/fixtures/users.json # 导出user表中主键为8的数据
示例
class FinishRenyingPlanTest(MyTestCase): fixtures = ['users', 'sub_govern_regions', 'plan_types', 'owner_managers', 'companies', 'user_company_mappings', 'countries', "b_departments", "userspacemappings", "airspaceinfos", 'map_datas'] def setUp(self): super(FinishRenyingPlanTest, self).setUp() add_renying_plan() self.path = "/api/req/finish_renying_plan" self.display_id = approve_renying_plan() self._renying_user_login() def test_finish_renying_plan(self): request_param = ''' { "b": { "plan_request_id": "%s" }, "c":{ "vid": "1.0.0" }, "v":"gau" } ''' % self.display_id response = self.client.post(self.path, request_param, self.content_type) plan_request = PlanRequest.objects.get(display_id=self.display_id) self.assertEqual(plan_request.status, PlanRequestStatus.executed.value) self.assertEqual(json.loads(response.content.decode('utf-8')).get('success'), True)
class MyTestCase(TestCase): def setUp(self): self.client = Client() self.content_type = 'raw' self.user = None self.request_param = '''{ "b": { }, "c":{ "vid": "1.0.0" }, "v":"gau" }''' def _personal_user_login(self): self.user = personal_user_login(self.client) self.role = self.user.last_login_role