def test_node_name_from_machine_id(mock_loads, mock_subprocess): json_node_object = { 'items': [{ 'metadata': { 'name': 'my-node-1' }, 'status': { 'nodeInfo': { 'machineID': '49f8e2911a1449b7b5ef2bf92282909a' } } }, { 'metadata': { 'name': 'my-node-2' }, 'status': { 'nodeInfo': { 'machineID': '9ea12911449eb7b5f8f228294bf9209a' } } }] } breaking_json_node_object = {'Items': []} mock_process = Mock() mock_process.communicate.return_value = ( json.dumps(json_node_object).encode(), b'') mock_process.returncode = 0 mock_subprocess.return_value = mock_process mock_loads.return_value = json_node_object assert node_name_from_machine_id() == 'my-node-2' json_node_object2 = json_node_object json_node_object2['items'][1]['status']['nodeInfo']['machineID'] = \ 'another-id-that-doesnt-reflect-a-node' mock_loads.return_value = json_node_object2 exception = False try: node_name_from_machine_id() == 'my-node-2' except Exception as e: exception = True assert 'Node name could not be determined' in str(e) assert exception mock_loads.return_value = breaking_json_node_object exception = False try: node_name_from_machine_id() == 'my-node-2' except Exception as e: exception = True assert 'Unexpected format' in str(e) assert exception exception = False mock_process.returncode = 1 try: node_name_from_machine_id() == 'my-node' except Exception as e: exception = True assert 'Kubectl failed getting nodes list' in str(e) assert exception
def test_run_zypper_command(mock_subprocess): mock_process = Mock() mock_process.communicate.return_value = (b'stdout', b'stderr') mock_process.returncode = 0 mock_subprocess.return_value = mock_process assert run_zypper_command(['patch']) == 0 mock_process.returncode = ZYPPER_EXIT_INF_RESTART_NEEDED mock_subprocess.return_value = mock_process assert run_zypper_command(['patch']) == ZYPPER_EXIT_INF_RESTART_NEEDED
def test_annotate(mock_subprocess, capsys): mock_process = Mock() mock_process.communicate.return_value = (b'node/my-node-1 annotated', b'stderr') mock_process.returncode = 0 mock_subprocess.return_value = mock_process assert annotate('node', 'my-node-1', KUBE_DISRUPTIVE_UPDATES_KEY, 'yes') == 'node/my-node-1 annotated' mock_process.returncode = 1 annotate('node', 'my-node-1', KUBE_DISRUPTIVE_UPDATES_KEY, 'yes') out, err = capsys.readouterr() assert 'Warning! kubectl returned non zero exit code' in out
def patch_diff(command, **kwargs): if command[0:4] == ['git', '-c', 'diff.mnemonicprefix=no', 'diff']: mock = Mock() mock.communicate.return_value = (stdout, stderr) mock.returncode = returncode return mock elif command[0:2] == ['git', 'rev-parse']: mock = Mock() mock.communicate.return_value = (self._git_root_path, '') mock.returncode = returncode return mock else: process = Popen(command, **kwargs) return process
def test_snapshot_mount_error_raises_Exception(self, mock_create_dir, mock_get_lvm_info, mock_get_vol_fs_type, mock_popen, mock_lvm_snap_remove): mock_get_vol_fs_type.return_value = 'xfs' mock_get_lvm_info.return_value = { 'volgroup': 'lvm_volgroup', 'srcvol': 'lvm_device', 'snap_path': 'snap_path'} mock_lvcreate_process, mock_mount_process = Mock(), Mock() mock_lvcreate_process.communicate.return_value = '', '' mock_lvcreate_process.returncode = 0 mock_mount_process.communicate.return_value = '', 'mount error' mock_mount_process.returncode = 1 mock_popen.side_effect = [mock_lvcreate_process, mock_mount_process] backup_opt = Mock() backup_opt.snapshot = True backup_opt.lvm_auto_snap = '' backup_opt.path_to_backup = '/just/a/path' backup_opt.lvm_dirmount = '/var/mountpoint' backup_opt.lvm_snapperm = 'ro' with self.assertRaises(Exception) as cm: lvm.lvm_snap(backup_opt) the_exception = cm.exception self.assertIn('lvm snapshot mounting error', the_exception.message) mock_lvm_snap_remove.assert_called_once_with(backup_opt)
def test_branches(_): """ Ensure git branches are listed when calling PrestineRepo#branches. """ branches_readlines = [ b' brightmd/master\n', b' brightmd/stable\n', b' brightmd/develop\n', ] repo = PrestineRepo('/tmp/stop') mResult = Mock() mResult.returncode = 0 mResult.stdout.readlines.return_value = branches_readlines mockPopen = patch('reflex.repo.Popen', return_value=mResult) with mockPopen as patchPopen: assert repo.branches() == ['brightmd/master', 'brightmd/stable', 'brightmd/develop'] repo.branches('shrubbery') patchPopen.assert_has_calls([ call(['git', 'branch', '--list', '--remote'], cwd='/tmp', stderr=PIPE, stdout=PIPE), call(['git', 'branch', '--list', '--remote', 'shrubbery'], cwd='/tmp', stderr=PIPE, stdout=PIPE), ])
def test_get_last_tag(_): """ Ensure PrestineRepo#get_last_tag calls `git describe --abbrev=0` to get the last tag on a repo. """ tag = b' 1.3.5\n' repo = PrestineRepo('/tmp/stop') mResult = Mock() mResult.returncode = 0 mResult.stdout.read.return_value = tag mockPopen = patch('reflex.repo.Popen', return_value=mResult) with mockPopen as patchPopen: repo.get_last_tag() repo.get_last_tag('abc') repo.get_last_tag('abc', 'test-*') repo.get_last_tag(match='test-*') patchPopen.assert_has_calls([ call(['git', 'describe', '--abbrev=0'], cwd='/tmp', stderr=PIPE, stdout=PIPE), call(['git', 'describe', '--abbrev=0', 'abc'], cwd='/tmp', stderr=PIPE, stdout=PIPE), call(['git', 'describe', '--abbrev=0', '--match', 'test-*', 'abc'], cwd='/tmp', stderr=PIPE, stdout=PIPE), call(['git', 'describe', '--abbrev=0', '--match', 'test-*'], cwd='/tmp', stderr=PIPE, stdout=PIPE), ]) assert repo.get_last_tag() == '1.3.5'
def test_prestinerepo_creation(): """ Ensure that a brand new git repo is created when using PrestineRepo. """ temp_dir = '/tmp/aorta_tmp' clone_uri = 'no' mResult = Mock() mResult.returncode = 0 mockTmpdir = patch('reflex.repo.mkdtemp', return_value=temp_dir) mockPopen = patch('reflex.repo.Popen', return_value=mResult) mockRmtree = patch('reflex.repo.rmtree') with mockTmpdir as pTmpdir, mockPopen as pPopen, mockRmtree as pRmtree: with PrestineRepo(clone_uri) as repo: pTmpdir.assert_called_with() pPopen.assert_has_calls([ call(['git', 'clone', clone_uri, temp_dir], cwd=temp_dir, stderr=PIPE, stdout=PIPE), call(['git', 'fetch', 'origin'], cwd=temp_dir, stderr=PIPE, stdout=PIPE), ]) assert repo.dir == temp_dir assert repo.clone_uri == clone_uri assert repo.production_branch == 'master' assert repo.development_branches == ['develop'] pRmtree.assert_called_with(temp_dir)
def test_downloadStream_should_timeout_on_stall(self): ospatcher = patch("os.path.getsize") ospatcher.start() import os os.path.getsize = Mock() os.path.getsize.return_value = 1234 patcher = patch("subprocess.Popen") patcher.start() import subprocess popen = Mock() communicate = Mock() communicate.communicate.return_value = ("", "filesize 1234568\n") communicate.returncode = None popen.return_value = communicate subprocess.Popen = popen sys.modules["__main__"].xbmcvfs.exists.return_value = True downloader = self.SimpleDownloader.SimpleDownloader() communicate.stdout.read.return_value = "out" downloader._showMessage = Mock() downloader._updateProgress = Mock() downloader._downloadStream("filename", {"videoid": "someid", "url": "rtmp://url", "Title": "some_title", "download_path": "some_path", "path_incomplete": "incomplete_path", "total_size": 12340.0, "cmd_call": ['rtmpdump', '-r', 'rtmp://url', '-o', 'incomplete_path']}) ospatcher.stop() patcher.stop() result = popen.call_args_list[0][0][0] print repr(result) assert("rtmpdump" in result) assert("-r" in result) assert("rtmp://url" in result) assert("-o" in result) assert("incomplete_path" in result) assert(len(result) == 5)
def patch_popen(self, return_value=0): process = Mock() process.returncode = return_value process.communicate = Mock(return_value=('output', 'error output')) self.patch( provisioningserver.utils, 'Popen', Mock(return_value=process)) return process
def set_up(self): when(execution.LOGGER).info(ANY_ARGUMENTS).then_return(None) when(execution.LOGGER).error(ANY_ARGUMENTS).then_return(None) process_mock = Mock() process_mock.returncode = 0 self.process_mock = process_mock
def test_setup_default_grub(self, mock_Command_run, mock_sysconfig, mock_exists): grep_grub_option = Mock() grep_grub_option.returncode = 0 mock_Command_run.return_value = grep_grub_option grub_default = MagicMock() mock_sysconfig.return_value = grub_default mock_exists.return_value = True self.bootloader.terminal = 'serial' self.bootloader.theme = 'openSUSE' self.firmware.efi_mode.return_value = 'efi' self.bootloader._setup_default_grub() mock_sysconfig.assert_called_once_with('root_dir/etc/default/grub') grub_default.write.assert_called_once_with() assert grub_default.__setitem__.call_args_list == [ call('GRUB_BACKGROUND', '/boot/grub2/themes/openSUSE/background.png'), call('GRUB_CMDLINE_LINUX_DEFAULT', '"some-cmdline"'), call('GRUB_DISTRIBUTOR', '"Bob"'), call('GRUB_ENABLE_BLSCFG', 'true'), call('GRUB_ENABLE_CRYPTODISK', 'y'), call('GRUB_GFXMODE', '800x600'), call( 'GRUB_SERIAL_COMMAND', '"serial --speed=38400 --unit=0 --word=8 --parity=no --stop=1"' ), call('GRUB_TERMINAL', '"serial"'), call('GRUB_THEME', '/boot/grub2/themes/openSUSE/theme.txt'), call('GRUB_TIMEOUT', 10), call('GRUB_USE_INITRDEFI', 'true'), call('GRUB_USE_LINUXEFI', 'true'), call('SUSE_BTRFS_SNAPSHOT_BOOTING', 'true') ]
def test_raises_stderr_on_failure(self, Popen): result = Mock() result.returncode = 1 result.communicate.return_value = ('', 'error') Popen.return_value = result with self.assertRaises(AssetHandlerError): Exec().run('input')
def test_annotate_updates_available(mock_subprocess, mock_open, mock_name): mock_name.return_value = 'mynode' mock_process = Mock() mock_process.communicate.return_value = ( b'<stream><update-status><update-list><update interactive="message">' b'</update></update-list></update-status></stream>', b'' ) mock_process.returncode = 0 mock_subprocess.return_value = mock_process annotate_updates_available() assert mock_subprocess.call_args_list == [ call( ['zypper', '--non-interactive', '--xmlout', 'list-patches'], stdout=-1, stderr=-1, env=ANY ), call( ["kubectl", "annotate", "--overwrite", "node", "mynode", "caasp.suse.com/has-updates=yes"], stdout=-1, stderr=-1, env=ANY ), call( ["kubectl", "annotate", "--overwrite", "node", "mynode", "caasp.suse.com/has-security-updates=no"], stdout=-1, stderr=-1, env=ANY ), call( ["kubectl", "annotate", "--overwrite", "node", "mynode", "caasp.suse.com/has-disruptive-updates=yes"], stdout=-1, stderr=-1, env=ANY ) ]
def test_return_none_on_success(self, mock_os, mock_popen): mock_process = Mock() mock_process.communicate.return_value = '', '' mock_process.returncode = 0 mock_popen.return_value = mock_process mock_os.rmdir.return_value = None self.assertIsNone(lvm._umount('path'))
def test_run_job_no_watchdog(self, m_tempfile, m_safe_dump, m_mkdir, m_environ, m_popen, m_t_config, m_symlink_log, m_sleep): config = { "suite_path": "suite/path", "config": { "foo": "bar" }, "verbose": True, "owner": "the_owner", "archive_path": "archive/path", "name": "the_name", "description": "the_description", "worker_log": "worker/log.log", "job_id": "1", } m_tmp = MagicMock() temp_file = Mock() temp_file.name = "the_name" m_tmp.__enter__.return_value = temp_file m_tempfile.return_value = m_tmp env = dict(PYTHONPATH="python/path") m_environ.copy.return_value = env m_p = Mock() m_p.returncode = 1 m_popen.return_value = m_p m_t_config.results_server = False worker.run_job(config, "teuth/bin/path", "archive/dir", verbose=False) m_symlink_log.assert_called_with(config["worker_log"], config["archive_path"])
def test_raises_on_popen_returncode_not_0(self, mock_os, mock_popen): mock_process = Mock() mock_process.communicate.return_value = '', '' mock_process.returncode = 1 mock_popen.return_value = mock_process mock_os.rmdir.return_value = None self.assertRaises(Exception, lvm._umount, 'path')
def test_run_job_no_watchdog(self, m_tempfile, m_safe_dump, m_environ, m_popen, m_t_config, m_symlink_log, m_sleep): config = { "suite_path": "suite/path", "config": {"foo": "bar"}, "verbose": True, "owner": "the_owner", "archive_path": "archive/path", "name": "the_name", "description": "the_description", "worker_log": "worker/log.log" } m_tmp = MagicMock() temp_file = Mock() temp_file.name = "the_name" m_tmp.__enter__.return_value = temp_file m_tempfile.return_value = m_tmp env = dict(PYTHONPATH="python/path") m_environ.copy.return_value = env m_p = Mock() m_p.returncode = 1 m_popen.return_value = m_p m_t_config.results_server = False worker.run_job(config, "teuth/bin/path") m_symlink_log.assert_called_with(config["worker_log"], config["archive_path"])
def side_effect(cmd, *args, **kwargs): ret = Mock() ret.returncode = 0 git_command = cmd[1] if len(cmd) > 0 else None output = outputs.get(git_command, b'') ret.communicate.return_value = (output, b'') return ret
def test_run_job_with_watchdog(self, m_tempfile, m_safe_dump, m_mkdir, m_environ, m_popen, m_t_config, m_run_watchdog): config = { "suite_path": "suite/path", "config": { "foo": "bar" }, "verbose": True, "owner": "the_owner", "archive_path": "archive/path", "name": "the_name", "description": "the_description", "job_id": "1", } m_tmp = MagicMock() temp_file = Mock() temp_file.name = "the_name" m_tmp.__enter__.return_value = temp_file m_tempfile.return_value = m_tmp env = dict(PYTHONPATH="python/path") m_environ.copy.return_value = env m_p = Mock() m_p.returncode = 0 m_popen.return_value = m_p m_t_config.results_server = True worker.run_job(config, "teuth/bin/path", "archive/dir", verbose=False) m_run_watchdog.assert_called_with(m_p, config) expected_args = [ 'teuth/bin/path/teuthology', '-v', '--lock', '--block', '--owner', 'the_owner', '--archive', 'archive/path', '--name', 'the_name', '--description', 'the_description', '--', "the_name" ] m_popen.assert_called_with(args=expected_args, env=env)
def test_is_reboot_needed_falsey(mock_subprocess): mock_process = Mock() mock_process.communicate.return_value = (b'', b'') mock_process.returncode = ZYPPER_EXIT_INF_RESTART_NEEDED mock_subprocess.return_value = mock_process assert not is_reboot_needed()
def test_annotate_updates_available_is_reboot( mock_subprocess, mock_annotate, mock_name ): mock_name.return_value = 'mynode' mock_process = Mock() mock_process.communicate.return_value = ( b'<stream><update-status><update-list><update interactive="reboot">' b'</update></update-list></update-status></stream>', b'' ) mock_process.returncode = 0 mock_subprocess.return_value = mock_process annotate_updates_available() assert mock_subprocess.call_args_list == [ call( ['zypper', '--non-interactive', '--xmlout', 'list-patches'], stdout=-1, stderr=-1, env=ANY ) ] assert mock_annotate.call_args_list == [ call('node', 'mynode', KUBE_UPDATES_KEY, 'yes'), call('node', 'mynode', KUBE_SECURITY_UPDATES_KEY, 'no'), call('node', 'mynode', KUBE_DISRUPTIVE_UPDATES_KEY, 'yes') ]
def test_mysql_mode_locks_unlocks_tables(self, mock_create_dir, mock_get_lvm_info, mock_get_vol_fs_type, mock_popen): mock_get_vol_fs_type.return_value = 'xfs' mock_get_lvm_info.return_value = { 'volgroup': 'lvm_volgroup', 'srcvol': 'lvm_device', 'snap_path': 'snap_path'} mock_process = Mock() mock_process.communicate.return_value = '', '' mock_process.returncode = 0 mock_popen.return_value = mock_process backup_opt = Mock() backup_opt.snapshot = True backup_opt.lvm_auto_snap = '' backup_opt.path_to_backup = '/just/a/path' backup_opt.lvm_dirmount = '/var/mountpoint' backup_opt.lvm_snapperm = 'ro' backup_opt.mode = 'mysql' backup_opt.mysql_db_inst = Mock() mock_cursor = Mock() backup_opt.mysql_db_inst.cursor.return_value = mock_cursor self.assertTrue(lvm.lvm_snap(backup_opt)) first_call = call('FLUSH TABLES WITH READ LOCK') second_call = call('UNLOCK TABLES') self.assertEquals(first_call, mock_cursor.execute.call_args_list[0]) self.assertEquals(second_call, mock_cursor.execute.call_args_list[1])
def test_snapshot_mount_error_raises_Exception(self, mock_create_dir, mock_get_lvm_info, mock_get_vol_fs_type, mock_popen, mock_lvm_snap_remove): mock_get_vol_fs_type.return_value = 'xfs' mock_get_lvm_info.return_value = { 'volgroup': 'lvm_volgroup', 'srcvol': 'lvm_device', 'snap_path': 'snap_path' } mock_lvcreate_process, mock_mount_process = Mock(), Mock() mock_lvcreate_process.communicate.return_value = '', '' mock_lvcreate_process.returncode = 0 mock_mount_process.communicate.return_value = '', 'mount error' mock_mount_process.returncode = 1 mock_popen.side_effect = [mock_lvcreate_process, mock_mount_process] backup_opt = Mock() backup_opt.snapshot = True backup_opt.path_to_backup = '/just/a/path' backup_opt.lvm_dirmount = '/var/mountpoint' backup_opt.lvm_snapperm = 'ro' backup_opt.lvm_snapsize = '1G' with self.assertRaises(Exception) as cm: lvm.lvm_snap(backup_opt) the_exception = cm.exception self.assertIn('lvm snapshot mounting error', str(the_exception)) mock_lvm_snap_remove.assert_called_once_with(backup_opt)
def test_write_dhcp_config_invokes_script_correctly(self): mocked_proc = Mock() mocked_proc.returncode = 0 mocked_proc.communicate = Mock(return_value=('output', 'error output')) mocked_popen = self.patch(utils, "Popen", Mock(return_value=mocked_proc)) config_params = self.make_dhcp_config_params() write_dhcp_config(**config_params) # It should construct Popen with the right parameters. mocked_popen.assert_any_call([ "sudo", "-n", "maas-provision", "atomic-write", "--filename", celery_config.DHCP_CONFIG_FILE, "--mode", "0644" ], stdin=PIPE) # It should then pass the content to communicate(). content = config.get_config(**config_params).encode("ascii") mocked_proc.communicate.assert_any_call(content) # Similarly, it also writes the DHCPD interfaces to # /var/lib/maas/dhcpd-interfaces. mocked_popen.assert_any_call([ "sudo", "-n", "maas-provision", "atomic-write", "--filename", celery_config.DHCP_INTERFACES_FILE, "--mode", "0644" ], stdin=PIPE)
def test_annotate(mock_subprocess): mock_process = Mock() mock_process.communicate.return_value = (b'node/my-node-1 annotated', b'stderr') mock_process.returncode = 0 mock_subprocess.return_value = mock_process assert annotate('node', 'my-node-1', KUBE_DISRUPTIVE_UPDATES_KEY, 'yes') == 'node/my-node-1 annotated'
def test_is_mounted_false(self, mock_command): command = Mock() command.returncode = 1 mock_command.return_value = command assert self.mount_manager.is_mounted() is False mock_command.assert_called_once_with( command=['mountpoint', '-q', '/some/mountpoint'], raise_on_error=False)
def test_run_command_no_redirect(mock_subprocess): mock_popen = Mock() mock_popen.communicate.return_value = (None, None) mock_popen.returncode = 0 mock_subprocess.Popen.return_value = mock_popen run_command("ls -la", redirect_output=False) assert mock_subprocess.Popen("ls -la")
def test_run_command_failure(self, mock_subprocess): mock_process = Mock() mock_process.communicate.return_value = (None, None) mock_process.returncode = 1 mock_subprocess.return_value = mock_process try: run_command(['dummycmd', 'arg1']) == 'stdout' except Exception as e: assert 'Command "dummycmd arg1" failed' in str(e)
def test_configure_auth(self, mock_popen): p = Mock(Popen) mock_popen.return_value = p p.returncode = 0 p.communicate.return_value = self.to_bytes("out: foo"), self.to_bytes("error: bar") om_manager.config_opsman_auth(self.settings) mock_popen.assert_called_with( "om -k --target https://cf.example.com configure-authentication --username 'admin' --password 'monkey-123' --decryption-passphrase 'monkey-123'", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True )
def test_run_command(mock_subprocess): mock_process = Mock() mock_process.communicate.return_value = (b'stdout', b'stderr') mock_process.returncode = 0 mock_subprocess.return_value = mock_process result = run_command(['/bin/dummycmd', 'arg1']) assert result.output == "stdout" assert result.returncode == 0 assert result.error == 'stderr' mock_process.returncode = 1 result = run_command(['/bin/dummycmd', 'arg1']) assert result.output == "stdout" assert result.returncode == 1 mock_process.communicate.return_value = (b'', b'stderr') result = run_command(['/bin/dummycmd', 'arg1']) assert result.output == "" assert result.returncode == 1
def test_run_command(mock_subprocess): mock_popen = Mock() mock_popen.communicate.return_value = (None, None) mock_popen.returncode = 0 mock_subprocess.Popen.return_value = mock_popen run_command("ls") assert mock_subprocess.Popen.called_with( "ls", stdout=subprocess.PIPE, stderr=subprocess.STDOUT )
def test_pend_status_slow_lsf(self, status_process): """ Test LSF pending status when LSF is slow """ status_process_obj = Mock() status_process_obj.returncode = 0 status_process_obj.stdout = self.status_pend_please_wait status_process.return_value = status_process_obj status = self.lsf_client.status(self.example_id) expected_status = Status.PENDING, self.pend_reason self.assertEqual(status, expected_status)
def test_abort(self, abort_process): """ Test LSF abort """ abort_process_obj = Mock() abort_process_obj.returncode = 0 abort_process.return_value = abort_process_obj expected_command = ["bkill", "-g", self.example_lsf_id, "0"] aborted = self.lsf_client.abort(self.example_job_id) self.assertEqual(abort_process.call_args[0][0], expected_command) self.assertEqual(aborted, True)
def test_run_command_strip_response(mock_subprocess): expected = "test" mock_popen = Mock() mock_popen.communicate.return_value = ("{} \n".format(expected), None) mock_popen.returncode = 0 mock_subprocess.Popen.return_value = mock_popen output = run_command("ls") assert output == expected
def test_failing_git_command(self): """ Make sure we properly wrap up any failing git commands in an exception """ code = Code(self.build) proc_mock = Mock() proc_mock.returncode = 1 response = Response(proc_mock, '', 'herp derp') code._command = Mock(return_value=response) code._which_git = Mock(return_value='lol') code.update()
def test_which_git(self): """ Ensure that we can locate the git binary. We should store the path to the git binary. """ proc_mock = Mock() proc_mock.returncode = 0 response = Response(proc_mock, '/usr/local/bin/git', '') code = Code(self.build) code._command = Mock(return_value=response) assert_equal(code._which_git(), '/usr/local/bin/git')
def _mock_uploader_modules(self, emulate_success): self.mock_dict = {} popen_mock = Mock() popen_mock.communicate.return_value = ("scp_out dump", "scp_err dump") if emulate_success: popen_mock.returncode = 0 else: popen_mock.returncode = 1 subprocess_mock = Mock() subprocess_mock.Popen.return_value = popen_mock subprocess_mock.PIPE = "MYPIPE" tempfile_mock = Mock() tempfile_mock.mkstemp.return_value = ("my_handle", "my_tempfile_name") self.mock_dict["tempfile"] = tempfile_mock self.mock_dict["subprocess"] = subprocess_mock self.mock_dict["os"] = Mock() self.DPMS.module_uploader.modules = self.mock_dict
def setUp(self): mock_host_rpm_builder = Mock(HostRpmBuilder) mock_host_rpm_builder.hostname = 'berweb01' mock_host_rpm_builder.thread_name = 'thread-0' mock_host_rpm_builder.logger = Mock() mock_host_rpm_builder.work_dir = '/path/to/working/directory' mock_host_rpm_builder.rpm_build_dir = '/path/to/rpm/build/directory' mock_host_rpm_builder._tar_sources.return_value = '/path/to/tarred_sources.tar.gz' mock_process = Mock() mock_process.communicate.return_value = ('stdout', 'stderr') mock_process.returncode = 0 self.mock_host_rpm_builder = mock_host_rpm_builder self.mock_process = mock_process
def test_run_success(self, monkeypatch): job = DoitUnstableNoContinue(DODO_FILE, 't1', THIS_PATH) doit_result = SAMPLE_RESULT mock_result = Mock(return_value=doit_result) monkeypatch.setattr(job, "read_json_result", mock_result) mock_process = Mock() mock_process.returncode = 0 # success (ignore failed on data) yi = job.run() # 1) execute first time (run1, pause1) = yi.next() assert isinstance(run1, ProcessTask) assert 'run' in run1.cmd assert isinstance(pause1, TaskPause) run1.proc = mock_process py.test.raises(StopIteration, yi.next)
def test_run_error(self, monkeypatch): job = DoitUnstableNoContinue(DODO_FILE, 't1', THIS_PATH) doit_result = None mock_result = Mock(return_value=doit_result) monkeypatch.setattr(job, "read_json_result", mock_result) mock_process = Mock() mock_process.returncode = 1 yi = job.run() # 1) execute first time (run1, pause1) = yi.next() run1.proc = mock_process # 2) try again (run2, pause2) = yi.next() run2.proc = mock_process # 3 give-up py.test.raises(StopIteration, yi.next)
def test_using_mount(self, mock_get_mount_from_path, mock_lvm_guess, mock_popen): mock_get_mount_from_path.return_value = '/home/somedir', 'some-snap-path' mock_lvm_guess.side_effect = [(None, None, None), ('vg_test', 'lv_test', 'lvm_device')] mounts = ('/dev/mapper/vg_prova-lv_prova_vol1 /home/pippo ext4 rw,relatime,data=ordered 0 0') mocked_open_function = mock_open(read_data=mounts) mock_process = Mock() mock_process.returncode = 0 mock_popen.return_value = mock_process mock_process.communicate.return_value = '', '' with patch("__builtin__.open", mocked_open_function): res = lvm.get_lvm_info('lvm_auto_snap_value') expected_result = {'volgroup': 'vg_test', 'snap_path': 'some-snap-path', 'srcvol': 'lvm_device'} self.assertEquals(res, expected_result)
def test_recoverable_error(self, mock_popen): mock_popen_instance = Mock() mock_popen_instance.communicate.return_value = ("stdout", "stderr") mock_popen_instance.returncode = 0 mock_popen.return_value = mock_popen_instance self.aptd._call_apport_recoverable_error( "msg", "traceback-error", "custom:dupes:signature") mock_popen.assert_called_with( [APPORT_RECOVERABLE_ERROR], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # check that we really send the right data args, kwargs = mock_popen_instance.communicate.call_args self.assertEqual( kwargs["input"].split("\0"), [ 'DialogBody', 'msg', 'Traceback', 'traceback-error', 'DuplicateSignature', 'custom:dupes:signature', ])
def test_ok(self, mock_create_dir, mock_get_lvm_info, mock_get_vol_fs_type, mock_popen, mock_validate_lvm_params): mock_get_lvm_info.return_value = { 'volgroup': 'lvm_volgroup', 'srcvol': 'lvm_device', 'snap_path': 'snap_path'} mock_process = Mock() mock_process.communicate.return_value = '', '' mock_process.returncode = 0 mock_popen.return_value = mock_process backup_opt = Mock() backup_opt.snapshot = True backup_opt.lvm_auto_snap = '' backup_opt.path_to_backup = '/just/a/path' backup_opt.lvm_dirmount = '/var/mountpoint' backup_opt.lvm_snapperm = 'ro' backup_opt.lvm_volgroup = '' backup_opt.lvm_srcvol = '' self.assertTrue(lvm.lvm_snap(backup_opt))
def test_snapshot_fails(self, mock_create_dir, mock_get_lvm_info, mock_get_vol_fs_type, mock_popen, mock_validate_lvm_params): mock_get_lvm_info.return_value = { 'volgroup': 'lvm_volgroup', 'srcvol': 'lvm_device', 'snap_path': 'snap_path'} mock_process = Mock() mock_process.communicate.return_value = '', '' mock_process.returncode = 1 mock_popen.return_value = mock_process backup_opt = Mock() backup_opt.snapshot = True backup_opt.lvm_auto_snap = '' backup_opt.path_to_backup = '/just/a/path' backup_opt.lvm_dirmount = '/var/mountpoint' backup_opt.lvm_snapperm = 'ro' with self.assertRaises(Exception) as cm: lvm.lvm_snap(backup_opt) the_exception = cm.exception self.assertIn('lvm snapshot creation error', the_exception.message)
def test_run_job_with_watchdog(self, m_tempfile, m_safe_dump, m_mkdir, m_environ, m_popen, m_t_config, m_run_watchdog): config = { "suite_path": "suite/path", "config": {"foo": "bar"}, "verbose": True, "owner": "the_owner", "archive_path": "archive/path", "name": "the_name", "description": "the_description", "job_id": "1", } m_tmp = MagicMock() temp_file = Mock() temp_file.name = "the_name" m_tmp.__enter__.return_value = temp_file m_tempfile.return_value = m_tmp env = dict(PYTHONPATH="python/path") m_environ.copy.return_value = env m_p = Mock() m_p.returncode = 0 m_popen.return_value = m_p m_t_config.results_server = True worker.run_job(config, "teuth/bin/path", "archive/dir", verbose=False) m_run_watchdog.assert_called_with(m_p, config) expected_args = [ 'teuth/bin/path/teuthology', '-v', '--lock', '--block', '--owner', 'the_owner', '--archive', 'archive/path', '--name', 'the_name', '--description', 'the_description', '--', "the_name" ] m_popen.assert_called_with(args=expected_args, env=env)
def test_run_with_failures(self, monkeypatch): job = DoitUnstableNoContinue(DODO_FILE, 't1', THIS_PATH) doit_result = SAMPLE_RESULT mock_result = Mock(return_value=doit_result) monkeypatch.setattr(job, "read_json_result", mock_result) mock_process = Mock() mock_process.returncode = 1 yi = job.run() # 1) execute first time (run1, pause1) = yi.next() assert isinstance(run1, ProcessTask) assert 'run' in run1.cmd assert isinstance(pause1, TaskPause) run1.proc = mock_process # 2) execute second time (run2, pause2) = yi.next() run2.proc = mock_process assert 'run' in run2.cmd # 3) execute ignore (ignore, pause3) = yi.next() assert 'ignore' in ignore.cmd # final result is fail assert 'fail' == job.final_result['t1']['result']
def test_write_dhcp_config_invokes_script_correctly(self): mocked_proc = Mock() mocked_proc.returncode = 0 mocked_proc.communicate = Mock(return_value=('output', 'error output')) mocked_popen = self.patch( utils, "Popen", Mock(return_value=mocked_proc)) config_params = self.make_dhcp_config_params() write_dhcp_config(**config_params) # It should construct Popen with the right parameters. mocked_popen.assert_any_call( ["sudo", "-n", "maas-provision", "atomic-write", "--filename", celery_config.DHCP_CONFIG_FILE, "--mode", "0644"], stdin=PIPE) # It should then pass the content to communicate(). content = config.get_config(**config_params).encode("ascii") mocked_proc.communicate.assert_any_call(content) # Similarly, it also writes the DHCPD interfaces to # /var/lib/maas/dhcpd-interfaces. mocked_popen.assert_any_call( ["sudo", "-n", "maas-provision", "atomic-write", "--filename", celery_config.DHCP_INTERFACES_FILE, "--mode", "0644"], stdin=PIPE)
def test_raises_on_popen_returncode_not_0(self, mock_popen): mock_process = Mock() mock_process.communicate.return_value = '', '' mock_process.returncode = 1 mock_popen.return_value = mock_process self.assertRaises(Exception, lvm._lvremove, 'path')
def test_return_none_on_success(self, mock_popen): mock_process = Mock() mock_process.communicate.return_value = '', '' mock_process.returncode = 0 mock_popen.return_value = mock_process self.assertIsNone(lvm._lvremove('logicalvolume'))
def test_return_none_on_success(self, mock_popen): mock_process = Mock() mock_process.communicate.return_value = '', '' mock_process.returncode = 0 mock_popen.return_value = mock_process self.assertIsNone(lvm._umount('path'))
def test_successful_run(self, popen): proc = Mock() proc.returncode = 0 popen.return_value = proc self.assertEquals(self.bevel._run("foo", ["bar"]), 0)
def test_returns_stdout_on_success(self, Popen): result = Mock() result.returncode = 0 result.communicate.return_value = ('output', '') Popen.return_value = result self.assertEqual(Exec().run('input'), 'output')