├── .coveragerc ├── .gitignore ├── birdie ├── __init__.py ├── admin.py ├── apps.py ├── forms.py ├── migrations │ └── __init__.py ├── models.py ├── templates │ └── birdie │ │ └── home.html ├── tests │ ├── __init__.py │ ├── test_admin.py │ ├── test_forms.py │ ├── test_models.py │ └── test_views.py └── views.py ├── manage.py ├── pytest.ini └── tested ├── __init__.py ├── settings.py ├── test_settings.py ├── urls.py └── wsgi.py /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | omit = 3 | *apps.py, 4 | *migrations/*, 5 | *settings*, 6 | *tests/*, 7 | *urls.py, 8 | *wsgi.py, 9 | manage.py 10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | .coverage 3 | .cache/ 4 | htmlcov/ 5 | -------------------------------------------------------------------------------- /birdie/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mbrochh/django-testing-cookbook/cea575a52bfd543040ddaaf182802ead00aab024/birdie/__init__.py -------------------------------------------------------------------------------- /birdie/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from . import models 3 | 4 | 5 | class PostAdmin(admin.ModelAdmin): 6 | list_display = ['excerpt', ] 7 | 8 | def excerpt(self, obj): 9 | return obj.get_excerpt(5) 10 | admin.site.register(models.Post, PostAdmin) 11 | -------------------------------------------------------------------------------- /birdie/apps.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | 3 | from django.apps import AppConfig 4 | 5 | 6 | class BirdieConfig(AppConfig): 7 | name = 'birdie' 8 | -------------------------------------------------------------------------------- /birdie/forms.py: -------------------------------------------------------------------------------- 1 | from django import forms 2 | 3 | from . import models 4 | 5 | 6 | class PostForm(forms.ModelForm): 7 | class Meta: 8 | model = models.Post 9 | fields = ('body', ) 10 | 11 | def clean_body(self): 12 | data = self.cleaned_data.get('body') 13 | if len(data) < 10: 14 | raise forms.ValidationError('Please enter at least 10 characters') 15 | return data 16 | -------------------------------------------------------------------------------- /birdie/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mbrochh/django-testing-cookbook/cea575a52bfd543040ddaaf182802ead00aab024/birdie/migrations/__init__.py -------------------------------------------------------------------------------- /birdie/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | from django.db import models 3 | 4 | 5 | class Post(models.Model): 6 | body = models.TextField() 7 | 8 | def get_excerpt(self, chars): 9 | return self.body[:chars] 10 | -------------------------------------------------------------------------------- /birdie/templates/birdie/home.html: -------------------------------------------------------------------------------- 1 | Hello World 2 | -------------------------------------------------------------------------------- /birdie/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mbrochh/django-testing-cookbook/cea575a52bfd543040ddaaf182802ead00aab024/birdie/tests/__init__.py -------------------------------------------------------------------------------- /birdie/tests/test_admin.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from django.contrib.admin.sites import AdminSite 3 | from mixer.backend.django import mixer 4 | from .. import admin 5 | from .. import models 6 | pytestmark = pytest.mark.django_db 7 | 8 | 9 | class TestPostAdmin: 10 | def test_excerpt(self): 11 | site = AdminSite() 12 | post_admin = admin.PostAdmin(models.Post, site) 13 | obj = mixer.blend('birdie.Post', body='Hello World') 14 | 15 | result = post_admin.excerpt(obj) 16 | expected = obj.get_excerpt(5) 17 | assert result == expected, ( 18 | 'Should return the result form the .excerpt() function') 19 | -------------------------------------------------------------------------------- /birdie/tests/test_forms.py: -------------------------------------------------------------------------------- 1 | from .. import forms 2 | 3 | 4 | class TestPostForm: 5 | def test_form(self): 6 | form = forms.PostForm(data={}) 7 | assert form.is_valid() is False, ( 8 | 'Should be invalid if no data is given') 9 | 10 | data = {'body': 'Hello'} 11 | form = forms.PostForm(data=data) 12 | assert form.is_valid() is False, ( 13 | 'Should be invalid if body text is less than 10 characters') 14 | assert 'body' in form.errors, 'Should return field error for `body`' 15 | 16 | data = {'body': 'Hello World!'} 17 | form = forms.PostForm(data=data) 18 | assert form.is_valid() is True, 'Should be valid all data is given' 19 | -------------------------------------------------------------------------------- /birdie/tests/test_models.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from mixer.backend.django import mixer 3 | pytestmark = pytest.mark.django_db 4 | 5 | 6 | class TestPost: 7 | def test_init(self): 8 | obj = mixer.blend('birdie.Post') 9 | assert obj.pk == 1, 'Should save an instance' 10 | 11 | def test_get_excerpt(self): 12 | obj = mixer.blend('birdie.Post', body='Hello World!') 13 | result = obj.get_excerpt(5) 14 | expected = 'Hello' 15 | assert result == expected, ( 16 | 'Should return the given number of characters') 17 | -------------------------------------------------------------------------------- /birdie/tests/test_views.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from django.core import mail 3 | from django.contrib.auth.models import AnonymousUser 4 | from django.http import Http404 5 | from django.test import RequestFactory 6 | from mock import patch 7 | from mixer.backend.django import mixer 8 | pytestmark = pytest.mark.django_db 9 | 10 | from .. import views 11 | 12 | 13 | class TestHomeView: 14 | def test_anonymous(self): 15 | req = RequestFactory().get('/') 16 | resp = views.HomeView.as_view()(req) 17 | assert resp.status_code == 200, 'Should be callable by anyone' 18 | 19 | 20 | class TestAdminView: 21 | def test_anonymous(self): 22 | req = RequestFactory().get('/') 23 | req.user = AnonymousUser() 24 | resp = views.AdminView.as_view()(req) 25 | assert 'login' in resp.url, 'Should redirect to login' 26 | 27 | def test_superuser(self): 28 | user = mixer.blend('auth.User', is_superuser=True) 29 | req = RequestFactory().get('/') 30 | req.user = user 31 | resp = views.AdminView.as_view()(req) 32 | assert resp.status_code == 200, 'Should be callable by superuser' 33 | 34 | 35 | class TestPostUpdateView: 36 | def test_get(self): 37 | post = mixer.blend('birdie.Post') 38 | req = RequestFactory().get('/') 39 | req.user = AnonymousUser() 40 | resp = views.PostUpdateView.as_view()(req, pk=post.pk) 41 | assert resp.status_code == 200, 'Should be callable by anyone' 42 | 43 | def test_post(self): 44 | post = mixer.blend('birdie.Post') 45 | data = {'body': 'New Body Text!'} 46 | req = RequestFactory().post('/', data=data) 47 | req.user = AnonymousUser() 48 | resp = views.PostUpdateView.as_view()(req, pk=post.pk) 49 | assert resp.status_code == 302, 'Should redirect to success view' 50 | post.refresh_from_db() 51 | assert post.body == 'New Body Text!', 'Should update the post' 52 | 53 | def test_security(self): 54 | user = mixer.blend('auth.User', first_name='Martin') 55 | post = mixer.blend('birdie.Post') 56 | req = RequestFactory().post('/', data={}) 57 | req.user = user 58 | with pytest.raises(Http404): 59 | views.PostUpdateView.as_view()(req, pk=post.pk) 60 | 61 | 62 | class TestPaymentView: 63 | @patch('birdie.views.stripe') 64 | def test_payment(self, mock_stripe): 65 | mock_stripe.Charge.return_value = {'id': '234'} 66 | req = RequestFactory().post('/', data={'token': '123'}) 67 | resp = views.PaymentView.as_view()(req) 68 | assert resp.status_code == 302, 'Should redirect to success_url' 69 | assert len(mail.outbox) == 1, 'Should send an email' 70 | -------------------------------------------------------------------------------- /birdie/views.py: -------------------------------------------------------------------------------- 1 | from django.contrib.auth.decorators import login_required 2 | from django.core.mail import send_mail 3 | from django.http import Http404 4 | from django.shortcuts import redirect 5 | from django.utils.decorators import method_decorator 6 | from django.views import generic 7 | 8 | import stripe 9 | 10 | from . import models 11 | from . import forms 12 | 13 | 14 | class HomeView(generic.TemplateView): 15 | template_name = 'birdie/home.html' 16 | 17 | 18 | class AdminView(generic.TemplateView): 19 | template_name = 'birdie/admin.html' 20 | 21 | @method_decorator(login_required) 22 | def dispatch(self, request, *args, **kwargs): 23 | return super(AdminView, self).dispatch(request, *args, **kwargs) 24 | 25 | 26 | class PostUpdateView(generic.UpdateView): 27 | model = models.Post 28 | form_class = forms.PostForm 29 | success_url = '/' 30 | 31 | def post(self, request, *args, **kwargs): 32 | if getattr(request.user, 'first_name', None) == 'Martin': 33 | raise Http404() 34 | return super(PostUpdateView, self).post(request, *args, **kwargs) 35 | 36 | 37 | class PaymentView(generic.View): 38 | def post(self, request, *args, **kwargs): 39 | charge = stripe.Charge.create( 40 | amount=100, 41 | currency='sgd', 42 | description='', 43 | token=request.POST.get('token'), 44 | ) 45 | send_mail( 46 | 'Payment received', 47 | 'Charge {} succeeded!'.format(charge['id']), 48 | 'server@example.com', 49 | ['admin@example.com', ], 50 | ) 51 | return redirect('/') 52 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tested.settings") 7 | 8 | from django.core.management import execute_from_command_line 9 | 10 | execute_from_command_line(sys.argv) 11 | -------------------------------------------------------------------------------- /pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | DJANGO_SETTINGS_MODULE = tested.test_settings 3 | addopts = --nomigrations 4 | -------------------------------------------------------------------------------- /tested/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mbrochh/django-testing-cookbook/cea575a52bfd543040ddaaf182802ead00aab024/tested/__init__.py -------------------------------------------------------------------------------- /tested/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for tested project. 3 | 4 | Generated by 'django-admin startproject' using Django 1.9.2. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.9/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/1.9/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'hb^o)@%%tj&g=155k9ztw--bur^10xg-z-zw$&#^3ht4+eod7s' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'birdie', 41 | ] 42 | 43 | MIDDLEWARE_CLASSES = [ 44 | 'django.middleware.security.SecurityMiddleware', 45 | 'django.contrib.sessions.middleware.SessionMiddleware', 46 | 'django.middleware.common.CommonMiddleware', 47 | 'django.middleware.csrf.CsrfViewMiddleware', 48 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 49 | 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 50 | 'django.contrib.messages.middleware.MessageMiddleware', 51 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 52 | ] 53 | 54 | ROOT_URLCONF = 'tested.urls' 55 | 56 | TEMPLATES = [ 57 | { 58 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 59 | 'DIRS': [], 60 | 'APP_DIRS': True, 61 | 'OPTIONS': { 62 | 'context_processors': [ 63 | 'django.template.context_processors.debug', 64 | 'django.template.context_processors.request', 65 | 'django.contrib.auth.context_processors.auth', 66 | 'django.contrib.messages.context_processors.messages', 67 | ], 68 | }, 69 | }, 70 | ] 71 | 72 | WSGI_APPLICATION = 'tested.wsgi.application' 73 | 74 | 75 | # Database 76 | # https://docs.djangoproject.com/en/1.9/ref/settings/#databases 77 | 78 | DATABASES = { 79 | 'default': { 80 | 'ENGINE': 'django.db.backends.sqlite3', 81 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 82 | } 83 | } 84 | 85 | 86 | # Password validation 87 | # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators 88 | 89 | AUTH_PASSWORD_VALIDATORS = [ 90 | { 91 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 92 | }, 93 | { 94 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 95 | }, 96 | { 97 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 98 | }, 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 101 | }, 102 | ] 103 | 104 | 105 | # Internationalization 106 | # https://docs.djangoproject.com/en/1.9/topics/i18n/ 107 | 108 | LANGUAGE_CODE = 'en-us' 109 | 110 | TIME_ZONE = 'UTC' 111 | 112 | USE_I18N = True 113 | 114 | USE_L10N = True 115 | 116 | USE_TZ = True 117 | 118 | 119 | # Static files (CSS, JavaScript, Images) 120 | # https://docs.djangoproject.com/en/1.9/howto/static-files/ 121 | 122 | STATIC_URL = '/static/' 123 | -------------------------------------------------------------------------------- /tested/test_settings.py: -------------------------------------------------------------------------------- 1 | from .settings import * 2 | 3 | DATABASES = { 4 | "default": { 5 | "ENGINE": "django.db.backends.sqlite3", 6 | "NAME": ":memory:", 7 | } 8 | } 9 | 10 | EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' 11 | -------------------------------------------------------------------------------- /tested/urls.py: -------------------------------------------------------------------------------- 1 | """tested URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/1.9/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.conf.urls import url, include 14 | 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) 15 | """ 16 | from django.conf.urls import url 17 | from django.contrib import admin 18 | 19 | urlpatterns = [ 20 | url(r'^admin/', admin.site.urls), 21 | ] 22 | -------------------------------------------------------------------------------- /tested/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for tested project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tested.settings") 15 | 16 | application = get_wsgi_application() 17 | --------------------------------------------------------------------------------