Skip to content

Commit

Permalink
Make tests more idiomatic for pytest
Browse files Browse the repository at this point in the history
We don't need to put tests in a class anymore. I also
sprinkled some type hints here and there. Left a few because
the commit would be too big otherwise.
  • Loading branch information
WyattBlue committed Sep 24, 2024
1 parent 3c0f496 commit d1a21b5
Show file tree
Hide file tree
Showing 18 changed files with 1,723 additions and 1,719 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ fate-suite:
rsync -vrltLW rsync://fate-suite.ffmpeg.org/fate-suite/ tests/assets/fate-suite/

lint:
$(PIP) install -U black isort flake8 flake8-pyproject pillow numpy mypy==1.11.2
$(PIP) install -U black isort flake8 flake8-pyproject pillow numpy mypy==1.11.2 pytest
black --check av examples tests setup.py
flake8 av
isort --check-only --diff av examples tests
Expand Down
82 changes: 26 additions & 56 deletions tests/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import types
from unittest import TestCase as _Base

import numpy as np

from av.datasets import fate as fate_suite

try:
Expand Down Expand Up @@ -55,7 +57,7 @@ def asset(*args: str) -> str:
os.environ["PYAV_TESTDATA_DIR"] = asset()


def fate_png():
def fate_png() -> str:
return fate_suite("png1/55c99e750a5fd6_50314226.png")


Expand Down Expand Up @@ -85,33 +87,32 @@ def _inner(self, *args, **kwargs):
return _inner


class MethodLogger:
def __init__(self, obj):
self._obj = obj
self._log = []
def assertNdarraysEqual(a: np.ndarray, b: np.ndarray) -> None:
assert a.shape == b.shape

comparison = a == b
if not comparison.all():
it = np.nditer(comparison, flags=["multi_index"])
msg = ""
for equal in it:
if not equal:
msg += "- arrays differ at index {}; {} {}\n".format(
it.multi_index,
a[it.multi_index],
b[it.multi_index],
)
assert False, f"ndarrays contents differ\n{msg}"

def __getattr__(self, name):
value = getattr(self._obj, name)
if isinstance(
value,
(
types.MethodType,
types.FunctionType,
types.BuiltinFunctionType,
types.BuiltinMethodType,
),
):
return functools.partial(self._method, name, value)
else:
self._log.append(("__getattr__", (name,), {}))
return value

def _method(self, name, meth, *args, **kwargs):
self._log.append((name, args, kwargs))
return meth(*args, **kwargs)
def assertImagesAlmostEqual(a, b, epsilon=0.1):
import PIL.ImageFilter as ImageFilter

def _filter(self, type_):
return [log for log in self._log if log[0] == type_]
assert a.size == b.size
a = a.filter(ImageFilter.BLUR).getdata()
b = b.filter(ImageFilter.BLUR).getdata()
for i, ax, bx in zip(range(len(a)), a, b):
diff = sum(abs(ac / 256 - bc / 256) for ac, bc in zip(ax, bx)) / 3
assert diff < epsilon, f"images differed by {diff} at index {i}; {ax} {bx}"


class TestCase(_Base):
Expand All @@ -129,34 +130,3 @@ def sandboxed(self, *args, **kwargs) -> str:
kwargs.setdefault("sandbox", self.sandbox)
kwargs.setdefault("timed", True)
return sandboxed(*args, **kwargs)

def assertNdarraysEqual(self, a, b):
import numpy

self.assertEqual(a.shape, b.shape)

comparison = a == b
if not comparison.all():
it = numpy.nditer(comparison, flags=["multi_index"])
msg = ""
for equal in it:
if not equal:
msg += "- arrays differ at index %s; %s %s\n" % (
it.multi_index,
a[it.multi_index],
b[it.multi_index],
)
self.fail("ndarrays contents differ\n%s" % msg)

def assertImagesAlmostEqual(self, a, b, epsilon=0.1, *args):
import PIL.ImageFilter as ImageFilter

self.assertEqual(a.size, b.size, "sizes dont match")
a = a.filter(ImageFilter.BLUR).getdata()
b = b.filter(ImageFilter.BLUR).getdata()
for i, ax, bx in zip(range(len(a)), a, b):
diff = sum(abs(ac / 256 - bc / 256) for ac, bc in zip(ax, bx)) / 3
if diff > epsilon:
self.fail(
"images differed by %s at index %d; %s %s" % (diff, i, ax, bx)
)
47 changes: 24 additions & 23 deletions tests/test_audioformat.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,28 @@
import sys

import pytest

from av import AudioFormat

from .common import TestCase

postfix = "le" if sys.byteorder == "little" else "be"


class TestAudioFormats(TestCase):
def test_s16_inspection(self) -> None:
fmt = AudioFormat("s16")
assert fmt.name == "s16"
assert not fmt.is_planar
assert fmt.bits == 16
assert fmt.bytes == 2
assert fmt.container_name == "s16" + postfix
assert fmt.planar.name == "s16p"
assert fmt.packed is fmt

def test_s32p_inspection(self) -> None:
fmt = AudioFormat("s32p")
assert fmt.name == "s32p"
assert fmt.is_planar
assert fmt.bits == 32
assert fmt.bytes == 4
self.assertRaises(ValueError, lambda: fmt.container_name)

def test_s16_inspection() -> None:
fmt = AudioFormat("s16")
postfix = "le" if sys.byteorder == "little" else "be"

assert fmt.name == "s16"
assert not fmt.is_planar
assert fmt.bits == 16
assert fmt.bytes == 2
assert fmt.container_name == "s16" + postfix
assert fmt.planar.name == "s16p"
assert fmt.packed is fmt


def test_s32p_inspection() -> None:
fmt = AudioFormat("s32p")
assert fmt.name == "s32p"
assert fmt.is_planar
assert fmt.bits == 32
assert fmt.bytes == 4

pytest.raises(ValueError, lambda: fmt.container_name)
Loading

0 comments on commit d1a21b5

Please sign in to comment.