Skip to content

Commit 10420b7

Browse files
Reject unexpected schedule creation statuses.
1 parent 3d172de commit 10420b7

2 files changed

Lines changed: 29 additions & 7 deletions

File tree

‎pythonanywhere_core/schedule.py‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import List, Optional
1+
from typing import List
22

33
from typing_extensions import Literal
44

@@ -29,24 +29,24 @@ class Schedule:
2929

3030
base_url: str = get_api_endpoint(username=get_username(), flavor="schedule")
3131

32-
def create(self, params: dict) -> Optional[dict]:
32+
def create(self, params: dict) -> dict:
3333
"""Creates new scheduled task using `params`.
3434
3535
Params should be: command, enabled (True or False), interval (daily or
3636
hourly), hour (24h format) and minute.
3737
3838
:param params: dictionary with required scheduled task specs
39-
:returns: dictionary with created task specs"""
39+
:returns: dictionary with created task specs on HTTP 201
40+
:raises PythonAnywhereApiException: if the response is not HTTP 201"""
4041

4142
result = call_api(self.base_url, "POST", json=params)
4243

4344
if result.status_code == 201:
4445
return result.json()
4546

46-
if not result.ok:
47-
raise PythonAnywhereApiException(
48-
f"POST to set new task via API failed, got {result}: {result.text}"
49-
)
47+
raise PythonAnywhereApiException(
48+
f"POST to set new task via API failed, got {result}: {result.text}"
49+
)
5050

5151
def delete(self, task_id: int) -> Literal[True]:
5252
"""Deletes scheduled task by id.

‎tests/test_schedule.py‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,28 @@ def test_creates_hourly_task(
8383
assert Schedule().create(hourly_task_params) == task_specs
8484

8585

86+
@pytest.mark.parametrize("status_code, body", [
87+
(200, '{"task_id": 42}'),
88+
(202, '{"status": "accepted"}'),
89+
(204, ""),
90+
(400, '{"detail": "Invalid task"}'),
91+
(403, '{"detail": "Forbidden"}'),
92+
(500, '{"detail": "Server error"}'),
93+
(500, "Non-JSON server error"),
94+
])
95+
def test_create_raises_unless_response_is_201(
96+
api_token, api_responses, task_base_url, daily_task_params, status_code, body
97+
):
98+
api_responses.add(responses.POST, task_base_url, status=status_code, body=body)
99+
100+
with pytest.raises(PythonAnywhereApiException) as exc:
101+
Schedule().create(daily_task_params)
102+
103+
assert str(status_code) in str(exc.value)
104+
assert body in str(exc.value)
105+
assert len(api_responses.calls) == 1
106+
107+
86108
def test_raises_because_missing_params(api_token, api_responses, task_base_url):
87109
body = (
88110
'{"interval":["This field is required."],"command":["This field is required."],'

0 commit comments

Comments
 (0)