"Fossies" - the Fresh Open Source Software Archive

Member "salt-3002.2/tests/unit/modules/test_opkg.py" (18 Nov 2020, 14891 Bytes) of package /linux/misc/salt-3002.2.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. See also the latest Fossies "Diffs" side-by-side code changes report for "test_opkg.py": 3002.1_vs_3002.2.

    1 """
    2     :synopsis: Unit Tests for Package Management module 'module.opkg'
    3     :platform: Linux
    4 """
    5 
    6 import collections
    7 import copy
    8 import os
    9 import textwrap
   10 
   11 import salt.modules.opkg as opkg
   12 import salt.utils.platform
   13 from tests.support.mixins import LoaderModuleMockMixin
   14 from tests.support.mock import MagicMock, mock_open, patch
   15 from tests.support.unit import TestCase, skipIf
   16 
   17 
   18 @skipIf(not salt.utils.platform.is_linux(), "Must be on Linux!")
   19 class OpkgTestCase(TestCase, LoaderModuleMockMixin):
   20     """
   21     Test cases for salt.modules.opkg
   22     """
   23 
   24     @classmethod
   25     def setUpClass(cls):
   26         cls.opkg_vim_info = {
   27             "vim": {
   28                 "Package": "vim",
   29                 "Version": "7.4.769-r0.31",
   30                 "Status": "install ok installed",
   31             }
   32         }
   33         cls.opkg_vim_files = {
   34             "errors": [],
   35             "packages": {
   36                 "vim": [
   37                     "/usr/bin/view",
   38                     "/usr/bin/vim.vim",
   39                     "/usr/bin/xxd",
   40                     "/usr/bin/vimdiff",
   41                     "/usr/bin/rview",
   42                     "/usr/bin/rvim",
   43                     "/usr/bin/ex",
   44                 ]
   45             },
   46         }
   47         cls.installed = {"vim": {"new": "7.4", "old": ""}}
   48         cls.removed = {"vim": {"new": "", "old": "7.4"}}
   49         cls.packages = {"vim": "7.4"}
   50 
   51     @classmethod
   52     def tearDownClass(cls):
   53         cls.opkg_vim_info = (
   54             cls.opkg_vim_files
   55         ) = cls.installed = cls.removed = cls.packages = None
   56 
   57     def setup_loader_modules(self):  # pylint: disable=no-self-use
   58         """
   59         Tested modules
   60         """
   61         return {opkg: {}}
   62 
   63     def test_virtual_ni_linux_rt_system(self):
   64         """
   65         Test - Module virtual name on NI Linux RT
   66         """
   67         with patch.dict(opkg.__grains__, {"os_family": "NILinuxRT"}):
   68             with patch.object(os, "makedirs", MagicMock(return_value=True)):
   69                 with patch.object(os, "listdir", MagicMock(return_value=[])):
   70                     with patch.object(opkg, "_update_nilrt_restart_state", MagicMock()):
   71                         self.assertEqual("pkg", opkg.__virtual__())
   72 
   73     def test_virtual_open_embedded_system(self):
   74         """
   75         Test - Module virtual name on Open Embedded
   76         """
   77         with patch.object(os.path, "isdir", MagicMock(return_value=True)):
   78             self.assertEqual("pkg", opkg.__virtual__())
   79 
   80     def test_virtual_not_supported_system(self):
   81         """
   82         Test - Module not supported
   83         """
   84         with patch.object(os.path, "isdir", MagicMock(return_value=False)):
   85             expected = (False, "Module opkg only works on OpenEmbedded based systems")
   86             self.assertEqual(expected, opkg.__virtual__())
   87 
   88     def test_virtual_update_restart_state_called(self):
   89         """
   90         Test - Update restart state is called when empty dir
   91         """
   92         mock_cmd = MagicMock()
   93         with patch.dict(opkg.__grains__, {"os_family": "NILinuxRT"}):
   94             with patch.object(os, "makedirs", MagicMock(return_value=True)):
   95                 with patch.object(os, "listdir", MagicMock(return_value=[])):
   96                     with patch.object(opkg, "_update_nilrt_restart_state", mock_cmd):
   97                         opkg.__virtual__()
   98                         mock_cmd.assert_called_once()
   99 
  100     def test_virtual_update_restart_state_not_called(self):
  101         """
  102         Test - Update restart state is not called when dir contains files
  103         """
  104         mock_cmd = MagicMock()
  105         with patch.dict(opkg.__grains__, {"os_family": "NILinuxRT"}):
  106             with patch.object(os, "makedirs", MagicMock(return_value=True)):
  107                 with patch.object(os, "listdir", MagicMock(return_value=["test"])):
  108                     with patch.object(opkg, "_update_nilrt_restart_state", mock_cmd):
  109                         opkg.__virtual__()
  110                         mock_cmd.assert_not_called()
  111 
  112     def test_version(self):
  113         """
  114         Test - Returns a string representing the package version or an empty string if
  115         not installed.
  116         """
  117         version = self.opkg_vim_info["vim"]["Version"]
  118         mock = MagicMock(return_value=version)
  119         with patch.dict(opkg.__salt__, {"pkg_resource.version": mock}):
  120             self.assertEqual(opkg.version(*["vim"]), version)
  121 
  122     def test_upgrade_available(self):
  123         """
  124         Test - Check whether or not an upgrade is available for a given package.
  125         """
  126         with patch("salt.modules.opkg.latest_version", MagicMock(return_value="")):
  127             self.assertFalse(opkg.upgrade_available("vim"))
  128 
  129     def test_file_dict(self):
  130         """
  131         Test - List the files that belong to a package, grouped by package.
  132         """
  133         std_out = "\n".join(self.opkg_vim_files["packages"]["vim"])
  134         ret_value = {"stdout": std_out}
  135         mock = MagicMock(return_value=ret_value)
  136         with patch.dict(opkg.__salt__, {"cmd.run_all": mock}):
  137             self.assertEqual(opkg.file_dict("vim"), self.opkg_vim_files)
  138 
  139     def test_file_list(self):
  140         """
  141         Test - List the files that belong to a package.
  142         """
  143         std_out = "\n".join(self.opkg_vim_files["packages"]["vim"])
  144         ret_value = {"stdout": std_out}
  145         mock = MagicMock(return_value=ret_value)
  146         files = {
  147             "errors": self.opkg_vim_files["errors"],
  148             "files": self.opkg_vim_files["packages"]["vim"],
  149         }
  150         with patch.dict(opkg.__salt__, {"cmd.run_all": mock}):
  151             self.assertEqual(opkg.file_list("vim"), files)
  152 
  153     def test_owner(self):
  154         """
  155         Test - Return the name of the package that owns the file.
  156         """
  157         paths = ["/usr/bin/vimdiff"]
  158         mock = MagicMock(return_value="vim - version - info")
  159         with patch.dict(opkg.__salt__, {"cmd.run_stdout": mock}):
  160             self.assertEqual(opkg.owner(*paths), "vim")
  161 
  162     def test_install(self):
  163         """
  164         Test - Install packages.
  165         """
  166         with patch(
  167             "salt.modules.opkg.list_pkgs", MagicMock(side_effect=[{}, self.packages])
  168         ):
  169             ret_value = {"retcode": 0}
  170             mock = MagicMock(return_value=ret_value)
  171             patch_kwargs = {
  172                 "__salt__": {
  173                     "cmd.run_all": mock,
  174                     "pkg_resource.parse_targets": MagicMock(
  175                         return_value=({"vim": "7.4"}, "repository")
  176                     ),
  177                     "restartcheck.restartcheck": MagicMock(
  178                         return_value="No packages seem to need to be restarted"
  179                     ),
  180                 }
  181             }
  182             with patch.multiple(opkg, **patch_kwargs):
  183                 self.assertEqual(opkg.install("vim:7.4"), self.installed)
  184 
  185     def test_install_noaction(self):
  186         """
  187         Test - Install packages.
  188         """
  189         with patch("salt.modules.opkg.list_pkgs", MagicMock(side_effect=({}, {}))):
  190             std_out = "Downloading http://feedserver/feeds/test/vim_7.4_arch.ipk.\n\nInstalling vim (7.4) on root\n"
  191             ret_value = {"retcode": 0, "stdout": std_out}
  192             mock = MagicMock(return_value=ret_value)
  193             patch_kwargs = {
  194                 "__salt__": {
  195                     "cmd.run_all": mock,
  196                     "pkg_resource.parse_targets": MagicMock(
  197                         return_value=({"vim": "7.4"}, "repository")
  198                     ),
  199                     "restartcheck.restartcheck": MagicMock(
  200                         return_value="No packages seem to need to be restarted"
  201                     ),
  202                 }
  203             }
  204             with patch.multiple(opkg, **patch_kwargs):
  205                 self.assertEqual(opkg.install("vim:7.4", test=True), self.installed)
  206 
  207     def test_remove(self):
  208         """
  209         Test - Remove packages.
  210         """
  211         with patch(
  212             "salt.modules.opkg.list_pkgs", MagicMock(side_effect=[self.packages, {}])
  213         ):
  214             ret_value = {"retcode": 0}
  215             mock = MagicMock(return_value=ret_value)
  216             patch_kwargs = {
  217                 "__salt__": {
  218                     "cmd.run_all": mock,
  219                     "pkg_resource.parse_targets": MagicMock(
  220                         return_value=({"vim": "7.4"}, "repository")
  221                     ),
  222                     "restartcheck.restartcheck": MagicMock(
  223                         return_value="No packages seem to need to be restarted"
  224                     ),
  225                 }
  226             }
  227             with patch.multiple(opkg, **patch_kwargs):
  228                 self.assertEqual(opkg.remove("vim"), self.removed)
  229 
  230     def test_remove_noaction(self):
  231         """
  232         Test - Remove packages.
  233         """
  234         with patch(
  235             "salt.modules.opkg.list_pkgs",
  236             MagicMock(side_effect=[self.packages, self.packages]),
  237         ):
  238             std_out = "\nRemoving vim (7.4) from root...\n"
  239             ret_value = {"retcode": 0, "stdout": std_out}
  240             mock = MagicMock(return_value=ret_value)
  241             patch_kwargs = {
  242                 "__salt__": {
  243                     "cmd.run_all": mock,
  244                     "pkg_resource.parse_targets": MagicMock(
  245                         return_value=({"vim": "7.4"}, "repository")
  246                     ),
  247                     "restartcheck.restartcheck": MagicMock(
  248                         return_value="No packages seem to need to be restarted"
  249                     ),
  250                 }
  251             }
  252             with patch.multiple(opkg, **patch_kwargs):
  253                 self.assertEqual(opkg.remove("vim:7.4", test=True), self.removed)
  254 
  255     def test_info_installed(self):
  256         """
  257         Test - Return the information of the named package(s) installed on the system.
  258         """
  259         installed = copy.deepcopy(self.opkg_vim_info["vim"])
  260         del installed["Package"]
  261         ordered_info = collections.OrderedDict(sorted(installed.items()))
  262         expected_dict = {"vim": {k.lower(): v for k, v in ordered_info.items()}}
  263         std_out = "\n".join(
  264             [k + ": " + v for k, v in self.opkg_vim_info["vim"].items()]
  265         )
  266         ret_value = {"stdout": std_out, "retcode": 0}
  267         mock = MagicMock(return_value=ret_value)
  268         with patch.dict(opkg.__salt__, {"cmd.run_all": mock}):
  269             self.assertEqual(opkg.info_installed("vim"), expected_dict)
  270 
  271     def test_version_clean(self):
  272         """
  273         Test - Return the information of version_clean
  274         """
  275         self.assertEqual(opkg.version_clean("1.0.1"), "1.0.1")
  276 
  277     def test_check_extra_requirements(self):
  278         """
  279         Test - Return the information of check_extra_requirements
  280         """
  281         self.assertEqual(opkg.check_extra_requirements("vim", "1.0.1"), True)
  282 
  283     def _get_repo(self, enabled, compressed, name, uri, file, trusted=None):
  284         feed = {
  285             "enabled": enabled,
  286             "compressed": compressed,
  287             "name": name,
  288             "uri": uri,
  289             "file": file,
  290         }
  291         if trusted is not None:
  292             feed["trusted"] = trusted
  293         return feed
  294 
  295     def test_list_repos(self):
  296         feeds_content = textwrap.dedent(
  297             """\
  298             src/gz   name1     url1
  299             src   name2     url2
  300             #src/gz   name3     url3
  301             src/gz   name4     url4 [trusted=yes]
  302             src/gz   "name5 space"    url5 [trusted=no]
  303             """
  304         )
  305         expected_feed1 = self._get_repo(
  306             True, True, "name1", "url1", "/etc/opkg/test.conf"
  307         )
  308         expected_feed2 = self._get_repo(
  309             True, False, "name2", "url2", "/etc/opkg/test.conf"
  310         )
  311         expected_feed3 = self._get_repo(
  312             False, True, "name3", "url3", "/etc/opkg/test.conf"
  313         )
  314         expected_feed4 = self._get_repo(
  315             True, True, "name4", "url4", "/etc/opkg/test.conf", True
  316         )
  317         expected_feed5 = self._get_repo(
  318             True, True, "name5 space", "url5", "/etc/opkg/test.conf", False
  319         )
  320 
  321         file_mock = mock_open(read_data={"/etc/opkg/test.conf": feeds_content})
  322         with patch.object(
  323             opkg.os, "listdir", MagicMock(return_value=["test.conf", "test"])
  324         ):
  325             with patch.object(opkg.salt.utils.files, "fopen", file_mock):
  326                 repos = opkg.list_repos()
  327                 self.assertDictEqual(expected_feed1, repos["url1"][0])
  328                 self.assertDictEqual(expected_feed2, repos["url2"][0])
  329                 self.assertDictEqual(expected_feed3, repos["url3"][0])
  330                 self.assertDictEqual(expected_feed4, repos["url4"][0])
  331                 self.assertDictEqual(expected_feed5, repos["url5"][0])
  332 
  333     def test_mod_repo_add_new_repo(self):
  334         kwargs = {"uri": "url", "compressed": True, "enabled": True, "trusted": True}
  335         file_mock = mock_open()
  336         expected = "src/gz repo url [trusted=yes]\n"
  337         with patch.object(opkg, "list_repos", MagicMock(return_value=[])):
  338             with patch.object(opkg.salt.utils.files, "fopen", file_mock):
  339                 opkg.mod_repo("repo", **kwargs)
  340                 handle = file_mock.filehandles["/etc/opkg/repo.conf"][0]
  341                 handle.write.assert_called_once_with(expected)
  342 
  343     def test_mod_repo_set_trusted(self):
  344         file_content = textwrap.dedent(
  345             """\
  346             src/gz   repo     url
  347             """
  348         )
  349         file_mock = mock_open(read_data={"/etc/opkg/repo.conf": file_content})
  350         kwargs = {"trusted": True}
  351         expected = "src/gz repo url [trusted=yes]\n"
  352         with patch.object(opkg.os, "listdir", MagicMock(return_value=["repo.conf"])):
  353             with patch.object(opkg.salt.utils.files, "fopen", file_mock):
  354                 opkg.mod_repo("repo", **kwargs)
  355                 handle = file_mock.filehandles["/etc/opkg/repo.conf"][2]
  356                 handle.writelines.assert_called_once_with([expected])
  357 
  358     def test_mod_repo_repo_exists(self):
  359         file_content = textwrap.dedent(
  360             """\
  361             src/gz   repo     url
  362             """
  363         )
  364         file_mock = mock_open(read_data={"/etc/opkg/repo.conf": file_content})
  365         kwargs = {"uri": "url"}
  366         expected = "Repository 'url' already exists as 'repo'."
  367         with patch.object(opkg.os, "listdir", MagicMock(return_value=["repo.conf"])):
  368             with patch.object(opkg.salt.utils.files, "fopen", file_mock):
  369                 with self.assertRaisesRegex(opkg.CommandExecutionError, expected):
  370                     opkg.mod_repo("repo2", **kwargs)
  371 
  372     def test_mod_repo_uri_not_provided(self):
  373         expected = "Repository 'repo' not found and no URI passed to create one."
  374         with patch.object(opkg, "list_repos", MagicMock(return_value=[])):
  375             with self.assertRaisesRegex(opkg.CommandExecutionError, expected):
  376                 opkg.mod_repo("repo")