1/*
2    tests/test_enums.cpp -- enumerations
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
12TEST_SUBMODULE(enums, m) {
13    // test_unscoped_enum
14    enum UnscopedEnum {
15        EOne = 1,
16        ETwo,
17        EThree
18    };
19    py::enum_<UnscopedEnum>(m, "UnscopedEnum", py::arithmetic(), "An unscoped enumeration")
20        .value("EOne", EOne, "Docstring for EOne")
21        .value("ETwo", ETwo, "Docstring for ETwo")
22        .value("EThree", EThree, "Docstring for EThree")
23        .export_values();
24
25    // test_scoped_enum
26    enum class ScopedEnum {
27        Two = 2,
28        Three
29    };
30    py::enum_<ScopedEnum>(m, "ScopedEnum", py::arithmetic())
31        .value("Two", ScopedEnum::Two)
32        .value("Three", ScopedEnum::Three);
33
34    m.def("test_scoped_enum", [](ScopedEnum z) {
35        return "ScopedEnum::" + std::string(z == ScopedEnum::Two ? "Two" : "Three");
36    });
37
38    // test_binary_operators
39    enum Flags {
40        Read = 4,
41        Write = 2,
42        Execute = 1
43    };
44    py::enum_<Flags>(m, "Flags", py::arithmetic())
45        .value("Read", Flags::Read)
46        .value("Write", Flags::Write)
47        .value("Execute", Flags::Execute)
48        .export_values();
49
50    // test_implicit_conversion
51    class ClassWithUnscopedEnum {
52    public:
53        enum EMode {
54            EFirstMode = 1,
55            ESecondMode
56        };
57
58        static EMode test_function(EMode mode) {
59            return mode;
60        }
61    };
62    py::class_<ClassWithUnscopedEnum> exenum_class(m, "ClassWithUnscopedEnum");
63    exenum_class.def_static("test_function", &ClassWithUnscopedEnum::test_function);
64    py::enum_<ClassWithUnscopedEnum::EMode>(exenum_class, "EMode")
65        .value("EFirstMode", ClassWithUnscopedEnum::EFirstMode)
66        .value("ESecondMode", ClassWithUnscopedEnum::ESecondMode)
67        .export_values();
68
69    // test_enum_to_int
70    m.def("test_enum_to_int", [](int) { });
71    m.def("test_enum_to_uint", [](uint32_t) { });
72    m.def("test_enum_to_long_long", [](long long) { });
73
74    // test_duplicate_enum_name
75    enum SimpleEnum
76    {
77        ONE, TWO, THREE
78    };
79
80    m.def("register_bad_enum", [m]() {
81        py::enum_<SimpleEnum>(m, "SimpleEnum")
82            .value("ONE", SimpleEnum::ONE)          //NOTE: all value function calls are called with the same first parameter value
83            .value("ONE", SimpleEnum::TWO)
84            .value("ONE", SimpleEnum::THREE)
85            .export_values();
86    });
87}
88