Skip to content

Commit 49dde4d

Browse files
committed
Add unit tests for utility functions in test_tools.py
1 parent 8b5e0c0 commit 49dde4d

1 file changed

Lines changed: 73 additions & 0 deletions

File tree

tests/utils/test_tools.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
# PolyKin: A polymerization kinetics library for Python.
2+
#
3+
# Copyright Hugo Vale 2024
4+
5+
6+
from numbers import Number
7+
8+
import numpy as np
9+
import pytest
10+
from numpy import isclose
11+
12+
from polykin.utils.exceptions import RangeError
13+
from polykin.utils.tools import (
14+
check_subclass,
15+
check_type,
16+
convert_check_pressure,
17+
pprint_matrix,
18+
)
19+
20+
21+
def test_check_type():
22+
# Test with correct types
23+
check_type(5, int, "a")
24+
check_type(3.14, float, "a")
25+
check_type([1, 2, 3], list, "a")
26+
check_type((1, 2), tuple, "a")
27+
check_type({"a": 1}, dict, "a")
28+
check_type(np.array([1, 2]), np.ndarray, "a")
29+
30+
# Test with incorrect types
31+
with pytest.raises(TypeError):
32+
check_type(5, float, "a")
33+
with pytest.raises(TypeError):
34+
check_type(3.14, int, "a")
35+
with pytest.raises(TypeError):
36+
check_type([1, 2, 3], tuple, "a")
37+
with pytest.raises(TypeError):
38+
check_type((1, 2), list, "a")
39+
with pytest.raises(TypeError):
40+
check_type({"a": 1}, list, "a")
41+
with pytest.raises(TypeError):
42+
check_type(np.array([1, 2]), list, "a")
43+
44+
# Test with containers
45+
check_type([1, 2, 3], int, "a", check_inside=True)
46+
check_type((1.0, 2.0, 3.0), float, "a", check_inside=True)
47+
check_type({"a", "b", "c"}, str, "a", check_inside=True)
48+
with pytest.raises(TypeError):
49+
check_type([1, "2", 3], int, "a", check_inside=True)
50+
51+
52+
def test_check_subclass():
53+
check_subclass(int, object, "a")
54+
check_subclass(float, Number, "a")
55+
check_subclass([int, float, complex], Number, "a", check_inside=True)
56+
with pytest.raises(TypeError):
57+
check_subclass(str, Number, "a")
58+
with pytest.raises(TypeError):
59+
check_subclass([int, str, float], Number, "a", check_inside=True)
60+
61+
62+
def test_pprint_matrix():
63+
matrix = np.array([[10.2552, 2], [3.456789, 4.567890]])
64+
expected_output = "[[1.03e+01 2.00e+00]\n [3.46e+00 4.57e+00]]\n"
65+
assert pprint_matrix(matrix) == expected_output
66+
67+
68+
def test_convert_check_pressure():
69+
for Psol, unit in zip([1, 1e5, 1e6], ["Pa", "bar", "MPa"]):
70+
P = convert_check_pressure(1.0, unit)
71+
assert isclose(P, Psol)
72+
with pytest.raises(RangeError):
73+
convert_check_pressure(-1.0, "bar")

0 commit comments

Comments
 (0)