django單元測試

django test

測試用例放於django app的tests.py中python

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

git地址:https://github.com/yaosir0317/showEachTestRuntimegithub

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)
View Code
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
View Code
相關文章
相關標籤/搜索