#!/bin/sh
set -eu
cp wrappers/python/test.py "$AUTOPKGTEST_TMP/upstream_test.py"
cd "$AUTOPKGTEST_TMP"
interpreters=$(py3versions -d)
test -n "$interpreters"
for py in $interpreters; do
    echo "Testing installed binding with $py:"
    "$py" -I - <<'PY'
import importlib.machinery
import importlib.util
from pathlib import Path
import unittest

# Import required image adapters explicitly so upstream's skipIf checks cannot
# silently omit the NumPy, Pillow or OpenCV coverage.
import numpy
import PIL.Image
import cv2
import zxingcpp
import zxingcpp.zxingcpp as native

installed_dir = Path('/usr/lib/python3/dist-packages')
for module in (zxingcpp, native):
    origin = Path(module.__file__).resolve()
    assert origin.is_relative_to(installed_dir), origin
    print(f'{module.__name__}: {origin}', flush=True)
assert str(native.__file__).endswith(tuple(importlib.machinery.EXTENSION_SUFFIXES))
print(f'NumPy {numpy.__version__}; Pillow {PIL.__version__}; OpenCV {cv2.__version__}', flush=True)

spec = importlib.util.spec_from_file_location('upstream_test', 'upstream_test.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
suite = unittest.defaultTestLoader.loadTestsFromModule(module)
assert suite.countTestCases() > 0
result = unittest.TextTestRunner(verbosity=2).run(suite)
if not result.wasSuccessful() or result.skipped:
    raise SystemExit(1)
PY
done
