diff --git a/src/blueapi/cli/rest.py b/src/blueapi/cli/rest.py index 465959caa..b2735d46a 100644 --- a/src/blueapi/cli/rest.py +++ b/src/blueapi/cli/rest.py @@ -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) diff --git a/tests/test_cli.py b/tests/test_cli.py index f6425fe6a..94ddcf3fe 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -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}, + } + )