예제 #1
0
 def test_tracking_single_not_found_parsing(self):
     with patch("purplship.mappers.dhl_express.proxy.http") as mock:
         mock.return_value = TrackingSingleNotFound
         parsed_response = (Tracking.fetch(
             self.TrackingRequest).from_(gateway).parse())
         self.assertEqual(DP.to_dict(parsed_response),
                          DP.to_dict(ParsedTrackingSingNotFound))
예제 #2
0
 def test_parse_rate_response_errors(self):
     with patch("purplship.mappers.usps.proxy.http") as mock:
         mock.return_value = ERROR_XML
         parsed_response = Rating.fetch(
             self.RateRequest).from_(gateway).parse()
         self.assertEqual(DP.to_dict(parsed_response),
                          DP.to_dict(PARSED_ERRORS))
예제 #3
0
 def test_parse_rate_missing_args_error(self):
     with patch("purplship.mappers.canadapost.proxy.http") as mock:
         mock.return_value = QuoteMissingArgsError
         parsed_response = Rating.fetch(
             self.RateRequest).from_(gateway).parse()
         self.assertEqual(DP.to_dict(parsed_response),
                          DP.to_dict(ParsedQuoteMissingArgsError))
예제 #4
0
    def update(payload: dict,
               carrier: models.Carrier = None,
               **carrier_filters) -> datatypes.PickupResponse:
        carrier = carrier or Carriers.first(
            **{
                **dict(active=True, capability="pickup", raise_not_found=True),
                **carrier_filters,
            })

        if carrier is None:
            raise NotFound(
                "No active carrier connection found to process the request")

        request = purplship.Pickup.update(
            datatypes.PickupUpdateRequest(**DP.to_dict(payload)))

        # The request call is wrapped in identity to simplify mocking in tests
        pickup, messages = identity(
            lambda: request.from_(carrier.gateway).parse())

        if pickup is None:
            raise exceptions.PurplShipApiException(
                detail=datatypes.ErrorResponse(messages=messages),
                status_code=status.HTTP_400_BAD_REQUEST,
            )

        return datatypes.PickupResponse(
            pickup=datatypes.Pickup(
                **{
                    **payload,
                    **DP.to_dict(pickup),
                    "test_mode": carrier.test,
                }),
            messages=messages,
        )
예제 #5
0
    def track(payload: dict,
              carrier_filter: dict = None,
              carrier: models.Carrier = None) -> TrackingResponse:
        carrier = carrier or next(
            iter(Carriers.list(**{
                **(carrier_filter or {}), 'active': True
            })), None)

        if carrier is None:
            raise NotFound('No configured and active carrier found')

        request = purplship.Tracking.fetch(
            TrackingRequest(**DP.to_dict(payload)))
        gateway = purplship.gateway[carrier.data.carrier_name].create(
            carrier.data.dict())

        # The request call is wrapped in identity to simplify mocking in tests
        results, messages = identity(lambda: request.from_(gateway).parse())

        if any(messages or []) and not any(results or []):
            raise PurplShipApiException(
                detail=ErrorResponse(messages=messages),
                status_code=status.HTTP_404_NOT_FOUND)

        return TrackingResponse(tracking=(Tracking(
            **{
                **DP.to_dict(results[0]),
                'id': f'trk_{uuid.uuid4().hex}',
                'test_mode': carrier.test,
            }) if any(results) else None),
                                messages=messages)
예제 #6
0
    def update(payload: dict,
               carrier_filter: dict = None,
               carrier: models.Carrier = None) -> PickupResponse:
        carrier = carrier or next(
            iter(Carriers.list(**{
                **(carrier_filter or {}), 'active': True
            })), None)

        if carrier is None:
            raise NotFound('No configured and active carrier found')

        request = purplship.Pickup.update(
            PickupUpdateRequest(**DP.to_dict(payload)))
        gateway = purplship.gateway[carrier.data.carrier_name].create(
            carrier.data.dict())

        # The request call is wrapped in identity to simplify mocking in tests
        pickup, messages = identity(lambda: request.from_(gateway).parse())

        if pickup is None:
            raise PurplShipApiException(
                detail=ErrorResponse(messages=messages),
                status_code=status.HTTP_400_BAD_REQUEST)

        return PickupResponse(
            pickup=Pickup(**{
                **payload,
                **DP.to_dict(pickup),
                'test_mode': carrier.test,
            }),
            messages=messages)
예제 #7
0
    def test_create_rate_request_with_package_preset_missing_weight(self, _):
        processing_error = (Rating.fetch(
            RateRequest(
                **RateWithPresetMissingWeightPayload)).from_(gateway).parse())

        self.assertEqual(DP.to_dict(processing_error),
                         DP.to_dict(ProcessingError))
예제 #8
0
 def test_parse_rate_error(self):
     with patch("purplship.mappers.ups.proxy.http") as mock:
         mock.return_value = RateteParsingErrorXML
         parsed_response = Rating.fetch(
             self.RateRequest).from_(gateway).parse()
         self.assertEqual(DP.to_dict(parsed_response),
                          DP.to_dict(ParsedRateteParsingError))
예제 #9
0
 def test_tracking_unknown_response_parsing(self):
     with patch("purplship.mappers.ups.proxy.http") as mock:
         mock.return_value = InvalidTrackingNumberResponseXML
         parsed_response = (Tracking.fetch(
             self.TrackingRequest).from_(gateway).parse())
         self.assertEqual(DP.to_dict(parsed_response),
                          DP.to_dict(ParsedInvalidTrackingNumberResponse))
예제 #10
0
 def test_parse_tracking_response(self):
     with patch("purplship.mappers.usps.proxy.http") as mock:
         mock.return_value = TRACKING_RESPONSE
         parsed_response = (Tracking.fetch(
             self.TrackingRequest).from_(gateway).parse())
         self.assertEqual(DP.to_dict(parsed_response),
                          DP.to_dict(PARSED_TRACKING_RESPONSE))
예제 #11
0
파일: rate.py 프로젝트: iliaaz/purplship
 def test_parse_rate_vol_weight_higher_response(self):
     with patch("purplship.mappers.dhl_express.proxy.http") as mock:
         mock.return_value = RateVolWeightHigher
         parsed_response = Rating.fetch(self.RateRequest).from_(gateway).parse()
         self.assertEqual(
             DP.to_dict(parsed_response), DP.to_dict(ParsedRateVolWeightHigher)
         )
예제 #12
0
 def test_parse_shipment_response(self):
     with patch("purplship.mappers.usps_international.proxy.http") as mocks:
         mocks.return_value = ShipmentResponseXML
         parsed_response = (purplship.Shipment.create(
             self.ShipmentRequest).from_(gateway).parse())
         self.assertEqual(DP.to_dict(parsed_response),
                          DP.to_dict(ParsedShipmentResponse))
예제 #13
0
 def test_tracking_auth_error_parsing(self):
     with patch("purplship.mappers.ups.proxy.http") as mock:
         mock.return_value = AuthError
         parsed_response = (Tracking.fetch(
             self.TrackingRequest).from_(gateway).parse())
         self.assertEqual(DP.to_dict(parsed_response),
                          DP.to_dict(ParsedAuthError))
예제 #14
0
    def test_parse_tracking_response(self):
        with patch("purplship.mappers.canadapost.proxy.http") as mock:
            mock.return_value = TrackingResponseXml
            parsed_response = (Tracking.fetch(
                self.TrackingRequest).from_(gateway).parse())

            self.assertEqual(DP.to_dict(parsed_response),
                             DP.to_dict(ParsedTrackingResponse))
예제 #15
0
파일: pickup.py 프로젝트: iliaaz/purplship
    def test_parse_request_pickup_response(self):
        with patch("purplship.mappers.canpar.proxy.http") as mock:
            mock.return_value = PickupResponseXML
            parsed_response = (purplship.Pickup.schedule(
                self.PickupRequest).from_(gateway).parse())

            self.assertEqual(DP.to_dict(parsed_response),
                             DP.to_dict(ParsedPickupResponse))
예제 #16
0
    def test_parse_modify_pickup_response(self):
        with patch("purplship.mappers.dhl_express.proxy.http") as mock:
            mock.return_value = ModifyPURequestXML
            parsed_response = Pickup.update(
                self.ModifyPURequest).from_(gateway).parse()

            self.assertEqual(DP.to_dict(parsed_response),
                             DP.to_dict(ParsedModifyPUResponse))
예제 #17
0
    def test_parse_void_shipment_response(self):
        with patch("purplship.mappers.canpar.proxy.http") as mock:
            mock.return_value = VoidShipmentResponseXML
            parsed_response = (purplship.Shipment.cancel(
                self.VoidShipmentRequest).from_(gateway).parse())

            self.assertEqual(DP.to_dict(parsed_response),
                             DP.to_dict(ParsedVoidShipmentResponse))
예제 #18
0
    def test_parse_void_shipment_response(self):
        with patch("purplship.mappers.[carrier].proxy.http") as mock:
            mock.return_value = PickupCancelResponseXML
            parsed_response = (purplship.Pickup.cancel(
                self.PickupCancelRequest).from_(gateway).parse())

            self.assertEqual(DP.to_dict(parsed_response),
                             DP.to_dict(ParsedPickupCancelResponse))
예제 #19
0
    def test_parse_error_response(self):
        with patch("purplship.mappers.aramex.proxy.http") as mock:
            mock.return_value = ErrorResponseXML
            parsed_response = (Tracking.fetch(
                self.TrackingRequest).from_(gateway).parse())

            self.assertEqual(DP.to_dict(parsed_response),
                             DP.to_dict(ParsedErrorResponse))
예제 #20
0
    def test_parse_rate_response(self):
        with patch("purplship.mappers.usps_international.proxy.http") as mock:
            mock.return_value = RATE_RESPONSE_XML
            parsed_response = Rating.fetch(
                self.RateRequest).from_(gateway).parse()

            self.assertEqual(DP.to_dict(parsed_response),
                             DP.to_dict(PARSED_RATE_RESPONSE))
예제 #21
0
    def test_parse_cancellation_pickup_response(self):
        with patch("purplship.mappers.dhl_express.proxy.http") as mock:
            mock.return_value = CancelPUResponseXML
            parsed_response = Pickup.cancel(
                self.CancelPURequest).from_(gateway).parse()

            self.assertEqual(DP.to_dict(parsed_response),
                             DP.to_dict(ParsedCancelPUResponse))
예제 #22
0
    def test_parse_request_pickup_error(self):
        with patch("purplship.mappers.dhl_express.proxy.http") as mock:
            mock.return_value = PickupErrorResponseXML
            parsed_response = Pickup.schedule(
                self.BookPURequest).from_(gateway).parse()

            self.assertEqual(DP.to_dict(parsed_response),
                             DP.to_dict(ParsedPickupErrorResponse))
예제 #23
0
파일: rate.py 프로젝트: iliaaz/purplship
    def test_parse_rate_response(self):
        with patch("purplship.mappers.canpar.proxy.http") as mock:
            mock.return_value = RateResponseXml
            parsed_response = Rating.fetch(
                self.RateRequest).from_(gateway).parse()

            self.assertEqual(DP.to_dict(parsed_response),
                             DP.to_dict(ParsedQuoteResponse))
예제 #24
0
    def test_parse_shipment_response(self):
        with patch("purplship.mappers.canadapost.proxy.http") as mocks:
            mocks.side_effect = [ShipmentResponseXML, LabelResponse]
            parsed_response = (purplship.Shipment.create(
                self.ShipmentRequest).from_(gateway).parse())

            self.assertEqual(DP.to_dict(parsed_response),
                             DP.to_dict(ParsedShipmentResponse))
예제 #25
0
    def test_parse_address_validation_response(self):
        with patch("purplship.mappers.ups.proxy.http") as mock:
            mock.return_value = AddressValidationResponseXML
            parsed_response = (purplship.Address.validate(
                self.AddressValidationRequest).from_(gateway).parse())

            self.assertEqual(DP.to_dict(parsed_response),
                             DP.to_dict(ParsedAddressValidationResponse))
예제 #26
0
    def test_parse_tracking_error_response(self):
        with patch("purplship.mappers.royalmail.proxy.http") as mock:
            mock.return_value = TrackingErrorResponseJSON
            parsed_response = (Tracking.fetch(
                self.TrackingRequest).from_(gateway).parse())

            self.assertEqual(DP.to_dict(parsed_response),
                             DP.to_dict(ParsedTrackingErrorResponse))
예제 #27
0
    def test_parse_cancel_shipment_response(self):
        with patch("purplship.mappers.freightcom.proxy.http") as mock:
            mock.return_value = ShipmentCancelResponseXML
            parsed_response = (Shipment.cancel(
                self.ShipmentCancelRequest).from_(gateway).parse())

            self.assertEqual(DP.to_dict(parsed_response),
                             DP.to_dict(ParsedCancelShipmentResponse))
예제 #28
0
    def test_parse_error_tracking_response(self):
        with patch("purplship.mappers.fedex_express.proxy.http") as mock:
            mock.return_value = TrackingErrorResponseXML
            parsed_response = Tracking.fetch(
                self.TrackRequest).from_(gateway).parse()

            self.assertEqual(DP.to_dict(parsed_response),
                             DP.to_dict(ParsedTrackingResponseError))
예제 #29
0
    def test_parse_in_transit_tracking_response(self):
        with patch("purplship.mappers.dhl_express.proxy.http") as mock:
            mock.return_value = IntransitTrackingResponseXML
            parsed_response = (Tracking.fetch(
                self.TrackingRequest).from_(gateway).parse())

            self.assertEqual(DP.to_dict(parsed_response),
                             DP.to_dict(ParsedInTransitTrackingResponse))
예제 #30
0
    def create(payload: dict,
               resolve_tracking_url: Callable[[Shipment], str] = None,
               carrier: models.Carrier = None) -> Shipment:
        selected_rate = next(
            (Rate(**rate) for rate in payload.get('rates')
             if rate.get('id') == payload.get('selected_rate_id')), None)

        if selected_rate is None:
            raise NotFound(
                f'Invalid selected_rate_id "{payload.get("selected_rate_id")}" \n '
                f'Please select one of the following: [ {", ".join([r.get("id") for r in payload.get("rates")])} ]'
            )

        carrier = carrier or Carriers.retrieve(
            carrier_id=selected_rate.carrier_id).data
        request = ShipmentRequest(
            **{
                **DP.to_dict(payload), 'service': selected_rate.service
            })
        gateway = purplship.gateway[carrier.carrier_name].create(
            carrier.dict())

        # The request is wrapped in identity to simplify mocking in tests
        shipment, messages = identity(
            lambda: purplship.Shipment.create(request).from_(gateway).parse())

        if shipment is None:
            raise PurplShipApiException(
                detail=ErrorResponse(messages=messages),
                status_code=status.HTTP_400_BAD_REQUEST)

        shipment_rate = ({
            **DP.to_dict(shipment.selected_rate), 'id':
            f'rat_{uuid.uuid4().hex}'
        } if shipment.selected_rate is not None else DP.to_dict(selected_rate))

        def generate_tracking_url():
            if resolve_tracking_url is None:
                return ''

            return f"{resolve_tracking_url(shipment)}{'?test' if carrier.test else ''}"

        return Shipment(
            **{
                **payload,
                **DP.to_dict(shipment), "id": f"shp_{uuid.uuid4().hex}",
                "test_mode": carrier.test,
                "selected_rate": shipment_rate,
                "service": shipment_rate["service"],
                "selected_rate_id": shipment_rate["id"],
                "tracking_url": generate_tracking_url(),
                "status": ShipmentStatus.purchased.value,
                "created_at": datetime.now().strftime(
                    "%Y-%m-%d %H:%M:%S.%f%z"),
                "messages": messages
            })