def test_find_obj_by_id(self, many_test_data, session, monkeypatch):
        obj_class = many_test_data['class']
        test_data = many_test_data
        persisted_obj = test_data['factory'].create()
        session.add(persisted_obj)
        session.commit()
        mapper_manager = MapperManager()
        mapper_manager.createMappers(persisted_obj.workspace.name)

        def mock_unsafe_io_with_server(host, test_data, server_io_function,
                                       server_expected_response, server_url,
                                       **payload):
            mocked_response = test_data['mocked_response']
            assert '{0}/ws/{1}/{2}/{3}/'.format(_create_server_api_url(),
                                                persisted_obj.workspace.name,
                                                test_data['api_end_point'],
                                                persisted_obj.id) == server_url
            return MockResponse(mocked_response, 200)

        monkeypatch.setattr(
            persistence.server.server, '_unsafe_io_with_server',
            partial(mock_unsafe_io_with_server, persisted_obj, test_data))
        found_obj = mapper_manager.find(obj_class.class_signature,
                                        persisted_obj.id)
        serialized_obj = test_data['get_properties_function'](found_obj)
        if obj_class not in [Command]:
            metadata = serialized_obj.pop('metadata')
        assert serialized_obj == test_data['serialized_expected_results']
Ejemplo n.º 2
0
class MapperManagerTestSuite(unittest.TestCase):
    def setUp(self):
        self.mapper_manager = MapperManager()

    def tearDown(self):
        pass

    def test_create_and_retrieve_host(self):
        self.mapper_manager.createMappers(NullPersistenceManager())
        host = Host(name="pepito", os="linux")
        host.setDescription("Some description")
        host.setOwned(True)
        self.mapper_manager.save(host)

        h = self.mapper_manager.find(host.getID())

        self.assertNotEquals(
            h,
            None,
            "Host retrieved shouldn't be None")

        self.assertEquals(
            host,
            h,
            "Host created should be the same as host retrieved")
    def test_find_obj_by_id(self, obj_class, many_test_data, session, monkeypatch):
        for test_data in many_test_data:
            persisted_obj = test_data['factory'].create()
            session.add(persisted_obj)
            session.commit()
            mapper_manager = MapperManager()
            mapper_manager.createMappers(persisted_obj.workspace.name)

            def mock_unsafe_io_with_server(host, test_data, server_io_function, server_expected_response, server_url, **payload):
                mocked_response = test_data['mocked_response']
                assert '{0}/ws/{1}/{2}/{3}/'.format(
                    _create_server_api_url(),
                    persisted_obj.workspace.name,
                    test_data['api_end_point'],
                    persisted_obj.id) == server_url
                return MockResponse(mocked_response, 200)

            monkeypatch.setattr(persistence.server.server, '_unsafe_io_with_server', partial(mock_unsafe_io_with_server, persisted_obj, test_data))
            found_obj = mapper_manager.find(obj_class.class_signature, persisted_obj.id)
            serialized_obj = test_data['get_properties_function'](found_obj)
            if obj_class not in [Command]:
                metadata = serialized_obj.pop('metadata')
            assert serialized_obj == test_data['serialized_expected_results']
Ejemplo n.º 4
0
class MapperWithCouchDbManagerInegrationTest(unittest.TestCase):
    def setUp(self):
        self.db_name = self.new_random_workspace_name()

        self.couchdbmanager = CouchDbManager(CONF.getCouchURI())

        self.connector = self.couchdbmanager.createDb(self.db_name)
        self.mapper_manager = MapperManager()
        self.mapper_manager.createMappers(self.connector)

    def new_random_workspace_name(self):
        return ("aworkspace" +
                "".join(random.sample([chr(i)
                                       for i in range(65, 90)], 10))).lower()

    def tearDown(self):
        self.couchdbmanager.deleteDb(self.db_name)
        time.sleep(3)

    def test_host_saving(self):
        host = Host(name="pepito", os="linux")
        host.setDescription("Some description")
        host.setOwned(True)
        self.mapper_manager.save(host)

        self.assertNotEquals(self.connector.getDocument(host.getID()), None,
                             "Document shouldn't be None")

        self.assertEquals(
            self.connector.getDocument(host.getID()).get("name"),
            host.getName(), "Document should have the same host name")

    def test_load_nonexistent_host_using_manager_find(self):
        self.assertEquals(self.connector.getDocument("1234"), None,
                          "Nonexistent host should return None document")

        self.assertEquals(self.mapper_manager.find("1234"), None,
                          "Nonexistent host should return None object")

    def test_load_nonexistent_host_using_mapper_find(self):
        self.assertEquals(self.connector.getDocument("1234"), None,
                          "Nonexistent host should return None document")

        self.assertEquals(
            self.mapper_manager.getMapper(Host.__name__).find("1234"), None,
            "Nonexistent host should return None object")

    def test_find_not_loaded_host(self):
        host = Host(name="pepito", os="linux")
        host.setDescription("Some description")
        host.setOwned(True)
        self.mapper_manager.save(host)

        #create a set of mappers, so we have a clean map
        self.mapper_manager = MapperManager()
        self.mapper_manager.createMappers(self.connector)

        h = self.mapper_manager.find(host.getID())
        self.assertNotEquals(h, None, "Existent host shouldn't return None")

        self.assertEquals(h.getName(), "pepito", "Host name should be pepito")

        self.assertEquals(h.getOS(), "linux", "Host os should be linux")

    def test_host_create_and_delete(self):
        host = Host(name="coquito")
        self.mapper_manager.save(host)
        h_id = host.getID()

        self.assertNotEquals(self.mapper_manager.find(h_id), None,
                             "Host should be in the mapper")

        self.assertNotEquals(self.connector.getDocument(h_id), None,
                             "Host should be in the db")

        self.mapper_manager.remove(h_id)

        self.assertEquals(self.mapper_manager.find(h_id), None,
                          "Host shouldn't exist anymore in the mapper")

        self.assertEquals(self.connector.getDocument(h_id), None,
                          "Host shouldn't exist anymore in the db")

    def test_composite_host(self):
        # add host
        host = Host(name="pepito", os="linux")
        host.setDescription("Some description")
        host.setOwned(True)
        self.mapper_manager.save(host)
        # add inteface
        iface = Interface(name="192.168.10.168", mac="01:02:03:04:05:06")
        iface.setDescription("Some description")
        iface.setOwned(True)
        iface.addHostname("www.test.com")
        iface.setIPv4({
            "address": "192.168.10.168",
            "mask": "255.255.255.0",
            "gateway": "192.168.10.1",
            "DNS": "192.168.10.1"
        })
        iface.setPortsOpened(2)
        iface.setPortsClosed(3)
        iface.setPortsFiltered(4)
        host.addChild(iface)
        self.mapper_manager.save(iface)

        h = self.mapper_manager.find(host.getID())
        self.assertEquals(
            len(h.getAllInterfaces()), len(host.getAllInterfaces()),
            "Interfaces from original host should be equals to retrieved host's interfaces"
        )

        i = self.mapper_manager.find(h.getAllInterfaces()[0].getID())
        self.assertEquals(
            i.getID(), iface.getID(),
            "Interface's id' from original host should be equals to retrieved host's interface's id"
        )

    def test_load_not_loaded_composite_host(self):
        # add host
        host = Host(name="pepito", os="linux")
        host.setDescription("Some description")
        host.setOwned(True)
        self.mapper_manager.save(host)
        # add inteface
        iface = Interface(name="192.168.10.168", mac="01:02:03:04:05:06")
        iface.setDescription("Some description")
        iface.setOwned(True)
        iface.addHostname("www.test.com")
        iface.setIPv4({
            "address": "192.168.10.168",
            "mask": "255.255.255.0",
            "gateway": "192.168.10.1",
            "DNS": "192.168.10.1"
        })
        iface.setPortsOpened(2)
        iface.setPortsClosed(3)
        iface.setPortsFiltered(4)
        host.addChild(iface)
        self.mapper_manager.save(iface)

        #create a set of mappers, so we have a clean map
        self.mapper_manager = MapperManager()
        self.mapper_manager.createMappers(self.connector)

        h = self.mapper_manager.find(host.getID())
        self.assertEquals(
            len(h.getAllInterfaces()), len(host.getAllInterfaces()),
            "Interfaces from original host should be equals to retrieved host's interfaces"
        )

        i = self.mapper_manager.find(h.getAllInterfaces()[0].getID())
        self.assertEquals(
            i.getID(), iface.getID(),
            "Interface's id' from original host should be equals to retrieved host's interface's id"
        )
Ejemplo n.º 5
0
class CompositeMapperTestSuite(unittest.TestCase):
    def setUp(self):
        self.mapper_manager = MapperManager()
        self.mapper_manager.createMappers(NullPersistenceManager())

    def tearDown(self):
        pass

    def create_host(self):
        host = Host(name="pepito", os="linux")
        host.setDescription("Some description")
        host.setOwned(True)
        return host

    def create_interface(self):
        iface = Interface(name="192.168.10.168", mac="01:02:03:04:05:06")
        iface.setDescription("Some description")
        iface.setOwned(True)
        iface.addHostname("www.test.com")
        iface.setIPv4({
            "address": "192.168.10.168",
            "mask": "255.255.255.0",
            "gateway": "192.168.10.1",
            "DNS": "192.168.10.1"
        })
        iface.setPortsOpened(2)
        iface.setPortsClosed(3)
        iface.setPortsFiltered(4)
        return iface

    def test_find_composite_host(self):
        '''
        We are going to create a host, then save it.
        Next we create an interface and then add it
        to the host, and finally save it.
        '''
        # add host
        host = self.create_host()
        self.mapper_manager.save(host)
        # add inteface
        interface = self.create_interface()
        host.addChild(interface)
        self.mapper_manager.save(interface)

        h = self.mapper_manager.find(host.getID())
        self.assertEquals(
            h.getAllInterfaces(), host.getAllInterfaces(),
            "Interfaces from original host should be equals to retrieved host's interfaces"
        )

    def test_load_composite_one_host_one_interface(self):
        '''
        We are going to create a host, then save it.
        Next we create an interface and then add it
        to the host, and finally save it.
        '''

        doc_host = {
            "type": "Host",
            "_id": "1234",
            "name": "pepito",
            "owned": False,
            "parent": None,
            "owner": None,
            "description": "some description",
            "metadata": None,
            "os": "linux",
            "default_gateway": None
        }

        doc_interface = {
            "type": "Interface",
            "_id": "5678",
            "name": "192.168.10.168",
            "owned": False,
            "parent": "1234",
            "owner": None,
            "description": "some description",
            "metadata": None,
            "mac": "01:02:03:04:05:06",
            "network_segment": None,
            "hostnames": ["www.test.com"],
            "ipv4": {
                "address": "192.168.10.168",
                "mask": "255.255.255.0",
                "gateway": "192.168.10.1",
                "DNS": "192.168.10.1"
            },
            "ipv6": {},
            "ports": {
                "opened": 2,
                "closed": 3,
                "filtered": 4,
            }
        }

        pmanager = mock(NullPersistenceManager)
        when(pmanager).getDocument("1234").thenReturn(doc_host)
        when(pmanager).getDocument("5678").thenReturn(doc_interface)
        when(pmanager).getChildren(any(str)).thenReturn([])
        when(pmanager).getChildren("1234").thenReturn([{
            '_id': "5678",
            'type': "Interface"
        }])
        self.mapper_manager.createMappers(pmanager)

        host = self.mapper_manager.find("1234")
        self.assertNotEquals(host, None, "Existent host shouldn't be None")

        self.assertEquals(len(host.getAllInterfaces()), 1,
                          "Host should have one interface")

        iface = self.mapper_manager.find("5678")
        self.assertNotEquals(iface, None,
                             "Existent interface shouldn't be None")

        self.assertEquals(
            host.getInterface("5678"), iface,
            "Interface inside host should be equals to retrieved interface")

        self.assertEquals(iface.getParent(), host,
                          "Host should be the interface's parent")

    def test_load_composite_one_host_two_interfaces(self):

        doc_host = {
            "type": "Host",
            "_id": "1234",
            "name": "pepito",
            "owned": False,
            "parent": None,
            "owner": None,
            "description": "some description",
            "metadata": None,
            "os": "linux",
            "default_gateway": None
        }

        doc_interface1 = {
            "type": "Interface",
            "_id": "5678",
            "name": "192.168.10.168",
            "owned": False,
            "parent": "1234",
            "owner": None,
            "description": "some description",
            "metadata": None,
            "mac": "01:02:03:04:05:06",
            "network_segment": None,
            "hostnames": ["www.test.com"],
            "ipv4": {
                "address": "192.168.10.168",
                "mask": "255.255.255.0",
                "gateway": "192.168.10.1",
                "DNS": "192.168.10.1"
            },
            "ipv6": {},
            "ports": {
                "opened": 2,
                "closed": 3,
                "filtered": 4,
            }
        }

        doc_interface2 = {
            "type": "Interface",
            "_id": "6789",
            "name": "192.168.10.168",
            "owned": False,
            "parent": "1234",
            "owner": None,
            "description": "some description",
            "metadata": None,
            "mac": "01:02:03:04:05:06",
            "network_segment": None,
            "hostnames": ["www.test.com"],
            "ipv4": {
                "address": "192.168.10.168",
                "mask": "255.255.255.0",
                "gateway": "192.168.10.1",
                "DNS": "192.168.10.1"
            },
            "ipv6": {},
            "ports": {
                "opened": 2,
                "closed": 3,
                "filtered": 4,
            }
        }

        pmanager = mock(NullPersistenceManager)
        when(pmanager).getDocument("1234").thenReturn(doc_host)
        when(pmanager).getDocument("5678").thenReturn(doc_interface1)
        when(pmanager).getDocument("6789").thenReturn(doc_interface2)
        when(pmanager).getChildren(any(str)).thenReturn([])
        when(pmanager).getChildren("1234").thenReturn([{
            '_id': "5678",
            'type': "Interface"
        }, {
            '_id': "6789",
            'type': "Interface"
        }])
        self.mapper_manager.createMappers(pmanager)

        host = self.mapper_manager.find("1234")
        self.assertNotEquals(host, None, "Existent host shouldn't be None")

        self.assertEquals(len(host.getAllInterfaces()), 2,
                          "Host should have two interface")

        iface1 = self.mapper_manager.find("5678")
        self.assertNotEquals(iface1, None,
                             "Existent interface1 shouldn't be None")

        self.assertEquals(
            host.getInterface("5678"), iface1,
            "Interface1 inside host should be equals to retrieved interface1")

        self.assertEquals(iface1.getParent(), host,
                          "Host should be the interface1's parent")

        iface2 = self.mapper_manager.find("6789")
        self.assertNotEquals(iface2, None,
                             "Existent interface2 shouldn't be None")

        self.assertEquals(
            host.getInterface("6789"), iface2,
            "Interface2 inside host should be equals to retrieved interface2")

        self.assertEquals(iface2.getParent(), host,
                          "Host should be the interface2's parent")

    def test_load_composite_one_host_one_interface_two_services(self):

        doc_host = {
            "type": "Host",
            "_id": "1234",
            "name": "pepito",
            "owned": False,
            "parent": None,
            "owner": None,
            "description": "some description",
            "metadata": None,
            "os": "linux",
            "default_gateway": None
        }

        doc_interface = {
            "type": "Interface",
            "_id": "5678",
            "name": "192.168.10.168",
            "owned": False,
            "parent": "1234",
            "owner": None,
            "description": "some description",
            "metadata": None,
            "mac": "01:02:03:04:05:06",
            "network_segment": None,
            "hostnames": ["www.test.com"],
            "ipv4": {
                "address": "192.168.10.168",
                "mask": "255.255.255.0",
                "gateway": "192.168.10.1",
                "DNS": "192.168.10.1"
            },
            "ipv6": {},
            "ports": {
                "opened": 2,
                "closed": 3,
                "filtered": 4,
            }
        }

        doc_service1 = {
            "type": "Service",
            "_id": "abcd",
            "name": "http",
            "owned": False,
            "parent": "5678",
            "owner": None,
            "description": "some description",
            "metadata": None,
            "protocol": "tcp",
            "status": "open",
            "ports": [80],
            "version": "Apache 2.4"
        }

        doc_service2 = {
            "type": "Service",
            "_id": "efgh",
            "name": "ssh",
            "owned": False,
            "parent": "5678",
            "owner": None,
            "description": "some description",
            "metadata": None,
            "protocol": "tcp",
            "status": "open",
            "ports": [22],
            "version": "OpenSSH"
        }

        pmanager = mock(NullPersistenceManager)
        when(pmanager).getDocument("1234").thenReturn(doc_host)
        when(pmanager).getDocument("5678").thenReturn(doc_interface)
        when(pmanager).getDocument("abcd").thenReturn(doc_service1)
        when(pmanager).getDocument("efgh").thenReturn(doc_service2)
        when(pmanager).getChildren(any(str)).thenReturn([])
        when(pmanager).getChildren("1234").thenReturn([{
            '_id': "5678",
            'type': "Interface"
        }])
        when(pmanager).getChildren("5678").thenReturn([{
            '_id': "abcd",
            'type': "Service"
        }, {
            '_id': "efgh",
            'type': "Service"
        }])
        self.mapper_manager.createMappers(pmanager)

        iface = self.mapper_manager.find("5678")
        self.assertNotEquals(iface, None,
                             "Existent interface shouldn't be None")

        # Lets make sure that the host was created
        host = iface.getParent()
        self.assertEquals(host.getID(), "1234",
                          "Interface's parent id should be 1234")

        self.assertEquals(
            host, self.mapper_manager.find("1234"),
            "Interface1's parent should be equals to the host retrieved")

        self.assertEquals(len(iface.getAllServices()), 2,
                          "Interface should have two services")

        services_ids = [srv.getID() for srv in iface.getAllServices()]
        self.assertIn(
            "abcd", services_ids,
            "Service 'abcd' should be one of the interface's services")

        self.assertIn(
            "efgh", services_ids,
            "Service 'efgh' should be one of the interface's services")

    def test_load_composite_one_host_one_note_one_vuln_one_credential(self):

        doc_host = {
            "type": "Host",
            "_id": "1234",
            "name": "pepito",
            "owned": False,
            "parent": None,
            "owner": None,
            "description": "some description",
            "metadata": None,
            "os": "linux",
            "default_gateway": None
        }

        doc_note = {
            "type": "Note",
            "_id": "note1",
            "name": "Note1",
            "owned": False,
            "parent": "1234",
            "owner": None,
            "description": "some description",
            "metadata": None,
            "text": "this is a note"
        }

        doc_vuln = {
            "type": "Vulnerability",
            "_id": "vuln1",
            "name": "Vuln1",
            "owned": False,
            "parent": "1234",
            "owner": None,
            "description": "some description",
            "metadata": None,
            "desc": "this is a vuln",
            "severity": "high",
            "refs": ["cve1", "cve2"]
        }

        doc_cred = {
            "type": "Cred",
            "_id": "cred1",
            "name": "Vuln1",
            "owned": False,
            "parent": "1234",
            "owner": None,
            "description": "some description",
            "metadata": None,
            "username": "******",
            "password": "******"
        }

        pmanager = mock(NullPersistenceManager)
        when(pmanager).getDocument("1234").thenReturn(doc_host)
        when(pmanager).getDocument("note1").thenReturn(doc_note)
        when(pmanager).getDocument("vuln1").thenReturn(doc_vuln)
        when(pmanager).getDocument("cred1").thenReturn(doc_cred)
        when(pmanager).getChildren(any(str)).thenReturn([])
        when(pmanager).getChildren("1234").thenReturn([{
            '_id': "note1",
            'type': "Note"
        }, {
            '_id': "vuln1",
            'type': "Vulnerability"
        }, {
            '_id': "cred1",
            'type': "Cred"
        }])

        self.mapper_manager.createMappers(pmanager)

        host = self.mapper_manager.find("1234")
        self.assertNotEquals(host, None, "Existent host shouldn't be None")

        self.assertEquals(len(host.getNotes()), 1, "Host should have one note")

        self.assertEquals(len(host.getVulns()), 1, "Host should have one vuln")

        self.assertEquals(len(host.getCreds()), 1, "Host should have one cred")

    def test_delete_interface_from_composite_one_host_one_interface_two_services(
            self):
        doc_host = {
            "type": "Host",
            "_id": "1234",
            "name": "pepito",
            "owned": False,
            "parent": None,
            "owner": None,
            "description": "some description",
            "metadata": None,
            "os": "linux",
            "default_gateway": None
        }

        doc_interface = {
            "type": "Interface",
            "_id": "5678",
            "name": "192.168.10.168",
            "owned": False,
            "parent": "1234",
            "owner": None,
            "description": "some description",
            "metadata": None,
            "mac": "01:02:03:04:05:06",
            "network_segment": None,
            "hostnames": ["www.test.com"],
            "ipv4": {
                "address": "192.168.10.168",
                "mask": "255.255.255.0",
                "gateway": "192.168.10.1",
                "DNS": "192.168.10.1"
            },
            "ipv6": {},
            "ports": {
                "opened": 2,
                "closed": 3,
                "filtered": 4,
            }
        }

        doc_service1 = {
            "type": "Service",
            "_id": "abcd",
            "name": "http",
            "owned": False,
            "parent": "5678",
            "owner": None,
            "description": "some description",
            "metadata": None,
            "protocol": "tcp",
            "status": "open",
            "ports": [80],
            "version": "Apache 2.4"
        }

        doc_service2 = {
            "type": "Service",
            "_id": "efgh",
            "name": "ssh",
            "owned": False,
            "parent": "5678",
            "owner": None,
            "description": "some description",
            "metadata": None,
            "protocol": "tcp",
            "status": "open",
            "ports": [22],
            "version": "OpenSSH"
        }

        self.pmanager = mock(NullPersistenceManager)
        when(self.pmanager).getDocument("1234").thenReturn(doc_host)
        when(self.pmanager).getDocument("5678").thenReturn(doc_interface)
        when(self.pmanager).getDocument("abcd").thenReturn(doc_service1)
        when(self.pmanager).getDocument("efgh").thenReturn(doc_service2)
        when(self.pmanager).getChildren(any(str)).thenReturn([])
        when(self.pmanager).getChildren("1234").thenReturn([{
            '_id': "5678",
            'type': "Interface"
        }])
        when(self.pmanager).getChildren("5678").thenReturn([{
            '_id': "abcd",
            'type': "Service"
        }, {
            '_id': "efgh",
            'type': "Service"
        }])

        self.mapper_manager.createMappers(self.pmanager)

        # load the host first
        host = self.mapper_manager.find("1234")

        #then remove the interface
        iface_id = host.getInterface("5678").getID()
        host.deleteChild(iface_id)

        def fake_remove(id):
            when(self.pmanager).getDocument(id).thenReturn(None)

        when(self.pmanager).remove("5678").thenReturn(fake_remove("5678"))
        when(self.pmanager).remove("abcd").thenReturn(fake_remove("abcd"))
        when(self.pmanager).remove("efgh").thenReturn(fake_remove("efgh"))
        self.mapper_manager.remove(iface_id)

        # now we make sure that we have removed the interface
        # and the services

        self.assertEquals(len(host.getAllInterfaces()), 0,
                          "Host should have no interfaces")

        self.assertEquals(self.mapper_manager.find("5678"), None,
                          "Service abcd shouldn't exist anymore")

        self.assertEquals(self.mapper_manager.find("abcd"), None,
                          "Service abcd shouldn't exist anymore")

        self.assertEquals(self.mapper_manager.find("efgh"), None,
                          "Service efgh shouldn't exist anymore")

    def test_load_composite_one_workspace_two_hosts(self):

        doc_ws = {
            "type": "Workspace",
            "_id": "test_ws",
            "name": "test_ws",
            "description": "some description",
            "customer": "Infobyte",
            "sdate": None,
            "fdate": None
        }

        doc_host1 = {
            "type": "Host",
            "_id": "1234",
            "name": "pepito",
            "owned": False,
            "parent": "test_ws",
            "owner": None,
            "description": "some description",
            "metadata": None,
            "os": "linux",
            "default_gateway": None
        }

        doc_host2 = {
            "type": "Host",
            "_id": "5678",
            "name": "coquito",
            "owned": False,
            "parent": "test_ws",
            "owner": None,
            "description": "some description",
            "metadata": None,
            "os": "windows",
            "default_gateway": None
        }

        pmanager = NullPersistenceManager()
        when(pmanager).getDocument("test_ws").thenReturn(doc_ws)
        when(pmanager).getDocument("1234").thenReturn(doc_host1)
        when(pmanager).getDocument("5678").thenReturn(doc_host2)
        when(pmanager).getDocsByFilter(any, any).thenReturn([])
        when(pmanager).getDocsByFilter(any(str), None).thenReturn([])
        when(pmanager).getDocsByFilter(None, None).thenReturn([])
        when(pmanager).getDocsByFilter("test_ws", None).thenReturn([{
            '_id':
            "1234",
            'type':
            "Host"
        }, {
            '_id':
            "5678",
            'type':
            "Host"
        }])
        #when(pmanager).getDocsByFilter(None, "Host").thenReturn([])

        self.mapper_manager.createMappers(pmanager)

        ws = self.mapper_manager.find("test_ws")
        self.assertNotEquals(ws, None, "Existent Workspace shouldn't be None")

        self.assertEquals(len(ws.getHosts()), 2,
                          "Workspace should have two hosts")

        hosts_ids = [host.getID() for host in ws.getHosts()]
        self.assertIn("1234", hosts_ids,
                      "Host '1234' should be one of the workspace's hosts")

        self.assertIn("5678", hosts_ids,
                      "Host '5678' should be one of the workspace's hosts")
Ejemplo n.º 6
0
class CompositeMapperTestSuite(unittest.TestCase):
    def setUp(self):
        self.mapper_manager = MapperManager()
        self.mapper_manager.createMappers(NullPersistenceManager())

    def tearDown(self):
        pass

    def create_host(self):
        host = Host(name="pepito", os="linux")
        host.setDescription("Some description")
        host.setOwned(True)
        return host

    def create_interface(self):
        iface = Interface(name="192.168.10.168", mac="01:02:03:04:05:06")
        iface.setDescription("Some description")
        iface.setOwned(True)
        iface.addHostname("www.test.com")
        iface.setIPv4({
            "address": "192.168.10.168",
            "mask": "255.255.255.0",
            "gateway": "192.168.10.1",
            "DNS": "192.168.10.1"
        })
        iface.setPortsOpened(2)
        iface.setPortsClosed(3)
        iface.setPortsFiltered(4)
        return iface

    def test_find_composite_host(self):
        '''
        We are going to create a host, then save it.
        Next we create an interface and then add it
        to the host, and finally save it.
        '''
        # add host
        host = self.create_host()
        self.mapper_manager.save(host)
        # add inteface
        interface = self.create_interface()
        host.addChild(interface)
        self.mapper_manager.save(interface)

        h = self.mapper_manager.find(host.getID())
        self.assertEquals(
            h.getAllInterfaces(),
            host.getAllInterfaces(),
            "Interfaces from original host should be equals to retrieved host's interfaces")

    def test_load_composite_one_host_one_interface(self):
        '''
        We are going to create a host, then save it.
        Next we create an interface and then add it
        to the host, and finally save it.
        '''

        doc_host = {
            "type": "Host",
            "_id": "1234",
            "name": "pepito",
            "owned": False,
            "parent": None,
            "owner": None,
            "description": "some description",
            "metadata": None,
            "os": "linux",
            "default_gateway": None
        }

        doc_interface = {
            "type": "Interface",
            "_id": "5678",
            "name": "192.168.10.168",
            "owned": False,
            "parent": "1234",
            "owner": None,
            "description": "some description",
            "metadata": None,
            "mac": "01:02:03:04:05:06",
            "network_segment": None,
            "hostnames": ["www.test.com"],
            "ipv4": {
                "address": "192.168.10.168",
                "mask": "255.255.255.0",
                "gateway": "192.168.10.1",
                "DNS": "192.168.10.1"
            },
            "ipv6": {},
            "ports": {
                "opened": 2,
                "closed": 3,
                "filtered": 4,
            }
        }

        pmanager = mock(NullPersistenceManager)
        when(pmanager).getDocument("1234").thenReturn(doc_host)
        when(pmanager).getDocument("5678").thenReturn(doc_interface)
        when(pmanager).getChildren(any(str)).thenReturn([])
        when(pmanager).getChildren("1234").thenReturn([{'_id': "5678", 'type': "Interface"}])
        self.mapper_manager.createMappers(pmanager)

        host = self.mapper_manager.find("1234")
        self.assertNotEquals(
            host,
            None,
            "Existent host shouldn't be None")

        self.assertEquals(
            len(host.getAllInterfaces()),
            1,
            "Host should have one interface")

        iface = self.mapper_manager.find("5678")
        self.assertNotEquals(
            iface,
            None,
            "Existent interface shouldn't be None")

        self.assertEquals(
            host.getInterface("5678"),
            iface,
            "Interface inside host should be equals to retrieved interface")

        self.assertEquals(
            iface.getParent(),
            host,
            "Host should be the interface's parent")

    def test_load_composite_one_host_two_interfaces(self):

        doc_host = {
            "type": "Host",
            "_id": "1234",
            "name": "pepito",
            "owned": False,
            "parent": None,
            "owner": None,
            "description": "some description",
            "metadata": None,
            "os": "linux",
            "default_gateway": None
        }

        doc_interface1 = {
            "type": "Interface",
            "_id": "5678",
            "name": "192.168.10.168",
            "owned": False,
            "parent": "1234",
            "owner": None,
            "description": "some description",
            "metadata": None,
            "mac": "01:02:03:04:05:06",
            "network_segment": None,
            "hostnames": ["www.test.com"],
            "ipv4": {
                "address": "192.168.10.168",
                "mask": "255.255.255.0",
                "gateway": "192.168.10.1",
                "DNS": "192.168.10.1"
            },
            "ipv6": {},
            "ports": {
                "opened": 2,
                "closed": 3,
                "filtered": 4,
            }
        }

        doc_interface2 = {
            "type": "Interface",
            "_id": "6789",
            "name": "192.168.10.168",
            "owned": False,
            "parent": "1234",
            "owner": None,
            "description": "some description",
            "metadata": None,
            "mac": "01:02:03:04:05:06",
            "network_segment": None,
            "hostnames": ["www.test.com"],
            "ipv4": {
                "address": "192.168.10.168",
                "mask": "255.255.255.0",
                "gateway": "192.168.10.1",
                "DNS": "192.168.10.1"
            },
            "ipv6": {},
            "ports": {
                "opened": 2,
                "closed": 3,
                "filtered": 4,
            }
        }

        pmanager = mock(NullPersistenceManager)
        when(pmanager).getDocument("1234").thenReturn(doc_host)
        when(pmanager).getDocument("5678").thenReturn(doc_interface1)
        when(pmanager).getDocument("6789").thenReturn(doc_interface2)
        when(pmanager).getChildren(any(str)).thenReturn([])
        when(pmanager).getChildren("1234").thenReturn([{'_id': "5678", 'type': "Interface"}, {'_id': "6789", 'type': "Interface"}])
        self.mapper_manager.createMappers(pmanager)

        host = self.mapper_manager.find("1234")
        self.assertNotEquals(
            host,
            None,
            "Existent host shouldn't be None")

        self.assertEquals(
            len(host.getAllInterfaces()),
            2,
            "Host should have two interface")

        iface1 = self.mapper_manager.find("5678")
        self.assertNotEquals(
            iface1,
            None,
            "Existent interface1 shouldn't be None")

        self.assertEquals(
            host.getInterface("5678"),
            iface1,
            "Interface1 inside host should be equals to retrieved interface1")

        self.assertEquals(
            iface1.getParent(),
            host,
            "Host should be the interface1's parent")

        iface2 = self.mapper_manager.find("6789")
        self.assertNotEquals(
            iface2,
            None,
            "Existent interface2 shouldn't be None")

        self.assertEquals(
            host.getInterface("6789"),
            iface2,
            "Interface2 inside host should be equals to retrieved interface2")

        self.assertEquals(
            iface2.getParent(),
            host,
            "Host should be the interface2's parent")

    def test_load_composite_one_host_one_interface_two_services(self):

        doc_host = {
            "type": "Host",
            "_id": "1234",
            "name": "pepito",
            "owned": False,
            "parent": None,
            "owner": None,
            "description": "some description",
            "metadata": None,
            "os": "linux",
            "default_gateway": None
        }

        doc_interface = {
            "type": "Interface",
            "_id": "5678",
            "name": "192.168.10.168",
            "owned": False,
            "parent": "1234",
            "owner": None,
            "description": "some description",
            "metadata": None,
            "mac": "01:02:03:04:05:06",
            "network_segment": None,
            "hostnames": ["www.test.com"],
            "ipv4": {
                "address": "192.168.10.168",
                "mask": "255.255.255.0",
                "gateway": "192.168.10.1",
                "DNS": "192.168.10.1"
            },
            "ipv6": {},
            "ports": {
                "opened": 2,
                "closed": 3,
                "filtered": 4,
            }
        }

        doc_service1 = {
            "type": "Service",
            "_id": "abcd",
            "name": "http",
            "owned": False,
            "parent": "5678",
            "owner": None,
            "description": "some description",
            "metadata": None,
            "protocol": "tcp",
            "status": "open",
            "ports": [80],
            "version": "Apache 2.4"
        }

        doc_service2 = {
            "type": "Service",
            "_id": "efgh",
            "name": "ssh",
            "owned": False,
            "parent": "5678",
            "owner": None,
            "description": "some description",
            "metadata": None,
            "protocol": "tcp",
            "status": "open",
            "ports": [22],
            "version": "OpenSSH"
        }

        pmanager = mock(NullPersistenceManager)
        when(pmanager).getDocument("1234").thenReturn(doc_host)
        when(pmanager).getDocument("5678").thenReturn(doc_interface)
        when(pmanager).getDocument("abcd").thenReturn(doc_service1)
        when(pmanager).getDocument("efgh").thenReturn(doc_service2)
        when(pmanager).getChildren(any(str)).thenReturn([])
        when(pmanager).getChildren("1234").thenReturn([{'_id': "5678", 'type': "Interface"}])
        when(pmanager).getChildren("5678").thenReturn([{'_id': "abcd", 'type': "Service"}, {'_id': "efgh", 'type': "Service"}])
        self.mapper_manager.createMappers(pmanager)

        iface = self.mapper_manager.find("5678")
        self.assertNotEquals(
            iface,
            None,
            "Existent interface shouldn't be None")

        # Lets make sure that the host was created
        host = iface.getParent()
        self.assertEquals(
            host.getID(),
            "1234",
            "Interface's parent id should be 1234")

        self.assertEquals(
            host,
            self.mapper_manager.find("1234"),
            "Interface1's parent should be equals to the host retrieved")

        self.assertEquals(
            len(iface.getAllServices()),
            2,
            "Interface should have two services")

        services_ids = [srv.getID() for srv in iface.getAllServices()]
        self.assertIn(
            "abcd",
            services_ids,
            "Service 'abcd' should be one of the interface's services")

        self.assertIn(
            "efgh",
            services_ids,
            "Service 'efgh' should be one of the interface's services")

    def test_load_composite_one_host_one_note_one_vuln_one_credential(self):

        doc_host = {
            "type": "Host",
            "_id": "1234",
            "name": "pepito",
            "owned": False,
            "parent": None,
            "owner": None,
            "description": "some description",
            "metadata": None,
            "os": "linux",
            "default_gateway": None
        }

        doc_note = {
            "type": "Note",
            "_id": "note1",
            "name": "Note1",
            "owned": False,
            "parent": "1234",
            "owner": None,
            "description": "some description",
            "metadata": None,
            "text": "this is a note"
        }

        doc_vuln = {
            "type": "Vulnerability",
            "_id": "vuln1",
            "name": "Vuln1",
            "owned": False,
            "parent": "1234",
            "owner": None,
            "description": "some description",
            "metadata": None,
            "desc": "this is a vuln",
            "severity": "high",
            "refs": ["cve1", "cve2"]
        }

        doc_cred = {
            "type": "Cred",
            "_id": "cred1",
            "name": "Vuln1",
            "owned": False,
            "parent": "1234",
            "owner": None,
            "description": "some description",
            "metadata": None,
            "username": "******",
            "password": "******"
        }

        pmanager = mock(NullPersistenceManager)
        when(pmanager).getDocument("1234").thenReturn(doc_host)
        when(pmanager).getDocument("note1").thenReturn(doc_note)
        when(pmanager).getDocument("vuln1").thenReturn(doc_vuln)
        when(pmanager).getDocument("cred1").thenReturn(doc_cred)
        when(pmanager).getChildren(any(str)).thenReturn([])
        when(pmanager).getChildren("1234").thenReturn(
            [{'_id': "note1", 'type': "Note"},
             {'_id': "vuln1", 'type': "Vulnerability"},
             {'_id': "cred1", 'type': "Cred"}])

        self.mapper_manager.createMappers(pmanager)

        host = self.mapper_manager.find("1234")
        self.assertNotEquals(
            host,
            None,
            "Existent host shouldn't be None")

        self.assertEquals(
            len(host.getNotes()),
            1,
            "Host should have one note")


        self.assertEquals(
            len(host.getVulns()),
            1,
            "Host should have one vuln")

        self.assertEquals(
            len(host.getCreds()),
            1,
            "Host should have one cred")

    def test_delete_interface_from_composite_one_host_one_interface_two_services(self): 
        doc_host = {
            "type": "Host",
            "_id": "1234",
            "name": "pepito",
            "owned": False,
            "parent": None,
            "owner": None,
            "description": "some description",
            "metadata": None,
            "os": "linux",
            "default_gateway": None
        }

        doc_interface = {
            "type": "Interface",
            "_id": "5678",
            "name": "192.168.10.168",
            "owned": False,
            "parent": "1234",
            "owner": None,
            "description": "some description",
            "metadata": None,
            "mac": "01:02:03:04:05:06",
            "network_segment": None,
            "hostnames": ["www.test.com"],
            "ipv4": {
                "address": "192.168.10.168",
                "mask": "255.255.255.0",
                "gateway": "192.168.10.1",
                "DNS": "192.168.10.1"
            },
            "ipv6": {},
            "ports": {
                "opened": 2,
                "closed": 3,
                "filtered": 4,
            }
        }

        doc_service1 = {
            "type": "Service",
            "_id": "abcd",
            "name": "http",
            "owned": False,
            "parent": "5678",
            "owner": None,
            "description": "some description",
            "metadata": None,
            "protocol": "tcp",
            "status": "open",
            "ports": [80],
            "version": "Apache 2.4"
        }

        doc_service2 = {
            "type": "Service",
            "_id": "efgh",
            "name": "ssh",
            "owned": False,
            "parent": "5678",
            "owner": None,
            "description": "some description",
            "metadata": None,
            "protocol": "tcp",
            "status": "open",
            "ports": [22],
            "version": "OpenSSH"
        }

        self.pmanager = mock(NullPersistenceManager)
        when(self.pmanager).getDocument("1234").thenReturn(doc_host)
        when(self.pmanager).getDocument("5678").thenReturn(doc_interface)
        when(self.pmanager).getDocument("abcd").thenReturn(doc_service1)
        when(self.pmanager).getDocument("efgh").thenReturn(doc_service2)
        when(self.pmanager).getChildren(any(str)).thenReturn([])
        when(self.pmanager).getChildren("1234").thenReturn([{'_id': "5678", 'type': "Interface"}])
        when(self.pmanager).getChildren("5678").thenReturn([{'_id': "abcd", 'type': "Service"}, {'_id': "efgh", 'type': "Service"}])

        self.mapper_manager.createMappers(self.pmanager)

        # load the host first
        host = self.mapper_manager.find("1234")

        #then remove the interface
        iface_id = host.getInterface("5678").getID()
        host.deleteChild(iface_id)

        def fake_remove(id):
            when(self.pmanager).getDocument(id).thenReturn(None)
        when(self.pmanager).remove("5678").thenReturn(fake_remove("5678"))
        when(self.pmanager).remove("abcd").thenReturn(fake_remove("abcd"))
        when(self.pmanager).remove("efgh").thenReturn(fake_remove("efgh"))
        self.mapper_manager.remove(iface_id)

        # now we make sure that we have removed the interface
        # and the services

        self.assertEquals(
            len(host.getAllInterfaces()),
            0,
            "Host should have no interfaces")

        self.assertEquals(
            self.mapper_manager.find("5678"),
            None,
            "Service abcd shouldn't exist anymore")


        self.assertEquals(
            self.mapper_manager.find("abcd"),
            None,
            "Service abcd shouldn't exist anymore")

        self.assertEquals(
            self.mapper_manager.find("efgh"),
            None,
            "Service efgh shouldn't exist anymore")

    def test_load_composite_one_workspace_two_hosts(self):

        doc_ws = {
            "type": "Workspace",
            "_id": "test_ws",
            "name": "test_ws",
            "description": "some description",
            "customer": "Infobyte",
            "sdate": None,
            "fdate": None
        }

        doc_host1 = {
            "type": "Host",
            "_id": "1234",
            "name": "pepito",
            "owned": False,
            "parent": "test_ws",
            "owner": None,
            "description": "some description",
            "metadata": None,
            "os": "linux",
            "default_gateway": None
        }

        doc_host2 = {
            "type": "Host",
            "_id": "5678",
            "name": "coquito",
            "owned": False,
            "parent": "test_ws",
            "owner": None,
            "description": "some description",
            "metadata": None,
            "os": "windows",
            "default_gateway": None
        }

        pmanager = NullPersistenceManager()
        when(pmanager).getDocument("test_ws").thenReturn(doc_ws)
        when(pmanager).getDocument("1234").thenReturn(doc_host1)
        when(pmanager).getDocument("5678").thenReturn(doc_host2)
        when(pmanager).getDocsByFilter(any, any).thenReturn([])
        when(pmanager).getDocsByFilter(any(str), None).thenReturn([])
        when(pmanager).getDocsByFilter(None, None).thenReturn([])
        when(pmanager).getDocsByFilter("test_ws", None).thenReturn(
            [{'_id': "1234", 'type': "Host"},
             {'_id': "5678", 'type': "Host"}])
        #when(pmanager).getDocsByFilter(None, "Host").thenReturn([])

        self.mapper_manager.createMappers(pmanager)

        ws = self.mapper_manager.find("test_ws")
        self.assertNotEquals(
            ws,
            None,
            "Existent Workspace shouldn't be None")

        self.assertEquals(
            len(ws.getHosts()),
            2,
            "Workspace should have two hosts")

        hosts_ids = [host.getID() for host in ws.getHosts()]
        self.assertIn(
            "1234",
            hosts_ids,
            "Host '1234' should be one of the workspace's hosts")

        self.assertIn(
            "5678",
            hosts_ids,
            "Host '5678' should be one of the workspace's hosts")
Ejemplo n.º 7
0
class MapperWithCouchDbManagerInegrationTest(unittest.TestCase):
    def setUp(self):
        self.db_name = self.new_random_workspace_name()

        self.couchdbmanager = CouchDbManager(CONF.getCouchURI())

        self.connector = self.couchdbmanager.createDb(self.db_name)
        self.mapper_manager = MapperManager()
        self.mapper_manager.createMappers(self.connector)

    def new_random_workspace_name(self):
        return ("aworkspace" + "".join(random.sample(
            [chr(i) for i in range(65, 90)], 10))).lower()

    def tearDown(self):
        self.couchdbmanager.deleteDb(self.db_name)
        time.sleep(3)

    def test_host_saving(self):
        host = Host(name="pepito", os="linux")
        host.setDescription("Some description")
        host.setOwned(True)
        self.mapper_manager.save(host)

        self.assertNotEquals(
            self.connector.getDocument(host.getID()),
            None,
            "Document shouldn't be None")

        self.assertEquals(
            self.connector.getDocument(host.getID()).get("name"),
            host.getName(),
            "Document should have the same host name")

    def test_load_nonexistent_host_using_manager_find(self):
        self.assertEquals(
            self.connector.getDocument("1234"),
            None,
            "Nonexistent host should return None document")

        self.assertEquals(
            self.mapper_manager.find("1234"),
            None,
            "Nonexistent host should return None object")

    def test_load_nonexistent_host_using_mapper_find(self):
        self.assertEquals(
            self.connector.getDocument("1234"),
            None,
            "Nonexistent host should return None document")

        self.assertEquals(
            self.mapper_manager.getMapper(Host.__name__).find("1234"),
            None,
            "Nonexistent host should return None object")

    def test_find_not_loaded_host(self):
        host = Host(name="pepito", os="linux")
        host.setDescription("Some description")
        host.setOwned(True)
        self.mapper_manager.save(host)

        #create a set of mappers, so we have a clean map
        self.mapper_manager = MapperManager()
        self.mapper_manager.createMappers(self.connector)

        h = self.mapper_manager.find(host.getID())
        self.assertNotEquals(
            h,
            None,
            "Existent host shouldn't return None")

        self.assertEquals(
            h.getName(),
            "pepito",
            "Host name should be pepito")

        self.assertEquals(
            h.getOS(),
            "linux",
            "Host os should be linux")

    def test_host_create_and_delete(self):
        host = Host(name="coquito")
        self.mapper_manager.save(host)
        h_id = host.getID()

        self.assertNotEquals(
            self.mapper_manager.find(h_id),
            None,
            "Host should be in the mapper")

        self.assertNotEquals(
            self.connector.getDocument(h_id),
            None,
            "Host should be in the db")

        self.mapper_manager.remove(h_id)

        self.assertEquals(
            self.mapper_manager.find(h_id),
            None,
            "Host shouldn't exist anymore in the mapper")

        self.assertEquals(
            self.connector.getDocument(h_id),
            None,
            "Host shouldn't exist anymore in the db")

    def test_composite_host(self):
        # add host
        host = Host(name="pepito", os="linux")
        host.setDescription("Some description")
        host.setOwned(True)
        self.mapper_manager.save(host)
        # add inteface
        iface = Interface(name="192.168.10.168", mac="01:02:03:04:05:06")
        iface.setDescription("Some description")
        iface.setOwned(True)
        iface.addHostname("www.test.com")
        iface.setIPv4({
            "address": "192.168.10.168",
            "mask": "255.255.255.0",
            "gateway": "192.168.10.1",
            "DNS": "192.168.10.1"
        })
        iface.setPortsOpened(2)
        iface.setPortsClosed(3)
        iface.setPortsFiltered(4)
        host.addChild(iface)
        self.mapper_manager.save(iface)

        h = self.mapper_manager.find(host.getID())
        self.assertEquals(
            len(h.getAllInterfaces()),
            len(host.getAllInterfaces()),
            "Interfaces from original host should be equals to retrieved host's interfaces")

        i = self.mapper_manager.find(h.getAllInterfaces()[0].getID())
        self.assertEquals(
            i.getID(),
            iface.getID(),
            "Interface's id' from original host should be equals to retrieved host's interface's id")

    def test_load_not_loaded_composite_host(self):
        # add host
        host = Host(name="pepito", os="linux")
        host.setDescription("Some description")
        host.setOwned(True)
        self.mapper_manager.save(host)
        # add inteface
        iface = Interface(name="192.168.10.168", mac="01:02:03:04:05:06")
        iface.setDescription("Some description")
        iface.setOwned(True)
        iface.addHostname("www.test.com")
        iface.setIPv4({
            "address": "192.168.10.168",
            "mask": "255.255.255.0",
            "gateway": "192.168.10.1",
            "DNS": "192.168.10.1"
        })
        iface.setPortsOpened(2)
        iface.setPortsClosed(3)
        iface.setPortsFiltered(4)
        host.addChild(iface)
        self.mapper_manager.save(iface)

        #create a set of mappers, so we have a clean map
        self.mapper_manager = MapperManager()
        self.mapper_manager.createMappers(self.connector)

        h = self.mapper_manager.find(host.getID())
        self.assertEquals(
            len(h.getAllInterfaces()),
            len(host.getAllInterfaces()),
            "Interfaces from original host should be equals to retrieved host's interfaces")

        i = self.mapper_manager.find(h.getAllInterfaces()[0].getID())
        self.assertEquals(
            i.getID(),
            iface.getID(),
            "Interface's id' from original host should be equals to retrieved host's interface's id")
Ejemplo n.º 8
0
class TestWorkspacesManagement(unittest.TestCase):

    def setUp(self):
        self.couch_uri = CONF.getCouchURI()
        # self.cdm = CouchdbManager(uri=self.couch_uri)
        wpath = os.path.expanduser("~/.faraday/persistence/" )
        # self.fsm = FSManager(wpath)
        
        self.dbManager = DbManager()
        self.mappersManager = MapperManager()
        self.changesController = ChangeController(self.mappersManager)

        self.wm = WorkspaceManager(self.dbManager, self.mappersManager,
                                    self.changesController)
        self._fs_workspaces = []
        self._couchdb_workspaces = []

    def tearDown(self):
        self.cleanCouchDatabases()
        self.cleanFSWorkspaces()
        # pass

    def new_random_workspace_name(self):
        return ("aworkspace" + "".join(random.sample(
            [chr(i) for i in range(65, 90)], 10))).lower()

    def cleanFSWorkspaces(self):
        import shutil
        basepath = os.path.expanduser("~/.faraday/persistence/")

        for d in self._fs_workspaces:
            wpath = os.path.join(basepath, d)
            if os.path.isdir(wpath):
                shutil.rmtree(wpath)

    def cleanCouchDatabases(self):
        try:
            for wname in self._couchdb_workspaces:
                self.cdm.removeWorkspace(wname)
        except Exception as e:
            print e

    def test_create_fs_workspace(self):
        """
        Verifies the creation of a filesystem workspace
        """
        wname = self.new_random_workspace_name()
        self._fs_workspaces.append(wname)
        self.wm.createWorkspace(wname, 'desc', DBTYPE.FS)

        wpath = os.path.expanduser("~/.faraday/persistence/%s" % wname)
        self.assertTrue(os.path.exists(wpath))

    def test_create_couch_workspace(self):
        """
        Verifies the creation of a couch workspace
        """
        wname = self.new_random_workspace_name()
        self._couchdb_workspaces.append(wname)
        self.wm.createWorkspace(wname, 'a desc', DBTYPE.COUCHDB)

        res_connector = self.dbManager.getConnector(wname)
        self.assertTrue(res_connector)
        self.assertEquals(res_connector.getType(), DBTYPE.COUCHDB)
        self.assertTrue(self.mappersManager.find(wname), "Workspace document not found")

        wpath = os.path.expanduser("~/.faraday/persistence/%s" % wname)
        self.assertFalse(os.path.exists(wpath))

        # self.assertEquals(WorkspaceOnCouch.__name__, self.wm.getWorkspaceType(wname))

    def test_delete_couch_workspace(self):
        """
        Verifies the deletion of a couch workspace
        """
        wname = self.new_random_workspace_name()
        self.wm.createWorkspace(wname, 'a desc', DBTYPE.COUCHDB)

        self.assertTrue(self.mappersManager.find(wname), "Workspace document not found")

        #Delete workspace
        self.wm.removeWorkspace(wname)
        self.assertIsNone(self.mappersManager.find(wname))
        self.assertFalse(self.dbManager.connectorExists(wname))

    def test_delete_fs_workspace(self):
        """
        Verifies the deletion of a filesystem workspace
        """
        wname = self.new_random_workspace_name()
        self.wm.createWorkspace(wname, 'desc', DBTYPE.FS)

        wpath = os.path.expanduser("~/.faraday/persistence/%s" % wname)
        self.assertTrue(os.path.exists(wpath))

        #Delete workspace
        self.wm.removeWorkspace(wname)
        self.assertFalse(os.path.exists(wpath))

    def test_list_workspaces(self):
        """ Lists FS workspaces and Couch workspaces """
        # First create workspaces manually 
        wnamefs = self.new_random_workspace_name()
        wnamecouch = self.new_random_workspace_name() 
        # FS
        self.wm.createWorkspace(wnamefs, 'a desc', DBTYPE.FS)
        # Couch
        self.wm.createWorkspace(wnamecouch, 'a desc', DBTYPE.COUCHDB)

        self.assertIn(wnamefs, self.wm.getWorkspacesNames(), 'FS Workspace not loaded')
        self.assertIn(wnamecouch, self.wm.getWorkspacesNames(), 'Couch Workspace not loaded')

        self.assertEquals(self.wm.getWorkspaceType(wnamecouch), 'CouchDB', 'Workspace type bad defined' )
        self.assertEquals(self.wm.getWorkspaceType(wnamefs), 'FS', 'Workspace type bad defined') 


    def test_get_workspace(self):
        """ Create a workspace, now ask for it """
        
        # When
        wname = self.new_random_workspace_name()
        workspace = self.wm.createWorkspace(wname, 'a desc', DBTYPE.FS)

        added_workspace = self.wm.openWorkspace(wname)

        # Then
        self.assertIsNotNone(workspace, 'Workspace added should not be none')
        self.assertEquals(workspace, added_workspace, 'Workspace created and added diffier')

    def _test_get_existent_couch_workspace(self): # Deprecate
        """ Create a workspace in the backend, now ask for it """
        
        # When
        wname = self.new_random_workspace_name()
        workspace = self.cdm.addWorkspace(wname)

        added_workspace = self.wm.getWorkspace(wname)

        # Then
        self.assertIsNotNone(added_workspace, 'Workspace added should not be none')

    def _test_get_existent_fs_workspace(self): # Deprecate
        """ Create a workspace in the backend, now ask for it """
        
        # When
        wname = self.new_random_workspace_name()
        workspace = self.fsm.addWorkspace(wname)
        self.wm.loadWorkspaces()

        added_workspace = self.wm.getWorkspace(wname)

        # Then
        self.assertIsNotNone(added_workspace, 'Workspace added should not be none')

    def test_get_non_existent_workspace(self):
        """ Retrieve a non existent workspace """
        
        added_workspace = self.wm.openWorkspace('inventado')

        # Then
        self.assertIsNone(added_workspace, 'Workspace added should not be none') 

    def test_set_active_workspace(self):
        ''' create a workspace through the backend, then set it as active '''

        wname = self.new_random_workspace_name()
        workspace = self.wm.createWorkspace(wname, 'desc', DBTYPE.FS)

        # when
        self.wm.setActiveWorkspace(workspace)

        self.assertEquals(workspace, self.wm.getActiveWorkspace(),
                    'Active workspace diffiers with expected workspace')

        self.assertTrue(self.wm.isActive(workspace.name),
                'Workspace is active flag not set')

    def test_remove_fs_workspace(self):
        # First
        wname = self.new_random_workspace_name()
        added_workspace = self.wm.createWorkspace(wname, 'desc', DBTYPE.FS)

        # When
        self.wm.removeWorkspace(wname) 

        # Then
        self.assertNotIn(wname, self.wm.getWorkspacesNames())
        wpath = os.path.expanduser("~/.faraday/persistence/%s" % wname)
        self.assertFalse(os.path.exists(wpath))

    def test_remove_couch_workspace(self):
        # First
        wname = self.new_random_workspace_name()
        added_workspace = self.wm.createWorkspace(wname, 'desc', DBTYPE.COUCHDB)

        # When
        self.wm.removeWorkspace(wname) 

        # Then
        self.assertNotIn(wname, self.wm.getWorkspacesNames())

    def test_remove_non_existent_workspace(self):
        # When
        self.wm.removeWorkspace('invented')