Source code for Muscat.Helpers.CheckTools

# -*- coding: utf-8 -*-
#
# This file is subject to the terms and conditions defined in
# file 'LICENSE.txt', which is part of this source code package.
#
from typing import List, Callable
import os


[docs]def SkipTest(environnementVariableName: str) -> bool: """chef if a environnement variable is present to help the user to skip test Parameters ---------- environnementVariableName : str the name of a environnement variable Returns ------- bool true if the variable is present false if absent """ if environnementVariableName in os.environ: print("Warning skipping test (environnement variable "+str(environnementVariableName)+" set)") return True return False
[docs]def RunListOfCheckIntegrities(toTest: List[Callable[[bool], str]], GUI: bool = False) -> str: """ Execute all the functions in the list. Stop at the first error. the functions must return "ok", "skip" to be treated as successful function Parameters ---------- toTest : List[Callable[[bool],str] ] a list of functions GUI : bool, optional bool argument passed to every function , by default False Returns ------- str "ok" if all functions are executed correctly (the return of every function is "ok") "error..." at the first error encountered """ for func in toTest: print("running test : " + str(func)) res = func(GUI) if any([str(res).lower().startswith(x) for x in ["ok", "skip"]]): continue return f"error in {func} res" # pragma: no cover return "ok"
[docs]def MustFailFunctionWith(exceptionType, func: Callable, *args, **kwargs) -> None: """Helper function to check a call of a function raise an exception correctly Parameters ---------- func : Callable the function to be called, args, kwargs are the argument passed to the function Raises ------ RuntimeError Raise un exception of the function does NOT fail (in the sens of a exception raise) """ fail = True try: res = func(*args, **kwargs) fail = False except Exception as e: if isinstance(e, exceptionType): pass else: raise RuntimeError(f"function failed, but with wrong type of exception ({e},) expeted ({exceptionType})") if fail == False: raise RuntimeError(f"function {func} must fail, but returned {res}")
[docs]def MustFailFunction(func: Callable, *args, **kwargs) -> None: """Helper function to check a call of a function raise an exception correctly Parameters ---------- func : Callable the function to be called, args, kwargs are the argument passed to the function Raises ------ RuntimeError Raise un exception of the function does NOT fail (in the sens of a exception raise) """ fail = True try: res = func(*args, **kwargs) fail = False except: pass if fail == False: raise RuntimeError(f"function {func} must fail, but returned {res}")
[docs]def assert_numpy_shape(x, shape:list): """ ex: assert_shape(conv_input_array, [8, 3, None, None]) """ assert len(x.shape) == len(shape), (x.shape, shape) for _a, _b in zip(x.shape, shape): if isinstance(_b, int): assert _a == _b, (x.shape, shape)
[docs]def CheckIntegrityAbsent(GUI:bool=False): assert (SkipTest("THIS_ENV_VARIABLE_MUST_NOT_EXIST") == False) return "OK"
[docs]def CheckIntegrityPresent(GUI:bool=False): import os os.environ["MUSCAT_TEMP_VAR"] = "True" assert (SkipTest("MUSCAT_TEMP_VAR") == True) return "ok"
[docs]def CheckIntegrity(GUI:bool=False): RunListOfCheckIntegrities([CheckIntegrityAbsent, CheckIntegrityPresent]) fail = False try: MustFailFunction(sum, [1, 2]) except: fail = True pass if fail == False: raise RuntimeError("Error in the detection of fail") # pragma: no cover MustFailFunction(sum, 1) fail = False try: MustFailFunctionWith(TypeError, sum, [1, 2]) except: fail = True pass if fail == False: raise RuntimeError("Error in the detection of fail") # pragma: no cover MustFailFunctionWith(TypeError, sum, "3",5) fail = False try: MustFailFunctionWith(BufferError, sum, "3",5) except: fail = True pass if fail == False: raise RuntimeError("Error in the detection of fail") # pragma: no cover import numpy as np assert_numpy_shape(np.zeros((1,2)), [1,2] ) assert_numpy_shape(np.zeros((1,2)), [None,2] ) MustFailFunction(assert_numpy_shape,np.zeros((1,2)), [None,2,None] ) return "OK"