| 1 |
# -*- coding: utf-8 -*- |
| 2 |
"""This file contains code for setting up C++ unit tests with gtest |
| 3 |
from within Python tests using py.test. |
| 4 |
|
| 5 |
""" |
| 6 |
import pytest |
| 7 |
import os |
| 8 |
import inspect |
| 9 |
from collections import defaultdict |
| 10 |
import subprocess |
| 11 |
|
| 12 |
from ffc.backends.ufc import get_include_path |
| 13 |
|
| 14 |
|
| 15 |
# TODO: For a generic framework, this needs to change somewhat: |
| 16 |
_supportcode = ''' |
| 17 |
#include <ufc.h> |
| 18 |
#include <ufc_geometry.h> |
| 19 |
#include "mock_cells.h" |
| 20 |
//#include "debugging.h" |
| 21 |
''' |
| 22 |
|
| 23 |
_gtest_runner_template = """ |
| 24 |
#include <gtest/gtest.h> |
| 25 |
|
| 26 |
{supportcode} |
| 27 |
|
| 28 |
{testincludes} |
| 29 |
|
| 30 |
int main(int argc, char **argv) |
| 31 |
{{ |
| 32 |
::testing::InitGoogleTest(&argc, argv); |
| 33 |
return RUN_ALL_TESTS(); |
| 34 |
}} |
| 35 |
""" |
| 36 |
|
| 37 |
_gtest_template = """ |
| 38 |
/** Autogenerated from Python test |
| 39 |
{pytestname} |
| 40 |
at |
| 41 |
{pyfilename}:{pylineno} |
| 42 |
*/ |
| 43 |
TEST ({suite}, {case}) |
| 44 |
{{ |
| 45 |
{body} |
| 46 |
}} |
| 47 |
""" |
| 48 |
|
| 49 |
|
| 50 |
def find_parent_test_function(): |
| 51 |
"""Return (filename, lineno, functionname) of the |
| 52 |
first function named "test_*" found on the stack.""" |
| 53 |
|
| 54 |
# Get current frame |
| 55 |
frame = inspect.currentframe() |
| 56 |
info = inspect.getframeinfo(frame) |
| 57 |
|
| 58 |
# Jump back frames until we're in a 'test_*' function |
| 59 |
while not info[2].startswith("test_"): |
| 60 |
frame = frame.f_back |
| 61 |
info = inspect.getframeinfo(frame) |
| 62 |
|
| 63 |
# Get info from frame |
| 64 |
filename = info[0] |
| 65 |
lineno = info[1] |
| 66 |
function = info[2] |
| 67 |
|
| 68 |
assert len(info) == 5 |
| 69 |
assert function.startswith("test_") |
| 70 |
|
| 71 |
return filename, lineno, function |
| 72 |
|
| 73 |
|
| 74 |
class GTestContext: |
| 75 |
_all = [] |
| 76 |
|
| 77 |
def __init__(self, config): |
| 78 |
self._basedir = os.path.dirname(__file__) |
| 79 |
self._gendir = os.path.join(self._basedir, "generated") |
| 80 |
self._binary_filename = os.path.join(self._basedir, "run_gtest") |
| 81 |
self._gtest_log = os.path.join(self._basedir, "gtest.log") |
| 82 |
self._code = defaultdict(list) |
| 83 |
self._dirlist = [] |
| 84 |
GTestContext._all.append(self) |
| 85 |
|
| 86 |
|
| 87 |
def info(self, msg): |
| 88 |
pre = "In gtest generation:" |
| 89 |
if '\n' in msg: |
| 90 |
print(pre) |
| 91 |
print(msg) |
| 92 |
else: |
| 93 |
print(pre, msg) |
| 94 |
|
| 95 |
|
| 96 |
def add(self, body): |
| 97 |
# Look through stack to find frame with test_... function name |
| 98 |
filename, lineno, function = find_parent_test_function() |
| 99 |
|
| 100 |
# Using function testcase class name as suite and function |
| 101 |
# name as case |
| 102 |
basename = os.path.basename(filename) |
| 103 |
suite = basename.replace(".py", "") |
| 104 |
case = function |
| 105 |
|
| 106 |
# Use a header filename matching the python filename |
| 107 |
hfilename = os.path.join(self._gendir, basename.replace(".py", ".h")) |
| 108 |
|
| 109 |
# Get python filename relative to test directory |
| 110 |
pyfilename = os.path.relpath(filename, self._basedir) |
| 111 |
|
| 112 |
# Format as a test in target framework and store |
| 113 |
code = _gtest_template.format(pyfilename=pyfilename, |
| 114 |
pylineno=lineno, |
| 115 |
pytestname=function, |
| 116 |
suite=suite, |
| 117 |
case=case, |
| 118 |
body=body) |
| 119 |
self._code[hfilename].append(code) |
| 120 |
|
| 121 |
|
| 122 |
def write(self): |
| 123 |
# Make sure we have the directory for generated code |
| 124 |
if not os.path.isdir(self._gendir): |
| 125 |
os.mkdir(self._gendir) |
| 126 |
|
| 127 |
# Write test code collected during py.test run to files |
| 128 |
headers = [] |
| 129 |
header_basenames = [] |
| 130 |
for hfilename in sorted(self._code): |
| 131 |
tests = self._code[hfilename] |
| 132 |
code = '\n'.join(tests) |
| 133 |
with open(hfilename, "w") as f: |
| 134 |
f.write(code) |
| 135 |
headers.append(hfilename) |
| 136 |
|
| 137 |
# Collect headers in include list for runner code |
| 138 |
self._test_header_names = [os.path.split(h)[-1] for h in headers] |
| 139 |
testincludes = '\n'.join('#include "{0}"'.format(h) for h in self._test_header_names) |
| 140 |
|
| 141 |
# Write test runner code to file |
| 142 |
runner_code = _gtest_runner_template.format(supportcode=_supportcode, |
| 143 |
testincludes=testincludes) |
| 144 |
|
| 145 |
self._main_filename = os.path.join(self._gendir, "main.cpp") |
| 146 |
with open(self._main_filename, "w") as f: |
| 147 |
f.write(runner_code) |
| 148 |
|
| 149 |
|
| 150 |
def build_gtest(self): |
| 151 |
"Build gtest library" |
| 152 |
|
| 153 |
# Source and build directories |
| 154 |
gtest_dir = "../../../libs/gtest-1.7.0" |
| 155 |
gtest_dir = os.path.abspath(os.path.join(self._basedir, gtest_dir)) |
| 156 |
build_dir = os.path.join(gtest_dir, "lib") |
| 157 |
|
| 158 |
# Check if GTest source can be found |
| 159 |
if os.path.isdir(gtest_dir): |
| 160 |
# Make build directory, if required |
| 161 |
if not os.path.isdir(build_dir): |
| 162 |
os.mkdir(build_dir) |
| 163 |
|
| 164 |
# Configure gtest using cmake |
| 165 |
error = subprocess.call("cmake ..", cwd=build_dir, shell=True) |
| 166 |
if error: |
| 167 |
raise RuntimeError("Could not call CMake successfully to build gtest") |
| 168 |
|
| 169 |
# Build gtest library |
| 170 |
err = subprocess.call("make", cwd=build_dir, shell=True) |
| 171 |
if error: |
| 172 |
raise RuntimeError("Could not call make successfully to build gtest") |
| 173 |
|
| 174 |
else: |
| 175 |
raise RuntimeError("Cannot find gtest source") |
| 176 |
|
| 177 |
|
| 178 |
def build(self): |
| 179 |
# Prepare command |
| 180 |
UFC_INCLUDE_DIR = get_include_path() |
| 181 |
if not os.path.exists(os.path.join(UFC_INCLUDE_DIR, "ufc.h")): |
| 182 |
import IPython; IPython.embed() |
| 183 |
raise RuntimeError("Cannot find ufc.h in provided include path: %s" % (UFC_INCLUDE_DIR,)) |
| 184 |
UFC_CXX_FLAGS = " ".join(["-g", "-O0", "-std=c++11", "-Wall"]) |
| 185 |
cmd = ['make', 'UFC_INCLUDE_DIR="%s"' % UFC_INCLUDE_DIR, 'CXXFLAGS="%s"' % UFC_CXX_FLAGS] |
| 186 |
self.info("Running command: " + " ".join(cmd)) |
| 187 |
|
| 188 |
# Execute |
| 189 |
try: |
| 190 |
out = subprocess.check_output(cmd, |
| 191 |
cwd=self._basedir, shell=True, |
| 192 |
universal_newlines=True) |
| 193 |
self.info(out) |
| 194 |
self.info("Building ok.") |
| 195 |
except subprocess.CalledProcessError as e: |
| 196 |
self.info("Building '{0}' FAILED (code {1}, headers: {2})".format(self._binary_filename, |
| 197 |
e.returncode, self._test_header_names)) |
| 198 |
self.info("Build output:") |
| 199 |
self.info(e.output) |
| 200 |
pytest.fail() |
| 201 |
|
| 202 |
|
| 203 |
def run(self): |
| 204 |
try: |
| 205 |
out = subprocess.check_output(self._binary_filename, |
| 206 |
cwd=self._basedir, shell=True, |
| 207 |
universal_newlines=True) |
| 208 |
self.info("Gtest running ok!") |
| 209 |
with open(self._gtest_log, "w") as f: |
| 210 |
f.write(out) |
| 211 |
self.info(out) |
| 212 |
except subprocess.CalledProcessError as e: |
| 213 |
self.info("Gtest running FAILED with code {0}!".format(e.returncode)) |
| 214 |
with open(self._gtest_log, "w") as f: |
| 215 |
f.write(e.output) |
| 216 |
self.info(e.output) |
| 217 |
pytest.fail() |
| 218 |
|
| 219 |
|
| 220 |
def finalize(self): |
| 221 |
# Build gtest library itself |
| 222 |
self.build_gtest() |
| 223 |
|
| 224 |
# Write collected test code to files |
| 225 |
self.write() |
| 226 |
|
| 227 |
# Build test code |
| 228 |
self.build() |
| 229 |
|
| 230 |
# Run compiled tests |
| 231 |
self.run() |
| 232 |
|
| 233 |
|
| 234 |
@pytest.fixture(scope="session") |
| 235 |
def gtest(): |
| 236 |
"create initial files for gtest generation" |
| 237 |
config = None |
| 238 |
gtc = GTestContext(config) |
| 239 |
return gtc |
| 240 |
|
| 241 |
|
| 242 |
def gtest_sessionfinish(session): |
| 243 |
session.trace("finalizing gtest contexts") |
| 244 |
while GTestContext._all: |
| 245 |
gtc = GTestContext._all.pop() |
| 246 |
gtc.finalize() |
| 247 |
session.trace("done finalizing gtest contexts") |
| 248 |
|
| 249 |
|
| 250 |
def pytest_sessionfinish(session): |
| 251 |
gtest_sessionfinish(session) |