Example #1
0
    def test_responses(self):
        # We're going to mock the Apple's response and put 21007 status
        with patch.object(requests, 'post') as mock_post:
            iap_status_21007 = self.iap_response.copy()
            iap_status_21007['status'] = 21007
            mock_post.return_value.content = json.dumps(iap_status_21007)
            mock_post.return_value.status_code = 200
            set_verification_mode('production')
            request = Request('DummyReceipt')
            try:
                receipt = request.validate()
            except exceptions.InvalidReceipt as e:
                assert e.status == 21007
                assert e.description == e._descriptions[21007]

        # We're going to return an invalid http status code
        with patch.object(requests, 'post') as mock_post:
            mock_post.return_value.content = 'Not avaliable'
            mock_post.return_value.status_code = 500
            set_verification_mode('production')
            request = Request('DummyReceipt')
            try:
                receipt = request.validate()
            except exceptions.ItunesServerNotAvailable as e:
                assert e[0] == 500
                assert e[1] == 'Not avaliable'
Example #2
0
 def test_fail_on_production_if_connection_error(self, verify_mock):
     verify_mock.side_effect = [exceptions.ConnectionError, self.dummy_receipt]
     request = Request(self.receipt_data, password=self.password, use_production=True, use_sandbox=True)
     with pytest.raises(exceptions.ConnectionError):
         request.verify()
     calls = verify_mock.call_args_list
     assert calls == [mock.call(RECEIPT_PRODUCTION_VALIDATION_URL)]
Example #3
0
def test_request():
    try:
        from testdata import sandbox_receipt
    except ImportError:
        print 'No receipt data to test'
        return

    set_verification_mode('production')
    request = Request(sandbox_receipt)
    try:
        receipt = request.validate()
        assert False
    except exceptions.InvalidReceipt, e:
        assert e.status == 21007
        assert e.description == e._descriptions[21007]
Example #4
0
class ItunesIapTestCase(ItunesIapMixin, unittest.TestCase):

    def setUp(self):
        super(ItunesIapTestCase, self).setUp()
        self.request = Request(self.receipt_data, password=self.password, use_production=False, use_sandbox=True)
        self.dummy_receipt = dict(receipt={}, status=0)

    @vcr.use_cassette('verified_receipt')
    def test_receipt_is_verified(self):
        receipt = self.request.verify()
        assert receipt.status == 0

    @mock.patch.object(Request, 'verify_from')
    def test_try_both_production_and_sandbox_mode(self, verify_mock):
        verify_mock.side_effect = [exceptions.InvalidReceipt, self.dummy_receipt]
        request = Request(self.receipt_data, password=self.password, use_production=True, use_sandbox=True)
        request.verify()
        calls = verify_mock.call_args_list
        assert calls == [mock.call(RECEIPT_PRODUCTION_VALIDATION_URL), mock.call(RECEIPT_SANDBOX_VALIDATION_URL)]

    @mock.patch.object(Request, 'verify_from')
    def test_fail_on_production_if_connection_error(self, verify_mock):
        verify_mock.side_effect = [exceptions.ConnectionError, self.dummy_receipt]
        request = Request(self.receipt_data, password=self.password, use_production=True, use_sandbox=True)
        with pytest.raises(exceptions.ConnectionError):
            request.verify()
        calls = verify_mock.call_args_list
        assert calls == [mock.call(RECEIPT_PRODUCTION_VALIDATION_URL)]

    @mock.patch.object(requests, 'post', side_effect=requests.HTTPError)
    def test_connection_error(self, post_mock):
        with pytest.raises(exceptions.ConnectionError):
            self.request.verify()

    @mock.patch.object(requests, 'post')
    def test_http_error(self, post_mock):
        post_mock.return_value = mock.MagicMock(status_code=404)
        with pytest.raises(exceptions.ItunesNotAvailable):
            self.request.verify()

    @mock.patch.object(requests.Response, 'content', mock.PropertyMock(return_value=b'Not available'))
    def test_json_error(self):
        with pytest.raises(exceptions.ItunesNotAvailable):
            self.request.verify()

    @vcr.use_cassette('invalid_receipt_data')
    def test_invalid_receipt(self):
        receipt_data = 'invalid'
        self.request = Request(receipt_data, password=self.password, use_production=False, use_sandbox=True)
        with pytest.raises(exceptions.InvalidReceipt):
            self.request.verify()
Example #5
0
 def test_context(self):
     request = Request(sandbox_receipt)
     configs = request.use_production, request.use_sandbox
     with request.verification_mode('production'):
         try:
             request.verify()
             assert False
         except exceptions.InvalidReceipt as e:
             assert e.status == 21007
         with request.verification_mode('sandbox'):
             request.verify()
         try:
             request.verify()
             assert False
         except exceptions.InvalidReceipt as e:
             assert e.status == 21007
     assert configs == (request.use_production, request.use_sandbox)
Example #6
0
 def test_global_mode(self):
     set_verification_mode('production')
     assert Request('').use_production is True
     assert Request('').use_sandbox is False
     set_verification_mode('sandbox')
     assert Request('').use_production is False
     assert Request('').use_sandbox is True
     set_verification_mode('reject')
     assert Request('').use_production is False
     assert Request('').use_sandbox is False
     set_verification_mode('review')
     assert Request('').use_production is True
     assert Request('').use_sandbox is True
Example #7
0
    def test_extract_receipt(self):
        """
            Testing the extract receipt function.
            The function which helps to put the last 'in_app's fields' in the
            'receipt dictionary'
        """

        # Test IAP Response without in_app list
        request = Request('DummyReceipt', use_production=True)
        ext_receipt = request._extract_receipt(self.iap_response)

        assert ext_receipt['status'] == 0  # 0 is normal
        assert ext_receipt['receipt']['product_id'] == u'TestProduction1'
        assert ext_receipt['receipt'][
            'original_transaction_id'] == u'1000000012345678'  # original transaction id
        assert ext_receipt['receipt']['quantity'] == u'1'  # check quantity

        # Test IAP Response with in_app list
        request = Request('DummyReceipt', use_production=True)
        ext_receipt = request._extract_receipt(self.iap_response_in_app)

        assert ext_receipt['status'] == 0  # 0 is normal
        assert ext_receipt['receipt']['product_id'] == u'org.itunesiap'
        assert ext_receipt['receipt'][
            'original_transaction_id'] == u'1000000155715958'  # original transaction id
        assert ext_receipt['receipt']['quantity'] == u'1'  # check quantity
Example #8
0
    def test_responses(self):
        # We're going to mock the Apple's response and put 21007 status
        with patch.object(requests, 'post') as mock_post:
            iap_status_21007 = self.iap_response.copy()
            iap_status_21007['status'] = 21007
            mock_post.return_value.content = json.dumps(iap_status_21007)
            mock_post.return_value.status_code = 200
            set_verification_mode('production')
            request = Request('DummyReceipt')
            try:
                receipt = request.validate()
            except exceptions.InvalidReceipt as e:
                assert e.status == 21007
                assert e.description == e._descriptions[21007]

        # We're going to return an invalid http status code
        with patch.object(requests, 'post') as mock_post:
            mock_post.return_value.content = 'Not avaliable'
            mock_post.return_value.status_code = 500
            set_verification_mode('production')
            request = Request('DummyReceipt')
            try:
                receipt = request.validate()
            except exceptions.ItunesServerNotAvailable as e:
                assert e[0] == 500
                assert e[1] == 'Not avaliable'
Example #9
0
 def test_context(self):
     try:
         from testdata import sandbox_receipt
     except ImportError:
         print('No receipt data to test')
         return
     request = Request(sandbox_receipt)
     configs = request.use_production, request.use_sandbox
     with request.verification_mode('production'):
         try:
             request.verify()
             assert False
         except exceptions.InvalidReceipt as e:
             assert e.status == 21007
         with request.verification_mode('sandbox'):
             request.verify()
         try:
             request.verify()
             assert False
         except exceptions.InvalidReceipt as e:
             assert e.status == 21007
     assert configs == (request.use_production, request.use_sandbox)
Example #10
0
    def test_extract_receipt(self):
        """
            Testing the extract receipt function.
            The function which helps to put the last 'in_app's fields' in the
            'receipt dictionary'
        """

        # Test IAP Response without in_app list
        request = Request('DummyReceipt', use_production=True)
        ext_receipt = request._extract_receipt(self.iap_response)

        assert ext_receipt['status'] == 0  # 0 is normal
        assert ext_receipt['receipt']['product_id'] == u'TestProduction1'
        assert ext_receipt['receipt']['original_transaction_id'] == u'1000000012345678'  # original transaction id
        assert ext_receipt['receipt']['quantity'] == u'1'  # check quantity

        # Test IAP Response with in_app list
        request = Request('DummyReceipt', use_production=True)
        ext_receipt = request._extract_receipt(self.iap_response_in_app)

        assert ext_receipt['status'] == 0  # 0 is normal
        assert ext_receipt['receipt']['product_id'] == u'org.itunesiap'
        assert ext_receipt['receipt']['original_transaction_id'] == u'1000000155715958'  # original transaction id
        assert ext_receipt['receipt']['quantity'] == u'1'  # check quantity
Example #11
0
def test_context():
    try:
        from testdata import sandbox_receipt
    except ImportError:
        print 'No receipt data to test'
        return
    request = Request(sandbox_receipt)
    configs = request.use_production, request.use_sandbox
    with request.verification_mode('production'):
        try:
            request.verify()
            assert False
        except exceptions.InvalidReceipt, e:
            assert e.status == 21007
        with request.verification_mode('sandbox'):
            request.verify()
        try:
            request.verify()
            assert False
        except exceptions.InvalidReceipt, e:
            assert e.status == 21007
Example #12
0
 def test_request(self):
     set_verification_mode('production')
     request = Request(sandbox_receipt)
     try:
         receipt = request.validate()
         assert False
     except exceptions.InvalidReceipt as e:
         assert e.status == 21007
         assert e.description == e._descriptions[21007]
     set_verification_mode('review')
     request = Request(sandbox_receipt)
     receipt = request.validate()
     assert receipt
Example #13
0
    def test_request(self):
        try:
            from testdata import sandbox_receipt
        except ImportError:
            print('No receipt data to test')
            return

        set_verification_mode('production')
        request = Request(sandbox_receipt)
        try:
            receipt = request.validate()
            assert False
        except exceptions.InvalidReceipt as e:
            assert e.status == 21007
            assert e.description == e._descriptions[21007]
        set_verification_mode('review')
        request = Request(sandbox_receipt)
        receipt = request.validate()
        assert receipt
Example #14
0
 def test_try_both_production_and_sandbox_mode(self, verify_mock):
     verify_mock.side_effect = [exceptions.InvalidReceipt, self.dummy_receipt]
     request = Request(self.receipt_data, password=self.password, use_production=True, use_sandbox=True)
     request.verify()
     calls = verify_mock.call_args_list
     assert calls == [mock.call(RECEIPT_PRODUCTION_VALIDATION_URL), mock.call(RECEIPT_SANDBOX_VALIDATION_URL)]
Example #15
0
 def setUp(self):
     super(ItunesIapTestCase, self).setUp()
     self.request = Request(self.receipt_data, password=self.password, use_production=False, use_sandbox=True)
     self.dummy_receipt = dict(receipt={}, status=0)
Example #16
0
    try:
        from testdata import sandbox_receipt
    except ImportError:
        print 'No receipt data to test'
        return

    set_verification_mode('production')
    request = Request(sandbox_receipt)
    try:
        receipt = request.validate()
        assert False
    except exceptions.InvalidReceipt, e:
        assert e.status == 21007
        assert e.description == e._descriptions[21007]
    set_verification_mode('review')
    request = Request(sandbox_receipt)
    receipt = request.validate()
    assert receipt

def test_context():
    try:
        from testdata import sandbox_receipt
    except ImportError:
        print 'No receipt data to test'
        return
    request = Request(sandbox_receipt)
    configs = request.use_production, request.use_sandbox
    with request.verification_mode('production'):
        try:
            request.verify()
            assert False
Example #17
0
 def itunes_iap_validation_handle(self, msgtype, req):
     from itunesiap import Request, set_verification_mode
     from itunesiap.exceptions import InvalidReceipt, ItunesServerNotAvailable
     from session.utils import sdk_username
     from sdk.payment import end_payment, get_payment, gen_payment
     player = self.player
     try:
         # set_verification_mode('sandbox')
         request = Request(req.receipt)
         with request.verification_mode('review'):
             receipt = request.verify()
         logger.info(receipt)
         configs = get_config(RechargeConfig)
         goods = filter(
             lambda item: item.goodsid == receipt.product_id and item.
             sdktype == poem_pb.SDK_APP_IOS, configs.values())
         if len(goods) != 1:
             logger.error('Invalid goodsid: {},{}'.format(
                 player.entityID, receipt.product_id))
             return False
         goods = goods[0]
         logger.debug(goods)
         sdkorderid = sdk_username(poem_pb.SDK_APP_IOS,
                                   receipt.transaction_id)
         payment = get_payment(sdkorderid)
         if not payment:
             result = gen_payment(sdkorderid, player.entityID,
                                  poem_pb.SDK_APP_IOS, receipt.product_id)
             payment = get_payment(sdkorderid)
         if payment.get('status', None) != 'SUCCESS':
             if not end_payment(sdkorderid):
                 logger.error('insert callback pay record failed %s' %
                              sdkorderid)
                 return False
             payment = get_payment(sdkorderid)
             logger.debug(payment)
             data = {
                 "clientVersion": "",
                 "amount": goods.amount,
                 "orderNO": sdkorderid,
                 "_level": "",
                 "_username": "",
                 "_userID": 0,
                 "_entityID": player.entityID,
                 "result": 1
             }
             username = player.username
             userID = player.userID
             idfa = player.idfa
             appid = player.appid
             rs = pay_handler(player.entityID,
                              username,
                              payment["goodsid"],
                              amount=int(goods.amount))
             if not rs:
                 return False
             logger.debug(rs)
             get_gold = rs["get_gold"]
             username = rs["username"]
             level = rs["level"]
             rsp = poem_pb.PayResult(success=True,
                                     roleID=player.entityID,
                                     userID=0,
                                     payID=receipt.transaction_id,
                                     goods=0,
                                     count=get_gold,
                                     data=req.receipt)
             g_playerManager.sendto(player.entityID,
                                    success_msg(msgid.SDK_PAY_RESULT, rsp))
             data.update(_username=username, _level=level)
             data.update(_gold=get_gold)
             role_credit(**data)
             gm_logger.info({
                 'pay': {
                     'transaction_id': receipt.transaction_id,
                     'userID': userID,
                     'entityID': player.entityID,
                     'channel': player.channel,
                     'amount': goods.amount,
                     'gold': get_gold,
                     'idfa': idfa,
                     'appid': appid,
                     'username': username
                 },
                 'payID': sdkorderid
             })
         if payment.get('status', None) == 'SUCCESS':
             response = poem_pb.iTunesStoreReceiptResponse()
             response.transaction_id = receipt.transaction_id
             response.successed = True
             g_playerManager.sendto(player.entityID,
                                    success_msg(msgtype, response))
     except InvalidReceipt:
         logger.warning('invalid receipt')
Example #18
0
 def test_invalid_receipt(self):
     receipt_data = 'invalid'
     self.request = Request(receipt_data, password=self.password, use_production=False, use_sandbox=True)
     with pytest.raises(exceptions.InvalidReceipt):
         self.request.verify()