copapy/tests/test_ops.py

70 lines
2.2 KiB
Python
Raw Permalink Normal View History

2025-12-06 17:09:25 +00:00
from copapy import value, Target, NumLike, iif
import pytest
import copapy
2025-10-09 20:53:51 +00:00
2025-10-18 21:20:40 +00:00
def function1(c1: NumLike) -> list[NumLike]:
2025-10-13 20:58:55 +00:00
return [c1 / 4, c1 / -4, c1 // 4, c1 // -4, (c1 * -1) // 4,
c1 * 4, c1 * -4,
c1 + 4, c1 - 4,
c1 > 2, c1 > 100, c1 < 4, c1 < 100]
2025-10-09 20:53:51 +00:00
2025-10-18 21:20:40 +00:00
def function2(c1: NumLike) -> list[NumLike]:
2025-10-13 20:58:55 +00:00
return [c1 / 4.44, c1 / -4.44, c1 // 4.44, c1 // -4.44, (c1 * -1) // 4.44,
c1 * 4.44, c1 * -4.44,
c1 + 4.44, c1 - 4.44,
c1 > 2, c1 > 100.11, c1 < 4.44, c1 < 100.11]
2025-10-09 20:53:51 +00:00
2025-10-18 21:20:40 +00:00
def function3(c1: NumLike) -> list[NumLike]:
2025-10-12 20:22:30 +00:00
return [c1 / 4]
2025-10-18 21:20:40 +00:00
def function4(c1: NumLike) -> list[NumLike]:
2025-10-13 20:58:55 +00:00
return [c1 == 9, c1 == 4, c1 != 9, c1 != 4]
2025-10-18 21:20:40 +00:00
def function5(c1: NumLike) -> list[NumLike]:
return [c1 == True, c1 == False, c1 != True, c1 != False, c1 / 2, c1 + 2]
def function6(c1: NumLike) -> list[NumLike]:
return [c1 == True]
2025-10-13 20:58:55 +00:00
2025-10-19 20:48:52 +00:00
def iiftests(c1: NumLike) -> list[NumLike]:
return [iif(c1 > 5, 8, 9),
iif(c1 < 5, 8.5, 9.5),
iif(1 > 5, 3.3, 8.8) + c1,
iif(1 < 5, c1 * 3.3, 8.8),
iif(c1 < 5, c1 * 3.3, 8.8)]
2025-10-09 20:53:51 +00:00
2025-10-19 20:48:52 +00:00
def test_compile():
2025-12-06 17:09:25 +00:00
c_i = value(9)
c_f = value(1.111)
c_b = value(True)
2025-10-13 20:58:55 +00:00
2025-12-06 17:09:25 +00:00
ret_test = function1(c_i) + function1(c_f) + function2(c_i) + function2(c_f) + function3(c_i) + function4(c_i) + function5(c_b) + [value(9) % 2] + iiftests(c_i) + iiftests(c_f)
2025-10-19 20:48:52 +00:00
ret_ref = function1(9) + function1(1.111) + function2(9) + function2(1.111) + function3(9) + function4(9) + function5(True) + [9 % 2] + iiftests(9) + iiftests(1.111)
2025-10-13 20:58:55 +00:00
2025-10-09 20:53:51 +00:00
tg = Target()
print('* compile and copy ...')
2025-10-13 20:58:55 +00:00
tg.compile(ret_test)
2025-10-09 20:53:51 +00:00
print('* run and copy ...')
tg.run()
2025-10-13 20:58:55 +00:00
print('* finished')
2025-10-09 20:53:51 +00:00
2025-10-13 20:58:55 +00:00
for test, ref in zip(ret_test, ret_ref):
2025-12-06 17:09:25 +00:00
assert isinstance(test, copapy.value)
2025-10-09 20:53:51 +00:00
val = tg.read_value(test)
2025-10-18 21:20:40 +00:00
print('+', val, ref, test.dtype)
for t in (int, float, bool):
2025-10-13 20:58:55 +00:00
assert isinstance(val, t) == isinstance(ref, t), f"Result type does not match for {val} and {ref}"
assert val == pytest.approx(ref, 1e-5), f"Result does not match: {val} and reference: {ref}" # pyright: ignore[reportUnknownMemberType]
2025-10-09 20:53:51 +00:00
if __name__ == "__main__":
test_compile()