Best Python code snippet using localstack_python
sale.py
Source:sale.py
1import datetime2from trytond.model import fields3from trytond.pool import Pool, PoolMeta4from trytond.exceptions import UserError, UserWarning5from trytond.transaction import Transaction6from decimal import Decimal7import logging8from sql import Table9class Cron(metaclass=PoolMeta):10 'Cron'11 __name__ = 'ir.cron'12 @classmethod13 def __setup__(cls):14 super().__setup__()15 cls.method.selection.append(16 ('sale.sale|import_data_sale', "Importar ventas"),17 )18#Heredamos del modelo sale.sale para agregar el campo id_tecno19class Sale(metaclass=PoolMeta):20 'Sale'21 __name__ = 'sale.sale'22 id_tecno = fields.Char('Id Tabla Sqlserver', required=False)23 @classmethod24 def import_data_sale(cls):25 logging.warning('RUN VENTAS')26 pool = Pool()27 Config = pool.get('conector.configuration')28 Actualizacion = pool.get('conector.actualizacion')29 data = ()30 ventas_tecno = Config.get_documentos_tecno('1')31 if ventas_tecno:32 data = ventas_tecno33 devoluciones_tecno = Config.get_documentos_tecno('2')34 if devoluciones_tecno:35 data += devoluciones_tecno #FIX TUPLE + LIST36 #Se crea o actualiza la fecha de importación37 actualizacion = Actualizacion.create_or_update('VENTAS')38 if not data:39 actualizacion.save()40 logging.warning('FINISH VENTAS')41 return42 Sale = pool.get('sale.sale')43 SaleLine = pool.get('sale.line')44 Product = pool.get('product.product')45 SaleDevice = pool.get('sale.device')46 Location = pool.get('stock.location')47 payment_term = pool.get('account.invoice.payment_term')48 Party = pool.get('party.party')49 Address = pool.get('party.address')50 Shop = pool.get('sale.shop')51 Tax = pool.get('account.tax')52 User = pool.get('res.user')53 Module = pool.get('ir.module')54 55 # Se consulta si el módulo company_operation esta activado56 company_operation = Module.search([('name', '=', 'company_operation'), ('state', '=', 'activated')])57 if company_operation:58 CompanyOperation = pool.get('company.operation_center')59 company_operation = CompanyOperation(1)60 venta_pos = []61 pdevoluciones_pos = Config.get_data_parametros('10')62 if pdevoluciones_pos:63 pdevoluciones_pos = (pdevoluciones_pos[0].Valor).strip().split(',')64 venta_pos += pdevoluciones_pos65 pventa_pos = Config.get_data_parametros('8')66 if pventa_pos:67 pventa_pos = (pventa_pos[0].Valor).strip().split(',')68 venta_pos += pventa_pos69 venta_electronica = Config.get_data_parametros('9')70 if venta_electronica:71 venta_electronica = (venta_electronica[0].Valor).strip().split(',')72 logs = []73 to_created = []74 to_exception = []75 #Procedemos a realizar una venta76 for venta in data:77 try:78 sw = venta.sw79 numero_doc = venta.Numero_documento80 tipo_doc = venta.tipo81 id_venta = str(sw)+'-'+tipo_doc+'-'+str(numero_doc)82 existe = Sale.search([('id_tecno', '=', id_venta)])83 if existe:84 to_created.append(id_venta)85 continue86 print(id_venta)87 tbltipodocto, = Config.get_tbltipodoctos(tipo_doc)88 analytic_account = None89 if hasattr(SaleLine, 'analytic_accounts'):90 if tbltipodocto.Encabezado != '0':91 AnalyticAccount = pool.get('analytic_account.account')92 analytic_account, = AnalyticAccount.search([('code', '=', str(tbltipodocto.Encabezado))])93 #Se trae la fecha de la venta y se adapta al formato correcto para Tryton94 fecha = str(venta.fecha_hora).split()[0].split('-')95 fecha_date = datetime.date(int(fecha[0]), int(fecha[1]), int(fecha[2]))96 nit_cedula = venta.nit_Cedula97 party = Party.search([('id_number', '=', nit_cedula)])98 if not party:99 msg2 = f'EXCEPCION {id_venta} - No se encontro el tercero {nit_cedula}'100 logging.error(msg2)101 logs.append(msg2)102 actualizacion.reset_writedate('TERCEROS')103 to_exception.append(id_venta)104 continue105 party = party[0]106 #Se indica a que bodega pertenece107 id_tecno_bodega = venta.bodega108 bodega = Location.search([('id_tecno', '=', id_tecno_bodega)])109 if not bodega:110 msg2 = f'EXCEPCION {id_venta} - Bodega {id_tecno_bodega} no existe'111 logging.error(msg2)112 logs.append(msg2)113 to_exception.append(id_venta)114 continue115 bodega = bodega[0]116 shop = Shop.search([('warehouse', '=', bodega.id)])117 if not shop:118 msg2 = f'EXCEPCION {id_venta} - Tienda (bodega) {id_tecno_bodega} no existe'119 logging.error(msg2)120 logs.append(msg2)121 to_exception.append(id_venta)122 continue123 shop = shop[0]124 #Se le asigna el plazo de pago correspondiente125 condicion = venta.condicion126 plazo_pago = payment_term.search([('id_tecno', '=', condicion)])127 if not plazo_pago:128 msg2 = f'EXCEPCION {id_venta} - Plazo de pago {condicion} no existe'129 logging.error(msg2)130 logs.append(msg2)131 to_exception.append(id_venta)132 continue133 plazo_pago = plazo_pago[0]134 #Ahora traemos las lineas (productos) para la venta135 documentos_linea = Config.get_lineasd_tecno(id_venta)136 if not documentos_linea:137 msg = f"EXCEPCION {id_venta} - No se encontraron lÃneas para la venta"138 logs.append(msg)139 to_exception.append(id_venta)140 continue141 with Transaction().set_user(1):142 context = User.get_preferences()143 with Transaction().set_context(context, shop=shop.id, _skip_warnings=True):144 sale = Sale()145 sale.number = tipo_doc+'-'+str(numero_doc)146 sale.reference = tipo_doc+'-'+str(numero_doc)147 sale.id_tecno = id_venta148 sale.description = (venta.notas).replace('\n', ' ').replace('\r', '')149 sale.invoice_type = 'C'150 sale.sale_date = fecha_date151 sale.party = party.id152 sale.invoice_party = party.id153 sale.shipment_party = party.id154 sale.warehouse = bodega155 sale.shop = shop156 sale.payment_term = plazo_pago157 sale.self_pick_up = False158 #Se revisa si la venta es clasificada como electronica o pos y se cambia el tipo159 if tipo_doc in venta_electronica:160 #continue #TEST161 sale.invoice_type = '1'162 elif tipo_doc in venta_pos:163 sale.invoice_type = 'P'164 sale.invoice_date = fecha_date165 sale.pos_create_date = fecha_date166 #sale.self_pick_up = True167 #Busco la terminal y se la asigno168 sale_device, = SaleDevice.search([('id_tecno', '=', venta.pc)])169 sale.sale_device = sale_device170 sale.invoice_number = sale.number171 #Se busca una dirección del tercero para agregar en la factura y envio172 address = Address.search([('party', '=', party.id)], limit=1)173 if address:174 sale.invoice_address = address[0].id175 sale.shipment_address = address[0].id176 #SE CREA LA VENTA177 sale.save()178 #Se revisa si se aplico alguno de los 3 impuestos en la venta179 retencion_iva = False180 if venta.retencion_iva > 0:181 retencion_iva = True182 retencion_ica = False183 if venta.retencion_ica > 0:184 retencion_ica = True185 retencion_rete = False186 if venta.retencion_causada > 0:187 if not retencion_iva and not retencion_ica:188 retencion_rete = True189 elif (venta.retencion_iva + venta.retencion_ica) != venta.retencion_causada:190 retencion_rete = True191 #Ahora se procede a crear las lÃneas para la venta192 #_lines = []193 for lin in documentos_linea:194 producto, = Product.search(['OR', ('id_tecno', '=', str(lin.IdProducto)), ('code', '=', str(lin.IdProducto))])195 linea = SaleLine()196 linea.sale = sale197 linea.product = producto198 linea.type = 'line'199 linea.unit = producto.template.default_uom200 #Se verifica si es una devolución201 cant = float(lin.Cantidad_Facturada)202 cantidad_facturada = abs(round(cant, 3))203 if linea.unit.id == 1:204 cantidad_facturada = int(cantidad_facturada)205 #print(cant, cantidad_facturada)206 if sw == 2:207 linea.quantity = cantidad_facturada * -1208 dcto_base = str(venta.Tipo_Docto_Base)+'-'+str(venta.Numero_Docto_Base)209 #Se indica a que documento hace referencia la devolucion210 sale.reference = dcto_base211 sale.comment = f"DEVOLUCIÃN DE LA FACTURA {dcto_base}"212 else:213 linea.quantity = cantidad_facturada214 #Se verifica si tiene activo el módulo centro de operaciones y se añade 1 por defecto215 if company_operation:216 linea.operation_center = company_operation217 #Comprueba los cambios y trae los impuestos del producto218 linea.on_change_product()219 #Se verifica si el impuesto al consumo fue aplicado220 impuesto_consumo = lin.Impuesto_Consumo221 #A continuación se verifica las retenciones e impuesto al consumo222 impuestos_linea = []223 for impuestol in linea.taxes:224 clase_impuesto = impuestol.classification_tax225 if clase_impuesto == '05' and retencion_iva:226 if impuestol not in impuestos_linea:227 impuestos_linea.append(impuestol)228 elif clase_impuesto == '06' and retencion_rete:229 if impuestol not in impuestos_linea:230 impuestos_linea.append(impuestol)231 elif clase_impuesto == '07' and retencion_ica:232 if impuestol not in impuestos_linea:233 impuestos_linea.append(impuestol)234 elif impuestol.consumo and impuesto_consumo > 0:235 #Se busca el impuesto al consumo con el mismo valor para aplicarlo236 tax = Tax.search([('consumo', '=', True), ('type', '=', 'fixed'), ('amount', '=', impuesto_consumo)])237 if tax:238 tax, = tax239 impuestos_linea.append(tax)240 else:241 raise UserError('ERROR IMPUESTO', 'No se encontró el impuesto al consumo: '+id_venta)242 elif clase_impuesto != '05' and clase_impuesto != '06' and clase_impuesto != '07' and not impuestol.consumo:243 if impuestol not in impuestos_linea:244 impuestos_linea.append(impuestol)245 linea.taxes = impuestos_linea246 linea.unit_price = lin.Valor_Unitario247 #Verificamos si hay descuento para la linea de producto y se agrega su respectivo descuento248 if lin.Porcentaje_Descuento_1 > 0:249 porcentaje = lin.Porcentaje_Descuento_1/100250 linea.base_price = lin.Valor_Unitario251 linea.discount_rate = Decimal(str(porcentaje))252 linea.on_change_discount_rate()253 # Se guarda la linea para la venta254 # linea.on_change_quantity()255 if analytic_account:256 AnalyticEntry = pool.get('analytic.account.entry')257 root, = AnalyticAccount.search([('type', '=', 'root')])258 analytic_entry = AnalyticEntry()259 analytic_entry.root = root260 analytic_entry.account = analytic_account261 linea.analytic_accounts = [analytic_entry]262 # _lines.append(linea)263 linea.save()264 #Se procesa los registros creados265 with Transaction().set_user(1):266 context = User.get_preferences()267 with Transaction().set_context(context, _skip_warnings=True):268 Sale.quote([sale])269 Sale.confirm([sale])270 Sale.process([sale])271 cls.finish_shipment_process(sale)272 if sale.invoice_type == 'P':273 Sale.post_invoices(sale)274 if sale.payment_term.id_tecno == '0':275 cls.set_payment_pos(sale, logs, to_exception)276 Sale.update_state([sale])277 else:278 cls.finish_invoice_process(sale, venta, logs, to_exception)279 to_created.append(id_venta)280 except Exception as e:281 msg = f"EXCEPCION {id_venta} - {str(e)}"282 logs.append(msg)283 to_exception.append(id_venta)284 Actualizacion.add_logs(actualizacion, logs)285 for idt in to_created:286 if idt not in to_exception:287 Config.update_exportado(idt, 'T')288 # print('creado...', idt) #TEST289 for idt in to_exception:290 Config.update_exportado(idt, 'E')291 # print('excepcion...', idt) #TEST292 logging.warning('FINISH VENTAS')293 # Funcion encargada de finalizar el proceso de envÃo de la venta294 @classmethod295 def finish_shipment_process(cls, sale):296 for shipment in sale.shipments:297 shipment.number = sale.number298 shipment.reference = sale.reference299 shipment.effective_date = sale.sale_date300 shipment.wait([shipment])301 shipment.pick([shipment])302 shipment.pack([shipment])303 shipment.done([shipment])304 for shipment in sale.shipment_returns:305 shipment.number = sale.number306 shipment.reference = sale.reference307 shipment.effective_date = sale.sale_date308 shipment.receive([shipment])309 shipment.done([shipment])310 #Se actualiza las facturas y envios con la información de la venta311 @classmethod312 def finish_invoice_process(cls, sale, venta, logs, to_exception):313 pool = Pool()314 Invoice = pool.get('account.invoice')315 PaymentLine = pool.get('account.invoice-account.move.line')316 Config = pool.get('conector.configuration')317 #Procesamos la venta para generar la factura y procedemos a rellenar los campos de la factura318 if not sale.invoices:319 sale._process_invoice([sale])320 if not sale.invoices:321 msg1 = f"EXCEPTION {sale.id_tecno} VENTA SIN FACTURA"322 logging.error(msg1)323 logs.append(msg1)324 to_exception.append(sale.id_tecno)325 for invoice in sale.invoices:326 invoice.accounting_date = sale.sale_date327 invoice.number = sale.number328 invoice.reference = sale.reference329 invoice.invoice_date = sale.sale_date330 invoice.invoice_type = 'C'331 tipo_numero = sale.number.split('-')332 #Se agrega en la descripcion el nombre del tipo de documento de la tabla en sqlserver333 desc = Config.get_tbltipodoctos(tipo_numero[0])334 if desc:335 invoice.description = desc[0].TipoDoctos.replace('\n', ' ').replace('\r', '')336 invoice.save()337 Invoice.validate_invoice([invoice])338 total_tryton = abs(invoice.untaxed_amount)339 #Se almacena el total de la venta traida de TecnoCarnes340 total_tecno = 0341 valor_total = Decimal(abs(venta.valor_total))342 valor_impuesto = Decimal(abs(venta.Valor_impuesto) + abs(venta.Impuesto_Consumo))343 if valor_impuesto > 0:344 total_tecno = valor_total - valor_impuesto345 else:346 total_tecno = valor_total347 diferencia_total = abs(total_tryton - total_tecno)348 if venta.sw == 2:349 dcto_base = str(venta.Tipo_Docto_Base)+'-'+str(venta.Numero_Docto_Base)350 original_invoice = Invoice.search([('number', '=', dcto_base)])351 if original_invoice:352 invoice.original_invoice = original_invoice[0]353 else:354 msg = f"NO SE ENCONTRO LA FACTURA {dcto_base} PARA CRUZAR CON LA DEVOLUCION {invoice.number}"355 logs.append(msg)356 logging.error(msg)357 to_exception.append(sale.id_tecno)358 if diferencia_total < Decimal(6.0):359 Invoice.post_batch([invoice])360 Invoice.post([invoice])361 if invoice.original_invoice:362 if invoice.original_invoice.amount_to_pay + invoice.amount_to_pay != 0:363 paymentline = PaymentLine()364 paymentline.invoice = invoice.original_invoice365 paymentline.invoice_account = invoice.account366 paymentline.invoice_party = invoice.party367 for ml in invoice.move.lines:368 if ml.account.type.receivable:369 paymentline.line = ml370 paymentline.save()371 Invoice.reconcile_invoice(invoice)372 else:373 msg1 = f'FACTURA {sale.id_tecno}'374 msg2 = f'No contabilizada diferencia total mayor al rango permitido'375 full_msg = ' - '.join([msg1, msg2])376 logging.error(full_msg)377 logs.append(full_msg)378 invoice.comment = msg2379 invoice.save()380 #Función encargada de buscar recibos de caja pagados en TecnoCarnes y pagarlos en Tryton381 @classmethod382 def set_payment_pos(cls, sale, logs, to_exception):383 Config = Pool().get('conector.configuration')384 pagos = Config.get_tipos_pago(sale.id_tecno)385 if not pagos:386 msg = f"EXCEPCION {sale.id_tecno} - No se encontraron pagos asociados en tecnocarnes (documentos_che)"387 logs.append(msg)388 to_exception.append(sale.id_tecno)389 return390 #si existe pagos pos...391 pool = Pool()392 Journal = pool.get('account.statement.journal')393 for pago in pagos:394 fecha = str(pago.fecha).split()[0].split('-')395 fecha_date = datetime.date(int(fecha[0]), int(fecha[1]), int(fecha[2]))396 journal, = Journal.search([('id_tecno', '=', pago.forma_pago)])397 args_statement = {398 'device': sale.sale_device,399 'date': fecha_date,400 'journal': journal,401 }402 statement, = cls.search_or_create_statement(args_statement)403 valor = pago.valor404 if pago.sw == 2 and valor > 0:405 valor = valor*-1406 data_payment = {407 'sales': {408 sale: valor409 },410 'statement': statement.id,411 'date': fecha_date412 }413 result_payment = cls.multipayment_invoices_statement(data_payment, logs, to_exception)414 if result_payment != 'ok':415 msg = f"ERROR AL PROCESAR EL PAGO DE LA VENTA POS {sale.number}"416 logging.error(msg)417 logs.append(msg)418 419 #Metodo encargado de buscar el estado de cuenta de una terminal y en caso de no existir, se crea.420 @classmethod421 def search_or_create_statement(cls, args):422 pool = Pool()423 Statement = pool.get('account.statement')424 Device = pool.get('sale.device')425 device = Device(args['device'])426 date = args['date']427 journal = args['journal']428 statement = Statement.search([429 ('journal', '=', journal.id),430 ('sale_device', '=', device.id),431 ('date', '=', date),432 ('state', '=', 'draft')433 ])434 if not statement:435 statements_date = Statement.search([436 ('journal', '=', journal.id),437 ('date', '=', date),438 ('sale_device', '=', device.id),439 ])440 turn = len(statements_date) + 1441 values = {442 'name': '%s - %s' % (device.rec_name, journal.rec_name),443 'date': date,444 'journal': journal.id,445 'company': device.shop.company.id,446 'start_balance': journal.default_start_balance or Decimal('0.0'),447 'end_balance': Decimal('0.0'),448 'turn': turn,449 'sale_device': device.id,450 }451 statement = Statement.create([values])452 return statement453 # Metodo encargado de pagar multiples facturas con multiples formas de pago454 @classmethod455 def multipayment_invoices_statement(cls, args, logs, to_exception):456 pool = Pool()457 Date = pool.get('ir.date')458 Sale = pool.get('sale.sale')459 Configuration = pool.get('account.configuration')460 User = pool.get('res.user')461 StatementLine = pool.get('account.statement.line')462 sales = args.get('sales', None)463 if not sales:464 sales_ids = args.get('sales_ids', None)465 sales = Sale.browse(sales_ids)466 statement_id = args.get('statement', None)467 if not statement_id:468 journal_id = args.get('journal_id', None)469 user = User(1)470 statements = cls.search([471 ('journal', '=', journal_id),472 ('state', '=', 'draft'),473 ('sale_device', '=', user.sale_device.id),474 ])475 if statements:476 statement_id = statements[0].id477 else:478 return479 date = args.get('date', None)480 if not date:481 date = Date.today()482 for sale in sales.keys():483 total_paid = Decimal(0.0)484 if sale.payments:485 total_paid = sum([p.amount for p in sale.payments])486 if total_paid >= sale.total_amount:487 if total_paid == sale.total_amount:488 Sale.do_reconcile([sale])489 else:490 msg = f"{sale.id_tecno} sale_pos.msg_total_paid_>_total_amount"491 logs.append(msg)492 to_exception.append(sale.id_tecno)493 continue494 total_pay = args.get('sales')[sale]495 if not total_pay:496 total_pay = sale.total_amount497 else:498 dif = Decimal(total_paid + total_pay) - sale.total_amount499 dif = Decimal(abs(dif))500 if dif < Decimal(600.0) and dif != 0:501 total_pay = sale.total_amount502 if not sale.invoice or (sale.invoice.state != 'posted' and sale.invoice.state != 'paid'):503 Sale.post_invoice(sale)504 if not sale.party.account_receivable:505 Party = pool.get('party.party')506 config = Configuration(1)507 if config.default_account_receivable:508 Party.write([sale.party], {509 'account_receivable': config.default_account_receivable.id510 })511 else:512 msg = f"sale_pos.msg_party_without_account_receivable"513 logs.append(msg)514 to_exception.append(sale.id_tecno)515 continue516 account_id = sale.party.account_receivable.id517 to_create = {518 'sale': sale.id,519 'date': date,520 'statement': statement_id,521 'amount': total_pay,522 'party': sale.party.id,523 'account': account_id,524 'description': sale.invoice_number or sale.invoice.number or '',525 }526 line, = StatementLine.create([to_create])527 write_sale = {528 'turn': line.statement.turn,529 }530 if hasattr(sale, 'order_status'):531 write_sale['order_status'] = 'delivered'532 Sale.write([sale], write_sale)533 if (total_pay + total_paid) == sale.total_amount:534 Sale.do_reconcile([sale])535 return 'ok'536 @classmethod537 def force_draft(cls, sales):538 sale_table = Table('sale_sale')539 invoice_table = Table('account_invoice')540 move_table = Table('account_move')541 stock_move_table = Table('stock_move')542 statement_line = Table('account_statement_line')543 cursor = Transaction().connection.cursor()544 for sale in sales:545 for invoice in sale.invoices:546 if (hasattr(invoice, 'cufe') and invoice.cufe) or \547 hasattr(invoice, 'electronic_state') and \548 invoice.electronic_state == 'submitted':549 raise UserError('account_col.msg_with_electronic_invoice')550 if invoice.state == 'paid':551 invoice.unreconcile_move(invoice.move)552 if invoice.move:553 cursor.execute(*move_table.update(554 columns=[move_table.state],555 values=['draft'],556 where=move_table.id == invoice.move.id)557 )558 cursor.execute(*move_table.delete(559 where=move_table.id == invoice.move.id)560 )561 cursor.execute(*invoice_table.update(562 columns=[invoice_table.state, invoice_table.number],563 values=['validate', None],564 where=invoice_table.id == invoice.id)565 )566 cursor.execute(*invoice_table.delete(567 where=invoice_table.id == invoice.id)568 )569 #Se pasa a estado borrador la venta570 cursor.execute(*sale_table.update(571 columns=[sale_table.state, sale_table.shipment_state, sale_table.invoice_state],572 values=['draft', 'none', 'none'],573 where=sale_table.id == sale.id)574 )575 # The stock moves must be delete576 stock_moves = [m.id for line in sale.lines for m in line.moves]577 if stock_moves:578 cursor.execute(*stock_move_table.update(579 columns=[stock_move_table.state],580 values=['draft'],581 where=stock_move_table.id.in_(stock_moves)582 ))583 #Eliminación de los movimientos584 cursor.execute(*stock_move_table.delete(585 where=stock_move_table.id.in_(stock_moves))586 )587 #Se verifica si tiene lineas de pago y se eliminan588 if sale.payments:589 for payment in sale.payments:590 cursor.execute(*statement_line.delete(591 where=statement_line.id == payment.id)592 )593 @classmethod594 def delete_imported_sales(cls, sales):595 sale_table = Table('sale_sale')596 cursor = Transaction().connection.cursor()597 Conexion = Pool().get('conector.configuration')598 ids_tecno = []599 for sale in sales:600 if sale.id_tecno:601 ids_tecno.append(sale.id_tecno)602 else:603 raise UserError("Error: ", f"No se encontró el id_tecno de {sale}")604 cls.force_draft([sale])605 #Se elimina la venta606 cursor.execute(*sale_table.delete(where=sale_table.id == sale.id))607 for id in ids_tecno:...
test_model.py
Source:test_model.py
...23 def test_is_exception(self):24 self.assertFalse(self.model.is_exception(ElementTree.fromstring("<RTT>test</RTT>")))25 self.assertTrue(self.model.is_exception(ElementTree.fromstring("<TransitServiceError>test</TransitServiceError>")))26 self.assertTrue(self.model.is_exception(ElementTree.fromstring("<TransitServiceError></TransitServiceError>")))27 def test_to_exception(self):28 self.assertRaises(ValueError, self.model.to_exception, ElementTree.fromstring("<RTT>test</RTT>"))29 self.assertIsInstance(self.model.to_exception(30 ElementTree.fromstring("<TransitServiceError>No match</TransitServiceError>")), 31 TransitServiceError)32 self.assertIsInstance(self.model.to_exception(33 ElementTree.fromstring("<TransitServiceError>Token is required</TransitServiceError>")), 34 TokenRequired)35 self.assertIsInstance(self.model.to_exception(36 ElementTree.fromstring("<TransitServiceError>Invalid credentials</TransitServiceError>")), 37 InvalidToken)38 self.assertIsInstance(self.model.to_exception(39 ElementTree.fromstring("<TransitServiceError> The Agency name is Invalid </TransitServiceError>")), 40 InvalidAgency)41 self.assertIsInstance(self.model.to_exception(42 ElementTree.fromstring("<TransitServiceError> Agency is required </TransitServiceError>")), 43 AgencyRequired)44 self.assertIsInstance(self.model.to_exception(45 ElementTree.fromstring("<TransitServiceError> routeIDF is required </TransitServiceError>")), 46 RouteIDFRequired)47 self.assertIsInstance(self.model.to_exception(48 ElementTree.fromstring("<TransitServiceError> Invalid routeIDF </TransitServiceError>")), 49 InvalidRouteIDF)50 self.assertIsInstance(self.model.to_exception(51 ElementTree.fromstring("<TransitServiceError> stopCode is required </TransitServiceError>")), 52 StopCodeRequired)...
helpers.py
Source:helpers.py
...15 res.__qualname__ = wrapped.__qualname__16 res.__doc__ = wrapped.__doc__17 res.__module__ = wrapped.__module__18 return res19def to_exception(exc_type, exc_value=None, exc_tb=None):20 if exc_type is None:21 return None22 if isinstance(exc_type, BaseException):23 exc_value = exc_type24 exc_type = type(exc_value)25 if exc_value is None:26 exc_value = exc_type()27 if exc_tb is not None:28 exc_value = exc_value.with_traceback(exc_tb)29 return exc_value...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!