-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconftest.py
75 lines (57 loc) · 1.72 KB
/
conftest.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
from datetime import timedelta
from django_webtest import WebTest
from durin.models import AuthToken, Client
from pytest import fixture
from rest_framework.test import APIClient
from caraauth.models import User
from caraauth.tests.factories import UserFactory
@fixture
def user() -> User:
return UserFactory.create()
@fixture
def user_2fa(user):
user.get_or_create_totp_device(confirmed=True)
user.create_static_device()
return user
@fixture
def admin_user() -> User:
return UserFactory.create(is_superuser=True)
@fixture
def web_client():
"""
Return web client (durin) for api calls.
"""
return Client.objects.get_or_create(name="web", token_ttl=timedelta(days=1))[0]
@fixture
def apitest(web_client):
"""
Return API client to make requests.
"""
def _auth(user: User = None) -> APIClient:
"""
Return API client with optional authorization header if user is set.
"""
api_client = APIClient()
headers = {"HTTP_X_API_CLIENT": web_client.name}
if user:
try:
token = AuthToken.objects.get(user=user, client=web_client)
except AuthToken.DoesNotExist:
token = AuthToken.objects.create(user=user, client=web_client)
headers["HTTP_AUTHORIZATION"] = f"Bearer {token.token}"
api_client.credentials(**headers)
return api_client
return _auth
@fixture
def webtest(django_app):
"""
Return Web client to make requests.
"""
def _auth(user: User = None) -> WebTest:
"""
Return Web client with optional authorized user if set.
"""
if user:
django_app.set_user(user)
return django_app
return _auth