#!/usr/bin/python3
"""Exercise the built or installed package, including its bundled resources."""

import contextlib
import io
import os
import tempfile
from pathlib import Path

os.environ["MPLBACKEND"] = "Agg"

# Keep Matplotlib's font cache writable in headless build/test environments.
with tempfile.TemporaryDirectory(prefix="logomaker-test-") as temporary:
    os.environ["MPLCONFIGDIR"] = temporary

    import matplotlib.pyplot as plt
    import numpy as np
    import logomaker
    from logomaker.tests import functional_tests_logomaker as tests

    print(f"Testing {logomaker.__file__}")
    np.random.seed(0)
    logomaker.run_tests()
    assert tests.global_success_counter > 0
    assert tests.global_fail_counter == 0

    # These resources must be present in the binary package, not just the
    # source tree. Reading each file also exercises compressed datasets.
    for name in logomaker.list_example_matrices():
        matrix = logomaker.get_example_matrix(name, print_description=False)
        assert not matrix.empty, name
    for name in logomaker.list_example_datafiles():
        with logomaker.open_example_datafile(name, print_description=False) as data:
            assert data.read(1), name

    # Upstream's suite does not run the demos. Render every documented demo
    # and save vector output to check the complete plotting path.
    for name in ("fig1b", "fig1c", "fig1d", "fig1e", "fig1f", "logo"):
        with contextlib.redirect_stdout(io.StringIO()):
            figure = logomaker.demo(name)
        output = Path(temporary) / f"{name}.svg"
        figure.savefig(output)
        assert "<svg" in output.read_text(), name
        plt.close("all")

    print(f"Passed {tests.global_success_counter} upstream checks and all resource/demo checks")
