Best Python code snippet using lisa_python
test_mach_commands.py
Source:test_mach_commands.py  
...31        pass32    def __exit__(self, type, value, traceback):33        pass34@contextmanager35def _get_command(klass=Perftest):36    from mozbuild.base import MozbuildObject37    from mozperftest.argparser import PerftestArgumentParser38    config = MozbuildObject.from_environment()39    class context:40        topdir = config.topobjdir41        cwd = os.getcwd()42        settings = {}43        log_manager = mock.Mock()44        state_dir = tempfile.mkdtemp()45    # used to make arguments passed by the test as46    # being set by the user.47    def _run_perftest(func):48        def _run(**kwargs):49            parser.set_by_user = list(kwargs.keys())50            return func(**kwargs)51        return _run52    try:53        obj = klass(context())54        parser = PerftestArgumentParser()55        obj.get_parser = lambda: parser56        if isinstance(obj, Perftest):57            obj.run_perftest = _run_perftest(obj.run_perftest)58        yield obj59    finally:60        shutil.rmtree(context.state_dir)61@mock.patch("mozperftest.MachEnvironment", new=_TestMachEnvironment)62@mock.patch("mozperftest.mach_commands.MachCommandBase.activate_virtualenv")63def test_command(mocked_func):64    with _get_command() as test, silence(test):65        test.run_perftest(tests=[EXAMPLE_TEST], flavor="desktop-browser")66@mock.patch("mozperftest.MachEnvironment")67@mock.patch("mozperftest.mach_commands.MachCommandBase.activate_virtualenv")68def test_command_iterations(venv, env):69    kwargs = {70        "tests": [EXAMPLE_TEST],71        "hooks": ITERATION_HOOKS,72        "flavor": "desktop-browser",73    }74    with _get_command() as test, silence(test):75        test.run_perftest(**kwargs)76    # the hook changes the iteration value to 5.77    # each iteration generates 5 calls, so we want to see 2578    assert len(env.mock_calls) == 2579@mock.patch("mozperftest.MachEnvironment")80@mock.patch("mozperftest.mach_commands.MachCommandBase.activate_virtualenv")81def test_hooks_state(venv, env):82    kwargs = {83        "tests": [EXAMPLE_TEST],84        "hooks": STATE_HOOKS,85        "flavor": "desktop-browser",86    }87    with _get_command() as test, silence(test):88        test.run_perftest(**kwargs)89@mock.patch("mozperftest.MachEnvironment", new=_TestMachEnvironment)90@mock.patch("mozperftest.mach_commands.MachCommandBase.activate_virtualenv")91@mock.patch("tryselect.push.push_to_try")92def test_push_command(push_to_try, venv):93    with _get_command() as test, silence(test):94        test.run_perftest(95            tests=[EXAMPLE_TEST],96            flavor="desktop-browser",97            push_to_try=True,98            try_platform="g5",99        )100        push_to_try.assert_called()101        # XXX add assertions102@mock.patch("mozperftest.MachEnvironment", new=_TestMachEnvironment)103@mock.patch("mozperftest.mach_commands.MachCommandBase.activate_virtualenv")104@mock.patch("tryselect.push.push_to_try")105def test_push_command_unknown_platforms(push_to_try, venv):106    # full stop when a platform is unknown107    with _get_command() as test, pytest.raises(NotImplementedError):108        test.run_perftest(109            tests=[EXAMPLE_TEST],110            flavor="desktop-browser",111            push_to_try=True,112            try_platform=["solaris", "linux", "mac"],113        )114@mock.patch("mozperftest.MachEnvironment", new=_TestMachEnvironment)115@mock.patch("mozperftest.mach_commands.MachCommandBase.activate_virtualenv")116@mock.patch("tryselect.push.push_to_try")117def test_push_command_several_platforms(push_to_try, venv):118    with running_on_try(False), _get_command() as test:  # , silence(test):119        test.run_perftest(120            tests=[EXAMPLE_TEST],121            flavor="desktop-browser",122            push_to_try=True,123            try_platform=["linux", "mac"],124        )125        push_to_try.assert_called()126        name, args, kwargs = push_to_try.mock_calls[0]127        params = kwargs["try_task_config"]["parameters"]["try_task_config"]128        assert "perftest-linux-try-browsertime" in params["tasks"]129        assert "perftest-macosx-try-browsertime" in params["tasks"]130@mock.patch("mozperftest.MachEnvironment", new=_TestMachEnvironment)131@mock.patch("mozperftest.mach_commands.MachCommandBase.activate_virtualenv")132def test_doc_flavor(mocked_func):133    with _get_command() as test, silence(test):134        test.run_perftest(tests=[EXAMPLE_TEST], flavor="doc")135@mock.patch("mozperftest.MachEnvironment", new=_TestMachEnvironment)136@mock.patch("mozperftest.mach_commands.MachCommandBase.activate_virtualenv")137@mock.patch("mozperftest.utils.run_script")138def test_test_runner(*mocked):139    with running_on_try(False), _get_command(PerftestTests) as test:140        test.run_tests(tests=[EXAMPLE_TEST], verbose=True)141@mock.patch("mozperftest.MachEnvironment", new=_TestMachEnvironment)142@mock.patch("mozperftest.mach_commands.MachCommandBase.activate_virtualenv")143@mock.patch("mozperftest.utils.run_python_script")144def test_test_runner_on_try(*mocked):145    # simulating on try to run the paths parser146    with running_on_try(), _get_command(PerftestTests) as test:147        test.run_tests(tests=[EXAMPLE_TEST])148@mock.patch("mozperftest.MachEnvironment", new=_TestMachEnvironment)149@mock.patch("mozperftest.mach_commands.MachCommandBase.activate_virtualenv")150@mock.patch("mozperftest.utils.run_script")151def test_test_runner_coverage(*mocked):152    # simulating with coverage not installed153    with running_on_try(False), _get_command(PerftestTests) as test:154        old = list(sys.meta_path)155        sys.meta_path = []156        try:157            test.run_tests(tests=[EXAMPLE_TEST])158        finally:159            sys.meta_path = old160def fzf_selection(*args):161    try:162        full_path = args[-1][-1]["path"]163    except IndexError:164        return []165    path = Path(full_path.replace(str(ROOT), ""))166    return [f"[bt][sometag] {path.name} in {path.parent}"]167def resolve_tests(tests=None):168    if tests is None:169        tests = [{"path": str(EXAMPLE_TEST)}]170    def _resolve(*args, **kw):171        return tests172    return _resolve173@mock.patch("mozperftest.MachEnvironment", new=_TestMachEnvironment)174@mock.patch("mozperftest.mach_commands.MachCommandBase.activate_virtualenv")175@mock.patch("mozperftest.fzf.fzf.select", new=fzf_selection)176@mock.patch("moztest.resolve.TestResolver.resolve_tests", new=resolve_tests())177def test_fzf_flavor(*mocked):178    with running_on_try(False), _get_command() as test:  # , silence():179        test.run_perftest(flavor="desktop-browser")180@mock.patch("mozperftest.MachEnvironment", new=_TestMachEnvironment)181@mock.patch("mozperftest.mach_commands.MachCommandBase.activate_virtualenv")182@mock.patch("mozperftest.fzf.fzf.select", new=fzf_selection)183@mock.patch("moztest.resolve.TestResolver.resolve_tests", new=resolve_tests([]))184def test_fzf_nothing_selected(*mocked):185    with running_on_try(False), _get_command() as test, silence():186        test.run_perftest(flavor="desktop-browser")187if __name__ == "__main__":...test_userdatautils.py
Source:test_userdatautils.py  
...27    except OSError:28        pass29@mock.patch('cloudbaseinit.osutils.factory.get_os_utils')30class UserDataUtilsTest(unittest.TestCase):31    def _get_command(self, data):32        """Get a command from the given data.33        If a command was obtained, then a cleanup will be added in order34        to remove the underlying target path of the command.35        """36        command = userdatautils._get_command(data)37        if command and not isinstance(command, execcmd.CommandExecutor):38            self.addCleanup(_safe_remove, command._target_path)39        return command40    def test__get_command(self, _):41        command = self._get_command(b'rem cmd test')42        self.assertIsInstance(command, execcmd.Shell)43        command = self._get_command(b'#!/usr/bin/env python\ntest')44        self.assertIsInstance(command, execcmd.Python)45        command = self._get_command(b'#!/bin/bash')46        self.assertIsInstance(command, execcmd.Bash)47        command = self._get_command(b'#ps1_sysnative\n')48        self.assertIsInstance(command, execcmd.PowershellSysnative)49        command = self._get_command(b'#ps1_x86\n')50        self.assertIsInstance(command, execcmd.Powershell)51        command = self._get_command(b'<script>echo test</script>')52        self.assertIsInstance(command, execcmd.CommandExecutor)53        command = self._get_command(b'unknown')54        self.assertIsNone(command)55    def test_execute_user_data_script_no_commands(self, _):56        retval = userdatautils.execute_user_data_script(b"unknown")57        self.assertEqual(0, retval)58    @mock.patch('cloudbaseinit.plugins.common.userdatautils.'59                '_get_command')60    def test_execute_user_data_script_fails(self, mock_get_command, _):61        mock_get_command.return_value.side_effect = ValueError62        retval = userdatautils.execute_user_data_script(63            mock.sentinel.user_data)64        self.assertEqual(0, retval)65    @mock.patch('cloudbaseinit.plugins.common.userdatautils.'66                '_get_command')67    def test_execute_user_data_script(self, mock_get_command, _):...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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
