-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathdrake_variant_pybind_test.cc
59 lines (47 loc) · 1.66 KB
/
drake_variant_pybind_test.cc
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
#include "drake/bindings/pydrake/common/drake_variant_pybind.h"
#include <string>
#include <vector>
#include <fmt/format.h>
#include <gtest/gtest.h>
#include "pybind11/embed.h"
#include "pybind11/eval.h"
#include "pybind11/pybind11.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
using std::string;
namespace drake {
namespace pydrake {
namespace {
string VariantToString(const variant<int, double, string>& value) {
const bool is_int = holds_alternative<int>(value);
const bool is_double = holds_alternative<double>(value);
const bool is_string = holds_alternative<string>(value);
return
is_int ? fmt::format("int({})", get<int>(value)) :
is_double ? fmt::format("double({})", get<double>(value)) :
is_string ? fmt::format("string({})", get<string>(value)) :
"FAILED";
}
void ExpectString(const string& expr, const string& expected) {
EXPECT_EQ(py::eval(expr).cast<string>(), expected) << expr;
}
GTEST_TEST(VariantTest, CheckCasting) {
py::module m("__main__");
m.def("VariantToString", &VariantToString, py::arg("value"));
py::globals().attr("update")(m.attr("__dict__"));
ExpectString("VariantToString(1)", "int(1)");
ExpectString("VariantToString(0.5)", "double(0.5)");
ExpectString("VariantToString('foo')", "string(foo)");
}
int main(int argc, char** argv) {
// Reconstructing `scoped_interpreter` multiple times (e.g. via `SetUp()`)
// while *also* importing `numpy` wreaks havoc.
py::scoped_interpreter guard;
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
} // namespace
} // namespace pydrake
} // namespace drake
int main(int argc, char** argv) {
return drake::pydrake::main(argc, argv);
}