|
19 | 19 | from unittest import mock |
20 | 20 |
|
21 | 21 | import pytest |
| 22 | +import requests |
22 | 23 | from botocore.exceptions import ClientError |
23 | 24 | from moto import mock_aws |
24 | 25 |
|
|
27 | 28 | ENV_NAME = "test_env" |
28 | 29 | PATH = "/dags/test_dag/dagRuns" |
29 | 30 | METHOD = "POST" |
| 31 | +BODY: dict = {"conf": {}} |
30 | 32 | QUERY_PARAMS = {"limit": 30} |
| 33 | +HOSTNAME = "example.com" |
31 | 34 |
|
32 | 35 |
|
33 | 36 | class TestMwaaHook: |
| 37 | + @pytest.fixture |
| 38 | + def mock_conn(self): |
| 39 | + with mock.patch.object(MwaaHook, "conn") as m: |
| 40 | + yield m |
| 41 | + |
34 | 42 | def setup_method(self): |
35 | 43 | self.hook = MwaaHook() |
36 | 44 |
|
37 | | - # these example responses are included here instead of as a constant because the hook will mutate |
38 | | - # responses causing subsequent tests to fail |
39 | | - self.example_responses = { |
| 45 | + def test_init(self): |
| 46 | + assert self.hook.client_type == "mwaa" |
| 47 | + |
| 48 | + @mock_aws |
| 49 | + def test_get_conn(self): |
| 50 | + assert self.hook.conn is not None |
| 51 | + |
| 52 | + @pytest.mark.parametrize( |
| 53 | + "body", |
| 54 | + [ |
| 55 | + pytest.param(None, id="no_body"), |
| 56 | + pytest.param(BODY, id="non_empty_body"), |
| 57 | + ], |
| 58 | + ) |
| 59 | + def test_invoke_rest_api_success(self, body, mock_conn, example_responses): |
| 60 | + boto_invoke_mock = mock.MagicMock(return_value=example_responses["success"]) |
| 61 | + mock_conn.invoke_rest_api = boto_invoke_mock |
| 62 | + |
| 63 | + retval = self.hook.invoke_rest_api( |
| 64 | + env_name=ENV_NAME, path=PATH, method=METHOD, body=body, query_params=QUERY_PARAMS |
| 65 | + ) |
| 66 | + kwargs_to_assert = { |
| 67 | + "Name": ENV_NAME, |
| 68 | + "Path": PATH, |
| 69 | + "Method": METHOD, |
| 70 | + "Body": body if body else {}, |
| 71 | + "QueryParameters": QUERY_PARAMS, |
| 72 | + } |
| 73 | + boto_invoke_mock.assert_called_once_with(**kwargs_to_assert) |
| 74 | + mock_conn.create_web_login_token.assert_not_called() |
| 75 | + assert retval == {k: v for k, v in example_responses["success"].items() if k != "ResponseMetadata"} |
| 76 | + |
| 77 | + def test_invoke_rest_api_failure(self, mock_conn, example_responses): |
| 78 | + error = ClientError(error_response=example_responses["failure"], operation_name="invoke_rest_api") |
| 79 | + mock_conn.invoke_rest_api = mock.MagicMock(side_effect=error) |
| 80 | + mock_error_log = mock.MagicMock() |
| 81 | + self.hook.log.error = mock_error_log |
| 82 | + |
| 83 | + with pytest.raises(ClientError) as caught_error: |
| 84 | + self.hook.invoke_rest_api(env_name=ENV_NAME, path=PATH, method=METHOD) |
| 85 | + |
| 86 | + assert caught_error.value == error |
| 87 | + mock_conn.create_web_login_token.assert_not_called() |
| 88 | + expected_log = {k: v for k, v in example_responses["failure"].items() if k != "ResponseMetadata"} |
| 89 | + mock_error_log.assert_called_once_with(expected_log) |
| 90 | + |
| 91 | + @pytest.mark.parametrize("generate_local_token", [pytest.param(True), pytest.param(False)]) |
| 92 | + @mock.patch("airflow.providers.amazon.aws.hooks.mwaa.requests.Session") |
| 93 | + def test_invoke_rest_api_local_token_parameter( |
| 94 | + self, mock_create_session, generate_local_token, mock_conn |
| 95 | + ): |
| 96 | + self.hook.invoke_rest_api( |
| 97 | + env_name=ENV_NAME, path=PATH, method=METHOD, generate_local_token=generate_local_token |
| 98 | + ) |
| 99 | + if generate_local_token: |
| 100 | + mock_conn.invoke_rest_api.assert_not_called() |
| 101 | + mock_conn.create_web_login_token.assert_called_once() |
| 102 | + mock_create_session.assert_called_once() |
| 103 | + mock_create_session.return_value.request.assert_called_once() |
| 104 | + else: |
| 105 | + mock_conn.invoke_rest_api.assert_called_once() |
| 106 | + |
| 107 | + @mock.patch.object(MwaaHook, "_get_session_conn") |
| 108 | + def test_invoke_rest_api_fallback_success_when_iam_fails( |
| 109 | + self, mock_get_session_conn, mock_conn, example_responses |
| 110 | + ): |
| 111 | + boto_invoke_error = ClientError( |
| 112 | + error_response=example_responses["missingIamRole"], operation_name="invoke_rest_api" |
| 113 | + ) |
| 114 | + mock_conn.invoke_rest_api = mock.MagicMock(side_effect=boto_invoke_error) |
| 115 | + |
| 116 | + kwargs_to_assert = { |
| 117 | + "method": METHOD, |
| 118 | + "url": f"https://{HOSTNAME}/api/v1{PATH}", |
| 119 | + "params": QUERY_PARAMS, |
| 120 | + "json": BODY, |
| 121 | + "timeout": 10, |
| 122 | + } |
| 123 | + |
| 124 | + mock_response = mock.MagicMock() |
| 125 | + mock_response.status_code = example_responses["success"]["RestApiStatusCode"] |
| 126 | + mock_response.json.return_value = example_responses["success"]["RestApiResponse"] |
| 127 | + mock_session = mock.MagicMock() |
| 128 | + mock_session.request.return_value = mock_response |
| 129 | + |
| 130 | + mock_get_session_conn.return_value = (mock_session, HOSTNAME) |
| 131 | + |
| 132 | + retval = self.hook.invoke_rest_api( |
| 133 | + env_name=ENV_NAME, path=PATH, method=METHOD, body=BODY, query_params=QUERY_PARAMS |
| 134 | + ) |
| 135 | + |
| 136 | + mock_session.request.assert_called_once_with(**kwargs_to_assert) |
| 137 | + mock_response.raise_for_status.assert_called_once() |
| 138 | + assert retval == {k: v for k, v in example_responses["success"].items() if k != "ResponseMetadata"} |
| 139 | + |
| 140 | + @mock.patch.object(MwaaHook, "_get_session_conn") |
| 141 | + def test_invoke_rest_api_using_local_session_token_failure( |
| 142 | + self, mock_get_session_conn, example_responses |
| 143 | + ): |
| 144 | + mock_response = mock.MagicMock() |
| 145 | + mock_response.json.return_value = example_responses["failure"]["RestApiResponse"] |
| 146 | + error = requests.HTTPError(response=mock_response) |
| 147 | + mock_response.raise_for_status.side_effect = error |
| 148 | + |
| 149 | + mock_session = mock.MagicMock() |
| 150 | + mock_session.request.return_value = mock_response |
| 151 | + |
| 152 | + mock_get_session_conn.return_value = (mock_session, HOSTNAME) |
| 153 | + |
| 154 | + mock_error_log = mock.MagicMock() |
| 155 | + self.hook.log.error = mock_error_log |
| 156 | + |
| 157 | + with pytest.raises(requests.HTTPError) as caught_error: |
| 158 | + self.hook.invoke_rest_api(env_name=ENV_NAME, path=PATH, method=METHOD, generate_local_token=True) |
| 159 | + |
| 160 | + assert caught_error.value == error |
| 161 | + mock_error_log.assert_called_once_with(example_responses["failure"]["RestApiResponse"]) |
| 162 | + |
| 163 | + @mock.patch("airflow.providers.amazon.aws.hooks.mwaa.requests.Session") |
| 164 | + def test_get_session_conn(self, mock_create_session, mock_conn): |
| 165 | + token = "token" |
| 166 | + mock_conn.create_web_login_token.return_value = {"WebServerHostname": HOSTNAME, "WebToken": token} |
| 167 | + login_url = f"https://{HOSTNAME}/aws_mwaa/login" |
| 168 | + login_payload = {"token": token} |
| 169 | + |
| 170 | + mock_session = mock.MagicMock() |
| 171 | + mock_create_session.return_value = mock_session |
| 172 | + |
| 173 | + retval = self.hook._get_session_conn(env_name=ENV_NAME) |
| 174 | + |
| 175 | + mock_conn.create_web_login_token.assert_called_once_with(Name=ENV_NAME) |
| 176 | + mock_create_session.assert_called_once_with() |
| 177 | + mock_session.post.assert_called_once_with(login_url, data=login_payload, timeout=10) |
| 178 | + mock_session.post.return_value.raise_for_status.assert_called_once() |
| 179 | + |
| 180 | + assert retval == (mock_session, HOSTNAME) |
| 181 | + |
| 182 | + @pytest.fixture |
| 183 | + def example_responses(self): |
| 184 | + """Fixture for test responses to avoid mutation between tests.""" |
| 185 | + return { |
40 | 186 | "success": { |
41 | 187 | "ResponseMetadata": { |
42 | 188 | "RequestId": "some ID", |
@@ -73,57 +219,13 @@ def setup_method(self): |
73 | 219 | "type": "https://airflow.apache.org/docs/apache-airflow/2.10.3/stable-rest-api-ref.html#section/Errors/NotFound", |
74 | 220 | }, |
75 | 221 | }, |
| 222 | + "missingIamRole": { |
| 223 | + "Error": {"Message": "No Airflow role granted in IAM.", "Code": "AccessDeniedException"}, |
| 224 | + "ResponseMetadata": { |
| 225 | + "RequestId": "some ID", |
| 226 | + "HTTPStatusCode": 403, |
| 227 | + "HTTPHeaders": {"header1": "value1"}, |
| 228 | + "RetryAttempts": 0, |
| 229 | + }, |
| 230 | + }, |
76 | 231 | } |
77 | | - |
78 | | - def test_init(self): |
79 | | - assert self.hook.client_type == "mwaa" |
80 | | - |
81 | | - @mock_aws |
82 | | - def test_get_conn(self): |
83 | | - assert self.hook.conn is not None |
84 | | - |
85 | | - @pytest.mark.parametrize( |
86 | | - "body", |
87 | | - [ |
88 | | - pytest.param(None, id="no_body"), |
89 | | - pytest.param({"conf": {}}, id="non_empty_body"), |
90 | | - ], |
91 | | - ) |
92 | | - @mock.patch.object(MwaaHook, "conn") |
93 | | - def test_invoke_rest_api_success(self, mock_conn, body) -> None: |
94 | | - boto_invoke_mock = mock.MagicMock(return_value=self.example_responses["success"]) |
95 | | - mock_conn.invoke_rest_api = boto_invoke_mock |
96 | | - |
97 | | - retval = self.hook.invoke_rest_api(ENV_NAME, PATH, METHOD, body, QUERY_PARAMS) |
98 | | - kwargs_to_assert = { |
99 | | - "Name": ENV_NAME, |
100 | | - "Path": PATH, |
101 | | - "Method": METHOD, |
102 | | - "Body": body if body else {}, |
103 | | - "QueryParameters": QUERY_PARAMS, |
104 | | - } |
105 | | - boto_invoke_mock.assert_called_once_with(**kwargs_to_assert) |
106 | | - assert retval == { |
107 | | - k: v for k, v in self.example_responses["success"].items() if k != "ResponseMetadata" |
108 | | - } |
109 | | - |
110 | | - @mock.patch.object(MwaaHook, "conn") |
111 | | - def test_invoke_rest_api_failure(self, mock_conn) -> None: |
112 | | - error = ClientError( |
113 | | - error_response=self.example_responses["failure"], operation_name="invoke_rest_api" |
114 | | - ) |
115 | | - boto_invoke_mock = mock.MagicMock(side_effect=error) |
116 | | - mock_conn.invoke_rest_api = boto_invoke_mock |
117 | | - mock_log = mock.MagicMock() |
118 | | - self.hook.log.error = mock_log |
119 | | - |
120 | | - with pytest.raises(ClientError) as caught_error: |
121 | | - self.hook.invoke_rest_api(ENV_NAME, PATH, METHOD) |
122 | | - |
123 | | - assert caught_error.value == error |
124 | | - expected_log = { |
125 | | - k: v |
126 | | - for k, v in self.example_responses["failure"].items() |
127 | | - if k != "ResponseMetadata" and k != "Error" |
128 | | - } |
129 | | - mock_log.assert_called_once_with(expected_log) |
|
0 commit comments