Commit 35d31bd5 authored by freetux's avatar freetux

Initial commit

parents
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
db.sqlite3
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
.hypothesis/
# Translations
*.mo
*.pot
# Django stuff:
*.log
# Sphinx documentation
docs/_build/
# PyBuilder
target/
#Ipython Notebook
.ipynb_checkpoints
#virtualENV
my_project
The MIT License (MIT)
Copyright (c) 2016 Fatih Erikli
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
\ No newline at end of file
## DRF-TDD-Example
An example Django REST framework project for test driven development.
### Test Case Scenarios
* Test to verify registration with invalid password.
* Test to verify registration with already exists username.
* Test to verify registration with valid datas.
* Tested API authentication endpoint validations.
* Tested authenticated user authorization.
* Create a todo with API.
* Update a todo with API.
* Update a todo with API.
* Delete a todo with API.
* Get todo list for a user.
### API Endpoints
#### Users
* **/api/users/** (User registration endpoint)
* **/api/users/login/** (User login endpoint)
* **/api/users/logout/** (User logout endpoint)
#### Todos
* **/api/todos/** (Todo create and list endpoint)
* **/api/todos/{todo-id}/** (Todo retrieve, update and destroy endpoint)
### Install
pip install -r requirements.txt
### Usage
python manage.py test
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${file}",
"outFiles": [
"${workspaceFolder}/**/*.js"
]
}
]
}
\ No newline at end of file
{
"typescript.tsdk": "node_modules\\typescript\\lib"
}
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tanbama.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
# API Usage Guide:
### API Endpoints
#### Users
* **/api/users/** (User registration endpoint)
allow methods:post
example:
POST:
curl -X POST -H 'Content-Type: application/json' -d "username=yourusername&password=yourpassword&email=your@demoemail.com" yourdomain/api/users/
output:
give you an token
* **/api/users/login/** (User login endpoint)
curl -X POST -H 'Content-Type: application/json' -d "username=yourusername&password=yourpassword" yourdomain/api/users/login
output:
give you an token
* **/api/users/logout/** (User logout endpoint)
curl -X POST -H 'Content-Type: application/json' -d "username=yourusername&password=yourpassword" yourdomain/api/users/logout
output:
delete your token from database.dont worry you can login for another one!
#### Weights
* **/api/weights/** (Weight create and list endpoint)
Allowed methods:GET, POST
GET:
curl -H "Authorization: JWT yourtoken" -H "Content-type: application/json" -H "Accept: application/json" -X GET http://localhost:8000/api/weights
output:
list of your height and weights
POST
curl -H "Authorization: JWT yourtoken" -H "Content-type: application/json" -H "Accept: application/json" -d '{"weight":70,"height":182,"text":"demo"}' -X POST http://localhost:8000/api/weights
output:
create an weight and height to database
* **/api/weights/{weight-id}/** (Weight retrieve, update and destroy endpoint)
"""
Django settings for tanbama project.
Generated by 'django-admin startproject' using Django 1.9.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import datetime
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 = 'k8b^y952f(10ox6993@h0q3-+&d_r#-g!qu+1zpggva_kux)2x'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
'users',
'weights',
'django_nose'
]
JWT_AUTH = {
'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=259200), # 3 days
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(seconds=259200), # 3 days
'JWT_AUTH_COOKIE': 'JWT',
'JWT_ALLOW_REFRESH': True,
}
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'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 = 'tanbama.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 = 'tanbama.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'TEST_REQUEST_DEFAULT_FORMAT': 'json',
}
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
CORS_ORIGIN_ALLOW_ALL=True
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Tehran'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
# Use nose to run all tests
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
# Tell nose to measure coverage on the 'foo' and 'bar' apps
NOSE_ARGS = [
'--with-coverage',
'--cover-package=users,weights',
]
38eb7e0a7e1efd74f1dd2de0c860f6ddee98f68a
\ No newline at end of file
from django.conf.urls import url, include
from django.contrib import admin
api_urls = [
url(r'^weights/', include('weights.urls', namespace='weights')),
url(r'^users/', include('users.urls', namespace='users')),
]
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/', include(api_urls)),
]
"""
WSGI config for todoapp project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "todoapp.settings")
application = get_wsgi_application()
from django.contrib import admin
# Register your models here.
from __future__ import unicode_literals
from django.apps import AppConfig
class UsersConfig(AppConfig):
name = 'users'
from __future__ import unicode_literals
from django.db import models
# Create your models here.
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from rest_framework.authtoken.models import Token
class UserRegistrationSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('email', 'username', 'password')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
user = User(
email=validated_data['email'],
username=validated_data['username']
)
user.set_password(validated_data['password'])
user.save()
return user
class UserLoginSerializer(serializers.Serializer):
username = serializers.CharField(required=True)
password = serializers.CharField(required=True)
default_error_messages = {
'inactive_account': _('User account is disabled.'),
'invalid_credentials': _('Unable to login with provided credentials.')
}
def __init__(self, *args, **kwargs):
super(UserLoginSerializer, self).__init__(*args, **kwargs)
self.user = None
def validate(self, attrs):
self.user = authenticate(username=attrs.get("username"), password=attrs.get('password'))
if self.user:
if not self.user.is_active:
raise serializers.ValidationError(self.error_messages['inactive_account'])
return attrs
else:
raise serializers.ValidationError(self.error_messages['invalid_credentials'])
import json
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from rest_framework.authtoken.models import Token
from rest_framework.test import APITestCase
class UserRegistrationAPIViewTestCase(APITestCase):
url = reverse("users:list")
def test_invalid_password(self):
"""
Test to verify that a post call with invalid passwords
"""
user_data = {
"username": "testuser",
"email": "test@testuser.com",
"password": "password",
"confirm_password": "INVALID_PASSWORD"
}
response = self.client.post(self.url, user_data)
self.assertEqual(400, response.status_code)
def test_user_registration(self):
"""
Test to verify that a post call with user valid data
"""
user_data = {
"username": "testuser",
"email": "test@testuser.com",
"password": "123123",
"confirm_password": "123123"
}
response = self.client.post(self.url, user_data)
self.assertEqual(201, response.status_code)
self.assertTrue("token" in json.loads(response.content))
def test_unique_username_validation(self):
"""
Test to verify that a post call with already exists username
"""
user_data_1 = {
"username": "testuser",
"email": "test@testuser.com",
"password": "123123",
"confirm_password": "123123"
}
response = self.client.post(self.url, user_data_1)
self.assertEqual(201, response.status_code)
user_data_2 = {
"username": "testuser",
"email": "test2@testuser.com",
"password": "123123",
"confirm_password": "123123"
}
response = self.client.post(self.url, user_data_2)
self.assertEqual(400, response.status_code)
class UserLoginAPIViewTestCase(APITestCase):
url = reverse("users:login")
def setUp(self):
self.username = "john"
self.email = "john@snow.com"
self.password = "you_know_nothing"
self.user = User.objects.create_user(self.username, self.email, self.password)
def test_authentication_without_password(self):
response = self.client.post(self.url, {"username": "snowman"})
self.assertEqual(400, response.status_code)
def test_authentication_with_wrong_password(self):
response = self.client.post(self.url, {"username": self.username, "password": "I_know"})
self.assertEqual(400, response.status_code)
def test_authentication_with_valid_data(self):
response = self.client.post(self.url, {"username": self.username, "password": self.password})
self.assertEqual(200, response.status_code)
self.assertTrue("token" in json.loads(response.content))
class UserLogoutAPIViewTestCase(APITestCase):
url = reverse("users:logout")
def setUp(self):
self.username = "john"
self.email = "john@snow.com"
self.password = "you_know_nothing"
self.user = User.objects.create_user(self.username, self.email, self.password)
self.token = Token.objects.create(user=self.user)
self.api_authentication()