33
44Global conftest file for shared pytest fixtures
55"""
6+ import datetime
7+ import os
8+ from contextlib import asynccontextmanager
9+ from unittest import mock
10+
611import pytest
7- from fastapi .testclient import TestClient
812from async_asgi_testclient import TestClient as AsyncTestClient
13+ from fastapi .testclient import TestClient
914
1015from app .main import APP
16+ from app .utils import httputils
1117
1218
1319@pytest .fixture
@@ -25,3 +31,86 @@ async def async_api_client():
2531 Returns an async_asgi_testclient.TestClient.
2632 """
2733 return AsyncTestClient (APP )
34+
35+
36+ class DateTimeStrpTime :
37+ """Returns instance of `DateTimeStrpTime`
38+ when calling `app.services.location.jhu.datetime.trptime(date, '%m/%d/%y').isoformat()`.
39+ """
40+
41+ def __init__ (self , date , strformat ):
42+ self .date = date
43+ self .strformat = strformat
44+
45+ def isoformat (self ):
46+ return datetime .datetime .strptime (self .date , self .strformat ).isoformat ()
47+
48+
49+ class FakeRequestsGetResponse :
50+ """Fake instance of a response from `aiohttp.ClientSession.get`.
51+ """
52+
53+ def __init__ (self , url , filename , state ):
54+ self .url = url
55+ self .filename = filename
56+ self .state = state
57+
58+ async def text (self ):
59+ return self .read_file (self .state )
60+
61+ def read_file (self , state ):
62+ """
63+ Mock HTTP GET-method and return text from file
64+ """
65+ state = state .lower ()
66+
67+ # Determine filepath.
68+ filepath = os .path .join (os .path .dirname (__file__ ), "example_data/{}.csv" .format (state ))
69+
70+ # Return fake response.
71+ print ("Try to read {}" .format (filepath ))
72+ with open (filepath , "r" ) as file :
73+ return file .read ()
74+
75+
76+ @asynccontextmanager
77+ async def mock_client_session ():
78+ """Context manager that replaces the global client_session with an AsyncMock instance.
79+
80+ :Example:
81+
82+ >>> async with mock_client_session() as mocked_client_session:
83+ >>> mocked_client_session.get = mocked_session_get
84+ >>> # test code...
85+
86+ """
87+
88+ httputils .client_session = mocked_client_session = mock .AsyncMock ()
89+ try :
90+ yield mocked_client_session
91+ finally :
92+ del httputils .client_session
93+
94+
95+ @asynccontextmanager
96+ async def mocked_session_get (* args , ** kwargs ):
97+ """Mock response from client_session.get.
98+ """
99+
100+ url = args [0 ]
101+ filename = url .split ("/" )[- 1 ]
102+
103+ # clean up for id token (e.g. Deaths)
104+ state = filename .split ("-" )[- 1 ].replace (".csv" , "" ).lower ().capitalize ()
105+
106+ yield FakeRequestsGetResponse (url , filename , state )
107+
108+
109+ def mocked_strptime_isoformat (* args , ** kwargs ):
110+ """Mock return value from datetime.strptime().isoformat().
111+ """
112+
113+ date = args [0 ]
114+ strformat = args [1 ]
115+
116+ return DateTimeStrpTime (date , strformat )
0 commit comments