|
| 1 | +import logging |
| 2 | +import sys |
| 3 | +import datetime |
| 4 | +import os |
| 5 | +import yaml |
| 6 | +from typing import Dict, List |
| 7 | +from src.buildspec import Buildspec |
| 8 | +from test.test_utils import get_buildspec_path |
| 9 | +from codebuild_environment import get_cloned_folder_path |
| 10 | +from .validators.platform_validator_utils import get_platform_validator |
| 11 | + |
| 12 | + |
| 13 | +def create_logger(name, level=logging.INFO): |
| 14 | + logger = logging.getLogger(name) |
| 15 | + if logger.handlers: |
| 16 | + return logger |
| 17 | + |
| 18 | + logger.setLevel(level) |
| 19 | + formatter = logging.Formatter( |
| 20 | + "[%(asctime)s PST %(levelname)s %(name)s %(filename)s:%(lineno)d] %(message)s", |
| 21 | + datefmt="%Y-%m-%d %H:%M:%S", |
| 22 | + ) |
| 23 | + formatter.converter = lambda *args: datetime.datetime.now( |
| 24 | + datetime.timezone(datetime.timedelta(hours=-8)) |
| 25 | + ).timetuple() |
| 26 | + |
| 27 | + handler = logging.StreamHandler(sys.stdout) |
| 28 | + handler.setFormatter(formatter) |
| 29 | + logger.addHandler(handler) |
| 30 | + logger.propagate = False |
| 31 | + return logger |
| 32 | + |
| 33 | + |
| 34 | +LOGGER = create_logger(__name__) |
| 35 | + |
| 36 | + |
| 37 | +def resolve_buildspec_variables(config): |
| 38 | + """Resolve environment variables in buildspec""" |
| 39 | + region = os.getenv("REGION", "us-west-2") |
| 40 | + account_id = os.getenv("ACCOUNT_ID", "") |
| 41 | + config_str = yaml.dump(config) |
| 42 | + config_str = config_str.replace("<set-$REGION-in-environment>", region) |
| 43 | + config_str = config_str.replace("<set-$ACCOUNT_ID-in-environment>", account_id) |
| 44 | + return yaml.safe_load(config_str) |
| 45 | + |
| 46 | + |
| 47 | +def parse_buildspec(image_uri): |
| 48 | + """Parse buildspec for test configurations""" |
| 49 | + repo_root = get_cloned_folder_path() |
| 50 | + buildspec_path = get_buildspec_path(repo_root) |
| 51 | + |
| 52 | + if not os.path.exists(buildspec_path): |
| 53 | + raise FileNotFoundError(f"Buildspec file not found: {buildspec_path}") |
| 54 | + |
| 55 | + BUILDSPEC = Buildspec() |
| 56 | + BUILDSPEC.load(buildspec_path) |
| 57 | + |
| 58 | + images = BUILDSPEC.get("images", {}) |
| 59 | + image_key = list(images.keys())[0] |
| 60 | + LOGGER.info(f"Using image config: {image_key}") |
| 61 | + image_config = images[image_key] |
| 62 | + |
| 63 | + tests = image_config.get("tests", []) |
| 64 | + globals_data = { |
| 65 | + "region": BUILDSPEC.get("region"), |
| 66 | + "arch_type": BUILDSPEC.get("arch_type"), |
| 67 | + "framework": BUILDSPEC.get("framework"), |
| 68 | + } |
| 69 | + |
| 70 | + return {"tests": tests, "globals": globals_data} |
| 71 | + |
| 72 | + |
| 73 | +def validate_and_filter_tests(buildspec_data: Dict, test_type: str, base_path: str) -> List[Dict]: |
| 74 | + """Validate and filter tests for the given test type""" |
| 75 | + applicable_tests = [] |
| 76 | + validation_errors = [] |
| 77 | + |
| 78 | + all_tests = buildspec_data.get("tests", []) |
| 79 | + LOGGER.info(f"Found {len(all_tests)} total test configurations") |
| 80 | + |
| 81 | + platform_tests = [test for test in all_tests if test["platform"].startswith(test_type)] |
| 82 | + LOGGER.info(f"Found {len(platform_tests)} applicable test configurations for {test_type}") |
| 83 | + |
| 84 | + for test in platform_tests: |
| 85 | + try: |
| 86 | + validator = get_platform_validator(test["platform"], base_path) |
| 87 | + test_config = {**test, "globals": buildspec_data.get("globals", {})} |
| 88 | + errors = validator.validate(test_config) |
| 89 | + |
| 90 | + if errors: |
| 91 | + validation_errors.extend( |
| 92 | + [f"Test {test['platform']}:", *[f" {error}" for error in errors], ""] |
| 93 | + ) |
| 94 | + else: |
| 95 | + applicable_tests.append(test) |
| 96 | + except ValueError as e: |
| 97 | + validation_errors.append(f"Test {test['platform']}: {str(e)}") |
| 98 | + |
| 99 | + if validation_errors: |
| 100 | + error_msg = "\n".join(validation_errors) |
| 101 | + LOGGER.error("Test validation failed:") |
| 102 | + LOGGER.error(error_msg) |
| 103 | + raise ValueError("Test validation failed. See errors above.") |
| 104 | + |
| 105 | + LOGGER.info(f"Validated {len(applicable_tests)} test configurations successfully") |
| 106 | + return applicable_tests |
| 107 | + |
| 108 | + |
| 109 | +def execute_platform_tests(platform, test_config, buildspec_data, image_uri): |
| 110 | + """Execute tests for a platform""" |
| 111 | + try: |
| 112 | + setup_params = { |
| 113 | + **test_config["params"], |
| 114 | + **buildspec_data["globals"], |
| 115 | + "image_uri": image_uri, |
| 116 | + } |
| 117 | + |
| 118 | + platform.setup(setup_params) |
| 119 | + LOGGER.info(f"{platform.__class__.__name__} setup completed") |
| 120 | + |
| 121 | + LOGGER.info(f"Executing {len(test_config['run'])} commands:") |
| 122 | + for cmd in test_config["run"]: |
| 123 | + LOGGER.info(f" - {cmd}") |
| 124 | + platform.execute_command(cmd) |
| 125 | + except Exception as e: |
| 126 | + LOGGER.error(f"Test failed: {e}") |
| 127 | + raise |
0 commit comments