def test_run_already_in_progress(self, mock_sync, mock_get, mock_status):
        # Setup
        data = {
            options.OPTION_REPO_ID.keyword: 'test-repo',
            sp.NAME_BACKGROUND: False,
        }

        # Simulate a task already running
        task_data = copy.copy(CALL_REPORT_TEMPLATE)
        task_data['response'] = 'accepted'
        task_data['state'] = 'running'
        task = Task(task_data)
        mock_get.return_value = Response(200, [task])

        # Response from the sync call
        task_data = copy.copy(CALL_REPORT_TEMPLATE)
        task = Task(task_data)
        mock_sync.return_value = Response(202, [task])

        # Test
        self.command.run(**data)

        # Verify
        self.assertEqual(1, mock_status.call_count)

        tags = self.prompt.get_write_tags()
        self.assertEqual(2, len(tags))
        self.assertEqual(tags[1], 'in-progress')
示例#2
0
    def test_rpm_group_export_missing_distributor(self, mock_distributors,
                                                  mock_create, mock_publish):
        """
        Test that when there is no distributor attached to the repository group, one is added
        """
        # Setup
        mock_distributors.return_value = Response(200, [])
        mock_publish.return_value = Response(200, [])

        expected_distributor_config = {
            constants.PUBLISH_HTTP_KEYWORD: True,
            constants.PUBLISH_HTTPS_KEYWORD: True,
        }

        # Test
        command = export.RpmGroupExportCommand(
            self.context, mock.MagicMock(),
            ids.TYPE_ID_DISTRIBUTOR_GROUP_EXPORT)
        command.run(**self.kwargs)

        # Assert that the call get get the distributor was made correctly
        self.assertEqual(1, mock_distributors.call_count)
        self.assertEqual('test-group', mock_distributors.call_args[0][1])

        # Assert that when the NonFoundException is raised, a call to create a distributor is made
        self.assertEqual(1, mock_create.call_count)
        self.assertEqual('test-group', mock_create.call_args[0][1])
        self.assertEqual(ids.TYPE_ID_DISTRIBUTOR_GROUP_EXPORT,
                         mock_create.call_args[0][2])
        self.assertEqual(expected_distributor_config,
                         mock_create.call_args[0][3])
示例#3
0
    def test_rpm_group_export_run(self, mock_distributors, mock_create,
                                  mock_publish):
        """
        Test to make sure the publish binding is called correctly with an existing distributor.
        """
        # Setup
        mock_distributor = {
            'distributor_type_id': ids.TYPE_ID_DISTRIBUTOR_GROUP_EXPORT,
            'id': 'foo-distributor'
        }
        mock_distributors.return_value = Response(200, [mock_distributor])
        mock_publish.return_value = Response(200, [])

        expected_publish_config = {
            constants.PUBLISH_HTTP_KEYWORD: True,
            constants.PUBLISH_HTTPS_KEYWORD: True,
        }

        # Test
        command = export.RpmGroupExportCommand(
            self.context, mock.MagicMock(),
            ids.TYPE_ID_DISTRIBUTOR_GROUP_EXPORT)
        command.run(**self.kwargs)

        # Assert that the call get get the distributor was made correctly
        self.assertEqual(1, mock_distributors.call_count)
        self.assertEqual('test-group', mock_distributors.call_args[0][1])

        mock_publish.assert_called_once_with(mock.ANY, 'test-group', mock.ANY,
                                             expected_publish_config)
示例#4
0
    def test_run_search_errata_details(self, mock_search):
        """
        Test that when the --erratum-id argument is used, the custom output
        function write_erratum_detail is called instead of render_document_list
        """
        # Setup
        mock_out = mock.MagicMock()
        units = [{'a': 'a', 'metadata': 'm'}]
        mock_search.return_value = Response(200, units)

        user_input = {
            'repo-id': 'repo-1',
            'erratum-id': 'RHEA-0000:0000',
            DisplayUnitAssociationsCommand.ASSOCIATION_FLAG.keyword: False
        }

        # Test
        command = contents.SearchErrataCommand(self.context)
        command.write_erratum_detail = mock_out
        command.errata(**user_input)

        # Verify
        expected = {
            'type_ids': [contents.TYPE_ERRATUM],
            'filters': {'id': 'RHEA-0000:0000'},
        }
        mock_search.assert_called_once_with('repo-1', **expected)
        # Because there's only one type_id and contents.FIELDS_BY_TYPE[FIELDS_ERRATA] is
        # defined, the write_erratum_detail should be called with the metadata and FIELDS_ERRATA
        mock_out.assert_called_once_with(['m'], contents.FIELDS_ERRATA)
示例#5
0
    def test_run_search_errata(self, mock_search):
        """
        Test that when the --erratum-id argument isn't used, the default
        render_document_list output function is called
        """
        # Setup
        mock_out = mock.MagicMock()
        units = [{'a': 'a', 'metadata': 'm'}]
        mock_search.return_value = Response(200, units)

        user_input = {
            'repo-id': 'repo-1',
            'erratum-id': None,
            DisplayUnitAssociationsCommand.ASSOCIATION_FLAG.keyword: False,
        }

        # Test
        self.context.prompt.render_document_list = mock_out
        command = contents.SearchErrataCommand(self.context)
        command.errata(**user_input)

        # Verify
        expected = {
            'type_ids': [contents.TYPE_ERRATUM],
            'erratum-id': None,
            DisplayUnitAssociationsCommand.ASSOCIATION_FLAG.keyword: False,
        }
        mock_search.assert_called_once_with('repo-1', **expected)
        # Because there's only one type_id and contents.FIELDS_BY_TYPE[FIELDS_ERRATA] is
        # defined, the output function should be called with the metadata and FIELDS_ERRATA
        mock_out.assert_called_once_with(['m'], contents.FIELDS_ERRATA)
示例#6
0
    def test_run_search_with_field_filters(self, mock_search):
        # Setup
        mock_out = mock.MagicMock()
        units = [{'a': 'a', 'metadata': 'm'}]
        mock_search.return_value = Response(200, units)

        user_input = {
            'repo-id': 'repo-1',
            DisplayUnitAssociationsCommand.ASSOCIATION_FLAG.keyword: False,
        }

        # Test
        command = contents.BaseSearchCommand(None, self.context)
        command.run_search([contents.TYPE_RPM],
                           out_func=mock_out,
                           **user_input)

        # Verify
        expected = {
            'type_ids': [contents.TYPE_RPM],
            DisplayUnitAssociationsCommand.ASSOCIATION_FLAG.keyword: False,
        }
        mock_search.assert_called_once_with('repo-1', **expected)
        mock_out.assert_called_once_with(
            ['m'], contents.FIELDS_BY_TYPE[contents.TYPE_RPM])
示例#7
0
    def test_update(self):
        # Setup
        strategy = mock.Mock()
        strategy.update_schedule.return_value = Response(200, {})

        update_command = commands.UpdateScheduleCommand(
            self.context, strategy, 'update', 'update')
        update_command.create_option('--extra', 'extra')
        self.cli.add_command(update_command)

        # Test
        self.cli.run(
            'update --schedule-id foo --schedule 2012-05-22T00:00:00/P1D --failure-threshold 1 --enabled true --extra bar'
            .split())

        # Verify
        args = strategy.update_schedule.call_args[0]
        self.assertEqual(1, len(args))
        self.assertEqual('foo', args[0])

        kwargs = strategy.update_schedule.call_args[1]
        self.assertTrue('schedule' in kwargs)
        self.assertEqual('2012-05-22T00:00:00/P1D', kwargs['schedule'])
        self.assertTrue('failure_threshold' in kwargs)
        self.assertEqual('1', kwargs['failure_threshold'])
        self.assertTrue('enabled' in kwargs)
        self.assertEqual(True, kwargs['enabled'])

        self.assertEqual(1, len(self.prompt.get_write_tags()))
        self.assertEqual(TAG_SUCCESS, self.prompt.get_write_tags()[0])
示例#8
0
    def test_list(self):
        # Setup
        strategy = mock.Mock()
        strategy.retrieve_schedules.return_value = Response(
            200, copy.deepcopy(EXAMPLE_SCHEDULE_LIST))

        list_command = commands.ListScheduleCommand(self.context, strategy,
                                                    'list', 'list')
        list_command.create_option('--extra', 'extra')
        self.cli.add_command(list_command)

        # Test
        self.cli.run('list --extra foo'.split())

        # Verify
        self.assertEqual(strategy.retrieve_schedules.call_count, 1)
        self.assertEqual(strategy.retrieve_schedules.call_args[0][0]['extra'],
                         'foo')

        # Spot check the ID lines in the displayed list
        id_lines = [l for l in self.recorder.lines if l.startswith('Id')]
        self.assertEqual(3, len(id_lines))

        ids = [l.split()[1] for l in id_lines]
        self.assertTrue(EXAMPLE_SCHEDULE_LIST[0]['_id'] in ids)
        self.assertTrue(EXAMPLE_SCHEDULE_LIST[1]['_id'] in ids)
        self.assertTrue(EXAMPLE_SCHEDULE_LIST[2]['_id'] in ids)
示例#9
0
    def test_list_details(self):
        # Setup
        strategy = mock.Mock()
        strategy.retrieve_schedules.return_value = Response(
            200, copy.deepcopy(EXAMPLE_SCHEDULE_LIST))

        list_command = commands.ListScheduleCommand(self.context, strategy,
                                                    'list', 'list')
        self.cli.add_command(list_command)

        # Test
        self.cli.run('list --details'.split())

        # Verify
        self.assertEqual(strategy.retrieve_schedules.call_count, 1)

        # Spot check the ID lines in the displayed list
        fr_lines = [
            l for l in self.recorder.lines if l.startswith('First Run')
        ]
        self.assertEqual(3, len(fr_lines))

        first_runs = [l.split()[2] for l in fr_lines]
        self.assertTrue(EXAMPLE_SCHEDULE_LIST[0]['first_run'] in first_runs)
        self.assertTrue(EXAMPLE_SCHEDULE_LIST[1]['first_run'] in first_runs)
        self.assertTrue(EXAMPLE_SCHEDULE_LIST[2]['first_run'] in first_runs)
示例#10
0
 def _mock_initialize_upload(self):
     """
     Configures the mock bindings to return a valid upload ID.
     """
     body = {
         'upload_id': MOCK_UPLOAD_ID,
         '_href': MOCK_LOCATION,
     }
     self.mock_upload_bindings.initialize_upload.return_value = Response(201, body)
示例#11
0
文件: server.py 项目: ipanova/pulp
    def _request(self, method, path, queries=(), body=None, ensure_encoding=True):
        """
        make a HTTP request to the pulp server and return the response

        :param method:  name of an HTTP method such as GET, POST, PUT, HEAD
                        or DELETE
        :type  method:  basestring

        :param path:    URL for this request
        :type  path:    basestring

        :param queries: mapping object or a sequence of 2-element tuples,
                        in either case representing key-value pairs to be used
                        as query parameters on the URL.
        :type  queries: mapping object or sequence of 2-element tuples

        :param body:    Data structure that will be JSON serialized and send as
                        the request's body.
        :type  body:    Anything that is JSON-serializable.

        :param ensure_encoding: toggle proper string encoding for the body
        :type ensure_encoding: bool

        :return:    Response object
        :rtype:     pulp.bindings.responses.Response

        :raises:    ConnectionException or one of the RequestExceptions
                    (depending on response codes) in case of unsuccessful
                    request
        """
        url = self._build_url(path, queries)
        if ensure_encoding:
            body = self._process_body(body)
        if not isinstance(body, (NoneType, basestring)):
            body = json.dumps(body)
        self.log.debug('sending %s request to %s' % (method, url))

        response_code, response_body = self.server_wrapper.request(method, url, body)

        if self.api_responses_logger:
            self.api_responses_logger.info('%s request to %s with parameters %s' % (method, url, body))
            self.api_responses_logger.info("Response status : %s \n" % response_code)
            self.api_responses_logger.info("Response body :\n %s\n" % json.dumps(response_body, indent=2))

        if response_code >= 300:
            self._handle_exceptions(response_code, response_body)
        elif response_code == 200 or response_code == 201:
            body = response_body
        elif response_code == 202:
            if isinstance(response_body, list):
                body = [Task(t) for t in response_body]
            else:
                body = Task(response_body)

        return Response(response_code, body)
    def test_run(self, mock_sync, mock_get, mock_status):
        # Setup
        data = {
            options.OPTION_REPO_ID.keyword: 'test-repo',
            sp.NAME_BACKGROUND: False,
        }

        # No tasks are running
        mock_get.return_value = Response(200, [])

        # Response from the sync call
        task_data = copy.copy(CALL_REPORT_TEMPLATE)
        task = Task(task_data)
        mock_sync.return_value = Response(202, [task])

        # Test
        self.command.run(**data)

        # Verify
        self.assertEqual(1, mock_status.call_count)
示例#13
0
    def test_next_run_no_schedules(self):
        # Setup
        strategy = mock.Mock()
        strategy.retrieve_schedules.return_value = Response(200, {})

        next_command = commands.NextRunCommand(self.context, strategy, 'next',
                                               'next')
        self.cli.add_command(next_command)

        # Test
        self.cli.run('next'.split())

        # Verify
        self.assertTrue('no schedules' in self.recorder.lines[0])
    def test_run_background(self, mock_publish, mock_get, mock_status):
        # Setup
        data = {
            options.OPTION_REPO_ID.keyword: 'test-repo',
            sp.NAME_BACKGROUND: True,
        }

        # No tasks are running
        mock_get.return_value = Response(200, [])

        # Response from the sync call
        task_data = copy.copy(CALL_REPORT_TEMPLATE)
        task = Task(task_data)
        mock_publish.return_value = Response(202, task)

        # Test
        self.command.run(**data)

        # Verify
        self.assertEqual(0, mock_status.call_count)  # since its background

        tags = self.prompt.get_write_tags()
        self.assertEqual(2, len(tags))
        self.assertEqual(tags[1], 'background')
示例#15
0
        def poll(task_id):
            task = Task(TASK_TEMPLATE)

            # Wait for the first 2 polls
            if mock_get.call_count < 3:
                task.state = STATE_WAITING

            # Running for the next 10
            elif mock_get.call_count < 13:
                task.state = STATE_RUNNING

            # Finally finish
            else:
                task.state = STATE_ERROR

            return Response(200, task)
    def test_run_no_status(self, mock_get, mock_status):
        # Setup
        data = {
            options.OPTION_REPO_ID.keyword: 'test-repo',
        }

        # No tasks are running
        mock_get.return_value = Response(200, [])

        # Test
        self.command.run(**data)

        # Verify
        self.assertEqual(1, mock_get.call_count)
        self.assertEqual(0, mock_status.call_count)
        self.assertEqual(self.prompt.get_write_tags(), [TAG_TITLE, 'no-tasks'])
示例#17
0
    def test_next_run_quiet(self):
        # Setup
        strategy = mock.Mock()
        strategy.retrieve_schedules.return_value = Response(
            200, copy.copy(EXAMPLE_SCHEDULE_LIST))

        next_command = commands.NextRunCommand(self.context, strategy, 'next',
                                               'next')
        self.cli.add_command(next_command)

        # Test
        self.cli.run('next --quiet'.split())

        # Verify
        self.assertEqual(1, len(self.prompt.get_write_tags()))
        self.assertEqual(TAG_PARAGRAPH, self.prompt.get_write_tags()[0])
        self.assertEqual('2012-05-22T00:00:00Z\n', self.recorder.lines[0])
    def test_run(self, mock_get, mock_status):
        # Setup
        data = {
            options.OPTION_REPO_ID.keyword: 'test-repo',
        }

        # Simulate a task already running
        task_data = copy.copy(CALL_REPORT_TEMPLATE)
        task_data['response'] = 'accepted'
        task_data['state'] = 'running'
        task = Task(task_data)
        mock_get.return_value = Response(200, [task])

        # Test
        self.command.run(**data)

        # Verify
        self.assertEqual(1, mock_get.call_count)
        self.assertEqual(1, mock_status.call_count)
示例#19
0
    def test_delete(self):
        # Setup
        strategy = mock.Mock()
        strategy.create_schedule.return_value = Response(200, {})

        delete_command = commands.DeleteScheduleCommand(
            self.context, strategy, 'delete', 'delete')
        delete_command.create_option('--extra', 'extra stuff')
        self.cli.add_command(delete_command)

        # Test
        self.cli.run('delete --schedule-id foo --extra e1'.split())

        # Verify
        args = strategy.delete_schedule.call_args[0]
        self.assertEqual('foo', args[0])
        self.assertTrue('extra' in args[1])
        self.assertEqual('e1', args[1]['extra'])

        self.assertEqual(1, len(self.prompt.get_write_tags()))
        self.assertEqual(TAG_SUCCESS, self.prompt.get_write_tags()[0])
示例#20
0
    def test_run_search(self, mock_search):
        # Setup
        mock_out = mock.MagicMock()
        units = [{'a': 'a', 'metadata': 'm'}]
        mock_search.return_value = Response(200, units)

        user_input = {
            'repo-id': 'repo-1',
            DisplayUnitAssociationsCommand.ASSOCIATION_FLAG.keyword: True,
        }

        # Test
        command = contents.BaseSearchCommand(self.context)
        command.run_search(['fake-type'], out_func=mock_out, **user_input)

        # Verify
        expected = {
            'type_ids': ['fake-type'],
            DisplayUnitAssociationsCommand.ASSOCIATION_FLAG.keyword: True,
        }
        mock_search.assert_called_once_with('repo-1', **expected)
        mock_out.assert_called_once_with(units)
示例#21
0
    def test_next_run(self):
        # Setup
        strategy = mock.Mock()
        strategy.retrieve_schedules.return_value = Response(
            200, copy.copy(EXAMPLE_SCHEDULE_LIST))

        next_command = commands.NextRunCommand(self.context, strategy, 'next',
                                               'next')
        next_command.create_option('--extra', 'extra')
        self.cli.add_command(next_command)

        # Test
        self.cli.run('next --extra foo'.split())

        # Verify
        self.assertEqual(1, strategy.retrieve_schedules.call_count)
        self.assertEqual(strategy.retrieve_schedules.call_args[0][0]['extra'],
                         'foo')

        self.assertEqual(1, len(self.prompt.get_write_tags()))
        self.assertEqual(TAG_PARAGRAPH, self.prompt.get_write_tags()[0])
        self.assertTrue('2012-05-22T00:00:00Z' in self.recorder.lines[0])
        self.assertTrue('2012-05-15T00:00:00Z/P1W' in self.recorder.lines[0])
示例#22
0
    def test_add(self):
        # Setup
        strategy = mock.Mock()
        strategy.create_schedule.return_value = Response(201, {})

        create_command = commands.CreateScheduleCommand(
            self.context, strategy, 'add', 'add')
        create_command.create_option('--extra', 'extra')
        self.cli.add_command(create_command)

        # Test
        self.cli.run(
            'add --schedule 2012-05-22T00:00:00/P1D --failure-threshold 10 --extra foo'
            .split())

        # Verify
        args = strategy.create_schedule.call_args[0]
        self.assertEqual('2012-05-22T00:00:00/P1D', args[0])
        self.assertEqual('10', args[1])
        self.assertEqual(True, args[2])
        self.assertEqual('foo', args[3]['extra'])

        self.assertEqual(1, len(self.prompt.get_write_tags()))
        self.assertEqual(TAG_SUCCESS, self.prompt.get_write_tags()[0])
示例#23
0
 def search_simulator(repo_id, **criteria):
     response = Response(200, copy.copy(search_results))
     if len(search_results):
         search_results.pop(0)
     return response
示例#24
0
 def _mock_import_upload(self):
     """
     Configures the mock bindings to return a valid response on importing an upload.
     """
     self.mock_upload_bindings.import_upload.return_value = Response(200, {})
示例#25
0
 def _mock_delete_upload(self):
     """
     Configures the mock bindings to return a valid response to deleting an upload.
     """
     self.mock_upload_bindings.delete_upload.return_value = Response(200, {})
示例#26
0
 def _mock_upload_segment(self):
     """
     Configures the mock bindings to return a valid response to uploading a segment.
     """
     self.mock_upload_bindings.upload_segment.return_value = Response(200, {})