File: test_auth.py

package info (click to toggle)
python-gcal-sync 7.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 416 kB
  • sloc: python: 4,994; sh: 9; makefile: 5
file content (239 lines) | stat: -rw-r--r-- 7,871 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
"""Tests for the request client library."""

from typing import Awaitable, Callable

import aiohttp
import pytest

from gcal_sync.auth import AbstractAuth
from gcal_sync.exceptions import ApiException, ApiForbiddenException, AuthException


async def test_request(
    app: aiohttp.web.Application, auth_client: Callable[[str], Awaitable[AbstractAuth]]
) -> None:
    """Test of basic request/response handling."""

    async def handler(request: aiohttp.web.Request) -> aiohttp.web.Response:
        assert request.path == "/path-prefix/some-path"
        assert request.headers["Authorization"] == "Bearer some-token"
        assert request.query == {"client_id": "some-client-id"}
        return aiohttp.web.json_response(
            {
                "some-key": "some-value",
            }
        )

    app.router.add_get("/path-prefix/some-path", handler)

    auth = await auth_client("/path-prefix")
    resp = await auth.request(
        "get",
        "some-path",
        params={"client_id": "some-client-id"},
    )
    resp.raise_for_status()
    data = await resp.json()
    assert data == {"some-key": "some-value"}


async def test_get_json_response(
    app: aiohttp.web.Application, auth_client: Callable[[str], Awaitable[AbstractAuth]]
) -> None:
    """Test of basic json response."""

    async def handler(request: aiohttp.web.Request) -> aiohttp.web.Response:
        assert request.query["client_id"] == "some-client-id"
        return aiohttp.web.json_response(
            {
                "some-key": "some-value",
            }
        )

    app.router.add_get("/path-prefix/some-path", handler)

    auth = await auth_client("/path-prefix")
    data = await auth.get_json("some-path", params={"client_id": "some-client-id"})
    assert data == {"some-key": "some-value"}


async def test_get_json_response_unexpected(
    app: aiohttp.web.Application, auth_client: Callable[[str], Awaitable[AbstractAuth]]
) -> None:
    """Test json response with wrong response type."""

    async def handler(_: aiohttp.web.Request) -> aiohttp.web.Response:
        return aiohttp.web.json_response(["value1", "value2"])

    app.router.add_get("/path-prefix/some-path", handler)

    auth = await auth_client("/path-prefix")
    with pytest.raises(ApiException):
        await auth.get_json("some-path")


async def test_get_json_response_unexpected_text(
    app: aiohttp.web.Application, auth_client: Callable[[str], Awaitable[AbstractAuth]]
) -> None:
    """Test json response that was not json."""

    async def handler(_: aiohttp.web.Request) -> aiohttp.web.Response:
        return aiohttp.web.Response(text="body")

    app.router.add_get("/path-prefix/some-path", handler)

    auth = await auth_client("/path-prefix")
    with pytest.raises(ApiException):
        await auth.get_json("some-path")


async def test_post_json_response(
    app: aiohttp.web.Application, auth_client: Callable[[str], Awaitable[AbstractAuth]]
) -> None:
    """Test post that returns json."""

    async def handler(request: aiohttp.web.Request) -> aiohttp.web.Response:
        body = await request.json()
        assert body == {"client_id": "some-client-id"}
        return aiohttp.web.json_response(
            {
                "some-key": "some-value",
            }
        )

    app.router.add_post("/path-prefix/some-path", handler)

    auth = await auth_client("/path-prefix")
    data = await auth.post_json("some-path", json={"client_id": "some-client-id"})
    assert data == {"some-key": "some-value"}


async def test_post_json_response_unexpected(
    app: aiohttp.web.Application, auth_client: Callable[[str], Awaitable[AbstractAuth]]
) -> None:
    """Test post that returns wrong json type."""

    async def handler(_: aiohttp.web.Request) -> aiohttp.web.Response:
        return aiohttp.web.json_response(["value1", "value2"])

    app.router.add_post("/path-prefix/some-path", handler)

    auth = await auth_client("/path-prefix")
    with pytest.raises(ApiException):
        await auth.post_json("some-path")


async def test_post_json_response_unexpected_text(
    app: aiohttp.web.Application, auth_client: Callable[[str], Awaitable[AbstractAuth]]
) -> None:
    """Test post that returns unexpected format."""

    async def handler(_: aiohttp.web.Request) -> aiohttp.web.Response:
        return aiohttp.web.Response(text="body")

    app.router.add_post("/path-prefix/some-path", handler)

    auth = await auth_client("/path-prefix")
    with pytest.raises(ApiException):
        await auth.post_json("some-path")


async def test_get_json_response_bad_request(
    app: aiohttp.web.Application, auth_client: Callable[[str], Awaitable[AbstractAuth]]
) -> None:
    """Test error handling with detailed json response."""

    async def handler(_: aiohttp.web.Request) -> aiohttp.web.Response:
        return aiohttp.web.json_response(
            {
                "error": {
                    "errors": [
                        {
                            "domain": "calendar",
                            "reason": "timeRangeEmpty",
                            "message": "The specified time range is empty.",
                            "locationType": "parameter",
                            "location": "timeMax",
                        }
                    ],
                    "code": 400,
                    "message": "The specified time range is empty.",
                }
            },
            status=400,
        )

    app.router.add_get("/path-prefix/some-path", handler)
    app.router.add_post("/path-prefix/some-path", handler)

    auth = await auth_client("/path-prefix")

    with pytest.raises(
        ApiException,
        match=r"Error from API: 400: The specified time range is empty.: Bad Request",
    ):
        await auth.get("some-path")

    with pytest.raises(
        ApiException,
        match=r"Error from API: 400: The specified time range is empty.: Bad Request",
    ):
        await auth.get_json("some-path")

    with pytest.raises(
        ApiException,
        match=r"Error from API: 400: The specified time range is empty.: Bad Request",
    ):
        await auth.post("some-path")

    with pytest.raises(
        ApiException,
        match=r"Error from API: 400: The specified time range is empty.: Bad Request",
    ):
        await auth.post_json("some-path")


async def test_auth_refresh_error(
    app: aiohttp.web.Application,
    refreshing_auth_client: Callable[[], Awaitable[AbstractAuth]],
) -> None:
    """Test an authentication token refresh error."""

    async def auth_handler(_: aiohttp.web.Request) -> aiohttp.web.Response:
        return aiohttp.web.Response(status=401)

    app.router.add_get("/refresh-auth", auth_handler)

    auth = await refreshing_auth_client()
    with pytest.raises(AuthException):
        await auth.get_json("some-path")


async def test_unavailable_error(
    app: aiohttp.web.Application, auth_client: Callable[[str], Awaitable[AbstractAuth]]
) -> None:
    """Test of basic request/response handling."""

    async def handler(_: aiohttp.web.Request) -> aiohttp.web.Response:
        return aiohttp.web.Response(status=500)

    app.router.add_get("/path-prefix/some-path", handler)

    auth = await auth_client("/path-prefix")
    with pytest.raises(ApiException):
        await auth.get_json("some-path")


async def test_forbidden_error(
    app: aiohttp.web.Application, auth_client: Callable[[str], Awaitable[AbstractAuth]]
) -> None:
    """Test request/response handling for 403 status."""

    async def handler(_: aiohttp.web.Request) -> aiohttp.web.Response:
        return aiohttp.web.Response(status=403)

    app.router.add_get("/path-prefix/some-path", handler)

    auth = await auth_client("/path-prefix")
    with pytest.raises(ApiForbiddenException):
        await auth.get_json("some-path")