Ejemplo n.º 1
0
 def test_unknown_status(self):
     """Assert the method correctly handles an unknown bug status."""
     ver = Version('0')
     bug = selectors._Bug('foo', ver)
     with mock.patch.object(selectors, '_get_bug', return_value=bug):
         with self.assertRaises(exceptions.BugStatusUnknownError):
             selectors.bug_is_testable(None, ver)
 def test_unknown_status(self):
     """Assert the method correctly handles an unknown bug status."""
     ver = Version('0')
     bug = selectors._Bug('foo', ver)
     with mock.patch.object(selectors, '_get_bug', return_value=bug):
         with self.assertRaises(exceptions.BugStatusUnknownError):
             selectors.bug_is_testable(None, ver)
Ejemplo n.º 3
0
 def test_unknown_status(self):
     """Make the dependent function return an unknown bug status."""
     with mock.patch.object(
         selectors,
         '_get_bug_status',
         return_value=None,
     ):
         with self.assertRaises(exceptions.BugStatusUnknownError):
             selectors.bug_is_testable(None)
 def test_connection_error(self):
     """Make the dependent function raise a connection error."""
     ver = Version('0')
     with mock.patch.object(selectors, '_get_bug') as get_bug:
         get_bug.side_effect = requests.exceptions.ConnectionError
         with self.assertWarns(RuntimeWarning):
             selectors.bug_is_testable(None, ver)
         with self.assertWarns(RuntimeWarning):
             selectors.bug_is_untestable(None, ver)
Ejemplo n.º 5
0
 def test_connection_error(self):
     """Make the dependent function raise a connection error."""
     ver = Version('0')
     with mock.patch.object(selectors, '_get_bug') as get_bug:
         get_bug.side_effect = requests.exceptions.ConnectionError
         with self.assertWarns(RuntimeWarning):
             selectors.bug_is_testable(None, ver)
         with self.assertWarns(RuntimeWarning):
             selectors.bug_is_untestable(None, ver)
def setUpModule():  # pylint:disable=invalid-name
    """Conditionally skip tests. Create repositories with fixture data."""
    cfg = config.get_config()
    if selectors.bug_is_untestable(1991, cfg.version):
        raise unittest.SkipTest('https://pulp.plan.io/issues/1991')
    set_up_module()

    # Fetch RPMs.
    _SIGNED_PACKAGES['rpm'] = utils.http_get(RPM_URL)
    _SIGNED_PACKAGES['srpm'] = utils.http_get(SRPM_URL)
    _UNSIGNED_PACKAGES['rpm'] = utils.http_get(RPM_UNSIGNED_URL)
    _UNSIGNED_PACKAGES['srpm'] = utils.http_get(SRPM_UNSIGNED_URL)
    if selectors.bug_is_testable(1806, cfg.version):
        _SIGNED_PACKAGES['drpm'] = utils.http_get(DRPM_URL)
        _UNSIGNED_PACKAGES['drpm'] = utils.http_get(DRPM_UNSIGNED_URL)

    # Create repos, and upload RPMs to them.
    client = api.Client(cfg, api.json_handler)
    try:
        repo = client.post(REPOSITORY_PATH, gen_repo())
        _REPOS['signed'] = repo
        for type_id, pkg in _SIGNED_PACKAGES.items():
            utils.upload_import_unit(cfg, pkg, type_id, repo['_href'])

        repo = client.post(REPOSITORY_PATH, gen_repo())
        _REPOS['unsigned'] = repo
        for type_id, pkg in _UNSIGNED_PACKAGES.items():
            utils.upload_import_unit(cfg, pkg, type_id, repo['_href'])
    except:
        _SIGNED_PACKAGES.clear()
        _UNSIGNED_PACKAGES.clear()
        for _ in range(len(_REPOS)):
            client.delete(_REPOS.popitem()[1]['_href'])
        raise
def setUpModule():  # pylint:disable=invalid-name
    """Conditionally skip tests. Cache packages to be uploaded to repos.

    Skip the tests in this module if:

    * The RPM plugin is unsupported.
    * `Pulp #1991 <https://pulp.plan.io/issues/1991>`_ is untestable for the
      version of Pulp under test.
    """
    cfg = config.get_config()
    if selectors.bug_is_untestable(1991, cfg.version):
        raise unittest.SkipTest('https://pulp.plan.io/issues/1991')
    set_up_module()
    try:
        _SIGNED_PACKAGES['rpm'] = utils.http_get(RPM_SIGNED_URL)
        _SIGNED_PACKAGES['srpm'] = utils.http_get(SRPM_SIGNED_URL)
        _UNSIGNED_PACKAGES['rpm'] = utils.http_get(RPM_UNSIGNED_URL)
        _UNSIGNED_PACKAGES['srpm'] = utils.http_get(SRPM_UNSIGNED_URL)
        if selectors.bug_is_testable(1806, cfg.version):
            _SIGNED_PACKAGES['drpm'] = utils.http_get(DRPM_SIGNED_URL)
            _UNSIGNED_PACKAGES['drpm'] = utils.http_get(DRPM_UNSIGNED_URL)
    except:
        _SIGNED_PACKAGES.clear()
        _UNSIGNED_PACKAGES.clear()
        raise
def setUpModule():  # pylint:disable=invalid-name
    """Conditionally skip tests. Cache packages to be uploaded to repos.

    Skip the tests in this module if:

    * The RPM plugin is unsupported.
    * `Pulp #1991 <https://pulp.plan.io/issues/1991>`_ is untestable for the
      version of Pulp under test.
    """
    cfg = config.get_config()
    if selectors.bug_is_untestable(1991, cfg.version):
        raise unittest.SkipTest('https://pulp.plan.io/issues/1991')
    set_up_module()
    try:
        _SIGNED_PACKAGES['rpm'] = utils.http_get(RPM_URL)
        _SIGNED_PACKAGES['srpm'] = utils.http_get(SRPM_URL)
        _UNSIGNED_PACKAGES['rpm'] = utils.http_get(RPM_UNSIGNED_URL)
        _UNSIGNED_PACKAGES['srpm'] = utils.http_get(SRPM_UNSIGNED_URL)
        if selectors.bug_is_testable(1806, cfg.version):
            _SIGNED_PACKAGES['drpm'] = utils.http_get(DRPM_URL)
            _UNSIGNED_PACKAGES['drpm'] = utils.http_get(DRPM_UNSIGNED_URL)
    except:
        _SIGNED_PACKAGES.clear()
        _UNSIGNED_PACKAGES.clear()
        raise
Ejemplo n.º 9
0
    def test_all(self):
        """Work with an image whose name has no namespace.

        Create, sync and publish a Docker repository whose ``UPSTREAM_NAME``
        doesn't include a namespace. A typical Docker image has a name like
        "library/busybox." When a non-namespaced image name like "busybox" is
        given, a prefix of "library" is assumed.
        """
        cfg = config.get_config()
        client = api.Client(cfg, api.json_handler)
        body = gen_repo()
        body['importer_config'].update({
            'enable_v1': False,
            'enable_v2': True,
            'feed': DOCKER_V2_FEED_URL,
            'upstream_name': 'busybox',
        })
        body['distributors'] = [gen_distributor()]
        repo = client.post(REPOSITORY_PATH, body)
        self.addCleanup(client.delete, repo['_href'])
        repo = client.get(repo['_href'], params={'details': True})
        utils.sync_repo(cfg, repo)
        utils.publish_repo(cfg, repo)

        # Make Crane read the metadata. (Now!)
        cli.GlobalServiceManager(cfg).restart(('httpd', ))

        # Get and inspect /crane/repositories/v2.
        if (cfg.pulp_version >= Version('2.14')
                and selectors.bug_is_testable(2723, cfg.pulp_version)):
            client = self.make_crane_client(cfg)
            repo_id = repo['id']
            repos = client.get('/crane/repositories/v2')
            self.assertIn(repo_id, repos.keys())
            self.assertFalse(repos[repo_id]['protected'])
Ejemplo n.º 10
0
    def test_all(self):
        """Publish the rpm rsync distributor before the yum distributor."""
        cfg = config.get_config()
        if selectors.bug_is_untestable(2187, cfg.pulp_version):
            self.skipTest('https://pulp.plan.io/issues/2187')

        # Create a user and a repository.
        ssh_user, priv_key = self.make_user(cfg)
        ssh_identity_file = self.write_private_key(cfg, priv_key)
        repo = self.make_repo(
            cfg, {
                'remote': {
                    'host': urlparse(cfg.get_base_url()).hostname,
                    'root': '/home/' + ssh_user,
                    'ssh_identity_file': ssh_identity_file,
                    'ssh_user': ssh_user,
                }
            })

        # Publish with the rsync distributor.
        distribs = get_dists_by_type_id(cfg, repo)
        args = (cfg, repo, {'id': distribs['rpm_rsync_distributor']['id']})
        self.verify_publish_is_skip(cfg, utils.publish_repo(*args).json())

        # Verify that the rsync distributor hasn't placed files.
        sudo = '' if utils.is_root(cfg) else 'sudo '
        cmd = (sudo + 'ls -1 /home/{}'.format(ssh_user)).split()
        dirs = set(cli.Client(cfg).run(cmd).stdout.strip().split('\n'))
        self.assertNotIn('content', dirs)

        # Publish with the rsync distributor again, and verify again.
        if selectors.bug_is_testable(2722, cfg.pulp_version):
            self.verify_publish_is_skip(cfg, utils.publish_repo(*args).json())
            dirs = set(cli.Client(cfg).run(cmd).stdout.strip().split('\n'))
            self.assertNotIn('content', dirs)
def setUpModule():  # pylint:disable=invalid-name
    """Conditionally skip tests. Create repositories with fixture data."""
    cfg = config.get_config()
    if selectors.bug_is_untestable(1991, cfg.pulp_version):
        raise unittest.SkipTest('https://pulp.plan.io/issues/1991')
    set_up_module()

    # Fetch RPMs.
    _SIGNED_PACKAGES['rpm'] = utils.http_get(RPM_SIGNED_URL)
    _SIGNED_PACKAGES['srpm'] = utils.http_get(SRPM_SIGNED_URL)
    _UNSIGNED_PACKAGES['rpm'] = utils.http_get(RPM_UNSIGNED_URL)
    _UNSIGNED_PACKAGES['srpm'] = utils.http_get(SRPM_UNSIGNED_URL)
    if selectors.bug_is_testable(1806, cfg.pulp_version):
        _SIGNED_PACKAGES['drpm'] = utils.http_get(DRPM_SIGNED_URL)
        _UNSIGNED_PACKAGES['drpm'] = utils.http_get(DRPM_UNSIGNED_URL)

    # Create repos, and upload RPMs to them.
    client = api.Client(cfg, api.json_handler)
    try:
        repo = client.post(REPOSITORY_PATH, gen_repo())
        _REPOS['signed'] = repo
        for type_id, pkg in _SIGNED_PACKAGES.items():
            utils.upload_import_unit(cfg, pkg, {'unit_type_id': type_id}, repo)

        repo = client.post(REPOSITORY_PATH, gen_repo())
        _REPOS['unsigned'] = repo
        for type_id, pkg in _UNSIGNED_PACKAGES.items():
            utils.upload_import_unit(cfg, pkg, {'unit_type_id': type_id}, repo)
    except:  # noqa:E722
        _SIGNED_PACKAGES.clear()
        _UNSIGNED_PACKAGES.clear()
        for _ in range(len(_REPOS)):
            client.delete(_REPOS.popitem()[1]['_href'])
        raise
def _get_pkglist(update):
    """Parse the "pkglist" element in an ``updateinfo.xml`` update.

    :param update: An ``xml.etree`` element corresponding to an "update"
        element in an ``updateinfo.xml`` file.
    :returns: A list of packages, each in the format used by an erratum.
    """
    src_pkglist = update.find('pkglist')
    out_pkglist = [{
        'name': src_pkglist.find('collection').find('name').text,
        'packages': [],
        'short': src_pkglist.find('collection').attrib['short'],
    }]
    for package in src_pkglist.find('collection').findall('package'):
        out_pkglist[0]['packages'].append({
            'arch': package.attrib['arch'],
            'epoch': package.attrib['epoch'],
            'filename': package.find('filename').text,
            'name': package.attrib['name'],
            'release': package.attrib['release'],
            'src': package.attrib['src'],
            'version': package.attrib['version'],
        })
        if selectors.bug_is_testable(2042, config.get_config().version):
            checksum = package.find('sum')
            out_pkglist[0]['packages'][-1]['sum'] = [
                checksum.attrib['type'], checksum.text
            ]
    return out_pkglist
Ejemplo n.º 13
0
    def test_failure(self):
        """Unsuccessfully log in to the server.

        Assert that:

        * The response has an HTTP 401 status code.
        * The response body is valid JSON and has correct keys.
        """
        # By default, `Client` objects munge every response they receive. They
        # act cautiously, and do things like raise an exception if the response
        # has an HTTP 4XX or 5XX status code. We don't want that to happen in
        # this test case. So, we pass the `Client` object a non-default
        # function with which to munge responses. In addition, we override the
        # default authentication handling for just this one API call.
        #
        # The API and CLI clients are interesting and capable classes. Read
        # about them.
        cfg = config.get_config()
        response = (api.Client(cfg, api.echo_handler).post(LOGIN_PATH,
                                                           auth=('', '')))
        with self.subTest(comment='check response status code'):
            self.assertEqual(response.status_code, 401)
        # The `version` attribute should correspond to the version of the Pulp
        # server under test. This block of code says "if bug 1412 is not fixed
        # in Pulp version X, then skip this test."
        if selectors.bug_is_testable(1412, cfg.pulp_version):
            with self.subTest(comment='check response body'):
                self.assertEqual(frozenset(response.json().keys()), ERROR_KEYS)
Ejemplo n.º 14
0
 def test_connection_error(self):
     """Make the dependent function raise a connection error."""
     with mock.patch.object(
         selectors,
         '_get_bug_status',
         side_effect=requests.exceptions.ConnectionError
     ):
         with self.assertWarns(RuntimeWarning):
             self.assertTrue(selectors.bug_is_testable(None))
 def test_testable_status(self):
     """Assert the method correctly handles "testable" bug statuses."""
     ver = Version('0')
     for bug_status in selectors._TESTABLE_BUGS:
         bug = selectors._Bug(bug_status, ver)
         with mock.patch.object(selectors, '_get_bug', return_value=bug):
             with self.subTest(bug_status=bug_status):
                 self.assertTrue(selectors.bug_is_testable(None, ver))
                 self.assertFalse(selectors.bug_is_untestable(None, ver))
Ejemplo n.º 16
0
 def test_untestable_status(self):
     """Assert the method correctly handles "untestable" bug statuses."""
     ver = Version('0')
     for bug_status in selectors._UNTESTABLE_BUGS:
         bug = selectors._Bug(bug_status, ver)
         with mock.patch.object(selectors, '_get_bug', return_value=bug):
             with self.subTest(bug_status=bug_status):
                 self.assertFalse(selectors.bug_is_testable(None, ver))
                 self.assertTrue(selectors.bug_is_untestable(None, ver))
Ejemplo n.º 17
0
 def test_untestable_status(self):
     """Make the dependent function return a "untestable" bug status."""
     with mock.patch.object(
         selectors,
         '_get_bug_status',
         # pylint:disable=protected-access
         return_value=random.sample(selectors._UNTESTABLE_BUGS, 1)[0]
     ):
         with self.subTest():
             self.assertFalse(selectors.bug_is_testable(None))
         with self.subTest():
             self.assertTrue(selectors.bug_is_untestable(None))
Ejemplo n.º 18
0
 def test_pulp_server_fc(self):
     """Test files listed in ``pulp-server.fc``."""
     files_labels = [
         ('/etc/pki/pulp', ':object_r:pulp_cert_t:s0'),
         ('/etc/pulp', ':object_r:httpd_sys_content_t:s0'),
         ('/usr/share/pulp/wsgi', ':object_r:httpd_sys_content_t:s0'),
         ('/var/log/pulp', ':object_r:httpd_sys_rw_content_t:s0'),
     ]
     if selectors.bug_is_testable(2508, config.get_config().pulp_version):
         files_labels.append(
             ('/var/lib/pulp', ':object_r:httpd_sys_rw_content_t:s0')
         )
     for file_, label in files_labels:
         with self.subTest((file_, label)):
             self._do_test(file_, label, True)
Ejemplo n.º 19
0
    def do_test(self, feed, type_ids):
        """Remove units from a repo and make assertions about it.

        Do the following:

        1. Create and sync a repository with the given ``feed``.
        2. For each type ID in ``type_ids``, remove a content unit of that type
           from the repository. See :meth:`do_remove_unit`.
        3. Assert the correct units are still in the repository. The repository
           should have all the units that were originally synced into the
           repository, minus those that have been removed.
        4. Remove a non-existent unit from the repository. Assert that the
           ``last_unit_removed`` timestamp was not updated.
        """
        body = gen_repo()
        body['importer_config']['feed'] = feed
        client = api.Client(self.cfg, api.json_handler)
        repo = client.post(REPOSITORY_PATH, body)
        self.addCleanup(client.delete, repo['_href'])
        repo = client.get(repo['_href'], params={'details': True})
        utils.sync_repo(self.cfg, repo)
        self.initial_units = utils.search_units(self.cfg, repo)

        for type_id in type_ids:
            with self.subTest(type_id=type_id):
                self.do_remove_unit(type_id, repo)

        with self.subTest('remaining units'):
            removed_ids = {_get_unit_id(unit) for unit in self.removed_units}
            remaining_ids = {
                _get_unit_id(unit)
                for unit in utils.search_units(self.cfg, repo)
            }
            self.assertEqual(removed_ids & remaining_ids, set())

        if selectors.bug_is_testable(2630, self.cfg.pulp_version):
            with self.subTest('last removed unit'):
                lur_before = self.get_repo_last_unit_removed(repo)
                time.sleep(1)  # ensure last_unit_removed increments
                # Select an unit and mess it up
                unit = random.choice(self.initial_units).copy()
                unit_id_name, _ = _get_unit_id(unit)
                unit['metadata'][unit_id_name] = utils.uuid4()
                # Remove the non-existent unit
                _remove_unit(self.cfg, repo, unit)
                lur_after = self.get_repo_last_unit_removed(repo)
                self.assertEqual(lur_before, lur_after)
Ejemplo n.º 20
0
    def maybe_disable_selinux(self, cfg, pulp_issue_id):
        """Disable SELinux if appropriate.

        If the given Pulp issue is unresolved, and if SELinux is installed and
        enforcing on the target Pulp system, then disable SELinux and schedule
        it to be re-enabled. (Method ``addCleanup`` is used for the schedule.)

        :param pulp_smash.config.PulpSmashConfig cfg: Information about the
            Pulp deployment being targeted.
        :param pulp_issue_id: The (integer) ID of a `Pulp issue`_. If the
            referenced issue is fixed in the Pulp system under test, this
            method immediately returns.
        :returns: Nothing.

        .. _Pulp issue: https://pulp.plan.io/issues/
        """
        # Abort if the Pulp issue is resolved, if SELinux is not installed or
        # if SELinux is not enforcing.
        #
        # NOTE: Hard-coding the absolute path to a command is a Bad Idea™.
        # However, non-login non-root shells may have short PATH environment
        # variables. For example:
        #
        #     /usr/lib64/qt-3.3/bin:/usr/local/bin:/usr/bin
        #
        # We cannot execute `PATH=${PATH}:/usr/sbin which getenforce` because
        # Plumbum does a good job of preventing shell expansions. See:
        # https://github.com/PulpQE/pulp-smash/issues/89
        if selectors.bug_is_testable(pulp_issue_id, cfg.pulp_version):
            return
        client = cli.Client(cfg, cli.echo_handler)
        cmd = 'test -e /usr/sbin/getenforce'.split()
        if client.run(cmd).returncode != 0:
            return
        client.response_handler = cli.code_handler
        cmd = ['/usr/sbin/getenforce']
        if client.run(cmd).stdout.strip().lower() != 'enforcing':
            return

        # Temporarily disable SELinux.
        sudo = '' if utils.is_root(cfg) else 'sudo '
        cmd = (sudo + 'setenforce 0').split()
        client.run(cmd)
        cmd = (sudo + 'setenforce 1').split()
        self.addCleanup(client.run, cmd)
Ejemplo n.º 21
0
    def test_update_is_correct(self):
        """Assert the uploaded erratum is in ``updateinfo.xml`` and correct.

        Specificially, this method does the following:

        1. Select the "update" element in ``updateinfo.xml`` corresponding to
           the uploaded erratum.
        2. Build our own erratum from the selected "update" element.
        3. Compare the uploaded erratum to the generated erratum.

        .. WARNING:: This test may be erroneous. See
            :func:`parse_updateinfo_update`.
        """
        # Find our erratum in ``updateinfo.xml``.
        updates = [
            update for update in self.updateinfo.findall('update')
            if update.find('id').text == self.erratum['id']
        ]
        self.assertEqual(len(updates), 1)

        # The erratum we uploaded will be different from the erratum that Pulp
        # published. Here, we try to erase the differences between the two, by
        # modifying the uploaded erratum.
        old_erratum = self.erratum.copy()  # dont modify original
        if selectors.bug_is_untestable(2021, self.cfg.version):
            del old_erratum['release']
        if selectors.bug_is_testable(2042, self.cfg.version):
            for package_list in old_erratum['pkglist']:
                for package in package_list['packages']:
                    # ['md5', '…', 'sha256', '…'] → ['sha256': '…']
                    i = package['sum'].index('sha256')
                    package['sum'] = package['sum'][i:i + 2]
        else:
            for package_list in old_erratum['pkglist']:
                for package in package_list['packages']:
                    del package['sum']
        new_erratum = parse_updateinfo_update(updates[0])

        # Parse and verify the erratum. Simply asserting that the original
        # erratum and constructed erratum are equal produces awful failure
        # messages. Iterating like this lets us narrow things down a bit.
        for key, value in old_erratum.items():
            with self.subTest(key=key):
                self.assertIn(key, new_erratum)
                self.assertEqual(value, new_erratum[key])
Ejemplo n.º 22
0
    def maybe_disable_selinux(self, cfg, pulp_issue_id):
        """Disable SELinux if appropriate.

        If the given Pulp issue is unresolved, and if SELinux is installed and
        enforcing on the target Pulp system, then disable SELinux and schedule
        it to be re-enabled. (Method ``addCleanup`` is used for the schedule.)

        :param pulp_smash.config.ServerConfig cfg: Information about the Pulp
            server being targeted.
        :param pulp_issue_id: The (integer) ID of a `Pulp issue`_. If the
            referenced issue is fixed in the Pulp system under test, this
            method immediately returns.
        :returns: Nothing.

        .. _Pulp issue: https://pulp.plan.io/issues/
        """
        # Abort if the Pulp issue is resolved, if SELinux is not installed or
        # if SELinux is not enforcing.
        #
        # NOTE: Hard-coding the absolute path to a command is a Bad Idea™.
        # However, non-login non-root shells may have short PATH environment
        # variables. For example:
        #
        #     /usr/lib64/qt-3.3/bin:/usr/local/bin:/usr/bin
        #
        # We cannot execute `PATH=${PATH}:/usr/sbin which getenforce` because
        # Plumbum does a good job of preventing shell expansions. See:
        # https://github.com/PulpQE/pulp-smash/issues/89
        if selectors.bug_is_testable(pulp_issue_id, cfg.version):
            return
        client = cli.Client(cfg, cli.echo_handler)
        cmd = 'test -e /usr/sbin/getenforce'.split()
        if client.run(cmd).returncode != 0:
            return
        client.response_handler = cli.code_handler
        cmd = ['/usr/sbin/getenforce']
        if client.run(cmd).stdout.strip().lower() != 'enforcing':
            return

        # Temporarily disable SELinux.
        sudo = '' if utils.is_root(cfg) else 'sudo '
        cmd = (sudo + 'setenforce 0').split()
        client.run(cmd)
        cmd = (sudo + 'setenforce 1').split()
        self.addCleanup(client.run, cmd)
    def test_update_is_correct(self):
        """Assert the uploaded erratum is in ``updateinfo.xml`` and correct.

        Specificially, this method does the following:

        1. Select the "update" element in ``updateinfo.xml`` corresponding to
           the uploaded erratum.
        2. Build our own erratum from the selected "update" element.
        3. Compare the uploaded erratum to the generated erratum.

        .. WARNING:: This test may be erroneous. See
            :func:`parse_updateinfo_update`.
        """
        # Find our erratum in ``updateinfo.xml``.
        updates = [
            update for update in self.updateinfo.findall('update')
            if update.find('id').text == self.erratum['id']
        ]
        self.assertEqual(len(updates), 1)

        # The erratum we uploaded will be different from the erratum that Pulp
        # published. Here, we try to erase the differences between the two, by
        # modifying the uploaded erratum.
        old_erratum = self.erratum.copy()  # dont modify original
        if selectors.bug_is_untestable(2021, self.cfg.version):
            del old_erratum['release']
        if selectors.bug_is_testable(2042, self.cfg.version):
            for package_list in old_erratum['pkglist']:
                for package in package_list['packages']:
                    # ['md5', '…', 'sha256', '…'] → ['sha256': '…']
                    i = package['sum'].index('sha256')
                    package['sum'] = package['sum'][i:i + 2]
        else:
            for package_list in old_erratum['pkglist']:
                for package in package_list['packages']:
                    del package['sum']
        new_erratum = parse_updateinfo_update(updates[0])

        # Parse and verify the erratum. Simply asserting that the original
        # erratum and constructed erratum are equal produces awful failure
        # messages. Iterating like this lets us narrow things down a bit.
        for key, value in old_erratum.items():
            with self.subTest(key=key):
                self.assertIn(key, new_erratum)
                self.assertEqual(value, new_erratum[key])
Ejemplo n.º 24
0
 def test_all(self):
     """Create a docker repo with an invalid feed and sync it."""
     repo_id = utils.uuid4()
     self.assertNotIn('Task Failed', repo_create(
         self.cfg,
         feed='https://docker.example.com',
         repo_id=repo_id,
         upstream_name=get_upstream_name(self.cfg),
     ).stdout)
     self.addCleanup(repo_delete, self.cfg, repo_id)
     client = cli.Client(self.cfg, cli.echo_handler)
     proc = client.run((
         'pulp-admin', 'docker', 'repo', 'sync', 'run', '--repo-id', repo_id
     ))
     if selectors.bug_is_testable(427, self.cfg.pulp_version):
         with self.subTest():
             self.assertNotEqual(proc.returncode, 0)
     with self.subTest():
         self.assertNotIn('Task Succeeded', proc.stdout)
     with self.subTest():
         self.assertIn('Task Failed', proc.stdout)
Ejemplo n.º 25
0
def get_auth(cfg=None):
    """Return a random authentication object.

    By default, :class:`pulp_smash.api.Client` uses the same authentication
    method (HTTP BASIC) for every request. While this is a sane default, it
    doesn't let tests exercise other authentication procedures. This function
    returns a random authentication object. To demonstrate how this object can
    be used, here's an example showing how to create a user:

    >>> from pulp_smash.api import Client
    >>> from pulp_smash.config import get_config
    >>> from pulp_smash.tests.pulp3.utils import get_auth
    >>> from pulp_smash.tests.pulp3.constants import USER_PATH
    >>> cfg = config.get_config()
    >>> client = api.Client(cfg, api.json_handler)
    >>> client.request_kwargs['auth'] = get_auth()
    >>> client.post(USER_PATH, {
    >>>     'username': '******',
    >>>     'password': '******',
    >>>     'is_superuser': True
    >>> })

    The returned object can also be used directly with `Requests`_. For more
    information, see the For more information, see the `Requests
    Authentication`_ documentation.

    :param pulp_smash.config.PulpSmashConfig cfg: Information about a Pulp app.
    :returns: A random authentication object.

    .. _Requests Authentication:
        http://docs.python-requests.org/en/master/user/authentication/
    .. _Requests: http://docs.python-requests.org/en/master/
    """
    if not cfg:
        cfg = config.get_config()
    choices = [_get_basic_auth]
    if selectors.bug_is_testable(3248, cfg.pulp_version):
        choices.append(_get_jwt_auth)
    return random.choice(choices)(cfg)
Ejemplo n.º 26
0
def _get_pkglist(update):
    """Parse the "pkglist" element in an ``updateinfo.xml`` update.

    :param update: An ``xml.etree`` element corresponding to an "update"
        element in an ``updateinfo.xml`` file.
    :returns: A list of packages, each in the format used by an erratum.
    """
    src_pkglist = update.find('pkglist')
    out_pkglist = [{
        'name': src_pkglist.find('collection').find('name').text,
        'packages': [],
        'short': src_pkglist.find('collection').attrib['short'],
    }]
    for package in src_pkglist.find('collection').findall('package'):
        out_pkglist[0]['packages'].append({
            'arch':
            package.attrib['arch'],
            'epoch':
            package.attrib['epoch'],
            'filename':
            package.find('filename').text,
            'name':
            package.attrib['name'],
            'release':
            package.attrib['release'],
            'src':
            package.attrib['src'],
            'version':
            package.attrib['version'],
        })
        if selectors.bug_is_testable(2042, config.get_config().version):
            checksum = package.find('sum')
            out_pkglist[0]['packages'][-1]['sum'] = [
                checksum.attrib['type'], checksum.text
            ]
    return out_pkglist
Ejemplo n.º 27
0
    def verify_repo_search(self, repo):
        """Search for units in the given ``repo``.

        Verify that only one content unit is in ``repo``, and that several of
        its metadata attributes are correct. This test targets `Pulp #2365
        <https://pulp.plan.io/issues/2365>`_ and `Pulp #2754
        <https://pulp.plan.io/issues/2754>`_
        """
        units = utils.search_units(self.cfg, repo)
        self.assertEqual(len(units), 1)

        # filename and derived attributes
        with self.subTest():
            self.assertEqual(units[0]['metadata']['filename'], RPM)
        with self.subTest():
            self.assertEqual(units[0]['metadata']['epoch'], RPM_DATA['epoch'])
        with self.subTest():
            self.assertEqual(units[0]['metadata']['name'], RPM_DATA['name'])
        with self.subTest():
            self.assertEqual(units[0]['metadata']['version'],
                             RPM_DATA['version'])
        with self.subTest():
            self.assertEqual(units[0]['metadata']['release'],
                             RPM_DATA['release'])

        # other attributes
        with self.subTest():
            self.assertEqual(units[0]['metadata']['license'],
                             RPM_DATA['metadata']['license'])
        with self.subTest():
            self.assertEqual(
                units[0]['metadata']['description'],
                RPM_DATA['metadata']['description'],
            )
        with self.subTest():
            self.assertEqual(
                units[0]['metadata']['files'],
                RPM_DATA['metadata']['files'],
            )

        if selectors.bug_is_testable(2754, self.cfg.pulp_version):
            # Test that additional fields are available.
            # Affected by Pulp issue #2754

            with self.subTest():
                self.assertEqual(
                    units[0]['metadata']['group'],
                    RPM_DATA['metadata']['group'],
                )
            with self.subTest():
                self.assertEqual(
                    units[0]['metadata']['summary'],
                    RPM_DATA['metadata']['summary'],
                )
            with self.subTest():
                self.assertEqual(
                    units[0]['metadata']['size'],
                    RPM_DATA['metadata']['size']['package'],
                )
            with self.subTest():
                self.assertEqual(
                    units[0]['metadata']['sourcerpm'],
                    RPM_DATA['metadata']['sourcerpm'],
                )