1#!/usr/bin/env python 2# Copyright 2023 The Pigweed Authors 3# 4# Licensed under the Apache License, Version 2.0 (the "License"); you may not 5# use this file except in compliance with the License. You may obtain a copy of 6# the License at 7# 8# https://www.apache.org/licenses/LICENSE-2.0 9# 10# Unless required by applicable law or agreed to in writing, software 11# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13# License for the specific language governing permissions and limitations under 14# the License. 15"""Common utilities for tests.""" 16 17import json 18import os 19import subprocess 20import tempfile 21import unittest 22 23from pathlib import Path 24from typing import Any 25 26from pw_emu.frontend import Emulator 27 28 29def check_prog(prog: str) -> tuple: 30 msg = f'running {prog}' 31 try: 32 proc = subprocess.run([prog, '--help'], capture_output=True) 33 if proc.returncode != 0: 34 output = proc.stdout.decode('ascii') + proc.stderr.decode('ascii') 35 msg = f'error {msg}: {output}' 36 return (False, msg) 37 except OSError as err: 38 msg = f'error {msg}: {str(err)}' 39 return (False, msg) 40 return (True, msg) 41 42 43class ConfigHelper(unittest.TestCase): 44 """Helper that setups and tears down the configuration file""" 45 46 _config: dict[str, Any] | None = None 47 48 def setUp(self) -> None: 49 self._wdir = tempfile.TemporaryDirectory() 50 with tempfile.NamedTemporaryFile('wt', delete=False) as file: 51 pw_emu_config: dict[str, Any] = {'pw': {'pw_emu': {}}} 52 if self._config: 53 pw_emu_config['pw']['pw_emu'].update(self._config) 54 json.dump(pw_emu_config, file) 55 self._config_file = file.name 56 57 def tearDown(self) -> None: 58 self._wdir.cleanup() 59 os.unlink(self._config_file) 60 61 62class ConfigHelperWithEmulator(ConfigHelper): 63 """Helper that setups and tears down the configuration file""" 64 65 def setUp(self) -> None: 66 super().setUp() 67 self._emu = Emulator(Path(self._wdir.name), Path(self._config_file)) 68