class BatchAckOfTransmittalsTests(TestCase): def setUp(self): self.trs = create_transmittal() self.category = self.trs.document.category self.user = UserFactory(email='*****@*****.**', password='******', is_superuser=True, category=self.category) self.client.login(email=self.user.email, password='******') self.url = reverse('transmittal_batch_ack_of_receipt', args=[ self.category.organisation.slug, self.category.slug, ]) def test_internal_user_cannot_ack_transmittal(self): res = self.client.post(self.url, {'document_ids': [self.trs.document_id]}) self.assertEqual(res.status_code, 403) def test_acks_receipt(self): self.user.is_external = True self.user.save() res = self.client.post(self.url, {'document_ids': [self.trs.document_id]}, follow=True) self.assertEqual(res.status_code, 200) self.trs.refresh_from_db() self.assertIsNotNone(self.trs.ack_of_receipt_date) self.assertEqual(self.trs.ack_of_receipt_author, self.user)
def test_change_account_password_failure_cases(self): # Should reject the password change request if old password is incorrect user = UserFactory() old_password = '******' new_password = '******' user.set_password(old_password) user.save() self.client.force_login(user) url = reverse('api_accounts:current_user_detail') # Test old password is incorrect response = self.client.put(url, { 'old_password': '******', 'new_password1': new_password, 'new_password2': new_password, }, format='json') self.assertEqual(response.status_code, 400) execpted = {u'old_password': [u'Old password is incorrect']} self.assertDictContainsSubset(execpted, response.json()) # Test two passwords mismatch response = self.client.put(url, { 'old_password': old_password, 'new_password1': new_password, 'new_password2': new_password + '1', }, format='json') self.assertEqual(response.status_code, 400) execpted = {u'new_password1': [u'Password1 and Password2 mismatch']} self.assertDictContainsSubset(execpted, response.json())
class DocumentDetailTests(TestCase): """Test action menu items""" def setUp(self): self.category = CategoryFactory() self.user = UserFactory( name='User', password='******', is_superuser=True, category=self.category) self.client.login(username=self.user.email, password='******') self.doc = DocumentFactory( category=self.category, revision={ 'leader': self.user, } ) self.url = reverse("document_detail", args=[ self.category.organisation.slug, self.category.slug, self.doc.document_key ]) def test_admin_can_delete_document(self): res = self.client.get(self.url) self.assertContains(res, delete_button) def test_simple_user_cannot_delete_document(self): self.user.is_superuser = False self.user.save() res = self.client.get(self.url) self.assertNotContains(res, delete_button)
class BatchAckOfTransmittalsTests(TestCase): def setUp(self): self.trs = create_transmittal() self.category = self.trs.document.category self.user = UserFactory( email='*****@*****.**', password='******', is_superuser=True, category=self.category) self.client.login(email=self.user.email, password='******') self.url = reverse('transmittal_batch_ack_of_receipt', args=[ self.category.organisation.slug, self.category.slug, ]) def test_internal_user_cannot_ack_transmittal(self): res = self.client.post(self.url, {'document_ids': [self.trs.document_id]}) self.assertEqual(res.status_code, 403) def test_acks_receipt(self): self.user.is_external = True self.user.save() res = self.client.post( self.url, {'document_ids': [self.trs.document_id]}, follow=True) self.assertEqual(res.status_code, 200) self.trs.refresh_from_db() self.assertIsNotNone(self.trs.ack_of_receipt_date) self.assertEqual(self.trs.ack_of_receipt_author, self.user)
def handle(self, *args, **options): KHARKOV = [50.040156499999995, 36.3003934] SMELA = [49.2391097, 31.859249100000003] CITIES = [KHARKOV, SMELA] print("COMMAND STARTED") unique_categories = list() while len(unique_categories) < 5: unique_categories.append(fake.word()) unique_categories = list(set(unique_categories)) unique_emails = list() while len(unique_emails) < 100: unique_emails.append(fake.email()) unique_emails = list(set(unique_emails)) print("CREATING OF CATEGORIES") categories = [ CategoryFactory(name=category) for category in unique_categories ] print("CREATING OF USERS-PROFILES-POSTS") iteration = 0 for email in unique_emails: coords = random.choice(CITIES) try: user = UserFactory(email=email, latitude=coords[0], longitude=coords[1], full_name=fake.name()) user.set_password('qweqweqwe') user.save() except IntegrityError: print('EMAIL SKIPPED') continue try: image_url = fake.image_url() while "lorempixel" in image_url: image_url = fake.image_url() image_path = load_image_by_url(image_url) image = Image.objects.create(user=user, image=image_path) except Exception as e: print(e) continue profile = ProfileFactory(user=user, avatar=image, age=random.randint(18, 55)) post = PostFactory(profile=profile, category=random.choice(categories), looking_for=random.choice(GENDERS)) post.photos.add(image) post.save() print('{}/{}'.format(iteration, len(unique_emails))) iteration += 1 print("COMMAND FINISHED")
def test_buy_a_bet(self): """ Buy a bet """ event = EventFactory() user = UserFactory(total_cash=event.current_buy_for_price) old_price = event.current_buy_for_price bet_user, bet_event, bet = Bet.objects.buy_a_bet(user, event.id, Bet.YES, event.current_buy_for_price) self.assertEqual(user, bet_user) self.assertEqual(event, bet_event) self.assertEqual(event.current_buy_for_price, bet.bought_avg_price) self.assertEqual(1, bet.has) self.assertEqual(1, bet.bought) self.assertEqual(0, bet_user.total_cash) self.assertEqual(old_price, bet_user.portfolio_value) self.assertNotEqual(old_price, bet_event.current_buy_for_price) self.assertEqual(1, bet_event.turnover) with self.assertRaises(PriceMismatch): Bet.objects.buy_a_bet(user, event.id, Bet.YES, old_price) with self.assertRaises(InsufficientCash): Bet.objects.buy_a_bet(user, event.id, Bet.YES, bet_event.current_buy_for_price) user.total_cash = bet_event.current_buy_against_price user.save() # TODO should throw exception Bet.objects.buy_a_bet(user, event.id, Bet.NO, bet_event.current_buy_against_price)
def superuser(): """Generates a valid and active superuser.""" user = UserFactory() user.is_superuser = True user.save() return user
class UserApiAclTests(APITestCase): def setUp(self): self.category = CategoryFactory() self.user = UserFactory(name='user', password='******', category=self.category) self.dc_perms = Permission.objects.filter(codename__endswith='_document') self.dc = UserFactory(name='dc', password='******', category=self.category) self.dc.user_permissions = self.dc_perms self.dc.save() self.url = reverse('user-list', args=[ self.category.organisation.slug, self.category.category_template.slug, ]) def test_anonymous_access_forbidden(self): """Anonymous cannot access the user api.""" res = self.client.get(self.url) self.assertEqual(res.status_code, 403) def test_simple_user_access_forbidden(self): """Simple users don't have access to the user api.""" self.client.login(username=self.user.email, password='******') res = self.client.get(self.url) self.assertEqual(res.status_code, 403) def test_dc_can_access_user_api(self): """Document controllers can access the user api.""" self.client.login(username=self.dc.email, password='******') res = self.client.get(self.url) self.assertEqual(res.status_code, 200) def test_dc_can_only_access_users_from_his_category(self): other_category = CategoryFactory() user = UserFactory(name='dc2', password='******', category=other_category) user.user_permissions = self.dc_perms user.save() self.client.login(username=user.email, password='******') res = self.client.get(self.url) self.assertEqual(res.status_code, 403) def test_dc_cannot_see_users_from_other_categories(self): other_category = CategoryFactory() user1 = UserFactory(name='toto', password='******', category=other_category) user1.save() user2 = UserFactory(name='tata', password='******', category=self.category) user2.save() self.client.login(username=self.dc.email, password='******') res = self.client.get(self.url) self.assertEqual(res.status_code, 200) self.assertTrue('tata' in res.content) self.assertTrue('toto' not in res.content)
def test_dc_can_only_access_users_from_his_category(self): other_category = CategoryFactory() user = UserFactory(name='dc2', password='******', category=other_category) user.user_permissions = self.dc_perms user.save() self.client.login(username=user.email, password='******') res = self.client.get(self.url) self.assertEqual(res.status_code, 403)
class AdminTest(FunctionalTest): def setUp(self): super().setUp() # Create a superuser self.password = '******' self.admin_user = UserFactory(password=self.password) self.admin_user.is_admin = True self.admin_user.save() # Create packages and doctypes for the new audit PackageFactory(name='TestPackage') DoctypeFactory(name='TestDoctype') def test_can_create_new_audit_via_admin_site(self): # Gertrude opens her web browser, and goes to the admin page self.browser.get(self.server_url + '/admin/') # She sees the familiar 'Django administration' heading body = self.browser.find_element_by_tag_name('body') self.assertIn('Django administration', body.text) # She inserts her email and password email_input = self.browser.find_element_by_id('id_username') email_input.send_keys(self.admin_user.email) password_input = self.browser.find_element_by_id('id_password') password_input.send_keys(self.password + '\n') # Aftwer beign logged in, she visits the audit creation page audit_section = self.browser.find_element_by_css_selector('.model-audit') audit_section.find_element_by_css_selector('.addlink').click() # She inserts all the required information in order to create a new audit self.browser.find_element_by_id('id_name').send_keys('A new test audit') self.browser.find_element_by_id('id_description').send_keys('A text description for our new audit') package_dropdown = Select(self.browser.find_element_by_id('id_package')) package_dropdown.select_by_visible_text('TestPackage') doctype_selection = Select(self.browser.find_element_by_id('id_required_doctypes')) doctype_selection.select_by_visible_text('TestDoctype') runner_dropdown = Select(self.browser.find_element_by_id('id_runner')) runner_dropdown.select_by_visible_text('DummyAudit') # She then saves her new audit by clicking on the Save button self.browser.find_element_by_css_selector('.default').click() # A list page is displayed, and she can see her newly created audit is in there self.assertTrue(self.browser.find_element_by_link_text('A new test audit')) # Finally, she visits to the home page to check if her new audit is displayed self.browser.find_element_by_link_text('VIEW SITE').click() page_text = self.browser.find_element_by_tag_name('body').text self.assertIn('A new test audit', page_text)
class PendingReviewsReminderTests(TestCase): def setUp(self): self.category = CategoryFactory() self.user = UserFactory( email='*****@*****.**', password='******', is_superuser=True, category=self.category ) self.client.login(email=self.user.email, password='******') self.doc1 = DocumentFactory( category=self.category, revision={ 'leader': self.user, 'received_date': datetime.date.today(), } ) self.doc2 = DocumentFactory( category=self.category, revision={ 'leader': self.user, 'received_date': datetime.date.today(), } ) def test_empty_reminder_list(self): call_command('send_review_reminders') self.assertEqual(len(mail.outbox), 0) def test_send_reminders(self): self.doc1.get_latest_revision().start_review() self.assertEqual(Review.objects.all().count(), 1) call_command('send_review_reminders') self.assertEqual(len(mail.outbox), 1) def test_finished_reviews(self): rev = self.doc1.get_latest_revision() rev.start_review() rev.end_review() self.assertEqual(Review.objects.all().count(), 1) call_command('send_review_reminders') self.assertEqual(len(mail.outbox), 0) def test_do_not_send_reminder(self): """Reminders are not send to users if their mail config says so.""" self.doc1.get_latest_revision().start_review() self.assertEqual(Review.objects.all().count(), 1) self.user.send_pending_reviews_mails = False self.user.save() call_command('send_review_reminders') self.assertEqual(len(mail.outbox), 0)
def test_dc_can_only_access_users_from_his_category(self): other_category = CategoryFactory() user = UserFactory(name='dc2', password='******', category=other_category) user.user_permissions = self.dc_perms user.save() self.client.login(username=user.email, password='******') res = self.client.get(self.url) self.assertEqual(res.status_code, 403)
class FileTransmittedDownloadTests(TestCase): def setUp(self): self.trs = create_transmittal() self.rev = self.trs.latest_revision self.category = self.trs.document.category self.user = UserFactory(email='*****@*****.**', password='******', is_superuser=True, is_external=True, category=self.category) self.trs.recipient.users.add(self.user) self.client.login(email=self.user.email, password='******') self.linked_rev = self.trs.get_revisions()[0] self.url = reverse('file_transmitted_download', args=[ self.category.organisation.slug, self.category.slug, self.trs.document_number, self.linked_rev.metadata.document_key, self.linked_rev.revision, ]) pdf_doc = 'sample_doc_pdf.pdf' sample_pdf = SimpleUploadedFile(pdf_doc, b'content') self.linked_rev.file_transmitted = sample_pdf self.linked_rev.save() def test_url_is_accessible_to_externals(self): u"""This download url is for contractors only.""" res = self.client.get(self.url) self.assertEqual(res.status_code, 200) self.user.is_external = False self.user.save() res = self.client.get(self.url) self.assertEqual(res.status_code, 404) def test_that_revision_is_linked_to_transmittal(self): u"""The file must have been transmitted.""" self.linked_rev.transmittals.clear() self.linked_rev.save() res = self.client.get(self.url) self.assertEqual(res.status_code, 404) def test_that_contractor_is_in_recipients(self): u"""The contractor must be allowed to access the transmittal.""" self.trs.recipient.users.clear() self.trs.recipient.save() res = self.client.get(self.url) self.assertEqual(res.status_code, 404)
class FileTransmittedDownloadTests(TestCase): def setUp(self): self.trs = create_transmittal() self.rev = self.trs.latest_revision self.category = self.trs.document.category self.user = UserFactory( email='*****@*****.**', password='******', is_superuser=True, is_external=True, category=self.category) self.trs.recipient.users.add(self.user) self.client.login(email=self.user.email, password='******') self.linked_rev = self.trs.get_revisions()[0] self.url = reverse('file_transmitted_download', args=[ self.category.organisation.slug, self.category.slug, self.trs.document_number, self.linked_rev.metadata.document_key, self.linked_rev.revision, ]) pdf_doc = 'sample_doc_pdf.pdf' sample_pdf = SimpleUploadedFile(pdf_doc, b'content') self.linked_rev.file_transmitted = sample_pdf self.linked_rev.save() def test_url_is_accessible_to_externals(self): u"""This download url is for contractors only.""" res = self.client.get(self.url) self.assertEqual(res.status_code, 200) self.user.is_external = False self.user.save() res = self.client.get(self.url) self.assertEqual(res.status_code, 404) def test_that_revision_is_linked_to_transmittal(self): u"""The file must have been transmitted.""" self.linked_rev.transmittals.clear() self.linked_rev.save() res = self.client.get(self.url) self.assertEqual(res.status_code, 404) def test_that_contractor_is_in_recipients(self): u"""The contractor must be allowed to access the transmittal.""" self.trs.recipient.users.clear() self.trs.recipient.save() res = self.client.get(self.url) self.assertEqual(res.status_code, 404)
class PendingReviewsReminderTests(TestCase): def setUp(self): self.category = CategoryFactory() self.user = UserFactory(email='*****@*****.**', password='******', is_superuser=True, category=self.category) self.client.login(email=self.user.email, password='******') self.doc1 = DocumentFactory(category=self.category, revision={ 'leader': self.user, 'received_date': datetime.date.today(), }) self.doc2 = DocumentFactory(category=self.category, revision={ 'leader': self.user, 'received_date': datetime.date.today(), }) def test_empty_reminder_list(self): call_command('send_review_reminders') self.assertEqual(len(mail.outbox), 0) def test_send_reminders(self): self.doc1.get_latest_revision().start_review() self.assertEqual(Review.objects.all().count(), 1) call_command('send_review_reminders') self.assertEqual(len(mail.outbox), 1) def test_finished_reviews(self): rev = self.doc1.get_latest_revision() rev.start_review() rev.end_review() self.assertEqual(Review.objects.all().count(), 1) call_command('send_review_reminders') self.assertEqual(len(mail.outbox), 0) def test_do_not_send_reminder(self): """Reminders are not send to users if their mail config says so.""" self.doc1.get_latest_revision().start_review() self.assertEqual(Review.objects.all().count(), 1) self.user.send_pending_reviews_mails = False self.user.save() call_command('send_review_reminders') self.assertEqual(len(mail.outbox), 0)
def test_dc_cannot_see_users_from_other_categories(self): other_category = CategoryFactory() user1 = UserFactory(name='toto', password='******', category=other_category) user1.save() user2 = UserFactory(name='tata', password='******', category=self.category) user2.save() self.client.login(username=self.dc.email, password='******') res = self.client.get(self.url) self.assertEqual(res.status_code, 200) self.assertTrue('tata' in res.content) self.assertTrue('toto' not in res.content)
def test_user_can_have_multiple_roles(): """Roles are not exclusive. A user can have multiple roles.""" multi_role_user = UserFactory(is_contributor=True) SearchPageFactory(administrator=multi_role_user) guadeloupe = PerimeterFactory(name='Guadeloupe', scale=Perimeter.SCALES.region) multi_role_user.animator_perimeter = guadeloupe multi_role_user.save() Token.objects.get_or_create(user=multi_role_user) assert User.objects.count() == 1 assert User.objects.contributors().count() == 1 assert User.objects.search_page_admins().count() == 1 assert User.objects.animators().count() == 1 assert User.objects.with_api_token().count() == 1
def test_change_account_password(self): user = UserFactory() old_password = '******' new_password = '******' user.set_password(old_password) user.save() self.client.force_login(user) url = reverse('api_accounts:current_user_detail') response = self.client.put(url, { 'old_password': old_password, 'new_password1': new_password, 'new_password2': new_password, }, format='json') self.assertEqual(response.status_code, 200) updated_user = User.objects.get(pk=user.pk) self.assertTrue(updated_user.check_password(new_password))
class AclTests(TestCase): def setUp(self): category = CategoryFactory() self.user = UserFactory(name='User', password='******', category=category) self.home_url = reverse( 'category_document_list', args=[category.organisation.slug, category.slug]) self.create_url = reverse( 'document_create', args=[category.organisation.slug, category.slug]) self.login_url = '/accounts/login/' self.dc_perms = Permission.objects.filter( codename__endswith='_document') def test_anonymous_access(self): res = self.client.get(self.home_url) self.assertRedirects(res, '%s?next=%s' % (self.login_url, self.home_url)) res = self.client.get(self.create_url) self.assertRedirects(res, '%s?next=%s' % (self.login_url, self.create_url)) def test_authenticated_user_access(self): self.client.login(username=self.user.email, password='******') res = self.client.get(self.home_url) self.assertEqual(res.status_code, 200) res = self.client.get(self.create_url) self.assertRedirects(res, '%s?next=%s' % (self.login_url, self.create_url)) def test_document_controller_access(self): self.user.user_permissions = self.dc_perms self.user.save() self.client.login(username=self.user.email, password='******') res = self.client.get(self.home_url) self.assertEqual(res.status_code, 200) res = self.client.get(self.create_url) self.assertEqual(res.status_code, 200)
def test_dc_cannot_see_users_from_other_categories(self): other_category = CategoryFactory() user1 = UserFactory(name='toto', password='******', category=other_category) user1.save() user2 = UserFactory(name='tata', password='******', category=self.category) user2.save() self.client.login(username=self.dc.email, password='******') res = self.client.get(self.url) self.assertEqual(res.status_code, 200) self.assertTrue('tata' in res.content) self.assertTrue('toto' not in res.content)
class AclTests(TestCase): def setUp(self): category = CategoryFactory() self.user = UserFactory(name='User', password='******', category=category) self.home_url = reverse('category_document_list', args=[ category.organisation.slug, category.slug ]) self.create_url = reverse('document_create', args=[ category.organisation.slug, category.slug ]) self.login_url = '/accounts/login/' self.dc_perms = Permission.objects.filter(codename__endswith='_document') def test_anonymous_access(self): res = self.client.get(self.home_url) self.assertRedirects(res, '%s?next=%s' % (self.login_url, self.home_url)) res = self.client.get(self.create_url) self.assertRedirects(res, '%s?next=%s' % (self.login_url, self.create_url)) def test_authenticated_user_access(self): self.client.login(username=self.user.email, password='******') res = self.client.get(self.home_url) self.assertEqual(res.status_code, 200) res = self.client.get(self.create_url) self.assertRedirects(res, '%s?next=%s' % (self.login_url, self.create_url)) def test_document_controller_access(self): self.user.user_permissions = self.dc_perms self.user.save() self.client.login(username=self.user.email, password='******') res = self.client.get(self.home_url) self.assertEqual(res.status_code, 200) res = self.client.get(self.create_url) self.assertEqual(res.status_code, 200)
class AckReceiptOfTransmittalTests(TestCase): def setUp(self): self.trs = create_transmittal() self.category = self.trs.document.category self.user = UserFactory(email='*****@*****.**', password='******', is_superuser=True, category=self.category) self.client.login(email=self.user.email, password='******') self.url = reverse('transmittal_ack_of_receipt', args=[ self.category.organisation.slug, self.category.slug, self.trs.document.document_key ]) def test_non_contractor_acks_receipt(self): """Non contractor cannot ack receipt of transmittals.""" res = self.client.post(self.url) self.assertEqual(res.status_code, 403) def test_acks_receipt(self): self.assertIsNone(self.trs.ack_of_receipt_date) self.assertIsNone(self.trs.ack_of_receipt_author) self.user.is_external = True self.user.save() res = self.client.post(self.url, follow=True) self.assertEqual(res.status_code, 200) self.trs.refresh_from_db() self.assertIsNotNone(self.trs.ack_of_receipt_date) self.assertEqual(self.trs.ack_of_receipt_author, self.user) def test_acks_receipt_twice_fails(self): self.user.is_external = True self.user.save() self.trs.ack_receipt(self.user) res = self.client.post(self.url, follow=True) self.assertEqual(res.status_code, 403)
class AckReceiptOfTransmittalTests(TestCase): def setUp(self): self.trs = create_transmittal() self.category = self.trs.document.category self.user = UserFactory( email='*****@*****.**', password='******', is_superuser=True, category=self.category) self.client.login(email=self.user.email, password='******') self.url = reverse('transmittal_ack_of_receipt', args=[ self.category.organisation.slug, self.category.slug, self.trs.document.document_key ]) def test_non_contractor_acks_receipt(self): """Non contractor cannot ack receipt of transmittals.""" res = self.client.post(self.url) self.assertEqual(res.status_code, 403) def test_acks_receipt(self): self.assertIsNone(self.trs.ack_of_receipt_date) self.assertIsNone(self.trs.ack_of_receipt_author) self.user.is_external = True self.user.save() res = self.client.post(self.url, follow=True) self.assertEqual(res.status_code, 200) self.trs.refresh_from_db() self.assertIsNotNone(self.trs.ack_of_receipt_date) self.assertEqual(self.trs.ack_of_receipt_author, self.user) def test_acks_receipt_twice_fails(self): self.user.is_external = True self.user.save() self.trs.ack_receipt(self.user) res = self.client.post(self.url, follow=True) self.assertEqual(res.status_code, 403)
class TransmittalActionTests(TestCase): def setUp(self): self.trs = create_transmittal() self.doc = self.trs.document self.category = self.doc.category self.url = reverse("document_detail", args=[ self.category.organisation.slug, self.category.slug, self.doc.document_key ]) self.user = UserFactory( name='User', password='******', is_superuser=True, category=self.category) self.client.login(username=self.user.email, password='******') def test_internal_user_cannot_ack_transmittal(self): self.assertIsNone(self.trs.ack_of_receipt_date) self.assertFalse(self.user.is_external) res = self.client.get(self.url) self.assertNotContains(res, ack_button) def test_external_user_can_ack_transmittal(self): self.user.is_external = True self.user.save() res = self.client.get(self.url) self.assertContains(res, ack_button) def test_transmittal_cannot_be_acked_twice(self): self.user.is_external = True self.trs.ack_receipt(self.user) self.assertIsNotNone(self.trs.ack_of_receipt_date) res = self.client.get(self.url) self.assertNotContains(res, ack_button)
class UserTestCases(TestCase): """ User model test cases. """ def setUp(self) -> None: super().setUp() # Create users from UserFactory self.user = UserFactory() def tearDown(self) -> None: super().tearDown() User.objects.all().delete() def test_user_and_customer_can_be_created(self): self.assertEqual(self.user.id, 1) customer_obj = Customer.objects.get(account=self.user.id) self.assertEqual(customer_obj.email.email, self.user.email) def test_user_can_be_updated(self): update_data = { 'email': factories.Faker('email').generate(), } for key, value in update_data.items(): setattr(self.user, key, value) self.user.save() self.assertEqual(self.user.email, update_data['email']) # Check customer of this user customer_obj = Customer.objects.filter(account=self.user)[0] self.assertEqual(customer_obj.email.email, update_data['email']) def test_user_can_be_deleted(self): self.user.delete() self.assertEqual(self.user.id, None) customer = Customer.objects.filter(account=self.user.id) self.assertEqual(len(customer), 0)
def test_delete_account_avatar(self): image_obj = StringIO() image = Image.new( "RGBA", size=( 1, 1, ), ) image.save(image_obj, 'JPEG') image_obj.seek(0) image_file = File(image_obj, name='test_ifle') user = UserFactory() self.client.force_login(user) user.avatar = image_file user.save() url = reverse('api_accounts:current_user_detail') response = self.client.put(url, {'avatar': ''}, format='multipart') self.assertEqual(response.status_code, 200) updated_user = User.objects.get(pk=user.pk) self.assertTrue(bool(updated_user.avatar) is False)
class TransmittalActionTests(TestCase): def setUp(self): self.trs = create_transmittal() self.doc = self.trs.document self.category = self.doc.category self.url = reverse("document_detail", args=[ self.category.organisation.slug, self.category.slug, self.doc.document_key ]) self.user = UserFactory(name='User', password='******', is_superuser=True, category=self.category) self.client.login(username=self.user.email, password='******') def test_internal_user_cannot_ack_transmittal(self): self.assertIsNone(self.trs.ack_of_receipt_date) self.assertFalse(self.user.is_external) res = self.client.get(self.url) self.assertNotContains(res, ack_button) def test_external_user_can_ack_transmittal(self): self.user.is_external = True self.user.save() res = self.client.get(self.url) self.assertContains(res, ack_button) def test_transmittal_cannot_be_acked_twice(self): self.user.is_external = True self.trs.ack_receipt(self.user) self.assertIsNotNone(self.trs.ack_of_receipt_date) res = self.client.get(self.url) self.assertNotContains(res, ack_button)
def test_list_company_users(self): user1 = UserFactory() user2 = UserFactory() company = CompanyFactory() self.client.force_login(user1) user1.company = company user2.company = company user1.save() user2.save() response = self.client.get(reverse('api_accounts:company_users-list')) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.json()), 2) first_user = response.json()[0] expected_keys = [ 'first_name', 'last_name', 'id', 'email', ] self.assertItemsEqual(expected_keys, first_user.keys())
class CustomCustomPasswordResetFormTest(TestCase): """ Test our cutomised reset password form. These tests are a modified version of those found at django.contrib.auth.tests.testforms """ def setUp(self): self.user = UserFactory(email='*****@*****.**') def test_invalid_email(self): form = CustomPasswordResetForm({'email': 'not valid'}) self.assertFalse(form.is_valid()) self.assertEqual(form['email'].errors, [_('Please enter a valid email address.')]) def test_nonexistent_email(self): """ Test nonexistent email address. This should not fail because it would expose information about registered users. """ form = CustomPasswordResetForm({'email': '*****@*****.**'}) self.assertTrue(form.is_valid()) self.assertEqual(len(mail.outbox), 0) def test_cleaned_data(self): form = CustomPasswordResetForm({'email': self.user.email}) self.assertTrue(form.is_valid()) form.save(domain_override='example.com') self.assertEqual(form.cleaned_data['email'], self.user.email) self.assertEqual(len(mail.outbox), 1) def test_custom_email_subject(self): data = {'email': '*****@*****.**'} form = CustomPasswordResetForm(data) self.assertTrue(form.is_valid()) # Since we're not providing a request object, we must provide a # domain_override to prevent the save operation from failing in the # potential case where contrib.sites is not installed. Refs #16412. form.save(domain_override='example.com') self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, 'Reset your example.com password') def test_inactive_user(self): """ Test that inactive user cannot receive password reset email. """ self.user.is_active = False self.user.save() form = CustomPasswordResetForm({'email': self.user.email}) self.assertTrue(form.is_valid()) form.save() self.assertEqual(len(mail.outbox), 0) def test_unusable_password(self): data = {"email": "*****@*****.**"} form = CustomPasswordResetForm(data) self.assertTrue(form.is_valid()) self.user.set_unusable_password() self.user.save() form = CustomPasswordResetForm(data) # The form itself is valid, but no email is sent self.assertTrue(form.is_valid()) form.save() self.assertEqual(len(mail.outbox), 0)
class FeedAuthenticationTests(TestCase): def setUp(self): self.category = CategoryFactory() self.user = UserFactory( email='*****@*****.**', password='******', is_superuser=True, category=self.category ) self.url = reverse('feed_new_documents', args=[ self.category.organisation.slug, self.category.slug, ]) DocumentFactory( title='document 1', category=self.category, ) def test_authenticated_user(self): self.client.login(email=self.user.email, password='******') res = self.client.get(self.url) self.assertEqual(res.status_code, 200) def test_unsecure_unauthenticated_user(self): res = self.client.get(self.url, **{'wsgi.url_scheme': 'http'}) self.assertEqual(res.status_code, 403) def test_secure_unauthenticated_user(self): res = self.client.get(self.url, **{'wsgi.url_scheme': 'https'}) self.assertEqual(res.status_code, 401) self.assertTrue('WWW-AUTHENTICATE' in res) def test_login_with_invalid_credentials(self): res = self.client.get(self.url, **{ 'wsgi.url_scheme': 'https', 'HTTP_AUTHORIZATION': 'portenawak' }) self.assertEqual(res.status_code, 403) def test_login_unactive_user(self): self.user.is_active = False self.user.save() credentials = '{}:pass'.format(self.user.email).encode() b64_credentials = base64.b64encode(credentials).decode() full_credentials = 'Basic: {}'.format(b64_credentials) res = self.client.get(self.url, **{ 'wsgi.url_scheme': 'https', 'HTTP_AUTHORIZATION': full_credentials }) self.assertEqual(res.status_code, 401) def test_login_with_wrong_password(self): credentials = '{}:wrongpassword'.format(self.user.email).encode() b64_credentials = base64.b64encode(credentials).decode() full_credentials = 'Basic: {}'.format(b64_credentials) res = self.client.get(self.url, **{ 'wsgi.url_scheme': 'https', 'HTTP_AUTHORIZATION': full_credentials }) self.assertEqual(res.status_code, 401) def test_sucessfull_login_user(self): credentials = '{}:pass'.format(self.user.email).encode() b64_credentials = base64.b64encode(credentials).decode() full_credentials = 'Basic: {}'.format(b64_credentials) res = self.client.get(self.url, **{ 'wsgi.url_scheme': 'https', 'HTTP_AUTHORIZATION': full_credentials }) self.assertEqual(res.status_code, 200)
class NavigationTests(TestCase): """Navbar and navigation column shows different options depending on user's permissions.""" def setUp(self): category = CategoryFactory() self.user = UserFactory(name='User', password='******', category=category) self.url = reverse('category_document_list', args=[category.organisation.slug, category.slug]) self.dc_perms = Permission.objects.filter( codename__endswith='_document') self.create_url = reverse( 'document_create', args=[category.organisation.slug, category.slug]) def test_anonymous_navbar(self): res = self.client.get(self.url, follow=True) self.assertNotContains(res, 'href="/favorites/"') self.assertNotContains(res, '<a href="#nav-organisations"') self.assertNotContains(res, 'href="%s"' % self.create_url) self.assertNotContains(res, 'href="/admin/"') self.assertNotContains(res, '<a href="#nav-transmittals"') self.assertNotContains(res, '<a href="#nav-imports"') def test_authenticated_user_navbar(self): self.client.login(username=self.user.email, password='******') self.assertTrue(self.user.is_authenticated()) res = self.client.get(self.url, follow=True) self.assertContains(res, 'href="/favorites/"') self.assertContains(res, '<a href="#nav-organisations"') self.assertNotContains(res, 'href="%s"' % self.create_url) self.assertNotContains(res, 'href="/admin/"') self.assertNotContains(res, '<a href="#nav-transmittals"') self.assertNotContains(res, '<a href="#nav-imports"') def test_document_controller_navbar(self): self.user.user_permissions = self.dc_perms self.user.save() self.client.login(username=self.user.email, password='******') self.assertTrue(self.user.is_authenticated()) self.assertTrue(self.user.has_perm('documents.add_document')) res = self.client.get(self.url, follow=True) self.assertContains(res, 'href="/favorites/"') self.assertContains(res, '<a href="#nav-organisations"') self.assertContains(res, 'href="%s"' % self.create_url) self.assertNotContains(res, 'href="/admin/"') self.assertContains(res, '<a href="#nav-transmittals"') self.assertContains(res, '<a href="#nav-imports"') def test_admin_navbar(self): self.user.is_superuser = True self.user.save() self.client.login(username=self.user.email, password='******') self.assertTrue(self.user.is_authenticated()) res = self.client.get(self.url, follow=True) self.assertContains(res, 'href="/favorites/"') self.assertContains(res, '<a href="#nav-organisations"') self.assertContains(res, 'href="%s"' % self.create_url) self.assertContains(res, 'href="/admin/"') self.assertContains(res, '<a href="#nav-transmittals"') self.assertContains(res, '<a href="#nav-imports"')
class FeedAuthenticationTests(TestCase): def setUp(self): self.category = CategoryFactory() self.user = UserFactory(email='*****@*****.**', password='******', is_superuser=True, category=self.category) self.url = reverse('feed_new_documents', args=[ self.category.organisation.slug, self.category.slug, ]) DocumentFactory( title='document 1', category=self.category, ) def test_authenticated_user(self): self.client.login(email=self.user.email, password='******') res = self.client.get(self.url) self.assertEqual(res.status_code, 200) def test_unsecure_unauthenticated_user(self): res = self.client.get(self.url, **{'wsgi.url_scheme': 'http'}) self.assertEqual(res.status_code, 403) def test_secure_unauthenticated_user(self): res = self.client.get(self.url, **{'wsgi.url_scheme': 'https'}) self.assertEqual(res.status_code, 401) self.assertTrue('WWW-AUTHENTICATE' in res) def test_login_with_invalid_credentials(self): res = self.client.get( self.url, **{ 'wsgi.url_scheme': 'https', 'HTTP_AUTHORIZATION': 'portenawak' }) self.assertEqual(res.status_code, 403) def test_login_unactive_user(self): self.user.is_active = False self.user.save() credentials = '{}:pass'.format(self.user.email).encode() b64_credentials = base64.b64encode(credentials).decode() full_credentials = 'Basic: {}'.format(b64_credentials) res = self.client.get( self.url, **{ 'wsgi.url_scheme': 'https', 'HTTP_AUTHORIZATION': full_credentials }) self.assertEqual(res.status_code, 401) def test_login_with_wrong_password(self): credentials = '{}:wrongpassword'.format(self.user.email).encode() b64_credentials = base64.b64encode(credentials).decode() full_credentials = 'Basic: {}'.format(b64_credentials) res = self.client.get( self.url, **{ 'wsgi.url_scheme': 'https', 'HTTP_AUTHORIZATION': full_credentials }) self.assertEqual(res.status_code, 401) def test_sucessfull_login_user(self): credentials = '{}:pass'.format(self.user.email).encode() b64_credentials = base64.b64encode(credentials).decode() full_credentials = 'Basic: {}'.format(b64_credentials) res = self.client.get( self.url, **{ 'wsgi.url_scheme': 'https', 'HTTP_AUTHORIZATION': full_credentials }) self.assertEqual(res.status_code, 200)
class AppPurchaseViewTestCase(APITestCase): """Test app run via API request """ def setUp(self): self.user = UserFactory() # make sure enough coins to buy self.app = AppFactory(price=self.user.coins - 1, price_life=self.user.coins) self.login(self.user) def test_purchase_success(self): response = self.client.post('/api/purchase/', { 'app': self.app.id }) response.status_code.should.equal(status.HTTP_200_OK) response.data['success'].should.be.true UserApp.objects.filter(user=self.user, app=self.app).count().should.equal(1) user_app = UserApp.objects.get(user=self.user, app=self.app) (user_app.expires - timezone.now().date()).days.should.equal(30) self.User.objects.get(pk=self.user.id).coins.should.equal(1) def test_purchase_success_life(self): response = self.client.post('/api/purchase/', { 'app': self.app.id, 'kind': 'life', }) response.status_code.should.equal(status.HTTP_200_OK) user_app = UserApp.objects.get(user=self.user, app=self.app) user_app.expires.should.be.none self.User.objects.get(pk=self.user.id).coins.should.equal(0) def test_purchase_fail_not_enough_coins(self): UserApp.objects.filter(user=self.user, app=self.app).count().should.equal(0) self.app.price = self.user.coins + 1 self.app.save() response = self.client.post('/api/purchase/', { 'app': self.app.id }) response.status_code.should.equal(status.HTTP_402_PAYMENT_REQUIRED) self.error_messages(response).should.contain("You need more 1 coin(s) to buy this app.") self.error_message_codes(response).should.contain("NOT_ENOUGH_COINS") def test_purchase_duplicate_extend_usage_time(self): user_app = UserAppFactory(user=self.user, app=self.app) response = self.client.post('/api/purchase/', { 'app': self.app.id }) response.status_code.should.equal(status.HTTP_200_OK) response.data['success'].should.be.true expires = UserApp.objects.get(pk=user_app.pk).expires diff = expires - user_app.expires diff.days.should.equal(30) def init_expired(self): expired_date = timezone.now().date() - timedelta(days=1) self.user_app = UserAppFactory(user=self.user, app=self.app, expires=expired_date) def test_purchase_life_after_expired(self): self.init_expired() self.test_purchase_success_life() def test_purchase_expired_app_renew_expires(self): self.init_expired() self.test_purchase_success() def test_purchase_life_after_month(self): response = self.client.post('/api/purchase/', { 'app': self.app.id, }) response.status_code.should.equal(status.HTTP_200_OK) self.user.coins = self.app.price_life self.user.save() response = self.client.post('/api/purchase/', { 'app': self.app.id, 'kind': 'life', }) response.status_code.should.equal(status.HTTP_200_OK) response.data['success'].should.be.true user_app = UserApp.objects.get(user=self.user, app=self.app) user_app.expires.should.be.none self.User.objects.get(pk=self.user.id).coins.should.equal(self.app.price) def test_purchase_life_after_month_with_just_enough_coins(self): response = self.client.post('/api/purchase/', { 'app': self.app.id, }) response.status_code.should.equal(status.HTTP_200_OK) response = self.client.post('/api/purchase/', { 'app': self.app.id, 'kind': 'life', }) response.status_code.should.equal(status.HTTP_200_OK) self.User.objects.get(pk=self.user.id).coins.should.equal(0)
class Command(BaseCommand): help = "Popoulates databse with dummy data" def handle(self, *args, **options): if not User.objects.filter(username="******"): self.create_admin() else: self.admin = User.objects.get(username="******") print("admin user already exists") self.create_transactions() self.create_debt_loans() def create_admin(self): # Factory creates simple user, so ``is_staff`` is set later self.admin = UserFactory(username="******", password="******") self.admin.is_staff = True self.admin.is_superuser = True self.admin.save() print("admin user have been created successfully") def _get_last_month(self): "Returns random date in last month" today = timezone.now() first_month_day = today.replace(day=1) last_month = first_month_day - timedelta(days=1) return datetime(last_month.year, last_month.month, random.randint(1, 28), tzinfo=pytz.utc) def _get_this_year(self): "Returns random date in this year" today = timezone.now() return datetime(today.year, random.randint(1, today.month), random.randint(1, today.day), tzinfo=pytz.utc) def _get_all_time(self): "Returns random date" today = timezone.now() return datetime( random.randint(2000, today.year - 1), random.randint(1, 12), random.randint(1, 28), tzinfo=pytz.utc ) def create_transactions(self): categories = [Transaction.EXPENSE, Transaction.INCOME] # create now TransactionFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, ) # create for last month TransactionFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, created=factory.Sequence(lambda n: self._get_last_month()), ) # create for this year TransactionFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, created=factory.Sequence(lambda n: self._get_this_year()), ) # create for all time TransactionFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, created=factory.Sequence(lambda n: self._get_all_time()), ) print("Transactions for admin created") def create_debt_loans(self): categories = [DebtLoan.DEBT, DebtLoan.LOAN] # create now DebtLoanFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, ) # create for last month DebtLoanFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, created=factory.Sequence(lambda n: self._get_last_month()), ) # create for this year DebtLoanFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, created=factory.Sequence(lambda n: self._get_this_year()), ) # create for all time DebtLoanFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, created=factory.Sequence(lambda n: self._get_all_time()), ) print("DebtLoans for admin created")
class UserApiAclTests(APITestCase): def setUp(self): self.category = CategoryFactory() self.user = UserFactory(name='user', password='******', category=self.category) self.dc_perms = Permission.objects.filter( codename__endswith='_document') self.dc = UserFactory(name='dc', password='******', category=self.category) self.dc.user_permissions = self.dc_perms self.dc.save() self.url = reverse('user-list', args=[ self.category.organisation.slug, self.category.category_template.slug, ]) def test_anonymous_access_forbidden(self): """Anonymous cannot access the user api.""" res = self.client.get(self.url) self.assertEqual(res.status_code, 403) def test_simple_user_access_forbidden(self): """Simple users don't have access to the user api.""" self.client.login(username=self.user.email, password='******') res = self.client.get(self.url) self.assertEqual(res.status_code, 403) def test_dc_can_access_user_api(self): """Document controllers can access the user api.""" self.client.login(username=self.dc.email, password='******') res = self.client.get(self.url) self.assertEqual(res.status_code, 200) def test_dc_can_only_access_users_from_his_category(self): other_category = CategoryFactory() user = UserFactory(name='dc2', password='******', category=other_category) user.user_permissions = self.dc_perms user.save() self.client.login(username=user.email, password='******') res = self.client.get(self.url) self.assertEqual(res.status_code, 403) def test_dc_cannot_see_users_from_other_categories(self): other_category = CategoryFactory() user1 = UserFactory(name='toto', password='******', category=other_category) user1.save() user2 = UserFactory(name='tata', password='******', category=self.category) user2.save() self.client.login(username=self.dc.email, password='******') res = self.client.get(self.url) self.assertEqual(res.status_code, 200) self.assertTrue('tata' in res.content) self.assertTrue('toto' not in res.content)
def fake_db_for_tester(user): EXAMPLE_PIC_PATH = 'server/media/gallery/example_pic.jpg' first_image = shutil.copy( EXAMPLE_PIC_PATH, 'server/media/gallery/example_pic_%d.jpg' % user.id) source = shutil.copy(EXAMPLE_PIC_PATH, 'server/media/source/example_pic_%d.jpg' % user.id) source_image = SourceImage.objects.create(user=user, image=source[13:]) image = Image.objects.create(user=user, image=first_image[12:], source=source_image) emails = generate_fake_emails(50) if Category.objects.all().count() < 3: Category.objects.create(name='Sport') Category.objects.create(name='Dating') Category.objects.create(name='Food') categories = Category.objects.all() for email in emails: try: user = UserFactory( email=email, latitude=user.latitude, longitude=user.longitude, full_name=fake.name(), ) user.set_password('qweqweqwe') user.save() except IntegrityError: print('EMAIL SKIPPED') continue new_image = shutil.copy( EXAMPLE_PIC_PATH, 'server/media/gallery/example_pic_%d.jpg' % user.id) try: image = Image.objects.create(user=user, image=new_image[12:]) avatar = Avatar.objects.create(user=user, image=new_image[12:], source=source_image) except Exception as e: print(e) continue profile = ProfileFactory(user=user, avatar=avatar, age=random.randint(18, 55), name=fake.name()) post = PostFactory(profile=profile, category=random.choice(categories), looking_for=random.choice(GENDERS), text=fake.text()[:random.randint(0, 500)]) post = PostFactory(profile=profile, category=random.choice(categories), looking_for=random.choice(GENDERS), text=fake.text()[:random.randint(0, 500)], is_matches=True) images = Image.objects.all() asd = "1.jpeg" # str(uuid.uuid1()) post_image_path = copy_image( "server/media/gallery/%s" % image.file_name, "server/media/gallery_edited/%s" % asd) post_image_1 = PostImage.objects.create(image='gallery_edited/1.jpeg', source=source_image) post_image_2 = PostImage.objects.create(image='gallery_edited/1.jpeg', source=source_image) post_image_3 = PostImage.objects.create(image='gallery_edited/1.jpeg', source=source_image) post.photos.add(post_image_1) post.photos.add(post_image_2) post.photos.add(post_image_3) post.save()
class NavigationTests(TestCase): """Navbar and navigation column shows different options depending on user's permissions.""" def setUp(self): category = CategoryFactory() self.user = UserFactory(name='User', password='******', category=category) self.url = reverse('category_document_list', args=[ category.organisation.slug, category.slug ]) self.dc_perms = Permission.objects.filter(codename__endswith='_document') self.create_url = reverse('document_create', args=[ category.organisation.slug, category.slug ]) def test_anonymous_navbar(self): res = self.client.get(self.url, follow=True) self.assertNotContains(res, 'href="/favorites/"') self.assertNotContains(res, '<a href="#nav-organisations"') self.assertNotContains(res, 'href="%s"' % self.create_url) self.assertNotContains(res, 'href="/admin/"') self.assertNotContains(res, '<a href="#nav-transmittals"') self.assertNotContains(res, '<a href="#nav-imports"') def test_authenticated_user_navbar(self): self.client.login(username=self.user.email, password='******') self.assertTrue(self.user.is_authenticated()) res = self.client.get(self.url, follow=True) self.assertContains(res, 'href="/favorites/"') self.assertContains(res, '<a href="#nav-organisations"') self.assertNotContains(res, 'href="%s"' % self.create_url) self.assertNotContains(res, 'href="/admin/"') self.assertNotContains(res, '<a href="#nav-transmittals"') self.assertNotContains(res, '<a href="#nav-imports"') def test_document_controller_navbar(self): self.user.user_permissions = self.dc_perms self.user.save() self.client.login(username=self.user.email, password='******') self.assertTrue(self.user.is_authenticated()) self.assertTrue(self.user.has_perm('documents.add_document')) res = self.client.get(self.url, follow=True) self.assertContains(res, 'href="/favorites/"') self.assertContains(res, '<a href="#nav-organisations"') self.assertContains(res, 'href="%s"' % self.create_url) self.assertNotContains(res, 'href="/admin/"') self.assertContains(res, '<a href="#nav-transmittals"') self.assertContains(res, '<a href="#nav-imports"') def test_admin_navbar(self): self.user.is_superuser = True self.user.save() self.client.login(username=self.user.email, password='******') self.assertTrue(self.user.is_authenticated()) res = self.client.get(self.url, follow=True) self.assertContains(res, 'href="/favorites/"') self.assertContains(res, '<a href="#nav-organisations"') self.assertContains(res, 'href="%s"' % self.create_url) self.assertContains(res, 'href="/admin/"') self.assertContains(res, '<a href="#nav-transmittals"') self.assertContains(res, '<a href="#nav-imports"')
class Command(BaseCommand): help = "Popoulates databse with dummy data" def handle(self, *args, **options): if not User.objects.filter(username='******'): self.create_admin() else: self.admin = User.objects.get(username='******') print("admin user already exists") self.create_transactions() self.create_debt_loans() def create_admin(self): # Factory creates simple user, so ``is_staff`` is set later self.admin = UserFactory(username='******', password='******') self.admin.is_staff = True self.admin.is_superuser = True self.admin.save() print("admin user have been created successfully") def _get_last_month(self): "Returns random date in last month" today = timezone.now() first_month_day = today.replace(day=1) last_month = first_month_day - timedelta(days=1) return datetime(last_month.year, last_month.month, random.randint(1, 28), tzinfo=pytz.utc) def _get_this_year(self): "Returns random date in this year" today = timezone.now() return datetime(today.year, random.randint(1, today.month), random.randint(1, today.day), tzinfo=pytz.utc) def _get_all_time(self): "Returns random date" today = timezone.now() return datetime(random.randint(2000, today.year - 1), random.randint(1, 12), random.randint(1, 28), tzinfo=pytz.utc) def create_transactions(self): categories = [Transaction.EXPENSE, Transaction.INCOME] # create now TransactionFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, ) # create for last month TransactionFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, created=factory.Sequence(lambda n: self._get_last_month()), ) # create for this year TransactionFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, created=factory.Sequence(lambda n: self._get_this_year()), ) # create for all time TransactionFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, created=factory.Sequence(lambda n: self._get_all_time()), ) print("Transactions for admin created") def create_debt_loans(self): categories = [DebtLoan.DEBT, DebtLoan.LOAN] # create now DebtLoanFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, ) # create for last month DebtLoanFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, created=factory.Sequence(lambda n: self._get_last_month()), ) # create for this year DebtLoanFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, created=factory.Sequence(lambda n: self._get_this_year()), ) # create for all time DebtLoanFactory.create_batch( 5, amount=factory.Sequence(lambda n: random.randint(1, 10)), category=factory.Sequence(lambda n: random.choice(categories)), user=self.admin, created=factory.Sequence(lambda n: self._get_all_time()), ) print("DebtLoans for admin created")
class AppPurchaseViewTestCase(APITestCase): """Test app run via API request """ def setUp(self): self.user = UserFactory() # make sure enough coins to buy self.app = AppFactory(price=self.user.coins - 1, price_life=self.user.coins) self.login(self.user) def test_purchase_success(self): response = self.client.post('/api/purchase/', {'app': self.app.id}) response.status_code.should.equal(status.HTTP_200_OK) response.data['success'].should.be.true UserApp.objects.filter(user=self.user, app=self.app).count().should.equal(1) user_app = UserApp.objects.get(user=self.user, app=self.app) (user_app.expires - timezone.now().date()).days.should.equal(30) self.User.objects.get(pk=self.user.id).coins.should.equal(1) def test_purchase_success_life(self): response = self.client.post('/api/purchase/', { 'app': self.app.id, 'kind': 'life', }) response.status_code.should.equal(status.HTTP_200_OK) user_app = UserApp.objects.get(user=self.user, app=self.app) user_app.expires.should.be.none self.User.objects.get(pk=self.user.id).coins.should.equal(0) def test_purchase_fail_not_enough_coins(self): UserApp.objects.filter(user=self.user, app=self.app).count().should.equal(0) self.app.price = self.user.coins + 1 self.app.save() response = self.client.post('/api/purchase/', {'app': self.app.id}) response.status_code.should.equal(status.HTTP_402_PAYMENT_REQUIRED) self.error_messages(response).should.contain( "You need more 1 coin(s) to buy this app.") self.error_message_codes(response).should.contain("NOT_ENOUGH_COINS") def test_purchase_duplicate_extend_usage_time(self): user_app = UserAppFactory(user=self.user, app=self.app) response = self.client.post('/api/purchase/', {'app': self.app.id}) response.status_code.should.equal(status.HTTP_200_OK) response.data['success'].should.be.true expires = UserApp.objects.get(pk=user_app.pk).expires diff = expires - user_app.expires diff.days.should.equal(30) def init_expired(self): expired_date = timezone.now().date() - timedelta(days=1) self.user_app = UserAppFactory(user=self.user, app=self.app, expires=expired_date) def test_purchase_life_after_expired(self): self.init_expired() self.test_purchase_success_life() def test_purchase_expired_app_renew_expires(self): self.init_expired() self.test_purchase_success() def test_purchase_life_after_month(self): response = self.client.post('/api/purchase/', { 'app': self.app.id, }) response.status_code.should.equal(status.HTTP_200_OK) self.user.coins = self.app.price_life self.user.save() response = self.client.post('/api/purchase/', { 'app': self.app.id, 'kind': 'life', }) response.status_code.should.equal(status.HTTP_200_OK) response.data['success'].should.be.true user_app = UserApp.objects.get(user=self.user, app=self.app) user_app.expires.should.be.none self.User.objects.get(pk=self.user.id).coins.should.equal( self.app.price) def test_purchase_life_after_month_with_just_enough_coins(self): response = self.client.post('/api/purchase/', { 'app': self.app.id, }) response.status_code.should.equal(status.HTTP_200_OK) response = self.client.post('/api/purchase/', { 'app': self.app.id, 'kind': 'life', }) response.status_code.should.equal(status.HTTP_200_OK) self.User.objects.get(pk=self.user.id).coins.should.equal(0)