覆盖率显示Django测试的百分比太低

问题描述 投票:3回答:1

我正在使用一些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.082s

OK
Destroying 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.

你有好主意吗?

python django code-coverage python-unittest
1个回答
2
投票

我找到了答案。我写错了测试。 Django提供了自己的测试工具,您应该使用它们!并且不要写一些请求导致覆盖将识别您的代码,例如auth.py未使用导致您的测试不使用django测试工具

© www.soinside.com 2019 - 2024. All rights reserved.