Example #1
0
    def test_server_sends_marshaled_exception_when_callback_raises_exception(self, mock_command_response):
        request = '{"name": "foobar", "arg": {"arg1": "value"}}'

        expected = '{"error": "raise me!", "value": null}'

        command_response = Mock(CommandResponse)
        command_response.error = "raise me!"
        command_response.value = None
        mock_command_response.return_value = command_response
        callback = Mock(side_effect=BusCtlServerError())

        marshaler = Mock(Marshaler)
        server = BusCtlServer()
        server._marshaler = marshaler

        command = Mock()
        command.name = "foobar"
        marshaler.unmarshal_command.return_value = command
        marshaler.marshal_response.return_value = expected

        command_class = Mock()
        command_class.name = "foobar"

        server.add_command(command_class, callback)

        response = server._process_next_command(request)

        self.assertEqual(response, expected)
        marshaler.marshal_response.assert_called_once_with(command_response)
    def test_vm_deployer_error(self):
        name = "name"
        name_gen = Mock(return_value=name)
        pv_service = Mock()
        si = Mock()
        clone_parmas = Mock()
        clone_res = Mock()
        clone_res.error = Mock()

        pv_service.CloneVmParameters = Mock(return_value=clone_parmas)
        pv_service.clone_vm = Mock(return_value=clone_res)
        params = DeployDataHolder.create_from_params(
            template_model={
                "vCenter_resource_name": "vcenter_resource_name",
                "vm_folder": "vfolder_name",
                "template_name": "template_name",
            },
            vm_cluster_model={"cluster_name": "cluster_name", "resource_pool": "resource_pool"},
            datastore_name="datastore_name",
            power_on=False,
        )

        deployer = VirtualMachineDeployer(pv_service, name_gen)

        self.assertRaises(Exception, deployer.deploy_from_template, si, params)
        self.assertTrue(pv_service.CloneVmParameters.called)
Example #3
0
    def test_redirect_oauth_error(self):
        error_identifier = "eid"
        redirect_uri = "https://callback"

        expected_redirect = "%s?error=%s" % (redirect_uri, error_identifier)

        error_mock = Mock(spec=OAuthUserError)
        error_mock.error = error_identifier

        response_mock = Mock(spec=Response)

        handler = AuthorizationCodeAuthHandler(
            auth_token_store=Mock(),
            client_store=Mock(),
            scope_handler=Mock(),
            site_adapter=Mock(),
            token_generator=Mock(),
        )
        handler.redirect_uri = redirect_uri
        result = handler.redirect_oauth_error(error_mock, response_mock)

        response_mock.add_header.assert_called_with("Location", expected_redirect)
        response_mock.status_code = 302
        response_mock.body = ""
        self.assertEqual(result, response_mock)
    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)
    def test_log_not_written_when_exception_not_thrown(self):
        # Arrange
        logger = Mock()
        logger.error = MagicMock()

        # Act
        with ErrorHandlingContext(logger=logger):
            print "hello world"

        # Assert
        logger.error.assert_not_called()
Example #6
0
    def get_obj(self, logger=None):
        if not logger:

            def print_msg(msg):
                print(msg)

            logger = Mock()
            logger.error = Mock(side_effect=print_msg)
            logger.warning = Mock(side_effect=print_msg)
            logger.info = Mock(side_effect=print_msg)
            logger.debug = Mock(side_effect=print_msg)
        return self.test_obj(logger)
Example #7
0
 def login(self, adapter, provider_name):
     del adapter, provider_name
     response = Mock()
     response.error = self.error
     if self.error:
         response.user = False
     else:
         user = Mock()
         user.name = self.name
         user.email = self.email
         response.user = user
     return response
    def test_log_written_when_exception_occurs(self):
        # Arrange
        logger = Mock()
        logger.error = MagicMock()
        try:

            # Act
            with ErrorHandlingContext(logger=logger):
                raise ValueError("some value error occurred")
        except ValueError:

            # Assert
            logger.error.assert_called()
Example #9
0
    def test_handle_produce_response_transport_error(self, fake_retry):
        m1 = Message("test_driver", {"val": 1}, None, None, 0, 1)
        m2 = Message("test_driver", {"val": 2}, None, None, 0, 1)
        response = Mock()
        response.code = 599
        response.error = object()
        response.request = Mock()
        response.request._batch = [m1, m2]
        response.request._id = 1

        self.producer._handle_produce_response("test_driver", response)

        self.client.mock_for("response_5xx").assert_called_once_with("test_driver", response)
        fake_retry.assert_has_calls([call("test_driver", m1), call("test_driver", m2)])
Example #10
0
    def test_handle_produce_response_on_200(self, fake_decode, fake_handle_success):
        m1 = Message("test_driver", {"val": 1}, None, None, 0, 1)
        m2 = Message("test_driver", {"val": 2}, None, None, 0, 1)
        response = Mock()
        response.code = 200
        response.error = False
        response.request = Mock()
        response.request._batch = [m1, m2]
        response.request._id = 1
        body = {"offsets": [{}, {}], "value_schema_id": 1, "key_schema_id": 2}
        fake_decode.return_value = body

        self.producer._handle_produce_response("test_driver", response)

        fake_handle_success.assert_called_once_with("test_driver", response, body)
Example #11
0
    def get_obj(self, logger=None, setup=None, config=None):
        if config is None:
            config = lxml.etree.Element("Configuration")
        if not logger:

            def print_msg(msg):
                print(msg)

            logger = Mock()
            logger.error = Mock(side_effect=print_msg)
            logger.warning = Mock(side_effect=print_msg)
            logger.info = Mock(side_effect=print_msg)
            logger.debug = Mock(side_effect=print_msg)
        if not setup:
            setup = MagicMock()
        return self.test_obj(logger, setup, config)
Example #12
0
def get_posix_object(logger=None, setup=None, config=None):
    if config is None:
        config = lxml.etree.Element("Configuration")
    if not logger:

        def print_msg(msg):
            print(msg)

        logger = Mock()
        logger.error = Mock(side_effect=print_msg)
        logger.warning = Mock(side_effect=print_msg)
        logger.info = Mock(side_effect=print_msg)
        logger.debug = Mock(side_effect=print_msg)
    if not setup:
        setup = MagicMock()
    return Bcfg2.Client.Tools.POSIX.POSIX(logger, setup, config)
    def setUp(self):
        config = types.ModuleType("config")

        handler_mock = Mock()
        config.HANDLER_CLASS = lambda: handler_mock

        logger_mock = Mock()
        logger_mock.info = Mock()
        logger_mock.error = Mock()
        logger_mock.debug = Mock()
        config.GET_LOGGER_FUNCTION = lambda: logger_mock

        def test_bindings(binder):
            binder.bind("cli_service", Mock())

        self.driver = CiscoNXOSDriver(config, test_bindings)
Example #14
0
    def test_execute_command_with_fetch_response(self):
        command = Mock()
        request = Mock()
        raw_response = Mock()
        response = Mock()
        response.error = None
        self.marshaler.marshal_command.return_value = request
        self.transport.rpc_call.return_value = raw_response
        self.marshaler.unmarshal_response.return_value = response

        self.agent_client._fetch_response = True
        result = self.agent_client._execute_command(command)

        self.marshaler.marshal_command.assert_called_once_with(command)
        self.transport.rpc_call.assert_called_once_with("", self.QUEUE_NAME, request)
        self.assertEqual(result, response.value)
Example #15
0
    def test_redirect_oauth_error(self):
        error_identifier = "eid"
        expected_content = {"error": error_identifier}

        error_mock = Mock(spec=OAuthUserError)
        error_mock.error = error_identifier

        response_mock = Mock(spec=Response)

        handler = AuthorizationCodeTokenHandler(Mock(), Mock(), Mock(), Mock())
        result = handler.redirect_oauth_error(error_mock, response_mock)

        response_mock.add_header.assert_called_with("Content-type", "application/json")
        self.assertEqual(response_mock.status_code, 400)
        self.assertEqual(response_mock.body, json.dumps(expected_content))
        self.assertEqual(result, response_mock)
Example #16
0
 def make_response(self, response_attrs=None, request_attrs=None):
     response = Mock()
     request = Mock()
     response.code = 200
     response.error = None
     response.body = json.dumps({"offsets": [{}]})
     request._id = 1
     request._topic = "test_driver"
     request._batch = [Message("test_driver", self.test_value, None, None, 0, 1)]
     for k, v in (response_attrs or {}).items():
         if k == "body":
             v = json.dumps(v)
         setattr(response, k, v)
     for k, v in (request_attrs or {}).items():
         setattr(request, k, v)
     response.request = request
     return response
Example #17
0
    def test_handle_produce_response_on_retriable(self, fake_decode, fake_retry):
        m1 = Message("test_driver", {"val": 1}, None, None, 0, 1)
        m2 = Message("test_driver", {"val": 2}, None, None, 0, 1)
        response = Mock()
        response.code = 500
        response.error = False
        response.request = Mock()
        response.request._batch = [m1, m2]
        response.request._id = 1
        body = {
            "offsets": [{}, {}],
            "value_schema_id": 1,
            "key_schema_id": 2,
            "error_code": 50001,
            "message": "Retriable",
        }
        fake_decode.return_value = body

        self.producer._handle_produce_response("test_driver", response)

        fake_retry.assert_has_calls([call("test_driver", m1), call("test_driver", m2)])
Example #18
0
    def get_obj(self, logger=None, setup=None, config=None):
        if config is None:
            config = lxml.etree.Element("Configuration")
        if not logger:

            def print_msg(msg):
                print(msg)

            logger = Mock()
            logger.error = Mock(side_effect=print_msg)
            logger.warning = Mock(side_effect=print_msg)
            logger.info = Mock(side_effect=print_msg)
            logger.debug = Mock(side_effect=print_msg)
        if not setup:
            setup = MagicMock()
        if "command_timeout" not in setup:
            setup["command_timeout"] = None
        execs = self.test_obj.__execs__
        self.test_obj.__execs__ = []
        rv = self.test_obj(logger, setup, config)
        self.test_obj.__execs__ = execs
        return rv
    def test_vm_deployer(self):
        name = "name"
        uuid = "uuid"
        name_gen = Mock(return_value=name)
        pv_service = Mock()
        si = Mock()
        clone_parmas = Mock()
        clone_res = Mock()
        clone_res.error = None
        clone_res.vm = Mock()
        clone_res.vm.summary = Mock()
        clone_res.vm.summary.config = Mock()
        clone_res.vm.summary.config.uuid = uuid

        pv_service.CloneVmParameters = Mock(return_value=clone_parmas)
        pv_service.clone_vm = Mock(return_value=clone_res)
        params = DeployDataHolder(
            {
                "resource_context": None,
                "template_model": {
                    "vCenter_resource_name": "vcenter_resource_name",
                    "vm_folder": "vfolder_name",
                    "template_name": "template_name",
                },
                "vm_cluster_model": {"cluster_name": "cluster_name", "resource_pool": "resource_pool"},
                "datastore_name": "datastore_name",
                "power_on": False,
            }
        )

        deployer = VirtualMachineDeployer(pv_service, name_gen)
        res = deployer.deploy_from_template(si, params)

        self.assertEqual(res.vm_name, name)
        self.assertEqual(res.vm_uuid, uuid)
        self.assertEqual(res.cloud_provider_resource_name, params.template_model.vCenter_resource_name)
        self.assertTrue(pv_service.CloneVmParameters.called)
Example #20
0
    def test_redirect_oauth_error(self):
        error_code = "error_code"
        client_id = "cid"
        redirect_uri = "https://callback"
        scope = "scope"
        state = "state"
        expected_redirect_location = "%s#error=%s" % (redirect_uri, error_code)

        client_mock = Mock(Client)
        client_mock.redirect_uris = [redirect_uri]
        client_mock.has_redirect_uri.return_value = True

        client_store_mock = Mock(spec=ClientStore)
        client_store_mock.fetch_by_client_id.return_value = client_mock

        error_mock = Mock(spec=OAuthUserError)
        error_mock.error = error_code

        request_mock = Mock(spec=Request)
        request_mock.get_param.side_effect = [client_id, redirect_uri, scope, state]

        response_mock = Mock(spec=Response)

        handler = ImplicitGrantHandler(
            Mock(spec=AccessTokenStore),
            client_store=client_store_mock,
            scope_handler=Mock(Scope),
            site_adapter=Mock(),
            token_generator=Mock(),
        )
        handler.read_validate_params(request_mock)
        altered_response = handler.redirect_oauth_error(error_mock, response_mock)

        response_mock.add_header.assert_called_with("Location", expected_redirect_location)
        self.assertEqual(altered_response.status_code, 302)
        self.assertEqual(altered_response.body, "")