class CNAMEStaticRegTests(TestCase):
    def create_domain(self, name, ip_type=None, delegated=False):
        if ip_type is None:
            ip_type = '4'
        if name in ('arpa', 'in-addr.arpa', 'ip6.arpa'):
            pass
        else:
            name = ip_to_domain_name(name, ip_type=ip_type)
        d = Domain(name=name, delegated=delegated)
        d.clean()
        self.assertTrue(d.is_reverse)
        return d

    def setUp(self):
        self.arpa = self.create_domain(name='arpa')
        self.arpa.save()
        self.i_arpa = self.create_domain(name='in-addr.arpa')
        self.i_arpa.save()

        self.c = Domain(name="ccc")
        self.c.save()
        self.f_c = Domain(name="foo.ccc")
        self.f_c.save()
        self.r1 = self.create_domain(name="10")
        self.r1.save()
        self.n = System()
        self.n.clean()
        self.n.save()

    def do_add_intr(self, mac, label, domain, ip_str, ip_type='4'):
        r = StaticInterface(mac=mac, label=label, domain=domain, ip_str=ip_str,
                            ip_type=ip_type, system=self.n)
        r.clean()
        r.save()
        repr(r)
        return r

    def test1_delete_cname(self):
        mac = "11:22:33:44:55:66"
        label = "foo4"
        domain = self.f_c
        ip_str = "10.0.0.2"
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        i = self.do_add_intr(**kwargs)
        cn, _ = CNAME.objects.get_or_create(label='foo', domain=domain,
                                            target=label + "." + domain.name)
        self.assertRaises(ValidationError, i.delete)

    def test1_delete_override(self):
        mac = "12:22:33:44:55:66"
        label = "foo6"
        domain = self.f_c
        ip_str = "10.0.0.2"
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        i = self.do_add_intr(**kwargs)
        cn, _ = CNAME.objects.get_or_create(label='food', domain=domain,
                                            target=label + "." + domain.name)
        i.delete(check_cname=False)
class StaticIntrV6APITests(MozdnsAPITests, ResourceTestCase):
    test_type = StaticInterface

    def setUp(self):
        create_fake_zone('2.ip6.arpa', suffix="")
        super(StaticIntrV6APITests, self).setUp()
        self.s = System(hostname="foobar")
        self.s.save()

    def compare_data(self, old_data, new_obj_data):
        for key in old_data.keys():
            if key == 'iname' or key == 'system':
                continue  # StaticInterface needs this done. Too lazy to factor
                          # a comparison function out
            self.assertEqual(old_data[key], new_obj_data[key])

    def post_data(self):
        return {
            'description': random_label(),
            'ttl': random_byte(),
            'fqdn': 'p' + random_label() + "." + self.domain.name,
            'iname': 'mgmt4',
            'dhcp_enabled': True,
            'dns_enabled': True,
            'mac': '11:22:33:44:55:00',
            'system': '/tasty/v3/system/{0}/'.format(self.s.pk),
            'ip_str': "2000:a{0}:a{1}:a{2}::".format(
                random_byte(), random_byte(), random_byte()),
            'ip_type': '6'
        }
class DeleteStaticInterTests(TestCase):
    def create_domain(self, name, ip_type=None, delegated=False):
        if ip_type is None:
            ip_type = '4'
        if name in ('arpa', 'in-addr.arpa', 'ip6.arpa'):
            pass
        else:
            name = ip_to_domain_name(name, ip_type=ip_type)
        d = Domain(name=name, delegated=delegated)
        d.clean()
        self.assertTrue(d.is_reverse)
        return d

    def setUp(self):
        self.arpa = self.create_domain(name='arpa')
        self.arpa.save()
        self.i_arpa = self.create_domain(name='in-addr.arpa')
        self.i_arpa.save()

        self.c = Domain(name="ccc")
        self.c.save()
        self.f_c = Domain(name="foo.ccc")
        self.f_c.save()
        self.r1 = self.create_domain(name="10")
        self.r1.save()
        self.n = System()
        self.n.clean()
        self.n.save()
        View.objects.get_or_create(name="private")

    def do_add(self, mac, label, domain, ip_str, system, ip_type='4'):
        r = StaticInterface(mac=mac, label=label, domain=domain, ip_str=ip_str,
                            ip_type=ip_type, system=system)
        r.clean()
        r.save()
        return r

    def do_delete(self, r):
        ip_str = r.ip_str
        fqdn = r.fqdn
        r.delete()
        self.assertFalse(
            AddressRecord.objects.filter(ip_str=ip_str, fqdn=fqdn))

    def test1_delete_basic(self):
        # Does deleting a system delete it's interfaces?
        mac = "11:22:33:44:55:66"
        label = "foo"
        domain = self.f_c
        ip_str = "10.0.0.2"
        system = System(hostname="foo")
        system.save()
        kwargs = {
            'mac': mac, 'label': label, 'domain': domain, 'ip_str': ip_str,
            'system': system}
        self.do_add(**kwargs)
        self.assertTrue(StaticInterface.objects.filter(**kwargs))
        system.delete()
        self.assertFalse(StaticInterface.objects.filter(**kwargs))
    def create(self, request, system_id=None):
        s = System()
        s.hostname = system_id
        try:
            s.save()
            resp = rc.CREATED
            resp.write('json = {"id":%i, "hostname":"%s"}' % (s.id, s.hostname))
        except:
            resp = rc.BAD_REQUEST
            resp.write("Unable to Create Host")

        return resp
 def create(self, request, system_id=None):
     s = System()
     s.hostname = system_id 
     try:
         s.save()
         resp = rc.CREATED
         resp.write('json = {"id":%i, "hostname":"%s"}' % (s.id, s.hostname))
     except:
         resp = rc.BAD_REQUEST
         resp.write('Unable to Create Host')
         
     return resp
 def test1_delete_basic(self):
     # Does deleting a system delete it's interfaces?
     mac = "11:22:33:44:55:66"
     label = "foo"
     domain = self.f_c
     ip_str = "10.0.0.2"
     system = System(hostname="foo")
     system.save()
     kwargs = {
         'mac': mac, 'label': label, 'domain': domain, 'ip_str': ip_str,
         'system': system}
     self.do_add(**kwargs)
     self.assertTrue(StaticInterface.objects.filter(**kwargs))
     system.delete()
     self.assertFalse(StaticInterface.objects.filter(**kwargs))
class StaticIntrV4APITests(MozdnsAPITests, ResourceTestCase):
    test_type = StaticInterface

    def setUp(self):
        create_fake_zone('11.in-addr.arpa', suffix="")
        super(StaticIntrV4APITests, self).setUp()
        self.s = System(hostname="foobar")
        self.s.save()

    def compare_data(self, old_data, new_obj_data):
        for key in old_data.keys():
            if key == 'system_hostname':
                self.assertEqual(
                    old_data[key], new_obj_data['system']['hostname'])
                continue
            if key in ('iname', 'system'):
                continue  # StaticInterface needs this done. Too lazy to factor
                          # a comparison function out
            self.assertEqual(old_data[key], new_obj_data[key])

    def test_create_hostname(self):
        post_data = self.post_data()
        del post_data['system']
        post_data['system_hostname'] = self.s.hostname
        resp, post_data = self.generic_create(post_data)
        new_object_url = resp['Location']
        new_resp = self.api_client.get(
            new_object_url, format='json', follow=True
        )
        self.assertValidJSONResponse(new_resp)
        new_obj_data = json.loads(new_resp.content)
        self.compare_data(post_data, new_obj_data)

    def post_data(self):
        return {
            'description': 'm' + random_label(),
            'ttl': random_byte(),
            'mac': '11:22:33:44:55:00',
            'system': '/tasty/v3/system/{0}/'.format(self.s.pk),
            'fqdn': 'a' + random_label() + "." + self.domain.name,
            'iname': 'eth2.4',
            'dhcp_enabled': False,
            'dns_enabled': True,
            'ip_str': "11.255.{0}.{1}".format(random_byte(), random_byte()),
            'ip_type': '4'
        }
 def do_add(self, mac, label, domain, ip_str, ip_type='4'):
     self.n = System()
     r = StaticInterface(mac=mac, label=label, domain=domain, ip_str=ip_str,
                         ip_type=ip_type, system=self.n)
     r.clean()
     r.save()
     repr(r)
     return r
Exemple #9
0
def create_fake_host(**kwargs):
    """
    This is a factory for building valid Systems. This factory should be used
    instead of calling System methods directly for making new systems made for
    testing.

    If a new field ever becomes required we can make sure it is filled in here
    instead of updating every test that creates a new System.
    """
    if 'system_type' in kwargs:
        system_type = kwargs.pop('system_type')
    else:
        type_name = random_str()
        while SystemType.objects.filter(type_name=type_name).exists():
            type_name = random_str()
        system_type, _ = SystemType.objects.get_or_create(type_name=type_name)

    if 'allocation' in kwargs:
        allocation = kwargs.pop('allocation')
    else:
        allocation_name = random_str()
        while Allocation.objects.filter(name=allocation_name).exists():
            allocation_name = random_str()
        allocation, _ = Allocation.objects.get_or_create(name=allocation_name)

    if 'serial' in kwargs:
        serial = kwargs.pop('serial')
    else:
        serial = random_str()
        while System.objects.filter(serial=serial).exists():
            type_name = random_str()

    save = kwargs.pop('save', True)

    s = System(
        allocation=allocation,
        serial=serial,
        system_type=system_type,
        warranty_start=datetime.datetime.now(),
        warranty_end=datetime.datetime.now(),
        **kwargs
    )

    if save:
        s.save()
    return s
def create_fake_host(**kwargs):
    """
    This is a factory for building valid Systems. This factory should be used
    instead of calling System methods directly for making new systems made for
    testing.

    If a new field ever becomes required we can make sure it is filled in here
    instead of updating every test that creates a new System.
    """
    if 'system_type' in kwargs:
        system_type = kwargs.pop('system_type')
    else:
        type_name = random_str()
        while SystemType.objects.filter(type_name=type_name).exists():
            type_name = random_str()
        system_type, _ = SystemType.objects.get_or_create(type_name=type_name)

    if 'allocation' in kwargs:
        allocation = kwargs.pop('allocation')
    else:
        allocation_name = random_str()
        while Allocation.objects.filter(name=allocation_name).exists():
            allocation_name = random_str()
        allocation, _ = Allocation.objects.get_or_create(name=allocation_name)

    if 'serial' in kwargs:
        serial = kwargs.pop('serial')
    else:
        serial = random_str()
        while System.objects.filter(serial=serial).exists():
            type_name = random_str()

    save = kwargs.pop('save', True)

    s = System(allocation=allocation,
               serial=serial,
               system_type=system_type,
               warranty_start=datetime.datetime.now(),
               warranty_end=datetime.datetime.now(),
               **kwargs)

    if save:
        s.save()
    return s
    def setUp(self):
        self.g = create_fake_zone("gz", suffix="")
        self.c_g = create_fake_zone("coo.gz", suffix="")
        self.d = create_fake_zone("dz", suffix="")

        self.r1 = create_fake_zone("10.in-addr.arpa", suffix="")
        self.r1.save()

        self.s = System()
        self.s.save()
Exemple #12
0
 def service_import_set_systems(self, hostnames):
     # Note: Make sure to call save() after calling this function
     self.systems.clear()
     for hostname in hostnames:
         try:
             system = System.objects.get(hostname=hostname)
         except System.DoesNotExist:
             raise System.DoesNotExist(
                 "The system with hostname '{0}' does not "
                 "exist".format(hostname))
         self.systems.add(system)
Exemple #13
0
    def service_import_set_site(self, site_name):
        try:
            if not site_name or site_name.title() == 'None':
                site = None
            else:
                site = Site.objects.get(full_name=site_name)
        except Site.DoesNotExist:
            raise System.DoesNotExist(
                "The site with name '{0}' does not exist".format(site_name))

        self.site = site
    def set_kv(self, key, value):
        key_str = "nic.{0}.{1}.{2}".format(self.primary, key, self.alias)
        kv = self.obj.keyvalue_set.filter(key=key_str)
        if kv:
            kv = kv[0]
            kv.value = value
            kv.save()
        else:
            kv = System.KeyValue(key=key_str, value=str(value))
            kv.save()

        setattr(self, key, value)
        return
def system_import(blob):
    if 'pk' in blob:
        try:
            system = System.objects.get(pk=blob['pk'])
            return system_update(system, blob)
        except System.DoesNotExist:
            raise BadImportData(
                bad_blob=blob,
                msg='Could not find the System with primary key '
                '{0}.'.format(blob['pk']))
    else:
        recurse_confirm_no_pk(blob)
        system = System()
        return system_update(system, blob)
    def test2(self):
        ip_start = "10.0.1.0"
        ip_end = "10.0.1.99"
        ptr = PTR(name="foo.mz", ip_str="10.0.1.3", ip_type='4')
        ptr.full_clean()
        ptr.save()

        a = AddressRecord(label="foo", domain=self.domain, ip_str="10.0.1.3",
                          ip_type='4')
        a.full_clean()
        a.save()

        s = System()
        s.save()
        intr = StaticInterface(
            label="foo", domain=self.domain, ip_str="10.0.1.4",
            ip_type='4', system=s, mac="00:11:22:33:44:55")
        intr.full_clean()
        intr.save()

        istart, iend, ipf_q = start_end_filter(ip_start, ip_end, '4')
        addrs = list(AddressRecord.objects.filter(ipf_q).
                     order_by('ip_lower').order_by('ip_upper'))
        ptrs = list(PTR.objects.filter(ipf_q).
                    order_by('ip_lower').order_by('ip_upper'))
        intrs = list(StaticInterface.objects.filter(ipf_q).
                     order_by('ip_lower').order_by('ip_upper'))
        self.assertEqual(a.pk, addrs[0].pk)
        self.assertEqual(ptr.pk, ptrs[0].pk)
        self.assertEqual(intr.pk, intrs[0].pk)

        range_details = range_usage(ip_start, ip_end, '4')
        self.assertEqual(98, range_details['unused'])
        self.assertEqual(2, range_details['used'])
        self.assertEqual([(int(istart) + 0, int(istart) + 2),
                          (int(istart) + 5, int(istart) + 99)],
                         range_details['free_ranges'])
Exemple #17
0
def bulk_action_export(request):
    search = request.GET.get('q', '')
    if not search:
        return HttpResponse(dumps({'errors': 'what do you want?'}))
    q_map, errors = compile_to_q(search)
    if errors:
        return HttpResponse(dumps({'errors': errors}))

    try:  # We might have to catch shitty regular expressions
        bundles = System.get_bulk_action_list(q_map['SYS'])
    except OperationalError as why:
        return HttpResponse(dumps({'error_messages': str(why)}))

    pprint.pprint(bundles)
    return HttpResponse(dumps({'systems': bundles}))
Exemple #18
0
def bulk_action_export(request):
    search = request.GET.get('q', '')
    if not search:
        return HttpResponse(dumps({'errors': 'what do you want?'}))
    q_map, errors = compile_to_q(search)
    if errors:
        return HttpResponse(dumps({'errors': errors}))

    try:  # We might have to catch shitty regular expressions
        bundles = System.get_bulk_action_list(q_map['SYS'])
    except OperationalError as why:
        return HttpResponse(dumps({'error_messages': str(why)}))

    pprint.pprint(bundles)
    return HttpResponse(dumps({'systems': bundles}))
    def setUp(self):
        self.arpa = self.create_domain(name='arpa')
        self.arpa.save()
        self.i_arpa = self.create_domain(name='in-addr.arpa')
        self.i_arpa.save()

        self.c = Domain(name="ccc")
        self.c.save()
        self.f_c = Domain(name="foo.ccc")
        self.f_c.save()
        self.r1 = self.create_domain(name="10")
        self.r1.save()
        self.n = System()
        self.n.clean()
        self.n.save()
Exemple #20
0
    def import_services(cls, services):
        """
        Import a json blob that has the same format generated by the
        Service.export_services function. This function may raise a
        System.DoesNotExist, Service.DoesNotExist, ValueError, or
        Site.DoesNotExist excpetion. The caller should handle these accordingly

        This function does not manage transactions itself but should probably
        be ran in a transaction
        """
        for service_blob in services:
            try:
                site = service_blob.get('site', None)
                if site:
                    site = Site.objects.get(full_name=site)
                if 'pk' in service_blob:
                    service = Service.objects.get(pk=service_blob['pk'])
                else:
                    service, created = Service.objects.get_or_create(
                        name=service_blob.get('name', ''), site=site)
            except Service.DoesNotExist:
                raise Service.DoesNotExist(
                    "The service with pk '{0}' does not "
                    "exist".format(service_blob['pk']))
            except Site.DoesNotExist:
                raise System.DoesNotExist(
                    "The service with name '{0}' is asking for a site '{1}' "
                    "that does not exist".format(
                        service_blob.get('name', 'None'),
                        service_blob.get('site', 'None')))

            # set all the fields on the service we are importing
            for field, value in service_blob.iteritems():
                if field == 'systems':
                    service.service_import_set_systems(value)
                elif field == 'parent_service':
                    service.service_import_set_parent_service(value)
                elif field == 'site':
                    service.service_import_set_site(value)
                elif field == 'pk':
                    # lets not let the user shoot themselves in the foot
                    continue
                elif field == 'depends_on':
                    service.service_import_set_depends_on(value)
                else:
                    service.service_import_set_field(field, value)

            service.save()
    def setUp(self):
        self.arpa = self.create_domain(name='arpa')
        self.arpa.save()
        self.i_arpa = self.create_domain(name='in-addr.arpa')
        self.i_arpa.save()

        self.c = Domain(name="ccc")
        self.c.save()
        self.f_c = Domain(name="foo.ccc")
        self.f_c.save()
        self.r1 = self.create_domain(name="10")
        self.r1.save()
        self.n = System()
        self.n.clean()
        self.n.save()
        View.objects.get_or_create(name="private")
    def setUp(self):
        self.arpa = self.create_domain(name='arpa')
        self.arpa.save()
        self.i_arpa = self.create_domain(name='ip6.arpa', ip_type='6')
        self.i_arpa.save()

        self.c = Domain(name="ccc")
        self.c.save()
        self.f_c = Domain(name="foo.ccc")
        self.f_c.save()
        self.r1 = self.create_domain(name="0", ip_type='6')
        self.r1.save()
        self.r2 = self.create_domain(name="1", ip_type='6')
        self.r2.save()
        self.n = System()
        self.n.clean()
        self.n.save()
    def setUp(self):
        self.r1 = create_fake_zone("10.in-addr.arpa", suffix="")
        self.sr = self.r1.soa
        self.sr.dirty = False
        self.sr.save()

        self.dom = create_fake_zone("bgaz", suffix="")
        self.soa = self.dom.soa
        self.soa.dirty = False
        self.soa.save()

        self.rdom = create_fake_zone("123.in-addr.arpa", suffix="")
        self.rsoa = self.r1.soa
        self.rsoa.dirty = False
        self.rsoa.save()

        self.s = System()
        self.s.save()
    def setUp(self):
        self.factory = RequestFactory()
        self.arpa = self.create_domain(name='arpa')
        self.arpa.save()
        self.i_arpa = self.create_domain(name='in-addr.arpa')
        self.i_arpa.save()
        self.i6_arpa = self.create_domain(name='ip6.arpa')
        self.i6_arpa.save()

        self.r = Domain(name="ru")
        self.r.save()
        self.f_r = Domain(name="foo.ru")
        self.f_r.save()
        self.b_f_r = Domain(name="bar.foo.ru")
        self.b_f_r.save()

        self.f = Domain(name="fam")
        self.f.save()

        self._128 = self.create_domain(name='128', ip_type='4')
        self._128.save()

        self.s = System()
        self.s.save()
class AuxAttrTests(TestCase):
    def create_domain(self, name, ip_type=None, delegated=False):
        if ip_type is None:
            ip_type = '4'
        if name in ('arpa', 'in-addr.arpa', 'ip6.arpa'):
            pass
        else:
            name = ip_to_domain_name(name, ip_type=ip_type)
        d = Domain(name=name, delegated=delegated)
        d.clean()
        self.assertTrue(d.is_reverse)
        return d

    def setUp(self):
        self.arpa = self.create_domain(name='arpa')
        self.arpa.save()
        self.i_arpa = self.create_domain(name='in-addr.arpa')
        self.i_arpa.save()

        self.c = Domain(name="ccc")
        self.c.save()
        self.f_c = Domain(name="foo.ccc")
        self.f_c.save()
        self.r1 = self.create_domain(name="10")
        self.r1.save()
        self.n = System()
        self.n.clean()
        self.n.save()

    def do_add(self, mac, label, domain, ip_str, ip_type='4'):
        self.n = System()
        r = StaticInterface(mac=mac, label=label, domain=domain, ip_str=ip_str,
                            ip_type=ip_type, system=self.n)
        r.clean()
        r.save()
        repr(r)
        return r

    def do_delete(self, r):
        ip_str = r.ip_str
        fqdn = r.fqdn
        r.delete()
        self.assertFalse(
            AddressRecord.objects.filter(ip_str=ip_str, fqdn=fqdn))

    def test1_create(self):
        mac = "11:22:33:44:55:66"
        label = "foo"
        domain = self.f_c
        ip_str = "10.0.0.2"
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        intr = self.do_add(**kwargs)
        intr.update_attrs()

        def bad_get():
            intr.attrs.primary
        self.assertRaises(AttributeError, bad_get)
        x = StaticIntrKeyValue.objects.filter(key='primary', obj=intr)
        self.assertFalse(x)
        intr.attrs.primary = '1'
        self.assertEqual(intr.attrs.cache['primary'], '1')
        self.assertEqual(intr.attrs.primary, '1')
        x = StaticIntrKeyValue.objects.filter(key='primary', obj=intr)
        self.assertEqual(x[0].value, '1')

    def test6_create(self):
        mac = "24:22:33:44:55:66"
        label = "foo"
        domain = self.f_c
        ip_str = "10.0.0.2"
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        intr = self.do_add(**kwargs)
        intr.update_attrs()
        intr.update_attrs()
        intr.update_attrs()

        def bad_get():
            intr.attrs.primary
        self.assertRaises(AttributeError, bad_get)
        intr.attrs.primary = '1'
        self.assertEqual(intr.attrs.primary, '1')
        self.assertEqual(intr.attrs.cache['primary'], '1')

    def test2_create(self):
        mac = "13:22:33:44:55:66"
        label = "foo"
        domain = self.f_c
        ip_str = "10.0.0.2"
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        intr = self.do_add(**kwargs)
        intr.update_attrs()
        intr.attrs.primary = '2'
        self.assertEqual(intr.attrs.primary, '2')
        self.assertEqual(intr.attrs.cache['primary'], '2')
        del intr.attrs.primary

        def bad_get():
            intr.attrs.primary
        self.assertRaises(AttributeError, bad_get)
        intr.attrs.primary = '3'
        self.assertEqual(intr.attrs.primary, '3')
        self.assertEqual(intr.attrs.cache['primary'], '3')

    def test1_del(self):
        mac = "12:22:33:44:55:66"
        label = "foo"
        domain = self.f_c
        ip_str = "10.0.0.2"
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        intr = self.do_add(**kwargs)
        intr.update_attrs()
        intr.attrs.primary = '88'
        self.assertEqual(intr.attrs.primary, '88')
        del intr.attrs.primary

        def bad_get():
            intr.attrs.primary
        self.assertRaises(AttributeError, bad_get)

    def test3_create(self):
        mac = "19:22:33:44:55:66"
        label = "foo"
        domain = self.f_c
        ip_str = "10.0.0.2"
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        intr = self.do_add(**kwargs)
        intr.update_attrs()

        def bad_assign():
            intr.attrs.primary = 'a'
        self.assertRaises(ValidationError, bad_assign)

    def test1_existing_attrs(self):
        mac = "19:22:33:44:55:66"
        label = "foo"
        domain = self.f_c
        ip_str = "10.0.0.2"
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        intr = self.do_add(**kwargs)
        StaticIntrKeyValue(key="foo", value="bar", obj=intr).save()
        StaticIntrKeyValue(
            key="interface_type", value="eth0", obj=intr).save()
        StaticIntrKeyValue(key="alias", value="5", obj=intr).save()
        intr.update_attrs()
        self.assertEqual(intr.attrs.alias, '5')
        self.assertEqual(intr.attrs.cache['alias'], '5')
        self.assertEqual(intr.attrs.interface_type, 'eth0')
        self.assertEqual(intr.attrs.cache['interface_type'], 'eth0')
        self.assertEqual(intr.attrs.foo, 'bar')
        self.assertEqual(intr.attrs.cache['foo'], 'bar')
class DirtySOATests(TestCase):
    def setUp(self):
        self.r1 = create_fake_zone("10.in-addr.arpa", suffix="")
        self.sr = self.r1.soa
        self.sr.dirty = False
        self.sr.save()

        self.dom = create_fake_zone("bgaz", suffix="")
        self.soa = self.dom.soa
        self.soa.dirty = False
        self.soa.save()

        self.rdom = create_fake_zone("123.in-addr.arpa", suffix="")
        self.rsoa = self.r1.soa
        self.rsoa.dirty = False
        self.rsoa.save()

        self.s = System()
        self.s.save()

    def test_print_soa(self):
        self.assertTrue(self.soa.bind_render_record() not in ('', None))
        self.assertTrue(self.rsoa.bind_render_record() not in ('', None))

    def generic_dirty(self, Klass, create_data, update_data, local_soa):
        Task.dns.all().delete()  # Delete all tasks
        local_soa.dirty = False
        local_soa.save()
        rec = Klass(**create_data)
        rec.full_clean()
        rec.save()
        self.assertTrue(rec.bind_render_record() not in ('', None))
        local_soa = SOA.objects.get(pk=local_soa.pk)
        self.assertTrue(local_soa.dirty)

        self.assertEqual(1, Task.dns.all().count())

        # Now try updating
        Task.dns.all().delete()  # Delete all tasks
        local_soa.dirty = False
        local_soa.save()
        local_soa = SOA.objects.get(pk=local_soa.pk)
        self.assertFalse(local_soa.dirty)
        for k, v in update_data.iteritems():
            setattr(rec, k, v)
        rec.save()
        local_soa = SOA.objects.get(pk=local_soa.pk)
        self.assertTrue(local_soa.dirty)

        self.assertEqual(1, Task.dns.all().count())

        # Now delete
        Task.dns.all().delete()  # Delete all tasks
        local_soa.dirty = False
        local_soa.save()
        local_soa = SOA.objects.get(pk=local_soa.pk)
        self.assertFalse(local_soa.dirty)
        rec.delete()
        local_soa = SOA.objects.get(pk=local_soa.pk)
        self.assertTrue(local_soa.dirty)

        self.assertEqual(1, Task.dns.all().count())

    def test_dirty_a(self):
        create_data = {
            'label': 'asdf',
            'domain': self.dom,
            'ip_str': '10.2.3.1',
            'ip_type': '4'
        }
        update_data = {
            'label': 'asdfx',
        }
        self.generic_dirty(AddressRecord, create_data, update_data, self.soa)

    def test_dirty_intr(self):
        create_data = {
            'label': 'asdf1',
            'domain': self.dom,
            'ip_str': '10.2.3.1',
            'ip_type': '4',
            'system': self.s,
            'mac': '11:22:33:44:55:66'
        }
        update_data = {
            'label': 'asdfx1',
        }
        self.generic_dirty(StaticInterface, create_data, update_data, self.soa)

    def test_dirty_cname(self):
        create_data = {
            'label': 'asdf2',
            'domain': self.dom,
            'target': 'foo.bar.com',
        }
        update_data = {
            'label': 'asdfx2',
        }
        self.generic_dirty(CNAME, create_data, update_data, self.soa)

    def test_dirty_ptr(self):
        create_data = {
            'ip_str': '10.2.3.4',
            'ip_type': '4',
            'name': 'foo.bar.com',
        }
        update_data = {
            'label': 'asdfx2',
        }
        self.generic_dirty(PTR, create_data, update_data, local_soa=self.sr)

    def test_dirty_mx(self):
        create_data = {
            'label': '',
            'domain': self.dom,
            'priority': 10,
            'server': 'foo.bar.com',
        }
        update_data = {
            'label': 'asdfx3',
        }
        self.generic_dirty(MX, create_data, update_data, self.soa)

    def test_dirty_ns(self):
        create_data = {
            'domain': self.dom,
            'server': 'foo.bar.com',
        }
        update_data = {
            'label': 'asdfx4',
        }
        self.generic_dirty(Nameserver, create_data, update_data, self.soa)

    def test_dirty_soa(self):
        self.soa.dirty = False
        self.soa.refresh = 123
        self.soa.save()
        self.assertTrue(self.soa.dirty)

    def test_dirty_srv(self):
        create_data = {
            'label': '_asdf7',
            'domain': self.dom,
            'priority': 10,
            'port': 10,
            'weight': 10,
            'target': 'foo.bar.com',
        }
        update_data = {
            'label': '_asdfx4',
        }
        self.generic_dirty(SRV, create_data, update_data, self.soa)

    def test_dirty_txt(self):
        create_data = {
            'label': 'asdf8',
            'domain': self.dom,
            'txt_data': 'some shit',
        }
        update_data = {
            'label': 'asdfx5',
        }
        self.generic_dirty(TXT, create_data, update_data, self.soa)
 class Meta:
     queryset = System.objects.all()
     fields = System.get_api_fields()
     always_return_data = True
     authorization = Authorization()
     allowed_methods = allowed_methods
class CNAMETests(TestCase):

    def create_domain(self, name, ip_type=None, delegated=False):
        if ip_type is None:
            ip_type = '4'
        if name in ('arpa', 'in-addr.arpa', 'ip6.arpa'):
            pass
        else:
            name = ip_to_domain_name(name, ip_type=ip_type)
        d = Domain(name=name, delegated=delegated)
        d.clean()
        self.assertTrue(d.is_reverse)
        return d

    def setUp(self):
        self.g = create_fake_zone("gz", suffix="")
        self.c_g = create_fake_zone("coo.gz", suffix="")
        self.d = create_fake_zone("dz", suffix="")

        self.r1 = create_fake_zone("10.in-addr.arpa", suffix="")
        self.r1.save()

        self.s = System()
        self.s.save()

    def do_add(self, label, domain, data):
        cn = CNAME(label=label, domain=domain, target=data)
        cn.full_clean()
        cn.save()
        cn.save()
        self.assertTrue(cn.get_absolute_url())
        self.assertTrue(cn.get_edit_url())
        self.assertTrue(cn.get_delete_url())
        self.assertTrue(cn.details())

        cs = CNAME.objects.filter(
            label=label, domain=domain, target=data)
        self.assertEqual(len(cs), 1)
        return cn

    def test_add(self):
        label = "foo"
        domain = self.g
        data = "foo.com"
        self.do_add(label, domain, data)

        label = "boo"
        domain = self.c_g
        data = "foo.foo.com"
        self.do_add(label, domain, data)

        label = "fo1"
        domain = self.g
        data = "foo.com"
        self.do_add(label, domain, data)
        self.assertRaises(ValidationError, self.do_add, *(label, domain, data))

        label = "adsf"
        domain = self.c_g
        data = "foo.com"
        self.do_add(label, domain, data)

    def test1_add_glob(self):
        label = "*foo"
        domain = self.g
        data = "foo.com"
        self.do_add(label, domain, data)

        label = "*"
        domain = self.c_g
        data = "foo.foo.com"
        self.do_add(label, domain, data)

        label = "*.fo1"
        domain = self.g
        data = "foo.com"
        self.assertRaises(ValidationError, self.do_add, *(label, domain, data))

        label = "*sadfasfd-asdf"
        domain = self.g
        data = "foo.com"
        self.do_add(label, domain, data)

    def test2_add_glob(self):
        label = "*coo"
        domain = self.g
        data = "foo.com"
        self.do_add(label, domain, data)

        label = "*"
        domain = self.c_g
        data = "foo.com"
        self.do_add(label, domain, data)

    def test_soa_condition(self):
        label = ""
        domain = self.c_g
        data = "foo.com"
        self.assertRaises(ValidationError, self.do_add, *(label, domain, data))

    def test_add_bad(self):
        label = ""
        domain = self.g
        data = "..foo.com"
        self.assertRaises(ValidationError, self.do_add, *(label, domain, data))

    def test_add_mx_with_cname(self):
        label = "cnamederp1"
        domain = self.c_g
        data = "foo.com"

        fqdn = label + '.' + domain.name
        mx_data = {'label': '', 'domain': self.c_g, 'server':
                   fqdn, 'priority': 2, 'ttl': 2222}
        mx = MX(**mx_data)
        mx.save()

        cn = CNAME(label=label, domain=domain, target=data)

        self.assertRaises(ValidationError, cn.full_clean)

    def test_address_record_exists(self):
        label = "testyfoo"
        data = "wat"
        dom, _ = Domain.objects.get_or_create(name="cd")
        dom, _ = Domain.objects.get_or_create(name="what.cd")

        rec, _ = AddressRecord.objects.get_or_create(
            label=label, domain=dom, ip_type='4', ip_str="128.193.1.1")

        cn = CNAME(label=label, domain=dom, target=data)
        self.assertRaises(ValidationError, cn.full_clean)

    def test_address_record_exists_upper_case(self):
        label = "testyfoo"
        data = "wat"
        dom, _ = Domain.objects.get_or_create(name="cd")
        dom, _ = Domain.objects.get_or_create(name="what.cd")

        rec, _ = AddressRecord.objects.get_or_create(
            label=label, domain=dom, ip_type='4', ip_str="128.193.1.1")

        cn = CNAME(label=label.title(), domain=dom, target=data)
        self.assertRaises(ValidationError, cn.full_clean)

    def test_address_record_cname_exists(self):
        label = "testyfoo"
        data = "wat"
        dom, _ = Domain.objects.get_or_create(name="cd")
        dom, _ = Domain.objects.get_or_create(name="what.cd")

        CNAME.objects.get_or_create(label=label, domain=dom, target=data)
        rec = AddressRecord(label=label, domain=dom, ip_str="128.193.1.1")

        self.assertRaises(ValidationError, rec.save)

    def test_address_record_cname_exists_upper(self):
        label = "testyfoo"
        data = "wat"
        dom, _ = Domain.objects.get_or_create(name="cd")
        dom, _ = Domain.objects.get_or_create(name="what.cd")

        CNAME.objects.get_or_create(label=label, domain=dom, target=data)
        rec = AddressRecord(
            label=label.title(), domain=dom, ip_str="128.193.1.1")

        self.assertRaises(ValidationError, rec.save)

    def test_srv_exists(self):
        label = "_testyfoo"
        data = "wat"
        dom, _ = Domain.objects.get_or_create(name="cd")
        dom, _ = Domain.objects.get_or_create(name="what.cd")

        rec, _ = SRV.objects.get_or_create(
            label=label, domain=dom, target="asdf",
                                            port=2, priority=2, weight=4)

        cn = CNAME(label=label, domain=dom, target=data)
        self.assertRaises(ValidationError, cn.full_clean)

    def test_srv_cname_exists(self):
        label = "testyfoo"
        data = "wat"
        dom, _ = Domain.objects.get_or_create(name="cd")
        dom, _ = Domain.objects.get_or_create(name="what.cd")

        CNAME.objects.get_or_create(
            label=label, domain=dom, target=data)

        rec = SRV(label=label, domain=dom, target="asdf",
                  port=2, priority=2, weight=4)

        self.assertRaises(ValidationError, rec.save)

    def test_txt_exists(self):
        label = "testyfoo"
        data = "wat"
        dom, _ = Domain.objects.get_or_create(name="cd")
        dom, _ = Domain.objects.get_or_create(name="what.cd")

        rec, _ = TXT.objects.get_or_create(
            label=label, domain=dom, txt_data="asdf")

        cn = CNAME(label=label, domain=dom, target=data)
        self.assertRaises(ValidationError, cn.full_clean)

    def test_txt_cname_exists(self):
        label = "testyfoo"
        data = "wat"
        dom, _ = Domain.objects.get_or_create(name="cd")
        dom, _ = Domain.objects.get_or_create(name="what.cd")

        cn, _ = CNAME.objects.get_or_create(
            label=label, domain=dom, target=data)
        cn.full_clean()
        cn.save()

        rec = TXT(label=label, domain=dom, txt_data="asdf1")

        self.assertRaises(ValidationError, rec.save)

    def test_mx_exists(self):
        label = "testyfoo"
        data = "wat"
        dom, _ = Domain.objects.get_or_create(name="cd")
        dom, _ = Domain.objects.get_or_create(name="what.cd")

        rec, _ = MX.objects.get_or_create(
            label=label, domain=dom, server="asdf",
                                            priority=123, ttl=123)

        cn = CNAME(label=label, domain=dom, target=data)
        self.assertRaises(ValidationError, cn.full_clean)

    def test_mx_cname_exists(self):
        # Duplicate test?
        label = "testyfoo"
        data = "wat"
        dom, _ = Domain.objects.get_or_create(name="cd")
        dom, _ = Domain.objects.get_or_create(name="what.cd")

        cn, _ = CNAME.objects.get_or_create(
            label=label, domain=dom, target=data)
        cn.full_clean()
        cn.save()

        rec = MX(label=label, domain=dom, server="asdf1",
                 priority=123, ttl=123)

        self.assertRaises(ValidationError, rec.save)

    def test_ns_exists(self):
        # Duplicate test?
        data = "wat"
        dom, _ = Domain.objects.get_or_create(name="cd")
        dom, _ = Domain.objects.get_or_create(name="what.cd")

        rec = Nameserver(domain=dom, server="asdf1")
        rec.save()
        cn = CNAME(label='', domain=dom, target=data)
        self.assertRaises(ValidationError, cn.clean)

    def test_ns_cname_exists(self):
        # Duplicate test?
        data = "wat"
        dom, _ = Domain.objects.get_or_create(name="cd")
        dom, _ = Domain.objects.get_or_create(name="what.cd")

        cn, _ = CNAME.objects.get_or_create(
            label='', domain=dom, target=data)
        cn.full_clean()
        cn.save()

        rec = Nameserver(domain=dom, server="asdf1")
        self.assertRaises(ValidationError, rec.save)

    def test_intr_exists(self):
        label = "tdfestyfoo"
        data = "waasdft"
        dom, _ = Domain.objects.get_or_create(name="cd")
        dom, _ = Domain.objects.get_or_create(name="what.cd")

        intr = StaticInterface(label=label, domain=dom, ip_str="10.0.0.1",
                               ip_type='4', system=self.s,
                               mac="11:22:33:44:55:66")
        intr.clean()
        intr.save()

        cn = CNAME(label=label, domain=dom, target=data)
        self.assertRaises(ValidationError, cn.full_clean)

    def test_intr_cname_exists(self):
        # Duplicate test?
        label = "tesafstyfoo"
        data = "wadfakt"
        dom, _ = Domain.objects.get_or_create(name="cd")
        dom, _ = Domain.objects.get_or_create(name="what.cd")

        cn, _ = CNAME.objects.get_or_create(
            label=label, domain=dom, target=data)
        cn.full_clean()
        cn.save()

        intr = StaticInterface(label=label, domain=dom, ip_str="10.0.0.2",
                               ip_type='4', system=self.s,
                               mac="00:11:22:33:44:55")

        self.assertRaises(ValidationError, intr.clean)
        cn.label = "differentlabel"
        cn.save()
        intr.clean()
        intr.save()

    def test_ptr_exists(self):
        """
        Failing:
        see BUG https://bugzilla.mozilla.org/show_bug.cgi?id=810106
        """
        label = "testyfoo"
        data = "wat"
        dom, _ = Domain.objects.get_or_create(name="cd")
        dom, _ = Domain.objects.get_or_create(name="what.cd")

        rec = PTR(ip_str="10.193.1.1", ip_type='4', name='testyfoo.what.cd')
        rec.full_clean()
        rec.save()

        cn = CNAME(label=label, domain=dom, target=data)
        self.assertRaises(ValidationError, cn.full_clean)

    def test_ptr_cname_exists(self):
        """
        Failing:
        see BUG https://bugzilla.mozilla.org/show_bug.cgi?id=810106
        """
        label = "testyfoo"
        data = "wat"
        dom, _ = Domain.objects.get_or_create(name="cd")
        dom, _ = Domain.objects.get_or_create(name="what.cd")

        CNAME.objects.get_or_create(label=label, domain=dom, target=data)
        rec = PTR(ip_str="10.193.1.1", ip_type='4', name='testyfoo.what.cd')

        self.assertRaises(ValidationError, rec.clean)

    def test_cname_point_to_itself(self):
        label = "foopy"
        data = "foopy.what.cd"
        dom, _ = Domain.objects.get_or_create(name="cd")
        dom, _ = Domain.objects.get_or_create(name="what.cd")

        cn = CNAME(label=label, domain=dom, target=data)
        self.assertRaises(ValidationError, cn.clean)
class NSTestsModels(TestCase):
    def create_domain(self, name, ip_type=None, delegated=False):
        if ip_type is None:
            ip_type = '4'
        if name in ('arpa', 'in-addr.arpa', 'ip6.arpa'):
            pass
        else:
            name = ip_to_domain_name(name, ip_type=ip_type)
        d = Domain(name=name, delegated=delegated)
        d.clean()
        self.assertTrue(d.is_reverse)
        return d

    def setUp(self):
        self.factory = RequestFactory()
        self.arpa = self.create_domain(name='arpa')
        self.arpa.save()
        self.i_arpa = self.create_domain(name='in-addr.arpa')
        self.i_arpa.save()
        self.i6_arpa = self.create_domain(name='ip6.arpa')
        self.i6_arpa.save()

        self.r = Domain(name="ru")
        self.r.save()
        self.f_r = Domain(name="foo.ru")
        self.f_r.save()
        self.b_f_r = Domain(name="bar.foo.ru")
        self.b_f_r.save()

        self.f = Domain(name="fam")
        self.f.save()

        self._128 = self.create_domain(name='128', ip_type='4')
        self._128.save()

        self.s = System()
        self.s.save()

    def do_add(self, domain, server):
        ns = Nameserver(domain=domain, server=server)
        ns.save()
        self.assertTrue(ns.__repr__())
        self.assertTrue(ns.details())
        self.assertTrue(ns.get_absolute_url())
        self.assertTrue(ns.get_edit_url())
        self.assertTrue(ns.get_delete_url())
        ret = Nameserver.objects.filter(domain=domain, server=server)
        self.assertEqual(len(ret), 1)
        return ns

    def test_add_ns(self):
        data = {'domain': self.r, 'server': 'ns2.moot.ru'}
        self.do_add(**data)

        data = {'domain': self.r, 'server': 'ns5.moot.ru'}
        self.do_add(**data)

        data = {'domain': self.r, 'server': u'ns3.moot.ru'}
        self.do_add(**data)

        data = {'domain': self.b_f_r, 'server': 'n1.moot.ru'}
        self.do_add(**data)

        data = {'domain': self.b_f_r, 'server': 'ns2.moot.ru'}
        self.do_add(**data)

        data = {'domain': self.r, 'server': 'asdf.asdf'}
        self.do_add(**data)

    def test_add_invalid(self):
        data = {'domain': self.f_r, 'server': 'ns3.foo.ru'}
        self.assertRaises(ValidationError, self.do_add, **data)

        data = {'domain': self.f_r, 'server': ''}
        self.assertRaises(ValidationError, self.do_add, **data)

    def test_add_ns_in_domain(self):
        # Use an A record as a glue record.
        glue = AddressRecord(label='ns2', domain=self.r,
                             ip_str='128.193.1.10', ip_type='4')
        glue.clean()
        glue.save()
        data = {'domain': self.r, 'server': 'ns2.ru'}
        ns = self.do_add(**data)
        self.assertTrue(ns.glue)
        self.assertEqual(ns.server, ns.glue.fqdn)
        self.assertRaises(ValidationError, glue.delete)

        glue = AddressRecord(label='ns3', domain=self.f_r, ip_str=
                             '128.193.1.10', ip_type='4')
        glue.save()
        data = {'domain': self.f_r, 'server': 'ns3.foo.ru'}
        ns = self.do_add(**data)
        self.assertTrue(ns.glue)
        self.assertEqual(ns.server, ns.glue.fqdn)

    def test_disallow_name_update_of_glue_A(self):
        # Glue records should not be allowed to change their name.
        glue = AddressRecord(label='ns39', domain=self.f_r, ip_str=
                             '128.193.1.77', ip_type='4')
        glue.clean()
        glue.save()
        data = {'domain': self.f_r, 'server': 'ns39.foo.ru'}
        ns = self.do_add(**data)
        self.assertTrue(ns.glue)
        self.assertEqual(ns.glue, glue)

        glue.label = "ns22"
        self.assertRaises(ValidationError, glue.clean)

    def test_disallow_name_update_of_glue_Intr(self):
        # Glue records should not be allowed to change their name.
        glue = StaticInterface(label='ns24', domain=self.f_r, ip_str=
                               '128.193.99.10', ip_type='4', system=self.s,
                               mac="11:22:33:44:55:66")
        glue.clean()
        glue.save()
        data = {'domain': self.f_r, 'server': 'ns24.foo.ru'}
        ns = self.do_add(**data)
        self.assertTrue(ns.glue)
        self.assertEqual(ns.glue, glue)

        glue.label = "ns22"
        self.assertRaises(ValidationError, glue.clean)

    def test_disallow_delete_of_glue_intr(self):
        # Interface glue records should not be allowed to be deleted.
        glue = StaticInterface(label='ns24', domain=self.f_r, ip_str=
                               '128.193.99.10', ip_type='4', system=self.s,
                               mac="11:22:33:44:55:66")
        glue.clean()
        glue.save()
        data = {'domain': self.f_r, 'server': 'ns24.foo.ru'}
        ns = self.do_add(**data)
        self.assertTrue(ns.glue)
        self.assertEqual(ns.glue, glue)

        self.assertRaises(ValidationError, glue.delete)

    def test_manual_assign_of_glue(self):
        # Test that assigning a different glue record doesn't get overriden by
        # the auto assinging during the Nameserver's clean function.
        glue = StaticInterface(label='ns25', domain=self.f_r, ip_str=
                               '128.193.99.10', ip_type='4', system=self.s,
                               mac="11:22:33:44:55:66")
        glue.clean()
        glue.save()
        data = {'domain': self.f_r, 'server': 'ns25.foo.ru'}
        ns = self.do_add(**data)
        self.assertTrue(ns.glue)
        self.assertEqual(ns.glue, glue)

        glue2 = AddressRecord(label='ns25', domain=self.f_r, ip_str=
                              '128.193.1.78', ip_type='4')
        glue2.clean()
        glue2.save()

        ns.clean()

        # Make sure things didn't get overriden.
        self.assertEqual(ns.glue, glue)

        ns.glue = glue2
        ns.save()
        # Refresh the object
        ns = Nameserver.objects.get(pk=ns.pk)
        # Again, Make sure things didn't get overriden.
        self.assertEqual(ns.glue, glue2)
        # Make sure we still can't delete.
        self.assertRaises(ValidationError, glue2.delete)
        self.assertRaises(ValidationError, ns.glue.delete)

        # We shuold be able to delelte the other one.
        glue.delete()

    def test_add_ns_in_domain_intr(self):
        # Use an Interface as a glue record.
        glue = StaticInterface(label='ns232', domain=self.r, ip_str=
                               '128.193.99.10', ip_type='4', system=self.s,
                               mac="12:23:45:45:45:45")
        glue.clean()
        glue.save()
        data = {'domain': self.r, 'server': 'ns232.ru'}
        ns = self.do_add(**data)
        self.assertTrue(ns.glue)
        self.assertEqual(ns.server, ns.glue.fqdn)
        self.assertRaises(ValidationError, glue.delete)

        glue = StaticInterface(label='ns332', domain=self.f_r, ip_str=
                               '128.193.1.10', ip_type='4', system=self.s,
                               mac="11:22:33:44:55:66")
        glue.clean()
        glue.save()
        data = {'domain': self.f_r, 'server': 'ns332.foo.ru'}
        ns = self.do_add(**data)
        self.assertTrue(ns.glue)
        self.assertEqual(ns.server, ns.glue.fqdn)

    def test_add_ns_outside_domain(self):
        data = {'domain': self.f_r, 'server': 'ns2.ru'}
        ns = self.do_add(**data)
        self.assertFalse(ns.glue)

    def test_update_glue_to_no_intr(self):
        glue = StaticInterface(label='ns34', domain=self.r, ip_str=
                               '128.193.1.10', ip_type='4', system=self.s,
                               mac="11:22:33:44:55:66")
        glue.save()
        data = {'domain': self.r, 'server': 'ns34.ru'}
        ns = self.do_add(**data)
        self.assertTrue(ns.glue)

        ns.server = "ns4.wee"
        ns.save()
        self.assertTrue(ns.glue is None)

    def test_update_glue_record_intr(self):
        # Glue records can't change their name.
        glue = StaticInterface(label='ns788', domain=self.r, ip_str=
                               '128.193.1.10', ip_type='4', system=self.s,
                               mac="11:22:33:44:55:66")
        glue.save()
        data = {'domain': self.r, 'server': 'ns788.ru'}
        ns = self.do_add(**data)
        self.assertTrue(ns.glue)
        glue.label = "asdfasdf"
        self.assertRaises(ValidationError, glue.clean)

    def test_update_glue_to_no_glue(self):
        glue = AddressRecord(label='ns3', domain=self.r,
                             ip_str='128.193.1.10', ip_type='4')
        glue.save()
        data = {'domain': self.r, 'server': 'ns3.ru'}
        ns = self.do_add(**data)
        self.assertTrue(ns.glue)

        ns.server = "ns4.wee"
        ns.save()
        self.assertTrue(ns.glue is None)

    def test_delete_ns(self):
        glue = AddressRecord(label='ns4', domain=self.f_r,
                             ip_str='128.196.1.10', ip_type='4')
        glue.save()
        data = {'domain': self.f_r, 'server': 'ns4.foo.ru'}
        ns = self.do_add(**data)
        self.assertTrue(ns.glue)
        self.assertEqual(ns.server, ns.glue.fqdn)

        ns.delete()
        nsret = Nameserver.objects.filter(
            server='ns2.foo.ru', domain=self.f_r)
        self.assertFalse(nsret)

    def test_invalid_create(self):
        glue = AddressRecord(label='ns2', domain=self.r,
                             ip_str='128.193.1.10', ip_type='4')
        glue.save()

        data = {'domain': self.r, 'server': 'ns2 .ru'}
        self.assertRaises(ValidationError, self.do_add, **data)
        data = {'domain': self.r, 'server': 'ns2$.ru'}
        self.assertRaises(ValidationError, self.do_add, **data)
        data = {'domain': self.r, 'server': 'ns2..ru'}
        self.assertRaises(ValidationError, self.do_add, **data)
        data = {'domain': self.r, 'server': 'ns2.ru '}
        self.assertRaises(ValidationError, self.do_add, **data)
        data = {'domain': self.r, 'server': ''}
        self.assertRaises(ValidationError, self.do_add, **data)

    def test_add_dup(self):
        data = {'domain': self.r, 'server': 'ns2.moot.ru'}
        self.do_add(**data)

        self.assertRaises(ValidationError, self.do_add, **data)

    def _get_post_data(self, random_str):
        """Return a valid set of data"""
        return {
            'root_domain': '{0}.mozilla.com'.format(random_str),
            'soa_primary': 'ns1.mozilla.com',
            'soa_contact': 'noc.mozilla.com',
            'nameserver_1': 'ns1.mozilla.com',
            'ttl_1': '1234'
        }

    def test_bad_nameserver_soa_state_case_1_0(self):
        # This is Case 1
        root_domain = create_fake_zone("asdf10")
        for ns in root_domain.nameserver_set.all():
            ns.delete()

        # At his point we should have a domain at the root of a zone with no
        # other records in it.

        # Adding a record shouldn't be allowed because there is no NS record on
        # the zone's root domain.
        a = AddressRecord(
            label='', domain=root_domain, ip_type="6", ip_str="1::")
        self.assertRaises(ValidationError, a.save)
        cn = CNAME(label='', domain=root_domain, target="asdf")
        self.assertRaises(ValidationError, cn.save)

    def test_bad_nameserver_soa_state_case_1_1(self):
        # This is Case 1
        root_domain = create_fake_zone("asdf111")
        for ns in root_domain.nameserver_set.all():
            ns.delete()

        # At his point we should have a domain at the root of a zone with no
        # other records in it.

        # Let's create a child domain and try to add a record there.
        cdomain = Domain(name="test." + root_domain.name)
        cdomain.soa = root_domain.soa
        cdomain.save()

        # Adding a record shouldn't be allowed because there is no NS record on
        # the zone's root domain.
        a = AddressRecord(label='', domain=cdomain, ip_type="6", ip_str="1::")
        self.assertRaises(ValidationError, a.save)
        cn = CNAME(label='', domain=cdomain, target="asdf")
        self.assertRaises(ValidationError, cn.save)

    def test_bad_nameserver_soa_state_case_1_2(self):
        # This is Case 1 ... with ptr's
        root_domain = create_fake_zone("12.in-addr.arpa", suffix="")
        for ns in root_domain.nameserver_set.all():
            ns.delete()

        # At his point we should have a domain at the root of a zone with no
        # other records in it.

        # Adding a record shouldn't be allowed because there is no NS record on
        # the zone's root domain.
        ptr = PTR(name="asdf", ip_str="12.10.1.1", ip_type="4")
        self.assertRaises(ValidationError, ptr.save)

    def test_bad_nameserver_soa_state_case_1_3(self):
        # This is Case 1 ... with ptr's
        root_domain = create_fake_zone("13.in-addr.arpa", suffix="")
        for ns in root_domain.nameserver_set.all():
            ns.delete()

        # At his point we should have a domain at the root of a zone with no
        # other records in it.

        # Let's create a child domain and try to add a record there.
        cdomain = Domain(name="10.13.in-addr.arpa")
        cdomain.soa = root_domain.soa
        cdomain.save()

        # Adding a record shouldn't be allowed because there is no NS record on
        # the zone's root domain.
        ptr = PTR(name="asdf", ip_str="13.10.1.1", ip_type="4")
        self.assertRaises(ValidationError, ptr.save)

    def test_bad_nameserver_soa_state_case_1_4(self):
        # This is Case 1 ... with StaticInterfaces's
        reverse_root_domain = create_fake_zone("14.in-addr.arpa", suffix="")
        root_domain = create_fake_zone("asdf14")
        for ns in root_domain.nameserver_set.all():
            ns.delete()

        # At his point we should have a domain at the root of a zone with no
        # other records in it.

        # Let's create a child domain and try to add a record there.
        cdomain = Domain(name="10.14.in-addr.arpa")
        cdomain.soa = reverse_root_domain.soa
        cdomain.save()

        # Adding a record shouldn't be allowed because there is no NS record on
        # the zone's root domain.
        intr = StaticInterface(
            label="asdf", domain=root_domain, ip_str="14.10.1.1", ip_type="4",
            mac="11:22:33:44:55:66", system=self.s)
        self.assertRaises(ValidationError, intr.save)

    # See record.tests for the case a required view is deleted.
    def test_bad_nameserver_soa_state_case_2_0(self):
        # This is Case 2
        root_domain = create_fake_zone("asdf20")
        self.assertEqual(root_domain.nameserver_set.count(), 1)
        ns = root_domain.nameserver_set.all()[0]

        # At his point we should have a domain at the root of a zone with one
        # ns record associated to the domain.

        a = AddressRecord(
            label='', domain=root_domain, ip_type="6", ip_str="1::")
        a.save()

        self.assertRaises(ValidationError, ns.delete)

    def test_bad_nameserver_soa_state_case_2_1(self):
        # This is Case 2
        root_domain = create_fake_zone("asdf21")
        self.assertEqual(root_domain.nameserver_set.count(), 1)
        ns = root_domain.nameserver_set.all()[0]

        # At his point we should have a domain at the root of a zone with one
        # ns record associated to the domain.

        # Let's create a child domain and add a record there, then try to
        # delete the NS record
        cdomain = Domain(name="test." + root_domain.name)
        cdomain.soa = root_domain.soa
        cdomain.save()

        a = AddressRecord(label='', domain=cdomain, ip_type="6", ip_str="1::")
        a.save()

        self.assertRaises(ValidationError, ns.delete)

    def test_bad_nameserver_soa_state_case_2_2(self):
        # This is Case 2 ... with ptrs
        root_domain = create_fake_zone("22.in-addr.arpa", suffix="")
        self.assertEqual(root_domain.nameserver_set.count(), 1)
        ns = root_domain.nameserver_set.all()[0]

        # At his point we should have a domain at the root of a zone with one
        # ns record associated to the domain.

        ptr = PTR(name="asdf", ip_str="22.1.1.1", ip_type="4")
        ptr.save()

        self.assertRaises(ValidationError, ns.delete)

    def test_bad_nameserver_soa_state_case_2_3(self):
        # This is Case 2 ... with ptrs
        root_domain = create_fake_zone("10.23.in-addr.arpa", suffix="")
        self.assertEqual(root_domain.nameserver_set.count(), 1)
        ns = root_domain.nameserver_set.all()[0]

        # At his point we should have a domain at the root of a zone with one
        # ns record associated to the domain.

        # Let's create a child domain and add a record there, then try to
        # delete the NS record
        cdomain = Domain(name="test." + root_domain.name)
        cdomain.soa = root_domain.soa
        cdomain.save()

        ptr = PTR(name="asdf", ip_str="23.10.1.1", ip_type="4")
        ptr.save()

        self.assertRaises(ValidationError, ns.delete)

    def test_bad_nameserver_soa_state_case_3_0(self):
        # This is Case 3
        root_domain = create_fake_zone("asdf30")
        for ns in root_domain.nameserver_set.all():
            ns.delete()

        soa = ns.domain.soa
        ns.domain.soa = None
        root_domain.soa = None  # Shit's getting cached
        ns.domain.save()
        soa.delete()

        # At his point we should have a domain pointed at no SOA record with no
        # records attached to it. It also has no child domains.

        # Add a record to the domain.
        a = AddressRecord(
            label='', domain=root_domain, ip_type="6", ip_str="1::")
        a.save()

        s = SOA(primary="asdf.asdf", contact="asdf.asdf", description="asdf")
        s.save()
        root_domain.soa = s

        self.assertRaises(ValidationError, root_domain.save)

    def test_bad_nameserver_soa_state_case_3_1(self):
        # This is Case 3
        root_domain = create_fake_zone("asdf31")
        for ns in root_domain.nameserver_set.all():
            ns.delete()

        # At his point we should have a domain pointed at an SOA record with no
        # records attached to it (esspecially no ns recods). It also has no
        # child domains.
        # Try case 3 but add a record to a child domain of root_domain
        cdomain = Domain(name="test." + root_domain.name)
        cdomain.save()

        # Add a record to the domain.
        a = AddressRecord(label='', domain=cdomain, ip_type="6", ip_str="1::")
        a.save()

        # Now try to add the domain to the zone that has no NS records at it's
        # root
        cdomain.soa = root_domain.soa

        self.assertRaises(ValidationError, cdomain.save)

    def test_bad_nameserver_soa_state_case_3_2(self):
        # This is Case 3 ... with ptrs
        root_domain = create_fake_zone("32.in-addr.arpa", suffix="")
        for ns in root_domain.nameserver_set.all():
            ns.delete()

        soa = ns.domain.soa
        ns.domain.soa = None
        root_domain.soa = None  # Shit's getting cached
        ns.domain.save()
        soa.delete()

        # At his point we should have a domain pointed at no SOA record with no
        # records attached to it. It also has no child domains.

        # Add a record to the domain.

        ptr = PTR(name="asdf", ip_str="32.1.1.1", ip_type="4")
        ptr.save()

        s = SOA(primary="asdf.asdf", contact="asdf.asdf", description="asdf")
        s.save()
        root_domain.soa = s

        self.assertRaises(ValidationError, root_domain.save)

    def test_bad_nameserver_soa_state_case_3_3(self):
        # This is Case 3 ... with ptrs
        root_domain = create_fake_zone("33.in-addr.arpa", suffix="")
        for ns in root_domain.nameserver_set.all():
            ns.delete()

        # At his point we should have a domain pointed at an SOA record with no
        # records attached to it (esspecially no ns recods). It also has no
        # child domains.
        # Try case 3 but add a record to a child domain of root_domain
        cdomain = Domain(name="10.33.in-addr.arpa")
        cdomain.save()

        # Add a record to the domain.
        ptr = PTR(name="asdf", ip_str="33.10.1.1", ip_type="4")
        ptr.save()

        # Now try to add the domain to the zone that has no NS records at it's
        # root
        cdomain.soa = root_domain.soa

        self.assertRaises(ValidationError, cdomain.save)
class AStaticRegTests(TestCase):
    def create_domain(self, name, ip_type=None, delegated=False):
        if ip_type is None:
            ip_type = '4'
        if name in ('arpa', 'in-addr.arpa', 'ip6.arpa'):
            pass
        else:
            name = ip_to_domain_name(name, ip_type=ip_type)
        d = Domain(name=name, delegated=delegated)
        d.clean()
        self.assertTrue(d.is_reverse)
        return d

    def setUp(self):
        self.arpa = self.create_domain(name='arpa')
        self.arpa.save()
        self.i_arpa = self.create_domain(name='in-addr.arpa')
        self.i_arpa.save()

        self.c = Domain(name="ccc")
        self.c.save()
        self.f_c = Domain(name="foo.ccc")
        self.f_c.save()
        self.r1 = self.create_domain(name="10")
        self.r1.save()
        self.n = System()
        self.n.clean()
        self.n.save()

    def do_add_intr(self, mac, label, domain, ip_str, ip_type='4'):
        r = StaticInterface(mac=mac, label=label, domain=domain, ip_str=ip_str,
                            ip_type=ip_type, system=self.n)
        r.clean()
        r.save()
        repr(r)
        return r

    def do_add_a(self, label, domain, ip_str, ip_type='4'):
        a = AddressRecord(label=label, domain=domain, ip_str=ip_str,
                          ip_type=ip_type)
        a.clean()
        a.save()
        return a

    def do_delete(self, r):
        ip_str = r.ip_str
        fqdn = r.fqdn
        r.delete()
        self.assertFalse(
            AddressRecord.objects.filter(ip_str=ip_str, fqdn=fqdn))

    def test1_conflict_add_intr_first(self):
        # Add an intr and make sure A can't exist.
        mac = "11:22:33:44:55:66"
        label = "foo4"
        domain = self.f_c
        ip_str = "10.0.0.2"
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        self.do_add_intr(**kwargs)
        kwargs = {'label': label, 'domain': domain, 'ip_str': ip_str}
        self.assertRaises(ValidationError, self.do_add_a, **kwargs)

    def test1_conflict_add_A_first(self):
        # Add an A and make sure an intr can't exist.
        mac = "11:22:33:44:55:66"
        label = "foo5"
        domain = self.f_c
        ip_str = "10.0.0.2"
        kwargs = {'label': label, 'domain': domain, 'ip_str': ip_str}
        self.do_add_a(**kwargs)
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        self.assertRaises(ValidationError, self.do_add_intr, **kwargs)

    def test2_conflict_add_intr_first(self):
        # Add an intr and update an existing A to conflict. Test for exception.
        mac = "12:22:33:44:55:66"
        label = "fo99"
        domain = self.f_c
        ip_str = "10.0.0.2"
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        self.do_add_intr(**kwargs)
        ip_str = "10.0.0.3"
        kwargs = {'label': label, 'domain': domain, 'ip_str': ip_str}
        a = self.do_add_a(**kwargs)
        a.ip_str = "10.0.0.2"
        self.assertRaises(ValidationError, a.save)

    def test2_conflict_add_A_first(self):
        # Add an A and update and existing intr to conflict. Test for
        # exception.
        mac = "11:22:33:44:55:66"
        label = "foo98"
        domain = self.f_c
        ip_str = "10.0.0.2"
        # Add A
        kwargs = {'label': label, 'domain': domain, 'ip_str': ip_str}
        self.do_add_a(**kwargs)

        # Add Intr with diff IP
        ip_str = "10.0.0.3"
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        intr = self.do_add_intr(**kwargs)

        # Conflict the IP on the intr
        intr.ip_str = "10.0.0.2"
        self.assertRaises(ValidationError, intr.save)
class StaticInterTests(TestCase):
    def create_domain(self, name, ip_type=None, delegated=False):
        if ip_type is None:
            ip_type = '4'
        if name in ('arpa', 'in-addr.arpa', 'ip6.arpa'):
            pass
        else:
            name = ip_to_domain_name(name, ip_type=ip_type)
        d = Domain(name=name, delegated=delegated)
        d.clean()
        self.assertTrue(d.is_reverse)
        return d

    def setUp(self):
        self.arpa = self.create_domain(name='arpa')
        self.arpa.save()
        self.i_arpa = self.create_domain(name='in-addr.arpa')
        self.i_arpa.save()

        self.c = Domain(name="ccc")
        self.c.save()
        self.f_c = Domain(name="foo.ccc")
        self.f_c.save()
        self.r1 = self.create_domain(name="10")
        self.r1.save()

        self.r2 = self.create_domain(name="128")
        self.r2.save()
        self.n = System()
        self.n.clean()
        self.n.save()
        View.objects.get_or_create(name="private")

    def do_add(self, mac, label, domain, ip_str, ip_type='4'):
        r = StaticInterface(mac=mac, label=label, domain=domain, ip_str=ip_str,
                            ip_type=ip_type, system=self.n)
        r.clean()
        r.save()
        r.details()
        r.get_edit_url()
        r.get_delete_url()
        r.get_absolute_url()
        repr(r)
        return r

    def do_delete(self, r):
        ip_str = r.ip_str
        fqdn = r.fqdn
        r.delete()
        self.assertFalse(
            AddressRecord.objects.filter(ip_str=ip_str, fqdn=fqdn))

    def test1_create_basic(self):
        mac = "11:22:33:44:55:66"
        label = "foo"
        domain = self.f_c
        ip_str = "10.0.0.2"
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        i = self.do_add(**kwargs)
        i.update_attrs()
        self.assertEqual('None', i.interface_name())
        i.attrs.interface_type = "eth"
        self.assertEqual('None', i.interface_name())
        i.attrs.primary = "0"
        self.assertEqual('eth0', i.interface_name())
        i.attrs.alias = "0"
        self.assertEqual('eth0.0', i.interface_name())
        i.clean()

        def bad_assign():
            i.attrs.interface_type = "wee"
        self.assertRaises(ValidationError, bad_assign)

        def bad_assign1():
            i.attrs.primary = "wee"
        self.assertRaises(ValidationError, bad_assign1)

        def bad_assign2():
            i.attrs.alias = "wee"
        self.assertRaises(ValidationError, bad_assign2)

    def test2_create_basic(self):
        mac = "11:22:33:44:55:66"
        label = "foo1"
        domain = self.f_c
        ip_str = "10.0.0.1"
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        i = self.do_add(**kwargs)
        self.assertEqual(self.r1, i.reverse_domain)

        i.dhcp_enabled = False
        i.clean()
        i.save()
        i2 = StaticInterface.objects.get(pk=i.pk)
        self.assertFalse(i2.dhcp_enabled)
        self.assertEqual(self.r1, i2.reverse_domain)

        i.dhcp_enabled = True
        i.clean()
        i.save()
        i3 = StaticInterface.objects.get(pk=i.pk)
        self.assertTrue(i3.dhcp_enabled)

    def test3_create_basic(self):
        mac = "11:22:33:44:55:66"
        label = "foo1"
        domain = self.f_c
        ip_str = "10.0.0.2"
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        self.do_add(**kwargs)

    def test4_create_basic(self):
        mac = "12:22:33:44:55:66"
        label = "foo1"
        domain = self.f_c
        ip_str = "10.0.0.2"
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        self.do_add(**kwargs)

    def test5_create_basic(self):
        mac = "00:00:00:00:00:00"
        label = "foo1"
        domain = self.f_c
        ip_str = "10.0.0.2"
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        self.do_add(**kwargs)

        # Change the mac by one.
        mac = "00:00:00:00:00:01"
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        self.do_add(**kwargs)

    def test6_create_basic(self):
        mac = "11:22:33:44:55:66"
        label = "foo1"
        domain = self.f_c
        ip_str = "128.0.0.2"
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        i = self.do_add(**kwargs)
        self.assertEqual(self.r2, i.reverse_domain)

    def test1_delete(self):
        mac = "12:22:33:44:55:66"
        label = "foo1"
        domain = self.f_c
        ip_str = "10.0.0.2"
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        r = self.do_add(**kwargs)
        self.do_delete(r)

    def test1_dup_create_basic(self):
        mac = "11:22:33:44:55:66"
        label = "foo3"
        domain = self.f_c
        ip_str = "10.0.0.2"
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        self.do_add(**kwargs)
        self.assertRaises(ValidationError, self.do_add, **kwargs)

    def test1_bad_add_for_a_ptr(self):
        # Intr exists, then try ptr and A
        mac = "11:22:33:44:55:66"
        label = "9988food"
        domain = self.c
        ip_str = "10.0.0.1"
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        ip_type = '4'
        i = self.do_add(**kwargs)
        i.clean()
        i.save()
        a = AddressRecord(label=label, domain=domain, ip_str=ip_str,
                          ip_type=ip_type)
        self.assertRaises(ValidationError, a.clean)
        ptr = PTR(ip_str=ip_str, ip_type=ip_type, name=i.fqdn)
        self.assertRaises(ValidationError, ptr.clean)

    def test2_bad_add_for_a_ptr(self):
        # PTR and A exist, then try add intr
        mac = "11:22:33:44:55:66"
        label = "9988fdfood"
        domain = self.c
        ip_str = "10.0.0.1"
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        ip_type = '4'
        a = AddressRecord(label=label, domain=domain, ip_str=ip_str,
                          ip_type=ip_type)
        a.clean()
        a.save()
        ptr = PTR(ip_str=ip_str, ip_type=ip_type, name=a.fqdn)
        ptr.clean()
        ptr.save()
        self.assertRaises(ValidationError, self.do_add, **kwargs)

    def test1_bad_reverse_domain(self):
        mac = "11:22:33:44:55:66"
        label = "8888foo"
        domain = self.f_c
        ip_str = "10.0.0.1"
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        i = self.do_add(**kwargs)
        i.ip_str = "9.0.0.1"
        self.assertRaises(ValidationError, i.clean)

    def test1_no_system(self):
        mac = "15:22:33:44:55:66"
        label = "8888foo"
        domain = self.f_c
        ip_str = "10.0.0.1"
        ip_type = '4'
        r = StaticInterface(label=label, domain=domain, ip_str=ip_str,
                            ip_type=ip_type, system=None, mac=mac)
        self.assertRaises(ValidationError, r.clean)
 def setUp(self):
     create_fake_zone('2.ip6.arpa', suffix="")
     super(StaticIntrV6APITests, self).setUp()
     self.s = System(hostname="foobar")
     self.s.save()
class PTRStaticRegTests(TestCase):
    def create_domain(self, name, ip_type=None, delegated=False):
        if ip_type is None:
            ip_type = '4'
        if name in ('arpa', 'in-addr.arpa', 'ip6.arpa'):
            pass
        else:
            name = ip_to_domain_name(name, ip_type=ip_type)
        d = Domain(name=name, delegated=delegated)
        d.clean()
        self.assertTrue(d.is_reverse)
        return d

    def setUp(self):
        self.arpa = self.create_domain(name='arpa')
        self.arpa.save()
        self.i_arpa = self.create_domain(name='in-addr.arpa')
        self.i_arpa.save()

        self.c = Domain(name="ccc")
        self.c.save()
        self.f_c = Domain(name="foo.ccc")
        self.f_c.save()
        self.r1 = self.create_domain(name="10")
        self.r1.save()
        self.n = System()
        self.n.clean()
        self.n.save()

    def do_add_intr(self, mac, label, domain, ip_str, ip_type='4'):
        r = StaticInterface(mac=mac, label=label, domain=domain, ip_str=ip_str,
                            ip_type=ip_type, system=self.n)
        r.clean()
        r.save()
        repr(r)
        return r

    def do_add_ptr(self, label, domain, ip_str, ip_type='4'):
        ptr = PTR(name=label + '.' + domain.name, ip_str=ip_str,
                  ip_type=ip_type)
        ptr.clean()
        ptr.save()
        return ptr

    def test1_conflict_add_intr_first(self):
        # PTRdd an intr and make sure PTR can't exist.
        mac = "11:22:33:44:55:66"
        label = "foo4"
        domain = self.f_c
        ip_str = "10.0.0.2"
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        self.do_add_intr(**kwargs)
        kwargs = {'label': label, 'domain': domain, 'ip_str': ip_str}
        self.assertRaises(ValidationError, self.do_add_ptr, **kwargs)

    def test1_conflict_add_PTR_first(self):
        # Add an PTR and make sure an intr can't exist.
        mac = "11:22:33:44:55:66"
        label = "foo5"
        domain = self.f_c
        ip_str = "10.0.0.2"
        kwargs = {'label': label, 'domain': domain, 'ip_str': ip_str}
        self.do_add_ptr(**kwargs)
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        self.assertRaises(ValidationError, self.do_add_intr, **kwargs)

    def test2_conflict_add_intr_first(self):
        # Add an intr and update an existing PTR to conflict. Test for
        # exception.
        mac = "12:22:33:44:55:66"
        label = "fo99"
        domain = self.f_c
        ip_str = "10.0.0.2"
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        self.do_add_intr(**kwargs)
        ip_str = "10.0.0.3"
        kwargs = {'label': label, 'domain': domain, 'ip_str': ip_str}
        ptr = self.do_add_ptr(**kwargs)
        ptr.ip_str = "10.0.0.2"
        self.assertRaises(ValidationError, ptr.clean)

    def test2_conflict_add_A_first(self):
        # Add an PTR and update and existing intr to conflict. Test for
        # exception.
        mac = "11:22:33:44:55:66"
        label = "foo98"
        domain = self.f_c
        ip_str = "10.0.0.2"
        # Add PTR
        kwargs = {'label': label, 'domain': domain, 'ip_str': ip_str}
        self.do_add_ptr(**kwargs)

        # Add Intr with diff IP
        ip_str = "10.0.0.3"
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        intr = self.do_add_intr(**kwargs)

        # Conflict the IP on the intr
        intr.ip_str = "10.0.0.2"
        self.assertRaises(ValidationError, intr.save)
test_role_1 = Role(name="Test Role 1", owner=extra_users[0])
test_role_1.save()
extra_users[0].roles.add(test_role_1)
test_role_1_admin_permission = create_permission(ValidPermissions.ROLE_ADMIN,
                                                 test_role_1.id)
test_role_1.permissions.add(test_role_1_admin_permission)

with open("data/systems.json") as f:
    systems_data = json.load(f)

for system_data in systems_data:
    if not system_data.get("basics", False):
        system_data["basics"] = None
    system = System(**{
        k: v
        for k, v in system_data.items() if k not in ["genres", "publisher"]
    })
    system.save()
    if system_data["publisher"]:
        publisher, _ = Publisher.objects.get_or_create(
            name=system_data["publisher"]["name"],
            defaults={"website": system_data["publisher"]["site"]},
        )
        system.publisher = publisher
    if system_data["genres"]:
        for genre_data in system_data["genres"]:
            genre, _ = Genre.objects.get_or_create(genre=genre_data)
            system.genres.add(genre)
    print(f"Created system: {system.name}")
print("\n")
class V6StaticInterTests(TestCase):
    def create_domain(self, name, ip_type=None, delegated=False):
        if ip_type is None:
            ip_type = '4'
        if name in ('arpa', 'in-addr.arpa', 'ip6.arpa'):
            pass
        else:
            name = ip_to_domain_name(name, ip_type=ip_type)
        d = Domain(name=name, delegated=delegated)
        d.clean()
        self.assertTrue(d.is_reverse)
        return d

    def setUp(self):
        self.arpa = self.create_domain(name='arpa')
        self.arpa.save()
        self.i_arpa = self.create_domain(name='ip6.arpa', ip_type='6')
        self.i_arpa.save()

        self.c = Domain(name="ccc")
        self.c.save()
        self.f_c = Domain(name="foo.ccc")
        self.f_c.save()
        self.r1 = self.create_domain(name="0", ip_type='6')
        self.r1.save()
        self.r2 = self.create_domain(name="1", ip_type='6')
        self.r2.save()
        self.n = System()
        self.n.clean()
        self.n.save()

    def do_add(self, mac, label, domain, ip_str, ip_type='6'):
        r = StaticInterface(mac=mac, label=label, domain=domain, ip_str=ip_str,
                            ip_type=ip_type, system=self.n)
        r.clean()
        r.save()
        repr(r)
        return r

    def do_delete(self, r):
        ip_str = r.ip_str
        fqdn = r.fqdn
        r.delete()
        self.assertFalse(
            AddressRecord.objects.filter(ip_str=ip_str, fqdn=fqdn))

    def test1_create_basic(self):
        mac = "11:22:33:44:55:66"
        label = "foo"
        domain = self.f_c
        ip_str = "12::" + mac
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        self.do_add(**kwargs)

    def test2_create_basic(self):
        mac = "20:22:33:44:55:66"
        label = "foo1"
        domain = self.f_c
        ip_str = "123::" + mac
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        self.do_add(**kwargs)

    def test3_create_basic(self):
        mac = "11:22:33:44:55:66"
        label = "foo1"
        domain = self.f_c
        ip_str = "1234::" + mac
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        self.do_add(**kwargs)

    def test4_create_basic(self):
        mac = "12:22:33:44:55:66"
        label = "foo1"
        domain = self.f_c
        ip_str = "11::" + mac
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        self.do_add(**kwargs)

    def test1_delete(self):
        mac = "12:22:33:44:55:66"
        label = "foo1"
        domain = self.f_c
        ip_str = "112::" + mac
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        r = self.do_add(**kwargs)
        self.do_delete(r)

    def test1_dup_create_basic(self):
        mac = "11:22:33:44:55:66"
        label = "foo3"
        domain = self.f_c
        ip_str = "1123::" + mac
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        self.do_add(**kwargs)
        self.assertRaises(ValidationError, self.do_add, **kwargs)

    def test1_bad_add_for_a_ptr(self):
        # Intr exists, then try ptr and A
        mac = "11:22:33:44:55:6e"
        label = "9988fooddfdf"
        domain = self.c
        ip_str = "111::" + mac
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        ip_type = '6'
        i = self.do_add(**kwargs)
        i.clean()
        i.save()
        a = AddressRecord(label=label, domain=domain, ip_str=ip_str,
                          ip_type=ip_type)
        self.assertRaises(ValidationError, a.clean)
        ptr = PTR(ip_str=ip_str, ip_type=ip_type, name=i.fqdn)
        self.assertRaises(ValidationError, ptr.clean)

    def test2_bad_add_for_a_ptr(self):
        # PTR and A exist, then try add intr
        mac = "11:22:33:44:55:66"
        label = "9988fdfood"
        domain = self.c
        ip_str = "1112::" + mac
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        ip_type = '6'
        a = AddressRecord(label=label, domain=domain, ip_str=ip_str,
                          ip_type=ip_type)
        a.clean()
        a.save()
        ptr = PTR(ip_str=ip_str, ip_type=ip_type, name=a.fqdn)
        ptr.clean()
        ptr.save()
        self.assertRaises(ValidationError, self.do_add, **kwargs)

    def test1_bad_reverse_domain(self):
        mac = "11:22:33:44:55:66"
        label = "8888foo"
        domain = self.f_c
        ip_str = "115::" + mac
        kwargs = {'mac': mac, 'label': label, 'domain': domain,
                  'ip_str': ip_str}
        i = self.do_add(**kwargs)
        i.ip_str = "9111::"
        self.assertRaises(ValidationError, i.clean)

    def test1_no_system(self):
        mac = "15:22:33:44:55:66"
        label = "8888foo"
        domain = self.f_c
        ip_str = "188::" + mac
        ip_type = '6'
        r = StaticInterface(label=label, domain=domain, ip_str=ip_str,
                            ip_type=ip_type, system=None)
        self.assertRaises(ValidationError, r.clean)