1from typing import Dict, List 2 3 4class MapperException(Exception): 5 # Raised when the Mapper expectation equality fails. 6 pass 7 8 9class Mapper: 10 """ 11 This will overwrite the value of the metadata field whose key is |dictionary_key| 12 with the value declared in |write_value|, before the overwrite happens, it 13 will check if the expected_value matches the value in the metadata field. 14 15 Passing None to the |expected_value| will expect that the key does not exist 16 at all in the metadata. 17 """ 18 19 def __init__(self, dictionary_key: str, expected_value, write_value): 20 self._key = dictionary_key 21 self._expected_value = expected_value 22 self._write_value = write_value 23 24 def write(self, 25 metadata: Dict[str, str | List[str]]) -> None: 26 """ 27 Writes the value |write_value| which is passed in the constructor of 28 the Mapper to the |metadata| provided. Before the write operation happens, 29 a check will occur to make sure that the value being overwritten matches 30 the |expected_value| that was passed in the constructor. 31 32 If |None| was passed as |expected_value| then the expectation is that 33 the |key| should not exist in metadata.keys(). 34 35 :param metadata: A dictionary whose field with key |key| will be overwritten. 36 :raises: MapperException if the expectation check has failed. 37 """ 38 if self._expected_value is None and self._key in metadata: 39 # We expected the key not to exist but it existed. 40 raise MapperException( 41 f"Expected absence of key `{self._key}` but " 42 f"found {metadata[self._key]}") 43 44 if self._key not in metadata.keys() and self._expected_value: 45 # We expected a value but the key didn't exist, throw! 46 raise MapperException(f"Expected presence of key {self._key} but was" 47 f"not found.") 48 49 if self._key in metadata.keys() and metadata[ 50 self._key] != self._expected_value: 51 # We expected the value to match but it didn't. 52 raise MapperException( 53 f"Expected \"{self._expected_value}\" but found" 54 f" {metadata[self._key]} in the README.chromium") 55 56 metadata[self._key] = self._write_value 57