def test_match_failure(self):
        interface = random_string()
        remote_device = random_string()
        remote_interface = random_string()

        for intf in ['none', interface + 'dummy']:
            pattern = InterfacePattern(intf, remote_device, 
                                       remote_interface,
                                       random_string())
            neighbor = Neighbor(remote_device, remote_interface)
            result = pattern.match(interface, [neighbor])
            self.assertFalse(result)

        for remote_d in ['none', remote_device + 'dummy']:
            pattern = InterfacePattern(interface, remote_d, 
                                       remote_interface,
                                       random_string())
            neighbor = Neighbor(remote_device, remote_interface)
            result = pattern.match(interface, [neighbor])
            self.assertFalse(result)

        for remote_i in ['none', remote_interface + 'dummy']:
            pattern = InterfacePattern(interface, remote_device, 
                                       remote_i, random_string())
            neighbor = Neighbor(remote_device, remote_interface)
            result = pattern.match(interface, [neighbor])
            self.assertFalse(result)

        for remote_d in ['none', remote_device + 'dummy']:
            for remote_i in ['none', remote_interface + 'dummy']:
                pattern = InterfacePattern(interface, remote_d, 
                                           remote_i, random_string())
                neighbor = Neighbor(remote_device, remote_interface)
                result = pattern.match(interface, [neighbor])
                self.assertFalse(result)

        for intf in ['none', interface + 'dummy']:
            for remote_i in ['none', remote_interface + 'dummy']:
                pattern = InterfacePattern(intf, remote_device, 
                                           remote_i, random_string())
                neighbor = Neighbor(remote_device, remote_interface)
                result = pattern.match(interface, [neighbor])
                self.assertFalse(result)

        for intf in ['none', interface + 'dummy']:
            for remote_d in ['none', remote_device + 'dummy']:
                pattern = InterfacePattern(intf, remote_d, 
                                           remote_interface, random_string())
                neighbor = Neighbor(remote_device, remote_interface)
                result = pattern.match(interface, [neighbor])
                self.assertFalse(result)

        for intf in ['none', interface + 'dummy']:
            for remote_d in ['none', remote_device + 'dummy']:
                for remote_i in ['none', remote_interface + 'dummy']:
                    pattern = InterfacePattern(intf, remote_d, 
                                               remote_i, random_string())
                    neighbor = Neighbor(remote_device, remote_interface)
                    result = pattern.match(interface, [neighbor])
                    self.assertFalse(result)
예제 #2
0
 def test_load_file_failure(self, m_load, _):
     m_load.side_effect = ztpserver.serializers.SerializerError
     self.assertRaises(ztpserver.serializers.SerializerError,
                       load_file,
                       random_string(),
                       random_string(),
                       random_string())
예제 #3
0
    def test_create_pattern_kwargs(self):
        kwargs = dict(name=random_string(),
                      definition=random_string(),
                      interfaces=None)

        pattern = Pattern(**kwargs)
        self.assertIsInstance(pattern, Pattern)
예제 #4
0
 def test_load_pattern_minimal(self):
     pattern = load_pattern({
         'name': random_string(),
         'definition': random_string(),
         'interfaces': []
     })
     self.assertIsInstance(pattern, Pattern)
    def test_add_nested_folder(self):
        folder = '%s/%s/%s' % \
            (random_string(), random_string(), random_string())
        self.filestore.add_folder(folder)

        filepath = os.path.join(self.filepath, folder)
        self.assertTrue(os.path.exists(filepath))
    def test_create_pattern_kwargs(self):
        kwargs = dict(name=random_string(),
                      definition=random_string(),
                      interfaces=None)

        pattern = Pattern(**kwargs)
        self.assertIsInstance(pattern, Pattern)
예제 #7
0
    def test_add_interface_failure(self):
        kwargs = dict(name=random_string(),
                      definition=random_string(),
                      interfaces=None)

        pattern = Pattern(**kwargs)
        self.assertRaises(PatternError, pattern.add_interface, random_string())
    def test_add_interface_failure(self):
        kwargs = dict(name=random_string(),
                      definition=random_string(),
                      interfaces=None)

        pattern = Pattern(**kwargs)
        self.assertRaises(PatternError, pattern.add_interface, 
                          random_string())
    def test_file_exists(self):
        filename = random_string()
        contents = random_string()
        filepath = os.path.join(self.filepath, filename)
        write_file(contents, filepath)
        assert os.path.exists(filepath)

        self.assertTrue(self.filestore.exists(filename))
    def test_write_file(self):
        filename = random_string()
        contents = random_string()
        self.filestore.write_file(filename, contents)

        filepath = os.path.join(self.filepath, filename)
        self.assertTrue(os.path.exists(filepath))
        self.assertEqual(open(filepath).read(), contents)
예제 #11
0
    def test_match_failure(self):
        interface = random_string()
        remote_device = random_string()
        remote_interface = random_string()

        for intf in ['none', interface + 'dummy']:
            pattern = InterfacePattern(intf, remote_device, remote_interface,
                                       random_string())
            neighbor = Neighbor(remote_device, remote_interface)
            result = pattern.match(interface, [neighbor])
            self.assertFalse(result)

        for remote_d in ['none', remote_device + 'dummy']:
            pattern = InterfacePattern(interface, remote_d, remote_interface,
                                       random_string())
            neighbor = Neighbor(remote_device, remote_interface)
            result = pattern.match(interface, [neighbor])
            self.assertFalse(result)

        for remote_i in ['none', remote_interface + 'dummy']:
            pattern = InterfacePattern(interface, remote_device, remote_i,
                                       random_string())
            neighbor = Neighbor(remote_device, remote_interface)
            result = pattern.match(interface, [neighbor])
            self.assertFalse(result)

        for remote_d in ['none', remote_device + 'dummy']:
            for remote_i in ['none', remote_interface + 'dummy']:
                pattern = InterfacePattern(interface, remote_d, remote_i,
                                           random_string())
                neighbor = Neighbor(remote_device, remote_interface)
                result = pattern.match(interface, [neighbor])
                self.assertFalse(result)

        for intf in ['none', interface + 'dummy']:
            for remote_i in ['none', remote_interface + 'dummy']:
                pattern = InterfacePattern(intf, remote_device, remote_i,
                                           random_string())
                neighbor = Neighbor(remote_device, remote_interface)
                result = pattern.match(interface, [neighbor])
                self.assertFalse(result)

        for intf in ['none', interface + 'dummy']:
            for remote_d in ['none', remote_device + 'dummy']:
                pattern = InterfacePattern(intf, remote_d, remote_interface,
                                           random_string())
                neighbor = Neighbor(remote_device, remote_interface)
                result = pattern.match(interface, [neighbor])
                self.assertFalse(result)

        for intf in ['none', interface + 'dummy']:
            for remote_d in ['none', remote_device + 'dummy']:
                for remote_i in ['none', remote_interface + 'dummy']:
                    pattern = InterfacePattern(intf, remote_d, remote_i,
                                               random_string())
                    neighbor = Neighbor(remote_device, remote_interface)
                    result = pattern.match(interface, [neighbor])
                    self.assertFalse(result)
예제 #12
0
    def test_put_config_success(self):
        resource = random_string()
        body = random_string()
        request = Mock(content_type=constants.CONTENT_TYPE_OTHER, body=body)

        controller = ztpserver.controller.NodesController()
        resp = controller.put_config(request, resource=resource)

        self.assertEqual(resp, dict())
    def test_delete_file(self):
        filename = random_string()
        contents = random_string()
        filepath = os.path.join(self.filepath, filename)
        write_file(contents, filepath)
        assert os.path.exists(filepath)

        self.filestore.delete_file(filename)
        self.assertFalse(os.path.exists(filename))
예제 #14
0
    def test_put_config_success(self):
        resource = random_string()
        body = random_string()
        request = Mock(content_type=constants.CONTENT_TYPE_OTHER, body=body)

        controller = ztpserver.controller.NodesController()
        resp = controller.put_config(request,
                                     resource=resource)

        self.assertEqual(resp, dict())
예제 #15
0
    def test_get_attributes_success(self, m_repository):
        cfg = {'return_value.read.return_value': random_string()}
        m_repository.return_value.get_file.configure_mock(**cfg)

        controller = ztpserver.controller.NodesController()
        (resp, state) = controller.get_attributes(dict(),
                                                  resource=random_string())

        self.assertEqual(state, 'do_substitution')
        self.assertIsInstance(resp, dict)
예제 #16
0
    def test_get_attributes_success(self, m_repository):
        cfg = {'return_value.read.return_value': random_string()}
        m_repository.return_value.get_file.configure_mock(**cfg)

        controller = ztpserver.controller.NodesController()
        (resp, state) = controller.get_attributes(dict(),
                                                  resource=random_string())

        self.assertEqual(state, 'do_substitution')
        self.assertIsInstance(resp, dict)
예제 #17
0
    def test_create_using_systemmac(self, m_repository):
        node = Mock(systemmac=random_string(), serialnumber=random_string())
        body = dict(systemmac=node.systemmac, serialnumber=node.serialnumber)

        request = Request.blank('/nodes')
        request.body = json.dumps(body)

        controller = ztpserver.controller.NodesController()
        with patch.object(controller, 'fsm') as m_fsm:
            controller.create(request)
            self.assertEqual(node.serialnumber, m_fsm.call_args[1]['node_id'])
예제 #18
0
 def m_get_file(arg):
     fileobj = Mock()
     if arg.endswith('.node'):
         fileobj.read.return_value = node.as_dict()
     elif arg.endswith('startup-config'):
         fileobj.read.return_value = random_string()
     elif arg.endswith('pattern'):
         fileobj.read.return_value = random_string()
     else:
         raise ztpserver.repository.FileObjectNotFound
     return fileobj
    def test_get_file(self):

        filename = random_string()
        contents = random_string()
        filepath = os.path.join(self.filepath, filename)
        write_file(contents, filename=filepath)

        obj = self.filestore.get_file(filename)
        self.assertIsInstance(obj, ztpserver.repository.FileObject)
        self.assertTrue(obj.exists)
        self.assertEqual(filepath, obj.name)
예제 #20
0
 def m_get_file(arg):
     fileobj = Mock()
     if arg.endswith('.node'):
         fileobj.read.return_value = node.as_dict()
     elif arg.endswith('startup-config'):
         fileobj.read.return_value = random_string()
     elif arg.endswith('pattern'):
         fileobj.read.return_value = random_string()
     else:
         raise ztpserver.repository.FileObjectNotFound
     return fileobj
    def test_do_put_config_invalid_content_type(self):
        filestore = Mock()
        ztpserver.controller.create_file_store = filestore

        resource = random_string()
        body = random_string()
        request = Mock(content_type='text/html', body=body)

        controller = ztpserver.controller.NodesController()
        self.assertRaises(AssertionError, controller.do_put_config, dict(),
                          resource=resource, request=request)
    def test_add_neighbor_existing_interface(self):
        systemmac = random_string()
        peer = Mock()
        intf = random_string()

        node = Node(systemmac=systemmac)
        node.add_neighbor(intf, [dict(device=peer.remote_device, 
                                      port=peer.remote_interface)])
        self.assertRaises(NodeError, node.add_neighbor,
                          intf, [dict(device=peer.remote_device, 
                                      port=peer.remote_interface)])
예제 #23
0
    def test_create_interface_pattern(self):
        intf = 'Ethernet1'
        remote_device = random_string()
        remote_interface = random_string()

        obj = InterfacePattern(intf, remote_device, remote_interface,
                               random_string())
        reprobj = 'InterfacePattern(interface=%s, remote_device=%s, ' \
                   'remote_interface=%s)' % \
                  (intf, remote_device, remote_interface)
        self.assertEqual(repr(obj), reprobj)
예제 #24
0
    def test_create_using_systemmac(self, m_repository):
        node = Mock(systemmac=random_string(), serialnumber=random_string())
        body = dict(systemmac=node.systemmac, serialnumber=node.serialnumber)

        request = Request.blank('/nodes')
        request.body = json.dumps(body)

        controller = ztpserver.controller.NodesController()
        with patch.object(controller, 'fsm') as m_fsm:
            controller.create(request)
            self.assertEqual(node.serialnumber, m_fsm.call_args[1]['node_id'])
예제 #25
0
    def test_post_config_success(self):
        request = Mock(json=dict(config=random_string()))
        node = Mock(serialnumber=random_string())

        controller = ztpserver.controller.NodesController()
        (resp, state) = controller.post_config(dict(), request=request,
                                               node=node, 
                                               node_id=node.serialnumber)

        self.assertEqual(state, 'set_location')
        self.assertIsInstance(resp, dict)
        self.assertEqual(resp['status'], constants.HTTP_STATUS_CREATED)
    def test_do_put_config_invalid_resource(self):
        filestore = Mock()
        filestore.return_value.write_file = Mock(side_effect=IOError)
        ztpserver.controller.create_file_store = filestore

        resource = random_string()
        body = random_string()
        request = Mock(content_type='text/plain', body=body)

        controller = ztpserver.controller.NodesController()
        self.assertRaises(IOError, controller.do_put_config, dict(),
                          resource=resource, request=request)
    def test_create_interface_pattern(self):
        intf = 'Ethernet1'
        remote_device = random_string()
        remote_interface = random_string()

        obj = InterfacePattern(intf, remote_device,
                               remote_interface,
                               random_string())
        reprobj = 'InterfacePattern(interface=%s, remote_device=%s, ' \
                   'remote_interface=%s)' % \
                  (intf, remote_device, remote_interface)
        self.assertEqual(repr(obj), reprobj)
예제 #28
0
    def test_add_neighbor_existing_interface(self):
        systemmac = random_string()
        peer = Mock()
        intf = random_string()

        node = Node(systemmac=systemmac)
        node.add_neighbor(
            intf,
            [dict(device=peer.remote_device, port=peer.remote_interface)])
        self.assertRaises(
            NodeError, node.add_neighbor, intf,
            [dict(device=peer.remote_device, port=peer.remote_interface)])
    def test_get_definition_w_attributes_no_substitution(self):
        ztpserver.config.runtime.set_value(\
            'disable_topology_validation', False, 'default')

        node = create_node()

        g_attr_foo = random_string()
        attributes_file = create_attributes()
        attributes_file.add_attribute('variables', {'foo': g_attr_foo})

        l_attr_url = random_string()
        definitions_file = create_definition()
        definitions_file.add_attribute('foo', random_string())
        definitions_file.add_action(name='dummy action',
                                    attributes=dict(url=l_attr_url))

        filestore = Mock()

        def exists(filepath):
            if filepath.endswith('startup-config'):
                return False
            return True
        filestore.return_value.exists = Mock(side_effect=exists)

        def get_file(filepath):
            fileobj = Mock()
            if filepath.endswith('node'):
                fileobj.contents = node.as_json()
            elif filepath.endswith('definition'):
                fileobj.contents = definitions_file.as_yaml()
            elif filepath.endswith('attributes'):
                fileobj.contents = attributes_file.as_yaml()
            return fileobj
        filestore.return_value.get_file = Mock(side_effect=get_file)

        ztpserver.controller.create_file_store = filestore

        ztpserver.neighbordb.load_pattern = Mock()
        cfg = {'return_value.match_node.return_value': True}
        ztpserver.neighbordb.load_pattern.configure_mock(**cfg)

        url = '/nodes/%s' % node.systemmac
        request = Request.blank(url, method='GET')
        resp = request.get_response(ztpserver.controller.Router())

        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.content_type, 'application/json')

        attrs = resp.json['actions'][0]['attributes']
        self.assertFalse('variables' in attrs)
        self.assertFalse('foo' in attrs)
        self.assertEqual(attrs['url'], l_attr_url)
예제 #30
0
    def test_config_success(self, m_repository):
        config = create_bootstrap_conf()
        config.add_logging(dict(destination=random_string(),
                                level=random_string()))

        cfg = {'return_value.read.return_value': config.as_dict()}
        m_repository.return_value.get_file.configure_mock(**cfg)

        controller = ztpserver.controller.BootstrapController()
        resp = controller.config(None)

        self.assertEqual(resp['body'], config.as_dict())
        self.assertEqual(resp['content_type'], constants.CONTENT_TYPE_JSON)
예제 #31
0
    def test_post_config_success(self):
        request = Mock(json=dict(config=random_string()))
        node = Mock(serialnumber=random_string())

        controller = ztpserver.controller.NodesController()
        (resp, state) = controller.post_config(dict(),
                                               request=request,
                                               node=node,
                                               node_id=node.serialnumber)

        self.assertEqual(state, 'set_location')
        self.assertIsInstance(resp, dict)
        self.assertEqual(resp['status'], constants.HTTP_STATUS_CREATED)
예제 #32
0
    def test_config_success(self, m_repository):
        config = create_bootstrap_conf()
        config.add_logging(
            dict(destination=random_string(), level=random_string()))

        cfg = {'return_value.read.return_value': config.as_dict()}
        m_repository.return_value.get_file.configure_mock(**cfg)

        controller = ztpserver.controller.BootstrapController()
        resp = controller.config(None)

        self.assertEqual(resp['body'], config.as_dict())
        self.assertEqual(resp['content_type'], constants.CONTENT_TYPE_JSON)
    def test_add_interface_success(cls):
        kwargs = dict(name=random_string(),
                      definition=random_string(),
                      interfaces=None)

        pattern = Pattern(**kwargs)

        remote_remote_device = random_string()
        remote_intf = random_string()
        neighbors = dict(Ethernet1={'device': remote_remote_device,
                                    'port': remote_intf})

        pattern.add_interface(neighbors)
    def test_success(self):
        filename = random_string()
        contents = random_string()

        filepath = write_file(contents, filename)
        path = os.path.dirname(filepath)
        assert os.path.exists(filepath)

        obj = FileObject(filename, path=path)

        self.assertTrue(obj.name, filepath)
        self.assertTrue(obj.exists)
        self.assertEqual(obj.contents, contents)
예제 #35
0
    def test_get_bootstrap_config_success(self):
        config = create_bootstrap_conf()
        config.add_logging(
            dict(destination=random_string(), level=random_string()))

        cfg = {'return_value.read.return_value': config.as_dict()}
        self.m_repository.return_value.get_file.configure_mock(**cfg)

        request = Request.blank('/bootstrap/config')
        resp = request.get_response(ztpserver.controller.Router())

        self.assertEqual(resp.status_code, constants.HTTP_STATUS_OK)
        self.assertEqual(resp.content_type, constants.CONTENT_TYPE_JSON)
        self.assertEqual(json.loads(resp.body), config.as_dict())
예제 #36
0
    def test_match_success(self):
        interface = random_string()
        remote_device = random_string()
        remote_interface = random_string()

        neighbor = Neighbor(remote_device, remote_interface)
        for intf in ['any', interface]:
            for remote_d in ['any', remote_device]:
                for remote_i in ['any', remote_interface]:

                    pattern = InterfacePattern(intf, remote_d, remote_i,
                                               random_string())
                    result = pattern.match(interface, [neighbor])
                    self.assertTrue(result)
    def test_match_success(self):
        interface = random_string()
        remote_device = random_string()
        remote_interface = random_string()

        neighbor = Neighbor(remote_device, remote_interface)
        for intf in ['any', interface]:
            for remote_d in ['any', remote_device]:
                for remote_i in ['any', remote_interface]:
                    
                    pattern = InterfacePattern(intf, remote_d, remote_i,
                                               random_string())
                    result = pattern.match(interface, [neighbor])
                    self.assertTrue(result)
예제 #38
0
    def test_get_bootstrap_config_success(self):
        config = create_bootstrap_conf()
        config.add_logging(dict(destination=random_string(),
                                level=random_string()))

        cfg = {'return_value.read.return_value': config.as_dict()}
        self.m_repository.return_value.get_file.configure_mock(**cfg)

        request = Request.blank('/bootstrap/config')
        resp = request.get_response(ztpserver.controller.Router())

        self.assertEqual(resp.status_code, constants.HTTP_STATUS_OK)
        self.assertEqual(resp.content_type, constants.CONTENT_TYPE_JSON)
        self.assertEqual(json.loads(resp.body), config.as_dict())
예제 #39
0
    def test_get_action_success(self, m_repository):
        contents = random_string()
        cfg = {'return_value.read.return_value': contents}
        m_repository.return_value.get_file.configure_mock(**cfg)

        filename = random_string()
        url = '/actions/%s' % filename

        request = Request.blank(url)
        resp = request.get_response(ztpserver.controller.Router())

        m_repository.return_value.get_file.assert_called_with(url[1:])
        self.assertEqual(resp.status_code, constants.HTTP_STATUS_OK)
        self.assertEqual(resp.content_type, constants.CONTENT_TYPE_PYTHON)
        self.assertEqual(resp.body, contents)
예제 #40
0
    def test_get_action_success(self, m_repository):
        contents = random_string()
        cfg = {'return_value.read.return_value': contents}
        m_repository.return_value.get_file.configure_mock(**cfg)

        filename = random_string()
        url = '/actions/%s' % filename

        request = Request.blank(url)
        resp = request.get_response(ztpserver.controller.Router())

        m_repository.return_value.get_file.assert_called_with(url[1:])
        self.assertEqual(resp.status_code, constants.HTTP_STATUS_OK)
        self.assertEqual(resp.content_type, constants.CONTENT_TYPE_PYTHON)
        self.assertEqual(resp.body, contents)
    def test_add_neighbor(self):
        systemmac = random_string()
        peer = Mock()
        intf = random_string()

        node = Node(systemmac=systemmac)
        node.add_neighbor(intf, [dict(device=peer.remote_device, 
                                      port=peer.remote_interface)])

        self.assertIsNotNone(node.neighbors(intf))

        self.assertEqual(node.neighbors(intf)[0].device, 
                         peer.remote_device)
        self.assertEqual(node.neighbors(intf)[0].interface, 
                         peer.remote_interface)
예제 #42
0
    def test_add_interface_success(cls):
        kwargs = dict(name=random_string(),
                      definition=random_string(),
                      interfaces=None)

        pattern = Pattern(**kwargs)

        remote_remote_device = random_string()
        remote_intf = random_string()
        neighbors = dict(Ethernet1={
            'device': remote_remote_device,
            'port': remote_intf
        })

        pattern.add_interface(neighbors)
예제 #43
0
    def test_post_config(self, m_repository):
        url = '/nodes'
        serialnumber = random_string()
        config = random_string()
        body = json.dumps(dict(serialnumber=serialnumber, config=config))

        m_repository.return_value.exists.return_value = False

        request = Request.blank(url, body=body, method='POST',
                                headers=ztp_headers())
        resp = request.get_response(ztpserver.controller.Router())

        location = 'http://localhost/nodes/%s' % serialnumber
        self.assertEqual(resp.status_code, constants.HTTP_STATUS_CREATED)
        self.assertEqual(resp.location, location)
예제 #44
0
    def test_add_neighbor(self):
        systemmac = random_string()
        peer = Mock()
        intf = random_string()

        node = Node(systemmac=systemmac)
        node.add_neighbor(
            intf,
            [dict(device=peer.remote_device, port=peer.remote_interface)])

        self.assertIsNotNone(node.neighbors(intf))

        self.assertEqual(node.neighbors(intf)[0].device, peer.remote_device)
        self.assertEqual(
            node.neighbors(intf)[0].interface, peer.remote_interface)
예제 #45
0
    def test_get_definition_w_validation_failure(self, m_load_pattern,
                                                 m_repository):
        definitions_file = create_definition()
        definitions_file.add_action()

        serialnumber = random_string()
        node = Mock(serialnumber=serialnumber)
        node.identifier.return_value = serialnumber

        cfg = dict()

        def m_get_file(arg):
            m_file_object = Mock()
            if arg.endswith('.node'):
                m_file_object.read.return_value = node
            elif arg.endswith('definition'):
                m_file_object.read.return_value = definitions_file.as_dict()
            return m_file_object

        cfg['return_value.get_file.side_effect'] = m_get_file
        m_repository.configure_mock(**cfg)

        m_load_pattern.return_value.match_node.return_value = False

        url = '/nodes/%s' % node.serialnumber
        request = Request.blank(url, method='GET')
        resp = request.get_response(ztpserver.controller.Router())

        self.assertEqual(resp.status_code, constants.HTTP_STATUS_BAD_REQUEST)
        self.assertEqual(resp.content_type, constants.CONTENT_TYPE_HTML)
        self.assertEqual(resp.body, str())
예제 #46
0
    def test_success(self, m_repository):
        sha1 = random_string()
        size = random.randint(1, 1000000)
        cfg = {'return_value.get_file.return_value.hash.return_value': 
               sha1,
               'return_value.get_file.return_value.size.return_value': 
               size}
        m_repository.configure_mock(**cfg)
 
        controller = ztpserver.controller.MetaController()
        resp = controller.metadata(None, 
                                   type=random.choice(['files', 'actions']), 
                                   path_info=random_string())

        self.assertEqual(resp['body'], {'sha1': sha1, 'size': size})
        self.assertEqual(resp['content_type'], constants.CONTENT_TYPE_JSON)
예제 #47
0
    def test_success(self, m_repository):
        sha1 = random_string()
        size = random.randint(1, 1000000)
        cfg = {
            'return_value.get_file.return_value.hash.return_value': sha1,
            'return_value.get_file.return_value.size.return_value': size
        }
        m_repository.configure_mock(**cfg)

        controller = ztpserver.controller.MetaController()
        resp = controller.metadata(None,
                                   type=random.choice(['files', 'actions']),
                                   path_info=random_string())

        self.assertEqual(resp['body'], {'sha1': sha1, 'size': size})
        self.assertEqual(resp['content_type'], constants.CONTENT_TYPE_JSON)
    def test_delete_missing_file(self):
        filename = random_string()
        filepath = os.path.join(self.filepath, filename)
        assert not os.path.exists(filepath)

        self.filestore.delete_file(filepath)
        self.assertFalse(os.path.exists(filepath))
예제 #49
0
    def test_get_definition_w_validation_failure(self, m_load_pattern, 
                                                 m_repository):
        definitions_file = create_definition()
        definitions_file.add_action()

        serialnumber = random_string()
        node = Mock(serialnumber=serialnumber)
        node.identifier.return_value = serialnumber

        cfg = dict()

        def m_get_file(arg):
            m_file_object = Mock()
            if arg.endswith('.node'):
                m_file_object.read.return_value = node
            elif arg.endswith('definition'):
                m_file_object.read.return_value = definitions_file.as_dict()
            return m_file_object

        cfg['return_value.get_file.side_effect'] = m_get_file
        m_repository.configure_mock(**cfg)

        m_load_pattern.return_value.match_node.return_value = False

        url = '/nodes/%s' % node.serialnumber
        request = Request.blank(url, method='GET')
        resp = request.get_response(ztpserver.controller.Router())

        self.assertEqual(resp.status_code, constants.HTTP_STATUS_BAD_REQUEST)
        self.assertEqual(resp.content_type, constants.CONTENT_TYPE_HTML)
        self.assertEqual(resp.body, str())
예제 #50
0
    def test_get_definition_w_attributes_no_substitution(
            self, m_load_pattern, m_repository):

        node = create_node()

        g_attr_foo = random_string()
        attributes_file = create_attributes()
        attributes_file.add_attribute('variables', {'foo': g_attr_foo})

        l_attr_url = random_string()
        definitions_file = create_definition()
        definitions_file.add_attribute('foo', random_string())
        definitions_file.add_action(name='dummy action',
                                    attributes=dict(url=l_attr_url))

        cfg = dict()

        def m_get_file(arg):
            m_file_object = Mock()
            if arg.endswith('.node'):
                m_file_object.read.return_value = node.as_dict()
            elif arg.endswith('definition'):
                m_file_object.read.return_value = definitions_file.as_dict()
            elif arg.endswith('attributes'):
                m_file_object.read.return_value = attributes_file.as_dict()
            elif arg.endswith('startup-config'):
                raise ztpserver.repository.FileObjectNotFound
            return m_file_object

        cfg['return_value.get_file'] = Mock(side_effect=m_get_file)

        cfg['return_value.match_node.return_value'] = True
        m_repository.configure_mock(**cfg)

        url = '/nodes/%s' % node.serialnumber
        request = Request.blank(url, method='GET')

        resp = request.get_response(ztpserver.controller.Router())

        self.assertEqual(resp.status_code, constants.HTTP_STATUS_OK)
        self.assertEqual(resp.content_type, constants.CONTENT_TYPE_JSON)

        attrs = resp.json['actions'][0]['attributes']
        self.assertFalse('variables' in attrs)
        self.assertFalse('foo' in attrs)
        self.assertEqual(attrs['url'], l_attr_url)
예제 #51
0
    def test_post_config(self, m_repository):
        url = '/nodes'
        serialnumber = random_string()
        config = random_string()
        body = json.dumps(dict(serialnumber=serialnumber, config=config))

        m_repository.return_value.exists.return_value = False

        request = Request.blank(url,
                                body=body,
                                method='POST',
                                headers=ztp_headers())
        resp = request.get_response(ztpserver.controller.Router())

        location = 'http://localhost/nodes/%s' % serialnumber
        self.assertEqual(resp.status_code, constants.HTTP_STATUS_CREATED)
        self.assertEqual(resp.location, location)
예제 #52
0
    def test_get_startup_config_success_no_definition(self,
                                                      m_replace_config_action):
        resource = random_string()

        action_name = random_string()
        action = {'name': action_name, 'action': 'replace_config'}
        m_replace_config_action.return_value = action
        ztpserver.topology.replace_config_action = Mock(return_value=action)

        controller = ztpserver.controller.NodesController()
        (resp, state) = controller.get_startup_config(dict(),
                                                      resource=resource)

        self.assertEqual(state, 'do_actions')
        self.assertIsInstance(resp, dict)
        self.assertTrue(resp['get_startup_config'])
        self.assertTrue(resp['definition'], 'Autogenerated definition')
        self.assertEqual(resp['definition']['actions'][0]['name'], action_name)
예제 #53
0
    def test_index_success(self, m_substitute, m_repository):
        m_substitute.return_value = random_string()

        controller = ztpserver.controller.BootstrapController()
        resp = controller.index(None)

        self.assertTrue(m_substitute.called)
        self.assertEqual(resp['content_type'], constants.CONTENT_TYPE_PYTHON)
        self.assertEqual(resp['body'], m_substitute.return_value)
예제 #54
0
    def test_get_fsm_missing_node(self, m_repository):
        cfg = {'return_value.get_file.side_effect': FileObjectNotFound}
        m_repository.configure_mock(**cfg)

        url = '/nodes/%s' % random_string()
        request = Request.blank(url, method='GET')
        resp = request.get_response(ztpserver.controller.Router())

        self.assertEqual(resp.status_code, constants.HTTP_STATUS_BAD_REQUEST)
예제 #55
0
    def test_do_validation_disabled_success(self):
        ztpserver.config.runtime.set_value(\
            'disable_topology_validation', True, 'default')

        controller = ztpserver.controller.NodesController()
        (resp, state) = controller.do_validation(dict(),
                                                 resource=random_string())

        self.assertEqual(state, 'get_startup_config')
        self.assertIsInstance(resp, dict)
예제 #56
0
 def test_load_neighbordb(self, _, m_load):
     contents = '''
         variables:
             foo: bar
         patterns:
             - any: any
     '''
     m_load.return_value = yaml.load(contents)
     result = load_neighbordb(random_string())
     self.assertIsNotNone(result)
예제 #57
0
    def test_get_bootstrap_success(self, m_substitute):
        contents = random_string()
        m_substitute.return_value = contents

        request = Request.blank('/bootstrap', headers=ztp_headers())
        resp = request.get_response(ztpserver.controller.Router())

        self.assertEqual(resp.status_code, constants.HTTP_STATUS_OK)
        self.assertEqual(resp.content_type, constants.CONTENT_TYPE_PYTHON)
        self.assertEqual(resp.body, contents)
예제 #58
0
    def test_do_resources_success(self):
        var_foo = random_string()
        ztpserver.controller.resources = Mock(return_value=dict(foo=var_foo))

        definition = create_definition()
        definition.add_action(name='dummy action',
                              attributes=dict(foo=random_string()))

        response = dict(definition=definition.as_dict())

        controller = ztpserver.controller.NodesController()
        (resp, state) = controller.do_resources(response,
                                                node=Mock(),
                                                resource=random_string())

        self.assertEqual(state, 'finalize_response')
        self.assertIsInstance(resp, dict)
        foo = resp['definition']['actions'][0]['attributes']['foo']
        self.assertEqual(foo, var_foo)
예제 #59
0
    def test_set_location_success(self):
        node = Mock(serialnumber=random_string())
        controller = ztpserver.controller.NodesController()
        (resp, state) = controller.set_location(dict(),
                                                node=node,
                                                node_id=node.serialnumber)

        location = 'nodes/%s' % node.serialnumber
        self.assertIsNone(state)
        self.assertIsInstance(resp, dict)
        self.assertEqual(resp['location'], location)
예제 #60
0
    def test_add_neighbors_success(self):
        nodeattrs = create_node()

        remote_device = random_string()
        remote_interface = random_string()
        neighbors = {
            'Ethernet1': [{
                'device': remote_device,
                'port': remote_interface
            }]
        }

        kwargs = nodeattrs.as_dict()
        node = Node(**kwargs)
        node.add_neighbors(neighbors)

        self.assertIsNotNone(node.neighbors('Ethernet1'))
        self.assertEqual(node.neighbors('Ethernet1')[0].device, remote_device)
        self.assertEqual(
            node.neighbors('Ethernet1')[0].interface, remote_interface)