|
| 1 | +""" |
| 2 | +Command to scan and overwrite the static tests' gas limits to new optimized value given in the |
| 3 | +input file. |
| 4 | +""" |
| 5 | + |
| 6 | +import json |
| 7 | +import re |
| 8 | +from pathlib import Path |
| 9 | +from typing import Dict, List, Set |
| 10 | + |
| 11 | +import click |
| 12 | +import yaml |
| 13 | + |
| 14 | +from ethereum_test_base_types import EthereumTestRootModel, HexNumber, ZeroPaddedHexNumber |
| 15 | +from ethereum_test_specs import StateStaticTest |
| 16 | +from pytest_plugins.filler.static_filler import NoIntResolver |
| 17 | + |
| 18 | + |
| 19 | +class GasLimitDict(EthereumTestRootModel): |
| 20 | + """Formatted JSON file with new gas limits in each test.""" |
| 21 | + |
| 22 | + root: Dict[str, int | None] |
| 23 | + |
| 24 | + def unique_files(self) -> Set[Path]: |
| 25 | + """Return a list of unique test files.""" |
| 26 | + files = set() |
| 27 | + for test in self.root: |
| 28 | + filename, _ = test.split("::") |
| 29 | + files.add(Path(filename)) |
| 30 | + return files |
| 31 | + |
| 32 | + def get_tests_by_file_path(self, file: Path | str) -> Set[str]: |
| 33 | + """Return a list of all tests that belong to a given file path.""" |
| 34 | + tests = set() |
| 35 | + for test in self.root: |
| 36 | + current_file, _ = test.split("::") |
| 37 | + if current_file == str(file): |
| 38 | + tests.add(test) |
| 39 | + return tests |
| 40 | + |
| 41 | + |
| 42 | +class StaticTestFile(EthereumTestRootModel): |
| 43 | + """A static test file.""" |
| 44 | + |
| 45 | + root: Dict[str, StateStaticTest] |
| 46 | + |
| 47 | + |
| 48 | +def _check_fixtures(*, input_path: Path, max_gas_limit: int | None, dry_run: bool, verbose: bool): |
| 49 | + """Perform some checks on the fixtures contained in the specified directory.""" |
| 50 | + # Load the test dictionary from the input JSON file |
| 51 | + test_dict = GasLimitDict.model_validate_json(input_path.read_text()) |
| 52 | + |
| 53 | + # Iterate through each unique test file that needs modification |
| 54 | + for test_file in test_dict.unique_files(): |
| 55 | + tests = test_dict.get_tests_by_file_path(test_file) |
| 56 | + test_file_contents = test_file.read_text() |
| 57 | + |
| 58 | + # Parse the test file based on its format (YAML or JSON) |
| 59 | + if test_file.suffix == ".yml" or test_file.suffix == ".yaml": |
| 60 | + loaded_yaml = yaml.load(test_file.read_text(), Loader=NoIntResolver) |
| 61 | + try: |
| 62 | + parsed_test_file = StaticTestFile.model_validate(loaded_yaml) |
| 63 | + except Exception as e: |
| 64 | + raise Exception( |
| 65 | + f"Unable to parse file {test_file}: {json.dumps(loaded_yaml, indent=2)}" |
| 66 | + ) from e |
| 67 | + else: |
| 68 | + parsed_test_file = StaticTestFile.model_validate_json(test_file_contents) |
| 69 | + |
| 70 | + # Validate that the file contains exactly one test |
| 71 | + assert len(parsed_test_file.root) == 1, f"File {test_file} contains more than one test." |
| 72 | + _, parsed_test = parsed_test_file.root.popitem() |
| 73 | + |
| 74 | + # Skip files with multiple gas limit values |
| 75 | + if len(parsed_test.transaction.gas_limit) != 1: |
| 76 | + if dry_run or verbose: |
| 77 | + print( |
| 78 | + f"Test file {test_file} contains more than one test (after parsing), skipping." |
| 79 | + ) |
| 80 | + continue |
| 81 | + |
| 82 | + # Get the current gas limit and check if modification is needed |
| 83 | + current_gas_limit = int(parsed_test.transaction.gas_limit[0]) |
| 84 | + if max_gas_limit is not None and current_gas_limit <= max_gas_limit: |
| 85 | + # Nothing to do, finished |
| 86 | + for test in tests: |
| 87 | + test_dict.root.pop(test) |
| 88 | + continue |
| 89 | + |
| 90 | + # Collect valid gas values for this test file |
| 91 | + gas_values: List[int] = [] |
| 92 | + for gas_value in [test_dict.root[test] for test in tests]: |
| 93 | + if gas_value is None: |
| 94 | + if dry_run or verbose: |
| 95 | + print( |
| 96 | + f"Test file {test_file} contains at least one test that cannot " |
| 97 | + "be updated, skipping." |
| 98 | + ) |
| 99 | + continue |
| 100 | + else: |
| 101 | + gas_values.append(gas_value) |
| 102 | + |
| 103 | + # Calculate the new gas limit (rounded up to nearest 100,000) |
| 104 | + new_gas_limit = max(gas_values) |
| 105 | + modified_new_gas_limit = ((new_gas_limit // 100000) + 1) * 100000 |
| 106 | + if verbose: |
| 107 | + print( |
| 108 | + f"Changing exact new gas limit ({new_gas_limit}) to " |
| 109 | + f"rounded ({modified_new_gas_limit})" |
| 110 | + ) |
| 111 | + new_gas_limit = modified_new_gas_limit |
| 112 | + |
| 113 | + # Check if the new gas limit exceeds the maximum allowed |
| 114 | + if max_gas_limit is not None and new_gas_limit > max_gas_limit: |
| 115 | + if dry_run or verbose: |
| 116 | + print(f"New gas limit ({new_gas_limit}) exceeds max ({max_gas_limit})") |
| 117 | + continue |
| 118 | + |
| 119 | + if dry_run or verbose: |
| 120 | + print(f"Test file {test_file} requires modification ({new_gas_limit})") |
| 121 | + |
| 122 | + # Find the appropriate pattern to replace the current gas limit |
| 123 | + potential_types = [int, HexNumber, ZeroPaddedHexNumber] |
| 124 | + substitute_pattern = None |
| 125 | + substitute_string = None |
| 126 | + |
| 127 | + attempted_patterns = [] |
| 128 | + |
| 129 | + for current_type in potential_types: |
| 130 | + potential_substitute_pattern = rf"\b{current_type(current_gas_limit)}\b" |
| 131 | + potential_substitute_string = f"{current_type(new_gas_limit)}" |
| 132 | + if ( |
| 133 | + re.search( |
| 134 | + potential_substitute_pattern, test_file_contents, flags=re.RegexFlag.MULTILINE |
| 135 | + ) |
| 136 | + is not None |
| 137 | + ): |
| 138 | + substitute_pattern = potential_substitute_pattern |
| 139 | + substitute_string = potential_substitute_string |
| 140 | + break |
| 141 | + |
| 142 | + attempted_patterns.append(potential_substitute_pattern) |
| 143 | + |
| 144 | + # Validate that a replacement pattern was found |
| 145 | + assert substitute_pattern is not None, ( |
| 146 | + f"Current gas limit ({attempted_patterns}) not found in {test_file}" |
| 147 | + ) |
| 148 | + assert substitute_string is not None |
| 149 | + |
| 150 | + # Perform the replacement in the test file content |
| 151 | + new_test_file_contents = re.sub(substitute_pattern, substitute_string, test_file_contents) |
| 152 | + |
| 153 | + assert test_file_contents != new_test_file_contents, "Could not modify test file" |
| 154 | + |
| 155 | + # Skip writing changes if this is a dry run |
| 156 | + if dry_run: |
| 157 | + continue |
| 158 | + |
| 159 | + # Write the modified content back to the test file |
| 160 | + test_file.write_text(new_test_file_contents) |
| 161 | + for test in tests: |
| 162 | + test_dict.root.pop(test) |
| 163 | + |
| 164 | + if dry_run: |
| 165 | + return |
| 166 | + |
| 167 | + # Write changes to the input file |
| 168 | + input_path.write_text(test_dict.model_dump_json(indent=2)) |
| 169 | + |
| 170 | + |
| 171 | +MAX_GAS_LIMIT = 16_777_216 |
| 172 | + |
| 173 | + |
| 174 | +@click.command() |
| 175 | +@click.option( |
| 176 | + "--input", |
| 177 | + "-i", |
| 178 | + "input_str", |
| 179 | + type=click.Path(exists=True, file_okay=True, dir_okay=False, readable=True), |
| 180 | + required=True, |
| 181 | + help="The input json file or directory containing json listing the new gas limits for the " |
| 182 | + "static test files files.", |
| 183 | +) |
| 184 | +@click.option( |
| 185 | + "--max-gas-limit", |
| 186 | + default=MAX_GAS_LIMIT, |
| 187 | + expose_value=True, |
| 188 | + help="Gas limit that triggers a test modification, and also the maximum value that a test " |
| 189 | + "should have after modification.", |
| 190 | +) |
| 191 | +@click.option( |
| 192 | + "--dry-run", |
| 193 | + "-d", |
| 194 | + "dry_run", |
| 195 | + is_flag=True, |
| 196 | + default=False, |
| 197 | + expose_value=True, |
| 198 | + help="Don't modify any files, simply print operations to be performed.", |
| 199 | +) |
| 200 | +@click.option( |
| 201 | + "--verbose", |
| 202 | + "-v", |
| 203 | + "verbose", |
| 204 | + is_flag=True, |
| 205 | + default=False, |
| 206 | + expose_value=True, |
| 207 | + help="Print extra information.", |
| 208 | +) |
| 209 | +def main(input_str: str, max_gas_limit, dry_run: bool, verbose: bool): |
| 210 | + """Perform some checks on the fixtures contained in the specified directory.""" |
| 211 | + input_path = Path(input_str) |
| 212 | + if not dry_run: |
| 213 | + # Always dry-run first before actually modifying |
| 214 | + _check_fixtures( |
| 215 | + input_path=input_path, |
| 216 | + max_gas_limit=max_gas_limit, |
| 217 | + dry_run=True, |
| 218 | + verbose=False, |
| 219 | + ) |
| 220 | + _check_fixtures( |
| 221 | + input_path=input_path, |
| 222 | + max_gas_limit=max_gas_limit, |
| 223 | + dry_run=dry_run, |
| 224 | + verbose=verbose, |
| 225 | + ) |
0 commit comments