def test_should_exit_with_appropriate_code_when_command_is_ignore_and_no_message_was_given(self, mock_exit):
        options = Mock()
        options.message = None

        validate_command_line_options("ignore", options, self.fake_show_help_callback)

        mock_exit.assert_called_with(EXIT_CODE_MISSING_MESSAGE_OPTION)
    def test_should_execute_show_help_callback_when_no_ignore_message_is_given(self, _):
        options = Mock()
        options.message = None

        validate_command_line_options("ignore", options, self.fake_show_help_callback)

        self.assertTrue(self._show_help_callback_has_been_called)
    def test_should_not_exit_when_command_is_ignore_and_message_is_given(self, mock_exit):
        options = Mock()
        options.message = "ignore message"

        validate_command_line_options("ignore", options, self.fake_show_help_callback)

        mock_exit.assert_not_called()
    def test_broadcast_message(self, mock_add_timestamp):
        mock_logger = Mock()
        mock_config = Mock()
        mock_config.colors = {"admin": "admin colors", "default": "default colors"}
        mock_message = Mock()
        mock_message.message = "###test"
        mock_add_timestamp.return_value = "without add_normalizer"
        mock_just_player = Mock()
        mock_player_moderator = Mock()
        mock_factory = Mock()
        mock_factory.protocols = {"normal player": mock_just_player, "moderator": mock_player_moderator}
        mock_protocol = Mock()
        mock_protocol.player.access_level = UserLevels.ADMIN
        plugin = AdminMessenger()
        plugin.factory = mock_factory
        plugin.config = mock_config
        plugin.logger = mock_logger
        plugin.protocol = mock_protocol
        expected_message = "{}{}BROADCAST: ^red;{}{}".format(
            "without add_normalizer", "admin colors", "TEST", "default colors"
        )

        plugin.broadcast_message(mock_message)
        mock_player_moderator.send_chat_message.assert_called_with(expected_message)
        mock_just_player.send_chat_message.assert_called_with(expected_message)
        mock_logger.info.assert_called_with("Broadcast from %s. Message: %s", mock_protocol.player.name, "TEST")
        self.assertFalse(mock_protocol.send_chat_message.called)
    def test_message_admins(self, mock_add_timestamp):
        mock_logger = Mock()
        mock_config = Mock()
        mock_config.colors = {"moderator": "moderator colors"}
        mock_message = Mock()
        mock_message.message = "##test"
        mock_add_timestamp.return_value = "with add_normalizer"
        mock_just_player = Mock()
        mock_just_player.player.access_level = UserLevels.GUEST
        mock_player_moderator = Mock()
        mock_player_moderator.player.access_level = UserLevels.MODERATOR
        mock_factory = Mock()
        mock_factory.protocols = {"normal player": mock_just_player, "moderator": mock_player_moderator}
        mock_protocol = Mock()
        mock_protocol.player.colored_name.return_value = "player colors"
        plugin = AdminMessenger()
        plugin.factory = mock_factory
        plugin.config = mock_config
        plugin.logger = mock_logger
        plugin.protocol = mock_protocol

        plugin.message_admins(mock_message)
        mock_player_moderator.send_chat_message.assert_called_with(
            "{}{}ADMIN: ^yellow;<{}^yellow;> {}{}".format(
                "with add_normalizer", "moderator colors", "player colors", "moderator colors", "test"
            )
        )
        mock_logger.info.assert_called_with(
            "Received an admin message from %s. Message: %s", mock_protocol.player.name, "test"
        )
        self.assertFalse(mock_just_player.send_chat_message.called)
        mock_add_timestamp.assert_called_with(add_normalizer=True)
Example #6
0
    def test_agent_policies(self):

        # set up data
        gc = Mock()
        service_key = "service_key"
        resource_id = "resource_id"
        pdpm = PolicyDecisionPointManager(gc)
        invocation = Mock()
        mock_header = Mock()
        invocation.message_annotations = {}
        invocation.message = {"argument1": 0}
        invocation.headers = {
            "op": "op",
            "process": "process",
            "request": "request",
            "ion-actor-id": "ion-actor-id",
            "receiver": "resource-registry",
            "sender-type": "sender-type",
            "sender-service": "Unknown",
            "ion-actor-roles": {"org_name": ["ION_MANAGER"]},
        }
        invocation.get_message_receiver.return_value = "service_key"
        invocation.get_service_name.return_value = "Unknown"
        invocation.get_message_sender.return_value = ["Unknown", "Unknown"]

        def get_header_value(key, default):
            return invocation.headers.get(key, default)

        mock_header.side_effect = get_header_value
        invocation.get_header_value = mock_header
        mock_args = Mock()
        process = Mock()
        process.org_governance_name = "org_name"
        process.resource_id = "resource_id"
        invocation.args = {"process": process}

        def get_arg_value(key, default="Unknown"):
            return invocation.args.get(key, default)

        mock_args.side_effect = get_arg_value
        invocation.get_arg_value = mock_args
        gc.system_root_org_name = "sys_org_name"

        # check that service policies result in denying the request
        pdpm.load_service_policy_rules(service_key, self.deny_ION_MANAGER_rule)
        pdpm.load_resource_policy_rules(resource_id, self.permit_ION_MANAGER_rule)
        response = pdpm.check_agent_request_policies(invocation)
        self.assertEqual(response.value, "Deny")

        # check that resource policies result in denying the request
        pdpm.load_service_policy_rules(service_key, self.permit_ION_MANAGER_rule)
        pdpm.load_resource_policy_rules(resource_id, self.deny_ION_MANAGER_rule)
        response = pdpm.check_agent_request_policies(invocation)
        self.assertEqual(response.value, "Deny")

        # check that both service and resource policies need to allow a request
        pdpm.load_service_policy_rules(service_key, self.permit_ION_MANAGER_rule)
        pdpm.load_resource_policy_rules(resource_id, self.permit_ION_MANAGER_rule)
        response = pdpm.check_agent_request_policies(invocation)
        self.assertEqual(response.value, "Permit")
Example #7
0
 def create_mock_scheduled_tasks(cls):
     jobs = []
     for name in ["foo", "bar", "baz"]:
         job = Mock()
         job.key = JobKey(role=cls.TEST_ROLE, environment=cls.TEST_ENV, name=name)
         job.failure_count = 0
         job.assignedTask = Mock(spec=AssignedTask)
         job.assignedTask.slaveHost = "slavehost"
         job.assignedTask.task = Mock(spec=TaskConfig)
         job.assignedTask.task.maxTaskFailures = 1
         job.assignedTask.task.executorConfig = Mock(spec=ExecutorConfig)
         job.assignedTask.task.executorConfig.data = Mock()
         job.assignedTask.task.packages = []
         job.assignedTask.task.owner = Identity(role="mchucarroll")
         job.assignedTask.task.environment = "test"
         job.assignedTask.task.jobName = "woops"
         job.assignedTask.task.numCpus = 2
         job.assignedTask.task.ramMb = 2
         job.assignedTask.task.diskMb = 2
         job.assignedTask.instanceId = 4237894
         job.assignedTask.assignedPorts = None
         job.status = ScheduleStatus.RUNNING
         mockEvent = Mock(spec=TaskEvent)
         mockEvent.timestamp = 28234726395
         mockEvent.status = ScheduleStatus.RUNNING
         mockEvent.message = "Hi there"
         job.taskEvents = [mockEvent]
         jobs.append(job)
     return jobs
Example #8
0
def event():
    result = Mock()
    for k, v in DEFAULT_PLUGIN_CONFIGURATION.items():
        setattr(result.project, k, v)

    result.message = "An error has occured"
    result.error.return_value = result.message

    return result
Example #9
0
 def create_blank_response(cls, code, msg):
     response = Mock(spec=Response)
     response.responseCode = code
     mock_msg = Mock()
     mock_msg.message = msg
     response.details = [mock_msg]
     response.messageDEPRECATED = msg
     response.result = Mock(spec=Result)
     return response
 def test_handle_lifecycle_control(self):
     ctrl = Mock()
     ctrl.message = "start"
     ctrl.config = ConfigParser()
     self.assertRaises(RuntimeError, self.participant.handle_lifecycle_control, ctrl)
     ctrl.config.add_section("obs")
     ctrl.config.set("obs", "oscrc", "oscrc_file")
     self.participant.handle_lifecycle_control(ctrl)
     ctrl.config.add_section("check_yaml")
     ctrl.config.set("check_yaml", "spec_pattern", "test")
     self.participant.handle_lifecycle_control(ctrl)
 def setUp(self):  # pylint: disable=C0103
     """Test setup."""
     os.mkdir(TMP)
     self.queuename = os.path.join(TMP, "wq")
     ctrl = Mock()
     ctrl.message = "start"
     ctrl.config = ConfigParser()
     ctrl.config.add_section("obsticket")
     ctrl.config.set("obsticket", "prjdir", TMP)
     self.participant = obsticket.ParticipantHandler()
     self.participant.handle_lifecycle_control(ctrl)
Example #12
0
def event():
    result = Mock()
    for k, v in DEFAULT_PLUGIN_CONFIGURATION.items():
        setattr(result.project, k, v)

    result.get_level_display = Mock()
    result.get_level_display.return_value = "ERROR"

    result.message = "An error has occured"

    return result
 def setUp(self):  # pylint: disable=C0103
     """Test setup."""
     BaseTestParticipantHandler.setUp(self)
     ctrl = Mock()
     ctrl.message = "start"
     ctrl.config = ConfigParser()
     ctrl.config.add_section("obs")
     ctrl.config.add_section("defineimage")
     ctrl.config.add_section("testing")
     ctrl.config.set("obs", "oscrc", "oscrc_file")
     ctrl.config.set("defineimage", "imagetypes", "testing")
     ctrl.config.set("testing", "always_include", "base-tests")
     self.ctrl = ctrl
    def test_handle_lifecycle_control(self):
        """Test participant.handle_lifecycle_control()"""
        config = ConfigParser()
        ctrl = Mock()
        ctrl.message = "start"
        ctrl.config = config

        self.assertRaises(RuntimeError, self.participant.handle_lifecycle_control, ctrl)
        config.add_section("obs")
        config.set("obs", "oscrc", "oscrc_file")
        self.assertRaises(RuntimeError, self.participant.handle_lifecycle_control, ctrl)
        config.add_section("getbuildlog")
        config.set("getbuildlog", "logdir", "test_tmp")
 def setUp(self):
     """Set up the tests."""
     BaseTestParticipantHandler.setUp(self)
     os.mkdir(TEMP_DIR)
     config = ConfigParser()
     config.add_section("obs")
     config.set("obs", "oscrc", "oscrc_file")
     config.add_section("getbuildlog")
     config.set("getbuildlog", "logdir", "test_tmp")
     ctrl = Mock()
     ctrl.message = "start"
     ctrl.config = config
     self.participant.handle_lifecycle_control(ctrl)
 def test_fault(self):
     fault_message = "Error"
     fault_details = "details"
     fault_date = "now"
     temp_fault = Mock()
     temp_fault.message = fault_message
     temp_fault.details = fault_details
     temp_fault.updated = fault_date
     fault_mock = Mock(return_value=temp_fault)
     with patch.object(DBInstanceFault, "find_by", fault_mock):
         fault = self.instance.fault
         self.assertEqual(fault_message, fault.message)
         self.assertEqual(fault_details, fault.details)
         self.assertEqual(fault_date, fault.updated)
def test_handle_http_exception():
    e = Mock(HttpExceptionBase)
    e.status = 1234
    e.message = "message"

    request = mock_http_request()

    with patch.multiple("http.handle_requests", has_error_handler=DEFAULT, get_error_handler=DEFAULT) as values:
        values["has_error_handler"].return_value = False
        resp = handle_http_exception(request, e)
        values["has_error_handler"].assert_called_once()
        values["get_error_handler"].assert_has_calls([])

    assert isinstance(resp, HTTPResponse)
    assert resp.status == 1234
    assert resp.code == "message"
    assert resp.content_type == "text/html"
    def configure_participant(self):
        ctrl = Mock()
        ctrl.message = "start"
        ctrl.config = ConfigParser()
        ctrl.config.add_section("obs")
        ctrl.config.set("obs", "oscrc", "oscrc_file")
        self.participant.handle_lifecycle_control(ctrl)

        self.mut.subprocess = Mock()
        self.mut.subprocess.Popen.side_effect = self.mock_specify

        self.participant.obs.getFile.return_value = TEST_SPEC
        self.specify_out = TEST_SPEC

        self.wid = Workitem(WI_TEMPLATE)
        self.wid.fields.msg = None
        self.wid.fields.ev.actions = self.fake_actions
        self.wid.fields.ev.namespace = "test"
Example #19
0
 def create_blank_response(cls, code, msg):
     response = Mock(spec=Response)
     response.responseCode = code
     response.message = msg
     response.result = Mock(spec=Result)
     return response
 def test_handle_lifecycle_control(self):
     ctrl = Mock()
     ctrl.message = "start"
     ctrl.config = self.config
     self.participant.handle_lifecycle_control(ctrl)
Example #21
0
 def test_remove_duplicates(self):
     self.assertEqual([], remove_duplicates([]))
     issue1 = Mock()
     issue2 = Mock()
     issue1.path = "/filename"
     issue2.path = "/filename"
     issue1.severity = 10
     issue2.severity = 10
     issue1.line_number_start = None
     issue2.line_number_start = None
     issue1.line_position = None
     issue2.line_position = None
     issue1.message = "foo"
     issue2.message = "bar"
     self.assertEqual([issue1, issue2], remove_duplicates([issue1, issue2]))
     issue1.line_number_start = 42
     issue2.line_number_start = 42
     issue1.message = "line too long"
     issue2.message = "unused import foo"
     self.assertEqual([issue1, issue2], remove_duplicates([issue1, issue2]))
     issue1.line_number_start = 42
     issue2.line_number_start = 42
     issue1.line_position = -1
     issue2.line_position = -1
     issue1.message = "unused import bar"
     issue2.message = "module bar not used"
     self.assertEqual([issue1], remove_duplicates([issue1, issue2]))
     issue1.line_number_start = 42
     issue2.line_number_start = 42
     issue1.line_position = 12
     issue2.line_position = 28
     issue1.message = "unused import bar"
     issue2.message = "module foo not used"
     self.assertEqual([issue1, issue2], remove_duplicates([issue1, issue2]))
     issue1.line_number_start = 32
     issue2.line_number_start = 32
     issue1.line_position = 80
     issue2.line_position = -1
     issue1.message = "line too long (92 characters)"
     issue2.message = "Line too long (92/80)"
     self.assertEqual([issue1], remove_duplicates([issue1, issue2]))
     issue1.line_number_start = 32
     issue2.line_number_start = 33
     issue1.line_position = 80
     issue2.line_position = -1
     issue1.message = "line too long (92 characters)"
     issue2.message = "Line too long (92/80)"
     self.assertEqual([issue1, issue2], remove_duplicates([issue1, issue2]))
 def test_handle_wi_control(self):
     """Test participant.handle_wi_control()"""
     ctrl = Mock()
     ctrl.message = "start"
     self.participant.handle_wi_control(ctrl)
Example #23
0
 def test_is_boto_no_update_required_exception_returns_false_with_other_exception(self):
     exception = Mock(spec=Exception)
     exception.message = "No updates are to be performed."
     self.assertFalse(CloudFormation.is_boto_no_update_required_exception(exception))
Example #24
0
    def test_service_policies(self):
        gc = Mock()
        service_key = "service_key"
        pdpm = PolicyDecisionPointManager(gc)
        # see that the PDP for service is the default
        self.assertEqual(pdpm.get_service_pdp(service_key), pdpm.load_common_service_pdp)

        pdpm.load_service_policy_rules(service_key, self.permit_ION_MANAGER_rule)

        # see that the PDP for service is not the default anymore
        self.assertNotEqual(pdpm.get_service_pdp(service_key), pdpm.load_common_service_pdp)

        # check request without a service_key raises NotFound error
        invocation = Mock()
        invocation.message_annotations = {}

        invocation.get_message_receiver.return_value = None
        with self.assertRaises(NotFound) as chk_res:
            pdpm.check_service_request_policies(invocation)
        self.assertIn(chk_res.exception.message, "No receiver for this message")

        # check that, because actor does not have ION_MANAGER role, policy evaluates to a denial
        # (really Not Applicable, because of the inelegant hack of a policy we are setting up our pdp with)
        mock_header = Mock()
        invocation.message_annotations = {}
        invocation.message = {"argument1": 0}
        invocation.headers = {
            "op": "op",
            "process": "process",
            "request": "request",
            "ion-actor-id": "ion-actor-id",
            "receiver": "resource-registry",
            "sender-type": "sender-type",
            "sender-service": "Unknown",
            "ion-actor-roles": {"org_name": ["ion-actor-roles"]},
        }
        invocation.get_message_receiver.return_value = "service_key"
        invocation.get_service_name.return_value = "Unknown"
        invocation.get_message_sender.return_value = ["Unknown", "Unknown"]

        def get_header_value(key, default):
            return invocation.headers.get(key, default)

        mock_header.side_effect = get_header_value
        invocation.get_header_value = mock_header
        mock_args = Mock()
        process = Mock()
        process.org_governance_name = "org_name"
        invocation.args = {"process": process}

        def get_arg_value(key, default):
            return invocation.args.get(key, default)

        mock_args.side_effect = get_arg_value
        invocation.get_arg_value = mock_args

        gc.system_root_org_name = "sys_org_name"

        response = pdpm.check_service_request_policies(invocation)
        self.assertEqual(response.value, "NotApplicable")

        # check that policy evaluates to Permit because actor has ION_MANAGER role
        invocation.message_annotations = {}
        invocation.headers = {
            "op": "op",
            "process": "process",
            "request": "request",
            "ion-actor-id": "ion-actor-id",
            "receiver": "resource-registry",
            "sender-type": "sender-type",
            "sender-service": "sender-service",
            "ion-actor-roles": {"sys_org_name": ["ION_MANAGER"]},
        }
        response = pdpm.check_service_request_policies(invocation)
        self.assertEqual(response.value, "Permit")
Example #25
0
 def test_is_boto_no_update_required_exception_returns_true_for_message(self):
     exception = Mock(spec=BotoServerError)
     exception.message = "No updates are to be performed."
     self.assertTrue(CloudFormation.is_boto_no_update_required_exception(exception))
Example #26
0
 def test_is_boto_no_update_required_exception_returns_false_without_message(self):
     exception = Mock(spec=BotoServerError)
     exception.message = "Something went wrong."
     self.assertFalse(CloudFormation.is_boto_no_update_required_exception(exception))