From 9d6b64da4b2e5b56623d675c8cbf01686b53a7b7 Mon Sep 17 00:00:00 2001
From: Michael Calmer <mc@suse.de>
Date: Thu, 23 Jun 2022 10:45:25 +0200
Subject: [PATCH] add support for gpgautoimport to refresh_db in the
 zypperpkg module

call refresh_db function from mod_repo

call refresh_db with kwargs where possible

ignore no repos defined exit code

fix zypperpkg test after adding more success return codes
---
 salt/modules/zypperpkg.py            |  59 +++++++----
 tests/unit/modules/test_zypperpkg.py | 147 +++++++++++++++++++++------
 2 files changed, 160 insertions(+), 46 deletions(-)

diff --git a/salt/modules/zypperpkg.py b/salt/modules/zypperpkg.py
index 4cb99aacdf..e28e0a03af 100644
--- a/salt/modules/zypperpkg.py
+++ b/salt/modules/zypperpkg.py
@@ -535,7 +535,7 @@ def list_upgrades(refresh=True, root=None, **kwargs):
         salt '*' pkg.list_upgrades
     '''
     if refresh:
-        refresh_db(root)
+        refresh_db(root, **kwargs)
 
     ret = dict()
     cmd = ['list-updates']
@@ -646,8 +646,8 @@ def info_available(*names, **kwargs):
     root = kwargs.get('root', None)
 
     # Refresh db before extracting the latest package
-    if kwargs.get('refresh', True):
-        refresh_db(root)
+    if kwargs.get("refresh", True):
+        refresh_db(root, **kwargs)
 
     pkg_info = []
     batch = names[:]
@@ -1315,8 +1315,7 @@ def mod_repo(repo, **kwargs):
     if 'humanname' in kwargs:
         cmd_opt.extend(["--name", kwargs.get("humanname")])
 
-    if kwargs.get('gpgautoimport') is True:
-        global_cmd_opt.append('--gpg-auto-import-keys')
+    if kwargs.get("gpgautoimport") is True:
         call_refresh = True
 
     if cmd_opt:
@@ -1328,8 +1327,8 @@ def mod_repo(repo, **kwargs):
         # when used with "zypper ar --refresh" or "zypper mr --refresh"
         # --gpg-auto-import-keys is not doing anything
         # so we need to specifically refresh here with --gpg-auto-import-keys
-        refresh_opts = global_cmd_opt + ['refresh'] + [repo]
-        __zypper__(root=root).xml.call(*refresh_opts)
+        kwargs.update({"repos": repo})
+        refresh_db(root=root, **kwargs)
     elif not added and not cmd_opt:
         comment = 'Specified arguments did not result in modification of repo'
 
@@ -1340,7 +1339,7 @@ def mod_repo(repo, **kwargs):
     return repo
 
 
-def refresh_db(root=None, force=None):
+def refresh_db(root=None, force=None, **kwargs):
     """
     Trigger a repository refresh by calling ``zypper refresh``. Refresh will run
     with ``--force`` if the "force=True" flag is passed on the CLI or
@@ -1351,6 +1350,20 @@ def refresh_db(root=None, force=None):
 
         {'<database name>': Bool}
 
+    gpgautoimport : False
+        If set to True, automatically trust and import public GPG key for
+        the repository.
+
+        .. versionadded:: 3005
+
+    repos
+        Refresh just the specified repos
+
+        .. versionadded:: 3005
+
+    root
+        operate on a different root directory.
+
     CLI Example:
 
     .. code-block:: bash
@@ -1367,12 +1380,24 @@ def refresh_db(root=None, force=None):
     # Remove rtag file to keep multiple refreshes from happening in pkg states
     salt.utils.pkg.clear_rtag(__opts__)
     ret = {}
-    refresh_opts = ['refresh']
+    refresh_opts = ["refresh"]
+    global_opts = []
     if force is None:
         force = __pillar__.get('zypper', {}).get('refreshdb_force', True)
     if force:
-        refresh_opts.append('--force')
-    out = __zypper__(root=root).refreshable.call(*refresh_opts)
+        refresh_opts.append("--force")
+    repos = kwargs.get("repos", [])
+    refresh_opts.extend([repos] if not isinstance(repos, list) else repos)
+
+    if kwargs.get("gpgautoimport", False):
+        global_opts.append("--gpg-auto-import-keys")
+
+    # We do the actual call to zypper refresh.
+    # We ignore retcode 6 which is returned when there are no repositories defined.
+    final_opts = global_opts + refresh_opts
+    out = __zypper__(root=root).refreshable.call(
+        *final_opts, success_retcodes=[0, 6]
+    )
 
     for line in out.splitlines():
         if not line:
@@ -1556,7 +1581,7 @@ def install(name=None,
                 'arch': '<new-arch>'}}}
     '''
     if refresh:
-        refresh_db(root)
+        refresh_db(root, **kwargs)
 
     try:
         pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
@@ -1798,7 +1823,7 @@ def upgrade(name=None,
         cmd_update.insert(0, '--no-gpg-checks')
 
     if refresh:
-        refresh_db(root)
+        refresh_db(root, **kwargs)
 
     if dryrun:
         cmd_update.append('--dry-run')
@@ -2678,7 +2703,7 @@ def search(criteria, refresh=False, **kwargs):
     root = kwargs.get('root', None)
 
     if refresh:
-        refresh_db(root)
+        refresh_db(root, **kwargs)
 
     cmd = ['search']
     if kwargs.get('match') == 'exact':
@@ -2824,7 +2849,7 @@ def download(*packages, **kwargs):
 
     refresh = kwargs.get('refresh', False)
     if refresh:
-        refresh_db(root)
+        refresh_db(root, **kwargs)
 
     pkg_ret = {}
     for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
@@ -2968,7 +2993,7 @@ def list_patches(refresh=False, root=None, **kwargs):
         salt '*' pkg.list_patches
     '''
     if refresh:
-        refresh_db(root)
+        refresh_db(root, **kwargs)
 
     return _get_patches(root=root)
 
@@ -3060,7 +3085,7 @@ def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
         salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
     '''
     if refresh:
-        refresh_db(root)
+        refresh_db(root, **kwargs)
 
     ret = list()
     for pkg in pkgs:
diff --git a/tests/unit/modules/test_zypperpkg.py b/tests/unit/modules/test_zypperpkg.py
index 85e10292c1..f9a3bbfca1 100644
--- a/tests/unit/modules/test_zypperpkg.py
+++ b/tests/unit/modules/test_zypperpkg.py
@@ -288,7 +288,8 @@ class ZypperTestCase(TestCase, LoaderModuleMockMixin):
         call_kwargs = {
             "output_loglevel": "trace",
             "python_shell": False,
-            "env": {}
+            "env": {},
+            "success_retcodes": [0, 6],
         }
         with patch.dict(zypper.__salt__, {"cmd.run_all": zypper_mock}):
             with patch.object(salt.utils.pkg, "clear_rtag", Mock()):
@@ -310,6 +311,73 @@ class ZypperTestCase(TestCase, LoaderModuleMockMixin):
                     ["zypper", "--non-interactive", "refresh", "--force"],
                     **call_kwargs
                 )
+                zypper.refresh_db(gpgautoimport=True)
+                zypper_mock.assert_called_with(
+                    [
+                        "zypper",
+                        "--non-interactive",
+                        "--gpg-auto-import-keys",
+                        "refresh",
+                        "--force",
+                    ],
+                    **call_kwargs
+                )
+                zypper.refresh_db(gpgautoimport=True, force=True)
+                zypper_mock.assert_called_with(
+                    [
+                        "zypper",
+                        "--non-interactive",
+                        "--gpg-auto-import-keys",
+                        "refresh",
+                        "--force",
+                    ],
+                    **call_kwargs
+                )
+                zypper.refresh_db(gpgautoimport=True, force=False)
+                zypper_mock.assert_called_with(
+                    [
+                        "zypper",
+                        "--non-interactive",
+                        "--gpg-auto-import-keys",
+                        "refresh",
+                    ],
+                    **call_kwargs
+                )
+                zypper.refresh_db(
+                    gpgautoimport=True,
+                    refresh=True,
+                    repos="mock-repo-name",
+                    root=None,
+                    url="http://repo.url/some/path",
+                )
+                zypper_mock.assert_called_with(
+                    [
+                        "zypper",
+                        "--non-interactive",
+                        "--gpg-auto-import-keys",
+                        "refresh",
+                        "--force",
+                        "mock-repo-name",
+                    ],
+                    **call_kwargs
+                )
+                zypper.refresh_db(
+                    gpgautoimport=True,
+                    repos="mock-repo-name",
+                    root=None,
+                    url="http://repo.url/some/path",
+                )
+                zypper_mock.assert_called_with(
+                    [
+                        "zypper",
+                        "--non-interactive",
+                        "--gpg-auto-import-keys",
+                        "refresh",
+                        "--force",
+                        "mock-repo-name",
+                    ],
+                    **call_kwargs
+                )
 
     def test_info_installed(self):
         '''
@@ -1555,18 +1623,25 @@ Repository 'DUMMY' not found by its alias, number, or URI.
         zypper_patcher = patch.multiple(
             'salt.modules.zypperpkg', **self.zypper_patcher_config)
 
-        url = self.new_repo_config['url']
-        name = self.new_repo_config['name']
-        with zypper_patcher:
-            zypper.mod_repo(name, **{'url': url, 'gpgautoimport': True})
+        url = self.new_repo_config["url"]
+        name = self.new_repo_config["name"]
+        with zypper_patcher, patch.object(zypper, "refresh_db", Mock()) as refreshmock:
+            zypper.mod_repo(name, **{"url": url, "gpgautoimport": True})
             self.assertEqual(
                 zypper.__zypper__(root=None).xml.call.call_args_list,
                 [
-                    call('ar', url, name),
-                    call('--gpg-auto-import-keys', 'refresh', name)
-                ]
+                    call("ar", url, name),
+                ],
+            )
+            self.assertTrue(
+                zypper.__zypper__(root=None).refreshable.xml.call.call_count == 0
+            )
+            refreshmock.assert_called_once_with(
+                gpgautoimport=True,
+                repos=name,
+                root=None,
+                url="http://repo.url/some/path",
             )
-            self.assertTrue(zypper.__zypper__(root=None).refreshable.xml.call.call_count == 0)
 
     def test_repo_noadd_nomod_ref(self):
         '''
@@ -1584,13 +1659,17 @@ Repository 'DUMMY' not found by its alias, number, or URI.
         zypper_patcher = patch.multiple(
             'salt.modules.zypperpkg', **self.zypper_patcher_config)
 
-        with zypper_patcher:
-            zypper.mod_repo(name, **{'url': url, 'gpgautoimport': True})
-            self.assertEqual(
-                zypper.__zypper__(root=None).xml.call.call_args_list,
-                [call('--gpg-auto-import-keys', 'refresh', name)]
+        with zypper_patcher, patch.object(zypper, "refresh_db", Mock()) as refreshmock:
+            zypper.mod_repo(name, **{"url": url, "gpgautoimport": True})
+            self.assertTrue(
+                zypper.__zypper__(root=None).refreshable.xml.call.call_count == 0
+            )
+            refreshmock.assert_called_once_with(
+                gpgautoimport=True,
+                repos=name,
+                root=None,
+                url="http://repo.url/some/path",
             )
-            self.assertTrue(zypper.__zypper__(root=None).refreshable.xml.call.call_count == 0)
 
     def test_repo_add_mod_ref(self):
         '''
@@ -1601,11 +1680,12 @@ Repository 'DUMMY' not found by its alias, number, or URI.
         :return:
         '''
         zypper_patcher = patch.multiple(
-            'salt.modules.zypperpkg', **self.zypper_patcher_config)
+            "salt.modules.zypperpkg", **self.zypper_patcher_config
+        )
+        url = self.new_repo_config["url"]
+        name = self.new_repo_config["name"]
 
-        url = self.new_repo_config['url']
-        name = self.new_repo_config['name']
-        with zypper_patcher:
+        with zypper_patcher, patch.object(zypper, "refresh_db", Mock()) as refreshmock:
             zypper.mod_repo(
                 name,
                 **{'url': url, 'refresh': True, 'gpgautoimport': True}
@@ -1613,12 +1693,18 @@ Repository 'DUMMY' not found by its alias, number, or URI.
             self.assertEqual(
                 zypper.__zypper__(root=None).xml.call.call_args_list,
                 [
-                    call('ar', url, name),
-                    call('--gpg-auto-import-keys', 'refresh', name)
-                ]
+                    call("ar", url, name),
+                ],
             )
             zypper.__zypper__(root=None).refreshable.xml.call.assert_called_once_with(
-                '--gpg-auto-import-keys', 'mr', '--refresh', name
+                "mr", "--refresh", name
+            )
+            refreshmock.assert_called_once_with(
+                gpgautoimport=True,
+                refresh=True,
+                repos=name,
+                root=None,
+                url="http://repo.url/some/path",
             )
 
     def test_repo_noadd_mod_ref(self):
@@ -1637,17 +1723,20 @@ Repository 'DUMMY' not found by its alias, number, or URI.
         zypper_patcher = patch.multiple(
             'salt.modules.zypperpkg', **self.zypper_patcher_config)
 
-        with zypper_patcher:
+        with zypper_patcher, patch.object(zypper, "refresh_db", Mock()) as refreshmock:
             zypper.mod_repo(
                 name,
                 **{'url': url, 'refresh': True, 'gpgautoimport': True}
             )
-            self.assertEqual(
-                zypper.__zypper__(root=None).xml.call.call_args_list,
-                [call('--gpg-auto-import-keys', 'refresh', name)]
-            )
             zypper.__zypper__(root=None).refreshable.xml.call.assert_called_once_with(
-                '--gpg-auto-import-keys', 'mr', '--refresh', name
+                "mr", "--refresh", name
+            )
+            refreshmock.assert_called_once_with(
+                gpgautoimport=True,
+                refresh=True,
+                repos=name,
+                root=None,
+                url="http://repo.url/some/path",
             )
 
     def test_wildcard_to_query_match_all(self):
-- 
2.36.1


