Esempio n. 1
0
class TestRegistrationProcessor(unittest.TestCase):
    def prepare_organization(self):
        self.paid_organization = Organization(
            name='test_org_for_paid_account',
            sector='PublicHealth',
            address='add',
            city='Pune',
            country='India',
            zipcode='411006',
            account_type='Pro SMS',
            org_id=OrganizationIdCreator().generateId())

        self.trial_organization = Organization(
            name='test_org_for_trial_account',
            sector='PublicHealth',
            address='add',
            city='Pune',
            country='India',
            zipcode='411006',
            account_type='Basic',
            org_id=OrganizationIdCreator().generateId())
        self.paid_organization.save()
        self.trial_organization.save()

    def setUp(self):
        set_email_settings()
        User.objects.filter(username='******').delete()
        User.objects.filter(username='******').delete()
        Organization.objects.filter(name='test_org_for_paid_account').delete()
        Organization.objects.filter(name='test_org_for_trial_account').delete()

        self.user1 = RegistrationProfile.objects.create_inactive_user(
            username='******',
            email='*****@*****.**',
            password='******',
            site=Site(),
            send_email=False)
        self.user2 = RegistrationProfile.objects.create_inactive_user(
            username='******',
            email='*****@*****.**',
            password='******',
            site=Site(),
            send_email=False)

        self.user1.first_name = 'first_name1 last_name1'

        self.user2.first_name = 'first_name2 last_name2'

        self.user1.save()
        self.user2.save()

        self.prepare_organization()

        NGOUserProfile(user=self.user1,
                       title='Mr.',
                       org_id=self.paid_organization.org_id).save()
        NGOUserProfile(user=self.user2,
                       title='Ms.',
                       org_id=self.trial_organization.org_id).save()
        self.processor = RegistrationBackend()

    def tearDown(self):
        self.user1.delete()
        self.user2.delete()
        self.paid_organization.delete()
        self.trial_organization.delete()

    def test_should_get_the_correct_registration_processor(self):

        self.assertTrue(
            isinstance(
                self.processor.get_registration_processor(
                    self.trial_organization),
                TrialAccountRegistrationProcessor))

        self.assertTrue(
            isinstance(
                self.processor.get_registration_processor(
                    self.paid_organization), PaidAccountRegistrationProcessor))

    def test_should_process_registration_data_for_paid_acccount_in_english(
            self):
        with patch.object(ProSMSAccountRegistrationProcessor,
                          '_get_invoice_total') as get_invoice_total_patch:
            get_invoice_total_patch.return_value = PRO_SMS_MONTHLY_PRICING, '1 month'
            processor = self.processor.get_registration_processor(
                self.paid_organization)

            site = Site(domain='test', name='test_site')
            kwargs = dict(invoice_period='', preferred_payment='')

            processor.process(self.user1, site, 'en', kwargs)

            emails = [mail.outbox.pop() for i in range(len(mail.outbox))]

            self.assertEqual(1, len(emails))
            sent_email = emails[0]

            self.assertEqual("html", sent_email.content_subtype)
            self.assertEqual(settings.EMAIL_HOST_USER, sent_email.from_email)
            self.assertEqual(['*****@*****.**'], sent_email.to)
            self.assertEqual([settings.HNI_SUPPORT_EMAIL_ID], sent_email.bcc)

            self.assertEqual(
                render_to_string(
                    'registration/activation_email_subject_in_en.txt'),
                sent_email.subject)
            ctx_dict = {
                'activation_key':
                RegistrationProfile.objects.get(
                    user=self.user1).activation_key,
                'expiration_days':
                settings.ACCOUNT_ACTIVATION_DAYS,
                'site':
                site,
                'username':
                self.user1.first_name,
                'invoice_total':
                PRO_SMS_MONTHLY_PRICING,
                'period':
                '1 month'
            }
            self.assertEqual(
                render_to_string(
                    'registration/pro_sms_activation_email_in_en.html',
                    ctx_dict), sent_email.body)

            payment_detail = PaymentDetails.objects.filter(
                organization=self.paid_organization)
            self.assertTrue(is_not_empty(payment_detail))
            payment_detail.delete()

    def test_should_process_registration_data_for_trial_acccount_in_english(
            self):
        processor = self.processor.get_registration_processor(
            self.trial_organization)

        site = Site(domain='test', name='test_site')
        kwargs = dict(invoice_period='', preferred_payment='')

        processor.process(self.user2, site, 'en', kwargs)

        emails = [mail.outbox.pop() for i in range(len(mail.outbox))]

        self.assertEqual(1, len(emails))
        sent_email = emails[0]

        self.assertEqual("html", sent_email.content_subtype)
        self.assertEqual(settings.EMAIL_HOST_USER, sent_email.from_email)
        self.assertEqual(['*****@*****.**'], sent_email.to)
        self.assertEqual([settings.HNI_SUPPORT_EMAIL_ID], sent_email.bcc)

        ctx_dict = {
            'activation_key':
            RegistrationProfile.objects.get(user=self.user2).activation_key,
            'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
            'site': site,
            'username': self.user2.first_name
        }
        self.assertEqual(
            render_to_string(
                'registration/activation_email_subject_for_trial_account_in_en.txt'
            ), sent_email.subject)
        self.assertEqual(
            render_to_string(
                'registration/activation_email_for_trial_account_in_en.html',
                ctx_dict), sent_email.body)

    def test_should_process_registration_data_for_paid_acccount_in_french(
            self):
        with patch.object(ProSMSAccountRegistrationProcessor,
                          '_get_invoice_total') as get_invoice_total_patch:
            get_invoice_total_patch.return_value = PRO_SMS_MONTHLY_PRICING, '1 month'
            processor = self.processor.get_registration_processor(
                self.paid_organization)

            site = Site(domain='test', name='test_site')
            kwargs = dict(invoice_period='', preferred_payment='')

            processor.process(self.user1, site, 'fr', kwargs)

            emails = [mail.outbox.pop() for i in range(len(mail.outbox))]

            self.assertEqual(1, len(emails))
            sent_email = emails[0]

            self.assertEqual("html", sent_email.content_subtype)
            self.assertEqual(settings.EMAIL_HOST_USER, sent_email.from_email)
            self.assertEqual(['*****@*****.**'], sent_email.to)
            self.assertEqual([settings.HNI_SUPPORT_EMAIL_ID], sent_email.bcc)

            self.assertEqual(
                render_to_string(
                    'registration/activation_email_subject_in_fr.txt'),
                sent_email.subject)
            ctx_dict = {
                'activation_key':
                RegistrationProfile.objects.get(
                    user=self.user1).activation_key,
                'expiration_days':
                settings.ACCOUNT_ACTIVATION_DAYS,
                'site':
                site,
                'username':
                self.user1.first_name,
                'invoice_total':
                PRO_SMS_MONTHLY_PRICING,
                'period':
                '1 month'
            }
            self.assertEqual(
                render_to_string(
                    'registration/pro_sms_activation_email_in_fr.html',
                    ctx_dict), sent_email.body)

            payment_detail = PaymentDetails.objects.filter(
                organization=self.paid_organization)
            self.assertTrue(is_not_empty(payment_detail))
            payment_detail.delete()

    def test_should_process_registration_data_for_trial_acccount_in_french(
            self):
        processor = self.processor.get_registration_processor(
            self.trial_organization)

        site = Site(domain='test', name='test_site')
        kwargs = dict(invoice_period='', preferred_payment='')

        processor.process(self.user2, site, 'fr', kwargs)

        emails = [mail.outbox.pop() for i in range(len(mail.outbox))]

        self.assertEqual(1, len(emails))
        sent_email = emails[0]

        self.assertEqual("html", sent_email.content_subtype)
        self.assertEqual(settings.EMAIL_HOST_USER, sent_email.from_email)
        self.assertEqual(['*****@*****.**'], sent_email.to)
        self.assertEqual([settings.HNI_SUPPORT_EMAIL_ID], sent_email.bcc)

        ctx_dict = {
            'activation_key':
            RegistrationProfile.objects.get(user=self.user2).activation_key,
            'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
            'site': site,
            'username': self.user2.first_name
        }
        self.assertEqual(
            render_to_string(
                'registration/activation_email_subject_for_trial_account_in_fr.txt'
            ), sent_email.subject)
        self.assertEqual(
            render_to_string(
                'registration/activation_email_for_trial_account_in_fr.html',
                ctx_dict), sent_email.body)
class TestPostActivationEvents(unittest.TestCase):
    def setUp(self):
        self.username = '******'
        self.paid_user, _ = User.objects.get_or_create(username=self.username,
                                                       email=self.username,
                                                       password='******')
        self.paid_user.save()
        self.paid_org = Organization(name='test_org_for_correct_active_date',
                                     sector='PublicHealth',
                                     address='add',
                                     city='city',
                                     country=Country('MG'),
                                     zipcode='10000',
                                     active_date=None)
        self.paid_org.save()
        self.mobile_number = "1233"
        self.paid_user_profile = NGOUserProfile(
            user=self.paid_user,
            title='Mr.',
            org_id=self.paid_org.org_id,
            mobile_phone=self.mobile_number)
        self.paid_user_profile.save()

        self.trial_username = '******'
        self.trial_user, _ = User.objects.get_or_create(
            username=self.trial_username,
            email=self.trial_username,
            password='******')
        self.trial_user.save()

        self.trial_org = Organization(name='trial_org',
                                      sector='PublicHealth',
                                      address='add',
                                      city='city',
                                      country=Country('MG'),
                                      zipcode='10000',
                                      active_date=None,
                                      account_type='Basic',
                                      org_id='test')
        self.trial_org.save()

        self.trial_mobile_number = "12445"
        self.trial_user_profile = NGOUserProfile(
            user=self.trial_user,
            title='Mr.',
            org_id=self.trial_org.org_id,
            mobile_phone=self.trial_mobile_number)
        self.trial_user_profile.save()

        self.patcher1 = patch(
            'datawinners.accountmanagement.post_activation_events.get_entity_count_for_type'
        )
        self.get_all_entities_mock = self.patcher1.start()

        self.patcher2 = patch(
            'datawinners.accountmanagement.post_activation_events.create_contact'
        )
        self.create_entity_mock = self.patcher2.start()

    def test_active_organization_with_should_active_date_is_none_save_active_date(
            self):
        active_organization(org=self.paid_org)
        self.assertIsNotNone(
            Organization.objects.get(org_id=self.paid_org.org_id).active_date)
        self.assertEqual(
            Organization.objects.get(
                org_id=self.paid_org.org_id).active_date.microsecond, 0)

    def test_should_make_datasender_entity_for_paid_account(self):
        mock_manager = Mock(spec=DatabaseManager)
        entity_mock = Mock(spec=Contact)
        entity_mock.type_path = [REPORTER]
        self.get_all_entities_mock.return_value = 1
        self.create_entity_mock = entity_mock

        make_user_as_a_datasender(mock_manager, self.paid_org, self.username,
                                  self.mobile_number)

        entity_mock.add_data.assert_called_once()

    def test_should_make_datasender_entity_and_datasender_on_trial_account_for_trial_account(
            self):
        mock_manager = Mock(spec=DatabaseManager)
        entity_mock = Mock(spec=Entity)
        entity_mock.type_path = [REPORTER]
        self.get_all_entities_mock.return_value = 1
        self.create_entity_mock = entity_mock

        make_user_as_a_datasender(mock_manager, self.trial_org,
                                  self.trial_username,
                                  self.trial_mobile_number)

        entity_mock.add_data.assert_called_once()

        data_senders_on_trial_account = DataSenderOnTrialAccount.objects.filter(
            organization=self.trial_org)
        self.assertEqual(1, len(data_senders_on_trial_account))
        self.assertEqual(self.trial_mobile_number,
                         data_senders_on_trial_account[0].mobile_number)
        self.assertEqual(self.trial_org,
                         data_senders_on_trial_account[0].organization)

    def tearDown(self):
        self.paid_user_profile.delete()
        self.paid_org.delete()
        self.paid_user.delete()

        self.trial_user_profile.delete()
        self.trial_org.delete()
        self.trial_user.delete()
        DataSenderOnTrialAccount.objects.filter(
            organization=self.trial_org).delete()

        self.patcher1.stop()
        self.patcher2.stop()
class TestDeactivateExpiredAccount(unittest.TestCase):
    def prepare_organization(self):
        self.expired_organization_out_of_one_year = Organization(
            name='test_org_for_expired_organization_out_of_one_year',
            sector='PublicHealth',
            address='add',
            city='xian',
            country='china',
            zipcode='10000',
            account_type='Basic',
            active_date=datetime.today() -
            relativedelta(years=settings.TRIAL_PERIOD_IN_YEAR, days=1),
            org_id=OrganizationIdCreator().generateId())
        self.paid_organization = Organization(
            name='test_org_for_paid_account',
            sector='PublicHealth',
            address='add',
            city='xian',
            country='china',
            zipcode='10000',
            account_type='Pro SMS',
            active_date=datetime(2011, 8, 15),
            org_id=OrganizationIdCreator().generateId())
        self.unexpired_organization = Organization(
            name='test_org_for_unexpired_account',
            sector='PublicHealth',
            address='add',
            city='xian',
            country='china',
            zipcode='10000',
            account_type='Basic',
            active_date=datetime.today(),
            org_id=OrganizationIdCreator().generateId())
        self.expired_organization_of_one_year = Organization(
            name='test_org_for_expired_organization_of_one_year',
            sector='PublicHealth',
            address='add',
            city='xian',
            country='china',
            zipcode='10000',
            account_type='Basic',
            active_date=datetime.today() -
            relativedelta(years=settings.TRIAL_PERIOD_IN_YEAR),
            org_id=OrganizationIdCreator().generateId())
        self.expired_organization_of_one_year.save()
        self.expired_organization_out_of_one_year.save()
        self.unexpired_organization.save()
        self.paid_organization.save()

    def setUp(self):
        try:
            User.objects.get(username='******').delete()
            User.objects.get(username='******').delete()
            Organization.objects.get(
                name='test_org_for_expired_organization_out_of_one_years'
            ).delete()
            Organization.objects.get(name='test_org_for_paid_account').delete()
            Organization.objects.get(
                name='test_org_for_unexpired_account').delete()
            Organization.objects.get(
                name='test_org_for_expired_organization_of_one_year').delete()
        except:
            pass
        self.user1 = User(username='******',
                          email='*****@*****.**',
                          password='******',
                          first_name='first_name1 last_name1')
        self.user2 = User(username='******',
                          email='*****@*****.**',
                          password='******',
                          first_name='first_name2 last_name2')
        self.user1.set_password('expired')
        self.user2.set_password('expired')
        self.user1.save()
        self.user2.save()

        self.prepare_organization()

        NGOUserProfile(
            user=self.user1,
            title='Mr.',
            org_id=self.expired_organization_of_one_year.org_id).save()
        NGOUserProfile(
            user=self.user2,
            title='Ms.',
            org_id=self.expired_organization_of_one_year.org_id).save()

    def tearDown(self):
        self.user1.delete()
        self.user2.delete()
        self.expired_organization_of_one_year.delete()
        self.expired_organization_out_of_one_year.delete()
        self.unexpired_organization.delete()
        self.paid_organization.delete()

    def test_get_organization_creator_should_return_first_user_of_organization(
            self):
        self.assertEqual(get_creator(self.expired_organization_of_one_year),
                         self.user1)

    def test_should_not_contain_unexpired_organizations(self):
        organizations = get_expired_trial_organizations_without_deactivate_email_sent(
        )
        self.assertIn(self.expired_organization_of_one_year, organizations)
        self.assertNotIn(self.unexpired_organization, organizations)

    def test_should_not_contain_paid_organizations(self):
        organizations = get_expired_trial_organizations_without_deactivate_email_sent(
        )
        self.assertNotIn(self.paid_organization, organizations)

    def test_should_not_contain_organization_active_date_out_of_one_year(self):
        organizations = get_expired_trial_organizations_without_deactivate_email_sent(
        )
        self.assertIn(self.expired_organization_out_of_one_year, organizations)

    def test_get_user_list_should_return_organization_creator(self):
        creators = get_creators([self.expired_organization_of_one_year])
        self.assertIn(self.user1, creators)

    def test_create_email_should_get_email_with_html_content(self):
        msg1 = create_email(self.user1)
        msg2 = create_email(self.user2)
        self.assertEqual(msg1.content_subtype, 'html')
        self.assertEqual(msg2.content_subtype, 'html')

    def test_create_email_should_get_email_with_right_subject(self):
        msg1 = create_email(self.user1)
        msg2 = create_email(self.user2)
        self.assertEqual(msg1.subject, 'Account Expired')
        self.assertEqual(msg2.subject, 'Account Expired')

    def test_create_email_should_get_email_contain_right_user_name(self):
        msg1 = create_email(self.user1)
        msg2 = create_email(self.user2)
        self.assertIn(self.user1.first_name, msg1.body)
        self.assertIn(self.user2.first_name, msg2.body)

    def test_create_email_should_get_right_recipient(self):
        msg1 = create_email(self.user1)
        msg2 = create_email(self.user2)
        self.assertIn(self.user1.email, msg1.to)
        self.assertIn(self.user2.email, msg2.to)

    def test_deactivate_email_sent(self):
        settings.EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
        settings.EMAIL_FILE_PATH = 'email'
        send_deactivate_email()
        list = dircache.listdir('email')
        emails = ''
        for email in list:
            emails += open('email/' + email, 'r').read()
            os.remove('email/' + email)
        self.assertIn('From: ' + settings.EMAIL_HOST_USER, emails)
        self.assertIn('To: [email protected]', emails)
        self.assertIn('Subject: Account Expired', emails)
        self.assertIn('Hello first_name1 last_name1', emails)
        self.assertNotIn('To: [email protected]', emails)

    def test_deactivate_email_only_sent_once(self):
        organisation_list = get_expired_trial_organizations_without_deactivate_email_sent(
        )
        number_before = len(organisation_list)
        self.assertIsNot(0, number_before)

        send_deactivate_email()
        organisation_list = get_expired_trial_organizations_without_deactivate_email_sent(
        )
        number_after = len(organisation_list)
        self.assertLess(number_after, number_before)

    def test_paid_account_not_in_all_expired_account(self):
        organizations = get_expired_trial_organizations()
        self.assertNotIn(self.paid_organization, organizations)

    def test_unexpired_account_not_in_expired_account(self):
        organizations = get_expired_trial_organizations()
        self.assertNotIn(self.unexpired_organization, organizations)

    def test_should_deactivate_related_users_when_deactivating_organization(
            self):
        organization = self.expired_organization_of_one_year
        for user in organization.get_related_users():
            self.assertTrue(user.is_active)
        organization.deactivate()
        for user in organization.get_related_users():
            self.assertFalse(user.is_active)