Hide keyboard shortcuts

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

1import logging 

2from typing import Optional 

3from uuid import uuid1 

4from django.contrib.auth.models import User 

5from rest_framework.test import APIClient 

6from rest_framework.authtoken.models import Token 

7 

8logger = logging.getLogger(__name__) 

9 

10 

11class TestSetupMixin: 

12 @staticmethod 

13 def add_test_user(email: str = '', password: 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 :return: User 

19 """ 

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

21 email = '{}@example.com'.format(uuid1().hex) 

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

23 email = email.split('@')[0] 

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

25 assert isinstance(user, User) 

26 user.set_password(password) 

27 user.save() 

28 return user 

29 

30 @staticmethod 

31 def create_api_client(user: Optional[User] = None) -> APIClient: 

32 """ 

33 Creates APIClient with optionally authenticated user (by authorization token). 

34 :param user: User to authenticate (optional) 

35 :return: APIClient 

36 """ 

37 token: Optional[Token] = None 

38 if user: 38 ↛ 39line 38 didn't jump to line 39, because the condition on line 38 was never true

39 token = Token.objects.get_or_create(user=user)[0] 

40 assert isinstance(token, Token) 

41 api_client = APIClient() 

42 if token: 42 ↛ 43line 42 didn't jump to line 43, because the condition on line 42 was never true

43 api_client.credentials(HTTP_AUTHORIZATION='Token {}'.format(token.key)) 

44 return api_client