Esempio n. 1
0
 def setUp(self):
     """Define the test client and other variables."""
     super().setUp()
     self.zone_one = ForwardZone(name="example.org",
                                 primary_ns="ns1.example.org",
                                 email="*****@*****.**")
     self.host_one = Host(name='ns1.example.org',
                          contact="*****@*****.**")
     self.host_two = Host(name='ns2.example.org',
                          contact="*****@*****.**")
     self.host_three = Host(name='ns3.example.org',
                            contact="*****@*****.**")
     self.ns_one = NameServer(name='ns1.example.org', ttl=400)
     self.ns_two = NameServer(name='ns2.example.org', ttl=400)
     self.post_data_one = {
         'name': 'example.com',
         'primary_ns': ['ns1.example.org', 'ns2.example.org'],
         'email': "*****@*****.**",
         'refresh': 400,
         'retry': 300,
         'expire': 800,
         'soa_ttl': 350
     }
     self.post_data_two = {
         'name': 'example.net',
         'primary_ns': ['ns1.example.org', 'ns2.example.org'],
         'email': "*****@*****.**"
     }
     self.patch_data = {'refresh': '500', 'expire': '1000'}
     clean_and_save(self.host_one)
     clean_and_save(self.host_two)
     clean_and_save(self.ns_one)
     clean_and_save(self.ns_two)
     clean_and_save(self.zone_one)
Esempio n. 2
0
 def setUp(self):
     """Define the test client and other test variables."""
     self.host_one = Host(name='some-host.example.org',
                          contact='*****@*****.**',
                          ttl=300,
                          loc='23 58 23 N 10 43 50 E 80m',
                          comment='some comment')
Esempio n. 3
0
 def setUp(self):
     """Define the test client and other variables."""
     super().setUp()
     self.zone_one = ReverseZone.objects.create(
         name="0.0.10.in-addr.arpa",
         primary_ns="ns1.example.org",
         email="*****@*****.**")
     self.host_one = Host(name='ns1.example.org',
                          contact="*****@*****.**")
     self.host_two = Host(name='ns2.example.org',
                          contact="*****@*****.**")
     self.host_three = Host(name='ns3.example.org',
                            contact="*****@*****.**")
     self.ns_one = NameServer(name='ns1.example.org', ttl=400)
     self.ns_two = NameServer(name='ns2.example.org', ttl=400)
     self.post_data_one = {
         'name': '0.10.in-addr.arpa',
         'primary_ns': ['ns1.example.org', 'ns2.example.org'],
         'email': "*****@*****.**",
         'refresh': 400,
         'retry': 300,
         'expire': 800,
         'soa_ttl': 350,
         'default_ttl': 1000
     }
     self.post_data_two = {
         'name': '0.16.172.in-addr.arpa',
         'primary_ns': ['ns1.example.org', 'ns2.example.org'],
         'email': "*****@*****.**"
     }
     self.patch_data = {'refresh': '500', 'expire': '1000'}
     clean_and_save(self.host_one)
     clean_and_save(self.host_two)
     clean_and_save(self.ns_one)
     clean_and_save(self.ns_two)
Esempio n. 4
0
    def setUp(self):
        """Define the test client and other test variables."""
        self.zone_sample = ForwardZone(name='example.org',
                                       primary_ns='ns.example.org',
                                       email='*****@*****.**')
        clean_and_save(self.zone_sample)

        self.zone_1010 = ReverseZone(name='10.10.in-addr.arpa',
                                     primary_ns='ns.example.org',
                                     email='*****@*****.**')
        clean_and_save(self.zone_1010)

        self.network_sample = Network(range='10.0.0.0/24',
                                      description='some description')
        clean_and_save(self.network_sample)

        self.ns_hostsample = Host(name='ns.example.org',
                                  contact='*****@*****.**')
        clean_and_save(self.ns_hostsample)

        self.ns_hostip = Ipaddress(host=self.ns_hostsample,
                                   ipaddress='10.0.0.111')
        clean_and_save(self.ns_hostip)

        self.ns_sample = NameServer(name='ns.example.org', ttl=300)
        clean_and_save(self.ns_sample)
        self.zone_sample.nameservers.add(self.ns_sample)
        self.zone_sample.save()
Esempio n. 5
0
File: views.py Progetto: JarleB/mreg
    def post(self, request, *args, **kwargs):
        if "name" in request.data:
            if self.queryset.filter(name=request.data["name"]).exists():
                content = {'ERROR': 'name already in use'}
                return Response(content, status=status.HTTP_409_CONFLICT)

        hostdata = request.data.copy()

        if 'ipaddress' in hostdata:
            ipkey = hostdata['ipaddress']
            del hostdata['ipaddress']
            host = Host()
            hostserializer = HostSerializer(host, data=hostdata)

            if hostserializer.is_valid(raise_exception=True):
                with transaction.atomic():
                    hostserializer.save()
                    ipdata = {'host': host.pk, 'ipaddress': ipkey}
                    ip = Ipaddress()
                    ipserializer = IpaddressSerializer(ip, data=ipdata)
                    if ipserializer.is_valid(raise_exception=True):
                        self.perform_create(ipserializer)
                        location = request.path + host.name
                        return Response(status=status.HTTP_201_CREATED, headers={'Location': location})
        else:
            host = Host()
            hostserializer = HostSerializer(host, data=hostdata)
            if hostserializer.is_valid(raise_exception=True):
                self.perform_create(hostserializer)
                location = request.path + host.name
                return Response(status=status.HTTP_201_CREATED, headers={'Location': location})
Esempio n. 6
0
 def setUp(self):
     """Define the test client and other test variables."""
     super().setUp()
     self.host_one = Host(name='host1.example.org',
                          contact='*****@*****.**')
     self.host_one.save()
     self.id_one = BACnetID.objects.create(id=BACnetID.first_unused_id(),
                                           host=self.host_one)
     self.host_two = Host(name='host2.example.org',
                          contact='*****@*****.**')
     self.host_two.save()
Esempio n. 7
0
class NameServerDeletionTestCase(TestCase):
    """This class defines the test suite for the NameServer model."""

    def setUp(self):
        """Define the test client and other test variables."""
        self.zone_sample = ForwardZone(name='example.org',
                                       primary_ns='ns.example.org',
                                       email='*****@*****.**')
        clean_and_save(self.zone_sample)

        self.zone_1010 = ReverseZone(name='10.10.in-addr.arpa',
                                     primary_ns='ns.example.org',
                                     email='*****@*****.**')
        clean_and_save(self.zone_1010)

        self.network_sample = Network(range='10.0.0.0/24',
                                      description='some description')
        clean_and_save(self.network_sample)

        self.ns_hostsample = Host(name='ns.example.org',
                                  contact='*****@*****.**')
        clean_and_save(self.ns_hostsample)

        self.ns_hostip = Ipaddress(host=self.ns_hostsample,
                                   ipaddress='10.0.0.111')
        clean_and_save(self.ns_hostip)

        self.ns_sample = NameServer(name='ns.example.org',
                                    ttl=300)
        clean_and_save(self.ns_sample)
        self.zone_sample.nameservers.add(self.ns_sample)
        self.zone_sample.save()

    def test_model_cant_delete_ns_host(self):
        """Test that it won't delete nameserver host-object if in use in a zone"""
        with self.assertRaises(PermissionDenied):
            self.ns_hostsample.delete()

    def test_model_cant_delete_ns_hostip(self):
        """Test that it won't delete nameserver with only 1 IP if in use in a zone"""
        with self.assertRaises(PermissionDenied):
            self.ns_hostip.delete()

    def test_model_can_delete_ns_hostip(self):
        """Test that the model is able to delete an IP from a nameserver, if nameserver has multiple IPs."""
        self.ns_hostip2 = Ipaddress(host=self.ns_hostsample,
                                    ipaddress='10.0.0.112')
        clean_and_save(self.ns_hostip2)
        old_count = Ipaddress.objects.count()
        self.ns_hostip2.delete()
        new_count = Ipaddress.objects.count()
        self.assertNotEqual(old_count, new_count)
Esempio n. 8
0
 def setUp(self):
     """Define the test client and other test variables."""
     self.group_one = HostGroup(name='group1')
     self.group_two = HostGroup(name='group2')
     self.group_three = HostGroup(name='group3')
     self.group_four = HostGroup(name='group4')
     self.host_one = Host(name='host1.example.org',
                          contact='*****@*****.**')
     clean_and_save(self.group_one)
     clean_and_save(self.group_two)
     clean_and_save(self.group_three)
     clean_and_save(self.group_four)
     clean_and_save(self.host_one)
Esempio n. 9
0
class ModelHostsTestCase(TestCase):
    """This class defines the test suite for the Host model."""

    def setUp(self):
        """Define the test client and other test variables."""
        self.host_one = Host(name='some-host.example.org',
                             contact='*****@*****.**',
                             ttl=300,
                             loc='23 58 23 N 10 43 50 E 80m',
                             comment='some comment')

    def test_model_can_create_a_host(self):
        """Test that the model is able to create a host."""
        old_count = Host.objects.count()
        clean_and_save(self.host_one)
        new_count = Host.objects.count()
        self.assertNotEqual(old_count, new_count)

    def test_model_can_change_a_host(self):
        """Test that the model is able to change a host."""
        clean_and_save(self.host_one)
        old_name = self.host_one.name
        new_name = 'some-new-host.example.org'
        host_sample_id = Host.objects.get(name=old_name).id
        self.host_one.name = new_name
        clean_and_save(self.host_one)
        updated_name = Host.objects.get(pk=host_sample_id).name
        self.assertEqual(new_name, updated_name)

    def test_model_can_delete_a_host(self):
        """Test that the model is able to delete a host."""
        clean_and_save(self.host_one)
        old_count = Host.objects.count()
        self.host_one.delete()
        new_count = Host.objects.count()
        self.assertNotEqual(old_count, new_count)

    def test_model_host_can_alter_loc(self):
        """
        Test that the model can validate and store all examples
        from RFC1876, section 4 "Example data".
        """
        clean_and_save(self.host_one)
        for loc in ('42 21 54 N 71 06 18 W -24m 30m',
                    '42 21 43.952 N 71 5 6.344 W -24m 1m 200m',
                    '52 14 05 N 00 08 50 E 10m',
                    '32 7 19 S 116 2 25 E 10m',
                    '42 21 28.764 N 71 00 51.617 W -44m 2000m'):
            self.host_one.loc = loc
            clean_and_save(self.host_one)
Esempio n. 10
0
    def setUp(self):
        """Define the test client and other test variables."""
        # Needs sample host to test properly
        self.host_one = Host(name='some-host.example.org',
                             contact='*****@*****.**')

        clean_and_save(self.host_one)

        self.cname_sample = Cname(host=Host.objects.get(name='some-host.example.org'),
                                  name='some-cname.example.org',
                                  ttl=300)
Esempio n. 11
0
    def setUp(self):
        """Define the test client and other test variables."""
        # Needs sample host to test properly
        self.host_one = Host(name='some-host.example.org',
                             contact='*****@*****.**',
                             ttl=300,
                             loc='23 58 23 N 10 43 50 E 80m',
                             comment='some comment')

        clean_and_save(self.host_one)

        self.sshfp_sample = Sshfp(host=Host.objects.get(name='some-host.example.org'),
                              algorithm=1, hash_type=1, fingerprint='01234567890abcdef')
Esempio n. 12
0
    def setUp(self):
        """Define the test client and other test variables."""
        # Needs sample host to test properly
        self.host_one = Host(name='some-host.example.org',
                             contact='*****@*****.**',
                             ttl=300,
                             loc='23 58 23 N 10 43 50 E 80m',
                             comment='some comment')

        clean_and_save(self.host_one)

        self.txt_sample = Txt(host=Host.objects.get(name='some-host.example.org'),
                              txt='some-text')
Esempio n. 13
0
 def test_model_case_insesitive(self):
     """Hosts names must be case insensitive"""
     clean_and_save(self.host_one)
     self.assertEqual(self.host_one, Host.objects.get(name=self.host_one.name.upper()))
     upper = Host(name=self.host_one.name.upper(), contact=self.host_one.contact)
     with self.assertRaises(ValidationError) as context:
         clean_and_save(upper)
     self.assertEqual(context.exception.messages,
                      ['Host with this Name already exists.'])
     hostname = 'UPPERCASE.EXAMPLE.ORG'
     host = Host.objects.create(name=hostname, contact='*****@*****.**')
     # Must do a refresh_from_db() as host.name is otherwise the unmodfied
     # uppercase hostname.
     host.refresh_from_db()
     self.assertEqual(host.name, hostname.lower())
Esempio n. 14
0
    def setUp(self):
        """Define the test client and other test variables."""
        # Needs sample host to test properly
        self.host_one = Host(name='some-host.example.org',
                             contact='*****@*****.**',
                             ttl=300,
                             loc='23 58 23 N 10 43 50 E 80m',
                             comment='some comment')

        clean_and_save(self.host_one)

        self.srv_sample = Srv(name='_abc._udp.example.org',
                              priority=3,
                              weight=1,
                              port=5433,
                              ttl=300,
                              target='some-target')
Esempio n. 15
0
    def setUp(self):
        """Define the test client and other test variables."""
        # Needs sample host to test properly
        self.host_one = Host(name='some-host.example.org',
                             contact='*****@*****.**',
                             ttl=300,
                             loc='23 58 23 N 10 43 50 E 80m',
                             comment='some comment')

        clean_and_save(self.host_one)

        self.naptr_sample = Naptr(host=Host.objects.get(name='some-host.example.org'),
                                  preference=1,
                                  order=1,
                                  flag='a',
                                  service='SER+VICE',
                                  regex='^naptrregex',
                                  replacement='some replacement')
Esempio n. 16
0
    def test_model_two_ipv6s_no_ptroverrides(self):
        """When three or more hosts all have the same IPv6 address and the first host, 
        e.g. the one with the PtrOverride, is deleted, a new PtrOverride is
        not created automatically.
        """
        def _add_ip(host, ipaddress):
            ip = Ipaddress(host=host, ipaddress=ipaddress)
            clean_and_save(ip)
        _add_ip(self.host_ipv6_one, '2001:db8::4')
        _add_ip(self.host_ipv6_two, '2001:db8::4')
        host_ipv6_three = Host(name='host6.example.org',
                        contact='*****@*****.**')

        clean_and_save(host_ipv6_three)
        _add_ip(host_ipv6_three, '2001:db8::4')
        self.host_ipv6_one.delete()
        self.assertEqual(PtrOverride.objects.count(), 0)
        self.assertEqual(Ipaddress.objects.filter(ipaddress='2001:db8::4').count(), 2)
Esempio n. 17
0
    def setUp(self):
        """Define the test client and other test variables."""
        # Needs sample host and sample network to test properly
        self.host_one = Host(name='some-host.example.org',
                             contact='*****@*****.**',
                             ttl=300,
                             loc='23 58 23 N 10 43 50 E 80m',
                             comment='some comment')

        self.network_sample = Network(range='129.240.202.0/20',
                                    description='some description',
                                    vlan=123,
                                    dns_delegated=False)

        clean_and_save(self.host_one)
        # clean_and_save(self.network_sample) # Needed when network ForeignKey is implemented.

        self.ipaddress_sample = Ipaddress(host=Host.objects.get(name='some-host.example.org'),
                                          ipaddress='129.240.202.123',
                                          macaddress='a4:34:d9:0e:88:b9')
Esempio n. 18
0
    def setUp(self):
        """Define the test client and other test variables."""
        self.host_one = Host(name='some-host.example.org',
                             contact='*****@*****.**',
                             ttl=300,
                             loc='23 58 23 N 10 43 50 E 80m',
                             comment='some comment')
        clean_and_save(self.host_one)

        self.log_data = {'id': self.host_one.id,
                         'name': self.host_one.name,
                         'contact': self.host_one.contact,
                         'ttl': self.host_one.ttl,
                         'loc': self.host_one.loc,
                         'comment': self.host_one.comment}

        self.log_entry_one = ModelChangeLog(table_name='Hosts',
                                            table_row=self.host_one.id,
                                            data=self.log_data,
                                            action='saved',
                                            timestamp=timezone.now())
Esempio n. 19
0
    def setUp(self):
        """Define the test client and other test variables."""
        # Needs sample host to test
        self.host_one = Host(name='host1.example.org',
                             contact='*****@*****.**')
        self.host_two = Host(name='host2.example.org',
                        contact='*****@*****.**')

        self.host_ipv6_one = Host(name='host3.example.org',
                             contact='*****@*****.**')
        self.host_ipv6_two = Host(name='host4.example.org',
                        contact='*****@*****.**')
        

        clean_and_save(self.host_one)
        clean_and_save(self.host_two)
        
        clean_and_save(self.host_ipv6_one)
        clean_and_save(self.host_ipv6_two)

        self.ptr_sample = PtrOverride(host=Host.objects.get(name='host1.example.org'),
                                      ipaddress='10.0.0.2')
        self.ptr_ipv6_sample = PtrOverride(host=Host.objects.get(name='host3.example.org'),
                                      ipaddress='2001:db8::beef')
Esempio n. 20
0
class ModelHostsTestCase(TestCase):
    """This class defines the test suite for the Host model."""

    def setUp(self):
        """Define the test client and other test variables."""
        self.host_one = Host(name='host.example.org',
                             contact='*****@*****.**',
                             ttl=300,
                             loc='23 58 23 N 10 43 50 E 80m',
                             comment='some comment')

    def assert_validation_error(self, obj):
        with self.assertRaises(ValidationError) as context:
            obj.full_clean()

    def test_model_can_create_a_host(self):
        """Test that the model is able to create a host."""
        old_count = Host.objects.count()
        clean_and_save(self.host_one)
        new_count = Host.objects.count()
        self.assertLess(old_count, new_count)
        str(self.host_one)

    def test_model_can_create_without_contact(self):
        old_count = Host.objects.count()
        host = Host(name='host2.example.org')
        clean_and_save(host)
        new_count = Host.objects.count()
        self.assertLess(old_count, new_count)

    def test_can_create_wildcard_host(self):
        Host(name='*.example.org').full_clean()
        Host(name='*.sub.example.org').full_clean()

    def test_model_case_insesitive(self):
        """Hosts names must be case insensitive"""
        clean_and_save(self.host_one)
        self.assertEqual(self.host_one, Host.objects.get(name=self.host_one.name.upper()))
        upper = Host(name=self.host_one.name.upper(), contact=self.host_one.contact)
        with self.assertRaises(ValidationError) as context:
            clean_and_save(upper)
        self.assertEqual(context.exception.messages,
                         ['Host with this Name already exists.'])
        hostname = 'UPPERCASE.EXAMPLE.ORG'
        host = Host.objects.create(name=hostname, contact='*****@*****.**')
        # Must do a refresh_from_db() as host.name is otherwise the unmodfied
        # uppercase hostname.
        host.refresh_from_db()
        self.assertEqual(host.name, hostname.lower())

    def test_reject_bad_host_names(self):
        def _assert(hostname):
            host = Host(name=hostname)
            self.assert_validation_error(host)

        _assert('host..example.org')
        _assert('host.example.org.')
        _assert('host-.example.org')
        _assert('looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong.example.org')
        _assert('host*.example.org')


    def test_model_can_change_a_host(self):
        """Test that the model is able to change a host."""
        clean_and_save(self.host_one)
        old_name = self.host_one.name
        new_name = 'some-new-host.example.org'
        host_sample_id = Host.objects.get(name=old_name).id
        self.host_one.name = new_name
        clean_and_save(self.host_one)
        updated_name = Host.objects.get(pk=host_sample_id).name
        self.assertEqual(new_name, updated_name)

    def test_model_can_delete_a_host(self):
        """Test that the model is able to delete a host."""
        clean_and_save(self.host_one)
        old_count = Host.objects.count()
        self.host_one.delete()
        new_count = Host.objects.count()
        self.assertNotEqual(old_count, new_count)

    def test_model_host_can_alter_loc(self):
        """
        Test that the model can validate and store all examples
        from RFC1876, section 4 "Example data".
        """
        clean_and_save(self.host_one)
        for loc in ('42 21 54 N 71 06 18 W -24m 30m',
                    '42 21 43.952 N 71 5 6.344 W -24m 1m 200m',
                    '52 14 05 N 00 08 50 E 10m',
                    '32 7 19 S 116 2 25 E 10m',
                    '42 21 28.764 N 71 00 51.617 W -44m 2000m'):
            self.host_one.loc = loc
            clean_and_save(self.host_one)
Esempio n. 21
0
    def post(self, request, *args, **kwargs):
        if "name" in request.data:
            if self.queryset.filter(name=request.data["name"]).exists():
                content = {'ERROR': 'name already in use'}
                return Response(content, status=status.HTTP_409_CONFLICT)

        if "ipaddress" in request.data and "network" in request.data:
            content = {
                'ERROR': '\'ipaddress\' and \'network\' is mutually exclusive'
            }
            return Response(content, status=status.HTTP_400_BAD_REQUEST)

        # request.data is immutable
        hostdata = request.data.copy()

        if 'network' in hostdata:
            try:
                ipaddress.ip_network(hostdata['network'])
            except ValueError as error:
                content = {'ERROR': str(error)}
                return Response(content, status=status.HTTP_400_BAD_REQUEST)

            network = Network.objects.filter(
                network=hostdata['network']).first()
            if not network:
                content = {'ERROR': 'no such network'}
                return Response(content, status=status.HTTP_404_NOT_FOUND)

            ip = network.get_random_unused()
            if not ip:
                content = {'ERROR': 'no available IP in network'}
                return Response(content, status=status.HTTP_404_NOT_FOUND)

            hostdata['ipaddress'] = ip
            del hostdata['network']

        if 'ipaddress' in hostdata:
            ipkey = hostdata['ipaddress']
            del hostdata['ipaddress']
            host = Host()
            hostserializer = HostSerializer(host, data=hostdata)

            if hostserializer.is_valid(raise_exception=True):
                with transaction.atomic():
                    # XXX: must fix. perform_creates failes as it has no ipaddress and the
                    # the permissions fails for most users. Maybe a nested serializer should fix it?
                    #self.perform_create(hostserializer)
                    hostserializer.save()
                    self.save_log_create(hostserializer)
                    ipdata = {'host': host.pk, 'ipaddress': ipkey}
                    ip = Ipaddress()
                    ipserializer = IpaddressSerializer(ip, data=ipdata)
                    if ipserializer.is_valid(raise_exception=True):
                        self.perform_create(ipserializer)
                        location = request.path + host.name
                        return Response(status=status.HTTP_201_CREATED,
                                        headers={'Location': location})
        else:
            host = Host()
            hostserializer = HostSerializer(host, data=hostdata)
            if hostserializer.is_valid(raise_exception=True):
                self.perform_create(hostserializer)
                location = request.path + host.name
                return Response(status=status.HTTP_201_CREATED,
                                headers={'Location': location})
Esempio n. 22
0
 def test_can_create_wildcard_host(self):
     Host(name='*.example.org').full_clean()
     Host(name='*.sub.example.org').full_clean()
Esempio n. 23
0
class ForwardZonesTestCase(MregAPITestCase):
    """"This class defines the test suite for forward zones API """
    def setUp(self):
        """Define the test client and other variables."""
        super().setUp()
        self.zone_one = ForwardZone(name="example.org",
                                    primary_ns="ns1.example.org",
                                    email="*****@*****.**")
        self.host_one = Host(name='ns1.example.org',
                             contact="*****@*****.**")
        self.host_two = Host(name='ns2.example.org',
                             contact="*****@*****.**")
        self.host_three = Host(name='ns3.example.org',
                               contact="*****@*****.**")
        self.ns_one = NameServer(name='ns1.example.org', ttl=400)
        self.ns_two = NameServer(name='ns2.example.org', ttl=400)
        self.post_data_one = {
            'name': 'example.com',
            'primary_ns': ['ns1.example.org', 'ns2.example.org'],
            'email': "*****@*****.**",
            'refresh': 400,
            'retry': 300,
            'expire': 800,
            'soa_ttl': 350
        }
        self.post_data_two = {
            'name': 'example.net',
            'primary_ns': ['ns1.example.org', 'ns2.example.org'],
            'email': "*****@*****.**"
        }
        self.patch_data = {'refresh': '500', 'expire': '1000'}
        clean_and_save(self.host_one)
        clean_and_save(self.host_two)
        clean_and_save(self.ns_one)
        clean_and_save(self.ns_two)
        clean_and_save(self.zone_one)

    def test_zones_get_404_not_found(self):
        """"Getting a non-existing entry should return 404"""
        self.assert_get_and_404('/zones/forward/nonexisting.example.org')

    def test_zones_get_200_ok(self):
        """"Getting an existing entry should return 200"""
        self.assert_get('/zones/forward/%s' % self.zone_one.name)

    def test_zones_list_200_ok(self):
        """Listing all zones should return 200"""
        response = self.assert_get('/zones/forward/')
        results = response.json()['results']
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0]['name'], self.zone_one.name)

    def test_zones_post_409_name_conflict(self):
        """"Posting a entry that uses a name that is already taken should return 409"""
        response = self.assert_get('/zones/forward/%s' % self.zone_one.name)
        self.assert_post_and_409('/zones/forward/',
                                 {'name': response.data['name']})

    def test_zones_post_201_created(self):
        """"Posting a new zone should return 201 and location"""
        response = self.assert_post('/zones/forward/', self.post_data_one)
        self.assertEqual(
            response['Location'],
            '/api/v1/zones/forward/%s' % self.post_data_one['name'])

    def test_zones_post_serialno(self):
        """serialno should be based on the current date and a sequential number"""
        self.assert_post('/zones/forward/', self.post_data_one)
        self.assert_post('/zones/forward/', self.post_data_two)
        response_one = self.assert_get('/zones/forward/%s' %
                                       self.post_data_one['name'])
        response_two = self.assert_get('/zones/forward/%s' %
                                       self.post_data_two['name'])
        self.assertEqual(response_one.data['serialno'],
                         response_two.data['serialno'])
        self.assertEqual(response_one.data['serialno'], create_serialno())

    def test_zones_patch_serialno(self):
        """Make sure that the zone's serialno_updated_at field is updated when
        the serialno is updated"""
        response = self.assert_post('/zones/forward/', self.post_data_one)
        old_data = self.assert_get(response['Location']).data
        self.assert_patch(response['Location'], data={'serialno': 1000000000})
        new_data = self.assert_get(response['Location']).data
        self.assertLess(old_data['serialno_updated_at'],
                        new_data['serialno_updated_at'])

    def test_zones_patch_403_forbidden_name(self):
        """"Trying to patch the name of an entry should return 403"""
        response = self.assert_get('/zones/forward/%s' % self.zone_one.name)
        self.assert_patch_and_403('/zones/forward/%s' % self.zone_one.name,
                                  {'name': response.data['name']})

    def test_zones_patch_403_forbidden_primary_ns(self):
        """Trying to patch the primary_ns to be a nameserver that isn't in the nameservers list should return 403"""
        self.assert_post('/zones/forward/', self.post_data_two)
        self.assert_patch_and_403(
            '/zones/forward/%s' % self.post_data_two['name'],
            {'primary_ns': self.host_three.name})

    def test_zones_patch_403_forbidden_nameservers(self):
        """Trying to patch the nameservers directly is not allowed."""
        self.assert_post('/zones/forward/', self.post_data_two)
        self.assert_patch_and_403(
            '/zones/forward/%s' % self.post_data_two['name'],
            {'nameservers': self.host_three.name})

    def test_zones_patch_404_not_found(self):
        """"Patching a non-existing entry should return 404"""
        self.assert_patch_and_404("/zones/forward/nonexisting.example.org",
                                  self.patch_data)

    def test_zones_patch_204_no_content(self):
        """"Patching an existing entry with valid data should return 204"""
        self.assert_patch('/zones/forward/%s' % self.zone_one.name,
                          self.patch_data)

    def test_zones_delete_204_no_content(self):
        """"Deleting an existing entry with no conflicts should return 204"""
        # must delete the hosts in that zone first, to allow deletion of the zone.
        self.host_one.delete()
        self.host_two.delete()
        self.assert_delete('/zones/forward/%s' % self.zone_one.name)

    def test_zones_delete_with_hosts_403_forbidden(self):
        """"Deleting an existing zone with Hosts should return 403"""
        self.assert_post('/hosts/', {'name': 'host.example.org'})
        self.assert_delete_and_403('/zones/forward/%s' % self.zone_one.name)

    def test_zones_404_not_found(self):
        """"Deleting a non-existing entry should return 404"""
        self.assert_delete_and_404("/zones/forward/nonexisting.example.org")

    def test_zone_by_hostname_404_not_found(self):
        self.assert_get_and_404(
            '/zones/forward/hostname/invalid.example.wrongtld')

    def test_zone_by_hostname_200_ok(self):
        def _test(hostname, zone, zonetype):
            data = self.assert_get(
                f'/zones/forward/hostname/{hostname}').json()
            self.assertEqual(data[zonetype]['name'], zone)

        _test('host.example.org', 'example.org', 'zone')
        _test('example.org', 'example.org', 'zone')
Esempio n. 24
0
 def _assert(hostname):
     host = Host(name=hostname)
     self.assert_validation_error(host)
Esempio n. 25
0
class ModelHostGroupTestCase(TestCase):
    """This class defines the test suite for the HostGroup model."""

    def setUp(self):
        """Define the test client and other test variables."""
        self.group_one = HostGroup(name='group1')
        self.group_two = HostGroup(name='group2')
        self.group_three = HostGroup(name='group3')
        self.group_four = HostGroup(name='group4')
        self.host_one = Host(name='host1.example.org',
                             contact='*****@*****.**')
        clean_and_save(self.group_one)
        clean_and_save(self.group_two)
        clean_and_save(self.group_three)
        clean_and_save(self.group_four)
        clean_and_save(self.host_one)

    def test_model_can_create_hostgroup(self):
        old_count = HostGroup.objects.count()
        group = HostGroup(name='testing')
        clean_and_save(group)
        new_count = HostGroup.objects.count()
        self.assertLess(old_count, new_count)
        str(group)

    def test_model_can_delete_hostgroup(self):
        old_count = HostGroup.objects.count()
        self.group_one.delete()
        new_count = HostGroup.objects.count()
        self.assertGreater(old_count, new_count)

    def test_model_can_add_host_to_hostgroup(self):
        old_count = self.group_one.hosts.count()
        self.group_one.hosts.add(self.host_one)
        new_count = self.group_one.hosts.count()
        self.assertLess(old_count, new_count)

    def test_model_can_remove_host_from_hostgroup(self):
        self.group_one.hosts.add(self.host_one)
        old_count = self.group_one.hosts.count()
        self.group_one.hosts.remove(self.host_one)
        new_count = self.group_one.hosts.count()
        self.assertGreater(old_count, new_count)

    def test_model_can_add_group_to_group(self):
        old_count = self.group_one.groups.count()
        self.group_one.groups.add(self.group_two)
        new_count = self.group_one.groups.count()
        self.assertNotEqual(old_count, new_count)

    def test_model_can_remove_group_from_group(self):
        self.group_one.groups.add(self.group_two)
        old_count = self.group_one.groups.count()
        self.group_two.parent.remove(self.group_one)
        new_count = self.group_one.groups.count()
        self.assertNotEqual(old_count, new_count)

    def test_model_can_not_be_own_child(self):
        with self.assertRaises(PermissionDenied) as context:
            self.group_one.groups.add(self.group_one)

    def test_model_can_not_be_own_grandchild(self):
        self.group_one.groups.add(self.group_two)
        with self.assertRaises(PermissionDenied) as context:
            self.group_two.groups.add(self.group_one)

    def test_model_group_parent_can_never_be_child_of_child_groupmember(self):
        self.group_one.groups.add(self.group_two)
        self.group_two.groups.add(self.group_three)
        self.group_three.groups.add(self.group_four)
        with self.assertRaises(PermissionDenied) as context:
            self.group_four.groups.add(self.group_one)

    def test_model_altered_updated_at_group_changes(self):
        group1_updated_at = self.group_one.updated_at
        group2_updated_at = self.group_two.updated_at
        self.group_one.groups.add(self.group_two)
        self.group_one.refresh_from_db()
        self.group_two.refresh_from_db()
        self.assertLess(group1_updated_at, self.group_one.updated_at)
        self.assertEqual(group2_updated_at, self.group_two.updated_at)

    def test_model_altered_updated_at_on_hosts_add(self):
        group1_updated_at = self.group_one.updated_at
        self.group_one.hosts.add(self.host_one)
        self.group_one.refresh_from_db()
        self.assertLess(group1_updated_at, self.group_one.updated_at)

    def test_model_altered_updated_at_on_host_rename(self):
        self.group_one.hosts.add(self.host_one)
        self.group_one.refresh_from_db()
        group1_updated_at = self.group_one.updated_at
        self.host_one.name = 'newname'
        self.host_one.save()
        self.group_one.refresh_from_db()
        self.assertLess(group1_updated_at, self.group_one.updated_at)

    def test_model_altered_updated_at_on_host_delete(self):
        self.group_one.hosts.add(self.host_one)
        self.group_one.refresh_from_db()
        group1_updated_at = self.group_one.updated_at
        self.host_one.delete()
        self.group_one.refresh_from_db()
        self.assertLess(group1_updated_at, self.group_one.updated_at)
Esempio n. 26
0
class BACnetIDTest(MregAPITestCase):

    basepath = '/api/v1/bacnet/ids/'

    def basejoin(self, path):
        if type(path) != 'str':
            path = str(path)
        return self.basepath + path

    def setUp(self):
        """Define the test client and other test variables."""
        super().setUp()
        self.host_one = Host(name='host1.example.org',
                             contact='*****@*****.**')
        self.host_one.save()
        self.id_one = BACnetID.objects.create(id=BACnetID.first_unused_id(),
                                              host=self.host_one)
        self.host_two = Host(name='host2.example.org',
                             contact='*****@*****.**')
        self.host_two.save()

    def test_get_200_ok(self):
        """"Getting an existing entry should return 200"""
        self.assert_get(self.basejoin(self.id_one.id))

    def test_list_200_ok(self):
        """List all should return 200"""
        self.id_two = BACnetID.objects.create(id=BACnetID.first_unused_id(),
                                              host=self.host_two)
        response = self.assert_get(self.basepath)
        data = response.json()
        self.assertEqual(data['count'], 2)
        self.assertEqual(len(data['results']), 2)

    def test_get_404_not_found(self):
        """"Getting a non-existing entry should return 404"""
        self.assert_get_and_404(self.basejoin('nonexisting'))

    def test_post_201_created(self):
        """Posting a new entry should return 201 and location"""
        post_data = {'id': 123, 'host': self.host_two.id}
        response = self.assert_post(self.basepath, post_data)
        self.assert_get(response['Location'])
        self.assertEqual(response['Location'],
                         self.basejoin(str(post_data['id'])))

    def test_post_no_id_201_created(self):
        """Posting a new entry without a specific id value should return 201 and location"""
        post_data = {'host': self.host_two.id}
        response = self.assert_post(self.basepath, post_data)
        response = self.assert_get(response['Location'])
        self.assertIn('id', response.data)
        self.assertEquals(response.data['host'], self.host_two.id)

    def test_post_with_hostname_instead_of_id(self):
        post_data = {'hostname': self.host_two.name}
        response = self.assert_post(self.basepath, post_data)
        response = self.assert_get(response['Location'])
        self.assertIn('id', response.data)
        self.assertEquals(response.data['host'], self.host_two.id)

    def test_post_without_host_400(self):
        """Posting a new entry without specifying a host should return 400 bad request"""
        post_data = {'id': 123}
        self.assert_post_and_400(self.basepath, post_data)

    def test_post_with_invalid_host_400(self):
        """Posting a new entry with a host that doesn't exist should return 400 bad request"""
        post_data = {'id': 123, 'host': 12345678}
        self.assert_post_and_400(self.basepath, post_data)

    def test_post_with_already_used_host_409(self):
        """Posting a new entry with a host that already has another BACnet ID should return 409 conflict"""
        post_data = {'host': self.host_one.id}
        self.assert_post_and_409(self.basepath, post_data)

    def test_post_with_already_used_id_409(self):
        """Posting a new entry with a BACnet ID that's in use should return 409 conflict"""
        post_data = {'id': self.id_one.id, 'host': self.host_two.id}
        self.assert_post_and_409(self.basepath, post_data)

    def test_delete_204_ok(self):
        """Delete should return 204 ok"""
        self.assert_delete(self.basejoin(self.id_one.id))

    def test_patch_405(self):
        """Patch method isn't allowed"""
        patch_data = {'id': self.id_one.id}
        self.assert_patch_and_405(self.basejoin(str(self.id_one.id)),
                                  patch_data)

    def test_client_must_be_logged_in(self):
        self.client.logout()
        self.assert_get_and_401(self.basepath)
        self.assert_get_and_401(self.basejoin(self.id_one.id))
        post_data = {'id': 123, 'host': self.host_two.id}
        self.assert_post_and_401(self.basepath, post_data)

    def test_client_must_have_write_access(self):
        self.client = self.get_token_client(superuser=False)
        post_data = {'id': 123, 'host': self.host_two.id}
        self.assert_post_and_403(self.basepath, post_data)

    def test_netgroupregex_permission(self):
        self.client = self.get_token_client(superuser=False)
        group = Group.objects.create(name='testgroup')
        group.user_set.add(self.user)
        Network.objects.create(network='10.1.0.0/25')
        NetGroupRegexPermission.objects.create(group='testgroup',
                                               range='10.1.0.0/25',
                                               regex=r'.*\.example\.org$')
        Ipaddress.objects.create(host=self.host_two, ipaddress='10.1.0.17')
        post_data = {'id': 123, 'host': self.host_two.id}
        self.assert_post(self.basepath, post_data)
Esempio n. 27
0
class ModelPtrOverrideTestCase(TestCase):
    """This class defines the test suite for the PtrOverride model."""

    def setUp(self):
        """Define the test client and other test variables."""
        # Needs sample host to test
        self.host_one = Host(name='host1.example.org',
                             contact='*****@*****.**')
        self.host_two = Host(name='host2.example.org',
                        contact='*****@*****.**')

        self.host_ipv6_one = Host(name='host3.example.org',
                             contact='*****@*****.**')
        self.host_ipv6_two = Host(name='host4.example.org',
                        contact='*****@*****.**')
        

        clean_and_save(self.host_one)
        clean_and_save(self.host_two)
        
        clean_and_save(self.host_ipv6_one)
        clean_and_save(self.host_ipv6_two)

        self.ptr_sample = PtrOverride(host=Host.objects.get(name='host1.example.org'),
                                      ipaddress='10.0.0.2')
        self.ptr_ipv6_sample = PtrOverride(host=Host.objects.get(name='host3.example.org'),
                                      ipaddress='2001:db8::beef')

    def test_model_can_create_ptr(self):
        """Test that the model is able to create a PTR Override."""
        old_count = PtrOverride.objects.count()
        clean_and_save(self.ptr_sample)
        new_count = PtrOverride.objects.count()
        self.assertNotEqual(old_count, new_count)

    def test_model_can_create_ipv6_ptr(self):
        """Test that the model is able to create an IPv6 PTR Override."""
        old_count = PtrOverride.objects.count()
        clean_and_save(self.ptr_ipv6_sample)
        new_count = PtrOverride.objects.count()
        self.assertNotEqual(old_count, new_count)

    def test_model_can_change_ptr(self):
        """Test that the model is able to change a PTR Override."""
        clean_and_save(self.ptr_sample)
        new_ptr = '10.0.0.3'
        self.ptr_sample.ipaddress = new_ptr
        clean_and_save(self.ptr_sample)
        updated_ptr = PtrOverride.objects.filter(host__name='host1.example.org').first().ipaddress
        self.assertEqual(new_ptr, updated_ptr)

    def test_model_can_change_ipv6_ptr(self):
        """Test that the model is able to change an IPv6 PTR Override."""
        clean_and_save(self.ptr_ipv6_sample)
        new_ipv6_ptr = '2011:db8::feed'
        self.ptr_ipv6_sample.ipaddress = new_ipv6_ptr
        clean_and_save(self.ptr_ipv6_sample)
        updated_ipv6_ptr = PtrOverride.objects.filter(host__name='host3.example.org').first().ipaddress
        self.assertEqual(new_ipv6_ptr, updated_ipv6_ptr)

    def test_model_can_delete_ptr(self):
        """Test that the model is able to delete a PTR Override."""
        clean_and_save(self.ptr_sample)
        old_count = PtrOverride.objects.count()
        self.ptr_sample.delete()
        new_count = PtrOverride.objects.count()
        self.assertNotEqual(old_count, new_count)

    def test_model_can_delete_ipv6_ptr(self):
        """Test that the model is able to delete an IPv6 PTR Override."""
        clean_and_save(self.ptr_ipv6_sample)
        old_count = PtrOverride.objects.count()
        self.ptr_ipv6_sample.delete()
        new_count = PtrOverride.objects.count()
        self.assertNotEqual(old_count, new_count)

    def test_model_updated_by_added_ip(self):
        """Test to check that an PtrOverride is added when two hosts share the same ip.
           Also makes sure that the PtrOverride points to the first host which held the ip."""
        initial_count = PtrOverride.objects.count()
        ip_one = Ipaddress(host=self.host_one, ipaddress='10.0.0.1')
        clean_and_save(ip_one)
        one_count = PtrOverride.objects.count()
        ip_two = Ipaddress(host=self.host_two, ipaddress='10.0.0.1')
        clean_and_save(ip_two)
        ptr =  PtrOverride.objects.first()
        self.assertEqual(ptr.host, self.host_one)
        self.assertEqual(ptr.ipaddress, '10.0.0.1')
        self.assertEqual(initial_count, 0)
        self.assertEqual(initial_count, one_count)
        self.assertEqual(PtrOverride.objects.count(), 1)

    def test_model_updated_by_added_ipv6(self):
        """Test to check that an PtrOverride is added when two hosts share the same ipv6.
           Also makes sure that the PtrOverride points to the first host which held the ipv6."""
        initial_count = PtrOverride.objects.count()
        ipv6_one = Ipaddress(host=self.host_ipv6_one, ipaddress='2001:db8::4')
        clean_and_save(ipv6_one)
        one_count = PtrOverride.objects.count()
        ipv6_two = Ipaddress(host=self.host_ipv6_two, ipaddress='2001:db8::4')
        clean_and_save(ipv6_two)
        ptr =  PtrOverride.objects.first()
        self.assertEqual(ptr.host, self.host_ipv6_one)
        self.assertEqual(ptr.ipaddress, '2001:db8::4')
        self.assertEqual(initial_count, 0)
        self.assertEqual(initial_count, one_count)
        self.assertEqual(PtrOverride.objects.count(), 1)

    def test_model_add_and_remove_ip(self):
        """Test to check that an PtrOverride is added when two hosts share the same ip.
           Also makes sure that the PtrOverride points to the first host which held the ip.
           Also makes sure that the PtrOverride is deleted when the host is deleted."""
        initial_count = PtrOverride.objects.count()
        ip_one = Ipaddress(host=self.host_one, ipaddress='10.0.0.1')
        clean_and_save(ip_one)
        one_count = PtrOverride.objects.count()
        ip_two = Ipaddress(host=self.host_two, ipaddress='10.0.0.1')
        clean_and_save(ip_two)
        two_count = PtrOverride.objects.count()
        ptr = PtrOverride.objects.first()
        self.assertEqual(ptr.host, self.host_one)
        self.assertEqual(ptr.ipaddress, '10.0.0.1')
        self.assertEqual(initial_count, 0)
        self.assertEqual(initial_count, one_count)
        self.assertEqual(two_count, 1)
        self.host_one.delete()
        self.assertEqual(PtrOverride.objects.count(), 0)

    def test_model_add_and_remove_ipv6(self):
        """Test to check that an PtrOverride is added when two hosts share the same ipv6.
           Also makes sure that the PtrOverride points to the first host which held the ipv6.
           Also makes sure that the PtrOverride is deleted when the host is deleted."""
        initial_count = PtrOverride.objects.count()
        ipv6_one = Ipaddress(host=self.host_ipv6_one, ipaddress='2001:db8::4')
        clean_and_save(ipv6_one)
        one_count = PtrOverride.objects.count()
        ipv6_two = Ipaddress(host=self.host_ipv6_two, ipaddress='2001:db8::4')
        clean_and_save(ipv6_two)
        two_count = PtrOverride.objects.count()
        ptr = PtrOverride.objects.first()
        self.assertEqual(ptr.host, self.host_ipv6_one)
        self.assertEqual(ptr.ipaddress, '2001:db8::4')
        self.assertEqual(initial_count, 0)
        self.assertEqual(initial_count, one_count)
        self.assertEqual(two_count, 1)
        self.host_ipv6_one.delete()
        self.assertEqual(PtrOverride.objects.count(), 0)

    def test_model_two_ips_no_ptroverrides(self):
        """When three or more hosts all have the same ipaddress and the first host, 
        e.g. the one with the PtrOverride, is deleted, a new PtrOverride is
        not created automatically.
        """
        def _add_ip(host, ipaddress):
            ip = Ipaddress(host=host, ipaddress=ipaddress)
            clean_and_save(ip)
        _add_ip(self.host_one, '10.0.0.1')
        _add_ip(self.host_two, '10.0.0.1')
        host_three = Host(name='host5.example.org',
                        contact='*****@*****.**')

        clean_and_save(host_three)
        _add_ip(host_three, '10.0.0.1')
        self.host_one.delete()
        self.assertEqual(PtrOverride.objects.count(), 0)
        self.assertEqual(Ipaddress.objects.filter(ipaddress='10.0.0.1').count(), 2)

    def test_model_two_ipv6s_no_ptroverrides(self):
        """When three or more hosts all have the same IPv6 address and the first host, 
        e.g. the one with the PtrOverride, is deleted, a new PtrOverride is
        not created automatically.
        """
        def _add_ip(host, ipaddress):
            ip = Ipaddress(host=host, ipaddress=ipaddress)
            clean_and_save(ip)
        _add_ip(self.host_ipv6_one, '2001:db8::4')
        _add_ip(self.host_ipv6_two, '2001:db8::4')
        host_ipv6_three = Host(name='host6.example.org',
                        contact='*****@*****.**')

        clean_and_save(host_ipv6_three)
        _add_ip(host_ipv6_three, '2001:db8::4')
        self.host_ipv6_one.delete()
        self.assertEqual(PtrOverride.objects.count(), 0)
        self.assertEqual(Ipaddress.objects.filter(ipaddress='2001:db8::4').count(), 2)
Esempio n. 28
0
 def test_model_can_create_without_contact(self):
     old_count = Host.objects.count()
     host = Host(name='host2.example.org')
     clean_and_save(host)
     new_count = Host.objects.count()
     self.assertLess(old_count, new_count)