How to use os_info method in lisa

Best Python code snippet using lisa_python

system_pm_test.py

Source:system_pm_test.py Github

copy

Full Screen

1import mock2import platform3import six4import unittest5from six import StringIO6from conans import tools7from conans.client.output import ConanOutput8from conans.client.tools.files import which9from conans.client.tools.oss import OSInfo10from conans.client.tools.system_pm import ChocolateyTool, SystemPackageTool, AptTool11from conans.errors import ConanException, ConanInvalidSystemRequirements12from conans.test.unittests.util.tools_test import RunnerMock13from conans.test.utils.mocks import MockSettings, MockConanfile, TestBufferConanOutput14class RunnerMultipleMock(object):15 def __init__(self, expected=None):16 self.calls = 017 self.expected = expected18 def __call__(self, command, *args, **kwargs): # @UnusedVariable19 self.calls += 120 return 0 if command in self.expected else 121class SystemPackageToolTest(unittest.TestCase):22 def setUp(self):23 self.out = TestBufferConanOutput()24 def test_sudo_tty(self):25 with tools.environment_append({"CONAN_SYSREQUIRES_SUDO": "False"}):26 self.assertFalse(SystemPackageTool._is_sudo_enabled())27 self.assertEqual(SystemPackageTool._get_sudo_str(), "")28 with tools.environment_append({"CONAN_SYSREQUIRES_SUDO": "True"}):29 self.assertTrue(SystemPackageTool._is_sudo_enabled())30 self.assertEqual(SystemPackageTool._get_sudo_str(), "sudo -A ")31 with mock.patch("sys.stdout.isatty", return_value=True):32 self.assertEqual(SystemPackageTool._get_sudo_str(), "sudo ")33 def test_system_without_sudo(self):34 with mock.patch("os.path.isfile", return_value=False):35 self.assertFalse(SystemPackageTool._is_sudo_enabled())36 self.assertEqual(SystemPackageTool._get_sudo_str(), "")37 with mock.patch("sys.stdout.isatty", return_value=True):38 self.assertEqual(SystemPackageTool._get_sudo_str(), "")39 def test_verify_update(self):40 # https://github.com/conan-io/conan/issues/314241 with tools.environment_append({"CONAN_SYSREQUIRES_SUDO": "False",42 "CONAN_SYSREQUIRES_MODE": "Verify"}):43 runner = RunnerMock()44 # fake os info to linux debian, default sudo45 os_info = OSInfo()46 os_info.is_macos = False47 os_info.is_linux = True48 os_info.is_windows = False49 os_info.linux_distro = "debian"50 spt = SystemPackageTool(runner=runner, os_info=os_info, output=self.out)51 spt.update()52 self.assertEqual(runner.command_called, None)53 self.assertIn('Not updating system_requirements. CONAN_SYSREQUIRES_MODE=verify',54 self.out)55 # We gotta mock the with_apt property, since it checks for the existence of apt.56 @mock.patch('conans.client.tools.oss.OSInfo.with_apt', new_callable=mock.PropertyMock)57 def test_add_repositories_exception_cases(self, patched_with_apt):58 os_info = OSInfo()59 os_info.is_macos = False60 os_info.is_linux = True61 os_info.is_windows = False62 os_info.linux_distro = "fedora" # Will instantiate DnfTool63 patched_with_apt.return_value = False64 with six.assertRaisesRegex(self, ConanException, "add_repository not implemented"):65 new_out = StringIO()66 spt = SystemPackageTool(os_info=os_info, output=ConanOutput(new_out))67 spt.add_repository(repository="deb http://repo/url/ saucy universe multiverse",68 repo_key=None)69 @mock.patch('conans.client.tools.oss.OSInfo.with_apt', new_callable=mock.PropertyMock)70 def test_add_repository(self, patched_with_apt):71 class RunnerOrderedMock:72 commands = [] # Command + return value73 def __call__(runner_self, command, output, win_bash=False, subsystem=None):74 if not len(runner_self.commands):75 self.fail("Commands list exhausted, but runner called with '%s'" % command)76 expected, ret = runner_self.commands.pop(0)77 self.assertEqual(expected, command)78 return ret79 def _run_add_repository_test(repository, gpg_key, sudo, isatty, update):80 sudo_cmd = ""81 if sudo:82 sudo_cmd = "sudo " if isatty else "sudo -A "83 runner = RunnerOrderedMock()84 if gpg_key:85 runner.commands.append(86 ("wget -qO - {} | {}apt-key add -".format(gpg_key, sudo_cmd), 0))87 runner.commands.append(("{}apt-add-repository {}".format(sudo_cmd, repository), 0))88 if update:89 runner.commands.append(("{}apt-get update".format(sudo_cmd), 0))90 with tools.environment_append({"CONAN_SYSREQUIRES_SUDO": str(sudo)}):91 os_info = OSInfo()92 os_info.is_macos = False93 os_info.is_linux = True94 os_info.is_windows = False95 os_info.linux_distro = "debian"96 patched_with_apt.return_value = True97 new_out = StringIO()98 spt = SystemPackageTool(runner=runner, os_info=os_info, output=ConanOutput(new_out))99 spt.add_repository(repository=repository, repo_key=gpg_key, update=update)100 self.assertEqual(len(runner.commands), 0)101 # Run several test cases102 repository = "deb http://repo/url/ saucy universe multiverse"103 gpg_key = 'http://one/key.gpg'104 _run_add_repository_test(repository, gpg_key, sudo=True, isatty=False, update=True)105 _run_add_repository_test(repository, gpg_key, sudo=True, isatty=False, update=False)106 _run_add_repository_test(repository, gpg_key, sudo=False, isatty=False, update=True)107 _run_add_repository_test(repository, gpg_key, sudo=False, isatty=False, update=False)108 _run_add_repository_test(repository, gpg_key=None, sudo=True, isatty=False, update=True)109 _run_add_repository_test(repository, gpg_key=None, sudo=False, isatty=True, update=False)110 with mock.patch("sys.stdout.isatty", return_value=True):111 _run_add_repository_test(repository, gpg_key, sudo=True, isatty=True, update=True)112 # We gotta mock the with_apt property, since it checks for the existence of apt.113 @mock.patch('conans.client.tools.oss.OSInfo.with_apt', new_callable=mock.PropertyMock)114 def test_system_package_tool(self, patched_with_apt):115 with tools.environment_append({"CONAN_SYSREQUIRES_SUDO": "True"}):116 runner = RunnerMock()117 # fake os info to linux debian, default sudo118 os_info = OSInfo()119 os_info.is_macos = False120 os_info.is_linux = True121 os_info.is_windows = False122 patched_with_apt.return_value = True123 os_info.linux_distro = "debian"124 spt = SystemPackageTool(runner=runner, os_info=os_info, output=self.out)125 spt.update()126 self.assertEqual(runner.command_called, "sudo -A apt-get update")127 os_info.linux_distro = "ubuntu"128 spt = SystemPackageTool(runner=runner, os_info=os_info, output=self.out)129 spt.update()130 self.assertEqual(runner.command_called, "sudo -A apt-get update")131 os_info.linux_distro = "knoppix"132 spt = SystemPackageTool(runner=runner, os_info=os_info, output=self.out)133 spt.update()134 self.assertEqual(runner.command_called, "sudo -A apt-get update")135 os_info.linux_distro = "neon"136 spt = SystemPackageTool(runner=runner, os_info=os_info, output=self.out)137 spt.update()138 self.assertEqual(runner.command_called, "sudo -A apt-get update")139 # We'll be testing non-Ubuntu and non-Debian-based distros.140 patched_with_apt.return_value = False141 with mock.patch("conans.client.tools.oss.which", return_value=True):142 os_info.linux_distro = "fedora"143 spt = SystemPackageTool(runner=runner, os_info=os_info, output=self.out)144 spt.update()145 self.assertEqual(runner.command_called, "sudo -A dnf check-update -y")146 # Without DNF in the path,147 os_info.linux_distro = "fedora"148 spt = SystemPackageTool(runner=runner, os_info=os_info, output=self.out)149 spt.update()150 self.assertEqual(runner.command_called, "sudo -A yum check-update -y")151 os_info.linux_distro = "opensuse"152 spt = SystemPackageTool(runner=runner, os_info=os_info, output=self.out)153 spt.update()154 self.assertEqual(runner.command_called, "sudo -A zypper --non-interactive ref")155 os_info.linux_distro = "redhat"156 spt = SystemPackageTool(runner=runner, os_info=os_info, output=self.out)157 spt.install("a_package", force=False)158 self.assertEqual(runner.command_called, "rpm -q a_package")159 spt.install("a_package", force=True)160 self.assertEqual(runner.command_called, "sudo -A yum install -y a_package")161 settings = MockSettings({"arch": "x86", "arch_build": "x86_64", "os": "Linux",162 "os_build": "Linux"})163 conanfile = MockConanfile(settings)164 spt = SystemPackageTool(runner=runner, os_info=os_info, output=self.out,165 conanfile=conanfile)166 spt.install("a_package", force=False)167 self.assertEqual(runner.command_called, "rpm -q a_package.i?86")168 spt.install("a_package", force=True)169 self.assertEqual(runner.command_called, "sudo -A yum install -y a_package.i?86")170 os_info.linux_distro = "debian"171 patched_with_apt.return_value = True172 spt = SystemPackageTool(runner=runner, os_info=os_info, output=self.out)173 with self.assertRaises(ConanException):174 runner.return_ok = False175 spt.install("a_package")176 self.assertEqual(runner.command_called,177 "sudo -A apt-get install -y --no-install-recommends a_package")178 runner.return_ok = True179 spt.install("a_package", force=False)180 self.assertEqual(runner.command_called,181 'dpkg-query -W -f=\'${Status}\' a_package | grep -q "ok installed"')182 os_info.is_macos = True183 os_info.is_linux = False184 os_info.is_windows = False185 patched_with_apt.return_value = False186 spt = SystemPackageTool(runner=runner, os_info=os_info, output=self.out)187 spt.update()188 self.assertEqual(runner.command_called, "brew update")189 spt.install("a_package", force=True)190 self.assertEqual(runner.command_called, "brew install a_package")191 os_info.is_freebsd = True192 os_info.is_macos = False193 patched_with_apt.return_value = False194 spt = SystemPackageTool(runner=runner, os_info=os_info, output=self.out)195 spt.update()196 self.assertEqual(runner.command_called, "sudo -A pkg update")197 spt.install("a_package", force=True)198 self.assertEqual(runner.command_called, "sudo -A pkg install -y a_package")199 spt.install("a_package", force=False)200 self.assertEqual(runner.command_called, "pkg info a_package")201 # Chocolatey is an optional package manager on Windows202 if platform.system() == "Windows" and which("choco.exe"):203 os_info.is_freebsd = False204 os_info.is_windows = True205 patched_with_apt.return_value = False206 spt = SystemPackageTool(runner=runner, os_info=os_info, output=self.out,207 tool=ChocolateyTool(output=self.out))208 spt.update()209 self.assertEqual(runner.command_called, "choco outdated")210 spt.install("a_package", force=True)211 self.assertEqual(runner.command_called, "choco install --yes a_package")212 spt.install("a_package", force=False)213 self.assertEqual(runner.command_called,214 'choco search --local-only --exact a_package | '215 'findstr /c:"1 packages installed."')216 with tools.environment_append({"CONAN_SYSREQUIRES_SUDO": "False"}):217 os_info = OSInfo()218 os_info.is_linux = True219 os_info.linux_distro = "redhat"220 patched_with_apt.return_value = False221 spt = SystemPackageTool(runner=runner, os_info=os_info, output=self.out)222 spt.install("a_package", force=True)223 self.assertEqual(runner.command_called, "yum install -y a_package")224 spt.update()225 self.assertEqual(runner.command_called, "yum check-update -y")226 os_info.linux_distro = "ubuntu"227 patched_with_apt.return_value = True228 spt = SystemPackageTool(runner=runner, os_info=os_info, output=self.out)229 spt.install("a_package", force=True)230 self.assertEqual(runner.command_called,231 "apt-get install -y --no-install-recommends a_package")232 spt.update()233 self.assertEqual(runner.command_called, "apt-get update")234 for arch, distro_arch in {"x86_64": "", "x86": ":i386", "ppc32": ":powerpc",235 "ppc64le": ":ppc64el", "armv7": ":arm", "armv7hf": ":armhf",236 "armv8": ":arm64", "s390x": ":s390x"}.items():237 settings = MockSettings({"arch": arch,238 "arch_build": "x86_64",239 "os": "Linux",240 "os_build": "Linux"})241 conanfile = MockConanfile(settings)242 spt = SystemPackageTool(runner=runner, os_info=os_info, output=self.out,243 conanfile=conanfile)244 spt.install("a_package", force=True)245 self.assertEqual(runner.command_called,246 "apt-get install -y --no-install-recommends a_package%s" % distro_arch)247 for arch, distro_arch in {"x86_64": "", "x86": ":all"}.items():248 settings = MockSettings({"arch": arch,249 "arch_build": "x86_64",250 "os": "Linux",251 "os_build": "Linux"})252 conanfile = MockConanfile(settings)253 spt = SystemPackageTool(runner=runner, os_info=os_info, output=self.out,254 conanfile=conanfile)255 spt.install("a_package", force=True, arch_names={"x86": "all"})256 self.assertEqual(runner.command_called,257 "apt-get install -y --no-install-recommends a_package%s" % distro_arch)258 os_info.is_macos = True259 os_info.is_linux = False260 os_info.is_windows = False261 patched_with_apt.return_value = False262 spt = SystemPackageTool(runner=runner, os_info=os_info, output=self.out)263 spt.update()264 self.assertEqual(runner.command_called, "brew update")265 spt.install("a_package", force=True)266 self.assertEqual(runner.command_called, "brew install a_package")267 os_info.is_freebsd = True268 os_info.is_macos = False269 os_info.is_windows = False270 patched_with_apt.return_value = False271 spt = SystemPackageTool(runner=runner, os_info=os_info, output=self.out)272 spt.update()273 self.assertEqual(runner.command_called, "pkg update")274 spt.install("a_package", force=True)275 self.assertEqual(runner.command_called, "pkg install -y a_package")276 spt.install("a_package", force=False)277 self.assertEqual(runner.command_called, "pkg info a_package")278 os_info.is_solaris = True279 os_info.is_freebsd = False280 os_info.is_windows = False281 patched_with_apt.return_value = False282 spt = SystemPackageTool(runner=runner, os_info=os_info, output=self.out)283 spt.update()284 self.assertEqual(runner.command_called, "pkgutil --catalog")285 spt.install("a_package", force=True)286 self.assertEqual(runner.command_called, "pkgutil --install --yes a_package")287 with tools.environment_append({"CONAN_SYSREQUIRES_SUDO": "True"}):288 # Chocolatey is an optional package manager on Windows289 if platform.system() == "Windows" and which("choco.exe"):290 os_info.is_solaris = False291 os_info.is_windows = True292 patched_with_apt.return_value = False293 spt = SystemPackageTool(runner=runner, os_info=os_info, output=self.out,294 tool=ChocolateyTool(output=self.out))295 spt.update()296 self.assertEqual(runner.command_called, "choco outdated")297 spt.install("a_package", force=True)298 self.assertEqual(runner.command_called, "choco install --yes a_package")299 spt.install("a_package", force=False)300 self.assertEqual(runner.command_called,301 'choco search --local-only --exact a_package | '302 'findstr /c:"1 packages installed."')303 def test_opensuse_zypper_aptitude(self):304 # https://github.com/conan-io/conan/issues/8737305 os_info = OSInfo()306 os_info.is_linux = True307 os_info.is_solaris = False308 os_info.is_macos = False309 os_info.is_windows = False310 os_info.linux_distro = "opensuse"311 runner = RunnerMock()312 with tools.environment_append({"CONAN_SYSREQUIRES_SUDO": "False"}):313 spt = SystemPackageTool(runner=runner, os_info=os_info, output=self.out)314 spt.update()315 self.assertEqual(runner.command_called, "zypper --non-interactive ref")316 def test_system_package_tool_try_multiple(self):317 packages = ["a_package", "another_package", "yet_another_package"]318 with tools.environment_append({"CONAN_SYSREQUIRES_SUDO": "True"}):319 runner = RunnerMultipleMock(['dpkg-query -W -f=\'${Status}\' another_package | '320 'grep -q "ok installed"'])321 spt = SystemPackageTool(runner=runner, tool=AptTool(output=self.out), output=self.out)322 spt.install(packages)323 self.assertEqual(2, runner.calls)324 runner = RunnerMultipleMock(["sudo -A apt-get update",325 "sudo -A apt-get install -y --no-install-recommends"326 " yet_another_package"])327 spt = SystemPackageTool(runner=runner, tool=AptTool(output=self.out), output=self.out)328 spt.install(packages)329 self.assertEqual(7, runner.calls)330 runner = RunnerMultipleMock(["sudo -A apt-get update"])331 spt = SystemPackageTool(runner=runner, tool=AptTool(output=self.out), output=self.out)332 with self.assertRaises(ConanException):333 spt.install(packages)334 self.assertEqual(7, runner.calls)335 def test_system_package_tool_mode(self):336 """337 System Package Tool mode is defined by CONAN_SYSREQUIRES_MODE env variable.338 Allowed values: (enabled, verify, disabled). Parser accepts it in lower/upper339 case or any combination.340 """341 packages = ["a_package", "another_package", "yet_another_package"]342 # Check invalid mode raises ConanException343 with tools.environment_append({344 "CONAN_SYSREQUIRES_MODE": "test_not_valid_mode",345 "CONAN_SYSREQUIRES_SUDO": "True"346 }):347 runner = RunnerMultipleMock([])348 spt = SystemPackageTool(runner=runner, tool=AptTool(output=self.out), output=self.out)349 with self.assertRaises(ConanException) as exc:350 spt.install(packages)351 self.assertIn("CONAN_SYSREQUIRES_MODE=test_not_valid_mode is not allowed",352 str(exc.exception))353 self.assertEqual(0, runner.calls)354 # Check verify mode, a package report should be shown in output and ConanException raised.355 # No system packages are installed356 with tools.environment_append({357 "CONAN_SYSREQUIRES_MODE": "VeRiFy",358 "CONAN_SYSREQUIRES_SUDO": "True"359 }):360 packages = ["verify_package", "verify_another_package", "verify_yet_another_package"]361 runner = RunnerMultipleMock(["sudo -A apt-get update"])362 spt = SystemPackageTool(runner=runner, tool=AptTool(output=self.out), output=self.out)363 with self.assertRaises(ConanInvalidSystemRequirements) as exc:364 spt.install(packages)365 self.assertIn("Aborted due to CONAN_SYSREQUIRES_MODE=", str(exc.exception))366 self.assertIn('\n'.join(packages), self.out)367 self.assertEqual(3, runner.calls)368 # Check disabled mode, a package report should be displayed in output.369 # No system packages are installed370 with tools.environment_append({371 "CONAN_SYSREQUIRES_MODE": "DiSaBlEd",372 "CONAN_SYSREQUIRES_SUDO": "True"373 }):374 packages = ["disabled_package", "disabled_another_package",375 "disabled_yet_another_package"]376 runner = RunnerMultipleMock(["sudo -A apt-get update"])377 spt = SystemPackageTool(runner=runner, tool=AptTool(output=self.out), output=self.out)378 spt.install(packages)379 self.assertIn('\n'.join(packages), self.out)380 self.assertEqual(0, runner.calls)381 # Check enabled, default mode, system packages must be installed.382 with tools.environment_append({383 "CONAN_SYSREQUIRES_MODE": "EnAbLeD",384 "CONAN_SYSREQUIRES_SUDO": "True"385 }):386 runner = RunnerMultipleMock(["sudo -A apt-get update"])387 spt = SystemPackageTool(runner=runner, tool=AptTool(output=self.out), output=self.out)388 with self.assertRaises(ConanException) as exc:389 spt.install(packages)390 self.assertNotIn("CONAN_SYSREQUIRES_MODE", str(exc.exception))391 self.assertEqual(7, runner.calls)392 # Check default_mode. The environment variable is not set and should behave like393 # the default_mode394 with tools.environment_append({395 "CONAN_SYSREQUIRES_MODE": None,396 "CONAN_SYSREQUIRES_SUDO": "True"397 }):398 packages = ["verify_package", "verify_another_package", "verify_yet_another_package"]399 runner = RunnerMultipleMock(["sudo -A apt-get update"])400 spt = SystemPackageTool(runner=runner, tool=AptTool(output=self.out), output=self.out,401 default_mode="verify")402 with self.assertRaises(ConanInvalidSystemRequirements) as exc:403 spt.install(packages)404 self.assertIn("Aborted due to CONAN_SYSREQUIRES_MODE=", str(exc.exception))405 self.assertIn('\n'.join(packages), self.out)406 self.assertEqual(3, runner.calls)407 def test_system_package_tool_installed(self):408 if (platform.system() != "Linux" and platform.system() != "Macos" and409 platform.system() != "Windows"):410 return411 if platform.system() == "Windows" and not which("choco.exe"):412 return413 spt = SystemPackageTool(output=self.out)414 expected_package = "git"415 if platform.system() == "Windows" and which("choco.exe"):416 spt = SystemPackageTool(tool=ChocolateyTool(output=self.out), output=self.out)417 # Git is not installed by default on Chocolatey418 expected_package = "chocolatey"419 else:420 if platform.system() != "Windows" and not which("git"):421 return422 # The expected should be installed on development/testing machines423 self.assertTrue(spt._tool.installed(expected_package))424 self.assertTrue(spt.installed(expected_package))425 # This package hopefully doesn't exist426 self.assertFalse(spt._tool.installed("oidfjgesiouhrgioeurhgielurhgaeiorhgioearhgoaeirhg"))427 self.assertFalse(spt.installed("oidfjgesiouhrgioeurhgielurhgaeiorhgioearhgoaeirhg"))428 def test_system_package_tool_fail_when_not_0_returned(self):429 def get_linux_error_message():430 """431 Get error message for Linux platform if distro is supported, None otherwise432 """433 os_info = OSInfo()434 update_command = None435 if os_info.with_apt:436 update_command = "sudo -A apt-get update"437 elif os_info.with_yum:438 update_command = "sudo -A yum check-update -y"439 elif os_info.with_dnf:440 update_command = "sudo -A dnf check-update -y"441 elif os_info.with_zypper:442 update_command = "sudo -A zypper --non-interactive ref"443 elif os_info.with_pacman:444 update_command = "sudo -A pacman -Syyu --noconfirm"445 return ("Command '{0}' failed".format(update_command)446 if update_command is not None else None)447 platform_update_error_msg = {448 "Linux": get_linux_error_message(),449 "Darwin": "Command 'brew update' failed",450 "Windows": "Command 'choco outdated' failed" if which("choco.exe") else None,451 }452 runner = RunnerMock(return_ok=False)453 output = ConanOutput(StringIO())454 pkg_tool = ChocolateyTool(output=output) if which("choco.exe") else None455 spt = SystemPackageTool(runner=runner, tool=pkg_tool, output=output)456 msg = platform_update_error_msg.get(platform.system(), None)457 if msg is not None:458 with six.assertRaisesRegex(self, ConanException, msg):459 spt.update()460 else:461 spt.update() # Won't raise anything because won't do anything462 def test_install_all_packages(self):463 """ SystemPackageTool must install all packages464 """465 # No packages installed466 packages = ["a_package", "another_package", "yet_another_package"]467 with tools.environment_append({"CONAN_SYSREQUIRES_SUDO": "True"}):468 runner = RunnerMultipleMock(["sudo -A apt-get update",469 "sudo -A apt-get install -y --no-install-recommends"470 " a_package another_package yet_another_package",471 ])472 spt = SystemPackageTool(runner=runner, tool=AptTool(output=self.out), output=self.out)473 spt.install_packages(packages)474 self.assertEqual(5, runner.calls)475 def test_install_few_packages(self):476 """ SystemPackageTool must install 2 packages only477 """478 packages = ["a_package", "another_package", "yet_another_package"]479 with tools.environment_append({"CONAN_SYSREQUIRES_SUDO": "True"}):480 runner = RunnerMultipleMock(['dpkg-query -W -f=\'${Status}\' a_package | '481 'grep -q "ok installed"',482 "sudo -A apt-get update",483 "sudo -A apt-get install -y --no-install-recommends"484 " another_package yet_another_package",485 ])486 spt = SystemPackageTool(runner=runner, tool=AptTool(output=self.out), output=self.out)487 spt.install_packages(packages)488 self.assertEqual(5, runner.calls)489 def test_packages_installed(self):490 """ SystemPackageTool must not install. All packages are installed.491 """492 packages = ["a_package", "another_package", "yet_another_package"]493 with tools.environment_append({"CONAN_SYSREQUIRES_SUDO": "True"}):494 runner = RunnerMultipleMock(['dpkg-query -W -f=\'${Status}\' a_package | '495 'grep -q "ok installed"',496 'dpkg-query -W -f=\'${Status}\' another_package | '497 'grep -q "ok installed"',498 'dpkg-query -W -f=\'${Status}\' yet_another_package | '499 'grep -q "ok installed"',500 ])501 spt = SystemPackageTool(runner=runner, tool=AptTool(output=self.out), output=self.out)502 spt.install_packages(packages)503 self.assertEqual(3, runner.calls)504 def test_empty_package_list(self):505 """ Install nothing506 """507 packages = []508 with tools.environment_append({"CONAN_SYSREQUIRES_SUDO": "True"}):509 runner = RunnerMultipleMock()510 spt = SystemPackageTool(runner=runner, tool=AptTool(output=self.out),511 output=self.out)512 spt.install_packages(packages)513 self.assertEqual(0, runner.calls)514 def test_install_variants_and_packages(self):515 """ SystemPackageTool must install one of variants and all packages at same list516 """517 packages = [("varianta", "variantb", "variantc"), "a_package", "another_package"]518 with tools.environment_append({"CONAN_SYSREQUIRES_SUDO": "True"}):519 runner = RunnerMultipleMock(["sudo -A apt-get update",520 "sudo -A apt-get install -y --no-install-recommends"521 " varianta",522 "sudo -A apt-get update",523 "sudo -A apt-get install -y --no-install-recommends"524 " a_package another_package",525 ])526 spt = SystemPackageTool(runner=runner, tool=AptTool(output=self.out), output=self.out)527 spt.install_packages(packages)528 self.assertEqual(8, runner.calls)529 def test_installed_variant_and_install_packages(self):530 """ Only packages must be installed. Variants are already installed531 """532 packages = [("varianta", "variantb", "variantc"), "a_package", "another_package"]533 with tools.environment_append({"CONAN_SYSREQUIRES_SUDO": "True"}):534 runner = RunnerMultipleMock(['dpkg-query -W -f=\'${Status}\' varianta | '535 'grep -q "ok installed"',536 "sudo -A apt-get update",537 "sudo -A apt-get install -y --no-install-recommends"538 " a_package another_package",539 ])540 spt = SystemPackageTool(runner=runner, tool=AptTool(output=self.out), output=self.out)541 spt.install_packages(packages)542 self.assertEqual(5, runner.calls)543 def test_installed_packages_and_install_variant(self):544 """ Only variant must be installed. Packages are already installed545 """546 packages = [("varianta", "variantb", "variantc"), "a_package", "another_package"]547 with tools.environment_append({"CONAN_SYSREQUIRES_SUDO": "True"}):548 runner = RunnerMultipleMock(['dpkg-query -W -f=\'${Status}\' a_package | '549 'grep -q "ok installed"',550 'dpkg-query -W -f=\'${Status}\' another_package | '551 'grep -q "ok installed"',552 "sudo -A apt-get update",553 "sudo -A apt-get install -y --no-install-recommends"554 " varianta",555 ])556 spt = SystemPackageTool(runner=runner, tool=AptTool(output=self.out), output=self.out)557 spt.install_packages(packages)558 self.assertEqual(7, runner.calls)559 def test_variants_and_packages_installed(self):560 """ Install nothing, all is already installed561 """562 packages = [("varianta", "variantb", "variantc"), "a_package", "another_package"]563 with tools.environment_append({"CONAN_SYSREQUIRES_SUDO": "True"}):564 runner = RunnerMultipleMock(['dpkg-query -W -f=\'${Status}\' varianta | '565 'grep -q "ok installed"',566 'dpkg-query -W -f=\'${Status}\' a_package | '567 'grep -q "ok installed"',568 'dpkg-query -W -f=\'${Status}\' another_package | '569 'grep -q "ok installed"',570 ])571 spt = SystemPackageTool(runner=runner, tool=AptTool(output=self.out), output=self.out)572 spt.install_packages(packages)573 self.assertEqual(3, runner.calls)574 def test_empty_variants_and_packages(self):575 packages = [(),]576 with tools.environment_append({"CONAN_SYSREQUIRES_SUDO": "True"}):577 runner = RunnerMultipleMock()578 spt = SystemPackageTool(runner=runner, tool=AptTool(output=self.out),579 output=self.out)580 spt.install_packages(packages)581 self.assertEqual(0, runner.calls)582 def test_install_all_multiple_package_list(self):583 """ Separated string list must be treated as full package list to be installed584 """585 packages = "varianta variantb", "variantc variantd"586 runner = RunnerMultipleMock([])587 spt = SystemPackageTool(runner=runner, tool=AptTool(output=self.out), output=self.out)588 with self.assertRaises(ConanException) as error:589 spt.install_packages(packages)590 self.assertEqual("Each string must contain only one package to be installed."...

Full Screen

Full Screen

linuxLocalExploit.py

Source:linuxLocalExploit.py Github

copy

Full Screen

...108 return True109 else:110 logging.warning("Not a 64bit node")111 return False112 def get_os_info(self):113 """114 Return a dict containing 'distro' and 'version' for the target OS115 """116 # Backup method in case we can't access /etc/os-release117 os = [118 {"name": "ubuntu", "path": "/etc/lsb-release", "reg": "DISTRIB_ID=(.*)\n.*DISTRIB_RELEASE=(.*)\n.*"},119 {"name": "debian", "path": "/etc/debian_version", "reg": "(.*).*"},120 {"name": "fedora", "path": "/etc/fedora-release", "reg": "(\w*) .* (\d*) .*"},121 {"name": "redhat", "path": "/etc/redhat-release", "reg": "(\w*) .* release (.*) \(.*"},122 {"name": "suse", "path": "/etc/SuSE-release", "reg": "(.*) \(.*\)\n.*VERSION = (.*)\n.*PATCHLEVEL = (.*)\n.*"},123 ]124 os_info = {}125 os_info["distro"] = "None"126 os_info["version"] = "None"127 fd = self.node.shell.open("/etc/os-release", self.node.shell.libc.getdefine('O_RDONLY'))128 if fd >= 0:129 data = self.node.shell.readall(fd)130 self.node.shell.close(fd)131 reg_1 = """NAME="(.*)"\n(?:.*=.*\n)*VERSION_ID="(.*)"\n.*"""132 reg_2 = """NAME=(.*)\n(?:.*=.*\n)*VERSION_ID=(.*)\n.*"""133 m = re.search(reg_1, data)134 if not m:135 m = re.search(reg_2, data)136 if m:137 os_info["distro"] = m.group(1).split()[0].lower()138 #139 # Special case for debian as os-release reports only major version140 #141 if os_info["distro"] == "debian":142 fd = self.node.shell.open("/etc/debian_version", self.node.shell.libc.getdefine("O_RDONLY"))143 if fd >= 0:144 data = self.node.shell.readall(fd)145 self.node.shell.close(fd)146 m = re.search("(.*).*", data)147 if m:148 os_info["version"] = m.group(1)149 else:150 os_info["version"] = m.group(2)151 return os_info152 else:153 logging.error("Error while retrieving version information (generic)")154 logging.info("Trying to parse specific release information")155 for entry in os:156 fd = self.node.shell.open(entry["path"], self.node.shell.libc.getdefine('O_RDONLY'))157 if fd < 0:158 continue159 logging.debug("Found %s (reg %s)" % (entry["name"], entry["reg"]))160 data = self.node.shell.readall(fd)161 self.node.shell.close(fd)162 m = re.search(entry["reg"], data)163 if m:164 if entry["name"] == "debian":165 os_info["distro"] = entry["name"]166 os_info["version"] = m.group(1)167 else:168 os_info["distro"] = m.group(1).split()[0].lower()169 if entry["name"] == "suse":170 os_info["version"] = "%s.%s" % (m.group(2), m.group(3))171 else:172 os_info["version"] = m.group(2)173 else:174 logging.error("Error while retrieving version information for %s" % entry["name"])175 break176 return os_info177 def is_ubuntu_14_04(self, os_info=None):178 if os_info is None:179 os_info = self.get_os_info()180 if os_info['distro'] == "ubuntu" and os_info['version'] == "14.04":181 return True182 return False183 def is_ubuntu_14_10(self, os_info=None):184 if os_info is None:185 os_info = self.get_os_info()186 if os_info['distro'] == "ubuntu" and os_info['version'] == "14.10":187 return True188 return False189 def is_ubuntu_15_04(self, os_info=None):190 if os_info is None:191 os_info = self.get_os_info()192 if os_info['distro'] == "ubuntu" and os_info['version'] == "15.04":193 return True194 return False195 def is_ubuntu_15_10(self, os_info=None):196 if os_info is None:197 os_info = self.get_os_info()198 if os_info['distro'] == "ubuntu" and os_info['version'] == "15.10":199 return True200 return False201 def fork_and_exec(self, command, wait = 0):202 """203 Fork and Exec either our exploit or helper on target node204 Caveats:205 - self.remote_helper is your remote helper path206 - self.remote_exp is your remote exploit path207 TODO: add ability to pass parameters to exploits208 """209 if not self.remote_helper:210 logging.error("self.remote_helper not set inside exploit class")211 return 1...

Full Screen

Full Screen

os_info_all_V1.py

Source:os_info_all_V1.py Github

copy

Full Screen

1# /usr/bin/env python2# coding:utf-83# author:Michael.Xu4# info:get os information5import os6import psutil7import platform8import datetime9import socket10import uuid11#对字典取子集12def sub_dict(form_dict, sub_keys, default=None):13 return dict([(k, form_dict.get(k.strip(), default)) for k in sub_keys.split(',')])14# 获取主机CPU核数,个数(逻辑/物理),主频,型号15def read_cpuinfo():16 cpu_stat = []17 with open('/proc/cpuinfo', 'r') as f:18 data = f.read()19 for line in data.split('\n\n'):20 cpu_stat.append(line)21 return cpu_stat[-2]22def get_cpuinfo(data):23 cpu_info = {}24 for i in data.splitlines():25 # x.strip(rm): 当 rm 为空时,默认删除开头,结尾空白符(包括'\n','\r','\t',' ')26 k, v = [ x.strip() for x in i.split(':')]27 cpu_info[k] = v28 # print cpu_info[k]29 cpu_info['physical id'] = str(int(cpu_info.get('physical id')) + 1)30 #cpu_cores = cpu_info['cpu cores']31 #cpu_physical_counts = cpu_info['physical id']32 #cpu_logic_counts = int(cpu_cores) * int(cpu_physical_counts)33 #cpu_type = cpu_info['model name']34 #print 'CPU核数: %s' % cpu_info['cpu cores']35 #print 'CPU个数(物理): %s' % cpu_info['physical id']36 #print 'CPU型号: %s' % cpu_info['model name']37 #return sub_dict(cpu_info, 'model name,physical id,cpu cores')38 return cpu_info 39# 获取内存、swap信息40def get_meminfo():41 mem_info = {}42 m = psutil.virtual_memory()43 mem_info['mem_total'] = m.total/1000/1000/100044 mem_info['mem_available'] = m.available/1000/1000/100045 mem_info['mem_free'] = m.free/1000/1000/100046 mem_info['mem_use_rate'] = m.percent47 s = psutil.swap_memory()48 mem_info['swap_total'] = s.total/1000/1000/100049 mem_info['swap_free'] = s.free/1000/1000/100050 mem_info['swap_use_rate'] = s.percent51 return mem_info52# 获取系统版本信息,主机开机时间,登录用户信息53def get_osinfo():54 os_info = {}55 os_info['os_type'] = platform.system()56 os_info['os_system'] = platform.linux_distribution()[0]57 os_info['os_version'] = platform.linux_distribution()[1]58 os_info['os_kernel'] = platform.release()59 os_info['os_hostname'] = platform.node()60 os_info['os_starttime'] = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S") 61 os_info['users_count'] = len(psutil.users())62 os_info['users_list'] = ",".join([u.name for u in psutil.users()])63 os_info['users_host'] = ",".join([u.host for u in psutil.users()])64 return os_info65# 获取磁盘信息66def get_diskinfo():67 disk_info = []68 disk_partitions = psutil.disk_partitions()69 for i in disk_partitions:70 partitions_info = {}71 partitions_info['device'] = i[0]72 partitions_info['mount'] = i[1]73 partitions_info['fstype'] = i[2]74 mount = partitions_info['mount']75 capacity = psutil.disk_usage(partitions_info['mount'])76 partitions_info['total_capacity'] = capacity.total/1000/1000/100077 partitions_info['used_capacity'] = capacity.used/1000/1000/100078 partitions_info['free_capacity'] = capacity.free/1000/1000/100079 partitions_info['used_rate'] = capacity.percent80 #print "挂载点: %s 分区:%s 分区类型:%s 分区总大小:%s GB 分区已使用大小:%s GB 分区未使用大小:%s GB 使用率: %s" %(partitions_info['mount'],partitions_info['device'] ,partitions_info['fstype'],partitions_info['total_capacity'],partitions_info['used_capacity'],partitions_info['free_capacity'],partitions_info['used_rate'])81 disk_info.append(partitions_info)82 return disk_info83# 获取主机IP地址方式 #84def get_netinfo():85 net_info = {}86 hostname = socket.gethostname()87 mac = uuid.UUID(int = uuid.getnode()).hex[-12:]88 #mac_info = ":".join([mac[e:e+2] for e in range(0,11,2)])89 net_info['ip'] = socket.gethostbyname(hostname)90 net_info['mac'] = ":".join([mac[e:e+2] for e in range(0,11,2)])91 return net_info92if __name__ == "__main__":93 rate = '%'94 cpu_info = get_cpuinfo(read_cpuinfo())95 os_info = get_osinfo()96 mem_info = get_meminfo()97 disk_info = get_diskinfo()98 net_info = get_netinfo()99 print '----- 系统信息 -----'100 print '系统类型: %s' % os_info['os_type']101 print '当前系统: %s %s ' % (os_info['os_system'],os_info['os_version'])102 print '系统内核版本: %s' % os_info['os_kernel']103 print '主机名: %s' % os_info['os_hostname']104 print '系统开始时间:%s' % os_info['os_starttime']105 print '当前登录用户数:%s' % os_info['users_count']106 print '当前登录用户分别为:%s' % os_info['users_list']107 print '用户来源IP分别为:%s' % os_info['users_host']108 print '----- CPU信息 -----'109 print 'CPU核数: %s' % cpu_info['cpu cores']110 print 'CPU个数(物理): %s' % cpu_info['physical id']111 print 'CPU型号: %s' % cpu_info['model name']112 print '----- 内存信息 -----'113 print '内存总计: %s GB' % mem_info['mem_total']114 print '有效内存: %s GB' % mem_info['mem_available']115 print '空闲内存: %s GB' % mem_info['mem_free']116 print '已使用内存占比: %s%s' % (mem_info['mem_use_rate'],rate)117 print 'SWAP内存总计:%s GB' % mem_info['swap_total']118 print 'SWAP空闲内存:%s GB' % mem_info['swap_free']119 print 'SWAP已使用内存占比:%s%s' % (mem_info['swap_use_rate'],rate)120 print '----- 磁盘信息 -----'121 for i in range(0,len(disk_info)):122 partitions_info = disk_info[i]123 #for k,v in partitions_info.items():124 # print k,v125 print "挂载点: %s 分区:%s 分区类型:%s 分区总大小:%s GB 分区已使用大小:%s GB 分区未使>用大小:%s GB 使用率: %s" %(partitions_info['mount'],partitions_info['device'] ,partitions_info['fstype'],partitions_info['total_capacity'],partitions_info['used_capacity'],partitions_info['free_capacity'],partitions_info['used_rate'])126 print '----- 网卡信息 -----'127 print '本机IP地址为:%s' % net_info['ip']128 print '本机网卡MAC地址为:%s' % net_info['mac']...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run lisa automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful