class CorreiosTestCase(unittest.TestCase): def setUp(self): self.correios = Correios() def test_get_url(self): self.assertEqual(self.correios._get_url('rastreio', 'PR12345BR'), 'http://api.postmon.com.br/v1/rastreio/PR12345BR') @requests_mock.Mocker() def test_cep(self, request_mock): url = 'http://api.postmon.com.br/v1/cep/59142070' data = { 'Rua': 'Hawaii', 'Número': '160', 'Bairro': 'Ponta Negra', 'Cidade': 'Natal', 'Estado': 'Rio Grande do Norte', 'UF': 'RN', 'CEP': '59142-070' } request_mock.get(url, json=data) self.assertEqual(self.correios.cep('59142070'), data) @requests_mock.Mocker() def test_encomenda(self, request_mock): url = 'http://api.postmon.com.br/v1/rastreio/ect/PR12345BR' data = { 'Codigo': '12345', 'Cidade': 'Natal/RN', 'Status': 'Saiu para entrega' } request_mock.get(url, json=data) self.assertEqual(self.correios.encomenda('PR12345BR'), data)
def test_correios_get_shipping_rates_single_service_errors(self): correios = Correios() package = BoxPackage() package.add_item(1.0, 2.0, 3.0, 0.3) origin = '10000000' destination = '30000000' result = correios.get_shipping_rates(origin, destination, package, [Correios.SERVICE_PAC]) self.assertTrue(result.has_errors())
def test_should_use_repository_to_get_encomenda(self): encomenda_repository_mock = Mock() when(encomenda_repository_mock).get('123').thenReturn('encomenda123') Correios.encomenda_repository = encomenda_repository_mock assert Correios.encomenda('123') == 'encomenda123'
def track_pack(provider, track): if provider == 'ect': try: encomenda = Correios.encomenda(track) resposta = dict() result = [] for status in encomenda.status: historico = dict() historico['data'] = status.data historico['local'] = status.local historico['situacao'] = status.situacao historico['detalhes'] = status.detalhes result.append(historico) resposta['servico'] = provider resposta['codigo'] = track resposta['historico'] = result return format_result(resposta) except AttributeError: message = "404 Pacote %s nao encontrado" % track logger.exception(message) response.status = message else: message = '404 Servico %s nao encontrado' % provider logger.warning(message) response.status = message
def test_correios_get_shipping_rates_multiple_service_success(self): correios = Correios() package = BoxPackage() package.add_item(1.0, 2.0, 3.0, 0.3) origin = '10000000' destination = '30000000' result = correios.get_shipping_rates( origin, destination, package, [Correios.SERVICE_PAC, Correios.SERVICE_SEDEX]) self.assertFalse(result.has_errors()) self.assertEqual(origin, result.origin) self.assertEqual(destination, result.destination)
def track_pack(provider, track): if provider == 'ect': try: encomenda = Correios.encomenda(track) resposta = dict() result = [] for status in encomenda.status: historico = dict() historico['data'] = status.data historico['local'] = status.local historico['situacao'] = status.situacao historico['detalhes'] = status.detalhes result.append(historico) resposta['servico'] = provider resposta['codigo'] = track resposta['historico'] = result return format_result(resposta) except AttributeError: response.status = '404 O pacote %s informado nao pode ser localizado' %track else: response.status = '404 O Servico %s nao pode ser encontrado' %provider
def track_pack(provider, track): if provider == 'ect': try: encomenda = Correios.encomenda(track) resposta = dict() result = [] for status in encomenda.status: historico = dict() historico['data'] = status.data historico['local'] = status.local historico['situacao'] = status.situacao historico['detalhes'] = status.detalhes result.append(historico) resposta['servico'] = provider resposta['codigo'] = track resposta['historico'] = result return json.dumps(resposta) except AttributeError: response.status = '404 O pacote %s informado nao pode ser localizado' % track else: response.status = '404 O Servico %s nao pode ser encontrado' % provider
def test_correios_get_shipping_rates_single_service_success_with_contract( self): correios = Correios() correios.set_credentials('someuser', 'somepass') package = BoxPackage() package.add_item(1.0, 2.0, 3.0, 0.3) origin = '10000000' destination = '30000000' result = correios.get_shipping_rates(origin, destination, package, [Correios.SERVICE_PAC]) self.assertFalse(result.has_errors()) self.assertEqual(origin, result.origin) self.assertEqual(destination, result.destination)
def get(self): self.response.headers['Content-Type'] = 'text/xml' self.response.out.write('<?xml version="1.0" encoding="UTF-8"?>') encomenda = None try: encomenda = Correios.encomenda(self.request.get('numero', default_value='')) except Exception, e: pass #will return empty result :)
def get(self): self.response.headers['Content-Type'] = 'text/xml' self.response.out.write('<?xml version="1.0" encoding="UTF-8"?>') encomenda = None try: encomenda = Correios.encomenda( self.request.get('numero', default_value='')) except Exception, e: pass #will return empty result :)
def get(request, identificador): try: encomenda = Encomenda.objects.get(identificador=identificador) except Encomenda.DoesNotExist: encomenda = Correios.get_encomenda(identificador) [Status( pais = Country.objects.get(name__iexact=status.pais), cidade = Municipality.objects.get(name__iexact=status.cidade) or None, estado = State.objects.get(name__iexact=status.estado) or None, agencia = status.agencia or None, situacao = status.situacao, observacao = status.observacao or None, atualizacao = status.atualizacao ) for status in encomenda.status]
from correios import Correios from telegram import TelegramBot bot = TelegramBot('1409626650:AAHTdjbu64aG23T2OaRdoBNCenrNwAzRBJk') correios = Correios( 'teste', '1abcd00b2731640e886fb41a8a9671ad1434c599dbaa0a0de9a5aa619f29a83f') encomendas_cache = {} def build_response(chat_id, mensagem, is_primeira): if mensagem == '/start' or is_primeira: return ( '🤖💬 Bem vindo ao bot de rastreamento de encomendas. \nPara fazer um novo rastreamento, envie apenas o código (13 dígitos):' ) elif len(mensagem) != 13: return ( '🤖💬 Quantidade de dígitos inválidos, por favor, digite apenas o código (13 dígitos):' ) rastreamento = correios.rastrear(mensagem) if rastreamento is not None and len(rastreamento["eventos"]) > 0: ultimo_evento = rastreamento["eventos"][0] encomendas_cache[rastreamento["codigo"]] = { "status": ultimo_evento["status"], "chat_id": chat_id, "ultimo": rastreamento["ultimo"] }
def options(): # getting current request body logger.info("Options got requested with the following body") logger.info(request.get_data(as_text=True)) req = request.get_json() # initializing correios client correios = Correios() available_services = [ config.OPTION_PAC_SERVICE, config.OPTION_SEDEX_SERVICE ] # getting cart specs for shipping costs calculation origin = req.get('origin').get('postal_code') destination = req.get('destination').get('postal_code') items = req.get('items') # getting base shipping costs # creating a correios package package = reduce(item_to_package_item, items, BoxPackage()) logger.info('CORREIOS PACKAGE') logger.info(package.api_format()) # requesting rates from webservice rates = correios.get_shipping_rates(origin=origin, destination=destination, package=package, services=available_services) # checking for errors if rates.has_errors(): # logging errors and returning result early for service in rates.services: code = service.code error = service.error_code message = service.error_message logger.warn( 'The service {} returned the error {} with message: {}'.format( code, error, message)) return abort(400) # checking for free shipping items in cart free_shipping_items_qty = reduce( lambda c, i: c + 1 if i.get('free_shipping') else 0, items, 0) free_shipping_cart = free_shipping_items_qty == len(items) if free_shipping_items_qty > 0 and not free_shipping_cart: # performing another shipping costs calculation in order to get the consumer prices non_free_shipping_items = [ item for item in items if item.get('free_shipping') is not True ] non_free_shipping_package = reduce(item_to_package_item, non_free_shipping_items, BoxPackage()) # requesting rates from webservice non_free_shipping_rates = correios.get_shipping_rates( origin=origin, destination=destination, package=non_free_shipping_package, services=available_services) if non_free_shipping_rates.has_errors(): for service in non_free_shipping_rates.services: code = service.code error = service.error_code message = service.error_message logger.warn( 'The service {} returned the error {} with message: {}'. format(code, error, message)) non_free_shipping_rates = rates else: non_free_shipping_rates = rates # parsing service rates to the shipping option format options = list( map(lambda s: rate_to_shipping_option(s, free_shipping_cart), zip(rates.services, non_free_shipping_rates.services))) return json.jsonify({'rates': options})
# encoding: utf-8 from correios import Correios # import json # TODO # Code will be received from post by a form print(Correios().encomenda('RG847988460CN'))
def setUp(self): self.correios = Correios()
from correios import Correios __author__ = 'Andreas' encomenda = Correios.encomenda("PE129381952BR") ultimo = encomenda.ultimo_status_disponivel() print "%s, %s, %s" % (ultimo.data, ultimo.local, ultimo.situacao)
from correios import Correios try: encomenda = Correios.encomenda("PJ514632791BR") for status in encomenda.status: print "Data: %s" % status.data print "Local: %s" % status.local print "Situacao: %s" % status.situacao print "Detalhes: %s" % status.detalhes print except Exception as e: print e
def get_tracking_info(track_code): """ Get package tracking information by a track code. """ # TODO command dispatch pattern to correios return Correios().encomenda(track_code)
# coding: utf-8 __author__ = 'Andreas' from correios import Correios encomenda = Correios.encomenda('PE129381952BR') print encomenda.numero for status in encomenda.status: print "Data: %s" % status.data print "Local: %s" % status.local print "Situacao: %s" % status.situacao print "Detalhes: %s" % status.detalhes print '-------------------------------'
from correios import Correios encomenda = Correios.encomenda("ES446391025BR") print encomenda.numero for status in encomenda.status: print "Data: %s" % status.data print "Local: %s" % status.local print "Situacao: %s" % status.situacao print "Detalhes: %s" % status.detalhes print