Add test coverage.

Rationals are 100% tested, Vectors are 82% covered.

I used example cases from the class, so it's not exhaustive but it should be good.

The untested code in the vector class is all related to raising nonconformant errors.
This commit is contained in:
Kyle Isom 2022-03-08 00:16:22 -08:00
parent c0f599e563
commit ff3aa3f349
3 changed files with 91 additions and 1 deletions

View File

@ -1,5 +1,7 @@
import math import math
import numpy
class Rational: class Rational:
""" """
@ -39,7 +41,7 @@ class Rational:
return Rational(self.n * other.d, self.d * other.n) return Rational(self.n * other.d, self.d * other.n)
def lcm(self, other): def lcm(self, other):
return int(math.lcm(self.d, other.d)) return int(numpy.lcm(self.d, other.d))
def normalize(self, other): def normalize(self, other):
lcm = self.lcm(other) lcm = self.lcm(other)
@ -107,6 +109,7 @@ def ipow(n, m):
while m > 1: while m > 1:
x = x * n x = x * n
m -= 1
return x return x

View File

@ -1,3 +1,5 @@
import sys
import numpy import numpy
import pytest import pytest
@ -165,3 +167,7 @@ def test_cross_product():
v7 = vec.Vector(-6.007, 0.124, 5.772) v7 = vec.Vector(-6.007, 0.124, 5.772)
area = 42.565 area = 42.565
assert fequal(vec.area_triangle(v6, v7), area) assert fequal(vec.area_triangle(v6, v7), area)
if __name__ == '__main__':
sys.exit(pytest.main(["-qq"]))

81
tests/rat.py Normal file
View File

@ -0,0 +1,81 @@
import sys
import pytest
import kmath.rat as rat
def test_add():
r1 = rat.Rational(1, 1)
r2 = rat.Int(3)
r3 = r1 + r2
assert r3.n == 4
assert r3.d == 1
assert float(r3) == 4.0
assert int(r3) == 4
def test_mul():
r1 = rat.Rational(1, 2)
r2 = rat.Rational(1, 8)
r3 = rat.Rational(1, 16)
assert r1 * r2 == r3
def test_div():
r1 = rat.Rational(1, 2)
r2 = rat.Rational(1, 8)
r3 = rat.Int(4)
assert r1 / r2 == r3
def test_pow():
r1 = rat.Rational(1, 2)
r2 = rat.Rational(3, 4)
r3 = rat.Rational(1, 4)
r4 = rat.Rational(9, 16)
r5 = rat.Rational(1, 8)
assert r1 ** 2 == r3
assert r2 ** 2 == r4
assert rat.ipow(r1, 3) == r5
def test_scale():
r1 = rat.Rational(1, 2)
r2 = rat.Rational(2, 4)
assert r1.scale(2) == r2
assert r1.scale(2).reduce() == r1
def test_dbz_protection():
assert rat.Rational(0, 0) == rat.Rational(1, 0)
def test_equality():
r1 = rat.Rational(1, 2)
r2 = rat.Rational(3, 4)
r3 = rat.Rational(2, 4)
assert r1 < r2
assert r3 < r2
assert r1 <= r3
assert r1 == r3
assert r2 > r1
assert r2 >= r3
def test_sub():
r1 = rat.Rational(1, 2)
r2 = rat.Rational(1, 8)
r3 = rat.Rational(3, 8)
assert r1 - r2 == r3
def test_recurse():
"""test from the calculus course"""
r = rat.Rational(239, 169)
assert rat.recurse(5) == r
if __name__ == '__main__':
sys.exit(pytest.main(["-qq"]))