Changelog ========= 0.6 - `master`_ ~~~~~~~~~~~~~~~ .. note:: This version is not yet released and is under active development. * Added :func:`~cryptography.hazmat.primitives.serialization.load_pem_private_key` to ease loading private keys, and :func:`~cryptography.hazmat.primitives.serialization.load_pem_public_key` to support loading public keys. * Removed the, deprecated in 0.4, support for the ``salt_length`` argument to the :class:`~cryptography.hazmat.primitives.asymmetric.padding.MGF1` constructor. The ``salt_length`` should be passed to :class:`~cryptography.hazmat.primitives.asymmetric.padding.PSS` instead. * Fix compilation on OS X Yosemite. * Deprecated ``elliptic_curve_private_key_from_numbers`` and ``elliptic_curve_public_key_from_numbers`` in favor of ``load_elliptic_curve_private_numbers`` and ``load_elliptic_curve_public_numbers`` on :class:`~cryptography.hazmat.backends.interfaces.EllipticCurveBackend`. 0.5.4 - 2014-08-20 ~~~~~~~~~~~~~~~~~~ * Added several functions to the OpenSSL bindings to support new functionality in pyOpenSSL. * Fixed a redefined constant causing compilation failure with Solaris 11.2. 0.5.3 - 2014-08-06 ~~~~~~~~~~~~~~~~~~ * Updated Windows wheels to be compiled against OpenSSL 1.0.1i. 0.5.2 - 2014-07-09 ~~~~~~~~~~~~~~~~~~ * Add :class:`~cryptography.hazmat.backends.interfaces.TraditionalOpenSSLSerializationBackend` support to :doc:`/hazmat/backends/multibackend`. * Fix compilation error on OS X 10.8 (Mountain Lion). 0.5.1 - 2014-07-07 ~~~~~~~~~~~~~~~~~~ * Add :class:`~cryptography.hazmat.backends.interfaces.PKCS8SerializationBackend` support to :doc:`/hazmat/backends/multibackend`. 0.5 - 2014-07-07 ~~~~~~~~~~~~~~~~ * **BACKWARDS INCOMPATIBLE:** :class:`~cryptography.hazmat.primitives.ciphers.modes.GCM` no longer allows truncation of tags by default. Previous versions of ``cryptography`` allowed tags to be truncated by default, applications wishing to preserve this behavior (not recommended) can pass the ``min_tag_length`` argument. * Windows builds now statically link OpenSSL by default. When installing a wheel on Windows you no longer need to install OpenSSL separately. Windows users can switch between static and dynamic linking with an environment variable. See :doc:`/installation` for more details. * Added :class:`~cryptography.hazmat.primitives.kdf.hkdf.HKDFExpand`. * Added :class:`~cryptography.hazmat.primitives.ciphers.modes.CFB8` support for :class:`~cryptography.hazmat.primitives.ciphers.algorithms.AES` and :class:`~cryptography.hazmat.primitives.ciphers.algorithms.TripleDES` on :doc:`/hazmat/backends/commoncrypto` and :doc:`/hazmat/backends/openssl`. * Added ``AES`` :class:`~cryptography.hazmat.primitives.ciphers.modes.CTR` support to the OpenSSL backend when linked against 0.9.8. * Added :class:`~cryptography.hazmat.backends.interfaces.PKCS8SerializationBackend` and :class:`~cryptography.hazmat.backends.interfaces.TraditionalOpenSSLSerializationBackend` support to the :doc:`/hazmat/backends/openssl`. * Added :doc:`/hazmat/primitives/asymmetric/ec` and :class:`~cryptography.hazmat.backends.interfaces.EllipticCurveBackend`. * Added :class:`~cryptography.hazmat.primitives.ciphers.modes.ECB` support for :class:`~cryptography.hazmat.primitives.ciphers.algorithms.TripleDES` on :doc:`/hazmat/backends/commoncrypto` and :doc:`/hazmat/backends/openssl`. * Deprecated :class:`~cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey` in favor of backend specific providers of the :class:`~cryptography.hazmat.primitives.interfaces.RSAPrivateKey` interface. * Deprecated :class:`~cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey` in favor of backend specific providers of the :class:`~cryptography.hazmat.primitives.interfaces.RSAPublicKey` interface. * Deprecated :class:`~cryptography.hazmat.primitives.asymmetric.dsa.DSAPrivateKey` in favor of backend specific providers of the :class:`~cryptography.hazmat.primitives.interfaces.DSAPrivateKey` interface. * Deprecated :class:`~cryptography.hazmat.primitives.asymmetric.dsa.DSAPublicKey` in favor of backend specific providers of the :class:`~cryptography.hazmat.primitives.interfaces.DSAPublicKey` interface. * Deprecated :class:`~cryptography.hazmat.primitives.asymmetric.dsa.DSAParameters` in favor of backend specific providers of the :class:`~cryptography.hazmat.primitives.interfaces.DSAParameters` interface. * Deprecated ``encrypt_rsa``, ``decrypt_rsa``, ``create_rsa_signature_ctx`` and ``create_rsa_verification_ctx`` on :class:`~cryptography.hazmat.backends.interfaces.RSABackend`. * Deprecated ``create_dsa_signature_ctx`` and ``create_dsa_verification_ctx`` on :class:`~cryptography.hazmat.backends.interfaces.DSABackend`. 0.4 - 2014-05-03 ~~~~~~~~~~~~~~~~ * Deprecated ``salt_length`` on :class:`~cryptography.hazmat.primitives.asymmetric.padding.MGF1` and added it to :class:`~cryptography.hazmat.primitives.asymmetric.padding.PSS`. It will be removed from ``MGF1`` in two releases per our :doc:`/api-stability` policy. * Added :class:`~cryptography.hazmat.primitives.ciphers.algorithms.SEED` support. * Added :class:`~cryptography.hazmat.primitives.cmac.CMAC`. * Added decryption support to :class:`~cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey` and encryption support to :class:`~cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey`. * Added signature support to :class:`~cryptography.hazmat.primitives.asymmetric.dsa.DSAPrivateKey` and verification support to :class:`~cryptography.hazmat.primitives.asymmetric.dsa.DSAPublicKey`. 0.3 - 2014-03-27 ~~~~~~~~~~~~~~~~ * Added :class:`~cryptography.hazmat.primitives.twofactor.hotp.HOTP`. * Added :class:`~cryptography.hazmat.primitives.twofactor.totp.TOTP`. * Added :class:`~cryptography.hazmat.primitives.ciphers.algorithms.IDEA` support. * Added signature support to :class:`~cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey` and verification support to :class:`~cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey`. * Moved test vectors to the new ``cryptography_vectors`` package. 0.2.2 - 2014-03-03 ~~~~~~~~~~~~~~~~~~ * Removed a constant definition that was causing compilation problems with specific versions of OpenSSL. 0.2.1 - 2014-02-22 ~~~~~~~~~~~~~~~~~~ * Fix a bug where importing cryptography from multiple paths could cause initialization to fail. 0.2 - 2014-02-20 ~~~~~~~~~~~~~~~~ * Added :doc:`/hazmat/backends/commoncrypto`. * Added initial :doc:`/hazmat/bindings/commoncrypto`. * Removed ``register_cipher_adapter`` method from :class:`~cryptography.hazmat.backends.interfaces.CipherBackend`. * Added support for the OpenSSL backend under Windows. * Improved thread-safety for the OpenSSL backend. * Fixed compilation on systems where OpenSSL's ``ec.h`` header is not available, such as CentOS. * Added :class:`~cryptography.hazmat.primitives.kdf.pbkdf2.PBKDF2HMAC`. * Added :class:`~cryptography.hazmat.primitives.kdf.hkdf.HKDF`. * Added :doc:`/hazmat/backends/multibackend`. * Set default random for the :doc:`/hazmat/backends/openssl` to the OS random engine. * Added :class:`~cryptography.hazmat.primitives.ciphers.algorithms.CAST5` (CAST-128) support. 0.1 - 2014-01-08 ~~~~~~~~~~~~~~~~ * Initial release. .. _`master`: https://github.com/pyca/cryptography/ 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
# -*- coding: utf-8 -*-
import pytest

from pybind11_tests import stl as m
from pybind11_tests import UserType
from pybind11_tests import ConstructorStats


def test_vector(doc):
    """std::vector <-> list"""
    lst = m.cast_vector()
    assert lst == [1]
    lst.append(2)
    assert m.load_vector(lst)
    assert m.load_vector(tuple(lst))

    assert m.cast_bool_vector() == [True, False]
    assert m.load_bool_vector([True, False])

    assert doc(m.cast_vector) == "cast_vector() -> List[int]"
    assert doc(m.load_vector) == "load_vector(arg0: List[int]) -> bool"

    # Test regression caused by 936: pointers to stl containers weren't castable
    assert m.cast_ptr_vector() == ["lvalue", "lvalue"]


def test_deque(doc):
    """std::deque <-> list"""
    lst = m.cast_deque()
    assert lst == [1]
    lst.append(2)
    assert m.load_deque(lst)
    assert m.load_deque(tuple(lst))


def test_array(doc):
    """std::array <-> list"""
    lst = m.cast_array()
    assert lst == [1, 2]
    assert m.load_array(lst)

    assert doc(m.cast_array) == "cast_array() -> List[int[2]]"
    assert doc(m.load_array) == "load_array(arg0: List[int[2]]) -> bool"


def test_valarray(doc):
    """std::valarray <-> list"""
    lst = m.cast_valarray()
    assert lst == [1, 4, 9]
    assert m.load_valarray(lst)

    assert doc(m.cast_valarray) == "cast_valarray() -> List[int]"
    assert doc(m.load_valarray) == "load_valarray(arg0: List[int]) -> bool"


def test_map(doc):
    """std::map <-> dict"""
    d = m.cast_map()
    assert d == {"key": "value"}
    assert "key" in d
    d["key2"] = "value2"
    assert "key2" in d
    assert m.load_map(d)

    assert doc(m.cast_map) == "cast_map() -> Dict[str, str]"
    assert doc(m.load_map) == "load_map(arg0: Dict[str, str]) -> bool"


def test_set(doc):
    """std::set <-> set"""
    s = m.cast_set()
    assert s == {"key1", "key2"}
    s.add("key3")
    assert m.load_set(s)

    assert doc(m.cast_set) == "cast_set() -> Set[str]"
    assert doc(m.load_set) == "load_set(arg0: Set[str]) -> bool"


def test_recursive_casting():
    """Tests that stl casters preserve lvalue/rvalue context for container values"""
    assert m.cast_rv_vector() == ["rvalue", "rvalue"]
    assert m.cast_lv_vector() == ["lvalue", "lvalue"]
    assert m.cast_rv_array() == ["rvalue", "rvalue", "rvalue"]
    assert m.cast_lv_array() == ["lvalue", "lvalue"]
    assert m.cast_rv_map() == {"a": "rvalue"}
    assert m.cast_lv_map() == {"a": "lvalue", "b": "lvalue"}
    assert m.cast_rv_nested() == [[[{"b": "rvalue", "c": "rvalue"}], [{"a": "rvalue"}]]]
    assert m.cast_lv_nested() == {
        "a": [[["lvalue", "lvalue"]], [["lvalue", "lvalue"]]],
        "b": [[["lvalue", "lvalue"], ["lvalue", "lvalue"]]],
    }

    # Issue #853 test case:
    z = m.cast_unique_ptr_vector()
    assert z[0].value == 7 and z[1].value == 42


def test_move_out_container():
    """Properties use the `reference_internal` policy by default. If the underlying function
    returns an rvalue, the policy is automatically changed to `move` to avoid referencing
    a temporary. In case the return value is a container of user-defined types, the policy
    also needs to be applied to the elements, not just the container."""
    c = m.MoveOutContainer()
    moved_out_list = c.move_list
    assert [x.value for x in moved_out_list] == [0, 1, 2]


@pytest.mark.skipif(not hasattr(m, "has_optional"), reason="no <optional>")
def test_optional():
    assert m.double_or_zero(None) == 0
    assert m.double_or_zero(42) == 84
    pytest.raises(TypeError, m.double_or_zero, "foo")

    assert m.half_or_none(0) is None
    assert m.half_or_none(42) == 21
    pytest.raises(TypeError, m.half_or_none, "foo")

    assert m.test_nullopt() == 42
    assert m.test_nullopt(None) == 42
    assert m.test_nullopt(42) == 42
    assert m.test_nullopt(43) == 43

    assert m.test_no_assign() == 42
    assert m.test_no_assign(None) == 42
    assert m.test_no_assign(m.NoAssign(43)) == 43
    pytest.raises(TypeError, m.test_no_assign, 43)

    assert m.nodefer_none_optional(None)

    holder = m.OptionalHolder()
    mvalue = holder.member
    assert mvalue.initialized
    assert holder.member_initialized()


@pytest.mark.skipif(
    not hasattr(m, "has_exp_optional"), reason="no <experimental/optional>"
)
def test_exp_optional():
    assert m.double_or_zero_exp(None) == 0
    assert m.double_or_zero_exp(42) == 84
    pytest.raises(TypeError, m.double_or_zero_exp, "foo")

    assert m.half_or_none_exp(0) is None
    assert m.half_or_none_exp(42) == 21
    pytest.raises(TypeError, m.half_or_none_exp, "foo")

    assert m.test_nullopt_exp() == 42
    assert m.test_nullopt_exp(None) == 42
    assert m.test_nullopt_exp(42) == 42
    assert m.test_nullopt_exp(43) == 43

    assert m.test_no_assign_exp() == 42
    assert m.test_no_assign_exp(None) == 42
    assert m.test_no_assign_exp(m.NoAssign(43)) == 43
    pytest.raises(TypeError, m.test_no_assign_exp, 43)

    holder = m.OptionalExpHolder()
    mvalue = holder.member
    assert mvalue.initialized
    assert holder.member_initialized()


@pytest.mark.skipif(not hasattr(m, "load_variant"), reason="no <variant>")
def test_variant(doc):
    assert m.load_variant(1) == "int"
    assert m.load_variant("1") == "std::string"
    assert m.load_variant(1.0) == "double"
    assert m.load_variant(None) == "std::nullptr_t"

    assert m.load_variant_2pass(1) == "int"
    assert m.load_variant_2pass(1.0) == "double"

    assert m.cast_variant() == (5, "Hello")

    assert (
        doc(m.load_variant) == "load_variant(arg0: Union[int, str, float, None]) -> str"
    )


def test_vec_of_reference_wrapper():
    """#171: Can't return reference wrappers (or STL structures containing them)"""
    assert (
        str(m.return_vec_of_reference_wrapper(UserType(4)))
        == "[UserType(1), UserType(2), UserType(3), UserType(4)]"
    )


def test_stl_pass_by_pointer(msg):
    """Passing nullptr or None to an STL container pointer is not expected to work"""
    with pytest.raises(TypeError) as excinfo:
        m.stl_pass_by_pointer()  # default value is `nullptr`
    assert (
        msg(excinfo.value)
        == """
        stl_pass_by_pointer(): incompatible function arguments. The following argument types are supported:
            1. (v: List[int] = None) -> List[int]

        Invoked with:
    """  # noqa: E501 line too long
    )

    with pytest.raises(TypeError) as excinfo:
        m.stl_pass_by_pointer(None)
    assert (
        msg(excinfo.value)
        == """
        stl_pass_by_pointer(): incompatible function arguments. The following argument types are supported:
            1. (v: List[int] = None) -> List[int]

        Invoked with: None
    """  # noqa: E501 line too long
    )

    assert m.stl_pass_by_pointer([1, 2, 3]) == [1, 2, 3]


def test_missing_header_message():
    """Trying convert `list` to a `std::vector`, or vice versa, without including
    <pybind11/stl.h> should result in a helpful suggestion in the error message"""
    import pybind11_cross_module_tests as cm

    expected_message = (
        "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
        "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
        "conversions are optional and require extra headers to be included\n"
        "when compiling your pybind11 module."
    )

    with pytest.raises(TypeError) as excinfo:
        cm.missing_header_arg([1.0, 2.0, 3.0])
    assert expected_message in str(excinfo.value)

    with pytest.raises(TypeError) as excinfo:
        cm.missing_header_return()
    assert expected_message in str(excinfo.value)


def test_function_with_string_and_vector_string_arg():
    """Check if a string is NOT implicitly converted to a list, which was the
    behavior before fix of issue #1258"""
    assert m.func_with_string_or_vector_string_arg_overload(("A", "B")) == 2
    assert m.func_with_string_or_vector_string_arg_overload(["A", "B"]) == 2
    assert m.func_with_string_or_vector_string_arg_overload("A") == 3


def test_stl_ownership():
    cstats = ConstructorStats.get(m.Placeholder)
    assert cstats.alive() == 0
    r = m.test_stl_ownership()
    assert len(r) == 1
    del r
    assert cstats.alive() == 0


def test_array_cast_sequence():
    assert m.array_cast_sequence((1, 2, 3)) == [1, 2, 3]


def test_issue_1561():
    """ check fix for issue #1561 """
    bar = m.Issue1561Outer()
    bar.list = [m.Issue1561Inner("bar")]
    bar.list
    assert bar.list[0].data == "bar"