# KEKS -- Python KEKS implementation
# Copyright (C) 2024-2025 Sergey Matveev <stargrave@stargrave.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program.  If not, see <http://www.gnu.org/licenses/>.

from unittest import TestCase

from hypothesis import given
from hypothesis.strategies import integers

from keks import DecodeError
from keks import dumps
from keks import loads
from keks import Magic
from keks import NotEnoughData
from tests.strategies import junk_st
from tests.strategies import magic_st


class TestMagic(TestCase):
    def test_test_vector(self) -> None:
        self.assertSequenceEqual(
            dumps(Magic(b"test-vector")),
            b"KEKS" + b"test-vector" + b"\x00",
        )

    def test_empty(self) -> None:
        self.assertSequenceEqual(dumps(Magic(b"")), b"KEKS" + 12 * b"\x00")

    @given(junk_st, magic_st)
    def test_symmetric(self, junk: bytes, magic: Magic) -> None:
        got, tail = loads(dumps(magic) + junk)
        self.assertEqual(got, magic)
        self.assertSequenceEqual(tail, junk)

    def test_raises_if_too_long(self) -> None:
        with self.assertRaises(ValueError):
            Magic(b"i-am-too-long-string")

    @given(integers(min_value=1, max_value=4))
    def test_not_enough_data(self, striplen: int) -> None:
        raw = dumps(Magic(b"short-one"))
        with self.assertRaises(NotEnoughData) as err:
            loads(raw[:-striplen])
        self.assertEqual(err.exception.n, striplen)

    def test_bad_magic(self) -> None:
        with self.assertRaises(DecodeError) as err:
            loads(b"KEKs" + 12 * b"\x00")
        self.assertEqual(str(err.exception), "wrong magic")
