Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 76 additions & 4 deletions tests/base/test_data.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,28 @@
import json
import os
import tempfile
import unittest
from pathlib import Path

import numpy as np
import numpy.testing as nt

from machinevisiontoolbox import iwrite, mvtb_path_to_datafile
from machinevisiontoolbox.base.data import mvtb_load_jsonfile, mvtb_load_matfile

# test mvtb_path_to_datafile() which is used by a number of other functions
# to locate files in the MVTB data package


class TestDataFiles(unittest.TestCase):

def test_datafile_local(self):

# test for exception if file not found
# test that exception raised if not present
with self.assertRaises(ValueError):
mvtb_path_to_datafile("notthere.png")

# create a local test image file
im = iwrite(np.zeros((5, 5)), "./test-image.png")
iwrite(np.zeros((5, 5)), "./test-image.png")
path = mvtb_path_to_datafile("./test-image.png")
self.assertTrue(os.path.isfile(path))
# remove the test image file
Expand All @@ -48,7 +49,78 @@ def tearDown(self):
pass


class TestDataLoaders(unittest.TestCase):
"""Read real data files with mvtb_load_matfile() and mvtb_load_jsonfile()."""

def test_matfile_in_mvtbdata(self):
# bunny.mat is in the mvtbdata package, and holds one array
data = mvtb_load_matfile("data/bunny.mat")
self.assertIsInstance(data["bunny"], np.ndarray)
self.assertEqual(data["bunny"].ndim, 2)

def test_matfile_missing_raises(self):
with self.assertRaises(ValueError):
mvtb_load_matfile("data/__not_there__.mat")

def test_matfile_struct_becomes_namedtuple(self):
from scipy.io import savemat

with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, "s.mat")
savemat(path, {"s": {"a": 1.5, "b": np.arange(3)}, "x": np.eye(2)})
data = mvtb_load_matfile(path)

# a MATLAB struct is returned as a namedtuple, so its fields are attributes
self.assertEqual(data["s"].a, 1.5)
nt.assert_array_equal(data["s"].b, [0, 1, 2])
nt.assert_array_equal(data["x"], np.eye(2))

def test_jsonfile(self):
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, "d.json")
with open(path, "w") as f:
json.dump({"name": "cube", "n": [1, 2, 3]}, f)
data = mvtb_load_jsonfile(path)

self.assertEqual(data, {"name": "cube", "n": [1, 2, 3]})

def test_jsonfile_missing_raises(self):
with self.assertRaises(ValueError):
mvtb_load_jsonfile("__not_there__.json")


class TestDataPaths(unittest.TestCase):
def test_absolute_path(self):
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "f.dat"
path.write_text("x")
self.assertEqual(mvtb_path_to_datafile(path), path.resolve())
self.assertEqual(
mvtb_path_to_datafile(path, string=True), str(path.resolve())
)

# an absolute path that does not exist is an error, with no search of mvtbdata
with self.assertRaises(ValueError):
mvtb_path_to_datafile(Path(tmp) / "gone.dat")

def test_string_result(self):
path = mvtb_path_to_datafile("data", "bunny.ply", string=True)
self.assertIsInstance(path, str)
self.assertTrue(os.path.isfile(path))

def test_local_file_string_result(self):
with tempfile.TemporaryDirectory() as tmp:
cwd = os.getcwd()
os.chdir(tmp)
try:
Path("local.dat").write_text("x")
path = mvtb_path_to_datafile("local.dat", string=True)
self.assertIsInstance(path, str)
self.assertTrue(path.endswith("local.dat"))
finally:
os.chdir(cwd)


# ------------------------------------------------------------------------ #
if __name__ == "__main__":

unittest.main()
36 changes: 1 addition & 35 deletions tests/base/test_meshgrid.py
Original file line number Diff line number Diff line change
@@ -1,43 +1,9 @@
import sys
import unittest
from pathlib import Path

import numpy as np
import numpy.testing as nt

# Load meshgrid module directly without importing the whole package
meshgrid_file = (
Path(__file__).parent.parent.parent
/ "src"
/ "machinevisiontoolbox"
/ "base"
/ "meshgrid.py"
)


def load_meshgrid_module():
"""Load meshgrid module by reading and executing its source code."""
with open(meshgrid_file, "r") as f:
source_code = f.read()

# Create a namespace with numpy imported as np
namespace = {
"__file__": str(meshgrid_file),
"__name__": "meshgrid_module",
"np": np,
}

try:
exec(source_code, namespace)
except Exception as e: # noqa: BLE001 - whatever goes wrong, report it as a failure to load
raise ImportError(f"Failed to load meshgrid module: {e}") from e

return namespace


mesh_namespace = load_meshgrid_module()
meshgrid = mesh_namespace["meshgrid"]
spherical_rotate = mesh_namespace["spherical_rotate"]
from machinevisiontoolbox.base.meshgrid import meshgrid, spherical_rotate

try:
from spatialmath.pose3d import SO3
Expand Down
41 changes: 41 additions & 0 deletions tests/base/test_version.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#!/usr/bin/env python
import unittest
from contextlib import redirect_stdout
from io import StringIO

import cv2
import numpy as np
import spatialmath as sm

import machinevisiontoolbox as mvt
from machinevisiontoolbox.base.version import mvtb_version


class TestVersion(unittest.TestCase):
def test_mvtb_version_reports_versions(self):
stream = StringIO()
with redirect_stdout(stream):
mvtb_version()
text = stream.getvalue()

# one line for each package, each with the version that is installed
self.assertIn(
f"Machine Vision Toolbox for Python: version {mvt.__version__}", text
)
self.assertIn(sm.__version__, text)
self.assertIn(np.__version__, text)
self.assertIn(cv2.__version__, text)

def test_mvtb_version_includes_opencv_build_information(self):
stream = StringIO()
with redirect_stdout(stream):
mvtb_version()
text = stream.getvalue()

self.assertIn("OpenCV build information:", text)
# the build information is indented as a quotation
self.assertIn("> General configuration for OpenCV", text)


if __name__ == "__main__":
unittest.main()
Loading