Enable testing for <optional> when available (#501)

This commit is contained in:
Jason Rhinelander 2016-11-15 16:24:26 -05:00 committed by Wenzel Jakob
parent 425b4970b2
commit 2e76daa53f
2 changed files with 38 additions and 6 deletions

View File

@ -290,11 +290,10 @@ test_initializer python_types([](py::module &m) {
return d;
});
// this only tests std::experimental::optional for now
bool has_optional = false;
#ifdef PYBIND11_HAS_EXP_OPTIONAL
bool has_optional = false, has_exp_optional = false;
#ifdef PYBIND11_HAS_OPTIONAL
has_optional = true;
using opt_int = std::experimental::optional<int>;
using opt_int = std::optional<int>;
m.def("double_or_zero", [](const opt_int& x) -> int {
return x.value_or(0) * 2;
});
@ -303,7 +302,23 @@ test_initializer python_types([](py::module &m) {
});
m.def("test_nullopt", [](opt_int x) {
return x.value_or(42);
}, py::arg_v("x", std::nullopt, "None"));
#endif
#ifdef PYBIND11_HAS_EXP_OPTIONAL
has_exp_optional = true;
using opt_int = std::experimental::optional<int>;
m.def("double_or_zero_exp", [](const opt_int& x) -> int {
return x.value_or(0) * 2;
});
m.def("half_or_none_exp", [](int x) -> opt_int {
return x ? opt_int(x / 2) : opt_int();
});
m.def("test_nullopt_exp", [](opt_int x) {
return x.value_or(42);
}, py::arg_v("x", std::experimental::nullopt, "None"));
#endif
m.attr("has_optional") = py::cast(has_optional);
m.attr("has_exp_optional") = py::cast(has_exp_optional);
});

View File

@ -1,6 +1,6 @@
import pytest
from pybind11_tests import ExamplePythonTypes, ConstructorStats, has_optional
from pybind11_tests import ExamplePythonTypes, ConstructorStats, has_optional, has_exp_optional
def test_static():
@ -297,7 +297,7 @@ def test_accessors():
assert d["var"] == 99
@pytest.mark.skipif(not has_optional, reason='no <experimental/optional>')
@pytest.mark.skipif(not has_optional, reason='no <optional>')
def test_optional():
from pybind11_tests import double_or_zero, half_or_none, test_nullopt
@ -313,3 +313,20 @@ def test_optional():
assert test_nullopt(None) == 42
assert test_nullopt(42) == 42
assert test_nullopt(43) == 43
@pytest.mark.skipif(not has_exp_optional, reason='no <experimental/optional>')
def test_exp_optional():
from pybind11_tests import double_or_zero_exp, half_or_none_exp, test_nullopt_exp
assert double_or_zero_exp(None) == 0
assert double_or_zero_exp(42) == 84
pytest.raises(TypeError, double_or_zero_exp, 'foo')
assert half_or_none_exp(0) is None
assert half_or_none_exp(42) == 21
pytest.raises(TypeError, half_or_none_exp, 'foo')
assert test_nullopt_exp() == 42
assert test_nullopt_exp(None) == 42
assert test_nullopt_exp(42) == 42
assert test_nullopt_exp(43) == 43