def test_rdiv(session): sess = session # scalar / session with must_warn(RuntimeWarning, msg="divide by zero encountered during operation", check_num=False): res = 2 / sess with np.errstate(divide='ignore'): expected_e = 2 / e expected_f = 2 / f expected_g = 2 / g assert_array_nan_equal(res['e'], expected_e) assert_array_nan_equal(res['f'], expected_f) assert_array_nan_equal(res['g'], expected_g) assert res.a is a assert res.a01 is a01 assert res.c is c # dict(Array and scalar) - session other = {'e': e, 'f': f} with must_warn( RuntimeWarning, msg= "invalid value (NaN) encountered during operation (this is typically caused by a 0 / 0)", check_num=False): res = other / sess with np.errstate(invalid='ignore'): expected_e = e / e expected_f = f / f assert_array_nan_equal(res['e'], expected_e) assert_array_nan_equal(res['f'], expected_f) assert res.a is a assert res.a01 is a01 assert res.c is c
def test_add_cs(checkedsession): cs = checkedsession test_add(cs) u = Axis('u=u0..u2') with must_warn(UserWarning, msg=f"'u' is not declared in '{cs.__class__.__name__}'", check_file=False): cs.add(u)
def test_to_globals(session): msg = "Session.to_globals should usually only be used in interactive consoles and not in scripts. " \ "Use warn=False to deactivate this warning." with must_warn(RuntimeWarning, msg=msg): session.to_globals() assert a is session.a assert b is session.b assert c is session.c assert d is session.d assert e is session.e assert f is session.f assert g is session.g # test inplace backup_dest = e backup_value = session.e.copy() session.e = zeros_like(e) session.to_globals(inplace=True, warn=False) # check the variable is correct (the same as before) assert e is backup_dest assert e is not session.e # check the content has changed assert_array_nan_equal(e, session.e) assert not e.equals(backup_value) # reset e to its original value e[:] = backup_value
def test_excel_report_sheets(): report = ExcelReport() # test adding new sheets report.new_sheet('Population') report.new_sheet('Births') report.new_sheet('Deaths') # test warning if sheet already exists with must_warn( UserWarning, msg= "Sheet 'Population' already exists in the report and will be reset" ): sheet_population2 = report.new_sheet('Population') # noqa: F841 # test sheet_names() assert report.sheet_names() == ['Population', 'Births', 'Deaths']
def test_setattr_cs(checkedsession): cs = checkedsession # only change values of an array -> OK cs.h = zeros_like(h) # trying to add an undeclared variable -> prints a warning message with must_warn(UserWarning, msg=f"'i' is not declared in '{cs.__class__.__name__}'"): cs.i = ndtest((3, 3)) # trying to set a variable with an object of different type -> should fail # a) type given explicitly # -> Axis with must_raise(TypeError, msg="instance of Axis expected"): cs.a = 0 # -> CheckedArray with must_raise(TypeError, msg="Expected object of type 'Array' or a scalar for the variable 'h' but got " "object of type 'ndarray'"): cs.h = h.data # b) type deduced from the given default value with must_raise(TypeError, msg="instance of Axis expected"): cs.b = ndtest((3, 3)) # trying to set a CheckedArray variable using a scalar -> OK cs.h = 5 # trying to set a CheckedArray variable using an array with axes in different order -> OK cs.h = h.transpose() assert cs.h.axes.names == h.axes.names # broadcasting (missing axis) is allowed cs.h = ndtest(a3) assert_array_nan_equal(cs.h['b0'], cs.h['b1']) # trying to set a CheckedArray variable using an array with wrong axes -> should fail # a) extra axis with must_raise(ValueError, msg="Array 'h' was declared with axes {a, b} but got array with axes {a, b, c} " "(unexpected {c} axis)"): cs.h = ndtest((a3, b2, 'c=c0..c2')) # b) incompatible axis msg = """\ Incompatible axis for array 'h': Axis(['a0', 'a1', 'a2', 'a3', 'a4'], 'a') vs Axis(['a0', 'a1', 'a2', 'a3'], 'a')""" with must_raise(ValueError, msg=msg): cs.h = h.append('a', 0, 'a4')
def test_div(session): sess = session session_cls = session.__class__ other = session_cls({'e': e, 'f': f}) other['e'] = e - 1 other['f'] = f + 1 with must_warn(RuntimeWarning, msg="divide by zero encountered during operation"): res = sess / other with np.errstate(divide='ignore', invalid='ignore'): flat_e = np.arange(6) / np.arange(-1, 5) assert_array_nan_equal(res['e'], flat_e.reshape(2, 3)) flat_f = np.arange(6) / np.arange(1, 7) assert_array_nan_equal(res['f'], flat_f.reshape(3, 2)) assert isnan(res['g']).all()
def test_create_checkedsession_instance(meta): # As of v1.0 of pydantic all fields with annotations (whether annotation-only or with a default value) # will precede all fields without an annotation. Within their respective groups, fields remain in the # order they were defined. # See https://pydantic-docs.helpmanual.io/usage/models/#field-ordering declared_variable_keys = ['a', 'a2', 'a01', 'c', 'e', 'g', 'f', 'h', 'b', 'b024', 'anonymous', 'ano01', 'd'] # setting variables without default values cs = TestCheckedSession(a, a01, a2=a2, e=e, f=f, g=g, h=h) assert list(cs.keys()) == declared_variable_keys assert cs.b.equals(b) assert cs.b024.equals(b024) assert cs.a.equals(a) assert cs.a2.equals(a2) assert cs.anonymous.equals(anonymous) assert cs.a01.equals(a01) assert cs.ano01.equals(ano01) assert cs.c == c assert cs.d == d assert cs.e.equals(e) assert cs.g.equals(g) assert cs.f.equals(f) assert cs.h.equals(h) # metadata cs = TestCheckedSession(a, a01, a2=a2, e=e, f=f, g=g, h=h, meta=meta) assert cs.meta == meta # override default value b_alt = Axis('b=b0..b4') cs = TestCheckedSession(a, a01, b=b_alt, a2=a2, e=e, f=f, g=g, h=h) assert cs.b is b_alt # test for "NOT_LOADED" variables with must_warn(UserWarning, msg="No value passed for the declared variable 'a'", check_file=False): TestCheckedSession(a01=a01, a2=a2, e=e, f=f, g=g, h=h) cs = TestCheckedSession() assert list(cs.keys()) == declared_variable_keys # --- variables with default values --- assert cs.b.equals(b) assert cs.b024.equals(b024) assert cs.anonymous.equals(anonymous) assert cs.ano01.equals(ano01) assert cs.c == c assert cs.d == d # --- variables without default values --- assert isinstance(cs.a, NotLoaded) assert isinstance(cs.a2, NotLoaded) assert isinstance(cs.a01, NotLoaded) assert isinstance(cs.e, NotLoaded) assert isinstance(cs.g, NotLoaded) assert isinstance(cs.f, NotLoaded) assert isinstance(cs.h, NotLoaded) # passing a scalar to set all elements a CheckedArray cs = TestCheckedSession(a, a01, a2=a2, e=e, f=f, g=g, h=5) assert cs.h.axes == AxisCollection((a3, b2)) assert cs.h.equals(full(axes=(a3, b2), fill_value=5)) # add the undeclared variable 'i' with must_warn(UserWarning, f"'i' is not declared in '{cs.__class__.__name__}'", check_file=False): cs = TestCheckedSession(a, a01, a2=a2, i=5, e=e, f=f, g=g, h=h) assert list(cs.keys()) == declared_variable_keys + ['i'] # test inheritance between checked sessions class TestInheritance(TestCheckedSession): # override variables b = b2 c: int = 5 f: CheckedArray((a3, b2), dtype=int) h: CheckedArray((Axis(3), Axis(2))) # new variables n0 = 'first new var' n1: str declared_variable_keys += ['n1', 'n0'] cs = TestInheritance(a, a01, a2=a2, e=e, f=h, g=g, h=f, n1='second new var') assert list(cs.keys()) == declared_variable_keys # --- overriden variables --- assert cs.b.equals(b2) assert cs.c == 5 assert cs.f.equals(h) assert cs.h.equals(f) # --- new variables --- assert cs.n0 == 'first new var' assert cs.n1 == 'second new var' # --- variables declared in the base class --- assert cs.b024.equals(b024) assert cs.a.equals(a) assert cs.a2.equals(a2) assert cs.anonymous.equals(anonymous) assert cs.a01.equals(a01) assert cs.ano01.equals(ano01) assert cs.d == d assert cs.e.equals(e) assert cs.g.equals(g)