2025-11-13 13:29:16 +01:00

87 lines
2.6 KiB
Python

import math
from _pytest.python_api import approx
from src.matrixmania.compute import matmul
import pytest
def test_square_matrix_multiplication():
"""Tests the multiplication of two square matrices"""
a = [[1, 2], [3, 4]]
b = [[5, 6], [7, 8]]
expected = [[19, 22], [43, 50]]
assert matmul(a, b) == expected
def test_rectangular_matrix_multiplication():
"""Testet eine 2x3-Matrix multipliziert mit einer 3x2-Matrix."""
a = [[1, 2, 3], [4, 5, 6]] # 2x3
b = [[7, 8], [9, 10], [11, 12]] # 3x2
expected = [[58, 64], [139, 154]]
assert matmul(a, b) == expected
def test_matmul_string():
a = "[[1, 2], [3, 4]]"
b = "[[5, 6], [7, 8]]"
result = None
try:
matmul(a, b)
except ValueError:
result = ValueError
assert result == ValueError
def test_multiply_with_identity_matrix():
"""Testet die Multiplikation mit einer Einheitsmatrix (sollte die Matrix selbst zurückgeben)."""
a = [[5, 8, -2], [3, 0, 1], [1, 1, 4]]
identity = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
assert matmul(a, identity) == a
assert matmul(identity, a) == a
def test_vector_multiplication():
"""Testet einen Zeilenvektor (1x3) mal einen Spaltenvektor (3x1)."""
a = [[1, 2, 3]] # 1x3
b = [[4], [5], [6]] # 3x1
# Erwartetes Ergebnis (1x1 Matrix): [1*4 + 2*5 + 3*6] = [32]
expected = [[32]]
assert matmul(a, b) == expected
def test_floats_and_negatives():
"""Testet die Multiplikation mit Fließkommazahlen und negativen Werten."""
a = [[1.5, -2], [0, 3]]
b = [[4], [-0.5]] # 2x1
expected = [[7.0], [-1.5]]
result = matmul(a, b)
assert len(result) == len(expected)
assert len(result[0]) == len(expected[0])
for i in range(len(expected)):
for j in range(len(expected[0])):
assert math.isclose(result[i][j], expected[i][j], abs_tol=1e-9)
def test_dimension_mismatch_error():
"""Prüft, ob bei inkompatiblen Dimensionen ein ValueError ausgelöst wird."""
a = [[1, 2], [3, 4]] # 2x2
b = [[1], [2], [3]] # 3x1 (Spalten von A (2) != Zeilen von B (3))
# Wir erwarten einen ValueError mit der spezifischen Fehlermeldung
# Hinweis: Der Tippfehler "Breath" ist aus deinem Originalcode übernommen.
with pytest.raises(ValueError, match="Breath of first matrix must be equivalent to the height of the second"):
matmul(a, b)
def test_multiply_by_zero_matrix():
"""Testet die Multiplikation mit einer Nullmatrix."""
a = [[1, 2, 3], [4, 5, 6]]
b_zero = [[0, 0], [0, 0], [0, 0]]
expected = [[0, 0], [0, 0]]
assert matmul(a, b_zero) == expected