File: test_api_client.py

package info (click to toggle)
pynina 1.0.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 756 kB
  • sloc: python: 761; makefile: 2
file content (70 lines) | stat: -rw-r--r-- 1,760 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
import asyncio
import json

import pytest
from aiohttp import ClientConnectionError, ClientSession
from aioresponses import aioresponses

from pynina.api_client import APIClient, ApiError

SAMPLE_URL = "https://example.com"
SAMPLE_BODY = {"key": "value"}
SAMPLE_BODY_JSON = json.dumps(SAMPLE_BODY)


@pytest.mark.asyncio
async def test_successful_request():
    client = APIClient()

    with aioresponses() as m:
        m.get(SAMPLE_URL, status=200, body=SAMPLE_BODY_JSON)

        result = await client.make_request(SAMPLE_URL)

        assert result == SAMPLE_BODY


@pytest.mark.asyncio
async def test_failed_request():
    client = APIClient()

    with aioresponses() as m:
        m.get(SAMPLE_URL, status=401)

        with pytest.raises(ApiError, match="Invalid response: 401"):
            await client.make_request(SAMPLE_URL)


@pytest.mark.asyncio
async def test_timed_out_request():
    client = APIClient()

    with aioresponses() as m:
        m.get(SAMPLE_URL, exception=asyncio.TimeoutError())

        with pytest.raises(ApiError, match=f"Could not connect to {SAMPLE_URL}"):
            await client.make_request(SAMPLE_URL)


@pytest.mark.asyncio
async def test_connection_error():
    client = APIClient()

    with aioresponses() as m:
        m.get(SAMPLE_URL, exception=ClientConnectionError())

        with pytest.raises(ApiError, match=f"Could not connect to {SAMPLE_URL}"):
            await client.make_request(SAMPLE_URL)


@pytest.mark.asyncio
async def test_external_session_not_closed():
    session = ClientSession()
    client = APIClient(session)

    with aioresponses() as m:
        m.get(SAMPLE_URL, status=200, body=SAMPLE_BODY_JSON)

        await client.make_request(SAMPLE_URL)

        assert not session.closed