test_eval.cpp revision 11986:c12e4625ab56
1/*
2    tests/test_eval.cpp -- Usage of eval() and eval_file()
3
4    Copyright (c) 2016 Klemens D. Morgenstern
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
11#include <pybind11/eval.h>
12#include "pybind11_tests.h"
13
14test_initializer eval([](py::module &m) {
15    auto global = py::dict(py::module::import("__main__").attr("__dict__"));
16
17    m.def("test_eval_statements", [global]() {
18        auto local = py::dict();
19        local["call_test"] = py::cpp_function([&]() -> int {
20            return 42;
21        });
22
23        auto result = py::eval<py::eval_statements>(
24            "print('Hello World!');\n"
25            "x = call_test();",
26            global, local
27        );
28        auto x = local["x"].cast<int>();
29
30        return result == py::none() && x == 42;
31    });
32
33    m.def("test_eval", [global]() {
34        auto local = py::dict();
35        local["x"] = py::int_(42);
36        auto x = py::eval("x", global, local);
37        return x.cast<int>() == 42;
38    });
39
40    m.def("test_eval_single_statement", []() {
41        auto local = py::dict();
42        local["call_test"] = py::cpp_function([&]() -> int {
43            return 42;
44        });
45
46        auto result = py::eval<py::eval_single_statement>("x = call_test()", py::dict(), local);
47        auto x = local["x"].cast<int>();
48        return result == py::none() && x == 42;
49    });
50
51    m.def("test_eval_file", [global](py::str filename) {
52        auto local = py::dict();
53        local["y"] = py::int_(43);
54
55        int val_out;
56        local["call_test2"] = py::cpp_function([&](int value) { val_out = value; });
57
58        auto result = py::eval_file(filename, global, local);
59        return val_out == 43 && result == py::none();
60    });
61
62    m.def("test_eval_failure", []() {
63        try {
64            py::eval("nonsense code ...");
65        } catch (py::error_already_set &) {
66            return true;
67        }
68        return false;
69    });
70
71    m.def("test_eval_file_failure", []() {
72        try {
73            py::eval_file("non-existing file");
74        } catch (std::exception &) {
75            return true;
76        }
77        return false;
78    });
79});
80