Skip to content

Commit 76e7500

Browse files
committed
Created and tested Star Wars character DOB function
Created, type hinted, and tested a Star Wars character DOB function using the SWAPI api. The function searches for DOB using the name (or substring of name) and returns the DOB if name is found. I tested the function including mocking the exceptions and requests.get. I had to add a pragma to the next call on the generator expression as coverage though that variable prior to exit immediately. Seems to be a bug related to this issue nedbat/coveragepy#515.
1 parent d251327 commit 76e7500

File tree

3 files changed

+70
-1
lines changed

3 files changed

+70
-1
lines changed

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ force_grid_wrap = 0
4545
use_parentheses = true
4646
line_length = 100
4747
indent = ' '
48-
known_third_party = ["pytest"]
48+
known_third_party = ["pytest", "requests"]
4949
known_first_party = ["sandbox_pytest"]
5050

5151
[tool.pytest.ini_options]

sandbox_pytest/star_wars_info.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
from typing import Any, Dict, List, Union
2+
3+
import requests
4+
from requests.exceptions import ConnectionError, HTTPError
5+
6+
7+
def get_person_dob(name: str) -> Union[None, str]:
8+
try:
9+
response: requests.models.Response
10+
with requests.get("https://swapi.dev/api/people/") as response:
11+
response.raise_for_status()
12+
resp_dict: Dict[str, Any] = response.json()
13+
14+
resp_results: List[Dict[str, Any]] = resp_dict["results"]
15+
resp_person: Dict[str, Any] = next( # pragma: no cover
16+
item for item in resp_results if name.lower() in item["name"].lower()
17+
)
18+
dob: str = resp_person["birth_year"]
19+
except HTTPError as http_err:
20+
raise http_err
21+
except ConnectionError as ce:
22+
print(ce)
23+
raise ce
24+
except Exception as err:
25+
print(f"Other error occurred: {err}")
26+
raise err
27+
else:
28+
print(f"successfully retrieved the DOB of {name}")
29+
return dob
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
from unittest.mock import patch
2+
3+
import pytest
4+
5+
from sandbox_pytest.star_wars_info import get_person_dob, requests
6+
7+
8+
@pytest.mark.parametrize(
9+
"arg_names, add_exp_result", [("Luke Skywalker", "19BBY"), ("Darth Vader", "41.9BBY")]
10+
)
11+
def test_get_dob(arg_names, add_exp_result) -> None:
12+
assert get_person_dob(arg_names) == add_exp_result
13+
14+
15+
@patch.object(
16+
requests,
17+
"get",
18+
side_effect=[requests.exceptions.HTTPError, requests.exceptions.ConnectionError, Exception],
19+
)
20+
def test_dob_erros(mock_requests) -> None:
21+
with pytest.raises(requests.exceptions.HTTPError):
22+
get_person_dob("Darth Vader")
23+
with pytest.raises(requests.exceptions.ConnectionError):
24+
get_person_dob("Darth Vader")
25+
with pytest.raises(Exception):
26+
get_person_dob("Darth Vader")
27+
28+
29+
def test_mock_dob() -> None:
30+
with patch.object(requests, "get") as mock_response:
31+
mock_response.return_value.__enter__.return_value.json.return_value = {
32+
"results": [
33+
{"name": "Luke Skywalker", "birth_year": "19BBY"},
34+
{"name": "Darth Vader", "birth_year": "41.9BBY"},
35+
]
36+
}
37+
assert get_person_dob("Luke Skywalker") == "19BBY"
38+
mock_response.assert_called_once()
39+
assert get_person_dob("Darth Vader") == "41.9BBY"
40+
mock_response.assert_called()

0 commit comments

Comments
 (0)