pybind11_tests.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #pragma once
  2. #include <pybind11/pybind11.h>
  3. #if defined(_MSC_VER) && _MSC_VER < 1910
  4. // We get some really long type names here which causes MSVC 2015 to emit warnings
  5. # pragma warning(disable: 4503) // warning C4503: decorated name length exceeded, name was truncated
  6. #endif
  7. namespace py = pybind11;
  8. using namespace pybind11::literals;
  9. class test_initializer {
  10. using Initializer = void (*)(py::module &);
  11. public:
  12. test_initializer(Initializer init);
  13. test_initializer(const char *submodule_name, Initializer init);
  14. };
  15. #define TEST_SUBMODULE(name, variable) \
  16. void test_submodule_##name(py::module &); \
  17. test_initializer name(#name, test_submodule_##name); \
  18. void test_submodule_##name(py::module &variable)
  19. /// Dummy type which is not exported anywhere -- something to trigger a conversion error
  20. struct UnregisteredType { };
  21. /// A user-defined type which is exported and can be used by any test
  22. class UserType {
  23. public:
  24. UserType() = default;
  25. UserType(int i) : i(i) { }
  26. int value() const { return i; }
  27. void set(int set) { i = set; }
  28. private:
  29. int i = -1;
  30. };
  31. /// Like UserType, but increments `value` on copy for quick reference vs. copy tests
  32. class IncType : public UserType {
  33. public:
  34. using UserType::UserType;
  35. IncType() = default;
  36. IncType(const IncType &other) : IncType(other.value() + 1) { }
  37. IncType(IncType &&) = delete;
  38. IncType &operator=(const IncType &) = delete;
  39. IncType &operator=(IncType &&) = delete;
  40. };
  41. /// Custom cast-only type that casts to a string "rvalue" or "lvalue" depending on the cast context.
  42. /// Used to test recursive casters (e.g. std::tuple, stl containers).
  43. struct RValueCaster {};
  44. NAMESPACE_BEGIN(pybind11)
  45. NAMESPACE_BEGIN(detail)
  46. template<> class type_caster<RValueCaster> {
  47. public:
  48. PYBIND11_TYPE_CASTER(RValueCaster, _("RValueCaster"));
  49. static handle cast(RValueCaster &&, return_value_policy, handle) { return py::str("rvalue").release(); }
  50. static handle cast(const RValueCaster &, return_value_policy, handle) { return py::str("lvalue").release(); }
  51. };
  52. NAMESPACE_END(detail)
  53. NAMESPACE_END(pybind11)