Skip to content

Commit

Permalink
rest refactor considered
Browse files Browse the repository at this point in the history
  • Loading branch information
stan-dot committed Mar 7, 2024
1 parent df06e86 commit c9fbc85
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/blueapi/cli/rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,8 @@ def _request_and_deserialize(
raise_if: Callable[[requests.Response], bool] = _is_exception,
) -> T:
url = self._url(suffix)
# todo consider changing this to a switch statement for easier mocking
# alternatively do single responsiblity principle and decoule request from deserializing.
response = requests.request(method, url, json=data)
if raise_if(response):
message = get_status_message(response.status_code)
Expand Down
46 changes: 46 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,3 +177,49 @@ def test_config_passed_down_to_command_children(
"params": {"time": 5},
}
}


@pytest.mark.handler
@patch("blueapi.service.handler.Handler")
def test_config_passed_down_to_command_children_2(
mock_handler: Mock,
handler, # This seems to be provided; ensure it's correctly instantiated
runner: CliRunner, # Ensure runner is correctly instantiated before the test
):
mock_handler.side_effect = Mock(return_value=handler)
config_path = "tests/example_yaml/rest_config.yaml"

with patch("uvicorn.run", side_effect=None):
result = runner.invoke(main, ["-c", config_path, "serve"])
assert result.exit_code == 0

# Mocking `requests.get` and `requests.post` separately
with patch("requests.request") as mock_get, patch("requests.post") as mock_post:
# Mock the GET response
mock_get.return_value = Mock()
mock_get.return_value.json.return_value = {"time": 5}

# Mock the POST response
mock_post.return_value = Mock(status_code=200) # Mock a successful POST request

# Invoke the command that triggers the HTTP requests
result = runner.invoke(
main, ["-c", config_path, "controller", "run", "sleep", '{"time": 5}']
)
assert result.exit_code == 0

# Check that the correct GET request was made
mock_get.assert_called_once_with(
"http://a.fake.host:12345/plans/sleep"
)

# If you're sending a POST request in the process that should be captured here
# This part depends on how your `main` function and its subcommands handle the POST request
# You might need to adjust the assertion to match your application's behavior
mock_post.assert_called_once_with(
"http://a.fake.host:12345/tasks",
json={
"name": "sleep",
"params": {"time": 5},
}
)

0 comments on commit c9fbc85

Please sign in to comment.