Hello, Every one, I write a "user login" code, and now I write a unit test for it, But the unit test cannot works well!
I write the unit test by using the django-test-addons
This is the main part for my settings.py
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'xkw=^1((9ae7cv0+)%b%jrq7e$+1xy_=&cpwk!lc*=8hqp9sdp'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
# django mongo engine
'django_mongoengine',
'django_mongoengine.mongo_auth',
'django_mongoengine.mongo_admin.sites',
'django_mongoengine.mongo_admin',
# Myself
'passage',
'account',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'BlogV2BackEnd.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'BlogV2BackEnd.wsgi.application'
# Set the Django-mongoengien
MONGODB_DATABASES = {
'default': {
'name': 'blog',
'host': 'localhost',
}
}
AUTH_USER_MODEL = 'mongo_auth.MongoUser'
AUTHENTICATION_BACKENDS = (
'django_mongoengine.mongo_auth.backends.MongoEngineBackend',
)
SESSION_ENGINE = 'django_mongoengine.sessions'
TEST_MONGO_DATABASE = {
'db': 'blog_test',
'host': ['localhost'],
'port': 27017
}
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
SITE_ID = 1
This is my unittest code:
# Create your tests here.
from django.utils.encoding import force_text
from django_mongoengine.mongo_auth.models import User
import test_addons
import time
class AuthTest(test_addons.MongoTestCase):
def test_can_login_with_correct_user(self):
User.objects.create(username='xff', password='abc123')
data = {'username': 'xff', 'password': 'abc123'}
# time.sleep(40)
response = self.client.post('/account/login/', data=data)
self.assertJSONEqual(force_text(response.content), {'status': 'success'})
This is my login code
#urls.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from django.conf.urls import url
from account import views
urlpatterns = [
url(r'^login/$', views.login),
]
# views.py
from django.http import JsonResponse, Http404
from django.contrib.auth import authenticate, login as django_login
# Create your views here.
def login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
django_login(request, user)
response = {
'status': 'success'
}
else:
response = {
'status': 'deny'
}
else:
response = {
'status': 'failed'
}
return JsonResponse(response)
else:
raise Http404
This is my test result:
➜ /home/michael/gitroom/BlogV2BackEnd (dev) ✗ [blog]$ ./manage.py test account
F
======================================================================
FAIL: test_can_login_with_correct_user (account.tests.AuthTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/michael/gitroom/BlogV2BackEnd/account/tests.py", line 15, in test_can_login_with_correct_user
self.assertJSONEqual(force_text(response.content), {'status': 'success'})
File "/home/michael/.virtualenvs/blog/lib/python3.4/site-packages/django/test/testcases.py", line 759, in assertJSONEqual
self.assertEqual(data, expected_data, msg=msg)
AssertionError: {'status': 'failed'} != {'status': 'success'}
- {'status': 'failed'}
+ {'status': 'success'}
----------------------------------------------------------------------
Ran 1 test in 0.070s
FAILED (failures=1)
I insert a sleep statement in my unit test code, and find the blog_test db in my mongodb, and the user which I created in the unit test, this is the mongo shell output:
➜ /home/michael/.virtualenvs/blog/lib/python3.4/site-packages/django_mongoengine/mongo_auth $ mongo
MongoDB shell version: 2.4.9
connecting to: test
> show dbs;
blog 0.203125GB
blog_test 0.203125GB
django_mongoengine 0.203125GB
> use blog_test
switched to db blog_test
> db.user.find();
{ "_id" : ObjectId("57344281f34a283ce4ff46de"), "_cls" : "User", "username" : "xff", "password" : "abc123", "is_staff" : false, "is_active" : true, "is_superuser" : false, "last_login" : ISODate("2016-05-12T08:44:49.706Z"), "date_joined" : ISODate("2016-05-12T08:44:49.706Z"), "user_permissions" : [ ] }
Hello, Every one, I write a "user login" code, and now I write a unit test for it, But the unit test cannot works well!
I write the unit test by using the django-test-addons
This is the main part for my settings.py
This is my unittest code:
This is my login code
This is my test result:
I insert a sleep statement in my unit test code, and find the blog_test db in my mongodb, and the user which I created in the unit test, this is the mongo shell output: