diff --git a/.bumpversion.cfg b/.bumpversion.cfg index f8338dd..80aaba9 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,20 +1,20 @@ [bumpversion] -current_version = 2.1.0 +current_version = 2.2.0 commit = True tag = True message = "Release {new_version}" [bumpversion:file:setup.py] search = version='{current_version}' replace = version='{new_version}' [bumpversion:file:src/pytest_postgresql/__init__.py] [bumpversion:file:README.rst] [bumpversion:file:CHANGES.rst] search = unreleased ------- replace = {new_version} ------- diff --git a/AUTHORS.rst b/AUTHORS.rst index 07455aa..b3c2f93 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -1,19 +1,20 @@ Authors ======= This file contains the list of people involved in the development of pytest-postgresql along its history. * Grzegorz Śliwiński * Jonas Brunsgaard * Tomasz Karbownicki * Domen Kožar * Przemysław Spodymek * Michał Masłowski * Karolina Blümke * Paweł Wilczyński * Georg Walther * François Scala * Donald Stufft * Will Vaughn * Hugo (hugovk) +* Damian Skrzypczak \ No newline at end of file diff --git a/CHANGES.rst b/CHANGES.rst index 46e5728..56a5cc4 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -1,94 +1,99 @@ CHANGELOG ========= +2.2.0 +------- + +- [feature] ability to properly connect to already existing postgresql server using ``postgresql_noproc`` fixture. + 2.1.0 ------- - [enhancement] Gather helper functions maintaining postgresql database in DatabaseJanitor class. - [deprecate] Deprecate ``init_postgresql_database`` in favour of ``DatabaseJanitor.init`` - [deprecate] Deprecate ``drop_postgresql_database`` in favour of ``DatabaseJanitor.drop`` 2.0.0 ------- - [feature] Drop support for python 2.7. From now on, only support python 3.5 and up - [feature] Ability to configure database name through plugin options - [enhancement] Use tmpdir_factory. Drop ``logsdir`` parameter - [ehnancement] Support only Postgresql 9.0 and up - [bugfix] Always start postgresql with LC_ALL, LC_TYPE and LANG set to C.UTF-8. It makes postgresql start in english. 1.4.1 ------- - [bugfix] Allow creating test databse with hyphens 1.4.0 ------- - [enhancements] Ability to configure additional options for postgresql process and connection - [bugfix] - removed hard dependency on ``psycopg2``, allowing any of its alternative packages, like ``psycopg2-binary``, to be used. - [maintenance] Drop support for python 3.4 and use 3.7 instead 1.3.4 ------- - [bugfix] properly detect if executor running and clean after executor is being stopped .. note:: Previously if a test failed, there was a possibility of the executor being removed when python was closing, causing it to print ignored errors on already unloaded modules. 1.3.3 ------- - [enhancement] use executor's context manager to start/stop postrgesql server in a fixture 1.3.2 ------- - [bugfix] version regexp to correctly catch postgresql 10 1.3.1 ------- - [enhancement] explicitly turn off logging_collector 1.3.0 ------- - [feature] pypy compatibility 1.2.0 ------- - [bugfix] - disallow connection to database before it gets dropped. .. note:: Otherwise it caused random test subprocess to connect again and this the drop was unsucessfull which resulted in many more test failes on setup. - [cleanup] - removed path.py dependency 1.1.1 ------- - [bugfix] - Fixing the default pg_ctl path creation 1.1.0 ------- - [feature] - migrate usage of getfuncargvalue to getfixturevalue. require at least pytest 3.0.0 1.0.0 ------- - create command line and pytest.ini configuration options for postgresql starting parameters - create command line and pytest.ini configuration options for postgresql username - make the port random by default - create command line and pytest.ini configuration options for executable - create command line and pytest.ini configuration options for host - create command line and pytest.ini configuration options for port - Extracted code from pytest-dbfixtures diff --git a/README.rst b/README.rst index 8cf81d9..6306bc1 100644 --- a/README.rst +++ b/README.rst @@ -1,203 +1,231 @@ +.. image:: https://raw.githubusercontent.com/ClearcodeHQ/pytest-postgresql/master/logo.png + :width: 100px + :height: 100px + pytest-postgresql ================= .. image:: https://img.shields.io/pypi/v/pytest-postgresql.svg :target: https://pypi.python.org/pypi/pytest-postgresql/ :alt: Latest PyPI version .. image:: https://img.shields.io/pypi/wheel/pytest-postgresql.svg :target: https://pypi.python.org/pypi/pytest-postgresql/ :alt: Wheel Status .. image:: https://img.shields.io/pypi/pyversions/pytest-postgresql.svg :target: https://pypi.python.org/pypi/pytest-postgresql/ :alt: Supported Python Versions .. image:: https://img.shields.io/pypi/l/pytest-postgresql.svg :target: https://pypi.python.org/pypi/pytest-postgresql/ :alt: License Package status -------------- -.. image:: https://travis-ci.org/ClearcodeHQ/pytest-postgresql.svg?branch=v2.1.0 +.. image:: https://travis-ci.org/ClearcodeHQ/pytest-postgresql.svg?branch=v2.2.0 :target: https://travis-ci.org/ClearcodeHQ/pytest-postgresql :alt: Tests -.. image:: https://coveralls.io/repos/ClearcodeHQ/pytest-postgresql/badge.png?branch=v2.1.0 - :target: https://coveralls.io/r/ClearcodeHQ/pytest-postgresql?branch=v2.1.0 +.. image:: https://coveralls.io/repos/ClearcodeHQ/pytest-postgresql/badge.png?branch=v2.2.0 + :target: https://coveralls.io/r/ClearcodeHQ/pytest-postgresql?branch=v2.2.0 :alt: Coverage Status -.. image:: https://requires.io/github/ClearcodeHQ/pytest-postgresql/requirements.svg?tag=v2.1.0 - :target: https://requires.io/github/ClearcodeHQ/pytest-postgresql/requirements/?tag=v2.1.0 - :alt: Requirements Status - What is this? ============= This is a pytest plugin, that enables you to test your code that relies on a running PostgreSQL Database. It allows you to specify fixtures for PostgreSQL process and client. How to use ========== .. warning:: Tested on PostgreSQL versions > 9.x. See tests for more details. Install with: .. code-block:: sh pip install pytest-postgresql You will also need to install ``psycopg2``, or one of its alternative packagings such as ``psycopg2-binary`` (pre-compiled wheels) or ``psycopg2cffi`` (CFFI based, useful on PyPy). Plugin contains two fixtures: * **postgresql** - it's a client fixture that has functional scope. After each test it ends all leftover connections, and drops test database from PostgreSQL ensuring repeatability. * **postgresql_proc** - session scoped fixture, that starts PostgreSQL instance at it's first use and stops at the end of the tests. Simply include one of these fixtures into your tests fixture list. You can also create additional postgresql client and process fixtures if you'd need to: .. code-block:: python from pytest_postgresql import factories postgresql_my_proc = factories.postgresql_proc( port=None, unixsocketdir='/var/run') postgresql_my = factories.postgresql('postgresql_my_proc') .. note:: Each PostgreSQL process fixture can be configured in a different way than the others through the fixture factory arguments. +Connecting to already existing postgresql database +-------------------------------------------------- + +Some projects are using already running postgresql servers (ie on docker instances). +In order to connect to them, one would be using the ``postgresql_nooproc`` fixture. + +.. code-block:: python + + postgresql_external = factories.postgresql('postgresql_nooproc') + +By default the ``postgresql_nooproc`` fixture would connect to postgresql instance using **5432** port. Standard configuration options apply to it. + +These are the configuration options that are working on all levels with the ``postgresql_nooproc`` fixture: + Configuration ============= You can define your settings in three ways, it's fixture factory argument, command line option and pytest.ini configuration option. You can pick which you prefer, but remember that these settings are handled in the following order: * ``Fixture factory argument`` * ``Command line option`` * ``Configuration option in your pytest.ini file`` .. list-table:: Configuration options :header-rows: 1 * - PostgreSQL option - Fixture factory argument - Command line option - pytest.ini option + - Noop process fixrture - Default * - Path to executable - executable - --postgresql-exec - postgresql_exec + - - - /usr/lib/postgresql/9.1/bin/pg_ctl * - host - host - --postgresql-host - postgresql_host + - yes - 127.0.0.1 * - port - port - --postgresql-port - postgresql_port + - yes (5436) - random * - postgresql user - user - --postgresql-user - postgresql_user + - yes - postgres * - Starting parameters - startparams - --postgresql-startparams - postgresql_startparams + - - - -w * - Log filename's prefix - logsprefix - --postgresql-logsprefix - postgresql_logsprefix + - - - * - Location for unixsockets - unixsocket - --postgresql-unixsocketdir - postgresql_unixsocketdir + - - - $TMPDIR * - Database name - db_name - --postgresql-dbname - postgresql_dbname + - - - test - + * - PostgreSQL connection options + - options + - --postgresql-options + - postgresql_options + - yes + - Example usage: * pass it as an argument in your own fixture .. code-block:: python postgresql_proc = factories.postgresql_proc( port=8888) * use ``--postgresql-port`` command line option when you run your tests .. code-block:: py.test tests --postgresql-port=8888 * specify your port as ``postgresql_port`` in your ``pytest.ini`` file. To do so, put a line like the following under the ``[pytest]`` section of your ``pytest.ini``: .. code-block:: ini [pytest] postgresql_port = 8888 Maintaining database state outside of the fixtures -------------------------------------------------- It is possible and appears it's used in other libraries for tests, to maintain database state with the use of the ``pytest-postgresql`` database managing functionality: For this import DatabaseJanitor and use it's init and drop methods: .. code-block:: python from pytest_postgresql.factories import DatabaseJanitor # variable definition janitor = DatabaseJanitor(user, host, port, db_name, version) janitor.init() # your code, or yield janitor.drop() # at this moment you'll have clean database step or use it as a context manager: .. code-block:: python from pytest_postgresql.factories import DatabaseJanitor # variable definition with DatabaseJanitor(user, host, port, db_name, version): # do something here Package resources ----------------- * Bug tracker: https://github.com/ClearcodeHQ/pytest-postgresql/issues diff --git a/logo.png b/logo.png new file mode 100644 index 0000000..f667660 Binary files /dev/null and b/logo.png differ diff --git a/logo.svg b/logo.svg new file mode 100644 index 0000000..fc9a109 --- /dev/null +++ b/logo.svg @@ -0,0 +1,238 @@ + + + + + + + +Created by potrace 1.15, written by Peter Selinger 2001-2017 + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/requirements-lint.txt b/requirements-lint.txt index 8090ff0..6b2c25f 100644 --- a/requirements-lint.txt +++ b/requirements-lint.txt @@ -1,7 +1,7 @@ # linters pycodestyle==2.5.0 pydocstyle==4.0.1 -pylint==2.3.1 +pylint==2.4.2 pygments pyroma==2.5 -r requirements-test.txt \ No newline at end of file diff --git a/requirements-test.txt b/requirements-test.txt index 3267457..f9ecd3b 100644 --- a/requirements-test.txt +++ b/requirements-test.txt @@ -1,11 +1,10 @@ # test runs requirements (versions we'll be testing against) - automatically updated by requires.io pip>=9 # minimum installation requirements setuptools>=21 # minimum installation requirements coverage==4.5.4 # pytest-cov -pytest==5.1.2 +pytest==5.2.1 psycopg2-binary==2.8.3; platform_python_implementation != "PyPy" psycopg2cffi==2.8.1; platform_python_implementation == "PyPy" port-for==0.4 mirakuru==2.1.0; python_version>'3.5' -mirakuru<2.1.0; python_version<='3.5' --e .[tests] \ No newline at end of file +-e .[tests] diff --git a/setup.py b/setup.py index af36c6c..e886937 100644 --- a/setup.py +++ b/setup.py @@ -1,102 +1,102 @@ # -*- coding: utf-8 -*- # Copyright (C) 2016 by Clearcode # and associates (see AUTHORS). # This file is part of pytest-postgresql. # pytest-postgresql is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # pytest-postgresql is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public License # along with pytest-postgresql. If not, see . """pytest-postgresql setup.py module.""" import os from setuptools import setup, find_packages here = os.path.dirname(__file__) def read(fname): """ Read given file's content. :param str fname: file name :returns: file contents :rtype: str """ return open(os.path.join(here, fname)).read() requirements = [ 'pytest>=3.0.0', 'port-for', 'mirakuru>=2.0.0' ] test_requires = [ 'pytest-cov==2.7.1', 'pytest-xdist==1.29.0', ] extras_require = { 'docs': ['sphinx'], 'tests': test_requires, } setup_requires = [ 'setuptools>=21', 'pip>=9' ] setup( name='pytest-postgresql', - version='2.1.0', + version='2.2.0', description='Postgresql fixtures and fixture factories for Pytest.', long_description=( read('README.rst') + '\n\n' + read('CHANGES.rst') ), keywords='tests py.test pytest fixture postgresql', author='Clearcode - The A Room', author_email='thearoom@clearcode.cc', url='https://github.com/ClearcodeHQ/pytest-postgresql', license='LGPLv3+', python_requires='>=3.5', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: ' 'GNU Lesser General Public License v3 or later (LGPLv3+)', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3 :: Only', 'Topic :: Software Development :: Libraries :: Python Modules', ], package_dir={'': 'src'}, packages=find_packages('src'), install_requires=requirements, tests_require=test_requires, setup_requires=setup_requires, test_suite='tests', entry_points={ 'pytest11': [ 'pytest_postgresql = pytest_postgresql.plugin' ]}, include_package_data=True, zip_safe=False, extras_require=extras_require, ) diff --git a/src/pytest_postgresql/__init__.py b/src/pytest_postgresql/__init__.py index eaf8b8e..3123a60 100644 --- a/src/pytest_postgresql/__init__.py +++ b/src/pytest_postgresql/__init__.py @@ -1,27 +1,27 @@ # -*- coding: utf-8 -*- # Copyright (C) 2016 by Clearcode # and associates (see AUTHORS). # This file is part of pytest-postgresql. # pytest-postgresql is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # pytest-postgresql is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public License # along with pytest-postgresql. If not, see . """Main module for pytest-postgresql.""" try: import psycopg2cffi.compat # pylint:disable=import-error except ImportError: pass else: psycopg2cffi.compat.register() -__version__ = '2.1.0' +__version__ = '2.2.0' diff --git a/src/pytest_postgresql/factories.py b/src/pytest_postgresql/factories.py index db02a12..e861f2d 100644 --- a/src/pytest_postgresql/factories.py +++ b/src/pytest_postgresql/factories.py @@ -1,214 +1,297 @@ # Copyright (C) 2013-2016 by Clearcode # and associates (see AUTHORS). # This file is part of pytest-dbfixtures. # pytest-dbfixtures is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # pytest-dbfixtures is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public License # along with pytest-dbfixtures. If not, see . """Fixture factories for postgresql fixtures.""" import os.path import platform import subprocess from tempfile import gettempdir from warnings import warn import pytest +from pkg_resources import parse_version from pytest_postgresql.janitor import DatabaseJanitor, psycopg2 from pytest_postgresql.executor import PostgreSQLExecutor from pytest_postgresql.port import get_port +class NoopExecutor: # pylint: disable=too-few-public-methods + """Nooperator executor.""" + + def __init__(self, host, port, user, options): + """ + Initialize nooperator executor mock. + + :param str host: Postgresql hostname + :param str|int port: Postrgesql port + :param str user: Postgresql username + :param str options: Additional connection options + """ + self.host = host + self.port = int(port) + self.user = user + self.options = options + self._version = None + + @property + def version(self): + """Get postgresql's version.""" + if self._version: + return self._version + try: + connection = psycopg2.connect( + dbname='postgres', + user=self.user, + host=self.host, + port=self.port, + options=self.options + ) + version = str(connection.server_version) + self._version = parse_version( + '.'.join([ + version[i: i+2] for i in range(0, len(version), 2) + if int(version[i: i+2]) + ]) + ) + return self._version + finally: + connection.close() + + def get_config(request): """Return a dictionary with config options.""" config = {} options = [ 'exec', 'host', 'port', 'user', 'options', 'startparams', 'logsprefix', 'unixsocketdir', 'dbname' ] for option in options: option_name = 'postgresql_' + option conf = request.config.getoption(option_name) or \ request.config.getini(option_name) config[option] = conf return config def init_postgresql_database(user, host, port, db_name): """ Create database in postgresql. :param str user: postgresql username :param str host: postgresql host :param str port: postgresql port :param str db_name: database name """ warn( 'init_postgresql_database is deprecated, ' 'use DatabaseJanitor.init istead.', DeprecationWarning ) DatabaseJanitor(user, host, port, db_name, 0.0).init() def drop_postgresql_database(user, host, port, db_name, version): """ Drop databse in postgresql. :param str user: postgresql username :param str host: postgresql host :param str port: postgresql port :param str db_name: database name :param packaging.version.Version version: postgresql version number """ warn( 'drop_postgresql_database is deprecated, ' 'use DatabaseJanitor.drop istead.', DeprecationWarning ) DatabaseJanitor(user, host, port, db_name, version).init() def postgresql_proc( executable=None, host=None, port=-1, user=None, options='', startparams=None, unixsocketdir=None, logs_prefix='', ): """ Postgresql process factory. :param str executable: path to postgresql_ctl :param str host: hostname :param str|int|tuple|set|list port: exact port (e.g. '8000', 8000) randomly selected port (None) - any random available port -1 - command line or pytest.ini configured port [(2000,3000)] or (2000,3000) - random available port from a given range [{4002,4003}] or {4002,4003} - random of 4002 or 4003 ports [(2000,3000), {4002,4003}] - random of given range and set :param str user: postgresql username + :param str options: Postgresql connection options :param str startparams: postgresql starting parameters :param str unixsocketdir: directory to create postgresql's unixsockets :param str logs_prefix: prefix for log filename :rtype: func :returns: function which makes a postgresql process """ @pytest.fixture(scope='session') def postgresql_proc_fixture(request, tmpdir_factory): """ Process fixture for PostgreSQL. :param FixtureRequest request: fixture request object :rtype: pytest_dbfixtures.executors.TCPExecutor :returns: tcp executor """ config = get_config(request) postgresql_ctl = executable or config['exec'] # check if that executable exists, as it's no on system PATH # only replace if executable isn't passed manually if not os.path.exists(postgresql_ctl) and executable is None: pg_bindir = subprocess.check_output( ['pg_config', '--bindir'], universal_newlines=True ).strip() postgresql_ctl = os.path.join(pg_bindir, 'pg_ctl') pg_host = host or config['host'] pg_port = get_port(port) or get_port(config['port']) datadir = os.path.join( gettempdir(), 'postgresqldata.{}'.format(pg_port)) pg_user = user or config['user'] pg_options = options or config['options'] pg_unixsocketdir = unixsocketdir or config['unixsocketdir'] pg_startparams = startparams or config['startparams'] logfile_path = tmpdir_factory.mktemp("data").join( '{prefix}postgresql.{port}.log'.format( prefix=logs_prefix, port=pg_port ) ) if platform.system() == 'FreeBSD': with (datadir / 'pg_hba.conf').open(mode='a') as conf_file: conf_file.write('host all all 0.0.0.0/0 trust\n') postgresql_executor = PostgreSQLExecutor( executable=postgresql_ctl, host=pg_host, port=pg_port, user=pg_user, options=pg_options, datadir=datadir, unixsocketdir=pg_unixsocketdir, logfile=logfile_path, startparams=pg_startparams, ) # start server with postgresql_executor: postgresql_executor.wait_for_postgres() yield postgresql_executor return postgresql_proc_fixture +def postgresql_noproc(host=None, port=None, user=None, options=''): + """ + Postgresql noprocess factory. + + :param str host: hostname + :param str|int port: exact port (e.g. '8000', 8000) + :param str user: postgresql username + :param str options: Postgresql connection options + :rtype: func + :returns: function which makes a postgresql process + """ + @pytest.fixture(scope='session') + def postgresql_noproc_fixture(request): + """ + Noop Process fixture for PostgreSQL. + + :param FixtureRequest request: fixture request object + :rtype: pytest_dbfixtures.executors.TCPExecutor + :returns: tcp executor-like object + """ + config = get_config(request) + pg_host = host or config['host'] + pg_port = port or config['port'] or 5432 + pg_user = user or config['user'] + pg_options = options or config['options'] + + noop_exec = NoopExecutor( + host=pg_host, + port=pg_port, + user=pg_user, + options=pg_options, + ) + + yield noop_exec + + return postgresql_noproc_fixture + + def postgresql(process_fixture_name, db_name=None): """ Return connection fixture factory for PostgreSQL. :param str process_fixture_name: name of the process fixture :param str db_name: database name :rtype: func :returns: function which makes a connection to postgresql """ @pytest.fixture def postgresql_factory(request): """ Fixture factory for PostgreSQL. :param FixtureRequest request: fixture request object :rtype: psycopg2.connection :returns: postgresql client """ config = get_config(request) if not psycopg2: raise ImportError( 'No module named psycopg2. Please install either ' 'psycopg2 or psycopg2-binary package for CPython ' 'or psycopg2cffi for Pypy.' ) proc_fixture = request.getfixturevalue(process_fixture_name) # _, config = try_import('psycopg2', request) pg_host = proc_fixture.host pg_port = proc_fixture.port pg_user = proc_fixture.user pg_options = proc_fixture.options pg_db = db_name or config['dbname'] with DatabaseJanitor( pg_user, pg_host, pg_port, pg_db, proc_fixture.version ): connection = psycopg2.connect( dbname=pg_db, user=pg_user, host=pg_host, port=pg_port, options=pg_options ) yield connection connection.close() return postgresql_factory __all__ = ('postgresql', 'postgresql_proc') diff --git a/src/pytest_postgresql/plugin.py b/src/pytest_postgresql/plugin.py index 0549c7f..bff07c3 100644 --- a/src/pytest_postgresql/plugin.py +++ b/src/pytest_postgresql/plugin.py @@ -1,158 +1,159 @@ # Copyright (C) 2016 by Clearcode # and associates (see AUTHORS). # This file is part of pytest-postgresql. # pytest-dbfixtures is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # pytest-postgresql is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public License # along with pytest-postgresql. If not, see . """Plugin module of pytest-postgresql.""" from tempfile import gettempdir from pytest_postgresql import factories # pylint:disable=invalid-name _help_executable = 'Path to PostgreSQL executable' _help_host = 'Host at which PostgreSQL will accept connections' _help_port = 'Port at which PostgreSQL will accept connections' _help_user = "PostgreSQL username" _help_options = "PostgreSQL connection options" _help_startparams = "Starting parameters for the PostgreSQL" _help_logsprefix = "Prefix for the log files" _help_unixsocketdir = "Location of the socket directory" _help_dbname = "Default database name" def pytest_addoption(parser): """Configure options for pytest-postgresql.""" parser.addini( name='postgresql_exec', help=_help_executable, default='/usr/lib/postgresql/9.1/bin/pg_ctl' ) parser.addini( name='postgresql_host', help=_help_host, default='127.0.0.1' ) parser.addini( name='postgresql_port', help=_help_port, default=None, ) parser.addini( name='postgresql_user', help=_help_user, default='postgres' ) parser.addini( name='postgresql_options', help=_help_options, default='' ) parser.addini( name='postgresql_startparams', help=_help_startparams, default='-w' ) parser.addini( name='postgresql_logsprefix', help=_help_logsprefix, default='' ) parser.addini( name='postgresql_unixsocketdir', help=_help_unixsocketdir, default=gettempdir() ) parser.addini( name='postgresql_dbname', help=_help_dbname, default='tests' ) parser.addoption( '--postgresql-exec', action='store', metavar='path', dest='postgresql_exec', help=_help_executable ) parser.addoption( '--postgresql-host', action='store', dest='postgresql_host', help=_help_host, ) parser.addoption( '--postgresql-port', action='store', dest='postgresql_port', help=_help_port ) parser.addoption( '--postgresql-user', action='store', dest='postgresql_user', help=_help_user ) parser.addoption( '--postgresql-options', action='store', dest='postgresql_options', help=_help_options ) parser.addoption( '--postgresql-startparams', action='store', dest='postgresql_startparams', help=_help_startparams ) parser.addoption( '--postgresql-logsprefix', action='store', dest='postgresql_logsprefix', help=_help_logsprefix ) parser.addoption( '--postgresql-unixsocketdir', action='store', dest='postgresql_unixsocketdir', help=_help_unixsocketdir ) parser.addoption( '--postgresql-dbname', action='store', dest='postgresql_dbname', help=_help_dbname ) postgresql_proc = factories.postgresql_proc() +postgresql_nooproc = factories.postgresql_noproc() postgresql = factories.postgresql('postgresql_proc') diff --git a/tests/test_noopexecutor.py b/tests/test_noopexecutor.py new file mode 100644 index 0000000..0e4203b --- /dev/null +++ b/tests/test_noopexecutor.py @@ -0,0 +1,27 @@ +"""Test for NoopExecutor.""" + +from pytest_postgresql.factories import NoopExecutor + + +def test_nooproc_version(postgresql_proc): + """Test the way postgresql version is being read.""" + postgresql_nooproc = NoopExecutor( + postgresql_proc.host, + postgresql_proc.port, + postgresql_proc.user, + postgresql_proc.options + ) + assert postgresql_proc.version == postgresql_nooproc.version + + +def test_nooproc_cached_version(postgresql_proc): + """Test that the version is being cached.""" + postgresql_nooproc = NoopExecutor( + postgresql_proc.host, + postgresql_proc.port, + postgresql_proc.user, + postgresql_proc.options + ) + ver = postgresql_nooproc.version + with postgresql_proc.stopped(): + assert ver == postgresql_nooproc.version