Migrate `tests.integration.states.test_pkgrepo` to functional tests.

Additionally, for Debian based distributions, test ``pkgrepo`` with the
system ``aptsources`` package and without it.

Signed-off-by: Pedro Algarvio <palgarvio@vmware.com>
This commit is contained in:
Pedro Algarvio 2022-04-11 07:56:18 +01:00 committed by Megan Wilhite
parent e4f76951d0
commit cedccff8c7
13 changed files with 767 additions and 666 deletions

View file

@ -680,6 +680,7 @@ allowed-3rd-party-modules=msgpack,
libcloud,
zmq,
pytest,
_pytest,
attr,
setuptools,
pytestsalt,

View file

@ -12,7 +12,8 @@ salt/modules/(apkpkg|aptpkg|ebuildpkg|dpkg_lowpkg|freebsdpkg|mac_brew_pkg|mac_po
- pytests.unit.states.test_pkg
- pytests.functional.modules.test_pkg
- pytests.functional.states.test_pkg
- integration.states.test_pkgrepo
- pytests.functional.states.pkgrepo.test_centos
- pytests.functional.states.pkgrepo.test_debian
salt/modules/(mac_user|useradd|pw_user|solaris_user|win_useradd)\.py:
- pytests.unit.states.test_user

View file

@ -1,27 +0,0 @@
{% if grains['os'] == 'CentOS' %}
# START CentOS pkgrepo tests
epel-salttest:
pkgrepo:
- absent
# END CentOS pkgrepo tests
{% elif grains['os'] == 'Ubuntu' %}
firefox-beta:
pkgrepo.absent:
- name: deb http://ppa.launchpad.net/mozillateam/firefox-next/ubuntu {{ grains['oscodename'] }} main
kubuntu-ppa:
pkgrepo.absent:
- ppa: kubuntu-ppa/backports
{% else %}
# No matching OS grain for pkgrepo management, just run something that will
# return a True result
date:
cmd:
- run
{% endif %}

View file

@ -1,30 +0,0 @@
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1.2.6 (GNU/Linux)
mQGiBEXopTIRBACZDBMOoFOakAjaxw1LXjeSvh/kmE35fU1rXfM7T0AV31NATCLF
l5CQiNDA4oWreDThg2Bf6+LIVTsGQb1V+XXuLak4Em5yTYwMTVB//4/nMxQEbpl/
QB2XwlJ7EQ0vW+kiPDz/7pHJz1p1jADzd9sQQicMtzysS4qT2i5A23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I/KgL1jw+7MW6Az8Ox+RXZLyGMVmbW/TMc8haJfKL
MoUo3TVk8nPiUhoOC0/kI7j9ilFrBxBU5dUtF4ITAWc8xnG6jJs/IsvRpQARAQAB
tChGZWRvcmEgRVBFTCAoOCkgPGVwZWxAZmVkb3JhcHJvamVjdC5vcmc+iQI4BBMB
AgAiBQJc9877AhsPBgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAKCRAh6kWrL4bW
oWagD/4xnLWws34GByVDQkjprk0fX7Iyhpm/U7BsIHKspHLL+Y46vAAGY/9vMvdE
0fcr9Ek2Zp7zE1RWmSCzzzUgTG6BFoTG1H4Fho/7Z8BXK/jybowXSZfqXnTOfhSF
alwDdwlSJvfYNV9MbyvbxN8qZRU1z7PEWZrIzFDDToFRk0R71zHpnPTNIJ5/YXTw
NqU9OxII8hMQj4ufF11040AJQZ7br3rzerlyBOB+Jd1zSPVrAPpeMyJppWFHSDAI
WK6x+am13VIInXtqB/Cz4GBHLFK5d2/IYspVw47Solj8jiFEtnAq6+1Aq5WH3iB4
bE2e6z00DSF93frwOyWN7WmPIoc2QsNRJhgfJC+isGQAwwq8xAbHEBeuyMG8GZjz
xohg0H4bOSEujVLTjH1xbAG4DnhWO/1VXLX+LXELycO8ZQTcjj/4AQKuo4wvMPrv
9A169oETG+VwQlNd74VBPGCvhnzwGXNbTK/KH1+WRH0YSb+41flB3NKhMSU6dGI0
SGtIxDSHhVVNmx2/6XiT9U/znrZsG5Kw8nIbbFz+9MGUUWgJMsd1Zl9R8gz7V9fp
n7L7y5LhJ8HOCMsY/Z7/7HUs+t/A1MI4g7Q5g5UuSZdgi0zxukiWuCkLeAiAP4y7
zKK4OjJ644NDcWCHa36znwVmkz3ixL8Q0auR15Oqq2BjR/fyog==
=84m8
-----END PGP PUBLIC KEY BLOCK-----

View file

@ -1,131 +0,0 @@
{% if grains['os'] == 'CentOS' %}
# START CentOS pkgrepo tests
{% if grains['osmajorrelease'] == 8 %}
epel-salttest:
pkgrepo.managed:
- humanname: Extra Packages for Enterprise Linux 8 - $basearch (salttest)
- comments:
- '#baseurl=http://download.fedoraproject.org/pub/epel/8/$basearch'
- mirrorlist: https://mirrors.fedoraproject.org/metalink?repo=epel-8&arch=$basearch
- failovermethod: priority
- enabled: 1
- gpgcheck: 1
- gpgkey: file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-8-salttest
- require:
- file: /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-8-salttest
/etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-8-salttest:
file.managed:
- source: salt://pkgrepo/files/RPM-GPG-KEY-EPEL-8-salttest
- user: root
- group: root
- mode: 644
{% elif grains['osmajorrelease'] == 7 %}
epel-salttest:
pkgrepo.managed:
- humanname: Extra Packages for Enterprise Linux 7 - $basearch (salttest)
- comments:
- '#baseurl=http://download.fedoraproject.org/pub/epel/7/$basearch'
- mirrorlist: https://mirrors.fedoraproject.org/metalink?repo=epel-7&arch=$basearch
- failovermethod: priority
- enabled: 1
- gpgcheck: 1
- gpgkey: file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7-salttest
- require:
- file: /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7-salttest
/etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7-salttest:
file.managed:
- source: salt://pkgrepo/files/RPM-GPG-KEY-EPEL-7-salttest
- user: root
- group: root
- mode: 644
{% elif grains['osrelease'].startswith('6.') %}
epel-salttest:
pkgrepo.managed:
- humanname: Extra Packages for Enterprise Linux 6 - $basearch (salttest)
- comments:
- '#baseurl=http://download.fedoraproject.org/pub/epel/6/$basearch'
- mirrorlist: https://mirrors.fedoraproject.org/metalink?repo=epel-6&arch=$basearch
- failovermethod: priority
- enabled: 1
- gpgcheck: 1
- gpgkey: file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6-salttest
- require:
- file: /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6-salttest
/etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6-salttest:
file.managed:
- source: salt://pkgrepo/files/RPM-GPG-KEY-EPEL-6-salttest
- user: root
- group: root
- mode: 644
{% elif grains['osrelease'].startswith('5.') %}
epel-salttest:
pkgrepo.managed:
- humanname: Extra Packages for Enterprise Linux 5 - $basearch (salttest)
- comments:
- '#baseurl=http://download.fedoraproject.org/pub/epel/5/$basearch'
- mirrorlist: http://mirrors.fedoraproject.org/mirrorlist?repo=epel-5&arch=$basearch
- failovermethod: priority
- enabled: 1
- gpgcheck: 1
- gpgkey: file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-5-salttest
- require:
- file: /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-5-salttest
/etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-5-salttest:
file.managed:
- source: salt://pkgrepo/files/RPM-GPG-KEY-EPEL-5-salttest
- user: root
- group: root
- mode: 644
{% endif %}
# END CentOS pkgrepo tests
{% elif grains['os'] == 'Ubuntu' %}
# START Ubuntu pkgrepo tests
{% set codename = grains['oscodename'] %}
{% set ubuntu_repos = [] %}
{% set beta = grains['oscodename'] in ['xenial', 'bionic', 'eoan', 'focal', 'groovy'] %}
{% set backports = grains['oscodename'] in ['xenial', 'bionic', 'eoan', 'focal'] %}
{%- if beta %}{%- do ubuntu_repos.append('firefox-beta') %}
firefox-beta:
pkgrepo.managed:
- name: deb http://ppa.launchpad.net/mozillateam/firefox-next/ubuntu {{ codename }} main
- dist: {{ codename }}
- file: /etc/apt/sources.list.d/firefox-beta.list
- keyid: CE49EC21
- keyserver: keyserver.ubuntu.com
{%- endif %}
{%- if backports %}{%- do ubuntu_repos.append('kubuntu-ppa') %}
kubuntu-ppa:
pkgrepo.managed:
- ppa: kubuntu-ppa/backports
{%- endif %}
pkgrepo-deps:
pkg.installed:
- pkgs:
- python-apt
- software-properties-common
{%- for repo in ubuntu_repos -%}
{% if loop.first %}
- require_in:{%- endif %}
- pkgrepo: {{ repo }}
{%- endfor %}
# END Ubuntu pkgrepo tests
{% else %}
# No matching OS grain for pkgrepo management, just run something that will
# return a True result
date:
cmd:
- run
{% endif %}

View file

@ -1,351 +0,0 @@
"""
tests for pkgrepo states
"""
import os
import pytest
import salt.utils.files
import salt.utils.platform
from saltfactories.utils.tempfiles import temp_file
from tests.support.case import ModuleCase
from tests.support.helpers import requires_system_grains, runs_on
from tests.support.mixins import SaltReturnAssertsMixin
from tests.support.runtests import RUNTIME_VARS
from tests.support.unit import skipIf
@skipIf(salt.utils.platform.is_windows(), "minion is windows")
@pytest.mark.destructive_test
class PkgrepoTest(ModuleCase, SaltReturnAssertsMixin):
"""
pkgrepo state tests
"""
@pytest.mark.requires_salt_states("pkgrepo.managed")
@requires_system_grains
def test_pkgrepo_01_managed(self, grains):
"""
Test adding a repo
"""
if grains["os_family"] == "Debian":
try:
from aptsources import sourceslist # pylint: disable=unused-import
except ImportError:
self.skipTest("aptsources.sourceslist python module not found")
ret = self.run_function("state.sls", mods="pkgrepo.managed", timeout=120)
# If the below assert fails then no states were run, and the SLS in
# tests/integration/files/file/base/pkgrepo/managed.sls needs to be
# corrected.
self.assertReturnNonEmptySaltType(ret)
for state_id, state_result in ret.items():
self.assertSaltTrueReturn(dict([(state_id, state_result)]))
@pytest.mark.requires_salt_states("pkgrepo.absent")
@requires_system_grains
def test_pkgrepo_02_absent(self, grains):
"""
Test removing the repo from the above test
"""
ret = self.run_function("state.sls", mods="pkgrepo.absent", timeout=120)
# If the below assert fails then no states were run, and the SLS in
# tests/integration/files/file/base/pkgrepo/absent.sls needs to be
# corrected.
self.assertReturnNonEmptySaltType(ret)
for state_id, state_result in ret.items():
self.assertSaltTrueReturn(dict([(state_id, state_result)]))
@pytest.mark.requires_salt_states("pkgrepo.absent", "pkgrepo.managed")
@requires_system_grains
@pytest.mark.slow_test
def test_pkgrepo_03_with_comments(self, grains):
"""
Test adding a repo with comments
"""
kwargs = {}
if grains["os_family"] == "RedHat":
kwargs = {
"name": "examplerepo",
"baseurl": "http://example.com/repo",
"enabled": False,
"comments": ["This is a comment"],
}
else:
self.skipTest(
"{}/{} test case needed".format(grains["os_family"], grains["os"])
)
try:
# Run the state to add the repo
ret = self.run_state("pkgrepo.managed", **kwargs)
self.assertSaltTrueReturn(ret)
# Run again with modified comments
kwargs["comments"].append("This is another comment")
ret = self.run_state("pkgrepo.managed", **kwargs)
self.assertSaltTrueReturn(ret)
ret = ret[next(iter(ret))]
self.assertEqual(
ret["changes"],
{
"comments": {
"old": ["This is a comment"],
"new": ["This is a comment", "This is another comment"],
}
},
)
# Run a third time, no changes should be made
ret = self.run_state("pkgrepo.managed", **kwargs)
self.assertSaltTrueReturn(ret)
ret = ret[next(iter(ret))]
self.assertFalse(ret["changes"])
self.assertEqual(
ret["comment"],
"Package repo '{}' already configured".format(kwargs["name"]),
)
finally:
# Clean up
self.run_state("pkgrepo.absent", name=kwargs["name"])
@pytest.mark.requires_salt_states("pkgrepo.managed")
@requires_system_grains
@pytest.mark.slow_test
def test_pkgrepo_04_apt_with_architectures(self, grains):
"""
Test managing a repo with architectures specified
"""
if grains["os_family"].lower() != "debian":
self.skipTest("APT-only test")
name = "deb {{arch}}http://foo.com/bar/latest {oscodename} main".format(
oscodename=grains["oscodename"]
)
def _get_arch(arch):
return "[arch={}] ".format(arch) if arch else ""
def _run(arch="", test=False):
ret = self.run_state(
"pkgrepo.managed",
name=name.format(arch=_get_arch(arch)),
file=fn_,
refresh=False,
test=test,
)
return ret[next(iter(ret))]
fn_ = salt.utils.files.mkstemp(dir="/etc/apt/sources.list.d", suffix=".list")
try:
# Run with test=True
ret = _run(test=True)
assert ret["changes"] == {"repo": name.format(arch="")}, ret["changes"]
assert "would be" in ret["comment"], ret["comment"]
assert ret["result"] is None, ret["result"]
# Run for real
ret = _run()
assert ret["changes"] == {"repo": name.format(arch="")}, ret["changes"]
assert ret["comment"].startswith("Configured"), ret["comment"]
assert ret["result"] is True, ret["result"]
# Run again with test=True, should exit with no changes and a True
# result.
ret = _run(test=True)
assert not ret["changes"], ret["changes"]
assert "already" in ret["comment"], ret["comment"]
assert ret["result"] is True, ret["result"]
# Run for real again, results should be the same as above (i.e. we
# should never get to the point where we exit with a None result).
ret = _run()
assert not ret["changes"], ret["changes"]
assert "already" in ret["comment"], ret["comment"]
assert ret["result"] is True, ret["result"]
expected_changes = {
"line": {
"new": name.format(arch=_get_arch("amd64")),
"old": name.format(arch=""),
},
"architectures": {"new": ["amd64"], "old": []},
}
# Run with test=True and the architecture set. We should get a None
# result with some expected changes.
ret = _run(arch="amd64", test=True)
assert ret["changes"] == expected_changes, ret["changes"]
assert "would be" in ret["comment"], ret["comment"]
assert ret["result"] is None, ret["result"]
# Run for real, with the architecture set. We should get a True
# result with the same changes.
ret = _run(arch="amd64")
assert ret["changes"] == expected_changes, ret["changes"]
assert ret["comment"].startswith("Configured"), ret["comment"]
assert ret["result"] is True, ret["result"]
# Run again with test=True, should exit with no changes and a True
# result.
ret = _run(arch="amd64", test=True)
assert not ret["changes"], ret["changes"]
assert "already" in ret["comment"], ret["comment"]
assert ret["result"] is True, ret["result"]
# Run for real again, results should be the same as above (i.e. we
# should never get to the point where we exit with a None result).
ret = _run(arch="amd64")
assert not ret["changes"], ret["changes"]
assert "already" in ret["comment"], ret["comment"]
assert ret["result"] is True, ret["result"]
expected_changes = {
"line": {
"new": name.format(arch=""),
"old": name.format(arch=_get_arch("amd64")),
},
"architectures": {"new": [], "old": ["amd64"]},
}
# Run with test=True and the architecture set back to the original
# value. We should get a None result with some expected changes.
ret = _run(test=True)
assert ret["changes"] == expected_changes, ret["changes"]
assert "would be" in ret["comment"], ret["comment"]
assert ret["result"] is None, ret["result"]
# Run for real, with the architecture set. We should get a True
# result with the same changes.
ret = _run()
assert ret["changes"] == expected_changes, ret["changes"]
assert ret["comment"].startswith("Configured"), ret["comment"]
assert ret["result"] is True, ret["result"]
# Run again with test=True, should exit with no changes and a True
# result.
ret = _run(test=True)
assert not ret["changes"], ret["changes"]
assert "already" in ret["comment"], ret["comment"]
assert ret["result"] is True, ret["result"]
# Run for real again, results should be the same as above (i.e. we
# should never get to the point where we exit with a None result).
ret = _run()
assert not ret["changes"], ret["changes"]
assert "already" in ret["comment"], ret["comment"]
assert ret["result"] is True, ret["result"]
finally:
try:
os.remove(fn_)
except OSError:
pass
@pytest.mark.requires_salt_states("pkgrepo.absent", "pkgrepo.managed")
@requires_system_grains
@pytest.mark.slow_test
def test_pkgrepo_05_copr_with_comments(self, grains):
"""
Test copr
"""
kwargs = {}
if grains["os_family"] == "RedHat":
if (
grains["osfinger"] == "CentOS Linux-7"
or grains["osfinger"] == "Amazon Linux-2"
or grains["os"] == "VMware Photon OS"
):
self.skipTest("copr plugin not installed on Centos 7 CI")
kwargs = {
"name": "hello-copr",
"copr": "mymindstorm/hello",
"enabled": False,
"comments": ["This is a comment"],
}
else:
self.skipTest(
"{}/{} test case needed".format(grains["os_family"], grains["os"])
)
try:
# Run the state to add the repo
ret = self.run_state("pkgrepo.managed", **kwargs)
self.assertSaltTrueReturn(ret)
# Run again with modified comments
kwargs["comments"].append("This is another comment")
ret = self.run_state("pkgrepo.managed", **kwargs)
self.assertSaltTrueReturn(ret)
ret = ret[next(iter(ret))]
self.assertEqual(
ret["changes"],
{
"comments": {
"old": ["This is a comment"],
"new": ["This is a comment", "This is another comment"],
}
},
)
# Run a third time, no changes should be made
ret = self.run_state("pkgrepo.managed", **kwargs)
self.assertSaltTrueReturn(ret)
ret = ret[next(iter(ret))]
self.assertFalse(ret["changes"])
self.assertEqual(
ret["comment"],
"Package repo '{}' already configured".format(kwargs["name"]),
)
finally:
# Clean up
self.run_state("pkgrepo.absent", copr=kwargs["copr"])
@runs_on(kernel="linux", os="Ubuntu")
def test_managed_multiple_comps(self):
state_file = """
ubuntu-backports:
pkgrepo.managed:
- name: 'deb http://fi.archive.ubuntu.com/ubuntu focal-backports'
- comps: main, restricted, universe, multiverse
- refresh: false
- disabled: false
- clean_file: true
- file: /etc/apt/sources.list.d/99-salt-archive-ubuntu-focal-backports.list
- require_in:
- pkgrepo: canonical-ubuntu
canonical-ubuntu:
pkgrepo.managed:
- name: 'deb http://archive.canonical.com/ubuntu {{ salt['grains.get']('oscodename') }}'
- comps: partner
- refresh: false
- disabled: false
- clean_file: true
- file: /etc/apt/sources.list.d/99-salt-canonical-ubuntu.list
"""
def remove_apt_list_file(path):
if os.path.exists(path):
os.unlink(path)
self.addCleanup(
remove_apt_list_file,
"/etc/apt/sources.list.d/99-salt-canonical-ubuntu.list",
)
self.addCleanup(
remove_apt_list_file,
"/etc/apt/sources.list.d/99-salt-archive-ubuntu-focal-backports.list",
)
with temp_file(
"multiple-comps-repos.sls", state_file, RUNTIME_VARS.TMP_BASEENV_STATE_TREE
):
ret = self.run_function("state.sls", ["multiple-comps-repos"])
for state_run in ret.values():
# On the first run, we must have changes
assert state_run["changes"]
ret = self.run_function("state.sls", ["multiple-comps-repos"])
for state_run in ret.values():
# On the second run though, we shouldn't have changes made
assert not state_run["changes"]

View file

@ -0,0 +1,297 @@
import logging
import _pytest._version
import pytest
PYTEST_GE_7 = getattr(_pytest._version, "version_tuple", (-1, -1)) >= (7, 0)
log = logging.getLogger(__name__)
pytestmark = [
pytest.mark.destructive_test,
pytest.mark.skip_if_not_root,
]
RPM_GPG_KEY_EPEL_8_SALTTEST = """\
-----BEGIN PGP PUBLIC KEY BLOCK-----
mQINBFz3zvsBEADJOIIWllGudxnpvJnkxQz2CtoWI7godVnoclrdl83kVjqSQp+2
dgxuG5mUiADUfYHaRQzxKw8efuQnwxzU9kZ70ngCxtmbQWGmUmfSThiapOz00018
+eo5MFabd2vdiGo1y+51m2sRDpN8qdCaqXko65cyMuLXrojJHIuvRA/x7iqOrRfy
a8x3OxC4PEgl5pgDnP8pVK0lLYncDEQCN76D9ubhZQWhISF/zJI+e806V71hzfyL
/Mt3mQm/li+lRKU25Usk9dWaf4NH/wZHMIPAkVJ4uD4H/uS49wqWnyiTYGT7hUbi
ecF7crhLCmlRzvJR8mkRP6/4T/F3tNDPWZeDNEDVFUkTFHNU6/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4spqpsTjtDM7qpytKLHKruZtvuWiqt5RfvT9ww9GUUFMZ4ZZGX4nUXg49q
ixDLayWR8ddG/s5kyOi3C0uX/6inzaYyRg+Bh70brqKUK14F1BrrPi29eaKfG+Gu
MFtXdBG2a7OtPmw3yuKmq9Epv6B0mP6E5KSdvSRSqJWtGcA6wRS/wDzXJENHp5re
9Ism3CYydpy0GLRA5wo4fPB5uLdUhLEUDvh2KK//fMjja3o0L+SNz8N0aDZyn5Ax
CU9RB3EHcTecFgoy5umRj99BZrebR1NO+4gBrivIfdvD4fJNfNBHXwhSH9ACGCNv
HnXVjHQF9iHWApKkRIeh8Fr2n5dtfJEF7SEX8GbX7FbsWo29kXMrVgNqHNyDnfAB
VoPubgQdtJZJkVZAkaHrMu8AytwT62Q4eNqmJI1aWbZQNI5jWYqc6RKuCK6/F99q
thFT9gJO17+yRuL6Uv2/vgzVR1RGdwVLKwlUjGPAjYflpCQwWMAASxiv9uPyYPHc
ErSrbRG0wjIfAR3vus1OSOx3xZHZpXFfmQTsDP7zVROLzV98R3JwFAxJ4/xqeON4
vCPFU6OsT3lWQ8w7il5ohY95wmujfr6lk89kEzJdOTzcn7DBbUru33CQMGKZ3Evt
RjsC7FDbL017qxS+ZVA/HGkyfiu4cpgV8VUnbql5eAZ+1Ll6Dw==
=hdPa
-----END PGP PUBLIC KEY BLOCK-----
"""
@pytest.fixture
def pkgrepo(states, grains):
if grains["os_family"] != "RedHat":
exc_kwargs = {}
if PYTEST_GE_7:
exc_kwargs["_use_item_location"] = True
raise pytest.skip.Exception(
"Test only for CentOS platforms, not '{}' based distributions.".format(
grains["os_family"]
),
**exc_kwargs
)
return states.pkgrepo
@pytest.fixture
def centos_state_tree(grains, pkgrepo, state_tree):
if grains["os"] not in ("CentOS", "CentOS Stream"):
pytest.skip("Test only applicable to CentOS, not '{}'.".format(grains["os"]))
managed_sls_contents = """
{% if grains['osmajorrelease'] == 8 %}
epel-salttest:
pkgrepo.managed:
- humanname: Extra Packages for Enterprise Linux 8 - $basearch (salttest)
- comments:
- '#baseurl=http://download.fedoraproject.org/pub/epel/8/$basearch'
- mirrorlist: https://mirrors.fedoraproject.org/metalink?repo=epel-8&arch=$basearch
- failovermethod: priority
- enabled: 1
- gpgcheck: 1
- gpgkey: file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-8-salttest
- require:
- file: /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-8-salttest
/etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-8-salttest:
file.managed:
- source: salt://pkgrepo/files/RPM-GPG-KEY-EPEL-8-salttest
- user: root
- group: root
- mode: 644
{% elif grains['osmajorrelease'] == 7 %}
epel-salttest:
pkgrepo.managed:
- humanname: Extra Packages for Enterprise Linux 7 - $basearch (salttest)
- comments:
- '#baseurl=http://download.fedoraproject.org/pub/epel/7/$basearch'
- mirrorlist: https://mirrors.fedoraproject.org/metalink?repo=epel-7&arch=$basearch
- failovermethod: priority
- enabled: 1
- gpgcheck: 1
- gpgkey: file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7-salttest
- require:
- file: /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7-salttest
/etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7-salttest:
file.managed:
- source: salt://pkgrepo/files/RPM-GPG-KEY-EPEL-7-salttest
- user: root
- group: root
- mode: 644
{% endif %}
"""
absend_sls_contents = """
epel-salttest:
pkgrepo:
- absent
"""
centos_7_gpg_key = pytest.helpers.temp_file(
"pkgrepo/files/RPM-GPG-KEY-EPEL-7-salttest",
RPM_GPG_KEY_EPEL_7_SALTTEST,
state_tree,
)
centos_8_gpg_key = pytest.helpers.temp_file(
"pkgrepo/files/RPM-GPG-KEY-EPEL-8-salttest",
RPM_GPG_KEY_EPEL_8_SALTTEST,
state_tree,
)
managed_state_file = pytest.helpers.temp_file(
"pkgrepo/managed.sls", managed_sls_contents, state_tree
)
absent_state_file = pytest.helpers.temp_file(
"pkgrepo/absent.sls", absend_sls_contents, state_tree
)
try:
with centos_7_gpg_key, centos_8_gpg_key, managed_state_file, absent_state_file:
yield
finally:
pass
@pytest.mark.requires_salt_states("pkgrepo.managed", "pkgrepo.absent")
def test_pkgrepo_managed_absent(grains, modules, subtests, centos_state_tree):
"""
Test adding/removing a repo
"""
add_repo_test_passed = False
with subtests.test("Add Repo"):
ret = modules.state.sls("pkgrepo.managed")
assert ret.failed is False
for state in ret:
assert state.result is True
add_repo_test_passed = True
with subtests.test("Remove Repo"):
if add_repo_test_passed is False:
pytest.skip("Adding the repo failed. Skipping.")
ret = modules.state.sls("pkgrepo.absent")
assert ret.failed is False
for state in ret:
assert state.result is True
@pytest.fixture
def pkgrepo_with_comments_name(pkgrepo):
pkgrepo_name = "examplerepo"
try:
yield pkgrepo_name
finally:
try:
pkgrepo.absent(pkgrepo_name)
except Exception: # pylint: disable=broad-except
pass
def test_pkgrepo_with_comments(pkgrepo, pkgrepo_with_comments_name, subtests):
"""
Test adding a repo with comments
"""
kwargs = {
"name": pkgrepo_with_comments_name,
"baseurl": "http://example.com/repo",
"enabled": False,
"comments": ["This is a comment"],
}
with subtests.test("Add repo"):
# Run the state to add the repo
ret = pkgrepo.managed(**kwargs.copy())
assert ret.result is True
with subtests.test("Modify comments"):
# Run again with modified comments
kwargs["comments"].append("This is another comment")
ret = pkgrepo.managed(**kwargs.copy())
assert ret.result is True
assert ret.changes == {
"comments": {
"old": ["This is a comment"],
"new": ["This is a comment", "This is another comment"],
}
}
with subtests.test("Repeat last call"):
# Run a third time, no changes should be made
ret = pkgrepo.managed(**kwargs.copy())
assert ret.result is True
assert not ret.changes
assert ret.comment == "Package repo '{}' already configured".format(
pkgrepo_with_comments_name
)
@pytest.fixture
def copr_pkgrepo_with_comments_name(pkgrepo, grains):
if (
grains["osfinger"] in ("CentOS Linux-7", "Amazon Linux-2")
or grains["os"] == "VMware Photon OS"
):
pytest.skip("copr plugin not installed on Centos 7 CI")
pkgrepo_name = "hello-copr"
try:
yield pkgrepo_name
finally:
try:
pkgrepo.absent(copr="mymindstorm/hello")
except Exception: # pylint: disable=broad-except
pass
def test_copr_pkgrepo_with_comments(pkgrepo, copr_pkgrepo_with_comments_name, subtests):
"""
Test adding a repo with comments
"""
kwargs = {
"name": copr_pkgrepo_with_comments_name,
"copr": "mymindstorm/hello",
"enabled": False,
"comments": ["This is a comment"],
}
with subtests.test("Add repo"):
# Run the state to add the repo
ret = pkgrepo.managed(**kwargs.copy())
assert ret.result is True
with subtests.test("Modify comments"):
# Run again with modified comments
kwargs["comments"].append("This is another comment")
ret = pkgrepo.managed(**kwargs.copy())
assert ret.result is True
assert ret.changes == {
"comments": {
"old": ["This is a comment"],
"new": ["This is a comment", "This is another comment"],
}
}
with subtests.test("Repeat last call"):
# Run a third time, no changes should be made
ret = pkgrepo.managed(**kwargs.copy())
assert ret.result is True
assert not ret.changes
assert ret.comment == "Package repo '{}' already configured".format(
copr_pkgrepo_with_comments_name
)

View file

@ -0,0 +1,467 @@
import glob
import logging
import os
import pathlib
import shutil
import sys
import _pytest._version
import pytest
import salt.utils.files
from tests.conftest import CODE_DIR
try:
from sysconfig import get_python_lib # pylint: disable=no-name-in-module
except ImportError:
from distutils.sysconfig import get_python_lib
PYTEST_GE_7 = getattr(_pytest._version, "version_tuple", (-1, -1)) >= (7, 0)
log = logging.getLogger(__name__)
pytestmark = [
pytest.mark.destructive_test,
pytest.mark.skip_if_not_root,
]
@pytest.fixture
def pkgrepo(states, grains):
if grains["os_family"] != "Debian":
exc_kwargs = {}
if PYTEST_GE_7:
exc_kwargs["_use_item_location"] = True
raise pytest.skip.Exception(
"Test only for debian based platforms", **exc_kwargs
)
return states.pkgrepo
@pytest.mark.requires_salt_states("pkgrepo.managed")
def test_adding_repo_file(pkgrepo, tmp_path):
"""
test adding a repo file using pkgrepo.managed
"""
repo_file = str(tmp_path / "stable-binary.list")
repo_content = "deb http://www.deb-multimedia.org stable main"
ret = pkgrepo.managed(name=repo_content, file=repo_file, clean_file=True)
with salt.utils.files.fopen(repo_file, "r") as fp:
file_content = fp.read()
assert file_content.strip() == repo_content
@pytest.mark.requires_salt_states("pkgrepo.managed")
def test_adding_repo_file_arch(pkgrepo, tmp_path):
"""
test adding a repo file using pkgrepo.managed
and setting architecture
"""
repo_file = str(tmp_path / "stable-binary.list")
repo_content = "deb [arch=amd64 ] http://www.deb-multimedia.org stable main"
pkgrepo.managed(name=repo_content, file=repo_file, clean_file=True)
with salt.utils.files.fopen(repo_file, "r") as fp:
file_content = fp.read()
assert (
file_content.strip()
== "deb [arch=amd64] http://www.deb-multimedia.org stable main"
)
def system_aptsources_ids(value):
return "{}(aptsources.sourceslist)".format(value.title())
@pytest.fixture(
params=("with", "without"), ids=system_aptsources_ids, scope="module", autouse=True
)
def system_aptsources(request, grains):
sys_modules = list(sys.modules)
copied_paths = []
exc_kwargs = {}
if PYTEST_GE_7:
exc_kwargs["_use_item_location"] = True
if grains["os_family"] != "Debian":
raise pytest.skip.Exception(
"Test only for debian based platforms", **exc_kwargs
)
try:
try:
from aptsources import sourceslist # pylint: disable=unused-import
if request.param == "without":
raise pytest.skip.Exception(
"This test is meant to run without the system aptsources package, but it's "
"available from '{}'.".format(sourceslist.__file__),
**exc_kwargs
)
else:
# Run the test
yield request.param
except ImportError:
if request.param == "without":
# Run the test
yield
else:
copied_paths = []
py_version_keys = [
"{}".format(*sys.version_info),
"{}.{}".format(*sys.version_info),
]
session_site_packages_dir = get_python_lib()
session_site_packages_dir = os.path.relpath(
session_site_packages_dir, str(CODE_DIR)
)
for py_version in py_version_keys:
dist_packages_path = "/usr/lib/python{}/dist-packages".format(
py_version
)
if not os.path.isdir(dist_packages_path):
continue
for aptpkg in glob.glob(os.path.join(dist_packages_path, "*apt*")):
src = os.path.realpath(aptpkg)
dst = os.path.join(
session_site_packages_dir, os.path.basename(src)
)
if os.path.exists(dst):
log.info(
"Not overwritting already existing %s with %s", dst, src
)
continue
log.info("Copying %s into %s", src, dst)
copied_paths.append(dst)
if os.path.isdir(src):
shutil.copytree(src, dst)
else:
shutil.copyfile(src, dst)
if not copied_paths:
raise pytest.skip.Exception(
"aptsources.sourceslist python module not found", **exc_kwargs
)
# Run the test
yield request.param
finally:
for path in copied_paths:
log.info("Deleting %r", path)
if os.path.isdir(path):
shutil.rmtree(path, ignore_errors=True)
else:
os.unlink(path)
for name in list(sys.modules):
if name in sys_modules:
continue
if "apt" not in name:
continue
log.debug("Removing '%s' from 'sys.modules'", name)
sys.modules.pop(name)
@pytest.fixture
def ubuntu_state_tree(system_aptsources, state_tree, grains):
if grains["os"] != "Ubuntu":
pytest.skip(
"Test only applicable to Ubuntu, not '{}'".format(grains["osfinger"])
)
managed_sls_contents = """
{% set codename = grains['oscodename'] %}
{% set ubuntu_repos = [] %}
{% set beta = grains['oscodename'] in ['xenial', 'bionic', 'eoan', 'focal', 'groovy'] %}
{% set backports = grains['oscodename'] in ['xenial', 'bionic', 'eoan', 'focal'] %}
{%- if beta %}{%- do ubuntu_repos.append('firefox-beta') %}
firefox-beta:
pkgrepo.managed:
- name: deb http://ppa.launchpad.net/mozillateam/firefox-next/ubuntu {{ codename }} main
- dist: {{ codename }}
- file: /etc/apt/sources.list.d/firefox-beta.list
- keyid: CE49EC21
- keyserver: keyserver.ubuntu.com
{%- endif %}
{%- if backports %}{%- do ubuntu_repos.append('kubuntu-ppa') %}
kubuntu-ppa:
pkgrepo.managed:
- ppa: kubuntu-ppa/backports
{%- endif %}
pkgrepo-deps:
pkg.installed:
- pkgs:
- python-apt
- software-properties-common
{%- for repo in ubuntu_repos -%}
{% if loop.first %}
- require_in:{%- endif %}
- pkgrepo: {{ repo }}
{%- endfor %}
"""
absent_sls_contents = """
firefox-beta:
pkgrepo.absent:
- name: deb http://ppa.launchpad.net/mozillateam/firefox-next/ubuntu {{ grains['oscodename'] }} main
kubuntu-ppa:
pkgrepo.absent:
- ppa: kubuntu-ppa/backports
"""
managed_state_file = pytest.helpers.temp_file(
"pkgrepo/managed.sls", managed_sls_contents, state_tree
)
absent_state_file = pytest.helpers.temp_file(
"pkgrepo/absent.sls", absent_sls_contents, state_tree
)
try:
with managed_state_file, absent_state_file:
yield
finally:
for pathstr in ("/etc/apt/sources.list.d/firefox-beta.list",):
path = pathlib.Path(pathstr)
if path.exists():
path.unlink()
@pytest.mark.requires_salt_states("pkgrepo.managed", "pkgrepo.absent")
def test_pkgrepo_managed_absent(modules, ubuntu_state_tree, subtests):
"""
Test adding a repo with the system aptsources package
"""
add_repo_test_passed = False
with subtests.test("Add Repo"):
ret = modules.state.sls("pkgrepo.managed")
assert ret.failed is False
for state in ret:
assert state.result is True
add_repo_test_passed = True
with subtests.test("Remove Repo"):
if add_repo_test_passed is False:
pytest.skip("Adding the repo failed. Skipping.")
ret = modules.state.sls("pkgrepo.absent")
assert ret.failed is False
for state in ret:
assert state.result is True
@pytest.fixture
def multiple_comps_repo_file_caconical(grains):
if grains["os"] != "Ubuntu":
pytest.skip(
"Test only applicable to Ubuntu, not '{}'".format(grains["osfinger"])
)
repo_file_path = "/etc/apt/sources.list.d/99-salt-canonical-ubuntu.list"
try:
yield repo_file_path
finally:
try:
os.unlink(repo_file_path)
except OSError:
pass
@pytest.fixture
def multiple_comps_repo_file_backports(grains):
if grains["os"] != "Ubuntu":
pytest.skip(
"Test only applicable to Ubuntu, not '{}'".format(grains["osfinger"])
)
repo_file_path = (
"/etc/apt/sources.list.d/99-salt-archive-ubuntu-focal-backports.list"
)
try:
yield repo_file_path
finally:
try:
os.unlink(repo_file_path)
except OSError:
pass
@pytest.fixture
def multiple_comps_state_tree(
multiple_comps_repo_file_caconical, multiple_comps_repo_file_backports, state_tree
):
sls_contents = """
ubuntu-backports:
pkgrepo.managed:
- name: 'deb http://fi.archive.ubuntu.com/ubuntu focal-backports'
- comps: main, restricted, universe, multiverse
- refresh: false
- disabled: false
- clean_file: true
- file: {}
- require_in:
- pkgrepo: canonical-ubuntu
canonical-ubuntu:
pkgrepo.managed:
- name: 'deb http://archive.canonical.com/ubuntu {{{{ salt['grains.get']('oscodename') }}}}'
- comps: partner
- refresh: false
- disabled: false
- clean_file: true
- file: {}
""".format(
multiple_comps_repo_file_backports,
multiple_comps_repo_file_caconical,
)
with pytest.helpers.temp_file("multiple-comps-repos.sls", sls_contents, state_tree):
yield
def test_managed_multiple_comps(modules, multiple_comps_state_tree):
# On the first run, we must have changes
ret = modules.state.sls("multiple-comps-repos")
assert ret.failed is False
for state in ret:
assert state.result is True
assert state.changes
# On the second run though, we shouldn't have changes made
ret = modules.state.sls("multiple-comps-repos")
assert ret.failed is False
for state in ret:
assert state.result is True
assert not state.changes
@pytest.fixture
def sources_list_file():
fn_ = salt.utils.files.mkstemp(dir="/etc/apt/sources.list.d", suffix=".list")
try:
yield fn_
finally:
try:
os.remove(fn_)
except OSError:
pass
def test_pkgrepo_with_architectures(pkgrepo, grains, sources_list_file, subtests):
"""
Test managing a repo with architectures specified
"""
name = "deb {{arch}}http://foo.com/bar/latest {oscodename} main".format(
oscodename=grains["oscodename"]
)
def _get_arch(arch):
return "[arch={}] ".format(arch) if arch else ""
def _run(arch=None, test=False):
return pkgrepo.managed(
name=name.format(arch=_get_arch(arch)),
file=sources_list_file,
refresh=False,
test=test,
)
with subtests.test("test=True"):
# Run with test=True
ret = _run(test=True)
assert ret.changes == {"repo": name.format(arch="")}
assert "would be" in ret.comment
assert ret.result is None
with subtests.test("test=False"):
# Run for real
ret = _run()
assert ret.changes == {"repo": name.format(arch="")}
assert ret.comment.startswith("Configured")
assert ret.result is True
with subtests.test("test=True repeat"):
# Run again with test=True, should exit with no changes and a True
# result.
ret = _run(test=True)
assert not ret.changes
assert "already" in ret.comment
assert ret.result is True
with subtests.test("test=False repeat"):
# Run for real again, results should be the same as above (i.e. we
# should never get to the point where we exit with a None result).
ret = _run()
assert not ret.changes
assert "already" in ret.comment
assert ret.result is True
expected_changes = {
"line": {
"new": name.format(arch=_get_arch("amd64")),
"old": name.format(arch=""),
},
"architectures": {"new": ["amd64"], "old": []},
}
with subtests.test("test=True arch=amd64"):
# Run with test=True and the architecture set. We should get a None
# result with some expected changes.
ret = _run(arch="amd64", test=True)
assert ret.changes == expected_changes
assert "would be" in ret.comment
assert ret.result is None
with subtests.test("test=False arch=amd64"):
# Run for real, with the architecture set. We should get a True
# result with the same changes.
ret = _run(arch="amd64")
assert ret.changes == expected_changes
assert ret.comment.startswith("Configured")
assert ret.result is True
with subtests.test("test=True arch=amd64 repeat"):
# Run again with test=True, should exit with no changes and a True
# result.
ret = _run(arch="amd64", test=True)
assert not ret.changes
assert "already" in ret.comment
assert ret.result is True
with subtests.test("test=False arch=amd64 repeat"):
# Run for real again, results should be the same as above (i.e. we
# should never get to the point where we exit with a None result).
ret = _run(arch="amd64")
assert not ret.changes
assert "already" in ret.comment
assert ret.result is True
expected_changes = {
"line": {
"new": name.format(arch=""),
"old": name.format(arch=_get_arch("amd64")),
},
"architectures": {"new": [], "old": ["amd64"]},
}
with subtests.test("test=True arch=None"):
# Run with test=True and the architecture set back to the original
# value. We should get a None result with some expected changes.
ret = _run(test=True)
assert ret.changes == expected_changes
assert "would be" in ret.comment
assert ret.result is None
with subtests.test("test=False arch=None"):
# Run for real, with the architecture set. We should get a True
# result with the same changes.
ret = _run()
assert ret.changes == expected_changes
assert ret.comment.startswith("Configured")
assert ret.result is True
with subtests.test("test=True arch=None repeat"):
# Run again with test=True, should exit with no changes and a True
# result.
ret = _run(test=True)
assert not ret.changes
assert "already" in ret.comment
assert ret.result is True
with subtests.test("test=False arch=None repeat"):
# Run for real again, results should be the same as above (i.e. we
# should never get to the point where we exit with a None result).
ret = _run()
assert not ret.changes
assert "already" in ret.comment
assert ret.result is True

View file

@ -1,40 +0,0 @@
import platform
import pytest
import salt.utils.files
@pytest.mark.skipif(
not any([x for x in ["ubuntu", "debian"] if x in platform.platform()]),
reason="Test only for debian based platforms",
)
def test_adding_repo_file(states, tmp_path):
"""
test adding a repo file using pkgrepo.managed
"""
repo_file = str(tmp_path / "stable-binary.list")
repo_content = "deb http://www.deb-multimedia.org stable main"
ret = states.pkgrepo.managed(name=repo_content, file=repo_file, clean_file=True)
with salt.utils.files.fopen(repo_file, "r") as fp:
file_content = fp.read()
assert file_content.strip() == repo_content
@pytest.mark.skipif(
not any([x for x in ["ubuntu", "debian"] if x in platform.platform()]),
reason="Test only for debian based platforms",
)
def test_adding_repo_file_arch(states, tmp_path):
"""
test adding a repo file using pkgrepo.managed
and setting architecture
"""
repo_file = str(tmp_path / "stable-binary.list")
repo_content = "deb [arch=amd64 ] http://www.deb-multimedia.org stable main"
ret = states.pkgrepo.managed(name=repo_content, file=repo_file, clean_file=True)
with salt.utils.files.fopen(repo_file, "r") as fp:
file_content = fp.read()
assert (
file_content.strip()
== "deb [arch=amd64] http://www.deb-multimedia.org stable main"
)