Debian Codegraph @

docs/conftest.py

raw symbols SCIP
1 # coding=utf-8
2 """
3 This module scans all ``*.rst`` files below ``docs/`` for example code. Example
4 code is discoved by checking for lines containing the ``.. literalinclude:: ``
5 directives.
6
7 An example consists of two consecutive literalinclude directives. The first
8 must include a ``*.py`` file and the second a ``*.out`` file. The ``*.py`` file
9 consists of the example code which is executed in a separate process. The
10 output of this process is compared to the contents of the ``*.out`` file.
11
12 """
13 import os.path
14 import subprocess
15 import errno
16 import random
17
18 import pytest
19 from py._code.code import TerminalRepr
20 from _pytest.assertion.util import _diff_text
21
22
23 blacklist = ['SimRTManual.rst']
24 """A list of strings with rst-files to skip."""
25
26
27 def pytest_collect_file(path, parent):
28 """Checks if the file is a rst file and creates an :class:`ExampleFile`
29 instance."""
30 if path.ext != '.rst':
31 return
32 for item in blacklist:
33 if str(path).endswith(item):
34 return
35 return ExampleFile(path, parent)
36
37
38 class ExampleFile(pytest.File):
39 """Collects all examples contained in a rst-file."""
40
41 def collect(self):
42 # Collect all literal includes.
43 literalincludes = []
44 with self.fspath.open() as data:
45 for lineno, line in enumerate(data):
46 if 'literalinclude' not in line:
47 continue
48 filename = line.split('::')[-1].strip()
49 filepath = os.path.join(self.fspath.dirname, filename)
50 literalincludes.append((lineno, filepath))
51
52 # Check for directly following output specification.
53 for idx in range(len(literalincludes) - 1):
54 example_lineno, example = literalincludes[idx]
55 output_lineno, output = literalincludes[idx + 1]
56 if not example.endswith('.py'):
57 continue
58 if not output.endswith('.out'):
59 continue
60 yield ExampleItem(output_lineno, example, output, self)
61
62
63 class ExampleItem(pytest.Item):
64 """Executes an example found in a rst-file."""
65
66 def __init__(self, lineno, example, output, parent):
67 pytest.Item.__init__(self, example, parent)
68 self.lineno = lineno
69 self.example = example
70 self.output = output
71 self.examplefile = os.path.join(self.fspath.dirname, self.example)
72 self.outputfile = os.path.join(self.fspath.dirname, self.output)
73
74 def runtest(self):
75 # Skip if random.expovariate with the old implementation is used.
76 with open(self.examplefile) as f:
77 src = f.read()
78 if 'expovariate' in src:
79 random.seed(0)
80 if int(random.expovariate(0.2)) == 0:
81 pytest.skip('Old exovariate implementation.')
82
83 # Read expected output.
84 with open(self.outputfile) as f:
85 expected = f.read()
86
87 # Execute the example.
88 if not hasattr(subprocess, 'check_output'): # The case on Python 2.6
89 pytest.skip('subprocess has no check_output() method.')
90
91 output = subprocess.check_output(['python', self.examplefile],
92 stderr=subprocess.STDOUT)
93
94 if isinstance(output, bytes): # The case on Python 3
95 output = output.decode('utf8')
96
97 if output != expected:
98 # Hijack the ValueError exception to identify mismatching output.
99 raise ValueError(expected, output)
100
101 def repr_failure(self, exc_info):
102 if exc_info.errisinstance((ValueError,)):
103 # Output is mismatching. Create a nice diff as failure description.
104 expected, output = exc_info.value.args
105
106 message = _diff_text(expected, output)
107 return ReprFailExample(self.fspath.basename, self.lineno,
108 self.outputfile, message)
109 elif exc_info.errisinstance((IOError,)):
110 # Something wrent wrong causing an IOError.
111 if exc_info.value.errno != errno.ENOENT:
112 # This isn't a file not found error so bail out and report the
113 # error in detail.
114 return pytest.Item.repr_failure(self, exc_info)
115 # Otherwise provide a concise error description.
116 return ReprFileNotFoundExample(self.fspath.basename, self.lineno,
117 self.examplefile, exc_info)
118 elif exc_info.errisinstance((subprocess.CalledProcessError,)):
119 # Something wrent wrong while executing the example. Provide a
120 # concise error description.
121 return ReprErrorExample(self.fspath.basename, self.lineno,
122 self.examplefile, exc_info)
123 else:
124 # Something went terribly wrong :(
125 return pytest.Item.repr_failure(self, exc_info)
126
127 def reportinfo(self):
128 """Returns a description of the example."""
129 return self.fspath, None, '[example %s]' % (
130 os.path.relpath(self.examplefile))
131
132
133 class ReprFailExample(TerminalRepr):
134 """Reports output mismatches in a nice and informative representation."""
135
136 Markup = {
137 '+': dict(green=True),
138 '-': dict(red=True),
139 '?': dict(bold=True),
140 }
141 """Colorize codes for the diff markup."""
142
143 def __init__(self, filename, lineno, outputfile, message):
144 self.filename = filename
145 self.lineno = lineno
146 self.outputfile = outputfile
147 self.message = message
148
149 def toterminal(self, tw):
150 for line in self.message:
151 markup = ReprFailExample.Markup.get(line[0], {})
152 tw.line(line, **markup)
153 tw.line('%s:%d (in %s): Unexpected output' % (self.filename,
154 self.lineno, os.path.relpath(self.outputfile)))
155
156
157 class ReprErrorExample(TerminalRepr):
158 """Reports failures in the execution of an example."""
159
160 def __init__(self, filename, lineno, examplefile, exc_info):
161 self.filename = filename
162 self.lineno = lineno
163 self.examplefile = examplefile
164 self.exc_info = exc_info
165
166 def toterminal(self, tw):
167 tw.line('Execution failed! Captured output:', bold=True)
168 tw.sep('-')
169 tw.line(self.exc_info.value.output, red=True, bold=True)
170 tw.line('%s:%d (%s) Example failed (exitcode=%d)' % (self.filename,
171 self.lineno, os.path.relpath(self.examplefile),
172 self.exc_info.value.returncode))
173
174
175 class ReprFileNotFoundExample(TerminalRepr):
176 """Reports concise error information in the case of a file not found."""
177
178 def __init__(self, filename, lineno, examplefile, exc_info):
179 self.filename = filename
180 self.lineno = lineno
181 self.examplefile = examplefile
182 self.exc_info = exc_info
183
184 def toterminal(self, tw):
185 tw.line(self.exc_info.value, red=True, bold=True)
186 tw.line('%s:%d (%s) Example failed' % (self.filename,
187 self.lineno, os.path.relpath(self.examplefile)))