2016-07-24 02:04:57 +00:00
|
|
|
import mock
|
2016-09-03 13:01:41 +00:00
|
|
|
import pytest
|
|
|
|
|
2016-07-02 08:51:47 +00:00
|
|
|
from netlib import encoding, tutils
|
2015-08-01 12:53:13 +00:00
|
|
|
|
2015-08-10 18:44:36 +00:00
|
|
|
|
2015-08-01 12:53:13 +00:00
|
|
|
def test_identity():
|
2016-07-02 08:51:47 +00:00
|
|
|
assert b"string" == encoding.decode(b"string", "identity")
|
|
|
|
assert b"string" == encoding.encode(b"string", "identity")
|
|
|
|
with tutils.raises(ValueError):
|
|
|
|
encoding.encode(b"string", "nonexistent encoding")
|
2015-08-01 12:53:13 +00:00
|
|
|
|
|
|
|
|
2016-09-03 13:01:41 +00:00
|
|
|
@pytest.mark.parametrize("encoder", [
|
|
|
|
'gzip',
|
|
|
|
'br',
|
|
|
|
'deflate',
|
|
|
|
])
|
|
|
|
def test_encoders(encoder):
|
|
|
|
assert "" == encoding.decode("", encoder)
|
|
|
|
assert b"" == encoding.decode(b"", encoder)
|
2015-08-01 12:53:13 +00:00
|
|
|
|
2016-09-03 13:01:41 +00:00
|
|
|
assert "string" == encoding.decode(
|
2016-07-30 12:43:53 +00:00
|
|
|
encoding.encode(
|
2016-09-03 13:01:41 +00:00
|
|
|
"string",
|
|
|
|
encoder
|
2016-07-30 12:43:53 +00:00
|
|
|
),
|
2016-09-03 13:01:41 +00:00
|
|
|
encoder
|
2016-07-30 12:43:53 +00:00
|
|
|
)
|
2015-09-15 17:12:15 +00:00
|
|
|
assert b"string" == encoding.decode(
|
2015-08-01 12:53:13 +00:00
|
|
|
encoding.encode(
|
2016-07-02 08:51:47 +00:00
|
|
|
b"string",
|
2016-09-03 13:01:41 +00:00
|
|
|
encoder
|
2016-07-02 08:51:47 +00:00
|
|
|
),
|
2016-09-03 13:01:41 +00:00
|
|
|
encoder
|
2015-09-15 17:12:15 +00:00
|
|
|
)
|
2016-09-03 13:01:41 +00:00
|
|
|
|
2016-07-02 08:51:47 +00:00
|
|
|
with tutils.raises(ValueError):
|
2016-09-03 14:37:03 +00:00
|
|
|
encoding.decode(b"foobar", encoder)
|
2016-07-24 02:04:57 +00:00
|
|
|
|
|
|
|
|
|
|
|
def test_cache():
|
|
|
|
decode_gzip = mock.MagicMock()
|
|
|
|
decode_gzip.return_value = b"decoded"
|
|
|
|
encode_gzip = mock.MagicMock()
|
|
|
|
encode_gzip.return_value = b"encoded"
|
|
|
|
|
|
|
|
with mock.patch.dict(encoding.custom_decode, gzip=decode_gzip):
|
|
|
|
with mock.patch.dict(encoding.custom_encode, gzip=encode_gzip):
|
|
|
|
assert encoding.decode(b"encoded", "gzip") == b"decoded"
|
|
|
|
assert decode_gzip.call_count == 1
|
|
|
|
|
|
|
|
# should be cached
|
|
|
|
assert encoding.decode(b"encoded", "gzip") == b"decoded"
|
|
|
|
assert decode_gzip.call_count == 1
|
|
|
|
|
|
|
|
# the other way around as well
|
|
|
|
assert encoding.encode(b"decoded", "gzip") == b"encoded"
|
|
|
|
assert encode_gzip.call_count == 0
|
|
|
|
|
|
|
|
# different encoding
|
|
|
|
decode_gzip.return_value = b"bar"
|
|
|
|
assert encoding.encode(b"decoded", "deflate") != b"decoded"
|
|
|
|
assert encode_gzip.call_count == 0
|
|
|
|
|
|
|
|
# This is not in the cache anymore
|
|
|
|
assert encoding.encode(b"decoded", "gzip") == b"encoded"
|
|
|
|
assert encode_gzip.call_count == 1
|