Skip to content

Commit e3838fd

Browse files
committed
ENH: unit tests for 'get_node' API
1 parent 668faf4 commit e3838fd

File tree

4 files changed

+118
-40
lines changed

4 files changed

+118
-40
lines changed

src/save_and_restore_api/_api_async.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,13 @@ async def close(self):
1111
await self._client.aclose()
1212
self._client = None
1313

14+
async def __aenter__(self):
15+
self.open()
16+
return self
17+
18+
async def __aexit__(self, exc_type, exc_value, traceback):
19+
await self.close()
20+
1421
async def send_request(
1522
self, method, url, *, params=None, url_params=None, headers=None, data=None, timeout=None, auth=None
1623
):

src/save_and_restore_api/_api_base.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# import getpass
2+
import json
23
import pprint
34
from collections.abc import Mapping
45

@@ -42,17 +43,14 @@ class _SaveRestoreAPI_Base:
4243
HTTPClientError = HTTPClientError
4344
HTTPServerError = HTTPServerError
4445

46+
ROOT_NODE_UID = "44bef5de-e8e6-4014-af37-b8f6c8a939a2"
47+
4548
def __init__(self, *, base_url, timeout, request_fail_exceptions=True):
4649
self._base_url = base_url
4750
self._timeout = timeout
4851
self._client = None
49-
self._root_node_uid = "44bef5de-e8e6-4014-af37-b8f6c8a939a2"
5052
self._auth = None
5153

52-
@property
53-
def ROOT_NODE_UID(self):
54-
return self._root_node_uid
55-
5654
@staticmethod
5755
def gen_auth(username, password):
5856
return httpx.BasicAuth(username=username, password=password)
@@ -109,11 +107,13 @@ def _process_comm_exception(self, *, method, params, client_response):
109107
common_params = {"request": exc.request, "response": exc.response}
110108
if client_response and (client_response.status_code < 500):
111109
# Include more detail that httpx does by default.
112-
message = (
113-
f"{exc.response.status_code}: "
114-
f"{exc.response.json()['detail'] if client_response.content else ''} "
115-
f"{exc.request.url}"
116-
)
110+
response_text = ""
111+
if client_response.content:
112+
try:
113+
response_text = exc.response.json()["detail"]
114+
except json.JSONDecodeError:
115+
response_text = exc.response.text
116+
message = f"{exc.response.status_code}: {response_text} {exc.request.url}"
117117
raise self.HTTPClientError(message, **common_params) from exc
118118
else:
119119
raise self.HTTPServerError(exc, **common_params) from exc

src/save_and_restore_api/_api_threads.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,13 @@ def close(self):
1111
self._client.close()
1212
self._client = None
1313

14+
def __enter__(self):
15+
self.open()
16+
return self
17+
18+
def __exit__(self, exc_type, exc_value, traceback):
19+
self.close()
20+
1421
def send_request(
1522
self, method, url, *, params=None, url_params=None, headers=None, data=None, timeout=None, auth=None
1623
):

tests/test_package.py

Lines changed: 94 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -18,63 +18,127 @@
1818
base_url = "http://localhost:8080/save-restore"
1919

2020

21-
def test_version():
21+
def test_version_01():
22+
"""
23+
Test that the versioning works correctly.
24+
"""
2225
assert importlib.metadata.version("save_and_restore_api") == save_and_restore_api.__version__
2326

2427

28+
# # fmt: off
29+
# @pytest.mark.parametrize("library", ["THREADS", "ASYNC"])
30+
# # fmt: on
31+
# def test_api_call_01(library):
32+
# """
33+
# Test generic API call
34+
# """
35+
# username, password = user_username, user_password
36+
37+
# if not _is_async(library):
38+
# SR = SaveRestoreAPI_Threads(base_url=base_url, timeout=2)
39+
# SR.set_auth(username=user_username, password=user_password)
40+
# SR.open()
41+
# response = SR.login(username=username, password=password)
42+
# assert response["userName"] == username
43+
# SR.close()
44+
# SR.open()
45+
# response = SR.login(username=username, password=password)
46+
# assert response["userName"] == username
47+
# SR.close()
48+
# else:
49+
# async def testing():
50+
# SR = SaveRestoreAPI_Async(base_url=base_url, timeout=2)
51+
# SR.set_auth(username=user_username, password=user_password)
52+
# SR.open()
53+
# response = await SR.login(username=username, password=password)
54+
# assert response["userName"] == username
55+
# await SR.close()
56+
# SR.open()
57+
# response = await SR.login(username=username, password=password)
58+
# assert response["userName"] == username
59+
# await SR.close()
60+
61+
# asyncio.run(testing())
62+
63+
2564
# fmt: off
2665
@pytest.mark.parametrize("library", ["THREADS", "ASYNC"])
2766
@pytest.mark.parametrize("username, password, roles, code", [
2867
(admin_username, admin_password, ["ROLE_SAR-ADMIN"], 200),
2968
(user_username, user_password, ["ROLE_SAR-USER"], 200),
3069
(read_username, read_password, [], 200),
31-
(user_username, read_password, [], 401),
70+
(user_username, read_password, [], 401), # Incorrect password
71+
(user_username + "_a", user_password, [], 401), # Incorrect login
3272
])
3373
# fmt: on
3474
def test_login_01(username, password, roles, library, code):
75+
"""
76+
Tests for the 'login' API.
77+
"""
3578
if not _is_async(library):
36-
SR = SaveRestoreAPI_Threads(base_url=base_url, timeout=2)
37-
SR.set_auth(username=user_username, password=user_password)
38-
SR.open()
39-
if code == 200:
40-
response = SR.login(username=username, password=password)
41-
assert response["userName"] == username
42-
assert response["roles"] == roles
43-
else:
44-
with pytest.raises(SR.HTTPClientError, match=f"{code}"):
45-
SR.login(username=username, password=password)
46-
SR.close()
47-
else:
48-
async def testing():
49-
SR = SaveRestoreAPI_Async(base_url=base_url, timeout=2)
50-
SR.set_auth(username=user_username, password=user_password)
79+
with SaveRestoreAPI_Threads(base_url=base_url, timeout=2) as SR:
5180
SR.open()
5281
if code == 200:
53-
response = await SR.login(username=username, password=password)
82+
response = SR.login(username=username, password=password)
5483
assert response["userName"] == username
5584
assert response["roles"] == roles
5685
else:
5786
with pytest.raises(SR.HTTPClientError, match=f"{code}"):
58-
await SR.login(username=username, password=password)
59-
await SR.close()
87+
SR.login(username=username, password=password)
88+
else:
89+
async def testing():
90+
async with SaveRestoreAPI_Async(base_url=base_url, timeout=2) as SR:
91+
SR.open()
92+
if code == 200:
93+
response = await SR.login(username=username, password=password)
94+
assert response["userName"] == username
95+
assert response["roles"] == roles
96+
else:
97+
with pytest.raises(SR.HTTPClientError, match=f"{code}"):
98+
await SR.login(username=username, password=password)
6099

61100
asyncio.run(testing())
62101

63102

103+
# fmt: off
104+
@pytest.mark.parametrize("library", ["THREADS", "ASYNC"])
105+
@pytest.mark.parametrize("node_uid, code", [
106+
(SaveRestoreAPI_Threads.ROOT_NODE_UID, 200),
107+
("abc", 404),
108+
])
109+
# fmt: on
110+
def test_get_node_01(node_uid, library, code):
111+
"""
112+
Tests for the 'login' API.
113+
"""
114+
if not _is_async(library):
115+
with SaveRestoreAPI_Threads(base_url=base_url, timeout=2) as SR:
116+
SR.open()
117+
if code == 200:
118+
response = SR.get_node(node_uid)
119+
assert response["uniqueId"] == node_uid
120+
else:
121+
with pytest.raises(SR.HTTPClientError, match=f"{code}"):
122+
SR.get_node(node_uid)
123+
else:
124+
async def testing():
125+
async with SaveRestoreAPI_Async(base_url=base_url, timeout=2) as SR:
126+
SR.open()
127+
if code == 200:
128+
response = await SR.get_node(node_uid)
129+
assert response["uniqueId"] == node_uid
130+
else:
131+
with pytest.raises(SR.HTTPClientError, match=f"{code}"):
132+
await SR.get_node(node_uid)
133+
134+
asyncio.run(testing())
135+
136+
137+
64138
def test_comm():
65139
SR = SaveRestoreAPI_Threads(base_url=base_url, timeout=2)
66140
SR.set_auth(username=user_username, password=user_password)
67141
SR.open()
68142
SR.login(username="user", password="userPass")
69143
SR.get_node(SR.ROOT_NODE_UID)
70144
SR.close()
71-
72-
73-
@pytest.mark.asyncio
74-
async def test_comm_async():
75-
SR = SaveRestoreAPI_Async(base_url=base_url, timeout=2)
76-
SR.set_auth(username="user", password="userPass")
77-
SR.open()
78-
await SR.login(username="user", password="userPass")
79-
await SR.get_node(SR.ROOT_NODE_UID)
80-
await SR.close()

0 commit comments

Comments
 (0)