#!/usr/bin/python
#
# A simple test runner that runs all of thee example files shipped with PyX.
# Requires Ghostscript and ImageMagick.
# Note that test output should not be present prior to running the tests

from __future__ import print_function

import os.path
import shutil
import sys
import os

gs_args = ['-r400', '-dQUIET', '-dEPSCrop', '-dNOPAUSE', '-dBATCH', '-sDEVICE=ppmraw']

def run_test(interp, filename):
    """Execute the example code and return the output filename."""
    base, ext = os.path.splitext(filename)
    base = os.path.basename(base)

    print(base, end=': ')

    name = {}
    for ft in ('eps', 'ppm', 'png'):
        name[ft] = "%s-%s.%s" % (base, interp, ft)

    if os.spawnlpe(os.P_WAIT, interp, interp, filename, new_env):
        print(interp + " FAILED")
        return

    if not os.path.exists(base + '.eps'):
        print("no EPS file")
        return
    else:
        os.rename(base + '.eps', name['eps'])

    gs_cmd = ['gs'] + gs_args + ['-sOutputFile=' + name['ppm'], name['eps']]
    if os.spawnvp(os.P_WAIT, 'gs', gs_cmd):
        print("gs FAILED")
        return
    os.unlink(name['eps'])

    convert_cmd = ['convert', '-resize', '25%', name['ppm'], name['png']]
    if os.spawnvp(os.P_WAIT, 'convert', convert_cmd):
        print("convert FAILED")
        return
    os.unlink(name['ppm'])

    print("ok")
    return name['png']

# Are we in the correct directory?
if not os.path.exists("examples"):
    print("must be in the toplevel directory of the PyX source")
    sys.exit(1)

# Set $PYTHONPATH so that we point to the correct location of the module.
new_env = os.environ.copy()
if "SYS_PYX" not in os.environ:
    new_env["PYTHONPATH"] = os.getcwd()

# Build a list of files to test.
def get_files(dir):
    r = []
    for (dirpath, dirnames, filenames) in os.walk(dir):
        if ".svn" in dirnames:
            dirnames.remove(".svn")
        for filename in filenames:
            full = os.path.join(dirpath, filename)
            full = os.path.abspath(full)

            if filename.endswith(".py"):
                r.append(full)
            elif filename.endswith(".dat") or filename.endswith(".jpg"):
                # The .dat and .jpg files are used by some of
                # the examples.
                shutil.copy(full, "output")
    return r

files = get_files("examples")

tests = 0
failed = 0

for f in files:
    tests += 1
    os.chdir(os.path.dirname(f))
    if not run_test("python", f):
        failed += 1

print(tests, "tests,", failed, "FAILED")

if failed:
    sys.exit(1)
