From 5820cd3e5c3c69520e8678101301f1a067b7314f Mon Sep 17 00:00:00 2001 From: Gergely Polonkai Date: Fri, 3 Nov 2023 08:49:03 +0100 Subject: [PATCH] test: Add tests for long_to_bytes and bytes_to_long --- tests/test_util.py | 75 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 tests/test_util.py diff --git a/tests/test_util.py b/tests/test_util.py new file mode 100644 index 0000000..3e804f8 --- /dev/null +++ b/tests/test_util.py @@ -0,0 +1,75 @@ +# SPDX-License-Identifier: MIT +# +# Copyright (c) 2017 PySecretHandshake contributors (see AUTHORS for more details) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +"""Tests for utility functions""" + +import math + +import pytest + +from secret_handshake.util import bytes_to_long, long_to_bytes + + +@pytest.mark.parametrize( + "in_,out", + ( + (0, b"\x00"), + (1, b"\x01"), + (4278255360, b"\xff\x00\xff\x00"), + (65536, b"\x01\x00\x00"), + (4546694913, b"\x01\x0f\x01\x0f\x01"), + ), +) +@pytest.mark.parametrize("blocksize", (0, 4, 6)) +def test_long_to_bytes(in_: int, out: bytes, blocksize: int) -> None: + """Test long_to_bytes""" + + result = long_to_bytes(in_, blocksize=blocksize) + + if blocksize: + block_count = math.ceil(len(out) / blocksize) + else: + block_count = 1 + + padding = b"\x00" * blocksize * block_count + expected = (padding + out)[-(blocksize * block_count) :] + + if blocksize: + assert not len(result) % blocksize + + assert result == expected + + +@pytest.mark.parametrize( + "in_,out", + ( + (b"\x00\x00\x00\x00", 0), + (b"\x00\x00\x00\x01", 1), + (b"\xff\x00\xff\x00", 4278255360), + (b"\x01\x00\x00", 65536), + (b"\x01\x0f\x01\x0f\x01", 4546694913), + ), +) +def test_bytes_to_long(in_: bytes, out: int) -> None: + """Test bytes_to_long""" + + assert bytes_to_long(in_) == out