Coverage for jutil/testing.py: 76%

# Coverage for jutil/testing.py : 76%

## 31 statements

Hot-keys on this page

r m x p toggle line displays

j k next/prev highlighted chunk

0 (zero) top of page

1 (one) first highlighted chunk

1 import logging

2 from typing import Optional

3 from uuid import uuid1

4 from django.contrib.auth.models import User

5 from rest_framework.test import APIClient

6 from rest_framework.authtoken.models import Token

7

8 logger = logging.getLogger(__name__)

9

10

11 class TestSetupMixin:

12 @staticmethod

13 def add_test_user(email: str = "", password: str = "", username: str = "", **kwargs) -> User: # nosec

14 """

15 Add and login test user.

16 :param email: Optional email. Default is <random>@example.com

17 :param password: Optional password. Default is <random>.

18 :param username: Optional username. Defaults to email.

19 :return: User

20 """

21 if not email: 21 ↛ 22line 21 didn't jump to line 22, because the condition on line 21 was never true

22 email = "{}@example.com".format(username or uuid1().hex)

23 if not password: 23 ↛ 24line 23 didn't jump to line 24, because the condition on line 23 was never true

24 email = email.split("@")[0]

25 if not username: 25 ↛ 27line 25 didn't jump to line 27, because the condition on line 25 was never false

26 username = email

27 user = User.objects.create(username=username, email=email, **kwargs)

28 assert isinstance(user, User)

29 user.set_password(password)

30 user.save()

31 return user

32

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