Example #1
0
def test_bytes_to_string():
    """Tests the ability to pass bytes to C++ string-accepting functions.  Note that this is
    one-way: the only way to return bytes to Python is via the pybind11::bytes class."""
    # Issue #816

    assert m.strlen(b"hi") == 2
    assert m.string_length(b"world") == 5
    assert m.string_length("a\x00b".encode()) == 3
    assert m.strlen("a\x00b".encode()) == 1  # C-string limitation

    # passing in a utf8 encoded string should work
    assert m.string_length("💩".encode()) == 4
def test_bytes_to_string():
    """Tests the ability to pass bytes to C++ string-accepting functions.  Note that this is
    one-way: the only way to return bytes to Python is via the pybind11::bytes class."""
    # Issue #816
    import sys
    byte = bytes if sys.version_info[0] < 3 else str

    assert m.strlen(byte("hi")) == 2
    assert m.string_length(byte("world")) == 5
    assert m.string_length(byte("a\x00b")) == 3
    assert m.strlen(byte("a\x00b")) == 1  # C-string limitation

    # passing in a utf8 encoded string should work
    assert m.string_length(u'💩'.encode("utf8")) == 4
Example #3
0
def test_bytearray_to_string():
    """Tests the ability to pass bytearray to C++ string-accepting functions"""
    assert m.string_length(bytearray(b"Hi")) == 2
    assert m.strlen(bytearray(b"bytearray")) == 9
    assert m.string_length(bytearray()) == 0
    assert m.string_length(bytearray("🦜", "utf-8", "strict")) == 4
    assert m.string_length(bytearray(b"\x80")) == 1
Example #4
0
def test_bytes_to_string():
    """Tests the ability to pass bytes to C++ string-accepting functions.  Note that this is
    one-way: the only way to return bytes to Python is via the pybind11::bytes class."""
    # Issue #816

    def to_bytes(s):
        b = s if env.PY2 else s.encode("utf8")
        assert isinstance(b, bytes)
        return b

    assert m.strlen(to_bytes("hi")) == 2
    assert m.string_length(to_bytes("world")) == 5
    assert m.string_length(to_bytes("a\x00b")) == 3
    assert m.strlen(to_bytes("a\x00b")) == 1  # C-string limitation

    # passing in a utf8 encoded string should work
    assert m.string_length(u"💩".encode("utf8")) == 4