Exemplo n.º 1
0
 def __serialize(self, segments):
     # create capital
     bank = BankGenerator().generate()
     p = PositionGenerator().generate(number_segments=segments,
                                      count=8,
                                      seller=None)
     # position under test:
     position = PositionGenerator().generate(number_segments=segments,
                                             count=8,
                                             company=p.buyer.company,
                                             seller=p.buyer,
                                             save=False,
                                             security=p.security,
                                             depot_bank=bank)
     url = reverse('position-detail', kwargs={'pk': position.id})
     request = self.factory.get(url)
     # authenticated request
     request.user = OperatorGenerator().generate(
         company=position.buyer.company).user
     request.session = {'company_pk': position.buyer.company.pk}
     # prepare data
     data = PositionSerializer(position, context={'request': request}).data
     data['bought_at'] = '2024-01-01T10:00'
     return (PositionSerializer(data=data, context={'request':
                                                    request}), position)
Exemplo n.º 2
0
        def serialize(segments):
            operator = OperatorGenerator().generate()
            company = operator.company
            securities = TwoInitialSecuritiesGenerator().generate(
                company=company)
            security = securities[1]
            security.track_numbers = True
            security.save()
            position = PositionGenerator().generate(company=company,
                                                    number_segments=segments,
                                                    save=False,
                                                    security=security,
                                                    count=8)

            url = reverse('position-detail', kwargs={'pk': position.id})
            request = self.factory.get(url)
            request.user = operator.user

            # prepare data
            position.seller = None
            position.buyer = None
            # get test data dict
            data = PositionSerializer(position, context={
                'request': request
            }).data
            # clear bad datetimedata
            data['bought_at'] = '2014-01-01T10:00'
            del data['seller'], data['buyer']
            # feed data into serializer
            return PositionSerializer(data=data, context={'request': request})
Exemplo n.º 3
0
 def test_create(self, signal_mock):
     del self.new_data['seller']
     del self.new_data['depot_bank']
     self.new_data['depot_type'] = 1
     serializer = PositionSerializer(data=self.new_data,
                                     context={'request': self.request})
     serializer.is_valid()
     obj = serializer.create(serializer.validated_data)
     calls = (mock.call(obj.buyer.pk))
     signal_mock.apply_async.has_calls(calls)
Exemplo n.º 4
0
 def __serialize(self, segments):
     position = PositionGenerator().generate(number_segments=segments,
                                             count=8)
     url = reverse('position-detail', kwargs={'pk': position.id})
     request = self.factory.get(url)
     # authenticated request
     request.user = OperatorGenerator().generate(
         company=position.buyer.company).user
     # prepare data
     data = PositionSerializer(position, context={'request': request}).data
     # clear bad datetimedata
     data['buyer']['user']['userprofile']['birthday'] = None
     data['seller']['user']['userprofile']['birthday'] = None
     data['bought_at'] = '2014-01-01T10:00'
     return (PositionSerializer(data=data, context={'request':
                                                    request}), position)
Exemplo n.º 5
0
    def post(self, request, fomat=None):
        data = request.data
        is_valid, errors = self._validate_data(data)
        if is_valid:
            # get company and run company.split_shares(data)
            company = request.user.operator_set.earliest('id').company
            data.update({
                'execute_at':
                dateutil.parser.parse(data['execute_at']),
                'security':
                Security.objects.get(id=data['security']['pk'])
            })
            company.split_shares(data)

            positions = Position.objects.filter(
                buyer__company__operator__user=request.user).order_by(
                    '-bought_at')

            serializer = PositionSerializer(positions,
                                            many=True,
                                            context={'request': request})
            return Response({
                'success': True,
                'data': serializer.data
            },
                            status=status.HTTP_201_CREATED)

        return Response(errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 6
0
    def setUp(self):
        self.factory = RequestFactory()
        self.client = Client()
        self.session = self.client.session

        self.position = PositionGenerator().generate(seller=None)
        self.operator = OperatorGenerator().generate(
            company=self.position.buyer.company)

        add_company_to_session(self.session, self.operator.company)
        self.request = self.factory.get('/services/rest/position')
        self.request.user = self.operator.user
        self.request.session = self.session
        self.new_data = PositionSerializer(self.position,
                                           context={
                                               'request': self.request
                                           }).data
        self.new_data.update({'bought_at': '2013-05-05T00:00'})
Exemplo n.º 7
0
    def test_get_is_certificate_valid(self):
        """
        is certificate valid or was it returned
        """
        pos = PositionGenerator().generate()
        pos.invalidate_certificate()
        pos2 = pos.certificate_invalidation_position

        serializer = PositionSerializer(instance=pos)
        self.assertFalse(serializer.get_is_certificate_valid(pos))
        self.assertFalse(serializer.get_is_certificate_valid(pos2))

        pos = PositionGenerator().generate()
        serializer = PositionSerializer(instance=pos)
        self.assertIsNone(serializer.get_is_certificate_valid(pos))

        pos = PositionGenerator().generate(certificate_id='123')
        serializer = PositionSerializer(instance=pos)
        self.assertTrue(serializer.get_is_certificate_valid(pos))
Exemplo n.º 8
0
    def invalidate(self, request, pk):
        """
        invalidate issued certificate
        """
        position = self.get_object()
        try:
            position.invalidate_certificate()
            return Response(
                PositionSerializer(instance=position,
                                   context={'request': request}).data,
                status=status.HTTP_200_OK)

        except ValueError as e:
            return Response(
                {
                    'success': False,
                    'errors': [_('Position cannot be invalidated. "{}"'
                                 '').format(e)]
                },
                status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 9
0
    def test_get_certificate_invalidation_position_url(self):
        """
        return url for cert invalidation position
        """
        pos = PositionGenerator().generate()
        pos.invalidate_certificate()

        serializer = PositionSerializer(instance=pos)
        self.assertIsNotNone(
            serializer.get_certificate_invalidation_position_url(pos))

        pos = PositionGenerator().generate()
        serializer = PositionSerializer(instance=pos)
        self.assertIsNone(
            serializer.get_certificate_invalidation_position_url(pos))
Exemplo n.º 10
0
    def test_fields(self):
        operator = OperatorGenerator().generate()
        poss, shs = ComplexPositionsWithSegmentsGenerator().generate(
            company=operator.company)  # does +2shs
        request = self.factory.get('/services/rest/shareholders')
        request.user = operator.user

        qs = Position.objects.filter(pk__in=[pos.pk for pos in poss])
        serializer = PositionSerializer(qs,
                                        many=True,
                                        context={'request': request})

        self.assertTrue(len(serializer.data) > 0)
        position_data = serializer.data[0]
        keys = position_data.keys()
        self.assertIsNotNone(position_data['stock_book_id'])
        self.assertIsNotNone(position_data['depot_type'])
        self.assertIn('depot_bank', keys)
        self.assertIn('certificate_invalidation_position_url', keys)
        self.assertIn('certificate_invalidation_initial_position_url', keys)
        self.assertIn('is_certificate_valid', keys)
Exemplo n.º 11
0
 def test_update(self, signal_mock):
     serializer = PositionSerializer(data=self.new_data,
                                     context={'request': self.request})
     serializer.is_valid()
     obj = serializer.update(self.position, serializer.validated_data)
     signal_mock.apply_async.assert_called_with([obj.pk])
Exemplo n.º 12
0
class PositionSerializerTestCase(TestCase):
    def __serialize(self, segments):
        # create capital
        bank = BankGenerator().generate()
        p = PositionGenerator().generate(number_segments=segments,
                                         count=8,
                                         seller=None)
        # position under test:
        position = PositionGenerator().generate(number_segments=segments,
                                                count=8,
                                                company=p.buyer.company,
                                                seller=p.buyer,
                                                save=False,
                                                security=p.security,
                                                depot_bank=bank)
        url = reverse('position-detail', kwargs={'pk': position.id})
        request = self.factory.get(url)
        # authenticated request
        request.user = OperatorGenerator().generate(
            company=position.buyer.company).user
        request.session = {'company_pk': position.buyer.company.pk}
        # prepare data
        data = PositionSerializer(position, context={'request': request}).data
        data['bought_at'] = '2024-01-01T10:00'
        return (PositionSerializer(data=data, context={'request':
                                                       request}), position)

    def setUp(self):
        self.factory = RequestFactory()
        self.client = Client()
        self.session = self.client.session

        self.position = PositionGenerator().generate(seller=None)
        self.operator = OperatorGenerator().generate(
            company=self.position.buyer.company)

        add_company_to_session(self.session, self.operator.company)
        self.request = self.factory.get('/services/rest/position')
        self.request.user = self.operator.user
        self.request.session = self.session
        self.new_data = PositionSerializer(self.position,
                                           context={
                                               'request': self.request
                                           }).data
        self.new_data.update({'bought_at': '2013-05-05T00:00'})

    @mock.patch('shareholder.signals.update_order_cache_task')
    def test_create(self, signal_mock):
        del self.new_data['seller']
        del self.new_data['depot_bank']
        self.new_data['depot_type'] = 1
        serializer = PositionSerializer(data=self.new_data,
                                        context={'request': self.request})
        serializer.is_valid()
        obj = serializer.create(serializer.validated_data)
        calls = (mock.call(obj.buyer.pk))
        signal_mock.apply_async.has_calls(calls)

    def test_get_certificate_invalidation_position_url(self):
        """
        return url for cert invalidation position
        """
        pos = PositionGenerator().generate()
        pos.invalidate_certificate()

        serializer = PositionSerializer(instance=pos)
        self.assertIsNotNone(
            serializer.get_certificate_invalidation_position_url(pos))

        pos = PositionGenerator().generate()
        serializer = PositionSerializer(instance=pos)
        self.assertIsNone(
            serializer.get_certificate_invalidation_position_url(pos))

    def test_get_certificate_invalidation_initial_position_url(self):
        """
        return url for initial position for an cert invalidation
        """
        pos = PositionGenerator().generate()
        pos.invalidate_certificate()
        pos2 = pos.certificate_invalidation_position

        serializer = PositionSerializer(instance=pos)
        self.assertIsNotNone(
            serializer.get_certificate_invalidation_initial_position_url(pos2))

        pos = PositionGenerator().generate()
        serializer = PositionSerializer(instance=pos)
        self.assertIsNone(
            serializer.get_certificate_invalidation_initial_position_url(pos))

    def test_get_is_certificate_valid(self):
        """
        is certificate valid or was it returned
        """
        pos = PositionGenerator().generate()
        pos.invalidate_certificate()
        pos2 = pos.certificate_invalidation_position

        serializer = PositionSerializer(instance=pos)
        self.assertFalse(serializer.get_is_certificate_valid(pos))
        self.assertFalse(serializer.get_is_certificate_valid(pos2))

        pos = PositionGenerator().generate()
        serializer = PositionSerializer(instance=pos)
        self.assertIsNone(serializer.get_is_certificate_valid(pos))

        pos = PositionGenerator().generate(certificate_id='123')
        serializer = PositionSerializer(instance=pos)
        self.assertTrue(serializer.get_is_certificate_valid(pos))

    def test_is_valid(self):
        """
        position serializer handling numbered shares
        """
        serializer, position = self.__serialize([1, 3, 4, u'6-9', 33])
        res = serializer.is_valid()
        self.assertEqual(res, True)

    def test_is_valid_fail_segment_used_with_optionplan(self):
        """
        position serializer handling numbered shares failes due to segment
        used with option plan
        """
        segments = [1, 3, 4, u'6-9', 33]
        serializer, position = self.__serialize(segments)
        security = position.security
        security.track_numbers = True
        security.save()

        OptionPlanGenerator().generate(company=position.security.company,
                                       security=position.security,
                                       number_segments=segments)

        with self.assertRaises(ValidationError) as cm:
            serializer.is_valid()

        self.assertEqual(cm.exception.detail.keys(), ['number_segments'])

    def test_create_capital_increase_numbered_shares(self):
        """
        position serializer handling numbered shares while doing a capital
        increase
        """
        def serialize(segments):
            operator = OperatorGenerator().generate()
            company = operator.company
            securities = TwoInitialSecuritiesGenerator().generate(
                company=company)
            security = securities[1]
            security.track_numbers = True
            security.save()
            position = PositionGenerator().generate(company=company,
                                                    number_segments=segments,
                                                    save=False,
                                                    security=security,
                                                    count=8)

            url = reverse('position-detail', kwargs={'pk': position.id})
            request = self.factory.get(url)
            request.user = operator.user
            request.session = {'company_pk': company.pk}

            # prepare data
            position.seller = None
            position.buyer = None
            position.depot_bank = BankGenerator().generate()
            # get test data dict
            data = PositionSerializer(position, context={
                'request': request
            }).data
            # clear bad datetimedata
            data['bought_at'] = '2014-01-01T10:00'
            del data['seller'], data['buyer']
            # feed data into serializer
            return PositionSerializer(data=data, context={'request': request})

        segments = [1, 3, 4, u'6-9', 33]
        serializer = serialize(human_readable_segments(segments))
        serializer.is_valid()
        position = serializer.create(serializer.validated_data)
        self.assertEqual([1, u'3-4', u'6-9', 33],
                         position.security.number_segments)
        self.assertEqual(position.registration_type, '1')
        self.assertEqual(position.depot_bank, Bank.objects.first())

    def test_fields(self):
        operator = OperatorGenerator().generate()
        poss, shs = ComplexPositionsWithSegmentsGenerator().generate(
            company=operator.company)  # does +2shs
        request = self.factory.get('/services/rest/shareholders')
        request.user = operator.user

        qs = Position.objects.filter(pk__in=[pos.pk for pos in poss])
        serializer = PositionSerializer(qs,
                                        many=True,
                                        context={'request': request})

        self.assertTrue(len(serializer.data) > 0)
        position_data = serializer.data[0]
        keys = position_data.keys()
        self.assertIsNotNone(position_data['stock_book_id'])
        self.assertIsNotNone(position_data['depot_type'])
        self.assertIn('depot_bank', keys)
        self.assertIn('certificate_invalidation_position_url', keys)
        self.assertIn('certificate_invalidation_initial_position_url', keys)
        self.assertIn('is_certificate_valid', keys)

    @unittest.skip('PLACEHOLDER - test for signal fired once implemented')
    @mock.patch('shareholder.signals.update_order_cache_task')
    def test_update(self, signal_mock):
        serializer = PositionSerializer(data=self.new_data,
                                        context={'request': self.request})
        serializer.is_valid()
        obj = serializer.update(self.position, serializer.validated_data)
        signal_mock.apply_async.assert_called_with([obj.pk])

    def test_validate_certificate_id(self):
        """ certificate id must be unique """
        serializer, position = self.__serialize('1, 3, 4, 6-9, 33')
        certificate_id = '222'
        self.assertEqual(serializer.validate_certificate_id(certificate_id),
                         certificate_id)
        # OptionTransaction existing -> fail
        ot = OptionTransactionGenerator().generate(
            certificate_id=certificate_id, company=position.buyer.company)
        with self.assertRaises(ValidationError):
            serializer.validate_certificate_id(certificate_id)
        ot.delete()

        # Position existing -> fail
        position.certificate_id = certificate_id
        position.save()
        with self.assertRaises(ValidationError):
            serializer.validate_certificate_id(certificate_id)

    def test_validate_count(self):
        """ count must be positive and more then what shareholder owns """
        serializer, position = self.__serialize('1, 3, 4, 6-9, 33')
        certificate_id = '222'

        # negative count -> fail
        with self.assertRaises(ValidationError):
            self.assertEqual(serializer.validate_count(-1), certificate_id)

        # less then shareholder owns -> fail
        with self.assertRaises(ValidationError):
            serializer.validate_count(
                position.seller.share_count(security=position.security) + 1)

        # success
        count = position.seller.share_count(security=position.security)
        self.assertEqual(count, serializer.validate_count(count))

    def test_validate_depot_bank(self):
        """
        force depot banks set if that is depot type 0 (cert depot)
        """
        serializer, position = self.__serialize('1, 3, 4, 6-9, 33')

        serializer.initial_data['depot_type'] = '1'
        self.assertEqual(serializer.validate_depot_bank(dict()), {})

        serializer.initial_data['depot_type'] = '0'
        self.assertEqual(serializer.validate_depot_bank('somevalue'),
                         'somevalue')

        with self.assertRaises(ValidationError):
            serializer.validate_depot_bank(None)