def test_TestNetworkAdaptersRetriever_E0(self):
        content = Mock()
        si = create_autospec(spec=vim.ServiceInstance)
        si.RetrieveContent = Mock(return_value=content)

        pvServiceConnectError = Mock()
        pvServiceConnectError.connect = Mock(side_effect=Exception("TEST Exception"))

        pvServiceConnectNone = Mock()
        pvServiceConnectNone.connect = Mock(return_value=si)
        pvServiceConnectNone.find_network_by_name = Mock(return_value=None)

        csRetrieverService = Mock()
        csRetrieverService.getVCenterInventoryPathAttributeData = Mock(
            return_value={"vCenter_resource_name": "Resource Name", "vm_folder": "TEST_FOLDER"}
        )

        helpers.get_resource_context_details = Mock(return_value={})

        connDetails = create_autospec(VCenterConnectionDetails)
        resourceConnectionDetailsRetriever = Mock()
        resourceConnectionDetailsRetriever.getConnectionDetails = Mock(return_value=connDetails)

        switchRetriever = NetworkAdaptersRetrieverCommand(
            pvServiceConnectError, csRetrieverService, resourceConnectionDetailsRetriever
        )
        with self.assertRaises(ConnectionException) as context:
            switchRetriever.execute()
        self.assertTrue("User:" in context.exception.message)

        switchRetriever = NetworkAdaptersRetrieverCommand(
            pvServiceConnectNone, csRetrieverService, resourceConnectionDetailsRetriever
        )
        nics = switchRetriever.execute()
        self.assertIsNone(nics)
Example #2
0
    def test_create_endpoint_existing_channel(self):
        ch = Mock(spec=SendChannel)
        e = self._ef.create_endpoint(existing_channel=ch)
        self.assertEquals(e.channel, ch)
        self.assertEquals(ch.connect.call_count, 0)

        ch.connect("exist")
        ch.connect.assert_called_once_with("exist")

        e.close()
    def test_TestNetworkAdaptersRetriever(self):
        content = Mock()
        si = create_autospec(spec=vim.ServiceInstance)
        si.RetrieveContent = Mock(return_value=content)

        vNic = create_autospec(spec=vim.vm.device.VirtualEthernetCard)
        vNic.deviceInfo = Mock()
        vNic.deviceInfo.summary = "network1"
        vNic.macAddress = "AA-BB"
        vNic.connectable = Mock()
        vNic.connectable.connected = "True"
        vNic.connectable.startConnected = "True"

        vmMachine = Mock()
        vmMachine.config.hardware.device = [vNic]

        pvService = Mock()
        pvService.connect = Mock(return_value=si)
        pvService.get_obj = Mock(return_value=vmMachine)
        pvService.find_network_by_name = Mock(return_value=vmMachine)

        pvServiceConnectError = Mock()
        pvServiceConnectError.connect = Mock(side_effect=Exception("TEST Exception"))

        pvServiceConnectNone = Mock()
        pvServiceConnectNone.connect = Mock(return_value=None)

        csRetrieverService = Mock()
        csRetrieverService.getVCenterInventoryPathAttributeData = Mock(
            return_value={"vCenter_resource_name": "Resource Name", "vm_folder": "TEST_FOLDER"}
        )

        helpers.get_resource_context_details = Mock(return_value={})

        connDetails = create_autospec(VCenterConnectionDetails)
        connDetails.host = "host"
        connDetails.user = "user"
        connDetails.password = "pwd"
        connDetails.port = 443

        resourceConnectionDetailsRetriever = Mock()
        resourceConnectionDetailsRetriever.getConnectionDetails = Mock(return_value=connDetails)

        switchRetriever = NetworkAdaptersRetrieverCommand(
            pvService, csRetrieverService, resourceConnectionDetailsRetriever
        )
        nics = switchRetriever.execute()

        self.assertEqual(nics[0].networkLabel, "network1")
        self.assertEqual(nics[0].macAddress, "AA-BB")
        self.assertEqual(nics[0].connected, "True")
        self.assertEqual(nics[0].connectAtPowerOn, "True")
    def test_should_add_menu_iten(self):
        # Set
        ind = NewrelicIndicator()

        # Mocks
        method_callback = Mock(name="Method")
        menu_obj = Mock(name="Menu")
        menu_obj.append = Mock()
        menu_iten_obj = Mock(name="MenuItem")
        menu_iten_obj.connect = Mock()
        menu_iten_obj.show = Mock()
        ind.indicator = Mock(name="Indicator")
        ind.indicator.set_menu = Mock()

        gtk.Menu = Mock(return_value=menu_obj)
        gtk.MenuItem = Mock(return_value=menu_iten_obj)

        # Assertion
        ind._NewrelicIndicator__add_menu_iten("ItemName", method_callback)

        gtk.MenuItem.assert_called_once_with("ItemName")

        self.assertEquals(ind.menu, menu_obj)
        menu_iten_obj.connect.assert_called_once_with("activate", method_callback)
        menu_iten_obj.show.assert_called_once()
        menu_obj.append.assert_called_once_with(menu_iten_obj)
        ind.indicator.set_menu.assert_called_once_with(menu_obj)
    def test_should_update_state_if_available(self):
        # Set
        app = NewrelicApp("1111", "777")
        headers = {"X-Api-Key": "1111"}
        url = "/v2/applications/777.json"

        # Mocks
        connection_obj = Mock()
        response_obj = Mock()
        httplib.HTTPConnection = Mock(return_value=connection_obj)

        response_obj.status = 200
        response_obj.read = Mock(return_value='{"some":"json"}')
        connection_obj.connect = Mock()
        connection_obj.request = Mock()
        connection_obj.getresponse = Mock(return_value=response_obj)

        # Assertion
        app.update_state()

        connection_obj.connect.assert_called_once()
        connection_obj.request.assert_called_once_with("GET", url, "", headers)
        connection_obj.getresponse.assert_called_once()

        self.assertEquals(app.raw_app, {"some": "json"})
        self.assertTrue(app.reachable)
    def test_delete_all(self):
        # arrange
        uuid = "uuid"
        si = Mock()
        vm = Mock()

        connection_detail = Mock()
        connection_detail.host = Mock()
        connection_detail.username = Mock()
        connection_detail.password = Mock()
        connection_detail.port = Mock()

        pv_service = Mock()
        pv_service.connect = Mock(return_value=si)
        pv_service.find_by_uuid = Mock(return_value=vm)

        connector = VirtualSwitchToMachineDisconnectCommand(pv_service, Mock(), "anetwork")
        # virtual_switch_to_machine_connector.remove_interfaces_from_vm = Mock(return_value=True)
        connector.get_network_by_name = lambda x, y: Mock()

        vcenter_data_model = VMwarevCenterResourceModel()

        # act
        res = connector.disconnect(
            si=si, logger=Mock(), vcenter_data_model=vcenter_data_model, vm_uuid=uuid, network_name=None, vm=None
        )
        # assert
        self.assertTrue(
            pv_service.connect.called_with(
                connection_detail.host, connection_detail.username, connection_detail.password, connection_detail.port
            )
        )
        self.assertTrue(pv_service.find_by_uuid.called_with(si, uuid))
        # self.assertTrue(virtual_switch_to_machine_connector.remove_interfaces_from_vm.called_with(vm))
        self.assertTrue(res)
    def test_should_not_update_state_if_unaavailable(self):
        # Set
        app = NewrelicApp("1111", "777")
        headers = {"X-Api-Key": "1111"}
        url = "/v2/applications/777.json"

        # Mocks
        connection_obj = Mock()
        response_obj = Mock()
        httplib.HTTPConnection = Mock(return_value=connection_obj)

        response_obj.status = 500  # Error
        response_obj.read = Mock(return_value="")
        connection_obj.connect = Mock()
        connection_obj.request = Mock()
        connection_obj.getresponse = Mock(return_value=response_obj)

        # Assertion
        app.update_state()

        connection_obj.connect.assert_called_once()
        connection_obj.request.assert_called_once_with("GET", url, "", headers)
        connection_obj.getresponse.assert_called_once()

        self.assertFalse(app.reachable)
    def test_getConnection_mysql(self):
        # mock the MySQLdb module so we can test in an environement which does not have this module installed
        mock_MySQLdb = Mock()
        mock_MySQLdb.connect = Mock(return_value=sentinel)
        with patch.dict("sys.modules", {"MySQLdb": mock_MySQLdb}):

            # verify that a correct dsn does work as expected
            storage = DatabaseStorage("mysql://someuser:somepasswd@somehost:someport/somedbname", Mock())
            assert mock_MySQLdb.connect.called, "expecting MySQLdb.connect to be called"
            self.assertEqual(sentinel, storage.db)

            # verify that an incorrect dsn does fail an stops the bot with a nice error message
            mock_MySQLdb.connect.reset_mock()
            console_mock = Mock()
            storage = DatabaseStorage("mysql://someuser:somepasswd@somehost:3446/", console_mock)
            assert console_mock.critical.called
            self.assertIn("missing MySQL database name", console_mock.critical.call_args[0][0])
            assert not mock_MySQLdb.connect.called, "expecting MySQLdb.connect not to be called"
            self.assertIsNone(storage.db)

            # verify that an incorrect dsn does fail an stops the bot with a nice error message
            mock_MySQLdb.connect.reset_mock()
            console_mock = Mock()
            storage = DatabaseStorage("mysql://someuser:somepasswd@/database", console_mock)
            assert console_mock.critical.called
            self.assertIn("invalid MySQL host", console_mock.critical.call_args[0][0])
            assert not mock_MySQLdb.connect.called, "expecting MySQLdb.connect not to be called"
            self.assertIsNone(storage.db)
    def test_connect(self):
        # Arrange
        si = Mock()

        py_vmomi_service = Mock()
        py_vmomi_service.connect = Mock(return_value=si)

        dv_port_group_creator = MagicMock()
        virtual_machine_port_group_configurer = MagicMock()
        vlan_spec = Mock()
        virtual_switch_to_machine_connector = VirtualSwitchToMachineConnector(
            dv_port_group_creator, virtual_machine_port_group_configurer
        )

        vm = Mock()

        network_map = Mock()
        network_map.dv_port_name = "dv_port_name"
        network_map.dv_switch_name = "dvSwitch"
        network_map.dv_switch_path = "QualiSB"
        network_map.vlan_id = "100"
        network_map.vlan_spec = "Access"
        # Act
        virtual_switch_to_machine_connector.connect_by_mapping(
            si=si,
            vm=vm,
            mapping=[network_map],
            default_network=Mock(spec=vim.Network),
            reserved_networks=[],
            logger=Mock(),
        )
    def test_delete(self):
        # arrange
        uuid = "uuid"
        network_name = "network_name"

        network = Mock()
        network.name = network_name
        si = Mock()
        vm = Mock()
        vm.network = [network]

        connection_detail = Mock()
        connection_detail.host = Mock()
        connection_detail.username = Mock()
        connection_detail.password = Mock()
        connection_detail.port = Mock()

        pv_service = Mock()
        pv_service.connect = Mock(return_value=si)
        pv_service.find_by_uuid = Mock(return_value=vm)

        connector = VirtualSwitchToMachineDisconnectCommand(pv_service, Mock(), "anetwork")

        # act
        res = connector.disconnect(si, uuid, network_name)

        # assert
        self.assertTrue(
            pv_service.connect.called_with(
                connection_detail.host, connection_detail.username, connection_detail.password, connection_detail.port
            )
        )
        self.assertTrue(pv_service.find_by_uuid.called_with(si, uuid))
        self.assertTrue(res)
    def test_deployFromTemplateCommand(self):
        content = Mock()
        si = create_autospec(spec=vim.ServiceInstance)
        si.RetrieveContent = Mock(return_value=content)

        vmTemplate = Mock()

        pvService = Mock()
        pvService.connect = Mock(return_value=si)
        pvService.disconnect = Mock(return_value=Mock())
        pvService.get_obj = Mock(return_value=vmTemplate)
        cloned_vm = Mock()
        cloned_vm.error = None
        pvService.clone_vm = Mock(return_value=cloned_vm)

        csRetrieverService = Mock()
        csRetrieverService.getVCenterTemplateAttributeData = Mock(
            return_value=VCenterTemplateModel(template_name="test", vm_folder="Alex", vCenter_resource_name="vCenter")
        )
        csRetrieverService.getPowerStateAttributeData = Mock(return_value=True)
        csRetrieverService.getVMClusterAttributeData = Mock(
            return_value=VMClusterModel(cluster_name="cluster1", resource_pool="resourcePool1")
        )
        csRetrieverService.getVMStorageAttributeData = Mock(return_value="datastore")
        csRetrieverService.getVCenterConnectionDetails = Mock(
            return_value={"vCenter_url": "vCenter", "user": "user1", "password": "pass1"}
        )

        resourceContext = Mock()
        resourceContext.attributes = {"vCenter Template": "vCenter/Alex/test"}
        helpers.get_resource_context_details = Mock(return_value=resourceContext)

        session = Mock()
        session.GetResourceDetails = Mock(return_value={})
        session.CreateResource = Mock()
        session.AddResourcesToReservation = Mock()
        session.SetAttributesValues = Mock()

        reservationContext = Mock(id="d8efb46f-4440-4685-b043-68de14ec4470")
        helpers.get_reservation_context_details = Mock(return_value=reservationContext)
        helpers.get_api_session = Mock(return_value=session)

        connection_details = VCenterConnectionDetails("vCenter", "user", "pass1")

        resource_connection_details_retriever = Mock()
        resource_connection_details_retriever.get_connection_details = Mock(return_value=connection_details)

        command = DeployFromTemplateCommand(pvService, csRetrieverService, resource_connection_details_retriever)
        command.execute()

        self.assertTrue(pvService.clone_vm.called)
        self.assertTrue(session.CreateResource.called)
        self.assertTrue(session.AddResourcesToReservation.called)
        self.assertTrue(session.SetAttributesValues.called)
Example #12
0
    def test_ssh_client_connect_timeout(self):
        mock_ssh_client = Mock()
        mock_ssh_client.connect = Mock()
        mock_ssh_client.connect.side_effect = IOError("bam")

        try:
            self.driver._ssh_client_connect(ssh_client=mock_ssh_client, timeout=0.5)
        except LibcloudError:
            e = sys.exc_info()[1]
            self.assertTrue(e.value.find("Giving up") != -1)
        else:
            self.fail("Exception was not thrown")
Example #13
0
    def test_mpdclient_connect_bad_host_raises_mpdclientexception(self):
        mpdconf = {"host": "badhost", "port": 6600}
        mpdclient = MpdClient(mpdconf)

        # Mock the mpd client
        mpdmock = Mock()
        mpdclient.client = mpdmock
        # Mock the connect method
        connect = Mock(side_effect=ConnectionError())
        mpdmock.connect = connect

        # Call
        with self.assertRaises(MpdClientException):
            mpdclient.connect()
Example #14
0
    def test_mpdclient_connectexception_raises_mpdclientexception(self):
        mpdconf = {"host": "badhost", "port": 6600}
        mpdclient = MpdClient(mpdconf)

        # Mock the mpd client
        mpdmock = Mock()
        mpdclient.client = mpdmock
        # Mock the connect method and reaise MPDError
        connect = Mock(side_effect=MPDError())
        mpdmock.connect = connect
        # Call
        with self.assertRaises(MpdClientException):
            mpdclient.connect()

        # Methods call assertions
        mpdmock.connect.assert_called_with(mpdconf["host"], mpdconf["port"])
    def test_connect(self):
        # Arrange
        si = Mock()

        py_vmomi_service = Mock()
        py_vmomi_service.connect = Mock(return_value=si)

        resource_connection_details_retriever = Mock()
        dv_port_group_creator = MagicMock()
        virtual_machine_port_group_configurer = MagicMock()
        virtual_switch_to_machine_connector = VirtualSwitchToMachineConnector(
            py_vmomi_service,
            resource_connection_details_retriever,
            dv_port_group_creator,
            virtual_machine_port_group_configurer,
        )

        virtual_machine_path = "ParentFlder\\ChildFolder"
        virtual_machine_name = "MachineName"
        vm_uuid = uuid.UUID("{12345678-1234-5678-1234-567812345678}")
        port_group_path = "QualiSB"
        dv_switch_path = "QualiSB"
        dv_switch_name = "dvSwitch"
        dv_port_name = "dv_port_name"

        # Act
        virtual_switch_to_machine_connector.connect(
            virtual_machine_name,
            dv_switch_path,
            dv_switch_name,
            dv_port_name,
            virtual_machine_path,
            vm_uuid,
            port_group_path,
        )

        # Assert
        dv_port_group_creator.create_dv_port_group.assert_called_with(dv_port_name, dv_switch_name, dv_switch_path, si)
        virtual_machine_port_group_configurer.configure_port_group_on_vm.assert_called_with(
            si, virtual_machine_path, vm_uuid, port_group_path, dv_port_name
        )
    def test_destroyVirtualMachineCommand(self):
        content = Mock()
        si = create_autospec(spec=vim.ServiceInstance)
        si.RetrieveContent = Mock(return_value=content)

        pvService = Mock()
        pvService.connect = Mock(return_value=si)
        pvService.destroy_vm_by_name = MagicMock()

        csRetrieverService = Mock()
        csRetrieverService.getVCenterTemplateAttributeData = Mock(
            return_value=VCenterTemplateModel(template_name="test", vm_folder="Alex", vCenter_resource_name="vCenter")
        )
        csRetrieverService.getPowerStateAttributeData = Mock(return_value=True)
        csRetrieverService.getVMClusterAttributeData = Mock(
            return_value=VMClusterModel(cluster_name="cluster1", resource_pool="resourcePool1")
        )
        csRetrieverService.getVMStorageAttributeData = Mock(return_value="datastore")
        csRetrieverService.getVCenterConnectionDetails = Mock(
            return_value={"vCenter_url": "vCenter", "user": "user1", "password": "pass1"}
        )

        resource_att = Mock()
        vm_name = Mock(return_value="test")
        resource_att.name = vm_name
        helpers.get_resource_context_details = Mock(return_value=resource_att)
        helpers.get_api_session = Mock()

        context_att = Mock()
        vm_id = Mock(return_value="id")
        context_att.id = vm_id
        helpers.get_reservation_context_details = Mock(return_value=context_att)

        command = DestroyVirtualMachineCommand(pvService, csRetrieverService)
        command.execute()

        self.assertTrue(pvService.connect.called)
        self.assertTrue(pvService.destroy_vm_by_name.called)
        self.assertTrue(si.RetrieveContent.called)
        pvService.destroy_vm_by_name.assert_called_with(content, si, vm_name)
        self.assertTrue(helpers.get_api_session().DeleteResource.called)
Example #17
0
    def test_connect_to(self):
        from functions import connect_to

        with nested(
            patch("functions.log_write"), patch("sys.stdout", new=StringIO()), patch("functions.get_datetime")
        ) as (log_write, stdout, get_dt):
            get_dt.return_value = {"date": "42", "time": "42"}

            s = Mock()
            s.connect.side_effect = IOError()

            address = ("server", "port")
            message = "Could not connect to {0}\n{1}".format(address, "\n")

            self.assertFalse(connect_to(address, s, "foo"))
            self.assertEqual(stdout.getvalue(), message)
            log_write.assert_called_with("foo", "42", " <> ", message)

            s.connect.side_effect = None
            s.connect = Mock()
            self.assertTrue(connect_to(address, s, "foo"))

            s.connect.assert_called_with(address)
Example #18
0
    def test_getConnection_mysql(self):
        # mock the pymysql module so we can test in an environement which does not have this module installed
        dsn = "mysql://someuser:somepasswd@somehost:someport/somedbname"
        mock_pymysql = Mock()
        mock_pymysql.connect = Mock(return_value=sentinel)
        with patch.dict("sys.modules", {"pymysql": mock_pymysql}):

            # verify that a correct dsn does work as expected
            mock_pymysql.connect.reset_mock()
            storage = MysqlStorage(dsn, splitDSN(dsn), Mock())
            when(storage).getTables().thenReturn(B3_DEFAULT_TABLES)
            storage.connect()
            assert mock_pymysql.connect.called, "expecting pymysql.connect to be called"
            self.assertEqual(sentinel, storage.db)

            # verify that B3 creates necessary tables when they are missing
            mock_pymysql.connect.reset_mock()
            storage = MysqlStorage(dsn, splitDSN(dsn), Mock())
            when(storage).getTables().thenReturn([])
            storage.queryFromFile = Mock()
            storage.connect()
            assert storage.queryFromFile.called, "expecting MysqlStorage.queryFromFile to be called"
            self.assertEqual(sentinel, storage.db)

            # verify that whenever B3 is not able to create necessary tables, it stops
            mock_pymysql.connect.reset_mock()
            console_mock = Mock()
            console_mock.critical = Mock()
            storage = MysqlStorage(dsn, splitDSN(dsn), console_mock)
            storage.shutdown = Mock()
            when(storage).getTables().thenReturn([])
            when(storage).queryFromFile(ANY()).thenRaise(Exception())
            storage.connect()
            assert storage.shutdown.called, "expecting MysqlStorage.shutdown to be called"
            assert console_mock.critical.called, "expecting console_mock.critical to be called"
            self.assertIn("Missing MySQL database tables", console_mock.critical.call_args[0][0])