File: test_asyncify.py

package info (click to toggle)
auth0-python 4.13.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,280 kB
  • sloc: python: 8,933; makefile: 15; sh: 2
file content (263 lines) | stat: -rw-r--r-- 9,148 bytes parent folder | download
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
import base64
import json
import platform
import re
import sys
import unittest
from tempfile import TemporaryFile
from unittest.mock import ANY, MagicMock

import aiohttp
import pytest
from aioresponses import CallbackResult, aioresponses
from yarl import URL

from auth0.asyncify import asyncify
from auth0.authentication import GetToken, Users
from auth0.management import Clients, Guardian, Jobs

clients = re.compile(r"^https://example\.com/api/v2/clients.*")
token = re.compile(r"^https://example\.com/oauth/token.*")
user_info = re.compile(r"^https://example\.com/userinfo.*")
factors = re.compile(r"^https://example\.com/api/v2/guardian/factors.*")
users_imports = re.compile(r"^https://example\.com/api/v2/jobs/users-imports.*")
payload = {"foo": "bar"}

telemetry = base64.b64encode(
    json.dumps(
        {
            "name": "auth0-python",
            "version": sys.modules["auth0"].__version__,
            "env": {
                "python": platform.python_version(),
            },
        }
    ).encode("utf-8")
).decode()

headers = {
    "User-Agent": f"Python/{platform.python_version()}",
    "Authorization": "Bearer jwt",
    "Content-Type": "application/json",
    "Auth0-Client": telemetry,
}


def get_callback(status=200, response=None):
    mock = MagicMock(
        return_value=CallbackResult(status=status, payload=response or payload)
    )

    def callback(url, **kwargs):
        return mock(url, **kwargs)

    return callback, mock


class TestAsyncify(unittest.IsolatedAsyncioTestCase):
    @pytest.mark.asyncio
    @aioresponses()
    async def test_get(self, mocked):
        callback, mock = get_callback()
        mocked.get(clients, callback=callback)
        c = asyncify(Clients)(domain="example.com", token="jwt")
        self.assertEqual(await c.all_async(), payload)
        mock.assert_called_with(
            URL("https://example.com/api/v2/clients?include_fields=true"),
            allow_redirects=True,
            params={"include_fields": "true"},
            headers=headers,
            timeout=ANY,
        )

    @pytest.mark.asyncio
    @aioresponses()
    async def test_post(self, mocked):
        callback, mock = get_callback()
        mocked.post(clients, callback=callback)
        c = asyncify(Clients)(domain="example.com", token="jwt")
        data = {"client": 1}
        self.assertEqual(await c.create_async(data), payload)
        mock.assert_called_with(
            URL("https://example.com/api/v2/clients"),
            allow_redirects=True,
            json=data,
            headers=headers,
            timeout=ANY,
        )

    @pytest.mark.asyncio
    @aioresponses()
    async def test_post_auth(self, mocked):
        callback, mock = get_callback()
        mocked.post(token, callback=callback)
        c = asyncify(GetToken)("example.com", "cid", client_secret="clsec")
        self.assertEqual(
            await c.login_async(username="usrnm", password="pswd"), payload
        )
        mock.assert_called_with(
            URL("https://example.com/oauth/token"),
            allow_redirects=True,
            json={
                "client_id": "cid",
                "username": "usrnm",
                "password": "pswd",
                "realm": None,
                "scope": None,
                "audience": None,
                "grant_type": "http://auth0.com/oauth/grant-type/password-realm",
                "client_secret": "clsec",
            },
            headers={i: headers[i] for i in headers if i != "Authorization"},
            timeout=ANY,
        )

    @pytest.mark.asyncio
    @aioresponses()
    async def test_user_info(self, mocked):
        callback, mock = get_callback()
        mocked.get(user_info, callback=callback)
        c = asyncify(Users)(domain="example.com")
        self.assertEqual(
            await c.userinfo_async(access_token="access-token-example"), payload
        )
        mock.assert_called_with(
            URL("https://example.com/userinfo"),
            headers={**headers, "Authorization": "Bearer access-token-example"},
            timeout=ANY,
            allow_redirects=True,
            params=None,
        )

    @pytest.mark.asyncio
    @aioresponses()
    async def test_file_post(self, mocked):
        callback, mock = get_callback()
        mocked.post(users_imports, callback=callback)
        j = asyncify(Jobs)(domain="example.com", token="jwt")
        users = TemporaryFile()
        self.assertEqual(await j.import_users_async("connection-1", users), payload)
        file_port_headers = headers.copy()
        file_port_headers.pop("Content-Type")
        mock.assert_called_with(
            URL("https://example.com/api/v2/jobs/users-imports"),
            allow_redirects=True,
            data={
                "connection_id": "connection-1",
                "upsert": "false",
                "send_completion_email": "true",
                "external_id": None,
                "users": users,
            },
            headers=file_port_headers,
            timeout=ANY,
        )
        users.close()

    @pytest.mark.asyncio
    @aioresponses()
    async def test_patch(self, mocked):
        callback, mock = get_callback()
        mocked.patch(clients, callback=callback)
        c = asyncify(Clients)(domain="example.com", token="jwt")
        data = {"client": 1}
        self.assertEqual(await c.update_async("client-1", data), payload)
        mock.assert_called_with(
            URL("https://example.com/api/v2/clients/client-1"),
            allow_redirects=True,
            json=data,
            headers=headers,
            timeout=ANY,
        )

    @pytest.mark.asyncio
    @aioresponses()
    async def test_put(self, mocked):
        callback, mock = get_callback()
        mocked.put(factors, callback=callback)
        g = asyncify(Guardian)(domain="example.com", token="jwt")
        data = {"factor": 1}
        self.assertEqual(await g.update_factor_async("factor-1", data), payload)
        mock.assert_called_with(
            URL("https://example.com/api/v2/guardian/factors/factor-1"),
            allow_redirects=True,
            json=data,
            headers=headers,
            timeout=ANY,
        )

    @pytest.mark.asyncio
    @aioresponses()
    async def test_delete(self, mocked):
        callback, mock = get_callback()
        mocked.delete(clients, callback=callback)
        c = asyncify(Clients)(domain="example.com", token="jwt")
        self.assertEqual(await c.delete_async("client-1"), payload)
        mock.assert_called_with(
            URL("https://example.com/api/v2/clients/client-1"),
            allow_redirects=True,
            params={},
            json=None,
            headers=headers,
            timeout=ANY,
        )

    @pytest.mark.asyncio
    @aioresponses()
    async def test_shared_session(self, mocked):
        callback, mock = get_callback()
        mocked.get(clients, callback=callback)
        async with asyncify(Clients)(domain="example.com", token="jwt") as c:
            self.assertEqual(await c.all_async(), payload)
        mock.assert_called_with(
            URL("https://example.com/api/v2/clients?include_fields=true"),
            allow_redirects=True,
            params={"include_fields": "true"},
            headers=headers,
            timeout=ANY,
        )

    @pytest.mark.asyncio
    @aioresponses()
    async def test_rate_limit(self, mocked):
        callback, mock = get_callback(status=429)
        mocked.get(clients, callback=callback)
        mocked.get(clients, callback=callback)
        mocked.get(clients, callback=callback)
        mocked.get(clients, payload=payload)
        c = asyncify(Clients)(domain="example.com", token="jwt")
        rest_client = c._async_client.client
        rest_client._skip_sleep = True
        self.assertEqual(await c.all_async(), payload)
        self.assertEqual(3, mock.call_count)
        (a, b, c) = rest_client._metrics["backoff"]
        self.assertTrue(100 <= a < b < c <= 1000)

    @pytest.mark.asyncio
    @aioresponses()
    async def test_rate_limit_post(self, mocked):
        callback, mock = get_callback(status=429)
        mocked.post(clients, callback=callback)
        mocked.post(clients, callback=callback)
        mocked.post(clients, callback=callback)
        mocked.post(clients, payload=payload)
        c = asyncify(Clients)(domain="example.com", token="jwt")
        rest_client = c._async_client.client
        rest_client._skip_sleep = True
        self.assertEqual(await c.create_async({}), payload)
        self.assertEqual(3, mock.call_count)

    @pytest.mark.asyncio
    @aioresponses()
    async def test_timeout(self, mocked):
        callback, mock = get_callback()
        mocked.get(clients, callback=callback)
        c = asyncify(Clients)(domain="example.com", token="jwt", timeout=(8.8, 9.9))
        self.assertEqual(await c.all_async(), payload)
        mock.assert_called_with(
            ANY,
            allow_redirects=ANY,
            params=ANY,
            headers=ANY,
            timeout=aiohttp.ClientTimeout(sock_connect=8.8, sock_read=9.9),
        )