### Manage patches with start and stop in setUp and tearDown Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst Move patching into setUp and tearDown using patcher.start() and patcher.stop(). You must ensure stop() is called to undo the patch. ```python3 >>> class MyTest(unittest.TestCase): ... def setUp(self): ... self.patcher = patch('mymodule.foo') ... self.mock_foo = self.patcher.start() ... ... def test_foo(self): ... self.assertIs(mymodule.foo, self.mock_foo) ... ... def tearDown(self): ... self.patcher.stop() ... >>> MyTest('test_foo').run() ``` -------------------------------- ### Multiple patches in setUp and tearDown Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock.rst Start multiple patches in setUp and stop them in tearDown. This avoids nesting decorators or context managers. ```python3 >>> class MyTest(unittest.TestCase): ... def setUp(self): ... self.patcher1 = patch('package.module.Class1') ... self.patcher2 = patch('package.module.Class2') ... self.MockClass1 = self.patcher1.start() ... self.MockClass2 = self.patcher2.start() ... ... def tearDown(self): ... self.patcher1.stop() ... self.patcher2.stop() ... ... def test_something(self): ... assert package.module.Class1 is self.MockClass1 ... assert package.module.Class2 is self.MockClass2 ... >>> MyTest('test_something').run() ``` -------------------------------- ### setup_scripts(context) Source: https://github.com/python/cpython/blob/main/Doc/library/venv.rst Installs activation scripts appropriate to the platform into the virtual environment. ```APIDOC ## setup_scripts(context) ### Description Installs activation scripts appropriate to the platform into the virtual environment. ### Method `setup_scripts` ### Parameters - **context** (types.SimpleNamespace) - Required - The context object returned by `ensure_directories`. ``` -------------------------------- ### Use addCleanup to ensure patcher.stop() is called Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst Use unittest.TestCase.addCleanup() to register patcher.stop() so the patch is undone even if setUp raises an exception. ```python3 >>> class MyTest(unittest.TestCase): ... def setUp(self): ... patcher = patch('mymodule.foo') ... self.addCleanup(patcher.stop) ... self.mock_foo = patcher.start() ... ... def test_foo(self): ... self.assertIs(mymodule.foo, self.mock_foo) ... >>> MyTest('test_foo').run() ``` -------------------------------- ### turtle.setup(width=_CFG['width'], height=_CFG['height'], startx=_CFG['leftright'], starty=_CFG['topbottom']) Source: https://github.com/python/cpython/blob/main/Doc/library/turtle.rst Sets the size and position of the main window. Default values are stored in the configuration dictionary and can be changed via a turtle.cfg file. ```APIDOC ## turtle.setup(width=_CFG['width'], height=_CFG['height'], startx=_CFG['leftright'], starty=_CFG['topbottom']) ### Description Set the size and position of the main window. Default values of arguments are stored in the configuration dictionary and can be changed via a `turtle.cfg` file. ### Method Function ### Parameters - **width** (int or float) – Optional – if an integer, a size in pixels, if a float, a fraction of the screen; default is 50% of screen - **height** (int or float) – Optional – if an integer, the height in pixels, if a float, a fraction of the screen; default is 75% of screen - **startx** (int or None) – Optional – if positive, starting position in pixels from the left edge of the screen, if negative from the right edge, if `None`, center window horizontally - **starty** (int or None) – Optional – if positive, starting position in pixels from the top edge of the screen, if negative from the bottom edge, if `None`, center window vertically ### Return Value None ``` -------------------------------- ### Set an attribute on a Mock Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst Assign an attribute directly on a Mock instance to set its value. ```pycon >>> mock = Mock() >>> mock.x = 3 >>> mock.x 3 ``` -------------------------------- ### Example class with chained backend calls Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst A sample class Something whose method calls a chain of methods on self.backend. Used to illustrate testing chained calls. ```pycon >>> class Something: ... def __init__(self): ... self.backend = BackendProvider() ... def method(self): ... response = self.backend.get_endpoint('foobar').create_call('spam', 'eggs').start_call() ... # more code ``` -------------------------------- ### Include Python.h for PyArg_ParseTuple examples Source: https://github.com/python/cpython/blob/main/Doc/extending/extending.rst Required header for the PyArg_ParseTuple example calls that follow. ```c #include ``` -------------------------------- ### ExtendedEnvBuilder with install_setuptools and install_pip and main Source: https://github.com/python/cpython/blob/main/Doc/library/venv.rst Example script extending EnvBuilder to install setuptools and pip, with a command-line main() supporting --no-setuptools, --no-pip, --system-site-packages, --symlinks, --clear, --upgrade, and --verbose. Supplying --upgrade and --clear together raises ValueError. ```python :param context: The information for the virtual environment creation request being processed. """ url = "https://bootstrap.pypa.io/ez_setup.py" self.install_script(context, 'setuptools', url) # clear up the setuptools archive which gets downloaded pred = lambda o: o.startswith('setuptools-') and o.endswith('.tar.gz') files = filter(pred, os.listdir(context.bin_path)) for f in files: f = os.path.join(context.bin_path, f) os.unlink(f) def install_pip(self, context): """ Install pip in the virtual environment. :param context: The information for the virtual environment creation request being processed. """ url = 'https://bootstrap.pypa.io/get-pip.py' self.install_script(context, 'pip', url) def main(args=None): import argparse parser = argparse.ArgumentParser(prog=__name__, description='Creates virtual Python ' 'environments in one or ' 'more target ' 'directories.') parser.add_argument('dirs', metavar='ENV_DIR', nargs='+', help='A directory in which to create the ' 'virtual environment.') parser.add_argument('--no-setuptools', default=False, action='store_true', dest='nodist', help="Don't install setuptools or pip in the " "virtual environment.") parser.add_argument('--no-pip', default=False, action='store_true', dest='nopip', help="Don't install pip in the virtual " "environment.") parser.add_argument('--system-site-packages', default=False, action='store_true', dest='system_site', help='Give the virtual environment access to the ' 'system site-packages dir.') if os.name == 'nt': use_symlinks = False else: use_symlinks = True parser.add_argument('--symlinks', default=use_symlinks, action='store_true', dest='symlinks', help='Try to use symlinks rather than copies, ' 'when symlinks are not the default for ' 'the platform.') parser.add_argument('--clear', default=False, action='store_true', dest='clear', help='Delete the contents of the ' 'virtual environment ' 'directory if it already ' 'exists, before virtual ' 'environment creation.') parser.add_argument('--upgrade', default=False, action='store_true', dest='upgrade', help='Upgrade the virtual ' 'environment directory to ' 'use this version of ' 'Python, assuming Python ' 'has been upgraded ' 'in-place.') parser.add_argument('--verbose', default=False, action='store_true', dest='verbose', help='Display the output ' 'from the scripts which ' 'install setuptools and pip.') options = parser.parse_args(args) if options.upgrade and options.clear: raise ValueError('you cannot supply --upgrade and --clear together.') builder = ExtendedEnvBuilder(system_site_packages=options.system_site, clear=options.clear, symlinks=options.symlinks, upgrade=options.upgrade, nodist=options.nodist, nopip=options.nopip, verbose=options.verbose) for d in options.dirs: builder.create(d) if __name__ == '__main__': rc = 1 try: main() rc = 0 except Exception as e: print('Error: %s' % e, file=sys.stderr) sys.exit(rc) ``` ``` -------------------------------- ### Set mock return_value Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst Assign return_value on a Mock to control the value returned when the mock is called. ```pycon >>> mock = Mock() >>> mock.return_value = 3 >>> mock() 3 ``` -------------------------------- ### Add dependency metadata with setup() requires, obsoletes, and download_url Source: https://github.com/python/cpython/blob/main/Doc/whatsnew/2.5.rst Use the new setup() keyword parameters requires, provides, obsoletes, and download_url to record dependency information. Building a source distribution with the sdist command records this dependency information in the PKG-INFO file. ```python VERSION = '1.0' setup(name='PyPackage', version=VERSION, requires=['numarray', 'zlib (>=1.1.4)'], obsoletes=['OldPackage'] download_url=('http://www.example.com/pypackage/dist/pkg-%s.tar.gz' % VERSION), ) ``` -------------------------------- ### Checking arguments inside side_effect for single-use mock Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst When the mock is used only once, you can assert inside a side_effect function. The example shows a passing call with {6} and a failing call with set(). ```pycon >>> def side_effect(arg): ... assert arg == {6} ... >>> mock = Mock(side_effect=side_effect) >>> mock({6}) >>> mock(set()) Traceback (most recent call last): ... AssertionError ``` -------------------------------- ### Raise an exception with side_effect Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst Set side_effect to an exception class or instance to raise that exception when the mock is called. ```pycon >>> mock = Mock(side_effect=Exception('Boom!')) >>> mock() Traceback (most recent call last): ... Exception: Boom! ``` -------------------------------- ### post_setup(context) Source: https://github.com/python/cpython/blob/main/Doc/library/venv.rst A placeholder method which can be overridden in third party implementations to pre-install packages in the virtual environment or perform other post-creation steps. ```APIDOC ## post_setup(context) ### Description A placeholder method which can be overridden in third party implementations to pre-install packages in the virtual environment or perform other post-creation steps. ### Method `post_setup` ### Parameters - **context** (types.SimpleNamespace) - Required - The context object returned by `ensure_directories`. ``` -------------------------------- ### Example command line using --file and -q Source: https://github.com/python/cpython/blob/main/Doc/library/optparse.rst Invoking the script with --file=outfile and -q sets options.filename to "outfile" and options.verbose to False. ```python3 --file=outfile -q ``` -------------------------------- ### Apply patch as class decorator to all test methods Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst Use patch() as a class decorator to apply the same patch to every test method (methods starting with 'test'). Non-test methods are not patched. ```python3 >>> @patch('mymodule.SomeClass') ... class MyTest(unittest.TestCase): ... ... def test_one(self, MockSomeClass): ... self.assertIs(mymodule.SomeClass, MockSomeClass) ... ... def test_two(self, MockSomeClass): ... self.assertIs(mymodule.SomeClass, MockSomeClass) ... ... def not_a_test(self): ... return 'something' ... >>> MyTest('test_one').test_one() >>> MyTest('test_two').test_two() >>> MyTest('test_two').not_a_test() 'something' ``` -------------------------------- ### Benchmark expressions with setup via CLI Source: https://github.com/python/cpython/blob/main/Doc/library/timeit.rst Provide a setup statement with -s that executes once before benchmarking expressions. The output displays loop count, repetition count, and the average time of the fastest repetition. ```shell-session $ python -m timeit -s "text = 'sample string'; char = 'g'" "char in text" 5000000 loops, best of 5: 0.0877 usec per loop $ python -m timeit -s "text = 'sample string'; char = 'g'" "text.find(char)" 1000000 loops, best of 5: 0.342 usec per loop ``` -------------------------------- ### Set return_value in Mock constructor Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst Pass return_value to the Mock constructor to set the return value at creation time. ```pycon >>> mock = Mock(return_value=3) >>> mock() 3 ``` -------------------------------- ### Set return_value on a mock method Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst Set return_value on a method attribute of a Mock to control the value returned when that method is called. ```pycon >>> mock = Mock() >>> mock.method.return_value = 3 >>> mock.method() 3 ``` -------------------------------- ### Create a virtual environment and install a package Source: https://github.com/python/cpython/blob/main/Doc/library/importlib.metadata.rst Sets up an isolated virtual environment and installs the target package using pip. ```shell-session $ python -m venv example $ source example/bin/activate (example) $ python -m pip install wheel ``` -------------------------------- ### Benchmark expressions with setup using timeit.timeit() Source: https://github.com/python/cpython/blob/main/Doc/library/timeit.rst Use the timeit() function directly in Python, supplying the setup keyword argument for statements executed once before timing. ```python3 >>> import timeit >>> timeit.timeit('char in text', setup='text = "sample string"; char = "g"') 0.41440500499993504 >>> timeit.timeit('text.find(char)', setup='text = "sample string"; char = "g"') 1.7246671520006203 ``` -------------------------------- ### Assert method called with assert_called_once_with Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst Patch a method on ProductionClass with MagicMock and verify it was called once with the expected arguments using assert_called_once_with. ```pycon >>> class ProductionClass: ... def method(self): ... self.something(1, 2, 3) ... def something(self, a, b, c): ... pass ... >>> real = ProductionClass() >>> real.something = MagicMock() >>> real.method() >>> real.something.assert_called_once_with(1, 2, 3) ``` -------------------------------- ### Install LLVM 21 on Ubuntu or Debian Source: https://github.com/python/cpython/blob/main/Tools/jit/README.md Download and run the official LLVM setup script to install LLVM 21 on Ubuntu and Debian distributions. ```sh wget https://apt.llvm.org/llvm.sh chmod +x llvm.sh sudo ./llvm.sh 21 ``` -------------------------------- ### Use create_patch helper with addCleanup to avoid nested patches Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst A `create_patch` helper starts a patch, registers `patcher.stop` with `addCleanup`, and returns the mock. This avoids nested `with` indentation while still restoring the original after the test. ```python3 >>> class MyTest(unittest.TestCase): ... ... def create_patch(self, name): ... patcher = patch(name) ... thing = patcher.start() ... self.addCleanup(patcher.stop) ... return thing ... ... def test_foo(self): ... mock_foo = self.create_patch('mymodule.Foo') ... mock_bar = self.create_patch('mymodule.Bar') ... mock_spam = self.create_patch('mymodule.Spam') ... ... assert mymodule.Foo is mock_foo ... assert mymodule.Bar is mock_bar ... assert mymodule.Spam is mock_spam ... >>> original = mymodule.Foo >>> MyTest('test_foo').run() >>> assert mymodule.Foo is original ``` -------------------------------- ### ,Run simple_logging_config.py and view console output Source: https://github.com/python/cpython/blob/main/Doc/howto/logging.rst ,Shows the command to run the fileConfig-based logging example and the resulting formatted log lines. The output is nearly identical to the non-config-file example, using the simpleExample logger name. ```,shell-session ,$ python simple_logging_config.py 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message 2005-03-19 15:38:55,979 - simpleExample - INFO - info message 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message ``` -------------------------------- ### Define a class with a generator method iter Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst Example class Foo whose iter method is a generator yielding 1, 2, 3. Calling list(foo.iter()) returns [1, 2, 3]. ```pycon >>> class Foo: ... def iter(self): ... for i in [1, 2, 3]: ... yield i ... >>> foo = Foo() >>> list(foo.iter()) [1, 2, 3] ``` -------------------------------- ### setup.py for custom extension Source: https://github.com/python/cpython/blob/main/Doc/extending/newtypes_tutorial.rst Setup script that defines the extension module. ```python from setuptools import Extension, setup setup(ext_modules=[Extension("custom", ["custom.c"])]) ``` -------------------------------- ### Matcher failure raises AssertionError Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst When the matcher does not match the actual call, assert_called_with raises an AssertionError showing the expected and actual calls. ```pycon >>> match_wrong = Matcher(compare, Foo(3, 4)) >>> mock.assert_called_with(match_wrong) Traceback (most recent call last): ... AssertionError: Expected: ((,), {}) Called with: ((,), {}) ``` -------------------------------- ### Update setup.py to include custom2 module Source: https://github.com/python/cpython/blob/main/Doc/extending/newtypes_tutorial.rst Updates setup.py to build both the original custom module and the new custom2 module. ```python from setuptools import Extension, setup setup(ext_modules=[ Extension("custom", ["custom.c"]), Extension("custom2", ["custom2.c"]), ]) ``` -------------------------------- ### Build C extensions using Extension and ext_modules Source: https://github.com/python/cpython/blob/main/Doc/whatsnew/2.0.rst Configure C extensions using `Extension` by specifying macro definitions, include directories, and source files. Pass the configured extension instances to `setup()` via `ext_modules` for automated compilation during install. ```python3 from distutils.core import setup, Extension expat_extension = Extension('xml.parsers.pyexpat', define_macros = [('XML_NS', None)], include_dirs = [ 'extensions/expat/xmltok', 'extensions/expat/xmlparse' ], sources = [ 'extensions/pyexpat.c', 'extensions/expat/xmltok/xmltok.c', 'extensions/expat/xmltok/xmlrole.c', ] ) setup (name = "PyXML", version = "0.5.4", ext_modules =[ expat_extension ] ) ``` -------------------------------- ### Assert most recent call with assert_called_with Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst Use assert_called_with to assert the most recent call to a mock. Set return_value and call the mock before asserting. ```pycon >>> mock = Mock() >>> mock.foo_bar.return_value = None >>> mock.foo_bar('baz', spam='eggs') >>> mock.foo_bar.assert_called_with('baz', spam='eggs') ``` -------------------------------- ### Set chained return value directly Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst Directly assign the return value for the final start_call in a chain by traversing return_value attributes. ```python3 mock_backend.get_endpoint.return_value.create_call.return_value.start_call.return_value = mock_response ``` -------------------------------- ### Example config.site file for configure overrides Source: https://github.com/python/cpython/blob/main/Doc/using/configure.rst Points CONFIG_SITE at a file containing configure variable overrides. This example sets getaddrinfo and device file cache variables for an aarch64 build. ```ini # config.site-aarch64 ac_cv_buggy_getaddrinfo=no ac_cv_file__dev_ptmx=yes ac_cv_file__dev_ptc=no ``` -------------------------------- ### Serve a WSGI application using setup_testing_defaults Source: https://github.com/python/cpython/blob/main/Doc/library/wsgiref.rst Populate the WSGI environment with default testing parameters and serve an application using make_server. This routine supplies dummy data for unit tests and should not be used in production servers or applications. ```python3 from wsgiref.util import setup_testing_defaults from wsgiref.simple_server import make_server # A relatively simple WSGI application. It's going to print out the # environment dictionary after being updated by setup_testing_defaults def simple_app(environ, start_response): setup_testing_defaults(environ) status = '200 OK' headers = [('Content-type', 'text/plain; charset=utf-8')] start_response(status, headers) ret = [("%s: %s\n" % (key, value)).encode("utf-8") for key, value in environ.items()] return ret with make_server('', 8000, simple_app) as httpd: print("Serving on port 8000...") httpd.serve_forever() ``` -------------------------------- ### Use an iterable side_effect to return different values Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst Set side_effect to an iterable so each call to the mock returns the next value from the iterable. ```pycon >>> mock = MagicMock(side_effect=[4, 5, 6]) >>> mock() 4 >>> mock() 5 >>> mock() 6 ``` -------------------------------- ### Create Testmapi.py using MAPI and win32api Source: https://github.com/python/cpython/blob/main/Tools/freeze/win32.html Initializes MAPI, queries the computer name via win32api, and uninitializes MAPI. ```python from win32com.mapi import mapi import win32api mapi.MAPIInitialize( (mapi.MAPI\_INIT\_VERSION, 0) ) print "Hello from", win32api.GetComputerName() mapi.MAPIUninitialize() ``` -------------------------------- ### Find all adverbs and their positions with re.finditer() Source: https://github.com/python/cpython/blob/main/Doc/library/re.rst Use re.finditer() to get Match objects instead of strings, providing more information about all matches. The example prints the start and end positions of each adverb. ```python3 >>> text = "He was carefully disguised but captured quickly by police." >>> for m in re.finditer(r"\w+ly\b", text): ... print('%02d-%02d: %s' % (m.start(), m.end(), m.group(0))) 07-16: carefully 40-47: quickly ``` -------------------------------- ### Run module with verbose output Source: https://github.com/python/cpython/blob/main/Doc/library/doctest.rst Use the -v switch to get a detailed report of all examples tried and summaries. ```python3 python M.py -v ``` -------------------------------- ### Assert calls in any order with assert_has_calls(any_order=True) Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst Pass any_order=True to assert_has_calls() to check that the specified calls were made without requiring a particular order. ```pycon >>> m = MagicMock() >>> m(1), m.two(2, 3), m.seven(7), m.fifty('50') (...) >>> calls = [call.fifty('50'), call(1), call.seven(7)] >>> m.assert_has_calls(calls, any_order=True) ``` -------------------------------- ### Install the extension with pip Source: https://github.com/python/cpython/blob/main/Doc/extending/newtypes_tutorial.rst Run this command in a shell to build and install the module, producing custom.so. ```shell-session $ python -m pip install . ``` -------------------------------- ### Mock package imports with patch.dict on sys.modules Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst Mock package imports by providing entries for both the package and its submodule in the sys.modules dictionary passed to patch.dict. ```pycon >>> mock = Mock() >>> modules = {'package': mock, 'package.module': mock.module} >>> with patch.dict('sys.modules', modules): ... from package.module import fooble ... fooble() ... >>> mock.module.fooble.assert_called_once_with() ``` -------------------------------- ### Batch site directory processing using site.StartupState Source: https://github.com/python/cpython/blob/main/Doc/library/site.rst Accumulates startup configuration data across multiple site directories to ensure all sys.path extensions are added before startup code runs. process() is not idempotent and must not be called more than once on the same instance. ```python state = site.StartupState() for sitedir in site_dirs: state.addsitedir(sitedir) state.process() ``` -------------------------------- ### Provide only specific magic methods with Mock Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst As an alternative to `MagicMock`, use `Mock` and assign only the magic methods you need, such as `__getitem__` and `__setitem__`, each with a `side_effect`. ```pycon >>> mock = Mock() >>> mock.__getitem__ = Mock(side_effect=getitem) >>> mock.__setitem__ = Mock(side_effect=setitem) ``` -------------------------------- ### Build and install the project with pip Source: https://github.com/python/cpython/blob/main/Doc/extending/first-extension-module.rst Installs the project in the current directory; the -v (--verbose) option shows compiler output. Re-run after every change to the extension since C requires an explicit compilation step. ```sh python -m pip -v install . ``` -------------------------------- ### Inspect all calls with call_args_list Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst Use call_args_list to make assertions about all calls when the mock is called several times. It returns a list of call objects. ```pycon >>> mock = Mock(return_value=None) >>> mock(1, 2, 3) >>> mock(4, 5, 6) >>> mock() >>> mock.call_args_list [call(1, 2, 3), call(4, 5, 6), call()] ``` -------------------------------- ### Monkey patch backend and call method Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst Replace the backend attribute with the configured mock_backend and invoke the real method to exercise the chained calls. ```python3 >>> something.backend = mock_backend >>> something.method() ``` -------------------------------- ### Link additional libraries in Modules/Setup.local Source: https://github.com/python/cpython/blob/main/Doc/extending/extending.rst List additional libraries to link with on the same configuration line, for example -lX11. ```sh spam spammodule.o -lX11 ``` -------------------------------- ### Use a function side_effect for dynamic return values Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst Set side_effect to a function; it is called with the same arguments as the mock and its return value is returned by the call. ```pycon >>> vals = {(1, 2): 1, (2, 3): 2} >>> def side_effect(*args): ... return vals[args] ... >>> mock = MagicMock(side_effect=side_effect) >>> mock(1, 2) 1 >>> mock(2, 3) 2 ``` -------------------------------- ### Create OptionParser and add options Source: https://github.com/python/cpython/blob/main/Doc/whatsnew/2.3.rst Start by creating an OptionParser instance and defining program options with add_option. The example defines -i/--input as a string and -l/--length as an integer. ```python3 import sys from optparse import OptionParser op = OptionParser() op.add_option('-i', '--input', action='store', type='string', dest='input', help='set input filename') op.add_option('-l', '--length', action='store', type='int', dest='length', help='set maximum length of output') ``` -------------------------------- ### Implement extended slicing with slice.indices() Source: https://github.com/python/cpython/blob/main/Doc/whatsnew/2.3.rst Use slice.indices(length) to get a (start, stop, step) tuple suitable for range(). The example shows a FakeSeq class handling slice objects in __getitem__. ```python3 class FakeSeq: ... def calc_item(self, i): ... def __getitem__(self, item): if isinstance(item, slice): indices = item.indices(len(self)) return FakeSeq([self.calc_item(i) for i in range(*indices)]) else: return self.calc_item(i) ``` -------------------------------- ### Check for get_distutil_options() before using new setup() keywords Source: https://github.com/python/cpython/blob/main/Doc/whatsnew/2.3.rst Use this in setup.py to conditionally pass new Distutils keywords like depends only when the installed Distutils supports them, avoiding aborts from older versions rejecting unknown keywords. ```python3 from distutils import core kw = {'sources': 'foo.c', ...} if hasattr(core, 'get_distutil_options'): kw['depends'] = ['foo.h'] ext = Extension(**kw) ``` -------------------------------- ### Create basic Helloworld.py script Source: https://github.com/python/cpython/blob/main/Tools/freeze/win32.html Standard Python script demonstrating basic argument handling to be frozen. ```python import sys print " ".join( ["Hello", "world"] + sys.argv[1:] ) ``` -------------------------------- ### Matcher class using a comparison function Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst A matcher object that uses a comparison function for its equality operation. It stores the comparison function and the object to compare against. ```pycon >>> class Matcher: ... def __init__(self, compare, some_obj): ... self.compare = compare ... self.some_obj = some_obj ... def __eq__(self, other): ... return self.compare(self.some_obj, other) ... ``` -------------------------------- ### Inspect manager.mock_calls to see recorded calls in order Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst The parent mock's mock_calls attribute lists all calls to its child mocks in the order they occurred. ```pycon >>> manager.mock_calls [call.foo.something(), call.bar.other.thing()] ``` -------------------------------- ### install_scripts(context, path) Source: https://github.com/python/cpython/blob/main/Doc/library/venv.rst Method that can be called from setup_scripts() or post_setup() in subclasses to assist in installing custom scripts into the virtual environment. It copies scripts from subdirectories common, posix, and nt (matching os.name) into the environment's bin directory, performing placeholder text replacement. ```APIDOC ## install_scripts(context, path) ### Description This method can be called from `setup_scripts()` or `post_setup()` in subclasses to assist in installing custom scripts into the virtual environment. ### Method `install_scripts` ### Parameters - **context** - The context object (as passed to setup_scripts/post_setup). - **path** (str) - Path to a directory that should contain subdirectories `common`, `posix`, `nt`; each containing scripts destined for the `bin` directory in the environment. The contents of `common` and the directory corresponding to `os.name` are copied after some text replacement of placeholders: - `__VENV_DIR__` is replaced with the absolute path of the environment directory. - `__VENV_NAME__` is replaced with the environment name (final path segment of environment directory). - `__VENV_PROMPT__` is replaced with the prompt (the environment name surrounded by parentheses and with a following space). - `__VENV_BIN_NAME__` is replaced with the name of the bin directory (either `bin` or `Scripts`). - `__VENV_PYTHON__` is replaced with the absolute path of the environment’s executable. The directories are allowed to exist (for when an existing environment is being upgraded). ``` -------------------------------- ### Assert single call with assert_called_once_with Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst assert_called_once_with also asserts call_count is one. Calling the mock a second time raises AssertionError showing the calls. ```pycon >>> mock.foo_bar.assert_called_once_with('baz', spam='eggs') >>> mock.foo_bar() >>> mock.foo_bar.assert_called_once_with('baz', spam='eggs') Traceback (most recent call last): ... AssertionError: Expected 'foo_bar' to be called once. Called 2 times. Calls: [call('baz', spam='eggs'), call()]. ``` -------------------------------- ### Factor out setup code with setUp() in WidgetTestCase Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.rst Implement setUp() to run automatically before each test method, avoiding repetitive setup. The framework calls setUp() once per test; if it raises, the test is treated as an error and the test method is not executed. ```python3 import unittest class WidgetTestCase(unittest.TestCase): def setUp(self): self.widget = Widget('The widget') def test_default_widget_size(self): self.assertEqual(self.widget.size(), (50,50), 'incorrect default size') def test_widget_resize(self): self.widget.resize(100,150) self.assertEqual(self.widget.size(), (100,150), 'wrong size after resize') ``` -------------------------------- ### Inspect chained calls via return_value mock Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst When a mock is called, its return_value is a new Mock. You can assert on calls made to that returned mock, such as mock.return_value.foo.assert_called_with. ```pycon >>> mock = Mock() >>> mock().foo(a=2, b=3) >>> mock.return_value.foo.assert_called_with(a=2, b=3) ``` -------------------------------- ### class site.StartupState(known_paths=None) Source: https://github.com/python/cpython/blob/main/Doc/library/site.rst Accumulates interpreter startup configuration data from one or more site directories. It is the preferred interface for batching the processing of .pth and .start files across multiple directories. ```APIDOC ## site.StartupState(known_paths=None) ### Description Accumulates interpreter startup configuration data from one or more site directories. Used for batching the processing of `.pth` and `.start` files across multiple site directories so that every `sys.path` extension is visible before any startup code runs. ### Constructor Parameters - **known_paths** (set, optional) - A set of case-normalized paths used to prevent duplicate `sys.path` entries. Defaults to `None` (built from current `sys.path`). ### Methods - **addsitedir(sitedir)**: Reads `.pth` and `.start` files in `sitedir` and records `sys.path` extensions, deprecated `.pth` import lines, and `.start` entry points. - **addusersitepackages()**: Adds the per-user site-packages directory if enabled and existing. - **addsitepackages(prefixes=None)**: Adds global site-packages directories computed from `prefixes` (or global `PREFIXES` if `None`). - **process()**: Applies the accumulated state to `sys.path` and executes entry points and import lines. Must not be called more than once per instance. ### Usage Example ```python state = site.StartupState() for sitedir in site_dirs: state.addsitedir(sitedir) state.process() ``` ``` -------------------------------- ### Decorate a test method with patch.object Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst A common pattern is to decorate test methods directly with patch.object. The original attribute is restored after the test method runs. ```pycon >>> class MyTest(unittest.TestCase): ... @patch.object(SomeClass, 'attribute', sentinel.attribute) ... def test_something(self): ... self.assertEqual(SomeClass.attribute, sentinel.attribute) ... >>> original = SomeClass.attribute >>> MyTest('test_something').test_something() >>> assert SomeClass.attribute == original ``` -------------------------------- ### Display PC/layout help Source: https://github.com/python/cpython/blob/main/PC/layout/README.md Run the PC/layout script with `--help` using any Python 3 interpreter from the repository root to see available options. ```shell python PC/layout --help ``` -------------------------------- ### Patch dotted module class attribute with patch Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst The module name in patch can be dotted in the form package.module.ClassName.attribute to patch a class attribute within a module. ```python3 >>> @patch('package.module.ClassName.attribute', sentinel.attribute) ... def test(): ... from package.module import ClassName ... assert ClassName.attribute == sentinel.attribute ... >>> test() ``` -------------------------------- ### Creating a PurePosixPath for parts demonstration Source: https://github.com/python/cpython/blob/main/Doc/library/pathlib.rst Example path used to illustrate the parent, name, stem, and suffix properties. ```python3 >>> p = PurePosixPath('/srv/holy/grail.tar.gz') ``` -------------------------------- ### Name a MagicMock and see propagated name Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst Give a MagicMock a name to improve repr and failure messages. The name propagates to attributes and methods of the mock. ```pycon >>> mock = MagicMock(name='foo') >>> mock >>> mock.method ``` -------------------------------- ### List all resources and command-line options with python -m test -h Source: https://github.com/python/cpython/blob/main/Doc/library/test.rst Prints the list of all resources and more command-line options for the test package. ```shell python -m test -h ``` -------------------------------- ### Demonstrate CLI argument concepts using ls Source: https://github.com/python/cpython/blob/main/Doc/howto/argparse.rst Demonstrates basic command-line interface concepts such as running with default behavior, specifying positional directory arguments, applying optional flags like -l, and displaying help text with --help. ```shell-session $ ls cpython devguide prog.py pypy rm-unused-function.patch $ ls pypy ctypes_configure demo dotviewer include lib_pypy lib-python ... $ ls -l total 20 drwxr-xr-x 19 wena wena 4096 Feb 18 18:51 cpython drwxr-xr-x 4 wena wena 4096 Feb 8 12:04 devguide -rwxr-xr-x 1 wena wena 535 Feb 19 00:05 prog.py drwxr-xr-x 14 wena wena 4096 Feb 7 00:59 pypy -rw-r--r-- 1 wena wena 741 Feb 18 01:01 rm-unused-function.patch $ ls --help Usage: ls [OPTION]... [FILE]... List information about the FILEs (the current directory by default). Sort entries alphabetically if none of -cftuvSUX nor --sort is specified. ... ``` -------------------------------- ### Patch a method with MagicMock and call it Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst Replace a method on an object with a MagicMock to record calls. After calling the mock, use its assertion methods to verify arguments. ```pycon >>> real = SomeClass() >>> real.method = MagicMock(name='method') >>> real.method(3, 4, 5, key='value') ``` -------------------------------- ### ,Run simple_logging_module.py and view console output Source: https://github.com/python/cpython/blob/main/Doc/howto/logging.rst ,Shows the command to run the explicit-code logging example and the resulting formatted log lines. The output includes timestamps, the simple_example logger name, level names, and messages. ```,shell-session ,$ python simple_logging_module.py 2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message 2005-03-19 15:10:26,620 - simple_example - INFO - info message 2005-03-19 15:10:26,695 - simple_example - WARNING - warn message 2005-03-19 15:10:26,697 - simple_example - ERROR - error message 2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message ``` -------------------------------- ### Attach patched mocks to a manager with attach_mock() Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst When patch creates mocks, attach them to a manager mock using attach_mock() so their calls are recorded in the manager's mock_calls. ```python3 >>> manager = MagicMock() >>> with patch('mymodule.Class1') as MockClass1: ... with patch('mymodule.Class2') as MockClass2: ... manager.attach_mock(MockClass1, 'MockClass1') ... manager.attach_mock(MockClass2, 'MockClass2') ... MockClass1().foo() ... MockClass2().bar() >>> manager.mock_calls [call.MockClass1(), call.MockClass1().foo(), call.MockClass2(), call.MockClass2().bar()] ``` -------------------------------- ### Assert call order by comparing manager.mock_calls to expected calls Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst Compare the manager's mock_calls attribute with a list of call objects to assert both the calls and their order. ```pycon >>> expected_calls = [call.foo.something(), call.bar.other.thing()] >>> manager.mock_calls == expected_calls True ``` -------------------------------- ### ,Configure logging with fileConfig and logging.conf Source: https://github.com/python/cpython/blob/main/Doc/howto/logging.rst ,Loads logging configuration from logging.conf using logging.config.fileConfig, then emits the same application log messages through the simpleExample logger. The logging.conf file must be present for this module to run. ```,python ,import logging import logging.config logging.config.fileConfig('logging.conf') # create logger logger = logging.getLogger('simpleExample') # 'application' code logger.debug('debug message') logger.info('info message') logger.warning('warn message') logger.error('error message') logger.critical('critical message') ``` -------------------------------- ### setup_python(context) Source: https://github.com/python/cpython/blob/main/Doc/library/venv.rst Creates a copy or symlink to the Python executable in the environment. On POSIX systems, if a specific executable python3.x was used, symlinks to python and python3 will be created pointing to that executable, unless files with those names already exist. On POSIX systems, a broken symlink at a destination path is removed before the copy or symlink is created. ```APIDOC ## setup_python(context) ### Description Creates a copy or symlink to the Python executable in the environment. On POSIX systems, if a specific executable `python3.x` was used, symlinks to `python` and `python3` will be created pointing to that executable, unless files with those names already exist. On POSIX systems, a broken symlink at a destination path is removed before the copy or symlink is created. ### Method `setup_python` ### Parameters - **context** (types.SimpleNamespace) - Required - The context object returned by `ensure_directories`. ### Version Notes - Changed in version 3.16: A broken symlink at a destination path is now removed and replaced. Previously it was left in place, or it made the copy fail. ``` -------------------------------- ### Mock from module import name with patch.dict Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst patch.dict on sys.modules also works for the from module import name form, allowing the imported name to be a mock attribute. ```pycon >>> mock = Mock() >>> with patch.dict('sys.modules', {'fooble': mock}): ... from fooble import blob ... blob.blip() ... >>> mock.blob.blip.assert_called_once_with() ``` -------------------------------- ### Assert dictionary access with call_args_list Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst After using the mock, inspect `call_args_list` on `__getitem__` and `__setitem__` to assert how the dictionary was accessed. The underlying `my_dict` reflects the recorded writes. ```pycon >>> mock.__getitem__.call_args_list [call('a'), call('c'), call('d'), call('b'), call('d')] >>> mock.__setitem__.call_args_list [call('b', 'fish'), call('d', 'eggs')] >>> my_dict {'a': 1, 'b': 'fish', 'c': 3, 'd': 'eggs'} ``` -------------------------------- ### test.support.import_helper.modules_setup() Source: https://github.com/python/cpython/blob/main/Doc/library/test.rst Returns a copy of sys.modules. Typically used together with modules_cleanup to save and restore the module cache. ```APIDOC ## test.support.import_helper.modules_setup() ### Description Return a copy of `sys.modules`. ### Method test.support.import_helper.modules_setup() ### Returns A copy of `sys.modules`. ``` -------------------------------- ### Run argparse example with -v and with -v -o -C plus input files Source: https://github.com/python/cpython/blob/main/Doc/whatsnew/2.7.rst Shows the parsed namespace printed by the example script for two invocations, with attributes named by the dest parameters. The second invocation supplies -o, -C, and two positional input filenames. ```python3 -> ./python.exe argparse-example.py -v {'output': None, 'is_verbose': True, 'context': 0, 'inputs': []} -> ./python.exe argparse-example.py -v -o /tmp/output -C 4 file1 file2 {'output': '/tmp/output', 'is_verbose': True, 'context': 4, 'inputs': ['file1', 'file2']} ``` -------------------------------- ### Dictionary-like mock behavior and KeyError Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst With the side effects in place, the mock behaves like a normal dictionary, records access, and raises `KeyError` for missing keys. ```pycon >>> mock['a'] 1 >>> mock['c'] 3 >>> mock['d'] Traceback (most recent call last): ... KeyError: 'd' >>> mock['b'] = 'fish' >>> mock['d'] = 'eggs' >>> mock['b'] 'fish' >>> mock['d'] 'eggs' ``` -------------------------------- ### Restrict MagicMock to dictionary magic methods with spec_set=dict Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst Use `MagicMock(spec_set=dict)` so the mock only exposes dictionary magic methods, then assign `side_effect` for `__getitem__` and `__setitem__`. ```pycon >>> mock = MagicMock(spec_set=dict) >>> mock.__getitem__.side_effect = getitem >>> mock.__setitem__.side_effect = setitem ``` -------------------------------- ### Show command-line options with python -m unittest -h Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.rst Use -h to list all command-line options. ```python3 python -m unittest -h ``` -------------------------------- ### Assert chained calls using call_list Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.mock-examples.rst Build the expected list of calls with call.call_list() and compare it to mock_backend.mock_calls. A chained call produces multiple entries in mock_calls. ```python3 >>> chained = call.get_endpoint('foobar').create_call('spam', 'eggs').start_call() >>> call_list = chained.call_list() >>> assert mock_backend.mock_calls == call_list ``` -------------------------------- ### SystemTap tapset for python.function.entry and python.function.return probes Source: https://github.com/python/cpython/blob/main/Doc/howto/instrumentation.rst Install this tapset file in SystemTap's tapset directory (e.g. /usr/share/systemtap/tapset) to expose the python.function.entry and python.function.return probe points. Based on a non-shared build of CPython. ```none /* Provide a higher-level wrapping around the function__entry and function__return markers: \*/ probe python.function.entry = process("python").mark("function__entry") { filename = user_string($arg1); funcname = user_string($arg2); lineno = $arg3; frameptr = $arg4 } probe python.function.return = process("python").mark("function__return") { filename = user_string($arg1); funcname = user_string($arg2); lineno = $arg3; frameptr = $arg4 } ```