Coverage for jutil/testing.py: 76%
31 statements
« prev ^ index » next coverage.py v6.5.0, created at 2022-10-07 16:40 -0500
« prev ^ index » next coverage.py v6.5.0, created at 2022-10-07 16:40 -0500
1import logging
2from typing import Optional
3from uuid import uuid1
4from django.contrib.auth import get_user_model
5from django.contrib.auth.models import User
6from rest_framework.test import APIClient
7from rest_framework.authtoken.models import Token
9logger = logging.getLogger(__name__)
12class TestSetupMixin:
13 @staticmethod
14 def add_test_user(email: str = "", password: str = "", username: str = "", **kwargs) -> User: # nosec
15 """
16 Add and login test user.
17 :param email: Optional email. Default is <random>@example.com
18 :param password: Optional password. Default is <random>.
19 :param username: Optional username. Defaults to email.
20 :return: User
21 """
22 if not email: 22 ↛ 23line 22 didn't jump to line 23, because the condition on line 22 was never true
23 email = "{}@example.com".format(username or uuid1().hex)
24 if not password: 24 ↛ 25line 24 didn't jump to line 25, because the condition on line 24 was never true
25 email = email.split("@")[0]
26 if not username: 26 ↛ 28line 26 didn't jump to line 28, because the condition on line 26 was never false
27 username = email
28 user = get_user_model().objects.create(username=username, email=email, **kwargs)
29 user.set_password(password)
30 user.save()
31 return user
33 @staticmethod
34 def create_api_client(user: Optional[User] = None) -> APIClient:
35 """
36 Creates APIClient with optionally authenticated user (by authorization token).
37 :param user: User to authenticate (optional)
38 :return: APIClient
39 """
40 token: Optional[Token] = None
41 if user: 41 ↛ 42line 41 didn't jump to line 42, because the condition on line 41 was never true
42 token = Token.objects.get_or_create(user=user)[0]
43 assert isinstance(token, Token)
44 api_client = APIClient()
45 if token: 45 ↛ 46line 45 didn't jump to line 46, because the condition on line 45 was never true
46 api_client.credentials(HTTP_AUTHORIZATION="Token {}".format(token.key))
47 return api_client