from pytest import approx, fail from polynomial import Polynomial def test_construct_polynomial_error(): coe = [3.5, -4.6, 0] # 3.5 - 4.6x + 0x^2 try: p = Polynomial(coe) # except RuntimeError as ex: print(ex) pass def test_construct_quadratic_polynomial(): coe = [3, -4.5, 1.5] # 3 - 4.5x + 1.5x^2 p = Polynomial(coe) assert p.getExponent(0) == 3 #e = p[0] def test_get_coefficient(): coe = [3, -4.5, 1.5] # 3 - 4.5x + 1.5x^2 p = Polynomial(coe) for idx in range(0, len(coe)): assert p[idx] == coe[idx] def test_get_coefficient_bad_argument(): coe = [3, -4.5, 1.5] # 3 - 4.5x + 1.5x^2 p = Polynomial(coe) try: p[-1] fail("Expected an exception") except IndexError as ex: pass def test_eval(): coe = [3, 2, 1] # 3 + 2x + x^2 p = Polynomial(coe) w = p.eval(0) # assert w == 3 w = p.eval(1) assert w == 6 w = p.eval(-1) def test_eval_per_operator(): coe = [3, 2, 1] # 3 + 2x + x^2 p = Polynomial(coe) w = p(-4.5) assert w == approx(14.25) def test_eval_per_operator_with_str_argument(): coe = [3, 2, 1] # 3 + 2x + x^2 p = Polynomial(coe) try: w = p("hello world") fail("Bad argument") except TypeError as ex: #assert ex.message == "Bad argument" print(ex) def test_approximate_eval(): coe = [3, 2, 1] # 3 + 2x + x^2 p = Polynomial(coe) w = p.eval(1.25) assert w == approx(7.0625) w = p.eval(1/3) assert w == approx(3.77777777)