def test_list_all_users_may_list_them(self): UserFactory.create_batch(5) url = reverse('user-list') response = self.client.get(url) expected_users_number = User.objects.count() self.assertEqual(status.HTTP_200_OK, response.status_code) self.assertEqual(expected_users_number, len(response.data['results']))
def handle(self, *args, **options): """Automatically called when the sampledata command is given.""" if settings.DEPLOYMENT_TYPE == 'prod' and not settings.DEBUG: raise management.base.CommandError( 'This command can only be executed in DEBUG mode on non-production website.' ) # Clear all data print(LOG_HEADER.format('Wipe database')) management.call_command('flush', interactive=False) print('Database wiped.') management.call_command('load_user_types') print(LOG_HEADER.format('Create sample users')) User = get_user_model() # Create admin account admin = User.objects.create_superuser( 'admin', '*****@*****.**', password=settings.SAMPLE_DATA_ADMIN_PASSWORD, first_name='Admin', last_name='Account', user_type=UserType.objects.get(slug='teacher')) EmailAddress.objects.create(user=admin, email=admin.email, primary=True, verified=True) print('Admin created.') # Create user account user = User.objects.create_user( 'user', '*****@*****.**', password=settings.SAMPLE_DATA_USER_PASSWORD, first_name='Alex', last_name='Doe', user_type=UserType.objects.get(slug='student')) EmailAddress.objects.create(user=user, email=user.email, primary=True, verified=True) UserFactory.create_batch(size=100) print('Users created.') # Codewof management.call_command('load_questions') print('Programming questions loaded.') # Research StudyFactory.create_batch(size=5) StudyGroupFactory.create_batch(size=15) print('Research studies loaded.')
def test_group_members(self): group = GroupFactory() assert group.members.count() == 0 user1 = UserFactory() user2 = UserFactory() group.members.add(user1, user2) assert group.members.count() == 2 group.members.add(user1) assert group.members.count() == 2 group.members.remove(user1) assert group.members.count() == 1
def handle(self, *args, **options): """Automatically called when the sampledata command is given.""" if settings.PRODUCTION_ENVIRONMENT: raise management.base.CommandError( 'This command can only be executed on a non-production website.' ) skip = options['skip_backdate'] # Clear all data print(LOG_HEADER.format('Wipe database')) management.call_command('flush', interactive=False) print('Database wiped.') # Update data management.call_command('update_data') print(LOG_HEADER.format('Create sample users')) # Create admin account management.call_command('create_admin') # Create user account User = get_user_model() # noqa N806 user = User.objects.create_user( 'user', '*****@*****.**', password=settings.SAMPLE_DATA_USER_PASSWORD, first_name='Alex', last_name='Doe', user_type=UserType.objects.get(slug='student')) EmailAddress.objects.create(user=user, email=user.email, primary=True, verified=True) UserFactory.create_batch(size=100) print('Users created.\n') # Attempts AttemptFactory.create_batch(size=50) print('Attempts loaded.\n') # Award points and achievements if not skip: management.call_command('backdate_points_and_achievements') else: print('Ignoring backdate step as requested.\n')
def test_authenticated(self, user: User, rf: RequestFactory): request = rf.get("/fake-url/") request.user = UserFactory() response = user_detail_view(request, username=user.username) assert response.status_code == 200
def test_clean_username(self): # A user with proto_user params does not exist yet. proto_user = UserFactory.build() form = UserCreationForm( { "username": proto_user.username, "password1": proto_user._password, # pylint: disable=protected-access # noqa E501 "password2": proto_user._password, # pylint: disable=protected-access # noqa E501 } ) assert form.is_valid() assert form.clean_username() == proto_user.username # Creating a user. form.save() # The user with proto_user params already exists, # hence cannot be created. form = UserCreationForm( { "username": proto_user.username, "password1": proto_user._password, # pylint: disable=protected-access # noqa E501 "password2": proto_user._password, # pylint: disable=protected-access # noqa E501 } ) assert not form.is_valid() assert len(form.errors) == 1 assert "username" in form.errors
def test_create_bulk_transactions_may_do_it(self): user = UserFactory() url = reverse('transaction-list') request_body = [ { "reference": "000001", "account": "S55555", "date": "2020-01-01", "amount": "21.13", "type": "inflow", "category": "transfer", "user_id": user.id }, { "reference": "000002", "account": "S55555", "date": "2020-01-01", "amount": "-21.13", "type": "outflow", "category": "payment", "user_id": user.id } ] response = self.client.post(url, request_body, format='json') expected_response = request_body self.assertEquals(status.HTTP_201_CREATED, response.status_code) self.assertEquals(expected_response, response.data)
def test_group_members(self): response = self.client.get(self.detail_url) assert response.status_code == status.HTTP_200_OK assert response.json()['members_list'] == [] members_ids = [UserFactory().id, UserFactory().id] response = self.client.patch( self.detail_url, {'members': members_ids} ) assert response.status_code == status.HTTP_200_OK response = self.client.get(self.detail_url) assert response.status_code == status.HTTP_200_OK assert ( set(m['id'] for m in response.json()['members_list']) == set(members_ids) )
def test_calculate_balance_may_do_it_properly(self): user = UserFactory() account_1 = '00001' inflow_transaction_1_account_1 = TransactionFactory( type=Transaction.INFLOW, account=account_1, user=user) inflow_transaction_2_account_1 = TransactionFactory( type=Transaction.INFLOW, account=account_1, user=user) outflow_transaction_1_account_1 = TransactionFactory( type=Transaction.OUTFLOW, account=account_1, user=user) outflow_transaction_2_account_1 = TransactionFactory( type=Transaction.OUTFLOW, account=account_1, user=user) total_inflow_account_1 = round( Decimal(inflow_transaction_1_account_1.amount + inflow_transaction_2_account_1.amount), 2) total_outflow_account_1 = round( Decimal(outflow_transaction_1_account_1.amount + outflow_transaction_2_account_1.amount), 2) balance_account_1 = round( Decimal(total_inflow_account_1 + total_outflow_account_1), 2) account_2 = '00002' inflow_transaction_1_account_2 = TransactionFactory( type=Transaction.INFLOW, account=account_2, user=user) inflow_transaction_2_account_2 = TransactionFactory( type=Transaction.INFLOW, account=account_2, user=user) outflow_transaction_1_account_2 = TransactionFactory( type=Transaction.OUTFLOW, account=account_2, user=user) outflow_transaction_2_account_2 = TransactionFactory( type=Transaction.OUTFLOW, account=account_2, user=user) total_inflow_account_2 = round( Decimal(inflow_transaction_1_account_2.amount + inflow_transaction_2_account_2.amount), 2) total_outflow_account_2 = round( Decimal(outflow_transaction_1_account_2.amount + outflow_transaction_2_account_2.amount), 2) balance_account_2 = round( Decimal(total_inflow_account_2 + total_outflow_account_2), 2) transactions = Transaction.objects.filter(user=user) queryset = TransactionService.calculate_balance(transactions) expected_account_1 = { 'account': '00001', 'total_inflow': total_inflow_account_1, 'total_outflow': total_outflow_account_1, 'balance': balance_account_1 } expected_account_2 = { 'account': '00002', 'total_inflow': total_inflow_account_2, 'total_outflow': total_outflow_account_2, 'balance': balance_account_2 } self.assertEquals(expected_account_1, queryset[0]) self.assertEquals(expected_account_2, queryset[1])
def test_get_balance_of_user_may_do_it_properly(self): user = UserFactory() TransactionFactory.create_batch(3, user=user) url = reverse('transaction-detail', kwargs={'user_id': user.id}) response = self.client.get(url) transaction_number = Transaction.objects.filter(user=user).count() self.assertEquals(status.HTTP_200_OK, response.status_code) self.assertEquals(transaction_number, len(response.data['results']))
def test_calculate_summary_may_do_it_properly(self): user = UserFactory() TransactionFactory.create_batch(5, user=user) summary = TransactionService.calculate_summary(user.id) self.assertIsInstance(summary, dict) self.assertIn('inflow', summary) self.assertIsInstance(summary['inflow'], dict) self.assertIn('outflow', summary) self.assertIsInstance(summary['outflow'], dict)
def user(request): """Pytest setup for user model.""" management.call_command('load_user_types') def fin(): print("teardown") User.objects.all().delete() UserType.objects.all().delete() request.addfinalizer(fin) return UserFactory()
def test_get_user_summary_may_do_it_properly(self): user = UserFactory() TransactionFactory.create_batch(5, user=user) url = reverse('transaction-summary', kwargs={'user_id': user.id}) response = self.client.get(url) self.assertEquals(status.HTTP_200_OK, response.status_code) self.assertIsInstance(response.data, dict) self.assertIn('inflow', response.data) self.assertIsInstance(response.data['inflow'], dict) self.assertIn('outflow', response.data) self.assertIsInstance(response.data['outflow'], dict)
def test_user_detail_when_user_exists_returns_its_data(self): user = UserFactory() url = reverse('user-detail', kwargs={'pk': user.id}) response = self.client.get(url) expected_response = { 'id': user.id, 'name': user.name, 'email': user.email, 'age': user.age } self.assertEquals(status.HTTP_200_OK, response.status_code) self.assertEquals(expected_response, response.data)
def test_user_groups(self): user = UserFactory() assert user.groups.count() == 0 group1 = GroupFactory() group2 = GroupFactory() user.groups.add(group1, group2) assert user.groups.count() == 2 user.groups.add(group1) assert user.groups.count() == 2 user.groups.remove(group1) assert user.groups.count() == 1
def test_create_user_with_existing_email_returns_error(self): user = UserFactory() url = reverse('user-list') request_body = {"name": "Batman", "email": user.email, "age": 27} response = self.client.post(url, request_body) expected_response = { 'email': [ 'user with this Email address already exists.', 'Enter a valid email address.' ] } self.assertEquals(status.HTTP_400_BAD_REQUEST, response.status_code) self.assertEquals(expected_response, response.data)
def test_get_balance_of_user_filtered_by_after_date_may_do_it_properly(self): user = UserFactory() date_1 = '2020-01-01' date_2 = '2020-10-01' TransactionFactory.create_batch(3, user=user, date=date_1) TransactionFactory.create_batch(4, user=user, date=date_2) url = reverse('transaction-detail', kwargs={'user_id': user.id}) date_after = '2020-09-01' url_with_filter = f'{url}?date_after={date_after}' response = self.client.get(url_with_filter) transaction_number = Transaction.objects.filter(user=user, date__gt=date_after).count() self.assertEquals(status.HTTP_200_OK, response.status_code) self.assertEquals(transaction_number, len(response.data['results']))
def test_create_outflow_transaction_with_positive_amount_returns_error(self): user = UserFactory() url = reverse('transaction-list') request_body = { "reference": "000001", "account": "S55555", "date": "2020-01-01", "amount": "21.13", "type": "outflow", "category": "payment", "user_id": user.id } response = self.client.post(url, request_body) expected_response = {'amount': ['Amount must be negative']} self.assertEquals(status.HTTP_400_BAD_REQUEST, response.status_code) self.assertEquals(expected_response, response.json())
def test_email_validation(self): """Tests email verification.""" user = UserFactory(email='invalid_email') with pytest.raises(ValidationError): user.full_clean()
def user() -> User: """Pytest setup for user model.""" return UserFactory()
def _existing_user(cls): user = UserFactory() cls.existing_user = user cls.detail_url = reverse('user-detail', args=[user.id])
def test_email_duplicates(self): """Tests duplicate emails.""" user = UserFactory() with pytest.raises(IntegrityError): UserFactory(email=user.email)
def test_state_validation(self): """Tests state verification.""" user = UserFactory(state='wrong_state') with pytest.raises(ValidationError): user.full_clean()
def test_new_user(self): """Tests new user creation.""" user = UserFactory() assert user.groups.count() == 0
def test_case_sensitivity(self, rf: RequestFactory): request = rf.get("/fake-url/") request.user = UserFactory(username="******") with pytest.raises(Http404): user_detail_view(request, username="******")
def user() -> User: return UserFactory()
def user() -> settings.AUTH_USER_MODEL: """Pytest setup for user model.""" return UserFactory()