pax_global_header00006660000000000000000000000064144316643130014517gustar00rootroot0000000000000052 comment=775e1d33a3d5deb0ae29e629ecfdb67302d03fdd pytest-djangoapp-1.2.0/000077500000000000000000000000001443166431300150105ustar00rootroot00000000000000pytest-djangoapp-1.2.0/.coveragerc000066400000000000000000000001011443166431300171210ustar00rootroot00000000000000[run] source = pytest_djangoapp/ omit = pytest_djangoapp/tests/* pytest-djangoapp-1.2.0/.github/000077500000000000000000000000001443166431300163505ustar00rootroot00000000000000pytest-djangoapp-1.2.0/.github/workflows/000077500000000000000000000000001443166431300204055ustar00rootroot00000000000000pytest-djangoapp-1.2.0/.github/workflows/python-package.yml000066400000000000000000000042201443166431300240400ustar00rootroot00000000000000name: Python package on: push: branches: [ master ] pull_request: branches: [ master ] workflow_dispatch: jobs: build: runs-on: ubuntu-latest strategy: fail-fast: false matrix: python-version: [3.7, 3.8, 3.9, "3.10", "3.11"] django-version: [1.8, 1.9, "1.10", 1.11, 2.0, 2.1, 2.2, 3.0, 3.1, 3.2, 4.0, 4.1, 4.2] exclude: - python-version: 3.11 django-version: 1.8 - python-version: 3.11 django-version: 1.9 - python-version: 3.11 django-version: "1.10" - python-version: 3.11 django-version: 1.11 - python-version: 3.11 django-version: 2.1 - python-version: 3.10 django-version: 1.8 - python-version: 3.10 django-version: 1.9 - python-version: 3.10 django-version: "1.10" - python-version: 3.10 django-version: 1.11 - python-version: 3.9 django-version: 1.8 - python-version: 3.9 django-version: 1.9 - python-version: 3.9 django-version: "1.10" - python-version: 3.8 django-version: 1.8 - python-version: 3.8 django-version: 1.9 - python-version: 3.8 django-version: "1.10" - python-version: 3.7 django-version: 1.8 - python-version: 3.7 django-version: 4.0 - python-version: 3.7 django-version: 4.1 - python-version: 3.7 django-version: 4.2 steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} & Django ${{ matrix.django-version }} uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - name: Install deps run: | python -m pip install pytest coverage coveralls "Django~=${{ matrix.django-version }}.0" - name: Run tests env: GITHUB_TOKEN: ${{ secrets.github_token }} run: | coverage run --source=pytest_djangoapp setup.py test coveralls --service=github pytest-djangoapp-1.2.0/.gitignore000066400000000000000000000001231443166431300167740ustar00rootroot00000000000000.project .pydevproject .idea .tox __pycache__ *.pyc *.pyo *.egg-info docs/_build/ pytest-djangoapp-1.2.0/AUTHORS000066400000000000000000000003701443166431300160600ustar00rootroot00000000000000pytest-djangoapp authors ======================== Created by Igor `idle sign` Starikov. Contributors ------------ John Vandenberg Kamal Mustafa Petr Dlouhý pytest-djangoapp-1.2.0/CHANGELOG000066400000000000000000000061021443166431300162210ustar00rootroot00000000000000pytest-djangoapp changelog ========================== v1.2.0 [2023-05-19] ------------------- + Add 'liveserver' and 'liveclient' fixtures (closes #24). v1.1.0 [2023-03-18] ------------------- + Added 'command_makemigrations' fixture. + Added 'conf_app_name' fixture (see #17). + Fixture 'template_context' now accepts a username. v1.0.0 [2022-11-09] ------------------- ! Dropped support for Django 1.7. ! Dropped support for Py2. Py3.6+ specific syntax is introduced. Code update may be required. + Introduced new 'check_migrations' fixture. v0.15.2 [2021-08-04] -------------------- ! Dropped QA for Python 2.7 and 3.5. ! This version is the last featuring Python 2 and 3.5 support. * Ignore temporary attributes from project settings module (see #21). v0.15.1 [2021-04-10] -------------------- * Made Django 3.2 compatible. v0.15.0 [2020-09-21] -------------------- + Fixture 'request_client' now accepts 'json' argument to encode post data. v0.14.0 [2020-01-25] -------------------- + Added support for testing entire Django projects (requires Py 3). * Added QA for Py3.8 and Django 3.0. v0.13.0 [2019-11-23] -------------------- + 'request_client' HTTP methods now can accept a tuple of view name with params instead of actual URL path. v0.12.0 [2019-10-19] -------------------- + Added 'db_queries' fixture. + Fixture 'request_client' now accepts 'raise_exceptions' argument to tech technical error views. * Added QA for py3.7 and Django 2.2. * Dropped QA for py3.4. * Fix PyCharm hints for some fixtures. v0.11.0 ------- + 'configure_djangoapp_plugin()' now accepts 'migrate' argument. * Silenced DB creation/teardown messages. v0.10.1 ------- * Fixed 'pytest_runtest_teardown' failure in case of makr.skipif or similar. v0.10.0 ------- + 'configure_djangoapp_plugin()' now accepts 'settings_hook' argument. + Added 'messages' fixture. v0.9.0 ------ + 'configure_djangoapp_plugin()' now accepts 'admin_contrib' argument. + 'request_client' fixture now accepts 'user' argument for easy auth. + Added 'compat' module with 'get_urlpatterns()' helper. + User password is now accessible via 'password_plain' attribute of user objects created with fixtures. v0.8.0 ------ + Added 'mail_outbox' fixture. v0.7.1 ------ * Fixed 'extend_' prefixed args handling in old Django versions. v0.7.0 ------ + 'configure_djangoapp_plugin()' now accepts 'extend_' prefixed args. v0.6.0 ------ + 'request_client' and 'request_factory' and co fixtures now accept 'ajax' argument. v0.5.0 ------ + 'settings' fixture now can be used as a context manager. v0.4.2 ------ * Improved templatetags compatibility for 1.8, 1.9. v0.4.1 ------ * Added mock package adaptive autoinstall. v0.4.0 ------ + Introduced 'command_run' fixture. * Removed six dependency. v0.3.2 ------ * Added STATIC_URL default. v0.3.1 ------ * Fixed test client work on Django < 2.0. v0.3.0 ------ + Introduced 'request_client' fixture. + Introduced 'request_post' fixture. + Introduced 'user' shortcut fixture. v0.2.0 ------ + Improved test discovery. + Introduced 'template_strip_tags' fixture. v0.1.0 ------ + Basic functionality.pytest-djangoapp-1.2.0/CONTRIBUTING000066400000000000000000000012601443166431300166410ustar00rootroot00000000000000pytest-djangoapp contributing ============================= Submit issues ------------- If you spotted something weird in application behavior or want to propose a feature you are welcome. Write code ---------- If you are eager to participate in application development and to work on an existing issue (whether it should be a bugfix or a feature implementation), fork, write code, and make a pull request right from the forked project page. Spread the word --------------- If you have some tips and tricks or any other words that you think might be of interest for the others — publish it wherever you find convenient. See also: https://github.com/idlesign/pytest-djangoapp pytest-djangoapp-1.2.0/INSTALL000066400000000000000000000007721443166431300160470ustar00rootroot00000000000000pytest-djangoapp installation ============================= Python ``pip`` package is required to install ``pytest-djangoapp``. From sources ------------ Use the following command line to install ``pytest-djangoapp`` from sources directory (containing setup.py): pip install . or python setup.py install From PyPI --------- Alternatively you can install ``pytest-djangoapp`` from PyPI: pip install pytest-djangoapp Use `-U` flag for upgrade: pip install -U pytest-djangoapp pytest-djangoapp-1.2.0/LICENSE000066400000000000000000000027451443166431300160250ustar00rootroot00000000000000Copyright (c) 2018-2023, Igor `idle sign` Starikov 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. * Neither the name of the pytest-djangoapp nor the names of its contributors may 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 HOLDER 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-djangoapp-1.2.0/MANIFEST.in000066400000000000000000000004301443166431300165430ustar00rootroot00000000000000include AUTHORS include CHANGELOG include INSTALL include LICENSE include README.rst include docs/Makefile recursive-include docs *.rst recursive-include docs *.py recursive-include tests * recursive-exclude * __pycache__ recursive-exclude * *.py[co] recursive-exclude * empty pytest-djangoapp-1.2.0/README.rst000066400000000000000000000063441443166431300165060ustar00rootroot00000000000000pytest-djangoapp ================ https://github.com/idlesign/pytest-djangoapp |release| |lic| |coverage| .. |release| image:: https://img.shields.io/pypi/v/pytest-djangoapp.svg :target: https://pypi.python.org/pypi/pytest-djangoapp .. |lic| image:: https://img.shields.io/pypi/l/pytest-djangoapp.svg :target: https://pypi.python.org/pypi/pytest-djangoapp .. |coverage| image:: https://img.shields.io/coveralls/idlesign/pytest-djangoapp/master.svg :target: https://coveralls.io/r/idlesign/pytest-djangoapp Description ----------- *Nice pytest plugin to help you with Django pluggable application testing.* This exposes some useful tools for Django applications developers to facilitate tests authoring, including: * Settings overriding * Template tags testing * User creation * Request object creation * Management command calls * Mailing * Migrations * Messages * DB queries audit * Live server & client UI testing * etc. Suitable for testing apps for Django 1.8+. How to use ---------- Let's say you have classical tests placing (inside application directory): .. code-block:: package_dir |__ myapp | |__ __init__.py | |__ tests | | |__ __init__.py | | |__ conftest.py <- Configure djangoapp here. | |__ setup.py Add the following lines into `conftest.py` to configure `djangoapp` and start using it: .. code-block:: python # conftest.py from pytest_djangoapp import configure_djangoapp_plugin pytest_plugins = configure_djangoapp_plugin() Fixtures usage examples can be found in the documentation and the source code. Testing an entire project ------------------------- Despite the fact that `djangoapp` is primarily aimed to reusable Django applications testing one can use it also to test a project (a set of apps). For that, pass a dotted settings module path into `settings` argument: .. code-block:: python pytest_plugins = configure_djangoapp_plugin( settings='myproject.settings.settings_testing', migrate=False, # If you do not want to apply migrations. ) What about pytest-django ------------------------ `pytest-djangoapp` does not depend on `pytest-django`. There are design decisions in `pytest-django` that might make it uncomfortable to work with. 1. It uses `setuptools` entrypoints feature for `pytest` plugin discovery. It's not a problem by itself, but all kinds of bootstrapping with side effects made by `pytest-django` just on startup, make the plugin a poor choice for cases of system-wide (i.e. not venv) installations. 2. Philosophy that next to no unit test should require DB access may be quite annoying. 3. Some fixtures (e.g. `django_assert_num_queries`) usability arouse questions. Despite that `pytest-django` is nice, of course. `pytest-djangoapp` fixtures allow the use of Django without marking all relevant tests as needing a database, as is required by pytest-django which provides the ``django_db`` mark and db fixtures. If you have `pytest-django` already installed, it can be disabled for projects using `pytest-djangoapp` by adding the following lines into ``pytest.ini``: .. code-block:: ini # pytest.ini [pytest] addopts = -p no:django Documentation ------------- http://pytest-djangoapp.readthedocs.org/ pytest-djangoapp-1.2.0/docs/000077500000000000000000000000001443166431300157405ustar00rootroot00000000000000pytest-djangoapp-1.2.0/docs/Makefile000066400000000000000000000110331443166431300173760ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build 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) source .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest 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 " 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-djangoapp.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/pytest-djangoapp.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-djangoapp" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/pytest-djangoapp" @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." 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-djangoapp-1.2.0/docs/build/000077500000000000000000000000001443166431300170375ustar00rootroot00000000000000pytest-djangoapp-1.2.0/docs/build/empty000066400000000000000000000000001443166431300201060ustar00rootroot00000000000000pytest-djangoapp-1.2.0/docs/requirements.txt000066400000000000000000000000641443166431300212240ustar00rootroot00000000000000# For autodoc to work. django==3.2.19 pytest==7.2.2 pytest-djangoapp-1.2.0/docs/source/000077500000000000000000000000001443166431300172405ustar00rootroot00000000000000pytest-djangoapp-1.2.0/docs/source/_static/000077500000000000000000000000001443166431300206665ustar00rootroot00000000000000pytest-djangoapp-1.2.0/docs/source/_static/empty000066400000000000000000000000001443166431300217350ustar00rootroot00000000000000pytest-djangoapp-1.2.0/docs/source/_templates/000077500000000000000000000000001443166431300213755ustar00rootroot00000000000000pytest-djangoapp-1.2.0/docs/source/_templates/empty000066400000000000000000000000001443166431300224440ustar00rootroot00000000000000pytest-djangoapp-1.2.0/docs/source/conf.py000066400000000000000000000170711443166431300205450ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # pytest-djangoapp documentation build configuration file. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # 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.insert(0, os.path.abspath('../../')) from pytest_djangoapp import VERSION # -- Mocking ------------------------------------------------------------------ # This is used to mock certain modules. # It helps to build docs in environments where those modules are not available. # E.g. it could be useful for http://readthedocs.org/ MODULES_TO_MOCK = [ 'django.conf', 'django.conf.settings', 'django.conf.locale', ] if MODULES_TO_MOCK: from unittest.mock import MagicMock for mod_name in MODULES_TO_MOCK: sys.modules[mod_name] = MagicMock() # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc'] # Instruct autoclass directive to document both class and __init__ docstrings. autoclass_content = 'both' # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'pytest-djangoapp' copyright = u'2018-2023, Igor `idle sign` Starikov' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '.'.join(map(str, VERSION)) # The full version, including alpha/beta/rc tags. release = '.'.join(map(str, VERSION)) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['rst_guide.rst'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # 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'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'pytest-djangoappdoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'pytest-djangoapp.tex', u'pytest-djangoapp Documentation', u'Igor `idle sign` Starikov', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'pytest-djangoapp', u'pytest-djangoapp Documentation', [u'Igor `idle sign` Starikov'], 1) ] pytest-djangoapp-1.2.0/docs/source/fixtures.rst000066400000000000000000000005551443166431300216500ustar00rootroot00000000000000Fixtures ======== ``djangoapp`` offers you various ``pytest`` fixtures falling into the categories below: .. toctree:: :maxdepth: 4 fixtures_commands fixtures_db fixtures_settings fixtures_request fixtures_templates fixtures_users fixtures_mail fixtures_messages fixtures_migrations fixtures_utils fixtures_live pytest-djangoapp-1.2.0/docs/source/fixtures_commands.rst000066400000000000000000000002171443166431300235240ustar00rootroot00000000000000Commands ======== These fixtures are related to Django management commands. .. automodule:: pytest_djangoapp.fixtures.commands :members: pytest-djangoapp-1.2.0/docs/source/fixtures_db.rst000066400000000000000000000002411443166431300223050ustar00rootroot00000000000000Database ======== These fixtures are related to Django database operation, including issued by ORM. .. automodule:: pytest_djangoapp.fixtures.db :members: pytest-djangoapp-1.2.0/docs/source/fixtures_live.rst000066400000000000000000000003151443166431300226610ustar00rootroot00000000000000Live server & client ==================== These instruments allows you to lunch a live servers and live clients, e.g. for UI testing purposes. .. automodule:: pytest_djangoapp.fixtures.live :members: pytest-djangoapp-1.2.0/docs/source/fixtures_mail.rst000066400000000000000000000001761443166431300226510ustar00rootroot00000000000000Mail ==== These fixtures are related to Django mailing system. .. automodule:: pytest_djangoapp.fixtures.mail :members: pytest-djangoapp-1.2.0/docs/source/fixtures_messages.rst000066400000000000000000000002041443166431300235260ustar00rootroot00000000000000Messages ======== Fixtures related to Django Messages framework. .. automodule:: pytest_djangoapp.fixtures.messages :members: pytest-djangoapp-1.2.0/docs/source/fixtures_migrations.rst000066400000000000000000000002231443166431300240740ustar00rootroot00000000000000Migrations ========== These fixtures are related to Django migrations system. .. automodule:: pytest_djangoapp.fixtures.migrations :members: pytest-djangoapp-1.2.0/docs/source/fixtures_request.rst000066400000000000000000000002101443166431300234040ustar00rootroot00000000000000Request ======= These fixtures are related to Django request objects. .. automodule:: pytest_djangoapp.fixtures.request :members: pytest-djangoapp-1.2.0/docs/source/fixtures_settings.rst000066400000000000000000000002211443166431300235560ustar00rootroot00000000000000Settings ======== These fixtures are related to Django project configuration. .. automodule:: pytest_djangoapp.fixtures.settings :members: pytest-djangoapp-1.2.0/docs/source/fixtures_templates.rst000066400000000000000000000002171443166431300237210ustar00rootroot00000000000000Templates ========= These fixtures are related to Django templates system. .. automodule:: pytest_djangoapp.fixtures.templates :members: pytest-djangoapp-1.2.0/docs/source/fixtures_users.rst000066400000000000000000000001701443166431300230620ustar00rootroot00000000000000Users ===== These fixtures are related to Django users. .. automodule:: pytest_djangoapp.fixtures.users :members: pytest-djangoapp-1.2.0/docs/source/fixtures_utils.rst000066400000000000000000000001551443166431300230640ustar00rootroot00000000000000Utils ===== Offers various utility fixtures. .. automodule:: pytest_djangoapp.fixtures.utils :members: pytest-djangoapp-1.2.0/docs/source/index.rst000066400000000000000000000013141443166431300211000ustar00rootroot00000000000000pytest-djangoapp documentation ============================== https://github.com/idlesign/pytest-djangoapp Description ----------- *Nice pytest plugin to help you with Django pluggable application testing.* This exposes some useful tools for Django applications developers to facilitate tests authoring, including: * Settings overriding * Template tags testing * User creation * Request object creation * Management command calls * Mailing * Migrations * Messages * DB queries audit * Live server & client UI testing * etc. Suitable for testing apps for Django 1.8+. Requirements ------------ 1. Python 3.6+ Table of Contents ----------------- .. toctree:: :maxdepth: 4 quickstart fixtures pytest-djangoapp-1.2.0/docs/source/quickstart.rst000066400000000000000000000103361443166431300221670ustar00rootroot00000000000000Quickstart ========== Application structuring ----------------------- Let's say you have classical tests placing (inside application directory):: package_dir |__ myapp | |__ __init__.py | |__ tests | | |__ __init__.py | | |__ conftest.py <- Configure djangoapp here. | |__ setup.py Configuring djangoapp --------------------- Add the following lines into `conftest.py` to configure `djangoapp` and start using it: .. code-block:: python # conftest.py from pytest_djangoapp import configure_djangoapp_plugin pytest_plugins = configure_djangoapp_plugin() You can override default settings: .. code-block:: python pytest_plugins = configure_djangoapp_plugin({ 'DEBUG': False, 'SOMETHING': 'else, }) Sometimes you may want to extend default settings, such as `INSTALLED_APPS` or `DATABASES`. To do this you can pass `extend_`-prefixed arguments: .. code-block:: python pytest_plugins = configure_djangoapp_plugin( extend_INSTALLED_APPS=[ 'django.contrib.sites', ], extend_MIDDLEWARE=[ 'django.contrib.sessions.middleware.SessionMiddleware', ], extend_DATABASES={ 'dummy': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, }, ) If you test an application providing some integration with Django Admin contrib, there is a convenient `admin_contrib` argument you can pass to activate this contrib: .. code-block:: python pytest_plugins = configure_djangoapp_plugin(admin_contrib=True) By default all DB migrations are applied on test runs. Since that can be unnecessary and take a long time, there is a `migrate` argument that you can always set to ``False``: .. code-block:: python pytest_plugins = configure_djangoapp_plugin(migrate=False) You can further change or altogether replace generated settings using `settings_hook` argument: .. code-block:: python def hook(settings): # Do something with settings. return settings pytest_plugins = configure_djangoapp_plugin( settings_hook=hook, ) Testing an entire project ------------------------- .. note:: Requires Python 3. Despite the fact that `djangoapp` is primarily aimed to reusable Django applications testing one can use it also to test a project (a set of apps). For that, pass a dotted settings module path into `settings` argument: .. code-block:: python pytest_plugins = configure_djangoapp_plugin( settings='myproject.settings.settings_testing', ) Using fixtures -------------- Use them just as you usually do with `pytest`: .. code-block:: python # test_some.py def test_this(settings, request_client): # We use `settings` fixture to temporarily override # project settings. with settings(DEBUG=True, MYVAR='someval'): # Now do some testing, with settings overridden. ... # And we use `request_client` fixture # to test our [AJAX] view. client = request_client(ajax=True) # We pass a tuple with a view name with arguments to not to bother with URL. response = client.get(('someview', {'somearg': 'one', 'otherarg': 33})) ... # See fixtures documentation for more fixtures. Additional app for testing -------------------------- Sometimes your app may provide tooling for other apps (say it automatically imports modules from them, or provides some urlpatterns). If so, you may want to simulate that other application in your tests. You can easily do that by adding ``testapp`` package under your test directory (this will be automatically added to ``INSTALLED_APPS`` and treated by Django just as any application package):: package_dir |__ myapp | |__ __init__.py | |__ tests | | |__ __init__.py | | |__ testapp <- Thirdparty app simulation package. | | | |__ __init__.py | | | |__ admin.py <- This module uses primitives provided by your app. | | | |__ models.py <- This module uses base models provided by your app. | | | |__ urls.py <- And this module uses urlpatterns provided by your app. | | |__ conftest.py | |__ setup.py pytest-djangoapp-1.2.0/docs/source/rst_guide.rst000066400000000000000000000025551443166431300217660ustar00rootroot00000000000000RST Quick guide =============== Online reStructuredText editor - http://rst.ninjs.org/ Main heading ============ Secondary heading ----------------- Minor heading ~~~~~~~~~~~~~ Typography ---------- **Bold** `Italic` ``Accent`` Blocks ------ Double colon to consider the following paragraphs preformatted:: This text is preformated. Can be used for code samples. .. code-block:: python # code-block accepts language name to highlight code # E.g.: python, html import this .. note:: This text will be rendered as a note block (usually green). .. warning:: This text will be rendered as a warning block (usually red). Lists ----- 1. Ordered item 1. Indent paragraph to make in belong to the above list item. 2. Ordered item 2. + Unordered item 1. + Unordered item . Links ----- :ref:`Documentation inner link label ` .. _some-marker: `Outer link label `_ Inline URLs are converted to links automatically: http://github.com/idlesign/makeapp/ Images ------ .. image:: path_to_image/image.png Automation ---------- http://sphinx-doc.org/ext/autodoc.html .. automodule:: my_module :members: .. autoclass:: my_module.MyClass :members: do_this, do_that :inherited-members: :undoc-members: :private-members: :special-members: :show-inheritance: pytest-djangoapp-1.2.0/pytest.ini000066400000000000000000000000511443166431300170350ustar00rootroot00000000000000[pytest] addopts = -p no:django --pyargs pytest-djangoapp-1.2.0/pytest_djangoapp/000077500000000000000000000000001443166431300203635ustar00rootroot00000000000000pytest-djangoapp-1.2.0/pytest_djangoapp/__init__.py000066400000000000000000000003011443166431300224660ustar00rootroot00000000000000from .toolbox import configure_djangoapp_plugin VERSION = (1, 2, 0) """Application version number tuple.""" VERSION_STR = '.'.join(map(str, VERSION)) """Application version number string."""pytest-djangoapp-1.2.0/pytest_djangoapp/compat.py000066400000000000000000000006661443166431300222300ustar00rootroot00000000000000from django import VERSION def get_urlpatterns(patterns_list: list) -> list: """Returns object suitable to use as urlpatterns in `urls.py`. Example:: urlpatterns = get_urlpatterns([ url(r'^index/$', index, name='index'), ]) :param patterns_list: """ if VERSION >= (1, 9): return patterns_list from django.conf.urls import patterns return patterns('', *patterns_list) pytest-djangoapp-1.2.0/pytest_djangoapp/configuration.py000066400000000000000000000220531443166431300236060ustar00rootroot00000000000000from threading import local from typing import Callable _THREAD_LOCAL = local() setattr(_THREAD_LOCAL, 'configuration', {}) class FakeMigrationModules: """Allows skipping migration applying process.""" def __init__(self, module_name: str): self.module_name = module_name def __getitem__(self, item: str) -> str: return self.module_name def __contains__(self, item: str): return True class Configuration: _prefix = 'DJANGOAPP_OPTIONS' _KEY_ADMIN = 'admin' KEY_APP = 'app_name' _KEY_EXTEND = 'extend' _KEY_HOOK = 'hook' _KEY_MIGRATE = 'migrate' DIR_TESTAPP = 'testapp' """Name of test application directory. Test application directory should be placed inside `tests` directory and needs to be a Python package (contain __init__.py). Test application is useful to place there modules like `urls.py`, `models.py` (e.g. with custom models), etc. """ @classmethod def get(cls) -> dict: return _THREAD_LOCAL.configuration @classmethod def set( cls, settings_dict: dict = None, *, app_name: str = None, admin_contrib: bool = False, settings_hook: Callable = None, migrate: bool = True, **kwargs ): """ :param settings_dict: :param app_name: :param admin_contrib: Setup Django to test Admin contrib related parts. :param settings_hook: Allows setting a function to get resulting settings. Function must accept settings dictionary, and return resulting settings dictionary. .. code-block:: python def hook_func(settings): return settings :param migrate: Allows applying or skipping migration applying process. Skipping could be useful for testing applications with many migrations. :param kwargs: Additional arguments. Use `extend_` prefix to extend default configuration. E.g.: extend_INSTALLED_APPS=['a'] """ settings_dict = settings_dict or {} extend = {} for key, val in kwargs.items(): _, _, extend_key = key.partition('extend_') if extend_key and extend_key == extend_key.upper(): extend[extend_key] = val base_settings = { cls._prefix: { cls.KEY_APP: app_name, cls._KEY_EXTEND: extend, cls._KEY_ADMIN: admin_contrib, cls._KEY_HOOK: settings_hook, cls._KEY_MIGRATE: migrate, } } base_settings.update(settings_dict) _THREAD_LOCAL.configuration = base_settings @classmethod def get_defaults(cls) -> dict: from django.conf import global_settings if hasattr(global_settings, 'MIDDLEWARE_CLASSES'): middleware = global_settings.MIDDLEWARE_CLASSES else: middleware = global_settings.MIDDLEWARE installed_apps = list(global_settings.INSTALLED_APPS[:]) installed_apps.extend([ 'django.contrib.auth', 'django.contrib.contenttypes', ]) installed_apps = list(set(installed_apps)) settings_dict = dict( SECRET_KEY='djangoapp', ALLOWED_HOSTS=( global_settings.ALLOWED_HOSTS + # Satisfy Django test client needed in Django < 2.0 ['testserver'] ), INSTALLED_APPS=installed_apps, STATIC_URL='/static/', DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, }, MIDDLEWARE=middleware, EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend', TEMPLATES=[ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'OPTIONS': {'context_processors': ['django.contrib.messages.context_processors.messages']} }, ], ) return settings_dict.copy() @classmethod def get_combined(cls, pytest_config) -> dict: from django import VERSION settings = cls.get() defaults = cls.get_defaults() defaults.update(settings) djapp_options = defaults[cls._prefix] app_name = djapp_options[cls.KEY_APP] extensions = djapp_options[cls._KEY_EXTEND] admin = djapp_options[cls._KEY_ADMIN] hook = djapp_options.pop(cls._KEY_HOOK, None) or (lambda settings_dict: settings_dict) # djangoapp is considered testing a whole project (a set of apps) # if hook function is a `partial` for function with a certain name. project_mode = getattr(getattr(hook, 'func', None), '__name__', '') == 'update_settings_from_module' if not djapp_options[cls._KEY_MIGRATE]: module_name = None if VERSION <= (1, 10): module_name = 'dummy_migrations' defaults['MIGRATIONS_MODULE_NAME'] = module_name defaults['MIGRATION_MODULES'] = FakeMigrationModules(module_name) if admin: middleware = extensions.setdefault('MIDDLEWARE', []) middleware.extend([ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ]) apps = extensions.setdefault('INSTALLED_APPS', []) apps.extend([ 'django.contrib.admin', 'django.contrib.sessions', ]) for key, value in extensions.items(): default_value = defaults.get(key, []) if isinstance(default_value, (list, tuple)): extended = list(default_value) for item in value: if item not in extended: extended.append(item) defaults[key] = extended if key == 'MIDDLEWARE': # Special case for renamed. defaults['MIDDLEWARE_CLASSES'] = extended elif isinstance(default_value, dict): defaults[key].update(value) else: # pragma: nocover raise ValueError(f'Unable to extend `{key}` option.') installed_apps = defaults['INSTALLED_APPS'] if app_name: if app_name not in installed_apps: installed_apps.append(app_name) else: dir_current = pytest_config.invocation_dir dir_tests = None app_name = dir_current.basename if app_name == 'tests': # Support certain module or function invocation tests dir as base (e.g. PyCharm behaviour). app_name = dir_current.parts()[-2].basename dir_tests = dir_current try: dir_tests = dir_current.listdir('tests')[0] except IndexError: pass if not dir_tests: # No `tests` subdir found. Let's try to deduce. app_name = None from setuptools import find_packages import py candidate_latest = '' candidates = [] for package in find_packages(f'{dir_current}'): # Consider only top level packages. if not candidate_latest or not package.startswith(candidate_latest): candidates.append(package) candidate_latest = package for candidate in candidates: dirs = py.path.local(candidate).listdir('tests') if dirs: app_name = candidate dir_tests = dirs[0] break if not app_name and not project_mode: raise Exception( 'Unable to deduce application name. ' 'Check application package and `tests` directory exists. ' f'Current dir: {dir_current}') if app_name: installed_apps.append(app_name) if dir_tests: # Try to find and add an additional test app. dir_testapp_name = cls.DIR_TESTAPP dir_testapp = dir_tests.listdir(dir_testapp_name) if dir_testapp: dir_testapp = dir_testapp[0] testapp_name = f'{app_name}.tests.{dir_testapp_name}' installed_apps.append(testapp_name) if dir_testapp.listdir('urls.py'): # Set customized `urls.py`. defaults['ROOT_URLCONF'] = f'{testapp_name}.urls' djapp_options[cls.KEY_APP] = app_name defaults = hook(defaults) return defaults @classmethod def get_dict(cls) -> dict: """Returns current configuration as a dict.""" return cls.get()[cls._prefix] pytest-djangoapp-1.2.0/pytest_djangoapp/fixtures/000077500000000000000000000000001443166431300222345ustar00rootroot00000000000000pytest-djangoapp-1.2.0/pytest_djangoapp/fixtures/__init__.py000066400000000000000000000010311443166431300243400ustar00rootroot00000000000000from .commands import command_run, command_makemigrations from .db import db_queries from .live import liveserver, liveclient from .mail import mail_outbox from .messages import messages from .migrations import check_migrations from .request import request_factory, request_get, request_post, request_client from .settings import settings from .templates import template_render_tag, template_context, template_strip_tags from .users import user_create, user_model, user from .utils import conf_app_name fixtures_registered: bool = True pytest-djangoapp-1.2.0/pytest_djangoapp/fixtures/commands.py000066400000000000000000000034441443166431300244140ustar00rootroot00000000000000from typing import Iterable, Optional import pytest from django.core.management import call_command @pytest.fixture def command_run(): """Allows management command run. Example:: def test_this(command_run, capsys): result = command_run('my_command', args=['one'], options={'two': 'three'}) out, err = capsys.readouterr() .. warning:: Django < 1.10 will always return `None`, no matter what command returns. :param command_name: Command name to run. :param args: Required arguments to pass to a command. :param options: Optional arguments to pass to a command. :returns: Command output. """ def command_run_(command_name: str, args: Iterable[str] = None, options: dict = None) -> Optional[str]: args = args or [] options = options or {} return call_command(command_name, *args, **options) return command_run_ @pytest.fixture def command_makemigrations(conf_app_name): """Allows to run makemigrations command. .. note:: This command can be useful to generate migrations for your application (without a project creation). Example:: def test_makemigrations(command_makemigrations): command_makemigrations() :param app: Application name to run 'makemigrations' for. * By default, a name from 'conf_app_name' fixture is used. * If empty string, command is run for any application. :param args: Additional arguments to pass to the command. """ def command_migration_(*, app: str = None, args: Iterable[str] = None) -> Optional[str]: args = args or [] if app is None: app = conf_app_name if app: args.append(app) return call_command('makemigrations', *args) return command_migration_ pytest-djangoapp-1.2.0/pytest_djangoapp/fixtures/db.py000066400000000000000000000063001443166431300231720ustar00rootroot00000000000000from typing import List import pytest from decimal import Decimal from django.db import connections, DEFAULT_DB_ALIAS, reset_queries if False: # pragma: nocover from collections import deque # noqa @pytest.fixture def db_queries(settings) -> 'Queries': """Allows access to executed DB queries. Example:: def test_db(db_queries): # Previous queries cleared at the beginning. assert len(db_queries) == 0 ... # Do some DB-related stuff. # Assert total queries on all DBs. assert len(db_queries) == 10 # Default DBs SQLs with auxiliary commands filtered out by default. sqls = db_queries.sql() # Assert total execution time is less than a second. assert db_queries.time() < 1 # Drop SQL gathered so far on default DB. db_queries.clear() .. warning:: Requires Django 1.9+ to work. """ queries = Queries() debug_values_prev = {} for connection in connections.all(): debug_values_prev[connection.alias] = connection.force_debug_cursor connection.force_debug_cursor = True try: queries.clear_all() yield queries finally: for connection in connections.all(): prev_debug_value = debug_values_prev.get(connection.alias, None) if prev_debug_value is not None: connection.force_debug_cursor = prev_debug_value queries.clear_all() class Queries: """Allows access to executed DB queries.""" sql_drop = { 'BEGIN', 'COMMIT', 'END', } def __len__(self) -> int: return len(self.get_log()) def get_log(self, db_alias: str = None) -> 'deque': """ :param db_alias: """ return connections[db_alias or DEFAULT_DB_ALIAS].queries_log def clear_all(self): """Clears all queries logged for all DBs.""" reset_queries() def clear(self, db_alias: str = None): """Clear queries for the given or default DB. :param db_alias: Database alias. Default is used if not given. """ self.get_log(db_alias=db_alias).clear() def sql(self, db_alias: str = None, *, drop_auxiliary: bool = True) -> List[str]: """Returns a list of queries executed using the given or default DB. :param db_alias: Database alias. Default is used if not given. :param drop_auxiliary: Filter out auxiliary SQL like: * BEGIN * COMMIT * END """ sqls = [] auxiliary = self.sql_drop for log_entry in self.get_log(db_alias=db_alias): sql = ' '.join(sql_line.strip() for sql_line in log_entry['sql'].splitlines()) if not drop_auxiliary or sql not in auxiliary: sqls.append(sql) return sqls def time(self, db_alias: str = None) -> Decimal: """Returns total time executing queries (in seconds) using the given or default DB. :param db_alias: Database alias. Default is used if not given. """ times = [Decimal(log_entry['time']) for log_entry in self.get_log(db_alias=db_alias)] return sum(times) pytest-djangoapp-1.2.0/pytest_djangoapp/fixtures/live.py000066400000000000000000000064231443166431300235520ustar00rootroot00000000000000from typing import Type, TypeVar, Dict import pytest from django.contrib.staticfiles.testing import StaticLiveServerTestCase TypeLiveClient = TypeVar('TypeLiveClient', bound='LiveClient') @pytest.fixture() def liveserver() -> Type['LiveServer']: """Runs a live server. Available as a context manager. .. warning:: For Django >= 4.0 Example:: def test_live(liveserver): with liveserver() as server: print(f'Live server is available at: {server.url}') """ return LiveServer @pytest.fixture() def liveclient(): """Runs a live client. Available as a context manager. Example:: def test_live(liveserver, liveclient): with liveserver() as server: # Let's run Firefox using Selenium. with liveclient('selenium', browser='firefox') as client: selenium = client.handle # Selenium driver is available in .handle # Let's open server's root URL and check heading 1 on that page selenium.get(server.url) assert selenium.find_element('tag name', 'h1').text == 'Not Found' """ def get_client(typename: str, *, browser: str) -> TypeLiveClient: return LiveClient.spawn(alias=typename, browser=browser) return get_client class LiveServer: _cls = StaticLiveServerTestCase def __init__(self, *, host: str = None, port: int = None): cls = self._cls if host: cls.host = host if port is not None: cls.port = port @property def url(self) -> str: """URL to access this live server.""" return self._cls.live_server_url def __enter__(self): self._cls._start_server_thread() return self def __exit__(self, exc_type, exc_val, exc_tb): self._cls._terminate_thread() class LiveClient: """Base class for live clients.""" alias: str = '' _registry: Dict[str, TypeLiveClient] = {} def __init_subclass__(cls, **kwargs): super().__init_subclass__() alias = cls.alias if alias: cls._registry[alias] = cls def __init__(self, *, browser: str): self._browser = browser self.handle = None def __enter__(self) -> TypeLiveClient: self.handle = self._handle_init() return self def __exit__(self, exc_type, exc_val, exc_tb): self._handle_destroy() @classmethod def spawn(cls, alias: str, **kwargs) -> TypeLiveClient: client_cls = LiveClient._registry[alias] return client_cls(**kwargs) def _handle_init(self): # pragma: nocover raise NotImplementedError def _handle_destroy(self): pass class SeleniumLiveClient(LiveClient): """This live client wraps Selenium. https://selenium-python.readthedocs.io/ """ alias: str = 'selenium' def _handle_init(self): from django.test.selenium import SeleniumTestCaseBase cls = SeleniumTestCaseBase browser = self._browser driver_cls = cls.import_webdriver(browser) return driver_cls(options=cls.import_options(browser)()) def _handle_destroy(self): handle = self.handle if handle: handle.quit() super()._handle_destroy() pytest-djangoapp-1.2.0/pytest_djangoapp/fixtures/mail.py000066400000000000000000000005601443166431300235310ustar00rootroot00000000000000from typing import List import pytest from django.core import mail mail.outbox = [] @pytest.fixture() def mail_outbox() -> List[mail.EmailMessage]: """Returns mail outbox: list of sent message objects. Example:: def test_this(mail_outbox): first_subject = mail_outbox[0].subject """ yield mail.outbox mail.outbox = [] pytest-djangoapp-1.2.0/pytest_djangoapp/fixtures/messages.py000066400000000000000000000026661443166431300244270ustar00rootroot00000000000000from typing import List, Dict import pytest from collections import defaultdict if False: # pragma: nocover from django.contrib.messages.storage.base import Message # noqa class DjangoappMessageStorage: def __init__(self): self.all: List['Message'] = [] self.tags: Dict[str, List['Message']] = defaultdict(list) def __contains__(self, item): for msg in self.all: if item in f'{msg}': return True return False def __len__(self): return len(self.all) def add(self, level, message, extra_tags=''): from django.contrib.messages.storage.base import Message msg = Message(level, message, extra_tags) self.all.append(msg) self.tags[msg.level_tag].append(msg) @pytest.fixture def messages(monkeypatch) -> DjangoappMessageStorage: """Holds messages sent by Django Messages framework. Attributes: * all -- a list of all messages * tags -- messages dictionary indexed by tags Example:: def test_this(messages): assert len(messages.all) assert len(messages.tags['error']) assert 'another error' in messages """ messages = DjangoappMessageStorage() def add(request, level, message, extra_tags='', **kwargs): messages.add(level, message, extra_tags) monkeypatch.setattr('django.contrib.messages.api.add_message', add) return messages pytest-djangoapp-1.2.0/pytest_djangoapp/fixtures/migrations.py000066400000000000000000000013021443166431300247560ustar00rootroot00000000000000import pytest from django import VERSION @pytest.fixture() def check_migrations(command_makemigrations): """Check if migrations are up to date (migration files exist for current models' state). Example:: def test_this(check_migrations): result = check_migrations() :param app: Application name to check migrations for. """ def check_migrations_(app: str = ''): if VERSION < (2, 0): raise Exception('Django 2.0+ required for checking migrations') try: command_makemigrations(app=app, args=['--check', '--dry-run']) except SystemExit: return False return True return check_migrations_ pytest-djangoapp-1.2.0/pytest_djangoapp/fixtures/request.py000066400000000000000000000125141443166431300243010ustar00rootroot00000000000000import pytest from django.test import RequestFactory, Client try: from django.urls import reverse except ImportError: # Django < 2.0 from django.core.urlresolvers import reverse if False: # pragma: nocover from django.contrib.auth.models import AbstractUser # noqa from django.http import HttpRequest def _contribute_ajax(headers, flag): if flag: headers['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest' class DjangoappRequestFactory(RequestFactory): def __init__(self, ajax=False, json=False, **defaults): _contribute_ajax(defaults, ajax) super(DjangoappRequestFactory, self).__init__(**defaults) self._json = json def _encode_json(self, data, content_type): if self._json: content_type = 'application/json' return super(DjangoappRequestFactory, self)._encode_json(data, content_type) def _encode_data(self, data, content_type): if self._json: content_type = 'application/json' return super(DjangoappRequestFactory, self)._encode_data(data, content_type) def generic(self, method, path, *args, **kwargs): if isinstance(path, tuple): path = reverse(path[0], kwargs=path[1]) return super(DjangoappRequestFactory, self).generic(method, path, *args, **kwargs) class DjagoappClient(Client, DjangoappRequestFactory): def __init__( self, *, ajax: bool = False, user: 'AbstractUser' = None, enforce_csrf_checks: bool = False, raise_exceptions: bool = True, json: bool = False, **defaults ): _contribute_ajax(defaults, ajax) super(DjagoappClient, self).__init__(enforce_csrf_checks, json=json, **defaults) if user: assert hasattr(user, 'password_plain'), ( 'Request client expects a user created with `user` or `user_create` fixtures.') logged_in = self.login(username=user.username, password=user.password_plain) else: logged_in = None self.user = user self.user_logged_in = logged_in self._raise_exc = raise_exceptions def store_exc_info(self, **kwargs): if self._raise_exc: super(DjagoappClient, self).store_exc_info(**kwargs) @pytest.fixture def request_factory(): """Fixture allowing request object generation. Example:: def test_this(request_factory): factory = request_factory() :param kwargs: """ def request_factory_(**kwargs) -> DjangoappRequestFactory: return DjangoappRequestFactory(**kwargs) return request_factory_ @pytest.fixture def request_get(request_factory): """Fixture allowing GET request object generation. Example:: def test_this(request_get): request = request_get('/some') :param path: :param user: User making this request. :param ajax: Make AJAX (XMLHttpRequest) request. :param kwargs: Additional arguments for .get() method. """ def request_get_(path: str = None, *, user: 'AbstractUser' = None, ajax: bool = False, **kwargs) -> 'HttpRequest': path = path or '/' request = request_factory(ajax=ajax).get(path, **kwargs) if user: request.user = user return request return request_get_ @pytest.fixture def request_post(request_factory): """Fixture allowing POST request object generation. Example:: def test_this(request_post): request = request_post('/some', {'a': 'b'}) :param path: :param data: Data to post. :param user: User making this request. :param ajax: Make AJAX (XMLHttpRequest) request. :param kwargs: Additional arguments for .post() method. """ def request_post_( path: str = None, data: dict = None, *, user: 'AbstractUser' = None, ajax: bool = False, **kwargs ) -> 'HttpRequest': path = path or '/' request = request_factory(ajax=ajax).post(path, data, **kwargs) if user: request.user = user return request return request_post_ @pytest.fixture def request_client(): """Fixture allowing test client object generation. Example:: def test_this(request_client): client = request_client() response = client.get( ('someview', {'somearg': 'one', 'otherarg': 33}) ).content ... ajax_client = request_client(ajax=True) ... :param ajax: Make AJAX (XMLHttpRequest) requests. :param user: User to perform queries from. :param raise_exceptions: Do not allow Django technical exception handlers to catch exceptions issued by views, propagate them instead. :param json: Encode data as JSON. .. warning:: To be used with Django 2.1+ :param kwargs: Additional arguments for test client initialization. """ def request_client_( *, ajax: bool = False, user: 'AbstractUser' = None, raise_exceptions: bool = True, json: bool = False, **kwargs ) -> DjagoappClient: return DjagoappClient( ajax=ajax, user=user, raise_exceptions=raise_exceptions, json=json, **kwargs ) return request_client_ pytest-djangoapp-1.2.0/pytest_djangoapp/fixtures/settings.py000066400000000000000000000047731443166431300244610ustar00rootroot00000000000000from typing import Any import pytest from django.conf import settings as django_settings _UNSET = set() @pytest.fixture() def settings() -> 'SettingsProxy': """Fixture allowing to temporarily override project settings. Example:: def test_this(settings): # By one. settings.DEBUG = True # Batch. settings.update({ 'DEBUG': True, 'ROOT_URLCONF': 'module.urls', }) # Context manager. with settings(DEBUG=True): ... """ proxy = SettingsProxy() yield proxy proxy.restore_initial() _PROXY_SETTING_ATTRS = '_settings', '_overridden' class SettingsProxy: def __init__(self): self._settings = django_settings self._overridden = {} def __setattr__(self, name: str, value: Any): if name in _PROXY_SETTING_ATTRS: return super(SettingsProxy, self).__setattr__(name, value) self._set(name, value) def __getattr__(self, name: str) -> Any: if name in _PROXY_SETTING_ATTRS: return super(SettingsProxy, self).__getattr__(name) try: return getattr(self._overridden, name) except AttributeError: return getattr(self._settings, name) def __call__(self, **kwargs) -> 'SettingsProxy': # Aid context manager mode. do_set = self._set for key, val in kwargs.items(): do_set(key, val) return self def __enter__(self) -> 'SettingsProxy': return self def __exit__(self, exc_type, exc_val, exc_tb): self.restore_initial() def _set(self, name: str, value: Any): settings = self._settings overridden = self._overridden current_val = getattr(settings, name, _UNSET) if name not in overridden: # Handle subsequent changes. overridden[name] = current_val setattr(settings, name, value) def update(self, settings: dict): """Mass update settings. :param settings: """ for name, value in settings.items(): self._set(name, value) def restore_initial(self): """Restore initial settings.""" settings = self._settings unset = _UNSET for key, val in self._overridden.items(): if val is unset: # wipe delattr(settings, key) else: # restore setattr(settings, key, val) pytest-djangoapp-1.2.0/pytest_djangoapp/fixtures/templates.py000066400000000000000000000102611443166431300246040ustar00rootroot00000000000000import re from typing import Union from unittest import mock import pytest from django import VERSION from django.template.base import Template from django.template.context import Context, RenderContext if False: # pragma: nocover from django.contrib.auth.models import AbstractUser # noqa from django.http import HttpRequest RE_TAG_VALUES = re.compile('>([^<]+)<') @pytest.fixture def template_strip_tags(): """Allows HTML tags strip from string. To be used with `template_render_tag` fixture to easy result assertions. Example:: def test_this(template_strip_tags): stripped = template_strip_tags('some') :param html: HTML to strin tags from :param joiner: String to join tags contents. Default: | """ def template_strip_tags_(html: str, joiner: str = '|') -> str: result = [] for match in RE_TAG_VALUES.findall(html): match = match.strip() if match: result.append(match) return joiner.join(result) return template_strip_tags_ @pytest.fixture def template_context(request_get, user_create): """Creates template context object. To be used with `template_render_tag` fixture. Example:: def test_this(template_context): context = template_context({'somevar': 'someval'}) :param context_dict: Template context. If not set empty context is used. :param request: Expects HttpRequest or string. String is used as a path for GET-request. :param current_app: :param user: User instance to associate request with. Defaults to a new anonymous user. If string is passed, it is considered to be """ def template_context_( context_dict: dict = None, *, request: 'HttpRequest' = None, current_app: str = '', user: Union[str, 'AbstractUser'] = 'anonymous' ) -> Context: context_dict = context_dict or {} if user and isinstance(user, str): if user == 'anonymous': user = user_create(anonymous=True) else: user = user_create(attributes={'username': user}) if not request or isinstance(request, str): request = request_get(request, user=user) context_updater = { 'request': request, } if user: context_updater['user'] = user context_dict.update(context_updater) context = Context(context_dict) contribute_to_context(context, current_app) return context return template_context_ @pytest.fixture def template_render_tag(): """Renders a template tag from a given library by its name. Example:: def test_this(template_render_tag): rendered = template_render_tag('library_name', 'mytag arg1 arg2') :param library: Template tags library name to load tag from. :param tag_str: Tag string itself. As used in templates, but without {% %}. :param context: Template context object. If not set, empty context object is used. """ def template_render_tag_(library: str, tag_str: str, context: Union[dict, Context] = None) -> str: context = context or {} if not isinstance(context, Context): context = Context(context) string = f'{{% load {library} %}}{{% {tag_str} %}}' template = Template(string) contribute_to_context(context, template=template) if VERSION >= (1, 11): # Prevent "TypeError: 'NoneType' object is not iterable" in get_exception_info template.nodelist[1].token.position = (0, 0) return template.render(context) return template_render_tag_ def contribute_to_context(context: Context, current_app: str = '', template: Template = None): template = template or mock.MagicMock() if VERSION >= (1, 8): template.engine.string_if_invalid = '' context.template = template if VERSION >= (1, 11): context.render_context = RenderContext() if VERSION >= (1, 10): match = mock.MagicMock() match.app_name = current_app context.resolver_match = match else: context._current_app = current_app pytest-djangoapp-1.2.0/pytest_djangoapp/fixtures/users.py000066400000000000000000000041051443166431300237470ustar00rootroot00000000000000from typing import Union import pytest from .utils import get_stamp if False: # pragma: nocover from django.contrib.auth.models import AbstractUser, AnonymousUser # noqa TypeUser = Union['AbstractUser', 'AnonymousUser'] @pytest.fixture() def user_model() -> TypeUser: """Returns user model class. Example:: def test_this(user_model): model_cls = user_model """ from django.contrib.auth import get_user_model return get_user_model() @pytest.fixture() def user_create(user_model): """Allows Django user object generation. Example:: def test_this(user_create): user = user_create() .. note:: User password is accessible via `password_plain` attribute. :param superuser: Whether to create a superuser. :param anonymous: Whether to create an anonymous user. :param attributes: Additional user object attributes to initialize. """ from django.contrib.auth.models import AnonymousUser def user_create_(*, superuser: bool = False, anonymous: bool = False, attributes: dict = None) -> TypeUser: if anonymous: return AnonymousUser() attributes = attributes or {} manager = user_model._default_manager username = (('admin' if superuser else 'user') + '_' + get_stamp()) kwargs = { 'username': username, 'email': f'{username}@example.com', 'password': 'password', } kwargs.update(attributes) if superuser: user = manager.create_superuser(**kwargs) else: user = manager.create_user(**kwargs) # Keep plain password for test purposes. user.password_plain = kwargs['password'] return user return user_create_ @pytest.fixture() def user(user_create) -> TypeUser: """Exposes Django user object. Shortcut for `user_create` fixture. Example:: def test_this(user): username = user.username .. note:: User password is accessible via `password_plain` attribute. """ return user_create() pytest-djangoapp-1.2.0/pytest_djangoapp/fixtures/utils.py000066400000000000000000000005531443166431300237510ustar00rootroot00000000000000from time import time import pytest from ..configuration import Configuration def get_stamp() -> str: """Returns current timestamp as a string.""" return f'{time()}' @pytest.fixture(scope='session') def conf_app_name() -> str: """Returns your application name (deduced or provided).""" return Configuration.get_dict()[Configuration.KEY_APP] pytest-djangoapp-1.2.0/pytest_djangoapp/plugin.py000066400000000000000000000020431443166431300222320ustar00rootroot00000000000000from django.conf import settings as django_settings from django.core.management import call_command from django.test.runner import DiscoverRunner from .fixtures import * # noqa from .toolbox import Configuration runner = DiscoverRunner(interactive=False, verbosity=0) setup_databases = runner.setup_databases teardown_databases = runner.teardown_databases def pytest_runtest_setup(item): # todo optional db initialization item.old_config = setup_databases() def pytest_runtest_teardown(item, nextitem): unset = {} old_config = getattr(item, 'old_config', unset) if old_config is unset: # _teardown will suddenly work even if no _setup has occured # e.g. in case of mark.skipif return call_command('flush', interactive=False, reset_sequences=False) teardown_databases(old_config) def pytest_configure(config): import django settings_dict = Configuration.get_combined(config) django_settings.configure(**settings_dict) django.setup() runner.verbosity = config.option.verbose pytest-djangoapp-1.2.0/pytest_djangoapp/tests/000077500000000000000000000000001443166431300215255ustar00rootroot00000000000000pytest-djangoapp-1.2.0/pytest_djangoapp/tests/__init__.py000066400000000000000000000000001443166431300236240ustar00rootroot00000000000000pytest-djangoapp-1.2.0/pytest_djangoapp/tests/conftest.py000066400000000000000000000012031443166431300237200ustar00rootroot00000000000000from pytest_djangoapp import configure_djangoapp_plugin def hook(settings): settings['HOOKED'] = True return settings pytest_plugins = configure_djangoapp_plugin( admin_contrib=True, extend_INSTALLED_APPS=[ 'django.contrib.sites', ], extend_MIDDLEWARE=[ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', # Bogus doubled check. ], extend_DATABASES={ 'dummy': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, }, settings_hook=hook, migrate=True, ) pytest-djangoapp-1.2.0/pytest_djangoapp/tests/settings_project.py000066400000000000000000000002431443166431300254640ustar00rootroot00000000000000from django.utils.translation import gettext_lazy as _ # noqa SOME_ATTR = 'some value' # this attr won't go into project config. def some_function(): pass pytest-djangoapp-1.2.0/pytest_djangoapp/tests/test_configuration.py000066400000000000000000000014451443166431300260110ustar00rootroot00000000000000import pytest from pytest_djangoapp.configuration import Configuration def test_configration(pytestconfig): settings = Configuration.get() settings[Configuration.KEY_APP] = 'some' assert Configuration.get_combined(pytestconfig) settings[Configuration.KEY_APP] = '' assert Configuration.get_combined(pytestconfig) def swap_dir(level): old_dir = pytestconfig.invocation_dir try: pytestconfig.invocation_dir = old_dir.parts()[level] assert Configuration.get_combined(pytestconfig) finally: pytestconfig.invocation_dir = old_dir with pytest.raises(Exception): # Unable to deduce app name. swap_dir(-4) def test_settings_hook(): from django.conf import settings assert settings.HOOKED pytest-djangoapp-1.2.0/pytest_djangoapp/tests/test_etc.py000066400000000000000000000012461443166431300237140ustar00rootroot00000000000000import sys import pytest from pytest_djangoapp import configure_djangoapp_plugin from pytest_djangoapp.configuration import Configuration @pytest.mark.skipif(sys.version_info > (2, 0), reason='teardown without setup should pass') def test_teardown_without_setup(): assert True @pytest.mark.skipif(sys.version_info < (3, 0), reason='whole project test are for Py 3') def test_whole_project_testing(request): configure_djangoapp_plugin('pytest_djangoapp.tests.settings_project') settings_dict = Configuration.get_combined(request.config) assert '_' not in settings_dict assert 'SOME_ATTR' in settings_dict assert 'some_function' not in settings_dict pytest-djangoapp-1.2.0/pytest_djangoapp/tests/test_fixtures_commands.py000066400000000000000000000010111443166431300266610ustar00rootroot00000000000000from django import VERSION def test_command_run(command_run, capsys): result = command_run('my_command', args=['one'], options={'two': 'three'}) out, err = capsys.readouterr() assert 'bingo' in out assert 'bongo' in err if VERSION >= (1, 10): assert result == 'one|three' def test_command_migration(command_makemigrations, capsys): result = command_makemigrations() out, err = capsys.readouterr() assert result is None assert 'No changes' in out assert err == '' pytest-djangoapp-1.2.0/pytest_djangoapp/tests/test_fixtures_live.py000066400000000000000000000014021443166431300260230ustar00rootroot00000000000000from unittest.mock import MagicMock import pytest from django import VERSION @pytest.mark.skipif(VERSION < (4, 0), reason='For Django 4.0+') def test_liveserver(liveserver, liveclient): with liveserver(host='localhost', port=33445) as server: assert server.url == 'http://localhost:33445' @pytest.mark.skipif(VERSION < (4, 0), reason='For Django 4.0+') def test_selenium(liveserver, liveclient, monkeypatch): monkeypatch.setattr('django.test.selenium.SeleniumTestCaseBase', MagicMock()) with liveserver() as server: with liveclient('selenium', browser='firefox') as client: selenium = client.handle selenium.get(server.url) assert 'MagicMock' in f"{selenium.find_element('tag name', 'h1').text}" pytest-djangoapp-1.2.0/pytest_djangoapp/tests/test_fixtures_mail.py000066400000000000000000000004651443166431300260160ustar00rootroot00000000000000from django.core.mail import send_mail def test_mail_outbox(mail_outbox): send_mail( 'Subject here', 'Here is the message.', 'from@example.com', ['to@example.com'], fail_silently=False, ) assert len(mail_outbox) == 1 assert mail_outbox[0].subject == 'Subject here' pytest-djangoapp-1.2.0/pytest_djangoapp/tests/test_fixtures_messages.py000066400000000000000000000006771443166431300267100ustar00rootroot00000000000000 def test_messages(messages): assert not messages.all from django.contrib import messages as djmessages djmessages.error(None, 'this is error') djmessages.error(None, 'ещё ошибка') djmessages.info(None, 'some info') assert len(messages) == 3 assert len(messages.tags['error']) == 2 assert len(messages.tags['info']) == 1 assert 'ещё ошибка' in messages assert 'other' not in messages pytest-djangoapp-1.2.0/pytest_djangoapp/tests/test_fixtures_migrations.py000066400000000000000000000015741443166431300272520ustar00rootroot00000000000000import re import pytest from django import VERSION @pytest.mark.skipif(VERSION < (2, 0), reason='Django 2.0+ required') def test_check_migrations_missing(check_migrations): result = check_migrations('testapp_missing_migrations') assert result is False, 'Migrations should be missing in testapp_missing_migrations' @pytest.mark.skipif(VERSION < (2, 0), reason='Django 2.0+ required') def test_check_migrations_ok(check_migrations): result = check_migrations() assert result, ( "ERROR: Migrations check failed! Models' changes not migrated, " "please run './manage.py makemigrations' to solve the issue!" ) @pytest.mark.skipif(VERSION >= (2, 0), reason='Testing Django 1.9- required') def test_old_django(check_migrations): with pytest.raises(Exception, match=re.escape('Django 2.0+ required for checking migrations')): check_migrations() pytest-djangoapp-1.2.0/pytest_djangoapp/tests/test_fixtures_request.py000066400000000000000000000025671443166431300265710ustar00rootroot00000000000000def test_request_factory(request_factory): assert request_factory() def test_request_get(request_get, user_create): assert request_get(user=user_create()) assert request_get(ajax=True) def test_request_post(request_post, user_create): assert request_post(data={'a': 'b'}, user=user_create()) assert request_post(ajax=True, data={'a': 'b'}) def test_request_client(request_client, user_create): client = request_client() assert client assert client.user is None assert not client.user_logged_in response = client.get(('index', {'some_id': 10})) assert response.status_code == 200 assert response.content == b'10 | fine /static/blank.png' # Now AJAX client. client = request_client(ajax=True) response = client.get(('index', {'some_id': 22})) assert response.status_code == 200 assert b'ajaxed' in response.content new_user = user_create() client = request_client(user=new_user) assert client.user is new_user assert client.user_logged_in # now technical 500 view client = request_client(raise_exceptions=False) response = client.get('/raiser/') assert b'

Server Error (500)

' in response.content # now json client = request_client(json=True) response = client.post(('index', {'some_id': 10}), {'a': 'b'}) content = response.content assert b'json' in content pytest-djangoapp-1.2.0/pytest_djangoapp/tests/test_fixtures_settings.py000066400000000000000000000046121443166431300267320ustar00rootroot00000000000000import pytest def test_settings(settings): from django.conf import settings as _actual_settings assert not _actual_settings.DEBUG settings.update({ 'DEBUG': True, 'SOMENEW': 'value', }) assert settings.DEBUG assert settings.SOMENEW == 'value' assert _actual_settings.DEBUG assert _actual_settings.SOMENEW == 'value' settings.SOMENEW = 'other' assert settings.SOMENEW == 'other' assert _actual_settings.SOMENEW == 'other' def test_context_manager(settings): from django.conf import settings as _actual_settings assert not _actual_settings.DEBUG with settings(SOME=1, DEBUG=True): assert settings.SOME == 1 assert settings.DEBUG assert _actual_settings.SOME == 1 assert _actual_settings.DEBUG settings.OTHER = 1 assert settings.OTHER == 1 assert _actual_settings.OTHER == 1 assert not hasattr(settings, 'SOME') assert not hasattr(settings, 'OTHER') assert not _actual_settings.DEBUG assert not hasattr(_actual_settings, 'SOME') assert not hasattr(_actual_settings, 'OTHER') assert 'django.contrib.sites' in _actual_settings.INSTALLED_APPS assert 'django.contrib.sessions.middleware.SessionMiddleware' in _actual_settings.MIDDLEWARE assert 'django.contrib.sessions.middleware.SessionMiddleware' in _actual_settings.MIDDLEWARE_CLASSES assert 'dummy' in _actual_settings.DATABASES settings.DEBUG = False assert not _actual_settings.DEBUG settings.SOME = 2 assert settings.SOME == 2 assert _actual_settings.SOME == 2 with settings(SOME='value', DEBUG=True): assert settings.SOME == 'value' assert settings.DEBUG assert _actual_settings.SOME == 'value' assert _actual_settings.DEBUG assert not settings.DEBUG assert not _actual_settings.DEBUG # SOME from before the context manager is now removed. assert not hasattr(settings, 'SOME') assert not hasattr(_actual_settings, 'SOME') with settings: settings.OTHER = 1 assert settings.OTHER == 1 assert _actual_settings.OTHER == 1 assert not _actual_settings.DEBUG assert not hasattr(settings, 'SOME') assert not hasattr(settings, 'OTHER') assert not hasattr(_actual_settings, 'SOME') assert not hasattr(_actual_settings, 'OTHER') settings.OTHER = 1 assert settings.OTHER == 1 pytest-djangoapp-1.2.0/pytest_djangoapp/tests/test_fixtures_templates.py000066400000000000000000000012461443166431300270700ustar00rootroot00000000000000 def test_template_context(template_context, user_create): assert template_context({'somevar': 'someval'}) context = template_context({'a': 'b'}, user='aname') assert context.get('user').username == 'aname' auser = user_create(attributes={'username': 'xx'}) context = template_context({'a': 'b'}, user=auser) assert context.get('user').username == 'xx' def test_template_render_tag(template_render_tag): rendered = template_render_tag('static', 'static "some.jpg"') assert rendered == '/static/some.jpg' def test_this_template_strip_tags(template_strip_tags): stripped = template_strip_tags('some') assert stripped == 'some' pytest-djangoapp-1.2.0/pytest_djangoapp/tests/test_fixtures_users.py000066400000000000000000000005061443166431300262310ustar00rootroot00000000000000 def test_user_create(user_create): assert not user_create().is_superuser assert user_create(superuser=True).is_superuser assert user_create(anonymous=True).is_anonymous def test_user_model(user_model): assert user_model def test_user(user): assert user assert user.password_plain == 'password' pytest-djangoapp-1.2.0/pytest_djangoapp/tests/test_fixtures_utils.py000066400000000000000000000001301443166431300262210ustar00rootroot00000000000000 def test_conf_app_name(conf_app_name): assert conf_app_name == 'pytest_djangoapp' pytest-djangoapp-1.2.0/pytest_djangoapp/tests/test_models.py000066400000000000000000000011271443166431300244220ustar00rootroot00000000000000import pytest from pytest_djangoapp.tests.testapp.models import Article from django import VERSION def test_models_basic(): article = Article(title='my title') article.save() @pytest.mark.skipif(VERSION < (1, 9), reason='Django 1.9+ required') def test_db_queries(db_queries): assert len(db_queries) == 0 article = Article(title='my title') article.save() print(db_queries.get_log()) assert len(db_queries) == 1 if VERSION >= (2, 2) else 2 assert len(db_queries.sql()) == 1 # auxiliary sql filtered assert db_queries.time() < 1 db_queries.clear() pytest-djangoapp-1.2.0/pytest_djangoapp/tests/testapp/000077500000000000000000000000001443166431300232055ustar00rootroot00000000000000pytest-djangoapp-1.2.0/pytest_djangoapp/tests/testapp/__init__.py000066400000000000000000000000001443166431300253040ustar00rootroot00000000000000pytest-djangoapp-1.2.0/pytest_djangoapp/tests/testapp/management/000077500000000000000000000000001443166431300253215ustar00rootroot00000000000000pytest-djangoapp-1.2.0/pytest_djangoapp/tests/testapp/management/__init__.py000066400000000000000000000000001443166431300274200ustar00rootroot00000000000000pytest-djangoapp-1.2.0/pytest_djangoapp/tests/testapp/management/commands/000077500000000000000000000000001443166431300271225ustar00rootroot00000000000000pytest-djangoapp-1.2.0/pytest_djangoapp/tests/testapp/management/commands/__init__.py000066400000000000000000000000001443166431300312210ustar00rootroot00000000000000pytest-djangoapp-1.2.0/pytest_djangoapp/tests/testapp/management/commands/compat.py000066400000000000000000000013371443166431300307630ustar00rootroot00000000000000class CommandOption: """Command line option wrapper.""" def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def options_getter(command_options): """Compatibility function to get rid of optparse in management commands after Django 1.10. :param tuple command_options: tuple with `CommandOption` objects. """ def get_options(option_func=None): from optparse import make_option func = option_func or make_option options = tuple([func(*option.args, **option.kwargs) for option in command_options]) if option_func is None: result = [] else: result = options return result return get_options pytest-djangoapp-1.2.0/pytest_djangoapp/tests/testapp/management/commands/my_command.py000066400000000000000000000011501443166431300316140ustar00rootroot00000000000000from django.core.management.base import BaseCommand from .compat import options_getter, CommandOption get_options = options_getter(( CommandOption('--two', action='store'), )) class Command(BaseCommand): help = 'Sends scheduled messages (both in pending and error statuses).' option_list = get_options() def add_arguments(self, parser): parser.add_argument('one') get_options(parser.add_argument) def handle(self, one, **options): self.stdout.write('bingo') self.stderr.write('bongo') two = options.get('two', None) return f'{one}|{two}' pytest-djangoapp-1.2.0/pytest_djangoapp/tests/testapp/migrations/000077500000000000000000000000001443166431300253615ustar00rootroot00000000000000pytest-djangoapp-1.2.0/pytest_djangoapp/tests/testapp/migrations/0001_initial.py000066400000000000000000000007511443166431300300270ustar00rootroot00000000000000# Generated by Django 3.2.15 on 2022-11-08 15:59 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Article', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=200)), ], ), ] pytest-djangoapp-1.2.0/pytest_djangoapp/tests/testapp/migrations/__init__.py000066400000000000000000000000001443166431300274600ustar00rootroot00000000000000pytest-djangoapp-1.2.0/pytest_djangoapp/tests/testapp/models.py000066400000000000000000000001521443166431300250400ustar00rootroot00000000000000from django.db import models class Article(models.Model): title = models.CharField(max_length=200) pytest-djangoapp-1.2.0/pytest_djangoapp/tests/testapp/urls.py000066400000000000000000000014751443166431300245530ustar00rootroot00000000000000try: from django.urls import re_path except ImportError: from django.conf.urls import url as re_path from django.http import HttpResponse from pytest_djangoapp.compat import get_urlpatterns def raise_exception(request): raise Exception('This one should be handled by 500 technical view') def index(request, some_id): if request.method == 'POST': return HttpResponse('json') if request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest': # .headers in Django 2.2+ return HttpResponse('ajaxed') from django.templatetags.static import static return HttpResponse(f"{some_id} | fine {static('blank.png')}") urlpatterns = get_urlpatterns([ re_path(r'^index/(?P\d+)/$', index, name='index'), re_path(r'^raiser/$', raise_exception, name='raiser'), ]) pytest-djangoapp-1.2.0/pytest_djangoapp/tests/testapp_missing_migrations/000077500000000000000000000000001443166431300271725ustar00rootroot00000000000000pytest-djangoapp-1.2.0/pytest_djangoapp/tests/testapp_missing_migrations/__init__.py000066400000000000000000000000001443166431300312710ustar00rootroot00000000000000pytest-djangoapp-1.2.0/pytest_djangoapp/tests/testapp_missing_migrations/migrations/000077500000000000000000000000001443166431300313465ustar00rootroot00000000000000pytest-djangoapp-1.2.0/pytest_djangoapp/tests/testapp_missing_migrations/migrations/__init__.py000066400000000000000000000000001443166431300334450ustar00rootroot00000000000000pytest-djangoapp-1.2.0/pytest_djangoapp/tests/testapp_missing_migrations/models.py000066400000000000000000000001521443166431300310250ustar00rootroot00000000000000from django.db import models class Article(models.Model): title = models.CharField(max_length=200) pytest-djangoapp-1.2.0/pytest_djangoapp/toolbox.py000066400000000000000000000060031443166431300224220ustar00rootroot00000000000000from functools import partial from typing import Union, Callable from .configuration import Configuration def configure_djangoapp_plugin( settings: Union[str, dict] = None, *, app_name: str = None, admin_contrib: bool = False, settings_hook: Callable = None, migrate: bool = True, **kwargs ) -> str: """Configures djangoapp pytest plugin. :param settings: Django project settings to override defaults. To get settings from a module (for testing an entire project, not just one app) use a string with the module name. :param app_name: Name of your application you write tests for. If not set ``djangoapp`` will try to guess (``tests`` dir needs to be inside application directory). :param admin_contrib: Setup Django to test Admin contrib related parts. :param settings_hook: Allows setting a function to get resulting settings. Function must accept settings dictionary, and return resulting settings dictionary. .. code-block:: python def hook_func(settings): return settings :param bool migrate: Allows applying or skipping migration applying process. Skipping could be useful for testing applications with many migrations. :param kwargs: Additional arguments. Use `extend_` prefix to extend default configuration. .. code:: python configure_djangoapp_plugin( extend_INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions' ], extend_DATABASES={ 'dummy': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, }, ) :returns: Plugin name to add into ``pytest_plugins`` module attribute of ``conftest.py``. """ try: import django except ImportError: # pragma: nocover raise Exception('Django is not available in test environment. Please install it.') if isinstance(settings, str): # Considering a whole project testing mode. settings_hook = partial(update_settings_from_module, module=settings) settings = {} Configuration.set( settings_dict=settings, app_name=app_name, admin_contrib=admin_contrib, settings_hook=settings_hook, migrate=migrate, **kwargs ) return 'pytest_djangoapp.plugin' def update_settings_from_module(settings: dict, *, module: str) -> dict: """Updates a given settings dict from a module denoted by a dotted path. :param settings: :param module: """ from importlib import import_module settings_module = import_module(module) settings_dict = { key: value for key, value in settings_module.__dict__.items() if key.upper() == key and not key.startswith('_') } settings.update(settings_dict) return settings pytest-djangoapp-1.2.0/setup.cfg000066400000000000000000000001071443166431300166270ustar00rootroot00000000000000[aliases] release = clean --all sdist bdist_wheel upload test = pytest pytest-djangoapp-1.2.0/setup.py000066400000000000000000000042771443166431300165340ustar00rootroot00000000000000import io import os import re import sys from setuptools import setup, find_packages PY2 = sys.version_info[0] == 2 PATH_BASE = os.path.dirname(__file__) PYTEST_RUNNER = ['pytest-runner'] if 'test' in sys.argv else [] def read_file(fpath): """Reads a file within package directories.""" with io.open(os.path.join(PATH_BASE, fpath)) as f: return f.read() def get_version(): """Returns version number, without module import (which can lead to ImportError if some dependencies are unavailable before install.""" contents = read_file(os.path.join('pytest_djangoapp', '__init__.py')) version = re.search('VERSION = \(([^)]+)\)', contents) version = version.group(1).replace(', ', '.').strip() return version install_requires = [ 'pytest', ] if PY2: install_requires.append('mock') # unittest.mock only since Python 3.3 setup( name='pytest-djangoapp', version=get_version(), url='https://github.com/idlesign/pytest-djangoapp', description='Nice pytest plugin to help you with Django pluggable application testing.', long_description=read_file('README.rst'), license='BSD 3-Clause License', author='Igor `idle sign` Starikov', author_email='idlesign@yandex.ru', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=install_requires, setup_requires=[] + PYTEST_RUNNER, tests_require=['pytest'], test_suite='tests', classifiers=[ # As in https://pypi.python.org/pypi?:action=list_classifiers 'Development Status :: 4 - Beta', 'Framework :: Pytest', 'Framework :: Django', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Topic :: Software Development :: Testing', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Programming Language :: Python :: 3.11', 'License :: OSI Approved :: BSD License' ], ) pytest-djangoapp-1.2.0/tox.ini000066400000000000000000000013361443166431300163260ustar00rootroot00000000000000# See http://tox.readthedocs.org/en/latest/examples.html for samples. [tox] envlist = py{37,38}-django{18,19,110,111,20,21,22} py{36,37,38,39,310,311}-django{30,31,32,40,41,42} skip_missing_interpreters = True install_command = pip install {opts} {packages} [testenv] commands = python setup.py test deps = django18: Django>=1.8,<1.9 django19: Django>=1.9,<1.10 django110: Django>=1.10,<1.11 django111: Django>=1.11,<1.12 django20: Django>=2.0,<2.1 django21: Django>=2.1,<2.2 django22: Django>=2.2,<2.3 django30: Django>=3.0,<3.1 django31: Django>=3.1,<3.2 django32: Django>=3.2,<3.3 django40: Django>=4.0,<4.1 django41: Django>=4.1,<4.2 django42: Django>=4.2,<4.3