|
| 1 | +pytest-sqlalchemy |
| 2 | +================= |
| 3 | + |
| 4 | +SQLAlchemy related fixtures to handle connections and transactions with SQLAlchemy in tests. |
| 5 | + |
| 6 | +Fixtures |
| 7 | +-------- |
| 8 | +This plugin provides the following fixtures which gives access to the SQLAlchemy objects of the same |
| 9 | +name. |
| 10 | + |
| 11 | +* **engine** The engine used to connect to the database. Scope is "module". |
| 12 | +* **connection** An open connection to the database. Scope is "module". |
| 13 | + |
| 14 | +See `Working with Engines and Connections`__ on how to use these fixtures. |
| 15 | + |
| 16 | +__ http://docs.sqlalchemy.org/en/latest/core/connections.html#module-sqlalchemy.engine |
| 17 | + |
| 18 | +* **transaction** A started transaction on the connection. Transaction will be rolled back. |
| 19 | + No Scope. |
| 20 | + |
| 21 | +See `Using Transactions`__ on how to use this fixtures |
| 22 | + |
| 23 | +__ http://docs.sqlalchemy.org/en/latest/core/connections.html#using-transactions |
| 24 | + |
| 25 | +* **dbsession** A sqlalchemy session *not* bound to any model. No scope. |
| 26 | + |
| 27 | +See `Session Basics`__ to learn about how to use sessions. |
| 28 | + |
| 29 | +__ http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#session-basics |
| 30 | + |
| 31 | +Usage |
| 32 | +----- |
| 33 | +The fixtures can be used in your tests like any other `Pytest Fixtures`__. |
| 34 | + |
| 35 | +__ https://docs.pytest.org/en/3.6.1/fixture.html |
| 36 | + |
| 37 | +**Example**: |
| 38 | + |
| 39 | +.. code-block:: python |
| 40 | +
|
| 41 | + import pytest |
| 42 | + from pytest_sqlalchemy import connection |
| 43 | + |
| 44 | + def test_connection(connection): |
| 45 | + # Do fancy stuff with the connection. |
| 46 | + # Note you will not need to close the connection. This is done |
| 47 | + # automatically when the scope (module) of the fixtures ends. |
| 48 | + assert connection |
| 49 | +
|
| 50 | +Invoke |
| 51 | +------ |
| 52 | +You need to provide the connection URL for the engine when invoking the pytest command: |
| 53 | + |
| 54 | +.. code-block:: bash |
| 55 | +
|
| 56 | + pytest --sqlalchemy-connect-url="postgresql://scott:tiger@localhost:5432/mydatabase" |
| 57 | + |
| 58 | +Or override the ``sqlalchemy_connect_url`` fixture on your ``conftest.py`` file: |
| 59 | + |
| 60 | +.. code-block:: python |
| 61 | +
|
| 62 | + @pytest.fixture(scope="session") |
| 63 | + def sqlalchemy_connect_url(): |
| 64 | + return 'postgresql://scott:tiger@localhost:5432/mydatabase' |
| 65 | +
|
| 66 | +Development |
| 67 | +---------- |
| 68 | + |
| 69 | +To get going, in a checkout: |
| 70 | + |
| 71 | +.. code-block:: bash |
| 72 | +
|
| 73 | + uv sync |
| 74 | +
|
| 75 | +You can then run the tests with: |
| 76 | + |
| 77 | +.. code-block:: bash |
| 78 | +
|
| 79 | + uv run pytest |
0 commit comments