# (c) cavaliba.com - tests / ipam / IpamSubnet unaligned CIDR handling (bug fix)

from django.test import TestCase

import app_home.cache as cache
from app_ipam.common import IpamSubnet
from tests import helper


class IpamSubnetAlignTest(TestCase):
    def setUp(self):
        cache.clear()
        helper.add_schema(
            classname="ipam_subnet",
            options={"keyname_mode": "edit"},
            field_definition={
                "description": {"dataformat": "string", "displayname": "Description"},
                "subnet": {
                    "dataformat": "ipv4",
                    "dataformat_ext": "subnet strict",
                    "displayname": "Subnet",
                },
            },
        )
        helper.add_instance(
            classname="ipam_subnet",
            keyname="10.1.2.0/24",
            fields={"subnet": "10.1.2.0/24", "description": "test subnet"},
        )

    def test_unaligned_cidr_resolves_to_the_aligned_instance(self):
        """Previously this raised ValueError internally (default strict=True) and silently
        returned an empty/unbound object - see the IPAM redesign plan, Bug #1."""
        subnet = IpamSubnet("10.1.2.34/24")
        self.assertEqual(subnet.subnet, "10.1.2.0/24")
        self.assertIsNotNone(subnet.instance)
        self.assertEqual(subnet.description, "test subnet")

    def test_already_aligned_cidr_still_works(self):
        subnet = IpamSubnet("10.1.2.0/24")
        self.assertEqual(subnet.subnet, "10.1.2.0/24")
        self.assertIsNotNone(subnet.instance)

    def test_ipv6_input_is_rejected(self):
        subnet = IpamSubnet("2001:db8::/32")
        self.assertIsNone(subnet.subnet)
        self.assertIsNone(subnet.instance)

    def test_garbage_input_is_rejected(self):
        subnet = IpamSubnet("not-a-subnet")
        self.assertIsNone(subnet.subnet)
        self.assertIsNone(subnet.instance)
