blob: 6b9389b47995cae1aeaaa2b21773178fbe61c906 [file] [edit]
# Copyright 2026 The Pigweed Authors
#
# 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
#
# https://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.
"""Test API for workflows module.
Provides test helpers for mocking workflow files in various formats (TextProto,
JSON, YAML, TOML) for recipe tests.
"""
from __future__ import annotations
from typing import Any
from recipe_engine import config_types, recipe_test_api, step_data
class WorkflowsTestApi(recipe_test_api.RecipeTestApi):
"""Test API for workflows module."""
def mock_file(
self,
directory: config_types.Path | None = None,
filename: str = 'workflows.textproto',
content: str | dict[str, Any] | None = None,
step_name: str | None = None,
) -> step_data.StepData:
"""Mocks the presence and content of a workflow configuration file.
Args:
directory: Directory where the mock file resides. Defaults to
`api.path.start_dir / 'co'`.
filename: Name of the workflow file (e.g. 'workflows.textproto',
'workflows.json', 'workflows.yaml', 'workflows.toml').
content: File content string or dictionary for YAML. If None,
sensible default content with a single build is used.
step_name: Step name for the mock file reading step. Defaults to
`read {filename}`.
Returns:
StepData combining path existence and file read step test data.
"""
if directory is None:
directory = self.m.path.start_dir / 'co'
step_name = step_name or f'read {filename}'
if filename.endswith('.yaml'):
if not isinstance(content, dict):
content = {'builds': [{'name': 'foo'}]}
step_data_obj = self.step_data(
step_name, self.m.json.output_stream(content)
)
else:
if not isinstance(content, str):
if filename.endswith('.json'):
content = '{"builds": [{"name": "foo"}]}'
elif filename.endswith('.toml'):
content = '[[builds]]\nname = "foo"\n'
elif filename.endswith('.textproto'):
content = 'builds { name: "foo" }'
else:
content = '' # pragma: no cover
step_data_obj = self.step_data(
step_name, self.m.file.read_text(content)
)
return self.m.path.exists(directory / filename) + step_data_obj