~ubuntu-branches/ubuntu/precise/checkbox/precise

« back to all changes in this revision

Viewing changes to test

  • Committer: Bazaar Package Importer
  • Author(s): Marc Tardif
  • Date: 2009-01-20 16:46:15 UTC
  • Revision ID: james.westby@ubuntu.com-20090120164615-7iz6nmlef41h4vx2
Tags: 0.4
* Setup bzr-builddeb in native mode.
* Removed LGPL notice from the copyright file.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python
 
2
#
 
3
# Copyright (c) 2008 Canonical
 
4
#
 
5
# Written by Marc Tardif <marc@interunion.ca>
 
6
#
 
7
# This file is part of Checkbox.
 
8
#
 
9
# Checkbox is free software: you can redistribute it and/or modify
 
10
# it under the terms of the GNU General Public License as published by
 
11
# the Free Software Foundation, either version 3 of the License, or
 
12
# (at your option) any later version.
 
13
#
 
14
# Checkbox is distributed in the hope that it will be useful,
 
15
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
16
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
17
# GNU General Public License for more details.
 
18
#
 
19
# You should have received a copy of the GNU General Public License
 
20
# along with Checkbox.  If not, see <http://www.gnu.org/licenses/>.
 
21
#
 
22
import optparse
 
23
 
 
24
import os
 
25
import sys
 
26
import posixpath
 
27
 
 
28
lib_dir = posixpath.abspath(posixpath.dirname(__file__))
 
29
sys.path.insert(0, lib_dir)
 
30
 
 
31
 
 
32
def find_tests(testpaths=()):
 
33
    """Find all test paths, or test paths contained in the provided sequence.
 
34
 
 
35
    @param testpaths: If provided, only tests in the given sequence will
 
36
                      be considered.  If not provided, all tests are
 
37
                      considered.
 
38
    @return: (unittests, doctests) tuple, with lists of unittests and
 
39
             doctests found, respectively.
 
40
    """
 
41
    topdir = posixpath.abspath(posixpath.dirname(__file__))
 
42
    testpaths = set(testpaths)
 
43
    unittests = []
 
44
    doctests = []
 
45
    for root, dirnames, filenames in os.walk(topdir):
 
46
        for filename in filenames:
 
47
            filepath = posixpath.join(root, filename)
 
48
            relpath = filepath[len(topdir)+1:]
 
49
 
 
50
            if (filename == "__init__.py"
 
51
               or filename.endswith(".pyc")
 
52
               or "/tests/" not in relpath):
 
53
                # Skip non-tests.
 
54
                continue
 
55
 
 
56
            if testpaths:
 
57
                # Skip any tests not in testpaths.
 
58
                for testpath in testpaths:
 
59
                    if relpath.startswith(testpath):
 
60
                        break
 
61
                else:
 
62
                    continue
 
63
 
 
64
            if filename.endswith(".py"):
 
65
                unittests.append(relpath)
 
66
            elif filename.endswith(".txt"):
 
67
                doctests.append(relpath)
 
68
 
 
69
    return unittests, doctests
 
70
 
 
71
def parse_sys_argv():
 
72
    """Extract any arguments not starting with '-' from sys.argv."""
 
73
    testpaths = []
 
74
    for i in range(len(sys.argv)-1,0,-1):
 
75
        arg = sys.argv[i]
 
76
        if not arg.startswith("-"):
 
77
            testpaths.append(arg)
 
78
            del sys.argv[i]
 
79
    return testpaths
 
80
 
 
81
def test_with_subunit(options):
 
82
    import unittest
 
83
    import subunit
 
84
 
 
85
    runner = unittest.TextTestRunner()
 
86
    if options.verbose:
 
87
        runner.verbosity = 2
 
88
 
 
89
    result = subunit.IsolatedTestSuite()
 
90
    loader = unittest.TestLoader()
 
91
    unittests, doctests = find_tests(options.args)
 
92
 
 
93
    if unittests:
 
94
        for relpath in unittests:
 
95
            modpath = relpath.replace('/', '.')[:-3]
 
96
            module = __import__(modpath, None, None, [""])
 
97
            tests = loader.loadTestsFromModule(module)
 
98
            result.addTests(tests)
 
99
 
 
100
        runner.run(result)
 
101
 
 
102
    return 0
 
103
 
 
104
def test_with_unittest(options):
 
105
    import unittest
 
106
    import doctest
 
107
 
 
108
    runner = unittest.TextTestRunner()
 
109
    if options.verbose:
 
110
        runner.verbosity = 2
 
111
 
 
112
    loader = unittest.TestLoader()
 
113
    unittests, doctests = find_tests(options.args)
 
114
 
 
115
    class Summary:
 
116
        def __init__(self):
 
117
            self.total_failures = 0
 
118
            self.total_errors = 0
 
119
            self.total_tests = 0
 
120
        def __call__(self, tests, failures, errors):
 
121
            self.total_tests += tests
 
122
            self.total_failures += failures
 
123
            self.total_errors += errors
 
124
            print "(tests=%d, failures=%d, errors=%d)" % \
 
125
                  (tests, failures, errors)
 
126
 
 
127
    unittest_summary = Summary()
 
128
    doctest_summary = Summary()
 
129
 
 
130
    if unittests:
 
131
        print "Running unittests..."
 
132
        for relpath in unittests:
 
133
            print "[%s]" % relpath
 
134
            modpath = relpath.replace('/', '.')[:-3]
 
135
            module = __import__(modpath, None, None, [""])
 
136
            test = loader.loadTestsFromModule(module)
 
137
            result = runner.run(test)
 
138
            unittest_summary(test.countTestCases(),
 
139
                             len(result.failures), len(result.errors))
 
140
            print
 
141
 
 
142
    if doctests:
 
143
        print "Running doctests..."
 
144
        doctest_flags = doctest.ELLIPSIS
 
145
        for relpath in doctests:
 
146
            print "[%s]" % relpath
 
147
            failures, total = doctest.testfile(relpath,
 
148
                                               optionflags=doctest_flags)
 
149
            doctest_summary(total, failures, 0)
 
150
            print
 
151
 
 
152
    print "Total test cases: %d" % unittest_summary.total_tests
 
153
    print "Total doctests: %d" % doctest_summary.total_tests
 
154
    print "Total failures: %d" % (unittest_summary.total_failures +
 
155
                                  doctest_summary.total_failures)
 
156
    print "Total errors: %d" % (unittest_summary.total_errors +
 
157
                                doctest_summary.total_errors)
 
158
 
 
159
    failed = bool(unittest_summary.total_failures or
 
160
                  unittest_summary.total_errors or
 
161
                  doctest_summary.total_failures or
 
162
                  doctest_summary.total_errors)
 
163
 
 
164
    return failed
 
165
 
 
166
if __name__ == "__main__":
 
167
    usage = "test [options] [<test filename>, ...]"
 
168
 
 
169
    parser = optparse.OptionParser(usage=usage)
 
170
    parser.add_option('--verbose', action='store_true')
 
171
    opts, args = parser.parse_args()
 
172
    opts.args = args
 
173
 
 
174
    runner = os.environ.get("CHECKBOX_TEST_RUNNER", "unittest")
 
175
    runner_func = globals().get("test_with_%s" % runner.replace(".", "_"))
 
176
    if not runner_func:
 
177
        sys.exit("Test runner not found: %s" % runner)
 
178
 
 
179
    sys.exit(runner_func(opts))
 
180
 
 
181
# vim:ts=4:sw=4:et