├── .gitignore ├── .travis.yml ├── AUTHORS.rst ├── CHANGELOG.rst ├── LICENSE ├── README.rst ├── docs ├── Makefile ├── make.bat └── source │ ├── conf.py │ ├── index.rst │ ├── reference.rst │ └── tutorial.rst ├── requirements.txt ├── rest_assured ├── __init__.py ├── contrib │ ├── __init__.py │ └── drf_fsm_transitions.py └── testcases.py ├── setup.py ├── tests ├── __init__.py ├── conftest.py ├── mocks.py ├── models.py ├── test_base.py ├── test_create.py ├── test_destroy.py ├── test_detail.py ├── test_list.py ├── test_update.py └── urls.py └── tox.ini /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .gitignore support plugin (hsz.mobi) 2 | ### Python template 3 | # Byte-compiled / optimized / DLL files 4 | __pycache__/ 5 | *.py[cod] 6 | 7 | # C extensions 8 | *.so 9 | 10 | # Distribution / packaging 11 | .Python 12 | env/ 13 | build/ 14 | develop-eggs/ 15 | dist/ 16 | eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | *.egg-info/ 23 | .installed.cfg 24 | *.egg 25 | 26 | # PyInstaller 27 | # Usually these files are written by a python script from a template 28 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 29 | *.manifest 30 | *.spec 31 | 32 | # Installer logs 33 | pip-log.txt 34 | pip-delete-this-directory.txt 35 | 36 | # Unit test / coverage reports 37 | htmlcov/ 38 | .tox/ 39 | .coverage 40 | .cache 41 | nosetests.xml 42 | coverage.xml 43 | 44 | # Translations 45 | *.mo 46 | *.pot 47 | 48 | # Django stuff: 49 | *.log 50 | 51 | # Sphinx documentation 52 | docs/_build/ 53 | 54 | # PyBuilder 55 | target/ 56 | 57 | .idea/ 58 | 59 | test.sh 60 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | dist: bionic 2 | 3 | language: python 4 | 5 | python: 6 | - 2.7 7 | - 3.5 8 | - 3.6 9 | - 3.7 10 | - 3.8 11 | 12 | matrix: 13 | fast_finish: true 14 | 15 | install: 16 | - pip install tox tox-travis 17 | 18 | script: 19 | - tox 20 | -------------------------------------------------------------------------------- /AUTHORS.rst: -------------------------------------------------------------------------------- 1 | Authored by: 2 | ------------ 3 | 4 | Yehonatan Daniv @ydaniv 5 | 6 | 7 | With contributions by: 8 | ---------------------- 9 | 10 | Tymur Maryokhin @maryokhin 11 | Yuri Prezument @yprez 12 | @alepn 13 | @sramana 14 | @gomlgs 15 | @belugame 16 | Nikita Sobolev @sobolevn 17 | -------------------------------------------------------------------------------- /CHANGELOG.rst: -------------------------------------------------------------------------------- 1 | 0.2.3 (2020-07-31) 2 | ------------------ 3 | 4 | *Fixed:* 5 | 6 | - Fixed ``long_description`` for PyPI. 7 | 8 | 0.2.2 (2020-07-31) 9 | ------------------ 10 | 11 | *Support:* 12 | 13 | - Updated support and now also tested against Django 3.0, and Python 3.8. 14 | 15 | 0.2.1 (2017-21-21) 16 | ------------------ 17 | 18 | *Fixed:* 19 | 20 | - Fixed bug that caused attribute checks in ``test_detail`` with callables in ``attributes_to_check`` to fail. 21 | 22 | *Removed:* 23 | 24 | - Official support for Python 3.2 since it's not supported by py.test. 25 | 26 | 0.2.0 (2015-11-27) 27 | ------------------ 28 | 29 | *Support:* 30 | 31 | - Updated support and now also tested against Django 1.8, and DRF 3.1, 3.2 and 3.3. 32 | 33 | *Breaking:* 34 | 35 | - A new ``pagination_results_field`` attribute on the ``ListAPITestCaseMixin`` that controls the name of the key the result set is nested under. This was previously hardcoded to ``'results'`` but now defaults to ``None``, which means the test assumes pagination is turned off. 36 | 37 | *New:* 38 | 39 | - ``response_lookup_field`` attribute and corresponding ``get_lookup_from_response()`` to ``CreateAPITestCaseMixin`` for custom lookups of the created object in DB from the response data. 40 | 41 | - ``relationship_lookup_field`` attribute and corresponding ``get_relationship_value()`` to ``UpdateAPITestCaseMixin`` for custom lookups of related objects, e.g. when using a ``HyperlinkedRelatedField``. 42 | 43 | - Added missing kwargs in ``get_update_response()`` (Thanks, @sramana!). 44 | 45 | - Allow passing a dictionary to ``_update_check_db()`` for performing checks on serialized object. 46 | 47 | - ``data`` argument to ``TransitionAPITestCaseMixin.transition()`` to pass to ``client.post()`` as data. 48 | 49 | *Removed:* 50 | 51 | - Related objects with a ``uuid`` field are not looked up automatically anymore. Use the new ``relationship_lookup_field`` attribute and ``get_relationship_value()`` method. 52 | 53 | 0.1 (2014-12-21) 54 | ---------------- 55 | 56 | *New:* 57 | 58 | - First public stable version of Django-REST-Assured. 59 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2014-2020, Yehonatan Daniv 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | Redistributions of source code must retain the above copyright notice, this 7 | list of conditions and the following disclaimer. 8 | Redistributions in binary form must reproduce the above copyright notice, this 9 | list of conditions and the following disclaimer in the documentation and/or 10 | other materials provided with the distribution. 11 | 12 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 13 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 14 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 15 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 16 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 17 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 18 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 20 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 21 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 22 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | django-rest-assured 2 | =================== 3 | 4 | .. image:: https://secure.travis-ci.org/ydaniv/django-rest-assured.svg 5 | :target: http://travis-ci.org/ydaniv/django-rest-assured/ 6 | :alt: Build 7 | 8 | .. image:: https://pypip.in/download/django-rest-assured/badge.svg 9 | :target: https://pypi.python.org/pypi/django-rest-assured/ 10 | :alt: Downloads 11 | 12 | .. image:: https://pypip.in/version/django-rest-assured/badge.svg 13 | :target: https://pypi.python.org/pypi/django-rest-assured/ 14 | :alt: Latest Version 15 | 16 | .. image:: https://pypip.in/license/django-rest-assured/badge.svg 17 | :target: https://pypi.python.org/pypi/django-rest-assured/ 18 | :alt: License 19 | 20 | 21 | Instantly test-cover your Django REST Framework based API. 22 | 23 | Django-REST-Assured adds another layer on top of 24 | Django REST Framework's `APITestCase `_ 25 | which allows covering a set of RESTful resource's endpoints with a single class declaration. 26 | 27 | This gives both a quick coverage of sanity tests to your API and a more DRY and more friendly 28 | platform for writing additional, more comprehensive tests. 29 | 30 | 31 | As easy as 32 | ---------- 33 | .. code-block:: python 34 | 35 | class CategoryTestCase(ReadWriteRESTAPITestCaseMixin, BaseRESTAPITestCase): 36 | 37 | base_name = 'category' 38 | factory_class = CategoryFactory 39 | create_data = {'name': 'comedy'} 40 | update_data = {'name': 'horror'} 41 | 42 | Django-REST-Assured is designed to work with `factory_boy `_ 43 | for mocking objects to test against. However, you can easily extend the ``BaseRESTAPITestCase`` 44 | to work directly with Django Models or any other factory. 45 | 46 | 47 | Main features 48 | ------------- 49 | 50 | * Class-based declarative API for creating tests. 51 | * Covers the stack through: ``route > view > serializer > model``. 52 | * Uses Django REST Framework's conventions to minimize configuration. 53 | * All tests return the response object for more extensive assertions. 54 | * Automatic mocking of authentication if a user factory is provided. 55 | 56 | 57 | Usage 58 | ----- 59 | 60 | The basic form of usage is simply to create a class that extends 61 | any mixin from ``rest_assured.testcases``, according to the 62 | endpoints you wish to cover, and the ``BaseRESTAPITestCase`` class. 63 | 64 | Then just set the required attributes, and continue extending it from there. 65 | 66 | .. admonition:: example 67 | 68 | .. code:: python 69 | 70 | class CategoryAPITestCase(ReadWriteRESTAPITestCaseMixin, BaseRESTAPITestCase): 71 | 72 | base_name = 'category' 73 | factory_class = Category 74 | create_data = {'name': 'documentary'} 75 | update_data = {'name': 'horror'} 76 | 77 | If your API requires authentication and/or authorization just add 78 | a user factory class. Assuming you use `factory_boy `_: 79 | 80 | .. admonition:: example 81 | 82 | .. code:: python 83 | 84 | # in some factories.py module in your accounts app 85 | class User(factory.DjangoModelFactory): 86 | 87 | class Meta: 88 | model = User 89 | exclude = ('raw_password',) 90 | 91 | first_name = 'Robert' 92 | last_name = factory.Sequence(lambda n: 'Paulson the {0}'.format(n)) 93 | email = factory.sequence(lambda n: 'account{0}@example.com'.format(n)) 94 | username = 'mayhem' 95 | raw_password = '123' 96 | password = factory.PostGenerationMethodCall('set_password', raw_password) 97 | is_active = True 98 | 99 | 100 | # now back in your tests.py module 101 | class CategoryAPITestCase(ReadWriteRESTAPITestCaseMixin, BaseRESTAPITestCase): 102 | 103 | base_name = 'category' 104 | factory_class = Category 105 | # see here: 106 | user_factory = User 107 | create_data = {'name': 'documentary'} 108 | update_data = {'name': 'horror'} 109 | 110 | 111 | 112 | Supports 113 | -------- 114 | 115 | Support is determined by which Django versions are supported, and the Python and Django REST Framework versions that go with them. Tests run against all Django versions supported as of July 28, 2020. 116 | 117 | * Django 1.11 with Django REST Framework 3.4 - 3.6 and Python 2.7 and 3.5. 118 | * Django 2.1 and 2.2 with Django REST Framework 3.7-3.10 and Python 3.5-3.8. 119 | * Django 3.0 with Django REST Framework 3.10 and Python 3.7-3.8. 120 | 121 | 122 | Installation 123 | ------------ 124 | 125 | PyPI: https://pypi.python.org/pypi/django-rest-assured 126 | 127 | .. code-block:: sh 128 | 129 | $ pip install django-rest-assured 130 | 131 | Source: https://github.com/ydaniv/django-rest-assured 132 | 133 | .. code-block:: sh 134 | 135 | $ git clone https://github.com/ydaniv/django-rest-assured 136 | $ python setup.py install 137 | 138 | 139 | Contributing 140 | ------------ 141 | 142 | Issues are tracked in the `github repository `_. 143 | 144 | Pull requests are welcome! 145 | 146 | 147 | Running tests 148 | ------------- 149 | 150 | .. code-block:: sh 151 | 152 | $ pip install pytest pytest-django 153 | $ py.test 154 | 155 | 156 | License 157 | ------- 158 | 159 | Django-REST-Assured is distributed under the BSD license. 160 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/django-rest-assured.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/django-rest-assured.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/django-rest-assured" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/django-rest-assured" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source 10 | set I18NSPHINXOPTS=%SPHINXOPTS% source 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | goto end 41 | ) 42 | 43 | if "%1" == "clean" ( 44 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 45 | del /q /s %BUILDDIR%\* 46 | goto end 47 | ) 48 | 49 | 50 | %SPHINXBUILD% 2> nul 51 | if errorlevel 9009 ( 52 | echo. 53 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 54 | echo.installed, then set the SPHINXBUILD environment variable to point 55 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 56 | echo.may add the Sphinx directory to PATH. 57 | echo. 58 | echo.If you don't have Sphinx installed, grab it from 59 | echo.http://sphinx-doc.org/ 60 | exit /b 1 61 | ) 62 | 63 | if "%1" == "html" ( 64 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 68 | goto end 69 | ) 70 | 71 | if "%1" == "dirhtml" ( 72 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 76 | goto end 77 | ) 78 | 79 | if "%1" == "singlehtml" ( 80 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 84 | goto end 85 | ) 86 | 87 | if "%1" == "pickle" ( 88 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can process the pickle files. 92 | goto end 93 | ) 94 | 95 | if "%1" == "json" ( 96 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 97 | if errorlevel 1 exit /b 1 98 | echo. 99 | echo.Build finished; now you can process the JSON files. 100 | goto end 101 | ) 102 | 103 | if "%1" == "htmlhelp" ( 104 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 105 | if errorlevel 1 exit /b 1 106 | echo. 107 | echo.Build finished; now you can run HTML Help Workshop with the ^ 108 | .hhp project file in %BUILDDIR%/htmlhelp. 109 | goto end 110 | ) 111 | 112 | if "%1" == "qthelp" ( 113 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 114 | if errorlevel 1 exit /b 1 115 | echo. 116 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 117 | .qhcp project file in %BUILDDIR%/qthelp, like this: 118 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\django-rest-assured.qhcp 119 | echo.To view the help file: 120 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\django-rest-assured.ghc 121 | goto end 122 | ) 123 | 124 | if "%1" == "devhelp" ( 125 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished. 129 | goto end 130 | ) 131 | 132 | if "%1" == "epub" ( 133 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 137 | goto end 138 | ) 139 | 140 | if "%1" == "latex" ( 141 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 145 | goto end 146 | ) 147 | 148 | if "%1" == "latexpdf" ( 149 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 150 | cd %BUILDDIR%/latex 151 | make all-pdf 152 | cd %BUILDDIR%/.. 153 | echo. 154 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 155 | goto end 156 | ) 157 | 158 | if "%1" == "latexpdfja" ( 159 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 160 | cd %BUILDDIR%/latex 161 | make all-pdf-ja 162 | cd %BUILDDIR%/.. 163 | echo. 164 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 165 | goto end 166 | ) 167 | 168 | if "%1" == "text" ( 169 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 170 | if errorlevel 1 exit /b 1 171 | echo. 172 | echo.Build finished. The text files are in %BUILDDIR%/text. 173 | goto end 174 | ) 175 | 176 | if "%1" == "man" ( 177 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 178 | if errorlevel 1 exit /b 1 179 | echo. 180 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 181 | goto end 182 | ) 183 | 184 | if "%1" == "texinfo" ( 185 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 186 | if errorlevel 1 exit /b 1 187 | echo. 188 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 189 | goto end 190 | ) 191 | 192 | if "%1" == "gettext" ( 193 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 194 | if errorlevel 1 exit /b 1 195 | echo. 196 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 197 | goto end 198 | ) 199 | 200 | if "%1" == "changes" ( 201 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 202 | if errorlevel 1 exit /b 1 203 | echo. 204 | echo.The overview file is in %BUILDDIR%/changes. 205 | goto end 206 | ) 207 | 208 | if "%1" == "linkcheck" ( 209 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 210 | if errorlevel 1 exit /b 1 211 | echo. 212 | echo.Link check complete; look for any errors in the above output ^ 213 | or in %BUILDDIR%/linkcheck/output.txt. 214 | goto end 215 | ) 216 | 217 | if "%1" == "doctest" ( 218 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 219 | if errorlevel 1 exit /b 1 220 | echo. 221 | echo.Testing of doctests in the sources finished, look at the ^ 222 | results in %BUILDDIR%/doctest/output.txt. 223 | goto end 224 | ) 225 | 226 | if "%1" == "xml" ( 227 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 228 | if errorlevel 1 exit /b 1 229 | echo. 230 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 231 | goto end 232 | ) 233 | 234 | if "%1" == "pseudoxml" ( 235 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 236 | if errorlevel 1 exit /b 1 237 | echo. 238 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 239 | goto end 240 | ) 241 | 242 | :end 243 | -------------------------------------------------------------------------------- /docs/source/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # django-rest-assured documentation build configuration file, created by 4 | # sphinx-quickstart on Fri Oct 24 10:48:27 2014. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | import sys 16 | import os 17 | 18 | # If extensions (or modules to document with autodoc) are in another directory, 19 | # add these directories to sys.path here. If the directory is relative to the 20 | # documentation root, use os.path.abspath to make it absolute, like shown here. 21 | sys.path.insert(0, os.path.abspath(os.path.join(os.path.pardir, os.path.pardir))) 22 | 23 | from django.conf import settings 24 | 25 | # mock the AUTH_USER_MODEL setting so that django imports won't break 26 | settings.configure(AUTH_USER_MODEL='account.Accounts') 27 | 28 | # -- General configuration ------------------------------------------------ 29 | 30 | # If your documentation needs a minimal Sphinx version, state it here. 31 | #needs_sphinx = '1.0' 32 | 33 | # Add any Sphinx extension module names here, as strings. They can be 34 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 35 | # ones. 36 | extensions = [ 37 | 'sphinx.ext.coverage', 38 | 'sphinx.ext.viewcode', 39 | 'sphinx.ext.autodoc', 40 | ] 41 | 42 | # Add any paths that contain templates here, relative to this directory. 43 | templates_path = ['_templates'] 44 | 45 | # The suffix of source filenames. 46 | source_suffix = '.rst' 47 | 48 | # The encoding of source files. 49 | #source_encoding = 'utf-8-sig' 50 | 51 | # The master toctree document. 52 | master_doc = 'index' 53 | 54 | # General information about the project. 55 | project = u'django-rest-assured' 56 | copyright = u'2014-2015, Yehonatan Daniv' 57 | 58 | # The version info for the project you're documenting, acts as replacement for 59 | # |version| and |release|, also used in various other places throughout the 60 | # built documents. 61 | # 62 | # The short X.Y version. 63 | version = '0.2' 64 | # The full version, including alpha/beta/rc tags. 65 | release = '0.2.0' 66 | 67 | # The language for content autogenerated by Sphinx. Refer to documentation 68 | # for a list of supported languages. 69 | #language = None 70 | 71 | # There are two options for replacing |today|: either, you set today to some 72 | # non-false value, then it is used: 73 | #today = '' 74 | # Else, today_fmt is used as the format for a strftime call. 75 | #today_fmt = '%B %d, %Y' 76 | 77 | # List of patterns, relative to source directory, that match files and 78 | # directories to ignore when looking for source files. 79 | exclude_patterns = [] 80 | 81 | # The reST default role (used for this markup: `text`) to use for all 82 | # documents. 83 | #default_role = None 84 | 85 | # If true, '()' will be appended to :func: etc. cross-reference text. 86 | #add_function_parentheses = True 87 | 88 | # If true, the current module name will be prepended to all description 89 | # unit titles (such as .. function::). 90 | #add_module_names = True 91 | 92 | # If true, sectionauthor and moduleauthor directives will be shown in the 93 | # output. They are ignored by default. 94 | #show_authors = False 95 | 96 | # The name of the Pygments (syntax highlighting) style to use. 97 | pygments_style = 'sphinx' 98 | 99 | # A list of ignored prefixes for module index sorting. 100 | #modindex_common_prefix = [] 101 | 102 | # If true, keep warnings as "system message" paragraphs in the built documents. 103 | #keep_warnings = False 104 | 105 | 106 | # -- Options for HTML output ---------------------------------------------- 107 | 108 | # The theme to use for HTML and HTML Help pages. See the documentation for 109 | # a list of builtin themes. 110 | html_theme = 'default' 111 | 112 | # Theme options are theme-specific and customize the look and feel of a theme 113 | # further. For a list of options available for each theme, see the 114 | # documentation. 115 | #html_theme_options = {} 116 | 117 | # Add any paths that contain custom themes here, relative to this directory. 118 | #html_theme_path = [] 119 | 120 | # The name for this set of Sphinx documents. If None, it defaults to 121 | # " v documentation". 122 | #html_title = None 123 | 124 | # A shorter title for the navigation bar. Default is the same as html_title. 125 | #html_short_title = None 126 | 127 | # The name of an image file (relative to this directory) to place at the top 128 | # of the sidebar. 129 | #html_logo = None 130 | 131 | # The name of an image file (within the static path) to use as favicon of the 132 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 133 | # pixels large. 134 | #html_favicon = None 135 | 136 | # Add any paths that contain custom static files (such as style sheets) here, 137 | # relative to this directory. They are copied after the builtin static files, 138 | # so a file named "default.css" will overwrite the builtin "default.css". 139 | html_static_path = ['_static'] 140 | 141 | # Add any extra paths that contain custom files (such as robots.txt or 142 | # .htaccess) here, relative to this directory. These files are copied 143 | # directly to the root of the documentation. 144 | #html_extra_path = [] 145 | 146 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 147 | # using the given strftime format. 148 | #html_last_updated_fmt = '%b %d, %Y' 149 | 150 | # If true, SmartyPants will be used to convert quotes and dashes to 151 | # typographically correct entities. 152 | #html_use_smartypants = True 153 | 154 | # Custom sidebar templates, maps document names to template names. 155 | #html_sidebars = {} 156 | 157 | # Additional templates that should be rendered to pages, maps page names to 158 | # template names. 159 | #html_additional_pages = {} 160 | 161 | # If false, no module index is generated. 162 | #html_domain_indices = True 163 | 164 | # If false, no index is generated. 165 | #html_use_index = True 166 | 167 | # If true, the index is split into individual pages for each letter. 168 | #html_split_index = False 169 | 170 | # If true, links to the reST sources are added to the pages. 171 | #html_show_sourcelink = True 172 | 173 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 174 | #html_show_sphinx = True 175 | 176 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 177 | #html_show_copyright = True 178 | 179 | # If true, an OpenSearch description file will be output, and all pages will 180 | # contain a tag referring to it. The value of this option must be the 181 | # base URL from which the finished HTML is served. 182 | #html_use_opensearch = '' 183 | 184 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 185 | #html_file_suffix = None 186 | 187 | # Output file base name for HTML help builder. 188 | htmlhelp_basename = 'django-rest-assureddoc' 189 | 190 | 191 | # -- Options for LaTeX output --------------------------------------------- 192 | 193 | latex_elements = { 194 | # The paper size ('letterpaper' or 'a4paper'). 195 | #'papersize': 'letterpaper', 196 | 197 | # The font size ('10pt', '11pt' or '12pt'). 198 | #'pointsize': '10pt', 199 | 200 | # Additional stuff for the LaTeX preamble. 201 | #'preamble': '', 202 | } 203 | 204 | # Grouping the document tree into LaTeX files. List of tuples 205 | # (source start file, target name, title, 206 | # author, documentclass [howto, manual, or own class]). 207 | latex_documents = [ 208 | ('index', 'django-rest-assured.tex', u'django-rest-assured Documentation', 209 | u'Yehonatan Daniv', 'manual'), 210 | ] 211 | 212 | # The name of an image file (relative to this directory) to place at the top of 213 | # the title page. 214 | #latex_logo = None 215 | 216 | # For "manual" documents, if this is true, then toplevel headings are parts, 217 | # not chapters. 218 | #latex_use_parts = False 219 | 220 | # If true, show page references after internal links. 221 | #latex_show_pagerefs = False 222 | 223 | # If true, show URL addresses after external links. 224 | #latex_show_urls = False 225 | 226 | # Documents to append as an appendix to all manuals. 227 | #latex_appendices = [] 228 | 229 | # If false, no module index is generated. 230 | #latex_domain_indices = True 231 | 232 | 233 | # -- Options for manual page output --------------------------------------- 234 | 235 | # One entry per manual page. List of tuples 236 | # (source start file, name, description, authors, manual section). 237 | man_pages = [ 238 | ('index', 'django-rest-assured', u'django-rest-assured Documentation', 239 | [u'Yehonatan Daniv'], 1) 240 | ] 241 | 242 | # If true, show URL addresses after external links. 243 | #man_show_urls = False 244 | 245 | 246 | # -- Options for Texinfo output ------------------------------------------- 247 | 248 | # Grouping the document tree into Texinfo files. List of tuples 249 | # (source start file, target name, title, author, 250 | # dir menu entry, description, category) 251 | texinfo_documents = [ 252 | ('index', 'django-rest-assured', u'django-rest-assured Documentation', 253 | u'Yehonatan Daniv', 'django-rest-assured', 'Instantly test-cover your Django REST Framework based API.', 254 | 'testing'), 255 | ] 256 | 257 | # Documents to append as an appendix to all manuals. 258 | #texinfo_appendices = [] 259 | 260 | # If false, no module index is generated. 261 | #texinfo_domain_indices = True 262 | 263 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 264 | #texinfo_show_urls = 'footnote' 265 | 266 | # If true, do not generate a @detailmenu in the "Top" node's menu. 267 | #texinfo_no_detailmenu = False 268 | 269 | autodoc_member_order = 'bysource' 270 | -------------------------------------------------------------------------------- /docs/source/index.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../../README.rst 2 | 3 | Table of Contents 4 | ================= 5 | 6 | .. toctree:: 7 | :maxdepth: 2 8 | 9 | reference 10 | tutorial 11 | 12 | 13 | Indices and tables 14 | ================== 15 | 16 | * :ref:`genindex` 17 | * :ref:`modindex` 18 | * :ref:`search` 19 | 20 | -------------------------------------------------------------------------------- /docs/source/reference.rst: -------------------------------------------------------------------------------- 1 | Reference 2 | ========= 3 | 4 | .. automodule:: rest_assured.testcases 5 | :members: 6 | 7 | .. automodule:: rest_assured.contrib.drf_fsm_transitions 8 | :members: 9 | -------------------------------------------------------------------------------- /docs/source/tutorial.rst: -------------------------------------------------------------------------------- 1 | Tutorial 2 | ======== 3 | 4 | .. note:: 5 | 6 | You can clone this example and run the tests yourself from: https://github.com/ydaniv/django-rest-assured-demo. 7 | 8 | Let's take a look at an 9 | `example from the Django documentation `_ 10 | of a Weblog application: 11 | 12 | .. code:: python 13 | 14 | from django.db import models 15 | 16 | 17 | class Blog(models.Model): 18 | 19 | name = models.CharField(max_length=100) 20 | tagline = models.TextField() 21 | 22 | def __str__(self): # __unicode__ on Python 2 23 | return self.name 24 | 25 | 26 | class Author(models.Model): 27 | 28 | name = models.CharField(max_length=50) 29 | email = models.EmailField() 30 | 31 | def __str__(self): # __unicode__ on Python 2 32 | return self.name 33 | 34 | 35 | class Entry(models.Model): 36 | 37 | blog = models.ForeignKey(Blog) 38 | headline = models.CharField(max_length=255) 39 | body_text = models.TextField() 40 | pub_date = models.DateField() 41 | mod_date = models.DateField(auto_now=True) 42 | authors = models.ManyToManyField(Author) 43 | n_comments = models.IntegerField() 44 | n_pingbacks = models.IntegerField() 45 | rating = models.IntegerField() 46 | 47 | def __str__(self): # __unicode__ on Python 2 48 | return self.headline 49 | 50 | The above file will serve as the ``models.py`` file in this example application. 51 | 52 | Say that we want to have a RESTful API endpoint for the ``Entry`` model. 53 | We'll need a serializer for ``Entry`` objects, so this will serve as our ``serializers.py``: 54 | 55 | .. code:: python 56 | 57 | from rest_framework import serializers 58 | from . import models 59 | 60 | 61 | class Entry(serializers.ModelSerializer): 62 | 63 | class Meta: 64 | model = models.Entry 65 | 66 | Now we're ready to define our views. The following shall serve as ``views.py``: 67 | 68 | .. code:: python 69 | 70 | from rest_framework import viewsets 71 | from . import models, serializers 72 | 73 | 74 | class Entries(viewsets.ModelViewSet): 75 | 76 | queryset = models.Entry.objects.all() 77 | serializer_class = serializers.Entry 78 | 79 | And hooking that viewset with URL's, we'll add a ``urls.py`` and define a router: 80 | 81 | .. code:: python 82 | 83 | from django.conf.urls import url, include 84 | from rest_framework import routers 85 | from . import views 86 | 87 | 88 | router = routers.DefaultRouter() 89 | router.register(r'entries', views.Entries) 90 | 91 | 92 | urlpatterns = [ 93 | url(r'^', include(router.urls)), 94 | ] 95 | 96 | And we'll assume the pattern above is added to the project's root ``urlpatterns`` 97 | under the prefix ``/api/``, so that our endpoint will look like ``/api/entries/``. 98 | 99 | Now we have an API endpoint we can test. Yay! 100 | 101 | To make things even easier we'll create a ``factories.py`` file 102 | that will include factories for our models using `Factory Boy `_: 103 | 104 | .. code:: python 105 | 106 | import datetime 107 | import factory 108 | from factory import fuzzy 109 | from . import models 110 | 111 | 112 | class Blog(factory.DjangoModelFactory): 113 | 114 | class Meta: 115 | model = models.Blog 116 | 117 | name = factory.Sequence(lambda n: 'Blog {0}'.format(n)) 118 | tagline = factory.Sequence(lambda n: 'Blog {0} tag line'.format(n)) 119 | 120 | 121 | class Author(factory.DjangoModelFactory): 122 | 123 | class Meta: 124 | model = models.Author 125 | 126 | name = factory.Sequence(lambda n: 'Author {0}'.format(n)) 127 | email = factory.Sequence(lambda n: 'author{0}@example.com'.format(n)) 128 | 129 | 130 | class Entry(factory.DjangoModelFactory): 131 | 132 | class Meta: 133 | model = models.Entry 134 | 135 | blog = factory.SubFactory(Blog) 136 | headline = factory.Sequence(lambda n: 'OMG Headline {0}!'.format(n)) 137 | body_text = fuzzy.FuzzyText(length=100) 138 | pub_date = datetime.date(2014, 11, 12) 139 | mod_date = datetime.date(2014, 11, 12) 140 | rating = fuzzy.FuzzyInteger(low=1, high=5, step=1) 141 | n_pingbacks = 0 142 | n_comments = 0 143 | 144 | @factory.post_generation 145 | def authors(self, create, extracted, **kwargs): 146 | if not create: 147 | return 148 | 149 | if extracted: 150 | for author in extracted: 151 | self.authors.add(author) 152 | 153 | This will make testing fun. 154 | 155 | Let's write the tests! This shall be our ``tests.py`` file: 156 | 157 | .. code:: python 158 | 159 | from rest_assured.testcases import ReadWriteRESTAPITestCaseMixin, BaseRESTAPITestCase 160 | from . import factories 161 | 162 | 163 | class EntryAPITestCase(ReadWriteRESTAPITestCaseMixin, BaseRESTAPITestCase): 164 | 165 | base_name = 'entry' # this is the base_name generated by the DefaultRouter 166 | factory_class = factories.Entry 167 | update_data = {'rating': 5} 168 | 169 | def setUp(self): 170 | self.author = factories.Author.create() 171 | super(EntryAPITestCase, self).setUp() 172 | 173 | def get_object(self, factory): 174 | return factory.create(authors=[self.author]) 175 | 176 | def get_create_data(self): 177 | return {'headline': 'Lucifer Sam', 178 | 'body_text': 'is a song by British psychedelic rock band Pink Floyd.', 179 | 'authors': [self.author.pk], 180 | 'rating': 4, 181 | 'n_pingbacks': 0, 182 | 'n_comments': 0, 183 | 'pub_date': datetime.date(2014, 11, 12), 184 | 'blog': self.object.blog.pk} 185 | 186 | And that's it! 187 | 188 | This simple class will make 5 tests if we'll run: 189 | 190 | .. code:: sh 191 | 192 | $ python manage.py test 193 | 194 | And will produce an output like such: 195 | 196 | .. code:: sh 197 | 198 | user@machine:~/project$ python manage.py test 199 | Creating test database for alias 'default'... 200 | ..... 201 | ---------------------------------------------------------------------- 202 | Ran 5 tests in 0.155s 203 | 204 | OK 205 | Destroying test database for alias 'default'... 206 | 207 | You can see the above example is not entirely trivial. 208 | We had to do some setup work to ensure we have a ready made Author instance. 209 | We also created dynamic getters for the main test object and the data dict used for 210 | the create request. In both cases this was required to obtain a lazy reference 211 | to the Author instance we created in ``setUp()``. 212 | 213 | Say now our API is not public and requires authentication (token, session, etc.). We'll need a user 214 | factory to mock authenticated requests. Let's create that factory: 215 | 216 | .. code:: python 217 | 218 | from django.contrib import auth 219 | 220 | 221 | class User(factory.DjangoModelFactory): 222 | 223 | class Meta: 224 | 225 | model = auth.get_user_model() 226 | exclude = ('raw_password',) 227 | 228 | first_name = 'Robert' 229 | last_name = factory.Sequence(lambda n: 'Paulson the {0}'.format(n)) 230 | email = factory.sequence(lambda n: 'account{0}@example.com'.format(n)) 231 | username = 'mayhem' 232 | raw_password = '123' 233 | password = factory.PostGenerationMethodCall('set_password', raw_password) 234 | is_active = True 235 | 236 | Our tests now will fail, since all responses will return a ``HTTP_401_UNAUTHORIZED`` status code. Which is great. 237 | 238 | Assuming that ``User`` factory resides in the previous ``factories.py`` module, we add a 239 | ``user_factory`` attribute to our test case: 240 | 241 | .. code:: python 242 | 243 | ... 244 | user_factory = factories.User 245 | ... 246 | 247 | The full version of our ``tests.py`` now look like: 248 | 249 | .. code:: python 250 | 251 | from rest_assured.testcases import ReadWriteRESTAPITestCaseMixin, BaseRESTAPITestCase 252 | from . import factories 253 | 254 | 255 | class EntryAPITestCase(ReadWriteRESTAPITestCaseMixin, BaseRESTAPITestCase): 256 | 257 | base_name = 'entry' # this is the base_name generated by the DefaultRouter 258 | factory_class = factories.Entry 259 | user_factory = factories.User # this is the user that will be authenticated for testing 260 | update_data = {'rating': 5} 261 | 262 | def setUp(self): 263 | self.author = factories.Author.create() 264 | super(EntryAPITestCase, self).setUp() 265 | 266 | def get_object(self, factory): 267 | return factory.create(authors=[self.author]) 268 | 269 | def get_create_data(self): 270 | return {'headline': 'Lucifer Sam', 271 | 'body_text': 'is a song by British psychedelic rock band Pink Floyd.', 272 | 'authors': [self.author.pk], 273 | 'rating': 4, 274 | 'n_pingbacks': 0, 275 | 'n_comments': 0, 276 | 'pub_date': datetime.date(2014, 11, 12), 277 | 'blog': self.object.blog.pk} 278 | 279 | And our tests pass again. 280 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Django 2 | djangorestframework 3 | sphinx 4 | six 5 | -------------------------------------------------------------------------------- /rest_assured/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ydaniv/django-rest-assured/22c86f0bcf9cbc12c6ea0d334776074a0fa993bc/rest_assured/__init__.py -------------------------------------------------------------------------------- /rest_assured/contrib/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ydaniv/django-rest-assured/22c86f0bcf9cbc12c6ea0d334776074a0fa993bc/rest_assured/contrib/__init__.py -------------------------------------------------------------------------------- /rest_assured/contrib/drf_fsm_transitions.py: -------------------------------------------------------------------------------- 1 | from rest_framework.reverse import reverse 2 | 3 | 4 | class TransitionAPITestCaseMixin(object): 5 | 6 | """Adds the ``transition()`` method for testing state transition API endpoints. 7 | 8 | This is a handy extension for quickly test-covering API endpoints that are generated using 9 | the DRF-FSM-Transition library. 10 | """ 11 | 12 | def transition(self, result, route, attribute='status', from_state=None, data=None): 13 | 14 | """Send request to a transition view endpoint, verify and return the response. 15 | 16 | :param result: The expected value of the instance's ``attribute``. 17 | :param route: The addition to the route, usually the name of the transition action's name. 18 | :param attribute: Name of the instance's attribute that holds the state. 19 | :param from_state: A state to update the object to, to initialize the "from" state. 20 | :return: The view's response. 21 | """ 22 | 23 | if from_state is not None: 24 | self.object.__class__.objects.filter(pk=self.object.pk).update(**{attribute: from_state}) 25 | 26 | updateview = reverse(self.base_name + self.DETAIL_SUFFIX, 27 | args=(self.object.pk,)) + '%s/' % route 28 | response = self.client.post(updateview, data) 29 | 30 | self.assertEqual(response.data[attribute], result) 31 | 32 | return response 33 | -------------------------------------------------------------------------------- /rest_assured/testcases.py: -------------------------------------------------------------------------------- 1 | from django.db.models import Manager 2 | from django.core.exceptions import ObjectDoesNotExist 3 | import six 4 | from rest_framework import status 5 | from rest_framework.reverse import reverse 6 | from rest_framework.test import APITestCase 7 | from six import text_type 8 | 9 | 10 | class BaseRESTAPITestCase(APITestCase): 11 | 12 | """Base test case class for testing REST API endpoints.""" 13 | 14 | #: *required*: Base route name of the API endpoints to test. 15 | base_name = None 16 | #: *required*: The factory class to use for creating the main object to test against. 17 | factory_class = None 18 | #: Suffix for list endpoint view names. Defaults to ``'-list'``. 19 | LIST_SUFFIX = '-list' 20 | #: Suffix for detail endpoint view names. Defaults to ``'-detail'``. 21 | DETAIL_SUFFIX = '-detail' 22 | #: The field to use for DB and route lookups. Defaults to ``'pk'``. 23 | lookup_field = 'pk' 24 | #: User factory to use in case you need user authentication for testing. Defaults to ``None``. 25 | user_factory = None 26 | #: The main test subject. 27 | object = None 28 | #: The user instance created if the ``user_factory`` is set and used. Defaults to ``None``. 29 | user = None 30 | 31 | def get_factory_class(self): 32 | """Return the factory class for generating the main object (or model instance) of this test case. 33 | 34 | By default this gets the ``factory_class`` attribute of this class. 35 | 36 | :returns: Factory class used for creating the mock objects. 37 | """ 38 | 39 | return getattr(self, 'factory_class') 40 | 41 | def get_object(self, factory): 42 | """Create and return the object (or model instance) of this test case. 43 | 44 | By default this calls the ``create()`` method of the factory class, assuming 45 | a Django Model or a factory_boy's Factory. 46 | 47 | :param factory: The factory class used for creating 48 | :returns: The main object of this test case. 49 | """ 50 | 51 | return factory.create() 52 | 53 | def setUp(self): 54 | """Generates the main object and user instance if needed. 55 | 56 | The user instance will be created only if the ``user_factory`` attribute is set to the factory class. 57 | 58 | If there is an available user instance, that user will be force authenticated. 59 | """ 60 | 61 | # create and force authenticate user 62 | user_factory = getattr(self, 'user_factory') 63 | if user_factory: 64 | self.user = user_factory.create() 65 | self.client.force_authenticate(self.user) 66 | 67 | # create the object 68 | self.object = self.get_object(self.get_factory_class()) 69 | 70 | 71 | class ListAPITestCaseMixin(object): 72 | 73 | """Adds a list view test to the test case.""" 74 | 75 | #: When using pagination set this attribute to the name of the property in the response data that holds the result set. Defaults to ``None``. 76 | pagination_results_field = None 77 | 78 | def get_list_url(self): 79 | """Return the list endpoint url. 80 | 81 | :returns: The url of list endpoint. 82 | """ 83 | 84 | return reverse(self.base_name + self.LIST_SUFFIX) 85 | 86 | def get_list_response(self, **kwargs): 87 | """Send the list request and return the response. 88 | 89 | :param kwargs: Extra arguments that are passed to the client's ``get()`` call. 90 | :returns: The response object. 91 | """ 92 | 93 | return self.client.get(self.get_list_url(), **kwargs) 94 | 95 | def test_list(self, **kwargs): 96 | """Send request to the list view endpoint, verify and return the response. 97 | 98 | Checks for a 200 status code and that there is a ``results`` property in the ``response.data``. 99 | 100 | You can extend it for more extensive checks. 101 | 102 | .. admonition:: example 103 | 104 | .. code:: python 105 | 106 | class LanguageRESTAPITestCase(ListAPITestCaseMixin, BaseRESTAPITestCase): 107 | 108 | def test_list(self, **kwargs): 109 | response = super(LanguageRESTAPITestCase, self).test_list(**kwargs) 110 | results = response.data.get('results') 111 | self.assertEqual(results[0].get('code'), self.object.code) 112 | 113 | :param kwargs: Extra arguments that are passed to the client's ``get()`` call. 114 | :returns: The view's response. 115 | """ 116 | 117 | response = self.get_list_response(**kwargs) 118 | 119 | self.assertEqual(response.status_code, status.HTTP_200_OK, response.data) 120 | 121 | results = response.data 122 | 123 | if self.pagination_results_field: 124 | self.assertIn(self.pagination_results_field, response.data) 125 | results = results[self.pagination_results_field] 126 | 127 | self.assertTrue(len(results) >= 1) 128 | 129 | return response 130 | 131 | 132 | class DetailAPITestCaseMixin(object): 133 | 134 | """Adds a detail view test to the test case.""" 135 | 136 | # A list of attribute names to check equality between the main object and the response data. 137 | # Defaults to ``['id']``. 138 | # You can also use a tuple of a string and a callable, that takes the object and returns an attribute's value. 139 | attributes_to_check = ['id'] 140 | 141 | def get_detail_url(self): 142 | """Return the detail endpoint url. 143 | 144 | :returns: The url of detail endpoint. 145 | """ 146 | 147 | object_id = getattr(self.object, self.lookup_field) 148 | return reverse(self.base_name + self.DETAIL_SUFFIX, args=[text_type(object_id)]) 149 | 150 | def get_detail_response(self, **kwargs): 151 | """Send the detail request and return the response. 152 | 153 | :param kwargs: Extra arguments that are passed to the client's ``get()`` call. 154 | :returns: The response object. 155 | """ 156 | 157 | return self.client.get(self.get_detail_url(), **kwargs) 158 | 159 | def test_detail(self, **kwargs): 160 | """Send request to the detail view endpoint, verify and return the response. 161 | 162 | Checks for a 200 status code and that there is an ``id`` property in the ``response.data`` 163 | and that it equals the main object's id. 164 | 165 | You can extend it for more extensive checks. 166 | 167 | .. admonition:: example 168 | 169 | .. code:: python 170 | 171 | class LanguageRESTAPITestCase(DetailAPITestCaseMixin, BaseRESTAPITestCase): 172 | 173 | def test_list(self, **kwargs): 174 | response = super(LanguageRESTAPITestCase, self).test_list(**kwargs) 175 | self.assertEqual(response.data.get('code'), self.object.code) 176 | 177 | Using a callable in ``attributes_to_check``: 178 | 179 | .. admonition:: example 180 | 181 | .. code:: python 182 | 183 | class TaggedFoodRESTAPITestCase(DetailAPITestCaseMixin, BaseRESTAPITestCase): 184 | 185 | attributes_to_check = ['name', ('similar', lambda obj: obj.tags.similar_objects())] 186 | 187 | 188 | :param kwargs: Extra arguments that are passed to the client's ``get()`` call. 189 | :returns: The view's response. 190 | """ 191 | 192 | response = self.get_detail_response(**kwargs) 193 | 194 | self.assertEqual(response.status_code, status.HTTP_200_OK, response.data) 195 | self._check_attributes(response.data) 196 | 197 | return response 198 | 199 | def _check_attributes(self, data): 200 | for attr in self.attributes_to_check: 201 | if isinstance(attr, (tuple, list, set)): 202 | value = text_type(attr[1](self.object)) 203 | attr = attr[0] 204 | else: 205 | value = text_type(getattr(self.object, attr)) 206 | 207 | self.assertEqual(value, text_type(data[attr]), attr) 208 | 209 | 210 | class CreateAPITestCaseMixin(object): 211 | 212 | """Adds a create view test to the test case.""" 213 | 214 | #: *required*: Dictionary of data to use as the POST request's body. 215 | create_data = None 216 | #: The name of the field in the response data for looking up the created object in DB. 217 | response_lookup_field = 'id' 218 | 219 | def get_create_data(self): 220 | """Return the data used for the create request. 221 | 222 | By default gets the ``create_data`` attribute of this class. 223 | 224 | :returns: The data dictionary. 225 | """ 226 | 227 | return getattr(self, 'create_data') 228 | 229 | def get_create_url(self): 230 | """Return the create endpoint url. 231 | 232 | :returns: The url of create endpoint. 233 | """ 234 | 235 | return reverse(self._get_create_name()) 236 | 237 | def get_create_response(self, data=None, **kwargs): 238 | """Send the create request and return the response. 239 | 240 | :param data: A dictionary of the data to use for the create request. 241 | :param kwargs: Extra arguments that are passed to the client's ``post()`` call. 242 | :returns: The response object. 243 | """ 244 | 245 | if data is None: 246 | data = self.get_create_data() 247 | 248 | return self.client.post(self.get_create_url(), data or {}, **kwargs) 249 | 250 | def get_lookup_from_response(self, data): 251 | """Return value for looking up the created object in DB. 252 | 253 | :Note: The created object will be looked up using the ``lookup_field`` attribute as key, which defaults to ``pk``. 254 | 255 | :param data: A dictionary of the response data to lookup the field in. 256 | :returns: The value for looking up the 257 | """ 258 | return data.get(self.response_lookup_field) 259 | 260 | def test_create(self, data=None, **kwargs): 261 | """Send request to the create view endpoint, verify and return the response. 262 | 263 | Also verifies that the object actually exists in the database. 264 | 265 | :param data: A dictionary of the data to use for the create request. 266 | :param kwargs: Extra arguments that are passed to the client's ``post()`` call. 267 | :returns: A tuple ``response, created`` of the view's response the created instance. 268 | """ 269 | 270 | response = self.get_create_response(data, **kwargs) 271 | 272 | self.assertEqual(response.status_code, status.HTTP_201_CREATED, getattr(response, 'data', response)) 273 | 274 | # another sanity check: 275 | # getting the instance from database simply to see that it's found and does not raise any exception 276 | created = self.object.__class__.objects.get( 277 | **{self.lookup_field: self.get_lookup_from_response(response.data)}) 278 | 279 | return response, created 280 | 281 | def _get_create_name(self): 282 | if hasattr(self, 'create_name'): 283 | view_name = self.create_name 284 | else: 285 | view_name = self.base_name + self.LIST_SUFFIX 286 | 287 | return view_name 288 | 289 | 290 | class DestroyAPITestCaseMixin(object): 291 | 292 | """Adds a destroy view test to the test case.""" 293 | 294 | def get_destroy_url(self): 295 | """Return the destroy endpoint url. 296 | 297 | :returns: The url of destroy endpoint. 298 | """ 299 | 300 | self.object_id = getattr(self.object, self.lookup_field) 301 | return reverse(self._get_destroy_name(), 302 | args=(self.object_id,)) 303 | 304 | def get_destroy_response(self, **kwargs): 305 | """Send the destroy request and return the response. 306 | 307 | :param kwargs: Extra arguments that are passed to the client's ``delete()`` call. 308 | :returns: The view's response. 309 | """ 310 | 311 | return self.client.delete(self.get_destroy_url(), **kwargs) 312 | 313 | def test_destroy(self, **kwargs): 314 | """Send request to the destroy view endpoint, verify and return the response. 315 | 316 | Also verifies the object does not exist anymore in the database. 317 | 318 | :param kwargs: Extra arguments that are passed to the client's ``delete()`` call. 319 | :returns: The view's response. 320 | """ 321 | 322 | response = self.get_destroy_response(**kwargs) 323 | 324 | self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT, response.data) 325 | # Another sanity check: 326 | # see that the instance is removed from the database. 327 | self.assertRaises(ObjectDoesNotExist, self.object.__class__.objects.get, **{self.lookup_field: self.object_id}) 328 | 329 | return response 330 | 331 | def _get_destroy_name(self): 332 | if hasattr(self, 'destroy_name'): 333 | view_name = self.destroy_name 334 | else: 335 | view_name = self.base_name + self.DETAIL_SUFFIX 336 | 337 | return view_name 338 | 339 | 340 | class UpdateAPITestCaseMixin(object): 341 | 342 | """Adds an update view test to the test case.""" 343 | 344 | #: Whether to send a PATCH request instead of PUT. Defaults to ``True``. 345 | use_patch = True 346 | #: *required*: Dictionary of data to use as the update request's body. 347 | update_data = None 348 | #: Dictionary mapping attributes to values to check against the updated instance in the database. 349 | #: Defaults to ``update_data``. 350 | update_results = None 351 | #: The name of the field in the response data for looking up the created object in DB. 352 | relationship_lookup_field = 'id' 353 | 354 | def get_update_url(self): 355 | """Return the update endpoint url. 356 | 357 | :returns: The url of update endpoint. 358 | """ 359 | 360 | self.object_id = getattr(self.object, self.lookup_field) 361 | return reverse(self._get_update_name(), 362 | args=(self.object_id,)) 363 | 364 | def get_update_response(self, data=None, results=None, use_patch=None, **kwargs): 365 | """Send the update request and return the response. 366 | 367 | :param data: Data dictionary for the update request. 368 | :param results: Dictionary mapping instance properties to expected values. 369 | :param kwargs: Extra arguments that are passed to the client's ``put()`` or ``patch()`` call. 370 | :returns: The response object. 371 | """ 372 | 373 | if data is None: 374 | data = self.get_update_data() 375 | self.__data = data 376 | 377 | if results is None: 378 | results = self.get_update_results(data) 379 | self.__results = results 380 | 381 | args = [self.get_update_url(), data] 382 | 383 | if use_patch is None: 384 | use_patch = self.use_patch 385 | 386 | return self.client.patch(*args, **kwargs) if use_patch else self.client.put(*args, **kwargs) 387 | 388 | def get_update_data(self): 389 | """Return the data used for the update request. 390 | 391 | By default gets the ``update_data`` attribute of this class. 392 | 393 | :returns: Data dictionary for the update request. 394 | """ 395 | 396 | return getattr(self, 'update_data') 397 | 398 | def get_update_results(self, data=None): 399 | """Return a dictionary of the expected results of the instance. 400 | 401 | By default gets the ``update_results`` attribute of this class. 402 | If that isn't set defaults to the data. 403 | 404 | :param data: The update request's data dictionary. 405 | :returns: Dictionary mapping instance properties to expected values. 406 | """ 407 | 408 | return getattr(self, 'update_results', data) 409 | 410 | def get_relationship_value(self, related_obj, key): 411 | """Return a value representing a relation to a related model instance. 412 | 413 | By default gets the ``relationship_lookup_field`` attribute of this class 414 | which defaults to ``id``, and converts it to a ``string``. 415 | 416 | :param related_obj: The related model instance to convert to a value. 417 | :param key: A ``string`` representing the name of the relation, or the key on the updated object. 418 | :returns: Value representing the relation to assert against. 419 | """ 420 | 421 | return text_type(getattr(related_obj, getattr(self, 'relationship_lookup_field'))) 422 | 423 | def test_update(self, data=None, results=None, use_patch=None, **kwargs): 424 | """Send request to the update view endpoint, verify and return the response. 425 | 426 | :param data: Data dictionary for the update request. 427 | :param results: Dictionary mapping instance properties to expected values. 428 | :param kwargs: Extra arguments that are passed to the client's ``put()`` or ``patch()`` call. 429 | :returns: A tuple ``response, updated`` of the view's response the updated instance. 430 | """ 431 | 432 | response = self.get_update_response(data, results, use_patch, **kwargs) 433 | 434 | self.assertEqual(response.status_code, status.HTTP_200_OK, response.data) 435 | 436 | # getting a fresh copy of the object from DB 437 | updated = self.object.__class__.objects.get(**{self.lookup_field: self.object_id}) 438 | # Sanity check: 439 | # check that the copy in the database was updated as expected. 440 | self._update_check_db(updated, data, results) 441 | 442 | return response, updated 443 | 444 | def _get_update_name(self): 445 | if hasattr(self, 'update_name'): 446 | view_name = self.update_name 447 | else: 448 | view_name = self.base_name + self.DETAIL_SUFFIX 449 | 450 | return view_name 451 | 452 | def _update_check_db(self, obj, data=None, results=None): 453 | if data is None: 454 | data = self.__data 455 | 456 | if results is None: 457 | results = self.__results or {} 458 | 459 | for key, value in six.iteritems(data): 460 | # check if ``obj`` is a dict to allow overriding ``_update_check_db()`` 461 | # and perform checks on a serialized object 462 | if isinstance(obj, dict): 463 | attribute = obj.get(key) 464 | if isinstance(attribute, list): 465 | self.assertListEqual(attribute, value, key) 466 | continue 467 | else: 468 | # check for foreign key 469 | if hasattr(obj, '%s_id' % key): 470 | related = getattr(obj, key) 471 | attribute = self.get_relationship_value(related, key) 472 | else: 473 | attribute = getattr(obj, key) 474 | # Handle case of a ManyToMany relation 475 | if isinstance(attribute, Manager): 476 | items = {self.get_relationship_value(item, key) for item in attribute.all()} 477 | self.assertTrue(set(value).issubset(items), key) 478 | continue 479 | 480 | self.assertEqual(attribute, results.get(key, value), key) 481 | 482 | 483 | class ReadRESTAPITestCaseMixin(ListAPITestCaseMixin, DetailAPITestCaseMixin): 484 | 485 | """Adds the read CRUD operations tests to the test case. 486 | 487 | Includes: :class:`ListAPITestCaseMixin`, :class:`DetailAPITestCaseMixin`. 488 | """ 489 | 490 | pass 491 | 492 | 493 | class WriteRESTAPITestCaseMixin(CreateAPITestCaseMixin, UpdateAPITestCaseMixin, DestroyAPITestCaseMixin): 494 | 495 | """Adds the write CRUD operations tests to the test case. 496 | 497 | Includes: :class:`CreateAPITestCaseMixin`, :class:`UpdateAPITestCaseMixin`, :class:`DestroyAPITestCaseMixin`. 498 | """ 499 | 500 | pass 501 | 502 | 503 | class ReadWriteRESTAPITestCaseMixin(ReadRESTAPITestCaseMixin, WriteRESTAPITestCaseMixin): 504 | 505 | """A complete API test case that covers all successful CRUD operation requests. 506 | 507 | Includes: :class:`ReadRESTAPITestCaseMixin`, :class:`WriteRESTAPITestCaseMixin`. 508 | """ 509 | 510 | pass 511 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from os import path 2 | from setuptools import setup, find_packages 3 | 4 | this_directory = path.abspath(path.dirname(__file__)) 5 | 6 | try: 7 | with open(path.join(this_directory, 'README.rst'), encoding='utf-8') as f: 8 | long_description = f.read() 9 | except TypeError: 10 | import io 11 | with io.open(path.join(this_directory, 'README.rst'), encoding='utf-8') as f: 12 | long_description = f.read() 13 | 14 | setup( 15 | name='django-rest-assured', 16 | version='0.2.3', 17 | description='Django REST Assured instantly test-covers your Django REST Framework based API.', 18 | long_description=long_description, 19 | long_description_content_type='text/x-rst', 20 | url='https://github.com/ydaniv/django-rest-assured', 21 | author='Yehonatan Daniv', 22 | author_email='maggotfish@gmail.com', 23 | license='BSD', 24 | packages=find_packages(), 25 | install_requires=["django>=1.6", "djangorestframework>=2.4.3", "six"], 26 | zip_safe=False, 27 | classifiers=[ 28 | 'Development Status :: 5 - Production/Stable', 29 | 'Environment :: Web Environment', 30 | 'Framework :: Django', 31 | 'Intended Audience :: Developers', 32 | 'License :: OSI Approved :: BSD License', 33 | 'Operating System :: OS Independent', 34 | 'Programming Language :: Python', 35 | 'Programming Language :: Python :: 3', 36 | 'Topic :: Internet :: WWW/HTTP', 37 | ] 38 | ) 39 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ydaniv/django-rest-assured/22c86f0bcf9cbc12c6ea0d334776074a0fa993bc/tests/__init__.py -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | from django.conf import settings 2 | 3 | 4 | def pytest_configure(): 5 | settings.configure( 6 | ROOT_URLCONF='tests.urls', 7 | 8 | ALLOWED_HOSTS=['testserver'], 9 | 10 | DATABASES={ 11 | 'default': { 12 | 'ENGINE': 'django.db.backends.sqlite3', 13 | 'NAME': 'test_db' 14 | } 15 | }, 16 | 17 | INSTALLED_APPS=[ 18 | 'django.contrib.auth', 19 | 'django.contrib.contenttypes', 20 | 'django.contrib.sessions', 21 | 22 | 'rest_framework', 23 | 'tests', 24 | ] 25 | ) 26 | -------------------------------------------------------------------------------- /tests/mocks.py: -------------------------------------------------------------------------------- 1 | from rest_framework import viewsets, serializers 2 | 3 | from rest_assured.testcases import BaseRESTAPITestCase 4 | from tests.models import Stuff, RelatedStuff, ManyRelatedStuff 5 | 6 | 7 | class MockObject(object): 8 | pass 9 | 10 | 11 | class MockFactory(object): 12 | @classmethod 13 | def create(cls): 14 | return MockObject() 15 | 16 | 17 | class StuffFactory(object): 18 | @classmethod 19 | def create(cls, **kwargs): 20 | if 'name' not in kwargs: 21 | kwargs['name'] = 'name of stuff' 22 | if 'answer' not in kwargs: 23 | kwargs['answer'] = 42 24 | return Stuff.objects.create(**kwargs) 25 | 26 | 27 | class RelatedStuffFactory(object): 28 | @classmethod 29 | def create(cls): 30 | thing = Stuff.objects.create(name='referenced stuff') 31 | return RelatedStuff.objects.create(thing=thing) 32 | 33 | 34 | class ManyRelatedStuffFactory(object): 35 | @classmethod 36 | def create(cls): 37 | thing1 = Stuff.objects.create(name='referenced stuff 1') 38 | thing2 = Stuff.objects.create(name='referenced stuff 2') 39 | obj = ManyRelatedStuff.objects.create() 40 | obj.stuff.add(thing1, thing2) 41 | return obj 42 | 43 | 44 | class MockUser(object): 45 | def get_username(self): 46 | return 'username' 47 | 48 | def is_authenticated(self): 49 | return True 50 | 51 | def has_perms(self, perms): 52 | return True 53 | 54 | 55 | class MockUserFactory(object): 56 | @classmethod 57 | def create(cls): 58 | return MockUser() 59 | 60 | 61 | class MockTestCase(BaseRESTAPITestCase): 62 | factory_class = MockFactory 63 | user_factory = MockUserFactory 64 | 65 | def __init__(self, *args, **kwargs): 66 | self._pre_setup() 67 | super(MockTestCase, self).__init__(*args, **kwargs) 68 | 69 | def _pre_setup(self): 70 | self.client = self.client_class() 71 | 72 | def dummy(self): 73 | pass 74 | 75 | 76 | class StuffSerializer(serializers.ModelSerializer): 77 | class Meta: 78 | model = Stuff 79 | fields = ['id', 'name', 'answer'] 80 | 81 | 82 | class StuffHyperlinkedSerializer(serializers.HyperlinkedModelSerializer): 83 | class Meta: 84 | model = Stuff 85 | fields = ['name', 'answer', 'url'] 86 | 87 | 88 | class RelatedStuffSerializer(serializers.ModelSerializer): 89 | class Meta: 90 | model = RelatedStuff 91 | fields = ['thing'] 92 | 93 | 94 | class RelatedStuffHyperlinkedSerializer(serializers.HyperlinkedModelSerializer): 95 | class Meta: 96 | model = RelatedStuff 97 | fields = ['thing'] 98 | 99 | thing = serializers.HyperlinkedRelatedField(queryset=Stuff.objects.all(), 100 | view_name='stuff-linked-detail') 101 | 102 | 103 | class ManyRelatedStuffSerializer(serializers.ModelSerializer): 104 | class Meta: 105 | model = ManyRelatedStuff 106 | fields = ['stuff'] 107 | 108 | 109 | class ManyRelatedStuffHyperlinkedSerializer(serializers.HyperlinkedModelSerializer): 110 | class Meta: 111 | model = ManyRelatedStuff 112 | fields = ['stuff'] 113 | 114 | # stuff = serializers.HyperlinkedRelatedField(queryset=Stuff.objects.all(), 115 | # many=True) 116 | 117 | 118 | class StuffViewSet(viewsets.ModelViewSet): 119 | queryset = Stuff.objects.all() 120 | serializer_class = StuffSerializer 121 | paginate_by = 10 122 | 123 | 124 | class StuffHyperlinkedViewSet(viewsets.ModelViewSet): 125 | queryset = Stuff.objects.all() 126 | serializer_class = StuffHyperlinkedSerializer 127 | paginate_by = 10 128 | 129 | 130 | class RelatedStuffViewSet(viewsets.ModelViewSet): 131 | queryset = RelatedStuff.objects.all() 132 | serializer_class = RelatedStuffSerializer 133 | paginate_by = 10 134 | 135 | 136 | class RelatedStuffHyperlinkedViewSet(viewsets.ModelViewSet): 137 | queryset = RelatedStuff.objects.all() 138 | serializer_class = RelatedStuffHyperlinkedSerializer 139 | paginate_by = 10 140 | 141 | 142 | class ManyRelatedStuffViewSet(viewsets.ModelViewSet): 143 | queryset = ManyRelatedStuff.objects.all() 144 | serializer_class = ManyRelatedStuffSerializer 145 | paginate_by = 10 146 | 147 | 148 | class ManyRelatedStuffHyperlinkedViewSet(viewsets.ModelViewSet): 149 | queryset = ManyRelatedStuff.objects.all() 150 | serializer_class = ManyRelatedStuffHyperlinkedSerializer 151 | paginate_by = 10 152 | -------------------------------------------------------------------------------- /tests/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | from rest_framework.reverse import reverse 3 | 4 | 5 | class Stuff(models.Model): 6 | name = models.CharField(max_length=200) 7 | answer = models.PositiveSmallIntegerField(null=True, blank=True) 8 | 9 | class Meta: 10 | app_label = 'tests' 11 | 12 | def get_absolute_url(self): 13 | return reverse('stuff-detail', [self.pk]) 14 | 15 | 16 | class RelatedStuff(models.Model): 17 | thing = models.ForeignKey(Stuff, models.CASCADE) 18 | 19 | class Meta: 20 | app_label = 'tests' 21 | 22 | 23 | class ManyRelatedStuff(models.Model): 24 | stuff = models.ManyToManyField(Stuff) 25 | 26 | class Meta: 27 | app_label = 'tests' 28 | -------------------------------------------------------------------------------- /tests/test_base.py: -------------------------------------------------------------------------------- 1 | from tests import mocks 2 | 3 | 4 | class TestBaseTestCase: 5 | def test_get_factory_class(self): 6 | instance = mocks.MockTestCase(methodName='dummy') 7 | assert instance.get_factory_class() is mocks.MockFactory 8 | 9 | def test_get_object(self): 10 | instance = mocks.MockTestCase(methodName='dummy') 11 | assert isinstance(instance.get_object(instance.get_factory_class()), mocks.MockObject) 12 | 13 | def test_user_exists_and_forced_auth(self): 14 | instance = mocks.MockTestCase(methodName='dummy') 15 | instance.setUp() 16 | assert isinstance(instance.user, mocks.MockUser) 17 | assert instance.client.handler._force_user is instance.user 18 | -------------------------------------------------------------------------------- /tests/test_create.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | from rest_assured.testcases import CreateAPITestCaseMixin 4 | from tests import mocks 5 | from tests.models import Stuff 6 | 7 | 8 | class TestCreateTestCase(TestCase): 9 | def get_case(self, **kwargs): 10 | class MockCreateTestCase(CreateAPITestCaseMixin, mocks.MockTestCase): 11 | base_name = kwargs.pop('base_name', 'stuff') 12 | factory_class = mocks.StuffFactory 13 | create_data = {"name": "moar stuff"} 14 | 15 | self.case_class = MockCreateTestCase 16 | 17 | return MockCreateTestCase(**kwargs) 18 | 19 | def test_get_create_url(self): 20 | instance = self.get_case(methodName='dummy') 21 | assert instance.get_create_url() == '/stuff/' 22 | 23 | def test_get_create_data(self): 24 | instance = self.get_case(methodName='dummy') 25 | assert instance.get_create_data() is self.case_class.create_data 26 | 27 | def test_get_create_response(self): 28 | instance = self.get_case(methodName='dummy') 29 | assert instance.get_create_response() 30 | 31 | def test_get_lookup_from_response(self): 32 | instance = self.get_case(methodName='dummy') 33 | response = instance.get_create_response() 34 | assert instance.get_lookup_from_response(response.data) 35 | 36 | def test_test_create(self): 37 | instance = self.get_case(methodName='dummy') 38 | instance.setUp() 39 | response, created = instance.test_create() 40 | assert response 41 | assert created 42 | assert isinstance(created, Stuff) 43 | assert response.data['name'] == created.name 44 | 45 | # try again using a different lookup field 46 | instance.response_lookup_field = 'name' 47 | instance.lookup_field = 'name' 48 | response, created = instance.test_create({'name': 'unique stuff'}) 49 | assert response 50 | assert created 51 | assert isinstance(created, Stuff) 52 | assert response.data['name'] == created.name 53 | 54 | def test_test_create_with_hyperlinkedmodelserializer(self): 55 | instance = self.get_case(methodName='dummy', base_name='stuff-linked') 56 | instance.setUp() 57 | instance.response_lookup_field = 'name' 58 | instance.lookup_field = 'name' 59 | response, created = instance.test_create({'name': 'moar unique stuff'}) 60 | assert response 61 | assert created 62 | assert isinstance(created, Stuff) 63 | assert response.data['name'] == created.name 64 | assert response.data['url'] 65 | -------------------------------------------------------------------------------- /tests/test_destroy.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | from rest_assured.testcases import DestroyAPITestCaseMixin 4 | from tests import mocks 5 | 6 | 7 | class TestDestroyTestCase(TestCase): 8 | def get_case(self, **kwargs): 9 | class MockDestroyTestCase(DestroyAPITestCaseMixin, mocks.MockTestCase): 10 | base_name = 'stuff' 11 | factory_class = mocks.StuffFactory 12 | 13 | self.case_class = MockDestroyTestCase 14 | 15 | return MockDestroyTestCase(**kwargs) 16 | 17 | def test_get_destroy_url(self): 18 | instance = self.get_case(methodName='dummy') 19 | instance.setUp() 20 | assert instance.get_destroy_url() == '/stuff/%s/' % instance.object.pk 21 | 22 | def test_get_destroy_response(self): 23 | instance = self.get_case(methodName='dummy') 24 | instance.setUp() 25 | response = instance.get_destroy_response() 26 | assert response 27 | assert response.status_code == 204 28 | 29 | def test_test_destroy(self): 30 | instance = self.get_case(methodName='dummy') 31 | instance.setUp() 32 | response = instance.test_destroy() 33 | assert response 34 | -------------------------------------------------------------------------------- /tests/test_detail.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | from rest_assured.testcases import DetailAPITestCaseMixin 4 | from tests import mocks 5 | 6 | 7 | class TestDetailTestCase(TestCase): 8 | def get_case(self, **kwargs): 9 | class MockDetailTestCase(DetailAPITestCaseMixin, mocks.MockTestCase): 10 | base_name = 'stuff' 11 | factory_class = mocks.StuffFactory 12 | 13 | self.case_class = MockDetailTestCase 14 | 15 | return MockDetailTestCase(**kwargs) 16 | 17 | def test_get_detail_url(self): 18 | instance = self.get_case(methodName='dummy') 19 | instance.setUp() 20 | assert instance.get_detail_url() == '/stuff/%s/' % instance.object.pk 21 | 22 | def test_get_detail_response(self): 23 | instance = self.get_case(methodName='dummy') 24 | instance.setUp() 25 | assert instance.get_detail_response() 26 | 27 | def test_test_detail(self): 28 | instance = self.get_case(methodName='dummy') 29 | instance.setUp() 30 | response = instance.test_detail() 31 | assert response 32 | 33 | def test_test_detail_callable_attribute(self): 34 | instance = self.get_case(methodName='dummy') 35 | instance.attributes_to_check = ['name', ('answer', lambda o: o.answer)] 36 | instance.setUp() 37 | response = instance.test_detail() 38 | assert response 39 | -------------------------------------------------------------------------------- /tests/test_list.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | from rest_assured.testcases import ListAPITestCaseMixin 4 | from tests import mocks 5 | 6 | 7 | class TestListTestCase(TestCase): 8 | def get_case(self, **kwargs): 9 | class MockListTestCase(ListAPITestCaseMixin, mocks.MockTestCase): 10 | base_name = 'stuff' 11 | factory_class = mocks.StuffFactory 12 | 13 | self.case_class = MockListTestCase 14 | 15 | return MockListTestCase(**kwargs) 16 | 17 | def test_get_list_url(self): 18 | instance = self.get_case(methodName='dummy') 19 | instance.setUp() 20 | assert instance.get_list_url() == '/stuff/' 21 | 22 | def test_get_list_response(self): 23 | instance = self.get_case(methodName='dummy') 24 | instance.setUp() 25 | response = instance.get_list_response() 26 | assert response 27 | assert response.status_code == 200 28 | assert response.data 29 | 30 | def test_test_list(self): 31 | instance = self.get_case(methodName='dummy') 32 | instance.setUp() 33 | response = instance.test_list() 34 | assert response 35 | -------------------------------------------------------------------------------- /tests/test_update.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | from rest_framework.reverse import reverse 4 | from rest_assured.testcases import UpdateAPITestCaseMixin 5 | from tests import mocks 6 | from tests.models import Stuff, RelatedStuff 7 | 8 | 9 | class TestUpdateTestCase(TestCase): 10 | def get_case(self, **kwargs): 11 | class MockUpdateTestCase(UpdateAPITestCaseMixin, mocks.MockTestCase): 12 | base_name = kwargs.pop('base_name', 'stuff') 13 | factory_class = mocks.StuffFactory 14 | update_data = {'name': 'other things'} 15 | 16 | self.case_class = MockUpdateTestCase 17 | 18 | return MockUpdateTestCase(**kwargs) 19 | 20 | def get_related_case(self, **kwargs): 21 | class MockUpdateTestCase(UpdateAPITestCaseMixin, mocks.MockTestCase): 22 | base_name = 'relatedstuff' 23 | factory_class = mocks.RelatedStuffFactory 24 | other_thing = mocks.StuffFactory.create(name='other related thing') 25 | update_data = {'thing': other_thing.id} 26 | update_results = {'thing': str(other_thing.id)} 27 | 28 | self.case_class = MockUpdateTestCase 29 | 30 | return MockUpdateTestCase(**kwargs) 31 | 32 | def get_related_linked_case(self, **kwargs): 33 | class MockUpdateTestCase(UpdateAPITestCaseMixin, mocks.MockTestCase): 34 | base_name = 'relatedstuff-linked' 35 | factory_class = mocks.RelatedStuffFactory 36 | other_thing = mocks.StuffFactory.create(name='other related thing') 37 | related_url = reverse('stuff-linked-detail', (other_thing.id,)) 38 | update_data = {'thing': related_url} 39 | update_results = {'thing': related_url} 40 | 41 | def get_relationship_value(self, related, key): 42 | return reverse('stuff-linked-detail', (related.id,)) 43 | 44 | self.case_class = MockUpdateTestCase 45 | 46 | return MockUpdateTestCase(**kwargs) 47 | 48 | def get_many_related_case(self, **kwargs): 49 | class MockUpdateTestCase(UpdateAPITestCaseMixin, mocks.MockTestCase): 50 | base_name = kwargs.pop('base_name', 'manyrelatedstuff') 51 | factory_class = mocks.ManyRelatedStuffFactory 52 | 53 | def get_update_data(self): 54 | other_thing = mocks.StuffFactory.create(name='other related thing') 55 | another_thing = mocks.StuffFactory.create(name='another related thing') 56 | return {'stuff': [other_thing.id, another_thing.id]} 57 | 58 | self.case_class = MockUpdateTestCase 59 | 60 | return MockUpdateTestCase(**kwargs) 61 | 62 | def test_get_update_url(self): 63 | instance = self.get_case(methodName='dummy') 64 | instance.setUp() 65 | assert instance.get_update_url() == '/stuff/%s/' % instance.object.pk 66 | 67 | def test_get_update_data(self): 68 | instance = self.get_case(methodName='dummy') 69 | assert instance.get_update_data() is self.case_class.update_data 70 | 71 | def test_get_update_response(self): 72 | instance = self.get_case(methodName='dummy') 73 | instance.setUp() 74 | assert instance.get_update_response() 75 | 76 | def test_test_update(self): 77 | instance = self.get_case(methodName='dummy') 78 | instance.setUp() 79 | response, updated = instance.test_update() 80 | assert response 81 | assert updated 82 | assert isinstance(updated, Stuff) 83 | assert response.data['name'] == updated.name 84 | 85 | def test_test_update_with_foreignkey(self): 86 | instance = self.get_related_case(methodName='dummy') 87 | instance.setUp() 88 | response, updated = instance.test_update() 89 | assert response 90 | assert updated 91 | assert isinstance(updated, RelatedStuff) 92 | assert response.data['thing'] == updated.thing.id 93 | 94 | def test_test_update_with_foreignkey_and_hyperlinkedmodelserializer(self): 95 | instance = self.get_related_linked_case(methodName='dummy') 96 | instance.setUp() 97 | response, updated = instance.test_update() 98 | assert response 99 | assert updated 100 | assert isinstance(updated, RelatedStuff) 101 | -------------------------------------------------------------------------------- /tests/urls.py: -------------------------------------------------------------------------------- 1 | from rest_framework import routers 2 | 3 | from tests import mocks 4 | 5 | 6 | router = routers.DefaultRouter() 7 | 8 | router.register(r'stuff', 9 | mocks.StuffViewSet, 10 | base_name='stuff') 11 | 12 | router.register(r'stuff-linked', 13 | mocks.StuffHyperlinkedViewSet, 14 | base_name='stuff-linked') 15 | 16 | router.register(r'related-stuff', 17 | mocks.RelatedStuffViewSet, 18 | base_name='relatedstuff') 19 | 20 | router.register(r'related-stuff-linked', 21 | mocks.RelatedStuffHyperlinkedViewSet, 22 | base_name='relatedstuff-linked') 23 | 24 | router.register(r'many-related-stuff', 25 | mocks.RelatedStuffViewSet, 26 | base_name='manyrelatedstuff') 27 | 28 | router.register(r'many-related-stuff-linked', 29 | mocks.RelatedStuffHyperlinkedViewSet, 30 | base_name='manyrelatedstuff-linked') 31 | 32 | urlpatterns = router.urls 33 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = 3 | py27-flake8, 4 | {py27,py35}-django{1.11}-drf{3.4,3.5,3.6}-pytest{2.8}-pytestdjango{2.9} 5 | {py35,py36,py37,py38}-django{2.1,2.2}-drf{3.7,3.8,3.9,3.10}-pytest{5.0}-pytestdjango{3.5} 6 | {py37,py38}-django{3.0}-drf{3.10}-pytest{5.0}-pytestdjango{3.5} 7 | 8 | [testenv] 9 | commands = 10 | python -V 11 | py.test -q 12 | setenv = 13 | PYTHONDONTWRITEBYTECODE=1 14 | deps = 15 | django1.11: Django>=1.11,<1.12 16 | django2.1: Django>=2.1,<2.2 17 | django2.2: Django>=2.2,<2.3 18 | django3.0: Django>=3.0 19 | drf3.4: djangorestframework==3.4.7 20 | drf3.5: djangorestframework==3.5.4 21 | drf3.6: djangorestframework==3.6.4 22 | drf3.7: djangorestframework==3.7.7 23 | drf3.8: djangorestframework==3.8.2 24 | drf3.9: djangorestframework==3.9.4 25 | drf3.10: djangorestframework==3.10.0 26 | pytest2.8: pytest==2.8.5 27 | pytest5.0: pytest==5.0.1 28 | pytestdjango2.9: pytest-django==2.9.1 29 | pytestdjango3.5: pytest-django==3.5.1 30 | 31 | 32 | [testenv:py27-flake8] 33 | commands = flake8 rest_assured tests --ignore=E501 34 | deps = flake8==2.2.5 35 | --------------------------------------------------------------------------------