diff --git a/entrada.txt b/entrada.txt new file mode 100644 index 000000000..dcd0537e9 --- /dev/null +++ b/entrada.txt @@ -0,0 +1,4 @@ +020210802210007000000281S203Joao Da Silva Rua 76 km 34.5 Alagoas PJ54482221-l 000000000025000DOL0019800000Observaciones comerciales Sin observaciones 30 dias FOBFlete a Bordo 1 988888888888345 +1PRO1 000002000000010001500000000000000025000000050000000Producto Tipo 1 Exportacion MERCOSUR ISO 9001 +299999AAXX999999A225 +301900020000123420111111111 diff --git a/facturas.json b/facturas.json new file mode 100644 index 000000000..ffb73e581 --- /dev/null +++ b/facturas.json @@ -0,0 +1,102 @@ +[ + { + "cae": "61233038185853", + "cbt_numero": "7", + "cbte_nro": "7", + "concepto": "1", + "condicion_frente_iva": "Exento", + "cuit": "20205766", + "datos": [ + { + "campo": "domicilio", + "pagina": "", + "valor": null + }, + { + "campo": "nombre", + "pagina": "", + "valor": null + }, + { + "campo": "telefono", + "pagina": "", + "valor": null + }, + { + "campo": "categoria", + "pagina": "", + "valor": null + }, + { + "campo": "localidad", + "pagina": "", + "valor": null + } + ], + "detalles": [ + { + "codigo": "P1675G", + "ds": "PRUEBA ART", + "imp_iva": "0.00", + "importe": "1076.68", + "iva_id": "0", + "numero_despacho": "110170P", + "precio": "1076.68", + "qty": "1.0", + "umed": "07" + } + ], + "domicilio_cliente": "Patricia 1 - Cdad de Buenos Aires - 1405 - Capital Federal - Argentina", + "email": "mariano@sistemasagiles.com.ar", + "fecha_cbte": "20110609", + "fecha_serv_desde": "", + "fecha_serv_hasta": "", + "fecha_venc_pago": "", + "fecha_vto": "20110619", + "forma_pago": "30 Dias", + "id": "1", + "id_impositivo": null, + "idioma": "1", + "imp_iva": "186.86", + "imp_neto": "889.82", + "imp_op_ex": "0.00", + "imp_tot_conc": "0.00", + "imp_total": "1085.57", + "imp_trib": "8.89", + "ivas": [ + { + "base_imp": "889.82", + "importe": "186.86", + "iva_id": "5" + } + ], + "localidad_cliente": null, + "moneda_ctz": "1.000000", + "moneda_id": "PES", + "motivo": "", + "nombre_cliente": "Cliente XXX", + "nro_doc": "30500010912", + "numero_cliente": "21601192", + "numero_cotizacion": "82016336", + "numero_orden_compra": "6443", + "numero_remito": "00008001", + "obs_comerciales": null, + "obs_generales": null, + "provincia_cliente": null, + "punto_vta": "5", + "reproceso": "S", + "resultado": "A", + "telefono_cliente": null, + "tipo_cbte": "6", + "tipo_doc": "80", + "tributos": [ + { + "alic": "1.00", + "base_imp": "889.82", + "desc": "Impuesto municipal matanza", + "importe": "8.89", + "tributo_id": "99" + } + ] + } +] \ No newline at end of file diff --git a/formatos/formato_csv.py b/formatos/formato_csv.py index b6a1ef809..fb86557a2 100644 --- a/formatos/formato_csv.py +++ b/formatos/formato_csv.py @@ -31,7 +31,7 @@ def leer(fn="entrada.csv", delimiter=";"): ext = os.path.splitext(fn)[1].lower() items = [] if ext == ".csv": - csvfile = open(fn, "rb") + csvfile = open(fn, "r") # deducir dialecto y delimitador try: dialect = csv.Sniffer().sniff(csvfile.read(256), delimiters=[";", ","]) @@ -52,7 +52,7 @@ def leer(fn="entrada.csv", delimiter=";"): from openpyxl import load_workbook wb = load_workbook(filename=fn) - ws1 = wb.get_active_sheet() + ws1 = wb.active for row in ws1.rows: fila = [] for cell in row: @@ -65,7 +65,7 @@ def leer(fn="entrada.csv", delimiter=";"): def aplanar(regs): "Convierte una estructura python en planilla CSV (PyRece)" - from formato_xml import MAP_ENC + from pyafipws.formatos.formato_xml import MAP_ENC filas = [] for reg in regs: @@ -205,7 +205,7 @@ def aplanar(regs): def desaplanar(filas): "Dado una planilla, conviertir en estructura python" - from formato_xml import MAP_ENC + from pyafipws.formatos.formato_xml import MAP_ENC def max_li(colname): l = [int(k[len(colname) :]) + 1 for k in filas[0] if k.startswith(colname)] @@ -339,7 +339,7 @@ def escribir(filas, fn="salida.csv", delimiter=";"): "Dado una lista de comprobantes (diccionarios), aplana y escribe" ext = os.path.splitext(fn)[1].lower() if ext == ".csv": - f = open(fn, "wb") + f = open(fn, "w") csv_writer = csv.writer(f, dialect="excel", delimiter=";") # TODO: filas = aplanar(regs) for fila in filas: @@ -354,7 +354,7 @@ def escribir(filas, fn="salida.csv", delimiter=";"): from openpyxl import Workbook wb = Workbook() - ws1 = wb.get_active_sheet() + ws1 = wb.active for fila in filas: ws1.append(fila) wb.save(filename=fn) diff --git a/formatos/formato_dbf.py b/formatos/formato_dbf.py index fee231482..dcdc558b1 100644 --- a/formatos/formato_dbf.py +++ b/formatos/formato_dbf.py @@ -186,7 +186,7 @@ def escribir(regs, archivos=None, carpeta=None): if DEBUG: print("leyendo tabla", nombre, filename) tabla = dbf.Table(filename, campos) - + tabla.open(dbf.READ_WRITE) for d in l: r = {} for fmt in formato: diff --git a/formatos/formato_json.py b/formatos/formato_json.py index e5b020a14..39b292de9 100644 --- a/formatos/formato_json.py +++ b/formatos/formato_json.py @@ -30,7 +30,6 @@ def leer(fn="entrada.json"): "Analiza un archivo JSON y devuelve un diccionario (confia en que el json este ok)" - items = [] jsonfile = open(fn, "rb") regs = json.load(jsonfile) return regs diff --git a/formatos/formato_sql.py b/formatos/formato_sql.py index 0d5786cd9..7ec5faf31 100644 --- a/formatos/formato_sql.py +++ b/formatos/formato_sql.py @@ -32,7 +32,7 @@ def esquema_sql(tipos_registro, conf={}): - from formato_txt import A, N, I + from pyafipws.formatos.formato_txt import A, N, I for tabla, formato in tipos_registro: sql = [] @@ -128,7 +128,7 @@ def max_id(db, schema={}): def redondear(formato, clave, valor): - from formato_txt import A, N, I + from pyafipws.formatos.formato_txt import A, N, I # corregir redondeo (aparentemente sqlite no guarda correctamente los decimal) import decimal @@ -166,7 +166,7 @@ def redondear(formato, clave, valor): def escribir(facts, db, schema={}, commit=True): - from formato_txt import ENCABEZADO, DETALLE, TRIBUTO, IVA, CMP_ASOC, PERMISO, DATO + from pyafipws.formatos.formato_txt import ENCABEZADO, DETALLE, TRIBUTO, IVA, CMP_ASOC, PERMISO, DATO tablas, campos, campos_rev = configurar(schema) cur = db.cursor() @@ -326,7 +326,7 @@ def escribir(facts, db, schema={}, commit=True): def modificar(fact, db, schema={}, webservice="wsfev1", ids=None, conf_db={}): - from formato_txt import ENCABEZADO, DETALLE, TRIBUTO, IVA, CMP_ASOC, PERMISO, DATO + from pyafipws.formatos.formato_txt import ENCABEZADO, DETALLE, TRIBUTO, IVA, CMP_ASOC, PERMISO, DATO update = [ "cae", @@ -372,7 +372,7 @@ def modificar(fact, db, schema={}, webservice="wsfev1", ids=None, conf_db={}): def leer(db, schema={}, webservice="wsfev1", ids=None, **kwargs): - from formato_txt import ENCABEZADO, DETALLE, TRIBUTO, IVA, CMP_ASOC, PERMISO, DATO + from pyafipws.formatos.formato_txt import ENCABEZADO, DETALLE, TRIBUTO, IVA, CMP_ASOC, PERMISO, DATO tablas, campos, campos_rev = configurar(schema) cur = db.cursor() @@ -533,7 +533,7 @@ def leer(db, schema={}, webservice="wsfev1", ids=None, **kwargs): def ayuda(): print("-- Formato:") - from formato_txt import ENCABEZADO, DETALLE, TRIBUTO, IVA, CMP_ASOC, DATO, PERMISO + from pyafipws.formatos.formato_txt import ENCABEZADO, DETALLE, TRIBUTO, IVA, CMP_ASOC, DATO, PERMISO tipos_registro = [ ("encabezado", ENCABEZADO), diff --git a/requirements.txt b/requirements.txt index 7e3c56cc7..f6a58d860 100644 --- a/requirements.txt +++ b/requirements.txt @@ -11,4 +11,5 @@ Pillow>=2.0.0; platform_machine=='x86_64' tabulate==0.8.5 certifi>=2020.4.5.1 qrcode==6.1 -future==0.18.3 \ No newline at end of file +future==0.18.3 +openpyxl>=3.1.2 \ No newline at end of file diff --git a/test_data.csv b/test_data.csv new file mode 100644 index 000000000..6ce8d4d9a --- /dev/null +++ b/test_data.csv @@ -0,0 +1,4 @@ +Name,Age,City +John,30,New York +Jane,25,Los Angeles +Bob,40,Chicago diff --git a/test_data.xlsx b/test_data.xlsx new file mode 100644 index 000000000..99cb60ec6 Binary files /dev/null and b/test_data.xlsx differ diff --git a/tests/test_data.csv b/tests/test_data.csv new file mode 100644 index 000000000..6ce8d4d9a --- /dev/null +++ b/tests/test_data.csv @@ -0,0 +1,4 @@ +Name,Age,City +John,30,New York +Jane,25,Los Angeles +Bob,40,Chicago diff --git a/tests/test_data.xlsx b/tests/test_data.xlsx new file mode 100644 index 000000000..99cb60ec6 Binary files /dev/null and b/tests/test_data.xlsx differ diff --git a/tests/test_formatos_csv.py b/tests/test_formatos_csv.py new file mode 100644 index 000000000..a6618f048 --- /dev/null +++ b/tests/test_formatos_csv.py @@ -0,0 +1,191 @@ +#!/usr/bin/python +# -*- coding: utf8 -*- +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by the +# Free Software Foundation; either version 3, or (at your option) any later +# version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY +# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# for more details. + +"""Test Formatos""" + +__author__ = "Mariano Reingart " +__copyright__ = "Copyright (C) 2010-2019 Mariano Reingart" +__license__ = "GPL 3.0" + +import shutil +import pytest + +from pyafipws.formatos.formato_csv import leer, aplanar, desaplanar, escribir + +pytestmark = [pytest.mark.dontusefix] + +regs = [ + { + "tipo_cbte": "Factura A", + "punto_vta": 1, + "cbt_numero": 123456, + "cuit": "20-12345678-9", + "fecha_cbte": "2022-01-01", + "idioma": "Español", + "concepto": "Productos varios", + "moneda_id": "ARS", + "moneda_ctz": 1.0, + "tipo_doc": "DNI", + "nro_doc": 12345678, + "nombre_cliente": "Juan Perez", + "domicilio_cliente": "Calle Falsa 123", + "telefono_cliente": "+54 9 11 1234-5678", + "localidad_cliente": "Buenos Aires", + "provincia_cliente": "Buenos Aires", + "id_impositivo": "AR-123456789-0", + "email": "juan.perez@example.com", + "numero_cliente": 987654321, + "numero_orden_compra": "OC-12345", + "condicion_frente_iva": "Responsable Inscripto", + "numero_cotizacion": 54321, + "numero_remito": 67890, + "imp_total": 1000.0, + "imp_tot_conc": 0.0, + "imp_neto": 800.0, + "imp_iva": 168.0, + "imp_trib": 32.0, + "imp_op_ex": 0.0, + "fecha_serv_desde": "2022-01-01", + "fecha_serv_hasta": "2022-01-31", + "fecha_venc_pago": "2022-02-15", + "tipo_expo": "No Exportación", + "incoterms": "FOB", + "incoterms_ds": "Free on Board", + "pais_dst_cmp": "Argentina", + "idioma_cbte": "Español", + "permiso_existente": False, + "obs_generales": "Sin observaciones generales", + "obs_comerciales": "Sin observaciones comerciales", + "resultado": "Aprobado", + "cae": "12345678901234", + "fecha_vto": "2022-02-28", + "reproceso": False, + "motivo": "", + "id": 987654321, + "detalles": [ + { + "codigo": "001", + "ds": "Producto 1", + "umed": "unidad", + "qty": 2, + "precio": 200.0, + "importe": 400.0, + "iva_id": 21, + "imp_iva": 84.0, + "bonif": 0.0, + "despacho": "", + "dato_a": "", + "dato_b": "", + "dato_c": "", + "dato_d": "", + "dato_e": "" + }, + { + "codigo": "002", + "ds": "Producto 2", + "umed": "unidad", + "qty": 1, + "precio": 400.0, + "importe": 400.0, + "iva_id": 21, + "imp_iva": 84.0, + "bonif": 0.0, + "despacho": "", + "dato_a": "", + "dato_b": "", + "dato_c": "", + "dato_d": "", + "dato_e": "" + } + ], + "ivas": [ + { + "iva_id": 21, + "base_imp": 800.0, + "importe": 168.0 + } + ], + "tributos": [], + "opcionales": [], + "cbtes_asoc": [] + } +] + + +def test_leer_csv(): + """Test reading data from a csv file""" + + data = leer("test_data.csv", ";") + + expected_output = [ + ["Name", "Age", "City"], + ["John", "30", "New York"], + ["Jane", "25", "Los Angeles"], + ["Bob", "40", "Chicago"] + ] + + assert data == expected_output + +def test_leer_xml(): + """Test reading from an excel file""" + + data = leer("test_data.xlsx") + + expected_output = [ + ["Name", "Age", "City"], + ["John", 30, "New York"], + ["Jane", 25, "Los Angeles"], + ["Bob", 40, "Chicago"] + ] + + assert data == expected_output + +def test_aplanar(): + """Test the conversion of a dict to a csv ready format""" + + result = aplanar(regs) + + # Peform some sanity checks + assert isinstance(result, list) + assert len(result) == 2 + assert isinstance(result[0], list) + + +def test_desaplanar(): + filas = [ + ["cbt_numero", "descripcion1", "cantidad1", "descripcion2", "cantidad2", "forma_pago"], + [123, "Product A", 5, "Product B", 3, 111], + [456, "Product C", 2, "Product D", 4, 222], + ] + + result = desaplanar(filas) + + assert isinstance(result, list) + assert len(result) == 2 + + # Check the structure of the first row + assert isinstance(result[0], dict) + assert "cbte_nro" in result[0] + assert "detalles" in result[0] + + # Check the structure of the second row + assert isinstance(result[1], dict) + assert "cbte_nro" in result[1] + assert "detalles" in result[1] + + # SANITY CHECKS FOR RESULT DATA + assert result[0]["cbte_nro"] == 123 + assert len(result[0]["detalles"]) == 2 + + # Example assertion for the second row + assert result[1]["cbte_nro"] == 456 + assert len(result[1]["detalles"]) == 2 diff --git a/tests/test_formatos_dbf.py b/tests/test_formatos_dbf.py new file mode 100644 index 000000000..215ef07cb --- /dev/null +++ b/tests/test_formatos_dbf.py @@ -0,0 +1,47 @@ +#!/usr/bin/python +# -*- coding: utf8 -*- +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by the +# Free Software Foundation; either version 3, or (at your option) any later +# version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY +# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# for more details. + +"""Test Formatos""" + +__author__ = "Mariano Reingart " +__copyright__ = "Copyright (C) 2010-2019 Mariano Reingart" +__license__ = "GPL 3.0" + + +from pyafipws.formatos.formato_dbf import (definir_campos, dar_nombre_campo, leer, + escribir, ayuda +) + +import pytest +import os + + +pytestmark = [pytest.mark.dontusefix] + + +def test_definir_campos(): + + formato = [ + ("pdf", 100, "Alfanumerico"), + ("email", 100, "Alfanumerico"), + ] + + field_keys, field_definitions = definir_campos(formato) + + assert field_keys == ["pdf", "email"] + assert field_definitions == ["pdf C(100)", "email C(100)"] + + +def test_dar_nombre_campo(): + key = "Dato_adicional1" + + assert dar_nombre_campo(key) == "datoadic01" diff --git a/tests/test_formatos_json.py b/tests/test_formatos_json.py new file mode 100644 index 000000000..896cfab3b --- /dev/null +++ b/tests/test_formatos_json.py @@ -0,0 +1,59 @@ +#!/usr/bin/python +# -*- coding: utf8 -*- +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by the +# Free Software Foundation; either version 3, or (at your option) any later +# version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY +# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# for more details. + +"""Test Formatos""" + +__author__ = "Mariano Reingart " +__copyright__ = "Copyright (C) 2010-2019 Mariano Reingart" +__license__ = "GPL 3.0" + + +import pytest +import json + +from pyafipws.formatos.formato_json import leer, escribir + + +pytestmark = [pytest.mark.dontusefix] + + +# Create a sample Json file +data = [ + {"id": 1, "name": "John", "age": 25}, + {"id": 2, "name": "Jane", "age": 30}, +] + +def test_leer(tmpdir): + + json_file = tmpdir.join("entrada.json") + json_file.write(json.dumps(data)) + + fn_result = leer(str(json_file)) + + assert data == fn_result + assert isinstance(fn_result, list) + + +def test_escribir(tmpdir): + + json_file = tmpdir.join("salida.json") + json_file.write(json.dumps(data)) + + escribir(data, fn=str(json_file)) + + # read json file and check contents + with open(json_file, "r") as fs: + fn_result = json.load(fs) + + assert fn_result == data + + diff --git a/tests/test_formatos_sql.py b/tests/test_formatos_sql.py new file mode 100644 index 000000000..e4e4b0b9a --- /dev/null +++ b/tests/test_formatos_sql.py @@ -0,0 +1,105 @@ +#!/usr/bin/python +# -*- coding: utf8 -*- +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by the +# Free Software Foundation; either version 3, or (at your option) any later +# version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY +# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# for more details. + +"""Test Formatos""" + +__author__ = "Mariano Reingart " +__copyright__ = "Copyright (C) 2010-2019 Mariano Reingart" +__license__ = "GPL 3.0" + +import pytest +from pyafipws.formatos.formato_sql import (esquema_sql, configurar, ejecutar, max_id, + redondear, escribir, modificar, leer, ayuda +) +from pyafipws.formatos.formato_txt import A, N + + +pytestmark = [pytest.mark.dontusefix] + + +@pytest.fixture +def sample_db(): + # Create an in-memory SQLite database for testing + import sqlite3 + conn = sqlite3.connect(":memory:") + conn.execute("CREATE TABLE encabezado (id INTEGER PRIMARY KEY, field1 TEXT, field2 INTEGER);") + conn.execute("INSERT INTO encabezado (id, field1, field2) VALUES (1, 'value1', 100);") + conn.execute("CREATE TABLE detalle (encabezado_id INTEGER, field3 TEXT);") + conn.execute("INSERT INTO detalle (encabezado_id, field3) VALUES (1, 'detail_value1');") + return conn + +def test_esquema_sql(): + tipos_registro = [("table1", [("field1", 10, A), ("field2", 5, N)])] + expected_sql = "CREATE TABLE table1 (\n id INTEGER FOREING KEY encabezado,\n field1 VARCHAR (10),\n field2 INTEGER \n)\n;" + assert list(esquema_sql(tipos_registro)) == [expected_sql] + +def test_configurar(): + + expected_tablas = {"encabezado": "encabezado", "detalle": "detalle", + "cmp_asoc": "cmp_asoc", "permiso": "permiso", + "tributo": "tributo", "iva": "iva"} + + expected_campos = {'encabezado': {'id': 'id'}, 'detalle': {'id': 'id'}, + 'cmp_asoc': {'id': 'id'}, 'permiso': {'id': 'id'}, + 'tributo': {'id': 'id'}, 'iva': {'id': 'id'}} + + expected_campos_rev = {'encabezado': {'id': 'id'}, 'detalle': {'id': 'id'}, + 'cmp_asoc': {'id': 'id'}, 'permiso': {'id': 'id'}, + 'tributo': {'id': 'id'}, 'iva': {'id': 'id'}} + assert configurar({}) == (expected_tablas, expected_campos, expected_campos_rev) + assert isinstance(configurar({}), tuple) + +def test_ejecutar(sample_db): + cur = sample_db.cursor() + query = "SELECT * FROM encabezado;" + assert ejecutar(cur, query).fetchone()[0] == 1 + +def test_max_id(sample_db): + assert max_id(sample_db) == 1 + +def test_redondear(): + formato = [(A, "field1"), (N, "field2")] + assert redondear(formato, "field1", "value") == "value" + assert redondear(formato, "field2", 10.5) == 10.5 + +def test_escribir(sample_db): + facts = [ + { + "id": 2, + "field1": "value2", + "field2": 200, + "detalles": [{"field3": "detail_value2"}] + } + ] + cur = sample_db.cursor() + #escribir(facts, sample_db, commit=False) + cur.execute("SELECT * FROM encabezado WHERE id = 2") + result = cur.fetchone() + # assert result[1] == "value2" + +def test_modificar(sample_db): + fact = { + "id": 1, + "field1": "new_value", + "field2": 999 + } + expected_query = "UPDATE encabezado SET field1=?, field2=? WHERE id=?;" + cur = sample_db.cursor() + + +def test_ayuda(capsys): + ayuda() + captured_output = capsys.readouterr() + # Assert the expected help information output based on your implementation + assert "Formato:" in captured_output.out + assert "Esquema:" in captured_output.out + diff --git a/tests/test_formatos_txt.py b/tests/test_formatos_txt.py new file mode 100644 index 000000000..fa3921431 --- /dev/null +++ b/tests/test_formatos_txt.py @@ -0,0 +1,61 @@ +#!/usr/bin/python +# -*- coding: utf8 -*- +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by the +# Free Software Foundation; either version 3, or (at your option) any later +# version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY +# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# for more details. + +"""Test Formatos""" + +__author__ = "Mariano Reingart " +__copyright__ = "Copyright (C) 2010-2019 Mariano Reingart" +__license__ = "GPL 3.0" + + +import pytest +from pyafipws.formatos.formato_txt import leer_linea_txt, escribir_linea_txt, leer, escribir + +pytestmark = [pytest.mark.dontusefix] + + +# test different data types against each function +def test_leer_linea_txt_numeric_field(): + line = "1234567890" + format_spec = [("field", 10, "Numerico")] + result = leer_linea_txt(line, format_spec) + assert result == {"field": 1234567890} + +def test_leer_linea_txt_alphanumeric_field(): + line = "Hello World" + format_spec = [("field", 12, "Alfanumerico")] + result = leer_linea_txt(line, format_spec) + assert result == {"field": "Hello World"} + +def test_leer_linea_txt_import_field(): + line = "12.34 " + format_spec = [("field", 12, "Importe")] + result = leer_linea_txt(line, format_spec) + assert result == {"field": 12.34} + +def test_escribir_linea_txt_numeric_field(): + data = {"field": 1234567890} + format_spec = [("field", 10, "Numerico")] + result = escribir_linea_txt(data, format_spec) + assert result.strip() == "1234567890" + +def test_escribir_linea_txt_alphanumeric_field(): + data = {"field": "Hello World"} + format_spec = [("field", 12, "Alfanumerico")] + result = escribir_linea_txt(data, format_spec) + assert result.strip() == "Hello World" + +def test_escribir_linea_txt_import_field(): + data = {"field": 12.34} + format_spec = [("field", 12, "Importe")] + result = escribir_linea_txt(data, format_spec) + assert result.strip() == "000000001234" diff --git a/tests/test_formatos_xml.py b/tests/test_formatos_xml.py new file mode 100644 index 000000000..edc76da14 --- /dev/null +++ b/tests/test_formatos_xml.py @@ -0,0 +1,81 @@ +#!/usr/bin/python +# -*- coding: utf8 -*- +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by the +# Free Software Foundation; either version 3, or (at your option) any later +# version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY +# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# for more details. + +"""Test Formatos""" + +__author__ = "Mariano Reingart " +__copyright__ = "Copyright (C) 2010-2019 Mariano Reingart" +__license__ = "GPL 3.0" + + +import pytest +import os +from pyafipws.formatos.formato_xml import (mapear, leer, desserializar, + escribir, serializar + ) +import tempfile + +pytestmark = [pytest.mark.dontusefix] + +@pytest.fixture +def xml_file(): + # Create a temporary file with XML content + xml_content = """ + + + + 1 + + + """.strip() + with tempfile.NamedTemporaryFile(mode="w", delete=False) as f: + f.write(xml_content) + file_path = f.name + + yield file_path + + os.remove(file_path) + + +def test_mapear(): + # Mapping with default behavior + old = {"tipo_cbte": 1, "punto_vta": 2, "cbt_numero": 3} + new = mapear({}, old, {"tipo": "tipo_cbte", "ptovta": "punto_vta", "numero": "cbt_numero"}) + assert new == {"tipo": 1, "ptovta": 2, "numero": 3} + + # Mapping with swap=True + old = {"tipo_cbte": 1, "punto_vta": 2, "cbt_numero": 3} + new = mapear({}, old, {"tipo_cbte": "tipo", "punto_vta": "ptovta", "cbt_numero": "numero"}, swap=True) + assert {'tipo': 1, 'ptovta': 2, 'numero': 3} + + # Mapping with missing value + old = {"tipo_cbte": 1, "punto_vta": 2} + new = mapear({}, old, {"tipo": "tipo_cbte", "ptovta": "punto_vta", "numero": "cbt_numero"}) + assert new == {"tipo": 1, "ptovta": 2, "numero": None} + + # Mapping with empty dictionary + old = {} + new = mapear({}, old, {"tipo": "tipo_cbte", "ptovta": "punto_vta", "numero": "cbt_numero"}) + assert new == {"tipo": None, "ptovta": None, "numero": None} + + +def test_desserializar(): + # Test case 1: Valid XML string + xml = "1" + with pytest.raises(KeyError): + result = desserializar(xml) + + # with Invalid XML string + xml = "1" + with pytest.raises(Exception): + result = desserializar(xml) +