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 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
|
import os
import os.path
import tempfile
import subprocess
import re
from docutils import nodes, statemachine, utils
from docutils.parsers.rst import directives, Directive, DirectiveError, Parser
from docutils.transforms import TransformError, Transform
from sphinx.util.console import bold, purple, darkgreen, red, term_width_line
from sphinx.errors import SphinxError
from sphinx.directives.code import LiteralInclude
from sphinx.util import logging
logger = logging.getLogger(__name__)
Initialized = False
App = None
Reporter = None
BTestBase = None
BTestTests = None
BTestTmp = None
Tests = {}
Includes = set()
# Maps file name extensiosn to Pygments formatter.
ExtMappings = {"bro": "bro", "rst": "rest", "c": "c", "cc": "cc", "py": "python"}
def init(settings, reporter):
global Initialized, App, Reporter, BTestBase, BTestTests, BTestTmp
Initialized = True
Reporter = reporter
BTestBase = settings.env.config.btest_base
BTestTests = settings.env.config.btest_tests
BTestTmp = settings.env.config.btest_tmp
if not BTestBase:
raise SphinxError("error: btest_base not set in config")
if not BTestTests:
raise SphinxError("error: btest_tests not set in config")
if not os.path.exists(BTestBase):
raise SphinxError("error: btest_base directory '%s' does not exists" % BTestBase)
joined = os.path.join(BTestBase, BTestTests)
if not os.path.exists(joined):
raise SphinxError("error: btest_tests directory '%s' does not exists" % joined)
if not BTestTmp:
BTestTmp = os.path.join(App.outdir, ".tmp/rst_output")
BTestTmp = os.path.abspath(BTestTmp)
if not os.path.exists(BTestTmp):
os.makedirs(BTestTmp)
def parsePartial(rawtext, settings):
parser = Parser()
document = utils.new_document("<partial node>")
document.settings = settings
parser.parse(rawtext, document)
return document.children
class Test(object):
def __init__(self):
self.has_run = False
def run(self):
if self.has_run:
return
logger.info("running test %s ..." % darkgreen(self.path))
self.rst_output = os.path.join(BTestTmp, "%s" % self.tag)
os.environ["BTEST_RST_OUTPUT"] = self.rst_output
self.cleanTmps()
try:
subprocess.check_call("btest -S %s" % self.path, shell=True)
except (OSError, IOError, subprocess.CalledProcessError) as e:
# Equivalent to Directive.error(); we don't have an
# directive object here and can't pass it in because
# it doesn't pickle.
logger.warning(red("BTest error: %s" % e))
def cleanTmps(self):
subprocess.call("rm %s#* 2>/dev/null" % self.rst_output, shell=True)
class BTestTransform(Transform):
default_priority = 800
def apply(self):
pending = self.startnode
(test, part) = pending.details
os.chdir(BTestBase)
if not test.tag in BTestTransform._run:
test.run()
BTestTransform._run.add(test.tag)
try:
rawtext = open("%s#%d" % (test.rst_output, part)).read()
except IOError as e:
rawtext = ""
settings = self.document.settings
content = parsePartial(rawtext, settings)
pending.replace_self(content)
_run = set()
class BTest(Directive):
required_arguments = 1
final_argument_whitespace = True
has_content = True
def error(self, msg):
self.state.document.settings.env.note_reread()
msg = red(msg)
msg = self.state.document.reporter.error(str(msg), line=self.lineno)
return [msg]
def message(self, msg):
Reporter.info(msg)
def run(self):
if not Initialized:
# FIXME: Better way to handle one-time initialization?
init(self.state.document.settings, self.state.document.reporter)
os.chdir(BTestBase)
self.assert_has_content()
document = self.state_machine.document
tag = self.arguments[0]
if not tag in Tests:
import sys
test = Test()
test.tag = tag
test.path = os.path.join(BTestTests, tag + ".btest")
test.parts = 0
Tests[tag] = test
test = Tests[tag]
test.parts += 1
part = test.parts
# Save the test.
if part == 1:
file = test.path
else:
file = test.path + "#%d" % part
out = open(file, "w")
for line in self.content:
out.write("%s\n" % line)
out.close()
details = (test, part)
pending = nodes.pending(BTestTransform, details, rawsource=self.block_text)
document.note_pending(pending)
return [pending]
class BTestInclude(LiteralInclude):
def __init__(self, *args, **kwargs):
super(BTestInclude, self).__init__(*args, **kwargs)
def error(self, msg):
self.state.document.settings.env.note_reread()
msg = red(msg)
msg = self.state.document.reporter.error(str(msg), line=self.lineno)
return [msg]
def message(self, msg):
Reporter.info(msg)
def run(self):
if not Initialized:
# FIXME: Better way to handle one-time initialization?
init(self.state.document.settings, self.state.document.reporter)
document = self.state.document
if not document.settings.file_insertion_enabled:
return [document.reporter.warning('File insertion disabled', line=self.lineno)]
env = document.settings.env
expanded_arg = os.path.expandvars(self.arguments[0])
sphinx_src_relation = os.path.relpath(expanded_arg, env.srcdir)
self.arguments[0] = os.path.join(os.sep, sphinx_src_relation)
(root, ext) = os.path.splitext(self.arguments[0])
if ext.startswith("."):
ext = ext[1:]
if ext in ExtMappings:
self.options["language"] = ExtMappings[ext]
else:
# Note that we always need to set a language, otherwise the lineos/emphasis don't seem to work.
self.options["language"] = "none"
self.options["linenos"] = True
self.options["prepend"] = "%s\n" % os.path.basename(self.arguments[0])
self.options["emphasize-lines"] = "1,1"
self.options["style"] = "X"
retnode = super(BTestInclude, self).run()
os.chdir(BTestBase)
tag = os.path.normpath(self.arguments[0])
tag = os.path.relpath(tag, BTestBase)
tag = re.sub("[^a-zA-Z0-9-]", "_", tag)
tag = re.sub("__+", "_", tag)
if tag.startswith("_"):
tag = tag[1:]
test_path = ("include-" + tag + ".btest")
if BTestTests:
test_path = os.path.join(BTestTests, test_path)
test_path = os.path.abspath(test_path)
i = 1
(base, ext) = os.path.splitext(test_path)
while test_path in Includes:
i += 1
test_path = "%s@%d" % (base, i)
if ext:
test_path += ext
Includes.add(test_path)
out = open(test_path, "w")
out.write("# @TEST-EXEC: cat %INPUT >output && btest-diff output\n\n")
for i in retnode:
out.write(i.rawsource)
out.close()
for node in retnode:
node["classes"] += ["btest-include"]
return retnode
directives.register_directive('btest', BTest)
directives.register_directive('btest-include', BTestInclude)
def setup(app):
global App
App = app
app.add_config_value('btest_base', None, 'env')
app.add_config_value('btest_tests', None, 'env')
app.add_config_value('btest_tmp', None, 'env')
|