1 | # -*- coding: utf-8 -*- |
---|
2 | # |
---|
3 | # Copyright (C) 2005-2007 Christopher Lenz <cmlenz@gmx.de> |
---|
4 | # Copyright (C) 2008 Matt Good <matt@matt-good.net> |
---|
5 | # Copyright (C) 2008-2010 Edgewall Software |
---|
6 | # All rights reserved. |
---|
7 | # |
---|
8 | # This software is licensed as described in the file COPYING, which |
---|
9 | # you should have received as part of this distribution. The terms |
---|
10 | # are also available at http://bitten.edgewall.org/wiki/License. |
---|
11 | |
---|
12 | from distutils import log |
---|
13 | from distutils.errors import DistutilsOptionError |
---|
14 | import os |
---|
15 | import re |
---|
16 | from StringIO import StringIO |
---|
17 | import sys |
---|
18 | import time |
---|
19 | from pkg_resources import Distribution, EntryPoint, PathMetadata, \ |
---|
20 | normalize_path, require, working_set |
---|
21 | from setuptools.command.test import test |
---|
22 | from unittest import _TextTestResult, TextTestRunner |
---|
23 | |
---|
24 | from bitten import __version__ as VERSION |
---|
25 | from bitten.util import xmlio |
---|
26 | |
---|
27 | __docformat__ = 'restructuredtext en' |
---|
28 | |
---|
29 | |
---|
30 | class XMLTestResult(_TextTestResult): |
---|
31 | |
---|
32 | def __init__(self, stream, descriptions, verbosity): |
---|
33 | _TextTestResult.__init__(self, stream, descriptions, verbosity) |
---|
34 | self.tests = [] |
---|
35 | |
---|
36 | def startTest(self, test): |
---|
37 | _TextTestResult.startTest(self, test) |
---|
38 | filename = sys.modules[test.__module__].__file__ |
---|
39 | if filename.endswith('.pyc') or filename.endswith('.pyo'): |
---|
40 | filename = filename[:-1] |
---|
41 | self.tests.append([test, filename, time.time(), None, None]) |
---|
42 | |
---|
43 | def stopTest(self, test): |
---|
44 | self.tests[-1][2] = time.time() - self.tests[-1][2] |
---|
45 | _TextTestResult.stopTest(self, test) |
---|
46 | |
---|
47 | |
---|
48 | class XMLTestRunner(TextTestRunner): |
---|
49 | |
---|
50 | def __init__(self, stream=sys.stdout, xml_stream=None): |
---|
51 | TextTestRunner.__init__(self, stream, descriptions=0, verbosity=2) |
---|
52 | self.xml_stream = xml_stream |
---|
53 | |
---|
54 | def _makeResult(self): |
---|
55 | return XMLTestResult(self.stream, self.descriptions, self.verbosity) |
---|
56 | |
---|
57 | def run(self, test): |
---|
58 | result = TextTestRunner.run(self, test) |
---|
59 | if not self.xml_stream: |
---|
60 | return result |
---|
61 | |
---|
62 | root = xmlio.Element('unittest-results') |
---|
63 | for testcase, filename, timetaken, stdout, stderr in result.tests: |
---|
64 | status = 'success' |
---|
65 | tb = None |
---|
66 | |
---|
67 | if testcase in [e[0] for e in result.errors]: |
---|
68 | status = 'error' |
---|
69 | tb = [e[1] for e in result.errors if e[0] is testcase][0] |
---|
70 | elif testcase in [f[0] for f in result.failures]: |
---|
71 | status = 'failure' |
---|
72 | tb = [f[1] for f in result.failures if f[0] is testcase][0] |
---|
73 | |
---|
74 | name = str(testcase) |
---|
75 | fixture = None |
---|
76 | description = testcase.shortDescription() or '' |
---|
77 | if description.startswith('doctest of '): |
---|
78 | name = 'doctest' |
---|
79 | fixture = description[11:] |
---|
80 | description = None |
---|
81 | else: |
---|
82 | match = re.match('(\w+)\s+\(([\w.]+)\)', name) |
---|
83 | if match: |
---|
84 | name = match.group(1) |
---|
85 | fixture = match.group(2) |
---|
86 | |
---|
87 | test_elem = xmlio.Element('test', file=filename, name=name, |
---|
88 | fixture=fixture, status=status, |
---|
89 | duration=timetaken) |
---|
90 | if description: |
---|
91 | test_elem.append(xmlio.Element('description')[description]) |
---|
92 | if stdout: |
---|
93 | test_elem.append(xmlio.Element('stdout')[stdout]) |
---|
94 | if stderr: |
---|
95 | test_elem.append(xmlio.Element('stdout')[stderr]) |
---|
96 | if tb: |
---|
97 | test_elem.append(xmlio.Element('traceback')[tb]) |
---|
98 | root.append(test_elem) |
---|
99 | |
---|
100 | root.write(self.xml_stream, newlines=True) |
---|
101 | return result |
---|
102 | |
---|
103 | |
---|
104 | class unittest(test): |
---|
105 | description = test.description + ', and optionally record code coverage' |
---|
106 | |
---|
107 | user_options = test.user_options + [ |
---|
108 | ('xml-output=', None, |
---|
109 | "Path to the XML file where test results are written to"), |
---|
110 | ('coverage-dir=', None, |
---|
111 | "Directory where coverage files are to be stored"), |
---|
112 | ('coverage-summary=', None, |
---|
113 | "Path to the file where the coverage summary should be stored"), |
---|
114 | ('coverage-method=', None, |
---|
115 | "Whether to use trace.py or coverage.py to collect code coverage. " |
---|
116 | "Valid options are 'trace' (the default) or 'coverage'.") |
---|
117 | ] |
---|
118 | |
---|
119 | def initialize_options(self): |
---|
120 | test.initialize_options(self) |
---|
121 | self.xml_output = None |
---|
122 | self.xml_output_file = None |
---|
123 | self.coverage_summary = None |
---|
124 | self.coverage_dir = None |
---|
125 | self.coverage_method = 'trace' |
---|
126 | |
---|
127 | def finalize_options(self): |
---|
128 | test.finalize_options(self) |
---|
129 | |
---|
130 | if self.xml_output is not None: |
---|
131 | output_dir = os.path.dirname(self.xml_output) or '.' |
---|
132 | if not os.path.exists(output_dir): |
---|
133 | os.makedirs(output_dir) |
---|
134 | self.xml_output_file = open(self.xml_output, 'w') |
---|
135 | |
---|
136 | if self.coverage_method not in ('trace', 'coverage', 'figleaf'): |
---|
137 | raise DistutilsOptionError('Unknown coverage method %r' % |
---|
138 | self.coverage_method) |
---|
139 | |
---|
140 | def run_tests(self): |
---|
141 | if self.coverage_summary: |
---|
142 | if self.coverage_method == 'coverage': |
---|
143 | self._run_with_coverage() |
---|
144 | elif self.coverage_method == 'figleaf': |
---|
145 | self._run_with_figleaf() |
---|
146 | else: |
---|
147 | self._run_with_trace() |
---|
148 | else: |
---|
149 | self._run_tests() |
---|
150 | |
---|
151 | def _run_with_figleaf(self): |
---|
152 | import figleaf |
---|
153 | figleaf.start() |
---|
154 | try: |
---|
155 | self._run_tests() |
---|
156 | finally: |
---|
157 | figleaf.stop() |
---|
158 | figleaf.write_coverage(self.coverage_summary) |
---|
159 | |
---|
160 | def _run_with_coverage(self): |
---|
161 | import coverage |
---|
162 | coverage.use_cache(False) |
---|
163 | coverage.start() |
---|
164 | try: |
---|
165 | self._run_tests() |
---|
166 | finally: |
---|
167 | coverage.stop() |
---|
168 | |
---|
169 | modules = [m for _, m in sys.modules.items() |
---|
170 | if m is not None and hasattr(m, '__file__') |
---|
171 | and os.path.splitext(m.__file__)[-1] in ('.py', '.pyc')] |
---|
172 | |
---|
173 | # Generate summary file |
---|
174 | buf = StringIO() |
---|
175 | coverage.report(modules, file=buf) |
---|
176 | buf.seek(0) |
---|
177 | fileobj = open(self.coverage_summary, 'w') |
---|
178 | try: |
---|
179 | filter_coverage(buf, fileobj) |
---|
180 | finally: |
---|
181 | fileobj.close() |
---|
182 | |
---|
183 | if self.coverage_dir: |
---|
184 | if not os.path.exists(self.coverage_dir): |
---|
185 | os.makedirs(self.coverage_dir) |
---|
186 | coverage.annotate(modules, directory=self.coverage_dir, |
---|
187 | ignore_errors=True) |
---|
188 | |
---|
189 | def _run_with_trace(self): |
---|
190 | from trace import Trace |
---|
191 | trace = Trace(ignoredirs=[sys.prefix, sys.exec_prefix], trace=False, |
---|
192 | count=True) |
---|
193 | try: |
---|
194 | trace.runfunc(self._run_tests) |
---|
195 | finally: |
---|
196 | results = trace.results() |
---|
197 | real_stdout = sys.stdout |
---|
198 | sys.stdout = open(self.coverage_summary, 'w') |
---|
199 | try: |
---|
200 | results.write_results(show_missing=True, summary=True, |
---|
201 | coverdir=self.coverage_dir) |
---|
202 | finally: |
---|
203 | sys.stdout.close() |
---|
204 | sys.stdout = real_stdout |
---|
205 | |
---|
206 | def _run_tests(self): |
---|
207 | old_path = sys.path[:] |
---|
208 | ei_cmd = self.get_finalized_command("egg_info") |
---|
209 | path_item = normalize_path(ei_cmd.egg_base) |
---|
210 | metadata = PathMetadata( |
---|
211 | path_item, normalize_path(ei_cmd.egg_info) |
---|
212 | ) |
---|
213 | dist = Distribution(path_item, metadata, project_name=ei_cmd.egg_name) |
---|
214 | working_set.add(dist) |
---|
215 | require(str(dist.as_requirement())) |
---|
216 | loader_ep = EntryPoint.parse("x=" + self.test_loader) |
---|
217 | loader_class = loader_ep.load(require=False) |
---|
218 | |
---|
219 | try: |
---|
220 | import unittest |
---|
221 | unittest.main( |
---|
222 | None, None, [unittest.__file__] + self.test_args, |
---|
223 | testRunner=XMLTestRunner(stream=sys.stdout, |
---|
224 | xml_stream=self.xml_output_file), |
---|
225 | testLoader=loader_class() |
---|
226 | ) |
---|
227 | except SystemExit, e: |
---|
228 | return e.code |
---|
229 | |
---|
230 | |
---|
231 | def filter_coverage(infile, outfile): |
---|
232 | for idx, line in enumerate(infile): |
---|
233 | if idx < 2 or line.startswith('--'): |
---|
234 | outfile.write(line) |
---|
235 | continue |
---|
236 | parts = line.split() |
---|
237 | name = parts[0] |
---|
238 | if name == 'TOTAL': |
---|
239 | continue |
---|
240 | if name not in sys.modules: |
---|
241 | outfile.write(line) |
---|
242 | continue |
---|
243 | filename = os.path.normpath(sys.modules[name].__file__) |
---|
244 | if filename.endswith('.pyc') or filename.endswith('.pyo'): |
---|
245 | filename = filename[:-1] |
---|
246 | outfile.write(line.rstrip() + ' ' + filename + '\n') |
---|
247 | |
---|
248 | |
---|
249 | def main(): |
---|
250 | from distutils.dist import Distribution |
---|
251 | from optparse import OptionParser |
---|
252 | |
---|
253 | parser = OptionParser(usage='usage: %prog [options] test_suite ...', |
---|
254 | version='%%prog %s' % VERSION) |
---|
255 | parser.add_option('-o', '--xml-output', action='store', dest='xml_output', |
---|
256 | metavar='FILE', help='write XML test results to FILE') |
---|
257 | parser.add_option('-d', '--coverage-dir', action='store', |
---|
258 | dest='coverage_dir', metavar='DIR', |
---|
259 | help='store coverage results in DIR') |
---|
260 | parser.add_option('-s', '--coverage-summary', action='store', |
---|
261 | dest='coverage_summary', metavar='FILE', |
---|
262 | help='write coverage summary to FILE') |
---|
263 | options, args = parser.parse_args() |
---|
264 | if len(args) < 1: |
---|
265 | parser.error('incorrect number of arguments') |
---|
266 | |
---|
267 | cmd = unittest(Distribution()) |
---|
268 | cmd.initialize_options() |
---|
269 | cmd.test_suite = args[0] |
---|
270 | if hasattr(options, 'xml_output'): |
---|
271 | cmd.xml_output = options.xml_output |
---|
272 | if hasattr(options, 'coverage_summary'): |
---|
273 | cmd.coverage_summary = options.coverage_summary |
---|
274 | if hasattr(options, 'coverage_dir'): |
---|
275 | cmd.coverage_dir = options.coverage_dir |
---|
276 | cmd.finalize_options() |
---|
277 | cmd.run() |
---|
278 | |
---|
279 | if __name__ == '__main__': |
---|
280 | main() |
---|