Repository navigation
[Better Tests] Add error injection and runtime overrides for GCE metadata fake values #5481
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
IvanBM18
merged 5 commits into
better-tests/02a-metadata-emulator-tests
from
better-tests/03-metadata-emulator-faults
Oct 6, 2026
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
bceafb1
[Better Tests] Add fault injection and runtime overrides to metadata …
IvanBM18 7ddb134
[Better tests] Makes args clearer by passing them as named args in tests
IvanBM18 6b6ff02
[Better Tests] Extract shared WireMock fault injector with compositio…
IvanBM18 35ed0cb
[Swarming][Refactor] Swarming constants and changes server URL format…
IvanBM18 3547bc8
[Better Tests] Rename WireMock fault injection to error injection
IvanBM18 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| # Copyright 2026 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| """Constants for Swarming API interaction.""" | ||
|
|
||
| from google.protobuf import json_format | ||
| from google.protobuf.timestamp_pb2 import \ | ||
| Timestamp # pylint: disable=no-name-in-module | ||
|
|
||
| # TODO(b/516627559): Move scopes to config file | ||
| SWARMING_SCOPES = [ | ||
| 'https://www.googleapis.com/auth/cloud-platform', | ||
| 'https://www.googleapis.com/auth/userinfo.email', | ||
| ] | ||
|
|
||
| COUNT_TASKS_ENDPOINT = '/prpc/swarming.v2.Tasks/CountTasks' | ||
| NEW_TASK_ENDPOINT = '/prpc/swarming.v2.Tasks/NewTask' | ||
|
|
||
| XSSI_PREFIX = ")]}'\n" | ||
|
|
||
| MIN_TASK_START_TIME = '2026-06-01T00:00:00Z' | ||
| MIN_TASK_START_TIME_PROTO = json_format.Parse(f'"{MIN_TASK_START_TIME}"', | ||
| Timestamp()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| # Copyright 2026 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,173 @@ | ||
| # Copyright 2026 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| """Shared WireMock error injection for service emulators.""" | ||
|
|
||
| import abc | ||
| from http import HTTPStatus | ||
| import uuid | ||
|
|
||
| from wiremock.client import HttpMethods | ||
| from wiremock.client import Mapping | ||
| from wiremock.client import MappingRequest | ||
| from wiremock.client import MappingResponse | ||
| from wiremock.client import Mappings | ||
| from wiremock.constants import Config | ||
|
|
||
| _DEFAULT_RESPONSE_HEADERS = { | ||
| 'Content-Type': 'text/plain; charset=utf-8', | ||
| } | ||
|
|
||
|
|
||
| class ErrorInjector(abc.ABC): | ||
| """Interface for injecting and clearing HTTP errors in service emulators.""" | ||
|
|
||
| @abc.abstractmethod | ||
| def inject_error( | ||
| self, | ||
| path: str, | ||
| status: int = HTTPStatus.INTERNAL_SERVER_ERROR, | ||
| times: int = 1, | ||
| delay_seconds: float = 0, | ||
| method: str = HttpMethods.ANY, | ||
| ) -> None: | ||
| """Makes the emulator fail requests to path.""" | ||
|
|
||
| @abc.abstractmethod | ||
| def clear_errors(self) -> None: | ||
| """Removes every injected error.""" | ||
|
|
||
|
|
||
| class WireMockErrorInjector(ErrorInjector): | ||
| """Injects and clears HTTP errors in a running WireMock container.""" | ||
|
|
||
| def __init__( | ||
| self, | ||
| admin_url: str, | ||
| path_prefix: str = '', | ||
| request_headers: dict | None = None, | ||
| response_headers: dict | None = None, | ||
| ): | ||
| self._admin_url = admin_url | ||
| self._path_prefix = path_prefix | ||
| self._request_headers = request_headers | ||
| self._response_headers = response_headers or _DEFAULT_RESPONSE_HEADERS | ||
|
|
||
| def _create_mapping(self, mapping: Mapping) -> None: | ||
| Config.base_url = self._admin_url | ||
| Mappings.create_mapping(mapping) | ||
|
|
||
| def _all_mappings(self) -> list[Mapping]: | ||
| Config.base_url = self._admin_url | ||
| return Mappings.retrieve_all_mappings().mappings | ||
|
|
||
| def _delete_mapping(self, mapping_id: str) -> None: | ||
| Config.base_url = self._admin_url | ||
| Mappings.delete_mapping(mapping_id) | ||
|
|
||
| def _error_mapping( | ||
| self, | ||
| path: str, | ||
| status_code: int, | ||
| method: str = HttpMethods.ANY, | ||
| delay_ms: int | None = None, | ||
| scenario_name: str | None = None, | ||
| required_state: str | None = None, | ||
| new_state: str | None = None, | ||
| ) -> Mapping: | ||
| """Returns a non-persistent Mapping that injects an HTTP error for path.""" | ||
| request_kwargs: dict = { | ||
| 'method': method, | ||
| 'url_path': f'{self._path_prefix}{path}', | ||
| } | ||
| if self._request_headers is not None: | ||
| request_kwargs['headers'] = self._request_headers | ||
|
|
||
| response_kwargs: dict = { | ||
| 'status': status_code, | ||
| 'body': f'injected error for {path}\n', | ||
| 'headers': self._response_headers, | ||
| } | ||
| if delay_ms is not None: | ||
| response_kwargs['fixed_delay_milliseconds'] = delay_ms | ||
|
|
||
| return Mapping( | ||
| persistent=False, | ||
| scenario_name=scenario_name, | ||
| required_scenario_state=required_state, | ||
| new_scenario_state=new_state, | ||
| metadata={ | ||
| 'error': True, | ||
| 'error_path': path, | ||
| }, | ||
| request=MappingRequest(**request_kwargs), | ||
| response=MappingResponse(**response_kwargs), | ||
| ) | ||
|
|
||
| def _remove_existing_errors_for_path(self, path: str) -> None: | ||
| """Removes any active error mappings targeting path.""" | ||
| for mapping in self._all_mappings(): | ||
| metadata = mapping.metadata or {} | ||
| if metadata.get('error') and metadata.get('error_path') == path: | ||
| self._delete_mapping(mapping.id) | ||
|
|
||
| def inject_error( | ||
| self, | ||
| path: str, | ||
| status: int = HTTPStatus.INTERNAL_SERVER_ERROR, | ||
| times: int = 1, | ||
| delay_seconds: float = 0, | ||
| method: str = HttpMethods.ANY, | ||
| ) -> None: | ||
| """Makes the emulator fail requests to path. | ||
|
|
||
| Args: | ||
| path: Endpoint path (relative to path_prefix if configured). | ||
| status: The HTTP status to return. | ||
| times: How many requests to affect. 0 means indefinitely until | ||
| clear_errors() is called. | ||
| delay_seconds: How long the emulator should stall before responding. | ||
| method: HTTP method to match (defaults to HttpMethods.ANY). | ||
| """ | ||
| status_code = status or HTTPStatus.INTERNAL_SERVER_ERROR | ||
| delay_ms = int(delay_seconds * 1000) if delay_seconds > 0 else None | ||
| if times < 0: | ||
| raise ValueError(f'times must be >= 0, got {times}') | ||
|
|
||
| self._remove_existing_errors_for_path(path) | ||
|
|
||
| if times == 0: | ||
| self._create_mapping( | ||
| self._error_mapping( | ||
| path, status_code, method=method, delay_ms=delay_ms)) | ||
| return | ||
|
|
||
| scenario_name = f'error-{path}-{uuid.uuid4().hex}' | ||
| for i in range(times): | ||
| self._create_mapping( | ||
| self._error_mapping( | ||
| path, | ||
| status_code, | ||
| method=method, | ||
| delay_ms=delay_ms, | ||
| scenario_name=scenario_name, | ||
| required_state='Started' if i == 0 else f'step_{i}', | ||
| new_state=f'step_{i + 1}', | ||
| )) | ||
|
|
||
| def clear_errors(self) -> None: | ||
| """Removes every injected error mapping.""" | ||
| for mapping in self._all_mappings(): | ||
| metadata = mapping.metadata or {} | ||
| if metadata.get('error'): | ||
| self._delete_mapping(mapping.id) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.