from django.views.decorators.cache import cache_control from django.contrib.auth import logout as logout_user import elasticsearch from django.core.mail import send_mail from smtplib import SMTPException from django.conf import settings import json from django.http import HttpResponse from django.core.exceptions import PermissionDenied from django.template.loader import render_to_string import smfhcp.utils.utils as utils import smfhcp.constants as constants from smfhcp.dao.elasticsearch_dao import ElasticsearchDao from smfhcp.esmapper.esmapper import ElasticsearchMapper smfhcp_utils = utils.SmfhcpUtils() es_dao = ElasticsearchDao() es_mapper = ElasticsearchMapper() @cache_control(no_cache=True, must_revalidate=True, no_store=True) def login_view(request): if 'is_authenticated' in request.session and request.session['is_authenticated']: return redirect('/') else: return render(request, constants.LOGIN_HTML_PATH) @cache_control(no_cache=True, must_revalidate=True, no_store=True) def index(request): request.session['user_name'] = request.user.username
class ElasticsearchDao: es = elasticsearch.Elasticsearch(hosts=[settings.ELASTICSEARCH_HOST]) smfhcp_utils = utils.SmfhcpUtils() es_mapper = ElasticsearchMapper() def get_general_user_by_user_name(self, user_name): return self.es.get(index=constants.GENERAL_USER_INDEX, id=user_name) def get_doctor_by_user_name(self, user_name): return self.es.get(index=constants.DOCTOR_INDEX, id=user_name) def search_posts_by_doctor_name(self, doctor_name): query_body = {"query": {"match": {"user_name": doctor_name}}} return self.es.search(index=[constants.POST_INDEX], body=query_body) def get_all_posts(self): query_body = {"query": {"match_all": {}}} return self.es.search(index=[constants.POST_INDEX], body=query_body) def search_users_by_email(self, email_id): query_body = {"query": {"match": {"email": email_id}}} return self.es.search( index=[constants.GENERAL_USER_INDEX, constants.DOCTOR_INDEX], body=query_body) def get_doctor_activation_by_email_id(self, email_id): return self.es.get(index=constants.DOCTOR_ACTIVATION_INDEX, id=email_id) def index_doctor_activation(self, email_id, token): body = self.es_mapper.map_doctor_activation(email_id, token) self.es.index(index=constants.DOCTOR_ACTIVATION_INDEX, id=email_id, body=body) def index_doctor(self, data, profile_picture): body = self.es_mapper.map_doctor(data, profile_picture) self.es.index(index=constants.DOCTOR_INDEX, id=body['user_name'], body=body) def index_general_user(self, body): self.es.index(index=constants.GENERAL_USER_INDEX, id=body['user_name'], body=body) def get_forgot_password_token_by_user_name(self, user_name): return self.es.get(index=constants.FORGOT_PASSWORD_TOKEN_INDEX, id=user_name) def add_token_to_forgot_password_token_list(self, user_name, token): body = { "script": { "source": "ctx._source.token.add(params.new_token)", "lang": "painless", "params": { "new_token": token } } } self.es.update(index=constants.FORGOT_PASSWORD_TOKEN_INDEX, id=user_name, body=body) def index_forgot_password_token(self, user_name, token): body = self.es_mapper.map_forgot_password_token(user_name, token) self.es.index(index=constants.FORGOT_PASSWORD_TOKEN_INDEX, id=user_name, body=body) def delete_forgot_password_token(self, user_name): self.es.delete(index=constants.FORGOT_PASSWORD_TOKEN_INDEX, id=user_name) def update_password_by_user_name(self, user_name, new_password, is_doctor): body = { "script": { "source": "ctx._source.password_hash = params.new_password;", "lang": "painless", "params": { "new_password": self.smfhcp_utils.find_hash(new_password) } } } if is_doctor: self.es.update(index=constants.DOCTOR_INDEX, id=user_name, body=body) else: self.es.update(index=constants.GENERAL_USER_INDEX, id=user_name, body=body) def index_post(self, user_name, user_info, data, post_type_case_study): body = self.es_mapper.map_post(user_name, user_info, data, post_type_case_study) return self.es.index(index=constants.POST_INDEX, body=body) def get_post_by_id(self, post_id): return self.es.get(index=constants.POST_INDEX, id=post_id) def update_post_count(self, user_name): body = { "script": { "source": "ctx._source.post_count += params.count", "lang": "painless", "params": { "count": 1 } } } self.es.update(index=constants.DOCTOR_INDEX, id=user_name, body=body) def update_post_view_count(self, post_id): body = { "script": { "source": "ctx._source.view_count += params.count", "lang": "painless", "params": { "count": 1 } } } self.es.update(index=constants.POST_INDEX, id=post_id, body=body) def add_comment_by_post_id(self, post_id, comment): body = { "script": { "source": "ctx._source.comments.add(params.new_comment)", "lang": "painless", "params": { "new_comment": comment } } } self.es.update(index=constants.POST_INDEX, id=post_id, body=body) def add_reply_by_post_id_and_comment_id(self, post_id, comment_id, reply): body = { "script": { "source": "for(int i=0; i < ctx._source.comments.size(); i++){ if(ctx._source.comments[i].comment_id " "== params.comment_id){ ctx._source.comments[i].replies.add(params.reply); } }", "lang": "painless", "params": { "comment_id": comment_id, "reply": reply } } } self.es.update(index=constants.POST_INDEX, id=post_id, body=body) def update_profile(self, user_name, data): inline_string = "" params = {} if data.get('password') is not None: inline_string += "ctx._source.password_hash = params.password_hash; " params['password_hash'] = str( self.smfhcp_utils.find_hash(data.get('password'))) if len(json.loads(data.get('qualification'))['qualifications']) > 0: inline_string += "ctx._source.qualification.addAll(params.qualification); " params['qualification'] = [ s.strip() for s in json.loads(data.get('qualification')) ['qualifications'] ] if str(data.get('profession')) != '': inline_string += "ctx._source.profession = params.profession; " params['profession'] = str(data.get('profession')) if str(data.get('institution')) != '': inline_string += "ctx._source.institution = params.institution; " params['institution'] = str(data.get('institution')) if len(json.loads( data.get('researchInterests'))['researchInterests']) > 0: inline_string += "ctx._source.research_interests.addAll(params.research_interests); " params['research_interests'] = [ s.strip() for s in json.loads(data.get('researchInterests')) ['researchInterests'] ] if len(json.loads( data.get('clinicalInterests'))['clinicalInterests']) > 0: inline_string += "ctx._source.clinical_interests.addAll(params.clinical_interests); " params['clinical_interests'] = [ s.strip() for s in json.loads(data.get('clinicalInterests')) ['clinicalInterests'] ] body = { "script": { "inline": inline_string, "lang": "painless", "params": params } } self.es.update(index=constants.DOCTOR_INDEX, id=user_name, body=body) def update_follow_count(self, data): body = {"script": {"lang": "painless", "params": {"count": 1}}} if data.get('follow') == "true": body['script'][ 'source'] = "ctx._source.follower_count += params.count" else: body['script'][ 'source'] = "if(ctx._source.follower_count > 0) {ctx._source.follower_count -= params.count}" self.es.update(index=constants.DOCTOR_INDEX, id=data.get('doctor_name'), body=body) def add_to_follow_list(self, user_name, doctor_user_name, is_doctor): body = { "script": { "inline": "ctx._source.follow_list.add(params.doctor_user_name);", "lang": "painless", "params": { "doctor_user_name": doctor_user_name } } } if is_doctor: self.es.update(index=constants.DOCTOR_INDEX, id=user_name, body=body) else: self.es.update(index=constants.GENERAL_USER_INDEX, id=user_name, body=body) def remove_from_follow_list(self, user_name, doctor_user_name, is_doctor): body = { "script": { "source": "ctx._source.follow_list.remove(ctx._source.follow_list.indexOf(params.doctor_user_name))", "lang": "painless", "params": { "doctor_user_name": doctor_user_name } } } if is_doctor: self.es.update(index=constants.DOCTOR_INDEX, id=user_name, body=body) else: self.es.update(index=constants.GENERAL_USER_INDEX, id=user_name, body=body) def search_for_doctors(self, query): query_body = { "query": { "multi_match": { "query": query, "fields": [ "user_name^2", "full_name^2", "institution", "profession" ], "fuzziness": "AUTO", "type": "best_fields" } } } return self.es.search(index=constants.DOCTOR_INDEX, body=query_body) def search_for_posts(self, query): with open(constants.SEARCH_QUERY_JSON) as file: query_body = json.load(file) for i, _ in enumerate(query_body["query"]["bool"]["should"]): query_body["query"]["bool"]["should"][i]["multi_match"][ "query"] = query return self.es.search(index=constants.POST_INDEX, body=query_body) def search_for_tags(self, tag): # Query is NOT fuzzy because we want to find posts tagged with exactly same tag query = {"query": {"term": {"tags.keyword": {"value": tag}}}} return self.es.search(index=constants.POST_INDEX, body=query)
class TestProfile(TestCase): smfhcp_utils = utils.SmfhcpUtils() es_dao = DummyObject() # es_mapper = DummyObject() dummy_function = MagicMock() def setUp(self): self.factory = RequestFactory() for k in list(self.es_dao.__dict__): self.es_dao.__delattr__(k) for k in list(self.smfhcp_utils.__dict__): self.smfhcp_utils.__delattr__(k) def permission_denied_test(self, url, function): request1 = self.factory.get(url) request2 = self.factory.put(url) request3 = self.factory.delete(url) request4 = self.factory.head(url) with self.assertRaises(PermissionDenied): _ = function(request1) _ = function(request2) _ = function(request3) _ = function(request4) def test_view_profile_when_user_not_authenticated(self): request = self.factory.get('/view_profile') request.session = dict() request.session['is_authenticated'] = False response = profile.view_profile(request, 'test_user_name') self.assertEqual(response.status_code, 302) self.assertEqual(response.url, '/') @patch('smfhcp.views.profile.es_dao', es_dao) @patch('smfhcp.views.profile.smfhcp_utils', smfhcp_utils) def test_view_profile_when_user_authenticated(self): self.es_dao.get_doctor_by_user_name = MagicMock(return_value=({ '_source': { 'user_name': 'test_user_name', 'full_name': 'test_full_name', 'email': 'test_email', 'qualification': 'test_qualification', 'research_interests': ['test_research_interests'], 'profession': 'test_profession', 'institution': 'test_institution', 'clinical_interests': ['test_clinical_interests'], 'follow_list': ['test_doctor_name'], 'post_count': 0, 'follower_count': 0, 'profile_picture': 'test_profile_picture.jpg' } })) self.es_dao.search_posts_by_doctor_name = MagicMock(return_value=({ 'hits': { 'hits': [{ '_source': { 'user_name': 'test_user_name', 'date': 'test_date_utc_string' } }], 'total': { 'value': 0 } } })) self.smfhcp_utils.create_time_from_utc_string = MagicMock( return_value=TEST_TIME) self.smfhcp_utils.pretty_date = MagicMock(return_value='pretty_date') self.smfhcp_utils.find_if_follows = MagicMock(return_value='true') request = self.factory.get('/view_profile') request.session = dict() request.session['is_authenticated'] = True response = profile.view_profile(request, 'test_user_name') self.assertEqual(response.status_code, 200) self.es_dao.get_doctor_by_user_name.assert_called_with( 'test_user_name') self.es_dao.search_posts_by_doctor_name.assert_called_with( 'test_user_name') self.smfhcp_utils.create_time_from_utc_string.assert_called_with( TEST_DATE) self.smfhcp_utils.pretty_date.assert_called_with(TEST_TIME) @patch('smfhcp.views.profile.es_dao', es_dao) @patch('smfhcp.views.profile.smfhcp_utils', smfhcp_utils) def test_view_profile_when_user_authenticated_profile_picture_absent(self): self.es_dao.get_doctor_by_user_name = MagicMock(return_value=({ '_source': { 'user_name': 'test_user_name', 'full_name': 'test_full_name', 'email': 'test_email', 'qualification': 'test_qualification', 'research_interests': ['test_research_interests'], 'profession': 'test_profession', 'institution': 'test_institution', 'clinical_interests': ['test_clinical_interests'], 'follow_list': ['test_doctor_name'], 'post_count': 0, 'follower_count': 0 } })) self.es_dao.search_posts_by_doctor_name = MagicMock(return_value=({ 'hits': { 'hits': [{ '_source': { 'user_name': 'test_user_name', 'date': 'test_date_utc_string' } }], 'total': { 'value': 1 } } })) self.smfhcp_utils.create_time_from_utc_string = MagicMock( return_value=TEST_TIME) self.smfhcp_utils.pretty_date = MagicMock(return_value='pretty_date') self.smfhcp_utils.find_if_follows = MagicMock(return_value='true') request = self.factory.get('/view_profile') request.session = dict() request.session['is_authenticated'] = True response = profile.view_profile(request, 'test_user_name') self.assertEqual(response.status_code, 200) self.es_dao.get_doctor_by_user_name.assert_called_with( 'test_user_name') self.es_dao.search_posts_by_doctor_name.assert_called_with( 'test_user_name') self.smfhcp_utils.create_time_from_utc_string.assert_called_with( TEST_DATE) self.smfhcp_utils.pretty_date.assert_called_with(TEST_TIME) def test_update_profile_when_request_not_post(self): self.permission_denied_test('/update_profile', profile.update_profile) @patch('smfhcp.views.profile.es_dao', es_dao) def test_update_profile_when_request_post(self): self.es_dao.update_profile = MagicMock() post_data = {'user_name': TEST_USER_NAME} request = self.factory.post('/update_profile', post_data) request.session = dict() request.session['user_name'] = 'test_user_name' response = profile.update_profile(request) query_dict = QueryDict('', mutable=True) query_dict.update(post_data) self.es_dao.update_profile.assert_called_with('test_user_name', query_dict) self.assertEqual( json.loads(response.content.decode(constants.UTF_8))['redirect'], True) self.assertEqual( json.loads(response.content.decode( constants.UTF_8))['redirect_url'], '/view_profile/test_user_name') def test_follow_or_unfollow_when_request_not_post(self): self.permission_denied_test('/follow_or_unfollow', profile.follow_or_unfollow) @patch('smfhcp.views.profile.es_dao', es_dao) def test_follow_or_unfollow_when_request_post_follow(self): self.es_dao.add_to_follow_list = MagicMock() post_data = {'follow': 'true', 'doctor_name': 'test_doctor_name'} request = self.factory.post('/follow_or_unfollow', post_data) request.session = dict() request.session['user_name'] = 'test_user_name' request.session['is_doctor'] = 'true' self.es_dao.update_follow_count = MagicMock() _ = profile.follow_or_unfollow(request) self.es_dao.add_to_follow_list.assert_called_with( 'test_user_name', 'test_doctor_name', 'true') query_dict = QueryDict('', mutable=True) query_dict.update(post_data) self.es_dao.update_follow_count.assert_called_with(query_dict) @patch('smfhcp.views.profile.es_dao', es_dao) def test_follow_or_unfollow_when_request_post_unfollow(self): self.es_dao.remove_from_follow_list = MagicMock() post_data = {'follow': 'false', 'doctor_name': 'test_doctor_name'} request = self.factory.post('/follow_or_unfollow', post_data) request.session = dict() request.session['user_name'] = 'test_user_name' request.session['is_doctor'] = 'true' self.es_dao.update_follow_count = MagicMock() _ = profile.follow_or_unfollow(request) self.es_dao.remove_from_follow_list.assert_called_with( 'test_user_name', 'test_doctor_name', 'true') query_dict = QueryDict('', mutable=True) query_dict.update(post_data) self.es_dao.update_follow_count.assert_called_with(query_dict) def test_get_follow_list_when_request_not_ajax(self): self.permission_denied_test('/get_follow_list', profile.get_follow_list) def test_get_follow_list_when_request_ajax_user_not_authenticated(self): with self.assertRaises(PermissionDenied): request = self.factory.get('/get_follow_list', HTTP_X_REQUESTED_WITH='XMLHttpRequest') request.session = dict() request.session['is_authenticated'] = False _ = profile.get_follow_list(request) @patch('smfhcp.views.profile.es_dao', es_dao) def test_get_follow_list_when_request_ajax_user_authenticated(self): self.es_dao.get_doctor_by_user_name = MagicMock(return_value=({ '_source': { 'follow_list': ['test_doctor_name'] } })) request = self.factory.get('/get_follow_list', HTTP_X_REQUESTED_WITH='XMLHttpRequest') request.session = dict() request.session['is_authenticated'] = True request.session['user_name'] = 'test_user_name' response = profile.get_follow_list(request) self.es_dao.get_doctor_by_user_name.assert_called_with( 'test_user_name') me = {'id': 'test_user_name', 'name': 'test_user_name'} talk_body = {'id': 'test_doctor_name', 'name': 'test_doctor_name'} follow_list = [] follow_list.append(talk_body) self.assertEqual( json.loads(response.content.decode(constants.UTF_8))['me'], me) self.assertEqual( json.loads(response.content.decode( constants.UTF_8))['follow_list'], follow_list)
class TestAuth(TestCase): smfhcp_utils = utils.SmfhcpUtils() es_dao = DummyObject() es_mapper = DummyObject() dummy_smfhcp_utils = DummyObject() dummy_function = MagicMock() index_general_user_return_false = MagicMock(return_value=False) index_general_user_return_true = MagicMock(return_value=True) send_mail_raises_error = MagicMock(side_effect=SMTPException()) send_mail_runs_correctly = MagicMock() check_email_existence_returns_true = MagicMock(return_value=(True, constants.SENT_INVITE)) check_email_existence_returns_false = MagicMock(return_value=(False, constants.USER_ALREADY_INVITED)) send_invitation_email_returns_false = MagicMock(return_value=False) send_invitation_email_returns_true = MagicMock(return_value=True) save_profile_picture_runs_ok = MagicMock(return_value='test_path') def setUp(self): self.factory = RequestFactory() for k in list(self.es_dao.__dict__): self.es_dao.__delattr__(k) for k in list(self.es_mapper.__dict__): self.es_mapper.__delattr__(k) for k in list(self.dummy_smfhcp_utils.__dict__): self.dummy_smfhcp_utils.__delattr__(k) def permission_denied_test(self, url, function): request1 = self.factory.get(url) request2 = self.factory.put(url) request3 = self.factory.delete(url) request4 = self.factory.head(url) with self.assertRaises(PermissionDenied): _ = function(request1) _ = function(request2) _ = function(request3) _ = function(request4) def login_user_valid_test(self, is_doctor): self.dummy_smfhcp_utils.find_user = MagicMock(return_value=({ 'user_name': TEST_USER_NAME, 'password_hash': TEST_PASSWORD_HASH, 'email': TEST_EMAIL }, is_doctor)) self.dummy_smfhcp_utils.find_hash = MagicMock(return_value=TEST_PASSWORD_HASH) post_data = { 'user_name': TEST_USER_NAME, 'password': TEST_PASSWORD } request = self.factory.post('/login/signup_email', post_data) request.session = dict() response = auth.login_user(request) self.assertEqual(request.session['user_name'], TEST_USER_NAME) self.assertEqual(request.session['email'], TEST_EMAIL) self.assertEqual(request.session['is_authenticated'], True) self.assertEqual(request.session['is_doctor'], is_doctor) self.assertEqual(json.loads(response.content.decode(constants.UTF_8))['redirect'], True) self.assertEqual(json.loads(response.content.decode(constants.UTF_8))['redirect_url'], '/') self.dummy_smfhcp_utils.find_user.assert_called_with(TEST_USER_NAME, self.es_dao) self.dummy_smfhcp_utils.find_hash.assert_called_with(TEST_PASSWORD) def test_login_view_when_user_authenticated(self): request = self.factory.get('/login') request.session = dict() request.session['is_authenticated'] = True response = auth.login_view(request) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, '/') def test_login_view_when_user_not_authenticated(self): request = self.factory.get('/login') request.session = dict() request.session['is_authenticated'] = False response = auth.login_view(request) self.assertEqual(response.status_code, 200) self.assertGreater(len(response.content.decode(constants.UTF_8)), 0) request.session = dict() response = auth.login_view(request) self.assertEqual(response.status_code, 200) self.assertGreater(len(response.content.decode(constants.UTF_8)), 0) @patch('smfhcp.views.auth.es_dao', es_dao) @patch('smfhcp.views.auth.es_mapper', es_mapper) @patch('smfhcp.views.auth.index_general_user', dummy_function) def test_index_when_user_not_present(self): self.es_dao.get_general_user_by_user_name = MagicMock(side_effect=elasticsearch.NotFoundError()) self.es_mapper.map_general_user = MagicMock(return_value={"test": "body"}) request = self.factory.get('/login_info') request.session = dict() request.user = DummyObject() request.user.username = TEST_USER_NAME request.user.email = TEST_EMAIL response = auth.index(request) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, '/') self.es_dao.get_general_user_by_user_name.assert_called_with(TEST_USER_NAME) self.es_mapper.map_general_user.assert_called_with(TEST_USER_NAME, TEST_EMAIL) self.dummy_function.assert_called_with({"test": "body"}) @patch('smfhcp.views.auth.es_dao', es_dao) def test_index_when_user_present(self): self.es_dao.get_general_user_by_user_name = MagicMock(return_value=True) request = self.factory.get('/login_info') request.session = dict() request.user = DummyObject() request.user.username = TEST_USER_NAME request.user.email = TEST_EMAIL response = auth.index(request) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, '/') self.es_dao.get_general_user_by_user_name.assert_called_with(TEST_USER_NAME) @patch('smfhcp.views.auth.es_dao', es_dao) def test_index_general_user_when_third_party_user(self): body = { "test": "data", } self.es_dao.index_general_user = MagicMock() self.es_dao.search_users_by_email = MagicMock() _ = auth.index_general_user(body) self.es_dao.index_general_user.assert_called_with(body) self.es_dao.search_users_by_email.assert_not_called() @patch('smfhcp.views.auth.es_dao', es_dao) def test_index_general_user_when_custom_user_and_user_exists(self): body = { "user_name": TEST_USER_NAME, "email": TEST_EMAIL, "password_hash": "test_password_hash" } self.es_dao.search_users_by_email = MagicMock(return_value={ "hits": { "total": { "value": 1 } } }) response = auth.index_general_user(body) self.assertFalse(response) self.es_dao.search_users_by_email.assert_called_with(TEST_EMAIL) self.es_dao.search_users_by_email = MagicMock(return_value={ "hits": { "total": { "value": 0 } } }) self.es_dao.get_general_user_by_user_name = MagicMock() response = auth.index_general_user(body) self.assertFalse(response) self.es_dao.search_users_by_email.assert_called_with(TEST_EMAIL) self.es_dao.get_general_user_by_user_name.assert_called_with(TEST_USER_NAME) self.es_dao.search_users_by_email = MagicMock(return_value={ "hits": { "total": { "value": 0 } } }) self.es_dao.get_general_user_by_user_name = MagicMock(side_effect=elasticsearch.NotFoundError()) self.es_dao.get_doctor_by_user_name = MagicMock() response = auth.index_general_user(body) self.assertFalse(response) self.es_dao.search_users_by_email.assert_called_with(TEST_EMAIL) self.es_dao.get_general_user_by_user_name.assert_called_with(TEST_USER_NAME) self.es_dao.get_doctor_by_user_name.assert_called_with(TEST_USER_NAME) @patch('smfhcp.views.auth.es_dao', es_dao) def test_index_general_user_when_custom_user_and_user_does_not_exist(self): body = { "user_name": TEST_USER_NAME, "email": TEST_EMAIL, "password_hash": "test_password_hash" } self.es_dao.search_users_by_email = MagicMock(return_value={ "hits": { "total": { "value": 0 } } }) self.es_dao.get_general_user_by_user_name = MagicMock(side_effect=elasticsearch.NotFoundError()) self.es_dao.get_doctor_by_user_name = MagicMock(side_effect=elasticsearch.NotFoundError()) self.es_dao.index_general_user = MagicMock() response = auth.index_general_user(body) self.assertTrue(response) self.es_dao.search_users_by_email.assert_called_with(TEST_EMAIL) self.es_dao.get_general_user_by_user_name.assert_called_with(TEST_USER_NAME) self.es_dao.get_doctor_by_user_name.assert_called_with(TEST_USER_NAME) self.es_dao.index_general_user.assert_called_with(body) def test_signup_email_when_request_not_post(self): self.permission_denied_test('/login/signup_email', auth.signup_email) @patch('smfhcp.views.auth.es_mapper', es_mapper) @patch('smfhcp.views.auth.index_general_user', index_general_user_return_false) def test_signup_email_when_user_already_exists(self): self.es_mapper.map_general_user = MagicMock(return_value={"test": "data"}) post_data = { 'user_name': TEST_USER_NAME, 'password': TEST_PASSWORD, 'email': TEST_EMAIL } request = self.factory.post('/login/signup_email', post_data) response = auth.signup_email(request) self.assertEqual(json.loads(response.content.decode(constants.UTF_8))['message'], constants.USER_OR_EMAIL_ALREADY_EXISTS_MESSAGE) self.index_general_user_return_false.assert_called_with({"test": "data"}) self.es_mapper.map_general_user.assert_called_with(TEST_USER_NAME, TEST_EMAIL, password=TEST_PASSWORD) @patch('smfhcp.views.auth.es_mapper', es_mapper) @patch('smfhcp.views.auth.index_general_user', index_general_user_return_true) def test_signup_email_when_user_does_not_exist(self): self.es_mapper.map_general_user = MagicMock(return_value={"test": "data"}) post_data = { 'user_name': TEST_USER_NAME, 'password': TEST_PASSWORD, 'email': TEST_EMAIL } request = self.factory.post('/login/signup_email', post_data) request.session = dict() response = auth.signup_email(request) self.assertEqual(request.session['user_name'], TEST_USER_NAME) self.assertEqual(request.session['email'], TEST_EMAIL) self.assertEqual(request.session['is_authenticated'], True) self.assertEqual(request.session['is_doctor'], False) self.assertEqual(json.loads(response.content.decode(constants.UTF_8))['redirect'], True) self.assertEqual(json.loads(response.content.decode(constants.UTF_8))['redirect_url'], '/') self.index_general_user_return_true.assert_called_with({"test": "data"}) self.es_mapper.map_general_user.assert_called_with(TEST_USER_NAME, TEST_EMAIL, password=TEST_PASSWORD) def test_login_user_when_request_not_post(self): self.permission_denied_test('/login/login_user', auth.login_user) @patch('smfhcp.views.auth.smfhcp_utils', dummy_smfhcp_utils) @patch('smfhcp.views.auth.es_dao', es_dao) def test_login_user_when_user_not_valid(self): self.dummy_smfhcp_utils.find_user = MagicMock(return_value=(None, False)) post_data = { 'user_name': TEST_USER_NAME, 'password': TEST_PASSWORD } request = self.factory.post('/login/signup_email', post_data) request.session = dict() response = auth.login_user(request) self.assertEqual(json.loads(response.content.decode(constants.UTF_8))['message'], constants.USERNAME_AND_PASSWORD_DO_NOT_MATCH) self.dummy_smfhcp_utils.find_user.assert_called_with(TEST_USER_NAME, self.es_dao) @patch('smfhcp.views.auth.smfhcp_utils', dummy_smfhcp_utils) @patch('smfhcp.views.auth.es_dao', es_dao) def test_login_user_when_user_valid_and_is_doctor(self): self.login_user_valid_test(True) @patch('smfhcp.views.auth.smfhcp_utils', dummy_smfhcp_utils) @patch('smfhcp.views.auth.es_dao', es_dao) def test_login_user_when_user_valid_and_is_general_user(self): self.login_user_valid_test(False) @patch('smfhcp.views.auth.es_dao', es_dao) def test_check_email_existence_when_email_already_exists(self): self.es_dao.search_users_by_email = MagicMock(return_value={ "hits": { "total": { "value": 1 } } }) response = auth.check_email_existence(TEST_EMAIL) self.assertFalse(response[0]) self.assertEqual(response[1], constants.USER_ALREADY_EXISTS) self.es_dao.search_users_by_email.assert_called_with(TEST_EMAIL) @patch('smfhcp.views.auth.es_dao', es_dao) def test_check_email_existence_when_email_already_invited(self): self.es_dao.search_users_by_email = MagicMock(return_value={ "hits": { "total": { "value": 0 } } }) self.es_dao.get_doctor_activation_by_email_id = MagicMock(return_value=True) response = auth.check_email_existence(TEST_EMAIL) self.assertFalse(response[0]) self.assertEqual(response[1], constants.USER_ALREADY_INVITED) self.es_dao.search_users_by_email.assert_called_with(TEST_EMAIL) self.es_dao.get_doctor_activation_by_email_id.assert_called_with(TEST_EMAIL) @patch('smfhcp.views.auth.es_dao', es_dao) def test_check_email_existence_when_email_valid_for_invite(self): self.es_dao.search_users_by_email = MagicMock(return_value={ "hits": { "total": { "value": 0 } } }) self.es_dao.get_doctor_activation_by_email_id = MagicMock(side_effect=elasticsearch.NotFoundError()) response = auth.check_email_existence(TEST_EMAIL) self.assertTrue(response[0]) self.assertEqual(response[1], constants.SENT_INVITE) self.es_dao.search_users_by_email.assert_called_with(TEST_EMAIL) self.es_dao.get_doctor_activation_by_email_id.assert_called_with(TEST_EMAIL) @patch('smfhcp.views.auth.send_mail', send_mail_raises_error) def test_send_invitation_email_when_error_in_sending_mail(self): test_email = TEST_EMAIL test_token = 123 response = auth.send_invitation_email(test_email, test_token) self.send_mail_raises_error.assert_called_with(constants.INVITE_EMAIL_SUBJECT, from_email=settings.EMAIL_HOST_USER, recipient_list=[test_email], html_message=ANY, fail_silently=False, message='') self.assertFalse(response) @patch('smfhcp.views.auth.send_mail', send_mail_runs_correctly) def test_send_invitation_email_when_sent_mail(self): test_email = TEST_EMAIL test_token = 123 response = auth.send_invitation_email(test_email, test_token) self.send_mail_runs_correctly.assert_called_with(constants.INVITE_EMAIL_SUBJECT, from_email=settings.EMAIL_HOST_USER, recipient_list=[test_email], html_message=ANY, fail_silently=False, message='') self.assertTrue(response) @patch('smfhcp.views.auth.check_email_existence', check_email_existence_returns_false) def test_send_invite_when_email_invalid(self): post_data = { 'email': TEST_EMAIL } request = self.factory.post('/send_invite', post_data) response = auth.send_invite(request) self.assertEqual(json.loads(response.content.decode(constants.UTF_8))['message'], constants.USER_ALREADY_INVITED) self.assertEqual(json.loads(response.content.decode(constants.UTF_8))['success'], False) self.check_email_existence_returns_false.assert_called_with(TEST_EMAIL) @patch('smfhcp.views.auth.send_invitation_email', send_invitation_email_returns_false) @patch('smfhcp.views.auth.check_email_existence', check_email_existence_returns_true) def test_send_invite_when_mail_not_sent(self): post_data = { 'email': TEST_EMAIL } request = self.factory.post('/send_invite', post_data) response = auth.send_invite(request) self.assertEqual(json.loads(response.content.decode(constants.UTF_8))['message'], constants.COULD_NOT_SEND_EMAIL) self.assertEqual(json.loads(response.content.decode(constants.UTF_8))['success'], False) self.send_invitation_email_returns_false.assert_called_with(TEST_EMAIL, ANY) self.check_email_existence_returns_true.assert_called_with(TEST_EMAIL) @patch('smfhcp.views.auth.send_invitation_email', send_invitation_email_returns_true) @patch('smfhcp.views.auth.check_email_existence', check_email_existence_returns_true) def test_send_invite_when_mail_sent(self): post_data = { 'email': TEST_EMAIL } request = self.factory.post('/send_invite', post_data) response = auth.send_invite(request) self.assertEqual(json.loads(response.content.decode(constants.UTF_8))['message'], constants.INVITATION_SENT_SUCCESSFULLY) self.assertEqual(json.loads(response.content.decode(constants.UTF_8))['success'], True) self.send_invitation_email_returns_true.assert_called_with(TEST_EMAIL, ANY) self.check_email_existence_returns_true.assert_called_with(TEST_EMAIL) def test_doctor_signup_when_user_already_logged_in(self): request = self.factory.get('/doctor_signup/123') request.session = dict() request.session['is_authenticated'] = True response = auth.doctor_signup(request, 123) self.assertFalse(response.content.decode(constants.UTF_8).__contains__('value="123"')) def test_doctor_signup_when_user_not_logged_in(self): request = self.factory.get('/doctor_signup/123') request.session = dict() response = auth.doctor_signup(request, 123) self.assertTrue(response.content.decode(constants.UTF_8).__contains__('value="123"')) @patch('smfhcp.views.auth.es_dao', es_dao) def test_index_doctor(self): self.es_dao.index_doctor = MagicMock() post_data = { 'user_name': TEST_USER_NAME, 'email': TEST_EMAIL } request = self.factory.post('/create_profile', post_data) request.session = dict() auth.index_doctor(request, post_data, 'test_profile_picture') self.assertEqual(request.session['user_name'], TEST_USER_NAME) self.assertEqual(request.session['email'], TEST_EMAIL) self.assertEqual(request.session['is_authenticated'], True) self.assertEqual(request.session['is_doctor'], True) self.es_dao.index_doctor.assert_called_with(post_data, 'test_profile_picture') @patch('smfhcp.views.auth.logout_user', dummy_function) def test_logout(self): request = self.factory.get('/logout') request.session = dict() response = auth.logout(request) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, '/') self.assertEqual(request.session['user_name'], None) self.assertEqual(request.session['email'], None) self.assertEqual(request.session['is_authenticated'], False) self.assertEqual(request.session['is_doctor'], None) self.dummy_function.assert_called_with(request) def test_create_profile_when_request_not_post(self): self.permission_denied_test('/create_profile', auth.create_profile) @patch('smfhcp.views.auth.smfhcp_utils', dummy_smfhcp_utils) @patch('smfhcp.views.auth.es_dao', es_dao) def test_create_profile_when_user_already_exists(self): self.dummy_smfhcp_utils.find_user = MagicMock(return_value=('not_none', False)) post_data = { 'user_name': TEST_USER_NAME } request = self.factory.post('/create_profile', post_data) response = auth.create_profile(request) self.dummy_smfhcp_utils.find_user.assert_called_with(TEST_USER_NAME, self.es_dao) self.assertEqual(json.loads(response.content.decode(constants.UTF_8))['message'], constants.USERNAME_ALREADY_EXISTS) @patch('smfhcp.views.auth.smfhcp_utils', dummy_smfhcp_utils) @patch('smfhcp.views.auth.es_dao', es_dao) def test_create_profile_when_user_not_invited(self): self.dummy_smfhcp_utils.find_user = MagicMock(return_value=(None, False)) self.es_dao.get_doctor_activation_by_email_id = MagicMock(side_effect=elasticsearch.NotFoundError()) post_data = { 'user_name': TEST_USER_NAME, 'email': TEST_EMAIL } request = self.factory.post('/create_profile', post_data) response = auth.create_profile(request) self.dummy_smfhcp_utils.find_user.assert_called_with(TEST_USER_NAME, self.es_dao) self.es_dao.get_doctor_activation_by_email_id.assert_called_with(TEST_EMAIL) self.assertEqual(json.loads(response.content.decode(constants.UTF_8))['message'], constants.EMAIL_DOES_NOT_HAVE_INVITE) @patch('smfhcp.views.auth.smfhcp_utils', dummy_smfhcp_utils) @patch('smfhcp.views.auth.es_dao', es_dao) def test_create_profile_when_otp_does_not_match(self): self.dummy_smfhcp_utils.find_user = MagicMock(return_value=(None, False)) self.es_dao.get_doctor_activation_by_email_id = MagicMock(return_value={ '_source': { 'token': '123' } }) post_data = { 'user_name': TEST_USER_NAME, 'email': TEST_EMAIL, 'otp': 1234 } request = self.factory.post('/create_profile', post_data) response = auth.create_profile(request) self.dummy_smfhcp_utils.find_user.assert_called_with(TEST_USER_NAME, self.es_dao) self.es_dao.get_doctor_activation_by_email_id.assert_called_with(TEST_EMAIL) self.assertEqual(json.loads(response.content.decode(constants.UTF_8))['message'], constants.OTP_EMAIL_PAIR_DOES_NOT_MATCH) @patch('smfhcp.views.auth.smfhcp_utils', dummy_smfhcp_utils) @patch('smfhcp.views.auth.es_dao', es_dao) @patch('smfhcp.views.auth.index_doctor', dummy_function) @patch('smfhcp.views.auth.save_profile_picture', save_profile_picture_runs_ok) def test_create_profile_when_profile_created(self): self.dummy_smfhcp_utils.find_user = MagicMock(return_value=(None, False)) self.es_dao.get_doctor_activation_by_email_id = MagicMock(return_value={ '_source': { 'token': '123' } }) post_data = { 'user_name': TEST_USER_NAME, 'email': TEST_EMAIL, 'otp': 123 } request = self.factory.post('/create_profile', post_data) response = auth.create_profile(request) self.dummy_smfhcp_utils.find_user.assert_called_with(TEST_USER_NAME, self.es_dao) self.es_dao.get_doctor_activation_by_email_id.assert_called_with(TEST_EMAIL) self.save_profile_picture_runs_ok.assert_called_with(request) self.dummy_function.assert_called_with(request, request.POST, 'test_path') self.assertEqual(json.loads(response.content.decode(constants.UTF_8))['redirect'], True) self.assertEqual(json.loads(response.content.decode(constants.UTF_8))['redirect_url'], '/')
class TestUtils(TestCase): smfhcp_utils = utils.SmfhcpUtils() es = DummyElasticSearchDao() def test_find_hash_when_valid_input(self): test_string = "test" returned_hash = self.smfhcp_utils.find_hash(test_string) import hashlib test_hash = hashlib.sha256(test_string.encode( constants.UTF_8)).hexdigest() self.assertEqual(returned_hash, test_hash, "Asserted and returned hash did not match.") def test_find_hash_when_None_input(self): with self.assertRaises(TypeError): self.smfhcp_utils.find_hash(None) def test_random_with_n_digits_when_n_greater_than_0(self): returned_value = self.smfhcp_utils.random_with_n_digits(5) self.assertIsInstance(returned_value, int) import math self.assertEquals(int(math.log10(returned_value)) + 1, 5) def test_random_with_n_digits_when_n_less_than_1(self): with self.assertRaises(ValueError): self.smfhcp_utils.random_with_n_digits(0) with self.assertRaises(ValueError): self.smfhcp_utils.random_with_n_digits(-1) def test_create_time_from_utc_string(self): utc_string = "2020-03-15T06:46:08.899691+00:00" returned_time = self.smfhcp_utils.create_time_from_utc_string( utc_string) self.assertEqual(str(returned_time.date()), "2020-03-15") self.assertEqual(returned_time.ctime().split(" ")[0], "Sun") self.assertEqual(str(returned_time.hour), "6") self.assertEqual(str(returned_time.minute), "46") self.assertEqual(str(returned_time.second), "8") def test_find_user_when_general_user(self): test_user_name = "test_user_name" self.es.get_general_user_by_user_name = MagicMock( return_value={'_source': { "test": "pass" }}) res, is_doctor = self.smfhcp_utils.find_user(test_user_name, self.es) self.es.get_general_user_by_user_name.assert_called_with( test_user_name) self.assertFalse(is_doctor) self.assertEqual(res['test'], 'pass') def test_find_user_when_doctor(self): test_user_name = "test_user_name" self.es.get_general_user_by_user_name = MagicMock( side_effect=elasticsearch.NotFoundError()) self.es.get_doctor_by_user_name = MagicMock( return_value={'_source': { "test": "pass" }}) res, is_doctor = self.smfhcp_utils.find_user(test_user_name, self.es) self.es.get_general_user_by_user_name.assert_called_with( test_user_name) self.es.get_doctor_by_user_name.assert_called_with(test_user_name) self.assertTrue(is_doctor) self.assertEqual(res['test'], 'pass') def test_find_user_when_neither_general_user_nor_doctor(self): test_user_name = "test_user_name" self.es.get_general_user_by_user_name = MagicMock( side_effect=elasticsearch.NotFoundError()) self.es.get_doctor_by_user_name = MagicMock( side_effect=elasticsearch.NotFoundError()) res, is_doctor = self.smfhcp_utils.find_user(test_user_name, self.es) self.es.get_general_user_by_user_name.assert_called_with( test_user_name) self.es.get_doctor_by_user_name.assert_called_with(test_user_name) self.assertIsNone(is_doctor) self.assertIsNone(res) def test_find_if_follows_when_general_user(self): request = Request() test_user_name = 'test_user_name' doctor_user_name = 'test_doctor_user_name' request.session = dict() request.session['user_name'] = test_user_name request.session['is_doctor'] = False self.es.get_general_user_by_user_name = MagicMock( return_value={'_source': { "follow_list": [doctor_user_name] }}) res = self.smfhcp_utils.find_if_follows(request, doctor_user_name, self.es) self.es.get_general_user_by_user_name.assert_called_with( test_user_name) self.assertTrue(res) self.es.get_general_user_by_user_name = MagicMock( return_value={'_source': { "follow_list": [] }}) res = self.smfhcp_utils.find_if_follows(request, doctor_user_name, self.es) self.es.get_general_user_by_user_name.assert_called_with( test_user_name) self.assertFalse(res) self.es.get_general_user_by_user_name = MagicMock( return_value={'_source': {}}) res = self.smfhcp_utils.find_if_follows(request, doctor_user_name, self.es) self.es.get_general_user_by_user_name.assert_called_with( test_user_name) self.assertFalse(res) def test_find_if_follows_when_doctor(self): request = Request() test_user_name = 'test_user_name' doctor_user_name = 'test_doctor_user_name' request.session = dict() request.session['user_name'] = test_user_name request.session['is_doctor'] = True self.es.get_doctor_by_user_name = MagicMock( return_value={'_source': { "follow_list": [doctor_user_name] }}) res = self.smfhcp_utils.find_if_follows(request, doctor_user_name, self.es) self.es.get_doctor_by_user_name.assert_called_with(test_user_name) self.assertTrue(res) self.es.get_doctor_by_user_name = MagicMock( return_value={'_source': { "follow_list": [] }}) res = self.smfhcp_utils.find_if_follows(request, doctor_user_name, self.es) self.es.get_doctor_by_user_name.assert_called_with(test_user_name) self.assertFalse(res) self.es.get_doctor_by_user_name = MagicMock( return_value={'_source': {}}) res = self.smfhcp_utils.find_if_follows(request, doctor_user_name, self.es) self.es.get_doctor_by_user_name.assert_called_with(test_user_name) self.assertFalse(res) def test_pretty_date(self): import datetime test_time = datetime.datetime.now( datetime.timezone.utc) + datetime.timedelta(minutes=10) diff = self.smfhcp_utils.pretty_date(test_time) self.assertEqual(diff, "") test_time = datetime.datetime.now( datetime.timezone.utc) - datetime.timedelta(seconds=9) diff = self.smfhcp_utils.pretty_date(test_time) self.assertEqual(diff, "just now") test_time = datetime.datetime.now( datetime.timezone.utc) - datetime.timedelta(seconds=20) diff = self.smfhcp_utils.pretty_date(test_time) self.assertEqual(diff.split(' ', 1)[1], "seconds ago") test_time = datetime.datetime.now( datetime.timezone.utc) - datetime.timedelta(seconds=80) diff = self.smfhcp_utils.pretty_date(test_time) self.assertEqual(diff, "a minute ago") test_time = datetime.datetime.now( datetime.timezone.utc) - datetime.timedelta(seconds=140) diff = self.smfhcp_utils.pretty_date(test_time) self.assertEqual(diff, "2 minutes ago") test_time = datetime.datetime.now( datetime.timezone.utc) - datetime.timedelta(hours=1, minutes=1) diff = self.smfhcp_utils.pretty_date(test_time) self.assertEqual(diff, "an hour ago") test_time = datetime.datetime.now( datetime.timezone.utc) - datetime.timedelta(hours=2, minutes=1) diff = self.smfhcp_utils.pretty_date(test_time) self.assertEqual(diff, "2 hours ago") test_time = datetime.datetime.now( datetime.timezone.utc) - datetime.timedelta(hours=24, minutes=1) diff = self.smfhcp_utils.pretty_date(test_time) self.assertEqual(diff, "Yesterday") test_time = datetime.datetime.now( datetime.timezone.utc) - datetime.timedelta(days=2, hours=2) diff = self.smfhcp_utils.pretty_date(test_time) self.assertEqual(diff, "2 days ago") test_time = datetime.datetime.now( datetime.timezone.utc) - datetime.timedelta(days=30, hours=2) diff = self.smfhcp_utils.pretty_date(test_time) self.assertEqual(diff, "1 months ago") test_time = datetime.datetime.now( datetime.timezone.utc) - datetime.timedelta(days=365, hours=2) diff = self.smfhcp_utils.pretty_date(test_time) self.assertEqual(diff, "1 years ago")
class TestPassword(TestCase): smfhcp_utils = utils.SmfhcpUtils() es_dao = DummyObject() dummy_smfhcp_utils = DummyObject() send_mail_raises_error = MagicMock(side_effect=SMTPException()) send_mail_runs_correctly = MagicMock() send_password_reset_email_success = MagicMock() get_random_string_test = MagicMock(return_value='123456') def setUp(self): self.factory = RequestFactory() for k in list(self.es_dao.__dict__): self.es_dao.__delattr__(k) for k in list(self.smfhcp_utils.__dict__): self.smfhcp_utils.__delattr__(k) def permission_denied_test(self, url, function): request1 = self.factory.get(url) request2 = self.factory.put(url) request3 = self.factory.delete(url) request4 = self.factory.head(url) with self.assertRaises(PermissionDenied): _ = function(request1) _ = function(request2) _ = function(request3) _ = function(request4) @patch('smfhcp.views.password.send_mail', send_mail_runs_correctly) def test_send_password_reset_email_success(self): res = {'user_name': TEST_USER_NAME, 'email': TEST_EMAIL} response = password.send_password_reset_email(res, TEST_OTP) self.send_mail_runs_correctly.assert_called_with( constants.PASSWORD_RESET_REQUEST_SUBJECT, from_email=settings.EMAIL_HOST_USER, recipient_list=[TEST_EMAIL], html_message=ANY, fail_silently=False, message='') self.assertTrue(response) @patch('smfhcp.views.password.send_mail', send_mail_raises_error) def test_send_password_reset_email_failure(self): res = {'user_name': TEST_USER_NAME, 'email': TEST_EMAIL} response = password.send_password_reset_email(res, TEST_OTP) self.send_mail_raises_error.assert_called_with( constants.PASSWORD_RESET_REQUEST_SUBJECT, from_email=settings.EMAIL_HOST_USER, recipient_list=[TEST_EMAIL], html_message=ANY, fail_silently=False, message='') self.assertFalse(response) def test_forgot_password_when_request_not_Post(self): self.permission_denied_test('/forgot_password', password.forgot_password) @patch('smfhcp.views.password.es_dao', es_dao) @patch('smfhcp.views.password.smfhcp_utils', dummy_smfhcp_utils) def test_forgot_password_when_request_is_Post_but_res_None(self): self.dummy_smfhcp_utils.find_user = MagicMock(return_value=(None, None)) post_data = {'user_name': TEST_USER_NAME} request = self.factory.post('/forgot_password', post_data) request.session = dict() response = password.forgot_password(request) self.assertEqual( json.loads(response.content.decode(constants.UTF_8))['message'], 'User does not exist') self.assertEqual( json.loads(response.content.decode(constants.UTF_8))['success'], False) self.dummy_smfhcp_utils.find_user.assert_called_with( TEST_USER_NAME, self.es_dao) @patch('smfhcp.views.password.es_dao', es_dao) @patch('smfhcp.views.password.smfhcp_utils', dummy_smfhcp_utils) def test_forgot_password_when_password_hash_not_present(self): self.dummy_smfhcp_utils.find_user = MagicMock(return_value=('not_none', False)) post_data = {'user_name': TEST_USER_NAME} request = self.factory.post('/forgot_password', post_data) request.session = dict() response = password.forgot_password(request) self.assertEqual( json.loads(response.content.decode(constants.UTF_8))['message'], 'User has signed up through a third-party service.') self.assertEqual( json.loads(response.content.decode(constants.UTF_8))['success'], False) self.dummy_smfhcp_utils.find_user.assert_called_with( TEST_USER_NAME, self.es_dao) @patch('smfhcp.views.password.es_dao', es_dao) @patch('smfhcp.views.password.smfhcp_utils', dummy_smfhcp_utils) @patch('smfhcp.views.password.send_password_reset_email', send_password_reset_email_success) def test_forgot_password_when_user_already_present(self): self.es_dao.get_forgot_password_token_by_user_name = MagicMock() self.es_dao.add_token_to_forgot_password_token_list = MagicMock() self.dummy_smfhcp_utils.find_user = MagicMock( return_value=({ 'user_name': TEST_USER_NAME, 'password_hash': TEST_PASSWORD_HASH, 'email': TEST_EMAIL }, False)) post_data = {'user_name': TEST_USER_NAME} request = self.factory.post('/forgot_password', post_data) request.session = dict() response = password.forgot_password(request) self.assertEqual( json.loads(response.content.decode(constants.UTF_8))['message'], 'A password reset conformation mail has been sent to {}'.format( TEST_EMAIL)) self.assertEqual( json.loads(response.content.decode(constants.UTF_8))['success'], True) self.es_dao.get_forgot_password_token_by_user_name.assert_called_with( TEST_USER_NAME) @patch('smfhcp.views.password.es_dao', es_dao) @patch('smfhcp.views.password.smfhcp_utils', dummy_smfhcp_utils) @patch('smfhcp.views.password.send_password_reset_email', send_password_reset_email_success) def test_forgot_password_when_user_not_present(self): self.es_dao.get_forgot_password_token_by_user_name = MagicMock( side_effect=elasticsearch.NotFoundError) self.es_dao.index_forgot_password_token = MagicMock() self.dummy_smfhcp_utils.find_user = MagicMock( return_value=({ 'user_name': TEST_USER_NAME, 'password_hash': TEST_PASSWORD_HASH, 'email': TEST_EMAIL }, False)) post_data = {'user_name': TEST_USER_NAME} request = self.factory.post('/forgot_password', post_data) request.session = dict() response = password.forgot_password(request) self.assertEqual( json.loads(response.content.decode(constants.UTF_8))['message'], 'A password reset conformation mail has been sent to {}'.format( TEST_EMAIL)) self.assertEqual( json.loads(response.content.decode(constants.UTF_8))['success'], True) self.es_dao.get_forgot_password_token_by_user_name.assert_called_with( TEST_USER_NAME) @patch('smfhcp.views.password.es_dao', es_dao) def test_reset_password_get_user_not_found(self): self.es_dao.get_forgot_password_token_by_user_name = MagicMock( side_effect=elasticsearch.NotFoundError) request = self.factory.get('/reset_password/test_user_name/test_otp') request.session = dict() response = password.reset_password(request, TEST_USER_NAME, TEST_OTP) self.assertEqual(response.status_code, 404) @patch('smfhcp.views.password.es_dao', es_dao) def test_reset_password_get_otp_not_found(self): self.es_dao.get_forgot_password_token_by_user_name = MagicMock() request = self.factory.get('/reset_password/test_user_name/test_otp') request.session = dict() response = password.reset_password(request, TEST_USER_NAME, TEST_OTP) self.assertEqual(response.status_code, 404) @patch('smfhcp.views.password.es_dao', es_dao) def test_reset_password_get_success(self): self.es_dao.get_forgot_password_token_by_user_name = MagicMock( return_value={'_source': { 'token': [TEST_OTP] }}) request = self.factory.get('/reset_password/test_user_name/test_otp') request.session = dict() response = password.reset_password(request, TEST_USER_NAME, TEST_OTP) self.assertEqual(response.status_code, 200) @patch('smfhcp.views.password.es_dao', es_dao) @patch('smfhcp.views.password.smfhcp_utils', dummy_smfhcp_utils) def test_reset_password_post_when_doctor(self): self.es_dao.delete_forgot_password_token = MagicMock() self.es_dao.update_password_by_user_name = MagicMock() self.dummy_smfhcp_utils.find_user = MagicMock( return_value=({ 'user_name': TEST_USER_NAME, 'password_hash': TEST_PASSWORD_HASH, 'email': TEST_EMAIL }, True)) post_data = {'new_password': '******'} request = self.factory.post('/reset_password/test_user/test_otp', post_data) request.session = dict() request.session['is_doctor'] = True request.session['user_name'] = TEST_USER_NAME request.session['email'] = TEST_EMAIL request.session['is_authenticated'] = True response = password.reset_password(request, TEST_USER_NAME, TEST_OTP) self.assertEqual(response.status_code, 302) self.es_dao.delete_forgot_password_token.assert_called_with( TEST_USER_NAME) self.dummy_smfhcp_utils.find_user.assert_called_with( TEST_USER_NAME, self.es_dao) self.es_dao.update_password_by_user_name.asser_called_with( TEST_USER_NAME, 'new_password', True) @patch('smfhcp.views.password.es_dao', es_dao) @patch('smfhcp.views.password.smfhcp_utils', dummy_smfhcp_utils) def test_reset_password_post_when_general_user(self): self.es_dao.delete_forgot_password_token = MagicMock() self.es_dao.update_password_by_user_name = MagicMock() self.dummy_smfhcp_utils.find_user = MagicMock( return_value=({ 'user_name': TEST_USER_NAME, 'password_hash': TEST_PASSWORD_HASH, 'email': TEST_EMAIL }, False)) post_data = {'new_password': '******'} request = self.factory.post('/reset_password/test_user/test_otp', post_data) request.session = dict() request.session['is_doctor'] = False request.session['user_name'] = TEST_USER_NAME request.session['email'] = TEST_EMAIL request.session['is_authenticated'] = True response = password.reset_password(request, TEST_USER_NAME, TEST_OTP) self.assertEqual(response.status_code, 302) self.es_dao.delete_forgot_password_token.assert_called_with( TEST_USER_NAME) self.dummy_smfhcp_utils.find_user.assert_called_with( TEST_USER_NAME, self.es_dao) self.es_dao.update_password_by_user_name.asser_called_with( TEST_USER_NAME, 'new_password', False) def test_reset_password_when_request_not_get_or_post(self): request = self.factory.put('/reset_password/test_user/test_otp') with self.assertRaises(PermissionDenied): _ = password.reset_password(request, TEST_USER_NAME, TEST_OTP)