def test_show(): """ Tests the show function """ # Mock just a small portion of the full "sysctl -ae" output, but be # sure to include a multi-line value. mock_cmd = MagicMock(return_value=dedent( """\ kern.ostype=FreeBSD kern.osrelease=13.0-CURRENT kern.osrevision=199506 kern.version=FreeBSD 13.0-CURRENT #246 r365916M: Thu Sep 24 09:17:12 MDT 2020 [email protected]:/usr/obj/usr/src/head /amd64.amd64/sys/GENERIC kern.maxvnodes=213989 """, "\n", )) with patch.dict(freebsd_sysctl.__salt__, {"cmd.run": mock_cmd}): ret = freebsd_sysctl.show() assert "FreeBSD" == ret["kern.ostype"] assert (dedent( """\ FreeBSD 13.0-CURRENT #246 r365916M: Thu Sep 24 09:17:12 MDT 2020 [email protected]:/usr/obj/usr/src/head /amd64.amd64/sys/GENERIC """, "\n", ) == ret["kern.version"])
def create_pillar(self, key): """ Utility method to create a pillar for the minion and a value of true, this method also removes and cleans up the pillar at the end of the test. """ top_path = os.path.join(RUNTIME_VARS.TMP_PILLAR_TREE, "top.sls") pillar_path = os.path.join(RUNTIME_VARS.TMP_PILLAR_TREE, "test_pillar.sls") with salt.utils.files.fopen(top_path, "w") as fd: fd.write( dedent( """ base: 'minion': - test_pillar """ ) ) with salt.utils.files.fopen(pillar_path, "w") as fd: fd.write( dedent( """ {}: true """.format( key ) ) ) self.addCleanup(self.cleanup_pillars, top_path, pillar_path)
def test_salt_documentation(self): """ Test to see if we're supporting --doc """ expect_to_find = "test.ping:" stdout, stderr = self.run_salt('-d "*" test', catch_stderr=True) error_msg = dedent( """ Failed to find \'{expected}\' in output {sep} --- STDOUT ----- {stdout} {sep} --- STDERR ----- {stderr} {sep} """.format( sep="-" * 80, expected=expect_to_find, stdout="\n".join(stdout).strip(), stderr="\n".join(stderr).strip(), ) ) self.assertIn(expect_to_find, stdout, msg=error_msg)
def test_read_certificate(self): """ :return: """ cet = dedent( """ -----BEGIN CERTIFICATE----- MIICdDCCAd2gAwIBAgIUH6g+PC0bGKSY4LMq7PISP09M5B4wDQYJKoZIhvcNAQEL BQAwTDELMAkGA1UEBhMCVVMxEDAOBgNVBAgMB0FyaXpvbmExEzARBgNVBAcMClNj b3R0c2RhbGUxFjAUBgNVBAoMDVN1cGVyIFdpZGdpdHMwHhcNMjEwMzIzMDExNDE2 WhcNMjIwMzIzMDExNDE2WjBMMQswCQYDVQQGEwJVUzEQMA4GA1UECAwHQXJpem9u YTETMBEGA1UEBwwKU2NvdHRzZGFsZTEWMBQGA1UECgwNU3VwZXIgV2lkZ2l0czCB nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAvtFFZP47UkzyAmVWtBnVHuXwe7iK yu19c3qx59KPVAMHkMKgCew4S2KBMDHySBVnspiEz1peP1ywozcP1tIeWHG6aY/7 j2ewzl5bJ4HZPDBnEOYzGsC/NM8YY3qFlrteda/awvwoF99MkpVlrcLBMJzjt/c8 HjuBb0zTlnm4r7ECAwEAAaNTMFEwHQYDVR0OBBYEFJwdb0PKsvu3dU0j3kx3uP4B NGpfMB8GA1UdIwQYMBaAFJwdb0PKsvu3dU0j3kx3uP4BNGpfMA8GA1UdEwEB/wQF MAMBAf8wDQYJKoZIhvcNAQELBQADgYEAZblVv70rSk6+7ti3mYxVo48VLf3hG5R/ rMd434WYTeDOWlvl5GSklrBc4ToBW5GsJe/+JaFbUFo9YB+a0K0xjyNZ5CWWiaxg 3lwqTx6vwK1ucS18B+nt2qqyq9hL0UvpSB7gH4KeCwCMDIfRMsrPi32jg1RyKftD B+O0S5LeuJw= -----END CERTIFICATE----- """ ) ret = x509.read_certificate(cet) assert "MD5 Finger Print" not in ret
def loader_dir(tmp_path): """ Create a simple directory with a couple modules to load and run tests against. """ mod_content = dedent( """ def __virtual__(): return True def set_context(key, value): __context__[key] = value def get_context(key): return __context__[key] """ ) tmp_path = str(tmp_path) with salt.utils.files.fopen(os.path.join(tmp_path, "mod_a.py"), "w") as fp: fp.write(mod_content) with salt.utils.files.fopen(os.path.join(tmp_path, "mod_b.py"), "w") as fp: fp.write(mod_content) try: yield tmp_path finally: shutil.rmtree(tmp_path)
def test_ssh_single__cmd_str_sudo_passwd_user(temp_salt_master): opts = temp_salt_master.config.copy() argv = [] id_ = "minion" host = "minion" user = "******" passwd = "salty" single = salt.client.ssh.Single( opts, argv, id_, host, sudo=True, passwd=passwd, sudo_user=user ) cmd = single._cmd_str() expected = dedent( """ SUDO="" if [ -n "sudo -p '[salt:sudo:d11bd4221135c33324a6bdc09674146fbfdf519989847491e34a689369bbce23]passwd:'" ] then SUDO="sudo -p '[salt:sudo:d11bd4221135c33324a6bdc09674146fbfdf519989847491e34a689369bbce23]passwd:' " fi SUDO_USER="******" if [ "$SUDO" ] && [ "$SUDO_USER" ] then SUDO="$SUDO -u $SUDO_USER" fi """ ) assert expected in cmd
def test_file_keyvalue_not_dict(tmp_path): """ test file.keyvalue when key_values not a dict """ contents = dedent("""\ #PermitRootLogin prohibit-password #StrictMode yes """) with pytest.helpers.temp_file("tempfile", contents=contents, directory=tmp_path) as tempfile: ret = filestate.keyvalue( name=str(tempfile), key_values=["PermiteRootLogin", "yes"], separator=" ", uncomment="#", key_ignore_case=True, ) assert ( ret["comment"] == "file.keyvalue key and value not supplied and key_values is not a dictionary" ) f_contents = tempfile.read_text() assert "PermitRootLogin yes" not in f_contents assert "#StrictMode yes" in f_contents
def test_issue_58763(tmp_path, modules, state_tree, caplog): venv_dir = tmp_path / "issue-2028-pip-installed" sls_contents = dedent(""" run_old: module.run: - name: test.random_hash - size: 10 - hash_type: md5 run_new: module.run: - test.random_hash: - size: 10 - hash_type: md5 """) with pytest.helpers.temp_file("issue-58763.sls", sls_contents, state_tree): with caplog.at_level(logging.DEBUG): ret = modules.state.sls(mods="issue-58763", ) assert len(ret.raw) == 2 for k in ret.raw: assert ret.raw[k]["result"] is True assert "Detected legacy module.run syntax: run_old" in caplog.messages assert "Using new style module.run syntax: run_new" in caplog.messages
def test_ssh_single__cmd_str_sudo_user(temp_salt_master): opts = temp_salt_master.config.copy() argv = [] id_ = "minion" host = "minion" user = "******" single = salt.client.ssh.Single(opts, argv, id_, host, sudo=True, sudo_user=user) cmd = single._cmd_str() expected = dedent(""" SUDO="" if [ -n "sudo" ] then SUDO="sudo " fi SUDO_USER="******" if [ "$SUDO" ] && [ "$SUDO_USER" ] then SUDO="$SUDO -u $SUDO_USER" fi """) assert expected in cmd
def source(): with pytest.helpers.temp_file( name="file.txt", contents=dedent(""" things = stuff port = 5432 # (change requires restart) # commented = something moar = things """), ) as source: yield source
def test_exec_code(self): """ cmd.exec_code """ code = dedent(""" import sys sys.stdout.write('cheese') """) self.assertEqual( self.run_function("cmd.exec_code", [AVAILABLE_PYTHON_EXECUTABLE, code]).rstrip(), "cheese", )
def create_pillar(self, key): ''' Utility method to create a pillar for the minion and a value of true, this method also removes and cleans up the pillar at the end of the test. ''' top_path = os.path.join(RUNTIME_VARS.TMP_PILLAR_TREE, 'top.sls') pillar_path = os.path.join(RUNTIME_VARS.TMP_PILLAR_TREE, 'test_pillar.sls') with salt.utils.files.fopen(top_path, 'w') as fd: fd.write( dedent(''' base: 'minion': - test_pillar ''')) with salt.utils.files.fopen(pillar_path, 'w') as fd: fd.write( dedent(''' {}: true '''.format(key))) self.addCleanup(self.cleanup_pillars, top_path, pillar_path)
def test_exec_code_with_multiple_args(self): """ cmd.exec_code """ code = dedent(""" import sys sys.stdout.write(sys.argv[1]) """) arg = "cheese" self.assertEqual( self.run_function("cmd.exec_code", [AVAILABLE_PYTHON_EXECUTABLE, code], args=[arg, "test"]).rstrip(), arg, )
def test_issue_58763_b(tmp_path, modules, state_tree, caplog): venv_dir = tmp_path / "issue-2028-pip-installed" sls_contents = dedent(""" test.ping: module.run """) with pytest.helpers.temp_file("issue-58763.sls", sls_contents, state_tree): with caplog.at_level(logging.DEBUG): ret = modules.state.sls(mods="issue-58763", ) assert len(ret.raw) == 1 print(ret) for k in ret.raw: assert ret.raw[k]["result"] is True assert "Detected legacy module.run syntax: test.ping" in caplog.messages
def test_format_sync_stats(self): ''' Test format rsync stats for preserving ordering of the keys :return: ''' support = saltsupport.SaltSupportModule() stats = dedent(''' robot: Bender cute: Leela weird: Zoidberg professor: Farnsworth ''') f_stats = support.format_sync_stats({'retcode': 0, 'stdout': stats}) assert list(f_stats['transfer'].keys()) == [ 'robot', 'cute', 'weird', 'professor' ] assert list(f_stats['transfer'].values()) == [ 'Bender', 'Leela', 'Zoidberg', 'Farnsworth' ]
def test_list_all(self): """ Test for List everything added for or enabled in a zone """ # pylint: disable=trailing-whitespace firewall_cmd_ret = dedent( """\ public target: default icmp-block-inversion: no interfaces: eth0 sources: services: cockpit dhcpv6-client ssh ports: protocols: masquerade: no forward-ports: source-ports: icmp-blocks: rich rules: """ ) # pylint: enable=trailing-whitespace ret = { "public": { "forward-ports": [""], "icmp-block-inversion": ["no"], "icmp-blocks": [""], "interfaces": ["eth0"], "masquerade": ["no"], "ports": [""], "protocols": [""], "rich rules": [""], "services": ["cockpit dhcpv6-client ssh"], "source-ports": [""], "sources": [""], "target": ["default"], } } with patch.object(firewalld, "__firewall_cmd", return_value=firewall_cmd_ret): self.assertEqual(firewalld.list_all(), ret)
def test_salt_documentation(self): ''' Test to see if we're supporting --doc ''' expect_to_find = 'test.ping:' stdout, stderr = self.run_salt('-d "*" test', catch_stderr=True) error_msg = dedent(''' Failed to find \'{expected}\' in output {sep} --- STDOUT ----- {stdout} {sep} --- STDERR ----- {stderr} {sep} '''.format(sep='-' * 80, expected=expect_to_find, stdout='\n'.join(stdout).strip(), stderr='\n'.join(stderr).strip())) self.assertIn(expect_to_find, stdout, msg=error_msg)
def test_file_keyvalue_key_values(tmp_path): """ test file.keyvalue when using key_values kwarg """ contents = dedent("""\ #PermitRootLogin prohibit-password #StrictMode yes """) with pytest.helpers.temp_file("tempfile", contents=contents, directory=tmp_path) as tempfile: ret = filestate.keyvalue( name=str(tempfile), key_values=collections.OrderedDict(PermitRootLogin="******"), separator=" ", uncomment="#", key_ignore_case=True, ) f_contents = tempfile.read_text() assert "PermitRootLogin yes" in f_contents assert "#StrictMode yes" in f_contents
def test_importable_installation_error(self): extra_requirements = [] for name, version in salt.version.dependency_information(): if name in ["PyYAML"]: extra_requirements.append("{}=={}".format(name, version)) failures = {} pip_version_requirements = [ # Latest pip 18 "<19.0", # Latest pip 19 "<20.0", # Latest pip 20 "<21.0", # Latest pip None, ] code = dedent("""\ import sys import traceback try: import salt.states.pip_state salt.states.pip_state.InstallationError except ImportError as exc: traceback.print_exc(file=sys.stdout) sys.stdout.flush() sys.exit(1) except AttributeError as exc: traceback.print_exc(file=sys.stdout) sys.stdout.flush() sys.exit(2) except Exception as exc: traceback.print_exc(exc, file=sys.stdout) sys.stdout.flush() sys.exit(3) sys.exit(0) """) for requirement in list(pip_version_requirements): try: with VirtualEnv() as venv: venv.install(*extra_requirements) if requirement: venv.install("pip{}".format(requirement)) try: subprocess.check_output([venv.venv_python, "-c", code]) except subprocess.CalledProcessError as exc: if exc.returncode == 1: failures[ requirement] = "Failed to import pip:\n{}".format( exc.output) elif exc.returncode == 2: failures[ requirement] = "Failed to import InstallationError from pip:\n{}".format( exc.output) else: failures[requirement] = exc.output except Exception as exc: # pylint: disable=broad-except failures[requirement] = str(exc) if failures: errors = "" for requirement, exception in failures.items(): errors += "pip{}: {}\n\n".format(requirement or "", exception) self.fail( "Failed to get InstallationError exception under at least one pip" " version:\n{}".format(errors))
def test_deferred_write_on_atexit(tmp_path): # Python will .flush() and .close() all logging handlers at interpreter shutdown. # This should be enough to flush our deferred messages. pyscript = dedent(r""" import sys import time import logging CODE_DIR = {!r} if CODE_DIR in sys.path: sys.path.remove(CODE_DIR) sys.path.insert(0, CODE_DIR) from salt._logging.handlers import DeferredStreamHandler # Reset any logging handlers we might have already logging.root.handlers[:] = [] handler = DeferredStreamHandler(sys.stderr) handler.setLevel(logging.DEBUG) logging.root.addHandler(handler) log = logging.getLogger(__name__) sys.stdout.write('STARTED\n') sys.stdout.flush() log.debug('Foo') sys.exit(0) """.format(RUNTIME_VARS.CODE_DIR)) script_path = tmp_path / "atexit_deferred_logging_test.py" script_path.write_text(pyscript, encoding="utf-8") proc = NonBlockingPopen( [sys.executable, str(script_path)], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) out = b"" err = b"" # This test should never take more than 5 seconds execution_time = 5 max_time = time.time() + execution_time try: # Just loop consuming output while True: if time.time() > max_time: pytest.fail("Script didn't exit after {} second".format( execution_time)) time.sleep(0.125) _out = proc.recv() _err = proc.recv_err() if _out: out += _out if _err: err += _err if _out is None and _err is None: # The script exited break if proc.poll() is not None: # The script exited break finally: terminate_process(proc.pid, kill_children=True) if b"Foo" not in err: pytest.fail("'Foo' should be in stderr and it's not: {}".format(err))
def test_deferred_write_on_sigint(tmp_path): pyscript = dedent(r""" import sys import time import signal import logging CODE_DIR = {!r} if CODE_DIR in sys.path: sys.path.remove(CODE_DIR) sys.path.insert(0, CODE_DIR) from salt._logging.handlers import DeferredStreamHandler # Reset any logging handlers we might have already logging.root.handlers[:] = [] handler = DeferredStreamHandler(sys.stderr) handler.setLevel(logging.DEBUG) logging.root.addHandler(handler) if signal.getsignal(signal.SIGINT) != signal.default_int_handler: # Looking at you Debian based distros :/ signal.signal(signal.SIGINT, signal.default_int_handler) log = logging.getLogger(__name__) start_printed = False while True: try: log.debug('Foo') if start_printed is False: sys.stdout.write('STARTED\n') sys.stdout.write('SIGINT HANDLER: {{!r}}\n'.format(signal.getsignal(signal.SIGINT))) sys.stdout.flush() start_printed = True time.sleep(0.125) except (KeyboardInterrupt, SystemExit): log.info('KeyboardInterrupt caught') sys.stdout.write('KeyboardInterrupt caught\n') sys.stdout.flush() break log.info('EXITING') sys.stdout.write('EXITING\n') sys.stdout.flush() sys.exit(0) """.format(RUNTIME_VARS.CODE_DIR)) script_path = tmp_path / "sigint_deferred_logging_test.py" script_path.write_text(pyscript, encoding="utf-8") proc = NonBlockingPopen( [sys.executable, str(script_path)], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) out = b"" err = b"" # Test should take less than 20 seconds, way less execution_time = 10 start = time.time() max_time = time.time() + execution_time try: signalled = False log.info("Starting Loop") while True: time.sleep(0.125) _out = proc.recv() _err = proc.recv_err() if _out: out += _out if _err: err += _err if b"STARTED" in out and not signalled: # Enough time has passed proc.send_signal(signal.SIGINT) signalled = True log.debug("Sent SIGINT after: %s", time.time() - start) if signalled is False: if out: pytest.fail( "We have stdout output when there should be none: {}". format(out)) if err: pytest.fail( "We have stderr output when there should be none: {}". format(err)) if _out is None and _err is None: log.info("_out and _err are None") if b"Foo" not in err: pytest.fail( "No more output and 'Foo' should be in stderr and it's not: {}" .format(err)) break if proc.poll() is not None: log.debug("poll() is not None") if b"Foo" not in err: pytest.fail( "Process terminated and 'Foo' should be in stderr and it's not: {}" .format(err)) break if time.time() > max_time: log.debug("Reached max time") if b"Foo" not in err: pytest.fail( "'Foo' should be in stderr and it's not:\n{0}\nSTDERR:\n{0}\n{1}\n{0}\nSTDOUT:\n{0}\n{2}\n{0}" .format("-" * 80, err, out)) finally: terminate_process(proc.pid, kill_children=True) log.debug("Test took %s seconds", time.time() - start)
def test_private_key_fips_mode(self): """ :return: """ test_key = dedent(""" -----BEGIN PRIVATE KEY----- MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDx7UUt0cPi5G51 FmRBhAZtZb5x6P0PFn7GwnLmSvLNhCsOcD/vq/yBUU62pknzmOjM5pgWTACZj66O GOFmWBg06v8+sqUbaF9PZ/CxQD5MogmQhYNgfyuopHWWgLXMub2hlP+15qGohkzg Tr/mXp2ohVAb6ihjqb7XV9MiZaLNVX+XWauM8SlhqXMiJyDUopEGbg2pLsHhIMcX 1twLlyDja+uDbCMZ4jDNB+wsWxTaPRH8KizfEabB1Cl+fdyD10pSAYcodOAnlkW+ G/DX2hwb/ZAM9B1SXTfZ3gzaIIbqXBEHcZQNXxHL7szBTVcOmfx/RPfOeRncytb9 Mit7RIBxAgMBAAECggEAD4Pi+uRIBsYVm2a7OURpURzEUPPbPtt3d/HCgqht1+ZR CJUEVK+X+wcm4Cnb9kZpL7LeMBfhtfdz/2LzGagurT4g7nlwg0h3TFVjJ0ryc+G0 cVNOsKKXPzKE5AkPH7kNw04V9Cl9Vpx+U6hZQEHzJHqgP5oNyw540cCtJriT700b fG1q3PYKWSkDwTiUnJTnVLybFIKQC6urxTeT2UWeiBadfDY7DjI4USfrQsqCfGMO uWPpOOJk5RIvw5r0Of2xvxV76xCgzVTkgtWjBRMTEkfeYx3019xKlQtAKoGbZd1T tF8DH0cDlnri4nG7YT8yYvx/LWVDg12E6IZij1X60QKBgQD7062JuQGEmTd99a7o 5TcgWYqDrmE9AEgJZjN+gnEPcsxc50HJaTQgrkV0oKrS8CMbStIymbzMKWifOj7o gvQBVecydq1AaXePt3gRe8vBFiP4cHjFcSegs9FDvdfJR36iHOBIgEp4DWvV1vgs +z82LT6Qy5kxUQvnlQ4dEaGdrQKBgQD175f0H4enRJ3BoWTrqt2mTAwtJcPsKmGD 9YfFB3H4+O2rEKP4FpBO5PFXZ0dqm54hDtxqyC/lSXorFCUjVUBero1ECGt6Gnn2 TSnhgk0VMxvhnc0GReIt4K9WrXGd0CMUDwIhFHj8kbb1X1yqt2hwyw7b10xFVStl sGv8CQB+VQKBgAF9q1VZZwzl61Ivli2CzeS/IvbMnX7C9ao4lK13EDxLLbKPG/CZ UtmurnKWUOyWx15t/viVuGxtAlWO/rhZriAj5g6CbVwoQ7DyIR/ZX8dw3h2mbNCe buGgruh7wz9J0RIcoadMOySiz7SgZS++/QzRD8HDstB77loco8zAQfixAoGBALDO FbTocfKbjrpkmBQg24YxR9OxQb/n3AEtI/VO2+38r4h6xxaUyhwd1S9bzWjkBXOI poeR8XTqNQ0BR422PTeUT3SohPPcUu/yG3jG3zmta47wjjPDS85lqEgtGvA0cPN7 srErcatJ6nlOnGUSw9/K65y6lFeH2lIZ2hfwNM2dAoGBAMVCc7i3AIhLp6UrGzjP 0ioCHCakpxfl8s1VQp55lhHlP6Y4RfqT72Zq7ScteTrisIAQyI9ot0gsuct2miQM nyDdyKGki/MPduGTzzWlBA7GZEHnxbAILH8kWJ7eE/Nh7zdF1CRts8utEO9L9S+0 lVz1j/xGOseQk4cVos681Wpw -----END PRIVATE KEY-----""") test_cert = dedent(""" -----BEGIN CERTIFICATE----- MIIDazCCAlOgAwIBAgIUAfATs1aodKw11Varh55msmU0LoowDQYJKoZIhvcNAQEL BQAwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAeFw0yMTAzMjMwMTM4MzdaFw0yMjAz MjMwMTM4MzdaMEUxCzAJBgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEw HwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwggEiMA0GCSqGSIb3DQEB AQUAA4IBDwAwggEKAoIBAQDx7UUt0cPi5G51FmRBhAZtZb5x6P0PFn7GwnLmSvLN hCsOcD/vq/yBUU62pknzmOjM5pgWTACZj66OGOFmWBg06v8+sqUbaF9PZ/CxQD5M ogmQhYNgfyuopHWWgLXMub2hlP+15qGohkzgTr/mXp2ohVAb6ihjqb7XV9MiZaLN VX+XWauM8SlhqXMiJyDUopEGbg2pLsHhIMcX1twLlyDja+uDbCMZ4jDNB+wsWxTa PRH8KizfEabB1Cl+fdyD10pSAYcodOAnlkW+G/DX2hwb/ZAM9B1SXTfZ3gzaIIbq XBEHcZQNXxHL7szBTVcOmfx/RPfOeRncytb9Mit7RIBxAgMBAAGjUzBRMB0GA1Ud DgQWBBT0qx4KLhozvuWAI9peT/utYV9FITAfBgNVHSMEGDAWgBT0qx4KLhozvuWA I9peT/utYV9FITAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQDx tWvUyGfEwJJg1ViBa10nVhg5sEc6KfqcPzc2GvatIGJlAbc3b1AYu6677X04SQNA dYRA2jcZcKudy6eolPJow6SDpkt66IqciZYdbQE5h9elnwpZxmXlJTQTB9cEwyIk 2em5DKpdIwa9rRDlbAjAVJb3015MtpKRu2gsQ7gl5X2U3K+DFsWtBPf+0xiJqUiq rd7tiHF/zylubSyH/LVONJZ6+/oT/qzJfxfpvygtQWcu4b2zzME/FPenMA8W6Rau ZYycQfpMVc7KwqF5/wfjnkmfxoFKnkD7WQ3qFCJ/xULk/Yn1hrvNeIr+khX3qKQi Y3BMA5m+J+PZrNy7EQSa -----END CERTIFICATE----- """) fp, name = tempfile.mkstemp() with salt.utils.files.fopen(name, "w") as fd: fd.write(test_key) fd.write(test_cert) ret = x509.private_key_managed(name) self.file_managed_mock.assert_called_once() assert (self.file_managed_mock.call_args.kwargs["contents"].strip() == test_key.strip())
def test_list_zones(self): """ Test for List everything added for or enabled in all zones """ # pylint: disable=trailing-whitespace firewall_cmd_ret = dedent( """\ nm-shared target: ACCEPT icmp-block-inversion: no interfaces: sources: services: dhcp dns ssh ports: protocols: icmp ipv6-icmp masquerade: no forward-ports: source-ports: icmp-blocks: rich rules: \trule priority="32767" reject public target: default icmp-block-inversion: no interfaces: sources: services: cockpit dhcpv6-client ssh ports: protocols: masquerade: no forward-ports: source-ports: icmp-blocks: rich rules: """ ) # pylint: enable=trailing-whitespace ret = { "nm-shared": { "forward-ports": [""], "icmp-block-inversion": ["no"], "icmp-blocks": [""], "interfaces": [""], "masquerade": ["no"], "ports": [""], "protocols": ["icmp ipv6-icmp"], "rich rules": ["", 'rule priority="32767" reject'], "services": ["dhcp dns ssh"], "source-ports": [""], "sources": [""], "target": ["ACCEPT"], }, "public": { "forward-ports": [""], "icmp-block-inversion": ["no"], "icmp-blocks": [""], "interfaces": [""], "masquerade": ["no"], "ports": [""], "protocols": [""], "rich rules": [""], "services": ["cockpit dhcpv6-client ssh"], "source-ports": [""], "sources": [""], "target": ["default"], }, } with patch.object(firewalld, "__firewall_cmd", return_value=firewall_cmd_ret): self.assertEqual(firewalld.list_zones(), ret)