def test_ability_modifier_getters(self): """ Test that ability modifiers are calculated correctly """ character = G(Character) self.assertEqual(character.strength_modifier, 0) character.strength += 4 self.assertEqual(character.strength_modifier, 2) character.strength -= 8 self.assertEqual(character.strength_modifier, -2)
def test_history_on_field_change_save(db, model): obj = G(model) new_obj = N(model) assert new_obj.field != obj.field obj.field = new_obj.field assert not FieldsHistory.objects.exists() obj.save() assert FieldsHistory.objects.count() == 1
def setUp(self): # Initialize client self.client = APIClient() # Initialize different POV users user_model = get_user_model() self.superuser = user_model.objects.create_superuser('superuser', password='******') self.owner = user_model.objects.create_user('owner', password='******') self.editor = user_model.objects.create_user('editor', password='******') self.other_user = user_model.objects.create_user('other_user', password='******') self.inactive_user = user_model.objects.create_user('inactive_user', \ password='******', is_active=False) self.skill = G(Skill, owner=self.owner, authorized_editors=[self.editor.id]) self.private_character = G(Character, is_private=True, \ owner=self.owner, authorized_editors=[self.editor.id])
def test_login_page_with_authenticated_user(self, client): user = G(User) client.force_login(user) response = client.get('/login/') assert response.status_code == 302, 'Logged in user should get redirected on accessing login page' assert response.has_header( 'location' ) == True, 'Redirection url should be present in response header' assert response.get( 'location' ) == '/', 'Location header must contain redirection url which is homepage in this case.'
def test_successful_logout(self): """ Testcase for successful logout. """ user = G(AUTH_USER) self.client.force_authenticate(user=user) response = self.client.delete(self.url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(Token.objects.filter(user=user).count(), 0)
def test_get_history_on_specific_field(db): obj = G(MultipleFieldModel) obj.first_field = f"new_{obj.first_field}" obj.save() obj.second_field = f"new_{obj.first_field}" obj.save() assert FieldsHistory.objects.count() == 2 assert len(obj.get_first_field_history()) == 1 assert len(obj.get_second_field_history()) == 1
def test_appointment_cancelled(self, doctor, student, client): self._login(doctor.user, client) appointment = G(Appointment, student=student, doctor=doctor) response = client.get(f'/appointments/update/{appointment.pk}/cancel/') assert response.status_code == 302, 'Updation of appointment should return redirect response' assert response.get( 'location' ) == '/doctor/dashboard/appointments/', 'Updation of appointment should return to appointment list view of doctor' appointment.refresh_from_db() assert appointment.is_cancelled == True, 'Appointment should be cancelled' assert appointment.is_confirmed == False, 'Appointment should not be confirmed'
def test_user_deletion(self): """ Testcase for checking deletion of user. """ user = G(AUTH_USER) self.client.force_authenticate(user=user) response = self.client.delete(f'{self.url}{user.id}/') self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) self.assertEqual(AUTH_USER.objects.filter(id=user.id).count(), 0) # As user is soft deleted hence users token will exist. self.assertEqual(Token.objects.filter(user__id=user.id).count(), 1) self.assertEqual(AUTH_USER.all_objects.filter(id=user.id).count(), 1)
def test_unique_email(self): """ Testcase for unique email id. """ user1 = G(AUTH_USER, email='*****@*****.**') user2 = get_user_data(email='*****@*****.**') response = self.client.post(self.url, data=user2) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual( response.data.get('email')[0].__str__(), 'user with this email already exists.' )
def test_multiple_changes(db, model): obj = G(model) current_value = obj.field new_obj = N(model) assert new_obj.field != current_value obj.field = new_obj.field obj.save() obj.field = current_value obj.save() assert FieldsHistory.objects.count() == 2
def test_history_on_field_change_save_after_get_from_db(db, model): obj = G(model) obj = model.objects.get(pk=obj.pk) new_obj = N(model) assert new_obj.field != obj.field old_value = obj.field obj.field = new_obj.field assert not FieldsHistory.objects.exists() obj.save() assert FieldsHistory.objects.count() == 1 assert old_value in {history.value for history in obj.get_field_history()}
def setUp(self): user_model = get_user_model() self.user_in_party_a = user_model.objects.create_user( username='******') self.user_in_party_b = user_model.objects.create_user( username='******') self.user_in_neither = user_model.objects.create_user( username='******') self.game_master_a = user_model.objects.create_user( username='******') self.game_master_b = user_model.objects.create_user( username='******') self.party_a = G(Party, players=[self.user_in_party_a.id], \ game_masters=[self.game_master_a.id]) self.party_b = G(Party, players=[self.user_in_party_b.id], \ game_masters=[self.game_master_b.id]) self.handout_a = G(Handout, parties=[self.party_a.id]) self.handout_b = G(Handout, parties=[self.party_b.id]) self.handout_both = G(Handout, parties=[self.party_a.id, self.party_b.id])
def test_resend_verification_email_failure(self, mock_send_account_verification_email): """ Testcase to not sending verification email to the already verified user. """ user = G(AUTH_USER, is_email_verified=True) self.client.force_authenticate(user=user) response = self.client.post(self.url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual( response.data.get(commons_constant.RESPONSE_MSG), commons_constant.PASS_RESET_LINK_SUCC ) mock_send_account_verification_email.delay.assert_not_called()
def client(): """ Enhanced test client for classic Django views and the admin https://django-functest.readthedocs.io/en/latest/common.html https://github.com/django-webtest/django-webtest/blob/master/django_webtest/pytest_plugin.py """ user = G(User, is_staff=True, is_superuser=True) client = FuncWebTest() client._patch_settings() client.renew_app() client.app.set_user(user) client.user = user yield client client._unpatch_settings()
def setUp(self) -> None: config = G(InstitutionConfig) self.template = EmailTemplate.objects.create( config=config, is_dynamic=True, subject='Подтверждение регистрации', type='REG_VERIFIED', template= 'Ваш логин: {{ user }}\nВаш пароль: {{ password }}\nДля подтверждения регистрации необходимо пройти по ссылке\n{{ link }}\n\nВНИМАНИЕ!!!\nРегистрация должна быть подтверждена в течении 1 дня.\nПо истечении этого срока Ваши данные будут удалены и потребуется повторная регистрация.', ) self.data = { 'user': '******', 'password': '******', 'link': 'https://test.com/qw41ch2/1441dxv/' }
def get_real_url(view, urlname, urlpattern): arguments = re.findall("<[^>]*>", urlpattern) if not arguments: return reverse(urlname) if hasattr(view, "view_class"): # TODO: Hopthesis create form: view.view_class.form_class if hasattr(view.view_class, "model"): # likely an ID which is required url argument if len(arguments) == 1: model = view.view_initkwargs.get( "model") or view.view_class.model urlargname = arguments[0].strip("<>").split(":")[-1] obj = G(model) return reverse(urlname, kwargs={urlargname: obj.id}) return None
def test_doctor_search_via_email(self, doctor, client): self._login(doctor.user, client) response = client.get('/doctor/dashboard/search/') assert response.status_code == 200, 'Search view should return 200 OK response for doctor' assert len( response.context_data.get('object_list') ) == 0, 'There should not be any results without the query url param' user_1 = G(User, email='*****@*****.**') student_1 = G(Student, user=user_1) user_2 = G(User, email='*****@*****.**') student_2 = G(Student, user=user_2) # testing with only username search_query = 'dummy' response = client.get(f'/doctor/dashboard/search/?q={search_query}') search_results = response.context_data.get('object_list') assert len(search_results) == 1, 'There should be exactly one result' assert search_results[ 0] == student_1, '"student_2" should be returned as only the search result' # testing with domain search_query = 'bar.com' response = client.get(f'/doctor/dashboard/search/?q={search_query}') search_results = response.context_data.get('object_list') assert len(search_results) == 1, 'There should be exactly one result' assert search_results[ 0] == student_2, '"student_2" should be returned as only the search result' # testing with full email search_query = '*****@*****.**' response = client.get(f'/doctor/dashboard/search/?q={search_query}') search_results = response.context_data.get('object_list') assert len(search_results) == 1, 'There should be exactly one result' assert search_results[ 0] == student_2, '"student_2" should be returned as only the search result'
def test_forget_password_success(self, mock_send_password_reset_email_async): """ Test for forget password success. """ user = G(AUTH_USER) data = { 'email': user.email, } response = self.client.post(self.url, data=data) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEquals(len(response.data), 1) self.assertEqual( response.data.get(commons_constant.RESPONSE_MSG), commons_constant.PASS_RESET_LINK_SUCC ) mock_send_password_reset_email_async.delay.assert_called()
def test_login_success(self): """ Testcase for successful logging in. """ user = G(AUTH_USER, password=make_password('password')) login_cred = { 'email': user.email, 'password': '******', } response = self.client.post(self.url, data=login_cred) expected_response = { commons_constant.RESPONSE_TOKEN: Token.objects.get(user=user).key } self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(dict(response.data), expected_response)
def test_response_for_invalid_credentials(self): """ Test for invalid credentials. """ user = G(AUTH_USER, password=make_password('right')) login_cred = { 'email': user.email, 'password': '******', } response = self.client.post(self.url, data=login_cred) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual(len(response.data), 1) self.assertEqual(len(response.data.get('non_field_errors')), 1) self.assertEqual( response.data.get('non_field_errors')[0].__str__(), 'Invalid Email or Password' )
def test_retrieve_and_list_method_not_allowed(self): """ Test for checking retrive method not allowed on the viewset. """ user = G(AUTH_USER) self.client.force_authenticate(user=user) # For listing users response = self.client.get(self.url) self.assertEqual( response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED ) # For retrieving request response = self.client.get(f'{self.url}{user.id}/') self.assertEqual( response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED )
def test_replantation_list(self, mock_chain, mock_chain2, mock3): G(Replantation) self.client.force_authenticate(self.super_user) response = self.client.get(self.replantation_list_url) self.assertEqual(response.status_code, status.HTTP_200_OK) replantation_count = Replantation.objects.all().count() self.assertEqual(response.data['count'], replantation_count) plot_response = self.create_carbonization_beginning() response = self.client.post(self.replantation_list_url, { "trees_planted": 1, "beginning_date": 1576181866, "ending_date": 1576181866, "location": self.location, "plot": plot_response.data['package_id'], "tree_specie": self.tree_specie.id }, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(replantation_count + 1, Replantation.objects.all().count())
def test_replantation_plots(self): # create new plot with LoggingEnding and create a replantation entry for it package = G(Package, type=Package.PLOT) entity = G(Entity, package=package, action='LE') G(LoggingEnding, entity=entity) G(Replantation, plot=package) package.last_action = entity package.save() # create new plot with LoggingEnding without a replantation entry package = G(Package, type=Package.PLOT) entity = G(Entity, package=package, action='LE') G(LoggingEnding, entity=entity) package.last_action = entity package.save() self.client.force_authenticate(self.super_user) response = self.client.get(self.replantation_plots_url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['count'], 1)
def test_updating_password_success(self): """ Testcase for updating user's password. """ user = G(AUTH_USER, password=make_password('old_password')) self.client.force_authenticate(user=user) data = { 'old_password': '******', 'new_password': '******' } response = self.client.post(self.url, data=data) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data), 1) self.assertEqual( response.data.get( commons_constant.RESPONSE_MSG), commons_constant.PASS_UPDATE_SUCC ) self.assertEquals( authenticate( email=user.email, password=data.get('new_password') ), user )
def test_appointments_list_page_response_with_appointments( self, student, doctor, client): self._login(student.user, client) appointment_1 = G(Appointment, student=student, doctor=doctor) appointment_2 = G(Appointment, student=student, doctor=doctor) appointment_3 = G(Appointment, student=student, doctor=doctor) # creating appointment for another student user_1 = G(User) student_1 = G(Student, user=user_1) appointment_4 = G(Appointment, student=student_1, doctor=doctor) response = client.get('/student/dashboard/all-appointments/') assert response.status_code == 200, 'Student should be able to view all appointments' appointments = response.context_data.get('object_list') assert len( appointments) == 3, 'Three appointments are made for the student'
def test_list(self, client: FuncWebTest, admin_url, result_count): G(Transaction, n=2) client.get_literal_url(admin_url(Transaction, "changelist")) assert result_count(client.last_response) == 2
def test_agents(self): G(User, is_superuser=True) self.client.force_authenticate(self.super_user) response = self.client.get(self.agents_url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data['results']), User.objects.count())
def test_applicant_verification_cron_job(): new_applicant = G(Applicant) call_command("runcrons") applicants = Applicant.objects.count() assert applicants == 0
def setup(self): G(AuthToken, user=F(email="*****@*****.**", password=make_password("qwerty123456789"), role=ROLE.ADMIN, organization__name="JTG"))
def setUp(self): G(User, email="*****@*****.**", password=make_password("qwerty123456789"), role=ROLE.ADMIN, organization__name="JTG")