def enable_legacy_auditing(): # To test and use these policy settings we have to set one of the policies to Disabled # Location: Windows Settings -> Security Settings -> Local Policies -> Security Options # Policy: "Audit: Force audit policy subcategory settings..." # Short Name: SceNoApplyLegacyAuditPolicy from tests.support.sminion import create_sminion salt_minion = create_sminion() test_setting = "Disabled" pre_security_setting = salt_minion.functions.lgpo.get_policy( policy_name="SceNoApplyLegacyAuditPolicy", policy_class="machine" ) pre_audit_setting = salt_minion.functions.lgpo.get_policy( policy_name="Audit Account Management", policy_class="machine" ) try: if pre_security_setting != test_setting: salt_minion.functions.lgpo.set_computer_policy( name="SceNoApplyLegacyAuditPolicy", setting=test_setting ) assert ( salt_minion.functions.lgpo.get_policy( policy_name="SceNoApplyLegacyAuditPolicy", policy_class="machine" ) == test_setting ) yield finally: salt_minion.functions.lgpo.set_computer_policy( name="SceNoApplyLegacyAuditPolicy", setting=pre_security_setting ) salt_minion.functions.lgpo.set_computer_policy( name="Audit Account Management", setting=pre_audit_setting )
def _getglobals(self): item_globals = super(GrainsMarkEvaluator, self)._getglobals() if GrainsMarkEvaluator._cached_grains is None: sminion = create_sminion() GrainsMarkEvaluator._cached_grains = sminion.opts["grains"].copy() item_globals["grains"] = GrainsMarkEvaluator._cached_grains.copy() return item_globals
def setUpClass(cls): """ Ensure that Chocolatey is installed """ if salt.utils.path.which("chocolatey.exe") is None: sminion = create_sminion() sminion.functions.chocolatey.bootstrap()
def __attrs_post_init__(self): if self.sminion is None: self.sminion = create_sminion() if self.username is None: self.username = random_string("account-", uppercase=False) if self.password is None: self.password = self.username if self.hashed_password is None: self.hashed_password = salt.utils.pycrypto.gen_hash(password=self.password)
def configure_loader_modules(): """ setup loader modules and override the azurearm.get_client utility """ minion_config = create_sminion().opts.copy() utils = salt.loader.utils(minion_config) funcs = salt.loader.minion_mods( minion_config, utils=utils, whitelist=["azurearm_dns", "config"] ) utils["azurearm.get_client"] = AzureClientMock() return { azurearm_dns: {"__utils__": utils, "__salt__": funcs}, }
def __attrs_post_init__(self): if self.sminion is None: self.sminion = create_sminion() if self.username is None: self.username = random_string("account-", uppercase=False) if self.password is None: self.password = random_string("pwd-", size=8) if (self.hashed_password is None and not salt.utils.platform.is_darwin() and not salt.utils.platform.is_windows()): self.hashed_password = salt.utils.pycrypto.gen_hash( password=self.password) if self.create_group is True and self.group_name is None: self.group_name = "group-{}".format(self.username) if self.group_name is not None: self._group = TestGroup(sminion=self.sminion, name=self.group_name)
def host_docker_network_ip_address(docker_client): sminion = create_sminion() network_name = "salt-e2e" network_subnet = "10.0.20.0/24" network_gateway = "10.0.20.1" try: ret = sminion.states.docker_network.present( network_name, driver="bridge", ipam_pools=[{"subnet": network_subnet, "gateway": network_gateway}], ) assert isinstance(ret, dict), ret assert ret["result"], "Failed to create docker network: {}".format(ret) yield network_gateway finally: sminion.states.docker_network.absent(network_name)
def setup_loader(): """ setup loader modules and override the azurearm.get_client utility """ minion_config = create_sminion().opts.copy() utils = salt.loader.utils(minion_config) funcs = salt.loader.minion_mods(minion_config, utils=utils, whitelist=["azurearm_dns", "config"]) utils["azurearm.get_client"] = AzureClientMock() setup_loader_modules = { azurearm_dns: { "__utils__": utils, "__salt__": funcs }, } with pytest.helpers.loader_mock(setup_loader_modules) as loader_mock: yield loader_mock
def setUpClass(cls): cls.sminion = sminion = create_sminion() config = ( '{"backend": {"file": {"path": "/vault/file"}}, "default_lease_ttl":' ' "168h", "max_lease_ttl": "720h", "disable_mlock": true}') sminion.states.docker_image.present(name="vault", tag="0.9.6") login_attempts = 1 container_created = False while True: if container_created: sminion.states.docker_container.stopped(name="vault") sminion.states.docker_container.absent(name="vault") ret = sminion.states.docker_container.running( name="vault", image="vault:0.9.6", port_bindings="8200:8200", environment={ "VAULT_DEV_ROOT_TOKEN_ID": "testsecret", "VAULT_LOCAL_CONFIG": config, }, ) log.debug("docker_container.running return: %s", ret) container_created = ret["result"] time.sleep(5) ret = sminion.functions.cmd.run_all( cmd="{} login token=testsecret".format(VAULT_BINARY_PATH), env={"VAULT_ADDR": "http://127.0.0.1:8200"}, hide_output=False, ) if ret["retcode"] == 0: break log.debug("Vault login failed. Return: %s", ret) login_attempts += 1 if login_attempts >= 3: raise SkipTest("unable to login to vault") ret = sminion.functions.cmd.retcode( cmd="{} policy write testpolicy {}/vault.hcl".format( VAULT_BINARY_PATH, RUNTIME_VARS.FILES), env={"VAULT_ADDR": "http://127.0.0.1:8200"}, ) if ret != 0: raise SkipTest("unable to assign policy to vault")
def grains(request): sminion = create_sminion() return sminion.opts["grains"].copy()
def sminion(): return create_sminion()
def __attrs_post_init__(self): if self.sminion is None: self.sminion = create_sminion() if self.name is None: self.name = random_string("group-", uppercase=False)
def pytest_runtest_setup(item): """ Fixtures injection based on markers or test skips based on CLI arguments """ destructive_tests_marker = item.get_closest_marker("destructive_test") if destructive_tests_marker is not None or _has_unittest_attr( item, "__destructive_test__"): if item.config.getoption("--run-destructive") is False: item._skipped_by_mark = True pytest.skip("Destructive tests are disabled") os.environ[str("DESTRUCTIVE_TESTS")] = str( item.config.getoption("--run-destructive")) expensive_tests_marker = item.get_closest_marker("expensive_test") if expensive_tests_marker is not None or _has_unittest_attr( item, "__expensive_test__"): if item.config.getoption("--run-expensive") is False: item._skipped_by_mark = True pytest.skip("Expensive tests are disabled") os.environ[str("EXPENSIVE_TESTS")] = str( item.config.getoption("--run-expensive")) skip_if_not_root_marker = item.get_closest_marker("skip_if_not_root") if skip_if_not_root_marker is not None or _has_unittest_attr( item, "__skip_if_not_root__"): if not sys.platform.startswith("win"): if os.getuid() != 0: item._skipped_by_mark = True pytest.skip("You must be logged in as root to run this test") else: current_user = salt.utils.win_functions.get_current_user() if current_user != "SYSTEM": if not salt.utils.win_functions.is_admin(current_user): item._skipped_by_mark = True pytest.skip( "You must be logged in as an Administrator to run this test" ) skip_if_binaries_missing_marker = item.get_closest_marker( "skip_if_binaries_missing") if skip_if_binaries_missing_marker is not None: binaries = skip_if_binaries_missing_marker.args if len(binaries) == 1: if isinstance(binaries[0], (list, tuple, set, frozenset)): binaries = binaries[0] check_all = skip_if_binaries_missing_marker.kwargs.get( "check_all", False) message = skip_if_binaries_missing_marker.kwargs.get("message", None) if check_all: for binary in binaries: if salt.utils.path.which(binary) is None: item._skipped_by_mark = True pytest.skip('{0}The "{1}" binary was not found'.format( message and "{0}. ".format(message) or "", binary)) elif salt.utils.path.which_bin(binaries) is None: item._skipped_by_mark = True pytest.skip( "{0}None of the following binaries was found: {1}".format( message and "{0}. ".format(message) or "", ", ".join(binaries))) requires_network_marker = item.get_closest_marker("requires_network") if requires_network_marker is not None: only_local_network = requires_network_marker.kwargs.get( "only_local_network", False) has_local_network = False # First lets try if we have a local network. Inspired in verify_socket try: pubsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) retsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) pubsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) pubsock.bind(("", 18000)) pubsock.close() retsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) retsock.bind(("", 18001)) retsock.close() has_local_network = True except socket.error: # I wonder if we just have IPV6 support? try: pubsock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) retsock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) pubsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) pubsock.bind(("", 18000)) pubsock.close() retsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) retsock.bind(("", 18001)) retsock.close() has_local_network = True except socket.error: # Let's continue pass if only_local_network is True: if has_local_network is False: # Since we're only supposed to check local network, and no # local network was detected, skip the test item._skipped_by_mark = True pytest.skip("No local network was detected") # We are using the google.com DNS records as numerical IPs to avoid # DNS lookups which could greatly slow down this check for addr in ( "173.194.41.198", "173.194.41.199", "173.194.41.200", "173.194.41.201", "173.194.41.206", "173.194.41.192", "173.194.41.193", "173.194.41.194", "173.194.41.195", "173.194.41.196", "173.194.41.197", ): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(0.25) sock.connect((addr, 80)) sock.close() # We connected? Stop the loop break except socket.error: # Let's check the next IP continue else: item._skipped_by_mark = True pytest.skip("No internet network connection was detected") requires_salt_modules_marker = item.get_closest_marker( "requires_salt_modules") if requires_salt_modules_marker is not None: required_salt_modules = requires_salt_modules_marker.args if len(required_salt_modules) == 1 and isinstance( required_salt_modules[0], (list, tuple, set)): required_salt_modules = required_salt_modules[0] required_salt_modules = set(required_salt_modules) sminion = create_sminion() available_modules = list(sminion.functions) not_available_modules = set() try: cached_not_available_modules = sminion.__not_availiable_modules__ except AttributeError: cached_not_available_modules = sminion.__not_availiable_modules__ = set( ) if cached_not_available_modules: for not_available_module in cached_not_available_modules: if not_available_module in required_salt_modules: not_available_modules.add(not_available_module) required_salt_modules.remove(not_available_module) for required_module_name in required_salt_modules: search_name = required_module_name if "." not in search_name: search_name += ".*" if not fnmatch.filter(available_modules, search_name): not_available_modules.add(required_module_name) cached_not_available_modules.add(required_module_name) if not_available_modules: item._skipped_by_mark = True if len(not_available_modules) == 1: pytest.skip("Salt module '{}' is not available".format( *not_available_modules)) pytest.skip("Salt modules not available: {}".format( ", ".join(not_available_modules)))
def _default_sminion(self): return create_sminion()