Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Documentation #20

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added docs/.static/placeholder.txt
Empty file.
Empty file added docs/.templates/placeholder.txt
Empty file.
212 changes: 212 additions & 0 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config

# -- Path setup --------------------------------------------------------------

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath('../..'))


# -- Project information -----------------------------------------------------

project = 'PyTest-Flask-SQLAlchemy'
copyright = '2019, Jean Cochrane and DataMade. Released under the MIT License.'
author = 'Jean Cochrane'

# The short X.Y version
version = '1.0'
# The full version, including alpha/beta/rc tags
release = '1.0.2'


# -- General configuration ---------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
# Cross Referencing
'sphinx.ext.intersphinx',
'sphinx.ext.autosectionlabel', # Explicit Referencing e.g. DOCUMENT:SECTION
# Code Documentation
'sphinx.ext.viewcode',
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
# Project Management
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinx.ext.githubpages',
# Typography
'sphinx.ext.mathjax',
# Document Control
'sphinx.ext.ifconfig',
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['.templates']

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'

# The master toctree document.
master_doc = 'index'

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path .
exclude_patterns = []

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# -- Auto-Section Label Configuration ----------------------------------------
autosectionlabel_prefix_document = True

# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'

# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
html_theme_options = {
# 'logo': 'logo.png',
'github_user': 'jeancochrane',
'github_repo': 'pytest-flask-sqlalchemy',
'github_banner': 'true',
'travis_button': 'true',
}

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['.static']

# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# The default sidebars (for documents that don't match any pattern) are
# defined by theme itself. Builtin themes are using these templates by
# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
# 'searchbox.html']``.
#
# html_sidebars = {}


# -- Options for HTMLHelp output ---------------------------------------------

# Output file base name for HTML help builder.
htmlhelp_basename = 'PyTest-Flask-SQLAlchemydoc'


# -- Options for LaTeX output ------------------------------------------------

latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',

# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',

# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',

# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'PyTest-Flask-SQLAlchemy.tex', 'PyTest-Flask-SQLAlchemy Documentation',
'Jean Cochrane', 'manual'),
]


# -- Options for manual page output ------------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'pytest-flask-sqlalchemy', 'PyTest-Flask-SQLAlchemy Documentation',
[author], 1)
]


# -- Options for Texinfo output ----------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'PyTest-Flask-SQLAlchemy', 'PyTest-Flask-SQLAlchemy Documentation',
author, 'PyTest-Flask-SQLAlchemy', 'One line description of project.',
'Miscellaneous'),
]


# -- Options for Epub output -------------------------------------------------

# Bibliographic Dublin Core info.
epub_title = project
epub_author = author
epub_publisher = author
epub_copyright = copyright

# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#
# epub_identifier = ''

# A unique identification for the text.
#
# epub_uid = ''

# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']


# -- Extension configuration -------------------------------------------------

# -- Options for intersphinx extension ---------------------------------------

# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'https://docs.python.org/': None}

# -- Options for todo extension ----------------------------------------------

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
11 changes: 11 additions & 0 deletions docs/databases.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---------
Databases
---------
.. Originally : Supported Back Ends

So far, pytest-flask-sqlalchemy has been most extensively tested against PostgreSQL 9.6.
It should theoretically work with any backend that is supported by SQLAlchemy, but Postgres is the only backend that is currently tested by the test suite.

Official support for SQLite and MySQL is `planned for a future release <https://github.com/jeancochrane/pytest-flask-sqlalchemy/issues/3>`_.
In the meantime, if you're using one of those backends and you run in to problems, we would greatly appreciate your help! `Open an issue <https://github.com/jeancochrane/pytest-flask-sqlalchemy/issues/new>`_ if something isn't working as you expect.

28 changes: 28 additions & 0 deletions docs/design.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
------
Design
------

Development
===========

Running the tests
-----------------

To run the tests, start by installing a development version of the plugin that includes test dependencies:

.. code-block:: console

pip install -e .[tests]


Next, export a `database connection string <http://docs.sqlalchemy.org/en/latest/core/engines.html#database-urls>`_ that the tests can use (the database referenced by the string will be created during test setup, so it does not need to exist):

.. code-block:: console

export TEST_DATABASE_URL=<db_connection_string>

Finally, run the tests using pytest:

.. code-block:: console

pytest
82 changes: 82 additions & 0 deletions docs/fixtures.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
--------
Fixtures
--------

This plugin provides two fixtures for performing database updates inside nested transactions that get rolled back at the end of a test: :ref:`db_session <db_session>` and :ref:`db_engine <db_engine>`.
The fixtures provide similar functionality, but with different APIs.

.. _db_session:

``db_session``
==============

The :ref:`db_session <db_session>` fixture allows you to perform direct updates that will be rolled back when the test exits.
It exposes the same API as `SQLAlchemy's scoped_session object <http://docs.sqlalchemy.org/en/latest/orm/contextual.html#sqlalchemy.orm.scoping.scoped_session>`_.

Including this fixture as a function argument of a test will activate any mocks that are defined by the configuration properties :ref:`mocked-engines <mocked-engines>`, :ref:`mocked-sessions <mocked-sessions>`, or :ref:`mocked-sessionmakers <mocked-sessionmakers>` in the test configuration file for the duration of that test.

.. rubric:: Example:

.. code-block:: Python

def test_a_transaction(db_session):
row = db_session.query(Table).get(1)
row.name = 'testing'

db_session.add(row)
db_session.commit()

def test_transaction_doesnt_persist(db_session):
row = db_session.query(Table).get(1)
assert row.name != 'testing'


.. _db_engine:

``db_engine``
=============

Like :ref:`db_session <db_session>`, the `db_engine` fixture allows you to perform direct updates against the test database that will be rolled back when the test exits.
It is an instance of Python's built-in `MagicMock <https://docs.python.org/3/library/unittest.mock.html#unittest.mock.MagicMock>`_ class, with a spec set to match the API of `SQLAlchemy's Engine <http://docs.sqlalchemy.org/en/latest/core/connections.html#sqlalchemy.engine.Engine>`_ object.

Only a few `Engine` methods are exposed on this fixture:

- `db_engine.begin`: begin a new nested transaction (`API docs <http://docs.sqlalchemy.org/en/latest/core/connections.html#sqlalchemy.engine.Engine.begin>`_)
- `db_engine.execute`: execute a raw SQL query (`API docs <http://docs.sqlalchemy.org/en/latest/core/connections.html#sqlalchemy.engine.Engine.execute>`_)
- `db_engine.raw_connection`: return a raw DBAPI connection (`API docs <http://docs.sqlalchemy.org/en/latest/core/connections.html#sqlalchemy.engine.Engine.raw_connection>`_)

Since `db_engine` is an instance of `MagicMock` with an `Engine` spec, other methods of the `Engine` API can be called, but they will not perform any useful work.

Including this fixture as a function argument of a test will activate any mocks that are defined by the configuration properties :ref:`mocked-engines <mocked-engines>`, :ref:`mocked-sessions <mocked-sessions>`, or :ref:`mocked-sessionmakers <mocked-sessionmakers>` in the test configuration file for the duration of that test.

.. rubric:: Example:

.. code-block:: Python

def test_a_transaction_using_engine(db_engine):
with db_engine.begin() as conn:
row = conn.execute('''UPDATE table SET name = 'testing' WHERE id = 1''')

def test_transaction_doesnt_persist(db_engine):
row_name = db_engine.execute('''SELECT name FROM table WHERE id = 1''').fetchone()[0]
assert row_name != 'testing'

.. _enabling-transactions-without-fixtures:

Enabling transactions without fixtures
--------------------------------------

If you know you want to make all of your tests transactional, it can be annoying to have to specify one of the :ref:`fixtures <Fixtures>` in every test signature.

The best way to automatically enable transactions without having to include an extra fixture in every test is to wire up an `autouse fixture <https://docs.pytest.org/en/latest/fixture.html#autouse-fixtures-xunit-setup-on-steroids>`_ for your test suite.
This can be as simple as ::

# Automatically enable transactions for all tests, without importing any extra fixtures.
@pytest.fixture(autouse=True)
def enable_transactional_tests(db_session):
pass


In this configuration, the `enable_transactional_tests` fixture will be automatically used in all tests, meaning that `db_session` will also be used.
This way, all tests will be wrapped in transactions without having to explicitly require either `db_session` or `enable_transactional_tests`.

56 changes: 56 additions & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
.. PyTest-Flask-SQLAlchemy documentation master file, created by
sphinx-quickstart on Fri Sep 20 10:22:51 2019.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.

=======================
PyTest-Flask-SQLAlchemy
=======================

.. image:: https://badge.fury.io/py/pytest-flask-sqlalchemy.svg
:target: https://badge.fury.io/py/pytest-flask-sqlalchemy

.. toctree::
:maxdepth: 2
:caption: Contents:

Quick Start <quickstart>
Install <installation>
Usage <utilization>
Fixtures <fixtures>
Databases <databases>
Design <design>

A `pytest <https://docs.pytest.org/en/latest/>`_ plugin providing fixtures for running tests in transactions using `Flask-SQLAlchemy <http://flask-sqlalchemy.pocoo.org/latest/>`_.

Motivation
----------

Inspired by `Django's built-in support for transactional tests <https://jeancochrane.com/blog/django-test-transactions>`_, this plugin seeks to provide comprehensive, easy-to-use Pytest fixtures for wrapping tests in database transactions for `Flask-SQLAlchemy <http://flask-sqlalchemy.pocoo.org/latest/>`_ apps.
The goal is to make testing stateful Flask-SQLAlchemy applications easier by providing fixtures that permit the developer to **make arbitrary database updates with the confidence that any changes made during a test will roll back** once the test exits.

Acknowledgements
----------------

This plugin was initially developed for testing `Dedupe.io <https://dedupe.io>`_, a web app for record linkage and entity resolution using machine learning.
Dedupe.io is built and maintained by `DataMade <https://datamade.us>`_.

The code is greatly indebted to `Alex Michael <https://github.com/alexmic>`_, whose blog post `"Delightful testing with pytest and Flask-SQLAlchemy" <http://alexmic.net/flask-sqlalchemy-pytest/>`_ helped establish the basic approach on which this plugin builds.

Many thanks to `Igor Ghisi <https://github.com/igortg/>`_, who donated the PyPi package name.
Igor had been working on a similar plugin and proposed combining efforts.
Thanks to Igor, the plugin name is much stronger.

Copyright
----------------

Copyright (c) 2019 Jean Cochrane and DataMade. Released under the MIT License.

Third-party copyright in this distribution is noted where applicable.

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
Loading