We are going to show how to write and run unit tests for a simple DAXPY operation (y := a*x + y) using Python's built‑in unittest.
Unit tests are small, focused tests that verify one function or behavior at a time. They help catch bugs early and document expected behavior.
import numpy as np
def daxpy(a, x, y):
x = np.asarray(x, dtype=float)
y = np.asarray(y, dtype=float)
if x.shape != y.shape:
raise ValueError("x and y must have the same shape")
return a * x + yimport unittest
import numpy as np
from daxpy import daxpy
class TestDaxpy(unittest.TestCase):
def test_basic(self):
a = 2.0
x = np.array([1., 2., 3.])
y = np.array([4., 5., 6.])
result = daxpy(a, x, y)
np.testing.assert_array_equal(result, np.array([6., 9., 12.]))
def test_zero_scalar(self):
result = daxpy(0.0, [1,2,3], [7,8,9])
np.testing.assert_array_equal(result, np.array([7., 8., 9.]))
def test_zero_vector(self):
result = daxpy(3.5, [0,0,0], [1,2,3])
np.testing.assert_array_equal(result, np.array([1., 2., 3.]))
def test_shape_mismatch_raises(self):
with self.assertRaises(ValueError):
daxpy(2.0, [1,2,3], [4,5])
def test_large_values(self):
a = 1e6
x = np.array([1., 2., 3.])
y = np.array([1., 1., 1.])
expected = np.array([1e6+1, 2e6+1, 3e6+1])
np.testing.assert_array_almost_equal(daxpy(a, x, y), expected)
if __name__ == "__main__":
unittest.main()Tests included:
test_basic— normal case → exact result[6, 9, 12].test_zero_scalar—a=0→ returnsy.test_zero_vector—xall zeros → returnsy.test_shape_mismatch_raises— different lengths forx,y→ raisesValueError.test_large_values— big numbers → almost-equal check for FP rounding.
From the project folder:
python -m unittest -vor directly:
python test_daxpy.pyThe following output was produced by running the command above in this environment showing all tests are ok
test_basic (test_daxpy.TestDaxpy.test_basic) ... ok
test_large_values (test_daxpy.TestDaxpy.test_large_values) ... ok
test_shape_mismatch_raises (test_daxpy.TestDaxpy.test_shape_mismatch_raises) ... ok
test_zero_scalar (test_daxpy.TestDaxpy.test_zero_scalar) ... ok
test_zero_vector (test_daxpy.TestDaxpy.test_zero_vector) ... ok
----------------------------------------------------------------------
Ran 5 tests in 0.008s
OK