pybind11_tests.cpp revision 12037:d28054ac6ec9
1/*
2    tests/pybind11_tests.cpp -- pybind example plugin
3
4    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
6    All rights reserved. Use of this source code is governed by a
7    BSD-style license that can be found in the LICENSE file.
8*/
9
10#include "pybind11_tests.h"
11#include "constructor_stats.h"
12
13/*
14For testing purposes, we define a static global variable here in a function that each individual
15test .cpp calls with its initialization lambda.  It's convenient here because we can just not
16compile some test files to disable/ignore some of the test code.
17
18It is NOT recommended as a way to use pybind11 in practice, however: the initialization order will
19be essentially random, which is okay for our test scripts (there are no dependencies between the
20individual pybind11 test .cpp files), but most likely not what you want when using pybind11
21productively.
22
23Instead, see the "How can I reduce the build time?" question in the "Frequently asked questions"
24section of the documentation for good practice on splitting binding code over multiple files.
25*/
26std::list<std::function<void(py::module &)>> &initializers() {
27    static std::list<std::function<void(py::module &)>> inits;
28    return inits;
29}
30
31test_initializer::test_initializer(std::function<void(py::module &)> initializer) {
32    initializers().push_back(std::move(initializer));
33}
34
35void bind_ConstructorStats(py::module &m) {
36    py::class_<ConstructorStats>(m, "ConstructorStats")
37        .def("alive", &ConstructorStats::alive)
38        .def("values", &ConstructorStats::values)
39        .def_readwrite("default_constructions", &ConstructorStats::default_constructions)
40        .def_readwrite("copy_assignments", &ConstructorStats::copy_assignments)
41        .def_readwrite("move_assignments", &ConstructorStats::move_assignments)
42        .def_readwrite("copy_constructions", &ConstructorStats::copy_constructions)
43        .def_readwrite("move_constructions", &ConstructorStats::move_constructions)
44        .def_static("get", (ConstructorStats &(*)(py::object)) &ConstructorStats::get, py::return_value_policy::reference_internal);
45}
46
47PYBIND11_PLUGIN(pybind11_tests) {
48    py::module m("pybind11_tests", "pybind testing plugin");
49
50    bind_ConstructorStats(m);
51
52    for (const auto &initializer : initializers())
53        initializer(m);
54
55    if (!py::hasattr(m, "have_eigen")) m.attr("have_eigen") = false;
56
57    return m.ptr();
58}
59