Пример #1
0
    def test_get_context_data(self, mock_get_context_data):

        company = CompanyGenerator().generate()
        customer = company.get_customer()

        # FIXME: somehow, settings can be modified
        plans = copy.deepcopy(settings.DJSTRIPE_PLANS)
        if 'unsubscribable' in plans['test']:
            del plans['test']['unsubscribable']
        mock_get_context_data.return_value = dict(customer=customer,
                                                  PAYMENT_PLANS=plans)

        with mock.patch.object(customer.subscriber,
                               'validate_plan',
                               return_value=(True, [])):
            context = self.view.get_context_data()
            self.assertNotIn('unsubscribable',
                             context['PAYMENT_PLANS']['test'])

        with mock.patch.object(customer.subscriber,
                               'validate_plan',
                               return_value=(False, [])):
            context = self.view.get_context_data()
            self.assertIn('unsubscribable', context['PAYMENT_PLANS']['test'])
            self.assertTrue(context['PAYMENT_PLANS']['test']['unsubscribable'])
Пример #2
0
    def test_get(self):

        company = CompanyGenerator().generate()
        customer = company.get_customer()
        self.assertEqual(customer.subscriber, company)
        operator = OperatorGenerator().generate(company=company)

        view_url = reverse('djstripe:confirm',
                           args=[operator.company_id, 'test'])
        subscribe_url = reverse('djstripe:subscribe', args=[company.pk])

        req = self.factory.get(view_url)
        req.user = operator.user
        req.resolver_match = resolve(view_url)
        view_kwargs = dict(company_id=operator.company_id)
        self.view.request = req

        res = self.view.get(req, **view_kwargs)
        self.assertEqual(res.status_code, 302)
        self.assertEqual(res.url, subscribe_url)

        # test success
        self.view.kwargs = dict(plan='test')

        res = self.view.get(req, **view_kwargs)
        self.assertEqual(res.status_code, 200)

        # test already subscribed
        self.add_subscription(company)

        res = self.view.get(req, **view_kwargs)
        self.assertEqual(res.status_code, 302)
        self.assertEqual(res.url, subscribe_url)
Пример #3
0
    def test_split_shares(self):
        """
        share split leaves value, percent unchanged but
        increases share count per shareholder
        """
        # test data
        company = CompanyGenerator().generate(share_count=1000)
        OperatorGenerator().generate(company=company)
        shareholders, security = ComplexShareholderConstellationGenerator()\
            .generate(company=company)

        data = {
            'execute_at': datetime.datetime.now(),
            'dividend': 3,
            'divisor': 7,
            'comment': "Some random comment",
            'security': security,
        }
        multiplier = float(data['divisor']) / float(data['dividend'])
        company_share_count = company.share_count

        # record initial shareholder asset status
        assets = {}
        for shareholder in shareholders:
            assets.update({
                shareholder.pk: {
                    'count': shareholder.share_count(),
                    'value': shareholder.share_value(),
                    'percent': shareholder.share_percent()
                }
            })

        # run
        company.split_shares(data)

        # asserts by checking overall shareholder situation
        # means each shareholder should have now more shares but some
        # overall stock value

        for shareholder in shareholders:
            self.assertEqual(
                shareholder.share_count(),
                round(assets[shareholder.pk]['count'] * multiplier))
            self.assertEqual(round(shareholder.share_value()),
                             assets[shareholder.pk]['value'])
            self.assertEqual(round(float(shareholder.share_percent()), 2),
                             float(assets[shareholder.pk]['percent']))

        self.assertEqual(company.share_count,
                         round(company_share_count * multiplier))

        self.assertEquals(len(mail.outbox), 1)
        self.assertEquals(
            mail.outbox[0].subject,
            u"Ihre Liste gespaltener Aktienanrechte f\xfcr das Unternehmen "
            u"'{}'".format(company.name))
Пример #4
0
    def _prepare_split_scenario(self):
        company = CompanyGenerator().generate()
        security = SecurityGenerator().generate(company=company)
        cshareholder = ShareholderGenerator().generate(company=company)
        shareholder1 = ShareholderGenerator().generate(company=company)
        shareholder2 = ShareholderGenerator().generate(company=company)
        shareholder3 = ShareholderGenerator().generate(company=company)
        shareholder4 = ShareholderGenerator().generate(company=company)
        PositionGenerator().generate(buyer=cshareholder,
                                     count=10000,
                                     value=1000,
                                     security=security,
                                     seller=None)
        p1 = PositionGenerator().generate(buyer=shareholder1,
                                          count=100,
                                          value=20,
                                          seller=cshareholder,
                                          security=security)
        p2 = PositionGenerator().generate(buyer=shareholder2,
                                          count=200,
                                          value=40,
                                          seller=cshareholder,
                                          security=security)
        p3 = PositionGenerator().generate(buyer=shareholder3,
                                          count=900,
                                          value=60,
                                          seller=cshareholder,
                                          security=security)
        p4 = PositionGenerator().generate(buyer=cshareholder,
                                          count=600,
                                          value=80,
                                          seller=shareholder3,
                                          security=security)
        PositionGenerator().generate(buyer=cshareholder,
                                     count=1000,
                                     value=1000,
                                     security=security,
                                     seller=None)
        company.share_count = 11000
        company.save()

        return dict(company=company,
                    cshareholder=cshareholder,
                    shareholder1=shareholder1,
                    shareholder2=shareholder2,
                    shareholder3=shareholder3,
                    shareholder4=shareholder4,
                    p1=p1,
                    p2=p2,
                    p3=p3,
                    p4=p4,
                    security=security)
Пример #5
0
    def test_send_statement_letter(self, mock_upload_document):

        self.assertFalse(send_statement_letter(0))

        company = CompanyGenerator().generate()
        report = mommy.make(ShareholderStatementReport, company=company)
        statement = mommy.make(ShareholderStatement, report=report,
                               pdf_file='example.pdf')

        # disabled for this company
        company.send_shareholder_statement_via_letter_enabled = False
        company.save()
        self.assertFalse(send_statement_letter(statement.pk))

        # no postal address
        self.assertFalse(send_statement_letter(statement.pk))

        # add postal address
        self.assertFalse(statement.user.userprofile.has_address)
        self.add_address(statement.user.userprofile)
        self.assertTrue(statement.user.userprofile.has_address)

        company.send_shareholder_statement_via_letter_enabled = True
        company.save()
        send_statement_letter(statement.pk)
        mock_upload_document.assert_called_once()

        statement.refresh_from_db()
        self.assertIsNotNone(statement.letter_sent_at)
Пример #6
0
    def test_post(self, mock_sync_subscriber):

        company = CompanyGenerator().generate()
        customer = company.get_customer()

        url = reverse('djstripe:sync_history', args=[company.pk])
        req = self.factory.post(url)
        req.resolver_match = resolve(url)

        mock_sync_subscriber.return_value = customer

        with mock.patch('company.views.render') as mock_render:
            self.view.post(req)
            mock_render.assert_called_with(req, self.view.template_name,
                                           dict(customer=customer))
Пример #7
0
    def test_transactions_xls(self):
        """ test download of all transactions data
        /company/3/download/transactions?from=2017-01-12T23:00:00.000Z&to=2017-01-13T23:00:00.000Z&security=56
        """
        company = CompanyGenerator().generate()
        security = SecurityGenerator().generate(company=company)
        # run test
        response = self.client.get(
            reverse('reports:transactions_xls',
                    kwargs={"company_id": company.id}), {
                        'to': '2017-01-12T23:00:00.000Z',
                        'from': '2011-01-12T23:00:00.000Z',
                        'security': security.pk
                    })

        # not logged in user
        self.assertEqual(response.status_code, 302)

        # login and retest
        user = UserGenerator().generate()
        self.client.force_login(user)

        response = self.client.get(
            reverse('reports:transactions_xls',
                    kwargs={"company_id": company.id}), {
                        'to': '2017-01-12T23:00:00.000Z',
                        'from': '2011-01-12T23:00:00.000Z',
                        'security': security.pk
                    })

        # assert response code
        self.assertEqual(response.status_code, 403)
Пример #8
0
    def test_send_statement_letters(self, mock_send_statement_letter):
        send_statement_letters()
        mock_send_statement_letter.assert_not_called()

        # add shareholder statements & report
        company = CompanyGenerator().generate()
        report = mommy.make(ShareholderStatementReport, company=company,
                            report_date=now().date())

        statements = mommy.make(ShareholderStatement, report=report,
                                pdf_file='example.pdf', _quantity=2)

        # no postal address
        send_statement_letters()
        mock_send_statement_letter.assert_not_called()

        # add postal address for one user
        user_profile = statements[0].user.userprofile
        self.assertFalse(user_profile.has_address)

        self.add_address(user_profile)

        self.assertTrue(user_profile.has_address)

        send_statement_letters()

        mock_send_statement_letter.assert_called_once()
Пример #9
0
 def setUp(self):
     super(CompanySerializerTestCase, self).setUp()
     self.instance = CompanyGenerator().generate()
     CompanyShareholderGenerator().generate(company=self.instance)
     url = reverse('company-detail', kwargs={'pk': self.instance.id})
     self.request = RequestFactory().get(url)
     self.serializer = CompanySerializer()
Пример #10
0
    def test_add_operator_foreign_company(self):
        operator = OperatorGenerator().generate()
        user = operator.user
        company = CompanyGenerator().generate()
        user2 = UserGenerator().generate()

        logged_in = self.client.login(username=user.username, password='******')
        self.assertTrue(logged_in)

        data = {
            "company":
            "http://{}/services/rest/company/"
            "{}".format(self.site.domain, company.pk),
            u"user": {
                'email': user2.email
            }
        }

        self.assertFalse(user2.operator_set.filter(company=company).exists())

        response = self.client.post(
            '/services/rest/operators', data, **{
                'HTTP_AUTHORIZATION': 'Token {}'.format(user.auth_token.key),
                'format': 'json'
            })

        self.assertEqual(response.status_code, 400)
        self.assertTrue('company' in response.content)
Пример #11
0
 def test_prepare_report(self):
     """ create report obj and set eta """
     company = CompanyGenerator().generate()
     report = _prepare_report(company, 'captable', 'share_count', 'PDF')
     self.assertIsNotNone(report.eta)
     self.assertIsNotNone(report.file_type)
     self.assertIsNotNone(report.report_type)
Пример #12
0
    def test_share_value(self):
        """
        share value is last trated price
        """
        company = CompanyGenerator().generate(share_count=1000000)
        security = SecurityGenerator().generate(company=company)
        sc = ShareholderGenerator().generate(company=company)
        s1 = ShareholderGenerator().generate(company=company)
        now = datetime.datetime.now()

        PositionGenerator().generate(buyer=sc,
                                     count=1000000,
                                     value=1,
                                     security=security,
                                     bought_at=now -
                                     datetime.timedelta(days=11))
        p = PositionGenerator().generate(buyer=s1,
                                         seller=sc,
                                         count=500000,
                                         value=100,
                                         security=security,
                                         bought_at=now -
                                         datetime.timedelta(days=10))
        p.value = None
        p.save()

        self.assertEqual(s1.share_value(), Decimal('500000.0000'))
Пример #13
0
    def test_send_statement_report_operator_notify(self, mock_mail_admins,
                                                   mock_email_message_send,
                                                   mock_email_multi_send):
        company = CompanyGenerator().generate()
        mommy.make(ShareholderStatementReport, company=company,
                   report_date=now().date())

        send_statement_report_operator_notify()
        mock_mail_admins.assert_called()
        mock_mail_admins.reset_mock()

        OperatorGenerator().generate(company=company)

        with self.settings(EMAIL_BACKEND='dummy'):
            send_statement_report_operator_notify()
            mock_email_multi_send.assert_called()

        djrill_settings = {
            'EMAIL_BACKEND': 'djrill',
            'MANDRILL_SHAREHOLDER_STATEMENT_REPORT'
            '_OPERATOR_NOTIFY_TEMPLATE': 'foo'
        }
        with self.settings(**djrill_settings):
            send_statement_report_operator_notify()
            mock_email_message_send.assert_called()

        mock_email_multi_send.return_value = 0
        send_statement_report_operator_notify()
        mock_mail_admins.assert_called()
Пример #14
0
    def test_save_number_segments(self):
        company = CompanyGenerator().generate()
        operator = OperatorGenerator().generate(company=company)
        security = SecurityGenerator().generate(company=company)
        url = reverse('security-detail', kwargs={'pk': security.id})
        request = self.factory.get(url)

        data = SecuritySerializer(security, context={'request': request}).data
        data.update({'number_segments': '1,2,3,4,8-10'})

        self.client.force_authenticate(user=operator.user)

        res = self.client.put(url, data=data)

        security = Security.objects.get(id=security.id)
        self.assertEqual(security.number_segments, [u'1-4', u'8-10'])

        data.update({'number_segments': '1,2,3,4,4,,8-10'})

        res = self.client.put(url, data=data)

        self.assertEqual(res.status_code, 200)

        security = Security.objects.get(id=security.id)
        self.assertEqual(security.number_segments, [u'1-4', u'8-10'])
Пример #15
0
    def test_prerender_reports(self, mock_xls, mock_pdf,
                               mock_assembly_participation_xls):
        """ render every night the reports for all corps """
        # corps not needing a report = noise
        CompanyGenerator().generate()
        ReportGenerator().generate()

        prerender_reports()

        company = self.shs[0].company
        pdf_report = company.report_set.filter(file_type='PDF',
                                               report_type='captable').last()
        xls_ass_report = company.report_set.filter(
            file_type='XLS', report_type='assembly_participation').last()
        xls_report = company.report_set.filter(file_type='XLS',
                                               report_type='captable').last()
        self.assertEqual(mock_pdf.call_count, 14)
        mock_pdf.assert_called_with(
            args=[company.pk, pdf_report.pk],
            kwargs={'ordering': pdf_report.order_by})
        self.assertEqual(mock_xls.call_count, 14)
        mock_xls.assert_called_with(
            args=[company.pk, xls_report.pk],
            kwargs={'ordering': xls_report.order_by})
        self.assertEqual(mock_assembly_participation_xls.call_count, 1)
        mock_assembly_participation_xls.assert_called_with(
            args=[company.pk, xls_ass_report.pk],
            kwargs={'ordering': xls_ass_report.order_by})
Пример #16
0
    def test_csv_download(self):
        """ rest download of captable csv """

        # data
        company = CompanyGenerator().generate()
        shareholder_list = []
        for x in range(1, 6):  # don't statt with 0, Generators 'if' will fail
            shareholder_list.append(ShareholderGenerator().generate(
                company=company, number=str(x)))

        # initial share creation
        PositionGenerator().generate(
            buyer=shareholder_list[0], count=1000, value=10)
        # single transaction
        PositionGenerator().generate(
            buyer=shareholder_list[1], count=10, value=10,
            seller=shareholder_list[0])
        # shareholder bought and sold
        PositionGenerator().generate(
            buyer=shareholder_list[2], count=20, value=20,
            seller=shareholder_list[0])
        PositionGenerator().generate(
            buyer=shareholder_list[0], count=20, value=20,
            seller=shareholder_list[2])

        # run test
        response = self.client.get(
            reverse('captable_csv', kwargs={"company_id": company.id}))

        # not logged in user
        self.assertEqual(response.status_code, 302)

        # login and retest
        user = UserGenerator().generate()
        OperatorGenerator().generate(user=user, company=company)
        is_loggedin = self.client.login(username=user.username, password='******')
        self.assertTrue(is_loggedin)
        response = self.client.get(reverse('captable_csv',
                                   kwargs={"company_id": company.id}))

        # assert response code
        self.assertEqual(response.status_code, 200)
        # assert proper csv
        lines = response.content.split('\r\n')
        lines.pop()  # remove last element based on final '\r\n'
        for row in lines:
            self.assertEqual(row.count(','), 7)
        self.assertEqual(len(lines), 3)  # ensure we have the right data
        # assert company itself
        self.assertEqual(shareholder_list[0].number, lines[1].split(',')[0])
        # assert share owner
        self.assertEqual(shareholder_list[1].number, lines[2].split(',')[0])
        # assert shareholder witout position not in there
        for line in lines:
            self.assertNotEqual(line[0], shareholder_list[3].number)
        # assert shareholder which bought and sold again
        for line in lines:
            self.assertNotEqual(line[0], shareholder_list[2].number)
Пример #17
0
class ImportTestCaseMixin(object):
    fixtures = ['initial.json']

    def setUp(self):
        self.filename = 'utils/tests/csv/sisware_export.csv'
        self.code = 'rot13'
        self.company = CompanyGenerator().generate()
        self.backend = SisWareImportBackend(self.filename)

    def assertImport(self):
        """
        reusable asserts after an import
        """
        # trigger fully featured share register validation,
        # raises ValidationError
        self.company.refresh_from_db()  # always use latest data
        with self.assertRaises(ValidationError):
            self.company.full_validate()
Пример #18
0
    def test_get_post_success_url(self):

        with self.assertRaises(NoReverseMatch):
            self.view.get_post_success_url()

        company = CompanyGenerator().generate()
        self.view.kwargs.update(dict(company_id=company.pk))

        self.assertIn(str(company.pk), self.view.get_post_success_url())
Пример #19
0
    def test_share_percent(self):
        """
        proper share percent math
        """
        company = CompanyGenerator().generate(share_count=1000000)
        security = SecurityGenerator().generate(company=company)
        sc = ShareholderGenerator().generate(company=company)
        s1 = ShareholderGenerator().generate(company=company)
        s2 = ShareholderGenerator().generate(company=company)
        s3 = ShareholderGenerator().generate(company=company)
        now = datetime.datetime.now()

        PositionGenerator().generate(buyer=sc,
                                     count=1000000,
                                     value=100,
                                     security=security,
                                     bought_at=now -
                                     datetime.timedelta(days=11))
        PositionGenerator().generate(buyer=s1,
                                     seller=sc,
                                     count=500000,
                                     value=100,
                                     security=security,
                                     bought_at=now -
                                     datetime.timedelta(days=10))
        PositionGenerator().generate(buyer=s2,
                                     seller=sc,
                                     count=5000,
                                     value=100,
                                     security=security,
                                     bought_at=now -
                                     datetime.timedelta(days=9))
        PositionGenerator().generate(buyer=s3,
                                     seller=sc,
                                     count=50,
                                     value=100,
                                     security=security,
                                     bought_at=now -
                                     datetime.timedelta(days=8))

        self.assertEqual(s1.share_percent(), '99.00')
        self.assertEqual(s2.share_percent(), '0.99')
        self.assertEqual(s3.share_percent(), '0.01')

        PositionGenerator().generate(buyer=s2,
                                     seller=s1,
                                     count=250000,
                                     value=100,
                                     security=security,
                                     bought_at=now -
                                     datetime.timedelta(days=7))

        self.assertEqual(s1.share_percent(), '49.50')
Пример #20
0
    def test_get_or_create_user(self):
        self.backend.company = CompanyGenerator().generate()
        kwargs = dict(shareholder_id='1',
                      first_name='first name',
                      last_name='last_name',
                      legal_type='Natürliche Person',
                      company='',
                      department='',
                      title='Prof.',
                      salutation='Herr',
                      street='Oxford St.',
                      street2='c/o Hamster',
                      pobox='PO123456',
                      postal_code='X3a',
                      city='London',
                      country='England',
                      language='Afghan Sign Language',
                      birthday='1943-03-06 00:00:00.000',
                      c_o='Walter Kalter',
                      nationality='England')
        self.backend._get_or_create_user(**kwargs)
        user = User.objects.last()
        for k, v in kwargs.iteritems():
            if hasattr(user, k):
                self.assertEqual(getattr(user, k), v)
            elif hasattr(user.userprofile, k):
                if k in ['country', 'nationality']:
                    self.assertEqual(
                        getattr(user.userprofile, k).name, 'United Kingdom')
                elif k == 'language':
                    self.assertEqual(getattr(user.userprofile, k), 'afg')
                elif k == 'legal_type':
                    self.assertEqual(getattr(user.userprofile, k), 'H')
                elif k == 'birthday':
                    self.assertEqual(getattr(user.userprofile, k),
                                     parse(v).date())
                else:
                    self.assertEqual(getattr(user.userprofile, k), v)
            elif hasattr(user.shareholder_set.first(), k):
                self.assertEqual(user.shareholder_set.first().number, v)

        kwargs.update({
            'legal_type': 'Juristische Person',
            'company': 'Large Corp',
            'department': 'Management and IT'
        })
        self.backend._get_or_create_user(**kwargs)

        user = User.objects.last()
        self.assertEqual(user.userprofile.legal_type, 'C')
        self.assertEqual(user.userprofile.company_name, 'Large Corp')
        self.assertEqual(user.userprofile.company_department,
                         'Management and IT')
Пример #21
0
    def test_csv_download_number_segments(self):
        """ rest download of captable csv """

        # data
        company = CompanyGenerator().generate()
        secs = TwoInitialSecuritiesGenerator().generate(company=company)
        security = secs[1]
        security.track_numbers = True
        security.save()

        shareholder_list = []
        for x in range(1, 6):  # don't statt with 0, Generators 'if' will fail
            shareholder_list.append(ShareholderGenerator().generate(
                company=company, number=str(x)))

        # initial share creation
        PositionGenerator().generate(
            buyer=shareholder_list[0], count=1000, value=10, security=security)
        # single transaction
        PositionGenerator().generate(
            buyer=shareholder_list[1], count=10, value=10, security=security,
            seller=shareholder_list[0])
        # shareholder bought and sold
        PositionGenerator().generate(
            buyer=shareholder_list[2], count=20, value=20, security=security,
            seller=shareholder_list[0])
        PositionGenerator().generate(
            buyer=shareholder_list[0], count=20, value=20, security=security,
            seller=shareholder_list[2])

        # login and retest
        user = UserGenerator().generate()
        OperatorGenerator().generate(user=user, company=company)
        is_loggedin = self.client.login(username=user.username, password='******')
        self.assertTrue(is_loggedin)
        response = self.client.get(reverse('captable_csv',
                                   kwargs={"company_id": company.id}))

        # assert response code
        self.assertEqual(response.status_code, 200)
        # assert proper csv
        lines = response.content.split('\r\n')
        lines.pop()  # remove last element based on final '\r\n'
        for row in lines:
            if row == lines[0]:  # skip first row
                continue
            self.assertEqual(row.count(','), 8)
            fields = row.split(',')
            s = Shareholder.objects.get(company=company, number=fields[0])
            text = s.current_segments(security)
            if text:
                self.assertTrue(text in fields[8])
Пример #22
0
    def test_xls_download_number_segments(self):
        """ rest download of captable xls """

        # data
        company = CompanyGenerator().generate()
        self.add_subscription(company)
        secs = TwoInitialSecuritiesGenerator().generate(company=company)
        security = secs[1]
        security.track_numbers = True
        security.save()

        shareholder_list = []
        for x in range(1, 6):  # don't statt with 0, Generators 'if' will fail
            shareholder_list.append(ShareholderGenerator().generate(
                company=company, number=str(x)))

        # initial share creation
        PositionGenerator().generate(buyer=shareholder_list[0],
                                     count=1000,
                                     value=10,
                                     security=security)
        # single transaction
        PositionGenerator().generate(buyer=shareholder_list[1],
                                     count=10,
                                     value=10,
                                     security=security,
                                     seller=shareholder_list[0])
        # shareholder bought and sold
        PositionGenerator().generate(buyer=shareholder_list[2],
                                     count=20,
                                     value=20,
                                     security=security,
                                     seller=shareholder_list[0])
        PositionGenerator().generate(buyer=shareholder_list[0],
                                     count=20,
                                     value=20,
                                     security=security,
                                     seller=shareholder_list[2])

        # login and retest
        report = ReportGenerator().generate(company=company, file_type='XLS')
        report.render()
        user = report.user
        OperatorGenerator().generate(user=user, company=company)
        self.client.force_login(user)
        response = self.client.get(
            reverse('reports:download', kwargs={"report_id": report.id}))

        # assert response code
        self.assertEqual(response.status_code, 200)
Пример #23
0
    def test_send_statement_generation_operator_notify(self, mock_mail_admins,
                                                       mock_email_message_send,
                                                       mock_email_multi_send,
                                                       mock_render_pdf):
        company = CompanyGenerator().generate()
        company.is_statement_sending_enabled = True
        company.statement_sending_date = now().date()
        company.save()

        # no subscription
        send_statement_generation_operator_notify()
        mock_mail_admins.assert_not_called()
        mock_email_message_send.assert_not_called()
        mock_email_multi_send.assert_not_called()

        # add subscription
        self.add_subscription(company)

        # no operators
        send_statement_generation_operator_notify()
        mock_mail_admins.assert_called()
        mock_email_message_send.assert_not_called()
        mock_email_multi_send.assert_not_called()

        OperatorGenerator().generate(company=company)

        with self.settings(EMAIL_BACKEND='dummy'):
            send_statement_generation_operator_notify()
            mock_email_multi_send.assert_called()

        djrill_settings = {
            'EMAIL_BACKEND': 'djrill',
            'MANDRILL_SHAREHOLDER_STATEMENT_OPERATOR_NOTIFY_TEMPLATE': 'foo'
        }
        with self.settings(**djrill_settings):
            send_statement_generation_operator_notify()
            mock_email_message_send.assert_called()

        mock_mail_admins.reset_mock()
        mock_email_multi_send.reset_mock()

        mock_render_pdf.return_value = 'PDFCONTENT'
        with mock.patch('shareholder.tasks.'
                        'EmailMultiAlternatives.attach') as mock_attach:
            send_statement_generation_operator_notify()
            mock_attach.assert_called()
            mock_attach.reset_mock()

            mock_render_pdf.side_effect = Exception
            send_statement_generation_operator_notify()
            mock_attach.assert_not_called()

        mock_mail_admins.assert_not_called()
        mock_email_multi_send.return_value = 0
        send_statement_generation_operator_notify()
        mock_mail_admins.assert_called()
Пример #24
0
    def test_check_subscription(self):

        with self.assertRaises(ValueError):
            self.mixin.check_subscription(None)

        company = CompanyGenerator().generate()

        self.assertFalse(self.mixin.check_subscription(company))

        # add subscription
        self.add_subscription(company)

        self.assertTrue(self.mixin.check_subscription(company))

        features = 'test'
        self.assertFalse(self.mixin.check_subscription(company, features))

        plan_name = company.get_current_subscription_plan()
        features = settings.DJSTRIPE_PLANS[plan_name]['features'].keys()
        self.assertTrue(self.mixin.check_subscription(company, features))

        # check iterable
        features = features[0]
        self.assertTrue(self.mixin.check_subscription(company, features))
Пример #25
0
    def test_captable_xls_download(self):
        """ rest download of captable xls """

        # data
        company = CompanyGenerator().generate()
        shareholder_list = []
        for x in range(1, 6):  # don't statt with 0, Generators 'if' will fail
            shareholder_list.append(ShareholderGenerator().generate(
                company=company, number=str(x)))
        shareholder_list = sorted(shareholder_list,
                                  key=lambda t: t.user.last_name.lower())

        # initial share creation
        p = PositionGenerator().generate(seller=None,
                                         buyer=shareholder_list[0],
                                         count=1000,
                                         value=10)
        security = p.security
        # single transaction
        PositionGenerator().generate(buyer=shareholder_list[1],
                                     count=10,
                                     value=10,
                                     seller=shareholder_list[0],
                                     security=security)
        # shareholder bought and sold
        PositionGenerator().generate(buyer=shareholder_list[2],
                                     count=20,
                                     value=20,
                                     seller=shareholder_list[0],
                                     security=security)
        PositionGenerator().generate(buyer=shareholder_list[0],
                                     count=20,
                                     value=20,
                                     seller=shareholder_list[2],
                                     security=security)

        # login and retest
        report = ReportGenerator().generate(company=company, file_type='XLS')
        report.render()
        user = report.user
        OperatorGenerator().generate(user=user, company=company)
        self.add_subscription(company)
        self.client.force_login(user)
        response = self.client.get(
            reverse('reports:download', kwargs={"report_id": report.id}))

        # assert response code
        self.assertEqual(response.status_code, 200)
Пример #26
0
    def test_get_queryset(self):
        self.mixin.get_company_pks = mock.Mock(return_value=[])

        with self.assertRaises(ValueError):
            self.mixin.get_queryset()

        company = CompanyGenerator().generate()
        add_company_to_session(self.client.session, company)
        self.mixin.request.session = self.client.session
        report = mommy.make(ShareholderStatementReport, company=company)

        self.mixin.get_company_pks.return_value = [company.pk]

        queryset = self.mixin.get_queryset()
        self.assertEqual(queryset.count(), 1)
        self.assertIn(report, queryset)
Пример #27
0
    def test_get_company(self):

        with self.assertRaises(Http404):
            self.mixin.get_company()

        self.mixin.kwargs.update(dict(company_id=0))

        with self.assertRaises(Http404):
            self.mixin.get_company()

        company = CompanyGenerator().generate()

        self.mixin.kwargs.update(dict(company_id=company.pk))
        result = self.mixin.get_company()
        self.assertIsNotNone(result)
        self.assertEqual(result, company)
Пример #28
0
    def test_numbered_shares(self):

        company = CompanyGenerator().generate()
        SecurityGenerator().generate(
            company=company, track_numbers=True)
        operator = OperatorGenerator().generate(company=company)

        self.client.login(username=operator.user.username,
                          password=DEFAULT_TEST_DATA.get('password'))

        res = self.client.get(reverse(
            'company', kwargs={'company_id': company.id}))

        self.assertEqual(res.status_code, 200)
        self.assertTrue(
            _('tracking security numbers for owners enabled. segments:') in res.content)
Пример #29
0
 def test_send_statement_generation_operator_template(self):
     """ test template content """
     company = CompanyGenerator().generate()
     company.is_statement_sending_enabled = True
     company.statement_sending_date = now().date()
     company.save()
     self.add_subscription(company)
     OperatorGenerator().generate(company=company)
     send_statement_generation_operator_notify()
     # proper brand url
     self.assertIn(
         u'https://example.com/static/compiled/images/dasaktienregister.png',
         mail.outbox[0].alternatives[0][0])
Пример #30
0
    def test_pdf_download_with_missing_operator(self):
        """ test download of captable pdf """
        company = CompanyGenerator().generate()
        # run test
        response = self.client.get(
            reverse('captable_pdf', kwargs={"company_id": company.id}))

        # not logged in user
        self.assertEqual(response.status_code, 302)

        # login and retest
        user = UserGenerator().generate()
        is_loggedin = self.client.login(username=user.username, password='******')
        self.assertTrue(is_loggedin)
        response = self.client.get(
            reverse('captable_pdf', kwargs={"company_id": company.id}))

        # assert response code
        self.assertEqual(response.status_code, 403)