id
int64 0
458k
| file_name
stringlengths 4
119
| file_path
stringlengths 14
227
| content
stringlengths 24
9.96M
| size
int64 24
9.96M
| language
stringclasses 1
value | extension
stringclasses 14
values | total_lines
int64 1
219k
| avg_line_length
float64 2.52
4.63M
| max_line_length
int64 5
9.91M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
101
| repo_stars
int64 100
139k
| repo_forks
int64 0
26.4k
| repo_open_issues
int64 0
2.27k
| repo_license
stringclasses 12
values | repo_extraction_date
stringclasses 433
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
15,800
|
test_sack.py
|
rpm-software-management_dnf/tests/test_sack.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf.exceptions
import dnf.repo
import dnf.sack
import tests.support
from tests.support import mock
class SackTest(tests.support.DnfBaseTestCase):
REPOS = []
def test_excludepkgs(self):
self.base.conf.excludepkgs = ['pepper']
self.base._setup_excludes_includes()
peppers = self.base.sack.query().filter(name='pepper').run()
self.assertLength(peppers, 0)
def test_exclude(self):
self.base.conf.exclude = ['pepper']
self.base._setup_excludes_includes()
peppers = self.base.sack.query().filter(name='pepper').run()
self.assertLength(peppers, 0)
def test_disable_excludes(self):
self.base.conf.disable_excludes = ['all']
self.base.conf.excludepkgs = ['pepper']
self.base._setup_excludes_includes()
peppers = self.base.sack.query().filter(name='pepper').run()
self.assertLength(peppers, 1)
def test_excludepkgs_glob(self):
# override base with custom repos
self.base = tests.support.MockBase('main')
self.base.repos['main'].excludepkgs = ['pepp*']
self.base._setup_excludes_includes()
peppers = self.base.sack.query().filter(name='pepper', reponame='main')
self.assertLength(peppers, 0)
def test_excludepkgs_includepkgs(self):
self.base.conf.excludepkgs = ['*.i?86']
self.base.conf.includepkgs = ['lib*']
self.base._setup_excludes_includes()
peppers = self.base.sack.query().run()
self.assertLength(peppers, 1)
self.assertEqual(str(peppers[0]), "librita-1-1.x86_64")
@mock.patch('dnf.sack._build_sack', lambda x: mock.Mock())
@mock.patch('dnf.goal.Goal', lambda x: mock.Mock())
def test_fill_sack(self):
def raiser():
raise dnf.exceptions.RepoError()
r = tests.support.MockRepo('bag', self.base.conf)
r.enable()
self.base._repos.add(r)
r.load = mock.Mock(side_effect=raiser)
r.skip_if_unavailable = False
self.assertRaises(dnf.exceptions.RepoError,
self.base.fill_sack, load_system_repo=False)
self.assertTrue(r.enabled)
self.assertTrue(r._check_config_file_age)
| 3,286
|
Python
|
.py
| 70
| 40.8
| 79
| 0.690194
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,801
|
test_subject.py
|
rpm-software-management_dnf/tests/test_subject.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2015-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf.exceptions
import tests.support
class SubjectTest(tests.support.DnfBaseTestCase):
REPOS = ['main', 'third_party']
def setUp(self):
super(SubjectTest, self).setUp()
pkg = self.base.sack.query().filter(name='lotus', arch='x86_64')[0]
self.base.sack.add_excludes([pkg])
def test_best_selectors_no_glob(self):
subj = dnf.subject.Subject('pepper')
sltrs = subj._get_best_selectors(self.base)
self.assertEqual(len(sltrs), 1)
def test_best_selectors_glob(self):
subj = dnf.subject.Subject('l*')
sltrs = subj._get_best_selectors(self.base)
q = self.base.sack.query().filter(name__glob='l*')
self.assertEqual(len(sltrs), len(set(map(lambda p: p.name, q))))
def test_best_selectors_arch(self):
subj = dnf.subject.Subject('l*.x86_64')
sltrs = subj._get_best_selectors(self.base)
q = self.base.sack.query().filter(name__glob='l*', arch__eq='x86_64')
self.assertEqual(len(sltrs), len(set(map(lambda p: p.name, q))))
for sltr in sltrs:
for pkg in sltr.matches():
self.assertEqual(pkg.arch, 'x86_64')
def test_best_selectors_ver(self):
subj = dnf.subject.Subject('*-1-1')
sltrs = subj._get_best_selectors(self.base)
for sltr in sltrs:
for pkg in sltr.matches():
self.assertEqual(pkg.evr, '1-1')
| 2,489
|
Python
|
.py
| 50
| 44.06
| 77
| 0.688092
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,802
|
test_cli.py
|
rpm-software-management_dnf/tests/test_cli.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import argparse
import os
import re
from argparse import Namespace
import dnf.cli.cli
import dnf.conf
import dnf.goal
import dnf.repo
import dnf.repodict
import tests.support
from tests.support import mock
VERSIONS_OUTPUT = """\
Installed: pepper-0:20-0.x86_64 at Thu Jan 1 00:00:00 1970
Built : at Thu Jan 1 00:00:00 1970
Installed: tour-0:5-0.noarch at Thu Jan 1 00:00:00 1970
Built : at Thu Jan 1 00:00:00 1970
"""
class VersionStringTest(tests.support.DnfBaseTestCase):
REPOS = []
def test_print_versions(self):
output = tests.support.MockOutput()
with mock.patch('sys.stdout') as stdout,\
mock.patch('dnf.sack._rpmdb_sack', return_value=self.base.sack):
dnf.cli.cli.print_versions(['pepper', 'tour'], self.base, output)
written = ''.join([mc[1][0] for mc in stdout.method_calls
if mc[0] == 'write'])
self.assertEqual(written, VERSIONS_OUTPUT)
@mock.patch('dnf.cli.cli.logger', new_callable=tests.support.mock_logger)
class BaseCliTest(tests.support.ResultTestCase):
REPOS = ["main", "updates"]
BASE_CLI = True
INIT_SACK = True
def setUp(self):
super(BaseCliTest, self).setUp()
self.base.output.term = tests.support.MockTerminal()
self.base.downgrade_to = mock.Mock(wraps=self.base.downgrade_to)
def test_downgradePkgs(self, logger):
self.base.downgradePkgs(('tour',))
self.assertEqual(self.base.downgrade_to.mock_calls, [mock.call('tour', strict=False)])
self.assertEqual(logger.mock_calls, [])
def test_downgradePkgs_notfound(self, logger):
with self.assertRaises(dnf.exceptions.Error) as ctx:
self.base.downgradePkgs(('non-existent',))
self.assertEqual(str(ctx.exception), 'No packages marked for downgrade.')
self.assertEqual(self.base.downgrade_to.mock_calls,
[mock.call('non-existent', strict=False)])
self.assertEqual(logger.mock_calls,
[mock.call.info('No package %s available.',
'non-existent')])
@mock.patch('dnf.cli.cli._', dnf.pycomp.NullTranslations().ugettext)
def test_downgradePkgs_notinstalled(self, logger):
tests.support.ObjectMatcher(dnf.package.Package, {'name': 'lotus'})
with self.assertRaises(dnf.exceptions.Error) as ctx:
self.base.downgradePkgs(('lotus',))
self.assertEqual(str(ctx.exception), 'No packages marked for downgrade.')
self.assertEqual(self.base.downgrade_to.mock_calls, [mock.call('lotus', strict=False)])
@mock.patch('dnf.cli.cli.Cli._read_conf_file')
class CliTest(tests.support.DnfBaseTestCase):
REPOS = ["main"]
CLI = "init"
def setUp(self):
super(CliTest, self).setUp()
self.base.output = tests.support.MockOutput()
def test_knows_upgrade(self, _):
upgrade = self.cli.cli_commands['upgrade']
update = self.cli.cli_commands['update']
self.assertIs(upgrade, update)
def test_simple(self, _):
self.assertFalse(self.base.conf.assumeyes)
self.cli.configure(['update', '-y'])
self.assertTrue(self.base.conf.assumeyes)
def test_glob_options_cmds(self, _):
params = [
['install', '-y', 'pkg1', 'pkg2'],
['install', 'pkg1', '-y', 'pkg2'],
['install', 'pkg1', 'pkg2', '-y'],
['-y', 'install', 'pkg1', 'pkg2']
]
for param in params:
self.cli.configure(args=param)
self.assertTrue(self.base.conf.assumeyes)
self.assertEqual(self.cli.command.opts.command, "install")
self.assertEqual(self.cli.command.opts.pkg_specs, ["pkg1", "pkg2"])
def test_configure_repos(self, _):
opts = Namespace()
opts.repo = []
opts.repos_ed = [('*', 'disable'), ('comb', 'enable')]
opts.cacheonly = True
opts.nogpgcheck = True
opts.repofrompath = {}
self.base._repos = dnf.repodict.RepoDict()
self.base._repos.add(tests.support.MockRepo('one', self.base.conf))
self.base._repos.add(tests.support.MockRepo('two', self.base.conf))
self.base._repos.add(tests.support.MockRepo('comb', self.base.conf))
self.cli._configure_repos(opts)
self.assertFalse(self.base.repos['one'].enabled)
self.assertFalse(self.base.repos['two'].enabled)
self.assertTrue(self.base.repos['comb'].enabled)
self.assertFalse(self.base.repos["comb"].gpgcheck)
self.assertFalse(self.base.repos["comb"].repo_gpgcheck)
def test_configure_repos_expired(self, _):
"""Ensure that --cacheonly beats the expired status."""
opts = Namespace()
opts.repo = []
opts.repos_ed = []
opts.cacheonly = True
opts.repofrompath = {}
pers = self.base._repo_persistor
pers.get_expired_repos = mock.Mock(return_value=('one',))
self.base._repos = dnf.repodict.RepoDict()
self.base._repos.add(tests.support.MockRepo('one', self.base.conf))
self.cli._configure_repos(opts)
# _process_demands() should respect --cacheonly in spite of modified demands
self.cli.demands.fresh_metadata = False
self.cli.demands.cacheonly = True
self.cli._process_demands()
self.assertEqual(self.base.repos['one']._repo.getSyncStrategy(),
dnf.repo.SYNC_ONLY_CACHE)
@mock.patch('dnf.logging.Logging._setup', new=mock.MagicMock)
class ConfigureTest(tests.support.DnfBaseTestCase):
REPOS = ["main"]
# CLI = "init"
def setUp(self):
super(ConfigureTest, self).setUp()
self.base._conf = dnf.conf.Conf()
self.base.output = tests.support.MockOutput()
self.base._plugins = mock.Mock()
self.cli = dnf.cli.cli.Cli(self.base)
self.cli.command = mock.Mock()
self.conffile = os.path.join(tests.support.dnf_toplevel(), "etc/dnf/dnf.conf")
@mock.patch('dnf.util.am_i_root', lambda: False)
def test_configure_user(self):
""" Test Cli.configure as user."""
# call setUp() once again *after* am_i_root() is mocked so the cachedir is set as expected
self.setUp()
self.base._conf.installroot = self._installroot
with mock.patch('dnf.rpm.detect_releasever', return_value=69):
self.cli.configure(['update', '-c', self.conffile])
reg = re.compile('^' + self._installroot + '/var/tmp/dnf-[.a-zA-Z0-9_-]+$')
self.assertIsNotNone(reg.match(self.base.conf.cachedir))
parser = argparse.ArgumentParser()
expected = "%s update -c %s " % (parser.prog, self.conffile)
self.assertEqual(self.cli.cmdstring, expected)
@mock.patch('dnf.util.am_i_root', lambda: True)
def test_configure_root(self):
""" Test Cli.configure as root."""
self.base._conf = dnf.conf.Conf()
with mock.patch('dnf.rpm.detect_releasever', return_value=69):
self.cli.configure(['update', '--nogpgcheck', '-c', self.conffile])
reg = re.compile('^/var/cache/dnf$')
self.assertIsNotNone(reg.match(self.base.conf.system_cachedir))
parser = argparse.ArgumentParser()
expected = "%s update --nogpgcheck -c %s " % (parser.prog, self.conffile)
self.assertEqual(self.cli.cmdstring, expected)
def test_configure_verbose(self):
self.base._conf.installroot = self._installroot
with mock.patch('dnf.rpm.detect_releasever', return_value=69):
self.cli.configure(['-v', 'update', '-c', self.conffile])
parser = argparse.ArgumentParser()
expected = "%s -v update -c %s " % (parser.prog, self.conffile)
self.assertEqual(self.cli.cmdstring, expected)
self.assertEqual(self.base.conf.debuglevel, 6)
self.assertEqual(self.base.conf.errorlevel, 6)
@mock.patch('dnf.cli.cli.Cli._parse_commands', new=mock.MagicMock)
@mock.patch('os.path.exists', return_value=True)
def test_conf_exists_in_installroot(self, ospathexists):
with mock.patch('logging.Logger.warning'), \
mock.patch('dnf.rpm.detect_releasever', return_value=69):
self.cli.configure(['--installroot', '/roots/dnf', 'update'])
self.assertEqual(self.base.conf.config_file_path, '/roots/dnf/etc/dnf/dnf.conf')
self.assertEqual(self.base.conf.installroot, '/roots/dnf')
@mock.patch('dnf.cli.cli.Cli._parse_commands', new=mock.MagicMock)
@mock.patch('os.path.exists', return_value=False)
def test_conf_notexists_in_installroot(self, ospathexists):
with mock.patch('dnf.rpm.detect_releasever', return_value=69):
self.cli.configure(['--installroot', '/roots/dnf', 'update'])
self.assertEqual(self.base.conf.config_file_path, '/etc/dnf/dnf.conf')
self.assertEqual(self.base.conf.installroot, '/roots/dnf')
@mock.patch('dnf.cli.cli.Cli._parse_commands', new=mock.MagicMock)
def test_installroot_with_etc(self):
"""Test that conffile is detected in a new installroot."""
self.base.extcmds = []
tlv = tests.support.dnf_toplevel()
self.cli.configure(['--installroot', tlv, 'update'])
self.assertEqual(self.base.conf.config_file_path, '%s/etc/dnf/dnf.conf' % tlv)
def test_installroot_configurable(self):
"""Test that conffile is detected in a new installroot."""
conf = os.path.join(tests.support.dnf_toplevel(), "tests/etc/installroot.conf")
self.cli.configure(['-c', conf, '--nogpgcheck', '--releasever', '17', 'update'])
self.assertEqual(self.base.conf.installroot, '/roots/dnf')
| 10,774
|
Python
|
.py
| 209
| 43.751196
| 98
| 0.657572
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,803
|
test_install.py
|
rpm-software-management_dnf/tests/test_install.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import itertools
import logging
import dnf.exceptions
import tests.support
class CommonTest(tests.support.ResultTestCase):
"""Tests common to any 'multilib_policy' and 'best'.
The test fixture consists of a dnf.Base instance that:
- contains a package "lotus-3-17.x86_64" (The package can be installed.)
- contains a package "lotus-3-17.i686" (The package can be installed.)
- contains a package "trampoline-2.1-1.noarch" that contains
"/all/be/there", provides "splendid > 2.0" and "php(a/b)" (The package
can be installed.)
- contains a package "mrkite-2-0.x86_64" (The package can be installed
together with the package "trampoline".)
- contains a package "mrkite-k-h-1-1.x86_64" (The package can be
installed.)
- contains a package "pepper-20-0.src"
- contains a package "pepper-20-2.x86_64" (The package cannot be
installed.)
- contains a package "librita-1-1.x86_64" (The package is already
installed.)
- contains a package "hole-1-2.x86_64" (The package can be installed as an
upgrade.)
"""
REPOS = ['main', 'third_party', 'broken_deps']
def test_install_arch_glob(self):
"""Test that the pkg specification can contain an architecture glob."""
self.base.install("lotus.*6*")
installed = self.installed_removed(self.base)[0]
self.assertCountEqual(map(str, installed),
['lotus-3-17.i686',
'lotus-3-17.x86_64'])
def test_install_filename_glob(self):
"""Test that the pkg to be installed can be specified by fname glob."""
self.base.install("*/there")
(installed, _) = self.installed_removed(self.base)
self.assertCountEqual(map(str, installed),
('trampoline-2.1-1.noarch',))
self.base.install("/all/*/there")
(installed, _) = self.installed_removed(self.base)
self.assertCountEqual(map(str, installed),
('trampoline-2.1-1.noarch',))
def test_install_name(self):
"""Test that the package to be installed can be specified by name."""
self.base.install("mrkite")
available = self.base.sack.query().available()
expected = available.filter(name=["mrkite", "trampoline"]).run()
# ensure sanity of the test (otherwise it would pass no matter what):
self.assertEqual(len(expected), 2)
new_set = self.base.sack.query().installed() + expected
self.assertResult(self.base, new_set)
def test_install_name_glob(self):
"""Test that the pkg to be installed can be specified by name glob."""
self.base.install("mrkite*")
installed = self.installed_removed(self.base)[0]
self.assertCountEqual(map(str, installed),
['mrkite-2-0.x86_64',
'mrkite-k-h-1-1.x86_64',
'trampoline-2.1-1.noarch'])
def test_install_name_glob_exclude(self):
"""Test that glob excludes play well with glob installs."""
subj_ex = dnf.subject.Subject('*-1')
pkgs_ex = subj_ex.get_best_query(self.base.sack)
self.base.sack.add_excludes(pkgs_ex)
self.base.install('mrkite*')
(installed, _) = self.installed_removed(self.base)
self.assertCountEqual(map(str, installed),
['mrkite-2-0.x86_64',
'trampoline-2.1-1.noarch'])
def test_install_nevra(self):
"""Test that the package to be installed can be specified by NEVRA."""
self.base.install("lotus-3-17.i686")
lotus, = dnf.subject.Subject('lotus-3-17.i686').get_best_query(self.base.sack)
new_set = self.base.sack.query().installed() + [lotus]
self.assertResult(self.base, new_set)
def test_install_provide_slash(self):
self.base.install("php(a/b)")
(installed, _) = self.installed_removed(self.base)
self.assertCountEqual(map(str, installed),
('trampoline-2.1-1.noarch',))
def test_install_provide_version(self):
"""Test that the pkg to be installed can be spec. by provide ver."""
self.base.install('splendid > 2.0')
self.assertGreater(self.base._goal.req_length(), 0)
trampoline = self.base.sack.query().available().filter(
name="trampoline")
new_set = self.base.sack.query().installed() + trampoline.run()
self.assertResult(self.base, new_set)
def test_package_install_conflict(self):
"""Test that a conflicting package cannot be installed."""
p = self.base.sack.query().available().filter(
nevra='pepper-20-2.x86_64')[0]
self.assertEqual(1, self.base.package_install(p))
with self.assertRaises(dnf.exceptions.DepsolveError):
self.base.resolve()
def test_package_install_installed(self):
"""Test that nothing changes if an installed package matches."""
p = self.base.sack.query().available()._nevra("librita-1-1.x86_64")[0]
with tests.support.mock.patch('logging.Logger.warning'):
self.base.package_install(p)
self.base.resolve()
self.assertEmpty(self.base._goal.list_reinstalls())
self.base.history.close()
self.base.package_reinstall(p)
self.base.resolve()
self.assertLength(self.base._goal.list_reinstalls(), 1)
def test_package_install_upgrade(self):
"""Test that the pkg to be installed can be an upgrade."""
p = self.base.sack.query().available().filter(
nevra='hole-1-2.x86_64')[0]
self.assertEqual(1, self.base.package_install(p))
installed, removed = self.installed_removed(self.base)
self.assertIn(p, installed)
self.assertGreaterEqual(
removed,
set(self.base.sack.query().installed().filter(name='hole')))
def test_pkg_install_installable(self):
"""Test that the package to be installed can be a package instance."""
p = self.base.sack.query().available().filter(
nevra='lotus-3-17.x86_64')[0]
self.assertEqual(1, self.base.package_install(p))
self.base.resolve()
self.assertEqual(1, len(self.base._goal.list_installs()))
def test_pkg_install_installonly(self):
"""Test that installonly packages are installed, not upgraded."""
self.base.conf.installonlypkgs += ['hole']
p = self.base.sack.query().available().filter(
nevra='hole-1-2.x86_64')[0]
self.assertEqual(1, self.base.package_install(p))
installed, removed = self.installed_removed(self.base)
self.assertIn(p, installed)
self.assertFalse(
set(removed) &
set(self.base.sack.query().installed().filter(name='hole')))
class MultilibAllTest(tests.support.ResultTestCase):
"""Tests for multilib_policy='all'.
The test fixture consists of a dnf.Base instance that:
- has conf.multilib_policy == "all"
- has conf.best == False
- contains a package "pepper-20-2" (The package cannot be installed.)
- contains a package "lotus-3-16.x86_64" that contains "/usr/lib*/liblot*"
in a "main" repository (The package can be installed.)
- contains a package "lotus-3-16.i686" that contains "/usr/lib*/liblot*" in
the "main" repository (The package can be installed.)
- contains a package "librita-1-1.x86_64" (The package is already
installed.)
- contains a package "hole-1-2.x86_64" (The package can be installed as an
upgrade.)
- contains a package "pepper-20-0.src"
- contains a package "pepper-20-0.x86_64" (The package is already
installed.)
- contains nothing that matches "not-available"
- contains a package that provides "henry(the_horse)" (The package can be
installed.)
- contains a package "lotus-3-17.x86_64" not in a "main" repository (The
package can be installed.)
- contains a package "lotus-3-17.i686" not in the "main" repository (The
package can be installed.)
"""
REPOS = ['main', 'third_party', 'broken_deps']
def setUp(self):
super(MultilibAllTest, self).setUp()
self.base.conf.multilib_policy = "all"
assert self.base.conf.best is False
def test_install_conflict(self):
"""Test that the exception is raised if the package conflicts."""
self.base.install('pepper-20-2')
with self.assertRaises(dnf.exceptions.DepsolveError):
self.base.resolve()
def test_install_filename(self):
"""Test that the pkg to be installed can be specified by filename."""
self.base.install("/usr/lib*/liblot*")
inst, _ = self.installed_removed(self.base)
self.assertCountEqual(
map(str, inst), ['lotus-3-16.x86_64', 'lotus-3-16.i686'])
def test_install_installed(self):
"""Test that nothing changes if an installed package matches."""
stdout = dnf.pycomp.StringIO()
with tests.support.wiretap_logs('dnf', logging.INFO, stdout):
self.base.install('librita')
self.assertEqual(self.base._goal.req_length(), 0)
self.assertIn(
'Package librita-1-1.x86_64 is already installed.',
stdout.getvalue())
def test_install_installonly(self):
"""Test that installonly packages are installed, not upgraded."""
self.base.conf.installonlypkgs += ['hole']
self.base.install('hole-1-2')
installed, removed = self.installed_removed(self.base)
self.assertGreaterEqual(
installed,
set(self.base.sack.query().available()._nevra('hole-1-2.x86_64')))
self.assertEmpty(removed)
def test_install_multilib(self):
"""Test that pkgs for all architectures are installed if available."""
cnt = self.base.install("lotus")
self.assertEqual(cnt, 2)
installed = self.installed_removed(self.base)[0]
self.assertLessEqual(
set(installed),
set(self.base.sack.query().available().filter(name='lotus')))
def test_install_name_choice(self):
"""Test that the matching pkg that can be installed is installed."""
# Don't install the SRPM.
self.base.sack.add_excludes(
dnf.subject.Subject('pepper.src').get_best_query(self.base.sack))
stdout = dnf.pycomp.StringIO()
with tests.support.wiretap_logs('dnf', logging.INFO, stdout):
self.base.install('pepper')
self.assertEqual(self.base._goal.req_length(), 0)
self.assertIn(
'Package pepper-20-0.x86_64 is already installed.',
stdout.getvalue())
def test_install_nonexistent(self):
"""Test that the exception is raised if no package matches."""
with self.assertRaises(dnf.exceptions.MarkingError) as context:
self.base.install('not-available')
self.assertEqual(context.exception.pkg_spec, 'not-available')
installed_pkgs = self.base.sack.query().installed().run()
self.assertResult(self.base, installed_pkgs)
def test_install_provide(self):
"""Test that the pkg to be installed can be specified by provide."""
self.base.install("henry(the_horse)")
self.assertGreater(self.base._goal.req_length(), 0)
def test_install_reponame(self):
"""Test whether packages are filtered by the reponame."""
result = itertools.chain(
self.base.sack.query().installed(),
dnf.subject.Subject('lotus-3-16').get_best_query(self.base.sack))
self.base.install('lotus', reponame='main')
self.assertResult(self.base, result)
assert dnf.subject.Subject('lotus-3-17').get_best_query(self.base.sack), \
('the base must contain packages a package in another repo '
'which matches the pattern but is preferred, otherwise the '
'test makes no sense')
def test_install_upgrade(self):
"""Test that the pkg to be installed can be an upgrade."""
self.base.install('hole-1-2')
installed, removed = self.installed_removed(self.base)
self.assertGreaterEqual(
installed,
set(self.base.sack.query().available()._nevra('hole-1-2.x86_64')))
self.assertGreaterEqual(
removed,
set(self.base.sack.query().installed().filter(name='hole')))
class MultilibBestTest(tests.support.ResultTestCase):
"""Tests for multilib_policy='best'.
The test fixture consists of a dnf.Base instance that:
- has conf.multilib_policy == "best"
- has conf.best == False
- contains a package "pepper-20-2" (The package cannot be installed.)
- contains a package "lotus-3-16.x86_64" that contains "/usr/lib*/liblot*"
in a "main" repository (The package can be installed.)
- contains a package "lotus-3-16.i686" that contains "/usr/lib*/liblot*"
in the "main" repository (The package can be installed.)
- contains nothing that matches "/not/exist/"
- contains a package "librita-1-1.x86_64" (The package is already
installed.)
- contains a package "hole-1-2.x86_64" (The package can be installed as an
upgrade.)
- contains a package "lotus-3-17.x86_64" not in the "main" repository (The
package can be installed.)
- contains a package "pepper-20-0.src"
- contains a package "pepper-20-0.x86_64" (The package is already
installed.)
- contains nothing that matches "not-available"
- contains a package "trampoline" that provides "henry(the_horse)" (The
package can be installed.)
- contains a package "lotus-3-17.i686" not in the "main" repository (The
package can be installed.)
- contains a package "hole-1-1.x86_64" (The package is already installed
and is not available.)
"""
REPOS = ['main', 'third_party', 'broken_deps']
def setUp(self):
super(MultilibBestTest, self).setUp()
self.installed = self.base.sack.query().installed().run()
self.assertEqual(self.base.conf.multilib_policy, "best")
assert self.base.conf.best is False
def test_install_conflict(self):
"""Test that the exception is raised if the package conflicts."""
self.base.install('pepper-20-2')
with self.assertRaises(dnf.exceptions.DepsolveError):
self.base.resolve()
def test_install_filename(self):
"""Test that the pkg to be installed can be specified by filename."""
self.base.install("/usr/lib*/liblot*")
inst, _ = self.installed_removed(self.base)
self.assertCountEqual(map(str, inst), ['lotus-3-16.x86_64'])
self.assertRaises(dnf.exceptions.MarkingError,
self.base.install, "/not/exist/")
def test_install_installed(self):
"""Test that nothing changes if an installed package matches."""
stdout = dnf.pycomp.StringIO()
with tests.support.wiretap_logs('dnf', logging.INFO, stdout):
self.base.install('librita')
installed, removed = self.installed_removed(self.base)
self.assertEmpty(installed)
self.assertEmpty(removed)
self.assertIn(
'Package librita-1-1.x86_64 is already installed.',
stdout.getvalue())
def test_install_installonly(self):
"""Test that installonly packages are installed, not upgraded."""
self.base.conf.installonlypkgs += ['hole']
self.base.install('hole-1-2')
installed, removed = self.installed_removed(self.base)
self.assertGreaterEqual(
installed,
set(self.base.sack.query().available()._nevra('hole-1-2.x86_64')))
self.assertEmpty(removed)
def test_install_multilib(self):
"""Test that a pkg for only one architecture are installed."""
cnt = self.base.install("lotus")
self.assertEqual(cnt, 1)
new_package, = dnf.subject.Subject('lotus-3-17.x86_64').get_best_query(self.base.sack)
new_set = self.installed + [new_package]
self.assertResult(self.base, new_set)
def test_install_name_choice(self):
"""Test that the matching pkg that can be installed is installed."""
# Don't install the SRPM.
self.base.sack.add_excludes(
dnf.subject.Subject('pepper.src').get_best_query(self.base.sack))
stdout = dnf.pycomp.StringIO()
with tests.support.wiretap_logs('dnf', logging.INFO, stdout):
self.base.install('pepper')
installed, removed = self.installed_removed(self.base)
self.assertEmpty(installed | removed)
self.assertIn(
'Package pepper-20-0.x86_64 is already installed.',
stdout.getvalue())
def test_install_nonexistent(self):
"""Test that the exception is raised if no package matches."""
with self.assertRaises(dnf.exceptions.MarkingError) as context:
self.base.install('not-available')
self.assertEqual(context.exception.pkg_spec, 'not-available')
installed_pkgs = self.base.sack.query().installed().run()
self.assertResult(self.base, installed_pkgs)
def test_install_provide(self):
"""Test that the pkg to be installed can be specified by provide."""
self.base.install("henry(the_horse)")
self.assertGreater(self.base._goal.req_length(), 0)
trampoline = self.base.sack.query().available().filter(
name="trampoline")
new_set = self.installed + trampoline.run()
self.assertResult(self.base, new_set)
def test_install_reponame(self):
"""Test whether packages are filtered by the reponame."""
result = itertools.chain(
self.base.sack.query().installed(),
dnf.subject.Subject('lotus-3-16.x86_64')
.get_best_query(self.base.sack))
self.base.install('lotus', reponame='main')
self.assertResult(self.base, result)
assert dnf.subject.Subject('lotus-3-17.x86_64').get_best_query(self.base.sack), \
('the base must contain packages a package in another repo '
'which matches the pattern but is preferred, otherwise the '
'test makes no sense')
def test_install_unavailable(self):
"""Test that nothing changes if an unavailable package matches."""
stdout = dnf.pycomp.StringIO()
with tests.support.wiretap_logs('dnf', logging.INFO, stdout):
cnt = self.base.install('hole')
self.assertEqual(cnt, 1)
installed_pkgs = self.base.sack.query().installed().run()
self.assertResult(self.base, installed_pkgs)
self.assertIn(
'Package hole-1-1.x86_64 is already installed.',
stdout.getvalue())
def test_install_upgrade(self):
"""Test that the pkg to be installed can be an upgrade."""
self.base.install('hole-1-2')
installed, removed = self.installed_removed(self.base)
self.assertGreaterEqual(
installed,
set(self.base.sack.query().available()._nevra('hole-1-2.x86_64')))
self.assertGreaterEqual(
removed,
set(self.base.sack.query().installed().filter(name='hole')))
class BestTrueTest(tests.support.ResultTestCase):
"""Tests for best=True.
The test fixture consists of a dnf.Base instance that:
- has conf.best == True
- contains a package "pepper-20-2" (The package cannot be installed.)
"""
REPOS = ['broken_deps']
def setUp(self):
super(BestTrueTest, self).setUp()
self.base.conf.best = True
def test_install_name_choice(self):
"""Test that the latest version of the matching pkg is installed."""
with tests.support.mock.patch('logging.Logger.warning'):
self.base.install('pepper')
with self.assertRaises(dnf.exceptions.DepsolveError):
self.base.resolve()
| 21,134
|
Python
|
.py
| 414
| 42.200483
| 94
| 0.649271
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,804
|
test_history_undo.py
|
rpm-software-management_dnf/tests/test_history_undo.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2013-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
"""Tests of the history undo command."""
from __future__ import absolute_import
from __future__ import unicode_literals
import libdnf.transaction
from dnf.exceptions import PackagesNotAvailableError, PackagesNotInstalledError
#from dnf.history import NEVRAOperations
#from dnf.transaction import ERASE, DOWNGRADE, INSTALL, REINSTALL, UPGRADE
#from dnf.transaction import TransactionItem
import tests.support
'''
class BaseTest(tests.support.DnfBaseTestCase):
"""Unit tests of dnf.Base."""
REPOS = ['main', 'updates']
def assertEqualTransactionItems(self, one, two):
self.assertEqual(one.op_type, two.op_type)
self.assertEqual(str(one.installed), str(two.installed))
self.assertEqual(str(one.erased), str(two.erased))
self.assertEqual([str(i) for i in one.obsoleted], [str(i) for i in two.obsoleted])
self.assertEqual(one.reason, two.reason)
def test_history_undo_operations_downgrade(self):
"""Test history_undo_operations with a downgrade."""
operations = NEVRAOperations()
operations.add(
'Downgrade',
'pepper-20-0.x86_64',
'pepper-20-1.x86_64',
('lotus-3-16.x86_64',)
)
with self.base:
self.base._history_undo_operations(operations, 0)
transaction_it = iter(self.base.transaction)
actual = next(transaction_it)
expected = TransactionItem(
UPGRADE,
installed='pepper-20-1.x86_64',
erased='pepper-20-0.x86_64'
)
self.assertEqualTransactionItems(actual, expected)
actual = next(transaction_it)
expected = TransactionItem(
INSTALL,
installed='lotus-3-16.x86_64',
reason=libdnf.transaction.TransactionItemReason_USER
)
self.assertEqualTransactionItems(actual, expected)
self.assertRaises(StopIteration, next, transaction_it)
def test_history_undo_operations_downgrade_notavailable(self):
"""Test history_undo_operations with an unavailable downgrade."""
operations = NEVRAOperations()
operations.add('Downgrade', 'pepper-20-0.x86_64', 'pepper-20-2.x86_64')
with self.base, self.assertRaises(PackagesNotAvailableError) as context:
self.base._history_undo_operations(operations, 0)
self.assertEqual(context.exception.pkg_spec, 'pepper-20-2.x86_64')
def test_history_undo_operations_downgrade_notinstalled(self):
"""Test history_undo_operations with a not installed downgrade."""
operations = NEVRAOperations()
operations.add('Downgrade', 'lotus-3-0.x86_64', 'lotus-3-16.x86_64')
with self.base, self.assertRaises(PackagesNotInstalledError) as context:
self.base._history_undo_operations(operations, 0)
self.assertEqual(context.exception.pkg_spec, 'lotus-3-0.x86_64')
def test_history_undo_operations_erase(self):
"""Test history_undo_operations with an erase."""
operations = NEVRAOperations()
operations.add('Erase', 'lotus-3-16.x86_64')
with self.base:
self.base._history_undo_operations(operations, 0)
transaction_it = iter(self.base.transaction)
actual = next(transaction_it)
expected = TransactionItem(
INSTALL,
installed='lotus-3-16.x86_64',
reason=libdnf.transaction.TransactionItemReason_USER
)
self.assertEqualTransactionItems(actual, expected)
self.assertRaises(StopIteration, next, transaction_it)
def test_history_undo_operations_erase_twoavailable(self):
"""Test history_undo_operations with an erase available in two repos."""
operations = NEVRAOperations()
operations.add('Erase', 'lotus-3-16.x86_64')
with self.base:
self.base._history_undo_operations(operations, 0)
transaction_it = iter(self.base.transaction)
actual = next(transaction_it)
expected = TransactionItem(
INSTALL,
installed='lotus-3-16.x86_64',
reason=libdnf.transaction.TransactionItemReason_USER
)
self.assertEqualTransactionItems(actual, expected)
self.assertRaises(StopIteration, next, transaction_it)
def test_history_undo_operations_erase_notavailable(self):
"""Test history_undo_operations with an unavailable erase."""
operations = NEVRAOperations()
operations.add('Erase', 'hole-1-1.x86_64')
with self.base, self.assertRaises(PackagesNotAvailableError) as context:
self.base._history_undo_operations(operations, 0)
self.assertEqual(context.exception.pkg_spec, 'hole-1-1.x86_64')
def test_history_undo_operations_install(self):
"""Test history_undo_operations with an install."""
operations = NEVRAOperations()
operations.add('Install', 'pepper-20-0.x86_64', obsoleted_nevras=('lotus-3-16.x86_64',))
with self.base:
self.base._history_undo_operations(operations, 0)
transaction_it = iter(self.base.transaction)
actual = next(transaction_it)
expected = TransactionItem(ERASE, erased='pepper-20-0.x86_64')
self.assertEqualTransactionItems(actual, expected)
actual = next(transaction_it)
expected = TransactionItem(
INSTALL,
installed='lotus-3-16.x86_64',
reason=libdnf.transaction.TransactionItemReason_USER
)
self.assertEqualTransactionItems(actual, expected)
self.assertRaises(StopIteration, next, transaction_it)
def test_history_undo_operations_install_notinstalled(self):
"""Test history_undo_operations with a not installed install."""
operations = NEVRAOperations()
operations.add('Install', 'mrkite-2-0.x86_64')
with self.base, self.assertRaises(PackagesNotInstalledError) as context:
self.base._history_undo_operations(operations, 0)
self.assertEqual(context.exception.pkg_spec, 'mrkite-2-0.x86_64')
def test_history_undo_operations_reinstall(self):
"""Test history_undo_operations with a reinstall."""
operations = NEVRAOperations()
operations.add(
'Reinstall',
'pepper-20-0.x86_64',
'pepper-20-0.x86_64',
('hole-1-1.x86_64',)
)
with self.base:
self.base._history_undo_operations(operations, 0)
transaction_it = iter(self.base.transaction)
actual = next(transaction_it)
expected = TransactionItem(
REINSTALL,
installed='pepper-20-0.x86_64',
erased='pepper-20-0.x86_64',
obsoleted=('hole-1-1.x86_64',)
)
self.assertEqualTransactionItems(actual, expected)
self.assertRaises(StopIteration, next, transaction_it)
def test_history_undo_operations_reinstall_notavailable(self):
"""Test history_undo_operations with an unvailable reinstall."""
operations = NEVRAOperations()
operations.add('Reinstall', 'mrkite-2-0.x86_64', 'mrkite-2-0.x86_64')
with self.base, self.assertRaises(PackagesNotInstalledError) as context:
self.base._history_undo_operations(operations, 0)
self.assertEqual(context.exception.pkg_spec, 'mrkite-2-0.x86_64')
def test_history_undo_operations_reinstall_notinstalled(self):
"""Test history_undo_operations with a not installed reinstall."""
operations = NEVRAOperations()
operations.add('Reinstall', 'hole-1-1.x86_64', 'hole-1-1.x86_64')
with self.base, self.assertRaises(PackagesNotAvailableError) as context:
self.base._history_undo_operations(operations, 0)
self.assertEqual(context.exception.pkg_spec, 'hole-1-1.x86_64')
def test_history_undo_operations_reinstall_notinstalled_obsoleted(self):
"""Test history_undo_operations with a not installed obsoleted of a reinstall."""
operations = NEVRAOperations()
operations.add(
'Reinstall',
'pepper-20-0.x86_64',
'pepper-20-0.x86_64',
('lotus-3-16.x86_64',)
)
with self.base:
self.base._history_undo_operations(operations, 0)
transaction_it = iter(self.base.transaction)
actual = next(transaction_it)
expected = TransactionItem(
REINSTALL,
installed='pepper-20-0.x86_64',
erased='pepper-20-0.x86_64',
obsoleted=()
)
self.assertEqualTransactionItems(actual, expected)
self.assertRaises(StopIteration, next, transaction_it)
def test_history_undo_operations_update(self):
"""Test history_undo_operations with an update."""
operations = NEVRAOperations()
operations.add('Update', 'tour-5-0.noarch', 'tour-4.6-1.noarch', ('lotus-3-16.x86_64',))
with self.base:
self.base._history_undo_operations(operations, 0)
transaction_it = iter(self.base.transaction)
actual = next(transaction_it)
expected = TransactionItem(
DOWNGRADE,
installed='tour-4.6-1.noarch',
erased='tour-5-0.noarch'
)
self.assertEqualTransactionItems(actual, expected)
actual = next(transaction_it)
expected = TransactionItem(
INSTALL,
installed='lotus-3-16.x86_64',
reason=libdnf.transaction.TransactionItemReason_USER
)
self.assertEqualTransactionItems(actual, expected)
self.assertRaises(StopIteration, next, transaction_it)
def test_history_undo_operations_update_notavailable(self):
"""Test history_undo_operations with an unavailable update."""
operations = NEVRAOperations()
operations.add('Update', 'tour-5-0.noarch', 'tour-4.6-2.noarch')
with self.base, self.assertRaises(PackagesNotAvailableError) as context:
self.base._history_undo_operations(operations, 0)
self.assertEqual(context.exception.pkg_spec, 'tour-4.6-2.noarch')
def test_history_undo_operations_update_notinstalled(self):
"""Test history_undo_operations with a not installed update."""
operations = NEVRAOperations()
operations.add('Update', 'lotus-4-0.x86_64', 'lotus-3-16.x86_64')
with self.base, self.assertRaises(PackagesNotInstalledError) as context:
self.base._history_undo_operations(operations, 0)
self.assertEqual(context.exception.pkg_spec, 'lotus-4-0.x86_64')
'''
| 11,924
|
Python
|
.py
| 232
| 41.025862
| 96
| 0.655997
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,805
|
test_persistor.py
|
rpm-software-management_dnf/tests/test_persistor.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2013-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import tempfile
import dnf.comps
import dnf.persistor
import dnf.pycomp
import tests.support
IDS = set(['one', 'two', 'three'])
class RepoPersistorTest(tests.support.TestCase):
def setUp(self):
self.persistdir = tempfile.mkdtemp(prefix="dnf-persistor-test-")
self.persistor = dnf.persistor.RepoPersistor(self.persistdir)
def tearDown(self):
dnf.util.rm_rf(self.persistdir)
def test_expired_repos(self):
self.assertLength(self.persistor.get_expired_repos(), 0)
self.persistor.expired_to_add = IDS
self.persistor.save()
self.assertEqual(self.persistor.get_expired_repos(), IDS)
persistor = dnf.persistor.RepoPersistor(self.persistdir)
self.assertEqual(persistor.get_expired_repos(), IDS)
| 1,844
|
Python
|
.py
| 38
| 45
| 77
| 0.754738
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,806
|
test_api.py
|
rpm-software-management_dnf/tests/test_api.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import unicode_literals
import dnf
from dnf.pycomp import unicode
import tests.support
class APITest(tests.support.TestCase):
def test_base(self):
self.assertIsInstance(dnf.Base, type)
def test_conf(self):
base = tests.support.MockBase()
self.assertIsInstance(base.conf.installroot, unicode)
# reasonable default
self.assertEqual(base.conf.installroot, '/tmp/dnf-test-installroot/')
# assignable
dnf.conf.installroot = '/mnt/rootimage'
| 1,506
|
Python
|
.py
| 31
| 45.290323
| 77
| 0.756131
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,807
|
test_cli_progress.py
|
rpm-software-management_dnf/tests/test_cli_progress.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf.callback
import dnf.cli.progress
import dnf.pycomp
import tests.support
from tests.support import mock
class MockStdout(dnf.pycomp.StringIO):
def visible_lines(self):
lines = self.lines()
last = len(lines) - 1
return [l[:-1] for (i, l) in enumerate(lines)
if l.endswith('\n') or i == last]
def lines(self):
return self.getvalue().splitlines(True)
class FakePayload(object):
def __init__(self, string, size):
self.string = string
self._size = size
def __str__(self):
return self.string
@property
def download_size(self):
return self._size
class ProgressTest(tests.support.TestCase):
def test_single(self):
now = 1379406823.9
fo = MockStdout()
with mock.patch('dnf.cli.progress._term_width', return_value=60), \
mock.patch('dnf.cli.progress.time', lambda: now):
p = dnf.cli.progress.MultiFileProgressMeter(fo)
p.isatty = True
pload = FakePayload('dummy-text', 5)
p.start(1, 1)
for i in range(6):
now += 1.0
p.progress(pload, i)
p.end(pload, None, None)
self.assertEqual(fo.lines(), [
'dummy-text 0% [ ] --- B/s | 0 B --:-- ETA\r',
'dummy-text 20% [== ] 1.0 B/s | 1 B 00:04 ETA\r',
'dummy-text 40% [==== ] 1.0 B/s | 2 B 00:03 ETA\r',
'dummy-text 60% [====== ] 1.0 B/s | 3 B 00:02 ETA\r',
'dummy-text 80% [======== ] 1.0 B/s | 4 B 00:01 ETA\r',
'dummy-text100% [==========] 1.0 B/s | 5 B 00:00 ETA\r',
'dummy-text 1.0 B/s | 5 B 00:05 \n'])
def test_mirror(self):
fo = MockStdout()
p = dnf.cli.progress.MultiFileProgressMeter(fo, update_period=-1)
p.isatty = True
p.start(1, 5)
pload = FakePayload('foo', 5.0)
now = 1379406823.9
with mock.patch('dnf.cli.progress._term_width', return_value=60), \
mock.patch('dnf.cli.progress.time', lambda: now):
p.progress(pload, 3)
p.end(pload, dnf.callback.STATUS_MIRROR, 'Timeout.')
p.progress(pload, 4)
self.assertEqual(fo.visible_lines(), [
'[MIRROR] foo: Timeout. ',
'foo 80% [======== ] --- B/s | 4 B --:-- ETA'])
_REFERENCE_TAB = [
['(1-2/2): f 0% [ ] --- B/s | 0 B --:-- ETA'],
['(1-2/2): b 10% [= ] 2.2 B/s | 3 B 00:12 ETA'],
['(1-2/2): f 20% [== ] 2.4 B/s | 6 B 00:10 ETA'],
['(1-2/2): b 30% [=== ] 2.5 B/s | 9 B 00:08 ETA'],
['(1-2/2): f 40% [==== ] 2.6 B/s | 12 B 00:06 ETA'],
['(1-2/2): b 50% [===== ] 2.7 B/s | 15 B 00:05 ETA'],
['(1-2/2): f 60% [====== ] 2.8 B/s | 18 B 00:04 ETA'],
['(1-2/2): b 70% [======= ] 2.8 B/s | 21 B 00:03 ETA'],
['(1-2/2): f 80% [======== ] 2.9 B/s | 24 B 00:02 ETA'],
['(1-2/2): b 90% [========= ] 2.9 B/s | 27 B 00:01 ETA'],
['(1/2): foo 1.0 B/s | 10 B 00:10 ',
'(2/2): bar100% [==========] 2.9 B/s | 30 B 00:00 ETA']]
def test_multi(self):
now = 1379406823.9
fo = MockStdout()
with mock.patch('dnf.cli.progress._term_width', return_value=60), \
mock.patch('dnf.cli.progress.time', lambda: now):
p = dnf.cli.progress.MultiFileProgressMeter(fo)
p.isatty = True
p.start(2, 30)
pload1 = FakePayload('foo', 10.0)
pload2 = FakePayload('bar', 20.0)
for i in range(11):
p.progress(pload1, float(i))
if i == 10:
p.end(pload1, None, None)
now += 0.5
p.progress(pload2, float(i * 2))
self.assertEqual(self._REFERENCE_TAB[i], fo.visible_lines())
if i == 10:
p.end(pload2, dnf.callback.STATUS_FAILED, 'some error')
now += 0.5
# check "end" events
self.assertEqual(fo.visible_lines(), [
'(1/2): foo 1.0 B/s | 10 B 00:10 ',
'[FAILED] bar: some error '])
self.assertTrue(2.0 < p.rate < 4.0)
@mock.patch('dnf.cli.progress._term_width', return_value=40)
def test_skip(self, mock_term_width):
fo = MockStdout()
p = dnf.cli.progress.MultiFileProgressMeter(fo)
p.start(2, 30)
pload1 = FakePayload('club', 20.0)
p.end(pload1, dnf.callback.STATUS_ALREADY_EXISTS, 'already got')
self.assertEqual(p.done_files, 1)
self.assertEqual(p.done_size, pload1._size)
self.assertEqual(fo.getvalue(),
'[SKIPPED] club: already got \n')
| 6,150
|
Python
|
.py
| 126
| 39.68254
| 77
| 0.51866
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,808
|
test_transaction.py
|
rpm-software-management_dnf/tests/test_transaction.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2013-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import libdnf.transaction
import rpm
import dnf.goal
import dnf.repo
import dnf.transaction
import tests.support
from tests.support import mock
'''
class TransactionItemTest(tests.support.DnfBaseTestCase):
REPOS = ['main', 'search']
@classmethod
def setUpClass(cls):
"""Prepare the class level fixture."""
cls.newpkg = tests.support.MockPackage('new-1.0-1.x86_64')
cls.oldpkg = tests.support.MockPackage('old-4.23-13.x86_64')
cls.obspkg1 = tests.support.MockPackage('obs1-3.12-12.x86_64')
cls.obspkg2 = tests.support.MockPackage('obs2-2.1-11.x86_64')
cls.obspkg3 = tests.support.MockPackage('obs3-1.0-10.x86_64')
def test_active_hist_state_erase(self):
"""Test active_history_state with the erase op_type."""
tsi = dnf.transaction.TransactionItem(
dnf.transaction.ERASE, erased=self.oldpkg)
history_state = tsi._active_history_state
self.assertEqual(history_state, 'Erase')
def test_active_hist_state_install(self):
"""Test active_history_state with the install op_type."""
tsi = dnf.transaction.TransactionItem(
dnf.transaction.INSTALL, installed=self.newpkg,
obsoleted=[self.obspkg1, self.obspkg2])
history_state = tsi._active_history_state
self.assertEqual(history_state, 'Install')
def test_creating(self):
tsi = dnf.transaction.TransactionItem(
dnf.transaction.UPGRADE, self.newpkg, self.oldpkg,
[self.obspkg1, self.obspkg2, self.obspkg3])
self.assertEqual(tsi.installed, self.newpkg)
self.assertEqual(tsi.erased, self.oldpkg)
self.assertCountEqual(
tsi.obsoleted, [self.obspkg1, self.obspkg2, self.obspkg3])
tsi = dnf.transaction.TransactionItem(dnf.transaction.ERASE,
erased=self.oldpkg)
self.assertEqual(tsi.installed, None)
self.assertEqual(tsi.erased, self.oldpkg)
self.assertCountEqual(tsi.obsoleted, ())
def test_history_iterator_reinstall(self):
"""Test self.history_iterator with the reinstall op_type."""
tsi = dnf.transaction.TransactionItem(
dnf.transaction.REINSTALL, self.newpkg, self.oldpkg,
[self.obspkg1, self.obspkg2, self.obspkg3])
self.assertCountEqual(
tsi._history_iterator(),
[(self.newpkg, 'Reinstall', True), (self.oldpkg, 'Reinstalled', False),
(self.obspkg1, 'Obsoleted', False), (self.obspkg2, 'Obsoleted', False),
(self.obspkg3, 'Obsoleted', False)])
def test_history_iterator_upgrade(self):
"""Test self.history_iterator with the upgrade op_type."""
tsi = dnf.transaction.TransactionItem(
dnf.transaction.UPGRADE, self.newpkg, self.oldpkg,
[self.obspkg1, self.obspkg2, self.obspkg3])
self.assertCountEqual(
tsi._history_iterator(),
[(self.newpkg, 'Update', True), (self.oldpkg, 'Updated', False),
(self.obspkg1, 'Obsoleted', False), (self.obspkg2, 'Obsoleted', False),
(self.obspkg3, 'Obsoleted', False)])
def test_propagated_reason(self):
self.newpkg._force_swdb_repoid = "main"
tsi1 = dnf.transaction.TransactionItem(
dnf.transaction.INSTALL,
installed=self.newpkg,
reason=libdnf.transaction.TransactionItemReason_DEPENDENCY
)
self.oldpkg._force_swdb_repoid = "main"
tsi2 = dnf.transaction.TransactionItem(
dnf.transaction.INSTALL,
installed=self.oldpkg,
reason=libdnf.transaction.TransactionItemReason_DEPENDENCY
)
tsis = [tsi1, tsi2]
self._swdb_commit(tsis)
ionly = self.sack.query().filter(empty=True) # installonly_query
tsi = dnf.transaction.TransactionItem(
dnf.transaction.INSTALL,
installed=self.newpkg,
reason='user'
)
actual = tsi._propagated_reason(self.history, ionly)
expected = libdnf.transaction.TransactionItemReason_USER
self.assertEqual(actual, expected)
tsi = dnf.transaction.TransactionItem(
dnf.transaction.UPGRADE,
installed=self.newpkg,
erased=self.oldpkg
)
actual = tsi._propagated_reason(self.history, ionly)
expected = libdnf.transaction.TransactionItemReason_DEPENDENCY
self.assertEqual(actual, expected)
tsi = dnf.transaction.TransactionItem(
dnf.transaction.DOWNGRADE,
installed=self.newpkg,
erased=self.oldpkg
)
actual = tsi._propagated_reason(self.history, ionly)
expected = libdnf.transaction.TransactionItemReason_DEPENDENCY
self.assertEqual(actual, expected)
# test the call can survive if no reason is known:
self.history.reset_db()
actual = tsi._propagated_reason(self.history, ionly)
expected = libdnf.transaction.TransactionItemReason_UNKNOWN
self.assertEqual(actual, expected)
def test_removes(self):
tsi = dnf.transaction.TransactionItem(
dnf.transaction.UPGRADE, self.newpkg, self.oldpkg,
[self.obspkg1, self.obspkg2, self.obspkg3])
self.assertCountEqual(
tsi.removes(),
[self.oldpkg, self.obspkg1, self.obspkg2, self.obspkg3])
class TransactionTest(tests.support.TestCase):
def setUp(self):
self.ipkg = tests.support.MockPackage('inst-1.0-1.x86_64')
self.upkg1 = tests.support.MockPackage('upg1-2.1-2.x86_64')
self.upkg2 = tests.support.MockPackage('upg2-3.2-3.x86_64')
self.dpkg = tests.support.MockPackage('down-4.3-4.x86_64')
self.rpkg1 = tests.support.MockPackage('rem1-2.1-1.x86_64')
self.rpkg2 = tests.support.MockPackage('rem2-3.2-2.x86_64')
self.rpkg3 = tests.support.MockPackage('rem3-4.3-5.x86_64')
self.opkg1 = tests.support.MockPackage('obs1-4.23-13.x86_64')
self.opkg2 = tests.support.MockPackage('obs2-3.12-12.x86_64')
self.opkg3 = tests.support.MockPackage('obs3-2.1-11.x86_64')
self.opkg4 = tests.support.MockPackage('obs4-1.0-10.x86_64')
self.trans = dnf.transaction.Transaction()
self.trans.add_install(self.ipkg, [self.opkg1, self.opkg2, self.opkg3])
self.trans.add_upgrade(self.upkg1, self.rpkg1, [self.opkg4])
self.trans.add_upgrade(self.upkg2, self.rpkg2, [])
self.trans.add_downgrade(self.dpkg, self.rpkg3, [])
def test_get_items(self):
self.assertLength(self.trans._get_items(dnf.transaction.ERASE), 0)
self.assertLength(self.trans._get_items(dnf.transaction.UPGRADE), 2)
def test_iter(self):
self.assertLength(list(self.trans), 4)
self.assertIsInstance(next(iter(self.trans)),
dnf.transaction.TransactionItem)
def test_length(self):
self.assertLength(self.trans, 4)
def test_sets(self):
self.assertCountEqual(
self.trans.install_set,
[self.ipkg, self.upkg1, self.upkg2, self.dpkg])
self.assertCountEqual(
self.trans.remove_set,
[self.opkg1, self.opkg2, self.opkg3, self.opkg4,
self.rpkg1, self.rpkg2, self.rpkg3])
def test_total_package_count(self):
self.assertEqual(self.trans._total_package_count(), 11)
class RPMLimitationsTest(tests.support.TestCase):
def test_rpm_limitations(self):
ts = dnf.transaction.Transaction()
pkg = tests.support.MockPackage('anyway-2-0.src')
ts.add_install(pkg, [])
msg = ts._rpm_limitations()
self.assertIsNot(msg, None)
class PopulateTSTest(tests.support.TestCase):
@staticmethod
def test_populate_rpm_ts():
ts = dnf.transaction.Transaction()
conf = tests.support.FakeConf(cachedir='/tmp')
repo = dnf.repo.Repo('r', conf)
inst = tests.support.MockPackage("ago-20.0-1.x86_64.fc69", repo)
upg = tests.support.MockPackage("billy-1.2-1.x86_64.fc69", repo)
old = tests.support.MockPackage("billy-1.1-1.x86_64.fc69", repo)
ts.add_install(inst, [])
ts.add_upgrade(upg, old, [])
rpm_ts = ts._populate_rpm_ts(mock.Mock())
rpm_ts.assert_has_calls([mock.call.addInstall(None, ts._tsis[0], 'i'),
mock.call.addInstall(None, ts._tsis[1], 'u')])
class RPMProbFilters(tests.support.DnfBaseTestCase):
REPOS = ['main', 'search']
@mock.patch('dnf.rpm.transaction.TransactionWrapper')
def test_filters_install(self, _mock_ts):
self.base.install("lotus")
ts = self.base._ts
ts.setProbFilter.assert_called_with(rpm.RPMPROB_FILTER_OLDPACKAGE)
@mock.patch('dnf.rpm.transaction.TransactionWrapper')
def test_filters_downgrade(self, _ts):
self.base.downgrade("tour")
ts = self.base._ts
ts.setProbFilter.assert_called_with(rpm.RPMPROB_FILTER_OLDPACKAGE)
@mock.patch('dnf.rpm.transaction.TransactionWrapper')
def test_filters_reinstall(self, _ts):
self.base.reinstall("librita")
expected = rpm.RPMPROB_FILTER_OLDPACKAGE
self.base._ts.setProbFilter.assert_called_with(expected)
'''
| 10,377
|
Python
|
.py
| 211
| 40.483412
| 84
| 0.666601
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,809
|
test_misc.py
|
rpm-software-management_dnf/tests/test_misc.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import unicode_literals
import dnf.yum.misc
import tests.support
class TestGenericHolder(tests.support.TestCase):
def test_merge_lists(self):
gh = dnf.yum.misc.GenericHolder()
gh2 = dnf.yum.misc.GenericHolder()
gh.l = ["lucy", "in", "the"]
gh2.l = ["sky"]
gh2.l2 = ["with", "diamonds"]
gh.merge_lists(gh2)
self.assertEqual(gh.l, ["lucy", "in", "the", "sky"])
self.assertEqual(gh.l2, ["with", "diamonds"])
| 1,478
|
Python
|
.py
| 30
| 45.8
| 77
| 0.722607
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,810
|
test_libcomps.py
|
rpm-software-management_dnf/tests/test_libcomps.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
import libcomps
import tests.support
class LibcompsTest(tests.support.TestCase):
"""Sanity tests of the Libcomps library."""
def test_environment_parse(self):
xml = """\
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE comps PUBLIC "-//Red Hat, Inc.//DTD Comps info//EN" "comps.dtd">
<comps>
<group>
<id>somerset</id>
<default>true</default>
<uservisible>true</uservisible>
<display_order>1024</display_order>
<name>Solid Ground</name>
<description>--</description>
<packagelist>
<packagereq type="mandatory">pepper</packagereq>
<packagereq type="mandatory">trampoline</packagereq>
</packagelist>
</group>
<environment>
<id>minimal</id>
<name>Min install</name>
<description>Basic functionality.</description>
<display_order>5</display_order>
<grouplist>
<groupid>somerset</groupid>
</grouplist>
</environment>
</comps>
"""
comps = libcomps.Comps()
ret = comps.fromxml_str(xml)
self.assertGreaterEqual(ret, 0)
def test_segv(self):
c1 = libcomps.Comps()
c2 = libcomps.Comps()
c2.fromxml_f(tests.support.COMPS_PATH)
c1 + c2 # sigsegved here
def test_segv2(self):
c1 = libcomps.Comps()
c1.fromxml_f(tests.support.COMPS_PATH)
c2 = libcomps.Comps()
c2.fromxml_f(tests.support.COMPS_PATH)
c = c1 + c2
c.groups[0].packages[0].name
| 2,463
|
Python
|
.py
| 65
| 33.569231
| 77
| 0.704526
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,811
|
test_cli_format.py
|
rpm-software-management_dnf/tests/test_cli_format.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf.cli.format
from dnf.cli.format import format_time, format_number
import tests.support
class FormatTest(tests.support.TestCase):
def test_format_time(self):
self.assertEqual(format_time(None), '--:--')
self.assertEqual(format_time(-1), '--:--')
self.assertEqual(format_time(12 * 60 + 34), '12:34')
self.assertEqual(format_time(12 * 3600 + 34 * 60 + 56), '754:56')
self.assertEqual(format_time(12 * 3600 + 34 * 60 + 56, use_hours=True), '12:34:56')
def test_format_number(self):
self.assertEqual(format_number(None), '0.0 ')
self.assertEqual(format_number(-1), '-1 ')
self.assertEqual(format_number(1.0), '1.0 ')
self.assertEqual(format_number(999.0), '999 ')
self.assertEqual(format_number(1000.0), '1.0 k')
self.assertEqual(format_number(1 << 20), '1.0 M')
self.assertEqual(format_number(1 << 30), '1.0 G')
self.assertEqual(format_number(1e6, SI=1), '1.0 M')
self.assertEqual(format_number(1e9, SI=1), '1.0 G')
def test_indent_block(self):
s = 'big\nbrown\nbag'
out = dnf.cli.format.indent_block(s)
self.assertEqual(out, ' big\n brown\n bag')
| 2,277
|
Python
|
.py
| 42
| 49.5
| 91
| 0.696902
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,812
|
test_modules.py
|
rpm-software-management_dnf/tests/test_modules.py
|
# Copyright (C) 2017 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import os
import shutil
import tempfile
import unittest
import libdnf
import dnf.conf
import dnf.base
TOP_DIR = os.path.abspath(os.path.dirname(__file__))
REPOS_DIR = os.path.join(TOP_DIR, "modules/modules")
# with profile
MODULE_NSVAP = "module-name:stream:1::x86_64/profile"
MODULE_NSVP = "module-name:stream:1/profile"
MODULE_NSAP = "module-name:stream::x86_64/profile"
MODULE_NSP = "module-name:stream/profile"
MODULE_NP = "module-name/profile"
MODULE_NAP = "module-name::x86_64/profile"
# without profile
MODULE_NSVA = "module-name:stream:1::x86_64"
MODULE_NSV = "module-name:stream:1"
MODULE_NSA = "module-name:stream::x86_64"
MODULE_NS = "module-name:stream"
MODULE_N = "module-name"
MODULE_NA = "module-name::x86_64"
class ModuleTest(unittest.TestCase):
def assertInstalls(self, nevras):
expected = sorted(set(nevras))
actual = sorted(set([str(i) for i in self.base._goal.list_installs()]))
self.assertEqual(expected, actual)
def setUp(self):
self.tmpdir = tempfile.mkdtemp(prefix="dnf_test_")
self.conf = dnf.conf.MainConf()
self.conf.cachedir = os.path.join(self.tmpdir, "cache")
self.conf.installroot = os.path.join(TOP_DIR, "modules")
self.conf.persistdir = os.path.join(self.conf.installroot, self.conf.persistdir.lstrip("/"))
self.conf.substitutions["arch"] = "x86_64"
self.conf.substitutions["basearch"] = dnf.rpm.basearch(self.conf.substitutions["arch"])
self.conf.assumeyes = True
self.base = dnf.Base(conf=self.conf)
self.module_base = dnf.module.module_base.ModuleBase(self.base)
self._add_module_repo("_all")
self.base.fill_sack(load_system_repo=False)
def tearDown(self):
shutil.rmtree(self.tmpdir)
def _add_module_repo(self, repo_id, modules=True):
url = "file://" + os.path.join(REPOS_DIR, repo_id, self.conf.substitutions["arch"])
repo = self.base.repos.add_new_repo(repo_id, self.base.conf, baseurl=[url], modules=modules)
return repo
# dnf module enable
def test_enable_name(self):
# use default stream
self.module_base.enable(["httpd"])
self.assertEqual(self.base._moduleContainer.getModuleState("httpd"),
libdnf.module.ModulePackageContainer.ModuleState_ENABLED)
self.assertEqual(self.base._moduleContainer.getEnabledStream("httpd"), "2.4")
def test_enable_name_stream(self):
self.module_base.enable(["httpd:2.4"])
self.assertEqual(self.base._moduleContainer.getModuleState("httpd"),
libdnf.module.ModulePackageContainer.ModuleState_ENABLED)
self.assertEqual(self.base._moduleContainer.getEnabledStream("httpd"), "2.4")
# also enable base-runtime; it's a dependency that's used in other tests
self.module_base.enable(["base-runtime:f26"])
def test_enable_pkgspec(self):
self.module_base.enable(["httpd:2.4:1/foo"])
self.assertEqual(self.base._moduleContainer.getModuleState("httpd"),
libdnf.module.ModulePackageContainer.ModuleState_ENABLED)
self.assertEqual(self.base._moduleContainer.getEnabledStream("httpd"), "2.4")
def test_enable_invalid(self):
with self.assertRaises(dnf.exceptions.Error):
self.module_base.enable(["httpd:invalid"])
def test_enable_different_stream(self):
self.module_base.enable(["httpd:2.4"])
self.assertEqual(self.base._moduleContainer.getModuleState("httpd"),
libdnf.module.ModulePackageContainer.ModuleState_ENABLED)
self.assertEqual(self.base._moduleContainer.getEnabledStream("httpd"), "2.4")
self.module_base.enable(["httpd:2.2"])
self.assertEqual(self.base._moduleContainer.getModuleState("httpd"),
libdnf.module.ModulePackageContainer.ModuleState_ENABLED)
self.assertEqual(self.base._moduleContainer.getEnabledStream("httpd"), "2.2")
def test_enable_different_stream_missing_profile(self):
pass
# dnf module disable
def test_disable_name(self):
self.module_base.enable(["httpd:2.4"])
self.assertEqual(self.base._moduleContainer.getModuleState("httpd"),
libdnf.module.ModulePackageContainer.ModuleState_ENABLED)
self.assertEqual(self.base._moduleContainer.getEnabledStream("httpd"), "2.4")
self.module_base.disable(["httpd"])
self.assertEqual(self.base._moduleContainer.getModuleState("httpd"),
libdnf.module.ModulePackageContainer.ModuleState_DISABLED)
self.assertEqual(self.base._moduleContainer.getEnabledStream("httpd"), "")
def test_disable_name_stream(self):
# It should disable whole module not only stream (strem = "")
self.module_base.enable(["httpd:2.4"])
self.assertEqual(self.base._moduleContainer.getModuleState("httpd"),
libdnf.module.ModulePackageContainer.ModuleState_ENABLED)
self.assertEqual(self.base._moduleContainer.getEnabledStream("httpd"), "2.4")
self.module_base.disable(["httpd:2.4"])
self.assertEqual(self.base._moduleContainer.getModuleState("httpd"),
libdnf.module.ModulePackageContainer.ModuleState_DISABLED)
self.assertEqual(self.base._moduleContainer.getEnabledStream("httpd"), "")
def test_disable_pkgspec(self):
# It should disable whole module not only profile (strem = "")
self.module_base.enable(["httpd:2.4"])
self.assertEqual(self.base._moduleContainer.getModuleState("httpd"),
libdnf.module.ModulePackageContainer.ModuleState_ENABLED)
self.assertEqual(self.base._moduleContainer.getEnabledStream("httpd"), "2.4")
self.module_base.disable(["httpd:2.4:1/foo"])
self.assertEqual(self.base._moduleContainer.getModuleState("httpd"),
libdnf.module.ModulePackageContainer.ModuleState_DISABLED)
self.assertEqual(self.base._moduleContainer.getEnabledStream("httpd"), "")
def test_disable_invalid(self):
self.module_base.enable(["httpd:2.4"])
self.assertEqual(self.base._moduleContainer.getModuleState("httpd"),
libdnf.module.ModulePackageContainer.ModuleState_ENABLED)
self.assertEqual(self.base._moduleContainer.getEnabledStream("httpd"), "2.4")
with self.assertRaises(dnf.exceptions.Error):
self.module_base.disable(["httpd:invalid"])
def test_info_name(self):
pass
def test_info_name_stream(self):
pass
def test_info_pkgspec(self):
pass
# dnf module list
def test_list_installed(self):
# install
self.module_base.install(["base-runtime"])
# check module conf
self.assertEqual(self.base._moduleContainer.getModuleState("base-runtime"),
libdnf.module.ModulePackageContainer.ModuleState_ENABLED)
self.assertEqual(self.base._moduleContainer.getEnabledStream("base-runtime"), "f26")
self.assertEqual(list(self.base._moduleContainer.getInstalledProfiles("base-runtime")),
["minimal"])
# dnf module install / dnf install @
def test_install_profile_latest(self):
self.test_enable_name_stream()
self.module_base.install(["httpd/default"])
self.base.resolve()
expected = [
"basesystem-11-3.noarch",
"filesystem-3.2-40.x86_64",
"glibc-2.25.90-2.x86_64",
"glibc-common-2.25.90-2.x86_64",
"httpd-2.4.25-8.x86_64",
"libnghttp2-1.21.1-1.x86_64", # expected behaviour, non-modular rpm pulled in
]
self.assertInstalls(expected)
def test_install_profile(self):
self.test_enable_name_stream()
self.module_base.install(["httpd:2.4:1/default"])
self.base.resolve()
expected = [
"basesystem-11-3.noarch",
"filesystem-3.2-40.x86_64",
"glibc-2.25.90-2.x86_64",
"glibc-common-2.25.90-2.x86_64",
"httpd-2.4.25-7.x86_64",
"libnghttp2-1.21.1-1.x86_64", # expected behaviour, non-modular rpm pulled in
]
self.assertInstalls(expected)
def test_install_two_profiles(self):
self.test_enable_name_stream()
self.module_base.install(["httpd:2.4:1/default", "httpd:2.4:1/doc"])
self.base.resolve()
expected = [
"basesystem-11-3.noarch",
"filesystem-3.2-40.x86_64",
"glibc-2.25.90-2.x86_64",
"glibc-common-2.25.90-2.x86_64",
"httpd-2.4.25-7.x86_64",
"httpd-doc-2.4.25-7.x86_64",
"libnghttp2-1.21.1-1.x86_64", # expected behaviour, non-modular rpm pulled in
]
self.assertInstalls(expected)
def test_install_two_profiles_different_versions(self):
self.test_enable_name_stream()
self.module_base.install(["httpd:2.4:2/default", "httpd:2.4:1/doc"])
self.base.resolve()
expected = [
"basesystem-11-3.noarch",
"filesystem-3.2-40.x86_64",
"glibc-2.25.90-2.x86_64",
"glibc-common-2.25.90-2.x86_64",
"httpd-2.4.25-8.x86_64",
"httpd-doc-2.4.25-8.x86_64",
"libnghttp2-1.21.1-1.x86_64", # expected behaviour, non-modular rpm pulled in
]
self.assertInstalls(expected)
def test_install_profile_updated(self):
return
"""
# install profile1 from an old module version
# then install profile2 from latest module version
# -> dnf forces upgrade profile1 to the latest module version
"""
self.test_install_profile()
self.module_base.install(["httpd:2.4:2/doc"])
self.base.resolve()
expected = [
"basesystem-11-3.noarch",
"filesystem-3.2-40.x86_64",
"glibc-2.25.90-2.x86_64",
"glibc-common-2.25.90-2.x86_64",
"httpd-2.4.25-8.x86_64",
"httpd-doc-2.4.25-8.x86_64",
"libnghttp2-1.21.1-1.x86_64",
]
self.assertInstalls(expected)
def test_install_deps_same_module_version(self):
pass
def test_install_implicit_empty_default_profile(self):
# install module without a 'default' profile
# -> It should raise an error
self.assertRaises(dnf.exceptions.MarkingErrors, self.module_base.install, ["m4:1.4.18"])
# dnf module upgrade / dnf upgrade @
def test_upgrade(self):
pass
def test_upgrade_lower_rpm_nevra(self):
pass
def test_upgrade_lower_module_nsvap(self):
pass
def test_upgrade_missing_profile(self):
pass
# dnf module downgrade / dnf downgrade @
def test_downgrade(self):
pass
# dnf module remove / dnf remove @
def test_remove(self):
pass
def test_remove_shared_rpms(self):
# don't remove RPMs that are part of another installed module / module profile
# also don't remove RPMs that are required by user-installed RPMs
pass
def test_remove_invalid(self):
pass
def test_bare_rpms_filtering(self):
"""
Test hybrid repos where RPMs of the same name (or Provides)
can be both modular and bare (non-modular).
"""
# no match with modular RPM $name -> keep
q = self.base.sack.query().filter(nevra="grub2-2.02-0.40.x86_64")
self.assertEqual(len(q), 1)
# $name matches with modular RPM $name -> exclude
q = self.base.sack.query().filter(nevra="httpd-2.2.10-1.x86_64")
self.assertEqual(len(q), 0)
# Provides: $name matches with modular RPM $name -> exclude
q = self.base.sack.query().filter(nevra="httpd-provides-name-3.0-1.x86_64")
self.assertEqual(len(q), 0)
# Provides: $name = ... matches with modular RPM $name -> exclude
q = self.base.sack.query().filter(nevra="httpd-provides-name-version-release-3.0-1.x86_64")
self.assertEqual(len(q), 0)
| 13,210
|
Python
|
.py
| 270
| 40.148148
| 100
| 0.657012
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,813
|
test_distsync.py
|
rpm-software-management_dnf/tests/test_distsync.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import rpm
import tests.support
class DistroSyncAll(tests.support.ResultTestCase):
REPOS = ["distro"]
INIT_SACK = True
def test_distro_sync_all(self):
self.base.distro_sync()
self.assertIn(rpm.RPMPROB_FILTER_OLDPACKAGE, self.base._rpm_probfilter)
packages = tests.support.installed_but(self.sack, "pepper", "librita").run()
q = self.sack.query().available().filter(name=["pepper", "librita"])
packages.extend(q)
self.assertResult(self.base, packages)
class DistroSync(tests.support.ResultTestCase):
REPOS = ["main", "updates"]
BASE_CLI = True
def test_distro_sync(self):
installed = self._get_installed(self.base)
original_pkg = list(filter(lambda p: p.name == "hole", installed))
self.base.distro_sync_userlist(('bla', 'hole'))
obsolete_pkg = list(filter(lambda p: p.name == "tour", installed))
installed2 = self._get_installed(self.base)
updated_pkg = list(filter(lambda p: p.name == "hole", installed2))
self.assertLength(updated_pkg, 1)
self.assertLength(original_pkg, 1)
self.assertLength(updated_pkg, 1)
# holy pkg upgraded from version 1 to 2 and obsoletes tour
self.assertEqual(original_pkg[0].version, "1")
self.assertEqual(updated_pkg[0].version, "2")
installed.remove(original_pkg[0])
installed.remove(obsolete_pkg[0])
installed2.remove(updated_pkg[0])
self.assertEqual(installed, installed2)
| 2,580
|
Python
|
.py
| 51
| 45.392157
| 84
| 0.713718
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,814
|
test_exceptions.py
|
rpm-software-management_dnf/tests/test_exceptions.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf.exceptions
import tests.support
JAY_ERR = """jay-3.x86_64: Can not download."""
class DownloadErrorTest(tests.support.TestCase):
def test_str(self):
exc = dnf.exceptions.DownloadError(errmap={
'jay-3.x86_64': ['Can not download.']})
self.assertEqual(str(exc), JAY_ERR)
exc = dnf.exceptions.DownloadError(errmap={'': ['Epic fatal.']})
self.assertEqual(str(exc), 'Epic fatal.')
| 1,507
|
Python
|
.py
| 29
| 48.965517
| 77
| 0.74455
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,815
|
test_downgrade_to.py
|
rpm-software-management_dnf/tests/test_downgrade_to.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2015-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf
import tests.support
class DowngradeTo(tests.support.ResultTestCase):
REPOS = ['main', 'old_versions']
def test_downgrade_to_lowest(self):
with tests.support.mock.patch('logging.Logger.warning'):
with self.assertRaises(dnf.exceptions.PackagesNotInstalledError):
self.base.downgrade_to('hole')
self.assertResult(self.base, self.base._sack.query().installed())
def test_downgrade_to_name(self):
self.base.downgrade_to('tour')
(installed, removed) = self.installed_removed(self.base)
self.assertCountEqual(map(str, installed),
('tour-4.9-1.noarch',))
self.assertCountEqual(map(str, removed),
('tour-5-0.noarch',))
def test_downgrade_to_wildcard_name(self):
self.base.downgrade_to('tour*')
(installed, removed) = self.installed_removed(self.base)
self.assertCountEqual(map(str, installed),
('tour-4.9-1.noarch',))
self.assertCountEqual(map(str, removed),
('tour-5-0.noarch',))
def test_downgrade_to_version(self):
self.base.downgrade_to('tour-4.6')
(installed, removed) = self.installed_removed(self.base)
self.assertCountEqual(map(str, installed),
('tour-4.6-1.noarch',))
self.assertCountEqual(map(str, removed),
('tour-5-0.noarch',))
| 2,556
|
Python
|
.py
| 49
| 44
| 77
| 0.671474
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,816
|
test_lock.py
|
rpm-software-management_dnf/tests/test_lock.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
"""Unit test dnf.lock module.
Locking is very hard to cover reasonably with a unit test, this is more or less
just a sanity check.
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import multiprocessing
import os
import re
import threading
import dnf.lock
import dnf.pycomp
import dnf.util
from dnf.exceptions import ProcessLockError, ThreadLockError
import tests.support
from tests.support import mock
class ConcurrencyMixin(object):
def __init__(self, lock):
self.lock = lock
def run(self):
try:
with self.lock:
pass
except (ProcessLockError, ThreadLockError) as e:
self.queue.put(e)
class OtherThread(ConcurrencyMixin, threading.Thread):
def __init__(self, lock):
ConcurrencyMixin.__init__(self, lock)
threading.Thread.__init__(self)
self.queue = dnf.pycomp.Queue(1)
class OtherProcess(ConcurrencyMixin, multiprocessing.Process):
def __init__(self, lock):
ConcurrencyMixin.__init__(self, lock)
multiprocessing.Process.__init__(self)
self.queue = multiprocessing.Queue(1)
TARGET = os.path.join(tests.support.USER_RUNDIR, 'unit-test.pid')
def build_lock(blocking=False):
return dnf.lock.ProcessLock(TARGET, 'unit-tests', blocking)
class LockTest(tests.support.TestCase):
def test_fit_lock_dir(self):
orig = '/some'
with mock.patch('dnf.util.am_i_root', return_value=True):
self.assertEqual(dnf.lock._fit_lock_dir(orig), '/some')
with mock.patch('dnf.util.am_i_root', return_value=False):
dir_ = dnf.lock._fit_lock_dir(orig)
match = re.match(
r'/var/tmp/dnf-[^:]+-[^/]+/locks/2690814ff0269c86e5109d2915ea572092918cb3',
dir_)
self.assertTrue(match)
class ProcessLockTest(tests.support.TestCase):
@classmethod
def tearDownClass(cls):
dnf.util.rm_rf(tests.support.USER_RUNDIR)
def test_simple(self):
l1 = build_lock()
target = l1.target
with l1:
self.assertFile(target)
self.assertPathDoesNotExist(target)
def test_reentrance(self):
l1 = build_lock()
with l1:
with l1:
pass
def test_another_process(self):
l1 = build_lock()
process = OtherProcess(l1)
with l1:
process.start()
process.join()
self.assertIsInstance(process.queue.get(), ProcessLockError)
def test_another_process_blocking(self):
l1 = build_lock(blocking=True)
l2 = build_lock(blocking=True)
process = OtherProcess(l1)
target = l1.target
with l2:
process.start()
process.join()
self.assertEqual(process.queue.empty(), True)
self.assertPathDoesNotExist(target)
def test_another_thread(self):
l1 = build_lock()
thread = OtherThread(l1)
with l1:
thread.start()
thread.join()
self.assertIsInstance(thread.queue.get(), ThreadLockError)
| 4,089
|
Python
|
.py
| 105
| 32.409524
| 91
| 0.678635
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,817
|
test_upgrade_to.py
|
rpm-software-management_dnf/tests/test_upgrade_to.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import itertools
import dnf
import tests.support
class UpgradeTo(tests.support.ResultTestCase):
REPOS = ['main', 'updates', 'third_party']
def test_upgrade_to(self):
self.base.upgrade("pepper-20-1.x86_64")
new_set = tests.support.installed_but(self.sack, "pepper").run()
q = self.sack.query().available()._nevra("pepper-20-1.x86_64")
new_set.extend(q)
self.assertResult(self.base, new_set)
def test_upgrade_to_reponame(self):
"""Test whether only packages in selected repo are used."""
self.base.upgrade('hole-1-2.x86_64', 'updates')
subject = dnf.subject.Subject('hole-1-2.x86_64')
self.assertResult(self.base, itertools.chain(
self.sack.query().installed().filter(name__neq='hole'),
subject.get_best_query(self.sack).filter(reponame='updates'))
)
def test_upgrade_to_reponame_not_in_repo(self):
"""Test whether no packages are upgraded if bad repo is selected."""
self.base.upgrade('hole-1-2.x86_64', 'main')
self.assertResult(self.base, self.sack.query().installed())
| 2,190
|
Python
|
.py
| 42
| 47.404762
| 77
| 0.716628
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,818
|
test_commands.py
|
rpm-software-management_dnf/tests/test_commands.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import itertools
import logging
import tempfile
import libdnf.transaction
import dnf.cli.commands
import dnf.cli.commands.group
import dnf.cli.commands.install
import dnf.cli.commands.reinstall
import dnf.cli.commands.upgrade
import dnf.pycomp
import dnf.repo
import tests.support
from tests.support import mock
class CommandsCliTest(tests.support.DnfBaseTestCase):
REPOS = []
CLI = "mock"
def setUp(self):
super(CommandsCliTest, self).setUp()
self.base.conf.persistdir = tempfile.mkdtemp()
@mock.patch('dnf.cli.commands._', dnf.pycomp.NullTranslations().ugettext)
def test_history_get_error_output_rollback_transactioncheckerror(self):
"""Test get_error_output with the history rollback and a TransactionCheckError."""
cmd = dnf.cli.commands.history.HistoryCommand(self.cli)
tests.support.command_configure(cmd, ['rollback', '1'])
lines = cmd.get_error_output(dnf.exceptions.TransactionCheckError())
self.assertEqual(
lines,
('Cannot rollback transaction 1, doing so would result in an '
'inconsistent package database.',))
@mock.patch('dnf.cli.commands._', dnf.pycomp.NullTranslations().ugettext)
def test_history_get_error_output_undo_transactioncheckerror(self):
"""Test get_error_output with the history undo and a TransactionCheckError."""
cmd = dnf.cli.commands.history.HistoryCommand(self.cli)
tests.support.command_configure(cmd, ['undo', '1'])
lines = cmd.get_error_output(dnf.exceptions.TransactionCheckError())
self.assertEqual(
lines,
('Cannot undo transaction 1, doing so would result in an '
'inconsistent package database.',))
@mock.patch('dnf.cli.commands._', dnf.pycomp.NullTranslations().ugettext)
def test_history_convert_tids(self):
"""Test history _convert_tids()."""
cmd = dnf.cli.commands.history.HistoryCommand(self.cli)
cmd.cli.base.output = mock.MagicMock()
cmd.cli.base.output.history.last().tid = 123
cmd.cli.base.output.history.search = mock.MagicMock(return_value=[99])
tests.support.command_configure(cmd, ['list', '1..5', 'last', 'last-10', 'kernel'])
self.assertEqual(cmd._args2transaction_ids(), ([123, 113, 99, 5, 4, 3, 2, 1], {(1, 5)}))
class CommandTest(tests.support.DnfBaseTestCase):
REPOS = ["main"]
BASE_CLI = True
def test_canonical(self):
cmd = dnf.cli.commands.upgrade.UpgradeCommand(self.base.mock_cli())
try:
tests.support.command_run(cmd, ['cracker', 'filling'])
except dnf.exceptions.Error as e:
if e.value != 'No packages marked for upgrade.':
raise
self.assertEqual(cmd._basecmd, 'upgrade')
self.assertEqual(cmd.opts.pkg_specs, ['cracker', 'filling'])
class InstallCommandTest(tests.support.ResultTestCase):
"""Tests of ``dnf.cli.commands.install.InstallCommand`` class."""
REPOS = ["main"]
BASE_CLI = True
CLI = "mock"
def setUp(self):
"""Prepare the test fixture."""
super(InstallCommandTest, self).setUp()
self._cmd = dnf.cli.commands.install.InstallCommand(self.cli)
def test_configure(self):
tests.support.command_configure(self._cmd, ['pkg'])
self.assertFalse(self.cli.demands.allow_erasing)
self.assertTrue(self.cli.demands.sack_activation)
@mock.patch('dnf.cli.commands.install._',
dnf.pycomp.NullTranslations().ugettext)
def test_run_group_notfound(self):
"""Test whether it fails if the group cannot be found."""
stdout = dnf.pycomp.StringIO()
with tests.support.wiretap_logs('dnf', logging.INFO, stdout):
self.assertRaises(dnf.exceptions.Error,
tests.support.command_run, self._cmd, ['@non-existent'])
self.assertEqual(stdout.getvalue(), "Module or Group 'non-existent' is not available.\n")
self.assertResult(self._cmd.cli.base,
self._cmd.cli.base.sack.query().installed())
def test_run_package(self):
"""Test whether a package is installed."""
tests.support.command_run(self._cmd, ['lotus'])
self.assertResult(self.base, itertools.chain(
self.base.sack.query().installed(),
dnf.subject.Subject('lotus.x86_64').get_best_query(self.base.sack))
)
@mock.patch('dnf.cli.commands.install._',
dnf.pycomp.NullTranslations().ugettext)
def test_run_package_notfound(self):
"""Test whether it fails if the package cannot be found."""
stdout = dnf.pycomp.StringIO()
with tests.support.wiretap_logs('dnf', logging.INFO, stdout):
self.assertRaises(dnf.exceptions.Error,
tests.support.command_run, self._cmd, ['non-existent', 'lotus'])
self.assertEqual(stdout.getvalue(),
'No match for argument: non-existent\n')
self.assertResult(self.base, itertools.chain(
self.base.sack.query().installed(),
dnf.subject.Subject('lotus.x86_64').get_best_query(self.base.sack))
)
class ReinstallCommandTest(tests.support.ResultTestCase):
"""Tests of ``dnf.cli.commands.ReinstallCommand`` class."""
REPOS = ["main"]
BASE_CLI = True
CLI = "mock"
def setUp(self):
"""Prepare the test fixture."""
super(ReinstallCommandTest, self).setUp()
self._cmd = dnf.cli.commands.reinstall.ReinstallCommand(self.cli)
def test_run(self):
"""Test whether the package is installed."""
tests.support.command_run(self._cmd, ['pepper'])
self.assertResult(self.base, itertools.chain(
self.base.sack.query().installed().filter(name__neq='pepper'),
dnf.subject.Subject('pepper.x86_64').get_best_query(self.base.sack)
.available()))
@mock.patch('dnf.cli.commands.reinstall._',
dnf.pycomp.NullTranslations().ugettext)
def test_run_notinstalled(self):
"""Test whether it fails if the package is not installed."""
stdout = dnf.pycomp.StringIO()
with tests.support.wiretap_logs('dnf', logging.INFO, stdout):
self.assertRaises(dnf.exceptions.Error, tests.support.command_run, self._cmd, ['lotus'])
self.assertEqual(stdout.getvalue(), 'Package lotus available, but not installed.\n'
'No match for argument: lotus\n')
self.assertResult(self._cmd.cli.base,
self._cmd.cli.base.sack.query().installed())
@mock.patch('dnf.cli.commands.reinstall._', dnf.pycomp.NullTranslations().ugettext)
def test_run_notavailable(self):
""" Test whether it fails if the package is not available. """
holes_query = dnf.subject.Subject('hole').get_best_query(self.base.sack)
tsis = []
for pkg in holes_query.installed():
pkg._force_swdb_repoid = "unknown"
self.history.rpm.add_install(pkg)
# tsi = dnf.transaction.TransactionItem(
# dnf.transaction.INSTALL,
# installed=pkg,
# reason=libdnf.transaction.TransactionItemReason_USER
# )
# tsis.append(tsi)
self._swdb_commit(tsis)
stdout = dnf.pycomp.StringIO()
with tests.support.wiretap_logs('dnf', logging.INFO, stdout):
self.assertRaises(dnf.exceptions.Error, tests.support.command_run, self._cmd, ['hole'])
self.assertEqual(
stdout.getvalue(),
'Installed package hole-1-1.x86_64 (from unknown) not available.\n')
self.assertResult(self.base, self.base.sack.query().installed())
class RepoPkgsCommandTest(tests.support.DnfBaseTestCase):
"""Tests of ``dnf.cli.commands.RepoPkgsCommand`` class."""
REPOS = []
BASE_CLI = True
CLI = "mock"
def setUp(self):
"""Prepare the test fixture."""
super(RepoPkgsCommandTest, self).setUp()
self.cmd = dnf.cli.commands.RepoPkgsCommand(self.cli)
def test_configure_badargs(self):
"""Test whether the command fail in case of wrong args."""
with self.assertRaises(SystemExit) as exit, \
tests.support.patch_std_streams() as (stdout, stderr), \
mock.patch('logging.Logger.critical'):
tests.support.command_configure(self.cmd, [])
self.assertEqual(exit.exception.code, 2)
class RepoPkgsCheckUpdateSubCommandTest(tests.support.DnfBaseTestCase):
"""Tests of ``dnf.cli.commands.RepoPkgsCommand.CheckUpdateSubCommand`` class."""
REPOS = ['main', 'updates', 'third_party']
BASE_CLI = True
CLI = "mock"
@mock.patch('dnf.cli.term._real_term_width', return_value=80)
def test(self, _real_term_width):
""" Test whether only upgrades in the repository are listed. """
tsis = []
for pkg in self.base.sack.query().installed().filter(name='tour'):
pkg._force_swdb_repoid = "updates"
self.history.rpm.add_install(pkg)
# tsi = dnf.transaction.TransactionItem(
# dnf.transaction.INSTALL,
# installed=pkg,
# reason=libdnf.transaction.TransactionItemReason_USER
# )
# tsis.append(tsi)
self._swdb_commit(tsis)
cmd = dnf.cli.commands.RepoPkgsCommand(self.cli)
with tests.support.patch_std_streams() as (stdout, _):
tests.support.command_run(cmd, ['updates', 'check-update'])
self.assertEqual(
stdout.getvalue(),
u'\n'
u'hole.x86_64 2-1'
u' updates \n'
u'pepper.x86_64 20-1'
u' updates \n'
u'Obsoleting Packages\n'
u'hole.i686 2-1'
u' updates \n'
u' tour.noarch 5-0'
u' @updates\n'
u'hole.x86_64 2-1'
u' updates \n'
u' tour.noarch 5-0'
u' @updates\n')
self.assertEqual(self.cli.demands.success_exit_status, 100)
def test_not_found(self):
"""Test whether exit code differs if updates are not found."""
cmd = dnf.cli.commands.RepoPkgsCommand(self.cli)
tests.support.command_run(cmd, ['main', 'check-update'])
# self.assertNotEqual(self.cli.demands.success_exit_status, 100)
class RepoPkgsInfoSubCommandTest(tests.support.DnfBaseTestCase):
"""Tests of ``dnf.cli.commands.RepoPkgsCommand.InfoSubCommand`` class."""
AVAILABLE_TITLE = u'Available Packages\n'
HOLE_I686_INFO = (u'Name : hole\n'
u'Version : 2\n'
u'Release : 1\n'
u'Architecture : i686\n'
u'Size : 0.0 \n'
u'Source : None\n'
u'Repository : updates\n'
u'Summary : \n'
u'License : \n'
u'Description : \n'
u'\n')
HOLE_X86_64_INFO = (u'Name : hole\n'
u'Version : 2\n'
u'Release : 1\n'
u'Architecture : x86_64\n'
u'Size : 0.0 \n'
u'Source : None\n'
u'Repository : updates\n'
u'Summary : \n'
u'License : \n'
u'Description : \n\n')
INSTALLED_TITLE = u'Installed Packages\n'
PEPPER_SYSTEM_INFO = (u'Name : pepper\n'
u'Version : 20\n'
u'Release : 0\n'
u'Architecture : x86_64\n'
u'Size : 0.0 \n'
u'Source : None\n'
u'Repository : @System\n'
u'From repo : main\n'
u'Summary : \n'
u'License : \n'
u'Description : \n\n')
PEPPER_UPDATES_INFO = (u'Name : pepper\n'
u'Version : 20\n'
u'Release : 1\n'
u'Architecture : x86_64\n'
u'Size : 0.0 \n'
u'Source : None\n'
u'Repository : updates\n'
u'Summary : \n'
u'License : \n'
u'Description : \n\n')
REPOS = ['main', 'updates', 'third_party']
BASE_CLI = True
CLI = "mock"
def setUp(self):
"""Prepare the test fixture."""
super(RepoPkgsInfoSubCommandTest, self).setUp()
self.base.conf.recent = 7
def test_info_all(self):
"""Test whether only packages related to the repository are listed."""
tsis = []
for pkg in self.base.sack.query().installed().filter(name='pepper'):
pkg._force_swdb_repoid = "main"
self.history.rpm.add_install(pkg)
# tsi = dnf.transaction.TransactionItem(
# dnf.transaction.INSTALL,
# installed=pkg,
# reason=libdnf.transaction.TransactionItemReason_USER
# )
# tsis.append(tsi)
self._swdb_commit(tsis)
cmd = dnf.cli.commands.RepoPkgsCommand(self.cli)
with tests.support.patch_std_streams() as (stdout, _):
tests.support.command_run(cmd, ['main', 'info', 'all', '*p*'])
self.assertEqual(
stdout.getvalue(),
''.join((
self.INSTALLED_TITLE,
self.PEPPER_SYSTEM_INFO,
self.AVAILABLE_TITLE,
u'Name : pepper\n'
u'Version : 20\n'
u'Release : 0\n'
u'Architecture : src\n'
u'Size : 0.0 \n'
u'Source : None\n'
u'Repository : main\n'
u'Summary : \n'
u'License : \n'
u'Description : \n'
u'\n',
u'Name : trampoline\n'
u'Version : 2.1\n'
u'Release : 1\n'
u'Architecture : noarch\n'
u'Size : 0.0 \n'
u'Source : None\n'
u'Repository : main\n'
u'Summary : \n'
u'License : \n'
u'Description : \n'
u'\n')))
def test_info_available(self):
"""Test whether only packages in the repository are listed."""
cmd = dnf.cli.commands.RepoPkgsCommand(self.cli)
with tests.support.patch_std_streams() as (stdout, _):
tests.support.command_run(cmd, ['updates', 'info', 'available'])
self.assertEqual(
stdout.getvalue(),
''.join((
self.AVAILABLE_TITLE,
self.HOLE_I686_INFO,
self.HOLE_X86_64_INFO,
self.PEPPER_UPDATES_INFO)))
def test_info_extras(self):
"""Test whether only extras installed from the repository are listed."""
tsis = []
for pkg in self.base.sack.query().installed().filter(name='test'):
pkg._force_swdb_repoid = "main"
self.history.rpm.add_install(pkg)
self._swdb_commit(tsis)
cmd = dnf.cli.commands.RepoPkgsCommand(self.cli)
with tests.support.patch_std_streams() as (stdout, _):
tests.support.command_run(cmd, ['main', 'info', 'extras'])
self.assertEqual(
stdout.getvalue(),
u'Extra Packages\n'
u'Name : test\n'
u'Version : 1\n'
u'Release : 0\n'
u'Architecture : noarch\n'
u'Size : 0.0 \n'
u'Source : None\n'
u'Repository : @System\n'
u'From repo : main\n'
u'Summary : \n'
u'License : \n'
u'Description : \n\n')
def test_info_installed(self):
"""Test whether only packages installed from the repository are listed."""
tsis = []
for pkg in self.base.sack.query().installed().filter(name='pepper'):
pkg._force_swdb_repoid = "main"
self.history.rpm.add_install(pkg)
# tsi = dnf.transaction.TransactionItem(
# dnf.transaction.INSTALL,
# installed=pkg,
# reason=libdnf.transaction.TransactionItemReason_USER
# )
# tsis.append(tsi)
self._swdb_commit(tsis)
cmd = dnf.cli.commands.RepoPkgsCommand(self.cli)
with tests.support.patch_std_streams() as (stdout, _):
tests.support.command_run(cmd, ['main', 'info', 'installed'])
self.assertEqual(
stdout.getvalue(),
''.join((self.INSTALLED_TITLE, self.PEPPER_SYSTEM_INFO)))
def test_info_obsoletes(self):
"""Test whether only obsoletes in the repository are listed."""
cmd = dnf.cli.commands.RepoPkgsCommand(self.cli)
with tests.support.patch_std_streams() as (stdout, _):
tests.support.command_run(cmd, ['updates', 'info', 'obsoletes'])
self.assertEqual(
stdout.getvalue(),
''.join((
u'Obsoleting Packages\n',
self.HOLE_I686_INFO,
self.HOLE_X86_64_INFO)))
def test_info_upgrades(self):
"""Test whether only upgrades in the repository are listed."""
cmd = dnf.cli.commands.RepoPkgsCommand(self.cli)
with tests.support.patch_std_streams() as (stdout, _):
tests.support.command_run(cmd, ['updates', 'info', 'upgrades'])
self.assertEqual(stdout.getvalue(), ''.join((
u'Available Upgrades\n', self.HOLE_X86_64_INFO, self.PEPPER_UPDATES_INFO)))
class RepoPkgsInstallSubCommandTest(tests.support.ResultTestCase):
"""Tests of ``dnf.cli.commands.RepoPkgsCommand.InstallSubCommand`` class."""
REPOS = ['main', 'third_party']
BASE_CLI = True
CLI = "mock"
def test_all(self):
"""Test whether all packages from the repository are installed."""
cmd = dnf.cli.commands.RepoPkgsCommand(self.cli)
tests.support.command_run(cmd, ['third_party', 'install'])
q = self.base.sack.query()
self.assertResult(self.base, itertools.chain(
q.installed(),
q.available().filter(reponame='third_party', arch='x86_64', name__neq='hole'))
)
class RepoPkgsMoveToSubCommandTest(tests.support.ResultTestCase):
"""Tests of ``dnf.cli.commands.RepoPkgsCommand.MoveToSubCommand`` class."""
REPOS = ['distro', 'main']
BASE_CLI = True
CLI = "mock"
def test_all(self):
"""Test whether only packages in the repository are installed."""
cmd = dnf.cli.commands.RepoPkgsCommand(self.cli)
tests.support.command_run(cmd, ['distro', 'move-to'])
self.assertResult(self.base, itertools.chain(
self.base.sack.query().installed().filter(name__neq='tour'),
dnf.subject.Subject('tour-5-0').get_best_query(self.base.sack)
.available()))
class RepoPkgsReinstallOldSubCommandTest(tests.support.ResultTestCase):
"""Tests of ``dnf.cli.commands.RepoPkgsCommand.ReinstallOldSubCommand`` class."""
REPOS = ["main"]
BASE_CLI = True
CLI = "mock"
def test_all(self):
"""Test whether all packages from the repository are reinstalled."""
tsis = []
for pkg in self.base.sack.query().installed():
reponame = 'main' if pkg.name != 'pepper' else 'non-main'
pkg._force_swdb_repoid = reponame
self.history.rpm.add_install(pkg)
# tsi = dnf.transaction.TransactionItem(
# dnf.transaction.INSTALL,
# installed=pkg,
# reason=libdnf.transaction.TransactionItemReason_USER
# )
# tsis.append(tsi)
self._swdb_commit(tsis)
cmd = dnf.cli.commands.RepoPkgsCommand(self.cli)
tests.support.command_run(cmd, ['main', 'reinstall-old'])
self.assertResult(self.base, itertools.chain(
self.base.sack.query().installed().filter(name__neq='librita'),
dnf.subject.Subject('librita.i686').get_best_query(self.base.sack).installed(),
dnf.subject.Subject('librita').get_best_query(self.base.sack).available())
)
class RepoPkgsReinstallSubCommandTest(tests.support.DnfBaseTestCase):
"""Tests of ``dnf.cli.commands.RepoPkgsCommand.ReinstallSubCommand`` class."""
REPOS = ["main"]
BASE_CLI = True
CLI = "mock"
def setUp(self):
"""Prepare the test fixture."""
super(RepoPkgsReinstallSubCommandTest, self).setUp()
self.mock = mock.Mock()
old_run_patcher = mock.patch(
'dnf.cli.commands.RepoPkgsCommand.ReinstallOldSubCommand.run_on_repo',
self.mock.reinstall_old_run)
move_run_patcher = mock.patch(
'dnf.cli.commands.RepoPkgsCommand.MoveToSubCommand.run_on_repo',
self.mock.move_to_run)
old_run_patcher.start()
self.addCleanup(old_run_patcher.stop)
move_run_patcher.start()
self.addCleanup(move_run_patcher.stop)
def test_all_fails(self):
"""Test whether it fails if everything fails."""
self.mock.reinstall_old_run.side_effect = dnf.exceptions.Error('test')
self.mock.move_to_run.side_effect = dnf.exceptions.Error('test')
cmd = dnf.cli.commands.RepoPkgsCommand(self.cli)
self.assertRaises(
dnf.exceptions.Error,
tests.support.command_run,
cmd,
['main', 'reinstall']
)
self.assertEqual(self.mock.mock_calls,
[mock.call.reinstall_old_run(),
mock.call.move_to_run()])
def test_all_moveto(self):
"""Test whether reinstall-old is called first and move-to next."""
self.mock.reinstall_old_run.side_effect = dnf.exceptions.Error('test')
cmd = dnf.cli.commands.RepoPkgsCommand(self.cli)
tests.support.command_run(cmd, ['main', 'reinstall'])
self.assertEqual(self.mock.mock_calls,
[mock.call.reinstall_old_run(),
mock.call.move_to_run()])
def test_all_reinstallold(self):
"""Test whether only reinstall-old is called."""
cmd = dnf.cli.commands.RepoPkgsCommand(self.cli)
tests.support.command_run(cmd, ['main', 'reinstall'])
self.assertEqual(self.mock.mock_calls,
[mock.call.reinstall_old_run()])
class RepoPkgsRemoveOrDistroSyncSubCommandTest(tests.support.ResultTestCase):
"""Tests of ``RemoveOrDistroSyncSubCommand`` class."""
REPOS = ["distro"]
BASE_CLI = True
CLI = "mock"
def test_run_on_repo_spec_sync(self):
"""Test running with a package which can be synchronized."""
tsis = []
for pkg in self.base.sack.query().installed():
reponame = 'non-distro' if pkg.name == 'pepper' else 'distro'
pkg._force_swdb_repoid = reponame
self.history.rpm.add_install(pkg)
# tsi = dnf.transaction.TransactionItem(
# dnf.transaction.INSTALL,
# installed=pkg,
# reason=libdnf.transaction.TransactionItemReason_USER
# )
# tsis.append(tsi)
self._swdb_commit(tsis)
cmd = dnf.cli.commands.RepoPkgsCommand(self.cli)
tests.support.command_run(cmd, ['non-distro', 'remove-or-distro-sync', 'pepper'])
self.assertResult(self.base, itertools.chain(
self.base.sack.query().installed().filter(name__neq='pepper'),
dnf.subject.Subject('pepper').get_best_query(self.base.sack)
.available()))
def test_run_on_repo_spec_remove(self):
"""Test running with a package which must be removed."""
tsis = []
for pkg in self.base.sack.query().installed():
reponame = 'non-distro' if pkg.name == 'hole' else 'distro'
pkg._force_swdb_repoid = reponame
self.history.rpm.add_install(pkg)
# tsi = dnf.transaction.TransactionItem(
# dnf.transaction.INSTALL,
# installed=pkg,
# reason=libdnf.transaction.TransactionItemReason_USER
# )
# tsis.append(tsi)
self._swdb_commit(tsis)
cmd = dnf.cli.commands.RepoPkgsCommand(self.cli)
tests.support.command_run(cmd, ['non-distro', 'remove-or-distro-sync', 'hole'])
self.assertResult(
self.base,
self.base.sack.query().installed().filter(name__neq='hole'))
def test_run_on_repo_all(self):
"""Test running without a package specification."""
nondist = {'pepper', 'hole'}
tsis = []
for pkg in self.base.sack.query().installed():
reponame = 'non-distro' if pkg.name in nondist else 'distro'
pkg._force_swdb_repoid = reponame
self.history.rpm.add_install(pkg)
# tsi = dnf.transaction.TransactionItem(
# dnf.transaction.INSTALL,
# installed=pkg,
# reason=libdnf.transaction.TransactionItemReason_USER
# )
# tsis.append(tsi)
self._swdb_commit(tsis)
cmd = dnf.cli.commands.RepoPkgsCommand(self.cli)
tests.support.command_run(cmd, ['non-distro', 'remove-or-distro-sync'])
self.assertResult(self.base, itertools.chain(
self.base.sack.query().installed().filter(name__neq='pepper')
.filter(name__neq='hole'),
dnf.subject.Subject('pepper').get_best_query(self.base.sack)
.available()))
@mock.patch('dnf.cli.commands._', dnf.pycomp.NullTranslations().ugettext)
def test_run_on_repo_spec_notinstalled(self):
"""Test running with a package which is not installed."""
stdout = dnf.pycomp.StringIO()
cmd = dnf.cli.commands.RepoPkgsCommand(self.cli)
with tests.support.wiretap_logs('dnf', logging.INFO, stdout):
self.assertRaises(dnf.exceptions.Error,
tests.support.command_run, cmd,
['non-distro', 'remove-or-distro-sync', 'not-installed'])
self.assertIn('No match for argument: not-installed\n', stdout.getvalue(),
'mismatch not logged')
@mock.patch('dnf.cli.commands._', dnf.pycomp.NullTranslations().ugettext)
def test_run_on_repo_all_notinstalled(self):
"""Test running with a repository from which nothing is installed."""
stdout = dnf.pycomp.StringIO()
cmd = dnf.cli.commands.RepoPkgsCommand(self.cli)
with tests.support.wiretap_logs('dnf', logging.INFO, stdout):
self.assertRaises(dnf.exceptions.Error,
tests.support.command_run, cmd,
['non-distro', 'remove-or-distro-sync'])
self.assertIn('No package installed from the repository.\n',
stdout.getvalue(), 'mismatch not logged')
class RepoPkgsRemoveOrReinstallSubCommandTest(tests.support.ResultTestCase):
"""Tests of ``dnf.cli.commands.RepoPkgsCommand.RemoveOrReinstallSubCommand`` class."""
REPOS = ["distro"]
BASE_CLI = True
def setUp(self):
"""Prepare the test fixture."""
super(RepoPkgsRemoveOrReinstallSubCommandTest, self).setUp()
self.cli = self.base.mock_cli()
def test_all_not_installed(self):
"""Test whether it fails if no package is installed from the repository."""
cmd = dnf.cli.commands.RepoPkgsCommand(self.cli)
self.assertRaises(dnf.exceptions.Error,
tests.support.command_run, cmd,
['non-distro', 'remove-or-distro-sync'])
self.assertResult(self.base, self.base.sack.query().installed())
def test_all_reinstall(self):
"""Test whether all packages from the repository are reinstalled."""
tsis = []
for pkg in self.base.sack.query().installed():
reponame = 'distro' if pkg.name != 'tour' else 'non-distro'
pkg._force_swdb_repoid = reponame
self.history.rpm.add_install(pkg)
# tsi = dnf.transaction.TransactionItem(
# dnf.transaction.INSTALL,
# installed=pkg,
# reason=libdnf.transaction.TransactionItemReason_USER
# )
# tsis.append(tsi)
self._swdb_commit(tsis)
cmd = dnf.cli.commands.RepoPkgsCommand(self.cli)
tests.support.command_run(cmd, ['non-distro', 'remove-or-reinstall'])
self.assertResult(self.base, itertools.chain(
self.base.sack.query().installed().filter(name__neq='tour'),
dnf.subject.Subject('tour').get_best_query(self.base.sack).available())
)
def test_all_remove(self):
"""Test whether all packages from the repository are removed."""
tsis = []
for pkg in self.base.sack.query().installed():
reponame = 'distro' if pkg.name != 'hole' else 'non-distro'
pkg._force_swdb_repoid = reponame
self.history.rpm.add_install(pkg)
# tsi = dnf.transaction.TransactionItem(
# dnf.transaction.INSTALL,
# installed=pkg,
# reason=libdnf.transaction.TransactionItemReason_USER
# )
# tsis.append(tsi)
self._swdb_commit(tsis)
cmd = dnf.cli.commands.RepoPkgsCommand(self.cli)
tests.support.command_run(cmd, ['non-distro', 'remove-or-reinstall'])
self.assertResult(
self.base,
self.base.sack.query().installed().filter(name__neq='hole'))
class RepoPkgsRemoveSubCommandTest(tests.support.ResultTestCase):
"""Tests of ``dnf.cli.commands.RepoPkgsCommand.RemoveSubCommand`` class."""
REPOS = ["main"]
BASE_CLI = True
CLI = "mock"
def test_all(self):
"""Test whether only packages from the repository are removed."""
tsis = []
for pkg in self.base.sack.query().installed():
reponame = 'main' if pkg.name == 'pepper' else 'non-main'
pkg._force_swdb_repoid = reponame
self.history.rpm.add_install(pkg)
# tsi = dnf.transaction.TransactionItem(
# dnf.transaction.INSTALL,
# installed=pkg,
# reason=libdnf.transaction.TransactionItemReason_USER
# )
# tsis.append(tsi)
self._swdb_commit(tsis)
cmd = dnf.cli.commands.RepoPkgsCommand(self.cli)
tests.support.command_run(cmd, ['main', 'remove'])
self.assertResult(
self.base,
self.base.sack.query().installed().filter(name__neq='pepper')
)
class RepoPkgsUpgradeSubCommandTest(tests.support.ResultTestCase):
"""Tests of ``dnf.cli.commands.RepoPkgsCommand.UpgradeSubCommand`` class."""
REPOS = ["updates", "third_party"]
BASE_CLI = True
CLI = "mock"
def test_all(self):
"""Test whether all packages from the repository are installed."""
cmd = dnf.cli.commands.RepoPkgsCommand(self.cli)
tests.support.command_run(cmd, ['third_party', 'upgrade'])
q = self.base.sack.query()
self.assertResult(self.base, itertools.chain(
q.installed().filter(name__neq='hole'),
q.upgrades().filter(reponame='third_party', arch='x86_64'))
)
class UpgradeCommandTest(tests.support.ResultTestCase):
"""Tests of ``dnf.cli.commands.upgrade.UpgradeCommand`` class."""
REPOS = ["updates"]
BASE_CLI = True
CLI = "mock"
def setUp(self):
super(UpgradeCommandTest, self).setUp()
self.cmd = dnf.cli.commands.upgrade.UpgradeCommand(self.cli)
def test_run(self):
"""Test whether a package is updated."""
tests.support.command_run(self.cmd, ['pepper'])
self.assertResult(self.cmd.base, itertools.chain(
self.cmd.base.sack.query().installed().filter(name__neq='pepper'),
self.cmd.base.sack.query().upgrades().filter(name='pepper')))
@mock.patch('dnf.cli.commands.upgrade._',
dnf.pycomp.NullTranslations().ugettext)
def test_updatePkgs_notfound(self):
"""Test whether it fails if the package cannot be found."""
stdout = dnf.pycomp.StringIO()
with tests.support.wiretap_logs('dnf', logging.INFO, stdout):
self.assertRaises(dnf.exceptions.Error,
tests.support.command_run, self.cmd, ['non-existent'])
self.assertEqual(stdout.getvalue(),
'No match for argument: non-existent\n')
self.assertResult(self.cmd.base, self.cmd.base.sack.query().installed())
| 34,689
|
Python
|
.py
| 709
| 38.981664
| 100
| 0.58964
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,819
|
test_queries.py
|
rpm-software-management_dnf/tests/test_queries.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf.query
import dnf.subject
import tests.support
class QueriesTest(tests.support.TestCase):
def setUp(self):
self.sack = tests.support.mock_sack('main', 'updates')
def test_duplicities(self):
pepper = self.sack.query().installed().filter(name="pepper")
# make sure 'pepper' package exists:
self.assertEqual(len(pepper), 1)
# we shouldn't see it more than once with a tricky query below:
res = self.sack.query().installed().filter(name=["pep*", "*per"])
res_set = set(res)
self.assertEqual(len(res), len(res_set))
def test_by_file(self):
# check sanity first:
q = self.sack.query().filter(file__eq="/raised/smile")
self.assertEqual(len(q.run()), 1)
q[0]
def test_by_repo(self):
pkgs = self.sack.query().filter(reponame__eq="updates")
self.assertEqual(len(pkgs), tests.support.UPDATES_NSOLVABLES)
pkgs = self.sack.query().filter(reponame__eq="main")
self.assertEqual(len(pkgs), tests.support.MAIN_NSOLVABLES)
def test_duplicated(self):
pkgs = self.sack.query().duplicated()
self.assertEqual(len(pkgs), 3)
def test_extras(self):
pkgs = self.sack.query().extras()
self.assertEqual(len(pkgs), tests.support.TOTAL_RPMDB_COUNT - 4)
def test_installed_exact(self):
pkgs = self.sack.query().installed()._nevra("tour-4.9-0.noarch")
self.assertEqual(len(pkgs), 0)
pkgs = self.sack.query().installed()._nevra("tour-5-0.x86_64")
self.assertEqual(len(pkgs), 0)
pkgs = self.sack.query().installed()._nevra("tour-5-0.noarch")
self.assertEqual(len(pkgs), 1)
def test_latest(self):
tours = self.sack.query().filter(name="tour")
all_tours = sorted(tours.run(), reverse=True)
head2 = all_tours[0:2]
tail2 = all_tours[2:]
pkgs = tours.latest(2).run()
self.assertEqual(pkgs, head2)
pkgs = tours.latest(-2).run()
self.assertEqual(pkgs, tail2)
class SubjectTest(tests.support.TestCase):
def setUp(self):
self.sack = tests.support.mock_sack('main', 'updates')
def test_wrong_name(self):
subj = dnf.subject.Subject("call-his-wife-in")
self.assertLength(subj.get_best_query(self.sack), 0)
def test_query_composing(self):
q = dnf.subject.Subject("librita").get_best_query(self.sack)
q = q.filter(arch="i686")
self.assertEqual(str(q[0]), "librita-1-1.i686")
def test_icase_name(self):
subj = dnf.subject.Subject("PEpper", ignore_case=True)
q = subj.get_best_query(self.sack)
self.assertLength(q, 4)
def test_get_best_selector(self):
s = dnf.subject.Subject("pepper-20-0.x86_64").get_best_selector(self.sack)
self.assertIsNotNone(s)
def test_get_best_selector_for_provides_glob(self):
s = dnf.subject.Subject("*otus.so*").get_best_selector(self.sack)
self.assertIsNotNone(s)
def test_best_selector_for_version(self):
sltr = dnf.subject.Subject("hole-2").get_best_selector(self.sack)
self.assertCountEqual(map(str, sltr.matches()),
['hole-2-1.x86_64', 'hole-2-1.i686'])
def test_with_confusing_dashes(self):
sltr = dnf.subject.Subject("mrkite-k-h").get_best_selector(self.sack)
self.assertLength(sltr.matches(), 1)
sltr = dnf.subject.Subject("mrkite-k-h.x86_64").get_best_selector(self.sack)
self.assertLength(sltr.matches(), 1)
class DictsTest(tests.support.TestCase):
def setUp(self):
self.sack = tests.support.mock_sack('main', 'updates')
def test_per_nevra_dict(self):
pkgs = self.sack.query().filter(name="lotus")
dct = dnf.query._per_nevra_dict(pkgs)
self.assertCountEqual(dct.keys(),
["lotus-3-16.x86_64", "lotus-3-16.i686"])
test_list = []
for list_items in dct.values():
for item in list_items:
test_list.append(item)
self.assertCountEqual(test_list, pkgs)
| 5,174
|
Python
|
.py
| 107
| 41.102804
| 84
| 0.661374
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,820
|
test_sanity.py
|
rpm-software-management_dnf/tests/test_sanity.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import os
import sys
import tests.support
class Sanity(tests.support.TestCase):
def test_sanity(self):
assert(os.access(tests.support.repo("@System.repo"), os.R_OK))
sack = tests.support.mock_sack()
assert(sack)
self.assertEqual(len(sack), tests.support.SYSTEM_NSOLVABLES)
sack2 = tests.support.MockBase("main", "updates").sack
self.assertEqual(len(sack2), tests.support.TOTAL_NSOLVABLES)
def test_toplevel(self):
self.assertIn(tests.support.dnf_toplevel(), sys.path)
| 1,602
|
Python
|
.py
| 32
| 46.8125
| 77
| 0.752241
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,821
|
test_main.py
|
rpm-software-management_dnf/tests/test_main.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
"""Tests of the CLI entry point."""
from __future__ import unicode_literals
import dnf.cli.main
import dnf.logging
import dnf.pycomp
import tests.support
class MainTest(tests.support.TestCase):
"""Tests the ``dnf.cli.main`` module."""
def test_ex_IOError_logs_traceback(self):
"""Test whether the traceback is logged if an error is raised."""
lvl = dnf.logging.SUBDEBUG
out = dnf.pycomp.StringIO()
with tests.support.wiretap_logs('dnf', lvl, out):
try:
raise OSError('test_ex_IOError_logs_traceback')
except OSError as e:
dnf.cli.main.ex_IOError(e)
self.assertTracebackIn('OSError: test_ex_IOError_logs_traceback\n',
out.getvalue())
| 1,761
|
Python
|
.py
| 36
| 43.888889
| 77
| 0.716035
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,822
|
test_base.py
|
rpm-software-management_dnf/tests/test_base.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import binascii
import itertools
import re
import hawkey
import libdnf.transaction
import rpm
import dnf
import dnf.exceptions
import dnf.package
import dnf.subject
import dnf.transaction
import tests.support
from tests.support import mock
class BaseTest(tests.support.TestCase):
@staticmethod
def _setup_packages(history):
pkg = tests.support.MockPackage('pepper-20-0.x86_64')
pkg._force_swdb_repoid = "main"
history.rpm.add_install(pkg)
history.beg("", [], [])
for tsi in history._swdb.getItems():
if tsi.getState() == libdnf.transaction.TransactionItemState_UNKNOWN:
tsi.setState(libdnf.transaction.TransactionItemState_DONE)
history.end("")
history.close()
def test_instance(self):
base = tests.support.MockBase()
self.assertIsNotNone(base)
base.close()
@mock.patch('dnf.rpm.detect_releasever', lambda x: 'x')
@mock.patch('dnf.util.am_i_root', lambda: True)
def test_default_config_root(self):
base = dnf.Base()
self.assertIsNotNone(base.conf)
self.assertIsNotNone(base.conf.cachedir)
reg = re.compile('/var/cache/dnf')
self.assertIsNotNone(reg.match(base.conf.cachedir))
base.close()
@mock.patch('dnf.rpm.detect_releasever', lambda x: 'x')
@mock.patch('dnf.util.am_i_root', lambda: False)
def test_default_config_user(self):
base = dnf.Base()
self.assertIsNotNone(base.conf)
self.assertIsNotNone(base.conf.cachedir)
reg = re.compile('/var/tmp/dnf-[a-zA-Z0-9_-]+')
self.assertIsNotNone(reg.match(base.conf.cachedir))
base.close()
def test_reset(self):
base = tests.support.MockBase('main')
base.reset(sack=True, repos=False)
self.assertIsNone(base._sack)
self.assertLength(base.repos, 1)
base.close()
@mock.patch('dnf.rpm.transaction.TransactionWrapper')
def test_ts(self, mock_ts):
base = dnf.Base()
self.assertEqual(base._priv_ts, None)
ts = base._ts
# check the setup is correct
ts.setFlags.call_args.assert_called_with(0)
flags = ts.setProbFilter.call_args[0][0]
self.assertTrue(flags & rpm.RPMPROB_FILTER_OLDPACKAGE)
self.assertFalse(flags & rpm.RPMPROB_FILTER_REPLACEPKG)
# check file conflicts are reported:
self.assertFalse(flags & rpm.RPMPROB_FILTER_REPLACENEWFILES)
# check we can close the connection
del base._ts
self.assertEqual(base._priv_ts, None)
ts.close.assert_called_once_with()
base.close()
def test_iter_userinstalled(self):
"""Test iter_userinstalled with a package installed by the user."""
base = tests.support.MockBase()
self._setup_packages(base.history)
base._sack = tests.support.mock_sack('main')
pkg, = base.sack.query().installed().filter(name='pepper')
# reason and repo are set in _setup_packages() already
self.assertEqual(base.history.user_installed(pkg), True)
self.assertEqual(base.history.repo(pkg), 'main')
base.close()
def test_iter_userinstalled_badfromrepo(self):
"""Test iter_userinstalled with a package installed from a bad repository."""
base = tests.support.MockBase()
base._sack = tests.support.mock_sack('main')
self._setup_packages(base.history)
history = base.history
pkg = tests.support.MockPackage('pepper-20-0.x86_64')
pkg._force_swdb_repoid = "anakonda"
history.rpm.add_install(pkg)
history.beg("", [], [])
for tsi in history._swdb.getItems():
if tsi.getState() == libdnf.transaction.TransactionItemState_UNKNOWN:
tsi.setState(libdnf.transaction.TransactionItemState_DONE)
history.end("")
history.close()
pkg, = base.sack.query().installed().filter(name='pepper')
self.assertEqual(base.history.user_installed(pkg), True)
self.assertEqual(base.history.repo(pkg), 'anakonda')
base.close()
def test_iter_userinstalled_badreason(self):
"""Test iter_userinstalled with a package installed for a wrong reason."""
base = tests.support.MockBase()
base._sack = tests.support.mock_sack('main')
self._setup_packages(base.history)
history = base.history
pkg = tests.support.MockPackage('pepper-20-0.x86_64')
pkg._force_swdb_repoid = "main"
history.rpm.add_install(pkg, reason=libdnf.transaction.TransactionItemReason_DEPENDENCY)
history.beg("", [], [])
for tsi in history._swdb.getItems():
if tsi.getState() == libdnf.transaction.TransactionItemState_UNKNOWN:
tsi.setState(libdnf.transaction.TransactionItemState_DONE)
history.end("")
history.close()
pkg, = base.sack.query().installed().filter(name='pepper')
self.assertEqual(base.history.user_installed(pkg), False)
self.assertEqual(base.history.repo(pkg), 'main')
base.close()
class MockBaseTest(tests.support.DnfBaseTestCase):
"""Test the Base methods that need a Sack."""
REPOS = ["main"]
INIT_SACK = True
def test_add_remote_rpms(self):
pkgs = self.base.add_remote_rpms([tests.support.TOUR_50_PKG_PATH])
self.assertIsInstance(pkgs[0], dnf.package.Package)
self.assertEqual(pkgs[0].name, 'tour')
class BuildTransactionTest(tests.support.DnfBaseTestCase):
REPOS = ["updates"]
def test_resolve(self):
self.base.upgrade("pepper")
self.assertTrue(self.base.resolve())
self.base._ds_callback.assert_has_calls([
mock.call.start(),
mock.call.pkg_added(mock.ANY, 'ud'),
mock.call.pkg_added(mock.ANY, 'u')
])
self.assertLength(self.base.transaction, 2)
# verify transaction test helpers
HASH = "68e9ded8ea25137c964a638f12e9987c"
def mock_sack_fn():
return (lambda base: tests.support.TestSack(tests.support.REPO_DIR, base))
@property
def ret_pkgid(self):
return self.name
class VerifyTransactionTest(tests.support.DnfBaseTestCase):
REPOS = ["main"]
INIT_TRANSACTION = True
@mock.patch('dnf.sack._build_sack', new_callable=mock_sack_fn)
@mock.patch('dnf.package.Package._pkgid', ret_pkgid) # neutralize @property
def test_verify_transaction(self, unused_build_sack):
# we don't simulate the transaction itself here, just "install" what is
# already there and "remove" what is not.
tsis = []
new_pkg = self.base.sack.query().available().filter(name="pepper")[1]
new_pkg._chksum = (hawkey.CHKSUM_MD5, binascii.unhexlify(HASH))
new_pkg.repo = mock.Mock()
new_pkg._force_swdb_repoid = "main"
self.history.rpm.add_install(new_pkg)
removed_pkg = self.base.sack.query().available().filter(name="mrkite")[0]
removed_pkg._force_swdb_repoid = "main"
self.history.rpm.add_remove(removed_pkg)
self._swdb_commit(tsis)
self.base._verify_transaction()
pkg = self.base.history.package_data(new_pkg)
self.assertEqual(pkg.ui_from_repo(), '@main')
self.assertEqual(pkg.action_name, "Install")
self.assertEqual(pkg.get_reason(), libdnf.transaction.TransactionItemReason_USER)
class InstallReasonTest(tests.support.ResultTestCase):
REPOS = ["main"]
def test_reason(self):
self.base.install("mrkite")
self.base.resolve()
new_pkgs = self.base._transaction._get_items(dnf.transaction.PKG_INSTALL)
pkg_reasons = [(tsi.name, tsi.reason) for tsi in new_pkgs]
self.assertCountEqual([
("mrkite", libdnf.transaction.TransactionItemReason_USER),
("trampoline", libdnf.transaction.TransactionItemReason_DEPENDENCY)],
pkg_reasons
)
class InstalledMatchingTest(tests.support.ResultTestCase):
REPOS = ["main"]
def test_query_matching(self):
subj = dnf.subject.Subject("pepper")
query = subj.get_best_query(self.sack)
inst, avail = self.base._query_matches_installed(query)
self.assertCountEqual(['pepper-20-0.x86_64'], map(str, inst))
self.assertCountEqual(['pepper-20-0.src'], map(str, itertools.chain.from_iterable(avail)))
def test_selector_matching(self):
subj = dnf.subject.Subject("pepper")
sltr = subj.get_best_selector(self.sack)
inst = self.base._sltr_matches_installed(sltr)
self.assertCountEqual(['pepper-20-0.x86_64'], map(str, inst))
class CompsTest(tests.support.DnfBaseTestCase):
# Also see test_comps.py
REPOS = ["main"]
COMPS = True
def test_read_comps(self):
self.assertLength(self.base.comps.groups, tests.support.TOTAL_GROUPS)
def test_read_comps_disabled(self):
self.base.repos['main'].enablegroups = False
self.assertEmpty(self.base.read_comps())
class Goal2TransactionTest(tests.support.DnfBaseTestCase):
REPOS = ["main", "updates"]
def test_upgrade(self):
self.base.upgrade("hole")
self.assertTrue(self.base._run_hawkey_goal(self.goal, allow_erasing=False))
ts = self.base._goal2transaction(self.goal)
self.assertLength(ts, 3)
tsis = list(ts)
tsi = tsis[0]
self.assertEqual(str(tsi.pkg), "hole-2-1.x86_64")
self.assertEqual(tsi.action, libdnf.transaction.TransactionItemAction_UPGRADE)
tsi = tsis[1]
self.assertEqual(str(tsi.pkg), "hole-1-1.x86_64")
self.assertEqual(tsi.action, libdnf.transaction.TransactionItemAction_UPGRADED)
tsi = tsis[2]
self.assertEqual(str(tsi.pkg), "tour-5-0.noarch")
self.assertEqual(tsi.action, libdnf.transaction.TransactionItemAction_OBSOLETED)
| 10,920
|
Python
|
.py
| 237
| 38.742616
| 98
| 0.677905
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,823
|
__init__.py
|
rpm-software-management_dnf/tests/__init__.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
import locale
import os
# run tests with C locales
os.environ["LC_ALL"] = "C.UTF-8"
os.environ["LANG"] = "C.UTF-8"
os.environ["LANGUAGE"] = "en_US:en"
locale.setlocale(locale.LC_ALL, "C.UTF-8")
| 1,180
|
Python
|
.py
| 24
| 48.041667
| 77
| 0.764961
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,824
|
mock.py
|
rpm-software-management_dnf/tests/mock.py
|
# mock.py
# Test tools for mocking and patching.
# Copyright (C) 2007-2012 Michael Foord & the mock team
# E-mail: fuzzyman AT voidspace DOT org DOT uk
# mock 1.0.1
# http://www.voidspace.org.uk/python/mock/
# Released subject to the BSD License
# Please see http://www.voidspace.org.uk/python/license.shtml
__all__ = (
'Mock',
'MagicMock',
'patch',
'sentinel',
'DEFAULT',
'ANY',
'call',
'create_autospec',
'FILTER_DIR',
'NonCallableMock',
'NonCallableMagicMock',
'mock_open',
'PropertyMock',
)
__version__ = '1.0.1'
import pprint
import sys
try:
import inspect
except ImportError:
# for alternative platforms that
# may not have inspect
inspect = None
try:
from functools import wraps as original_wraps
except ImportError:
# Python 2.4 compatibility
def wraps(original):
def inner(f):
f.__name__ = original.__name__
f.__doc__ = original.__doc__
f.__module__ = original.__module__
wrapped = getattr(original, '__wrapped__', original)
f.__wrapped__ = wrapped
return f
return inner
else:
if sys.version_info[:2] >= (3, 2):
wraps = original_wraps
else:
def wraps(func):
def inner(f):
f = original_wraps(func)(f)
wrapped = getattr(func, '__wrapped__', func)
f.__wrapped__ = wrapped
return f
return inner
try:
unicode
except NameError:
# Python 3
basestring = unicode = str
try:
long
except NameError:
# Python 3
long = int
try:
BaseException
except NameError:
# Python 2.4 compatibility
BaseException = Exception
try:
next
except NameError:
def next(obj):
return obj.next()
BaseExceptions = (BaseException,)
if 'java' in sys.platform:
# jython
import java
BaseExceptions = (BaseException, java.lang.Throwable)
try:
_isidentifier = str.isidentifier
except AttributeError:
# Python 2.X
import keyword
import re
regex = re.compile(r'^[a-z_][a-z0-9_]*$', re.I)
def _isidentifier(string):
if string in keyword.kwlist:
return False
return regex.match(string)
inPy3k = sys.version_info[0] == 3
# Needed to work around Python 3 bug where use of "super" interferes with
# defining __class__ as a descriptor
_super = super
self = 'im_self'
builtin = '__builtin__'
if inPy3k:
self = '__self__'
builtin = 'builtins'
FILTER_DIR = True
def _is_instance_mock(obj):
# can't use isinstance on Mock objects because they override __class__
# The base class for all mocks is NonCallableMock
return issubclass(type(obj), NonCallableMock)
def _is_exception(obj):
return (
isinstance(obj, BaseExceptions) or
isinstance(obj, ClassTypes) and issubclass(obj, BaseExceptions)
)
class _slotted(object):
__slots__ = ['a']
DescriptorTypes = (
type(_slotted.a),
property,
)
def _getsignature(func, skipfirst, instance=False):
if inspect is None:
raise ImportError('inspect module not available')
if isinstance(func, ClassTypes) and not instance:
try:
func = func.__init__
except AttributeError:
return
skipfirst = True
elif not isinstance(func, FunctionTypes):
# for classes where instance is True we end up here too
try:
func = func.__call__
except AttributeError:
return
if inPy3k:
try:
argspec = inspect.getfullargspec(func)
except TypeError:
# C function / method, possibly inherited object().__init__
return
regargs, varargs, varkw, defaults, kwonly, kwonlydef, ann = argspec
else:
try:
regargs, varargs, varkwargs, defaults = inspect.getargspec(func)
except TypeError:
# C function / method, possibly inherited object().__init__
return
# instance methods and classmethods need to lose the self argument
if getattr(func, self, None) is not None:
regargs = regargs[1:]
if skipfirst:
# this condition and the above one are never both True - why?
regargs = regargs[1:]
if inPy3k:
signature = inspect.formatargspec(
regargs, varargs, varkw, defaults,
kwonly, kwonlydef, ann, formatvalue=lambda value: "")
else:
signature = inspect.formatargspec(
regargs, varargs, varkwargs, defaults,
formatvalue=lambda value: "")
return signature[1:-1], func
def _check_signature(func, mock, skipfirst, instance=False):
if not _callable(func):
return
result = _getsignature(func, skipfirst, instance)
if result is None:
return
signature, func = result
# can't use self because "self" is common as an argument name
# unfortunately even not in the first place
src = "lambda _mock_self, %s: None" % signature
checksig = eval(src, {})
_copy_func_details(func, checksig)
type(mock)._mock_check_sig = checksig
def _copy_func_details(func, funcopy):
funcopy.__name__ = func.__name__
funcopy.__doc__ = func.__doc__
#funcopy.__dict__.update(func.__dict__)
funcopy.__module__ = func.__module__
if not inPy3k:
funcopy.func_defaults = func.func_defaults
return
funcopy.__defaults__ = func.__defaults__
funcopy.__kwdefaults__ = func.__kwdefaults__
def _callable(obj):
if isinstance(obj, ClassTypes):
return True
if getattr(obj, '__call__', None) is not None:
return True
return False
def _is_list(obj):
# checks for list or tuples
# XXXX badly named!
return type(obj) in (list, tuple)
def _instance_callable(obj):
"""Given an object, return True if the object is callable.
For classes, return True if instances would be callable."""
if not isinstance(obj, ClassTypes):
# already an instance
return getattr(obj, '__call__', None) is not None
klass = obj
# uses __bases__ instead of __mro__ so that we work with old style classes
if klass.__dict__.get('__call__') is not None:
return True
for base in klass.__bases__:
if _instance_callable(base):
return True
return False
def _set_signature(mock, original, instance=False):
# creates a function with signature (*args, **kwargs) that delegates to a
# mock. It still does signature checking by calling a lambda with the same
# signature as the original.
if not _callable(original):
return
skipfirst = isinstance(original, ClassTypes)
result = _getsignature(original, skipfirst, instance)
if result is None:
# was a C function (e.g. object().__init__ ) that can't be mocked
return
signature, func = result
src = "lambda %s: None" % signature
checksig = eval(src, {})
_copy_func_details(func, checksig)
name = original.__name__
if not _isidentifier(name):
name = 'funcopy'
context = {'_checksig_': checksig, 'mock': mock}
src = """def %s(*args, **kwargs):
_checksig_(*args, **kwargs)
return mock(*args, **kwargs)""" % name
exec (src, context)
funcopy = context[name]
_setup_func(funcopy, mock)
return funcopy
def _setup_func(funcopy, mock):
funcopy.mock = mock
# can't use isinstance with mocks
if not _is_instance_mock(mock):
return
def assert_called_with(*args, **kwargs):
return mock.assert_called_with(*args, **kwargs)
def assert_called_once_with(*args, **kwargs):
return mock.assert_called_once_with(*args, **kwargs)
def assert_has_calls(*args, **kwargs):
return mock.assert_has_calls(*args, **kwargs)
def assert_any_call(*args, **kwargs):
return mock.assert_any_call(*args, **kwargs)
def reset_mock():
funcopy.method_calls = _CallList()
funcopy.mock_calls = _CallList()
mock.reset_mock()
ret = funcopy.return_value
if _is_instance_mock(ret) and not ret is mock:
ret.reset_mock()
funcopy.called = False
funcopy.call_count = 0
funcopy.call_args = None
funcopy.call_args_list = _CallList()
funcopy.method_calls = _CallList()
funcopy.mock_calls = _CallList()
funcopy.return_value = mock.return_value
funcopy.side_effect = mock.side_effect
funcopy._mock_children = mock._mock_children
funcopy.assert_called_with = assert_called_with
funcopy.assert_called_once_with = assert_called_once_with
funcopy.assert_has_calls = assert_has_calls
funcopy.assert_any_call = assert_any_call
funcopy.reset_mock = reset_mock
mock._mock_delegate = funcopy
def _is_magic(name):
return '__%s__' % name[2:-2] == name
class _SentinelObject(object):
"A unique, named, sentinel object."
def __init__(self, name):
self.name = name
def __repr__(self):
return 'sentinel.%s' % self.name
class _Sentinel(object):
"""Access attributes to return a named object, usable as a sentinel."""
def __init__(self):
self._sentinels = {}
def __getattr__(self, name):
if name == '__bases__':
# Without this help(mock) raises an exception
raise AttributeError
return self._sentinels.setdefault(name, _SentinelObject(name))
sentinel = _Sentinel()
DEFAULT = sentinel.DEFAULT
_missing = sentinel.MISSING
_deleted = sentinel.DELETED
class OldStyleClass:
pass
ClassType = type(OldStyleClass)
def _copy(value):
if type(value) in (dict, list, tuple, set):
return type(value)(value)
return value
ClassTypes = (type,)
if not inPy3k:
ClassTypes = (type, ClassType)
_allowed_names = set(
[
'return_value', '_mock_return_value', 'side_effect',
'_mock_side_effect', '_mock_parent', '_mock_new_parent',
'_mock_name', '_mock_new_name'
]
)
def _delegating_property(name):
_allowed_names.add(name)
_the_name = '_mock_' + name
def _get(self, name=name, _the_name=_the_name):
sig = self._mock_delegate
if sig is None:
return getattr(self, _the_name)
return getattr(sig, name)
def _set(self, value, name=name, _the_name=_the_name):
sig = self._mock_delegate
if sig is None:
self.__dict__[_the_name] = value
else:
setattr(sig, name, value)
return property(_get, _set)
class _CallList(list):
def __contains__(self, value):
if not isinstance(value, list):
return list.__contains__(self, value)
len_value = len(value)
len_self = len(self)
if len_value > len_self:
return False
for i in range(0, len_self - len_value + 1):
sub_list = self[i:i+len_value]
if sub_list == value:
return True
return False
def __repr__(self):
return pprint.pformat(list(self))
def _check_and_set_parent(parent, value, name, new_name):
if not _is_instance_mock(value):
return False
if ((value._mock_name or value._mock_new_name) or
(value._mock_parent is not None) or
(value._mock_new_parent is not None)):
return False
_parent = parent
while _parent is not None:
# setting a mock (value) as a child or return value of itself
# should not modify the mock
if _parent is value:
return False
_parent = _parent._mock_new_parent
if new_name:
value._mock_new_parent = parent
value._mock_new_name = new_name
if name:
value._mock_parent = parent
value._mock_name = name
return True
class Base(object):
_mock_return_value = DEFAULT
_mock_side_effect = None
def __init__(self, *args, **kwargs):
pass
class NonCallableMock(Base):
"""A non-callable version of `Mock`"""
def __new__(cls, *args, **kw):
# every instance has its own class
# so we can create magic methods on the
# class without stomping on other mocks
new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__})
instance = object.__new__(new)
return instance
def __init__(
self, spec=None, wraps=None, name=None, spec_set=None,
parent=None, _spec_state=None, _new_name='', _new_parent=None,
**kwargs
):
if _new_parent is None:
_new_parent = parent
__dict__ = self.__dict__
__dict__['_mock_parent'] = parent
__dict__['_mock_name'] = name
__dict__['_mock_new_name'] = _new_name
__dict__['_mock_new_parent'] = _new_parent
if spec_set is not None:
spec = spec_set
spec_set = True
self._mock_add_spec(spec, spec_set)
__dict__['_mock_children'] = {}
__dict__['_mock_wraps'] = wraps
__dict__['_mock_delegate'] = None
__dict__['_mock_called'] = False
__dict__['_mock_call_args'] = None
__dict__['_mock_call_count'] = 0
__dict__['_mock_call_args_list'] = _CallList()
__dict__['_mock_mock_calls'] = _CallList()
__dict__['method_calls'] = _CallList()
if kwargs:
self.configure_mock(**kwargs)
_super(NonCallableMock, self).__init__(
spec, wraps, name, spec_set, parent,
_spec_state
)
def attach_mock(self, mock, attribute):
"""
Attach a mock as an attribute of this one, replacing its name and
parent. Calls to the attached mock will be recorded in the
`method_calls` and `mock_calls` attributes of this one."""
mock._mock_parent = None
mock._mock_new_parent = None
mock._mock_name = ''
mock._mock_new_name = None
setattr(self, attribute, mock)
def mock_add_spec(self, spec, spec_set=False):
"""Add a spec to a mock. `spec` can either be an object or a
list of strings. Only attributes on the `spec` can be fetched as
attributes from the mock.
If `spec_set` is True then only attributes on the spec can be set."""
self._mock_add_spec(spec, spec_set)
def _mock_add_spec(self, spec, spec_set):
_spec_class = None
if spec is not None and not _is_list(spec):
if isinstance(spec, ClassTypes):
_spec_class = spec
else:
_spec_class = _get_class(spec)
spec = dir(spec)
__dict__ = self.__dict__
__dict__['_spec_class'] = _spec_class
__dict__['_spec_set'] = spec_set
__dict__['_mock_methods'] = spec
def __get_return_value(self):
ret = self._mock_return_value
if self._mock_delegate is not None:
ret = self._mock_delegate.return_value
if ret is DEFAULT:
ret = self._get_child_mock(
_new_parent=self, _new_name='()'
)
self.return_value = ret
return ret
def __set_return_value(self, value):
if self._mock_delegate is not None:
self._mock_delegate.return_value = value
else:
self._mock_return_value = value
_check_and_set_parent(self, value, None, '()')
__return_value_doc = "The value to be returned when the mock is called."
return_value = property(__get_return_value, __set_return_value,
__return_value_doc)
@property
def __class__(self):
if self._spec_class is None:
return type(self)
return self._spec_class
called = _delegating_property('called')
call_count = _delegating_property('call_count')
call_args = _delegating_property('call_args')
call_args_list = _delegating_property('call_args_list')
mock_calls = _delegating_property('mock_calls')
def __get_side_effect(self):
sig = self._mock_delegate
if sig is None:
return self._mock_side_effect
return sig.side_effect
def __set_side_effect(self, value):
value = _try_iter(value)
sig = self._mock_delegate
if sig is None:
self._mock_side_effect = value
else:
sig.side_effect = value
side_effect = property(__get_side_effect, __set_side_effect)
def reset_mock(self):
"Restore the mock object to its initial state."
self.called = False
self.call_args = None
self.call_count = 0
self.mock_calls = _CallList()
self.call_args_list = _CallList()
self.method_calls = _CallList()
for child in self._mock_children.itervalues():
if isinstance(child, _SpecState):
continue
child.reset_mock()
ret = self._mock_return_value
if _is_instance_mock(ret) and ret is not self:
ret.reset_mock()
def configure_mock(self, **kwargs):
"""Set attributes on the mock through keyword arguments.
Attributes plus return values and side effects can be set on child
mocks using standard dot notation and unpacking a dictionary in the
method call:
>>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
>>> mock.configure_mock(**attrs)"""
for arg, val in sorted(kwargs.items(),
# we sort on the number of dots so that
# attributes are set before we set attributes on
# attributes
key=lambda entry: entry[0].count('.')):
args = arg.split('.')
final = args.pop()
obj = self
for entry in args:
obj = getattr(obj, entry)
setattr(obj, final, val)
def __getattr__(self, name):
if name == '_mock_methods':
raise AttributeError(name)
elif self._mock_methods is not None:
if name not in self._mock_methods or name in _all_magics:
raise AttributeError("Mock object has no attribute %r" % name)
elif _is_magic(name):
raise AttributeError(name)
result = self._mock_children.get(name)
if result is _deleted:
raise AttributeError(name)
elif result is None:
wraps = None
if self._mock_wraps is not None:
# XXXX should we get the attribute without triggering code
# execution?
wraps = getattr(self._mock_wraps, name)
result = self._get_child_mock(
parent=self, name=name, wraps=wraps, _new_name=name,
_new_parent=self
)
self._mock_children[name] = result
elif isinstance(result, _SpecState):
result = create_autospec(
result.spec, result.spec_set, result.instance,
result.parent, result.name
)
self._mock_children[name] = result
return result
def __repr__(self):
_name_list = [self._mock_new_name]
_parent = self._mock_new_parent
last = self
dot = '.'
if _name_list == ['()']:
dot = ''
seen = set()
while _parent is not None:
last = _parent
_name_list.append(_parent._mock_new_name + dot)
dot = '.'
if _parent._mock_new_name == '()':
dot = ''
_parent = _parent._mock_new_parent
# use ids here so as not to call __hash__ on the mocks
if id(_parent) in seen:
break
seen.add(id(_parent))
_name_list = list(reversed(_name_list))
_first = last._mock_name or 'mock'
if len(_name_list) > 1:
if _name_list[1] not in ('()', '().'):
_first += '.'
_name_list[0] = _first
name = ''.join(_name_list)
name_string = ''
if name not in ('mock', 'mock.'):
name_string = ' name=%r' % name
spec_string = ''
if self._spec_class is not None:
spec_string = ' spec=%r'
if self._spec_set:
spec_string = ' spec_set=%r'
spec_string = spec_string % self._spec_class.__name__
return "<%s%s%s id='%s'>" % (
type(self).__name__,
name_string,
spec_string,
id(self)
)
def __dir__(self):
"""Filter the output of `dir(mock)` to only useful members.
XXXX
"""
extras = self._mock_methods or []
from_type = dir(type(self))
from_dict = list(self.__dict__)
if FILTER_DIR:
from_type = [e for e in from_type if not e.startswith('_')]
from_dict = [e for e in from_dict if not e.startswith('_') or
_is_magic(e)]
return sorted(set(extras + from_type + from_dict +
list(self._mock_children)))
def __setattr__(self, name, value):
if name in _allowed_names:
# property setters go through here
return object.__setattr__(self, name, value)
elif (self._spec_set and self._mock_methods is not None and
name not in self._mock_methods and
name not in self.__dict__):
raise AttributeError("Mock object has no attribute '%s'" % name)
elif name in _unsupported_magics:
msg = 'Attempting to set unsupported magic method %r.' % name
raise AttributeError(msg)
elif name in _all_magics:
if self._mock_methods is not None and name not in self._mock_methods:
raise AttributeError("Mock object has no attribute '%s'" % name)
if not _is_instance_mock(value):
setattr(type(self), name, _get_method(name, value))
original = value
value = lambda *args, **kw: original(self, *args, **kw)
else:
# only set _new_name and not name so that mock_calls is tracked
# but not method calls
_check_and_set_parent(self, value, None, name)
setattr(type(self), name, value)
self._mock_children[name] = value
elif name == '__class__':
self._spec_class = value
return
else:
if _check_and_set_parent(self, value, name, name):
self._mock_children[name] = value
return object.__setattr__(self, name, value)
def __delattr__(self, name):
if name in _all_magics and name in type(self).__dict__:
delattr(type(self), name)
if name not in self.__dict__:
# for magic methods that are still MagicProxy objects and
# not set on the instance itself
return
if name in self.__dict__:
object.__delattr__(self, name)
obj = self._mock_children.get(name, _missing)
if obj is _deleted:
raise AttributeError(name)
if obj is not _missing:
del self._mock_children[name]
self._mock_children[name] = _deleted
def _format_mock_call_signature(self, args, kwargs):
name = self._mock_name or 'mock'
return _format_call_signature(name, args, kwargs)
def _format_mock_failure_message(self, args, kwargs):
message = 'Expected call: %s\nActual call: %s'
expected_string = self._format_mock_call_signature(args, kwargs)
call_args = self.call_args
if len(call_args) == 3:
call_args = call_args[1:]
actual_string = self._format_mock_call_signature(*call_args)
return message % (expected_string, actual_string)
def assert_called_with(_mock_self, *args, **kwargs):
"""assert that the mock was called with the specified arguments.
Raises an AssertionError if the args and keyword args passed in are
different to the last call to the mock."""
self = _mock_self
if self.call_args is None:
expected = self._format_mock_call_signature(args, kwargs)
raise AssertionError('Expected call: %s\nNot called' % (expected,))
if self.call_args != (args, kwargs):
msg = self._format_mock_failure_message(args, kwargs)
raise AssertionError(msg)
def assert_called_once_with(_mock_self, *args, **kwargs):
"""assert that the mock was called exactly once and with the specified
arguments."""
self = _mock_self
if not self.call_count == 1:
msg = ("Expected to be called once. Called %s times." %
self.call_count)
raise AssertionError(msg)
return self.assert_called_with(*args, **kwargs)
def assert_has_calls(self, calls, any_order=False):
"""assert the mock has been called with the specified calls.
The `mock_calls` list is checked for the calls.
If `any_order` is False (the default) then the calls must be
sequential. There can be extra calls before or after the
specified calls.
If `any_order` is True then the calls can be in any order, but
they must all appear in `mock_calls`."""
if not any_order:
if calls not in self.mock_calls:
raise AssertionError(
'Calls not found.\nExpected: %r\n'
'Actual: %r' % (calls, self.mock_calls)
)
return
all_calls = list(self.mock_calls)
not_found = []
for kall in calls:
try:
all_calls.remove(kall)
except ValueError:
not_found.append(kall)
if not_found:
raise AssertionError(
'%r not all found in call list' % (tuple(not_found),)
)
def assert_any_call(self, *args, **kwargs):
"""assert the mock has been called with the specified arguments.
The assert passes if the mock has *ever* been called, unlike
`assert_called_with` and `assert_called_once_with` that only pass if
the call is the most recent one."""
kall = call(*args, **kwargs)
if kall not in self.call_args_list:
expected_string = self._format_mock_call_signature(args, kwargs)
raise AssertionError(
'%s call not found' % expected_string
)
def _get_child_mock(self, **kw):
"""Create the child mocks for attributes and return value.
By default child mocks will be the same type as the parent.
Subclasses of Mock may want to override this to customize the way
child mocks are made.
For non-callable mocks the callable variant will be used (rather than
any custom subclass)."""
_type = type(self)
if not issubclass(_type, CallableMixin):
if issubclass(_type, NonCallableMagicMock):
klass = MagicMock
elif issubclass(_type, NonCallableMock) :
klass = Mock
else:
klass = _type.__mro__[1]
return klass(**kw)
def _try_iter(obj):
if obj is None:
return obj
if _is_exception(obj):
return obj
if _callable(obj):
return obj
try:
return iter(obj)
except TypeError:
# XXXX backwards compatibility
# but this will blow up on first call - so maybe we should fail early?
return obj
class CallableMixin(Base):
def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
wraps=None, name=None, spec_set=None, parent=None,
_spec_state=None, _new_name='', _new_parent=None, **kwargs):
self.__dict__['_mock_return_value'] = return_value
_super(CallableMixin, self).__init__(
spec, wraps, name, spec_set, parent,
_spec_state, _new_name, _new_parent, **kwargs
)
self.side_effect = side_effect
def _mock_check_sig(self, *args, **kwargs):
# stub method that can be replaced with one with a specific signature
pass
def __call__(_mock_self, *args, **kwargs):
# can't use self in-case a function / method we are mocking uses self
# in the signature
_mock_self._mock_check_sig(*args, **kwargs)
return _mock_self._mock_call(*args, **kwargs)
def _mock_call(_mock_self, *args, **kwargs):
self = _mock_self
self.called = True
self.call_count += 1
self.call_args = _Call((args, kwargs), two=True)
self.call_args_list.append(_Call((args, kwargs), two=True))
_new_name = self._mock_new_name
_new_parent = self._mock_new_parent
self.mock_calls.append(_Call(('', args, kwargs)))
seen = set()
skip_next_dot = _new_name == '()'
do_method_calls = self._mock_parent is not None
name = self._mock_name
while _new_parent is not None:
this_mock_call = _Call((_new_name, args, kwargs))
if _new_parent._mock_new_name:
dot = '.'
if skip_next_dot:
dot = ''
skip_next_dot = False
if _new_parent._mock_new_name == '()':
skip_next_dot = True
_new_name = _new_parent._mock_new_name + dot + _new_name
if do_method_calls:
if _new_name == name:
this_method_call = this_mock_call
else:
this_method_call = _Call((name, args, kwargs))
_new_parent.method_calls.append(this_method_call)
do_method_calls = _new_parent._mock_parent is not None
if do_method_calls:
name = _new_parent._mock_name + '.' + name
_new_parent.mock_calls.append(this_mock_call)
_new_parent = _new_parent._mock_new_parent
# use ids here so as not to call __hash__ on the mocks
_new_parent_id = id(_new_parent)
if _new_parent_id in seen:
break
seen.add(_new_parent_id)
ret_val = DEFAULT
effect = self.side_effect
if effect is not None:
if _is_exception(effect):
raise effect
if not _callable(effect):
result = next(effect)
if _is_exception(result):
raise result
return result
ret_val = effect(*args, **kwargs)
if ret_val is DEFAULT:
ret_val = self.return_value
if (self._mock_wraps is not None and
self._mock_return_value is DEFAULT):
return self._mock_wraps(*args, **kwargs)
if ret_val is DEFAULT:
ret_val = self.return_value
return ret_val
class Mock(CallableMixin, NonCallableMock):
"""
Create a new `Mock` object. `Mock` takes several optional arguments
that specify the behaviour of the Mock object:
* `spec`: This can be either a list of strings or an existing object (a
class or instance) that acts as the specification for the mock object. If
you pass in an object then a list of strings is formed by calling dir on
the object (excluding unsupported magic attributes and methods). Accessing
any attribute not in this list will raise an `AttributeError`.
If `spec` is an object (rather than a list of strings) then
`mock.__class__` returns the class of the spec object. This allows mocks
to pass `isinstance` tests.
* `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
or get an attribute on the mock that isn't on the object passed as
`spec_set` will raise an `AttributeError`.
* `side_effect`: A function to be called whenever the Mock is called. See
the `side_effect` attribute. Useful for raising exceptions or
dynamically changing return values. The function is called with the same
arguments as the mock, and unless it returns `DEFAULT`, the return
value of this function is used as the return value.
Alternatively `side_effect` can be an exception class or instance. In
this case the exception will be raised when the mock is called.
If `side_effect` is an iterable then each call to the mock will return
the next value from the iterable. If any of the members of the iterable
are exceptions they will be raised instead of returned.
* `return_value`: The value returned when the mock is called. By default
this is a new Mock (created on first access). See the
`return_value` attribute.
* `wraps`: Item for the mock object to wrap. If `wraps` is not None then
calling the Mock will pass the call through to the wrapped object
(returning the real result). Attribute access on the mock will return a
Mock object that wraps the corresponding attribute of the wrapped object
(so attempting to access an attribute that doesn't exist will raise an
`AttributeError`).
If the mock has an explicit `return_value` set then calls are not passed
to the wrapped object and the `return_value` is returned instead.
* `name`: If the mock has a name then it will be used in the repr of the
mock. This can be useful for debugging. The name is propagated to child
mocks.
Mocks can also be called with arbitrary keyword arguments. These will be
used to set attributes on the mock after it is created.
"""
def _dot_lookup(thing, comp, import_path):
try:
return getattr(thing, comp)
except AttributeError:
__import__(import_path)
return getattr(thing, comp)
def _importer(target):
components = target.split('.')
import_path = components.pop(0)
thing = __import__(import_path)
for comp in components:
import_path += ".%s" % comp
thing = _dot_lookup(thing, comp, import_path)
return thing
def _is_started(patcher):
# XXXX horrible
return hasattr(patcher, 'is_local')
class _patch(object):
attribute_name = None
_active_patches = set()
def __init__(
self, getter, attribute, new, spec, create,
spec_set, autospec, new_callable, kwargs
):
if new_callable is not None:
if new is not DEFAULT:
raise ValueError(
"Cannot use 'new' and 'new_callable' together"
)
if autospec is not None:
raise ValueError(
"Cannot use 'autospec' and 'new_callable' together"
)
self.getter = getter
self.attribute = attribute
self.new = new
self.new_callable = new_callable
self.spec = spec
self.create = create
self.has_local = False
self.spec_set = spec_set
self.autospec = autospec
self.kwargs = kwargs
self.additional_patchers = []
def copy(self):
patcher = _patch(
self.getter, self.attribute, self.new, self.spec,
self.create, self.spec_set,
self.autospec, self.new_callable, self.kwargs
)
patcher.attribute_name = self.attribute_name
patcher.additional_patchers = [
p.copy() for p in self.additional_patchers
]
return patcher
def __call__(self, func):
if isinstance(func, ClassTypes):
return self.decorate_class(func)
return self.decorate_callable(func)
def decorate_class(self, klass):
for attr in dir(klass):
if not attr.startswith(patch.TEST_PREFIX):
continue
attr_value = getattr(klass, attr)
if not hasattr(attr_value, "__call__"):
continue
patcher = self.copy()
setattr(klass, attr, patcher(attr_value))
return klass
def decorate_callable(self, func):
if hasattr(func, 'patchings'):
func.patchings.append(self)
return func
@wraps(func)
def patched(*args, **keywargs):
# don't use a with here (backwards compatibility with Python 2.4)
extra_args = []
entered_patchers = []
# can't use try...except...finally because of Python 2.4
# compatibility
exc_info = tuple()
try:
try:
for patching in patched.patchings:
arg = patching.__enter__()
entered_patchers.append(patching)
if patching.attribute_name is not None:
keywargs.update(arg)
elif patching.new is DEFAULT:
extra_args.append(arg)
args += tuple(extra_args)
return func(*args, **keywargs)
except:
if (patching not in entered_patchers and
_is_started(patching)):
# the patcher may have been started, but an exception
# raised whilst entering one of its additional_patchers
entered_patchers.append(patching)
# Pass the exception to __exit__
exc_info = sys.exc_info()
# re-raise the exception
raise
finally:
for patching in reversed(entered_patchers):
patching.__exit__(*exc_info)
patched.patchings = [self]
if hasattr(func, 'func_code'):
# not in Python 3
patched.compat_co_firstlineno = getattr(
func, "compat_co_firstlineno",
func.func_code.co_firstlineno
)
return patched
def get_original(self):
target = self.getter()
name = self.attribute
original = DEFAULT
local = False
try:
original = target.__dict__[name]
except (AttributeError, KeyError):
original = getattr(target, name, DEFAULT)
else:
local = True
if not self.create and original is DEFAULT:
raise AttributeError(
"%s does not have the attribute %r" % (target, name)
)
return original, local
def __enter__(self):
"""Perform the patch."""
new, spec, spec_set = self.new, self.spec, self.spec_set
autospec, kwargs = self.autospec, self.kwargs
new_callable = self.new_callable
self.target = self.getter()
# normalise False to None
if spec is False:
spec = None
if spec_set is False:
spec_set = None
if autospec is False:
autospec = None
if spec is not None and autospec is not None:
raise TypeError("Can't specify spec and autospec")
if ((spec is not None or autospec is not None) and
spec_set not in (True, None)):
raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
original, local = self.get_original()
if new is DEFAULT and autospec is None:
inherit = False
if spec is True:
# set spec to the object we are replacing
spec = original
if spec_set is True:
spec_set = original
spec = None
elif spec is not None:
if spec_set is True:
spec_set = spec
spec = None
elif spec_set is True:
spec_set = original
if spec is not None or spec_set is not None:
if original is DEFAULT:
raise TypeError("Can't use 'spec' with create=True")
if isinstance(original, ClassTypes):
# If we're patching out a class and there is a spec
inherit = True
Klass = MagicMock
_kwargs = {}
if new_callable is not None:
Klass = new_callable
elif spec is not None or spec_set is not None:
this_spec = spec
if spec_set is not None:
this_spec = spec_set
if _is_list(this_spec):
not_callable = '__call__' not in this_spec
else:
not_callable = not _callable(this_spec)
if not_callable:
Klass = NonCallableMagicMock
if spec is not None:
_kwargs['spec'] = spec
if spec_set is not None:
_kwargs['spec_set'] = spec_set
# add a name to mocks
if (isinstance(Klass, type) and
issubclass(Klass, NonCallableMock) and self.attribute):
_kwargs['name'] = self.attribute
_kwargs.update(kwargs)
new = Klass(**_kwargs)
if inherit and _is_instance_mock(new):
# we can only tell if the instance should be callable if the
# spec is not a list
this_spec = spec
if spec_set is not None:
this_spec = spec_set
if (not _is_list(this_spec) and not
_instance_callable(this_spec)):
Klass = NonCallableMagicMock
_kwargs.pop('name')
new.return_value = Klass(_new_parent=new, _new_name='()',
**_kwargs)
elif autospec is not None:
# spec is ignored, new *must* be default, spec_set is treated
# as a boolean. Should we check spec is not None and that spec_set
# is a bool?
if new is not DEFAULT:
raise TypeError(
"autospec creates the mock for you. Can't specify "
"autospec and new."
)
if original is DEFAULT:
raise TypeError("Can't use 'autospec' with create=True")
spec_set = bool(spec_set)
if autospec is True:
autospec = original
new = create_autospec(autospec, spec_set=spec_set,
_name=self.attribute, **kwargs)
elif kwargs:
# can't set keyword args when we aren't creating the mock
# XXXX If new is a Mock we could call new.configure_mock(**kwargs)
raise TypeError("Can't pass kwargs to a mock we aren't creating")
new_attr = new
self.temp_original = original
self.is_local = local
setattr(self.target, self.attribute, new_attr)
if self.attribute_name is not None:
extra_args = {}
if self.new is DEFAULT:
extra_args[self.attribute_name] = new
for patching in self.additional_patchers:
arg = patching.__enter__()
if patching.new is DEFAULT:
extra_args.update(arg)
return extra_args
return new
def __exit__(self, *exc_info):
"""Undo the patch."""
if not _is_started(self):
raise RuntimeError('stop called on unstarted patcher')
if self.is_local and self.temp_original is not DEFAULT:
setattr(self.target, self.attribute, self.temp_original)
else:
delattr(self.target, self.attribute)
if not self.create and not hasattr(self.target, self.attribute):
# needed for proxy objects like django settings
setattr(self.target, self.attribute, self.temp_original)
del self.temp_original
del self.is_local
del self.target
for patcher in reversed(self.additional_patchers):
if _is_started(patcher):
patcher.__exit__(*exc_info)
def start(self):
"""Activate a patch, returning any created mock."""
result = self.__enter__()
self._active_patches.add(self)
return result
def stop(self):
"""Stop an active patch."""
self._active_patches.discard(self)
return self.__exit__()
def _get_target(target):
try:
target, attribute = target.rsplit('.', 1)
except (TypeError, ValueError):
raise TypeError("Need a valid target to patch. You supplied: %r" %
(target,))
getter = lambda: _importer(target)
return getter, attribute
def _patch_object(
target, attribute, new=DEFAULT, spec=None,
create=False, spec_set=None, autospec=None,
new_callable=None, **kwargs
):
"""
patch.object(target, attribute, new=DEFAULT, spec=None, create=False,
spec_set=None, autospec=None, new_callable=None, **kwargs)
patch the named member (`attribute`) on an object (`target`) with a mock
object.
`patch.object` can be used as a decorator, class decorator or a context
manager. Arguments `new`, `spec`, `create`, `spec_set`,
`autospec` and `new_callable` have the same meaning as for `patch`. Like
`patch`, `patch.object` takes arbitrary keyword arguments for configuring
the mock object it creates.
When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
for choosing which methods to wrap.
"""
getter = lambda: target
return _patch(
getter, attribute, new, spec, create,
spec_set, autospec, new_callable, kwargs
)
def _patch_multiple(target, spec=None, create=False, spec_set=None,
autospec=None, new_callable=None, **kwargs):
"""Perform multiple patches in a single call. It takes the object to be
patched (either as an object or a string to fetch the object by importing)
and keyword arguments for the patches::
with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
...
Use `DEFAULT` as the value if you want `patch.multiple` to create
mocks for you. In this case the created mocks are passed into a decorated
function by keyword, and a dictionary is returned when `patch.multiple` is
used as a context manager.
`patch.multiple` can be used as a decorator, class decorator or a context
manager. The arguments `spec`, `spec_set`, `create`,
`autospec` and `new_callable` have the same meaning as for `patch`. These
arguments will be applied to *all* patches done by `patch.multiple`.
When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
for choosing which methods to wrap.
"""
if type(target) in (unicode, str):
getter = lambda: _importer(target)
else:
getter = lambda: target
if not kwargs:
raise ValueError(
'Must supply at least one keyword argument with patch.multiple'
)
# need to wrap in a list for python 3, where items is a view
items = list(kwargs.items())
attribute, new = items[0]
patcher = _patch(
getter, attribute, new, spec, create, spec_set,
autospec, new_callable, {}
)
patcher.attribute_name = attribute
for attribute, new in items[1:]:
this_patcher = _patch(
getter, attribute, new, spec, create, spec_set,
autospec, new_callable, {}
)
this_patcher.attribute_name = attribute
patcher.additional_patchers.append(this_patcher)
return patcher
def patch(
target, new=DEFAULT, spec=None, create=False,
spec_set=None, autospec=None, new_callable=None, **kwargs
):
"""
`patch` acts as a function decorator, class decorator or a context
manager. Inside the body of the function or with statement, the `target`
is patched with a `new` object. When the function/with statement exits
the patch is undone.
If `new` is omitted, then the target is replaced with a
`MagicMock`. If `patch` is used as a decorator and `new` is
omitted, the created mock is passed in as an extra argument to the
decorated function. If `patch` is used as a context manager the created
mock is returned by the context manager.
`target` should be a string in the form `'package.module.ClassName'`. The
`target` is imported and the specified object replaced with the `new`
object, so the `target` must be importable from the environment you are
calling `patch` from. The target is imported when the decorated function
is executed, not at decoration time.
The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
if patch is creating one for you.
In addition you can pass `spec=True` or `spec_set=True`, which causes
patch to pass in the object being mocked as the spec/spec_set object.
`new_callable` allows you to specify a different class, or callable object,
that will be called to create the `new` object. By default `MagicMock` is
used.
A more powerful form of `spec` is `autospec`. If you set `autospec=True`
then the mock with be created with a spec from the object being replaced.
All attributes of the mock will also have the spec of the corresponding
attribute of the object being replaced. Methods and functions being
mocked will have their arguments checked and will raise a `TypeError` if
they are called with the wrong signature. For mocks replacing a class,
their return value (the 'instance') will have the same spec as the class.
Instead of `autospec=True` you can pass `autospec=some_object` to use an
arbitrary object as the spec instead of the one being replaced.
By default `patch` will fail to replace attributes that don't exist. If
you pass in `create=True`, and the attribute doesn't exist, patch will
create the attribute for you when the patched function is called, and
delete it again afterwards. This is useful for writing tests against
attributes that your production code creates at runtime. It is off by by
default because it can be dangerous. With it switched on you can write
passing tests against APIs that don't actually exist!
Patch can be used as a `TestCase` class decorator. It works by
decorating each test method in the class. This reduces the boilerplate
code when your test methods share a common patchings set. `patch` finds
tests by looking for method names that start with `patch.TEST_PREFIX`.
By default this is `test`, which matches the way `unittest` finds tests.
You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
Patch can be used as a context manager, with the with statement. Here the
patching applies to the indented block after the with statement. If you
use "as" then the patched object will be bound to the name after the
"as"; very useful if `patch` is creating a mock object for you.
`patch` takes arbitrary keyword arguments. These will be passed to
the `Mock` (or `new_callable`) on construction.
`patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
available for alternate use-cases.
"""
getter, attribute = _get_target(target)
return _patch(
getter, attribute, new, spec, create,
spec_set, autospec, new_callable, kwargs
)
class _patch_dict(object):
"""
Patch a dictionary, or dictionary like object, and restore the dictionary
to its original state after the test.
`in_dict` can be a dictionary or a mapping like container. If it is a
mapping then it must at least support getting, setting and deleting items
plus iterating over keys.
`in_dict` can also be a string specifying the name of the dictionary, which
will then be fetched by importing it.
`values` can be a dictionary of values to set in the dictionary. `values`
can also be an iterable of `(key, value)` pairs.
If `clear` is True then the dictionary will be cleared before the new
values are set.
`patch.dict` can also be called with arbitrary keyword arguments to set
values in the dictionary::
with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
...
`patch.dict` can be used as a context manager, decorator or class
decorator. When used as a class decorator `patch.dict` honours
`patch.TEST_PREFIX` for choosing which methods to wrap.
"""
def __init__(self, in_dict, values=(), clear=False, **kwargs):
if isinstance(in_dict, basestring):
in_dict = _importer(in_dict)
self.in_dict = in_dict
# support any argument supported by dict(...) constructor
self.values = dict(values)
self.values.update(kwargs)
self.clear = clear
self._original = None
def __call__(self, f):
if isinstance(f, ClassTypes):
return self.decorate_class(f)
@wraps(f)
def _inner(*args, **kw):
self._patch_dict()
try:
return f(*args, **kw)
finally:
self._unpatch_dict()
return _inner
def decorate_class(self, klass):
for attr in dir(klass):
attr_value = getattr(klass, attr)
if (attr.startswith(patch.TEST_PREFIX) and
hasattr(attr_value, "__call__")):
decorator = _patch_dict(self.in_dict, self.values, self.clear)
decorated = decorator(attr_value)
setattr(klass, attr, decorated)
return klass
def __enter__(self):
"""Patch the dict."""
self._patch_dict()
def _patch_dict(self):
values = self.values
in_dict = self.in_dict
clear = self.clear
try:
original = in_dict.copy()
except AttributeError:
# dict like object with no copy method
# must support iteration over keys
original = {}
for key in in_dict:
original[key] = in_dict[key]
self._original = original
if clear:
_clear_dict(in_dict)
try:
in_dict.update(values)
except AttributeError:
# dict like object with no update method
for key in values:
in_dict[key] = values[key]
def _unpatch_dict(self):
in_dict = self.in_dict
original = self._original
_clear_dict(in_dict)
try:
in_dict.update(original)
except AttributeError:
for key in original:
in_dict[key] = original[key]
def __exit__(self, *args):
"""Unpatch the dict."""
self._unpatch_dict()
return False
start = __enter__
stop = __exit__
def _clear_dict(in_dict):
try:
in_dict.clear()
except AttributeError:
keys = list(in_dict)
for key in keys:
del in_dict[key]
def _patch_stopall():
"""Stop all active patches."""
for patch in list(_patch._active_patches):
patch.stop()
patch.object = _patch_object
patch.dict = _patch_dict
patch.multiple = _patch_multiple
patch.stopall = _patch_stopall
patch.TEST_PREFIX = 'test'
magic_methods = (
"lt le gt ge eq ne "
"getitem setitem delitem "
"len contains iter "
"hash str sizeof "
"enter exit "
"divmod neg pos abs invert "
"complex int float index "
"trunc floor ceil "
)
numerics = "add sub mul div floordiv mod lshift rshift and xor or pow "
inplace = ' '.join('i%s' % n for n in numerics.split())
right = ' '.join('r%s' % n for n in numerics.split())
extra = ''
if inPy3k:
extra = 'bool next '
else:
extra = 'unicode long nonzero oct hex truediv rtruediv '
# not including __prepare__, __instancecheck__, __subclasscheck__
# (as they are metaclass methods)
# __del__ is not supported at all as it causes problems if it exists
_non_defaults = set('__%s__' % method for method in [
'cmp', 'getslice', 'setslice', 'coerce', 'subclasses',
'format', 'get', 'set', 'delete', 'reversed',
'missing', 'reduce', 'reduce_ex', 'getinitargs',
'getnewargs', 'getstate', 'setstate', 'getformat',
'setformat', 'repr', 'dir'
])
def _get_method(name, func):
"Turns a callable object (like a mock) into a real function"
def method(self, *args, **kw):
return func(self, *args, **kw)
method.__name__ = name
return method
_magics = set(
'__%s__' % method for method in
' '.join([magic_methods, numerics, inplace, right, extra]).split()
)
_all_magics = _magics | _non_defaults
_unsupported_magics = set([
'__getattr__', '__setattr__',
'__init__', '__new__', '__prepare__'
'__instancecheck__', '__subclasscheck__',
'__del__'
])
_calculate_return_value = {
'__hash__': lambda self: object.__hash__(self),
'__str__': lambda self: object.__str__(self),
'__sizeof__': lambda self: object.__sizeof__(self),
'__unicode__': lambda self: unicode(object.__str__(self)),
}
_return_values = {
'__lt__': NotImplemented,
'__gt__': NotImplemented,
'__le__': NotImplemented,
'__ge__': NotImplemented,
'__int__': 1,
'__contains__': False,
'__len__': 0,
'__exit__': False,
'__complex__': 1j,
'__float__': 1.0,
'__bool__': True,
'__nonzero__': True,
'__oct__': '1',
'__hex__': '0x1',
'__long__': long(1),
'__index__': 1,
}
def _get_eq(self):
def __eq__(other):
ret_val = self.__eq__._mock_return_value
if ret_val is not DEFAULT:
return ret_val
return self is other
return __eq__
def _get_ne(self):
def __ne__(other):
if self.__ne__._mock_return_value is not DEFAULT:
return DEFAULT
return self is not other
return __ne__
def _get_iter(self):
def __iter__():
ret_val = self.__iter__._mock_return_value
if ret_val is DEFAULT:
return iter([])
# if ret_val was already an iterator, then calling iter on it should
# return the iterator unchanged
return iter(ret_val)
return __iter__
_side_effect_methods = {
'__eq__': _get_eq,
'__ne__': _get_ne,
'__iter__': _get_iter,
}
def _set_return_value(mock, method, name):
fixed = _return_values.get(name, DEFAULT)
if fixed is not DEFAULT:
method.return_value = fixed
return
return_calulator = _calculate_return_value.get(name)
if return_calulator is not None:
try:
return_value = return_calulator(mock)
except AttributeError:
# XXXX why do we return AttributeError here?
# set it as a side_effect instead?
return_value = AttributeError(name)
method.return_value = return_value
return
side_effector = _side_effect_methods.get(name)
if side_effector is not None:
method.side_effect = side_effector(mock)
class MagicMixin(object):
def __init__(self, *args, **kw):
_super(MagicMixin, self).__init__(*args, **kw)
self._mock_set_magics()
def _mock_set_magics(self):
these_magics = _magics
if self._mock_methods is not None:
these_magics = _magics.intersection(self._mock_methods)
remove_magics = set()
remove_magics = _magics - these_magics
for entry in remove_magics:
if entry in type(self).__dict__:
# remove unneeded magic methods
delattr(self, entry)
# don't overwrite existing attributes if called a second time
these_magics = these_magics - set(type(self).__dict__)
_type = type(self)
for entry in these_magics:
setattr(_type, entry, MagicProxy(entry, self))
class NonCallableMagicMock(MagicMixin, NonCallableMock):
"""A version of `MagicMock` that isn't callable."""
def mock_add_spec(self, spec, spec_set=False):
"""Add a spec to a mock. `spec` can either be an object or a
list of strings. Only attributes on the `spec` can be fetched as
attributes from the mock.
If `spec_set` is True then only attributes on the spec can be set."""
self._mock_add_spec(spec, spec_set)
self._mock_set_magics()
class MagicMock(MagicMixin, Mock):
"""
MagicMock is a subclass of Mock with default implementations
of most of the magic methods. You can use MagicMock without having to
configure the magic methods yourself.
If you use the `spec` or `spec_set` arguments then *only* magic
methods that exist in the spec will be created.
Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
"""
def mock_add_spec(self, spec, spec_set=False):
"""Add a spec to a mock. `spec` can either be an object or a
list of strings. Only attributes on the `spec` can be fetched as
attributes from the mock.
If `spec_set` is True then only attributes on the spec can be set."""
self._mock_add_spec(spec, spec_set)
self._mock_set_magics()
class MagicProxy(object):
def __init__(self, name, parent):
self.name = name
self.parent = parent
def __call__(self, *args, **kwargs):
m = self.create_mock()
return m(*args, **kwargs)
def create_mock(self):
entry = self.name
parent = self.parent
m = parent._get_child_mock(name=entry, _new_name=entry,
_new_parent=parent)
setattr(parent, entry, m)
_set_return_value(parent, m, entry)
return m
def __get__(self, obj, _type=None):
return self.create_mock()
class _ANY(object):
"A helper object that compares equal to everything."
def __eq__(self, other):
return True
def __ne__(self, other):
return False
def __repr__(self):
return '<ANY>'
ANY = _ANY()
def _format_call_signature(name, args, kwargs):
message = '%s(%%s)' % name
formatted_args = ''
args_string = ', '.join([repr(arg) for arg in args])
kwargs_string = ', '.join([
'%s=%r' % (key, value) for key, value in kwargs.items()
])
if args_string:
formatted_args = args_string
if kwargs_string:
if formatted_args:
formatted_args += ', '
formatted_args += kwargs_string
return message % formatted_args
class _Call(tuple):
"""
A tuple for holding the results of a call to a mock, either in the form
`(args, kwargs)` or `(name, args, kwargs)`.
If args or kwargs are empty then a call tuple will compare equal to
a tuple without those values. This makes comparisons less verbose::
_Call(('name', (), {})) == ('name',)
_Call(('name', (1,), {})) == ('name', (1,))
_Call(((), {'a': 'b'})) == ({'a': 'b'},)
The `_Call` object provides a useful shortcut for comparing with call::
_Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
_Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
If the _Call has no name then it will match any name.
"""
def __new__(cls, value=(), name=None, parent=None, two=False,
from_kall=True):
name = ''
args = ()
kwargs = {}
_len = len(value)
if _len == 3:
name, args, kwargs = value
elif _len == 2:
first, second = value
if isinstance(first, basestring):
name = first
if isinstance(second, tuple):
args = second
else:
kwargs = second
else:
args, kwargs = first, second
elif _len == 1:
value, = value
if isinstance(value, basestring):
name = value
elif isinstance(value, tuple):
args = value
else:
kwargs = value
if two:
return tuple.__new__(cls, (args, kwargs))
return tuple.__new__(cls, (name, args, kwargs))
def __init__(self, value=(), name=None, parent=None, two=False,
from_kall=True):
self.name = name
self.parent = parent
self.from_kall = from_kall
def __eq__(self, other):
if other is ANY:
return True
try:
len_other = len(other)
except TypeError:
return False
self_name = ''
if len(self) == 2:
self_args, self_kwargs = self
else:
self_name, self_args, self_kwargs = self
other_name = ''
if len_other == 0:
other_args, other_kwargs = (), {}
elif len_other == 3:
other_name, other_args, other_kwargs = other
elif len_other == 1:
value, = other
if isinstance(value, tuple):
other_args = value
other_kwargs = {}
elif isinstance(value, basestring):
other_name = value
other_args, other_kwargs = (), {}
else:
other_args = ()
other_kwargs = value
else:
# len 2
# could be (name, args) or (name, kwargs) or (args, kwargs)
first, second = other
if isinstance(first, basestring):
other_name = first
if isinstance(second, tuple):
other_args, other_kwargs = second, {}
else:
other_args, other_kwargs = (), second
else:
other_args, other_kwargs = first, second
if self_name and other_name != self_name:
return False
# this order is important for ANY to work!
return (other_args, other_kwargs) == (self_args, self_kwargs)
def __ne__(self, other):
return not self.__eq__(other)
def __call__(self, *args, **kwargs):
if self.name is None:
return _Call(('', args, kwargs), name='()')
name = self.name + '()'
return _Call((self.name, args, kwargs), name=name, parent=self)
def __getattr__(self, attr):
if self.name is None:
return _Call(name=attr, from_kall=False)
name = '%s.%s' % (self.name, attr)
return _Call(name=name, parent=self, from_kall=False)
def __repr__(self):
if not self.from_kall:
name = self.name or 'call'
if name.startswith('()'):
name = 'call%s' % name
return name
if len(self) == 2:
name = 'call'
args, kwargs = self
else:
name, args, kwargs = self
if not name:
name = 'call'
elif not name.startswith('()'):
name = 'call.%s' % name
else:
name = 'call%s' % name
return _format_call_signature(name, args, kwargs)
def call_list(self):
"""For a call object that represents multiple calls, `call_list`
returns a list of all the intermediate calls as well as the
final call."""
vals = []
thing = self
while thing is not None:
if thing.from_kall:
vals.append(thing)
thing = thing.parent
return _CallList(reversed(vals))
call = _Call(from_kall=False)
def create_autospec(spec, spec_set=False, instance=False, _parent=None,
_name=None, **kwargs):
"""Create a mock object using another object as a spec. Attributes on the
mock will use the corresponding attribute on the `spec` object as their
spec.
Functions or methods being mocked will have their arguments checked
to check that they are called with the correct signature.
If `spec_set` is True then attempting to set attributes that don't exist
on the spec object will raise an `AttributeError`.
If a class is used as a spec then the return value of the mock (the
instance of the class) will have the same spec. You can use a class as the
spec for an instance object by passing `instance=True`. The returned mock
will only be callable if instances of the mock are callable.
`create_autospec` also takes arbitrary keyword arguments that are passed to
the constructor of the created mock."""
if _is_list(spec):
# can't pass a list instance to the mock constructor as it will be
# interpreted as a list of strings
spec = type(spec)
is_type = isinstance(spec, ClassTypes)
_kwargs = {'spec': spec}
if spec_set:
_kwargs = {'spec_set': spec}
elif spec is None:
# None we mock with a normal mock without a spec
_kwargs = {}
_kwargs.update(kwargs)
Klass = MagicMock
if type(spec) in DescriptorTypes:
# descriptors don't have a spec
# because we don't know what type they return
_kwargs = {}
elif not _callable(spec):
Klass = NonCallableMagicMock
elif is_type and instance and not _instance_callable(spec):
Klass = NonCallableMagicMock
_new_name = _name
if _parent is None:
# for a top level object no _new_name should be set
_new_name = ''
mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
name=_name, **_kwargs)
if isinstance(spec, FunctionTypes):
# should only happen at the top level because we don't
# recurse for functions
mock = _set_signature(mock, spec)
else:
_check_signature(spec, mock, is_type, instance)
if _parent is not None and not instance:
_parent._mock_children[_name] = mock
if is_type and not instance and 'return_value' not in kwargs:
mock.return_value = create_autospec(spec, spec_set, instance=True,
_name='()', _parent=mock)
for entry in dir(spec):
if _is_magic(entry):
# MagicMock already does the useful magic methods for us
continue
if isinstance(spec, FunctionTypes) and entry in FunctionAttributes:
# allow a mock to actually be a function
continue
# XXXX do we need a better way of getting attributes without
# triggering code execution (?) Probably not - we need the actual
# object to mock it so we would rather trigger a property than mock
# the property descriptor. Likewise we want to mock out dynamically
# provided attributes.
# XXXX what about attributes that raise exceptions other than
# AttributeError on being fetched?
# we could be resilient against it, or catch and propagate the
# exception when the attribute is fetched from the mock
try:
original = getattr(spec, entry)
except AttributeError:
continue
kwargs = {'spec': original}
if spec_set:
kwargs = {'spec_set': original}
if not isinstance(original, FunctionTypes):
new = _SpecState(original, spec_set, mock, entry, instance)
mock._mock_children[entry] = new
else:
parent = mock
if isinstance(spec, FunctionTypes):
parent = mock.mock
new = MagicMock(parent=parent, name=entry, _new_name=entry,
_new_parent=parent, **kwargs)
mock._mock_children[entry] = new
skipfirst = _must_skip(spec, entry, is_type)
_check_signature(original, new, skipfirst=skipfirst)
# so functions created with _set_signature become instance attributes,
# *plus* their underlying mock exists in _mock_children of the parent
# mock. Adding to _mock_children may be unnecessary where we are also
# setting as an instance attribute?
if isinstance(new, FunctionTypes):
setattr(mock, entry, new)
return mock
def _must_skip(spec, entry, is_type):
if not isinstance(spec, ClassTypes):
if entry in getattr(spec, '__dict__', {}):
# instance attribute - shouldn't skip
return False
spec = spec.__class__
if not hasattr(spec, '__mro__'):
# old style class: can't have descriptors anyway
return is_type
for klass in spec.__mro__:
result = klass.__dict__.get(entry, DEFAULT)
if result is DEFAULT:
continue
if isinstance(result, (staticmethod, classmethod)):
return False
return is_type
# shouldn't get here unless function is a dynamically provided attribute
# XXXX untested behaviour
return is_type
def _get_class(obj):
try:
return obj.__class__
except AttributeError:
# in Python 2, _sre.SRE_Pattern objects have no __class__
return type(obj)
class _SpecState(object):
def __init__(self, spec, spec_set=False, parent=None,
name=None, ids=None, instance=False):
self.spec = spec
self.ids = ids
self.spec_set = spec_set
self.parent = parent
self.instance = instance
self.name = name
FunctionTypes = (
# python function
type(create_autospec),
# instance method
type(ANY.__eq__),
# unbound method
type(_ANY.__eq__),
)
FunctionAttributes = set([
'func_closure',
'func_code',
'func_defaults',
'func_dict',
'func_doc',
'func_globals',
'func_name',
])
file_spec = None
def mock_open(mock=None, read_data=''):
"""
A helper function to create a mock to replace the use of `open`. It works
for `open` called directly or used as a context manager.
The `mock` argument is the mock object to configure. If `None` (the
default) then a `MagicMock` will be created for you, with the API limited
to methods or attributes available on standard file handles.
`read_data` is a string for the `read` method of the file handle to return.
This is an empty string by default.
"""
global file_spec
if file_spec is None:
# set on first use
if inPy3k:
import _io
file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
else:
file_spec = file
if mock is None:
mock = MagicMock(name='open', spec=open)
handle = MagicMock(spec=file_spec)
handle.write.return_value = None
handle.__enter__.return_value = handle
handle.read.return_value = read_data
mock.return_value = handle
return mock
class PropertyMock(Mock):
"""
A mock intended to be used as a property, or other descriptor, on a class.
`PropertyMock` provides `__get__` and `__set__` methods so you can specify
a return value when it is fetched.
Fetching a `PropertyMock` instance from an object calls the mock, with
no args. Setting it calls the mock with the value being set.
"""
def _get_child_mock(self, **kwargs):
return MagicMock(**kwargs)
def __get__(self, obj, obj_type):
return self()
def __set__(self, obj, val):
self(val)
| 75,539
|
Python
|
.py
| 1,872
| 31.053419
| 86
| 0.594378
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,825
|
test_downgrade.py
|
rpm-software-management_dnf/tests/test_downgrade.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import rpm
import dnf
import dnf.goal
import tests.support
from tests.support import mock
class DowngradeTest(tests.support.ResultTestCase):
REPOS = ["main"]
INIT_SACK = True
@mock.patch('dnf.rpm.transaction.TransactionWrapper')
def test_package_downgrade(self, ts):
pkgs = self.base.add_remote_rpms([tests.support.TOUR_44_PKG_PATH])
cnt = self.base.package_downgrade(pkgs[0])
self.base._ts.setProbFilter.assert_called_with(
rpm.RPMPROB_FILTER_OLDPACKAGE)
self.assertGreater(cnt, 0)
(installed, removed) = self.installed_removed(self.base)
self.assertCountEqual(map(str, installed), ("tour-4-4.noarch", ))
self.assertCountEqual(map(str, removed), ("tour-5-0.noarch", ))
def test_downgrade(self):
cnt = self.base.downgrade("tour")
self.assertGreater(cnt, 0)
new_pkg = self.base.sack.query().available().filter(name="tour")[0]
self.assertEqual(new_pkg.evr, "4.6-1")
new_set = tests.support.installed_but(self.base.sack, "tour") + [new_pkg]
self.assertResult(self.base, new_set)
def test_downgrade2(self):
# override base with custom repos
self.base = tests.support.MockBase("old_versions")
self.base.downgrade("tour")
installed, removed = self.installed_removed(self.base)
self.assertCountEqual(map(str, installed), ['tour-4.9-1.noarch'])
self.assertCountEqual(map(str, removed), ['tour-5-0.noarch'])
class DowngradeTest2(tests.support.DnfBaseTestCase):
REPOS = ["main"]
INIT_SACK = True
def setUp(self):
super(DowngradeTest2, self).setUp()
self.base._goal = mock.create_autospec(dnf.goal.Goal)
def test_downgrade_pkgnevra(self):
""" Downgrade should handle full NEVRAs. """
tests.support.ObjectMatcher(dnf.package.Package, {'name': 'tour'})
with self.assertRaises(dnf.exceptions.PackagesNotInstalledError):
self.base.downgrade('tour-0:5-0.noarch')
def test_downgrade_notinstalled(self):
pkg = tests.support.ObjectMatcher(dnf.package.Package, {'name': 'lotus'})
with self.assertRaises(dnf.exceptions.PackagesNotInstalledError) as context:
self.base.downgrade('lotus')
self.assertEqual(context.exception.pkg_spec, 'lotus')
self.assertEqual(tuple(context.exception.packages), (pkg,) * 2)
self.assertEqual(self.goal.mock_calls, [])
def test_downgrade_notfound(self):
with self.assertRaises(dnf.exceptions.PackageNotFoundError) as context:
self.base.downgrade('non-existent')
self.assertEqual(context.exception.pkg_spec, 'non-existent')
self.assertEqual(self.goal.mock_calls, [])
def test_downgrade_nodowngrade(self):
downgraded_count = self.base.downgrade('pepper')
self.assertEqual(self.goal.mock_calls, [])
self.assertEqual(downgraded_count, 0)
| 4,006
|
Python
|
.py
| 78
| 45.205128
| 84
| 0.708909
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,826
|
test_logging.py
|
rpm-software-management_dnf/tests/test_logging.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2013-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import logging
import collections
import gzip
import operator
import os
import tempfile
import dnf.const
import dnf.logging
import tests.support
from tests.support import mock
LogfileEntry = collections.namedtuple('LogfileEntry', ('date', 'time', 'message'))
def _split_logfile_entry(entry):
record = entry.split(' ')
datetime = record[0].split('T')
# strip the trailing '\n' from the message:
message = ' '.join(record[2:])[:-1]
return LogfileEntry(date=datetime[0],
time=datetime[1], message=message)
def drop_all_handlers():
for logger_name in ('dnf', 'dnf.rpm'):
logger = logging.getLogger(logger_name)
for handler in logger.handlers[:]:
logger.removeHandler(handler)
class TestLogging(tests.support.TestCase):
"""Tests the logging mechanisms in DNF.
If it causes a problem in the future that loggers are singletons that don't
get torn down between tests, look at logging.Manager internals.
"""
def setUp(self):
self.logdir = tempfile.mkdtemp(prefix="dnf-logtest-")
self.log_size = 1024 * 1024
self.log_rotate = 4
self.log_compress = False
self.logging = dnf.logging.Logging()
def tearDown(self):
drop_all_handlers()
dnf.util.rm_rf(self.logdir)
@staticmethod
def _bench(logger):
logger.debug(u"d")
logger.info(u"i")
logger.warning(u"w")
logger.error(u"e")
def test_level_conversion(self):
self.assertRaises(AssertionError, dnf.logging._cfg_verbose_val2level, 11)
self.assertEqual(dnf.logging._cfg_verbose_val2level(0),
dnf.logging.SUPERCRITICAL)
self.assertEqual(dnf.logging._cfg_verbose_val2level(7),
dnf.logging.DDEBUG)
def test_setup(self):
logger = logging.getLogger("dnf")
with tests.support.patch_std_streams() as (stdout, stderr):
self.logging._setup(
logging.INFO, logging.ERROR, dnf.logging.TRACE,
self.logdir, self.log_size, self.log_rotate, self.log_compress)
self._bench(logger)
self.assertEqual("i\n", stdout.getvalue())
self.assertEqual("e\n", stderr.getvalue())
def test_setup_verbose(self):
logger = logging.getLogger("dnf")
with tests.support.patch_std_streams() as (stdout, stderr):
self.logging._setup(
logging.DEBUG, logging.WARNING, dnf.logging.TRACE,
self.logdir, self.log_size, self.log_rotate, self.log_compress)
self._bench(logger)
self.assertEqual("d\ni\n", stdout.getvalue())
self.assertEqual("w\ne\n", stderr.getvalue())
@mock.patch('dnf.logging.Logging._setup')
def test_setup_from_dnf_conf(self, setup_m):
conf = mock.Mock(
debuglevel=2, errorlevel=3, logfilelevel=2, logdir=self.logdir,
log_size=self.log_size, log_rotate=self.log_rotate, log_compress=self.log_compress)
self.logging._setup_from_dnf_conf(conf)
self.assertEqual(setup_m.call_args, mock.call(dnf.logging.INFO,
dnf.logging.WARNING,
dnf.logging.INFO,
self.logdir,
self.log_size,
self.log_rotate,
self.log_compress))
conf = mock.Mock(
debuglevel=6, errorlevel=6, logfilelevel=6, logdir=self.logdir,
log_size=self.log_size, log_rotate=self.log_rotate, log_compress=self.log_compress)
self.logging._setup_from_dnf_conf(conf)
self.assertEqual(setup_m.call_args, mock.call(dnf.logging.DEBUG,
dnf.logging.WARNING,
dnf.logging.DEBUG,
self.logdir,
self.log_size,
self.log_rotate,
self.log_compress))
def test_file_logging(self):
# log nothing to the console:
self.logging._setup(
dnf.logging.SUPERCRITICAL, dnf.logging.SUPERCRITICAL, dnf.logging.TRACE,
self.logdir, self.log_size, self.log_rotate, self.log_compress)
logger = logging.getLogger("dnf")
with tests.support.patch_std_streams() as (stdout, stderr):
logger.info("i")
logger.critical("c")
self.assertEqual(stdout.getvalue(), '')
self.assertEqual(stderr.getvalue(), '')
# yet the file should contain both the entries:
logfile = os.path.join(self.logdir, "dnf.log")
self.assertFile(logfile)
with open(logfile) as f:
msgs = map(operator.attrgetter("message"),
map(_split_logfile_entry, f.readlines()))
self.assertSequenceEqual(list(msgs), [dnf.const.LOG_MARKER, 'i', 'c'])
def test_rpm_logging(self):
# log everything to the console:
self.logging._setup(
dnf.logging.SUBDEBUG, dnf.logging.SUBDEBUG, dnf.logging.TRACE,
self.logdir, self.log_size, self.log_rotate, self.log_compress)
logger = logging.getLogger("dnf.rpm")
with tests.support.patch_std_streams() as (stdout, stderr):
logger.info('rpm transaction happens.')
# rpm logger never outputs to the console:
self.assertEqual(stdout.getvalue(), "")
self.assertEqual(stderr.getvalue(), "")
logfile = os.path.join(self.logdir, "dnf.rpm.log")
self.assertFile(logfile)
with open(logfile) as f:
msgs = map(operator.attrgetter("message"),
map(_split_logfile_entry, f.readlines()))
self.assertSequenceEqual(
list(msgs),
[dnf.const.LOG_MARKER, 'rpm transaction happens.']
)
def test_setup_only_once(self):
logger = logging.getLogger("dnf")
self.assertLength(logger.handlers, 0)
self.logging._setup(
dnf.logging.SUBDEBUG, dnf.logging.SUBDEBUG, dnf.logging.TRACE,
self.logdir, self.log_size, self.log_rotate, self.log_compress)
cnt = len(logger.handlers)
self.assertGreater(cnt, 0)
self.logging._setup(
dnf.logging.SUBDEBUG, dnf.logging.SUBDEBUG,
self.logdir, self.log_size, self.log_rotate, self.log_compress)
# no new handlers
self.assertEqual(cnt, len(logger.handlers))
def test_log_compression(self):
# log nothing to the console and set log_compress=True and log_size to minimal size, so it's always rotated:
self.logging._setup(
dnf.logging.SUPERCRITICAL, dnf.logging.SUPERCRITICAL, dnf.logging.TRACE,
self.logdir, log_size=1, log_rotate=self.log_rotate, log_compress=True)
logger = logging.getLogger("dnf")
with tests.support.patch_std_streams() as (stdout, stderr):
logger.info("i")
logger.critical("c")
logfile = os.path.join(self.logdir, "dnf.log")
self.assertFile(logfile)
with open(logfile) as f:
msgs = map(operator.attrgetter("message"),
map(_split_logfile_entry, f.readlines()))
self.assertSequenceEqual(list(msgs), ['c'])
logfile_rotated = os.path.join(self.logdir, "dnf.log.1.gz")
self.assertFile(logfile_rotated)
with gzip.open(logfile_rotated, 'rt') as f:
msgs = map(operator.attrgetter("message"),
map(_split_logfile_entry, f.readlines()))
self.assertSequenceEqual(list(msgs), ['i'])
| 8,998
|
Python
|
.py
| 182
| 37.78022
| 116
| 0.610239
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,827
|
test_arch.py
|
rpm-software-management_dnf/tests/test_arch.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf.rpm
import tests.support
class ArchTest(tests.support.TestCase):
def test_basearch(self):
fn = dnf.rpm.basearch
self.assertEqual(fn('armv6hl'), 'armhfp')
self.assertEqual(fn('armv7hl'), 'armhfp')
self.assertEqual(fn('armv8hl'), 'armhfp')
self.assertEqual(fn('armv8l'), 'arm')
self.assertEqual(fn('i686'), 'i386')
self.assertEqual(fn('noarch'), 'noarch')
self.assertEqual(fn('ppc64iseries'), 'ppc64')
self.assertEqual(fn('sparc64v'), 'sparc')
self.assertEqual(fn('x86_64'), 'x86_64')
| 1,647
|
Python
|
.py
| 33
| 46.151515
| 77
| 0.728687
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,828
|
test_rpmconnection.py
|
rpm-software-management_dnf/tests/test_rpmconnection.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import unicode_literals
import inspect
from dnf.rpm.connection import RpmConnection
import tests.support
class TestConnection(tests.support.TestCase):
def test_sanity(self):
rpm = RpmConnection('/')
ts = rpm.readonly_ts
self.assertTrue(inspect.isbuiltin(ts.clean))
| 1,299
|
Python
|
.py
| 26
| 47.615385
| 77
| 0.770932
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,829
|
test_dnssec.py
|
rpm-software-management_dnf/tests/test_dnssec.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
import dnf.dnssec
import tests.support
RPM_USER = 'RPM Packager (The guy who creates packages) <packager@example.com>'
EMAIL = 'packager@example.com'
RPM_RAW_KEY = b'-----BEGIN PGP PUBLIC KEY BLOCK-----\n\nmQENBFqWzewBCADMHY8wL2Gm+aeShboOf' \
b'G96/h/OJ8FHj+xrihPGY34FwLVqtvO+\nlRIO6t3w5y7O1MWzR1ePtQg1T1sg1s9UeoDRMZoV' \
b'gzZdRXtQH1Jy9xpTeMfL31ml\nc3wOnitcH0AdWhT7xnnlaCeJuMrX82PWtiJNd+Cy+bgyLfL' \
b'MwX18cimwYCnyIHQ5\n4qiiywXa1paVHkbEJdbd8f4AxArsHX33xCv76wct2uXiHYAHu67rE5' \
b'FhQ0mEqfIZ\nHwuFljGPj5UMgyd6MRMuL2Ho1hL7FDPIxDBv5tMWeZJszixIsCkA9Kc1ibylD' \
b'z9I\nx/keH1K9XXSb/o2EIfF6sWYcj0wNvJllIHAfABEBAAG0QlJQTSBQYWNrYWdlciAo\nVG' \
b'hlIGd1eSB3aG8gY3JlYXRlcyBwYWNrYWdlcykgPHBhY2thZ2VyQGV4YW1wbGUu\nY29tPokBT' \
b'gQTAQgAOBYhBMwU+9636QKkbYsjdMKSn1VZ4I5DBQJals3sAhsDBQsJ\nCAcCBhUKCQgLAgQW' \
b'AgMBAh4BAheAAAoJEMKSn1VZ4I5D6icH/2GY2MMnmcDO+ApI\nF6gGg9itzAHLTNcxEMl9ht1' \
b'Gu3JQ/VdsvMQ6lG+U8yffEmsfQebtt1UaMVXzyt0t\ncSOBJvVEI6qc6skvfea3hqL4srtTOC' \
b'wu7ZBA9gOE+eB5BWBspFUVIwUO1GKT48uz\nV6CaODLitaxc7NrJ9HYw4C4+ICCfbIJhjM/Hq' \
b'xLKOqVy/jsySqIHK96RrjY/m8Q9\nBzsi/6fj/GHkewaM8zaeNLHE7MgXFZAuJ8lzjD0r2oBD' \
b'JGeBKfjjz9xh26YWjG/A\noiolXfliTEox6p0bf820eRhdX9UdSesBROL3rkB+hM5FOT8crSP' \
b'JsuGZWJ9brikf\nsurWyU+5AQ0EWpbN7AEIAK0/PThuvsLdDGe5HeZn3VdrFcD9QSOV9Xjos8' \
b'zWkwx8\nv0t4KXPM4GshyU2ddNjgA+00LhzjACm2ropT5vdvKPtf8lRGOcWWHkiMPdDW/R3/\n' \
b'I5S0Oh1WFNrQZwQSXn/DoPnhUZNGErpZlUzF00BEltwoVWgT1n81Bp486U3oziZn\nUM8kxXXY' \
b'2PN8aTfWjsxOSmjyu2m7abeyjTqX9s++vUCQhmCNboSY1AhXF8GQl1Ce\nmpHVv0hOuC6Bead' \
b'ZRXEfEF0sQogswXpFhYG4GFUvVzKBn00/5phNWHvff1GDjzZz\nmVcRPje+rH6gGP8tpQn7NL' \
b'1SvrazSqSOih//FfV73EMAEQEAAYkBNgQYAQgAIBYh\nBMwU+9636QKkbYsjdMKSn1VZ4I5DB' \
b'QJals3sAhsMAAoJEMKSn1VZ4I5DshgIALSn\nLy7KL0bcqxoiEZT+P9O+gX34J2NEfITlu3MZ' \
b'yN26LbyJS7HuN1vmuUc/UM0ff7AW\n6eElCNFr5HQOrFELUZWiX7f4U8ihRN39g1PKRGANlUc' \
b'Lm1Z/JnKyYbyzRK70o5A3\n5EiXEHwY62c/b8I1N4kzNKpa0eQcJ7F8XoZhau0UsxqueVPeEI' \
b'aHX+fjbalz67ea\niFTu8MurdGKntVE1dOPYbGvZE0+HxfDOoVo05bRUH8By7dDgVaI9EijrV' \
b'zjA5jHP\nJxNIj9AQP9W8zst3l3d9v8o0Pw+L4cWzv+aBFakfjKGugs6lA53fB3RCfZ7OrMwC' \
b'\nBvlTfDigK9X50K6XoP0=\n=6SRV\n-----END PGP PUBLIC KEY BLOCK-----\n'
ASCII_RAW_KEY = b'mQENBFqWzewBCADMHY8wL2Gm+aeShboOfG96/h/OJ8FHj+xrihPGY34FwLVqtvO+lRIO6t3' \
b'w5y7O1MWzR1ePtQg1T1sg1s9UeoDRMZoVgzZdRXtQH1Jy9xpTeMfL31mlc3wOnitcH0AdWh' \
b'T7xnnlaCeJuMrX82PWtiJNd+Cy+bgyLfLMwX18cimwYCnyIHQ54qiiywXa1paVHkbEJdbd8' \
b'f4AxArsHX33xCv76wct2uXiHYAHu67rE5FhQ0mEqfIZHwuFljGPj5UMgyd6MRMuL2Ho1hL7' \
b'FDPIxDBv5tMWeZJszixIsCkA9Kc1ibylDz9Ix/keH1K9XXSb/o2EIfF6sWYcj0wNvJllIHA' \
b'fABEBAAG0QlJQTSBQYWNrYWdlciAoVGhlIGd1eSB3aG8gY3JlYXRlcyBwYWNrYWdlcykgPH' \
b'BhY2thZ2VyQGV4YW1wbGUuY29tPokBTgQTAQgAOBYhBMwU+9636QKkbYsjdMKSn1VZ4I5DB' \
b'QJals3sAhsDBQsJCAcCBhUKCQgLAgQWAgMBAh4BAheAAAoJEMKSn1VZ4I5D6icH/2GY2MMn' \
b'mcDO+ApIF6gGg9itzAHLTNcxEMl9ht1Gu3JQ/VdsvMQ6lG+U8yffEmsfQebtt1UaMVXzyt0' \
b'tcSOBJvVEI6qc6skvfea3hqL4srtTOCwu7ZBA9gOE+eB5BWBspFUVIwUO1GKT48uzV6CaOD' \
b'Litaxc7NrJ9HYw4C4+ICCfbIJhjM/HqxLKOqVy/jsySqIHK96RrjY/m8Q9Bzsi/6fj/GHke' \
b'waM8zaeNLHE7MgXFZAuJ8lzjD0r2oBDJGeBKfjjz9xh26YWjG/AoiolXfliTEox6p0bf820' \
b'eRhdX9UdSesBROL3rkB+hM5FOT8crSPJsuGZWJ9brikfsurWyU+5AQ0EWpbN7AEIAK0/PTh' \
b'uvsLdDGe5HeZn3VdrFcD9QSOV9Xjos8zWkwx8v0t4KXPM4GshyU2ddNjgA+00LhzjACm2ro' \
b'pT5vdvKPtf8lRGOcWWHkiMPdDW/R3/I5S0Oh1WFNrQZwQSXn/DoPnhUZNGErpZlUzF00BEl' \
b'twoVWgT1n81Bp486U3oziZnUM8kxXXY2PN8aTfWjsxOSmjyu2m7abeyjTqX9s++vUCQhmCN' \
b'boSY1AhXF8GQl1CempHVv0hOuC6BeadZRXEfEF0sQogswXpFhYG4GFUvVzKBn00/5phNWHv' \
b'ff1GDjzZzmVcRPje+rH6gGP8tpQn7NL1SvrazSqSOih//FfV73EMAEQEAAYkBNgQYAQgAIB' \
b'YhBMwU+9636QKkbYsjdMKSn1VZ4I5DBQJals3sAhsMAAoJEMKSn1VZ4I5DshgIALSnLy7KL' \
b'0bcqxoiEZT+P9O+gX34J2NEfITlu3MZyN26LbyJS7HuN1vmuUc/UM0ff7AW6eElCNFr5HQO' \
b'rFELUZWiX7f4U8ihRN39g1PKRGANlUcLm1Z/JnKyYbyzRK70o5A35EiXEHwY62c/b8I1N4k' \
b'zNKpa0eQcJ7F8XoZhau0UsxqueVPeEIaHX+fjbalz67eaiFTu8MurdGKntVE1dOPYbGvZE0' \
b'+HxfDOoVo05bRUH8By7dDgVaI9EijrVzjA5jHPJxNIj9AQP9W8zst3l3d9v8o0Pw+L4cWzv' \
b'+aBFakfjKGugs6lA53fB3RCfZ7OrMwCBvlTfDigK9X50K6XoP0='
class EmailToLocationTest(tests.support.TestCase):
def test_convert_simple_email_to_domain(self):
input = 'hugh@example.com'
output = 'c93f1e400f26708f98cb19d936620da35eec8f72e57f9eec01c1afd6._openpgpkey.example.com'
self.assertEqual(dnf.dnssec.email2location(input), output)
class KeyInfoTest(tests.support.TestCase):
def test_key_info_from_rpm_key_object_email_part(self):
key_info = dnf.dnssec.KeyInfo.from_rpm_key_object(RPM_USER, RPM_RAW_KEY)
self.assertEqual(key_info.email, EMAIL)
def test_key_info_from_rpm_key_object_key_part(self):
key_info = dnf.dnssec.KeyInfo.from_rpm_key_object(RPM_USER, RPM_RAW_KEY)
self.assertEqual(key_info.key, ASCII_RAW_KEY)
| 6,404
|
Python
|
.py
| 82
| 67.536585
| 99
| 0.76355
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,830
|
test_util.py
|
rpm-software-management_dnf/tests/test_util.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import operator
import os
import dnf.util
import tests.support
from tests.support import mock
class Slow(object):
def __init__(self, val):
self._val = val
self.computed = 0
def new_val(self, val):
self._val = val
del self._square1
del self._square2
@dnf.util.lazyattr("_square1")
def square1(self):
self.computed += 1
return self._val * self._val
@property
@dnf.util.lazyattr("_square2")
def square2(self):
self.computed += 1
return self._val * self._val
class Util(tests.support.TestCase):
def test_am_i_root(self):
with mock.patch('os.geteuid', return_value=1001):
self.assertFalse(dnf.util.am_i_root())
with mock.patch('os.geteuid', return_value=0):
assert(dnf.util.am_i_root())
def test_bunch(self):
b = dnf.util.Bunch()
self.assertRaises(AttributeError, lambda: b.more)
b.garden = 'weeds'
self.assertEqual(b['garden'], 'weeds')
b['digging'] = 4
self.assertEqual(b.digging, 4)
def test_empty(self):
self.assertTrue(dnf.util.empty(()))
self.assertFalse(dnf.util.empty([1, 2, 3]))
self.assertTrue(dnf.util.empty((x for x in [])))
self.assertTrue(dnf.util.empty(iter([])))
self.assertFalse(dnf.util.empty((x for x in [2, 3])))
def test_file_timestamp(self):
stat = mock.Mock()
stat.st_mtime = 123
with mock.patch('os.stat', return_value=stat):
self.assertEqual(dnf.util.file_timestamp("/yeah"), 123)
self.assertRaises(OSError, dnf.util.file_timestamp, "/does/not/ex1st")
def test_first(self):
self.assertEqual(dnf.util.first([5, 4, 3]), 5)
ge = (x for x in range(5, 8))
self.assertEqual(dnf.util.first(ge), 5)
self.assertEqual(dnf.util.first([]), None)
def generator():
if False:
yield 10
self.assertEqual(dnf.util.first(generator()), None)
def test_get_in(self):
dct = {1: {2: 3},
5: {8: {9: 10}}}
self.assertEqual(dnf.util.get_in(dct, (5, 8, 9), -3), 10)
self.assertEqual(dnf.util.get_in(dct, (5, 8, 8), -3), -3)
self.assertEqual(dnf.util.get_in(dct, (0, 8, 8), -3), -3)
def test_group_by_filter(self):
self.assertEqual(dnf.util.group_by_filter(lambda x: x % 2, range(5)),
([1, 3], [0, 2, 4]))
self.assertEqual(dnf.util.group_by_filter(lambda x: x, range(5)),
([1, 2, 3, 4], [0]))
def test_insert_if(self):
"""Test insert_if with sometimes fulfilled condition."""
item = object()
iterable = range(4)
def condition(item):
return item % 2 == 0
iterator = dnf.util.insert_if(item, iterable, condition)
self.assertEqual(next(iterator), item)
self.assertEqual(next(iterator), 0)
self.assertEqual(next(iterator), 1)
self.assertEqual(next(iterator), item)
self.assertEqual(next(iterator), 2)
self.assertEqual(next(iterator), 3)
self.assertRaises(StopIteration, next, iterator)
def test_is_exhausted_true(self):
"""Test is_exhausted with an iterator which is exhausted."""
iterator = iter(())
result = dnf.util.is_exhausted(iterator)
self.assertTrue(result)
def test_is_exhausted_false(self):
"""Test is_exhausted with an iterator which is not exhausted."""
iterator = iter((1,))
result = dnf.util.is_exhausted(iterator)
self.assertFalse(result)
def test_is_glob_pattern(self):
assert(dnf.util.is_glob_pattern("all*.ext"))
assert(dnf.util.is_glob_pattern("all?.ext"))
assert(not dnf.util.is_glob_pattern("not.ext"))
def test_lazyattr(self):
slow = Slow(12)
self.assertEqual(slow.computed, 0)
self.assertEqual(slow.square1(), 144)
self.assertEqual(slow.computed, 1)
self.assertEqual(slow.square1(), 144)
self.assertEqual(slow.square1(), 144)
self.assertEqual(slow.computed, 1)
self.assertEqual(slow.square2, 144)
self.assertEqual(slow.computed, 2)
self.assertEqual(slow.square2, 144)
self.assertEqual(slow.computed, 2)
slow.new_val(13)
self.assertEqual(slow.square1(), 169)
self.assertEqual(slow.square2, 169)
self.assertEqual(slow.computed, 4)
def test_mapall(self):
l = [1, 2, 3]
out = dnf.util.mapall(lambda n: 2 * n, l)
self.assertIsInstance(out, list)
self.assertEqual(out, [2, 4, 6])
def test_partition(self):
l = list(range(6))
smaller, larger = dnf.util.partition(lambda i: i > 4, l)
self.assertCountEqual(smaller, (0, 1, 2, 3, 4))
self.assertCountEqual(larger, (5,))
def test_split_by(self):
"""Test split_by with sometimes fulfilled condition."""
iterable = range(7)
def condition(item):
return item % 3 == 0
iterator = dnf.util.split_by(iterable, condition)
self.assertEqual(next(iterator), ())
self.assertEqual(next(iterator), (0, 1, 2))
self.assertEqual(next(iterator), (3, 4, 5))
self.assertEqual(next(iterator), (6,))
self.assertRaises(StopIteration, next, iterator)
def test_split_by_empty(self):
"""Test split with empty iterable."""
iterable = []
def condition(item):
return item % 3 == 0
iterator = dnf.util.split_by(iterable, condition)
self.assertEqual(next(iterator), ())
self.assertRaises(StopIteration, next, iterator)
def test_strip_prefix(self):
self.assertIsNone(dnf.util.strip_prefix("razorblade", "blade"))
self.assertEqual(dnf.util.strip_prefix("razorblade", "razor"), "blade")
def test_touch(self):
self.assertRaises(OSError, dnf.util.touch,
tests.support.NONEXISTENT_FILE, no_create=True)
def test_split_path(self):
path_orig = ""
path_split = dnf.util.split_path(path_orig)
path_join = os.path.join(*path_split)
self.assertEqual(path_split, [""])
self.assertEqual(path_join, path_orig)
path_orig = "/"
path_split = dnf.util.split_path(path_orig)
path_join = os.path.join(*path_split)
self.assertEqual(path_split, ["/"])
self.assertEqual(path_join, path_orig)
path_orig = "abc"
path_split = dnf.util.split_path(path_orig)
path_join = os.path.join(*path_split)
self.assertEqual(path_split, ["abc"])
self.assertEqual(path_join, path_orig)
path_orig = "/a/bb/ccc/dddd.conf"
path_split = dnf.util.split_path(path_orig)
path_join = os.path.join(*path_split)
self.assertEqual(path_split, ["/", "a", "bb", "ccc", "dddd.conf"])
self.assertEqual(path_join, path_orig)
class TestMultiCall(tests.support.TestCase):
def test_multi_call(self):
l = dnf.util.MultiCallList(["one", "two", "three"])
self.assertEqual(l.upper(), ["ONE", "TWO", "THREE"])
self.assertEqual(l.pop(), "three")
def test_assignment(self):
o1 = mock.Mock(x=3)
o2 = mock.Mock(x=5)
l = dnf.util.MultiCallList([o1, o2])
l.x = 5
self.assertEqual([5, 5], list(map(operator.attrgetter('x'), [o1, o2])))
| 8,540
|
Python
|
.py
| 197
| 35.258883
| 79
| 0.625287
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,831
|
test_repodict.py
|
rpm-software-management_dnf/tests/test_repodict.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2013-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import unicode_literals
import dnf.repodict
import tests.support
from tests.support import TestCase
class TestRepoDict(TestCase):
def setUp(self):
conf = tests.support.FakeConf()
self.x = tests.support.MockRepo('x', conf)
self.xx = tests.support.MockRepo('xx', conf)
self.y = tests.support.MockRepo('y', conf)
self.z = tests.support.MockRepo('z', conf)
self.repos = dnf.repodict.RepoDict()
self.repos.add(self.x)
self.repos.add(self.xx)
self.repos.add(self.y)
self.repos.add(self.z)
self.full_set = {self.x, self.xx, self.y, self.z}
def test_any_enabled(self):
self.assertTrue(self.repos._any_enabled())
self.repos.get_matching("*").disable()
self.assertFalse(self.repos._any_enabled())
def test_get_matching(self):
self.assertEqual(self.repos['x'], self.x)
self.assertCountEqual(self.repos.get_matching('*'), self.full_set)
self.assertCountEqual(self.repos.get_matching('y'), {self.y})
self.assertCountEqual(self.repos.get_matching('x*'), {self.x, self.xx})
self.assertCountEqual(self.repos.get_matching('nope'), [])
def test_iter_enabled(self):
self.assertCountEqual(self.repos.iter_enabled(), self.full_set)
self.repos.get_matching('x*').disable()
self.assertCountEqual(self.repos.iter_enabled(), {self.y, self.z})
def test_all(self):
self.assertCountEqual(self.repos.all(), self.full_set)
| 2,508
|
Python
|
.py
| 50
| 44.84
| 79
| 0.706051
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,832
|
test_crypto.py
|
rpm-software-management_dnf/tests/test_crypto.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import os
import tempfile
import dnf.crypto
import dnf.util
import dnf.yum.misc
import tests.support
FINGERPRINT = '88FBCE424BA9952A141A6A297B5443AEAA6F01F3'
KEYFILE = tests.support.resource_path('keys/key.pub')
KEYFILE_URL = 'file://%s' % KEYFILE
class CryptoTest(tests.support.TestCase):
PUBRING_DIR = None
@classmethod
def setUpClass(cls):
cls.PUBRING_DIR = tempfile.mkdtemp()
with open(KEYFILE, 'rb') as keyfile:
keyinfo = dnf.crypto.rawkey2infos(keyfile)[0]
dnf.yum.misc.import_key_to_pubring(
keyinfo.raw_key, keyinfo.short_id, gpgdir=cls.PUBRING_DIR,
make_ro_copy=False)
@classmethod
def tearDownClass(cls):
dnf.util.rm_rf(cls.PUBRING_DIR)
def test_keyids_from_pubring(self):
ids = dnf.crypto.keyids_from_pubring(self.PUBRING_DIR)
self.assertIn('7B5443AEAA6F01F3', ids)
def test_printable_fingerprint(self):
self.assertEqual(dnf.crypto._printable_fingerprint(FINGERPRINT),
'88FB CE42 4BA9 952A 141A 6A29 7B54 43AE AA6F 01F3')
def test_pubring_dir(self):
self.assertNotEqual(os.environ.get('GNUPGHOME'), self.PUBRING_DIR)
with dnf.crypto.pubring_dir(self.PUBRING_DIR):
self.assertEqual(os.environ['GNUPGHOME'], self.PUBRING_DIR)
def test_rawkey2infos(self):
with open(KEYFILE, 'rb') as keyfile:
info = dnf.crypto.rawkey2infos(keyfile)[0]
self.assertEqual(info.fingerprint, FINGERPRINT)
self.assertEqual(info.short_id, 'AA6F01F3')
self.assertEqual(info.rpm_id, 'aa6f01f3')
self.assertIn(b'E4bO2zVZwe\n', info.raw_key)
self.assertEqual(info.timestamp, 1721738657)
self.assertEqual(info.userid, 'Dandy Fied <dnf@example.com>')
def test_retrieve(self):
keyinfos = dnf.crypto.retrieve(KEYFILE_URL)
self.assertLength(keyinfos, 1)
keyinfo = keyinfos[0]
self.assertEqual(keyinfo.url, KEYFILE_URL)
| 3,059
|
Python
|
.py
| 65
| 41.430769
| 77
| 0.71961
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,833
|
test_comps.py
|
rpm-software-management_dnf/tests/test_comps.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2013-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import operator
import libcomps
import libdnf.transaction
import dnf.comps
import dnf.exceptions
import dnf.persistor
import dnf.util
import tests.support
from tests.support import mock
TRANSLATION = u"""Tato skupina zahrnuje nejmenší možnou množinu balíčků. Je vhodná například na instalace malých routerů nebo firewallů."""
class LangsTest(tests.support.TestCase):
@mock.patch('locale.getlocale', return_value=('cs_CZ', 'UTF-8'))
def test_get(self, _unused):
langs = dnf.comps._Langs().get()
self.assertEqual(langs, ['cs_CZ.UTF-8', 'cs_CZ', 'cs.UTF-8', 'cs', 'C'])
class CompsTest(tests.support.TestCase):
def setUp(self):
comps = dnf.comps.Comps()
comps._add_from_xml_filename(tests.support.COMPS_PATH)
self.comps = comps
def test_by_pattern(self):
comps = self.comps
self.assertLength(comps.groups_by_pattern('Base'), 1)
self.assertLength(comps.groups_by_pattern('*'), tests.support.TOTAL_GROUPS)
self.assertLength(comps.groups_by_pattern('Solid*'), 1)
group = dnf.util.first(comps.groups_by_pattern('Base'))
self.assertIsInstance(group, dnf.comps.Group)
def test_categories(self):
cat = self.comps.categories[0]
self.assertEqual(cat.name_by_lang['cs'], u'Základ systému')
self.assertEqual(cat.desc_by_lang['de'],
u'Verschiedene Kernstücke des Systems.')
self.assertCountEqual((id_.name for id_ in cat.group_ids),
('base', ))
self.assertCountEqual((id_.default for id_ in cat.group_ids),
(False, ))
self.assertTrue(all(isinstance(grp, dnf.comps.Group)
for grp in cat.groups_iter()))
def test_environments(self):
env = self.comps.environments[0]
self.assertEqual(env.name_by_lang['cs'], u'Prostředí Sugar')
self.assertEqual(env.desc_by_lang['de'],
u'Eine Software-Spielwiese zum Lernen des Lernens.')
self.assertCountEqual((id_.name for id_ in env.group_ids),
('somerset', 'Peppers'))
self.assertEqual(2, len(env.mandatory_groups))
self.assertTrue(all(isinstance(grp, dnf.comps.Group)
for grp in env.mandatory_groups))
self.assertCountEqual((id_.default for id_ in env.group_ids),
(True, False))
self.assertCountEqual((id_.name for id_ in env.option_ids),
('base',))
self.assertEqual(1, len(env.optional_groups))
self.assertTrue(all(isinstance(grp, dnf.comps.Group)
for grp in env.optional_groups))
self.assertTrue(all(isinstance(grp, dnf.comps.Group)
for grp in env.groups_iter()))
def test_groups(self):
g = self.comps.group_by_pattern('base')
self.assertTrue(g.visible)
g = self.comps.group_by_pattern('somerset')
self.assertFalse(g.visible)
def test_group_packages(self):
g = self.comps.group_by_pattern('base')
self.assertCountEqual(map(operator.attrgetter('name'), g.packages_iter()),
('tour', 'pepper'))
def test_iteration(self):
comps = self.comps
self.assertEqual([g.name for g in comps.groups_iter()],
['Base', 'Solid Ground', "Pepper's", "Broken Group", None])
self.assertEqual([c.name for c in comps.categories_iter()],
['Base System'])
g = dnf.util.first(comps.groups_iter())
self.assertEqual(g.desc_by_lang['cs'], TRANSLATION)
def test_group_display_order(self):
self.assertEqual([g.name for g in self.comps.groups],
["Pepper's", 'Base', 'Solid Ground', 'Broken Group', None])
def test_packages(self):
comps = self.comps
group = dnf.util.first(comps.groups_iter())
self.assertSequenceEqual([pkg.name for pkg in group.packages],
(u'pepper', u'tour'))
self.assertSequenceEqual([pkg.name for pkg in group.mandatory_packages],
(u'pepper', u'tour'))
def test_size(self):
comps = self.comps
self.assertLength(comps, 7)
self.assertLength(comps.groups, tests.support.TOTAL_GROUPS)
self.assertLength(comps.categories, 1)
self.assertLength(comps.environments, 1)
@mock.patch('locale.getlocale', return_value=('cs_CZ', 'UTF-8'))
def test_ui_name(self, _unused):
comps = self.comps
group = dnf.util.first(comps.groups_by_pattern('base'))
self.assertEqual(group.ui_name, u'Kritická cesta (Základ)')
@mock.patch('locale.getlocale', return_value=('cs_CZ', 'UTF-8'))
def test_ui_desc(self, _unused):
comps = self.comps
env = dnf.util.first(comps.environments_by_pattern('sugar-*'))
self.assertEqual(env.ui_description, u'Software pro výuku o vyučování.')
class PackageTest(tests.support.TestCase):
def test_instance(self):
lc_pkg = libcomps.Package('weather', libcomps.PACKAGE_TYPE_OPTIONAL)
pkg = dnf.comps.Package(lc_pkg)
self.assertEqual(pkg.name, 'weather')
self.assertEqual(pkg.option_type, dnf.comps.OPTIONAL)
class TestTransactionBunch(tests.support.TestCase):
def test_adding(self):
t1 = dnf.comps.TransactionBunch()
t1.install = {'right'}
t1.upgrade = {'tour'}
t1.remove = {'pepper'}
t2 = dnf.comps.TransactionBunch()
t2.install = {'pepper'}
t2.upgrade = {'right'}
t1 += t2
self.assertTransEqual(t1.install, ('right', 'pepper'))
self.assertTransEqual(t1.upgrade, ('tour', 'right'))
self.assertEmpty(t1.remove)
class SolverGroupTest(tests.support.DnfBaseTestCase):
REPOS = []
COMPS = True
COMPS_SOLVER = True
def test_install(self):
group_id = 'base'
trans = self.solver._group_install(group_id, dnf.comps.MANDATORY)
self.assertLength(trans.install, 2)
self._swdb_commit()
swdb_group = self.history.group.get(group_id)
self.assertCountEqual([i.getName() for i in swdb_group.getPackages()], ['pepper', 'tour'])
self.assertEqual(swdb_group.getPackageTypes(), dnf.comps.MANDATORY)
def test_removable_pkg(self):
comps_group = self.comps.group_by_pattern('base')
self.solver._group_install(comps_group.id, dnf.comps.MANDATORY, [])
tsis = []
pkg1 = self.base.sack.query().filter(name="pepper", epoch=0, version="20", release="0", arch="x86_64")[0]
self.history.rpm.add_install(pkg1, reason=libdnf.transaction.TransactionItemReason_GROUP)
pkg3 = self.base.sack.query().filter(name="tour", version="5", release="0", arch="noarch")[0]
self.history.rpm.add_install(pkg3, reason=libdnf.transaction.TransactionItemReason_GROUP)
group_id = "dupl"
swdb_group = self.history.group.new(group_id, group_id, group_id, dnf.comps.DEFAULT)
swdb_group.addPackage("tour", True, dnf.comps.MANDATORY)
self.history.group.install(swdb_group)
self._swdb_commit(tsis)
# pepper is in single group with reason "group"
self.assertTrue(self.solver._removable_pkg('pepper'))
# right's reason is "dep"
self.assertFalse(self.solver._removable_pkg('right'))
# tour appears in more than one group
self.assertFalse(self.solver._removable_pkg('tour'))
swdb_group = self.history.group.get(group_id)
self.history.group.remove(swdb_group)
# tour appears only in one group now
self.assertTrue(self.solver._removable_pkg('tour'))
def test_remove(self):
grp = self.comps.group_by_pattern('base')
self.solver._group_install(grp.id, dnf.comps.MANDATORY, [])
grps = self.history.group.search_by_pattern('base')
for grp in grps:
self.solver._group_remove(grp)
# need to load groups again - loaded object is stays the same
grps = self.history.group.search_by_pattern('base')
for grp in grps:
self.assertFalse(grp.installed)
def test_upgrade(self):
# setup of the "current state"
group_id = 'base'
swdb_group = self.history.group.new(group_id, group_id, group_id, dnf.comps.MANDATORY)
for pkg_name in ['pepper', 'handerson']:
swdb_group.addPackage(pkg_name, True, dnf.comps.MANDATORY)
self.history.group.install(swdb_group)
self._swdb_commit()
swdb_group = self.history.group.get(group_id)
self.assertCountEqual([i.getName() for i in swdb_group.getPackages()], ('handerson', 'pepper'))
comps_group = self.comps.group_by_pattern(group_id)
trans = self.solver._group_upgrade(group_id)
self.assertTransEqual(trans.install, ('tour',))
self.assertTransEqual(trans.remove, ('handerson',))
self.assertTransEqual(trans.upgrade, ('pepper',))
self._swdb_commit()
swdb_group = self.history.group.get(group_id)
self.assertCountEqual([i.getName() for i in swdb_group.getPackages()], ('tour', 'pepper'))
class SolverEnvironmentTest(tests.support.DnfBaseTestCase):
REPOS = []
COMPS = True
COMPS_SOLVER = True
def test_install(self):
env_id = 'sugar-desktop-environment'
env = self.comps._environment_by_id(env_id)
trans = self.solver._environment_install(env_id, dnf.comps.MANDATORY, [])
self._swdb_commit()
self.assertCountEqual([pkg.name for pkg in trans.install], ('pepper', 'trampoline', 'hole', 'lotus'))
sugar = self.history.env.get(env_id)
self.assertCountEqual([i.getGroupId() for i in sugar.getGroups()], ('Peppers', 'somerset', 'base'))
somerset = self.history.group.get('somerset')
self.assertIsNotNone(somerset)
self.assertEqual(somerset.getPackageTypes(), dnf.comps.MANDATORY)
base = self.history.group.get('base')
self.assertEqual(base, None)
def test_remove(self):
env_id = 'sugar-desktop-environment'
comps_env = self.comps.environment_by_pattern(env_id)
self.solver._environment_install(comps_env.id, dnf.comps.MANDATORY, [])
self._swdb_commit()
swdb_env = self.history.env.get(comps_env.id)
self.assertEqual(swdb_env.getPackageTypes(), dnf.comps.MANDATORY)
group_ids = [i.getGroupId() for i in swdb_env.getGroups()]
self.solver._environment_remove(comps_env.id)
self._swdb_commit()
swdb_env = self.history.env.get(comps_env.id)
# if swdb_env is None, then it's removed
self.assertIsNone(swdb_env)
# test if also all groups were removed
for group_id in group_ids:
swdb_group = self.history.group.get(group_id)
self.assertIsNone(swdb_group)
# install it again with different pkg_types
self.solver._environment_install(comps_env.id, dnf.comps.OPTIONAL, [])
self._swdb_commit()
swdb_env = self.history.env.get(comps_env.id)
self.assertIsNotNone(swdb_env)
self.assertEqual(swdb_env.getPackageTypes(), dnf.comps.OPTIONAL)
group_ids = [i.getGroupId() for i in swdb_env.getGroups()]
self.assertTrue(len(group_ids))
for group_id in group_ids:
swdb_group = self.history.group.get(group_id)
if group_id == "base" and swdb_group is None:
continue
self.assertEqual(swdb_group.getPackageTypes(), dnf.comps.OPTIONAL)
def test_upgrade(self):
"""Upgrade environment, the one group it knows is no longer installed."""
env_id = "sugar-desktop-environment"
comps_env = self.comps.environment_by_pattern(env_id)
self.solver._environment_install(comps_env.id, dnf.comps.ALL_TYPES, [])
self._swdb_commit()
swdb_env = self.history.env.get(comps_env.id)
self.assertNotEqual(swdb_env, None)
# create a new transaction item for group Peppers with no packages
self._swdb_commit()
swdb_group = self.history.group.get('Peppers')
swdb_group = self.history.group.new(swdb_group.getGroupId(), swdb_group.getName(), swdb_group.getTranslatedName(), swdb_group.getPackageTypes())
self.history.group.install(swdb_group)
self._swdb_commit()
trans = self.solver._environment_upgrade(comps_env.id)
self._swdb_commit()
self.assertTransEqual(trans.install, ('hole', 'lotus'))
self.assertTransEqual(trans.upgrade, ('pepper', 'trampoline', 'lotus'))
self.assertEmpty(trans.remove)
| 13,912
|
Python
|
.py
| 268
| 42.645522
| 152
| 0.649542
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,834
|
test_repoquery.py
|
rpm-software-management_dnf/tests/test_repoquery.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import dnf.cli.commands.repoquery
import dnf.exceptions
import tests.support
from tests.support import mock
EXPECTED_INFO_FORMAT = """\
Name : foobar
Version : 1.0.1
Release : 1.f20
Architecture: x86_64
Size : 100
License : BSD
Source RPM : foo-1.0.1-1.f20.src.rpm
Build Date : 1970-01-01 00:02
Packager : Eastford
URL : foorl.net
Summary : it.
Description :
A desc.A desc.A desc.A desc.A desc.A desc.A desc.A desc.\n"""
EXPECTED_FILELIST_FORMAT = """\
/tmp/foobar
/var/foobar\
"""
EXPECTED_SOURCERPM_FORMAT = """\
foo-1.0.1-1.f20.src.rpm"""
class PkgStub(object):
def __init__(self):
self.arch = 'x86_64'
self.buildtime = 120
self.description = 'A desc.' * 8
self.license = 'BSD'
self.name = 'foobar'
self.packager = 'Eastford'
self.release = '1.f20'
self.reponame = '@System'
self._size = 100
self.sourcerpm = 'foo-1.0.1-1.f20.src.rpm'
self.summary = 'it.'
self.url = 'foorl.net'
self.version = '1.0.1'
self.files = ['/tmp/foobar', '/var/foobar']
class ArgParseTest(tests.support.TestCase):
def setUp(self):
self.cmd = dnf.cli.commands.repoquery.RepoQueryCommand(
tests.support.CliStub(tests.support.BaseCliStub()))
def test_parse(self):
tests.support.command_configure(self.cmd, ['--whatrequires', 'prudence'])
self.assertEqual(self.cmd.opts.whatprovides, [])
self.assertEqual(self.cmd.opts.whatrequires, ['prudence'])
self.assertEqual(self.cmd.opts.queryformat,
dnf.cli.commands.repoquery.QFORMAT_DEFAULT)
@mock.patch('argparse.ArgumentParser.print_help', lambda x: x)
def test_conflict(self):
with self.assertRaises(SystemExit) as sysexit, \
tests.support.patch_std_streams() as (stdout, stderr):
tests.support.command_configure(self.cmd, ['--conflicts', '%{name}', '--provides'])
self.assertEqual(sysexit.exception.code, 1)
def test_options(self):
for arg in ('conflicts', 'enhances', 'provides',
'recommends', 'requires', 'suggests', 'supplements'):
tests.support.command_configure(self.cmd, ['--' + arg])
self.assertEqual(self.cmd.opts.packageatr, arg)
def test_file(self):
tests.support.command_configure(self.cmd, ['/var/foobar'])
self.assertIsNone(self.cmd.opts.file)
class FilelistFormatTest(tests.support.TestCase):
def test_filelist(self):
self.cmd = dnf.cli.commands.repoquery.RepoQueryCommand(
tests.support.CliStub(tests.support.BaseCliStub()))
tests.support.command_configure(self.cmd, ['-l'])
pkg = dnf.cli.commands.repoquery.PackageWrapper(PkgStub())
self.assertEqual(self.cmd.build_format_fn(self.cmd.opts, pkg),
EXPECTED_FILELIST_FORMAT)
class SourceRPMFormatTest(tests.support.TestCase):
def test_info(self):
self.cmd = dnf.cli.commands.repoquery.RepoQueryCommand(
tests.support.CliStub(tests.support.BaseCliStub()))
tests.support.command_configure(self.cmd, ['--source'])
pkg = dnf.cli.commands.repoquery.PackageWrapper(PkgStub())
self.assertEqual(self.cmd.build_format_fn(self.cmd.opts, pkg),
EXPECTED_SOURCERPM_FORMAT)
class OutputTest(tests.support.TestCase):
def test_output(self):
pkg = dnf.cli.commands.repoquery.PackageWrapper(PkgStub())
fmt = dnf.cli.commands.repoquery.rpm2py_format(
'%{NAME}-%{version}-%{RELEASE}.%{arch} (%{REPONAME})')
self.assertEqual(fmt.format(pkg), 'foobar-1.0.1-1.f20.x86_64 (@System)')
def test_nonexistant_attr(self):
"""
dnf.package.Package does not have a 'notfound' attribute.
Therefore, rpm2py_format should leave a %{notfound}
"""
pkg = dnf.cli.commands.repoquery.PackageWrapper(PkgStub())
fmt = dnf.cli.commands.repoquery.rpm2py_format('%{notfound}').format(pkg)
self.assertEqual(fmt, "%{notfound}")
def test_illegal_attr(self):
"""
dnf.package.Package has a 'base' attribute,
but it isn't allowed in queryformat strings and
should also leave a literal %{base}.
"""
pkg = dnf.cli.commands.repoquery.PackageWrapper(PkgStub())
fmt = dnf.cli.commands.repoquery.rpm2py_format("%{base}").format(pkg)
self.assertEqual(fmt, "%{base}")
def test_combo_attr(self):
"""
Ensure that illegal attributes in a queryformat string along with legal
attributes are properly escaped.
"""
pkg = dnf.cli.commands.repoquery.PackageWrapper(PkgStub())
fmt = dnf.cli.commands.repoquery.rpm2py_format(
"%{name} | %{base} | {brackets}").format(pkg)
self.assertEqual(fmt, "foobar | %{base} | {brackets}")
class Rpm2PyFormatTest(tests.support.TestCase):
def test_rpm2py_format(self):
fmt = dnf.cli.commands.repoquery.rpm2py_format('%{name}')
self.assertEqual(fmt, '{0.name}')
fmt = dnf.cli.commands.repoquery.rpm2py_format('%40{name}')
self.assertEqual(fmt, '{0.name:<40}')
fmt = dnf.cli.commands.repoquery.rpm2py_format('%-40{name}')
self.assertEqual(fmt, '{0.name:>40}')
fmt = dnf.cli.commands.repoquery.rpm2py_format(
'%{name}-%{repoid} :: %-40{arch}')
self.assertEqual(fmt, '{0.name}-{0.repoid} :: {0.arch:>40}')
| 6,623
|
Python
|
.py
| 143
| 39.531469
| 99
| 0.663825
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,835
|
test_config.py
|
rpm-software-management_dnf/tests/test_config.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import unicode_literals
import argparse
import dnf.conf
import dnf.conf.read
import dnf.exceptions
from dnf.conf import BaseConfig, Conf, RepoConf
import tests.support
from tests.support import mock
class CacheTest(tests.support.TestCase):
@mock.patch('dnf.util.am_i_root', return_value=True)
@mock.patch('dnf.const.SYSTEM_CACHEDIR', '/var/lib/spinning')
def test_root(self, unused_am_i_root):
conf = dnf.conf.Conf()
self.assertEqual(conf.system_cachedir, '/var/lib/spinning')
self.assertEqual(conf.cachedir, '/var/lib/spinning')
@mock.patch('dnf.yum.misc.getCacheDir',
return_value="/notmp/dnf-walr-yeAH")
@mock.patch('dnf.util.am_i_root', return_value=False)
@mock.patch('dnf.const.SYSTEM_CACHEDIR', '/var/lib/spinning')
def test_noroot(self, fn_root, fn_getcachedir):
self.assertEqual(fn_getcachedir.call_count, 0)
conf = dnf.conf.Conf()
self.assertEqual(conf.cachedir, '/notmp/dnf-walr-yeAH')
self.assertEqual(fn_getcachedir.call_count, 1)
class ConfTest(tests.support.TestCase):
def test_bugtracker(self):
conf = Conf()
self.assertEqual(conf.bugtracker_url,
"https://bugzilla.redhat.com/enter_bug.cgi" +
"?product=Fedora&component=dnf")
def test_conf_from_file(self):
conf = Conf()
# defaults
self.assertFalse(conf.gpgcheck)
self.assertEqual(conf.installonly_limit, 3)
self.assertTrue(conf.clean_requirements_on_remove)
conf.config_file_path = '%s/etc/dnf/dnf.conf' % tests.support.dnf_toplevel()
conf.read(priority=dnf.conf.PRIO_MAINCONFIG)
self.assertTrue(conf.gpgcheck)
self.assertEqual(conf.installonly_limit, 3)
self.assertTrue(conf.clean_requirements_on_remove)
def test_overrides(self):
conf = Conf()
self.assertFalse(conf.assumeyes)
self.assertFalse(conf.assumeno)
self.assertEqual(conf.color, 'auto')
opts = argparse.Namespace(assumeyes=True, color='never')
conf._configure_from_options(opts)
self.assertTrue(conf.assumeyes)
self.assertFalse(conf.assumeno) # no change
self.assertEqual(conf.color, 'never')
def test_order_insensitive(self):
conf = Conf()
conf.config_file_path = '%s/etc/dnf/dnf.conf' % tests.support.dnf_toplevel()
opts = argparse.Namespace(
gpgcheck=False,
main_setopts={'installonly_limit': ['5']}
)
# read config
conf.read(priority=dnf.conf.PRIO_MAINCONFIG)
# update from commandline
conf._configure_from_options(opts)
self.assertFalse(conf.gpgcheck)
self.assertEqual(conf.installonly_limit, 5)
# and the other way round should have the same result
# update from commandline
conf._configure_from_options(opts)
# read config
conf.read(priority=dnf.conf.PRIO_MAINCONFIG)
self.assertFalse(conf.gpgcheck)
self.assertEqual(conf.installonly_limit, 5)
def test_inheritance1(self):
conf = Conf()
repo = RepoConf(conf)
# minrate is inherited from conf
# default should be the same
self.assertEqual(conf.minrate, 1000)
self.assertEqual(repo.minrate, 1000)
# after conf change, repoconf still should inherit its value
conf.minrate = 2000
self.assertEqual(conf.minrate, 2000)
self.assertEqual(repo.minrate, 2000)
def test_inheritance2(self):
conf = Conf()
# if repoconf reads value from config it no more inherits changes from conf
conf.config_file_path = tests.support.resource_path('etc/repos.conf')
with mock.patch('logging.Logger.warning'):
reader = dnf.conf.read.RepoReader(conf, {})
repo = list(reader)[0]
self.assertEqual(conf.minrate, 1000)
self.assertEqual(repo.minrate, 4096)
# after global change
conf.minrate = 2000
self.assertEqual(conf.minrate, 2000)
self.assertEqual(repo.minrate, 4096)
def test_prepend_installroot(self):
conf = Conf()
conf.installroot = '/mnt/root'
conf.prepend_installroot('persistdir')
self.assertEqual(conf.persistdir, '/mnt/root/var/lib/dnf')
def test_ranges(self):
conf = Conf()
with self.assertRaises(dnf.exceptions.ConfigError):
conf.debuglevel = '11'
| 5,495
|
Python
|
.py
| 121
| 37.966942
| 84
| 0.681376
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,836
|
test_match_counter.py
|
rpm-software-management_dnf/tests/test_match_counter.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf.match_counter
import tests.support
from tests.support import mock
class PackageStub(tests.support.MockPackage):
@classmethod
def several(cls, count):
for _ in range(count):
yield cls()
def __init__(self, nevra='nevra-1-1.noarch', summary='summary'):
super(PackageStub, self).__init__(nevra)
self.summary = summary
self.url = ''
self.description = ''
class MatchCounterTest(tests.support.TestCase):
def test_canonize_string_set(self):
a = ['f', 'p']
b = ['p']
self.assertLess(dnf.match_counter._canonize_string_set(b, 2),
dnf.match_counter._canonize_string_set(a, 2))
def test_matched(self):
pkg = tests.support.MockPackage("humbert-1-1.noarch")
pkg.url = url = "http://humbert.com"
pkg.summary = summary = "Glimpses of an incomparably more poignant bliss."
counter = dnf.match_counter.MatchCounter()
counter.add(pkg, 'summary', 'poignant')
counter.add(pkg, 'url', 'humbert')
counter.add(pkg, 'summary', 'humbert')
self.assertCountEqual(counter.matched_needles(pkg),
['humbert', 'poignant'])
self.assertCountEqual(counter.matched_keys(pkg), ['url', 'summary'])
self.assertCountEqual(counter.matched_haystacks(pkg), [url, summary])
def test_sorted(self):
counter = dnf.match_counter.MatchCounter()
self.assertEqual(counter.sorted(), [])
counter = dnf.match_counter.MatchCounter()
pkg1, pkg2, pkg3 = PackageStub().several(3)
counter.add(pkg1, 'name', '')
counter.add(pkg2, 'summary', '')
self.assertEqual(counter.sorted(), [pkg1, pkg2])
counter.add(pkg3, 'url', '')
self.assertEqual(counter.sorted(), [pkg1, pkg2, pkg3])
self.assertEqual(counter.sorted(reverse=True), [pkg1, pkg2, pkg3])
def test_sorted_with_needles(self):
# the same needles should be listed together:
counter = dnf.match_counter.MatchCounter()
pkg1, pkg2, pkg3, pkg4 = PackageStub().several(4)
counter.add(pkg1, 'summary', 'grin')
counter.add(pkg2, 'summary', 'foolish')
counter.add(pkg3, 'summary', 'grin')
counter.add(pkg4, 'summary', 'grin')
srt = counter.sorted()
self.assertEqual(srt.index(pkg2), 1)
# more unique needles is more than less unique needles:
counter = dnf.match_counter.MatchCounter()
counter.add(pkg1, 'summary', 'a')
counter.add(pkg1, 'summary', 'b')
counter.add(pkg2, 'summary', 'b')
counter.add(pkg2, 'summary', 'b')
self.assertSequenceEqual(counter.sorted(), (pkg1, pkg2))
def test_sorted_limit(self):
counter = dnf.match_counter.MatchCounter()
pkg1, pkg2, pkg3 = PackageStub().several(3)
counter.add(pkg1, 'name', '')
counter.add(pkg2, 'url', '')
counter.add(pkg3, 'description', '')
self.assertSequenceEqual(counter.sorted(limit_to=[pkg1, pkg2]),
(pkg1, pkg2))
def test_sorted_exact_match(self):
"""Exactly matching the name beats name and summary non-exact match."""
counter = dnf.match_counter.MatchCounter()
pkg1 = PackageStub('wednesday-1-1.noarch', 'morning')
pkg2 = PackageStub('wednesdaymorning-1-1.noarch', "5 o'clock")
counter.add(pkg1, 'name', 'wednesday')
counter.add(pkg2, 'name', 'wednesday')
counter.add(pkg2, 'summary', 'clock')
self.assertSequenceEqual(counter.sorted(), (pkg1, pkg2))
def test_total(self):
counter = dnf.match_counter.MatchCounter()
counter.add(3, 'summary', 'humbert')
counter.add(3, 'url', 'humbert')
counter.add(20, 'summary', 'humbert')
self.assertEqual(len(counter), 2)
self.assertEqual(counter.total(), 3)
def test_distance(self):
pkg2 = tests.support.MockPackage('rust-and-stardust-1-2.x86_64')
pkg1 = tests.support.MockPackage('rust-1-3.x86_64')
counter = dnf.match_counter.MatchCounter()
counter.add(pkg1, 'name', 'rust')
counter.add(pkg2, 'name', 'rust')
# 'rust-and-stardust' is a worse match for 'rust' than 'rust' itself
self.assertSequenceEqual([x.name for x in counter.sorted()],
['rust', 'rust-and-stardust'])
| 5,489
|
Python
|
.py
| 111
| 41.558559
| 82
| 0.648871
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,837
|
test_reinstall.py
|
rpm-software-management_dnf/tests/test_reinstall.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import itertools
import dnf
import tests.support
class Reinstall(tests.support.ResultTestCase):
REPOS = ['main', 'updates']
def setUp(self):
super(Reinstall, self).setUp()
self.base.conf.multilib_policy = 'all'
def test_package_reinstall(self):
p = self.base.sack.query().available().filter(
nevra="librita-1-1.x86_64")[0]
self.assertEqual(1, self.base.package_reinstall(p))
self.base.resolve()
self.assertEqual(1, len(self.base._goal.list_reinstalls()))
def test_package_reinstall_fail(self):
p = self.base.sack.query().available().filter(nevra="hole-1-2.x86_64")[0]
with self.assertRaises(dnf.exceptions.MarkingError) as context:
self.base.package_reinstall(p)
self.assertEqual(context.exception.pkg_spec, 'hole')
self.base.resolve()
self.assertEmpty(self.base._goal.list_downgrades())
def test_reinstall(self):
cnt = self.base.reinstall('pepper')
self.assertEqual(cnt, 1)
new_set = tests.support.installed_but(self.sack, "pepper")
available_query = self.sack.query().available()
new_set += list(available_query._nevra("pepper-20-0.x86_64"))
self.assertResult(self.base, new_set)
def test_reinstall_new_reponame_available(self):
"""Test whether it installs packages only from the repository."""
reinstalled_count = self.base.reinstall('librita', new_reponame='main')
self.assertEqual(reinstalled_count, 1)
self.assertResult(self.base, itertools.chain(
self.sack.query().installed().filter(name__neq='librita'),
dnf.subject.Subject('librita.i686').get_best_query(self.sack).installed(),
dnf.subject.Subject('librita').get_best_query(self.sack).available()))
def test_reinstall_new_reponame_notavailable(self):
"""Test whether it installs packages only from the repository."""
self.assertRaises(
dnf.exceptions.PackagesNotAvailableError,
self.base.reinstall, 'librita', new_reponame='non-main')
def test_reinstall_new_reponame_neq_available(self):
"""Test whether it installs only packages not from the repository."""
reinstalled_count = self.base.reinstall('librita', new_reponame_neq='non-main')
self.assertEqual(reinstalled_count, 1)
self.assertResult(self.base, itertools.chain(
self.sack.query().installed().filter(name__neq='librita'),
dnf.subject.Subject('librita.i686').get_best_query(self.sack).installed(),
dnf.subject.Subject('librita').get_best_query(self.sack).available()))
def test_reinstall_new_reponame_neq_notavailable(self):
"""Test whether it installs only packages not from the repository."""
self.assertRaises(
dnf.exceptions.PackagesNotAvailableError,
self.base.reinstall, 'librita', new_reponame_neq='main')
def test_reinstall_notfound(self):
"""Test whether it fails if the package does not exist."""
with self.assertRaises(dnf.exceptions.PackagesNotInstalledError) as ctx:
self.base.reinstall('non-existent')
self.assertEqual(ctx.exception.pkg_spec, 'non-existent')
self.assertResult(self.base, self.sack.query().installed())
def test_reinstall_notinstalled(self):
"""Test whether it fails if the package is not installed."""
with self.assertRaises(dnf.exceptions.PackagesNotInstalledError) as ctx:
self.base.reinstall('lotus')
self.assertEqual(ctx.exception.pkg_spec, 'lotus')
self.assertResult(self.base, self.sack.query().installed())
def test_reinstall_notavailable(self):
"""Test whether it fails if the package is not available."""
with self.assertRaises(dnf.exceptions.PackagesNotAvailableError) as ctx:
self.base.reinstall('hole')
self.assertEqual(ctx.exception.pkg_spec, 'hole')
self.assertCountEqual(
ctx.exception.packages,
dnf.subject.Subject('hole').get_best_query(self.sack).installed())
self.assertResult(self.base, self.sack.query().installed())
def test_reinstall_notavailable_available(self):
"""Test whether it does not fail if some packages are available and some not."""
reinstalled_count = self.base.reinstall('librita')
self.assertEqual(reinstalled_count, 1)
self.assertResult(self.base, itertools.chain(
self.sack.query().installed().filter(name__neq='librita'),
dnf.subject.Subject('librita.i686').get_best_query(self.sack).installed(),
dnf.subject.Subject('librita').get_best_query(self.sack).available()))
def test_reinstall_old_reponame_installed(self):
"""Test whether it reinstalls packages only from the repository."""
self.base = tests.support.MockBase('main')
self.base.conf.multilib_policy = 'all'
for pkg in self.base.sack.query().installed().filter(name='librita'):
pkg._force_swdb_repoid = "main"
self.history.rpm.add_install(pkg)
self._swdb_commit()
reinstalled_count = self.base.reinstall('librita', old_reponame='main')
self.assertEqual(reinstalled_count, 1)
self.assertResult(self.base, itertools.chain(
self.sack.query().installed().filter(name__neq='librita'),
dnf.subject.Subject('librita.i686').get_best_query(self.sack).installed(),
dnf.subject.Subject('librita').get_best_query(self.sack).available())
)
def test_reinstall_old_reponame_notinstalled(self):
"""Test whether it reinstalls packages only from the repository."""
self.assertRaises(
dnf.exceptions.PackagesNotInstalledError,
self.base.reinstall, 'librita', old_reponame='non-main'
)
def test_reinstall_remove_notavailable(self):
"""Test whether it removes the package which is not available."""
self.base.reinstall('hole', remove_na=True)
self.assertResult(
self.base,
self.sack.query().installed().filter(name__neq='hole')
)
| 7,263
|
Python
|
.py
| 130
| 47.623077
| 88
| 0.686576
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,838
|
support.py
|
rpm-software-management_dnf/tests/support.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import contextlib
import logging
import os
import re
import shutil
import sys
import tempfile
import unittest
from functools import reduce
import hawkey
import hawkey.test
import libdnf.transaction
import dnf
import dnf.conf
import dnf.cli.cli
import dnf.cli.demand
import dnf.cli.option_parser
import dnf.comps
import dnf.exceptions
import dnf.goal
import dnf.i18n
import dnf.package
import dnf.persistor
import dnf.pycomp
import dnf.repo
import dnf.sack
if dnf.pycomp.PY3:
from unittest import mock
from unittest.mock import MagicMock, mock_open
else:
from tests import mock
from tests.mock import MagicMock
def mock_open(mock=None, data=None):
if mock is None:
mock = MagicMock(spec=file)
handle = MagicMock(spec=file)
handle.write.return_value = None
if data is None:
handle.__enter__.return_value = handle
else:
handle.__enter__.return_value = data
mock.return_value = handle
return mock
logger = logging.getLogger('dnf')
skip = unittest.skip
TRACEBACK_RE = re.compile(
r'(Traceback \(most recent call last\):\n'
r'(?: File "[^"\n]+", line \d+, in \w+\n'
r'(?: .+\n)?'
r'(?: \s*\~*\^+\~*\n)?)+'
r'\S.*\n)')
REASONS = {
'hole': 'group',
'pepper': 'group',
'right': 'dep',
'tour': 'group',
'trampoline': 'group',
}
# @System.repo doesn't provide sha1header/pkgid
# the checksum is computed from an empty string
RPMDB_CHECKSUM = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'
TOTAL_RPMDB_COUNT = 10
SYSTEM_NSOLVABLES = TOTAL_RPMDB_COUNT
MAIN_NSOLVABLES = 9
UPDATES_NSOLVABLES = 4
AVAILABLE_NSOLVABLES = MAIN_NSOLVABLES + UPDATES_NSOLVABLES
TOTAL_GROUPS = 5
TOTAL_NSOLVABLES = SYSTEM_NSOLVABLES + AVAILABLE_NSOLVABLES
# testing infrastructure
def dnf_toplevel():
return os.path.normpath(os.path.join(__file__, '../../'))
def repo(reponame):
return os.path.join(REPO_DIR, reponame)
def resource_path(path):
this_dir = os.path.dirname(__file__)
return os.path.join(this_dir, path)
REPO_DIR = resource_path('repos')
COMPS_PATH = os.path.join(REPO_DIR, 'main_comps.xml')
NONEXISTENT_FILE = resource_path('does-not/exist')
TOUR_44_PKG_PATH = resource_path('repos/rpm/tour-4-4.noarch.rpm')
TOUR_50_PKG_PATH = resource_path('repos/rpm/tour-5-0.noarch.rpm')
TOUR_51_PKG_PATH = resource_path('repos/rpm/tour-5-1.noarch.rpm')
USER_RUNDIR = '/tmp/dnf-user-rundir'
# often used query
def installed_but(sack, *args):
q = sack.query().filter(reponame__eq=hawkey.SYSTEM_REPO_NAME)
return reduce(lambda query, name: query.filter(name__neq=name), args, q)
# patching the stdout
@contextlib.contextmanager
def patch_std_streams():
with mock.patch('sys.stdout', new_callable=dnf.pycomp.StringIO) as stdout, \
mock.patch('sys.stderr', new_callable=dnf.pycomp.StringIO) as stderr:
yield (stdout, stderr)
@contextlib.contextmanager
def wiretap_logs(logger_name, level, stream):
"""Record *logger_name* logs of at least *level* into the *stream*."""
logger = logging.getLogger(logger_name)
orig_level = logger.level
logger.setLevel(level)
handler = logging.StreamHandler(stream)
orig_handlers = logger.handlers
logger.handlers = []
logger.addHandler(handler)
try:
yield stream
finally:
logger.removeHandler(handler)
logger.setLevel(orig_level)
logger.handlers = orig_handlers
def command_configure(cmd, args):
parser = dnf.cli.option_parser.OptionParser()
args = [cmd._basecmd] + args
parser.parse_main_args(args)
parser.parse_command_args(cmd, args)
return cmd.configure()
def command_run(cmd, args):
command_configure(cmd, args)
return cmd.run()
class Base(dnf.Base):
def __init__(self, *args, **kwargs):
with mock.patch('dnf.rpm.detect_releasever', return_value=69):
super(Base, self).__init__(*args, **kwargs)
# mock objects
def mock_comps(history, seed_history):
comps = dnf.comps.Comps()
comps._add_from_xml_filename(COMPS_PATH)
if seed_history:
name = 'Peppers'
pkg_types = dnf.comps.MANDATORY
swdb_group = history.group.new(name, name, name, pkg_types)
for pkg_name in ['hole', 'lotus']:
swdb_group.addPackage(pkg_name, True, dnf.comps.MANDATORY)
history.group.install(swdb_group)
name = 'somerset'
pkg_types = dnf.comps.MANDATORY
swdb_group = history.group.new(name, name, name, pkg_types)
for pkg_name in ['pepper', 'trampoline', 'lotus']:
swdb_group.addPackage(pkg_name, True, dnf.comps.MANDATORY)
history.group.install(swdb_group)
name = 'sugar-desktop-environment'
pkg_types = dnf.comps.ALL_TYPES
swdb_env = history.env.new(name, name, name, pkg_types)
for group_id in ['Peppers', 'somerset']:
swdb_env.addGroup(group_id, True, dnf.comps.MANDATORY)
history.env.install(swdb_env)
return comps
def mock_logger():
return mock.create_autospec(logger)
class _BaseStubMixin(object):
"""A reusable class for creating `dnf.Base` stubs.
See also: hawkey/test/python/__init__.py.
Note that currently the used TestSack has always architecture set to
"x86_64". This is to get the same behavior when running unit tests on
different arches.
"""
def __init__(self, *extra_repos, **config_opts):
super(_BaseStubMixin, self).__init__(FakeConf(**config_opts))
for r in extra_repos:
repo = MockRepo(r, self.conf)
repo.enable()
self._repos.add(repo)
self._repo_persistor = FakePersistor()
self._ds_callback = mock.Mock()
self._history = None
self._closed = False
self._closing = False
def add_test_dir_repo(self, id_, cachedir):
"""Add a repository located in a directory in the tests."""
repo = dnf.repo.Repo(id_, cachedir)
repo.baseurl = ['file://%s/%s' % (REPO_DIR, repo.id)]
self.repos.add(repo)
return repo
def close(self):
self._closing = True
super(_BaseStubMixin, self).close()
@property
def history(self):
if self._history:
return self._history
else:
self._history = super(_BaseStubMixin, self).history
if not self._closing:
# don't reset db on close, it causes several tests to fail
self._history.reset_db()
return self._history
@property
def sack(self):
if self._sack:
return self._sack
return self.init_sack()
def _build_comps_solver(self):
return dnf.comps.Solver(self.history, self._comps,
REASONS.get)
def _activate_persistor(self):
pass
def init_sack(self):
# Create the Sack, tell it how to build packages, passing in the Package
# class and a Base reference.
self._sack = TestSack(REPO_DIR, self)
self._sack.load_system_repo()
for repo in self.repos.iter_enabled():
if repo.__class__ is dnf.repo.Repo:
self._add_repo_to_sack(repo)
else:
fn = "%s.repo" % repo.id
self._sack.load_test_repo(repo.id, fn)
self._sack._configure(self.conf.installonlypkgs)
self._goal = dnf.goal.Goal(self._sack)
self._goal.protect_running_kernel = self.conf.protect_running_kernel
return self._sack
def mock_cli(self):
stream = dnf.pycomp.StringIO()
logger = logging.getLogger('test')
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler(stream))
return mock.Mock(base=self, log_stream=stream, logger=logger,
demands=dnf.cli.demand.DemandSheet())
def read_mock_comps(self, seed_history=True):
self._comps = mock_comps(self.history, seed_history)
return self._comps
def read_all_repos(self, opts=None):
for repo in self.repos.values():
repo._configure_from_options(opts)
def set_debuglevel(self, level):
self.conf._set_value('debuglevel', level, dnf.conf.PRIO_RUNTIME)
class BaseCliStub(_BaseStubMixin, dnf.cli.cli.BaseCli):
"""A class mocking `dnf.cli.cli.BaseCli`."""
def __init__(self, *extra_repos, **config_opts):
"""Initialize the base."""
super(BaseCliStub, self).__init__(*extra_repos, **config_opts)
self.output.term = MockTerminal()
class DemandsStub(object):
pass
class CliStub(object):
"""A class mocking `dnf.cli.Cli`."""
def __init__(self, base):
"""Initialize the CLI."""
self.base = base
self.cli_commands = {}
self.demands = DemandsStub()
self.logger = logging.getLogger()
self.register_command(dnf.cli.commands.HelpCommand)
def redirect_logger(self, stdout=None, stderr=None):
return
def redirect_repo_progress(self, fo=sys.stderr):
return
def register_command(self, command):
"""Register given *command*."""
self.cli_commands.update({alias: command for alias in command.aliases})
class MockOutput(object):
def __init__(self):
self.term = MockTerminal()
def setup_progress_callbacks(self):
return (None, None)
class MockPackage(object):
def __init__(self, nevra, repo=None):
self.baseurl = None
self._chksum = (None, None)
self.downloadsize = None
self._header = None
self.location = '%s.rpm' % nevra
self.repo = repo
self.reponame = None if repo is None else repo.id
self.str = nevra
self.buildtime = 0
nevra = hawkey.split_nevra(nevra)
self.name = nevra.name
self.epoch = nevra.epoch
self.version = nevra.version
self.release = nevra.release
self.arch = nevra.arch
self.evr = '%(epoch)d:%(version)s-%(release)s' % vars(self)
self.pkgtup = (self.name, self.arch, str(self.epoch), self.version,
self.release)
def __str__(self):
return self.str
def localPkg(self):
return os.path.join(self.repo.pkgdir, os.path.basename(self.location))
def returnIdSum(self):
return self._chksum
class MockRepo(dnf.repo.Repo):
def _valid(self):
return None
class MockQuery(dnf.query.Query):
def __init__(self, query):
self.pkgs = [MockPackage(str(p)) for p in query.run()]
self.i = 0
self.n = len(self.pkgs)
def __getitem__(self, key):
if key < self.n:
return self.pkgs[key]
else:
raise KeyError()
def __iter__(self):
return self
def __len__(self):
return self.n
def filter(self, pkg):
self.pkgs = []
self.pkgs.extend(pkg)
self.n = len(self.pkgs)
return self
def next(self):
return self.__next__()
def __next__(self):
if self.i < self.n:
i = self.i
self.i += 1
return self.pkgs[i]
else:
raise StopIteration()
def run(self):
return self.pkgs
class MockTerminal(object):
def __init__(self):
self.MODE = {'bold': '', 'normal': ''}
self.columns = 80
self.real_columns = 80
self.reinit = mock.Mock()
def bold(self, s):
return s
class TestSack(hawkey.test.TestSackMixin, dnf.sack.Sack):
def __init__(self, repo_dir, base):
hawkey.test.TestSackMixin.__init__(self, repo_dir)
dnf.sack.Sack.__init__(self,
arch=hawkey.test.FIXED_ARCH,
pkgcls=dnf.package.Package,
pkginitval=base,
make_cache_dir=True)
class MockBase(_BaseStubMixin, Base):
"""A class mocking `dnf.Base`."""
def mock_sack(*extra_repos):
return MockBase(*extra_repos).sack
class FakeConf(dnf.conf.Conf):
def __init__(self, **kwargs):
super(FakeConf, self).__init__()
self.substitutions['releasever'] = 'Fedora69'
options = [
('assumeyes', None),
('best', False),
('cachedir', dnf.const.TMPDIR),
('clean_requirements_on_remove', False),
('color', 'never'),
('color_update_installed', 'normal'),
('color_update_remote', 'normal'),
('color_list_available_downgrade', 'dim'),
('color_list_available_install', 'normal'),
('color_list_available_reinstall', 'bold'),
('color_list_available_upgrade', 'bold'),
('color_list_installed_extra', 'bold'),
('color_list_installed_newer', 'bold'),
('color_list_installed_older', 'bold'),
('color_list_installed_reinstall', 'normal'),
('color_update_local', 'bold'),
('debug_solver', False),
('debuglevel', 2),
('defaultyes', False),
('disable_excludes', []),
('diskspacecheck', True),
('exclude', []),
('includepkgs', []),
('install_weak_deps', True),
('history_record', False),
('installonly_limit', 0),
('installonlypkgs', ['kernel']),
('installroot', '/tmp/dnf-test-installroot/'),
('ip_resolve', None),
('multilib_policy', 'best'),
('obsoletes', True),
('persistdir', dnf.const.PERSISTDIR),
('transformdb', False),
('protected_packages', ["dnf"]),
('protect_running_kernel', True),
('plugins', False),
('showdupesfromrepos', False),
('tsflags', []),
('strict', True),
] + list(kwargs.items())
for optname, val in options:
self._set_value(optname, val, dnf.conf.PRIO_DEFAULT)
# TODO: consolidate with dnf.cli.Cli._read_conf_file()
for opt in ('cachedir', 'logdir', 'persistdir'):
# don't prepend installroot if option was specified by user
# TODO: is this desired? ^^^ (tests won't pass without it ATM)
if opt in kwargs:
continue
self.prepend_installroot(opt)
try:
os.makedirs(self.persistdir)
except:
pass
@property
def releasever(self):
return self.substitutions['releasever']
class FakePersistor(object):
reset_last_makecache = False
expired_to_add = set()
def get_expired_repos(self):
return set()
def since_last_makecache(self):
return None
def save(self):
pass
# object matchers for asserts
class ObjectMatcher(object):
"""Class allowing partial matching of objects."""
def __init__(self, type_=None, attrs=None):
"""Initialize a matcher instance."""
self._type = type_
self._attrs = attrs
def __eq__(self, other):
"""Test whether this object is equal to the *other* one."""
if self._type is not None:
if type(other) is not self._type:
return False
if self._attrs:
for attr, value in self._attrs.items():
if value != getattr(other, attr):
return False
return True
def __ne__(self, other):
"""Test whether this object is not equal to the *other* one."""
return not self == other
def __repr__(self):
"""Compute the "official" string representation of this object."""
args_strs = []
if self._type is not None:
args_strs.append('type_=%s' % repr(self._type))
if self._attrs:
attrs_str = ', '.join('%s: %s' % (dnf.i18n.ucd(attr), repr(value))
for attr, value in self._attrs.items())
args_strs.append('attrs={%s}' % attrs_str)
return '%s(%s)' % (type(self).__name__, ", ".join(args_strs))
# test cases:
class TestCase(unittest.TestCase):
if not dnf.pycomp.PY3:
assertCountEqual = unittest.TestCase.assertItemsEqual
def assertEmpty(self, collection):
return self.assertEqual(len(collection), 0)
def assertFile(self, path):
"""Assert the given path is a file."""
return self.assertTrue(os.path.isfile(path))
def assertLength(self, collection, length):
return self.assertEqual(len(collection), length)
def assertPathDoesNotExist(self, path):
return self.assertFalse(os.access(path, os.F_OK))
def assertStartsWith(self, string, what):
return self.assertTrue(string.startswith(what))
def assertTracebackIn(self, end, string):
"""Test that a traceback ending with line *end* is in the *string*."""
traces = (match.group() for match in TRACEBACK_RE.finditer(string))
self.assertTrue(any(trace.endswith(end) for trace in traces))
def assertTransEqual(self, trans_pkgs, list):
return self.assertCountEqual([pkg.name for pkg in trans_pkgs], list)
class DnfBaseTestCase(TestCase):
# create base with specified test repos
REPOS = []
# initialize mock sack
INIT_SACK = False
# initialize self.base._transaction
INIT_TRANSACTION = False
# False: self.base = MockBase()
# True: self.base = BaseCliStub()
BASE_CLI = False
# None: self.cli = None
# "init": self.cli = dnf.cli.cli.Cli(self.base)
# "mock": self.cli = self.base.mock_cli()
# "stub": self.cli = StubCli(self.base)
CLI = None
COMPS = False
COMPS_SEED_HISTORY = False
COMPS_SOLVER = False
def setUp(self):
self._installroot = tempfile.mkdtemp(prefix="dnf_test_installroot_")
if self.BASE_CLI:
self.base = BaseCliStub(*self.REPOS, installroot=self._installroot)
else:
self.base = MockBase(*self.REPOS, installroot=self._installroot)
if self.CLI is None:
self.cli = None
elif self.CLI == "init":
self.cli = dnf.cli.cli.Cli(self.base)
elif self.CLI == "mock":
self.cli = self.base.mock_cli()
elif self.CLI == "stub":
self.cli = CliStub(self.base)
else:
raise ValueError("Invalid CLI value: {}".format(self.CLI))
if self.COMPS:
self.base.read_mock_comps(seed_history=self.COMPS_SEED_HISTORY)
if self.INIT_SACK:
self.base.init_sack()
if self.INIT_TRANSACTION:
self.base._transaction = self.base.history.rpm
if self.COMPS_SOLVER:
self.solver = dnf.comps.Solver(self.history, self.comps, REASONS.get)
else:
self.solver = None
def tearDown(self):
self.base.close()
if self._installroot.startswith("/tmp/"):
shutil.rmtree(self._installroot)
@property
def comps(self):
return self.base.comps
@property
def goal(self):
return self.base._goal
@property
def history(self):
return self.base.history
@property
def sack(self):
return self.base.sack
def _swdb_begin(self, tsis=None):
# history.beg() replaces persistor.commit()
tsis = tsis or []
self.history.beg("", [], tsis)
def _swdb_end(self, tsis=None):
for tsi in self.history._swdb.getItems():
if tsi.getState() == libdnf.transaction.TransactionItemState_UNKNOWN:
tsi.setState(libdnf.transaction.TransactionItemState_DONE)
self.history.end("")
self.history.close()
def _swdb_commit(self, tsis=None):
self._swdb_begin(tsis)
self._swdb_end()
self.history.close()
class ResultTestCase(DnfBaseTestCase):
allow_erasing = False
def _get_installed(self, base):
try:
base.resolve(self.allow_erasing)
except dnf.exceptions.DepsolveError:
self.fail()
installed = set(base.sack.query().installed())
for r in base._transaction.remove_set:
installed.remove(r)
installed.update(base._transaction.install_set)
return installed
def assertResult(self, base, pkgs):
"""Check whether the system contains the given pkgs.
pkgs must be present. Any other pkgs result in an error. Pkgs are
present if they are in the rpmdb and are not REMOVEd or they are
INSTALLed.
"""
self.assertCountEqual(self._get_installed(base), pkgs)
def installed_removed(self, base):
try:
base.resolve(self.allow_erasing)
except dnf.exceptions.DepsolveError:
self.fail()
installed = base._transaction.install_set
removed = base._transaction.remove_set
return installed, removed
| 22,017
|
Python
|
.py
| 574
| 30.454704
| 81
| 0.623008
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,839
|
test_i18n.py
|
rpm-software-management_dnf/tests/test_i18n.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import sys
import unittest
import dnf.i18n
from dnf.pycomp import PY3
from dnf.i18n import fill_exact_width, textwrap_fill
import tests.support
from tests.support import mock
UC_TEXT = 'Šířka' # means 'Width' in Czech
UC_TEXT_OSERROR = 'Soubor již existuje' # 'File already exists'
STR_TEXT_OSERROR = 'Soubor již existuje'
@mock.patch('locale.setlocale')
class TestLocale(tests.support.TestCase):
def test_setup_locale(self, mock_setlocale):
dnf.i18n.setup_locale()
self.assertTrue(1 <= mock_setlocale.call_count <= 2)
class TestStdout(tests.support.TestCase):
def test_setup_stdout(self):
# No stdout output can be seen when sys.stdout is patched, debug msgs,
# etc. included.
with mock.patch('sys.stdout', spec=('write', 'isatty')):
retval = dnf.i18n.setup_stdout()
self.assertFalse(retval)
with mock.patch('sys.stdout') as mock_stdout:
mock_stdout.encoding = None
retval = dnf.i18n.setup_stdout()
self.assertFalse(retval)
with mock.patch('sys.stdout') as mock_stdout:
mock_stdout.encoding = 'UTF-8'
retval = dnf.i18n.setup_stdout()
self.assertTrue(retval)
with mock.patch('sys.stdout') as mock_stdout:
mock_stdout.encoding = 'ISO-8859-2'
retval = dnf.i18n.setup_stdout()
self.assertFalse(retval)
def test_stream(self):
fileobj = dnf.pycomp.StringIO()
stream = dnf.i18n.UnicodeStream(fileobj, "ISO-8859-2")
stream.write(UC_TEXT)
output = fileobj.getvalue()
self.assertEqual(output, u'\u0160\xed\u0159ka' if PY3 else b'\xa9\xed\xf8ka')
self.assertEqual(len(output), len(UC_TEXT))
class TestInput(tests.support.TestCase):
@unittest.skipIf(PY3, "builtin input accepts unicode and bytes")
def test_assumption(self):
""" Test that raw_input() always fails on a unicode string with accented
characters. If this is not the case we might not need i18n.input()
as a raw_input() wrapper.
"""
if sys.stdout.isatty():
# Only works when stdout is a terminal (and not captured in some
# way, for instance when nosetests is run without the -s switch).
self.assertRaises(UnicodeEncodeError, raw_input, UC_TEXT)
class TestConversion(tests.support.TestCase):
@mock.patch('dnf.i18n._guess_encoding', return_value='utf-8')
def test_ucd(self, _unused):
s = UC_TEXT.encode('utf8')
# the assumption is this string can't be simply converted back to
# unicode:
u = dnf.i18n.ucd(s)
self.assertEqual(u, UC_TEXT)
# test a sample OSError, typically constructed with an error code and a
# utf-8 encoded string:
obj = OSError(17, 'Soubor již existuje')
expected = u"[Errno 17] %s" % UC_TEXT_OSERROR
self.assertEqual(dnf.i18n.ucd(obj), expected)
# ucd() should return unicode unmodified
self.assertEqual(dnf.i18n.ucd(expected), expected)
def test_download_error_unicode(self):
err_map = {"e1": ["x", "y"]}
err = dnf.exceptions.DownloadError(err_map)
self.assertEqual("e1: x\ne1: y", str(err))
self.assertEqual("e1: x\ne1: y", dnf.i18n.ucd(err))
@mock.patch('locale.getpreferredencoding', return_value='ANSI_X3.4-1968')
def test_ucd_acii(self, _unused):
s = UC_TEXT.encode('utf8')
# ascii coding overridden by utf8
u = dnf.i18n.ucd(s)
self.assertEqual(u, UC_TEXT)
@mock.patch('dnf.i18n._guess_encoding', return_value='utf-8')
def test_ucd_skip(self, _unused):
s = UC_TEXT.encode('iso-8859-2')
# not decoded chars are skipped
u = dnf.i18n.ucd(s)
self.assertEqual(u, "ka")
class TestFormatedOutput(tests.support.TestCase):
def test_fill_exact_width(self):
msg = "message"
pre = "<"
suf = ">"
self.assertEqual("%-*.*s" % (5, 10, msg), fill_exact_width(msg, 5, 10))
self.assertEqual("重uř ", fill_exact_width("重uř", 5, 10))
self.assertEqual("%10.5s" % msg,
fill_exact_width(msg, 10, 5, left=False))
self.assertEqual("%s%.5s%s" % (pre, msg, suf),
fill_exact_width(msg, 0, 5, prefix=pre, suffix=suf))
def test_exact_width(self):
self.assertEqual(dnf.i18n.exact_width("重uř"), 4)
def test_textwrap_fill(self):
msg = "12345 67890"
one_line = textwrap_fill(msg, 12)
self.assertEqual(one_line, "12345 67890")
two_lines = textwrap_fill(msg, 7, subsequent_indent=">>")
self.assertEqual(two_lines,
"12345\n>>67890")
asian_msg = "重重 uř"
self.assertEqual(textwrap_fill(asian_msg, 7), asian_msg)
asian_two_lines = textwrap_fill("重重\nuř", 5, subsequent_indent=">>")
self.assertEqual(asian_two_lines, "重重\n>>uř")
| 6,071
|
Python
|
.py
| 127
| 40.149606
| 85
| 0.655916
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,840
|
test_list.py
|
rpm-software-management_dnf/tests/test_list.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import itertools
import libdnf.transaction
import tests.support
class List(tests.support.DnfBaseTestCase):
REPOS = ["main", "updates"]
def test_doPackageLists_reponame(self):
"""Test whether packages are filtered by the reponame."""
reponame = 'main'
lists = self.base._do_package_lists(reponame=reponame)
pkgs = itertools.chain.from_iterable(lists.all_lists().values())
self.assertCountEqual({pkg.reponame for pkg in pkgs}, {reponame})
assert len(set(pkg.reponame for pkg in self.base.sack.query())) > 1, \
('the base must contain packages from multiple repos, '
'otherwise the test makes no sense')
def test_list_installed(self):
ypl = self.base._do_package_lists('installed')
self.assertEqual(len(ypl.installed), tests.support.TOTAL_RPMDB_COUNT)
def test_list_installed_reponame(self):
"""Test whether only packages installed from the repository are listed."""
expected = self.base.sack.query().installed().filter(name={'pepper', 'librita'})
tsis = []
for pkg in expected:
pkg._force_swdb_repoid = "main"
self.history.rpm.add_install(pkg)
self._swdb_commit(tsis)
lists = self.base._do_package_lists('installed', reponame='main')
self.assertCountEqual(lists.installed, expected)
def test_list_updates(self):
ypl = self.base._do_package_lists('upgrades')
self.assertEqual(len(ypl.updates), tests.support.UPDATES_NSOLVABLES - 2)
pkg = ypl.updates[0]
self.assertEqual(pkg.name, "hole")
ypl = self.base._do_package_lists('upgrades', ["pepper"])
self.assertEqual(len(ypl.updates), 1)
ypl = self.base._do_package_lists('upgrades', ["mrkite"])
self.assertEqual(len(ypl.updates), 0)
ypl = self.base._do_package_lists('upgrades', ["hole"])
self.assertEqual(len(ypl.updates), 1)
def test_lists_multiple(self):
ypl = self.base._do_package_lists('upgrades', ['pepper', 'hole'])
self.assertLength(ypl.updates, 2)
class TestListAllRepos(tests.support.DnfBaseTestCase):
REPOS = ["main", "updates"]
def setUp(self):
super(TestListAllRepos, self).setUp()
self.base.conf.multilib_policy = "all"
def test_list_pattern(self):
ypl = self.base._do_package_lists('all', ['hole'])
self.assertLength(ypl.installed, 1)
self.assertLength(ypl.available, 2)
def test_list_pattern_arch(self):
ypl = self.base._do_package_lists('all', ['hole.x86_64'])
self.assertLength(ypl.installed, 1)
self.assertLength(ypl.available, 1)
def test_list_available(self):
ypl = self.base._do_package_lists('available', ['hole'], showdups=False)
self.assertCountEqual(map(str, ypl.available), ('hole-2-1.i686',
'hole-2-1.x86_64'))
ypl = self.base._do_package_lists('available', ['hole'], showdups=True)
self.assertCountEqual(map(str, ypl.available), ('hole-2-1.i686',
'hole-2-1.x86_64',
'hole-1-2.x86_64'))
| 4,321
|
Python
|
.py
| 81
| 44.950617
| 88
| 0.659943
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,841
|
test_check.py
|
rpm-software-management_dnf/tests/test_check.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2016-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import dnf.cli.commands.check
import dnf.pycomp
import tests.support
EXPECTED_DUPLICATES_FORMAT = """\
dup-1-0.noarch is a duplicate with dup-2-0.noarch
dup-1-0.noarch is a duplicate with dup-3-0.noarch
"""
EXPECTED_OBSOLETED_FORMAT = """\
test-1-0.noarch is obsoleted by obs-3-0.noarch
"""
class CheckDuplicatesTest(tests.support.DnfBaseTestCase):
REPOS = []
BASE_CLI = True
CLI = "stub"
def test_duplicates(self):
self.cmd = dnf.cli.commands.check.CheckCommand(self.cli)
tests.support.command_configure(self.cmd, ['--duplicates'])
with tests.support.patch_std_streams() as (stdout, _):
with self.assertRaises(dnf.exceptions.Error) as ctx:
self.cmd.run()
self.assertEqual(str(ctx.exception),
'Check discovered 2 problem(s)')
self.assertEqual(stdout.getvalue(), EXPECTED_DUPLICATES_FORMAT)
def test_obsoleted(self):
self.cmd = dnf.cli.commands.check.CheckCommand(self.cli)
tests.support.command_configure(self.cmd, ['--obsoleted'])
with tests.support.patch_std_streams() as (stdout, _):
with self.assertRaises(dnf.exceptions.Error) as ctx:
self.cmd.run()
self.assertEqual(str(ctx.exception),
'Check discovered 1 problem(s)')
self.assertEqual(stdout.getvalue(), EXPECTED_OBSOLETED_FORMAT)
| 2,522
|
Python
|
.py
| 52
| 43
| 77
| 0.711554
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,842
|
test_remove.py
|
rpm-software-management_dnf/tests/test_remove.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import itertools
import libdnf.transaction
import dnf.cli.commands
import tests.support
class Remove(tests.support.ResultTestCase):
REPOS = []
def setUp(self):
super(Remove, self).setUp()
self.allow_erasing = True
def test_not_installed(self):
""" Removing a not-installed package is a void operation. """
with self.assertRaises(dnf.exceptions.PackagesNotInstalledError) as context:
self.base.remove('mrkite')
self.assertEqual(context.exception.pkg_spec, 'mrkite')
installed_pkgs = self.base.sack.query().installed().run()
self.assertResult(self.base, installed_pkgs)
def test_remove(self):
""" Simple remove. """
self.base.remove("pepper")
self.assertResult(self.base,
tests.support.installed_but(self.base.sack, "pepper"))
def test_remove_dependent(self):
""" Remove a lib that some other package depends on. """
self.base.remove("librita")
# we should end up with nothing in this case:
new_set = tests.support.installed_but(self.base.sack, "librita", "pepper")
self.assertResult(self.base, new_set)
def test_remove_nevra(self):
self.base.remove("pepper-20-0.x86_64")
pepper = self.base.sack.query().installed().filter(name="pepper")
(installed, removed) = self.installed_removed(self.base)
self.assertLength(installed, 0)
self.assertCountEqual(removed, pepper.run())
def test_remove_glob(self):
""" Test that weird input combinations with globs work. """
ret = self.base.remove("*.i686")
self.assertEqual(ret, 1)
def test_remove_provides(self):
"""Remove uses provides too."""
self.assertEqual(1, self.base.remove('parking'))
def test_reponame(self):
"""Test whether only packages from the repository are uninstalled."""
pkg_subj = dnf.subject.Subject('librita.x86_64')
tsis = []
for pkg in pkg_subj.get_best_query(self.base.sack).installed():
pkg._force_swdb_repoid = "main"
self.history.rpm.add_install(pkg)
# tsi = dnf.transaction.TransactionItem(
# dnf.transaction.INSTALL,
# installed=pkg,
# reason=libdnf.transaction.TransactionItemReason_USER
# )
# tsis.append(tsi)
self._swdb_commit(tsis)
self.base.remove('librita', 'main')
self.assertResult(self.base, itertools.chain(
self.base.sack.query().installed().filter(name__neq='librita'),
dnf.subject.Subject('librita.i686').get_best_query(self.base.sack).installed())
)
| 3,773
|
Python
|
.py
| 78
| 42.179487
| 91
| 0.678455
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,843
|
test_groups.py
|
rpm-software-management_dnf/tests/test_groups.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import operator
import libdnf.transaction
import dnf.comps
import dnf.util
import tests.support
from tests.support import mock
class EmptyPersistorTest(tests.support.ResultTestCase):
"""Test group operations with empty persistor."""
REPOS = ['main']
COMPS = True
@mock.patch('locale.getlocale', return_value=('cs_CZ', 'UTF-8'))
def test_group_install_locale(self, _unused):
grp = self.comps.group_by_pattern('Kritick\xe1 cesta (Z\xe1klad)')
cnt = self.base.group_install(grp.id, ('mandatory',))
self.assertEqual(cnt, 2)
def test_finalize_comps_trans(self):
trans = dnf.comps.TransactionBunch()
trans.install = ('trampoline',)
self.assertGreater(self.base._add_comps_trans(trans), 0)
self.base._finalize_comps_trans()
self.assertIn('trampoline', self.base._goal.group_members)
(installed, removed) = self.installed_removed(self.base)
self.assertCountEqual(map(str, installed), ('trampoline-2.1-1.noarch',))
self.assertEmpty(removed)
class PresetPersistorTest(tests.support.ResultTestCase):
"""Test group operations with some data in the persistor."""
REPOS = ['main']
COMPS = True
COMPS_SEED_HISTORY = True
def _install_test_env(self):
"""Env installation itself does not handle packages. We need to handle
them manually for proper functionality of env remove"""
env_id = 'sugar-desktop-environment'
comps_env = self.comps._environment_by_id(env_id)
self.base.environment_install(comps_env.id, ('mandatory',))
self._swdb_commit()
swdb_env = self.history.env.get(comps_env.id)
self.assertIsNotNone(swdb_env)
for comps_group in comps_env.mandatory_groups:
swdb_group = self.history.group.get(comps_group.id)
self.assertIsNotNone(swdb_group)
tsis = []
seen_pkgs = set()
for swdb_env_group in swdb_env.getGroups():
swdb_group = self.history.group.get(swdb_env_group.getGroupId())
if not swdb_group:
continue
for swdb_pkg in swdb_group.getPackages():
swdb_pkg.setInstalled(True)
pkgs = self.base.sack.query().filter(name=swdb_pkg.getName(), arch="x86_64").run()
if not pkgs:
continue
pkg = pkgs[0]
if pkg in seen_pkgs:
# prevent RPMs from being twice in a transaction and triggering unique constraint error
continue
seen_pkgs.add(pkg)
pkg._force_swdb_repoid = "main"
self.history.rpm.add_install(pkg, reason=libdnf.transaction.TransactionItemReason_GROUP)
# tsi = dnf.transaction.TransactionItem(
# dnf.transaction.INSTALL,
# installed=pkg,
# reason=libdnf.transaction.TransactionItemReason_GROUP
# )
# tsis.append(tsi)
self._swdb_commit(tsis)
def _install_test_group(self):
"""Group installation itself does not handle packages. We need to
handle them manually for proper functionality of group remove"""
group_id = 'somerset'
self.base.group_install(group_id, ('mandatory',))
swdb_group = self.history.group._installed[group_id]
tsis = []
for swdb_pkg in swdb_group.getPackages():
swdb_pkg.setInstalled(True)
pkgs = self.base.sack.query().filter(name=swdb_pkg.getName(), arch="x86_64").run()
if not pkgs:
continue
pkg = pkgs[0]
pkg._force_swdb_repoid = "main"
self.history.rpm.add_install(pkg, reason=libdnf.transaction.TransactionItemReason_GROUP)
# tsi = dnf.transaction.TransactionItem(
# dnf.transaction.INSTALL,
# installed=pkg,
# reason=libdnf.transaction.TransactionItemReason_GROUP
# )
# tsis.append(tsi)
self._swdb_commit(tsis)
self.base.reset(goal=True)
def test_env_group_remove(self):
self._install_test_env()
env_id = 'sugar-desktop-environment'
pkg_count = self.base.env_group_remove([env_id])
self._swdb_commit()
self.assertEqual(3, pkg_count)
with tests.support.mock.patch('logging.Logger.error'):
self.assertRaises(dnf.exceptions.Error,
self.base.env_group_remove,
['nonexistent'])
def test_environment_remove(self):
self._install_test_env()
env_id = 'sugar-desktop-environment'
swdb_env = self.history.env.get(env_id)
self.assertIsNotNone(swdb_env)
self.assertEqual(swdb_env.getEnvironmentId(), 'sugar-desktop-environment')
removed_pkg_count = self.base.environment_remove(env_id)
self.assertGreater(removed_pkg_count, 0)
self._swdb_commit()
swdb_env = self.history.env.get(env_id)
self.assertIsNone(swdb_env)
peppers = self.history.group.get('Peppers')
self.assertIsNone(peppers)
somerset = self.history.group.get('somerset')
self.assertIsNone(somerset)
def test_env_upgrade(self):
self._install_test_env()
cnt = self.base.environment_upgrade("sugar-desktop-environment")
self.assertEqual(5, cnt)
peppers = self.history.group.get('Peppers')
self.assertIsNotNone(peppers)
somerset = self.history.group.get('somerset')
self.assertIsNotNone(somerset)
def test_group_install(self):
comps_group = self.base.comps.group_by_pattern('Base')
pkg_count = self.base.group_install(comps_group.id, ('mandatory',))
self.assertEqual(pkg_count, 2)
self._swdb_commit()
installed, removed = self.installed_removed(self.base)
self.assertEmpty(installed)
self.assertEmpty(removed)
swdb_group = self.history.group.get(comps_group.id)
self.assertIsNotNone(swdb_group)
def test_group_remove(self):
self._install_test_group()
group_id = 'somerset'
pkgs_removed = self.base.group_remove(group_id)
self.assertGreater(pkgs_removed, 0)
self._swdb_begin()
installed, removed = self.installed_removed(self.base)
self.assertEmpty(installed)
self.assertCountEqual([pkg.name for pkg in removed], ('pepper',))
self._swdb_end()
class ProblemGroupTest(tests.support.ResultTestCase):
"""Test some cases involving problems in groups: packages that
don't exist, and packages that exist but cannot be installed. The
"broken" group lists three packages. "meaning-of-life", explicitly
'default', does not exist. "lotus", implicitly 'mandatory' (no
explicit type), exists and is installable. "brokendeps",
explicitly 'optional', exists but has broken dependencies. See
https://bugzilla.redhat.com/show_bug.cgi?id=1292892,
https://bugzilla.redhat.com/show_bug.cgi?id=1337731,
https://bugzilla.redhat.com/show_bug.cgi?id=1427365, and
https://bugzilla.redhat.com/show_bug.cgi?id=1461539 for some of
the background on this.
"""
REPOS = ['main', 'broken_group']
COMPS = True
COMPS_SEED_PERSISTOR = True
def test_group_install_broken_mandatory(self):
"""Here we will test installing the group with only mandatory
packages. We expect this to succeed, leaving out the
non-existent 'meaning-of-life': it should also log a warning,
but we don't test that.
"""
comps_group = self.base.comps.group_by_pattern('Broken Group')
swdb_group = self.history.group.get(comps_group.id)
self.assertIsNone(swdb_group)
cnt = self.base.group_install(comps_group.id, ('mandatory',))
self._swdb_commit()
self.base.resolve()
# this counts packages *listed* in the group, so 2
self.assertEqual(cnt, 2)
inst, removed = self.installed_removed(self.base)
# the above should work, but only 'lotus' actually installed
self.assertLength(inst, 1)
self.assertEmpty(removed)
def test_group_install_broken_default(self):
"""Here we will test installing the group with only mandatory
and default packages. Again we expect this to succeed: the new
factor is an entry pulling in librita if no-such-package is
also included or installed. We expect this not to actually
pull in librita (as no-such-package obviously *isn't* there),
but also not to cause a fatal error.
"""
comps_group = self.base.comps.group_by_pattern('Broken Group')
swdb_group = self.history.group.get(comps_group.id)
self.assertIsNone(swdb_group)
cnt = self.base.group_install(comps_group.id, ('mandatory', 'default'))
self._swdb_commit()
self.base.resolve()
# this counts packages *listed* in the group, so 3
self.assertEqual(cnt, 3)
inst, removed = self.installed_removed(self.base)
# the above should work, but only 'lotus' actually installed
self.assertLength(inst, 1)
self.assertEmpty(removed)
def test_group_install_broken_optional(self):
"""Here we test installing the group with optional packages
included. We expect this to fail, as a package that exists but
has broken dependencies is now included.
"""
comps_group = self.base.comps.group_by_pattern('Broken Group')
swdb_group = self.history.group.get(comps_group.id)
self.assertIsNone(swdb_group)
cnt = self.base.group_install(comps_group.id, ('mandatory', 'default', 'optional'))
self.assertEqual(cnt, 4)
self._swdb_commit()
# this should fail, as optional 'brokendeps' is now pulled in
self.assertRaises(dnf.exceptions.DepsolveError, self.base.resolve)
def test_group_install_broken_optional_nonstrict(self):
"""Here we test installing the group with optional packages
included, but with strict=False. We expect this to succeed,
skipping the package with broken dependencies.
"""
comps_group = self.base.comps.group_by_pattern('Broken Group')
swdb_group = self.history.group.get(comps_group.id)
self.assertIsNone(swdb_group)
cnt = self.base.group_install(comps_group.id, ('mandatory', 'default', 'optional'),
strict=False)
self._swdb_commit()
self.base.resolve()
self.assertEqual(cnt, 4)
inst, removed = self.installed_removed(self.base)
# the above should work, but only 'lotus' actually installed
self.assertLength(inst, 1)
self.assertEmpty(removed)
def test_group_install_missing_name(self):
comps_group = self.base.comps.group_by_pattern('missing-name-group')
cnt = self.base.group_install(comps_group.id, ('mandatory', 'default', 'optional'),
strict=False)
self._swdb_commit()
self.base.resolve()
self.assertEqual(cnt, 1)
class EnvironmentInstallTest(tests.support.ResultTestCase):
"""Set up a test where sugar is considered not installed."""
REPOS = ['main']
COMPS = True
COMPS_SEED_HISTORY = True
def test_environment_install(self):
# actually commit the pre-mocked comps, as otherwise
# 'sugar-desktop-environment' is already present in the open
# transaction and it wins over the one installed here
self._swdb_commit()
env_id = 'sugar-desktop-environment'
comps_env = self.comps.environment_by_pattern(env_id)
self.base.environment_install(comps_env.id, ('mandatory',))
self._swdb_commit()
installed, _ = self.installed_removed(self.base)
self.assertCountEqual(map(operator.attrgetter('name'), installed),
('trampoline', 'lotus'))
swdb_env = self.history.env.get(env_id)
self.assertCountEqual([i.getGroupId() for i in swdb_env.getGroups()], ('somerset', 'Peppers', 'base'))
peppers = self.history.group.get('Peppers')
self.assertIsNotNone(peppers)
somerset = self.history.group.get('somerset')
self.assertIsNotNone(somerset)
base = self.history.group.get('base')
self.assertIsNone(base)
| 13,579
|
Python
|
.py
| 277
| 40.516245
| 110
| 0.655714
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,844
|
test_fill_sack_from_repos_in_cache.py
|
rpm-software-management_dnf/tests/test_fill_sack_from_repos_in_cache.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2021 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import os
import tempfile
import glob
import shutil
import unittest
import dnf.exceptions
import dnf.repo
import dnf.sack
import hawkey
import tests.support
from tests.support import mock
TEST_REPO_NAME = "test-repo"
class FillSackFromReposInCacheTest(unittest.TestCase):
def _create_cache_for_repo(self, repopath, tmpdir, repo_name=TEST_REPO_NAME):
conf = dnf.conf.MainConf()
conf.cachedir = os.path.join(tmpdir, "cache")
conf.installroot = tmpdir
conf.persistdir = os.path.join(conf.installroot, conf.persistdir.lstrip("/"))
conf.substitutions["arch"] = "x86_64"
conf.substitutions["basearch"] = dnf.rpm.basearch(conf.substitutions["arch"])
base = dnf.Base(conf=conf)
repoconf = dnf.repo.Repo(repo_name, base.conf)
repoconf.baseurl = repopath
repoconf.enable()
base.repos.add(repoconf)
base.fill_sack(load_system_repo=False)
base.close()
def _setUp_from_repo_path(self, original_repo_path):
repo_copy_path = os.path.join(self.tmpdir, "repo")
shutil.copytree(original_repo_path, repo_copy_path)
self._create_cache_for_repo(repo_copy_path, self.tmpdir)
# Just to be sure remove repo (it shouldn't be used)
shutil.rmtree(repo_copy_path)
# Prepare base for the actual test
conf = dnf.conf.MainConf()
conf.cachedir = os.path.join(self.tmpdir, "cache")
conf.installroot = self.tmpdir
conf.persistdir = os.path.join(conf.installroot, conf.persistdir.lstrip("/"))
conf.substitutions["arch"] = "x86_64"
conf.substitutions["basearch"] = dnf.rpm.basearch(conf.substitutions["arch"])
self.test_base = dnf.Base(conf=conf)
repoconf = dnf.repo.Repo(TEST_REPO_NAME, conf)
repoconf.baseurl = repo_copy_path
repoconf.enable()
self.test_base.repos.add(repoconf)
def setUp(self):
self.tmpdir = tempfile.mkdtemp(prefix="dnf_test_")
self.test_base = None
def tearDown(self):
shutil.rmtree(self.tmpdir)
if self.test_base:
self.test_base.close()
def test_with_solv_solvx_repomd(self):
self._setUp_from_repo_path(os.path.join(os.path.abspath(os.path.dirname(__file__)), "repos/rpm"))
# Remove xml metadata except repomd
# repomd.xml is not compressed and doesn't end with .gz
repodata_without_repomd = glob.glob(os.path.join(self.tmpdir, "cache/test-repo-*/repodata/*.gz"))
for f in repodata_without_repomd:
os.remove(f)
# Now we only have cache with just solv, solvx files and repomd.xml
self.test_base.fill_sack_from_repos_in_cache(load_system_repo=False)
q = self.test_base.sack.query()
packages = q.run()
self.assertEqual(len(packages), 9)
self.assertEqual(packages[0].evr, "4-4")
# Use *-updateinfo.solvx
adv_pkgs = q.get_advisory_pkgs(hawkey.LT | hawkey.EQ | hawkey.GT)
adv_titles = set()
for pkg in adv_pkgs:
adv_titles.add(pkg.get_advisory(self.test_base.sack).title)
self.assertEqual(len(adv_titles), 3)
def test_with_just_solv_repomd(self):
self._setUp_from_repo_path(os.path.join(os.path.abspath(os.path.dirname(__file__)), "repos/rpm"))
# Remove xml metadata except repomd
# repomd.xml is not compressed and doesn't end with .gz
repodata_without_repomd = glob.glob(os.path.join(self.tmpdir, "cache/test-repo-*/repodata/*.gz"))
for f in repodata_without_repomd:
os.remove(f)
# Remove solvx files
solvx = glob.glob(os.path.join(self.tmpdir, "cache/*.solvx"))
for f in solvx:
os.remove(f)
# Now we only have cache with just solv files and repomd.xml
self.test_base.fill_sack_from_repos_in_cache(load_system_repo=False)
q = self.test_base.sack.query()
packages = q.run()
self.assertEqual(len(packages), 9)
self.assertEqual(packages[0].evr, "4-4")
# No *-updateinfo.solvx -> we get no advisory packages
adv_pkgs = q.get_advisory_pkgs(hawkey.LT | hawkey.EQ | hawkey.GT)
self.assertEqual(len(adv_pkgs), 0)
def test_with_xml_metadata(self):
self._setUp_from_repo_path(os.path.join(os.path.abspath(os.path.dirname(__file__)), "repos/rpm"))
# Remove all solv and solvx files
solvx = glob.glob(os.path.join(self.tmpdir, "cache/*.solv*"))
for f in solvx:
os.remove(f)
# Now we only have cache with just xml metadata
self.test_base.fill_sack_from_repos_in_cache(load_system_repo=False)
q = self.test_base.sack.query()
packages = q.run()
self.assertEqual(len(packages), 9)
self.assertEqual(packages[0].evr, "4-4")
def test_exception_without_repomd(self):
self._setUp_from_repo_path(os.path.join(os.path.abspath(os.path.dirname(__file__)), "repos/rpm"))
# Remove xml metadata
repodata_without_repomd = glob.glob(os.path.join(self.tmpdir, "cache/test-repo-*/repodata/*"))
for f in repodata_without_repomd:
os.remove(f)
# Now we only have cache with just solv and solvx files
# Since we don't have repomd we cannot verify checksums -> fail (exception)
self.assertRaises(dnf.exceptions.RepoError,
self.test_base.fill_sack_from_repos_in_cache, load_system_repo=False)
def test_exception_with_just_repomd(self):
self._setUp_from_repo_path(os.path.join(os.path.abspath(os.path.dirname(__file__)), "repos/rpm"))
# Remove xml metadata except repomd
# repomd.xml is not compressed and doesn't end with .gz
repodata_without_repomd = glob.glob(os.path.join(self.tmpdir, "cache/test-repo-*/repodata/*.gz"))
for f in repodata_without_repomd:
os.remove(f)
# Remove all solv and solvx files
solvx = glob.glob(os.path.join(self.tmpdir, "cache/*.solv*"))
for f in solvx:
os.remove(f)
# Now we only have cache with just repomd
# repomd is not enough, it doesn't contain the metadata it self -> fail (exception)
self.assertRaises(dnf.exceptions.RepoError,
self.test_base.fill_sack_from_repos_in_cache, load_system_repo=False)
def test_exception_with_checksum_mismatch_and_only_repomd(self):
self._setUp_from_repo_path(os.path.join(os.path.abspath(os.path.dirname(__file__)), "repos/rpm"))
self._create_cache_for_repo(os.path.join(os.path.abspath(os.path.dirname(__file__)), "repos/drpm"),
self.tmpdir, "drpm-repo")
# Remove xml metadata except repomd
# repomd.xml is not compressed and doesn't end with .gz
repodata_without_repomd = glob.glob(os.path.join(self.tmpdir, "cache/test-repo-*/repodata/*.gz"))
for f in repodata_without_repomd:
os.remove(f)
# Replace solvfile of test-repo with solvfile from drpm-repo which has different data (different checksum)
shutil.move(os.path.join(self.tmpdir, "cache/drpm-repo.solv"),
os.path.join(self.tmpdir, "cache/test-repo.solv"))
# Now we only have cache with solvx, mismatching solv file and just repomd
# Since we don't have original xml metadata we cannot regenerate solv -> fail (exception)
self.assertRaises(dnf.exceptions.RepoError,
self.test_base.fill_sack_from_repos_in_cache, load_system_repo=False)
def test_checksum_mismatch_regenerates_solv(self):
self._setUp_from_repo_path(os.path.join(os.path.abspath(os.path.dirname(__file__)), "repos/rpm"))
self._create_cache_for_repo(os.path.join(os.path.abspath(os.path.dirname(__file__)), "repos/drpm"),
self.tmpdir, "drpm-repo")
# Replace solvfile of test-repo with solvfile from drpm-repo which has different data (different checksum)
shutil.move(os.path.join(self.tmpdir, "cache/drpm-repo.solv"),
os.path.join(self.tmpdir, "cache/test-repo.solv"))
# Now we only have cache with solvx, mismatching solv file and xml metadata.
# Checksum mismatch causes regeneration of solv file and repo works.
self.test_base.fill_sack_from_repos_in_cache(load_system_repo=False)
q = self.test_base.sack.query()
packages = q.run()
self.assertEqual(len(packages), 9)
self.assertEqual(packages[0].evr, "4-4")
def test_with_modules_yaml(self):
self._setUp_from_repo_path(os.path.join(os.path.abspath(os.path.dirname(__file__)),
"modules/modules/_all/x86_64"))
# Now we have full cache (also with modules.yaml)
self.test_base.fill_sack_from_repos_in_cache(load_system_repo=False)
q = self.test_base.sack.query()
packages = q.run()
pkg_names = []
for pkg in packages:
pkg_names.append(pkg.name)
self.assertEqual(pkg_names, ['grub2', 'httpd', 'httpd', 'httpd-doc', 'httpd-doc', 'httpd-provides-name-doc',
'httpd-provides-name-version-release-doc', 'libnghttp2'])
self.module_base = dnf.module.module_base.ModuleBase(self.test_base)
modules, _ = self.module_base._get_modules("base-runtime*")
self.assertEqual(len(modules), 3)
self.assertEqual(modules[0].getFullIdentifier(), "base-runtime:f26:1::")
def test_with_modular_repo_without_modules_yaml(self):
self._setUp_from_repo_path(os.path.join(os.path.abspath(os.path.dirname(__file__)),
"modules/modules/_all/x86_64"))
# Remove xml and yaml metadata except repomd
# repomd.xml is not compressed and doesn't end with .gz
repodata_without_repomd = glob.glob(os.path.join(self.tmpdir, "cache/test-repo-*/repodata/*.gz"))
for f in repodata_without_repomd:
os.remove(f)
# Now we have just solv, *-filenames.solvx and repomd.xml (modules.yaml are not processed into *-modules.solvx)
self.test_base.fill_sack_from_repos_in_cache(load_system_repo=False)
q = self.test_base.sack.query()
packages = q.run()
# We have many more packages because they are not hidden by modules
self.assertEqual(len(packages), 44)
self.assertEqual(packages[0].evr, "10.0-7")
self.module_base = dnf.module.module_base.ModuleBase(self.test_base)
modules, _ = self.module_base._get_modules("*")
self.assertEqual(len(modules), 0)
| 11,781
|
Python
|
.py
| 211
| 46.587678
| 119
| 0.656899
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,845
|
test_main.py
|
rpm-software-management_dnf/tests/automatic/test_main.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf.automatic.main
import tests.support
FILE = tests.support.resource_path('etc/automatic.conf')
class TestConfig(tests.support.TestCase):
def test_load(self):
# test values from config file take effect if no overrides
# note: config file specifies download = no apply = yes,
# test expects implication to turn download into True
conf = dnf.automatic.main.AutomaticConfig(FILE)
self.assertTrue(conf.commands.apply_updates)
self.assertTrue(conf.commands.download_updates)
self.assertEqual(conf.commands.random_sleep, 300)
self.assertEqual(conf.email.email_from, 'staring@crowd.net')
# test overriding installupdates
conf = dnf.automatic.main.AutomaticConfig(FILE, installupdates=False)
# as per above, download is set false in config
self.assertFalse(conf.commands.download_updates)
self.assertFalse(conf.commands.apply_updates)
# test overriding installupdates and downloadupdates
conf = dnf.automatic.main.AutomaticConfig(FILE, downloadupdates=True, installupdates=False)
self.assertTrue(conf.commands.download_updates)
self.assertFalse(conf.commands.apply_updates)
# test that reboot is "never" by default
conf = dnf.automatic.main.AutomaticConfig(FILE)
self.assertEqual(conf.commands.reboot, 'never')
| 2,448
|
Python
|
.py
| 44
| 50.659091
| 99
| 0.751358
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,846
|
__init__.py
|
rpm-software-management_dnf/tests/automatic/__init__.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
| 984
|
Python
|
.py
| 17
| 56.823529
| 77
| 0.777433
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,847
|
test_emitter.py
|
rpm-software-management_dnf/tests/automatic/test_emitter.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf.automatic.emitter
import tests.support
from tests.support import mock, mock_open
MSG = """\
downloaded on myhost:
packages..."""
class TestEmitter(tests.support.TestCase):
def test_prepare_msg(self):
emitter = dnf.automatic.emitter.Emitter('myhost')
emitter.notify_available('packages...')
emitter.notify_downloaded()
with mock.patch('dnf.automatic.emitter.DOWNLOADED', 'downloaded on %s:'):
self.assertEqual(emitter._prepare_msg(), MSG)
class TestMotdEmitter(tests.support.TestCase):
def test_motd(self):
m = mock_open()
with mock.patch('dnf.automatic.emitter.open', m, create=True):
emitter = dnf.automatic.emitter.MotdEmitter('myhost')
emitter.notify_available('packages...')
emitter.notify_downloaded()
with mock.patch('dnf.automatic.emitter.DOWNLOADED', 'downloaded on %s:'):
emitter.commit()
handle = m()
handle.write.assert_called_once_with(MSG)
| 2,092
|
Python
|
.py
| 43
| 43.790698
| 85
| 0.722413
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,848
|
test_dnf_const.py
|
rpm-software-management_dnf/tests/api/test_dnf_const.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf
from .common import TestCase
class DnfConstApiTest(TestCase):
def test_filename(self):
# dnf.const.CONF_FILENAME
self.assertHasAttr(dnf.const, "CONF_FILENAME")
self.assertHasType(dnf.const.CONF_FILENAME, str)
def test_group_package_types(self):
# dnf.const.GROUP_PACKAGE_TYPES
self.assertHasAttr(dnf.const, "GROUP_PACKAGE_TYPES")
self.assertHasType(dnf.const.GROUP_PACKAGE_TYPES, tuple)
def test_persistdir(self):
# dnf.const.PERSISTDIR
self.assertHasAttr(dnf.const, "PERSISTDIR")
self.assertHasType(dnf.const.PERSISTDIR, str)
def test_pluginconfpath(self):
# dnf.const.PLUGINCONFPATH
self.assertHasAttr(dnf.const, "PLUGINCONFPATH")
self.assertHasType(dnf.const.PLUGINCONFPATH, str)
| 918
|
Python
|
.py
| 22
| 35.227273
| 64
| 0.710259
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,849
|
test_dnf_db_group.py
|
rpm-software-management_dnf/tests/api/test_dnf_db_group.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf
from .common import TestCase
class DnfRPMTransactionApiTest(TestCase):
def setUp(self):
self.base = dnf.Base(dnf.conf.Conf())
self.base.conf.persistdir = "/tmp/tests"
self.base.fill_sack(False, False)
self.base.resolve()
self.rpmTrans = self.base.transaction
def tearDown(self):
self.base.close()
def test_iterator(self):
# RPMTransaction.__iter__
self.assertHasAttr(self.rpmTrans, "__iter__")
for i in self.rpmTrans:
pass
def test_install_set(self):
# RPMTransaction.install_set
self.assertHasAttr(self.rpmTrans, "install_set")
self.assertHasType(self.rpmTrans.install_set, set)
def test_remove_set(self):
# RPMTransaction.remove_set
self.assertHasAttr(self.rpmTrans, "remove_set")
self.assertHasType(self.rpmTrans.remove_set, set)
| 1,009
|
Python
|
.py
| 27
| 30.37037
| 58
| 0.667695
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,850
|
test_dnf_cli.py
|
rpm-software-management_dnf/tests/api/test_dnf_cli.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf
import dnf.cli
import dnf.exceptions
from .common import TestCase
class DnfCliInitApiTest(TestCase):
def test_cli_error(self):
# dnf.cli.CliError
self.assertHasAttr(dnf.cli, "CliError")
ex = dnf.cli.CliError(value=None)
self.assertHasType(ex, dnf.exceptions.Error)
def test_cli(self):
# dnf.cli.Cli
self.assertHasAttr(dnf.cli, "Cli")
self.assertHasType(dnf.cli.Cli, object)
def test_command(self):
# dnf.cli.Command
self.assertHasAttr(dnf.cli, "Command")
self.assertHasType(dnf.cli.Command, object)
| 713
|
Python
|
.py
| 21
| 28.190476
| 52
| 0.685673
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,851
|
test_dnf_repo.py
|
rpm-software-management_dnf/tests/api/test_dnf_repo.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf.conf
import dnf.repo
from .common import TestCase
class DnfRepoApiTest(TestCase):
def test_init(self):
# dnf.repo.Repo.__init__
self.assertHasAttr(dnf.repo, "Repo")
self.assertHasType(dnf.repo.Repo, object)
repo = dnf.repo.Repo(name=None, parent_conf=None)
def test_repo_id_invalid(self):
# dnf.repo.repo_id_invalid
self.assertHasAttr(dnf.repo, "repo_id_invalid")
dnf.repo.repo_id_invalid(repo_id="repo-id")
def test_metadata_fresh(self):
# dnf.repo.Metadata.fresh
self.assertHasAttr(dnf.repo, "Metadata")
class MockRepo:
def fresh(self):
return True
mock_repo = MockRepo()
md = dnf.repo.Metadata(repo=mock_repo)
self.assertEqual(md.fresh, True)
def test_DEFAULT_SYNC(self):
# dnf.repo.Repo.DEFAULT_SYNC
self.assertHasAttr(dnf.repo.Repo, "DEFAULT_SYNC")
self.assertHasType(dnf.repo.Repo.DEFAULT_SYNC, int)
def test_metadata(self):
# dnf.repo.Repo.metadata
repo = dnf.repo.Repo()
self.assertHasAttr(repo, "metadata")
self.assertEqual(repo.metadata, None)
def test_id(self):
# dnf.repo.Repo.id
repo = dnf.repo.Repo()
self.assertHasAttr(repo, "id")
self.assertEqual(repo.id, "")
def test_repofile(self):
# dnf.repo.Repo.
repo = dnf.repo.Repo()
self.assertEqual(repo.repofile, "")
def test_pkgdir(self):
# dnf.repo.Repo.pkgdir
conf = dnf.conf.Conf()
conf.cachedir = "/tmp/cache"
repo = dnf.repo.Repo(name=None, parent_conf=conf)
self.assertHasAttr(repo, "pkgdir")
self.assertHasType(repo.pkgdir, str)
def test_pkgdir_setter(self):
# dnf.repo.Repo.pkgdir - setter
repo = dnf.repo.Repo()
repo.pkgdir = "dir"
self.assertHasType(repo.pkgdir, str)
self.assertEqual(repo.pkgdir, "dir")
def test_disable(self):
# dnf.repo.Repo.disable
repo = dnf.repo.Repo()
self.assertHasAttr(repo, "disable")
repo.disable()
def test_enable(self):
# dnf.repo.Repo.enable
repo = dnf.repo.Repo()
self.assertHasAttr(repo, "enable")
repo.enable()
def test_add_metadata_type_to_download(self):
# dnf.repo.Repo.add_metadata_type_to_download
repo = dnf.repo.Repo()
self.assertHasAttr(repo, "add_metadata_type_to_download")
repo.add_metadata_type_to_download(metadata_type="primary")
def test_remove_metadata_type_from_download(self):
# dnf.repo.Repo.remove_metadata_type_from_download
repo = dnf.repo.Repo()
self.assertHasAttr(repo, "remove_metadata_type_from_download")
repo.remove_metadata_type_from_download(metadata_type="primary")
def test_get_metadata_path(self):
# dnf.repo.Repo.get_metadata_path
repo = dnf.repo.Repo()
self.assertHasAttr(repo, "get_metadata_path")
path = repo.get_metadata_path(metadata_type="primary")
self.assertHasType(path, str)
def test_get_metadata_content(self):
# dnf.repo.Repo.get_metadata_content
repo = dnf.repo.Repo()
self.assertHasAttr(repo, "get_metadata_content")
content = repo.get_metadata_content(metadata_type="primary")
self.assertHasType(content, str)
def test_load(self):
# dnf.repo.Repo.load
repo = dnf.repo.Repo()
class MockRepo:
def load(self):
return True
repo._repo = MockRepo()
self.assertHasAttr(repo, "load")
repo.load()
def test_dump(self):
# dnf.repo.Repo.dump - inherited from BaseConfig
repo = dnf.repo.Repo()
self.assertHasAttr(repo, "dump")
content = repo.dump()
self.assertHasType(content, str)
def test_set_progress_bar(self):
# dnf.repo.Repo.set_progress_bar
repo = dnf.repo.Repo()
self.assertHasAttr(repo, "set_progress_bar")
repo.set_progress_bar(progress=None)
def test_get_http_headers(self):
# dnf.repo.Repo.get_http_headers
repo = dnf.repo.Repo()
self.assertHasAttr(repo, "get_http_headers")
headers = repo.get_http_headers()
self.assertHasType(headers, tuple)
def test_set_http_headers(self):
# dnf.repo.Repo.set_http_headers
repo = dnf.repo.Repo()
self.assertHasAttr(repo, "set_http_headers")
headers = repo.set_http_headers(headers=[])
| 4,659
|
Python
|
.py
| 119
| 30.840336
| 72
| 0.633038
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,852
|
test_dnf_module_base.py
|
rpm-software-management_dnf/tests/api/test_dnf_module_base.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf
import dnf.module.module_base
import os
import shutil
import tempfile
from .common import TestCase
class DnfModuleBaseApiTest(TestCase):
def setUp(self):
self.base = dnf.Base(dnf.conf.Conf())
self._installroot = tempfile.mkdtemp(prefix="dnf_test_installroot_")
self.base.conf.installroot = self._installroot
self.base.conf.cachedir = os.path.join(self._installroot, "var/cache/dnf")
self.base._sack = dnf.sack._build_sack(self.base)
self.moduleBase = dnf.module.module_base.ModuleBase(self.base)
def tearDown(self):
self.base.close()
if self._installroot.startswith("/tmp/"):
shutil.rmtree(self._installroot)
def test_init(self):
moduleBase = dnf.module.module_base.ModuleBase(self.base)
def test_enable(self):
# ModuleBase.enable()
self.assertHasAttr(self.moduleBase, "enable")
self.assertRaises(
dnf.exceptions.Error,
self.moduleBase.enable,
module_specs=["nodejs:8"],
)
def test_disable(self):
# ModuleBase.disable()
self.assertHasAttr(self.moduleBase, "disable")
self.assertRaises(
dnf.exceptions.Error,
self.moduleBase.disable,
module_specs=["nodejs"],
)
def test_reset(self):
# ModuleBase.reset()
self.assertHasAttr(self.moduleBase, "reset")
self.assertRaises(
dnf.exceptions.Error,
self.moduleBase.reset,
module_specs=["nodejs:8"],
)
def test_install(self):
# ModuleBase.install()
self.assertHasAttr(self.moduleBase, "install")
self.moduleBase.install(module_specs=[], strict=False)
def test_remove(self):
# ModuleBase.remove()
self.assertHasAttr(self.moduleBase, "remove")
self.moduleBase.remove(module_specs=[])
def test_upgrade(self):
# ModuleBase.upgrade()
self.assertHasAttr(self.moduleBase, "upgrade")
self.moduleBase.upgrade(module_specs=[])
def test_get_modules(self):
# ModuleBase.get_modules()
self.assertHasAttr(self.moduleBase, "get_modules")
self.moduleBase.get_modules(module_spec="")
| 2,360
|
Python
|
.py
| 63
| 29.47619
| 82
| 0.6484
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,853
|
test_dnf_rpm.py
|
rpm-software-management_dnf/tests/api/test_dnf_rpm.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf
from .common import TestCase
class DnfRpmApiTest(TestCase):
def test_detect_releasever(self):
# dnf.rpm.detect_releasever
self.assertHasAttr(dnf.rpm, "detect_releasever")
def test_basearch(self):
# dnf.rpm.basearch
self.assertHasAttr(dnf.rpm, "basearch")
self.assertHasType(dnf.rpm.basearch(arch="x86_64"), str)
| 481
|
Python
|
.py
| 13
| 31.769231
| 64
| 0.704989
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,854
|
test_dnf_package.py
|
rpm-software-management_dnf/tests/api/test_dnf_package.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf
from .common import TestCase
class DnfPackageApiTest(TestCase):
def setUp(self):
self.base = dnf.Base(dnf.conf.Conf())
self.package = self._get_pkg()
def tearDown(self):
self.base.close()
def test_arch(self):
# Package.arch
self.assertHasAttr(self.package, "arch")
self.assertHasType(self.package.arch, str)
def test_baseurl(self):
# Package.baseurl
self.assertHasAttr(self.package, "baseurl")
# The value is missing here so the type is type(None) but it should be str
# self.assertHasType(self.package.baseurl, str)
self.package.baseurl
def test_buildtime(self):
# Package.buildtime
self.assertHasAttr(self.package, "buildtime")
self.assertHasType(self.package.buildtime, int)
def test_chksum(self):
# Package.chksum()
self.assertHasAttr(self.package, "chksum")
# The value is missing here so the type is type(None) but it should be str
# self.assertHasType(self.package.chksum, str)
self.package.chksum
def test_conflicts(self):
# Package.conflicts()
self.assertHasAttr(self.package, "conflicts")
self.assertHasType(self.package.conflicts, list)
def test_debug_name(self):
# Package.debug_name
self.assertHasAttr(self.package, "debug_name")
self.assertHasType(self.package.debug_name, str)
def test_description(self):
# Package.description
self.assertHasAttr(self.package, "description")
self.assertHasType(self.package.description, str)
def test_downloadsize(self):
# Package.downloadsize
self.assertHasAttr(self.package, "downloadsize")
self.assertHasType(self.package.downloadsize, int)
def test_epoch(self):
# Package.epoch
self.assertHasAttr(self.package, "epoch")
self.assertHasType(self.package.epoch, int)
def test_enhances(self):
# Package.enhances
self.assertHasAttr(self.package, "enhances")
self.assertHasType(self.package.enhances, list)
def test_evr(self):
# Package.evr
self.assertHasAttr(self.package, "evr")
self.assertHasType(self.package.evr, str)
def test_files(self):
# Package.files
self.assertHasAttr(self.package, "files")
self.assertHasType(self.package.files, list)
def test_group(self):
# Package.group
self.assertHasAttr(self.package, "group")
self.assertHasType(self.package.group, str)
def test_hdr_chksum(self):
# Package.hdr_chksum
self.assertHasAttr(self.package, "hdr_chksum")
# The value is missing here so the type is type(None) but it should be str
# self.assertHasType(self.package.hdr_chksum, str)
self.package.hdr_chksum
def test_hdr_end(self):
# Package.hdr_end
self.assertHasAttr(self.package, "hdr_end")
self.assertHasType(self.package.hdr_end, int)
def test_changelogs(self):
# Package.changelogs
self.assertHasAttr(self.package, "changelogs")
self.assertHasType(self.package.changelogs, list)
def test_installed(self):
# Package.installed
self.assertHasAttr(self.package, "installed")
self.assertHasType(self.package.installed, bool)
def test_installtime(self):
# Package.installtime
self.assertHasAttr(self.package, "installtime")
self.assertHasType(self.package.installtime, int)
def test_installsize(self):
# Package.installsize
self.assertHasAttr(self.package, "installsize")
self.assertHasType(self.package.installsize, int)
def test_license(self):
# Package.license
self.assertHasAttr(self.package, "license")
self.assertHasType(self.package.license, str)
def test_medianr(self):
# Package.medianr
self.assertHasAttr(self.package, "medianr")
self.assertHasType(self.package.medianr, int)
def test_name(self):
# Package.name
self.assertHasAttr(self.package, "name")
self.assertHasType(self.package.name, str)
def test_vendor(self):
# Package.vendor
self.assertHasAttr(self.package, "vendor")
self.assertHasType(self.package.vendor, str)
def test_obsoletes(self):
# Package.obsoletes
self.assertHasAttr(self.package, "obsoletes")
self.assertHasType(self.package.obsoletes, list)
def test_provides(self):
# Package.provides
self.assertHasAttr(self.package, "provides")
self.assertHasType(self.package.provides, list)
def test_recommends(self):
# Package.recommends
self.assertHasAttr(self.package, "recommends")
self.assertHasType(self.package.recommends, list)
def test_release(self):
# Package.release
self.assertHasAttr(self.package, "release")
self.assertHasType(self.package.release, str)
def test_reponame(self):
# Package.reponame
self.assertHasAttr(self.package, "reponame")
self.assertHasType(self.package.reponame, str)
def test_from_repo(self):
# Package.reponame
self.assertHasAttr(self.package, "from_repo")
self.assertHasType(self.package.from_repo, str)
def test_requires(self):
# Package.requires
self.assertHasAttr(self.package, "requires")
self.assertHasType(self.package.requires, list)
def test_requires_pre(self):
# Package.requires_pre
self.assertHasAttr(self.package, "requires_pre")
self.assertHasType(self.package.requires_pre, list)
def test_regular_requires(self):
# Package.regular_requires
self.assertHasAttr(self.package, "regular_requires")
self.assertHasType(self.package.regular_requires, list)
def test_prereq_ignoreinst(self):
# Package.prereq_ignoreinst
self.assertHasAttr(self.package, "prereq_ignoreinst")
self.assertHasType(self.package.prereq_ignoreinst, list)
def test_rpmdbid(self):
# Package.rpmdbid
self.assertHasAttr(self.package, "rpmdbid")
self.assertHasType(self.package.rpmdbid, int)
def test_source_debug_name(self):
# Package.source_debug_name
self.assertHasAttr(self.package, "source_debug_name")
self.assertHasType(self.package.source_debug_name, str)
def test_source_name(self):
# Package.source_name
self.assertHasAttr(self.package, "source_name")
self.assertHasType(self.package.source_name, str)
def test_debugsource_name(self):
# Package.debugsource_name
self.assertHasAttr(self.package, "debugsource_name")
self.assertHasType(self.package.debugsource_name, str)
def test_sourcerpm(self):
# Package.sourcerpm
self.assertHasAttr(self.package, "sourcerpm")
self.assertHasType(self.package.sourcerpm, str)
def test_suggests(self):
# Package.suggests
self.assertHasAttr(self.package, "suggests")
self.assertHasType(self.package.suggests, list)
def test_summary(self):
# Package.summary
self.assertHasAttr(self.package, "summary")
self.assertHasType(self.package.summary, str)
def test_supplements(self):
# Package.supplements
self.assertHasAttr(self.package, "supplements")
self.assertHasType(self.package.supplements, list)
def test_url(self):
# Package.url
self.assertHasAttr(self.package, "url")
# The value is missing here so the type is type(None) but it should be str
# self.assertHasType(self.package.url, str)
self.package.url
def test_version(self):
# Package.version
self.assertHasAttr(self.package, "version")
self.assertHasType(self.package.version, str)
def test_packager(self):
# Package.packager
self.assertHasAttr(self.package, "packager")
# The value is missing here so the type is type(None) but it should be str
# self.assertHasType(self.package.packager, str)
self.package.packager
def test_remote_location(self):
# Package.remote_location
self.assertHasAttr(self.package, "remote_location")
self.package.remote_location(schemes='http')
def test_debuginfo_suffix(self):
# Package.DEBUGINFO_SUFFIX
self.assertHasAttr(self.package, "DEBUGINFO_SUFFIX")
self.assertHasType(self.package.DEBUGINFO_SUFFIX, str)
def test_debugsource_suffix(self):
# Package.DEBUGSOURCE_SUFFIX
self.assertHasAttr(self.package, "DEBUGSOURCE_SUFFIX")
self.assertHasType(self.package.DEBUGSOURCE_SUFFIX, str)
| 8,902
|
Python
|
.py
| 209
| 34.497608
| 82
| 0.681755
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,855
|
test_dnf_exceptions.py
|
rpm-software-management_dnf/tests/api/test_dnf_exceptions.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf.exceptions
from .common import TestCase
class DnfExceptionsApiTest(TestCase):
def test_deprectation_warning(self):
# dnf.exceptions.DeprecationWarning
self.assertHasAttr(dnf.exceptions, "DeprecationWarning")
self.assertHasType(dnf.exceptions.DeprecationWarning(), DeprecationWarning)
def test_error(self):
# dnf.exceptions.Error
self.assertHasAttr(dnf.exceptions, "Error")
ex = dnf.exceptions.Error(value=None)
self.assertHasType(ex, Exception)
def test_comps_error(self):
# dnf.exceptions.CompsError
self.assertHasAttr(dnf.exceptions, "CompsError")
ex = dnf.exceptions.CompsError(value=None)
self.assertHasType(ex, dnf.exceptions.Error)
def test_depsolve_error(self):
# dnf.exceptions.DepsolveError
self.assertHasAttr(dnf.exceptions, "DepsolveError")
ex = dnf.exceptions.DepsolveError(value=None)
self.assertHasType(ex, dnf.exceptions.Error)
def test_download_error(self):
# dnf.exceptions.DownloadError
self.assertHasAttr(dnf.exceptions, "DownloadError")
ex = dnf.exceptions.DownloadError(errmap=None)
self.assertHasType(ex, dnf.exceptions.Error)
def test_marking_error(self):
# dnf.exceptions.MarkinError
self.assertHasAttr(dnf.exceptions, "MarkingError")
ex = dnf.exceptions.MarkingError(value=None, pkg_spec=None)
self.assertHasType(ex, dnf.exceptions.Error)
def test_marking_errors(self):
# dnf.exceptions.MarkinErrors
self.assertHasAttr(dnf.exceptions, "MarkingErrors")
ex = dnf.exceptions.MarkingErrors(
no_match_group_specs=(),
error_group_specs=(),
no_match_pkg_specs=(),
error_pkg_specs=(),
module_depsolv_errors=()
)
self.assertHasType(ex, dnf.exceptions.Error)
def test_repo_error(self):
# dnf.exceptions.RepoError
self.assertHasAttr(dnf.exceptions, "RepoError")
ex = dnf.exceptions.RepoError()
self.assertHasType(ex, dnf.exceptions.Error)
| 2,229
|
Python
|
.py
| 51
| 35.607843
| 83
| 0.688078
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,856
|
test_dnf.py
|
rpm-software-management_dnf/tests/api/test_dnf.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import unittest
import dnf
from .common import TestCase
class DnfApiTest(TestCase):
def test_version(self):
# dnf.__version__
self.assertHasAttr(dnf, "__version__")
self.assertHasType(dnf.__version__, str)
def test_base(self):
# dnf.Base
self.assertHasAttr(dnf, "Base")
self.assertHasType(dnf.Base, object)
def test_plugin(self):
# dnf.Plugin
self.assertHasAttr(dnf, "Plugin")
self.assertHasType(dnf.Plugin, object)
| 612
|
Python
|
.py
| 19
| 26.315789
| 48
| 0.660959
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,857
|
test_dnf_logging.py
|
rpm-software-management_dnf/tests/api/test_dnf_logging.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf
import logging
from .common import TestCase
class DnfLoggingApiTest(TestCase):
def test_levels(self):
self.assertHasAttr(dnf.logging, "SUPERCRITICAL")
self.assertHasType(dnf.logging.SUPERCRITICAL, int)
self.assertHasAttr(dnf.logging, "CRITICAL")
self.assertHasType(dnf.logging.CRITICAL, int)
self.assertHasAttr(dnf.logging, "ERROR")
self.assertHasType(dnf.logging.ERROR, int)
self.assertHasAttr(dnf.logging, "WARNING")
self.assertHasType(dnf.logging.WARNING, int)
self.assertHasAttr(dnf.logging, "INFO")
self.assertHasType(dnf.logging.INFO, int)
self.assertHasAttr(dnf.logging, "DEBUG")
self.assertHasType(dnf.logging.DEBUG, int)
self.assertHasAttr(dnf.logging, "DDEBUG")
self.assertHasType(dnf.logging.DDEBUG, int)
self.assertHasAttr(dnf.logging, "SUBDEBUG")
self.assertHasType(dnf.logging.SUBDEBUG, int)
self.assertHasAttr(dnf.logging, "TRACE")
self.assertHasType(dnf.logging.TRACE, int)
self.assertHasAttr(dnf.logging, "ALL")
self.assertHasType(dnf.logging.ALL, int)
def test_logging_level_names(self):
# Level names added in dnf logging initialization
self.assertTrue(logging.getLevelName(dnf.logging.DDEBUG) == "DDEBUG")
self.assertTrue(logging.getLevelName(dnf.logging.SUBDEBUG) == "SUBDEBUG")
self.assertTrue(logging.getLevelName(dnf.logging.TRACE) == "TRACE")
def test_dnf_logger(self):
# This doesn't really test much since python allows getting any logger,
# at least check if it has handlers (setup in dnf).
logger = logging.getLogger('dnf')
self.assertTrue(len(logger.handlers) > 0)
def test_dnf_rpm_logger(self):
# This doesn't really test dnf api since python allows getting any logger,
# but at least check that the messages are somehow taken care of.
logger = logging.getLogger('dnf.rpm')
self.assertTrue(len(logger.handlers) > 0 or logger.propagate)
def test_dnf_plugin_logger(self):
# This doesn't really test dnf api since python allows getting any logger,
# but at least check that the messages are somehow taken care of.
logger = logging.getLogger('dnf.plugin')
self.assertTrue(len(logger.handlers) > 0 or logger.propagate)
| 2,486
|
Python
|
.py
| 48
| 43.979167
| 82
| 0.700703
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,858
|
test_dnf_cli_cli.py
|
rpm-software-management_dnf/tests/api/test_dnf_cli_cli.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf
import dnf.cli.cli
from .common import TestCase
class DnfCliCliApiTest(TestCase):
def setUp(self):
base = dnf.Base(dnf.conf.Conf())
self.cli = dnf.cli.cli.Cli(base=base)
def test_cli(self):
# dnf.cli.cli.Cli
self.assertHasAttr(dnf.cli.cli, "Cli")
self.assertHasType(dnf.cli.cli.Cli, object)
def test_init(self):
base = dnf.Base(dnf.conf.Conf())
_ = dnf.cli.cli.Cli(base=base)
def test_demands(self):
# dnf.cli.cli.Cli.demands
self.assertHasAttr(self.cli, "demands")
self.assertHasType(self.cli.demands, dnf.cli.demand.DemandSheet)
def test_redirect_logger(self):
# dnf.cli.cli.Cli.redirect_logger
self.assertHasAttr(self.cli, "redirect_logger")
self.cli.redirect_logger(stdout=None, stderr=None)
def test_register_command(self):
# dnf.cli.cli.Cli.register_command
self.assertHasAttr(self.cli, "register_command")
command_cls = dnf.cli.commands.Command(cli=self.cli)
self.cli.register_command(command_cls=command_cls)
| 1,202
|
Python
|
.py
| 30
| 33.366667
| 72
| 0.674419
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,859
|
test_dnf_subject.py
|
rpm-software-management_dnf/tests/api/test_dnf_subject.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf
from .common import TestCase
class DnfSubjectApiTest(TestCase):
def setUp(self):
self.subject = dnf.subject.Subject("")
def test_subject(self):
# dnf.subject.Subject
self.assertHasAttr(dnf.subject, "Subject")
self.assertHasType(dnf.subject.Subject, object)
def test_init(self):
# Subject.__init__
_ = dnf.subject.Subject("")
def test_get_best_query(self):
# Subject.get_best_query
self.assertHasAttr(self.subject, "get_best_query")
b = dnf.Base(dnf.conf.Conf())
b.fill_sack(False, False)
self.assertHasType(
self.subject.get_best_query(
sack=b.sack,
with_nevra=False,
with_provides=False,
with_filenames=False,
forms=None
), dnf.query.Query)
b.close()
def test_get_best_selector(self):
# Subject.get_best_selector
self.assertHasAttr(self.subject, "get_best_selector")
b = dnf.Base(dnf.conf.Conf())
b.fill_sack(False, False)
self.assertHasType(
self.subject.get_best_selector(
sack=b.sack,
forms=None,
obsoletes=False,
reponame=None
), dnf.selector.Selector)
b.close()
def test_get_nevra_possibilities(self):
# Subject.get_nevra_possibilities
self.assertHasAttr(self.subject, "get_nevra_possibilities")
self.assertHasType(self.subject.get_nevra_possibilities(forms=None), list)
| 1,686
|
Python
|
.py
| 46
| 27.065217
| 82
| 0.604052
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,860
|
test_dnf_conf.py
|
rpm-software-management_dnf/tests/api/test_dnf_conf.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf
from .common import TestCase
class DnfConfTest(TestCase):
def setUp(self):
self.base = dnf.Base(dnf.conf.Conf())
self.conf = self.base.conf
def tearDown(self):
self.base.close()
def test_priorities(self):
self.assertHasAttr(dnf.conf.config, "PRIO_EMPTY")
self.assertHasType(dnf.conf.config.PRIO_EMPTY, int)
self.assertHasAttr(dnf.conf.config, "PRIO_DEFAULT")
self.assertHasType(dnf.conf.config.PRIO_DEFAULT, int)
self.assertHasAttr(dnf.conf.config, "PRIO_MAINCONFIG")
self.assertHasType(dnf.conf.config.PRIO_MAINCONFIG, int)
self.assertHasAttr(dnf.conf.config, "PRIO_AUTOMATICCONFIG")
self.assertHasType(dnf.conf.config.PRIO_AUTOMATICCONFIG, int)
self.assertHasAttr(dnf.conf.config, "PRIO_REPOCONFIG")
self.assertHasType(dnf.conf.config.PRIO_REPOCONFIG, int)
self.assertHasAttr(dnf.conf.config, "PRIO_PLUGINDEFAULT")
self.assertHasType(dnf.conf.config.PRIO_PLUGINDEFAULT, int)
self.assertHasAttr(dnf.conf.config, "PRIO_PLUGINCONFIG")
self.assertHasType(dnf.conf.config.PRIO_PLUGINCONFIG, int)
self.assertHasAttr(dnf.conf.config, "PRIO_COMMANDLINE")
self.assertHasType(dnf.conf.config.PRIO_COMMANDLINE, int)
self.assertHasAttr(dnf.conf.config, "PRIO_RUNTIME")
self.assertHasType(dnf.conf.config.PRIO_RUNTIME, int)
def test_get_reposdir(self):
# Conf.get_reposdir
self.conf.reposdir = ["."]
self.assertHasAttr(self.conf, "get_reposdir")
self.assertHasType(self.conf.get_reposdir, str)
def test_substitutions(self):
# Conf.substitutions
self.assertHasAttr(self.conf, "substitutions")
self.assertHasType(self.conf.substitutions, dnf.conf.substitutions.Substitutions)
def test_tempfiles(self):
# Conf.tempfiles
self.assertHasAttr(self.conf, "tempfiles")
self.assertHasType(self.conf.tempfiles, list)
def test_exclude_pkgs(self):
# Conf.exclude_pkgs
self.assertHasAttr(self.conf, "exclude_pkgs")
self.conf.exclude_pkgs(pkgs=["package_a", "package_b"])
def test_prepend_installroot(self):
# Conf.prepend_installroot
self.assertHasAttr(self.conf, "prepend_installroot")
self.conf.prepend_installroot(optname="logdir")
def test_read(self):
# Conf.read
self.assertHasAttr(self.conf, "read")
self.conf.read(filename=None, priority=dnf.conf.config.PRIO_DEFAULT)
def test_dump(self):
# Conf.dump
self.assertHasAttr(self.conf, "dump")
self.assertHasType(self.conf.dump(), str)
def test_releasever(self):
# Conf.releasever
self.assertHasAttr(self.conf, "releasever")
self.conf.releasever = "test setter"
self.assertHasType(self.conf.releasever, str)
def test_arch(self):
# Conf.arch
self.assertHasAttr(self.conf, "arch")
self.conf.arch = "aarch64"
self.assertHasType(self.conf.arch, str)
def test_basearch(self):
# Conf.basearch
self.assertHasAttr(self.conf, "basearch")
self.conf.basearch = "aarch64"
self.assertHasType(self.conf.basearch, str)
def test_write_raw_configfile(self):
# Conf.write_raw_configfile
self.assertHasAttr(self.conf, "write_raw_configfile")
s = dnf.conf.substitutions.Substitutions()
self.conf.write_raw_configfile(filename="file.conf", section_id='main', substitutions=s, modify={})
class DnfSubstitutionsTest(TestCase):
def test_update_from_etc(self):
# Substitutions.update_from_etc
substitutions = dnf.conf.substitutions.Substitutions()
self.assertHasAttr(substitutions, "update_from_etc")
substitutions.update_from_etc(installroot="path", varsdir=("/etc/path/", "/etc/path2"))
| 3,998
|
Python
|
.py
| 85
| 39.058824
| 107
| 0.688465
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,861
|
test_dnf_transaction.py
|
rpm-software-management_dnf/tests/api/test_dnf_transaction.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf
from .common import TestCase
class DnfTransactionApiTest(TestCase):
def test_pkg_action_constants(self):
self.assertHasAttr(dnf.transaction, "PKG_DOWNGRADE")
self.assertHasType(dnf.transaction.PKG_DOWNGRADE, int)
self.assertHasAttr(dnf.transaction, "PKG_DOWNGRADED")
self.assertHasType(dnf.transaction.PKG_DOWNGRADED, int)
self.assertHasAttr(dnf.transaction, "PKG_INSTALL")
self.assertHasType(dnf.transaction.PKG_INSTALL, int)
self.assertHasAttr(dnf.transaction, "PKG_OBSOLETE")
self.assertHasType(dnf.transaction.PKG_OBSOLETE, int)
self.assertHasAttr(dnf.transaction, "PKG_OBSOLETED")
self.assertHasType(dnf.transaction.PKG_OBSOLETED, int)
self.assertHasAttr(dnf.transaction, "PKG_REINSTALL")
self.assertHasType(dnf.transaction.PKG_REINSTALL, int)
self.assertHasAttr(dnf.transaction, "PKG_REINSTALLED")
self.assertHasType(dnf.transaction.PKG_REINSTALLED, int)
self.assertHasAttr(dnf.transaction, "PKG_REMOVE")
self.assertHasType(dnf.transaction.PKG_REMOVE, int)
self.assertHasAttr(dnf.transaction, "PKG_UPGRADE")
self.assertHasType(dnf.transaction.PKG_UPGRADE, int)
self.assertHasAttr(dnf.transaction, "PKG_UPGRADED")
self.assertHasType(dnf.transaction.PKG_UPGRADED, int)
self.assertHasAttr(dnf.transaction, "PKG_ERASE")
self.assertHasType(dnf.transaction.PKG_ERASE, int)
self.assertHasAttr(dnf.transaction, "PKG_CLEANUP")
self.assertHasType(dnf.transaction.PKG_CLEANUP, int)
self.assertHasAttr(dnf.transaction, "PKG_VERIFY")
self.assertHasType(dnf.transaction.PKG_VERIFY, int)
self.assertHasAttr(dnf.transaction, "PKG_SCRIPTLET")
self.assertHasType(dnf.transaction.PKG_SCRIPTLET, int)
def test_trans_action_constants(self):
self.assertHasAttr(dnf.transaction, "TRANS_PREPARATION")
self.assertHasType(dnf.transaction.TRANS_PREPARATION, int)
self.assertHasAttr(dnf.transaction, "TRANS_POST")
self.assertHasType(dnf.transaction.TRANS_POST, int)
def test_forward_action_constants(self):
self.assertHasAttr(dnf.transaction, "FORWARD_ACTIONS")
self.assertHasType(dnf.transaction.FORWARD_ACTIONS, list)
def test_backward_action_constants(self):
self.assertHasAttr(dnf.transaction, "BACKWARD_ACTIONS")
self.assertHasType(dnf.transaction.BACKWARD_ACTIONS, list)
def test_action_constants(self):
self.assertHasAttr(dnf.transaction, "ACTIONS")
self.assertHasType(dnf.transaction.ACTIONS, dict)
def test_file_action_constants(self):
self.assertHasAttr(dnf.transaction, "FILE_ACTIONS")
self.assertHasType(dnf.transaction.FILE_ACTIONS, dict)
| 2,913
|
Python
|
.py
| 52
| 47.923077
| 66
| 0.731664
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,862
|
test_dnf_comps.py
|
rpm-software-management_dnf/tests/api/test_dnf_comps.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf
import libcomps
from .common import TestCase
class MockLangs():
def get(self):
return []
class DnfCompsApiTest(TestCase):
def test_conditional(self):
# dnf.comps.CONDITIONAL
self.assertHasAttr(dnf.comps, "CONDITIONAL")
self.assertHasType(dnf.comps.CONDITIONAL, int)
def test_default(self):
# dnf.comps.DEFAULT
self.assertHasAttr(dnf.comps, "DEFAULT")
self.assertHasType(dnf.comps.DEFAULT, int)
def test_mandatory(self):
# dnf.comps.MANDATORY
self.assertHasAttr(dnf.comps, "MANDATORY")
self.assertHasType(dnf.comps.MANDATORY, int)
def test_optional(self):
# dnf.comps.OPTIONAL
self.assertHasAttr(dnf.comps, "OPTIONAL")
self.assertHasType(dnf.comps.OPTIONAL, int)
def test_category(self):
# dnf.comps.Category
self.assertHasAttr(dnf.comps, "Category")
self.assertHasType(dnf.comps.Category, object)
def test_category_init(self):
libcomps_category = libcomps.Category("id", "name", "description")
_ = dnf.comps.Category(iobj=libcomps_category, langs=None, group_factory=None)
def test_category_id(self):
# dnf.comps.Category.id
libcomps_category = libcomps.Category("id", "name", "description")
category = dnf.comps.Category(iobj=libcomps_category, langs=None, group_factory=None)
self.assertHasAttr(category, "id")
self.assertHasType(category.id, str)
def test_category_name(self):
# dnf.comps.Category.name
libcomps_category = libcomps.Category("id", "name", "description")
category = dnf.comps.Category(iobj=libcomps_category, langs=None, group_factory=None)
self.assertHasAttr(category, "name")
self.assertHasType(category.name, str)
def test_category_ui_name(self):
# dnf.comps.Category.ui_name
libcomps_category = libcomps.Category("id", "name", "description")
langs = MockLangs()
category = dnf.comps.Category(iobj=libcomps_category, langs=langs, group_factory=None)
self.assertHasAttr(category, "ui_name")
self.assertHasType(category.ui_name, str)
def test_category_ui_description(self):
# dnf.comps.Category.ui_description
libcomps_category = libcomps.Category("id", "name", "description")
langs = MockLangs()
category = dnf.comps.Category(iobj=libcomps_category, langs=langs, group_factory=None)
self.assertHasAttr(category, "ui_description")
self.assertHasType(category.ui_description, str)
def test_environment(self):
# dnf.comps.Environment
self.assertHasAttr(dnf.comps, "Environment")
self.assertHasType(dnf.comps.Environment, object)
def test_environment_init(self):
libcomps_environment = libcomps.Environment("id", "name", "description")
_ = dnf.comps.Environment(iobj=libcomps_environment, langs=None, group_factory=None)
def test_environment_id(self):
# dnf.comps.Environment.id
libcomps_environment = libcomps.Environment("id", "name", "description")
environment = dnf.comps.Environment(iobj=libcomps_environment, langs=None, group_factory=None)
self.assertHasAttr(environment, "id")
self.assertHasType(environment.id, str)
def test_environment_name(self):
# dnf.comps.Environment.name
libcomps_environment = libcomps.Environment("id", "name", "description")
environment = dnf.comps.Environment(iobj=libcomps_environment, langs=None, group_factory=None)
self.assertHasAttr(environment, "name")
self.assertHasType(environment.name, str)
def test_environment_ui_name(self):
# dnf.comps.Environment.ui_name
libcomps_environment = libcomps.Environment("id", "name", "description")
langs = MockLangs()
environment = dnf.comps.Environment(iobj=libcomps_environment, langs=langs, group_factory=None)
self.assertHasAttr(environment, "ui_name")
self.assertHasType(environment.ui_name, str)
def test_environment_ui_description(self):
# dnf.comps.Environment.ui_description
libcomps_environment = libcomps.Environment("id", "name", "description")
langs = MockLangs()
environment = dnf.comps.Environment(iobj=libcomps_environment, langs=langs, group_factory=None)
self.assertHasAttr(environment, "ui_description")
self.assertHasType(environment.ui_description, str)
def test_group(self):
# dnf.comps.Group
self.assertHasAttr(dnf.comps, "Group")
self.assertHasType(dnf.comps.Group, object)
def test_group_init(self):
libcomps_group = libcomps.Group("id", "name", "description")
_ = dnf.comps.Group(iobj=libcomps_group, langs=None, pkg_factory=None)
def test_group_id(self):
# dnf.comps.Group.id
libcomps_group = libcomps.Group("id", "name", "description")
group = dnf.comps.Group(iobj=libcomps_group, langs=None, pkg_factory=None)
self.assertHasAttr(group, "id")
self.assertHasType(group.id, str)
def test_group_name(self):
# dnf.comps.Group.name
libcomps_group = libcomps.Group("id", "name", "description")
group = dnf.comps.Group(iobj=libcomps_group, langs=None, pkg_factory=None)
self.assertHasAttr(group, "name")
self.assertHasType(group.name, str)
def test_group_ui_name(self):
# dnf.comps.Group.ui_name
libcomps_group = libcomps.Group("id", "name", "description")
langs = MockLangs()
group = dnf.comps.Group(iobj=libcomps_group, langs=langs, pkg_factory=None)
self.assertHasAttr(group, "ui_name")
self.assertHasType(group.ui_name, str)
def test_group_ui_description(self):
# dnf.comps.Group.ui_description
libcomps_group = libcomps.Group("id", "name", "description")
langs = MockLangs()
group = dnf.comps.Group(iobj=libcomps_group, langs=langs, pkg_factory=None)
self.assertHasAttr(group, "ui_description")
self.assertHasType(group.ui_description, str)
def test_group_packages_iter(self):
# dnf.comps.Group.packages_iter
libcomps_group = libcomps.Group("id", "name", "description")
group = dnf.comps.Group(libcomps_group, None, lambda x: x)
group.packages_iter()
def test_package(self):
# dnf.comps.Package
self.assertHasAttr(dnf.comps, "Package")
self.assertHasType(dnf.comps.Package, object)
def test_package_init(self):
libcomps_package = libcomps.Package()
_ = dnf.comps.Package(ipkg=libcomps_package)
def test_package_name(self):
# dnf.comps.Package.name
libcomps_package = libcomps.Package()
libcomps_package.name = "name"
package = dnf.comps.Package(libcomps_package)
self.assertHasAttr(package, "name")
self.assertHasType(package.name, str)
def test_package_option_type(self):
# dnf.comps.Package.option_type
libcomps_package = libcomps.Package()
libcomps_package.type = 0
package = dnf.comps.Package(libcomps_package)
self.assertHasAttr(package, "option_type")
self.assertHasType(package.option_type, int)
def test_comps(self):
# dnf.comps.Comps
self.assertHasAttr(dnf.comps, "Comps")
self.assertHasType(dnf.comps.Comps, object)
def test_comps_init(self):
_ = dnf.comps.Comps()
def test_comps_categories(self):
# dnf.comps.Comps.categories
comps = dnf.comps.Comps()
self.assertHasAttr(comps, "categories")
self.assertHasType(comps.categories, list)
def test_comps_category_by_pattern(self):
# dnf.comps.Comps.category_by_pattern
comps = dnf.comps.Comps()
comps.category_by_pattern(pattern="foo", case_sensitive=False)
def test_comps_categories_by_pattern(self):
# dnf.comps.Comps.categories_by_pattern
comps = dnf.comps.Comps()
comps.categories_by_pattern(pattern="foo", case_sensitive=False)
def test_comps_categories_iter(self):
# dnf.comps.Comps.categories_iter
comps = dnf.comps.Comps()
comps.categories_iter()
def test_comps_environments(self):
# dnf.comps.Comps.environments
comps = dnf.comps.Comps()
self.assertHasAttr(comps, "environments")
self.assertHasType(comps.environments, list)
def test_comps_environment_by_pattern(self):
# dnf.comps.Comps.environment_by_pattern
comps = dnf.comps.Comps()
comps.environment_by_pattern(pattern="foo", case_sensitive=False)
def test_comps_environments_by_pattern(self):
# dnf.comps.Comps.environments_by_pattern
comps = dnf.comps.Comps()
comps.environments_by_pattern(pattern="foo", case_sensitive=False)
def test_comps_environments_iter(self):
# dnf.comps.Comps.environments_iter
comps = dnf.comps.Comps()
comps.environments_iter()
def test_comps_groups(self):
# dnf.comps.Comps.groups
comps = dnf.comps.Comps()
self.assertHasAttr(comps, "groups")
self.assertHasType(comps.groups, list)
def test_comps_group_by_pattern(self):
# dnf.comps.Comps.group_by_pattern
comps = dnf.comps.Comps()
comps.group_by_pattern(pattern="foo", case_sensitive=False)
def test_comps_groups_by_pattern(self):
# dnf.comps.Comps.groups_by_pattern
comps = dnf.comps.Comps()
comps.groups_by_pattern(pattern="foo", case_sensitive=False)
def test_comps_groups_iter(self):
# dnf.comps.Comps.groups_iter
comps = dnf.comps.Comps()
comps.groups_iter()
| 9,899
|
Python
|
.py
| 208
| 39.394231
| 103
| 0.677436
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,863
|
test_dnf_plugin.py
|
rpm-software-management_dnf/tests/api/test_dnf_plugin.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf
import libdnf
from .common import TestCase
from .common import TOUR_4_4
class DnfPluginApiTest(TestCase):
def setUp(self):
self.plugin = dnf.Plugin(base=None, cli=None)
def test_plugin(self):
# dnf.Plugin
self.assertHasAttr(dnf, "Plugin")
self.assertHasType(dnf.Plugin, object)
def test_name(self):
# Plugin.name
self.assertHasAttr(self.plugin, "name")
self.plugin.name = "test"
self.assertHasType(self.plugin.name, str)
def test_read_config(self):
# dnf.Plugin.read_config
self.assertHasAttr(dnf.Plugin, "read_config")
self.assertHasType(dnf.Plugin.read_config(conf=dnf.conf.Conf()), libdnf.conf.ConfigParser)
def test_init(self):
# Plugin.__init__
_ = dnf.Plugin(base=None, cli=None)
def test_pre_config(self):
# Plugin.pre_config
self.assertHasAttr(self.plugin, "pre_config")
self.plugin.pre_config()
def test_config(self):
# Plugin.config
self.assertHasAttr(self.plugin, "config")
self.plugin.config()
def test_resolved(self):
# Plugin.resolved
self.assertHasAttr(self.plugin, "resolved")
self.plugin.resolved()
def test_sack(self):
# Plugin.sack
self.assertHasAttr(self.plugin, "sack")
self.plugin.sack()
def test_pre_transaction(self):
# Plugin.pre_transaction
self.assertHasAttr(self.plugin, "pre_transaction")
self.plugin.pre_transaction()
def test_transaction(self):
# Plugin.transaction
self.assertHasAttr(self.plugin, "transaction")
self.plugin.transaction()
class Dnfregister_commandApiTest(TestCase):
def test_register_command(self):
self.assertHasAttr(dnf.plugin, "register_command")
@dnf.plugin.register_command
class TestClassWithDecorator():
aliases = ('necessary-alias',)
self.assertHasAttr(TestClassWithDecorator, "_plugin")
| 2,118
|
Python
|
.py
| 57
| 29.842105
| 98
| 0.66487
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,864
|
test_dnf_callback.py
|
rpm-software-management_dnf/tests/api/test_dnf_callback.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf
from .common import TestCase
class DnfCallbackApiTest(TestCase):
def test_pkg_downgrade(self):
# dnf.callback.PKG_DOWNGRADE
self.assertHasAttr(dnf.callback, "PKG_DOWNGRADE")
self.assertHasType(dnf.callback.PKG_DOWNGRADE, int)
def test_downgraded(self):
# dnf.callback.PKG_DOWNGRADED
self.assertHasAttr(dnf.callback, "PKG_DOWNGRADED")
self.assertHasType(dnf.callback.PKG_DOWNGRADED, int)
def test_pkg_install(self):
# dnf.callback.PKG_INSTALL
self.assertHasAttr(dnf.callback, "PKG_INSTALL")
self.assertHasType(dnf.callback.PKG_INSTALL, int)
def test_pkg_obsolete(self):
# dnf.callback.PKG_OBSOLETE
self.assertHasAttr(dnf.callback, "PKG_OBSOLETE")
self.assertHasType(dnf.callback.PKG_OBSOLETE, int)
def test_pkg_obsoleted(self):
# dnf.callback.PKG_OBSOLETED
self.assertHasAttr(dnf.callback, "PKG_OBSOLETED")
self.assertHasType(dnf.callback.PKG_OBSOLETED, int)
def test_pkg_reinstall(self):
# dnf.callback.PKG_REINSTALL
self.assertHasAttr(dnf.callback, "PKG_REINSTALL")
self.assertHasType(dnf.callback.PKG_REINSTALL, int)
def test_pkg_reinstalled(self):
# dnf.callback.PKG_REINSTALLED
self.assertHasAttr(dnf.callback, "PKG_REINSTALLED")
self.assertHasType(dnf.callback.PKG_REINSTALLED, int)
def test_pkg_remove(self):
# dnf.callback.PKG_REMOVE
self.assertHasAttr(dnf.callback, "PKG_REMOVE")
self.assertHasType(dnf.callback.PKG_REMOVE, int)
def test_pkg_upgrade(self):
# dnf.callback.PKG_UPGRADE
self.assertHasAttr(dnf.callback, "PKG_UPGRADE")
self.assertHasType(dnf.callback.PKG_UPGRADE, int)
def test_pkg_upgraded(self):
# dnf.callback.PKG_UPGRADED
self.assertHasAttr(dnf.callback, "PKG_UPGRADED")
self.assertHasType(dnf.callback.PKG_UPGRADED, int)
def test_pkg_cleanup(self):
# dnf.callback.PKG_CLEANUP
self.assertHasAttr(dnf.callback, "PKG_CLEANUP")
self.assertHasType(dnf.callback.PKG_CLEANUP, int)
def test_pkg_verify(self):
# dnf.callback.PKG_VERIFY
self.assertHasAttr(dnf.callback, "PKG_VERIFY")
self.assertHasType(dnf.callback.PKG_VERIFY, int)
def test_pkg_scriptlet(self):
# dnf.callback.PKG_SCRIPTLET
self.assertHasAttr(dnf.callback, "PKG_SCRIPTLET")
self.assertHasType(dnf.callback.PKG_SCRIPTLET, int)
def test_trans_preparation(self):
# dnf.callback.TRANS_PREPARATION
self.assertHasAttr(dnf.callback, "TRANS_PREPARATION")
self.assertHasType(dnf.callback.TRANS_PREPARATION, int)
def test_trans_post(self):
# dnf.callback.TRANS_POST
self.assertHasAttr(dnf.callback, "TRANS_POST")
self.assertHasType(dnf.callback.TRANS_POST, int)
def test_status_ok(self):
# dnf.callback.STATUS_OK
self.assertHasAttr(dnf.callback, "STATUS_OK")
self.assertHasType(dnf.callback.STATUS_OK, object)
def test_status_failed(self):
# dnf.callback.STATUS_FAILED
self.assertHasAttr(dnf.callback, "STATUS_FAILED")
self.assertHasType(dnf.callback.STATUS_FAILED, int)
def test_status_already_exists(self):
# dnf.callback.STATUS_ALREADY_EXISTS
self.assertHasAttr(dnf.callback, "STATUS_ALREADY_EXISTS")
self.assertHasType(dnf.callback.STATUS_ALREADY_EXISTS, int)
def test_status_mirror(self):
# dnf.callback.STATUS_MIRROR
self.assertHasAttr(dnf.callback, "STATUS_MIRROR")
self.assertHasType(dnf.callback.STATUS_MIRROR, int)
def test_status_drpm(self):
# dnf.callback.STATUS_DRPM
self.assertHasAttr(dnf.callback, "STATUS_DRPM")
self.assertHasType(dnf.callback.STATUS_DRPM, int)
def test_payload(self):
# dnf.callback.Payload
self.assertHasAttr(dnf.callback, "Payload")
self.assertHasType(dnf.callback.Payload, object)
def test_payload_init(self):
# dnf.callback.Payload.__init__
download_progress = dnf.callback.DownloadProgress()
_ = dnf.callback.Payload(progress=download_progress)
def test_payload_str(self):
# dnf.callback.Payload.__str__
download_progress = dnf.callback.DownloadProgress()
payload = dnf.callback.Payload(progress=download_progress)
payload.__str__()
def test_payload_download_size(self):
# dnf.callback.Payload.download_size
download_progress = dnf.callback.DownloadProgress()
payload = dnf.callback.Payload(progress=download_progress)
self.assertHasAttr(payload, "download_size")
self.assertHasType(payload.download_size, object)
def test_download_progress(self):
# dnf.callback.DownloadProgress
self.assertHasAttr(dnf.callback, "DownloadProgress")
self.assertHasType(dnf.callback.DownloadProgress, object)
def test_download_progress_end(self):
# dnf.callback.DownloadProgress.end
download_progress = dnf.callback.DownloadProgress()
payload = dnf.callback.Payload(progress=download_progress)
download_progress.end(payload=payload, status=dnf.callback.STATUS_OK, msg="err_msg")
def test_download_progress_progress(self):
# dnf.callback.DownloadProgress.progress
download_progress = dnf.callback.DownloadProgress()
payload = dnf.callback.Payload(progress=download_progress)
download_progress.progress(payload=payload, done=0)
def test_download_progress_start(self):
# dnf.callback.DownloadProgress.start
download_progress = dnf.callback.DownloadProgress()
download_progress.start(total_files=1, total_size=1, total_drpms=0)
def test_TransactionProgress(self):
# dnf.callback.TransactionProgress
self.assertHasAttr(dnf.callback, "TransactionProgress")
self.assertHasType(dnf.callback.TransactionProgress, object)
| 6,107
|
Python
|
.py
| 127
| 40.110236
| 92
| 0.704003
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,865
|
test_dnf_sack.py
|
rpm-software-management_dnf/tests/api/test_dnf_sack.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf
from .common import TestCase
class DnfSackApiTest(TestCase):
def setUp(self):
self.base = dnf.Base(dnf.conf.Conf())
def tearDown(self):
self.base.close()
def test_rpmdb_sack(self):
# dnf.sack.rpmdb_sack
self.assertHasAttr(dnf.sack, "rpmdb_sack")
self.assertHasType(dnf.sack.rpmdb_sack(self.base), dnf.sack.Sack)
def test_query(self):
# Sack.query
self.base.fill_sack(False, False)
self.assertHasAttr(self.base.sack, "query")
self.assertHasType(self.base.sack.query(flags=0), dnf.query.Query)
| 703
|
Python
|
.py
| 19
| 30.894737
| 74
| 0.675556
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,866
|
test_dnf_yum_rpmtrans.py
|
rpm-software-management_dnf/tests/api/test_dnf_yum_rpmtrans.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf
from .common import TestCase
class DnfTransactionDisplayApiTest(TestCase):
def setUp(self):
self.td = dnf.yum.rpmtrans.TransactionDisplay()
def test_init(self):
td = dnf.yum.rpmtrans.TransactionDisplay()
self.assertHasType(td, dnf.yum.rpmtrans.TransactionDisplay)
def test_progress(self):
# TransactionDisplay.progress
self.assertHasAttr(self.td, "progress")
self.td.progress(
package=None,
action=None,
ti_done=None,
ti_total=None,
ts_done=None,
ts_total=None
)
def test_error(self):
# RPMTransaction.error
self.assertHasAttr(self.td, "error")
self.td.error(message="")
| 862
|
Python
|
.py
| 26
| 25.346154
| 67
| 0.639661
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,867
|
test_dnf_cli_demand.py
|
rpm-software-management_dnf/tests/api/test_dnf_cli_demand.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf
import dnf.cli.demand
from .common import TestCase
class DnfCliDemandApiTest(TestCase):
def setUp(self):
self.demand_sheet = dnf.cli.demand.DemandSheet()
def test_demand_sheet(self):
# dnf.cli.demand.DemandSheet
self.assertHasAttr(dnf.cli.demand, "DemandSheet")
self.assertHasType(dnf.cli.demand.DemandSheet, object)
def test_init(self):
_ = dnf.cli.demand.DemandSheet()
def test_allow_erasing(self):
# dnf.cli.demand.DemandSheet.allow_erasing
self.assertHasAttr(self.demand_sheet, "allow_erasing")
self.assertHasType(self.demand_sheet.allow_erasing, bool)
def test_available_repos(self):
# dnf.cli.demand.DemandSheet.available_repos
self.assertHasAttr(self.demand_sheet, "available_repos")
self.assertHasType(self.demand_sheet.available_repos, bool)
def test_resolving(self):
# dnf.cli.demand.DemandSheet.resolving
self.assertHasAttr(self.demand_sheet, "resolving")
self.assertHasType(self.demand_sheet.resolving, bool)
def test_root_user(self):
# dnf.cli.demand.DemandSheet.root_user
self.assertHasAttr(self.demand_sheet, "root_user")
self.assertHasType(self.demand_sheet.root_user, bool)
def test_sack_activation(self):
# dnf.cli.demand.DemandSheet.sack_activation
self.assertHasAttr(self.demand_sheet, "sack_activation")
self.assertHasType(self.demand_sheet.sack_activation, bool)
def test_load_system_repo(self):
# dnf.cli.demand.DemandSheet.load_system_repo
self.assertHasAttr(self.demand_sheet, "load_system_repo")
self.assertHasType(self.demand_sheet.load_system_repo, bool)
def test_success_exit_status(self):
# dnf.cli.demand.DemandSheet.success_exit_status
self.assertHasAttr(self.demand_sheet, "success_exit_status")
self.assertHasType(self.demand_sheet.success_exit_status, int)
def test_cacheonly(self):
# dnf.cli.demand.DemandSheet.cacheonly
self.assertHasAttr(self.demand_sheet, "cacheonly")
self.assertHasType(self.demand_sheet.cacheonly, bool)
def test_fresh_metadata(self):
# dnf.cli.demand.DemandSheet.fresh_metadata
self.assertHasAttr(self.demand_sheet, "fresh_metadata")
self.assertHasType(self.demand_sheet.fresh_metadata, bool)
def test_freshest_metadata(self):
# dnf.cli.demand.DemandSheet.freshest_metadata
self.assertHasAttr(self.demand_sheet, "freshest_metadata")
self.assertHasType(self.demand_sheet.freshest_metadata, bool)
def test_changelogs(self):
# dnf.cli.demand.DemandSheet.changelogs
self.assertHasAttr(self.demand_sheet, "changelogs")
self.assertHasType(self.demand_sheet.changelogs, bool)
def test_transaction_display(self):
# dnf.cli.demand.DemandSheet.transaction_display
self.assertHasAttr(self.demand_sheet, "transaction_display")
self.assertHasType(self.demand_sheet.changelogs, object)
def test_plugin_filtering_enabled(self):
# dnf.cli.demand.DemandSheet.plugin_filtering_enabled
self.assertHasAttr(self.demand_sheet, "plugin_filtering_enabled")
self.assertHasType(self.demand_sheet.plugin_filtering_enabled, object)
| 3,414
|
Python
|
.py
| 67
| 43.432836
| 78
| 0.720986
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,868
|
test_dnf_base.py
|
rpm-software-management_dnf/tests/api/test_dnf_base.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf
import dnf.conf
import tests.support
from .common import TestCase
from .common import TOUR_4_4
def conf_with_empty_plugins():
"""
Use empty configuration to avoid importing plugins from default paths
which would lead to crash of other tests.
"""
conf = tests.support.FakeConf()
conf.plugins = True
conf.pluginpath = []
return conf
class DnfBaseApiTest(TestCase):
def setUp(self):
self.base = dnf.Base(dnf.conf.Conf())
self.base.conf.persistdir = "/tmp/tests"
self.base.conf.installroot = "/tmp/dnf-test-installroot/"
def tearDown(self):
self.base.close()
def test_base(self):
# dnf.base.Base
self.assertHasAttr(dnf.base, "Base")
self.assertHasType(dnf.base.Base, object)
def test_init(self):
base = dnf.Base(dnf.conf.Conf())
def test_init_conf(self):
conf = dnf.conf.Conf()
base = dnf.base.Base(conf=conf)
def test_comps(self):
# Base.comps
self.assertHasAttr(self.base, "comps")
self.assertHasType(self.base.comps, dnf.comps.Comps)
self.base.read_comps()
self.assertHasType(self.base.comps, dnf.comps.Comps)
def test_conf(self):
# Base.conf
self.assertHasAttr(self.base, "conf")
self.assertHasType(self.base.conf, dnf.conf.Conf)
def test_repos(self):
# Base.repos
self.assertHasAttr(self.base, "repos")
self.assertHasType(self.base.repos, dnf.repodict.RepoDict)
del self.base.repos
self.assertEqual(self.base.repos, None)
def test_sack(self):
# Base.sack
self.assertHasAttr(self.base, "sack")
# blank initially
self.assertEqual(self.base.sack, None)
self.base.fill_sack(False, False)
self.assertHasType(self.base.sack, dnf.sack.Sack)
def test_transaction(self):
# Base.transaction
self.assertHasAttr(self.base, "transaction")
# blank initially
self.assertEqual(self.base.transaction, None)
# transaction attribute is set after resolving a transaction
self.base.fill_sack(False, False)
self.base.resolve()
self.assertHasType(self.base.transaction, dnf.db.group.RPMTransaction)
def test_init_plugins(self):
# Base.init_plugins()
self.assertHasAttr(self.base, "init_plugins")
self.base._conf = conf_with_empty_plugins()
self.base.init_plugins()
def test_pre_configure_plugins(self):
# Base.pre_configure_plugins()
self.assertHasAttr(self.base, "pre_configure_plugins")
self.base.pre_configure_plugins()
def test_configure_plugins(self):
# Base.configure_plugins()
self.assertHasAttr(self.base, "configure_plugins")
self.base.configure_plugins()
def test_unload_plugins(self):
# Base.unload_plugins()
self.assertHasAttr(self.base, "unload_plugins")
self.base._conf = conf_with_empty_plugins()
self.base.init_plugins()
self.base.unload_plugins()
def test_update_cache(self):
# Base.update_cache(self, timer=False)
self.assertHasAttr(self.base, "update_cache")
self.base.update_cache(timer=False)
def test_fill_sack(self):
# Base.fill_sack(self, load_system_repo=True, load_available_repos=True):
self.assertHasAttr(self.base, "fill_sack")
self.base.fill_sack(load_system_repo=False, load_available_repos=False)
def test_fill_sack_from_repos_in_cache(self):
# Base.fill_sack_from_repos_in_cache(self, load_system_repo=True):
self.assertHasAttr(self.base, "fill_sack_from_repos_in_cache")
self.base.fill_sack_from_repos_in_cache(load_system_repo=False)
def test_close(self):
# Base.close()
self.assertHasAttr(self.base, "close")
self.base.close()
def test_read_all_repos(self):
# Base.read_all_repos(self, opts=None):
self.assertHasAttr(self.base, "read_all_repos")
self.base.read_all_repos(opts=None)
def test_reset(self):
# Base.reset(self, sack=False, repos=False, goal=False):cloread_all_repos(self, opts=None)
self.assertHasAttr(self.base, "reset")
self.base.reset(sack=False, repos=False, goal=False)
def test_read_comps(self):
# Base.read_comps(self, arch_filter=False)
self.assertHasAttr(self.base, "read_comps")
self.base.read_comps(arch_filter=False)
def test_resolve(self):
# Base.resolve(self, allow_erasing=False)
self.assertHasAttr(self.base, "resolve")
self.base.fill_sack(load_system_repo=False, load_available_repos=False)
self.base.resolve(allow_erasing=False)
def test_do_transaction(self):
# Base.do_transaction(self, display=())
self.assertHasAttr(self.base, "do_transaction")
self.base.fill_sack(load_system_repo=False, load_available_repos=False)
self.base.resolve(allow_erasing=False)
self.base.do_transaction(display=None)
def test_download_packages(self):
# Base.download_packages(self, pkglist, progress=None, callback_total=None)
self.assertHasAttr(self.base, "download_packages")
self.base.download_packages(pkglist=[], progress=None, callback_total=None)
def test_add_remote_rpms(self):
# Base.add_remote_rpms(self, path_list, strict=True, progress=None)
self.assertHasAttr(self.base, "add_remote_rpms")
self.base.fill_sack(load_system_repo=False, load_available_repos=False)
self.base.add_remote_rpms(path_list=[TOUR_4_4], strict=True, progress=None)
def test_package_signature_check(self):
# Base.package_signature_check(self, pkg)
self.assertHasAttr(self.base, "package_signature_check")
self.base.package_signature_check(pkg=self._get_pkg())
def test_package_import_key(self):
# Base.package_import_key(self, pkg, askcb=None, fullaskcb=None)
self.assertHasAttr(self.base, "package_import_key")
self.assertRaises(
ValueError,
self.base.package_import_key,
pkg=self._get_pkg(),
askcb=None,
fullaskcb=None,
)
def test_environment_install(self):
# Base.environment_install(self, env_id, types, exclude=None, strict=True, exclude_groups=None)
self.assertHasAttr(self.base, "environment_install")
self._load_comps()
self.base.environment_install(
env_id="sugar-desktop-environment",
types=["mandatory", "default", "optional"],
exclude=None,
strict=True,
exclude_groups=None
)
def test_environment_remove(self):
# Base.environment_remove(self, env_id):
self.assertHasAttr(self.base, "environment_remove")
self.base.read_comps(arch_filter=False)
self.assertRaises(dnf.exceptions.CompsError, self.base.environment_remove, env_id="base")
def test_environment_upgrade(self):
# Base.environment_upgrade(self, env_id):
self.assertHasAttr(self.base, "environment_upgrade")
self._load_comps()
self.assertRaises(dnf.exceptions.CompsError, self.base.environment_upgrade, env_id="sugar-desktop-environment")
def test_group_install(self):
# Base.group_install(self, grp_id, pkg_types, exclude=None, strict=True)
self.assertHasAttr(self.base, "group_install")
self._load_comps()
self.base.group_install(
grp_id="base",
pkg_types=["mandatory", "default", "optional"],
exclude=None,
strict=True
)
def test_group_remove(self):
# Base.group_remove(self, env_id):
self.assertHasAttr(self.base, "group_remove")
self._load_comps()
self.assertRaises(dnf.exceptions.CompsError, self.base.group_remove, grp_id="base")
def test_group_upgrade(self):
# Base.group_upgrade(self, env_id):
self.assertHasAttr(self.base, "group_upgrade")
self.base.read_comps(arch_filter=False)
self.assertRaises(dnf.exceptions.CompsError, self.base.group_upgrade, grp_id="base")
def test_install_specs(self):
# Base.install_specs(self, install, exclude=None, reponame=None, strict=True, forms=None)
self.base.fill_sack(load_system_repo=False, load_available_repos=False)
self.base.install_specs(install=[], exclude=None, reponame=None, strict=True, forms=None)
def test_install(self):
# Base.install(self, pkg_spec, reponame=None, strict=True, forms=None)
self.base.fill_sack(load_system_repo=False, load_available_repos=False)
self.assertRaises(
dnf.exceptions.PackageNotFoundError,
self.base.install,
pkg_spec="",
reponame=None,
strict=True,
forms=None
)
def test_package_downgrade(self):
# Base.package_downgrade(self, pkg, strict=False)
pkg = self._get_pkg()
self.assertRaises(dnf.exceptions.MarkingError, self.base.package_downgrade, pkg=pkg, strict=False)
def test_package_install(self):
# Base.package_install(self, pkg, strict=False)
pkg = self._get_pkg()
self.base.package_install(pkg=pkg, strict=False)
def test_package_upgrade(self):
# Base.package_upgrade(self, pkg)
pkg = self._get_pkg()
self.assertRaises(dnf.exceptions.MarkingError, self.base.package_upgrade, pkg=pkg)
def test_upgrade(self):
# Base.upgrade(self, pkg_spec, reponame=None)
self.base.fill_sack(load_system_repo=False, load_available_repos=False)
self.assertRaises(dnf.exceptions.MarkingError, self.base.upgrade, pkg_spec="", reponame=None)
def test_upgrade_all(self):
# Base.upgrade_all(self, reponame=None)
self.base.fill_sack(load_system_repo=False, load_available_repos=False)
self.base.upgrade_all(reponame=None)
def test_autoremove(self):
# Base.autoremove(self, forms=None, pkg_specs=None, grp_specs=None, filenames=None)
self.base.fill_sack(load_system_repo=False, load_available_repos=False)
self.base.autoremove(forms=None, pkg_specs=None, grp_specs=None, filenames=None)
def test_remove(self):
# Base.remove(self, pkg_spec, reponame=None, forms=None)
self.base.fill_sack(load_system_repo=False, load_available_repos=False)
self.assertRaises(dnf.exceptions.MarkingError, self.base.remove, pkg_spec="", reponame=None, forms=None)
def test_downgrade(self):
# Base.downgrade(self, pkg_spec)
self.base.fill_sack(load_system_repo=False, load_available_repos=False)
self.assertRaises(dnf.exceptions.MarkingError, self.base.downgrade, pkg_spec="")
def test_urlopen(self):
# Base.urlopen(self, url, repo=None, mode='w+b', **kwargs)
self.base.urlopen(url="file:///dev/null", repo=None, mode='w+b')
def test_setup_loggers(self):
# Base.setup_loggers(self)
self.base.setup_loggers()
| 11,239
|
Python
|
.py
| 240
| 38.375
| 119
| 0.66688
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,869
|
test_dnf_repodict.py
|
rpm-software-management_dnf/tests/api/test_dnf_repodict.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf
import types
from .common import TestCase
class DnfRepodictApiTest(TestCase):
def setUp(self):
self.repodict = dnf.repodict.RepoDict()
def test_init(self):
_ = dnf.repodict.RepoDict()
def test_add(self):
# RepoDict.add
self.assertHasAttr(self.repodict, "add")
self.repodict.add(repo=dnf.repo.Repo())
def test_all(self):
# RepoDict.all
self.assertHasAttr(self.repodict, "all")
self.assertHasType(self.repodict.all(), list)
def test_add_new_repo(self):
# RepoDict.add_new_repo
self.assertHasAttr(self.repodict, "add_new_repo")
self.assertHasType(
self.repodict.add_new_repo(
repoid="r",
conf=dnf.conf.Conf(),
baseurl=(""),
key1="val1",
key2="val2"
), dnf.repo.Repo)
def test_enable_debug_repos(self):
# RepoDict.enable_debug_repos
self.assertHasAttr(self.repodict, "enable_debug_repos")
self.repodict.enable_debug_repos()
def test_enable_source_repos(self):
# RepoDict.enable_source_repos
self.assertHasAttr(self.repodict, "enable_source_repos")
self.repodict.enable_source_repos()
def test_get_matching(self):
# RepoDict.get_matching
self.assertHasAttr(self.repodict, "get_matching")
self.assertHasType(self.repodict.get_matching(key=""), list)
def test_iter_enabled(self):
# RepoDict.iter_enabled
self.assertHasAttr(self.repodict, "iter_enabled")
self.assertHasType(self.repodict.iter_enabled(), types.GeneratorType)
| 1,769
|
Python
|
.py
| 46
| 30.108696
| 77
| 0.640726
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,870
|
test_dnf_cli_commands.py
|
rpm-software-management_dnf/tests/api/test_dnf_cli_commands.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf
import dnf.cli.commands
from .common import TestCase
class DnfCliCommandsApiTest(TestCase):
def setUp(self):
base = dnf.Base(dnf.conf.Conf())
cli = dnf.cli.cli.Cli(base=base)
self.command = dnf.cli.commands.Command(cli=cli)
def test_command(self):
# dnf.cli.commands.Command
self.assertHasAttr(dnf.cli.commands, "Command")
self.assertHasType(dnf.cli.commands.Command, object)
def test_init(self):
base = dnf.Base(dnf.conf.Conf())
cli = dnf.cli.cli.Cli(base=base)
_ = dnf.cli.commands.Command(cli=cli)
def test_aliases(self):
# dnf.cli.commands.Command.aliases
self.assertHasAttr(self.command, "aliases")
self.assertHasType(self.command.aliases, list)
def test_summary(self):
# dnf.cli.commands.Command.summary
self.assertHasAttr(self.command, "summary")
self.assertHasType(self.command.summary, str)
def test_base(self):
# dnf.cli.commands.Command.base
self.assertHasAttr(self.command, "base")
self.assertHasType(self.command.base, dnf.Base)
def test_cli(self):
# dnf.cli.commands.Command.cli
self.assertHasAttr(self.command, "cli")
self.assertHasType(self.command.cli, dnf.cli.cli.Cli)
def test_pre_configure(self):
# dnf.cli.commands.Command.pre_configure
self.assertHasAttr(self.command, "pre_configure")
self.command.pre_configure()
def test_configure(self):
# dnf.cli.commands.Command.configure
self.assertHasAttr(self.command, "configure")
self.command.configure()
def test_run(self):
# dnf.cli.commands.Command.run
self.assertHasAttr(self.command, "run")
self.command.run()
| 1,890
|
Python
|
.py
| 47
| 32.93617
| 61
| 0.673961
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,871
|
common.py
|
rpm-software-management_dnf/tests/api/common.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import os
import unittest
REPOS_DIR = os.path.join(os.path.dirname(__file__), "../repos/")
TOUR_4_4 = os.path.join(REPOS_DIR, "rpm/tour-4-4.noarch.rpm")
COMPS = os.path.join(REPOS_DIR, "main_comps.xml")
class TestCase(unittest.TestCase):
def _get_pkg(self):
self.base.fill_sack(load_system_repo=False, load_available_repos=False)
self.base.add_remote_rpms(path_list=[TOUR_4_4], strict=True, progress=None)
pkg = self.base.sack.query().filter(name="tour")[0]
return pkg
def _load_comps(self):
self.base.read_comps()
self.base.comps._add_from_xml_filename(COMPS)
def assertHasAttr(self, obj, name):
self.assertTrue(hasattr(obj, name))
def assertHasType(self, obj, types):
self.assertTrue(isinstance(obj, types))
| 904
|
Python
|
.py
| 21
| 37.714286
| 83
| 0.682339
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,872
|
test_dnf_module_package.py
|
rpm-software-management_dnf/tests/api/test_dnf_module_package.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import os
import dnf
import libdnf
from .common import TestCase
class DnfModulePackageApiTest(TestCase):
def setUp(self):
self.base = dnf.Base(dnf.conf.Conf())
repo = self.base.repos.add_new_repo(
'api-module-test-repo', self.base.conf,
baseurl=[os.path.join(os.path.dirname(__file__), "../modules/modules/_all/x86_64/")]
)
self.base.fill_sack(load_system_repo=False, load_available_repos=True)
moduleBase = dnf.module.module_base.ModuleBase(self.base)
modulePackages, nsvcap = moduleBase.get_modules('*')
self.modulePackage = modulePackages[0]
def tearDown(self):
self.base.close()
def test_getName(self):
# ModulePackage.getName()
self.assertHasAttr(self.modulePackage, "getName")
self.modulePackage.getName()
def test_getStream(self):
# ModulePackage.getStream()
self.assertHasAttr(self.modulePackage, "getStream")
self.modulePackage.getStream()
def test_getVersion(self):
# ModulePackage.getVersion()
self.assertHasAttr(self.modulePackage, "getVersion")
self.modulePackage.getVersion()
def test_getVersionNum(self):
# ModulePackage.getVersionNum()
self.assertHasAttr(self.modulePackage, "getVersionNum")
self.modulePackage.getVersionNum()
def test_getContext(self):
# ModulePackage.getContext()
self.assertHasAttr(self.modulePackage, "getContext")
self.modulePackage.getContext()
def test_getArch(self):
# ModulePackage.getArch()
self.assertHasAttr(self.modulePackage, "getArch")
self.modulePackage.getArch()
def test_getNameStream(self):
# ModulePackage.getNameStream()
self.assertHasAttr(self.modulePackage, "getNameStream")
self.modulePackage.getNameStream()
def test_getNameStreamVersion(self):
# ModulePackage.getNameStreamVersion()
self.assertHasAttr(self.modulePackage, "getNameStreamVersion")
self.modulePackage.getNameStreamVersion()
def test_getFullIdentifier(self):
# ModulePackage.getFullIdentifier()
self.assertHasAttr(self.modulePackage, "getFullIdentifier")
self.modulePackage.getFullIdentifier()
def test_getProfiles(self):
# ModulePackage.getProfiles()
self.assertHasAttr(self.modulePackage, "getProfiles")
self.modulePackage.getProfiles("test_name_argument")
def test_getSummary(self):
# ModulePackage.getSummary()
self.assertHasAttr(self.modulePackage, "getSummary")
self.modulePackage.getSummary()
def test_getDescription(self):
# ModulePackage.getDescription()
self.assertHasAttr(self.modulePackage, "getDescription")
self.modulePackage.getDescription()
def test_getRepoID(self):
# ModulePackage.getRepoID()
self.assertHasAttr(self.modulePackage, "getRepoID")
self.modulePackage.getRepoID()
def test_getArtifacts(self):
# ModulePackage.getArtifacts()
self.assertHasAttr(self.modulePackage, "getArtifacts")
self.modulePackage.getArtifacts()
def test_getModuleDependencies(self):
# ModulePackage.getModuleDependencies()
self.assertHasAttr(self.modulePackage, "getModuleDependencies")
self.modulePackage.getModuleDependencies()
def test_getYaml(self):
# ModulePackage.getYaml()
self.assertHasAttr(self.modulePackage, "getYaml")
self.modulePackage.getYaml()
class DnfModuleProfileApiTest(TestCase):
def test_moduleProfile_getName(self):
# ModuleProfile.getName()
moduleProfile = libdnf.module.ModuleProfile()
self.assertHasAttr(moduleProfile, "getName")
moduleProfile.getName()
def test_moduleProfile_getDescription(self):
# ModuleProfile.getDescription()
moduleProfile = libdnf.module.ModuleProfile()
self.assertHasAttr(moduleProfile, "getDescription")
moduleProfile.getDescription()
def test_moduleProfile_getContent(self):
# ModuleProfile.getContent()
moduleProfile = libdnf.module.ModuleProfile()
self.assertHasAttr(moduleProfile, "getContent")
moduleProfile.getContent()
class DnfModuleDependenciesApiTest(TestCase):
def test_moduleDependencies_getRequires(self):
# ModuleDependencies.getRequires()
moduleDependecy = libdnf.module.ModuleDependencies()
self.assertHasAttr(moduleDependecy, "getRequires")
moduleDependecy.getRequires()
| 4,680
|
Python
|
.py
| 106
| 36.377358
| 96
| 0.710387
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,873
|
_createrepo_c_modularity_hack.py
|
rpm-software-management_dnf/tests/modules/specs/_createrepo_c_modularity_hack.py
|
#!/usr/bin/python
"""
Createrepo_c doesn't support indexing module metadata.
This script indexes all yaml files found in a target directory,
concatenates them and injects into repodata as "modules" mdtype.
"""
import os
import argparse
import subprocess
import tempfile
import gi
gi.require_version('Modulemd', '2.0')
from gi.repository import Modulemd
def get_parser():
"""
Construct argument parser.
:returns: ArgumentParser object with arguments set up.
:rtype: argparse.ArgumentParser
"""
parser = argparse.ArgumentParser(
description="Scan directory for modulemd yaml files and inject them into repodata.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"path",
metavar="directory_to_index",
)
return parser
def index_modulemd_files(repo_path):
merger = Modulemd.ModuleIndexMerger()
for fn in sorted(os.listdir(repo_path)):
if not fn.endswith(".yaml"):
continue
yaml_path = os.path.join(repo_path, fn)
mmd = Modulemd.ModuleIndex()
mmd.update_from_file(yaml_path, strict=True)
merger.associate_index(mmd, 0)
return merger.resolve()
def modify_repo(repo_path, module_index):
tmp = tempfile.mkdtemp()
path = os.path.join(tmp, "modules.yaml")
with open(path, 'w') as f:
f.write(module_index.dump_to_string())
subprocess.check_call(["modifyrepo_c", "--mdtype=modules", path,
os.path.join(repo_path, "repodata")])
os.unlink(path)
os.rmdir(tmp)
if __name__ == "__main__":
parser = get_parser()
args = parser.parse_args()
module_index = index_modulemd_files(args.path)
modify_repo(args.path, module_index)
| 1,764
|
Python
|
.py
| 52
| 28.519231
| 92
| 0.686541
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,874
|
_create_modulemd.py
|
rpm-software-management_dnf/tests/modules/specs/_create_modulemd.py
|
#!/usr/bin/python
"""
Generate module metadata for modularity tests.
Input:
RPMs built under ../modules/$name-$stream-$version/$arch
profiles defined in $name-$stream-$version/profiles.json
Output:
../modules/$name-$stream-$version/$arch/$name-$stream-$version.$arch.yaml
"""
import os
import json
import gi
gi.require_version('Modulemd', '2.0')
from gi.repository import Modulemd
MODULES_DIR = os.path.join(os.path.dirname(__file__), "..", "modules")
SPECS_DIR = os.path.join(os.path.dirname(__file__), "..", "specs")
def parse_module_id(module_id):
return module_id.rsplit("-", 2)
for module_id in os.listdir(MODULES_DIR):
if module_id.startswith("_"):
continue
name, stream, version = parse_module_id(module_id)
profiles_file = os.path.join(SPECS_DIR, module_id, "profiles.json")
if os.path.isfile(profiles_file):
with open(profiles_file, "r") as f:
profiles = json.load(f)
else:
profiles = {}
for arch in os.listdir(os.path.join(MODULES_DIR, module_id)):
if arch == "noarch":
continue
module_dir = os.path.join(MODULES_DIR, module_id, arch)
rpms = [i for i in os.listdir(module_dir) if i.endswith(".rpm")]
noarch_module_dir = os.path.join(MODULES_DIR, module_id, "noarch")
if os.path.isdir(noarch_module_dir):
noarch_rpms = [i for i in os.listdir(noarch_module_dir) if i.endswith(".rpm")]
else:
noarch_rpms = []
rpms = sorted(set(rpms) | set(noarch_rpms))
# HACK: force epoch to make test data compatible with libmodulemd >= 1.4.0
rpms_with_epoch = []
for i in rpms:
n, v, ra = i.rsplit("-", 2)
nevra = "%s-0:%s-%s" % (n, v, ra)
rpms_with_epoch.append(nevra)
rpms = rpms_with_epoch
module_stream = Modulemd.ModuleStreamV2.new(name, stream)
module_stream.set_version(int(version))
module_stream.add_module_license("LGPLv2")
module_stream.set_summary("Fake module")
module_stream.set_description(module_stream.get_summary())
for rpm in rpms:
module_stream.add_rpm_artifact(rpm[:-4])
for profile_name in profiles:
profile = Modulemd.Profile.new(profile_name)
profile.set_description("Description for profile %s." % profile_name)
for profile_rpm in profiles[profile_name]["rpms"]:
profile.add_rpm(profile_rpm)
module_stream.add_profile(profile)
module_index = Modulemd.ModuleIndex()
module_index.add_module_stream(module_stream)
with open(os.path.join(module_dir, "%s.%s.yaml" % (module_id, arch)), 'w') as f:
f.write(module_index.dump_to_string())
| 2,765
|
Python
|
.py
| 63
| 36.285714
| 90
| 0.634055
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,875
|
test_term.py
|
rpm-software-management_dnf/tests/cli/test_term.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import io
import dnf.cli.term
import tests.support
from tests.support import mock
class TermTest(tests.support.TestCase):
"""Tests of ```dnf.cli.term.Term``` class."""
def test_mode_tty(self):
"""Test whether all modes are properly set if the stream is a tty.
It also ensures that all the values are unicode strings.
"""
tty = mock.create_autospec(io.IOBase)
tty.isatty.return_value = True
def tigetstr(name):
return '<cap_%(name)s>' % locals()
with mock.patch('curses.tigetstr', autospec=True, side_effect=tigetstr):
term = dnf.cli.term.Term(tty)
self.assertEqual(term.MODE,
{u'blink': tigetstr(u'blink'),
u'bold': tigetstr(u'bold'),
u'dim': tigetstr(u'dim'),
u'normal': tigetstr(u'sgr0'),
u'reverse': tigetstr(u'rev'),
u'underline': tigetstr(u'smul')})
def test_mode_tty_incapable(self):
"""Test whether modes correct if the stream is an incapable tty.
It also ensures that all the values are unicode strings.
"""
tty = mock.create_autospec(io.IOBase)
tty.isatty.return_value = True
with mock.patch('curses.tigetstr', autospec=True, return_value=None):
term = dnf.cli.term.Term(tty)
self.assertEqual(term.MODE,
{u'blink': u'',
u'bold': u'',
u'dim': u'',
u'normal': u'',
u'reverse': u'',
u'underline': u''})
def test_mode_nontty(self):
"""Test whether all modes are properly set if the stream is not a tty.
It also ensures that all the values are unicode strings.
"""
nontty = mock.create_autospec(io.IOBase)
nontty.isatty.return_value = False
term = dnf.cli.term.Term(nontty)
self.assertEqual(term.MODE,
{u'blink': u'',
u'bold': u'',
u'dim': u'',
u'normal': u'',
u'reverse': u'',
u'underline': u''})
| 3,382
|
Python
|
.py
| 71
| 36.521127
| 80
| 0.594035
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,876
|
test_output.py
|
rpm-software-management_dnf/tests/cli/test_output.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import libdnf.transaction
import dnf.cli.output
import dnf.const
import dnf.transaction
import tests.support
from tests.support import mock
INFOOUTPUT_OUTPUT = """\
Name : tour
Epoch : 1
Version : 5
Release : 0
Architecture : noarch
Size : 0.0
Source : tour.src.rpm
Repository : None
Summary : A summary of the package.
URL : http://example.com
License : GPL+
Description :
"""
LIST_TRANSACTION_OUTPUT = u"""\
================================================================================
Package Arch Version Repository Size
================================================================================
Upgrading:
pepper x86_64 20-1 updates 0
replacing hole.x86_64 1-1
Transaction Summary
================================================================================
Upgrade 1 Package
"""
class OutputFunctionsTest(tests.support.TestCase):
def test_make_lists(self):
return
goal = mock.Mock(get_reason=lambda x: libdnf.transaction.TransactionItemReason_USER)
ts = dnf.transaction.Transaction()
# ts = dnf.db.history.
ts.add_install('pepper-3', [])
ts.add_install('pepper-2', [])
lists = dnf.cli.output._make_lists(ts, goal)
self.assertEmpty(lists.erased)
self.assertEqual([tsi._active for tsi in lists.installed],
['pepper-2', 'pepper-3'])
def test_spread(self):
fun = dnf.cli.output._spread_in_columns
self.assertEqual(fun(3, "tour", list(range(3))),
[('tour', 0, 1), ('', 2, '')])
self.assertEqual(fun(3, "tour", ()), [('tour', '', '')])
self.assertEqual(fun(5, "tour", list(range(8))),
[('tour', 0, 1, 2, 3), ('', 4, 5, 6, 7)])
class OutputTest(tests.support.DnfBaseTestCase):
REPOS = ['updates']
@staticmethod
def _keyboard_interrupt(*ignored):
raise KeyboardInterrupt
@staticmethod
def _eof_error(*ignored):
raise EOFError
def setUp(self):
super(OutputTest, self).setUp()
self.output = dnf.cli.output.Output(self.base, self.base.conf)
@mock.patch('dnf.cli.term._real_term_width', return_value=80)
def test_col_widths(self, _real_term_width):
rows = (('pep', 'per', 'row',
'', 'lon', 'e'))
self.assertCountEqual(self.output._col_widths(rows), (-38, -37, -1))
@mock.patch('dnf.cli.output._', dnf.pycomp.NullTranslations().ugettext)
@mock.patch('dnf.cli.output.P_', dnf.pycomp.NullTranslations().ungettext)
@mock.patch('dnf.cli.term._real_term_width', return_value=80)
def test_list_transaction(self, _real_term_width):
return
sack = self.base.sack
q = sack.query().filter(name='pepper')
i = q.installed()[0]
u = q.available()[0]
obs = sack.query().filter(name='hole').installed()[0]
transaction = dnf.transaction.Transaction()
transaction.add_upgrade(u, i, [obs])
self.assertEqual(self.output.list_transaction(transaction),
LIST_TRANSACTION_OUTPUT)
@mock.patch('dnf.cli.output._', dnf.pycomp.NullTranslations().ugettext)
@mock.patch('dnf.i18n.ucd_input')
def test_userconfirm(self, input_fnc):
# with defaultyes==False
input_fnc.return_value = 'y'
self.assertTrue(self.output.userconfirm())
self.assertEqual(input_fnc.call_args, mock.call(u'Is this ok [y/N]: '))
input_fnc.return_value = 'n'
self.assertFalse(self.output.userconfirm())
input_fnc.return_value = ''
self.assertFalse(self.output.userconfirm())
input_fnc.side_effect = self._keyboard_interrupt
input_fnc.return_value = 'y'
self.assertFalse(self.output.userconfirm())
input_fnc.side_effect = self._eof_error
self.assertFalse(self.output.userconfirm())
# with defaultyes==True
self.output.conf.defaultyes = True
input_fnc.side_effect = None
input_fnc.return_value = ''
self.assertTrue(self.output.userconfirm())
input_fnc.side_effect = self._keyboard_interrupt
input_fnc.return_value = ''
self.assertFalse(self.output.userconfirm())
input_fnc.side_effect = self._eof_error
self.assertTrue(self.output.userconfirm())
def _to_unicode_mock(str):
return {'y': 'a', 'yes': 'ano', 'n': 'e', 'no': 'ee'}.get(str, str)
@mock.patch('dnf.cli.output._', _to_unicode_mock)
@mock.patch('dnf.i18n.ucd_input')
def test_userconfirm_translated(self, input_fnc):
input_fnc.return_value = 'ee'
self.assertFalse(self.output.userconfirm())
input_fnc.return_value = 'ano'
self.assertTrue(self.output.userconfirm())
class _InputGenerator(object):
INPUT = ['haha', 'dada', 'n']
def __init__(self):
self.called = 0
def __call__(self, msg):
ret = self.INPUT[self.called]
self.called += 1
return ret
def test_userconfirm_bad_input(self):
input_fnc = self._InputGenerator()
with mock.patch('dnf.i18n.ucd_input', input_fnc):
self.assertFalse(self.output.userconfirm())
self.assertEqual(input_fnc.called, 3)
@mock.patch('dnf.cli.output._', dnf.pycomp.NullTranslations().ugettext)
@mock.patch('dnf.cli.term._real_term_width', return_value=80)
def test_infoOutput_with_none_description(self, _real_term_width):
pkg = tests.support.MockPackage('tour-5-0.noarch')
pkg._from_system = False
pkg._size = 0
pkg._pkgid = None
pkg.repoid = None
pkg.e = pkg.epoch = 1
pkg.v = pkg.version
pkg.r = pkg.release
pkg.sourcerpm = 'tour.src.rpm'
pkg.summary = 'A summary of the package.'
pkg.url = 'http://example.com'
pkg.license = 'GPL+'
pkg.description = None
with mock.patch('sys.stdout') as stdout:
print(self.output.infoOutput(pkg))
written = ''.join([mc[1][0] for mc in stdout.method_calls
if mc[0] == 'write'])
self.assertEqual(written, INFOOUTPUT_OUTPUT)
PKGS_IN_GROUPS_OUTPUT = u"""\
Group: Pepper's
Mandatory Packages:
hole
lotus
"""
PKGS_IN_GROUPS_VERBOSE_OUTPUT = u"""\
Group: Pepper's
Group-Id: Peppers
Mandatory Packages:
hole-1-1.x86_64 @System
lotus-3-16.i686 main
"""
GROUPS_IN_ENVIRONMENT_OUTPUT = """\
Environment Group: Sugar Desktop Environment
Description: A software playground for learning about learning.
Mandatory Groups:
Pepper's
Solid Ground
Optional Groups:
Base
"""
class GroupOutputTest(tests.support.DnfBaseTestCase):
REPOS = ['main']
COMPS = True
def setUp(self):
super(GroupOutputTest, self).setUp()
self.output = dnf.cli.output.Output(self.base, self.base.conf)
@mock.patch('dnf.cli.output._', dnf.pycomp.NullTranslations().ugettext)
@mock.patch('dnf.cli.term._real_term_width', return_value=80)
def test_group_info(self, _real_term_width):
group = self.base.comps.group_by_pattern('Peppers')
with tests.support.patch_std_streams() as (stdout, stderr):
self.output.display_pkgs_in_groups(group)
self.assertEqual(stdout.getvalue(), PKGS_IN_GROUPS_OUTPUT)
@mock.patch('dnf.cli.output._', dnf.pycomp.NullTranslations().ugettext)
@mock.patch('dnf.cli.term._real_term_width', return_value=80)
def test_group_verbose_info(self, _real_term_width):
group = self.base.comps.group_by_pattern('Peppers')
self.base.set_debuglevel(dnf.const.VERBOSE_LEVEL)
with tests.support.patch_std_streams() as (stdout, stderr):
self.output.display_pkgs_in_groups(group)
self.assertEqual(stdout.getvalue(), PKGS_IN_GROUPS_VERBOSE_OUTPUT)
@mock.patch('dnf.cli.output._', dnf.pycomp.NullTranslations().ugettext)
@mock.patch('dnf.cli.term._real_term_width', return_value=80)
def test_environment_info(self, _real_term_width):
env = self.base.comps.environments[0]
with tests.support.patch_std_streams() as (stdout, stderr):
self.output.display_groups_in_environment(env)
self.assertEqual(stdout.getvalue(), GROUPS_IN_ENVIRONMENT_OUTPUT)
| 9,605
|
Python
|
.py
| 218
| 37.527523
| 92
| 0.62508
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,877
|
__init__.py
|
rpm-software-management_dnf/tests/cli/__init__.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
| 984
|
Python
|
.py
| 17
| 56.823529
| 77
| 0.777433
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,878
|
test_demand.py
|
rpm-software-management_dnf/tests/cli/test_demand.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf.cli.demand
import tests.support
class DemandTest(tests.support.TestCase):
def test_bool_default(self):
demands = dnf.cli.demand.DemandSheet()
demands.resolving = True
self.assertTrue(demands.resolving)
demands.resolving = True
self.assertTrue(demands.resolving)
with self.assertRaises(AttributeError):
demands.resolving = False
def test_default(self):
demands = dnf.cli.demand.DemandSheet()
self.assertFalse(demands.resolving)
self.assertFalse(demands.sack_activation)
self.assertFalse(demands.root_user)
self.assertEqual(demands.success_exit_status, 0)
def test_independence(self):
d1 = dnf.cli.demand.DemandSheet()
d1.resolving = True
d2 = dnf.cli.demand.DemandSheet()
self.assertTrue(d1.resolving)
self.assertFalse(d2.resolving)
| 1,966
|
Python
|
.py
| 42
| 41.97619
| 77
| 0.738381
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,879
|
test_aliases.py
|
rpm-software-management_dnf/tests/cli/test_aliases.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf.cli.aliases
import os
import tests.support
CONF = tests.support.resource_path('etc/aliases.d/aliases.conf')
class AliasesTest(tests.support.TestCase):
def setUp(self):
# Set DNF_ALIASES_DISABLED so that no default config is loaded
self.env_var_set = False
if 'DNF_ALIASES_DISABLED' not in os.environ:
os.environ['DNF_ALIASES_DISABLED'] = '1'
self.env_var_set = True
self.aliases_base = dnf.cli.aliases.Aliases()
self.aliases_base._load_aliases([CONF])
def tearDown(self):
if self.env_var_set:
del os.environ['DNF_ALIASES_DISABLED']
def test_undefined(self):
args = ['undefined', 'undefined2']
expected_args = list(args)
args = self.aliases_base._resolve(args)
self.assertEqual(args, expected_args)
def test_simple(self):
args = ['h']
expected_args = ['history']
args = self.aliases_base._resolve(args)
self.assertEqual(args, expected_args)
def test_command_changed(self):
args = ['cu']
expected_args = ['check-update']
args = self.aliases_base._resolve(args)
self.assertEqual(args, expected_args)
def test_package_unchanged(self):
args = ['install', 'cu']
expected_args = ['install', 'cu']
args = self.aliases_base._resolve(args)
self.assertEqual(args, expected_args)
def test_recursive(self):
args = ['lsi']
expected_args = ['list', 'installed']
args = self.aliases_base._resolve(args)
self.assertEqual(args, expected_args)
def test_options(self):
args = ['FORCE']
expected_args = ['--skip-broken', '--disableexcludes=all']
args = self.aliases_base._resolve(args)
self.assertEqual(args, expected_args)
def test_options_recursive(self):
args = ['force-inst']
expected_args = ['--skip-broken', '--disableexcludes=all', 'install']
args = self.aliases_base._resolve(args)
self.assertEqual(args, expected_args)
| 3,141
|
Python
|
.py
| 70
| 38.714286
| 77
| 0.680747
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,880
|
test_option_parser.py
|
rpm-software-management_dnf/tests/cli/test_option_parser.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import argparse
from dnf.cli.option_parser import OptionParser
import dnf.cli.commands
import dnf.pycomp
import dnf.util
import tests.support
from tests.support import mock
def _parse(command, args):
parser = OptionParser()
opts = parser.parse_main_args(args)
opts = parser.parse_command_args(command, args)
return parser, opts
class OptionParserTest(tests.support.TestCase):
def setUp(self):
self.cli = mock.Mock()
self.command = MyTestCommand(self.cli)
def test_parse(self):
parser, opts = _parse(self.command, ['update', '--nogpgcheck'])
self.assertEqual(opts.command, 'update')
self.assertFalse(opts.gpgcheck)
self.assertIsNone(opts.color)
class MyTestCommand(dnf.cli.commands.Command):
aliases = ["test-cmd"]
summary = 'summary'
def __init__(self, cli):
dnf.cli.commands.Command.__init__(self, cli)
class MyTestCommand2(dnf.cli.commands.Command):
aliases = ["test-cmd2"]
summary = 'summary2'
def __init__(self, cli):
dnf.cli.commands.Command.__init__(self, cli)
class OptionParserAddCmdTest(tests.support.TestCase):
def setUp(self):
self.cli_commands = {}
self.parser = OptionParser()
self.parser._ = dnf.pycomp.NullTranslations().ugettext
self.cli = mock.Mock()
def _register_command(self, command_cls):
""" helper for simulate dnf.cli.cli.Cli.register_Command()"""
for name in command_cls.aliases:
self.cli_commands[name] = command_cls
def test_add_commands(self):
cmd = MyTestCommand(self.cli)
self._register_command(cmd)
self.parser.add_commands(self.cli_commands, "main")
name = cmd.aliases[0]
self.assertTrue(name in self.parser._cmd_usage)
group, summary = self.parser._cmd_usage[name]
self.assertEqual(group, 'main')
self.assertEqual(summary, cmd.summary)
self.assertEqual(self.parser._cmd_groups, set(['main']))
def test_add_commands_only_once(self):
cmd = MyTestCommand(self.cli)
self._register_command(cmd)
self.parser.add_commands(self.cli_commands, "main")
cmd = MyTestCommand(self.cli)
self._register_command(cmd)
self.parser.add_commands(self.cli_commands, "plugin")
self.assertEqual(len(self.parser._cmd_usage.keys()), 1)
self.assertEqual(self.parser._cmd_groups, set(['main']))
def test_cmd_groups(self):
cmd = MyTestCommand(self.cli)
self._register_command(cmd)
self.parser.add_commands(self.cli_commands, "main")
cmd = MyTestCommand2(self.cli)
self._register_command(cmd)
self.parser.add_commands(self.cli_commands, "plugin")
self.assertEqual(len(self.parser._cmd_groups), 2)
self.assertEqual(self.parser._cmd_groups, set(['main', 'plugin']))
def test_help_option_set(self):
opts = self.parser.parse_main_args(['-h'])
self.assertTrue(opts.help)
def test_help_option_notset(self):
opts = self.parser.parse_main_args(['foo', 'bar'])
self.assertFalse(opts.help)
def test_get_usage(self):
parser = argparse.ArgumentParser()
output = [
u'%s [options] COMMAND' % (parser.prog if parser.prog in ["dnf", "yum"] else "dnf"),
u'',
u'List of Main Commands:',
u'',
u'test-cmd summary',
u'',
u'List of Plugin Commands:',
u'',
u'test-cmd2 summary2',
u'']
cmd = MyTestCommand(self.cli)
self._register_command(cmd)
self.parser.add_commands(self.cli_commands, "main")
cmd2 = MyTestCommand2(self.cli)
self._register_command(cmd2)
self.parser.add_commands(self.cli_commands, "plugin")
self.assertEqual(len(self.parser._cmd_usage.keys()), 2)
usage = self.parser.get_usage().split('\n')
self.assertEqual(usage, output)
| 5,090
|
Python
|
.py
| 116
| 37.077586
| 96
| 0.666127
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,881
|
test_clean.py
|
rpm-software-management_dnf/tests/cli/commands/test_clean.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import os
from io import StringIO
import dnf.cli.cli
import tests.support
from tests.support import mock
'''
def _run(cli, args):
with mock.patch('sys.stdout', new_callable=StringIO), \
mock.patch('dnf.rpm.detect_releasever', return_value=69):
cli.configure(['clean', '--config', '/dev/null'] + args)
cli.run()
class CleanTest(tests.support.TestCase):
def setUp(self):
conf = dnf.conf.Conf()
base = tests.support.Base(conf)
base.repos.add(tests.support.MockRepo('main', conf))
base.conf.reposdir = '/dev/null'
base.conf.plugins = False
base.output = tests.support.MockOutput()
repo = base.repos['main']
repo.baseurl = ['http:///dnf-test']
repo.basecachedir = base.conf.cachedir
walk = [
(
repo.basecachedir,
[os.path.basename(repo._cachedir)],
[repo.id + '.solv'],
),
(repo._cachedir, ['repodata', 'packages'], ['metalink.xml']),
(repo._cachedir + '/repodata', [], ['foo.xml', 'bar.xml.bz2']),
(repo._cachedir + '/packages', [], ['foo.rpm']),
]
os.walk = self.walk = mock.Mock(return_value=walk)
self.base = base
self.cli = dnf.cli.cli.Cli(base)
def tearDown(self):
self.base.close()
def test_run(self):
with mock.patch('dnf.cli.commands.clean._clean') as _clean:
for args in [['all'],
['metadata'],
['metadata', 'packages'],
['metadata', 'packages', 'expire-cache'],
['dbcache'],
['expire-cache']]:
_run(self.cli, args)
calls = [call[0] for call in _clean.call_args_list]
counts = (5, 4, 5, 5, 1, 0)
for call, count in zip(calls, counts):
files = list(call[1])
assert len(files) == count
def test_walk_once(self):
_run(self.cli, ['all'])
assert len(self.walk.call_args_list) == 1
def test_clean_local_repo(self):
cachedir = self.base.conf.cachedir
repo = self.base.repos['main']
repo.baseurl = ['file:///localrepo']
_run(self.cli, ['all'])
# Make sure we never looked outside the base cachedir
dirs = [call[0][0] for call in self.walk.call_args_list]
assert all(d == cachedir for d in dirs)
'''
| 3,536
|
Python
|
.py
| 82
| 35.073171
| 77
| 0.613617
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,882
|
test_repolist.py
|
rpm-software-management_dnf/tests/cli/commands/test_repolist.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
import dnf.cli.commands.repolist as repolist
import dnf.repo
import tests.support
class TestRepolist(tests.support.TestCase):
@tests.support.mock.patch('dnf.cli.commands.repolist._',
dnf.pycomp.NullTranslations().ugettext)
def test_expire_str(self):
repo = dnf.repo.Repo('rollup', tests.support.FakeConf())
expire = repolist._expire_str(repo, None)
self.assertEqual(expire, '172800 second(s) (last: unknown)')
| 1,501
|
Python
|
.py
| 28
| 50.142857
| 77
| 0.750341
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,883
|
test_search.py
|
rpm-software-management_dnf/tests/cli/commands/test_search.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
import dnf.cli.commands.search as search
import dnf.match_counter
import dnf.pycomp
import tests.support
from tests import mock
class SearchCountedTest(tests.support.DnfBaseTestCase):
REPOS = ["main"]
CLI = "mock"
def setUp(self):
super(SearchCountedTest, self).setUp()
self.cmd = search.SearchCommand(self.cli)
def test_search_counted(self):
counter = dnf.match_counter.MatchCounter()
self.cmd._search_counted(counter, 'summary', 'ation')
self.assertEqual(len(counter), 2)
haystacks = set()
for pkg in counter:
haystacks.update(counter.matched_haystacks(pkg))
self.assertCountEqual(haystacks, ["It's an invitation.",
"Make a reservation."])
def test_search_counted_glob(self):
counter = dnf.match_counter.MatchCounter()
self.cmd._search_counted(counter, 'summary', '*invit*')
self.assertEqual(len(counter), 1)
class SearchTest(tests.support.DnfBaseTestCase):
REPOS = ["search"]
CLI = "mock"
def setUp(self):
super(SearchTest, self).setUp()
self.base.output = mock.MagicMock()
self.base.output.fmtSection = lambda str: str
self.cmd = search.SearchCommand(self.cli)
def patched_search(self, *args):
with tests.support.patch_std_streams() as (stdout, _):
tests.support.command_run(self.cmd, *args)
call_args = self.base.output.matchcallback.call_args_list
pkgs = [c[0][0] for c in call_args]
return (stdout.getvalue(), pkgs)
def test_search(self):
(_, pkgs) = self.patched_search(['lotus'])
pkg_names = list(map(str, pkgs))
self.assertIn('lotus-3-16.i686', pkg_names)
self.assertIn('lotus-3-16.x86_64', pkg_names)
@mock.patch('dnf.cli.commands.search._',
dnf.pycomp.NullTranslations().ugettext)
def test_search_caseness(self):
(stdout, pkgs) = self.patched_search(['LOTUS'])
self.assertEqual(stdout, 'Name Matched: LOTUS\n')
pkg_names = map(str, pkgs)
self.assertIn('lotus-3-16.i686', pkg_names)
self.assertIn('lotus-3-16.x86_64', pkg_names)
| 3,245
|
Python
|
.py
| 69
| 40.478261
| 77
| 0.682811
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,884
|
test_makecache.py
|
rpm-software-management_dnf/tests/cli/commands/test_makecache.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
import dnf.cli.commands.makecache as makecache
import dnf.pycomp
import tests.support
from tests.support import mock
class MakeCacheCommandTest(tests.support.DnfBaseTestCase):
REPOS = ['main']
CLI = "mock"
def setUp(self):
super(MakeCacheCommandTest, self).setUp()
for r in self.base.repos.values():
r.basecachedir = self.base.conf.cachedir
@staticmethod
@mock.patch('dnf.Base.fill_sack', new=mock.MagicMock())
def _do_makecache(cmd):
return tests.support.command_run(cmd, ['timer'])
def assert_last_info(self, logger, msg):
self.assertEqual(logger.info.mock_calls[-1], mock.call(msg))
@mock.patch('dnf.base.logger',
new_callable=tests.support.mock_logger)
@mock.patch('dnf.cli.commands._', dnf.pycomp.NullTranslations().ugettext)
@mock.patch('dnf.util.on_ac_power', return_value=True)
@mock.patch('dnf.util.on_metered_connection', return_value=False)
def test_makecache_timer(self, _on_ac_power, _on_metered_connection, logger):
cmd = makecache.MakeCacheCommand(self.cli)
self.base.conf.metadata_timer_sync = 0
self.assertFalse(self._do_makecache(cmd))
self.assert_last_info(logger, u'Metadata timer caching disabled.')
self.base.conf.metadata_timer_sync = 5 # resync after 5 seconds
self.base._repo_persistor.since_last_makecache = mock.Mock(return_value=3)
self.assertFalse(self._do_makecache(cmd))
self.assert_last_info(logger, u'Metadata cache refreshed recently.')
@mock.patch('dnf.base.logger',
new_callable=tests.support.mock_logger)
@mock.patch('dnf.cli.commands._', dnf.pycomp.NullTranslations().ugettext)
@mock.patch('dnf.util.on_ac_power', return_value=False)
@mock.patch('dnf.util.on_metered_connection', return_value=False)
def test_makecache_timer_battery(self, _on_ac_power, _on_metered_connection, logger):
cmd = makecache.MakeCacheCommand(self.cli)
self.base.conf.metadata_timer_sync = 5
self.assertFalse(self._do_makecache(cmd))
msg = u'Metadata timer caching disabled when running on a battery.'
self.assert_last_info(logger, msg)
@mock.patch('dnf.cli.commands._', dnf.pycomp.NullTranslations().ugettext)
@mock.patch('dnf.util.on_ac_power', return_value=None)
@mock.patch('dnf.util.on_metered_connection', return_value=False)
def test_makecache_timer_battery2(self, _on_ac_power, _on_metered_connection):
cmd = makecache.MakeCacheCommand(self.cli)
self.base.conf.metadata_timer_sync = 5
self.assertTrue(self._do_makecache(cmd))
@mock.patch('dnf.base.logger',
new_callable=tests.support.mock_logger)
@mock.patch('dnf.cli.commands._', dnf.pycomp.NullTranslations().ugettext)
@mock.patch('dnf.util.on_ac_power', return_value=False)
@mock.patch('dnf.util.on_metered_connection', return_value=True)
def test_makecache_timer_metered(self, _on_ac_power, _on_metered_connection, logger):
cmd = makecache.MakeCacheCommand(self.cli)
self.base.conf.metadata_timer_sync = 5
self.assertFalse(self._do_makecache(cmd))
msg = u'Metadata timer caching disabled when running on metered connection.'
self.assert_last_info(logger, msg)
| 4,341
|
Python
|
.py
| 78
| 49.75641
| 89
| 0.718021
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,885
|
test_autoremove.py
|
rpm-software-management_dnf/tests/cli/commands/test_autoremove.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
import libdnf.transaction
import dnf.cli.commands.autoremove as autoremove
from dnf.cli.option_parser import OptionParser
import tests.support
class AutoRemoveCommandTest(tests.support.ResultTestCase):
REPOS = []
CLI = "mock"
def test_run(self):
q = self.base.sack.query()
pkgs = list(q.filter(name='librita')) + list(q.filter(name='pepper'))
self._swdb_begin()
for pkg in pkgs:
self.base.history.set_reason(pkg, libdnf.transaction.TransactionItemReason_USER)
self._swdb_end()
cmd = autoremove.AutoremoveCommand(self.cli)
parser = OptionParser()
parser.parse_main_args(['autoremove', '-y'])
parser.parse_command_args(cmd, ['autoremove', '-y'])
cmd.run()
inst, rem = self.installed_removed(self.base)
self.assertEmpty(inst)
removed = ('librita-1-1.i686',
'librita-1-1.x86_64',
'pepper-20-0.x86_64')
self.assertCountEqual((map(str, pkgs)), removed)
| 2,054
|
Python
|
.py
| 43
| 42.465116
| 92
| 0.709
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,886
|
test_mark.py
|
rpm-software-management_dnf/tests/cli/commands/test_mark.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf
import logging
import tests.support
from tests.support import mock
class MarkCommandTest(tests.support.DnfBaseTestCase):
"""Tests of ``dnf.cli.commands.MarkCommand`` class."""
REPOS = ["main"]
CLI = "mock"
def setUp(self):
super(MarkCommandTest, self).setUp()
self.cmd = dnf.cli.commands.mark.MarkCommand(self.cli)
@mock.patch('dnf.cli.commands.mark._',
dnf.pycomp.NullTranslations().ugettext)
def test_run_notfound(self):
"""Test whether it fails if the package cannot be found."""
stdout = dnf.pycomp.StringIO()
tests.support.command_configure(self.cmd, ['install', 'non-existent'])
with tests.support.wiretap_logs('dnf', logging.INFO, stdout):
with self.assertRaises(dnf.cli.CliError):
self.cmd.run()
self.assertEqual(stdout.getvalue(),
'Error:\nPackage non-existent is not installed.\n')
@mock.patch('dnf.cli.commands.mark._',
dnf.pycomp.NullTranslations().ugettext)
def test_run(self):
"""Test whether it fails if the package cannot be found."""
stdout = dnf.pycomp.StringIO()
with tests.support.wiretap_logs('dnf', logging.INFO, stdout):
tests.support.command_run(self.cmd, ['install', 'pepper-20-0.x86_64'])
self.assertEqual(stdout.getvalue(),
'pepper-20-0.x86_64 marked as user installed.\npepper-20-0.x86_64 marked as user installed.\n')
| 2,575
|
Python
|
.py
| 50
| 45.4
| 120
| 0.700637
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,887
|
test_updateinfo.py
|
rpm-software-management_dnf/tests/cli/commands/test_updateinfo.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import datetime
import itertools
import shutil
import tempfile
import hawkey
import dnf.pycomp
import dnf.cli.commands.updateinfo
import tests.support
from tests.support import mock
class UpdateInfoCommandTest(tests.support.DnfBaseTestCase):
"""Test case validating updateinfo commands."""
REPOS = []
CLI = "mock"
def setUp(self):
"""Prepare the test fixture."""
super(UpdateInfoCommandTest, self).setUp()
cachedir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, cachedir)
self.cli.base.conf.cachedir = cachedir
self.cli.base.add_test_dir_repo('rpm', self.cli.base.conf)
self._stdout = dnf.pycomp.StringIO()
self.addCleanup(mock.patch.stopall)
mock.patch(
'dnf.cli.commands.updateinfo._',
dnf.pycomp.NullTranslations().ugettext).start()
mock.patch(
'dnf.cli.commands.updateinfo.print',
self._stub_print, create=True).start()
def _stub_print(self, *objects):
"""Pretend to print to standard output."""
print(*objects, file=self._stdout)
def test_avail_filter_pkgs(self):
"""Test querying with a packages filter."""
cmd = dnf.cli.commands.updateinfo.UpdateInfoCommand(self.cli)
tests.support.command_configure(cmd, [])
apkg_adv_insts = cmd.available_apkg_adv_insts(['to*r', 'nxst'])
self.assertCountEqual(
((apk.filename, adv.id, ins) for apk, adv, ins in apkg_adv_insts),
[('tour-5-1.noarch.rpm', 'DNF-2014-3', False)],
'incorrect pairs')
def test_avail_filter_pkgs_nonex(self):
"""Test querying with a non-existent packages filter."""
cmd = dnf.cli.commands.updateinfo.UpdateInfoCommand(self.cli)
tests.support.command_configure(cmd, ['non-existent'])
apkg_adv_insts = cmd.available_apkg_adv_insts(cmd.opts.spec)
self.assertCountEqual(
((apk.filename, adv.id, ins) for apk, adv, ins in apkg_adv_insts),
[], 'incorrect pairs')
def test_avail_filter_security(self):
"""Test querying with a security filter."""
cmd = dnf.cli.commands.updateinfo.UpdateInfoCommand(self.cli)
tests.support.command_configure(cmd, [])
apkg_adv_insts = cmd.available_apkg_adv_insts(['security'])
self.assertCountEqual(
((apk.filename, adv.id, ins) for apk, adv, ins in apkg_adv_insts),
[('tour-5-1.noarch.rpm', 'DNF-2014-3', False)],
'incorrect pairs')
def test_inst(self):
"""Test installed triplets querying."""
cmd = dnf.cli.commands.updateinfo.UpdateInfoCommand(self.cli)
tests.support.command_configure(cmd, [])
apkg_adv_insts = cmd.installed_apkg_adv_insts([])
self.assertCountEqual(
((apk.filename, adv.id, ins) for apk, adv, ins in apkg_adv_insts),
[('tour-4-4.noarch.rpm', 'DNF-2014-1', True),
('tour-5-0.noarch.rpm', 'DNF-2014-2', True)],
'incorrect pairs')
def test_inst_filter_bugfix(self):
"""Test querying with a bugfix filter."""
cmd = dnf.cli.commands.updateinfo.UpdateInfoCommand(self.cli)
tests.support.command_configure(cmd, ['bugfix'])
apkg_adv_insts = cmd.installed_apkg_adv_insts(cmd.opts.spec)
self.assertCountEqual(
((apk.filename, adv.id, ins) for apk, adv, ins in apkg_adv_insts),
[('tour-4-4.noarch.rpm', 'DNF-2014-1', True)],
'incorrect pairs')
def test_inst_filter_enhancement(self):
"""Test querying with an enhancement filter."""
cmd = dnf.cli.commands.updateinfo.UpdateInfoCommand(self.cli)
tests.support.command_configure(cmd, ['enhancement'])
apkg_adv_insts = cmd.installed_apkg_adv_insts(cmd.opts.spec)
self.assertCountEqual(
((apk.filename, adv.id, ins) for apk, adv, ins in apkg_adv_insts),
[('tour-5-0.noarch.rpm', 'DNF-2014-2', True)],
'incorrect pairs')
def test_upd(self):
"""Test updating triplets querying."""
cmd = dnf.cli.commands.updateinfo.UpdateInfoCommand(self.cli)
tests.support.command_configure(cmd, [])
apkg_adv_insts = cmd.updating_apkg_adv_insts([])
self.assertCountEqual(
((apk.filename, adv.id, ins) for apk, adv, ins in apkg_adv_insts),
[('tour-5-1.noarch.rpm', 'DNF-2014-3', False)],
'incorrect pairs')
def test_all(self):
"""Test all triplets querying."""
cmd = dnf.cli.commands.updateinfo.UpdateInfoCommand(self.cli)
tests.support.command_configure(cmd, [])
apkg_adv_insts = cmd.all_apkg_adv_insts([])
self.assertCountEqual(
((apk.filename, adv.id, ins) for apk, adv, ins in apkg_adv_insts),
[('tour-4-4.noarch.rpm', 'DNF-2014-1', True),
('tour-5-0.noarch.rpm', 'DNF-2014-2', True),
('tour-5-1.noarch.rpm', 'DNF-2014-3', False)])
def test_all_filter_advisories(self):
"""Test querying with an advisories filter."""
cmd = dnf.cli.commands.updateinfo.UpdateInfoCommand(self.cli)
tests.support.command_configure(cmd, ['DNF-201*-[13]', 'NO-0000-0'])
apkg_adv_insts = cmd.all_apkg_adv_insts(cmd.opts.spec)
self.assertCountEqual(
((apk.filename, adv.id, ins) for apk, adv, ins in apkg_adv_insts),
[('tour-4-4.noarch.rpm', 'DNF-2014-1', True),
('tour-5-1.noarch.rpm', 'DNF-2014-3', False)],
'incorrect pairs')
def test_display_list_mixed(self):
"""Test list displaying with mixed installs."""
apkg_adv_insts = itertools.chain(
((apkg, adv, False)
for pkg in self.cli.base.sack.query().installed()
for adv in pkg.get_advisories(hawkey.GT)
for apkg in adv.packages),
((apkg, adv, True)
for pkg in self.cli.base.sack.query().installed()
for adv in pkg.get_advisories(hawkey.LT | hawkey.EQ)
for apkg in adv.packages))
cmd = dnf.cli.commands.updateinfo.UpdateInfoCommand(self.cli)
tests.support.command_configure(cmd, ['--all'])
cmd.display_list(apkg_adv_insts)
self.assertEqual(
self._stdout.getvalue(),
'i DNF-2014-1 bugfix tour-4-4.noarch\n'
'i DNF-2014-2 enhancement tour-5-0.noarch\n'
' DNF-2014-3 Unknown/Sec. tour-5-1.noarch\n',
'incorrect output'
)
def test_display_info_verbose(self):
"""Test verbose displaying."""
apkg_adv_insts = (
(apkg, adv, False) for pkg in self.cli.base.sack.query().installed()
for adv in pkg.get_advisories(hawkey.GT)
for apkg in adv.packages
)
self.cli.base.set_debuglevel(dnf.const.VERBOSE_LEVEL)
cmd = dnf.cli.commands.updateinfo.UpdateInfoCommand(self.cli)
tests.support.command_configure(cmd, [])
cmd.display_info(apkg_adv_insts)
updated = datetime.datetime.fromtimestamp(1404841143)
self.assertEqual(self._stdout.getvalue(),
'========================================'
'=======================================\n'
' tour-5-1\n'
'========================================'
'=======================================\n'
' Update ID: DNF-2014-3\n'
' Type: security\n'
' Updated: ' + str(updated) + '\n'
'Description: testing advisory\n'
' Files: tour-5-1.noarch.rpm\n',
'incorrect output')
def test_display_info_verbose_mixed(self):
"""Test verbose displaying with mixed installs."""
apkg_adv_insts = itertools.chain(
((apkg, adv, False)
for pkg in self.cli.base.sack.query().installed()
for adv in pkg.get_advisories(hawkey.GT)
for apkg in adv.packages),
((apkg, adv, True)
for pkg in self.cli.base.sack.query().installed()
for adv in pkg.get_advisories(hawkey.LT | hawkey.EQ)
for apkg in adv.packages))
self.cli.base.set_debuglevel(dnf.const.VERBOSE_LEVEL)
cmd = dnf.cli.commands.updateinfo.UpdateInfoCommand(self.cli)
tests.support.command_configure(cmd, ['--all'])
cmd.display_info(apkg_adv_insts)
updated1 = datetime.datetime.fromtimestamp(1404840841)
updated2 = datetime.datetime.fromtimestamp(1404841082)
updated3 = datetime.datetime.fromtimestamp(1404841143)
self.assertEqual(self._stdout.getvalue(),
'========================================'
'=======================================\n'
' tour-4-4\n'
'========================================'
'=======================================\n'
' Update ID: DNF-2014-1\n'
' Type: bugfix\n'
' Updated: ' + str(updated1) + '\n'
'Description: testing advisory\n'
' Files: tour-4-4.noarch.rpm\n'
' Installed: true\n'
'\n'
'========================================'
'=======================================\n'
' tour-5-0\n'
'========================================'
'=======================================\n'
' Update ID: DNF-2014-2\n'
' Type: enhancement\n'
' Updated: ' + str(updated2) + '\n'
'Description: testing advisory\n'
' Files: tour-5-0.noarch.rpm\n'
' Installed: true\n'
'\n'
'========================================'
'=======================================\n'
' tour-5-1\n'
'========================================'
'=======================================\n'
' Update ID: DNF-2014-3\n'
' Type: security\n'
' Updated: ' + str(updated3) + '\n'
'Description: testing advisory\n'
' Files: tour-5-1.noarch.rpm\n'
' Installed: false\n',
'incorrect output')
# This test also tests the display_summary and available_apkg_adv_insts
# methods.
def test_run_available(self):
"""Test running with available advisories."""
cmd = dnf.cli.commands.updateinfo.UpdateInfoCommand(self.cli)
tests.support.command_run(cmd, [])
self.assertEqual(self._stdout.getvalue(),
'Updates Information Summary: available\n'
' 1 Security notice(s)\n'
' 1 Unknown Security notice(s)\n',
'incorrect output')
# This test also tests the display_list and available_apkg_adv_insts
# methods.
def test_run_list(self):
"""Test running the list sub-command."""
cmd = dnf.cli.commands.updateinfo.UpdateInfoCommand(self.cli)
tests.support.command_run(cmd, ['list'])
self.assertEqual(self._stdout.getvalue(),
'DNF-2014-3 Unknown/Sec. tour-5-1.noarch\n',
'incorrect output')
# This test also tests the display_info and available_apkg_adv_insts
# methods.
def test_run_info(self):
"""Test running the info sub-command."""
self.cli.base.set_debuglevel(2)
cmd = dnf.cli.commands.updateinfo.UpdateInfoCommand(self.cli)
tests.support.command_run(cmd, ['info'])
updated = datetime.datetime.fromtimestamp(1404841143)
self.assertEqual(self._stdout.getvalue(),
'========================================'
'=======================================\n'
' tour-5-1\n'
'========================================'
'=======================================\n'
' Update ID: DNF-2014-3\n'
' Type: security\n'
' Updated: ' + str(updated) + '\n'
'Description: testing advisory\n',
'incorrect output')
| 14,036
|
Python
|
.py
| 273
| 38.758242
| 80
| 0.531814
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,888
|
__init__.py
|
rpm-software-management_dnf/tests/cli/commands/__init__.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
| 984
|
Python
|
.py
| 17
| 56.823529
| 77
| 0.777433
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,889
|
test_remove.py
|
rpm-software-management_dnf/tests/cli/commands/test_remove.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import logging
import dnf.cli.commands.remove
from dnf.cli.option_parser import OptionParser
import tests.support
from tests.support import mock
class RemoveCommandTest(tests.support.ResultTestCase):
"""Tests of ``dnf.cli.commands.EraseCommand`` class."""
REPOS = []
BASE_CLI = True
CLI = "mock"
def setUp(self):
super(RemoveCommandTest, self).setUp()
self.cmd = dnf.cli.commands.remove.RemoveCommand(self.base.mock_cli())
def test_configure(self):
parser = OptionParser()
parser.parse_main_args(['autoremove', '-y'])
parser.parse_command_args(self.cmd, ['autoremove', '-y'])
self.cmd.configure()
self.assertTrue(self.cmd.cli.demands.allow_erasing)
@mock.patch('dnf.cli.commands.remove._',
dnf.pycomp.NullTranslations().ugettext)
def test_run_notfound(self):
"""Test whether it fails if the package cannot be found."""
stdout = dnf.pycomp.StringIO()
with tests.support.wiretap_logs('dnf', logging.INFO, stdout):
tests.support.command_run(self.cmd, ['non-existent'])
self.assertEqual(stdout.getvalue(),
'No match for argument: non-existent\nNo packages marked for removal.\n')
self.assertResult(self.cmd.base, self.cmd.base.sack.query().installed())
| 2,404
|
Python
|
.py
| 48
| 45.0625
| 98
| 0.720137
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,890
|
test_group.py
|
rpm-software-management_dnf/tests/cli/commands/test_group.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
import dnf.cli.commands.group as group
import dnf.comps
import dnf.exceptions
from dnf.comps import CompsQuery
from dnf.cli.option_parser import OptionParser
import tests.support
class GroupCommandStaticTest(tests.support.TestCase):
def test_canonical(self):
cmd = group.GroupCommand(tests.support.mock.MagicMock())
for args, out in [
(['grouplist', 'crack'], ['list', 'crack']),
(['groups'], ['summary']),
(['group', 'info', 'crack'], ['info', 'crack']),
(['group', 'update', 'crack'], ['upgrade', 'crack'])]:
parser = OptionParser()
parser.parse_main_args(args)
parser.parse_command_args(cmd, args)
cmd._canonical()
self.assertEqual(cmd.opts.subcmd, out[0])
self.assertEqual(cmd.opts.args, out[1:])
def test_split_extcmds(self):
cmd = group.GroupCommand(tests.support.mock.MagicMock())
cmd.base.conf = dnf.conf.Conf()
tests.support.command_run(cmd, ['install', 'crack'])
cmd.base.env_group_install.assert_called_with(
['crack'], ('mandatory', 'default', 'conditional'),
cmd.base.conf.strict)
class GroupCommandTest(tests.support.DnfBaseTestCase):
REPOS = ["main"]
COMPS = True
INIT_SACK = True
def setUp(self):
super(GroupCommandTest, self).setUp()
self.cmd = group.GroupCommand(self.base.mock_cli())
self.parser = OptionParser()
def test_environment_list(self):
env_inst, env_avail = self.cmd._environment_lists(['sugar*'])
self.assertLength(env_inst, 0)
self.assertLength(env_avail, 1)
self.assertEqual(env_avail[0].name, 'Sugar Desktop Environment')
def test_configure(self):
tests.support.command_configure(self.cmd, ['remove', 'crack'])
demands = self.cmd.cli.demands
self.assertTrue(demands.allow_erasing)
self.assertFalse(demands.freshest_metadata)
class CompsQueryTest(tests.support.DnfBaseTestCase):
REPOS = []
COMPS = True
def test_all(self):
status_all = CompsQuery.AVAILABLE | CompsQuery.INSTALLED
kinds_all = CompsQuery.ENVIRONMENTS | CompsQuery.GROUPS
q = CompsQuery(self.comps, self.history, kinds_all, status_all)
res = q.get('sugar*', '*er*')
self.assertCountEqual(res.environments,
('sugar-desktop-environment',))
self.assertCountEqual(res.groups, ("Peppers", 'somerset'))
def test_err(self):
q = CompsQuery(self.comps, self.history, CompsQuery.ENVIRONMENTS,
CompsQuery.AVAILABLE)
with self.assertRaises(dnf.exceptions.CompsError):
q.get('*er*')
def test_installed(self):
q = CompsQuery(self.comps, self.history, CompsQuery.GROUPS,
CompsQuery.INSTALLED)
self.base.read_mock_comps(False)
grp = self.base.comps.group_by_pattern('somerset')
self.base.group_install(grp.id, ('mandatory',))
self._swdb_commit()
res = q.get('somerset')
self.assertEmpty(res.environments)
grp_ids = list(res.groups)
self.assertCountEqual(grp_ids, ('somerset',))
| 4,276
|
Python
|
.py
| 90
| 39.888889
| 77
| 0.666506
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,891
|
disabled-plugin.py
|
rpm-software-management_dnf/tests/plugins/disabled-plugin.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2016-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import unicode_literals
import dnf.plugin
class DisabledPlugin(dnf.plugin.Plugin):
name = 'disabled-plugin'
config_name = 'disabled'
| 1,146
|
Python
|
.py
| 22
| 50.454545
| 77
| 0.775492
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,892
|
lucky.py
|
rpm-software-management_dnf/tests/plugins/lucky.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2013-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import unicode_literals
import dnf.plugin
class LuckyPlugin(dnf.plugin.Plugin):
name = 'lucky'
def __init__(self, *args):
self._config = False
def config(self):
self._config = True
| 1,216
|
Python
|
.py
| 25
| 46.2
| 77
| 0.755706
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,893
|
test_read.py
|
rpm-software-management_dnf/tests/conf/test_read.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf.conf
import dnf.conf.read
import tests.support
FN = tests.support.resource_path('etc/repos.conf')
class RepoReaderTest(tests.support.TestCase):
def test_read(self):
conf = dnf.conf.Conf()
conf.config_file_path = FN
conf.reposdir = []
reader = dnf.conf.read.RepoReader(conf, {})
all_repos = list(reader)
self.assertLength(all_repos, 2)
r1 = all_repos[0]
self.assertEqual(r1.id, 'fixing')
self.assertEqual(r1.baseurl, ['http://cracks'])
r2 = all_repos[1]
self.assertEqual(r2.id, 'rain')
self.assertEqual(r2.mirrorlist, 'http://through.net')
| 1,722
|
Python
|
.py
| 37
| 42.567568
| 77
| 0.727164
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,894
|
test_list_option.py
|
rpm-software-management_dnf/tests/conf/test_list_option.py
|
# Copyright (C) 2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import unittest
import dnf
class ListOptionTest(unittest.TestCase):
def setUp(self):
self.conf = dnf.conf.MainConf()
def test_delitem(self):
self.conf.pluginpath = ["a", "b", "c"]
self.assertEqual(list(self.conf.pluginpath), ["a", "b", "c"])
var = self.conf.pluginpath
self.assertEqual(var, ["a", "b", "c"])
del var[0]
self.assertEqual(list(self.conf.pluginpath), ["b", "c"])
self.assertEqual(var, ["b", "c"])
def test_iadd(self):
self.conf.pluginpath = ["a"]
self.assertEqual(self.conf.pluginpath, ["a"])
var = self.conf.pluginpath
self.assertEqual(var, ["a"])
var += ["b", "c"]
self.assertEqual(self.conf.pluginpath, ["a", "b", "c"])
self.assertEqual(var, ["a", "b", "c"])
def test_iadd_tuple(self):
self.conf.pluginpath = ("a", )
self.assertEqual(self.conf.pluginpath, ["a"])
var = self.conf.pluginpath
self.assertEqual(var, ["a"])
var += ("b", "c")
self.assertEqual(self.conf.pluginpath, ["a", "b", "c"])
self.assertEqual(var, ["a", "b", "c"])
def test_imul(self):
self.conf.pluginpath = ["a"]
self.assertEqual(self.conf.pluginpath, ["a"])
var = self.conf.pluginpath
self.assertEqual(var, ["a"])
var *= 3
self.assertEqual(self.conf.pluginpath, ["a", "a", "a"])
self.assertEqual(var, ["a", "a", "a"])
def test_setitem(self):
self.conf.pluginpath = ["a"]
self.assertEqual(self.conf.pluginpath, ["a"])
var = self.conf.pluginpath
self.assertEqual(var, ["a"])
var[0] = "b"
self.assertEqual(self.conf.pluginpath, ["b"])
self.assertEqual(var, ["b"])
def test_append(self):
self.conf.pluginpath = ["a"]
self.assertEqual(self.conf.pluginpath, ["a"])
var = self.conf.pluginpath
self.assertEqual(var, ["a"])
var.append("b")
self.assertEqual(self.conf.pluginpath, ["a", "b"])
self.assertEqual(var, ["a", "b"])
def test_clear(self):
self.conf.pluginpath = ["a"]
self.assertEqual(self.conf.pluginpath, ["a"])
var = self.conf.pluginpath
self.assertEqual(var, ["a"])
var.clear()
self.assertEqual(self.conf.pluginpath, [])
self.assertEqual(var, [])
def test_extend(self):
self.conf.pluginpath = ["a"]
self.assertEqual(self.conf.pluginpath, ["a"])
var = self.conf.pluginpath
self.assertEqual(var, ["a"])
var.extend(["b", "c"])
self.assertEqual(self.conf.pluginpath, ["a", "b", "c"])
self.assertEqual(var, ["a", "b", "c"])
def test_insert(self):
self.conf.pluginpath = ["a"]
self.assertEqual(self.conf.pluginpath, ["a"])
var = self.conf.pluginpath
self.assertEqual(var, ["a"])
var.insert(0, "b")
self.assertEqual(self.conf.pluginpath, ["b", "a"])
self.assertEqual(var, ["b", "a"])
def test_pop(self):
self.conf.pluginpath = ["a", "b", "c"]
self.assertEqual(self.conf.pluginpath, ["a", "b", "c"])
var = self.conf.pluginpath
self.assertEqual(var, ["a", "b", "c"])
var.pop()
self.assertEqual(self.conf.pluginpath, ["a", "b"])
self.assertEqual(var, ["a", "b"])
def test_remove(self):
self.conf.pluginpath = ["a", "b", "c"]
self.assertEqual(self.conf.pluginpath, ["a", "b", "c"])
var = self.conf.pluginpath
self.assertEqual(var, ["a", "b", "c"])
var.remove("b")
self.assertEqual(self.conf.pluginpath, ["a", "c"])
self.assertEqual(var, ["a", "c"])
def test_reverse(self):
self.conf.pluginpath = ["a", "b", "c"]
self.assertEqual(self.conf.pluginpath, ["a", "b", "c"])
var = self.conf.pluginpath
self.assertEqual(var, ["a", "b", "c"])
var.reverse()
self.assertEqual(self.conf.pluginpath, ["c", "b", "a"])
self.assertEqual(var, ["c", "b", "a"])
def test_sort(self):
self.conf.pluginpath = ["a", "c", "b"]
self.assertEqual(self.conf.pluginpath, ["a", "c", "b"])
var = self.conf.pluginpath
self.assertEqual(var, ["a", "c", "b"])
var.sort()
self.assertEqual(self.conf.pluginpath, ["a", "b", "c"])
self.assertEqual(var, ["a", "b", "c"])
def test_priority(self):
self.conf._set_value("pluginpath", ["a"], dnf.conf.config.PRIO_PLUGINDEFAULT)
self.assertEqual(self.conf.pluginpath, ["a"])
self.conf._set_value("pluginpath", ["b"], dnf.conf.config.PRIO_PLUGINDEFAULT)
self.assertEqual(self.conf.pluginpath, ["b"])
# setting with lower priority is NOT allowed
self.conf._set_value("pluginpath", ["c"], dnf.conf.config.PRIO_DEFAULT)
self.assertEqual(self.conf.pluginpath, ["b"])
# resetting with lower priority is NOT allowed
self.conf._set_value("pluginpath", [], dnf.conf.config.PRIO_DEFAULT)
self.assertEqual(self.conf.pluginpath, ["b"])
self.conf.pluginpath = ["d"]
self.assertEqual(self.conf.pluginpath, ["d"])
self.conf.pluginpath.append("e")
self.assertEqual(self.conf.pluginpath, ["d", "e"])
self.conf.pluginpath = []
self.assertEqual(self.conf.pluginpath, [])
def test_references(self):
self.conf.pluginpath = ["a"]
self.assertEqual(list(self.conf.pluginpath), ["a"])
var1 = self.conf.pluginpath
var2 = self.conf.pluginpath
self.assertEqual(var1, ["a"])
self.assertEqual(var2, ["a"])
var1 += ["b", "c"]
self.assertEqual(list(self.conf.pluginpath), ["a", "b", "c"])
self.assertEqual(var1, ["a", "b", "c"])
self.assertEqual(var2, ["a", "b", "c"])
def test_add(self):
self.conf.pluginpath = ["a"]
self.assertEqual(list(self.conf.pluginpath), ["a"])
var = self.conf.pluginpath
self.conf._set_value("pluginpath", ["b"])
var = var + ["c"]
self.assertEqual(list(self.conf.pluginpath), ["b"])
self.assertEqual(var, ["b", "c"])
def test_contains(self):
self.conf.pluginpath = ["a"]
self.assertEqual(list(self.conf.pluginpath), ["a"])
var = self.conf.pluginpath
self.conf._set_value("pluginpath", ["b"])
self.assertIn("b", var)
def test_eq(self):
self.conf.pluginpath = ["a"]
self.assertEqual(list(self.conf.pluginpath), ["a"])
var = self.conf.pluginpath
self.conf._set_value("pluginpath", ["b"])
self.assertEqual(var, ["b"])
def test_ge(self):
self.conf.pluginpath = ["a"]
self.assertEqual(list(self.conf.pluginpath), ["a"])
var = self.conf.pluginpath
self.conf._set_value("pluginpath", ["b"])
self.assertTrue(var >= ["a", "b"])
def test_gt(self):
self.conf.pluginpath = ["a"]
self.assertEqual(list(self.conf.pluginpath), ["a"])
var = self.conf.pluginpath
self.conf._set_value("pluginpath", ["b"])
self.assertTrue(var > ["a", "a"])
def test_le(self):
self.conf.pluginpath = ["a", "b"]
self.assertEqual(list(self.conf.pluginpath), ["a", "b"])
var = self.conf.pluginpath
self.conf._set_value("pluginpath", [])
self.conf._set_value("pluginpath", ["a"])
self.assertTrue(var <= ["a"])
def test_lt(self):
self.conf.pluginpath = ["a", "b"]
self.assertEqual(list(self.conf.pluginpath), ["a", "b"])
var = self.conf.pluginpath
self.conf._set_value("pluginpath", [])
self.conf._set_value("pluginpath", ["a"])
self.assertTrue(var < ["b"])
def test_ne(self):
self.conf.pluginpath = ["a"]
self.assertEqual(list(self.conf.pluginpath), ["a"])
var = self.conf.pluginpath
self.conf._set_value("pluginpath", ["b"])
self.assertNotEqual(var, ["a"])
def test_mul(self):
self.conf.pluginpath = ["a"]
self.assertEqual(list(self.conf.pluginpath), ["a"])
var = self.conf.pluginpath
self.assertEqual(var, ["a"])
var = var * 3
self.assertEqual(list(self.conf.pluginpath), ["a"])
self.assertEqual(var, ["a", "a", "a"])
def test_rmul(self):
self.conf.pluginpath = ["a"]
self.assertEqual(list(self.conf.pluginpath), ["a"])
var = self.conf.pluginpath
self.assertEqual(var, ["a"])
var = 3 * var
self.assertEqual(list(self.conf.pluginpath), ["a"])
self.assertEqual(var, ["a", "a", "a"])
def test_getitem(self):
self.conf.pluginpath = ["a"]
self.assertEqual(list(self.conf.pluginpath), ["a"])
var = self.conf.pluginpath
self.conf._set_value("pluginpath", ["a", "b"])
self.assertEqual(var[1], "b")
def test_iter(self):
self.conf.pluginpath = ["a"]
self.assertEqual(list(self.conf.pluginpath), ["a"])
var = self.conf.pluginpath
self.conf._set_value("pluginpath", ["b"])
length = 0
for i in iter(var):
length += 1
if length == 1:
self.assertEqual(i, "b")
self.assertEqual(length, 1)
def test_len(self):
self.conf.pluginpath = ["a", "b"]
self.assertEqual(list(self.conf.pluginpath), ["a", "b"])
var = self.conf.pluginpath
self.conf._set_value("pluginpath", ["b"])
self.assertEqual(len(var), 1)
def test_copy(self):
self.conf.pluginpath = ["a"]
self.assertEqual(list(self.conf.pluginpath), ["a"])
var = self.conf.pluginpath
self.conf._set_value("pluginpath", ["b"])
var2 = var.copy()
self.assertEqual(var2, ["b"])
def test_count(self):
self.conf.pluginpath = ["a"]
self.assertEqual(list(self.conf.pluginpath), ["a"])
var = self.conf.pluginpath
self.conf._set_value("pluginpath", ["a", "a"])
self.assertEqual(var.count("a"), 2)
def test_index(self):
self.conf.pluginpath = ["a"]
self.assertEqual(list(self.conf.pluginpath), ["a"])
var = self.conf.pluginpath
self.conf._set_value("pluginpath", ["a", "b"])
self.assertEqual(var.index("b"), 1)
| 11,429
|
Python
|
.py
| 265
| 34.845283
| 85
| 0.588766
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,895
|
test_parser.py
|
rpm-software-management_dnf/tests/conf/test_parser.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf.conf
from libdnf.conf import ConfigParser
import tests.support
substitute = ConfigParser.substitute
class ParserTest(tests.support.TestCase):
def test_substitute(self):
substs = {'lies': 'fact'}
# Test a single word without braces
rawstr = '$Substitute some $lies.'
result = '$Substitute some fact.'
self.assertEqual(substitute(rawstr, substs), result)
# And with braces
rawstr = '$Substitute some ${lies}.'
self.assertEqual(substitute(rawstr, substs), result)
# Test a word with braces without space
rawstr = '$Substitute some ${lies}withoutspace.'
result = '$Substitute some factwithoutspace.'
self.assertEqual(substitute(rawstr, substs), result)
# Tests a single brace before (no substitution)
rawstr = '$Substitute some ${lieswithoutspace.'
result = '$Substitute some ${lieswithoutspace.'
self.assertEqual(substitute(rawstr, substs), result)
# Tests a single brace after (substitution and leave the brace)
rawstr = '$Substitute some $lies}withoutspace.'
result = '$Substitute some fact}withoutspace.'
self.assertEqual(substitute(rawstr, substs), result)
# Test ${variable:-word} and ${variable:+word} shell-like expansion
rawstr = '${lies:+alternate}-${unset:-default}-${nn:+n${nn:-${nnn:}'
result = 'alternate-default-${nn:+n${nn:-${nnn:}'
self.assertEqual(substitute(rawstr, substs), result)
def test_empty_option(self):
# Parser is able to read config file with option without value
FN = tests.support.resource_path('etc/empty_option.conf')
conf = dnf.conf.Conf()
conf.config_file_path = FN
conf.read()
self.assertEqual(conf.reposdir, '')
| 2,879
|
Python
|
.py
| 56
| 45.767857
| 77
| 0.70651
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,896
|
__init__.py
|
rpm-software-management_dnf/tests/conf/__init__.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
| 984
|
Python
|
.py
| 17
| 56.823529
| 77
| 0.777433
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,897
|
test_substitutions.py
|
rpm-software-management_dnf/tests/conf/test_substitutions.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2019 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import os
import dnf.conf
from dnf.conf.substitutions import Substitutions
from dnf.exceptions import ReadOnlyVariableError
import tests.support
FN = tests.support.resource_path('etc/repos.conf')
class SubstitutionsFromEnvironmentTest(tests.support.TestCase):
def test_numeric(self):
env = os.environ
os.environ['DNF0'] = 'the_zero'
conf = dnf.conf.Conf()
os.environ = env
self.assertIn('DNF0', conf.substitutions)
self.assertEqual('the_zero', conf.substitutions['DNF0'])
def test_named(self):
env = os.environ
os.environ['DNF_VAR_GENRE'] = 'opera'
os.environ['DNF_VAR_EMPTY'] = ''
os.environ['DNF_VAR_MAL$FORMED'] = 'not this'
os.environ['DNF_VARMALFORMED'] = 'not this'
os.environ['DNF_VAR_MALFORMED '] = 'not this'
conf = dnf.conf.Conf()
os.environ = env
self.assertCountEqual(
conf.substitutions.keys(),
['basearch', 'arch', 'GENRE', 'EMPTY'])
self.assertEqual('opera', conf.substitutions['GENRE'])
class SubstitutionsReadOnlyTest(tests.support.TestCase):
def test_set_readonly(self):
conf = dnf.conf.Conf()
variable_name = "releasever_major"
self.assertTrue(Substitutions.is_read_only(variable_name))
with self.assertRaises(ReadOnlyVariableError) as cm:
conf.substitutions["releasever_major"] = "1"
self.assertEqual(cm.exception.variable_name, "releasever_major")
class SubstitutionsReleaseverTest(tests.support.TestCase):
def test_releasever_simple(self):
conf = dnf.conf.Conf()
conf.substitutions["releasever"] = "1.23"
self.assertEqual(conf.substitutions["releasever_major"], "1")
self.assertEqual(conf.substitutions["releasever_minor"], "23")
def test_releasever_major_only(self):
conf = dnf.conf.Conf()
conf.substitutions["releasever"] = "123"
self.assertEqual(conf.substitutions["releasever_major"], "123")
self.assertEqual(conf.substitutions["releasever_minor"], "")
def test_releasever_multipart(self):
conf = dnf.conf.Conf()
conf.substitutions["releasever"] = "1.23.45"
self.assertEqual(conf.substitutions["releasever_major"], "1")
self.assertEqual(conf.substitutions["releasever_minor"], "23.45")
| 3,409
|
Python
|
.py
| 70
| 42.842857
| 77
| 0.705086
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,898
|
rhbug.py
|
rpm-software-management_dnf/doc/rhbug.py
|
# rhbug.py
# rhbug Sphinx extension.
#
# Copyright (C) 2012-2016 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from docutils import nodes
try:
import bugzilla
except ImportError:
bugzilla = None
import json
import os
class Summary(object):
def __init__(self, cache_fn):
self.cache_fn = cache_fn
def __call__(self, bug_id):
bug_id = int(bug_id)
summary = self._from_cache(bug_id)
if summary is not None:
return summary
summary = self._from_bugzilla(bug_id)
self._store_in_cache(bug_id, summary)
return summary
def _from_bugzilla(self, bug_id):
if bugzilla is None:
return ''
rhbz = bugzilla.RHBugzilla(url="https://bugzilla.redhat.com/xmlrpc.cgi")
query = rhbz.build_query(bug_id=bug_id)
bug = rhbz.query(query)[0]
return bug.summary
def _from_cache(self, bug_id):
try:
with open(self.cache_fn, 'r') as json_file:
cache = json.load(json_file)
summary = [entry[1] for entry in cache if entry[0] == bug_id]
return summary[0]
except (IOError, IndexError):
return None
def _store_in_cache(self, bug_id, summary):
if bugzilla is None:
return
try:
with open(self.cache_fn, 'r') as json_file:
cache = json.load(json_file)
except IOError:
cache = []
cache.append((bug_id, summary))
with open(self.cache_fn, 'w') as json_file:
json.dump(cache, json_file, indent=4)
def RhBug_role(role, rawtext, text, lineno, inliner, options={}, content=[]):
source = inliner.document.settings._source
summaries_fn = '%s/summaries_cache' % os.path.dirname(source)
summary = Summary(summaries_fn)(text)
link_name = 'Bug %s - %s' % (text, summary)
url = 'https://bugzilla.redhat.com/show_bug.cgi?id=%s' % text
node = nodes.reference(rawtext, link_name, refuri=url)
return [node], []
def setup(app):
app.add_role('rhbug', RhBug_role)
| 2,973
|
Python
|
.py
| 73
| 34.506849
| 80
| 0.661709
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,899
|
conf.py.in
|
rpm-software-management_dnf/doc/conf.py.in
|
# -*- coding: utf-8 -*-
#
# Hawkey documentation build configuration file, created by
# sphinx-quickstart on Tue Aug 7 11:06:24 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import os
import re
import sys
_dirname = os.path.dirname(__file__)
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, _dirname)
# -- General configuration -----------------------------------------------------
AUTHORS=[u'See AUTHORS in DNF source distribution.']
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['rhbug']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'DNF'
copyright = u'2012-2020, Red Hat, Licensed under GPLv2+'
version = '@DNF_VERSION@'
# The full version, including alpha/beta/rc tags.
release = '%s-1' % version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = "sphinx_rtd_theme"
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'dnfdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'dnf.tex', u'DNF Documentation',
AUTHORS[0], 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('automatic', 'dnf-automatic', u'DNF Automatic',
AUTHORS, 8),
('command_ref', 'dnf4', u'DNF Command Reference',
AUTHORS, 8),
('conf_ref', 'dnf4.conf', u'DNF Configuration Reference',
AUTHORS, 5),
('conf_ref', 'yum.conf', u'redirecting to DNF Configuration Reference',
AUTHORS, 5),
('transaction_json', 'dnf4-transaction-json', u'DNF Stored Transaction JSON',
AUTHORS, 5),
('cli_vs_yum', 'yum2dnf', u'Changes in DNF compared to YUM',
AUTHORS, 8),
('command_ref', 'yum', u'redirecting to DNF Command Reference',
AUTHORS, 8),
('command_ref', 'yum-shell', u'redirecting to DNF Command Reference',
AUTHORS, 8),
('command_ref', 'yum-aliases', u'redirecting to DNF Command Reference',
AUTHORS, 1),
('modularity', 'dnf4.modularity', u'Modularity in DNF',
AUTHORS, 7),
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'dnf', u'DNF Documentation',
AUTHORS[0], 'DNF', 'Package manager for RPM-based distributions.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
rst_prolog = """
.. default-domain:: py
.. _DNF: https://github.com/rpm-software-management/dnf/
.. _hawkey: http://rpm-software-management.github.io/hawkey/
.. _YUM: http://yum.baseurl.org/
.. _bugzilla: https://bugzilla.redhat.com/enter_bug.cgi?product=Fedora&component=dnf
"""
| 8,698
|
Python
|
.py
| 201
| 41.412935
| 84
| 0.717693
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|