Skip to content

Commit

Permalink
Merge pull request #5 from andela/ch-unittests-setup-164798188
Browse files Browse the repository at this point in the history
#164798188 Writing tests for existing functionalities
  • Loading branch information
ja-odur committed Mar 28, 2019
2 parents 1d936c2 + 6c608fc commit c7accd4
Show file tree
Hide file tree
Showing 9 changed files with 388 additions and 41 deletions.
4 changes: 2 additions & 2 deletions .env_config_sample
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export DATABASE_URI='postgres://USER:PASSWORD@HOST:PORT/NAME'
export SECRET_KEY='AuthorsHaven'
DATABASE_URI='postgres://USER:PASSWORD@HOST:PORT/DB_NAME'
SECRET_KEY='AuthorsHaven'
Empty file.
17 changes: 17 additions & 0 deletions authors/apps/authentication/tests/test_base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
"""
Test base module
"""
from rest_framework.test import APITestCase, APIClient


class BaseTestCase(APITestCase):
"""
Class to define a testbase class
"""

def setUp(self):
"""
Method to handle data to be setup before running tests
"""
self.client = APIClient()

61 changes: 61 additions & 0 deletions authors/apps/authentication/tests/test_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
no_login_credentialds_data = {}

login_credentials_data = {
"user": {
"username": "user",
"email": "testuser@gmail.com",
"password": "user@12345"
}
}
empty_string_username = {
"user": {
"username": "",
"email": "userstest67@gmail.com",
"password": "Users@12345"
}
}
empty_string_email = {
"user": {
"username": "kiryowa22",
"email": "",
"password": "users@134"
}
}
empty_string_password = {
"user": {
"username": "kiryowa22",
"email": "kiryowa@gmail.com",
"password": ""
}
}
invalid_email_data = {
"user": {
"username": "Rogha1996",
"email": "Rogha",
"password": "12345678"
}
}
login_data = {
"user": {
"email":"testuser@gmail.com",
"password":"user@12345"
}
}
invalid_login_data = {
"user": {
"email":"testuser@gmail.comhhfhf",
"password":"user@12345"
}
}
login_data_miss_email = {
"user": {
"password":"kiryowa1993"
}
}
login_data_miss_password = {
"user": {
"email":"franciskiryowa68@gmail.com"
}
}

empty_login_data_object = {}
88 changes: 88 additions & 0 deletions authors/apps/authentication/tests/test_serializer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
from .test_base import BaseTestCase
from authors.apps.authentication.serializers import (
LoginSerializer, UserSerializer
)
from unittest.mock import patch, MagicMock, PropertyMock

from rest_framework.serializers import ValidationError

class TestLoginSerializer(BaseTestCase):
"""
class to handles user model tests
"""
def test_email_not_provided_to_validate_function(self):
"""
Method to test if email is not provided to validate function in serializers
"""
data_no_email = {
"email":None,
"password":"user@12345"
}
with self.assertRaises(ValidationError) as e:
LoginSerializer().validate(data_no_email)
self.assertEqual(e.exception.args[0], 'An email address is required to log in.')

def test_password_not_provided_to_validate_function(self):
"""
Method to test if password is not provided to validate function in serializers
"""
data_no_password = {
"email":"user@gmail.com",
"password":None
}
with self.assertRaises(ValidationError) as e:
LoginSerializer().validate(data_no_password)
self.assertEqual(e.exception.args[0], 'A password is required to log in.')

def test_user_is_not_active(self):
"""
Method to test if user is not active
"""
user_password_and_email = {
"email":"user@gmail.com",
"password":"user@1234"
}

class MockAuthenticate:
is_active = False

@classmethod
def __call__(cls, *args, **kwargs):
return cls

with patch('authors.apps.authentication.serializers.authenticate', new_callable=MockAuthenticate),\
self.assertRaises(ValidationError) as e:

LoginSerializer().validate(user_password_and_email)

self.assertEqual(e.exception.args[0], 'This user has been deactivated.')

def test_update_user_data(self):
"""
Method to test update user data
"""
class UpdateUserInstance:

def save(self):
pass
def set_password(self, password):
pass

data_to_update_user = {
"email":"user@gmail.com,",
"password":"user@123",
"username":"usher123"
}

class_instance = UpdateUserInstance()
self.assertEqual(UserSerializer().update(class_instance, data_to_update_user), class_instance)










55 changes: 55 additions & 0 deletions authors/apps/authentication/tests/test_user_manager_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
from .test_base import BaseTestCase
from authors.apps.authentication.models import UserManager
from unittest.mock import patch, MagicMock, PropertyMock
from authors.apps.authentication.models import User

class TestUserModel(BaseTestCase):
"""
class to handles user model tests
"""
def test_username_not_provided_on_creating_user(self):
"""
Method to test if user is created without providing a username
"""
with self.assertRaises(TypeError):
UserManager().create_user(username=None, email="user@gmail.com")

def test_email_not_provided_on_creating_user(self):
"""
Method to test if user is created without providing an email
"""
with self.assertRaises(TypeError):
UserManager().create_user(username="user22", email=None)

def test_password_not_provided_on_creating_super_user(self):
"""
Method to test if super user is create without a password
"""
with self.assertRaises(TypeError):
UserManager().create_superuser(username="user22", email="user@gmail.com", password=None)

def test_if_password_is_provided_when_creating_super_user(self):
"""
Method to test if super user is created with a password
"""
class MockCreateUser:
is_superuser = False
is_staff = False

@classmethod
def __call__(cls, *args, **kwargs):
return cls()

def save(self):
pass

with patch('authors.apps.authentication.models.UserManager.create_user', new_callable=MockCreateUser):
user = UserManager().create_superuser(username="user22", email="user@gmail.com", password="user@123")
self.assertTrue(user.is_superuser)
self.assertTrue(user.is_staff)
self.assertEqual(user.save(), None)





139 changes: 139 additions & 0 deletions authors/apps/authentication/tests/test_user_registration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
"""
Module to test functionality to register a user
"""
from rest_framework import status
from rest_framework.test import APITestCase
from .test_data import (
no_login_credentialds_data,
login_credentials_data,
empty_string_username,
empty_string_email,
empty_string_password,
invalid_email_data,
login_data,
invalid_login_data,
login_data_miss_email,
login_data_miss_password,
empty_login_data_object
)
from .test_base import BaseTestCase


class TestUserRegistration(BaseTestCase):
"""
class to handle user registration and user login tests
"""

def test_register_a_user_with_no_data(self):
"""
Method to test if posted user registration user object contains no data
"""

response = self.client.post('/api/users/', no_login_credentialds_data, format='json')
self.assertIn(response.data["errors"]["email"][0], 'This field is required.')
self.assertIn(response.data["errors"]["username"][0], 'This field is required.')
self.assertIn(response.data["errors"]["password"][0], 'This field is required.')
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)


def test_register_a_user_with_data(self):
"""
Method to test if posted registration user object contains data
"""
response = self.client.post('/api/users/', login_credentials_data, format='json')
self.assertEqual(response.data["email"], 'testuser@gmail.com')
self.assertEqual(response.data["username"], 'user')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)

response1 = self.client.post('/api/users/', login_credentials_data, format='json')
self.assertIn(response1.data["errors"]["email"][0], 'user with this email already exists.')
self.assertIn(response1.data["errors"]["username"][0], 'user with this username already exists.')
self.assertEqual(response1.status_code, status.HTTP_400_BAD_REQUEST)

def test_user_registered_with_empty_string_username(self):
"""
Method to test if username is an empty string
"""
response = self.client.post('/api/users/', empty_string_username, format='json')
self.assertIn(response.data["errors"]["username"][0], '"This field may not be blank."')
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

def test_user_registered_with_empty_email_string(self):
"""
Method to test if username is an empty string
"""
response = self.client.post('/api/users/', empty_string_email, format='json')
self.assertIn(response.data["errors"]["email"][0], '"This field may not be blank."')
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

def test_user_registered_with_empty_password_string(self):
"""
Method to test if username is an empty string
"""
response = self.client.post('/api/users/', empty_string_password, format='json')
self.assertIn(response.data["errors"]["password"][0], 'This field may not be blank.')
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

def test_user_registered_with_an_invalid_email(self):
"""
Method to test if email is an invalid email
"""
response = self.client.post('/api/users/', invalid_email_data , format='json')
self.assertIn(response.data["errors"]["email"][0], 'Enter a valid email address.')
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

def test_user_login_successfully_with_valid_data(self):
"""
Method to test if user successfully logs in using valid credentials
"""
self.client.post('/api/users/', login_credentials_data, format='json')
response = self.client.post('/api/users/login/', login_data, format='json')
self.assertEqual(response.data["email"], 'testuser@gmail.com')
self.assertEqual(response.data["username"], 'user')
self.assertEqual(response.status_code, status.HTTP_200_OK)

def test_user_logged_in__with_invalid_data(self):
"""
Method to test if user logs in using invalid credentials
"""
self.client.post('/api/users/', login_credentials_data, format='json')
response = self.client.post('/api/users/login/', invalid_login_data, format='json')
self.assertIn(response.data["errors"]["error"][0], 'A user with this email and password was not found.')
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

def test_user_log_in_credentials_miss_email(self):
"""
Method to test if email is not added in the login required credentials
"""
self.client.post('/api/users/', login_credentials_data, format='json')
response = self.client.post('/api/users/login/', login_data_miss_email, format='json')
self.assertIn(response.data["errors"]["email"][0], 'This field is required.')
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

def test_user_log_in_credentials_miss_password(self):
"""
Method to test if password is not added in the login required credentials
"""
self.client.post('/api/users/', login_credentials_data, format='json')
response = self.client.post('/api/users/login/', login_data_miss_password, format='json')
self.assertIn(response.data["errors"]["password"][0], 'This field is required.')
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

def test_user_log_in_credentials_miss_password_and_email(self):
"""
Method to test if password is not added in the login required credentials
"""
self.client.post('/api/users/', login_credentials_data, format='json')
response = self.client.post('/api/users/login/', empty_login_data_object, format='json')
self.assertIn(response.data["errors"]["password"][0], 'This field is required.')
self.assertIn(response.data["errors"]["email"][0], 'This field is required.')
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)









2 changes: 1 addition & 1 deletion authors/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '7pgozr2jn7zs_o%i8id6=rddie!*0f0qy3$oy$(8231i^4*@u3'
SECRET_KEY = config('SECRET_KEY', '')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
Expand Down
Loading

0 comments on commit c7accd4

Please sign in to comment.