summaryrefslogtreecommitdiff
path: root/src/zope/tal/runtest.py
blob: df9d1c76fe9b85d59d6fd96e5c100b9ad7dfe7a2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
#! /usr/bin/env python
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Driver program to run METAL and TAL regression tests:
compares interpeted test files with expected output files in a sibling
directory.
"""

from __future__ import print_function

import glob
import os
import sys
import traceback
import difflib
import copy
import optparse

try:
    # Python 2.x
    from cStringIO import StringIO
except ImportError:
    # Python 3.x
    from io import StringIO

import zope.tal.driver
import zope.tal.tests.utils


def showdiff(a, b, out):
    print(''.join(difflib.ndiff(a, b)), file=out)


def main(argv=None, out=sys.stdout):
    parser = optparse.OptionParser('usage: %prog [options] [testfile ...]',
                                   description=__doc__)
    parser.add_option('-q', '--quiet', action='store_true',
                      help="less verbose output")
    internal_options = optparse.OptionGroup(parser, 'Internal options')
    internal_options.add_option(
        '-Q',
        '--very-quiet',
        action='store_true',
        dest='unittesting',
        help="no output on success, only diff/traceback on failure")
    internal_options.add_option('-N', '--normalize-newlines',
                                action='store_true', dest='normalize_newlines',
                                help="ignore differences between CRLF and LF")
    parser.add_option_group(internal_options)
    driver_options = optparse.OptionGroup(
        parser,
        'Driver options',
        "(for debugging only; supplying these *will* cause test failures)")
    for option in zope.tal.driver.OPTIONS:
        driver_options.add_option(option)
    parser.add_option_group(driver_options)
    opts, args = parser.parse_args(argv)

    if not args:
        here = os.path.dirname(__file__)
        prefix = os.path.join(here, "tests", "input", "test*.")
        if zope.tal.tests.utils.skipxml:
            xmlargs = []
        else:
            xmlargs = sorted(glob.glob(prefix + "xml"))
        htmlargs = sorted(glob.glob(prefix + "html"))
        args = xmlargs + htmlargs
        if not args:
            sys.stderr.write("No tests found -- please supply filenames\n")
            sys.exit(1)
    errors = 0
    for arg in args:
        locopts = []
        if "metal" in arg and not opts.macro_only:
            locopts.append("-m")
        if "_sa" in arg and not opts.annotate:
            locopts.append("-a")
        if not opts.unittesting:
            print(arg, end=' ', file=out)
            sys.stdout.flush()
        if zope.tal.tests.utils.skipxml and arg.endswith(".xml"):
            print("SKIPPED (XML parser not available)", file=out)
            continue
        save = sys.stdout, sys.argv
        try:
            try:
                sys.stdout = stdout = StringIO()
                sys.argv = ["driver.py"] + locopts + [arg]
                zope.tal.driver.main(copy.copy(opts))
            finally:
                sys.stdout, sys.argv = save
        except SystemExit:
            raise
        except BaseException:
            errors = 1
            if opts.quiet:
                print(sys.exc_info()[0].__name__, file=out)
                sys.stdout.flush()
            else:
                if opts.unittesting:
                    print('', file=out)
                else:
                    print("Failed:", file=out)
                    sys.stdout.flush()
                traceback.print_exc()
            continue
        head, tail = os.path.split(arg)
        outfile = os.path.join(
            head.replace("input", "output"),
            tail)
        try:
            f = open(outfile)
        except IOError:
            expected = None
            print("(missing file %s)" % outfile, end=' ', file=out)
        else:
            expected = f.readlines()
            f.close()
        stdout.seek(0)
        if hasattr(stdout, "readlines"):
            actual = stdout.readlines()
        else:
            actual = readlines(stdout)
        if opts.normalize_newlines or "_sa" in arg or arg.endswith('.xml'):
            # EOL normalization makes the tests pass:
            # - XML files, on Windows, have \r\n line endings.  Because
            #   expat insists on byte streams on Python 3, we end up with
            #   those \r\n's going through the entire TAL engine and
            #   showing up in the actual output.  Expected output, on the
            #   other hand, has just \n's, since we read the file as text.
            # - Source annotation tests: when a developer converts all the
            #   input and output files to \r\n line endings and runs
            #   tests on Linux (because they're trying to debug Windows
            #   problems but can't be forced to use an inferior OS), we
            #   also have \r\n's going through the TAL engine and showing
            #   up both in actual and expected lists.  Except for source
            #   annotation lines added by TAL, which always use just \n.
            actual = [line.replace('\r\n', '\n') for line in actual]
            if expected is not None:
                expected = [line.replace('\r\n', '\n') for line in expected]
        if actual == expected:
            if not opts.unittesting:
                print("OK", file=out)
        else:
            if opts.unittesting:
                print('', file=out)
            else:
                print("not OK", file=out)
            errors = 1
            if not opts.quiet and expected is not None:
                showdiff(expected, actual, out)
    if errors:
        if opts.unittesting:
            return 1
        else:
            sys.exit(1)


def readlines(f):
    L = []
    while True:
        line = f.readline()
        if not line:
            break
        L.append(line)
    return L


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))