pax_global_header00006660000000000000000000000064130155173760014522gustar00rootroot0000000000000052 comment=7aee3670d2bd6067c36a88ecb691669250888dbd pytest-django-3.1.2/000077500000000000000000000000001301551737600143155ustar00rootroot00000000000000pytest-django-3.1.2/.coveragerc000066400000000000000000000000731301551737600164360ustar00rootroot00000000000000[run] parallel = true source = pytest_django branch = true pytest-django-3.1.2/.gitignore000066400000000000000000000002361301551737600163060ustar00rootroot00000000000000*.pyc build/ /dist/ *.egg-info _build .tox .DS_Store *~ .env /.coverage.* /.coverage /htmlcov/ /bin/ /include/ /lib/ /src/ /share/ .cache .Python .eggs *.egg pytest-django-3.1.2/.travis.yml000066400000000000000000000046011301551737600164270ustar00rootroot00000000000000# Use container-based environment (faster startup, allows caches). sudo: false language: python matrix: fast_finish: true include: - python: 3.5 env: TOXENV=py35-pytest30-djangomaster-postgres - python: 3.5 env: TOXENV=py35-pytest30-django1.10-postgres - python: 3.5 env: TOXENV=py35-pytest30-django1.9-postgres - python: 3.5 env: TOXENV=py35-pytest30-django1.8-postgres - python: 3.5 env: TOXENV=py35-checkqa - python: 3.4 env: TOXENV=py34-pytest30-django1.10-postgres - python: 3.3 env: TOXENV=py34-pytest30-django1.8-postgres - python: 2.7 env: TOXENV=py27-pytest30-djangomaster-postgres - python: 2.7 env: TOXENV=py27-pytest30-django1.10-mysql_innodb - python: 2.7 env: TOXENV=py27-pytest30-django1.10-mysql_myisam - python: 2.7 env: TOXENV=py27-pytest30-django1.10-postgres - python: 2.7 env: TOXENV=py27-pytest30-django1.9-postgres - python: 2.7 env: TOXENV=py27-pytest30-django1.8-postgres - python: 2.7 env: TOXENV=py27-pytest30-django1.7-postgres - python: 2.7 env: TOXENV=py27-checkqa - python: pypy3 env: TOXENV=pypy3-pytest29-django1.8-sqlite_file - python: pypy3 env: TOXENV=pypy3-pytest30-django1.8-sqlite - python: pypy3 env: TOXENV=pypy3-pytest30-django1.8-sqlite_file - python: pypy env: TOXENV=pypy-pytest30-django1.10-sqlite_file allow_failures: - env: TOXENV=py27-pytest30-djangomaster-postgres - env: TOXENV=py35-pytest30-djangomaster-postgres cache: directories: - "${TRAVIS_BUILD_DIR}/.tox" install: # Create pip wrapper script, using travis_retry (a function) and # inject it into tox.ini. - mkdir -p bin - PATH=$PWD/bin:$PATH - printf '#!/bin/sh\n' > bin/travis_retry_pip - declare -f travis_retry >> bin/travis_retry_pip - printf '\necho "Using pip-wrapper.." >&2\ntravis_retry pip "$@"' >> bin/travis_retry_pip - chmod +x bin/travis_retry_pip - sed -i.bak 's/^\[testenv\]/\0\ninstall_command = travis_retry_pip install {opts} {packages}/' tox.ini - diff tox.ini tox.ini.bak && return 1 || true - sed -i.bak 's/whitelist_externals =/\0\n travis_retry_pip/' tox.ini - diff tox.ini tox.ini.bak && return 1 || true - pip install tox==2.3.1 script: - tox - "find ${TRAVIS_BUILD_DIR}/.tox -name 'log' -o -name '__pycache__' -type d | xargs -I {} rm -rf {}" pytest-django-3.1.2/AUTHORS000066400000000000000000000007731301551737600153740ustar00rootroot00000000000000Ben Firshman created the original version of pytest-django. This fork is currently maintained by Andreas Pelme . These people have provided bug fixes, new features, improved the documentation or just made pytest-django more awesome: Ruben Bakker Ralf Schmitt Rob Berry Floris Bruynooghe Rafal Stozek Donald Stufft Nicolas Delaby Daniel Hahler pytest-django-3.1.2/LICENSE000066400000000000000000000062161301551737600153270ustar00rootroot00000000000000pytest-django is released under the BSD (3-clause) license ---------------------------------------------------------- Copyright (c) 2015, pytest-django authors (see AUTHORS file) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The names of its contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This version of pytest-django is a fork of pytest_django created by Ben Firshman. --------------------------------------------------------------------------------- Copyright (c) 2009, Ben Firshman All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The names of its contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. pytest-django-3.1.2/MANIFEST.in000066400000000000000000000005251301551737600160550ustar00rootroot00000000000000include AUTHORS include README.rst include LICENSE recursive-include test * recursive-exclude pytest_django_test * recursive-exclude .tox * recursive-exclude bin * recursive-exclude src * recursive-exclude .git * recursive-exclude bin * recursive-exclude include * recursive-exclude lib * recursive-exclude share * recursive-exclude src * pytest-django-3.1.2/Makefile000066400000000000000000000011311301551737600157510ustar00rootroot00000000000000.PHONY: docs test clean isort export DJANGO_SETTINGS_MODULE?=pytest_django_test.settings_sqlite_file testenv: bin/py.test test: bin/py.test bin/pip install -e . bin/py.test bin/python bin/pip: virtualenv . bin/py.test: bin/python requirements.txt bin/pip install -Ur requirements.txt touch $@ bin/sphinx-build: bin/pip bin/pip install sphinx docs: bin/sphinx-build SPHINXBUILD=../bin/sphinx-build $(MAKE) -C docs html # See setup.cfg for configuration. isort: find pytest_django tests -name '*.py' -exec isort {} + clean: rm -rf bin include/ lib/ man/ pytest_django.egg-info/ build/ pytest-django-3.1.2/README.rst000066400000000000000000000043071301551737600160100ustar00rootroot00000000000000.. image:: https://secure.travis-ci.org/pytest-dev/pytest-django.png?branch=master :alt: Build Status :target: https://travis-ci.org/pytest-dev/pytest-django Welcome to pytest-django! ========================= pytest-django allows you to test your Django project/applications with the `pytest testing tool `_. * `Quick start / tutorial `_ * `Changelog `_ * Full documentation: https://pytest-django.readthedocs.io/en/latest/ * `Contribution docs `_ * Version compatibility: * Django: 1.7-1.10 and latest master branch (compatible at the time of each release) * Python: CPython 2.7,3.3-3.5 or PyPy 2,3 * pytest: >2.9.x * Licence: BSD * Project maintainers: Andreas Pelme, Floris Bruynooghe and Daniel Hahler * `All contributors `_ * Github repository: https://github.com/pytest-dev/pytest-django * `Issue tracker `_ * `Python Package Index (PyPI) `_ Install pytest-django --------------------- :: pip install pytest-django Why would I use this instead of Django's `manage.py test` command? ------------------------------------------------------------------ Running your test suite with pytest-django allows you to tap into the features that are already present in pytest. Here are some advantages: * `Manage test dependencies with pytest fixtures. `_ * Less boilerplate tests: no need to import unittest, create a subclass with methods. Write tests as regular functions. * Database re-use: no need to re-create the test database for every test run. * Run tests in multiple processes for increased speed (with the pytest-xdist plugin). * Make use of other `pytest plugins `_. * Works with both worlds: Existing unittest-style TestCase's still work without any modifications. See the `pytest documentation `_ for more information on pytest itself. pytest-django-3.1.2/docs/000077500000000000000000000000001301551737600152455ustar00rootroot00000000000000pytest-django-3.1.2/docs/Makefile000066400000000000000000000127701301551737600167140ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = ifndef SPHINXBUILD SPHINXBUILD = ../bin/sphinx-build endif PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/pytest-django.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/pytest-django.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/pytest-django" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/pytest-django" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." pytest-django-3.1.2/docs/_ext/000077500000000000000000000000001301551737600162045ustar00rootroot00000000000000pytest-django-3.1.2/docs/_ext/pytestdocs.py000066400000000000000000000002311301551737600207530ustar00rootroot00000000000000def setup(app): app.add_crossref_type( directivename="fixture", rolename="fixture", indextemplate="pair: %s; fixture", ) pytest-django-3.1.2/docs/_static/000077500000000000000000000000001301551737600166735ustar00rootroot00000000000000pytest-django-3.1.2/docs/_static/basic.css000066400000000000000000000203711301551737600204710ustar00rootroot00000000000000/* * basic.css * ~~~~~~~~~ * * Sphinx stylesheet -- basic theme. * * :copyright: Copyright 2007-2011 by the Sphinx team, see AUTHORS. * :license: BSD, see LICENSE for details. * */ /* -- main layout ----------------------------------------------------------- */ div.clearer { clear: both; } /* -- relbar ---------------------------------------------------------------- */ div.related { width: 100%; font-size: 90%; } div.related h3 { display: none; } div.related ul { margin: 0; padding: 0 0 0 10px; list-style: none; } div.related li { display: inline; } div.related li.right { float: right; margin-right: 5px; } /* -- sidebar --------------------------------------------------------------- */ div.sphinxsidebarwrapper { padding: 10px 5px 0 10px; } div.sphinxsidebar { float: left; width: 230px; margin-left: -100%; font-size: 90%; } div.sphinxsidebar ul { list-style: none; } div.sphinxsidebar ul ul, div.sphinxsidebar ul.want-points { margin-left: 20px; list-style: square; } div.sphinxsidebar ul ul { margin-top: 0; margin-bottom: 0; } div.sphinxsidebar form { margin-top: 10px; } div.sphinxsidebar input { border: 1px solid #98dbcc; font-family: sans-serif; font-size: 1em; } div.sphinxsidebar input[type="text"] { width: 170px; } div.sphinxsidebar input[type="submit"] { width: 30px; } img { border: 0; } /* -- search page ----------------------------------------------------------- */ ul.search { margin: 10px 0 0 20px; padding: 0; } ul.search li { padding: 5px 0 5px 20px; background-image: url(file.png); background-repeat: no-repeat; background-position: 0 7px; } ul.search li a { font-weight: bold; } ul.search li div.context { color: #888; margin: 2px 0 0 30px; text-align: left; } ul.keywordmatches li.goodmatch a { font-weight: bold; } /* -- index page ------------------------------------------------------------ */ table.contentstable { width: 90%; } table.contentstable p.biglink { line-height: 150%; } a.biglink { font-size: 1.3em; } span.linkdescr { font-style: italic; padding-top: 5px; font-size: 90%; } /* -- general index --------------------------------------------------------- */ table.indextable { width: 100%; } table.indextable td { text-align: left; vertical-align: top; } table.indextable dl, table.indextable dd { margin-top: 0; margin-bottom: 0; } table.indextable tr.pcap { height: 10px; } table.indextable tr.cap { margin-top: 10px; background-color: #f2f2f2; } img.toggler { margin-right: 3px; margin-top: 3px; cursor: pointer; } div.modindex-jumpbox { border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; margin: 1em 0 1em 0; padding: 0.4em; } div.genindex-jumpbox { border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; margin: 1em 0 1em 0; padding: 0.4em; } /* -- general body styles --------------------------------------------------- */ a.headerlink { visibility: hidden; } h1:hover > a.headerlink, h2:hover > a.headerlink, h3:hover > a.headerlink, h4:hover > a.headerlink, h5:hover > a.headerlink, h6:hover > a.headerlink, dt:hover > a.headerlink { visibility: visible; } div.body p.caption { text-align: inherit; } div.body td { text-align: left; } .field-list ul { padding-left: 1em; } .first { margin-top: 0 !important; } p.rubric { margin-top: 30px; font-weight: bold; } img.align-left, .figure.align-left, object.align-left { clear: left; float: left; margin-right: 1em; } img.align-right, .figure.align-right, object.align-right { clear: right; float: right; margin-left: 1em; } img.align-center, .figure.align-center, object.align-center { display: block; margin-left: auto; margin-right: auto; } .align-left { text-align: left; } .align-center { text-align: center; } .align-right { text-align: right; } /* -- sidebars -------------------------------------------------------------- */ div.sidebar { margin: 0 0 0.5em 1em; border: 1px solid #ddb; padding: 7px 7px 0 7px; background-color: #ffe; width: 40%; float: right; } p.sidebar-title { font-weight: bold; } /* -- topics ---------------------------------------------------------------- */ div.topic { border: 1px solid #ccc; padding: 7px 7px 0 7px; margin: 10px 0 10px 0; } p.topic-title { font-size: 1.1em; font-weight: bold; margin-top: 10px; } /* -- admonitions ----------------------------------------------------------- */ div.admonition { margin-top: 10px; margin-bottom: 10px; padding: 7px; } div.admonition dt { font-weight: bold; } div.admonition dl { margin-bottom: 0; } p.admonition-title { margin: 0px 10px 5px 0px; font-weight: bold; } div.body p.centered { text-align: center; margin-top: 25px; } /* -- tables ---------------------------------------------------------------- */ table.docutils { border: 0; border-collapse: collapse; } table.docutils td, table.docutils th { padding: 1px 8px 1px 5px; border-top: 0; border-left: 0; border-right: 0; border-bottom: 1px solid #aaa; } table.field-list td, table.field-list th { border: 0 !important; } table.footnote td, table.footnote th { border: 0 !important; } th { text-align: left; padding-right: 5px; } table.citation { border-left: solid 1px gray; margin-left: 1px; } table.citation td { border-bottom: none; } /* -- other body styles ----------------------------------------------------- */ ol.arabic { list-style: decimal; } ol.loweralpha { list-style: lower-alpha; } ol.upperalpha { list-style: upper-alpha; } ol.lowerroman { list-style: lower-roman; } ol.upperroman { list-style: upper-roman; } dl { margin-bottom: 15px; } dd p { margin-top: 0px; } dd ul, dd table { margin-bottom: 10px; } dd { margin-top: 3px; margin-bottom: 10px; margin-left: 30px; } dt:target, .highlighted { background-color: #fbe54e; } dl.glossary dt { font-weight: bold; font-size: 1.1em; } .field-list ul { margin: 0; padding-left: 1em; } .field-list p { margin: 0; } .refcount { color: #060; } .optional { font-size: 1.3em; } .versionmodified { font-style: italic; } .system-message { background-color: #fda; padding: 5px; border: 3px solid red; } .footnote:target { background-color: #ffa; } .line-block { display: block; margin-top: 1em; margin-bottom: 1em; } .line-block .line-block { margin-top: 0; margin-bottom: 0; margin-left: 1.5em; } .guilabel, .menuselection { font-family: sans-serif; } .accelerator { text-decoration: underline; } .classifier { font-style: oblique; } abbr, acronym { border-bottom: dotted 1px; cursor: help; } /* -- code displays --------------------------------------------------------- */ pre { overflow: auto; overflow-y: hidden; /* fixes display issues on Chrome browsers */ } td.linenos pre { padding: 5px 0px; border: 0; background-color: transparent; color: #aaa; } table.highlighttable { margin-left: 0.5em; } table.highlighttable td { padding: 0 0.5em 0 0.5em; } tt.descname { background-color: transparent; font-weight: bold; font-size: 1.2em; } tt.descclassname { background-color: transparent; } tt.xref, a tt { background-color: transparent; font-weight: bold; } h1 tt, h2 tt, h3 tt, h4 tt, h5 tt, h6 tt { background-color: transparent; } .viewcode-link { float: right; } .viewcode-back { float: right; font-family: sans-serif; } div.viewcode-block:target { margin: -1px -10px; padding: 0 10px; } /* -- math display ---------------------------------------------------------- */ img.math { vertical-align: middle; } div.body div.math p { text-align: center; } span.eqno { float: right; } /* -- printout stylesheet --------------------------------------------------- */ @media print { div.document, div.documentwrapper, div.bodywrapper { margin: 0 !important; width: 100%; } div.sphinxsidebar, div.related, div.footer, #top-link { display: none; } }pytest-django-3.1.2/docs/_static/rtd.css000066400000000000000000000364011301551737600202020ustar00rootroot00000000000000/* * rtd.css * ~~~~~~~~~~~~~~~ * * Sphinx stylesheet -- sphinxdoc theme. Originally created by * Armin Ronacher for Werkzeug. * * Customized for ReadTheDocs by Eric Pierce & Eric Holscher * * :copyright: Copyright 2007-2010 by the Sphinx team, see AUTHORS. * :license: BSD, see LICENSE for details. * */ /* RTD colors * light blue: #e8ecef * medium blue: #8ca1af * dark blue: #465158 * dark grey: #444444 * * white hover: #d1d9df; * medium blue hover: #697983; * green highlight: #8ecc4c * light blue (project bar): #e8ecef */ @import url("basic.css"); /* PAGE LAYOUT -------------------------------------------------------------- */ body { font: 100%/1.5 "ff-meta-web-pro-1","ff-meta-web-pro-2",Arial,"Helvetica Neue",sans-serif; text-align: center; color: black; background-color: #465158; padding: 0; margin: 0; } div.document { text-align: left; background-color: #e8ecef; } div.bodywrapper { background-color: #ffffff; border-left: 1px solid #ccc; border-bottom: 1px solid #ccc; margin: 0 0 0 16em; } div.body { margin: 0; padding: 0.5em 1.3em; min-width: 20em; } div.related { font-size: 1em; background-color: #465158; } div.documentwrapper { float: left; width: 100%; background-color: #e8ecef; } /* HEADINGS --------------------------------------------------------------- */ h1 { margin: 0; padding: 0.7em 0 0.3em 0; font-size: 1.5em; line-height: 1.15; color: #111; clear: both; } h2 { margin: 2em 0 0.2em 0; font-size: 1.35em; padding: 0; color: #465158; } h3 { margin: 1em 0 -0.3em 0; font-size: 1.2em; color: #6c818f; } div.body h1 a, div.body h2 a, div.body h3 a, div.body h4 a, div.body h5 a, div.body h6 a { color: black; } h1 a.anchor, h2 a.anchor, h3 a.anchor, h4 a.anchor, h5 a.anchor, h6 a.anchor { display: none; margin: 0 0 0 0.3em; padding: 0 0.2em 0 0.2em; color: #aaa !important; } h1:hover a.anchor, h2:hover a.anchor, h3:hover a.anchor, h4:hover a.anchor, h5:hover a.anchor, h6:hover a.anchor { display: inline; } h1 a.anchor:hover, h2 a.anchor:hover, h3 a.anchor:hover, h4 a.anchor:hover, h5 a.anchor:hover, h6 a.anchor:hover { color: #777; background-color: #eee; } /* LINKS ------------------------------------------------------------------ */ /* Normal links get a pseudo-underline */ a { color: #444; text-decoration: none; border-bottom: 1px solid #ccc; } /* Links in sidebar, TOC, index trees and tables have no underline */ .sphinxsidebar a, .toctree-wrapper a, .indextable a, #indices-and-tables a { color: #444; text-decoration: none; border-bottom: none; } /* Most links get an underline-effect when hovered */ a:hover, div.toctree-wrapper a:hover, .indextable a:hover, #indices-and-tables a:hover { color: #111; text-decoration: none; border-bottom: 1px solid #111; } /* Footer links */ div.footer a { color: #86989B; text-decoration: none; border: none; } div.footer a:hover { color: #a6b8bb; text-decoration: underline; border: none; } /* Permalink anchor (subtle grey with a red hover) */ div.body a.headerlink { color: #ccc; font-size: 1em; margin-left: 6px; padding: 0 4px 0 4px; text-decoration: none; border: none; } div.body a.headerlink:hover { color: #c60f0f; border: none; } /* NAVIGATION BAR --------------------------------------------------------- */ div.related ul { height: 2.5em; } div.related ul li { margin: 0; padding: 0.65em 0; float: left; display: block; color: white; /* For the >> separators */ font-size: 0.8em; } div.related ul li.right { float: right; margin-right: 5px; color: transparent; /* Hide the | separators */ } /* "Breadcrumb" links in nav bar */ div.related ul li a { order: none; background-color: inherit; font-weight: bold; margin: 6px 0 6px 4px; line-height: 1.75em; color: #ffffff; padding: 0.4em 0.8em; border: none; border-radius: 3px; } /* previous / next / modules / index links look more like buttons */ div.related ul li.right a { margin: 0.375em 0; background-color: #697983; text-shadow: 0 1px rgba(0, 0, 0, 0.5); border-radius: 3px; -webkit-border-radius: 3px; -moz-border-radius: 3px; } /* All navbar links light up as buttons when hovered */ div.related ul li a:hover { background-color: #8ca1af; color: #ffffff; text-decoration: none; border-radius: 3px; -webkit-border-radius: 3px; -moz-border-radius: 3px; } /* Take extra precautions for tt within links */ a tt, div.related ul li a tt { background: inherit !important; color: inherit !important; } /* SIDEBAR ---------------------------------------------------------------- */ div.sphinxsidebarwrapper { padding: 0; } div.sphinxsidebar { margin: 0; margin-left: -100%; float: left; top: 3em; left: 0; padding: 0 1em; width: 14em; font-size: 1em; text-align: left; background-color: #e8ecef; } div.sphinxsidebar img { max-width: 12em; } div.sphinxsidebar h3, div.sphinxsidebar h4, div.sphinxsidebar p.logo { margin: 1.2em 0 0.3em 0; font-size: 1em; padding: 0; color: #222222; font-family: "ff-meta-web-pro-1", "ff-meta-web-pro-2", "Arial", "Helvetica Neue", sans-serif; } div.sphinxsidebar h3 a { color: #444444; } div.sphinxsidebar ul, div.sphinxsidebar p { margin-top: 0; padding-left: 0; line-height: 130%; background-color: #e8ecef; } /* No bullets for nested lists, but a little extra indentation */ div.sphinxsidebar ul ul { list-style-type: none; margin-left: 1.5em; padding: 0; } /* A little top/bottom padding to prevent adjacent links' borders * from overlapping each other */ div.sphinxsidebar ul li { padding: 1px 0; } /* A little left-padding to make these align with the ULs */ div.sphinxsidebar p.topless { padding-left: 0 0 0 1em; } /* Make these into hidden one-liners */ div.sphinxsidebar ul li, div.sphinxsidebar p.topless { white-space: nowrap; overflow: hidden; } /* ...which become visible when hovered */ div.sphinxsidebar ul li:hover, div.sphinxsidebar p.topless:hover { overflow: visible; } /* Search text box and "Go" button */ #searchbox { margin-top: 2em; margin-bottom: 1em; background: #ddd; padding: 0.5em; border-radius: 6px; -moz-border-radius: 6px; -webkit-border-radius: 6px; } #searchbox h3 { margin-top: 0; } /* Make search box and button abut and have a border */ input, div.sphinxsidebar input { border: 1px solid #999; float: left; } /* Search textbox */ input[type="text"] { margin: 0; padding: 0 3px; height: 20px; width: 144px; border-top-left-radius: 3px; border-bottom-left-radius: 3px; -moz-border-radius-topleft: 3px; -moz-border-radius-bottomleft: 3px; -webkit-border-top-left-radius: 3px; -webkit-border-bottom-left-radius: 3px; } /* Search button */ input[type="submit"] { margin: 0 0 0 -1px; /* -1px prevents a double-border with textbox */ height: 22px; color: #444; background-color: #e8ecef; padding: 1px 4px; font-weight: bold; border-top-right-radius: 3px; border-bottom-right-radius: 3px; -moz-border-radius-topright: 3px; -moz-border-radius-bottomright: 3px; -webkit-border-top-right-radius: 3px; -webkit-border-bottom-right-radius: 3px; } input[type="submit"]:hover { color: #ffffff; background-color: #8ecc4c; } div.sphinxsidebar p.searchtip { clear: both; padding: 0.5em 0 0 0; background: #ddd; color: #666; font-size: 0.9em; } /* Sidebar links are unusual */ div.sphinxsidebar li a, div.sphinxsidebar p a { background: #e8ecef; /* In case links overlap main content */ border-radius: 3px; -moz-border-radius: 3px; -webkit-border-radius: 3px; border: 1px solid transparent; /* To prevent things jumping around on hover */ padding: 0 5px 0 5px; } div.sphinxsidebar li a:hover, div.sphinxsidebar p a:hover { color: #111; text-decoration: none; border: 1px solid #888; } div.sphinxsidebar p.logo a { border: 0; } /* Tweak any link appearing in a heading */ div.sphinxsidebar h3 a { } /* OTHER STUFF ------------------------------------------------------------ */ cite, code, tt { font-family: 'Consolas', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace; font-size: 0.95em; letter-spacing: 0.01em; } tt { background-color: #f2f2f2; color: #444; } tt.descname, tt.descclassname, tt.xref { border: 0; } hr { border: 1px solid #abc; margin: 2em; } pre, #_fontwidthtest { font-family: 'Consolas', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace; margin: 1em 2em; font-size: 0.95em; letter-spacing: 0.015em; line-height: 120%; padding: 0.5em; border: 1px solid #ccc; background-color: #eee; border-radius: 6px; -moz-border-radius: 6px; -webkit-border-radius: 6px; } pre a { color: inherit; text-decoration: underline; } td.linenos pre { margin: 1em 0em; } td.code pre { margin: 1em 0em; } div.quotebar { background-color: #f8f8f8; max-width: 250px; float: right; padding: 2px 7px; border: 1px solid #ccc; } div.topic { background-color: #f8f8f8; } table { border-collapse: collapse; margin: 0 -0.5em 0 -0.5em; } table td, table th { padding: 0.2em 0.5em 0.2em 0.5em; } /* ADMONITIONS AND WARNINGS ------------------------------------------------- */ /* Shared by admonitions, warnings and sidebars */ div.admonition, div.warning, div.sidebar { font-size: 0.9em; margin: 2em; padding: 0; /* border-radius: 6px; -moz-border-radius: 6px; -webkit-border-radius: 6px; */ } div.admonition p, div.warning p, div.sidebar p { margin: 0.5em 1em 0.5em 1em; padding: 0; } div.admonition pre, div.warning pre, div.sidebar pre { margin: 0.4em 1em 0.4em 1em; } div.admonition p.admonition-title, div.warning p.admonition-title, div.sidebar p.sidebar-title { margin: 0; padding: 0.1em 0 0.1em 0.5em; color: white; font-weight: bold; font-size: 1.1em; text-shadow: 0 1px rgba(0, 0, 0, 0.5); } div.admonition ul, div.admonition ol, div.warning ul, div.warning ol, div.sidebar ul, div.sidebar ol { margin: 0.1em 0.5em 0.5em 3em; padding: 0; } /* Admonitions and sidebars only */ div.admonition, div.sidebar { border: 1px solid #609060; background-color: #e9ffe9; } div.admonition p.admonition-title, div.sidebar p.sidebar-title { background-color: #70A070; border-bottom: 1px solid #609060; } /* Warnings only */ div.warning { border: 1px solid #900000; background-color: #ffe9e9; } div.warning p.admonition-title { background-color: #b04040; border-bottom: 1px solid #900000; } /* Sidebars only */ div.sidebar { max-width: 30%; } div.versioninfo { margin: 1em 0 0 0; border: 1px solid #ccc; background-color: #DDEAF0; padding: 8px; line-height: 1.3em; font-size: 0.9em; } .viewcode-back { font-family: 'Lucida Grande', 'Lucida Sans Unicode', 'Geneva', 'Verdana', sans-serif; } div.viewcode-block:target { background-color: #f4debf; border-top: 1px solid #ac9; border-bottom: 1px solid #ac9; } dl { margin: 1em 0 2.5em 0; } /* Highlight target when you click an internal link */ dt:target { background: #ffe080; } /* Don't highlight whole divs */ div.highlight { background: transparent; } /* But do highlight spans (so search results can be highlighted) */ span.highlight { background: #ffe080; } div.footer { background-color: #465158; color: #eeeeee; padding: 0 2em 2em 2em; clear: both; font-size: 0.8em; text-align: center; } p { margin: 0.8em 0 0.5em 0; } .section p img.math { margin: 0; } .section p img { margin: 1em 2em; } /* MOBILE LAYOUT -------------------------------------------------------------- */ @media screen and (max-width: 600px) { h1, h2, h3, h4, h5 { position: relative; } ul { padding-left: 1.25em; } div.bodywrapper a.headerlink, #indices-and-tables h1 a { color: #e6e6e6; font-size: 80%; float: right; line-height: 1.8; position: absolute; right: -0.7em; visibility: inherit; } div.bodywrapper h1 a.headerlink, #indices-and-tables h1 a { line-height: 1.5; } pre { font-size: 0.7em; overflow: auto; word-wrap: break-word; white-space: pre-wrap; } div.related ul { height: 2.5em; padding: 0; text-align: left; } div.related ul li { clear: both; color: #465158; padding: 0.2em 0; } div.related ul li:last-child { border-bottom: 1px dotted #8ca1af; padding-bottom: 0.4em; margin-bottom: 1em; width: 100%; } div.related ul li a { color: #465158; padding-right: 0; } div.related ul li a:hover { background: inherit; color: inherit; } div.related ul li.right { clear: none; padding: 0.65em 0; margin-bottom: 0.5em; } div.related ul li.right a { color: #fff; padding-right: 0.8em; } div.related ul li.right a:hover { background-color: #8ca1af; } div.body { clear: both; min-width: 0; word-wrap: break-word; } div.bodywrapper { margin: 0 0 0 0; } div.sphinxsidebar { float: none; margin: 0; width: auto; } div.sphinxsidebar input[type="text"] { height: 2em; line-height: 2em; width: 70%; } div.sphinxsidebar input[type="submit"] { height: 2em; margin-left: 0.5em; width: 20%; } div.sphinxsidebar p.searchtip { background: inherit; margin-bottom: 1em; } div.sphinxsidebar ul li, div.sphinxsidebar p.topless { white-space: normal; } .bodywrapper img { display: block; margin-left: auto; margin-right: auto; max-width: 100%; } div.documentwrapper { float: none; } div.admonition, div.warning, pre, blockquote { margin-left: 0em; margin-right: 0em; } .body p img { margin: 0; } #searchbox { background: transparent; } .related:not(:first-child) li { display: none; } .related:not(:first-child) li.right { display: block; } div.footer { padding: 1em; } .rtd_doc_footer .badge { float: none; margin: 1em auto; position: static; } .rtd_doc_footer .badge.revsys-inline { margin-right: auto; margin-bottom: 2em; } table.indextable { display: block; width: auto; } .indextable tr { display: block; } .indextable td { display: block; padding: 0; width: auto !important; } .indextable td dt { margin: 1em 0; } ul.search { margin-left: 0.25em; } ul.search li div.context { font-size: 90%; line-height: 1.1; margin-bottom: 1; margin-left: 0; } } pytest-django-3.1.2/docs/changelog.rst000066400000000000000000000320461301551737600177330ustar00rootroot00000000000000Changelog ========= 3.1.2 ----- Bug fixes ^^^^^^^^^ * Auto clearing of ``mail.outbox`` has been re-introduced to not break functionality in 3.x.x release. This means that Compatibility issues mentioned in the 3.1.0 release are no longer present. Related issue: _`pytest-django issue ` 3.1.1 ----- Bug fixes ^^^^^^^^^ * Workaround `--pdb` interaction with Django TestCase. The issue is caused by Django TestCase not implementing TestCase.debug() properly but was brought to attention with recent changes in pytest 3.0.2. Related issues: `pytest issue `_, `Django issue `_. 3.1.0 ----- Features ^^^^^^^^ * Added new function scoped fixture ``mailoutbox`` that gives access to djangos ``mail.outbox``. The will clean/empty the ``mail.outbox`` to assure that no old mails are still in the outbox. * If ``django.contrib.sites`` is in your INSTALLED_APPS, Site cache will be cleared for each test to avoid hitting the cache and cause wrong Site object to be returned by ``Site.objects.get_current()``. Compatibility ^^^^^^^^^^^^^ * IMPORTANT: the internal autouse fixture _django_clear_outbox has been removed. If you have relied on this to get an empty outbox for your test, you should change tests to use the ``mailoutbox`` fixture instead. See documentation of ``mailoutbox`` fixture for usage. If you try to access mail.outbox directly, AssertionError will be raised. If you previously relied on the old behaviour and do not want to change your tests, put this in your project conftest.py:: @pytest.fixture(autouse=True) def clear_outbox(): from django.core import mail mail.outbox = [] 3.0.0 ----- Bug fixes ^^^^^^^^^ * Fix error when Django happens to be imported before pytest-django runs. Thanks to Will Harris for `the bug report `_. Features ^^^^^^^^ * Added a new option ``--migrations`` to negate a default usage of ``--nomigrations``. * The previously internal pytest-django fixture that handles database creation and setup has been refactored, refined and made a public API. This opens up more flexibility and advanced use cases to configure the test database in new ways. See :ref:`advanced-database-configuration` for more information on the new fixtures and example use cases. Compatibility ^^^^^^^^^^^^^ * Official for the pytest 3.0.0 (2.9.2 release should work too, though). The documentation is updated to mention ``pytest`` instead of ``py.test``. * Django versions 1.4, 1.5 and 1.6 is no longer supported. The supported versions are now 1.7 and forward. Django master is supported as of 2016-08-21. * pytest-django no longer supports Python 2.6. * Specifying the ``DJANGO_TEST_LIVE_SERVER_ADDRESS`` environment variable is no longer supported. Use ``DJANGO_LIVE_TEST_SERVER_ADDRESS`` instead. * Ensuring accidental database access is now stricter than before. Previously database access was prevented on the cursor level. To be safer and prevent more cases, it is now prevented at the connection level. If you previously had tests which interacted with the databases without a database cursor, you will need to mark them with the :func:`pytest.mark.django_db` marker or request the ``db`` fixture. * The previously undocumented internal fixtures ``_django_db_setup``, ``_django_cursor_wrapper`` have been removed in favour of the new public fixtures. If you previously relied on these internal fixtures, you must update your code. See :ref:`advanced-database-configuration` for more information on the new fixtures and example use cases. 2.9.1 ----- Bug fixes ^^^^^^^^^ * Fix regression introduced in 2.9.0 that caused TestCase subclasses with mixins to cause errors. Thanks MikeVL for `the bug report `_. 2.9.0 ----- 2.9.0 focus on compatibility with Django 1.9 and master as well as pytest 2.8.1 and Python 3.5 Features ^^^^^^^^ * ``--fail-on-template-vars`` - fail tests for invalid variables in templates. Thanks to Johannes Hoppe for idea and implementation. Thanks Daniel Hahler for review and feedback. Bug fixes ^^^^^^^^^ * Ensure urlconf is properly reset when using @pytest.mark.urls. Thanks to Sarah Bird, David Szotten, Daniel Hahler and Yannick PÉROUX for patch and discussions. Fixes `issue #183 `_. * Call ``setUpClass()`` in Django ``TestCase`` properly when test class is inherited multiple places. Thanks to Benedikt Forchhammer for report and initial test case. Fixes `issue #265 `_. Compatibility ^^^^^^^^^^^^^ * Settings defined in ``pytest.ini``/``tox.ini``/``setup.cfg`` used to override ``DJANGO_SETTINGS_MODULE`` defined in the environment. Previously the order was undocumented. Now, instead the settings from the environment will be used instead. If you previously relied on overriding the environment variable, you can instead specify ``addopts = --ds=yourtestsettings`` in the ini-file which will use the test settings. See `PR #199 `_. * Support for Django 1.9. * Support for Django master (to be 1.10) as of 2015-10-06. * Drop support for Django 1.3. While pytest-django supports a wide range of Django versions, extended for Django 1.3 was dropped in february 2013. 2.8.0 ----- Features ^^^^^^^^ * pytest's verbosity is being used for Django's code to setup/teardown the test database (#172). * Added a new option `--nomigrations` to avoid running Django 1.7+ migrations when constructing the test database. Huge thanks to Renan Ivo for complete patch, tests and documentation. Bug fixes ^^^^^^^^^ * Fixed compatibility issues related to Django 1.8's `setUpClass`/`setUpTestData`. Django 1.8 is now a fully supported version. Django master as of 2014-01-18 (the Django 1.9 branch) is also supported. 2.7.0 ----- Features ^^^^^^^^ * New fixtures: ``admin_user``, ``django_user_model`` and ``django_username_field`` (#109). * Automatic discovery of Django projects to make it easier for new users. This change is slightly backward incompatible, if you encounter problems with it, the old behaviour can be restored by adding this to ``pytest.ini``, ``setup.cfg`` or ``tox.ini``:: [pytest] django_find_project = false Please see the :ref:`managing_python_path` section for more information. Bugfixes ^^^^^^^^ * Fix interaction between ``db`` and ``transaction_db`` fixtures (#126). * Fix admin client with custom user models (#124). Big thanks to Benjamin Hedrich and Dmitry Dygalo for patch and tests. * Fix usage of South migrations, which were unconditionally disabled previously (#22). * Fixed #119, #134: Call ``django.setup()`` in Django >=1.7 directly after settings is loaded to ensure proper loading of Django applications. Thanks to Ionel Cristian Mărieș, Daniel Hahler, Tymur Maryokhin, Kirill SIbirev, Paul Collins, Aymeric Augustin, Jannis Leidel, Baptiste Mispelon and Anatoly Bubenkoff for report, discussion and feedback. * `The `live_server`` fixture can now serve static files also for Django>=1.7 if the ``django.contrib.staticfiles`` app is installed. (#140). * ``DJANGO_LIVE_TEST_SERVER_ADDRESS`` environment variable is read instead of ``DJANGO_TEST_LIVE_SERVER_ADDRESS``. (#140) 2.6.2 ----- * Fixed a bug that caused doctests to runs. Thanks to @jjmurre for the patch * Fixed issue #88 - make sure to use SQLite in memory database when running with pytest-xdist. 2.6.1 ----- This is a bugfix/support release with no new features: * Added support for Django 1.7 beta and Django master as of 2014-04-16. pytest-django is now automatically tested against the latest git master version of Django. * Support for MySQL with MyISAM tables. Thanks to Zach Kanzler and Julen Ruiz Aizpuru for fixing this. This fixes issue #8 #64. 2.6.0 ----- * Experimental support for Django 1.7 / Django master as of 2014-01-19. pytest-django is now automatically tested against the latest git version of Django. The support is experimental since Django 1.7 is not yet released, but the goal is to always be up to date with the latest Django master 2.5.1 ----- Invalid release accidentally pushed to PyPI (identical to 2.6.1). Should not be used - use 2.6.1 or newer to avoid confusion. 2.5.0 ----- * Python 2.5 compatibility dropped. py.test 2.5 dropped support for Python 2.5, therefore it will be hard to properly support in pytest-django. The same strategy as for pytest itself is used: No code will be changed to prevent Python 2.5 from working, but it will not be actively tested. * pytest-xdist support: it is now possible to run tests in parallel. Just use pytest-xdist as normal (pass -n to py.test). One database will be created for each subprocess so that tests run independent from each other. 2.4.0 ----- * Support for py.test 2.4 pytest_load_initial_conftests. This makes it possible to import Django models in project conftest.py files, since pytest-django will be initialized before the conftest.py is loaded. 2.3.1 ----- * Support for Django 1.5 custom user models, thanks to Leonardo Santagada. 2.3.0 ----- * Support for configuring settings via django-configurations. Big thanks to Donald Stufft for this feature! 2.2.1 ----- * Fixed an issue with the settings fixture when used in combination with django-appconf. It now uses pytest's monkeypatch internally and should be more robust. 2.2.0 ----- * Python 3 support. pytest-django now supports Python 3.2 and 3.3 in addition to 2.5-2.7. Big thanks to Rafal Stozek for making this happen! 2.1.0 ----- * Django 1.5 support. pytest-django is now tested against 1.5 for Python 2.6-2.7. This is the first step towards Python 3 support. 2.0.1 ----- * Fixed #24/#25: Make it possible to configure Django via ``django.conf.settings.configure()``. * Fixed #26: Don't set DEBUG_PROPAGATE_EXCEPTIONS = True for test runs. Django does not change this setting in the default test runner, so pytest-django should not do it either. 2.0.0 ----- This release is *backward incompatible*. The biggest change is the need to add the ``pytest.mark.django_db`` to tests which require database access. Finding such tests is generally very easy: just run your test suite, the tests which need database access will fail. Add ``pytestmark = pytest.mark.django_db`` to the module/class or decorate them with ``@pytest.mark.django_db``. Most of the internals have been rewritten, exploiting py.test's new fixtures API. This release would not be possible without Floris Bruynooghe who did the port to the new fixture API and fixed a number of bugs. The tests for pytest-django itself has been greatly improved, paving the way for easier additions of new and exciting features in the future! * Semantic version numbers will now be used for releases, see http://semver.org/. * Do not allow database access in tests by default. Introduce ``pytest.mark.django_db`` to enable database access. * Large parts re-written using py.test's 2.3 fixtures API (issue #9). - Fixes issue #17: Database changes made in fixtures or funcargs will now be reverted as well. - Fixes issue 21: Database teardown errors are no longer hidden. - Fixes issue 16: Database setup and teardown for non-TestCase classes works correctly. * ``pytest.urls()`` is replaced by the standard marking API and is now used as ``pytest.mark.urls()`` * Make the plugin behave gracefully without DJANGO_SETTINGS_MODULE specified. ``py.test`` will still work and tests needing django features will skip (issue #3). * Allow specifying of ``DJANGO_SETTINGS_MODULE`` on the command line (``--ds=settings``) and py.test ini configuration file as well as the environment variable (issue #3). * Deprecate the ``transaction_test_case`` decorator, this is now integrated with the ``django_db`` mark. 1.4 --- * Removed undocumented pytest.load_fixture: If you need this feature, just use ``django.management.call_command('loaddata', 'foo.json')`` instead. * Fixed issue with RequestFactory in Django 1.3. * Fixed issue with RequestFactory in Django 1.3. 1.3 --- * Added ``--reuse-db`` and ``--create-db`` to allow database re-use. Many thanks to `django-nose `_ for code and inspiration for this feature. 1.2.2 ----- * Fixed Django 1.3 compatibility. 1.2.1 ----- * Disable database access and raise errors when using --no-db and accessing the database by accident. 1.2 --- * Added the ``--no-db`` command line option. 1.1.1 ----- * Flush tables after each test run with transaction_test_case instead of before. 1.1 --- * The initial release of this fork from `Ben Firshman original project `_ * Added documentation * Uploaded to PyPI for easy installation * Added the ``transaction_test_case`` decorator for tests that needs real transactions * Added initial implementation for live server support via a funcarg (no docs yet, it might change!) pytest-django-3.1.2/docs/conf.py000066400000000000000000000026271301551737600165530ustar00rootroot00000000000000# -*- coding: utf-8 -*- import os import sys import datetime # 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. sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "_ext"))) # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ 'sphinx.ext.doctest', 'pytestdocs', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General information about the project. project = u'pytest-django' copyright = u'%d, Andreas Pelme and contributors' % datetime.date.today().year exclude_patterns = ['_build'] pygments_style = 'sphinx' html_theme = 'default' html_style = 'rtd.css' RTD_NEW_THEME = 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'] # Output file base name for HTML help builder. htmlhelp_basename = 'pytest-djangodoc' pytest-django-3.1.2/docs/configuring_django.rst000066400000000000000000000037711301551737600216430ustar00rootroot00000000000000.. _configuring_django_settings: Configuring Django settings =========================== There are a couple of different ways Django settings can be provided for the tests. The environment variable ``DJANGO_SETTINGS_MODULE`` --------------------------------------------------- Running the tests with DJANGO_SETTINGS_MODULE defined will find the Django settings the same way Django does by default. Example:: $ export DJANGO_SETTINGS_MODULE=test_settings $ pytest or:: $ DJANGO_SETTINGS_MODULE=test_settings pytest Command line option ``--ds=SETTINGS`` ------------------------------------- Example:: $ pytest --ds=test_settings pytest.ini settings ------------------- Example contents of pytest.ini:: [pytest] DJANGO_SETTINGS_MODULE = test_settings Order of choosing settings -------------------------- When the command option `--ds`, the environment variable and the pytest.ini configuration is used at the same time, pytest-django will prefer using settings from the command line option `--ds`, then the environment variable and last the pytest.ini. You can use `addopts = --ds=yourtestsettings` in your pytest configuration to automatically add the `--ds` option. Using django-configurations --------------------------- There is support for using `django-configurations `_. To do so configure the settings class using an environment variable, the --dc flag, or pytest.ini DJANGO_CONFIGURATION. Environment Variable:: $ export DJANGO_CONFIGURATION=MySettings $ pytest Command Line Option:: $ pytest --dc=MySettings INI File Contents:: [pytest] DJANGO_CONFIGURATION=MySettings Using ``django.conf.settings.configure()`` ------------------------------------------ Django settings can be set up by calling ``django.conf.settings.configure()``. This can be done from your project's ``conftest.py`` file:: from django.conf import settings def pytest_configure(): settings.configure(DATABASES=...) pytest-django-3.1.2/docs/contributing.rst000066400000000000000000000212211301551737600205040ustar00rootroot00000000000000############################# Contributing to pytest-django ############################# Like every open-source project, pytest-django is always looking for motivated individuals to contribute to its source code. However, to ensure the highest code quality and keep the repository nice and tidy, everybody has to follow a few rules (nothing major, I promise :) ) ********* Community ********* The fastest way to get feedback on contributions/bugs is usually to open an issue in the `issue tracker`_. Discussions also happen via IRC in #pylib on irc.freenode.org. You may also be interested in following `@andreaspelme`_ on Twitter. ************* In a nutshell ************* Here's what the contribution process looks like, in a bullet-points fashion: #. pytest-django is hosted on `GitHub`_, at https://github.com/pytest-dev/pytest-django #. The best method to contribute back is to create an account there and fork the project. You can use this fork as if it was your own project, and should push your changes to it. #. When you feel your code is good enough for inclusion, "send us a `pull request`_", by using the nice GitHub web interface. ***************** Contributing Code ***************** Getting the source code ======================= - Code will be reviewed and tested by at least one core developer, preferably by several. Other community members are welcome to give feedback. - Code *must* be tested. Your pull request should include unit-tests (that cover the piece of code you're submitting, obviously). - Documentation should reflect your changes if relevant. There is nothing worse than invalid documentation. - Usually, if unit tests are written, pass, and your change is relevant, then your pull request will be merged. Since we're hosted on GitHub, pytest-django uses `git`_ as a version control system. The `GitHub help`_ is very well written and will get you started on using git and GitHub in a jiffy. It is an invaluable resource for newbies and oldtimers alike. Syntax and conventions ====================== We try to conform to `PEP8`_ as much as possible. A few highlights: - Indentation should be exactly 4 spaces. Not 2, not 6, not 8. **4**. Also, tabs are evil. - We try (loosely) to keep the line length at 79 characters. Generally the rule is "it should look good in a terminal-based editor" (eg vim), but we try not be [Godwin's law] about it. Process ======= This is how you fix a bug or add a feature: #. `fork`_ the repository on GitHub. #. Checkout your fork. #. Hack hack hack, test test test, commit commit commit, test again. #. Push to your fork. #. Open a pull request. Tests ===== Having a wide and comprehensive library of unit-tests and integration tests is of exceeding importance. Contributing tests is widely regarded as a very prestigious contribution (you're making everybody's future work much easier by doing so). Good karma for you. Cookie points. Maybe even a beer if we meet in person :) Generally tests should be: - Unitary (as much as possible). I.E. should test as much as possible only on one function/method/class. That's the very definition of unit tests. Integration tests are also interesting obviously, but require more time to maintain since they have a higher probability of breaking. - Short running. No hard numbers here, but if your one test doubles the time it takes for everybody to run them, it's probably an indication that you're doing it wrong. In a similar way to code, pull requests will be reviewed before pulling (obviously), and we encourage discussion via code review (everybody learns something this way) or in the IRC channel. Running the tests ----------------- There is a Makefile in the repository which aids in setting up a virtualenv and running the tests:: $ make test You can manually create the virtualenv using:: $ make testenv This will install a virtualenv with pytest and the latest stable version of Django. The virtualenv can then be activated with:: $ source bin/activate Then, simply invoke pytest to run the test suite:: $ pytest --ds=tests.settings_sqlite tox can be used to run the test suite under different configurations by invoking:: $ tox There is a huge number of unique test configurations (98 at the time of writing), running them all will take a long time. All valid configurations can be found in `tox.ini`. To test against a few of them, invoke tox with the `-e` flag:: $ tox -e python3.3-1.7-postgres,python2.7-1.9-sqlite This will run the tests on Python 3.3/Django 1.7/PostgeSQL and Python 2.7/Django 1.9/SQLite. Measuring test coverage ----------------------- Some of the tests are executed in subprocesses. Because of that regular coverage measurements (using pytest-cov plugin) are not reliable. If you want to measure coverage you'll need to create .pth file as described in `subprocess section of coverage documentation`_. If you're using ``setup.py develop`` you should uninstall pytest_django (using pip) for the time of measuring coverage. You'll also need mysql and postgres databases. There are predefined settings for each database in the tests directory. You may want to modify these files but please don't include them in your pull requests. After this short initial setup you're ready to run tests:: $ COVERAGE_PROCESS_START=`pwd`/.coveragerc COVERAGE_FILE=`pwd`/.coverage PYTHONPATH=`pwd` pytest --ds=tests.postgres_settings You should repeat the above step for sqlite and mysql before the next step. This step will create a lot of ``.coverage`` files with additional suffixes for every process. The final step is to combine all the files created by different processes and generate the html coverage report:: $ coverage combine $ coverage html Your coverage report is now ready in the ``htmlcov`` directory. Continuous integration ---------------------- `Travis`_ is used to automatically run all tests against all supported versions of Python, Django and different database backends. The `pytest-django Travis`_ page shows the latest test run. Travis will automatically pick up pull requests, test them and report the result directly in the pull request. ************************** Contributing Documentation ************************** Perhaps considered "boring" by hard-core coders, documentation is sometimes even more important than code! This is what brings fresh blood to a project, and serves as a reference for oldtimers. On top of this, documentation is the one area where less technical people can help most - you just need to write a semi-decent English. People need to understand you. We don't care about style or correctness. Documentation should be: - We use `Sphinx`_/`restructuredText`_. So obviously this is the format you should use :) File extensions should be .rst. - Written in English. We can discuss how it would bring more people to the project to have a Klingon translation or anything, but that's a problem we will ask ourselves when we already have a good documentation in English. - Accessible. You should assume the reader to be moderately familiar with Python and Django, but not anything else. Link to documentation of libraries you use, for example, even if they are "obvious" to you (South is the first example that comes to mind - it's obvious to any Django programmer, but not to any newbie at all). A brief description of what it does is also welcome. Pulling of documentation is pretty fast and painless. Usually somebody goes over your text and merges it, since there are no "breaks" and that GitHub parses rst files automagically it's really convenient to work with. Also, contributing to the documentation will earn you great respect from the core developers. You get good karma just like a test contributor, but you get double cookie points. Seriously. You rock. .. note:: This very document is based on the contributing docs of the `django CMS`_ project. Many thanks for allowing us to steal it! .. _fork: https://github.com/pytest-dev/pytest-django .. _issue tracker: https://github.com/pytest-dev/pytest-django/issues .. _Sphinx: http://sphinx.pocoo.org/ .. _PEP8: http://www.python.org/dev/peps/pep-0008/ .. _GitHub : http://www.github.com .. _GitHub help : http://help.github.com .. _freenode : http://freenode.net/ .. _@andreaspelme : https://twitter.com/andreaspelme .. _pull request : http://help.github.com/send-pull-requests/ .. _git : http://git-scm.com/ .. _restructuredText: http://docutils.sourceforge.net/docs/ref/rst/introduction.html .. _django CMS: https://www.django-cms.org/ .. _Travis: https://travis-ci.org/ .. _pytest-django Travis: https://travis-ci.org/pytest-dev/pytest-django .. _`subprocess section of coverage documentation`: http://nedbatchelder.com/code/coverage/subprocess.html pytest-django-3.1.2/docs/database.rst000066400000000000000000000360761301551737600175570ustar00rootroot00000000000000Database creation/re-use ======================== ``pytest-django`` takes a conservative approach to enabling database access. By default your tests will fail if they try to access the database. Only if you explicitly request database access will this be allowed. This encourages you to keep database-needing tests to a minimum which is a best practice since next-to-no business logic should be requiring the database. Moreover it makes it very clear what code uses the database and catches any mistakes. Enabling database access in tests --------------------------------- You can use `pytest marks `_ to tell ``pytest-django`` your test needs database access:: import pytest @pytest.mark.django_db def test_my_user(): me = User.objects.get(username='me') assert me.is_superuser It is also possible to mark all tests in a class or module at once. This demonstrates all the ways of marking, even though they overlap. Just one of these marks would have been sufficient. See the `pytest documentation `_ for detail:: import pytest pytestmark = pytest.mark.django_db @pytest.mark.django_db class TestUsers: pytestmark = pytest.mark.django_db def test_my_user(self): me = User.objects.get(username='me') assert me.is_superuser By default ``pytest-django`` will set up the Django databases the first time a test needs them. Once setup the database is cached for used for all subsequent tests and rolls back transactions to isolate tests from each other. This is the same way the standard Django `TestCase `_ uses the database. However ``pytest-django`` also caters for transaction test cases and allows you to keep the test databases configured across different test runs. Testing transactions -------------------- Django itself has the ``TransactionTestCase`` which allows you to test transactions and will flush the database between tests to isolate them. The downside of this is that these tests are much slower to set up due to the required flushing of the database. ``pytest-django`` also supports this style of tests, which you can select using an argument to the ``django_db`` mark:: @pytest.mark.django_db(transaction=True) def test_spam(): pass # test relying on transactions Tests requiring multiple databases ---------------------------------- Currently ``pytest-django`` does not specifically support Django's multi-database support. You can however use normal Django ``TestCase`` instances to use it's `multi_db `_ support. If you have any ideas about the best API to support multiple databases directly in ``pytest-django`` please get in touch, we are interested in eventually supporting this but unsure about simply following Django's approach. ``--reuse-db`` - reuse the testing database between test runs -------------------------------------------------------------- Using ``--reuse-db`` will create the test database in the same way as ``manage.py test`` usually does. However, after the test run, the test database will not be removed. The next time a test run is started with ``--reuse-db``, the database will instantly be re used. This will allow much faster startup time for tests. This can be especially useful when running a few tests, when there are a lot of database tables to set up. ``--reuse-db`` will not pick up schema changes between test runs. You must run the tests with ``--reuse-db --create-db`` to re-create the database according to the new schema. Running without ``--reuse-db`` is also possible, since the database will automatically be re-created. ``--create-db`` - force re creation of the test database -------------------------------------------------------- When used with ``--reuse-db``, this option will re-create the database, regardless of whether it exists or not. Example work flow with ``--reuse-db`` and ``--create-db``. ----------------------------------------------------------- A good way to use ``--reuse-db`` and ``--create-db`` can be: * Put ``--reuse-db`` in your default options (in your project's ``pytest.ini`` file):: [pytest] addopts = --reuse-db * Just run tests with ``pytest``, on the first run the test database will be created. The next test run it will be reused. * When you alter your database schema, run ``pytest --create-db``, to force re-creation of the test database. ``--nomigrations`` - Disable Django 1.7+ migrations -------------------------------------------------------------- Using ``--nomigrations`` will disable Django migrations and create the database by inspecting all models. It may be faster when there are several migrations to run in the database setup. You can use ``--migrations`` to force running migrations in case ``--nomigrations`` is used, e.g. in ``setup.cfg``. .. _advanced-database-configuration: Advanced database configuration ------------------------------- pytest-django provides options to customize the way database is configured. The default database construction mostly follows Django's own test runner. You can however influence all parts of the database setup process to make it fit in projects with special requirements. This section assumes some familiary with the Django test runner, Django database creation and pytest fixtures. Fixtures ######## There are some fixtures which will let you change the way the database is configured in your own project. These fixtures can be overridden in your own project by specifying a fixture with the same name and scope in ``conftest.py``. .. admonition:: Use the pytest-django source code The default implementation of these fixtures can be found in `fixtures.py `_. The code is relatively short and straightforward and can provide a starting point when you need to customize database setup in your own project. django_db_setup """"""""""""""" .. fixture:: django_db_setup This is the top-level fixture that ensures that the test databases are created and available. This fixture is session scoped (it will be run once per test session) and is responsible for making sure the test database is available for tests that need it. The default implementation creates the test database by applying migrations and removes databases after the test run. You can override this fixture in your own ``conftest.py`` to customize how test databases are constructed. django_db_modify_db_settings """""""""""""""""""""""""""" .. fixture:: django_db_modify_db_settings This fixture allows modifying `django.conf.settings.DATABASES` just before the databases are configured. If you need to customize the location of your test database, this is the fixture you want to override. The default implementation of this fixture requests the :fixture:`django_db_modify_db_settings_xdist_suffix` to provide compatibility with pytest-xdist. This fixture is by default requested from :fixture:`django_db_setup`. django_db_modify_db_settings_xdist_suffix """"""""""""""""""""""""""""""""""""""""" .. fixture:: django_db_modify_db_settings_xdist_suffix Requesting this fixture will add a suffix to the database name when the tests are run via pytest-xdist. This fixture is by default requsted from :fixture:`django_db_modify_db_settings_xdist_suffix`. django_db_use_migrations """""""""""""""""""""""" .. fixture:: django_db_use_migrations Returns whether or not to use migrations to create the test databases. The default implementation returns the value of the ``--migrations``/``--nomigrations`` command line options. This fixture is by default requested from :fixture:`django_db_setup`. django_db_keepdb """""""""""""""" .. fixture:: django_db_keepdb Returns whether or not to re-use an existing database and to keep it after the test run. The default implementation handles the ``--reuse-db`` and ``--create-db`` command line options. This fixture is by default requested from :fixture:`django_db_setup`. django_db_blocker """"""""""""""""" .. fixture:: django_db_blocker .. warning:: It does not manage transactions and changes made to the database will not be automatically restored. Using the :func:`pytest.mark.django_db` marker or :fixture:`db` fixture, which wraps database changes in a transaction and restores the state is generally the thing you want in tests. This marker can be used when you are trying to influence the way the database is configured. Database access is by default not allowed. ``django_db_blocker`` is the object which can allow specific code paths to have access to the database. This fixture is used internally to implement the ``db`` fixture. :fixture:`django_db_blocker` can be used as a context manager to enable database access for the specified block:: @pytest.fixture def myfixture(django_db_blocker): with django_db_blocker.unblock(): ... # modify something in the database You can also manage the access manually via these methods: .. py:method:: django_db_blocker.unblock() Enable database access. Should be followed by a call to :func:`~django_db_blocker.restore`. .. py:method:: django_db_blocker.block() Disable database access. Should be followed by a call to :func:`~django_db_blocker.restore`. .. py:function:: django_db_blocker.restore() Restore the previous state of the database blocking. Examples ######## Using a template database for tests """"""""""""""""""""""""""""""""""" This example shows how a pre-created PostgreSQL source database can be copied and used for tests. Put this into ``conftest.py``:: import pytest from django.db import connections import psycopg2 from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT def run_sql(sql): conn = psycopg2.connect(database='postgres') conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cur = conn.cursor() cur.execute(sql) conn.close() @pytest.yield_fixture(scope='session') def django_db_setup(): from django.conf import settings settings.DATABASES['default']['NAME'] = 'the_copied_db' run_sql('DROP DATABASE IF EXISTS the_copied_db') run_sql('CREATE DATABASE the_copied_db TEMPLATE the_source_db') yield for connection in connections.all(): connection.close() run_sql('DROP DATABASE the_copied_db') Using an existing, external database for tests """""""""""""""""""""""""""""""""""""""""""""" This example shows how you can connect to an existing database and use it for your tests. This example is trivial, you just need to disable all of pytest-django and Django's test database creation and point to the existing database. This is achieved by simply implementing a no-op :fixture:`django_db_setup` fixture. Put this into ``conftest.py``:: import pytest @pytest.fixture(scope='session') def django_db_setup(): settings.DATABASES['default'] = { 'ENGINE': 'django.db.backends.mysql', 'HOST': 'db.example.com', 'NAME': 'external_db', } Populate the database with initial test data """""""""""""""""""""""""""""""""""""""""""" This example shows how you can populate the test database with test data. The test data will be saved in the database, i.e. it will not just be part of a transactions. This example uses Django's fixture loading mechanism, but it can be replaced with any way of loading data into the database. Notice that :fixture:`django_db_setup` is in the argument list. This may look odd at first, but it will make sure that the sure that the original pytest-django fixture is used to create the test database. When ``call_command`` is invoked, the test database is already prepared and configured. Put this in ``conftest.py``:: import pytest from django.core.management import call_command @pytest.fixture(scope='session') def django_db_setup(django_db_setup, django_db_blocker): with django_db_blocker.unblock(): call_command('loaddata', 'your_data_fixture.json') Use the same database for all xdist processes """"""""""""""""""""""""""""""""""""""""""""" By default, each xdist process gets its own database to run tests on. This is needed to have transactional tests that does not interfere with eachother. If you instead want your tests to use the same database, override the :fixture:`django_db_modify_db_settings` to not do anything. Put this in ``conftest.py``:: import pytest @pytest.fixture(scope='session') def django_db_modify_db_settings(): pass Randomize database sequences """""""""""""""""""""""""""" You can customize the test database after it has been created by extending the :fixture:`django_db_setup` fixture. This example shows how to give a PostgreSQL sequence a random starting value. This can be used to detect and prevent primary key id's from being hard-coded in tests. Put this in ``conftest.py``:: import random import pytest from django.db import connection @pytest.fixture(scope='session') def django_db_setup(django_db_setup, django_db_blocker): with django_db_blocker.unblock(): cur = connection.cursor() cur.execute('ALTER SEQUENCE app_model_id_seq RESTART WITH %s;', [random.randint(10000, 20000)]) Create the test database from a custom SQL script """"""""""""""""""""""""""""""""""""""""""""""""" You can replace the :fixture:`django_db_setup` fixture and run any code in its place. This includes creating your database by hand by running a SQL script directly. This example shows how sqlite3's executescript method. In more a more general use cases you probably want to load the SQL statements from a file or invoke the ``psql`` or the ``mysql`` command line tool. Put this in ``conftest.py``:: import pytest from django.db import connection @pytest.fixture(scope='session') def django_db_setup(django_db_blocker): with django_db_blocker.unblock(): with connection.cursor() as c: c.executescript(''' DROP TABLE IF EXISTS theapp_item; CREATE TABLE theapp_item (id, name); INSERT INTO theapp_item (name) VALUES ('created from a sql script'); ''') Use a read only database """""""""""""""""""""""" You can replace the ordinary `django_db_setup` to completely avoid database creation/migrations. If you have no need for rollbacks or truncating tables, you can simply avoid blocking the database and use it directly. When using this method you must ensure that your tests do not change the database state. Put this in ``conftest.py``:: import pytest @pytest.fixture(scope='session') def django_db_setup(): """Avoid creating/setting up the test database""" pass @pytest.fixture def db_access_without_rollback_and_truncate(request, django_db_setup, django_db_blocker): django_db_blocker.unblock() request.addfinalizer(django_db_blocker.restore) pytest-django-3.1.2/docs/faq.rst000066400000000000000000000110101301551737600165370ustar00rootroot00000000000000FAQ === .. _faq-import-error: I see an error saying "could not import myproject.settings" ----------------------------------------------------------- pytest-django tries to automatically add your project to the Python path by looking for a ``manage.py`` file and adding its path to the Python path. If this for some reason fails for you, you have to manage your Python paths explicitly. See the documentation on :ref:`managing_the_python_path_explicitly` for more information. How can I make sure that all my tests run with a specific locale? ----------------------------------------------------------------- Create a `pytest fixture `_ that is automatically run before each test case. To run all tests with the english locale, put the following code in your project's `conftest.py `_ file:: from django.utils.translation import activate @pytest.fixture(autouse=True) def set_default_language(): activate('en') .. _faq-tests-not-being-picked-up: My tests are not being found. Why not? ------------------------------------------------------------------------------------- By default, pytest looks for tests in files named ``test_*.py`` (note that this is not the same as ``test*.py``). If you have your tests in files with other names, they will not be collected. It is common to put tests under ``app_directory/tests/views.py``. To find those tests, create a ``pytest.ini`` file in your project root with the contents:: [pytest] python_files=*.py When debugging test collection problems, the ``--collectonly`` flag and ``-rs`` (report skipped tests) can be helpful. Does pytest-django work with the pytest-xdist plugin? ----------------------------------------------------- Yes. pytest-django supports running tests in parallel with pytest-xdist. Each process created by xdist gets its own separate database that is used for the tests. This ensures that each test can run independently, regardless of whether transactions are tested or not. .. _faq-getting-help: How can I use ``manage.py test`` with pytest-django? ---------------------------------------------------- pytest-django is designed to work with the ``pytest`` command, but if you really need integration with ``manage.py test``, you can create a simple test runner like this:: class PytestTestRunner(object): """Runs pytest to discover and run tests.""" def __init__(self, verbosity=1, failfast=False, keepdb=False, **kwargs): self.verbosity = verbosity self.failfast = failfast self.keepdb = keepdb def run_tests(self, test_labels): """Run pytest and return the exitcode. It translates some of Django's test command option to pytest's. """ import pytest argv = [] if self.verbosity == 0: argv.append('--quiet') if self.verbosity == 2: argv.append('--verbose') if self.verbosity == 3: argv.append('-vv') if self.failfast: argv.append('--exitfirst') if self.keepdb: argv.append('--reuse-db') argv.extend(test_labels) return pytest.main(argv) Add the path to this class in your Django settings:: TEST_RUNNER = 'my_project.runner.PytestTestRunner' Usage:: ./manage.py test -- **Note**: the pytest-django command line options ``--ds`` and ``--dc`` are not compatible with this approach, you need to use the standard Django methods of setting the ``DJANGO_SETTINGS_MODULE``/``DJANGO_CONFIGURATION`` environmental variables or the ``--settings`` command line option. How can I give database access to all my tests without the `django_db` marker? ------------------------------------------------------------------------------ Create an autouse fixture and put it in `conftest.py` in your project root:: @pytest.fixture(autouse=True) def enable_db_access_for_all_tests(db): pass How/where can I get help with pytest/pytest-django? --------------------------------------------------- Usage questions can be asked on StackOverflow with the `pytest tag `_. If you think you've found a bug or something that is wrong in the documentation, feel free to `open an issue on the Github project for pytest-django `_. Direct help can be found in the #pylib IRC channel on irc.freenode.org. pytest-django-3.1.2/docs/helpers.rst000066400000000000000000000173611301551737600174510ustar00rootroot00000000000000.. _helpers: Django helpers ============== Markers ------- ``pytest-django`` registers and uses markers. See the pytest documentation_ on what marks are and for notes on using_ them. .. _documentation: http://pytest.org/latest/mark.html .. _using: http://pytest.org/latest/example/markers.html#marking-whole-classes-or-modules ``pytest.mark.django_db(transaction=False)`` - request database access ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. :py:function:: pytest.mark.django_db: This is used to mark a test function as requiring the database. It will ensure the database is setup correctly for the test. Each test will run in its own transaction which will be rolled back at the end of the test. This behavior is the same as Django's standard `django.test.TestCase`_ class. In order for a test to have access to the database it must either be marked using the ``django_db`` mark or request one of the ``db`` or ``transactional_db`` fixtures. Otherwise the test will fail when trying to access the database. :type transaction: bool :param transaction: The ``transaction`` argument will allow the test to use real transactions. With ``transaction=False`` (the default when not specified), transaction operations are noops during the test. This is the same behavior that `django.test.TestCase`_ uses. When ``transaction=True``, the behavior will be the same as `django.test.TransactionTestCase`_ .. note:: If you want access to the Django database *inside a fixture* this marker will not help even if the function requesting your fixture has this marker applied. To access the database in a fixture, the fixture itself will have to request the ``db`` or ``transactional_db`` fixture. See below for a description of them. .. note:: Automatic usage with ``django.test.TestCase``. Test classes that subclass `django.test.TestCase`_ will have access to the database always to make them compatible with existing Django tests. Test classes that subclass Python's ``unittest.TestCase`` need to have the marker applied in order to access the database. .. _django.test.TestCase: https://docs.djangoproject.com/en/dev/topics/testing/overview/#testcase .. _django.test.TransactionTestCase: https://docs.djangoproject.com/en/dev/topics/testing/overview/#transactiontestcase ``pytest.mark.urls`` - override the urlconf ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. py:function:: pytest.mark.urls(urls) Specify a different ``settings.ROOT_URLCONF`` module for the marked tests. :type urls: string :param urls: The urlconf module to use for the test, e.g. ``myapp.test_urls``. This is similar to Django's ``TestCase.urls`` attribute. Example usage:: @pytest.mark.urls('myapp.test_urls') def test_something(client): assert 'Success!' in client.get('/some_url_defined_in_test_urls/') ``pytest.mark.ignore_template_errors`` - ignore invalid template variables ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. py:function:: pytest.mark.ignore_template_errors If you run pytest using the ``--fail-on-template-vars`` option, tests will fail should your templates contain any invalid variables. This marker will disable this feature by setting ``settings.TEMPLATE_STRING_IF_INVALID=None`` or the ``string_if_invalid`` template option in Django>=1.7 Example usage:: @pytest.mark.ignore_template_errors def test_something(client): client('some-url-with-invalid-template-vars') Fixtures -------- pytest-django provides some pytest fixtures to provide dependencies for tests. More information on fixtures is available in the `pytest documentation `_. ``rf`` - ``RequestFactory`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~ An instance of a `django.test.RequestFactory`_ .. _django.test.RequestFactory: https://docs.djangoproject.com/en/dev/topics/testing/advanced/#django.test.RequestFactory Example """"""" :: from myapp.views import my_view def test_details(rf): request = rf.get('/customer/details') response = my_view(request) assert response.status_code == 200 ``client`` - ``django.test.Client`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ An instance of a `django.test.Client`_ .. _django.test.Client: https://docs.djangoproject.com/en/dev/topics/testing/tools/#the-test-client Example """"""" :: def test_with_client(client): response = client.get('/') assert response.content == 'Foobar' ``admin_client`` - ``django.test.Client`` logged in as admin ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ An instance of a `django.test.Client`_, that is logged in as an admin user. Example """"""" :: def test_an_admin_view(admin_client): response = admin_client.get('/admin/') assert response.status_code == 200 As an extra bonus this will automatically mark the database using the ``django_db`` mark. ``admin_user`` - a admin user (superuser) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ An instance of a superuser, with username "admin" and password "password" (in case there is no "admin" user yet). As an extra bonus this will automatically mark the database using the ``django_db`` mark. ``django_user_model`` ~~~~~~~~~~~~~~~~~~~~~ The user model used by Django. This handles different versions of Django. ``django_username_field`` ~~~~~~~~~~~~~~~~~~~~~~~~~ The field name used for the username on the user model. ``db`` ~~~~~~~ .. fixture:: db This fixture will ensure the Django database is set up. This only required for fixtures which want to use the database themselves. A test function should normally use the :py:func:`~pytest.mark.django_db` mark to signal it needs the database. ``transactional_db`` ~~~~~~~~~~~~~~~~~~~~ This fixture can be used to request access to the database including transaction support. This is only required for fixtures which need database access themselves. A test function would normally use the :py:func:`~pytest.mark.django_db` mark to signal it needs the database. ``live_server`` ~~~~~~~~~~~~~~~ This fixture runs a live Django server in a background thread. The server's URL can be retrieved using the ``live_server.url`` attribute or by requesting it's string value: ``unicode(live_server)``. You can also directly concatenate a string to form a URL: ``live_server + '/foo``. ``settings`` ~~~~~~~~~~~~ This fixture will provide a handle on the Django settings module, and automatically revert any changes made to the settings (modifications, additions and deletions). Example """"""" :: def test_with_specific_settings(settings): settings.USE_TZ = True assert settings.USE_TZ ``mailoutbox`` ~~~~~~~~~~~~~~~~~~~~~~~~~ A clean mail outbox where django emails are being sent. Example """"""" :: from django.core import mail def test_mail(mailoutbox): mail.send_mail('subject', 'body', 'from@example.com', ['to@example.com']) assert len(mailoutbox) == 1 m = mailoutbox[0] assert m.subject == 'subject' assert m.body == 'body' assert m.from_email == 'from@example.com' assert list(m.to) == ['to@example.com'] Environment autouse fixtures ---------------------------- pytest-django provides some pytest fixtures that are of autouse nature. They provide functionality to assure a clean environment during tests. Clearing of site cache ~~~~~~~~~~~~~~~~~~~~~~ If ``django.contrib.sites`` is in your INSTALLED_APPS, Site cache will be cleared for each test to avoid hitting the cache and cause wrong Site object to be returned by ``Site.objects.get_current()``. Clearing of mail.outbox ~~~~~~~~~~~~~~~~~~~~~~~ ``mail.outbox`` will be cleared for each pytest, to give tests a empty mailbox. It is however more pytestic to use the ``mailoutbox`` fixture to access ``mail.outbox``. pytest-django-3.1.2/docs/index.rst000066400000000000000000000035071301551737600171130ustar00rootroot00000000000000Welcome to pytest-django's documentation! ========================================= pytest-django is a plugin for `pytest `_ that provides a set of useful tools for testing `Django `_ applications and projects. .. toctree:: :maxdepth: 3 tutorial configuring_django managing_python_path usage database helpers faq contributing changelog Why would I use this instead of Django's manage.py test command? ================================================================ Running the test suite with pytest offers some features that are not present in Django's standard test mechanism: * Less boilerplate: no need to import unittest, create a subclass with methods. Just write tests as regular functions. * `Manage test dependencies with fixtures `_ * Database re-use: no need to re-create the test database for every test run. * Run tests in multiple processes for increased speed * There are a lot of other nice plugins available for pytest. * Easy switching: Existing unittest-style tests will still work without any modifications. See the `pytest documentation `_ for more information on pytest. Quick Start =========== 1. ``pip install pytest-django`` 2. Make sure ``DJANGO_SETTINGS_MODULE`` is defined and and run tests with the ``pytest`` command. 3. (Optionally) If you put your tests under a tests directory (the standard Django application layout), and your files are not named ``test_FOO.py``, see the FAQ :ref:`faq-tests-not-being-picked-up`. Bugs? Feature suggestions? ============================ Report issues and feature requests at the `github issue tracker `_. Indices and tables ================== * :ref:`genindex` * :ref:`modindex` pytest-django-3.1.2/docs/make.bat000066400000000000000000000117661301551737600166650ustar00rootroot00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\pytest-django.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\pytest-django.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) :end pytest-django-3.1.2/docs/managing_python_path.rst000066400000000000000000000055771301551737600222130ustar00rootroot00000000000000.. _managing_python_path: Managing the Python path ======================== pytest needs to be able to import the code in your project. Normally, when interacting with Django code, the interaction happens via ``manage.py``, which will implicilty add that directory to the Python path. However, when Python is started via the ``pytest`` command, some extra care is needed to have the Python path setup properly. There are two ways to handle this problem, described below. Automatic looking for of Django projects ---------------------------------------- By default, pytest-django tries to find Django projects by automatically looking for the project's ``manage.py`` file and adding its directory to the Python path. Looking for the ``manage.py`` file uses the same algorithm as pytest uses to find ``pytest.ini``, ``tox.ini`` and ``setup.cfg``: Each test root directories parents will be searched for ``manage.py`` files, and it will stop when the first file is found. If you have a custom project setup, have none or multiple ``manage.py`` files in your project, the automatic detection may not be correct. See :ref:`managing_the_python_path_explicilty` for more details on how to configure your environment in that case. .. _managing_the_python_path_explicitly: Managing the Python path explicitly ----------------------------------- First, disable the automatic Django project finder. Add this to ``pytest.ini``, ``setup.cfg`` or ``tox.ini``:: [pytest] django_find_project = false Next, you need to make sure that your project code is available on the Python path. There are multiple ways to achieve this: Managing your project with virtualenv, pip and editable mode ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The easiest way to have your code available on the Python path when using virtualenv and pip is to have a setup.py file and install your project in editable mode when developing. If you don't already have a setup.py file, creating a setup.py file with this content will get you started:: import setuptools setuptools.setup(name='myproj', version='1.0') This ``setup.py`` file is not sufficient to distribute your package to PyPI or more general packaging, but it should help you get started. Please refer to the `Python Packaging User Guide `_ for more information on packaging Python applications.` To install the project afterwards:: pip install --editable . Your code should then be importable from any Python application. You can also add this directly to your project's requirements.txt file like this:: # requirements.txt -e . django>=1.7 pytest-django Using pytest-pythonpath ~~~~~~~~~~~~~~~~~~~~~~~ You can also use the `pytest-pythonpath `_ plugin to explicitly add paths to the Python path. pytest-django-3.1.2/docs/tutorial.rst000066400000000000000000000057031301551737600176470ustar00rootroot00000000000000Getting started with pytest and pytest-django ============================================= Introduction ------------ pytest and pytest-django are compatible with standard Django test suites and Nose test suites. They should be able to pick up and run existing tests without any or little configuration. This section describes how to get started quickly. Talks, articles and blog posts ------------------------------ * Talk from DjangoCon Europe 2014: `pytest: helps you write better Django apps, by Andreas Pelme `_ * Talk from EuroPython 2013: `Testing Django application with pytest, by Andreas Pelme `_ * Three part blog post tutorial (part 3 mentions Django integration): `pytest: no-boilerplate testing, by Daniel Greenfeld `_ * Blog post: `Django Projects to Django Apps: Converting the Unit Tests, by John Costa `_. For general information and tutorials on pytest, see the `pytest tutorial page `_. Step 1: Installation -------------------- pytest-django can be obtained directly from `PyPI `_, and can be installed with ``pip``:: pip install pytest-django Installing pytest-django will also automatically install the latest version of pytest. ``pytest-django`` uses ``pytest``'s plugin system and can be used right away after installation, there is nothing more to configure. Step 2: Point pytest to your Django settings -------------------------------------------- You need to tell pytest which Django settings that should be used for test runs. The easiest way to achieve this is to create a pytest configuration file with this information. Create a file called ``pytest.ini`` in your project root directory that contains:: [pytest] DJANGO_SETTINGS_MODULE=yourproject.settings You can also specify your Django settings by setting the ``DJANGO_SETTINGS_MODULE`` environment variable or specifying the ``--ds=yourproject.settings`` command line flag when running the tests. See the full documentation on :ref:`configuring_django_settings`. Step 3: Run your test suite --------------------------- Tests are invoked directly with the ``pytest`` command, instead of ``manage.py test``, that you might be used to:: pytest Do you have problems with pytest not finding your code? See the FAQ :ref:`faq-import-error`. Next steps ---------- The :ref:`usage` section describes more ways to interact with your test suites. pytest-django also provides some :ref:`helpers` to make it easier to write Django tests. Consult the `pytest documentation `_ for more information in pytest itself. Stuck? Need help? ----------------- No problem, see the FAQ on :ref:`faq-getting-help` for information on how to get help. pytest-django-3.1.2/docs/usage.rst000066400000000000000000000035621301551737600171110ustar00rootroot00000000000000.. _usage: Usage and invocations ===================== Basic usage ----------- When using pytest-django, django-admin.py or manage.py is not used to run tests. This makes it possible to invoke pytest and other plugins with all its different options directly. Running a test suite is done by invoking the pytest command directly:: pytest Specific test files or directories can be selected by specifying the test file names directly on the command line:: pytest test_something.py a_directory See the `pytest documentation on Usage and invocations `_ for more help on available parameters. Additional command line options ------------------------------- ``--fail-on-template-vars`` - fail for invalid variables in templates ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Fail tests that render templates which make use of invalid template variables. Running tests in parallel with pytest-xdist ------------------------------------------- pytest-django supports running tests on multiple processes to speed up test suite run time. This can lead to significant speed improvements on multi core/multi CPU machines. This requires the pytest-xdist plugin to be available, it can usually be installed with:: pip install pytest-xdist You can then run the tests by running:: pytest -n When tests are invoked with xdist, pytest-django will create a separate test database for each process. Each test database will be given a suffix (something like "gw0", "gw1") to map to a xdist process. If your database name is set to "foo", the test database with xdist will be "test_foo_gw0", "test_foo_gw1" etc. See the full documentation on `pytest-xdist `_ for more information. Among other features, pytest-xdist can distribute/coordinate test execution on remote machines. pytest-django-3.1.2/pytest_django/000077500000000000000000000000001301551737600171675ustar00rootroot00000000000000pytest-django-3.1.2/pytest_django/__init__.py000066400000000000000000000000001301551737600212660ustar00rootroot00000000000000pytest-django-3.1.2/pytest_django/compat.py000066400000000000000000000013271301551737600210270ustar00rootroot00000000000000# This file cannot be imported from until Django sets up try: # Django 1.11 from django.test.utils import setup_databases, teardown_databases # noqa except ImportError: # In Django prior to 1.11, teardown_databases is only available as a method on DiscoverRunner from django.test.runner import setup_databases, DiscoverRunner as _DiscoverRunner # noqa def teardown_databases(db_cfg, verbosity): (_DiscoverRunner(verbosity=verbosity, interactive=False) .teardown_databases(db_cfg)) try: from django.db.backends.base.base import BaseDatabaseWrapper # noqa except ImportError: # Django 1.7. from django.db.backends import BaseDatabaseWrapper # noqa pytest-django-3.1.2/pytest_django/db_reuse.py000066400000000000000000000045511301551737600213360ustar00rootroot00000000000000"""Functions to aid in creating, reusing and destroying Django test databases """ import os.path import sys import types def test_database_exists_from_previous_run(connection): # Try to open a cursor to the test database test_db_name = connection.creation._get_test_db_name() # When using a real SQLite backend (via TEST_NAME), check if the file # exists, because it gets created automatically. if connection.settings_dict['ENGINE'] == 'django.db.backends.sqlite3': if not os.path.exists(test_db_name): return False orig_db_name = connection.settings_dict['NAME'] connection.settings_dict['NAME'] = test_db_name # With SQLite memory databases the db never exists. if connection.settings_dict['NAME'] == ':memory:': return False try: connection.cursor() return True except Exception: # TODO: Be more discerning but still DB agnostic. return False finally: connection.close() connection.settings_dict['NAME'] = orig_db_name def _monkeypatch(obj, method_name, new_method): assert hasattr(obj, method_name), method_name if sys.version_info < (3, 0): wrapped_method = types.MethodType(new_method, obj, obj.__class__) else: wrapped_method = types.MethodType(new_method, obj) setattr(obj, method_name, wrapped_method) def create_test_db_with_reuse(self, verbosity=1, autoclobber=False, keepdb=False, serialize=False): """ This method is a monkey patched version of create_test_db that will not actually create a new database, but just reuse the existing. This is only used with Django < 1.8. """ test_database_name = self._get_test_db_name() self.connection.settings_dict['NAME'] = test_database_name if verbosity >= 1: test_db_repr = '' if verbosity >= 2: test_db_repr = " ('%s')" % test_database_name print("Re-using existing test database for alias '%s'%s..." % ( self.connection.alias, test_db_repr)) return test_database_name def monkey_patch_creation_for_db_reuse(): from django.db import connections for connection in connections.all(): if test_database_exists_from_previous_run(connection): _monkeypatch(connection.creation, 'create_test_db', create_test_db_with_reuse) pytest-django-3.1.2/pytest_django/django_compat.py000066400000000000000000000006411301551737600223470ustar00rootroot00000000000000# Note that all functions here assume django is available. So ensure # this is the case before you call them. def is_django_unittest(request_or_item): """Returns True if the request_or_item is a Django test case, otherwise False""" from django.test import SimpleTestCase cls = getattr(request_or_item, 'cls', None) if cls is None: return False return issubclass(cls, SimpleTestCase) pytest-django-3.1.2/pytest_django/fixtures.py000066400000000000000000000244151301551737600214200ustar00rootroot00000000000000"""All pytest-django fixtures""" from __future__ import with_statement import os import pytest from . import live_server_helper from .django_compat import is_django_unittest from .pytest_compat import getfixturevalue from .lazy_django import get_django_version, skip_if_no_django __all__ = ['django_db_setup', 'db', 'transactional_db', 'admin_user', 'django_user_model', 'django_username_field', 'client', 'admin_client', 'rf', 'settings', 'live_server', '_live_server_helper'] @pytest.fixture(scope='session') def django_db_modify_db_settings_xdist_suffix(request): skip_if_no_django() from django.conf import settings for db_settings in settings.DATABASES.values(): try: test_name = db_settings['TEST']['NAME'] except KeyError: test_name = None if not test_name: if db_settings['ENGINE'] == 'django.db.backends.sqlite3': return ':memory:' else: test_name = 'test_{}'.format(db_settings['NAME']) # Put a suffix like _gw0, _gw1 etc on xdist processes xdist_suffix = getattr(request.config, 'slaveinput', {}).get('slaveid') if test_name != ':memory:' and xdist_suffix is not None: test_name = '{}_{}'.format(test_name, xdist_suffix) db_settings.setdefault('TEST', {}) db_settings['TEST']['NAME'] = test_name @pytest.fixture(scope='session') def django_db_modify_db_settings(django_db_modify_db_settings_xdist_suffix): skip_if_no_django() @pytest.fixture(scope='session') def django_db_use_migrations(request): return not request.config.getvalue('nomigrations') @pytest.fixture(scope='session') def django_db_keepdb(request): return (request.config.getvalue('reuse_db') and not request.config.getvalue('create_db')) @pytest.fixture(scope='session') def django_db_setup( request, django_test_environment, django_db_blocker, django_db_use_migrations, django_db_keepdb, django_db_modify_db_settings, ): """Top level fixture to ensure test databases are available""" from .compat import setup_databases, teardown_databases setup_databases_args = {} if not django_db_use_migrations: _disable_native_migrations() if django_db_keepdb: if get_django_version() >= (1, 8): setup_databases_args['keepdb'] = True else: # Django 1.7 compatibility from .db_reuse import monkey_patch_creation_for_db_reuse with django_db_blocker.unblock(): monkey_patch_creation_for_db_reuse() with django_db_blocker.unblock(): db_cfg = setup_databases( verbosity=pytest.config.option.verbose, interactive=False, **setup_databases_args ) def teardown_database(): with django_db_blocker.unblock(): teardown_databases( db_cfg, verbosity=pytest.config.option.verbose, ) if not django_db_keepdb: request.addfinalizer(teardown_database) def _django_db_fixture_helper(transactional, request, django_db_blocker): if is_django_unittest(request): return if not transactional and 'live_server' in request.funcargnames: # Do nothing, we get called with transactional=True, too. return django_db_blocker.unblock() request.addfinalizer(django_db_blocker.restore) if transactional: from django.test import TransactionTestCase as django_case else: from django.test import TestCase as django_case test_case = django_case(methodName='__init__') test_case._pre_setup() request.addfinalizer(test_case._post_teardown) def _disable_native_migrations(): from django.conf import settings from .migrations import DisableMigrations settings.MIGRATION_MODULES = DisableMigrations() # ############### User visible fixtures ################ @pytest.fixture(scope='function') def db(request, django_db_setup, django_db_blocker): """Require a django test database This database will be setup with the default fixtures and will have the transaction management disabled. At the end of the test the outer transaction that wraps the test itself will be rolled back to undo any changes to the database (in case the backend supports transactions). This is more limited than the ``transactional_db`` resource but faster. If both this and ``transactional_db`` are requested then the database setup will behave as only ``transactional_db`` was requested. """ if 'transactional_db' in request.funcargnames \ or 'live_server' in request.funcargnames: getfixturevalue(request, 'transactional_db') else: _django_db_fixture_helper(False, request, django_db_blocker) @pytest.fixture(scope='function') def transactional_db(request, django_db_setup, django_db_blocker): """Require a django test database with transaction support This will re-initialise the django database for each test and is thus slower than the normal ``db`` fixture. If you want to use the database with transactions you must request this resource. If both this and ``db`` are requested then the database setup will behave as only ``transactional_db`` was requested. """ _django_db_fixture_helper(True, request, django_db_blocker) @pytest.fixture() def client(): """A Django test client instance.""" skip_if_no_django() from django.test.client import Client return Client() @pytest.fixture() def django_user_model(db): """The class of Django's user model.""" from django.contrib.auth import get_user_model return get_user_model() @pytest.fixture() def django_username_field(django_user_model): """The fieldname for the username used with Django's user model.""" return django_user_model.USERNAME_FIELD @pytest.fixture() def admin_user(db, django_user_model, django_username_field): """A Django admin user. This uses an existing user with username "admin", or creates a new one with password "password". """ UserModel = django_user_model username_field = django_username_field try: user = UserModel._default_manager.get(**{username_field: 'admin'}) except UserModel.DoesNotExist: extra_fields = {} if username_field != 'username': extra_fields[username_field] = 'admin' user = UserModel._default_manager.create_superuser( 'admin', 'admin@example.com', 'password', **extra_fields) return user @pytest.fixture() def admin_client(db, admin_user): """A Django test client logged in as an admin user.""" from django.test.client import Client client = Client() client.login(username=admin_user.username, password='password') return client @pytest.fixture() def rf(): """RequestFactory instance""" skip_if_no_django() from django.test.client import RequestFactory return RequestFactory() class SettingsWrapper(object): _to_restore = [] def __delattr__(self, attr): from django.test import override_settings override = override_settings() override.enable() from django.conf import settings delattr(settings, attr) self._to_restore.append(override) def __setattr__(self, attr, value): from django.test import override_settings override = override_settings(**{ attr: value }) override.enable() self._to_restore.append(override) def __getattr__(self, item): from django.conf import settings return getattr(settings, item) def finalize(self): for override in reversed(self._to_restore): override.disable() del self._to_restore[:] @pytest.yield_fixture() def settings(): """A Django settings object which restores changes after the testrun""" skip_if_no_django() wrapper = SettingsWrapper() yield wrapper wrapper.finalize() @pytest.fixture(scope='session') def live_server(request): """Run a live Django server in the background during tests The address the server is started from is taken from the --liveserver command line option or if this is not provided from the DJANGO_LIVE_TEST_SERVER_ADDRESS environment variable. If neither is provided ``localhost:8081,8100-8200`` is used. See the Django documentation for it's full syntax. NOTE: If the live server needs database access to handle a request your test will have to request database access. Furthermore when the tests want to see data added by the live-server (or the other way around) transactional database access will be needed as data inside a transaction is not shared between the live server and test code. Static assets will be automatically served when ``django.contrib.staticfiles`` is available in INSTALLED_APPS. """ skip_if_no_django() import django addr = (request.config.getvalue('liveserver') or os.getenv('DJANGO_LIVE_TEST_SERVER_ADDRESS')) if addr and django.VERSION >= (1, 11) and ':' in addr: request.config.warn('D001', 'Specifying a live server port is not supported ' 'in Django 1.11. This will be an error in a future ' 'pytest-django release.') if not addr: if django.VERSION < (1, 11): addr = 'localhost:8081,8100-8200' else: addr = 'localhost' server = live_server_helper.LiveServer(addr) request.addfinalizer(server.stop) return server @pytest.fixture(autouse=True, scope='function') def _live_server_helper(request): """Helper to make live_server work, internal to pytest-django. This helper will dynamically request the transactional_db fixture for a test which uses the live_server fixture. This allows the server and test to access the database without having to mark this explicitly which is handy since it is usually required and matches the Django behaviour. The separate helper is required since live_server can not request transactional_db directly since it is session scoped instead of function-scoped. """ if 'live_server' in request.funcargnames: getfixturevalue(request, 'transactional_db') pytest-django-3.1.2/pytest_django/lazy_django.py000066400000000000000000000013521301551737600220430ustar00rootroot00000000000000""" Helpers to load Django lazily when Django settings can't be configured. """ import os import sys import pytest def skip_if_no_django(): """Raises a skip exception when no Django settings are available""" if not django_settings_is_configured(): pytest.skip('Test skipped since no Django settings is present.') def django_settings_is_configured(): # Avoid importing Django if it has not yet been imported if not os.environ.get('DJANGO_SETTINGS_MODULE') \ and 'django.conf' not in sys.modules: return False # If DJANGO_SETTINGS_MODULE is defined at this point, Django is assumed to # always be loaded. return True def get_django_version(): return __import__('django').VERSION pytest-django-3.1.2/pytest_django/live_server_helper.py000066400000000000000000000077761301551737600234460ustar00rootroot00000000000000import sys class LiveServer(object): """The liveserver fixture This is the object which is returned to the actual user when they request the ``live_server`` fixture. The fixture handles creation and stopping however. """ def __init__(self, addr): import django from django.db import connections from django.test.testcases import LiveServerThread from django.test.utils import modify_settings connections_override = {} for conn in connections.all(): # If using in-memory sqlite databases, pass the connections to # the server thread. if (conn.settings_dict['ENGINE'] == 'django.db.backends.sqlite3' and conn.settings_dict['NAME'] == ':memory:'): # Explicitly enable thread-shareability for this connection conn.allow_thread_sharing = True connections_override[conn.alias] = conn liveserver_kwargs = {'connections_override': connections_override} from django.conf import settings if 'django.contrib.staticfiles' in settings.INSTALLED_APPS: from django.contrib.staticfiles.handlers import StaticFilesHandler liveserver_kwargs['static_handler'] = StaticFilesHandler else: from django.test.testcases import _StaticFilesHandler liveserver_kwargs['static_handler'] = _StaticFilesHandler if django.VERSION < (1, 11): host, possible_ports = parse_addr(addr) self.thread = LiveServerThread(host, possible_ports, **liveserver_kwargs) else: host = addr self.thread = LiveServerThread(host, **liveserver_kwargs) self._live_server_modified_settings = modify_settings( ALLOWED_HOSTS={'append': host}, ) self._live_server_modified_settings.enable() self.thread.daemon = True self.thread.start() self.thread.is_ready.wait() if self.thread.error: raise self.thread.error def stop(self): """Stop the server""" # .terminate() was added in Django 1.7 terminate = getattr(self.thread, 'terminate', lambda: None) terminate() self.thread.join() self._live_server_modified_settings.disable() @property def url(self): return 'http://%s:%s' % (self.thread.host, self.thread.port) if sys.version_info < (3, 0): def __unicode__(self): return self.url def __add__(self, other): return unicode(self) + other # noqa: pyflakes on python3 else: def __str__(self): return self.url def __add__(self, other): return str(self) + other def __repr__(self): return '' % self.url def parse_addr(specified_address): """Parse the --liveserver argument into a host/IP address and port range""" # This code is based on # django.test.testcases.LiveServerTestCase.setUpClass # The specified ports may be of the form '8000-8010,8080,9200-9300' # i.e. a comma-separated list of ports or ranges of ports, so we break # it down into a detailed list of all possible ports. possible_ports = [] try: host, port_ranges = specified_address.split(':') for port_range in port_ranges.split(','): # A port range can be of either form: '8000' or '8000-8010'. extremes = list(map(int, port_range.split('-'))) assert len(extremes) in (1, 2) if len(extremes) == 1: # Port range of the form '8000' possible_ports.append(extremes[0]) else: # Port range of the form '8000-8010' for port in range(extremes[0], extremes[1] + 1): possible_ports.append(port) except Exception: raise Exception( 'Invalid address ("%s") for live server.' % specified_address) return host, possible_ports pytest-django-3.1.2/pytest_django/migrations.py000066400000000000000000000007061301551737600217200ustar00rootroot00000000000000# code snippet copied from https://gist.github.com/NotSqrt/5f3c76cd15e40ef62d09 from pytest_django.lazy_django import get_django_version class DisableMigrations(object): def __init__(self): self._django_version = get_django_version() def __contains__(self, item): return True def __getitem__(self, item): if self._django_version >= (1, 9): return None else: return 'notmigrations' pytest-django-3.1.2/pytest_django/plugin.py000066400000000000000000000517141301551737600210470ustar00rootroot00000000000000"""A pytest plugin which helps testing Django applications This plugin handles creating and destroying the test environment and test database and provides some useful text fixtures. """ import contextlib import inspect from functools import reduce import os import sys import types import py import pytest from .django_compat import is_django_unittest # noqa from .fixtures import django_db_setup # noqa from .fixtures import django_db_use_migrations # noqa from .fixtures import django_db_keepdb # noqa from .fixtures import django_db_modify_db_settings # noqa from .fixtures import django_db_modify_db_settings_xdist_suffix # noqa from .fixtures import _live_server_helper # noqa from .fixtures import admin_client # noqa from .fixtures import admin_user # noqa from .fixtures import client # noqa from .fixtures import db # noqa from .fixtures import django_user_model # noqa from .fixtures import django_username_field # noqa from .fixtures import live_server # noqa from .fixtures import rf # noqa from .fixtures import settings # noqa from .fixtures import transactional_db # noqa from .pytest_compat import getfixturevalue from .lazy_django import (django_settings_is_configured, get_django_version, skip_if_no_django) SETTINGS_MODULE_ENV = 'DJANGO_SETTINGS_MODULE' CONFIGURATION_ENV = 'DJANGO_CONFIGURATION' INVALID_TEMPLATE_VARS_ENV = 'FAIL_INVALID_TEMPLATE_VARS' # ############### pytest hooks ################ def pytest_addoption(parser): group = parser.getgroup('django') group._addoption('--reuse-db', action='store_true', dest='reuse_db', default=False, help='Re-use the testing database if it already exists, ' 'and do not remove it when the test finishes.') group._addoption('--create-db', action='store_true', dest='create_db', default=False, help='Re-create the database, even if it exists. This ' 'option can be used to override --reuse-db.') group._addoption('--ds', action='store', type=str, dest='ds', default=None, help='Set DJANGO_SETTINGS_MODULE.') group._addoption('--dc', action='store', type=str, dest='dc', default=None, help='Set DJANGO_CONFIGURATION.') group._addoption('--nomigrations', '--no-migrations', action='store_true', dest='nomigrations', default=False, help='Disable Django 1.7+ migrations on test setup') group._addoption('--migrations', action='store_false', dest='nomigrations', default=False, help='Enable Django 1.7+ migrations on test setup') parser.addini(CONFIGURATION_ENV, 'django-configurations class to use by pytest-django.') group._addoption('--liveserver', default=None, help='Address and port for the live_server fixture.') parser.addini(SETTINGS_MODULE_ENV, 'Django settings module to use by pytest-django.') parser.addini('django_find_project', 'Automatically find and add a Django project to the ' 'Python path.', type='bool', default=True) group._addoption('--fail-on-template-vars', action='store_true', dest='itv', default=False, help='Fail for invalid variables in templates.') parser.addini(INVALID_TEMPLATE_VARS_ENV, 'Fail for invalid variables in templates.', type='bool', default=False) def _exists(path, ignore=EnvironmentError): try: return path.check() except ignore: return False PROJECT_FOUND = ('pytest-django found a Django project in %s ' '(it contains manage.py) and added it to the Python path.\n' 'If this is wrong, add "django_find_project = false" to ' 'pytest.ini and explicitly manage your Python path.') PROJECT_NOT_FOUND = ('pytest-django could not find a Django project ' '(no manage.py file could be found). You must ' 'explicitly add your Django project to the Python path ' 'to have it picked up.') PROJECT_SCAN_DISABLED = ('pytest-django did not search for Django ' 'projects since it is disabled in the configuration ' '("django_find_project = false")') @contextlib.contextmanager def _handle_import_error(extra_message): try: yield except ImportError as e: django_msg = (e.args[0] + '\n\n') if e.args else '' msg = django_msg + extra_message raise ImportError(msg) def _add_django_project_to_path(args): args = [x for x in args if not str(x).startswith("-")] if not args: args = [py.path.local()] for arg in args: arg = py.path.local(arg) for base in arg.parts(reverse=True): manage_py_try = base.join('manage.py') if _exists(manage_py_try): sys.path.insert(0, str(base)) return PROJECT_FOUND % base return PROJECT_NOT_FOUND def _setup_django(): if 'django' not in sys.modules: return import django.conf # Avoid force-loading Django when settings are not properly configured. if not django.conf.settings.configured: return django.setup() _blocking_manager.block() def _get_boolean_value(x, name, default=None): if x is None: return default if x in (True, False): return x possible_values = {'true': True, 'false': False, '1': True, '0': False} try: return possible_values[x.lower()] except KeyError: raise ValueError('{} is not a valid value for {}. ' 'It must be one of {}.' % (x, name, ', '.join(possible_values.keys()))) def pytest_load_initial_conftests(early_config, parser, args): # Register the marks early_config.addinivalue_line( 'markers', 'django_db(transaction=False): Mark the test as using ' 'the django test database. The *transaction* argument marks will ' "allow you to use real transactions in the test like Django's " 'TransactionTestCase.') early_config.addinivalue_line( 'markers', 'urls(modstr): Use a different URLconf for this test, similar to ' 'the `urls` attribute of Django `TestCase` objects. *modstr* is ' 'a string specifying the module of a URL config, e.g. ' '"my_app.test_urls".') options = parser.parse_known_args(args) if options.version or options.help: return django_find_project = _get_boolean_value( early_config.getini('django_find_project'), 'django_find_project') if django_find_project: _django_project_scan_outcome = _add_django_project_to_path(args) else: _django_project_scan_outcome = PROJECT_SCAN_DISABLED if (options.itv or _get_boolean_value(os.environ.get(INVALID_TEMPLATE_VARS_ENV), INVALID_TEMPLATE_VARS_ENV) or early_config.getini(INVALID_TEMPLATE_VARS_ENV)): os.environ[INVALID_TEMPLATE_VARS_ENV] = 'true' # Configure DJANGO_SETTINGS_MODULE if options.ds: ds_source = 'command line option' ds = options.ds elif SETTINGS_MODULE_ENV in os.environ: ds = os.environ[SETTINGS_MODULE_ENV] ds_source = 'environment variable' elif early_config.getini(SETTINGS_MODULE_ENV): ds = early_config.getini(SETTINGS_MODULE_ENV) ds_source = 'ini file' else: ds = None ds_source = None if ds: early_config._dsm_report_header = 'Django settings: %s (from %s)' % ( ds, ds_source) else: early_config._dsm_report_header = None # Configure DJANGO_CONFIGURATION dc = (options.dc or os.environ.get(CONFIGURATION_ENV) or early_config.getini(CONFIGURATION_ENV)) if ds: os.environ[SETTINGS_MODULE_ENV] = ds if dc: os.environ[CONFIGURATION_ENV] = dc # Install the django-configurations importer import configurations.importer configurations.importer.install() # Forcefully load Django settings, throws ImportError or # ImproperlyConfigured if settings cannot be loaded. from django.conf import settings as dj_settings with _handle_import_error(_django_project_scan_outcome): dj_settings.DATABASES _setup_django() def pytest_report_header(config): if config._dsm_report_header: return [config._dsm_report_header] @pytest.mark.trylast def pytest_configure(): # Allow Django settings to be configured in a user pytest_configure call, # but make sure we call django.setup() _setup_django() def _method_is_defined_at_leaf(cls, method_name): super_method = None for base_cls in cls.__bases__: if hasattr(base_cls, method_name): super_method = getattr(base_cls, method_name) assert super_method is not None, ( '%s could not be found in base class' % method_name) return getattr(cls, method_name).__func__ is not super_method.__func__ _disabled_classmethods = {} def _disable_class_methods(cls): if cls in _disabled_classmethods: return _disabled_classmethods[cls] = ( cls.setUpClass, _method_is_defined_at_leaf(cls, 'setUpClass'), cls.tearDownClass, _method_is_defined_at_leaf(cls, 'tearDownClass'), ) cls.setUpClass = types.MethodType(lambda cls: None, cls) cls.tearDownClass = types.MethodType(lambda cls: None, cls) def _restore_class_methods(cls): (setUpClass, restore_setUpClass, tearDownClass, restore_tearDownClass) = _disabled_classmethods.pop(cls) try: del cls.setUpClass except AttributeError: raise try: del cls.tearDownClass except AttributeError: pass if restore_setUpClass: cls.setUpClass = setUpClass if restore_tearDownClass: cls.tearDownClass = tearDownClass def pytest_runtest_setup(item): if django_settings_is_configured() and is_django_unittest(item): cls = item.cls _disable_class_methods(cls) @pytest.fixture(autouse=True, scope='session') def django_test_environment(request): """ Ensure that Django is loaded and has its testing environment setup. XXX It is a little dodgy that this is an autouse fixture. Perhaps an email fixture should be requested in order to be able to use the Django email machinery just like you need to request a db fixture for access to the Django database, etc. But without duplicating a lot more of Django's test support code we need to follow this model. """ if django_settings_is_configured(): _setup_django() from django.conf import settings as dj_settings from django.test.utils import (setup_test_environment, teardown_test_environment) dj_settings.DEBUG = False setup_test_environment() request.addfinalizer(teardown_test_environment) @pytest.fixture(scope='session') def django_db_blocker(): """Wrapper around Django's database access. This object can be used to re-enable database access. This fixture is used internally in pytest-django to build the other fixtures and can be used for special database handling. The object is a context manager and provides the methods .unblock()/.block() and .restore() to temporarily enable database access. This is an advanced feature that is meant to be used to implement database fixtures. """ if not django_settings_is_configured(): return None return _blocking_manager @pytest.fixture(autouse=True) def _django_db_marker(request): """Implement the django_db marker, internal to pytest-django. This will dynamically request the ``db`` or ``transactional_db`` fixtures as required by the django_db marker. """ marker = request.keywords.get('django_db', None) if marker: validate_django_db(marker) if marker.transaction: getfixturevalue(request, 'transactional_db') else: getfixturevalue(request, 'db') @pytest.fixture(autouse=True, scope='class') def _django_setup_unittest(request, django_db_blocker): """Setup a django unittest, internal to pytest-django.""" if django_settings_is_configured() and is_django_unittest(request): getfixturevalue(request, 'django_test_environment') getfixturevalue(request, 'django_db_setup') django_db_blocker.unblock() cls = request.node.cls # implement missing (as of 1.10) debug() method for django's TestCase # see pytest-dev/pytest-django#406 def _cleaning_debug(self): testMethod = getattr(self, self._testMethodName) skipped = ( getattr(self.__class__, "__unittest_skip__", False) or getattr(testMethod, "__unittest_skip__", False)) if not skipped: self._pre_setup() super(cls, self).debug() if not skipped: self._post_teardown() cls.debug = _cleaning_debug _restore_class_methods(cls) cls.setUpClass() _disable_class_methods(cls) def teardown(): _restore_class_methods(cls) cls.tearDownClass() django_db_blocker.restore() request.addfinalizer(teardown) @pytest.fixture(scope='function', autouse=True) def _dj_autoclear_mailbox(): if not django_settings_is_configured(): return from django.core import mail del mail.outbox[:] @pytest.fixture(scope='function') def mailoutbox(monkeypatch, _dj_autoclear_mailbox): if not django_settings_is_configured(): return from django.core import mail return mail.outbox @pytest.fixture(autouse=True, scope='function') def _django_set_urlconf(request): """Apply the @pytest.mark.urls marker, internal to pytest-django.""" marker = request.keywords.get('urls', None) if marker: skip_if_no_django() import django.conf from django.core.urlresolvers import clear_url_caches, set_urlconf validate_urls(marker) original_urlconf = django.conf.settings.ROOT_URLCONF django.conf.settings.ROOT_URLCONF = marker.urls clear_url_caches() set_urlconf(None) def restore(): django.conf.settings.ROOT_URLCONF = original_urlconf # Copy the pattern from # https://github.com/django/django/blob/master/django/test/signals.py#L152 clear_url_caches() set_urlconf(None) request.addfinalizer(restore) @pytest.fixture(autouse=True, scope='session') def _fail_for_invalid_template_variable(request): """Fixture that fails for invalid variables in templates. This fixture will fail each test that uses django template rendering should a template contain an invalid template variable. The fail message will include the name of the invalid variable and in most cases the template name. It does not raise an exception, but fails, as the stack trace doesn't offer any helpful information to debug. This behavior can be switched off using the marker: ``ignore_template_errors`` """ class InvalidVarException(object): """Custom handler for invalid strings in templates.""" def __init__(self): self.fail = True def __contains__(self, key): """There is a test for '%s' in TEMPLATE_STRING_IF_INVALID.""" return key == '%s' def _get_template(self): from django.template import Template stack = inspect.stack() # finding the ``render`` needle in the stack frame = reduce( lambda x, y: y[3] == 'render' and 'base.py' in y[1] and y or x, stack ) # assert 0, stack frame = frame[0] # finding only the frame locals in all frame members f_locals = reduce( lambda x, y: y[0] == 'f_locals' and y or x, inspect.getmembers(frame) )[1] # ``django.template.base.Template`` template = f_locals['self'] if isinstance(template, Template): return template def __mod__(self, var): """Handle TEMPLATE_STRING_IF_INVALID % var.""" template = self._get_template() if template: msg = "Undefined template variable '%s' in '%s'" % ( var, template.name) else: msg = "Undefined template variable '%s'" % var if self.fail: pytest.fail(msg, pytrace=False) else: return msg if (os.environ.get(INVALID_TEMPLATE_VARS_ENV, 'false') == 'true' and django_settings_is_configured()): from django.conf import settings as dj_settings if get_django_version() >= (1, 8) and dj_settings.TEMPLATES: dj_settings.TEMPLATES[0]['OPTIONS']['string_if_invalid'] = ( InvalidVarException()) else: dj_settings.TEMPLATE_STRING_IF_INVALID = InvalidVarException() @pytest.fixture(autouse=True) def _template_string_if_invalid_marker(request): """Apply the @pytest.mark.ignore_template_errors marker, internal to pytest-django.""" marker = request.keywords.get('ignore_template_errors', None) if os.environ.get(INVALID_TEMPLATE_VARS_ENV, 'false') == 'true': if marker and django_settings_is_configured(): from django.conf import settings as dj_settings if get_django_version() >= (1, 8) and dj_settings.TEMPLATES: dj_settings.TEMPLATES[0]['OPTIONS']['string_if_invalid'].fail = False else: dj_settings.TEMPLATE_STRING_IF_INVALID.fail = False @pytest.fixture(autouse=True, scope='function') def _django_clear_site_cache(): """Clears ``django.contrib.sites.models.SITE_CACHE`` to avoid unexpected behavior with cached site objects. """ if django_settings_is_configured(): from django.conf import settings as dj_settings if 'django.contrib.sites' in dj_settings.INSTALLED_APPS: from django.contrib.sites.models import Site Site.objects.clear_cache() # ############### Helper Functions ################ class _DatabaseBlockerContextManager(object): def __init__(self, db_blocker): self._db_blocker = db_blocker def __enter__(self): pass def __exit__(self, exc_type, exc_value, traceback): self._db_blocker.restore() class _DatabaseBlocker(object): """Manager for django.db.backends.base.base.BaseDatabaseWrapper. This is the object returned by django_db_blocker. """ def __init__(self): self._history = [] self._real_ensure_connection = None @property def _dj_db_wrapper(self): from .compat import BaseDatabaseWrapper # The first time the _dj_db_wrapper is accessed, we will save a # reference to the real implementation. if self._real_ensure_connection is None: self._real_ensure_connection = BaseDatabaseWrapper.ensure_connection return BaseDatabaseWrapper def _save_active_wrapper(self): return self._history.append(self._dj_db_wrapper.ensure_connection) def _blocking_wrapper(*args, **kwargs): __tracebackhide__ = True __tracebackhide__ # Silence pyflakes pytest.fail('Database access not allowed, ' 'use the "django_db" mark, or the ' '"db" or "transactional_db" fixtures to enable it.') def unblock(self): """Enable access to the Django database.""" self._save_active_wrapper() self._dj_db_wrapper.ensure_connection = self._real_ensure_connection return _DatabaseBlockerContextManager(self) def block(self): """Disable access to the Django database.""" self._save_active_wrapper() self._dj_db_wrapper.ensure_connection = self._blocking_wrapper return _DatabaseBlockerContextManager(self) def restore(self): self._dj_db_wrapper.ensure_connection = self._history.pop() _blocking_manager = _DatabaseBlocker() def validate_django_db(marker): """Validate the django_db marker. It checks the signature and creates the `transaction` attribute on the marker which will have the correct value. """ def apifun(transaction=False): marker.transaction = transaction apifun(*marker.args, **marker.kwargs) def validate_urls(marker): """Validate the urls marker. It checks the signature and creates the `urls` attribute on the marker which will have the correct value. """ def apifun(urls): marker.urls = urls apifun(*marker.args, **marker.kwargs) pytest-django-3.1.2/pytest_django/pytest_compat.py000066400000000000000000000002521301551737600224330ustar00rootroot00000000000000def getfixturevalue(request, value): if hasattr(request, 'getfixturevalue'): return request.getfixturevalue(value) return request.getfuncargvalue(value) pytest-django-3.1.2/pytest_django_test/000077500000000000000000000000001301551737600202265ustar00rootroot00000000000000pytest-django-3.1.2/pytest_django_test/__init__.py000066400000000000000000000000001301551737600223250ustar00rootroot00000000000000pytest-django-3.1.2/pytest_django_test/app/000077500000000000000000000000001301551737600210065ustar00rootroot00000000000000pytest-django-3.1.2/pytest_django_test/app/__init__.py000066400000000000000000000000001301551737600231050ustar00rootroot00000000000000pytest-django-3.1.2/pytest_django_test/app/fixtures/000077500000000000000000000000001301551737600226575ustar00rootroot00000000000000pytest-django-3.1.2/pytest_django_test/app/fixtures/items.json000066400000000000000000000001441301551737600246720ustar00rootroot00000000000000[ { "pk": 1, "model": "app.item", "fields": { "name": "Fixture item" } } ]pytest-django-3.1.2/pytest_django_test/app/migrations/000077500000000000000000000000001301551737600231625ustar00rootroot00000000000000pytest-django-3.1.2/pytest_django_test/app/migrations/0001_initial.py000066400000000000000000000011141301551737600256220ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Generated by Django 1.9a1 on 2016-06-22 04:33 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Item', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ], ), ] pytest-django-3.1.2/pytest_django_test/app/migrations/__init__.py000066400000000000000000000000001301551737600252610ustar00rootroot00000000000000pytest-django-3.1.2/pytest_django_test/app/models.py000066400000000000000000000003131301551737600226400ustar00rootroot00000000000000from django.db import models class Item(models.Model): name = models.CharField(max_length=100) def __unicode__(self): return self.name def __str__(self): return self.name pytest-django-3.1.2/pytest_django_test/app/static/000077500000000000000000000000001301551737600222755ustar00rootroot00000000000000pytest-django-3.1.2/pytest_django_test/app/static/a_file.txt000066400000000000000000000000041301551737600242470ustar00rootroot00000000000000bla pytest-django-3.1.2/pytest_django_test/app/views.py000066400000000000000000000006771301551737600225270ustar00rootroot00000000000000from django.http import HttpResponse from django.template import Template from django.template.context import Context from .models import Item def admin_required_view(request): if request.user.is_staff: return HttpResponse(Template('You are an admin').render(Context())) return HttpResponse(Template('Access denied').render(Context())) def item_count(request): return HttpResponse('Item count: %d' % Item.objects.count()) pytest-django-3.1.2/pytest_django_test/compat.py000066400000000000000000000005251301551737600220650ustar00rootroot00000000000000try: from urllib2 import urlopen, HTTPError # noqa except ImportError: from urllib.request import urlopen, HTTPError # noqa # Django 1.10 removes patterns, instead it is just a list try: from django.conf.urls import patterns except ImportError: def patterns(prefix, *urls): assert prefix == '' return urls pytest-django-3.1.2/pytest_django_test/db_helpers.py000066400000000000000000000117071301551737600227150ustar00rootroot00000000000000import os import subprocess import sqlite3 import pytest from django.conf import settings from django.utils.encoding import force_text # Construct names for the "inner" database used in runpytest tests _settings = settings.DATABASES['default'] DB_NAME = _settings['NAME'] TEST_DB_NAME = _settings['TEST']['NAME'] if _settings['ENGINE'] == 'django.db.backends.sqlite3' and TEST_DB_NAME is None: TEST_DB_NAME = ':memory:' else: DB_NAME += '_inner' if TEST_DB_NAME is None: # No explicit test db name was given, construct a default one TEST_DB_NAME = 'test_{}_inner'.format(DB_NAME) else: # An explicit test db name was given, is that as the base name TEST_DB_NAME = '{}_inner'.format(TEST_DB_NAME) def get_db_engine(): return _settings['ENGINE'].split('.')[-1] class CmdResult(object): def __init__(self, status_code, std_out, std_err): self.status_code = status_code self.std_out = std_out self.std_err = std_err def run_cmd(*args): r = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdoutdata, stderrdata = r.communicate() ret = r.wait() return CmdResult(ret, stdoutdata, stderrdata) def run_mysql(*args): user = _settings.get('USER', None) if user: args = ('-u', user) + tuple(args) args = ('mysql',) + tuple(args) return run_cmd(*args) def skip_if_sqlite_in_memory(): if _settings['ENGINE'] == 'django.db.backends.sqlite3' and _settings['TEST']['NAME'] is None: pytest.skip('Do not test db reuse since database does not support it') def drop_database(name=TEST_DB_NAME, suffix=None): assert bool(name) ^ bool(suffix), 'name and suffix cannot be used together' if suffix: name = '%s_%s' % (name, suffix) if get_db_engine() == 'postgresql_psycopg2': r = run_cmd('psql', 'postgres', '-c', 'DROP DATABASE %s' % name) assert ('DROP DATABASE' in force_text(r.std_out) or 'does not exist' in force_text(r.std_err)) return if get_db_engine() == 'mysql': r = run_mysql('-e', 'DROP DATABASE %s' % name) assert ('database doesn\'t exist' in force_text(r.std_err) or r.status_code == 0) return if get_db_engine() == 'sqlite3': if name == ':memory:': raise AssertionError( 'sqlite in-memory database cannot be dropped!') if os.path.exists(name): os.unlink(name) return raise AssertionError('%s cannot be tested properly!' % get_db_engine()) def db_exists(db_suffix=None): name = TEST_DB_NAME if db_suffix: name = '%s_%s' % (name, db_suffix) if get_db_engine() == 'postgresql_psycopg2': r = run_cmd('psql', name, '-c', 'SELECT 1') return r.status_code == 0 if get_db_engine() == 'mysql': r = run_mysql(name, '-e', 'SELECT 1') return r.status_code == 0 if get_db_engine() == 'sqlite3': if TEST_DB_NAME == ':memory:': raise AssertionError( 'sqlite in-memory database cannot be checked for existence!') return os.path.exists(name) raise AssertionError('%s cannot be tested properly!' % get_db_engine()) def mark_database(): if get_db_engine() == 'postgresql_psycopg2': r = run_cmd('psql', TEST_DB_NAME, '-c', 'CREATE TABLE mark_table();') assert r.status_code == 0 return if get_db_engine() == 'mysql': r = run_mysql(TEST_DB_NAME, '-e', 'CREATE TABLE mark_table(kaka int);') assert r.status_code == 0 return if get_db_engine() == 'sqlite3': if TEST_DB_NAME == ':memory:': raise AssertionError('sqlite in-memory database cannot be marked!') conn = sqlite3.connect(TEST_DB_NAME) try: with conn: conn.execute('CREATE TABLE mark_table(kaka int);') finally: # Close the DB even if an error is raised conn.close() return raise AssertionError('%s cannot be tested properly!' % get_db_engine()) def mark_exists(): if get_db_engine() == 'postgresql_psycopg2': r = run_cmd('psql', TEST_DB_NAME, '-c', 'SELECT 1 FROM mark_table') # When something pops out on std_out, we are good return bool(r.std_out) if get_db_engine() == 'mysql': r = run_mysql(TEST_DB_NAME, '-e', 'SELECT 1 FROM mark_table') return r.status_code == 0 if get_db_engine() == 'sqlite3': if TEST_DB_NAME == ':memory:': raise AssertionError( 'sqlite in-memory database cannot be checked for mark!') conn = sqlite3.connect(TEST_DB_NAME) try: with conn: conn.execute('SELECT 1 FROM mark_table') return True except sqlite3.OperationalError: return False finally: # Close the DB even if an error is raised conn.close() raise AssertionError('%s cannot be tested properly!' % get_db_engine()) pytest-django-3.1.2/pytest_django_test/settings_base.py000066400000000000000000000016571301551737600234430ustar00rootroot00000000000000import os ROOT_URLCONF = 'pytest_django_test.urls' INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'pytest_django_test.app', ] STATIC_URL = '/static/' SECRET_KEY = 'foobar' # Used to construct unique test database names to allow detox to run multiple # versions at the same time uid = os.getenv('UID', '') if uid: db_suffix = '_%s' % uid else: db_suffix = '' MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': {}, }, ] pytest-django-3.1.2/pytest_django_test/settings_mysql_innodb.py000066400000000000000000000004751301551737600252240ustar00rootroot00000000000000from .settings_base import * # noqa DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'pytest_django' + db_suffix, # noqa 'HOST': 'localhost', 'USER': 'root', 'OPTIONS': { 'init_command': 'SET storage_engine=InnoDB' } }, } pytest-django-3.1.2/pytest_django_test/settings_mysql_myisam.py000066400000000000000000000005171301551737600252470ustar00rootroot00000000000000from pytest_django_test.settings_base import * # noqa DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'pytest_django' + db_suffix, # noqa 'HOST': 'localhost', 'USER': 'root', 'OPTIONS': { 'init_command': 'SET storage_engine=MyISAM' } }, } pytest-django-3.1.2/pytest_django_test/settings_postgres.py000066400000000000000000000005631301551737600243720ustar00rootroot00000000000000from pytest_django_test.settings_base import * # noqa # PyPy compatibility try: from psycopg2ct import compat compat.register() except ImportError: pass DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'pytest_django' + db_suffix, # noqa 'HOST': 'localhost', 'USER': '', }, } pytest-django-3.1.2/pytest_django_test/settings_sqlite.py000066400000000000000000000002511301551737600240170ustar00rootroot00000000000000from .settings_base import * # noqa DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '/should_not_be_accessed', }, } pytest-django-3.1.2/pytest_django_test/settings_sqlite_file.py000066400000000000000000000007531301551737600250250ustar00rootroot00000000000000import tempfile from pytest_django_test.settings_base import * # noqa # This is a SQLite configuration, which uses a file based database for # tests (via setting TEST_NAME / TEST['NAME']). # The name as expected / used by Django/pytest_django (tests/db_helpers.py). _fd, _filename = tempfile.mkstemp(prefix='test_') DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '/should_never_be_accessed', 'TEST': {'NAME': _filename}, }, } pytest-django-3.1.2/pytest_django_test/urls.py000066400000000000000000000003401301551737600215620ustar00rootroot00000000000000from django.conf.urls import url from .app import views from .compat import patterns urlpatterns = patterns( '', url(r'^item_count/$', views.item_count), url(r'^admin-required/$', views.admin_required_view), ) pytest-django-3.1.2/pytest_django_test/urls_overridden.py000066400000000000000000000003421301551737600240050ustar00rootroot00000000000000from django.conf.urls import url from django.http import HttpResponse from .compat import patterns urlpatterns = patterns( '', url(r'^overridden_url/$', lambda r: HttpResponse('Overridden urlconf works!')) ) pytest-django-3.1.2/requirements.txt000066400000000000000000000001211301551737600175730ustar00rootroot00000000000000-e . setuptools django django-configurations pytest-xdist tox wheel twine flake8 pytest-django-3.1.2/setup.cfg000066400000000000000000000012151301551737600161350ustar00rootroot00000000000000[tool:pytest] # --strict: warnings become errors. # -r fEsxXw: show extra test summary info for everything. addopts = --ignore lib/ --ignore build/ --ignore include/ --ignore local/ --ignore src/ --strict -r fEsxXw DJANGO_SETTINGS_MODULE = pytest_django_test.settings_sqlite_file [wheel] universal = 1 [flake8] # Ref: https://flake8.readthedocs.io/en/latest/warnings.html#error-codes ignore = NONE # Default, if empty: # ignore = E123,E133,E226,E241,E242 max-line-length = 99 exclude = lib/,src/,docs/,bin/ [isort] # NOTE: local imports are handled special (they do not get handled as "tests"). forced_separate=tests,pytest_django,pytest_django_test pytest-django-3.1.2/setup.py000077500000000000000000000033401301551737600160320ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- import codecs import os from setuptools import setup # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): file_path = os.path.join(os.path.dirname(__file__), fname) return codecs.open(file_path, encoding='utf-8').read() setup( name='pytest-django', use_scm_version=True, description='A Django plugin for pytest.', author='Andreas Pelme', author_email='andreas@pelme.se', maintainer="Andreas Pelme", maintainer_email="andreas@pelme.se", url='https://pytest-django.readthedocs.io/', license='BSD-3-Clause', packages=['pytest_django'], long_description=read('README.rst'), setup_requires=['setuptools_scm==1.11.1'], install_requires=['pytest>=2.9'], classifiers=['Development Status :: 5 - Production/Stable', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Testing', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], # the following makes a plugin available to pytest entry_points={'pytest11': ['django = pytest_django.plugin']}) pytest-django-3.1.2/tests/000077500000000000000000000000001301551737600154575ustar00rootroot00000000000000pytest-django-3.1.2/tests/DBNAME_pytest_django_db000066400000000000000000000000001301551737600217150ustar00rootroot00000000000000pytest-django-3.1.2/tests/conftest.py000066400000000000000000000075061301551737600176660ustar00rootroot00000000000000import copy import shutil from textwrap import dedent import py import pytest from django.conf import settings from pytest_django_test.db_helpers import DB_NAME, TEST_DB_NAME pytest_plugins = 'pytester' REPOSITORY_ROOT = py.path.local(__file__).join('..') def pytest_configure(config): config.addinivalue_line( 'markers', 'django_project: options for the django_testdir fixture') def _marker_apifun(extra_settings='', create_manage_py=False, project_root=None): return { 'extra_settings': extra_settings, 'create_manage_py': create_manage_py, 'project_root': project_root, } @pytest.fixture(scope='function') def django_testdir(request, testdir, monkeypatch): marker = request.node.get_marker('django_project') options = _marker_apifun(**(marker.kwargs if marker else {})) if hasattr(request.node.cls, 'db_settings'): db_settings = request.node.cls.db_settings else: db_settings = copy.deepcopy(settings.DATABASES) db_settings['default']['NAME'] = DB_NAME db_settings['default']['TEST']['NAME'] = TEST_DB_NAME test_settings = dedent(''' # Pypy compatibility try: from psycopg2ct import compat except ImportError: pass else: compat.register() DATABASES = %(db_settings)s INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'tpkg.app', ] SECRET_KEY = 'foobar' MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': {}, }, ] %(extra_settings)s ''') % { 'db_settings': repr(db_settings), 'extra_settings': dedent(options['extra_settings'])} if options['project_root']: project_root = testdir.mkdir(options['project_root']) else: project_root = testdir.tmpdir tpkg_path = project_root.mkdir('tpkg') if options['create_manage_py']: project_root.ensure('manage.py') tpkg_path.ensure('__init__.py') app_source = REPOSITORY_ROOT.dirpath('pytest_django_test/app') test_app_path = tpkg_path.join('app') # Copy the test app to make it available in the new test run shutil.copytree(py.builtin._totext(app_source), py.builtin._totext(test_app_path)) tpkg_path.join("the_settings.py").write(test_settings) monkeypatch.setenv('DJANGO_SETTINGS_MODULE', 'tpkg.the_settings') def create_test_module(test_code, filename='test_the_test.py'): r = tpkg_path.join(filename) r.write(dedent(test_code), ensure=True) return r def create_app_file(code, filename): r = test_app_path.join(filename) r.write(dedent(code), ensure=True) return r testdir.create_test_module = create_test_module testdir.create_app_file = create_app_file testdir.project_root = project_root return testdir @pytest.fixture def django_testdir_initial(django_testdir): """A django_testdir fixture which provides initial_data.""" django_testdir.project_root.join('tpkg/app/migrations').remove() django_testdir.makefile('.json', initial_data=""" [{ "pk": 1, "model": "app.item", "fields": { "name": "mark_initial_data" } }]""") return django_testdir pytest-django-3.1.2/tests/test_database.py000066400000000000000000000146421301551737600206430ustar00rootroot00000000000000from __future__ import with_statement import pytest from django.db import connection from django.test.testcases import connections_support_transactions from pytest_django.pytest_compat import getfixturevalue from pytest_django_test.app.models import Item def test_noaccess(): with pytest.raises(pytest.fail.Exception): Item.objects.create(name='spam') with pytest.raises(pytest.fail.Exception): Item.objects.count() @pytest.fixture def noaccess(): with pytest.raises(pytest.fail.Exception): Item.objects.create(name='spam') with pytest.raises(pytest.fail.Exception): Item.objects.count() def test_noaccess_fixture(noaccess): # Setup will fail if this test needs to fail pass class TestDatabaseFixtures: """Tests for the db and transactional_db fixtures""" @pytest.fixture(params=['db', 'transactional_db']) def both_dbs(self, request): if request.param == 'transactional_db': return getfixturevalue(request, 'transactional_db') elif request.param == 'db': return getfixturevalue(request, 'db') def test_access(self, both_dbs): Item.objects.create(name='spam') def test_clean_db(self, both_dbs): # Relies on the order: test_access created an object assert Item.objects.count() == 0 def test_transactions_disabled(self, db): if not connections_support_transactions(): pytest.skip('transactions required for this test') assert connection.in_atomic_block def test_transactions_enabled(self, transactional_db): if not connections_support_transactions(): pytest.skip('transactions required for this test') assert not connection.in_atomic_block @pytest.fixture def mydb(self, both_dbs): # This fixture must be able to access the database Item.objects.create(name='spam') def test_mydb(self, mydb): if not connections_support_transactions(): pytest.skip('transactions required for this test') # Check the fixture had access to the db item = Item.objects.get(name='spam') assert item def test_fixture_clean(self, both_dbs): # Relies on the order: test_mydb created an object # See https://github.com/pytest-dev/pytest-django/issues/17 assert Item.objects.count() == 0 @pytest.fixture def fin(self, request, both_dbs): # This finalizer must be able to access the database request.addfinalizer(lambda: Item.objects.create(name='spam')) def test_fin(self, fin): # Check finalizer has db access (teardown will fail if not) pass class TestDatabaseFixturesBothOrder: @pytest.fixture def fixture_with_db(self, db): Item.objects.create(name='spam') @pytest.fixture def fixture_with_transdb(self, transactional_db): Item.objects.create(name='spam') def test_trans(self, fixture_with_transdb): pass def test_db(self, fixture_with_db): pass def test_db_trans(self, fixture_with_db, fixture_with_transdb): pass def test_trans_db(self, fixture_with_transdb, fixture_with_db): pass class TestDatabaseMarker: "Tests for the django_db marker." @pytest.mark.django_db def test_access(self): Item.objects.create(name='spam') @pytest.mark.django_db def test_clean_db(self): # Relies on the order: test_access created an object. assert Item.objects.count() == 0 @pytest.mark.django_db def test_transactions_disabled(self): if not connections_support_transactions(): pytest.skip('transactions required for this test') assert connection.in_atomic_block @pytest.mark.django_db(transaction=False) def test_transactions_disabled_explicit(self): if not connections_support_transactions(): pytest.skip('transactions required for this test') assert connection.in_atomic_block @pytest.mark.django_db(transaction=True) def test_transactions_enabled(self): if not connections_support_transactions(): pytest.skip('transactions required for this test') assert not connection.in_atomic_block def test_unittest_interaction(django_testdir): "Test that (non-Django) unittests cannot access the DB." django_testdir.create_test_module(''' import pytest import unittest from .app.models import Item class TestCase_setupClass(unittest.TestCase): @classmethod def setUpClass(cls): Item.objects.create(name='foo') def test_db_access_1(self): Item.objects.count() == 1 class TestCase_setUp(unittest.TestCase): @classmethod def setUp(cls): Item.objects.create(name='foo') def test_db_access_2(self): Item.objects.count() == 1 class TestCase(unittest.TestCase): def test_db_access_3(self): Item.objects.count() == 1 ''') result = django_testdir.runpytest_subprocess('-v', '--reuse-db') result.stdout.fnmatch_lines([ "*test_db_access_1 ERROR*", "*test_db_access_2 FAILED*", "*test_db_access_3 FAILED*", "*ERROR at setup of TestCase_setupClass.test_db_access_1*", '*Failed: Database access not allowed, use the "django_db" mark, ' 'or the "db" or "transactional_db" fixtures to enable it.', ]) class Test_database_blocking: def test_db_access_in_conftest(self, django_testdir): """Make sure database access in conftest module is prohibited.""" django_testdir.makeconftest(""" from tpkg.app.models import Item Item.objects.get() """) result = django_testdir.runpytest_subprocess('-v') result.stderr.fnmatch_lines([ '*Failed: Database access not allowed, use the "django_db" mark, ' 'or the "db" or "transactional_db" fixtures to enable it.*', ]) def test_db_access_in_test_module(self, django_testdir): django_testdir.create_test_module(""" from tpkg.app.models import Item Item.objects.get() """) result = django_testdir.runpytest_subprocess('-v') result.stdout.fnmatch_lines([ '*Failed: Database access not allowed, use the "django_db" mark, ' 'or the "db" or "transactional_db" fixtures to enable it.', ]) pytest-django-3.1.2/tests/test_db_setup.py000066400000000000000000000217251301551737600207040ustar00rootroot00000000000000import pytest from pytest_django.lazy_django import get_django_version from pytest_django_test.db_helpers import (db_exists, drop_database, mark_database, mark_exists, skip_if_sqlite_in_memory) def test_db_reuse_simple(django_testdir): "A test for all backends to check that `--reuse-db` works." django_testdir.create_test_module(''' import pytest from .app.models import Item @pytest.mark.django_db def test_db_can_be_accessed(): assert Item.objects.count() == 0 ''') result = django_testdir.runpytest_subprocess('-v', '--reuse-db') assert result.ret == 0 result.stdout.fnmatch_lines([ "*test_db_can_be_accessed PASSED*", ]) def test_db_reuse(django_testdir): """ Test the re-use db functionality. """ skip_if_sqlite_in_memory() django_testdir.create_test_module(''' import pytest from .app.models import Item @pytest.mark.django_db def test_db_can_be_accessed(): assert Item.objects.count() == 0 ''') # Use --create-db on the first run to make sure we are not just re-using a # database from another test run drop_database() assert not db_exists() # Do not pass in --create-db to make sure it is created when it # does not exist result_first = django_testdir.runpytest_subprocess('-v', '--reuse-db') assert result_first.ret == 0 result_first.stdout.fnmatch_lines([ "*test_db_can_be_accessed PASSED*", ]) assert not mark_exists() mark_database() assert mark_exists() result_second = django_testdir.runpytest_subprocess('-v', '--reuse-db') assert result_second.ret == 0 result_second.stdout.fnmatch_lines([ "*test_db_can_be_accessed PASSED*", ]) # Make sure the database has not been re-created assert mark_exists() result_third = django_testdir.runpytest_subprocess('-v', '--reuse-db', '--create-db') assert result_third.ret == 0 result_third.stdout.fnmatch_lines([ "*test_db_can_be_accessed PASSED*", ]) # Make sure the database has been re-created and the mark is gone assert not mark_exists() class TestSqlite: db_settings = {'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db_name', 'TEST': { 'NAME': 'test_custom_db_name' } }} def test_sqlite_test_name_used(self, django_testdir): django_testdir.create_test_module(''' import pytest from django.db import connections from django import VERSION @pytest.mark.django_db def test_a(): (conn, ) = connections.all() assert conn.vendor == 'sqlite' print(conn.settings_dict) assert conn.settings_dict['NAME'] == 'test_custom_db_name' ''') result = django_testdir.runpytest_subprocess('--tb=short', '-v') assert result.ret == 0 result.stdout.fnmatch_lines(['*test_a*PASSED*']) def test_xdist_with_reuse(django_testdir): skip_if_sqlite_in_memory() drop_database('gw0') drop_database('gw1') django_testdir.create_test_module(''' import pytest from .app.models import Item def _check(settings): # Make sure that the database name looks correct db_name = settings.DATABASES['default']['NAME'] assert db_name.endswith('_gw0') or db_name.endswith('_gw1') assert Item.objects.count() == 0 Item.objects.create(name='foo') assert Item.objects.count() == 1 @pytest.mark.django_db def test_a(settings): _check(settings) @pytest.mark.django_db def test_b(settings): _check(settings) @pytest.mark.django_db def test_c(settings): _check(settings) @pytest.mark.django_db def test_d(settings): _check(settings) ''') result = django_testdir.runpytest_subprocess('-vv', '-n2', '-s', '--reuse-db') assert result.ret == 0 result.stdout.fnmatch_lines(['*PASSED*test_a*']) result.stdout.fnmatch_lines(['*PASSED*test_b*']) result.stdout.fnmatch_lines(['*PASSED*test_c*']) result.stdout.fnmatch_lines(['*PASSED*test_d*']) assert db_exists('gw0') assert db_exists('gw1') result = django_testdir.runpytest_subprocess('-vv', '-n2', '-s', '--reuse-db') assert result.ret == 0 result.stdout.fnmatch_lines(['*PASSED*test_a*']) result.stdout.fnmatch_lines(['*PASSED*test_b*']) result.stdout.fnmatch_lines(['*PASSED*test_c*']) result.stdout.fnmatch_lines(['*PASSED*test_d*']) result = django_testdir.runpytest_subprocess('-vv', '-n2', '-s', '--reuse-db', '--create-db') assert result.ret == 0 result.stdout.fnmatch_lines(['*PASSED*test_a*']) result.stdout.fnmatch_lines(['*PASSED*test_b*']) result.stdout.fnmatch_lines(['*PASSED*test_c*']) result.stdout.fnmatch_lines(['*PASSED*test_d*']) class TestSqliteWithXdist: db_settings = {'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '/tmp/should-not-be-used', }} def test_sqlite_in_memory_used(self, django_testdir): django_testdir.create_test_module(''' import pytest from django.db import connections @pytest.mark.django_db def test_a(): (conn, ) = connections.all() assert conn.vendor == 'sqlite' db_name = conn.creation._get_test_db_name() assert 'file:memorydb' in db_name or db_name == ':memory:' ''') result = django_testdir.runpytest_subprocess('--tb=short', '-vv', '-n1') assert result.ret == 0 result.stdout.fnmatch_lines(['*PASSED*test_a*']) @pytest.mark.skipif(get_django_version() >= (1, 9), reason=('Django 1.9 requires migration and has no concept ' 'of initial data fixtures')) def test_initial_data(django_testdir_initial): """Test that initial data gets loaded.""" django_testdir_initial.create_test_module(''' import pytest from .app.models import Item @pytest.mark.django_db def test_inner(): assert [x.name for x in Item.objects.all()] \ == ["mark_initial_data"] ''') result = django_testdir_initial.runpytest_subprocess('--tb=short', '-v') assert result.ret == 0 result.stdout.fnmatch_lines(['*test_inner*PASSED*']) class TestNativeMigrations(object): """ Tests for Django 1.7 Migrations """ def test_no_migrations(self, django_testdir): django_testdir.create_test_module(''' import pytest @pytest.mark.django_db def test_inner_migrations(): pass ''') migration_file = django_testdir.project_root.join("tpkg/app/migrations/0001_initial.py") assert migration_file.isfile() migration_file.write('raise Exception("This should not get imported.")', ensure=True) result = django_testdir.runpytest_subprocess('--nomigrations', '--tb=short', '-v') assert result.ret == 0 result.stdout.fnmatch_lines(['*test_inner_migrations*PASSED*']) def test_migrations_run(self, django_testdir): testdir = django_testdir testdir.create_test_module(''' import pytest @pytest.mark.django_db def test_inner_migrations(): pass ''') testdir.create_app_file(""" from django.db import migrations, models def print_it(apps, schema_editor): print("mark_migrations_run") class Migration(migrations.Migration): dependencies = [] operations = [ migrations.CreateModel( name='Item', fields=[ ('id', models.AutoField(serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=100)), ], options={ }, bases=(models.Model,), ), migrations.RunPython( print_it, ), ] """, 'migrations/0001_initial.py') result = testdir.runpytest_subprocess('--tb=short', '-v', '-s') assert result.ret == 0 result.stdout.fnmatch_lines(['*mark_migrations_run*']) result = testdir.runpytest_subprocess('--no-migrations', '--migrations', '--tb=short', '-v', '-s') assert result.ret == 0 result.stdout.fnmatch_lines(['*mark_migrations_run*']) pytest-django-3.1.2/tests/test_django_configurations.py000066400000000000000000000057441301551737600234560ustar00rootroot00000000000000"""Tests which check the various ways you can set DJANGO_SETTINGS_MODULE If these tests fail you probably forgot to install django-configurations. """ import pytest pytest.importorskip('configurations') try: import configurations.importer configurations except ImportError as e: if 'LaxOptionParser' in e.args[0]: pytest.skip('This version of django-configurations is incompatible with Django: ' # noqa 'https://github.com/jezdez/django-configurations/issues/65') # noqa BARE_SETTINGS = ''' from configurations import Settings class MySettings(Settings): # At least one database must be configured DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:' }, } SECRET_KEY = 'foobar' ''' def test_dc_env(testdir, monkeypatch): monkeypatch.setenv('DJANGO_SETTINGS_MODULE', 'tpkg.settings_env') monkeypatch.setenv('DJANGO_CONFIGURATION', 'MySettings') pkg = testdir.mkpydir('tpkg') settings = pkg.join('settings_env.py') settings.write(BARE_SETTINGS) testdir.makepyfile(""" import os def test_settings(): assert os.environ['DJANGO_SETTINGS_MODULE'] == 'tpkg.settings_env' assert os.environ['DJANGO_CONFIGURATION'] == 'MySettings' """) result = testdir.runpytest_subprocess() result.stdout.fnmatch_lines(['*1 passed*']) assert result.ret == 0 def test_dc_ini(testdir, monkeypatch): monkeypatch.setenv('DJANGO_SETTINGS_MODULE', 'tpkg.settings_env') monkeypatch.setenv('DJANGO_CONFIGURATION', 'MySettings') testdir.makeini(""" [pytest] DJANGO_SETTINGS_MODULE = DO_NOT_USE_ini DJANGO_CONFIGURATION = DO_NOT_USE_ini """) pkg = testdir.mkpydir('tpkg') settings = pkg.join('settings_env.py') settings.write(BARE_SETTINGS) testdir.makepyfile(""" import os def test_ds(): assert os.environ['DJANGO_SETTINGS_MODULE'] == 'tpkg.settings_env' assert os.environ['DJANGO_CONFIGURATION'] == 'MySettings' """) result = testdir.runpytest_subprocess() result.stdout.fnmatch_lines(['*1 passed*']) assert result.ret == 0 def test_dc_option(testdir, monkeypatch): monkeypatch.setenv('DJANGO_SETTINGS_MODULE', 'DO_NOT_USE_env') monkeypatch.setenv('DJANGO_CONFIGURATION', 'DO_NOT_USE_env') testdir.makeini(""" [pytest] DJANGO_SETTINGS_MODULE = DO_NOT_USE_ini DJANGO_CONFIGURATION = DO_NOT_USE_ini """) pkg = testdir.mkpydir('tpkg') settings = pkg.join('settings_opt.py') settings.write(BARE_SETTINGS) testdir.makepyfile(""" import os def test_ds(): assert os.environ['DJANGO_SETTINGS_MODULE'] == 'tpkg.settings_opt' assert os.environ['DJANGO_CONFIGURATION'] == 'MySettings' """) result = testdir.runpytest_subprocess('--ds=tpkg.settings_opt', '--dc=MySettings') result.stdout.fnmatch_lines(['*1 passed*']) assert result.ret == 0 pytest-django-3.1.2/tests/test_django_settings_module.py000066400000000000000000000262661301551737600236330ustar00rootroot00000000000000"""Tests which check the various ways you can set DJANGO_SETTINGS_MODULE If these tests fail you probably forgot to run "python setup.py develop". """ import django import pytest BARE_SETTINGS = ''' # At least one database must be configured DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:' }, } SECRET_KEY = 'foobar' ''' def test_ds_ini(testdir, monkeypatch): monkeypatch.delenv('DJANGO_SETTINGS_MODULE') testdir.makeini(""" [pytest] DJANGO_SETTINGS_MODULE = tpkg.settings_ini """) pkg = testdir.mkpydir('tpkg') pkg.join('settings_ini.py').write(BARE_SETTINGS) testdir.makepyfile(""" import os def test_ds(): assert os.environ['DJANGO_SETTINGS_MODULE'] == 'tpkg.settings_ini' """) result = testdir.runpytest_subprocess() assert result.parseoutcomes()['passed'] == 1 result.stdout.fnmatch_lines(['Django settings: tpkg.settings_ini ' '(from ini file)*']) assert result.ret == 0 def test_ds_env(testdir, monkeypatch): monkeypatch.setenv('DJANGO_SETTINGS_MODULE', 'tpkg.settings_env') pkg = testdir.mkpydir('tpkg') settings = pkg.join('settings_env.py') settings.write(BARE_SETTINGS) testdir.makepyfile(""" import os def test_settings(): assert os.environ['DJANGO_SETTINGS_MODULE'] == 'tpkg.settings_env' """) result = testdir.runpytest_subprocess() result.stdout.fnmatch_lines(['Django settings: tpkg.settings_env (from ' 'environment variable)*']) assert result.parseoutcomes()['passed'] == 1 def test_ds_option(testdir, monkeypatch): monkeypatch.setenv('DJANGO_SETTINGS_MODULE', 'DO_NOT_USE_env') testdir.makeini(""" [pytest] DJANGO_SETTINGS_MODULE = DO_NOT_USE_ini """) pkg = testdir.mkpydir('tpkg') settings = pkg.join('settings_opt.py') settings.write(BARE_SETTINGS) testdir.makepyfile(""" import os def test_ds(): assert os.environ['DJANGO_SETTINGS_MODULE'] == 'tpkg.settings_opt' """) result = testdir.runpytest_subprocess('--ds=tpkg.settings_opt') result.stdout.fnmatch_lines(['Django settings: tpkg.settings_opt ' '(from command line option)']) assert result.parseoutcomes()['passed'] == 1 def test_ds_env_override_ini(testdir, monkeypatch): "DSM env should override ini." monkeypatch.setenv('DJANGO_SETTINGS_MODULE', 'tpkg.settings_env') testdir.makeini("""\ [pytest] DJANGO_SETTINGS_MODULE = DO_NOT_USE_ini """) pkg = testdir.mkpydir('tpkg') settings = pkg.join('settings_env.py') settings.write(BARE_SETTINGS) testdir.makepyfile(""" import os def test_ds(): assert os.environ['DJANGO_SETTINGS_MODULE'] == 'tpkg.settings_env' """) result = testdir.runpytest_subprocess() assert result.parseoutcomes()['passed'] == 1 assert result.ret == 0 def test_ds_non_existent(testdir, monkeypatch): """ Make sure we do not fail with INTERNALERROR if an incorrect DJANGO_SETTINGS_MODULE is given. """ monkeypatch.setenv('DJANGO_SETTINGS_MODULE', 'DOES_NOT_EXIST') testdir.makepyfile('def test_ds(): pass') result = testdir.runpytest_subprocess() result.stderr.fnmatch_lines(["*ImportError:*DOES_NOT_EXIST*"]) assert result.ret != 0 def test_ds_after_user_conftest(testdir, monkeypatch): """ Test that the settings module can be imported, after pytest has adjusted the sys.path. """ monkeypatch.setenv('DJANGO_SETTINGS_MODULE', 'settings_after_conftest') testdir.makepyfile('def test_ds(): pass') testdir.makepyfile(settings_after_conftest="SECRET_KEY='secret'") # testdir.makeconftest("import sys; print(sys.path)") result = testdir.runpytest_subprocess('-v') result.stdout.fnmatch_lines(['*1 passed*']) assert result.ret == 0 def test_ds_in_pytest_configure(testdir, monkeypatch): monkeypatch.delenv('DJANGO_SETTINGS_MODULE') pkg = testdir.mkpydir('tpkg') settings = pkg.join('settings_ds.py') settings.write(BARE_SETTINGS) testdir.makeconftest(""" import os from django.conf import settings def pytest_configure(): if not settings.configured: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tpkg.settings_ds') """) testdir.makepyfile(""" def test_anything(): pass """) r = testdir.runpytest_subprocess() assert r.parseoutcomes()['passed'] == 1 assert r.ret == 0 def test_django_settings_configure(testdir, monkeypatch): """ Make sure Django can be configured without setting DJANGO_SETTINGS_MODULE altogether, relying on calling django.conf.settings.configure() and then invoking pytest. """ monkeypatch.delenv('DJANGO_SETTINGS_MODULE') p = testdir.makepyfile(run=""" from django.conf import settings settings.configure(SECRET_KEY='set from settings.configure()', DATABASES={'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:' }}, INSTALLED_APPS=['django.contrib.auth', 'django.contrib.contenttypes',]) import pytest pytest.main() """) testdir.makepyfile(""" import pytest from django.conf import settings from django.test.client import RequestFactory from django.test import TestCase from django.contrib.auth.models import User def test_access_to_setting(): assert settings.SECRET_KEY == 'set from settings.configure()' # This test requires Django to be properly configured to be run def test_rf(rf): assert isinstance(rf, RequestFactory) # This tests that pytest-django actually configures the database # according to the settings above class ATestCase(TestCase): def test_user_count(self): assert User.objects.count() == 0 @pytest.mark.django_db def test_user_count(): assert User.objects.count() == 0 """) result = testdir.runpython(p) result.stdout.fnmatch_lines([ "*4 passed*", ]) def test_settings_in_hook(testdir, monkeypatch): monkeypatch.delenv('DJANGO_SETTINGS_MODULE') testdir.makeconftest(""" from django.conf import settings def pytest_configure(): settings.configure(SECRET_KEY='set from pytest_configure', DATABASES={'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}}, INSTALLED_APPS=['django.contrib.auth', 'django.contrib.contenttypes',]) """) testdir.makepyfile(""" import pytest from django.conf import settings from django.contrib.auth.models import User def test_access_to_setting(): assert settings.SECRET_KEY == 'set from pytest_configure' @pytest.mark.django_db def test_user_count(): assert User.objects.count() == 0 """) r = testdir.runpytest_subprocess() assert r.ret == 0 def test_django_not_loaded_without_settings(testdir, monkeypatch): """ Make sure Django is not imported at all if no Django settings is specified. """ monkeypatch.delenv('DJANGO_SETTINGS_MODULE') testdir.makepyfile(""" import sys def test_settings(): assert 'django' not in sys.modules """) result = testdir.runpytest_subprocess() result.stdout.fnmatch_lines(['*1 passed*']) assert result.ret == 0 def test_debug_false(testdir, monkeypatch): monkeypatch.delenv('DJANGO_SETTINGS_MODULE') testdir.makeconftest(""" from django.conf import settings def pytest_configure(): settings.configure(SECRET_KEY='set from pytest_configure', DEBUG=True, DATABASES={'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}}, INSTALLED_APPS=['django.contrib.auth', 'django.contrib.contenttypes',]) """) testdir.makepyfile(""" from django.conf import settings def test_debug_is_false(): assert settings.DEBUG is False """) r = testdir.runpytest_subprocess() assert r.ret == 0 @pytest.mark.skipif(not hasattr(django, 'setup'), reason="This Django version does not support app loading") @pytest.mark.django_project(extra_settings=""" INSTALLED_APPS = [ 'tpkg.app.apps.TestApp', ] """) def test_django_setup_sequence(django_testdir): django_testdir.create_app_file(""" from django.apps import apps, AppConfig class TestApp(AppConfig): name = 'tpkg.app' def ready(self): print ('READY(): populating=%r' % apps._lock.locked()) """, 'apps.py') django_testdir.create_app_file(""" from django.apps import apps print ('IMPORT: populating=%r,ready=%r' % ( apps._lock.locked(), apps.ready)) SOME_THING = 1234 """, 'models.py') django_testdir.create_app_file("", '__init__.py') django_testdir.makepyfile(""" from django.apps import apps from tpkg.app.models import SOME_THING def test_anything(): print ('TEST: populating=%r,ready=%r' % ( apps._lock.locked(), apps.ready)) """) result = django_testdir.runpytest_subprocess('-s', '--tb=line') result.stdout.fnmatch_lines(['*IMPORT: populating=True,ready=False*']) result.stdout.fnmatch_lines(['*READY(): populating=True*']) result.stdout.fnmatch_lines(['*TEST: populating=False,ready=True*']) assert result.ret == 0 def test_no_ds_but_django_imported(testdir, monkeypatch): """pytest-django should not bail out, if "django" has been imported somewhere, e.g. via pytest-splinter.""" monkeypatch.delenv('DJANGO_SETTINGS_MODULE') testdir.makepyfile(""" import os import django from pytest_django.lazy_django import django_settings_is_configured def test_django_settings_is_configured(): assert django_settings_is_configured() is False def test_env(): assert 'DJANGO_SETTINGS_MODULE' not in os.environ def test_cfg(pytestconfig): assert pytestconfig.option.ds is None """) r = testdir.runpytest_subprocess('-s') assert r.ret == 0 def test_no_django_settings_but_django_imported(testdir, monkeypatch): """Make sure we do not crash when Django happens to be imported, but settings is not properly configured""" monkeypatch.delenv('DJANGO_SETTINGS_MODULE') testdir.makeconftest('import django') r = testdir.runpytest_subprocess('--help') assert r.ret == 0 pytest-django-3.1.2/tests/test_doctest.txt000066400000000000000000000001201301551737600207150ustar00rootroot00000000000000This doctest should run without problems with pytest. >>> print('works') works pytest-django-3.1.2/tests/test_environment.py000066400000000000000000000170471301551737600214450ustar00rootroot00000000000000from __future__ import with_statement import os import pytest from django.contrib.sites.models import Site from django.contrib.sites import models as site_models from django.core import mail from django.db import connection from django.test import TestCase from pytest_django.lazy_django import get_django_version from pytest_django_test.app.models import Item # It doesn't matter which order all the _again methods are run, we just need # to check the environment remains constant. # This is possible with some of the testdir magic, but this is the lazy way # to do it. @pytest.mark.parametrize('subject', ['subject1', 'subject2']) def test_autoclear_mailbox(subject): assert len(mail.outbox) == 0 mail.send_mail(subject, 'body', 'from@example.com', ['to@example.com']) assert len(mail.outbox) == 1 m = mail.outbox[0] assert m.subject == subject assert m.body == 'body' assert m.from_email == 'from@example.com' assert m.to == ['to@example.com'] class TestDirectAccessWorksForDjangoTestCase(TestCase): def _do_test(self): assert len(mail.outbox) == 0 mail.send_mail('subject', 'body', 'from@example.com', ['to@example.com']) assert len(mail.outbox) == 1 def test_one(self): self._do_test() def test_two(self): self._do_test() @pytest.mark.django_project(extra_settings=""" TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) ROOT_URLCONF = 'tpkg.app.urls' """) def test_invalid_template_variable(django_testdir): django_testdir.create_app_file(""" from django.conf.urls import url from pytest_django_test.compat import patterns from tpkg.app import views urlpatterns = patterns( '', url(r'invalid_template/', views.invalid_template), ) """, 'urls.py') django_testdir.create_app_file(""" from django.shortcuts import render def invalid_template(request): return render(request, 'invalid_template.html', {}) """, 'views.py') django_testdir.create_app_file( "
{{ invalid_var }}
", 'templates/invalid_template.html' ) django_testdir.create_test_module(''' import pytest def test_for_invalid_template(client): client.get('/invalid_template/') @pytest.mark.ignore_template_errors def test_ignore(client): client.get('/invalid_template/') ''') result = django_testdir.runpytest_subprocess('-s', '--fail-on-template-vars') result.stdout.fnmatch_lines_random([ "tpkg/test_the_test.py F.", "Undefined template variable 'invalid_var' in 'invalid_template.html'", ]) @pytest.mark.django_project(extra_settings=""" TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) ROOT_URLCONF = 'tpkg.app.urls' """) def test_invalid_template_variable_opt_in(django_testdir): django_testdir.create_app_file(""" from django.conf.urls import url from pytest_django_test.compat import patterns from tpkg.app import views urlpatterns = patterns( '', url(r'invalid_template/', views.invalid_template), ) """, 'urls.py') django_testdir.create_app_file(""" from django.shortcuts import render def invalid_template(request): return render(request, 'invalid_template.html', {}) """, 'views.py') django_testdir.create_app_file( "
{{ invalid_var }}
", 'templates/invalid_template.html' ) django_testdir.create_test_module(''' import pytest def test_for_invalid_template(client): client.get('/invalid_template/') @pytest.mark.ignore_template_errors def test_ignore(client): client.get('/invalid_template/') ''') result = django_testdir.runpytest_subprocess('-s') result.stdout.fnmatch_lines_random([ "tpkg/test_the_test.py ..", ]) @pytest.mark.django_db def test_database_rollback(): assert Item.objects.count() == 0 Item.objects.create(name='blah') assert Item.objects.count() == 1 @pytest.mark.django_db def test_database_rollback_again(): test_database_rollback() @pytest.mark.django_db def test_database_name(): dirname, name = os.path.split(connection.settings_dict['NAME']) assert 'file:memorydb' in name or name == ':memory:' or name.startswith('test_') def test_database_noaccess(): with pytest.raises(pytest.fail.Exception): Item.objects.count() class TestrunnerVerbosity: """Test that Django's code to setup and teardown the databases uses pytest's verbosity level.""" @pytest.fixture def testdir(self, django_testdir): print("testdir") django_testdir.create_test_module(''' import pytest @pytest.mark.django_db def test_inner_testrunner(): pass ''') return django_testdir def test_default(self, testdir): """Not verbose by default.""" result = testdir.runpytest_subprocess('-s') result.stdout.fnmatch_lines([ "tpkg/test_the_test.py ."]) def test_vq_verbosity_0(self, testdir): """-v and -q results in verbosity 0.""" result = testdir.runpytest_subprocess('-s', '-v', '-q') result.stdout.fnmatch_lines([ "tpkg/test_the_test.py ."]) def test_verbose_with_v(self, testdir): """Verbose output with '-v'.""" result = testdir.runpytest_subprocess('-s', '-v') result.stdout.fnmatch_lines_random([ "tpkg/test_the_test.py:*", "*PASSED*", "*Destroying test database for alias 'default'...*"]) def test_more_verbose_with_vv(self, testdir): """More verbose output with '-v -v'.""" result = testdir.runpytest_subprocess('-s', '-v', '-v') result.stdout.fnmatch_lines([ "tpkg/test_the_test.py:*Creating test database for alias*", '*Operations to perform:*', "*Apply all migrations:*", "*PASSED*Destroying test database for alias 'default' ('*')...*"]) def test_more_verbose_with_vv_and_reusedb(self, testdir): """More verbose output with '-v -v', and --create-db.""" result = testdir.runpytest_subprocess('-s', '-v', '-v', '--create-db') result.stdout.fnmatch_lines([ "tpkg/test_the_test.py:*Creating test database for alias*", "*PASSED*"]) assert ("*Destroying test database for alias 'default' ('*')...*" not in result.stdout.str()) @pytest.mark.skipif( get_django_version() < (1, 8), reason='Django 1.7 requires settings.SITE_ID to be set, so this test is invalid' ) @pytest.mark.django_db @pytest.mark.parametrize('site_name', ['site1', 'site2']) def test_clear_site_cache(site_name, rf, monkeypatch): request = rf.get('/') monkeypatch.setattr(request, 'get_host', lambda: 'foo.com') Site.objects.create(domain='foo.com', name=site_name) assert Site.objects.get_current(request=request).name == site_name @pytest.mark.django_db @pytest.mark.parametrize('site_name', ['site1', 'site2']) def test_clear_site_cache_check_site_cache_size(site_name, settings): assert len(site_models.SITE_CACHE) == 0 site = Site.objects.create(domain='foo.com', name=site_name) settings.SITE_ID = site.id assert Site.objects.get_current() == site assert len(site_models.SITE_CACHE) == 1 pytest-django-3.1.2/tests/test_fixtures.py000066400000000000000000000374641301551737600207570ustar00rootroot00000000000000"""Tests for user-visible fixtures. Not quite all fixtures are tested here, the db and transactional_db fixtures are tested in test_database. """ from __future__ import with_statement import pytest from django.db import connection from django.conf import settings as real_settings from django.core import mail from django.test.client import Client, RequestFactory from django.test.testcases import connections_support_transactions from django.utils.encoding import force_text from pytest_django.lazy_django import get_django_version from pytest_django_test.app.models import Item from pytest_django_test.compat import HTTPError, urlopen def test_client(client): assert isinstance(client, Client) @pytest.mark.django_db def test_admin_client(admin_client): assert isinstance(admin_client, Client) resp = admin_client.get('/admin-required/') assert force_text(resp.content) == 'You are an admin' def test_admin_client_no_db_marker(admin_client): assert isinstance(admin_client, Client) resp = admin_client.get('/admin-required/') assert force_text(resp.content) == 'You are an admin' @pytest.mark.django_db def test_admin_user(admin_user, django_user_model): assert isinstance(admin_user, django_user_model) def test_admin_user_no_db_marker(admin_user, django_user_model): assert isinstance(admin_user, django_user_model) def test_rf(rf): assert isinstance(rf, RequestFactory) class TestSettings: """Tests for the settings fixture, order matters""" def test_modify_existing(self, settings): assert settings.SECRET_KEY == 'foobar' assert real_settings.SECRET_KEY == 'foobar' settings.SECRET_KEY = 'spam' assert settings.SECRET_KEY == 'spam' assert real_settings.SECRET_KEY == 'spam' def test_modify_existing_again(self, settings): assert settings.SECRET_KEY == 'foobar' assert real_settings.SECRET_KEY == 'foobar' def test_new(self, settings): assert not hasattr(settings, 'SPAM') assert not hasattr(real_settings, 'SPAM') settings.SPAM = 'ham' assert settings.SPAM == 'ham' assert real_settings.SPAM == 'ham' def test_new_again(self, settings): assert not hasattr(settings, 'SPAM') assert not hasattr(real_settings, 'SPAM') def test_deleted(self, settings): assert hasattr(settings, 'SECRET_KEY') assert hasattr(real_settings, 'SECRET_KEY') del settings.SECRET_KEY assert not hasattr(settings, 'SECRET_KEY') assert not hasattr(real_settings, 'SECRET_KEY') def test_deleted_again(self, settings): assert hasattr(settings, 'SECRET_KEY') assert hasattr(real_settings, 'SECRET_KEY') def test_signals(self, settings): result = [] def assert_signal(signal, sender, setting, value, enter): result.append((setting, value, enter)) from django.test.signals import setting_changed setting_changed.connect(assert_signal) result = [] settings.SECRET_KEY = 'change 1' settings.SECRET_KEY = 'change 2' assert result == [ ('SECRET_KEY', 'change 1', True), ('SECRET_KEY', 'change 2', True), ] result = [] settings.FOOBAR = 'abc123' assert sorted(result) == [ ('FOOBAR', 'abc123', True), ] def test_modification_signal(self, django_testdir): django_testdir.create_test_module(""" import pytest from django.conf import settings from django.test.signals import setting_changed @pytest.fixture(autouse=True, scope='session') def settings_change_printer(): def receiver(sender, **kwargs): fmt_dict = {'actual_value': getattr(settings, kwargs['setting'], '<>')} fmt_dict.update(kwargs) print('Setting changed: ' 'enter=%(enter)s,setting=%(setting)s,' 'value=%(value)s,actual_value=%(actual_value)s' % fmt_dict) setting_changed.connect(receiver, weak=False) def test_set(settings): settings.SECRET_KEY = 'change 1' settings.SECRET_KEY = 'change 2' def test_set_non_existent(settings): settings.FOOBAR = 'abc123' """) result = django_testdir.runpytest_subprocess('--tb=short', '-v', '-s') # test_set result.stdout.fnmatch_lines([ '*Setting changed: enter=True,setting=SECRET_KEY,value=change 1*', '*Setting changed: enter=True,setting=SECRET_KEY,value=change 2*', '*Setting changed: enter=False,setting=SECRET_KEY,value=change 1*', '*Setting changed: enter=False,setting=SECRET_KEY,value=foobar*', ]) result.stdout.fnmatch_lines([ '*Setting changed: enter=True,setting=FOOBAR,value=abc123*', ('*Setting changed: enter=False,setting=FOOBAR,value=None,' 'actual_value=<>*'), ]) class TestLiveServer: def test_url(self, live_server): assert live_server.url == force_text(live_server) def test_transactions(self, live_server): if not connections_support_transactions(): pytest.skip('transactions required for this test') assert not connection.in_atomic_block def test_db_changes_visibility(self, live_server): response_data = urlopen(live_server + '/item_count/').read() assert force_text(response_data) == 'Item count: 0' Item.objects.create(name='foo') response_data = urlopen(live_server + '/item_count/').read() assert force_text(response_data) == 'Item count: 1' def test_fixture_db(self, db, live_server): Item.objects.create(name='foo') response_data = urlopen(live_server + '/item_count/').read() assert force_text(response_data) == 'Item count: 1' def test_fixture_transactional_db(self, transactional_db, live_server): Item.objects.create(name='foo') response_data = urlopen(live_server + '/item_count/').read() assert force_text(response_data) == 'Item count: 1' @pytest.fixture def item(self): # This has not requested database access explicitly, but the # live_server fixture auto-uses the transactional_db fixture. Item.objects.create(name='foo') def test_item(self, item, live_server): pass @pytest.fixture def item_db(self, db): return Item.objects.create(name='foo') def test_item_db(self, item_db, live_server): response_data = urlopen(live_server + '/item_count/').read() assert force_text(response_data) == 'Item count: 1' @pytest.fixture def item_transactional_db(self, transactional_db): return Item.objects.create(name='foo') def test_item_transactional_db(self, item_transactional_db, live_server): response_data = urlopen(live_server + '/item_count/').read() assert force_text(response_data) == 'Item count: 1' @pytest.mark.django_project(extra_settings=""" INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.staticfiles', 'tpkg.app', ] STATIC_URL = '/static/' """) def test_serve_static_with_staticfiles_app(self, django_testdir, settings): """ LiveServer always serves statics with ``django.contrib.staticfiles`` handler. """ django_testdir.create_test_module(""" import pytest from django.utils.encoding import force_text try: from urllib2 import urlopen, HTTPError except ImportError: from urllib.request import urlopen, HTTPError class TestLiveServer: def test_a(self, live_server, settings): assert ('django.contrib.staticfiles' in settings.INSTALLED_APPS) response_data = urlopen( live_server + '/static/a_file.txt').read() assert force_text(response_data) == 'bla\\n' """) result = django_testdir.runpytest_subprocess('--tb=short', '-v') result.stdout.fnmatch_lines(['*test_a*PASSED*']) assert result.ret == 0 @pytest.mark.skipif(get_django_version() < (1, 7), reason="Django >= 1.7 required") def test_serve_static_dj17_without_staticfiles_app(self, live_server, settings): """ Because ``django.contrib.staticfiles`` is not installed LiveServer can not serve statics with django >= 1.7 . """ with pytest.raises(HTTPError): urlopen(live_server + '/static/a_file.txt').read() @pytest.mark.skipif(get_django_version() < (1, 11), reason='Django >= 1.11 required') def test_specified_port_error_message_django_111(self, django_testdir): django_testdir.create_test_module(""" def test_with_live_server(live_server): pass """) result = django_testdir.runpytest_subprocess('--liveserver=localhost:1234') result.stdout.fnmatch_lines([ '*Specifying a live server port is not supported in Django 1.11. This ' 'will be an error in a future pytest-django release.*' ]) @pytest.mark.django_project(extra_settings=""" AUTH_USER_MODEL = 'app.MyCustomUser' INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'tpkg.app', ] ROOT_URLCONF = 'tpkg.app.urls' """) def test_custom_user_model(django_testdir): django_testdir.create_app_file(""" from django.contrib.auth.models import AbstractUser from django.db import models class MyCustomUser(AbstractUser): identifier = models.CharField(unique=True, max_length=100) USERNAME_FIELD = 'identifier' """, 'models.py') django_testdir.create_app_file(""" from django.conf.urls import url from pytest_django_test.compat import patterns from tpkg.app import views urlpatterns = patterns( '', url(r'admin-required/', views.admin_required_view), ) """, 'urls.py') django_testdir.create_app_file(""" from django.http import HttpResponse from django.template import Template from django.template.context import Context def admin_required_view(request): if request.user.is_staff: return HttpResponse( Template('You are an admin').render(Context())) return HttpResponse( Template('Access denied').render(Context())) """, 'views.py') django_testdir.makepyfile(""" from django.utils.encoding import force_text from tpkg.app.models import MyCustomUser def test_custom_user_model(admin_client): resp = admin_client.get('/admin-required/') assert force_text(resp.content) == 'You are an admin' """) django_testdir.create_app_file('', 'migrations/__init__.py') django_testdir.create_app_file(""" # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone import django.core.validators class Migration(migrations.Migration): dependencies = [ ('auth', '0001_initial'), ('app', '0001_initial'), ] operations = [ migrations.CreateModel( name='MyCustomUser', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(null=True, verbose_name='last login', blank=True)), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, max_length=30, validators=[django.core.validators.RegexValidator('^[\\w.@+-]+$', 'Enter a valid username. This value may contain only letters, numbers and @/./+/-/_ characters.', 'invalid')], help_text='Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.', unique=True, verbose_name='username')), ('first_name', models.CharField(max_length=30, verbose_name='first name', blank=True)), ('last_name', models.CharField(max_length=30, verbose_name='last name', blank=True)), ('email', models.EmailField(max_length=254, verbose_name='email address', blank=True)), ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), ('identifier', models.CharField(unique=True, max_length=100)), ('groups', models.ManyToManyField(related_query_name='user', related_name='user_set', to='auth.Group', blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', verbose_name='groups')), ('user_permissions', models.ManyToManyField(related_query_name='user', related_name='user_set', to='auth.Permission', blank=True, help_text='Specific permissions for this user.', verbose_name='user permissions')), ], options={ 'abstract': False, 'verbose_name': 'user', 'verbose_name_plural': 'users', }, bases=None, ), ] """, 'migrations/0002_custom_user_model.py') # noqa result = django_testdir.runpytest_subprocess('-s') result.stdout.fnmatch_lines(['*1 passed*']) assert result.ret == 0 class Test_django_db_blocker: @pytest.mark.django_db def test_block_manually(self, django_db_blocker): try: django_db_blocker.block() with pytest.raises(pytest.fail.Exception): Item.objects.exists() finally: django_db_blocker.restore() @pytest.mark.django_db def test_block_with_block(self, django_db_blocker): with django_db_blocker.block(): with pytest.raises(pytest.fail.Exception): Item.objects.exists() def test_unblock_manually(self, django_db_blocker): try: django_db_blocker.unblock() Item.objects.exists() finally: django_db_blocker.restore() def test_unblock_with_block(self, django_db_blocker): with django_db_blocker.unblock(): Item.objects.exists() def test_mail(mailoutbox): assert mailoutbox is mail.outbox # check that mail.outbox and fixture value is same object assert len(mailoutbox) == 0 mail.send_mail('subject', 'body', 'from@example.com', ['to@example.com']) assert len(mailoutbox) == 1 m = mailoutbox[0] assert m.subject == 'subject' assert m.body == 'body' assert m.from_email == 'from@example.com' assert list(m.to) == ['to@example.com'] def test_mail_again(mailoutbox): test_mail(mailoutbox) pytest-django-3.1.2/tests/test_manage_py_scan.py000066400000000000000000000051311301551737600220340ustar00rootroot00000000000000import pytest @pytest.mark.django_project(project_root='django_project_root', create_manage_py=True) def test_django_project_found(django_testdir): # XXX: Important: Do not chdir() to django_project_root since runpytest_subprocess # will call "python /path/to/pytest.py", which will impliclity add cwd to # the path. By instead calling "python /path/to/pytest.py # django_project_root", we avoid impliclity adding the project to sys.path # This matches the behaviour when pytest is called directly as an # executable (cwd is not added to the Python path) django_testdir.create_test_module(""" def test_foobar(): assert 1 + 1 == 2 """) result = django_testdir.runpytest_subprocess('django_project_root') assert result.ret == 0 outcomes = result.parseoutcomes() assert outcomes['passed'] == 1 @pytest.mark.django_project(project_root='django_project_root', create_manage_py=True) def test_django_project_found_invalid_settings(django_testdir, monkeypatch): monkeypatch.setenv('DJANGO_SETTINGS_MODULE', 'DOES_NOT_EXIST') result = django_testdir.runpytest_subprocess('django_project_root') assert result.ret != 0 result.stderr.fnmatch_lines(['*ImportError:*DOES_NOT_EXIST*']) result.stderr.fnmatch_lines(['*pytest-django found a Django project*']) def test_django_project_scan_disabled_invalid_settings(django_testdir, monkeypatch): monkeypatch.setenv('DJANGO_SETTINGS_MODULE', 'DOES_NOT_EXIST') django_testdir.makeini(''' [pytest] django_find_project = false ''') result = django_testdir.runpytest_subprocess('django_project_root') assert result.ret != 0 result.stderr.fnmatch_lines(['*ImportError*DOES_NOT_EXIST*']) result.stderr.fnmatch_lines(['*pytest-django did not search for ' 'Django projects*']) @pytest.mark.django_project(project_root='django_project_root', create_manage_py=True) def test_django_project_found_invalid_settings_version(django_testdir, monkeypatch): """Invalid DSM should not cause an error with --help or --version.""" monkeypatch.setenv('DJANGO_SETTINGS_MODULE', 'DOES_NOT_EXIST') result = django_testdir.runpytest_subprocess('django_project_root', '--version') assert result.ret == 0 result.stderr.fnmatch_lines(['*This is pytest version*']) result = django_testdir.runpytest_subprocess('django_project_root', '--help') assert result.ret == 0 result.stdout.fnmatch_lines(['*usage:*']) pytest-django-3.1.2/tests/test_unittest.py000066400000000000000000000202031301551737600207440ustar00rootroot00000000000000import pytest from django.test import TestCase from pytest_django_test.app.models import Item class TestFixtures(TestCase): fixtures = ['items'] def test_fixtures(self): assert Item.objects.count() == 1 assert Item.objects.get().name == 'Fixture item' def test_fixtures_again(self): """Ensure fixtures are only loaded once.""" self.test_fixtures() class TestSetup(TestCase): def setUp(self): """setUp should be called after starting a transaction""" assert Item.objects.count() == 0 Item.objects.create(name='Some item') Item.objects.create(name='Some item again') def test_count(self): self.assertEqual(Item.objects.count(), 2) assert Item.objects.count() == 2 Item.objects.create(name='Foo') self.assertEqual(Item.objects.count(), 3) def test_count_again(self): self.test_count() def tearDown(self): """tearDown should be called before rolling back the database""" assert Item.objects.count() == 3 class TestFixturesWithSetup(TestCase): fixtures = ['items'] def setUp(self): assert Item.objects.count() == 1 Item.objects.create(name='Some item') def test_count(self): assert Item.objects.count() == 2 Item.objects.create(name='Some item again') def test_count_again(self): self.test_count() def tearDown(self): assert Item.objects.count() == 3 def test_sole_test(django_testdir): """ Make sure the database are configured when only Django TestCase classes are collected, without the django_db marker. """ django_testdir.create_test_module(''' import os from django.test import TestCase from django.conf import settings from .app.models import Item class TestFoo(TestCase): def test_foo(self): # Make sure we are actually using the test database _, db_name = os.path.split(settings.DATABASES['default']['NAME']) assert db_name.startswith('test_') or db_name == ':memory:' \\ or 'file:memorydb' in db_name # Make sure it is usable assert Item.objects.count() == 0 ''') result = django_testdir.runpytest_subprocess('-v') result.stdout.fnmatch_lines([ "*TestFoo*test_foo PASSED*", ]) assert result.ret == 0 class TestUnittestMethods: "Test that setup/teardown methods of unittests are being called." def test_django(self, django_testdir): django_testdir.create_test_module(''' from django.test import TestCase class TestFoo(TestCase): @classmethod def setUpClass(self): print('\\nCALLED: setUpClass') def setUp(self): print('\\nCALLED: setUp') def tearDown(self): print('\\nCALLED: tearDown') @classmethod def tearDownClass(self): print('\\nCALLED: tearDownClass') def test_pass(self): pass ''') result = django_testdir.runpytest_subprocess('-v', '-s') result.stdout.fnmatch_lines([ "CALLED: setUpClass", "CALLED: setUp", "CALLED: tearDown", "PASSED", "CALLED: tearDownClass", ]) assert result.ret == 0 def test_multi_inheritance_setUpClass(self, django_testdir): django_testdir.create_test_module(''' from django.test import TestCase from .app.models import Item # Using a mixin is a regression test, see #280 for more details: # https://github.com/pytest-dev/pytest-django/issues/280 class SomeMixin(object): pass class TestA(SomeMixin, TestCase): expected_state = ['A'] state = [] @classmethod def setUpClass(cls): super(TestA, cls).setUpClass() cls.state.append('A') @classmethod def tearDownClass(cls): assert cls.state.pop() == 'A' super(TestA, cls).tearDownClass() def test_a(self): assert self.state == self.expected_state class TestB(TestA): expected_state = ['A', 'B'] @classmethod def setUpClass(cls): super(TestB, cls).setUpClass() cls.state.append('B') @classmethod def tearDownClass(cls): assert cls.state.pop() == 'B' super(TestB, cls).tearDownClass() def test_b(self): assert self.state == self.expected_state class TestC(TestB): expected_state = ['A', 'B', 'C'] @classmethod def setUpClass(cls): super(TestC, cls).setUpClass() cls.state.append('C') @classmethod def tearDownClass(cls): assert cls.state.pop() == 'C' super(TestC, cls).tearDownClass() def test_c(self): assert self.state == self.expected_state ''') result = django_testdir.runpytest_subprocess('-vvvv', '-s') assert result.parseoutcomes()['passed'] == 6 assert result.ret == 0 def test_unittest(self, django_testdir): django_testdir.create_test_module(''' from unittest import TestCase class TestFoo(TestCase): @classmethod def setUpClass(self): print('\\nCALLED: setUpClass') def setUp(self): print('\\nCALLED: setUp') def tearDown(self): print('\\nCALLED: tearDown') @classmethod def tearDownClass(self): print('\\nCALLED: tearDownClass') def test_pass(self): pass ''') result = django_testdir.runpytest_subprocess('-v', '-s') result.stdout.fnmatch_lines([ "CALLED: setUpClass", "CALLED: setUp", "CALLED: tearDown", "PASSED", "CALLED: tearDownClass", ]) assert result.ret == 0 class TestCaseWithDbFixture(TestCase): pytestmark = pytest.mark.usefixtures('db') def test_simple(self): # We only want to check setup/teardown does not conflict assert 1 class TestCaseWithTrDbFixture(TestCase): pytestmark = pytest.mark.usefixtures('transactional_db') def test_simple(self): # We only want to check setup/teardown does not conflict assert 1 def test_pdb_enabled(django_testdir): """ Make sure the database is flushed and tests are isolated when using the --pdb option. See issue #405 for details: https://github.com/pytest-dev/pytest-django/issues/405 """ django_testdir.create_test_module(''' import os from django.test import TestCase from django.conf import settings from .app.models import Item class TestPDBIsolation(TestCase): def setUp(self): """setUp should be called after starting a transaction""" assert Item.objects.count() == 0 Item.objects.create(name='Some item') Item.objects.create(name='Some item again') def test_count(self): self.assertEqual(Item.objects.count(), 2) assert Item.objects.count() == 2 Item.objects.create(name='Foo') self.assertEqual(Item.objects.count(), 3) def test_count_again(self): self.test_count() def tearDown(self): """tearDown should be called before rolling back the database""" assert Item.objects.count() == 3 ''') result = django_testdir.runpytest_subprocess('-v', '--pdb') assert result.ret == 0 pytest-django-3.1.2/tests/test_urls.py000066400000000000000000000023621301551737600200600ustar00rootroot00000000000000import pytest from django.conf import settings from django.core.urlresolvers import is_valid_path from django.utils.encoding import force_text @pytest.mark.urls('pytest_django_test.urls_overridden') def test_urls(): assert settings.ROOT_URLCONF == 'pytest_django_test.urls_overridden' assert is_valid_path('/overridden_url/') @pytest.mark.urls('pytest_django_test.urls_overridden') def test_urls_client(client): response = client.get('/overridden_url/') assert force_text(response.content) == 'Overridden urlconf works!' def test_urls_cache_is_cleared(testdir): testdir.makepyfile(myurls=""" from django.conf.urls import url from pytest_django_test.compat import patterns def fake_view(request): pass urlpatterns = patterns('', url(r'first/$', fake_view, name='first')) """) testdir.makepyfile(""" from django.core.urlresolvers import reverse, NoReverseMatch import pytest @pytest.mark.urls('myurls') def test_something(): reverse('first') def test_something_else(): with pytest.raises(NoReverseMatch): reverse('first') """) result = testdir.runpytest_subprocess() assert result.ret == 0 pytest-django-3.1.2/tests/test_without_django_loaded.py000066400000000000000000000043231301551737600234270ustar00rootroot00000000000000import pytest @pytest.fixture def no_ds(monkeypatch): """Ensure DJANGO_SETTINGS_MODULE is unset""" monkeypatch.delenv('DJANGO_SETTINGS_MODULE') pytestmark = pytest.mark.usefixtures('no_ds') def test_no_ds(testdir): testdir.makepyfile(""" import os def test_env(): assert 'DJANGO_SETTINGS_MODULE' not in os.environ def test_cfg(pytestconfig): assert pytestconfig.option.ds is None """) r = testdir.runpytest_subprocess() assert r.ret == 0 def test_database(testdir): testdir.makepyfile(""" import pytest @pytest.mark.django_db def test_mark(): assert 0 @pytest.mark.django_db(transaction=True) def test_mark_trans(): assert 0 def test_db(db): assert 0 def test_transactional_db(transactional_db): assert 0 """) r = testdir.runpytest_subprocess() assert r.ret == 0 r.stdout.fnmatch_lines(['*4 skipped*']) def test_client(testdir): testdir.makepyfile(""" def test_client(client): assert 0 def test_admin_client(admin_client): assert 0 """) r = testdir.runpytest_subprocess() assert r.ret == 0 r.stdout.fnmatch_lines(['*2 skipped*']) def test_rf(testdir): testdir.makepyfile(""" def test_rf(rf): assert 0 """) r = testdir.runpytest_subprocess() assert r.ret == 0 r.stdout.fnmatch_lines(['*1 skipped*']) def test_settings(testdir): testdir.makepyfile(""" def test_settings(settings): assert 0 """) r = testdir.runpytest_subprocess() assert r.ret == 0 r.stdout.fnmatch_lines(['*1 skipped*']) def test_live_server(testdir): testdir.makepyfile(""" def test_live_server(live_server): assert 0 """) r = testdir.runpytest_subprocess() assert r.ret == 0 r.stdout.fnmatch_lines(['*1 skipped*']) def test_urls_mark(testdir): testdir.makepyfile(""" import pytest @pytest.mark.urls('foo.bar') def test_urls(): assert 0 """) r = testdir.runpytest_subprocess() assert r.ret == 0 r.stdout.fnmatch_lines(['*1 skipped*']) pytest-django-3.1.2/tox.ini000066400000000000000000000031011301551737600156230ustar00rootroot00000000000000[tox] envlist = - py35-pytest30-django{master,1.10,1.9,1.8}-postgres - py34-pytest30-django1.10-postgres - py33-pytest30-django1.8-postgres - py27-pytest30-django1.10-{mysql_innodb,mysql_myisam,postgres} - py27-pytest30-django{master,1.9,1.8,1.7}-postgres - pypy3-pytest30-django1.8-{sqlite,sqlite_file} - pypy3-pytest29-django1.8-sqlite_file - pypy-pytest30-django1.10-sqlite_file - py{35,py27}-checkqa [testenv] deps = django-configurations==1.0 pytest-xdist==1.15 checkqa: flake8 djangomaster: https://github.com/django/django/archive/master.tar.gz django1.10: Django>=1.10,<1.11 django1.9: Django>=1.9,<1.10 django1.8: Django>=1.8,<1.9 django1.7: Django>=1.7,<1.8 mysql_myisam: mysql-python==1.2.5 mysql_innodb: mysql-python==1.2.5 postgres: psycopg2 pytest29: pytest>=2.9,<3.0 pytest30: pytest>=3.0,<3.1 setenv = PYTHONPATH = {toxinidir}:{env:PYTHONPATH:} usedevelop = True whitelist_externals = sh commands = checkqa: flake8 --version && flake8 --show-source --statistics mysql_innodb: py.test --ds=pytest_django_test.settings_mysql_innodb --strict -r fEsxXw {posargs:tests} mysql_myisam: py.test --ds=pytest_django_test.settings_mysql_myisam --strict -r fEsxXw {posargs:tests} postgres: py.test --ds=pytest_django_test.settings_postgres --strict -r fEsxXw {posargs:tests} sqlite: py.test --ds=pytest_django_test.settings_sqlite --strict -r fEsxXw {posargs:tests} sqlite_file: py.test --ds=pytest_django_test.settings_sqlite_file --strict -r fEsxXw {posargs:tests}