我目前正在使用一些 api-unit-tests 測試我的 django (2.1.0) 應用程序。我使用 django rest 框架(3.9.0)來構建登錄。為此,我使用這樣的代碼:class LogoutTest(APITestCase): def test_login_post_unauth(self): response = requests.post('http://127.0.0.1:8000/myapp/user_info/') self.assertEqual(response.status_code, 401) def test_login_put_auth(self): token = auth() payload = {'Authorization': 'Token '+token} response = requests.put('http://127.0.0.1:8000/myapp/user_info/', headers=payload) self.assertEqual(response.status_code, 405) def test_login_delete_auth(self): token = auth() payload = {'Authorization': 'Token '+token} response = requests.delete('http://127.0.0.1:8000/myapp/user_info/', headers=payload) self.assertEqual(response.status_code, 405)當我使用時,測試正在運行:coverage run --source='.' manage.py test myapp就像你看到的:Creating test database for alias 'default'...System check identified no issues (0 silenced).....................................----------------------------------------------------------------------Ran 36 tests in 5.082sOKDestroying test database for alias 'default'...但是當我做覆蓋報告時,我只是得到myapp/auth.py 72 46 36%盡管我的 api 測試使用了我的 auth.py 中的代碼。我的 auth.py 看起來像這樣: def logout(request): if request.method == 'GET': request.user.auth_token.delete() return JsonResponse({'message':'You are sucessfully logged out'}, status=200) return JsonResponse({'error': 'Other Methods than GET not allowed'}, status=405)但報道說return JsonResponse({'error': 'Other Methods than GET not allowed'}, status=405) will never be used.你有想法嗎?
1 回答

HUX布斯
TA貢獻1876條經驗 獲得超6個贊
我找到了答案。我寫了錯誤的測試。Django 提供了他自己的測試工具,你應該使用它們!并且不要寫一些帶有請求的東西,因為覆蓋率會在例如 auth.py 中將您的代碼標識為未使用,因為您的測試不是使用 django 測試工具
添加回答
舉報
0/150
提交
取消