Package: pytest-services
Services plugin for pytest testing frameworkInstall pytest-servicespip install pytest-servicesFeaturesThe plugin provides a set of fixtures and utility functions to start service processes for your tests withpytestFixturesrun_servicesDetermines whether services should be run or not. False by default if not in distributed environment
(withoutpytest-xdist). Can be manually set to True by overriding this fixture in your test config or
just by using–run-servicescommand line argument (see below).Infrastructure fixturesworker_idId of the worker if tests are run usingpytest-xdist. It is set tolocalif tests are not run usingpytest-xdist(with–distcommand line option set toload).
Has a deprecated aliasslave_idwhich will be removed in a future version.session_idTest session id. Globally unique, and of course also guaranteed to be different for potentially multiple test
sessions running on same test node viapytest-xdist.watcher_getterFunction to instantiate test service watcher (popen object). Includes automatic finalization (exiting) of the
service process, and testing the service before returning the watcher from the function.
Example of usage for memcached service:@pytest.fixture(scope='session')defmemcached(request,run_services,memcached_socket,watcher_getter):"""The memcached instance which is ready to be used by the tests."""ifrun_services:returnwatcher_getter(name='memcached',arguments=['-s',memcached_socket],checker=lambda:os.path.exists(memcached_socket),# Needed for the correct execution order of finalizersrequest=request,)services_logLogger used for debug logging when managing test services.root_dirParent directory for test service artifacts (disk based). Set to/tmpby default.base_dirBase directory for test service artifacts (disk based), unique subdirectory ofroot_dir.
Automatically removed recursively at the end of the test session.temp_dirTemporarydirectory (disk based), subfolder of thebase_dir.
Used for strictly temporary artifacts (for example - folder where files are uploaded from the user input).memory_root_dirParent directory for test service artifacts (memory based). Main idea of having memory base directory is to
store performance-critical files there. For example - mysql service will use it to store database file, it speeds up
mysql server a lot, especially database management operations.
Set to/var/shmby default, with a fallback to ‘root_dir`. Note that if apparmor is running on your system, most
likely it will prevent your test service to use it (for example - mysql has it’s apparmor profile). You you’ll need
to disable such profile in apparmor configuration.
Example of disabling apparmor for mysqld:sudoln-s/etc/apparmor.d/usr.sbin.mysqld/etc/apparmor.d/disable/sudo/etc/init.d/apparmorrestartmemory_base_dirBase directory for test service artifacts (memory based), unique subdirectory ofmemory_root_dir.
Automatically removed recursively at the end of the test session.memory_temp_dirTemporarydirectory (memory based), subfolder of thebase_dir.lock_dirLock files directory for storing locks created for resource assignment (ports, display, etc). Subfolder ofmemory_root_dir.run_dirProcess id and socket files directory (like system-wide/var/runbut local for test session). Subfolder ofmemory_root_dir.port_getterFunction to get unallocated port.
Automatically ensures locking and un-locking of it on application level via flock.display_getterFunction to get unallocated display.
Automatically ensures locking and un-locking of it on application level via flock.lock_resource_timeoutUsed in function lock_resource.
A maximum of total sleep between attempts to lock resource.Service fixturesmemcachedStartmemcachedinstance.
Requirespylibmcinstalled ormemcacheindicated as an extra (pip install ‘pytest-services[memcached]’).memcached_socketMemcached unix socket file name to be used for connection.memcached_connectionMemcached connection string.do_memcached_cleanDetermine if memcached should be cleared before every test run. Equals torun_servicesfixture by default.
Requirespylibmcinstalled ormemcacheindicated as an extra (pip install ‘pytest-services[memcached]’).memcached_clientA pylibmc.Client instance bound to the service.
Requirespylibmcinstalled ormemcacheindicated as an extra (pip install ‘pytest-services[memcached]’).mysqlStartmysql-serverinstance.mysql_database_nameMySQL database name to be created after initialization of the mysql servicesystemdatabase.mysql_database_getterFunction with single parameter - database name. To create additional database(s) for tests.
Used inmysql_databasefixture which is used bymysqlone.mysql_connectionMySQL connection string.xvfbStartxvfbinstance.xvfb_displayXvfb display to use for connection.xvfb_resolutionXvfb display resolution to use. Tuple in form(1366, 768, 8).Utility functionsDjango settingsIn some cases, there’s a need of switching django settings during test run, because several django projects are tested
whithin the single test suite.pytest_services.django_settingssimplifies switching of django settings to a single function call:setup_django_settingsOverride the enviroment variable and call the _setup method of the settings object to reload them.Example of usage:conftest.py:frompytest_servicesimportdjango_settingsdjango_settings.clean_django_settings()django_settings.setup_django_settings('your.project.settings')Note that the nice projectpytest-djangodoesn’t help with the situation, as it’s single django project oriented, as
well as standard django testing technique. Single project approach works fine, as long as there are no fixtures to share
between them, but when there are fixtures to share, then you can get benefit of joining several django projects tests
into a single test run, because all session-scoped fixtures will be instantiated only once for all projects tests.
The benefit is only visible if you have big enough test suite and your fixtures are heavy enough.Command-line options–run-servicesForce services to be run even if tests are executed in a non-distributed way (withoutpytest-xdist).–xvfb-displaySkip xvfb service to run and use provided display. Useful when you need to run all services except thexvfbto debug your browser tests, if, for example you usepytest-splinterwith or withoutpytest-bdd.Exampletest_your_test.py:importMySQLdbdeftest_some_mysql_stuff(mysql):"""Test using mysql server."""conn=MySQLdb.connect(user='root')ContactIf you have questions, bug reports, suggestions, etc. please create an issue on
theGitHub project page.LicenseThis software is licensed under theMIT licenseSeeLicense file© 2014 Anatoly Bubenkov, Paylogic International and others.AuthorsAnatoly Bubenkovidea and implementationThese people have contributed topytest-services, in alphabetical order:Alessio BogonDmitrijs MilajevsJason R.CoombsJoep van DijkenMagnus StabergMichael ShriverOleg PidsadnyiZac Hatfield-DoddsChangelog2.2.1#42: Retry onzc.lockfile.LockErrorinfile_lock, use existing timeout kwarg (mshriver)2.2.0#38: Retry to lock resource if zc.lockfile.LockError is raised. Fix needed for pytest-xdist. (StabbarN)2.1.0#34: Deprecatedslave_idfixture in favor ofworker_id,
for compatibility withpytest-xdist2.2.0.1#20: Added workaround for issue with SysLogHandler.2.0.0#23: Rely onzc.lockfilefor lockfile behavior.#28: Fixtures now supports later versions of mysql and no longer
support versions of mysql prior tomysql--initializesupport.#29: Fix issues with later versions of mysql wheremysql_defaults_filefixture would prevent startup of mysql.Fixed issue in test suite where mysql fixture was not tested.Removedpytest_services.locks.lock_file.1.3.1Fix race condition causing when using port_getter/display_getter (youtux)1.3.0Addrequestparam to watcher_getter to have proper execution order
of finalizers (youtux).1.2.1Swap kill and terminate in watcher_getter finalization, allowing
for a more polite SIGTERM for terminating child procs on Unix. See
#15 for details (jaraco)1.2.0Make pylibmc an optional dependency, available as an extra (jaraco)1.1.15Fixed hang with updated netcat-openbsd>=1.130.3 (joepvandijken)1.1.14Use a different strategy to determine whether xvfb supports (youtux )1.1.12use realpath for mysql base dir (bubenkoff)1.1.11exclude locked displays for xvfb (bubenkoff)1.1.7django settings fix (olegpidsadnyi)1.1.3django 1.8 support (bubenkoff)1.1.2old django support fix (olegpidsadnyi)1.1.0django 1.7+ support (bubenkoff)1.0.10removed auto artifacts cleanup (bubenkoff)1.0.8fixed popen arguments (bubenkoff)1.0.2added port and display getters (bubenkoff)1.0.1Improved documentation (bubenkoff)1.0.0Initial public release