Best Python code snippet using autotest_python
_mock_backport.py
Source:_mock_backport.py  
...402        if sf is not None and not callable(sf) and not isinstance(sf, _MockIter):403            sf = _MockIter(sf)404            delegated.side_effect = sf405        return sf406    def __set_side_effect(self, value):407        value = _try_iter(value)408        delegated = self._mock_delegate409        if delegated is None:410            self._mock_side_effect = value411        else:412            delegated.side_effect = value413    side_effect = property(__get_side_effect, __set_side_effect)414    def reset_mock(self):415        "Restore the mock object to its initial state."416        self.called = False417        self.call_args = None418        self.call_count = 0419        self.mock_calls = _CallList()420        self.call_args_list = _CallList()...mock.py
Source:mock.py  
...372        sig = self._mock_delegate373        if sig is None:374            return self._mock_side_effect375        return sig.side_effect376    def __set_side_effect(self, value):377        value = _try_iter(value)378        sig = self._mock_delegate379        if sig is None:380            self._mock_side_effect = value381        else:382            sig.side_effect = value383    side_effect = property(__get_side_effect, __set_side_effect)384    def reset_mock(self):385        self.called = False386        self.call_args = None387        self.call_count = 0388        self.mock_calls = _CallList()389        self.call_args_list = _CallList()390        self.method_calls = _CallList()...profile.py
Source:profile.py  
1'''2Profiling plugin for pytest, with tabular and heat graph output.3Tests are profiled with cProfile_ and analysed with pstats_; heat graphs are4generated using gprof2dot_ and dot_.5.. _cProfile: http://docs.python.org/library/profile.html#module-cProfile6.. _pstats: http://docs.python.org/library/profile.html#pstats.Stats7.. _gprof2dot: http://code.google.com/p/jrfonseca/wiki/Gprof2Dot8.. _dot: http://www.graphviz.org/9Usage10-----11Once the enclosing package is installed into your virtualenv, the plugin12provides extra options to pytest::13    $ py.test --help14    ...15      Profiling:16        --profile           generate profiling information17        --profile-svg       generate profiling graph (using gprof2dot and dot18                            -Tsvg)19The ``--profile`` and ``profile-svg`` options can be combined with any other20option::21    $ py.test tests/unit/test_logging.py --profile22    ============================= test session starts ==============================23    platform linux2 -- Python 2.6.2 -- pytest-2.2.324    collected 3 items25    tests/unit/test_logging.py ...26    Profiling (from prof/combined.prof):27    Fri Oct 26 11:05:00 2012    prof/combined.prof28             289 function calls (278 primitive calls) in 0.001 CPU seconds29       Ordered by: cumulative time30       List reduced from 61 to 20 due to restriction <20>31       ncalls  tottime  percall  cumtime  percall filename:lineno(function)32            3    0.000    0.000    0.001    0.000 <string>:1(<module>)33          6/3    0.000    0.000    0.001    0.000 core.py:344(execute)34            3    0.000    0.000    0.001    0.000 python.py:63(pytest_pyfunc_call)35            1    0.000    0.000    0.001    0.001 test_logging.py:34(test_flushing)36            1    0.000    0.000    0.000    0.000 _startup.py:23(_flush)37            2    0.000    0.000    0.000    0.000 mock.py:979(__call__)38            2    0.000    0.000    0.000    0.000 mock.py:986(_mock_call)39            4    0.000    0.000    0.000    0.000 mock.py:923(_get_child_mock)40            6    0.000    0.000    0.000    0.000 mock.py:512(__new__)41            2    0.000    0.000    0.000    0.000 mock.py:601(__get_return_value)42            4    0.000    0.000    0.000    0.000 mock.py:695(__getattr__)43            6    0.000    0.000    0.000    0.000 mock.py:961(__init__)44        22/14    0.000    0.000    0.000    0.000 mock.py:794(__setattr__)45            6    0.000    0.000    0.000    0.000 core.py:356(getkwargs)46            6    0.000    0.000    0.000    0.000 mock.py:521(__init__)47            3    0.000    0.000    0.000    0.000 skipping.py:122(pytest_pyfunc_call)48            6    0.000    0.000    0.000    0.000 core.py:366(varnames)49            3    0.000    0.000    0.000    0.000 skipping.py:125(check_xfail_no_run)50            2    0.000    0.000    0.000    0.000 mock.py:866(assert_called_once_with)51            6    0.000    0.000    0.000    0.000 mock.py:645(__set_side_effect)52    =========================== 3 passed in 0.13 seconds ===========================53pstats files (one per test item) are retained for later analysis in ``prof``54directory, along with a ``combined.prof`` file::55    $ ls -1 prof/56    combined.prof57    test_app.prof58    test_flushing.prof59    test_import.prof60If the ``--profile-svg`` option is given, along with the prof files and tabular61output a svg file will be generated::62    $ py.test tests/unit/test_logging.py --profile-svg63    ...64    SVG profile in prof/combined.svg.65This is best viewed with a good svg viewer e.g. Chrome.66.. image:: ../_static/profile_combined.svg67'''68from __future__ import absolute_import69import pytest70import os71import cProfile72import pstats73import pipes74class Profiling(object):75    """Profiling plugin for pytest."""76    svg = False77    svg_name = None78    profs = []79    combined = None80    def __init__(self, svg):81        self.svg = svg82        self.profs = []83    def pytest_sessionstart(self, session):  # @UnusedVariable84        try:85            os.makedirs("prof")86        except OSError:87            pass88    def pytest_sessionfinish(self, session, exitstatus):  # @UnusedVariable89        if self.profs:90            combined = pstats.Stats(self.profs[0])91            for prof in self.profs[1:]:92                combined.add(prof)93            self.combined = os.path.join("prof", "combined.prof")94            combined.dump_stats(self.combined)95            if self.svg:96                self.svg_name = os.path.join("prof", "combined.svg")97                t = pipes.Template()98                t.append("gprof2dot -f pstats $IN", "f-")99                t.append("dot -Tsvg -o $OUT", "-f")100                t.copy(self.combined, self.svg_name)101    def pytest_terminal_summary(self, terminalreporter):102        if self.combined:103            terminalreporter.write("Profiling (from {prof}):\n".format(prof=self.combined))104            pstats.Stats(self.combined, stream=terminalreporter).strip_dirs().sort_stats('cumulative').print_stats(20)105        if self.svg_name:106            terminalreporter.write("SVG profile in {svg}.\n".format(svg=self.svg_name))107    @pytest.mark.tryfirst108    def pytest_pyfunc_call(self, __multicall__, pyfuncitem):109        """Hook into pytest_pyfunc_call; marked as a tryfirst hook so that we110        can call everyone else inside `cProfile.runctx`.111        """112        prof = os.path.join("prof", pyfuncitem.name + ".prof")113        cProfile.runctx("fn()", globals(), dict(fn=__multicall__.execute), filename=prof)114        self.profs.append(prof)115def pytest_addoption(parser):116    """pytest_addoption hook for profiling plugin"""117    group = parser.getgroup('Profiling')118    group.addoption("--profile", action="store_true",119                    help="generate profiling information")120    group.addoption("--profile-svg", action="store_true",121                    help="generate profiling graph (using gprof2dot and dot -Tsvg)")122def pytest_configure(config):123    """pytest_configure hook for profiling plugin"""124    profile_enable = any(config.getvalue(x) for x in ('profile', 'profile_svg'))125    if profile_enable:...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!!
