From 399310ce70b72bd08cf8938d49621f29c7b99ed9 Mon Sep 17 00:00:00 2001 From: SONIABHISHEK121 Date: Mon, 10 Jun 2024 12:25:30 +0530 Subject: [PATCH 1/3] test_formato_json.py : draft Signed-off-by: SONIABHISHEK121 --- formatos/formato_json.py | 19 ++-- tests/test_formato_json.py | 178 +++++++++++++++++++++++++++++++++++++ 2 files changed, 191 insertions(+), 6 deletions(-) create mode 100644 tests/test_formato_json.py diff --git a/formatos/formato_json.py b/formatos/formato_json.py index e5b020a14..d3e635f9f 100644 --- a/formatos/formato_json.py +++ b/formatos/formato_json.py @@ -28,12 +28,19 @@ print("para soporte de JSON debe instalar simplejson") -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 +def leer(archivo): + "Leer un archivo JSON y devolver una lista de diccionarios" + try: + with open(archivo, "r") as jsonfile: + content = jsonfile.read().strip() + if not content: + return [] # Return an empty list if the file is empty or contains only whitespace + regs = json.loads(content) + return regs + except json.decoder.JSONDecodeError: + return [] # Return an empty list if the file is not a valid JSON format + except Exception as e: + raise RuntimeError("Error al leer archivo JSON: {}".format(str(e))) def escribir(filas, fn="salida.json", **kwargs): diff --git a/tests/test_formato_json.py b/tests/test_formato_json.py new file mode 100644 index 000000000..0117c5da5 --- /dev/null +++ b/tests/test_formato_json.py @@ -0,0 +1,178 @@ +#!/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 para pyemail""" + +__author__ = "Mariano Reingart " +__copyright__ = "Copyright (C) 2010-2019 Mariano Reingart" +__license__ = "GPL 3.0" + + +import os +import unittest +import json +import stat +import pytest +from decimal import Decimal +from pyafipws.formatos.formato_json import leer, escribir +import tempfile + +@pytest.mark.dontusefix +class TestFormatoJSON(unittest.TestCase): + def setUp(self): + self.entrada_file = tempfile.NamedTemporaryFile(delete=False).name + self.salida_file = tempfile.NamedTemporaryFile(delete=False).name + + def tearDown(self): + try: + os.unlink(self.entrada_file) + except PermissionError: + pass + try: + os.unlink(self.salida_file) + except PermissionError: + pass + + def test_leer_archivo_facturas(self): + # Caso de prueba: Leer el archivo facturas.json + with open("tests/facturas.json", "r") as f: + expected_data = json.load(f) + result = leer("tests/facturas.json") + self.assertEqual(result, expected_data) + + def test_escribir_archivo_facturas(self): + # Caso de prueba: Escribir los datos de facturas.json en un nuevo archivo + with open("tests/facturas.json", "r") as f: + data = json.load(f) + temp_file = tempfile.NamedTemporaryFile(delete=False).name + escribir(data, temp_file) + with open(temp_file, "r") as f: + result = json.load(f) + self.assertEqual(result, data) + os.unlink(temp_file) + + def test_leer_archivo_facturas_modificado(self): + # Caso de prueba: Leer una versión modificada del archivo facturas.json + with open("tests/facturas.json", "r") as f: + data = json.load(f) + # Modificar los datos + data[0]["cae"] = "12345678901234" + data[0]["imp_total"] = "1500.00" + temp_file = tempfile.NamedTemporaryFile(delete=False).name + with open(temp_file, "w") as f: + json.dump(data, f) + result = leer(temp_file) + self.assertEqual(result, data) + os.unlink(temp_file) + + def test_leer_archivo_json_invalido(self): + # Caso de prueba: Leer un archivo con sintaxis JSON inválida + with open(self.entrada_file, "w") as f: + f.write('{"key": "value",}') # Sintaxis JSON inválida + with self.assertRaises(json.decoder.JSONDecodeError): + leer(self.entrada_file) + + def test_leer_archivo_vacio(self): + # Caso de prueba: Leer un archivo JSON vacío + with open(self.entrada_file, "w") as f: + f.write("") + try: + result = leer(self.entrada_file) + self.assertEqual(result, []) + except json.decoder.JSONDecodeError: + # Manejar el caso cuando el archivo está vacío o no tiene un formato JSON válido + pass + + def test_leer_archivo_valido(self): + # Caso de prueba: Leer un archivo JSON válido + data = [{"id": 1, "nombre": "Juan"}, {"id": 2, "nombre": "María"}] + with open(self.entrada_file, "w") as f: + json.dump(data, f) + result = leer(self.entrada_file) + self.assertEqual(result, data) + + def test_leer_archivo_inexistente(self): + # Caso de prueba: Leer un archivo JSON inexistente + with self.assertRaises(FileNotFoundError): + leer("archivo_inexistente.json") + + def test_leer_archivo_invalido(self): + # Caso de prueba: Leer un archivo JSON inválido + with open(self.entrada_file, "w") as f: + f.write("invalid JSON") + with self.assertRaises(json.JSONDecodeError): + leer(self.entrada_file) + + def test_escribir_lista_comprobantes(self): + # Caso de prueba: Escribir una lista de comprobantes (diccionarios) en un archivo JSON + comprobantes = [ + {"numero": 1, "fecha": "2023-06-01", "total": 100.50}, + {"numero": 2, "fecha": "2023-06-02", "total": 200.75}, + ] + escribir(comprobantes, self.salida_file) + with open(self.salida_file, "r") as f: + result = json.load(f) + self.assertEqual(result, comprobantes) + + def test_escribir_lista_vacia(self): + # Caso de prueba: Escribir una lista vacía en un archivo JSON + escribir([], self.salida_file) + with open(self.salida_file, "r") as f: + result = json.load(f) + self.assertEqual(result, []) + + def test_escribir_archivo_existente(self): + # Caso de prueba: Escribir en un archivo JSON existente + with open(self.salida_file, "w") as f: + f.write("existing content") + comprobantes = [{"numero": 1, "fecha": "2023-06-01", "total": 100.50}] + escribir(comprobantes, self.salida_file) + with open(self.salida_file, "r") as f: + result = json.load(f) + self.assertEqual(result, comprobantes) + + def test_escribir_datos_complejos(self): + # Caso de prueba: Escribir estructuras de datos complejas en un archivo JSON + datos = { + "nombre": "Juan", + "edad": 30, + "direccion": { + "calle": "Av. ejemplo", + "numero": 123, + "ciudad": "Buenos Aires" + }, + "telefonos": ["1234567890", "9876543210"], + "activo": True + } + escribir(datos, self.salida_file) + with open(self.salida_file, "r") as f: + result = json.load(f) + self.assertEqual(result, datos) + + def test_escribir_datos_unicode(self): + # Caso de prueba: Escribir datos con caracteres Unicode en un archivo JSON + datos = {"nombre": "Juan", "apellido": "Pérez", "ciudad": "Córdoba"} + escribir(datos, self.salida_file) + with open(self.salida_file, "r", encoding="utf-8") as f: + result = json.load(f) + self.assertEqual(result, datos) + + def test_escribir_datos_decimales(self): + # Caso de prueba: Escribir datos con objetos Decimal en un archivo JSON + datos = {"precio": Decimal("10.50"), "cantidad": Decimal("5")} + escribir(datos, self.salida_file, default=str) + with open(self.salida_file, "r") as f: + result = json.load(f) + self.assertEqual(result, {"precio": "10.50", "cantidad": "5"}) + +if __name__ == "__main__": + unittest.main() From 87db461ef2aed18e6a04ce5ef46597531b84bf2a Mon Sep 17 00:00:00 2001 From: SONIABHISHEK121 Date: Tue, 11 Jun 2024 12:45:57 +0530 Subject: [PATCH 2/3] build fail fixed Signed-off-by: SONIABHISHEK121 --- formatos/formato_json.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/formatos/formato_json.py b/formatos/formato_json.py index d3e635f9f..f54cde7e4 100644 --- a/formatos/formato_json.py +++ b/formatos/formato_json.py @@ -37,10 +37,11 @@ def leer(archivo): return [] # Return an empty list if the file is empty or contains only whitespace regs = json.loads(content) return regs - except json.decoder.JSONDecodeError: - return [] # Return an empty list if the file is not a valid JSON format - except Exception as e: - raise RuntimeError("Error al leer archivo JSON: {}".format(str(e))) + except json.decoder.JSONDecodeError as e: + raise json.decoder.JSONDecodeError("Error al leer archivo JSON: {}".format(str(e)), e.doc, e.pos) + except FileNotFoundError as e: + raise FileNotFoundError("Error al leer archivo JSON: {}".format(str(e))) + def escribir(filas, fn="salida.json", **kwargs): From 0bae6570d087cbf0c38d9b8a70ae2e180b4931c2 Mon Sep 17 00:00:00 2001 From: SONIABHISHEK121 Date: Tue, 9 Jul 2024 23:25:57 +0530 Subject: [PATCH 3/3] tests updated with pytest Signed-off-by: SONIABHISHEK121 --- tests/test_formato_json.py | 150 ++++++++++++++++--------------------- 1 file changed, 64 insertions(+), 86 deletions(-) diff --git a/tests/test_formato_json.py b/tests/test_formato_json.py index 0117c5da5..6e5af05e7 100644 --- a/tests/test_formato_json.py +++ b/tests/test_formato_json.py @@ -16,163 +16,141 @@ __copyright__ = "Copyright (C) 2010-2019 Mariano Reingart" __license__ = "GPL 3.0" - -import os -import unittest import json -import stat import pytest from decimal import Decimal from pyafipws.formatos.formato_json import leer, escribir -import tempfile + @pytest.mark.dontusefix -class TestFormatoJSON(unittest.TestCase): - def setUp(self): - self.entrada_file = tempfile.NamedTemporaryFile(delete=False).name - self.salida_file = tempfile.NamedTemporaryFile(delete=False).name +class TestFormatoJSON: + @pytest.fixture(autouse=True) + def setup(self, tmp_path): + self.entrada_file = tmp_path / "entrada.json" + self.salida_file = tmp_path / "salida.json" - def tearDown(self): - try: - os.unlink(self.entrada_file) - except PermissionError: - pass - try: - os.unlink(self.salida_file) - except PermissionError: - pass - def test_leer_archivo_facturas(self): - # Caso de prueba: Leer el archivo facturas.json + # Leer el archivo facturas.json with open("tests/facturas.json", "r") as f: expected_data = json.load(f) result = leer("tests/facturas.json") - self.assertEqual(result, expected_data) + assert result == expected_data - def test_escribir_archivo_facturas(self): - # Caso de prueba: Escribir los datos de facturas.json en un nuevo archivo + def test_escribir_archivo_facturas(self, tmp_path): + # Escribir los datos de facturas.json en un nuevo archivo with open("tests/facturas.json", "r") as f: data = json.load(f) - temp_file = tempfile.NamedTemporaryFile(delete=False).name - escribir(data, temp_file) + temp_file = tmp_path / "temp_facturas.json" + escribir(data, str(temp_file)) with open(temp_file, "r") as f: result = json.load(f) - self.assertEqual(result, data) - os.unlink(temp_file) + assert result == data - def test_leer_archivo_facturas_modificado(self): - # Caso de prueba: Leer una versión modificada del archivo facturas.json + def test_leer_archivo_facturas_modificado(self, tmp_path): + # Leer una versión modificada del archivo facturas.json with open("tests/facturas.json", "r") as f: data = json.load(f) # Modificar los datos data[0]["cae"] = "12345678901234" data[0]["imp_total"] = "1500.00" - temp_file = tempfile.NamedTemporaryFile(delete=False).name - with open(temp_file, "w") as f: - json.dump(data, f) - result = leer(temp_file) - self.assertEqual(result, data) - os.unlink(temp_file) - + temp_file = tmp_path / "modified_facturas.json" + temp_file.write_text(json.dumps(data)) + result = leer(str(temp_file)) + assert result == data + def test_leer_archivo_json_invalido(self): - # Caso de prueba: Leer un archivo con sintaxis JSON inválida - with open(self.entrada_file, "w") as f: - f.write('{"key": "value",}') # Sintaxis JSON inválida - with self.assertRaises(json.decoder.JSONDecodeError): - leer(self.entrada_file) - + # Leer un archivo con sintaxis JSON inválida + # Sintaxis JSON inválida + self.entrada_file.write_text('{"key": "value",}') + with pytest.raises(json.decoder.JSONDecodeError): + leer(str(self.entrada_file)) + def test_leer_archivo_vacio(self): - # Caso de prueba: Leer un archivo JSON vacío - with open(self.entrada_file, "w") as f: - f.write("") + # Leer un archivo JSON vacío + self.entrada_file.write_text("") try: - result = leer(self.entrada_file) - self.assertEqual(result, []) + result = leer(str(self.entrada_file)) + assert result == [] except json.decoder.JSONDecodeError: - # Manejar el caso cuando el archivo está vacío o no tiene un formato JSON válido + # Manejar el caso cuando el archivo está vacío o no tiene + # un formato JSON válido pass def test_leer_archivo_valido(self): - # Caso de prueba: Leer un archivo JSON válido + # Leer un archivo JSON válido data = [{"id": 1, "nombre": "Juan"}, {"id": 2, "nombre": "María"}] - with open(self.entrada_file, "w") as f: - json.dump(data, f) - result = leer(self.entrada_file) - self.assertEqual(result, data) - + self.entrada_file.write_text(json.dumps(data)) + result = leer(str(self.entrada_file)) + assert result == data + def test_leer_archivo_inexistente(self): - # Caso de prueba: Leer un archivo JSON inexistente - with self.assertRaises(FileNotFoundError): + # Leer un archivo JSON inexistente + with pytest.raises(FileNotFoundError): leer("archivo_inexistente.json") def test_leer_archivo_invalido(self): - # Caso de prueba: Leer un archivo JSON inválido - with open(self.entrada_file, "w") as f: - f.write("invalid JSON") - with self.assertRaises(json.JSONDecodeError): - leer(self.entrada_file) + # Leer un archivo JSON inválido + self.entrada_file.write_text("invalid JSON") + with pytest.raises(json.JSONDecodeError): + leer(str(self.entrada_file)) def test_escribir_lista_comprobantes(self): - # Caso de prueba: Escribir una lista de comprobantes (diccionarios) en un archivo JSON + # Escribir una lista de comprobantes (diccionarios) en un archivo JSON comprobantes = [ {"numero": 1, "fecha": "2023-06-01", "total": 100.50}, {"numero": 2, "fecha": "2023-06-02", "total": 200.75}, ] - escribir(comprobantes, self.salida_file) + escribir(comprobantes, str(self.salida_file)) with open(self.salida_file, "r") as f: result = json.load(f) - self.assertEqual(result, comprobantes) + assert result == comprobantes def test_escribir_lista_vacia(self): - # Caso de prueba: Escribir una lista vacía en un archivo JSON - escribir([], self.salida_file) + # Escribir una lista vacía en un archivo JSON + escribir([], str(self.salida_file)) with open(self.salida_file, "r") as f: result = json.load(f) - self.assertEqual(result, []) + assert result == [] def test_escribir_archivo_existente(self): - # Caso de prueba: Escribir en un archivo JSON existente - with open(self.salida_file, "w") as f: - f.write("existing content") + # Escribir en un archivo JSON existente + self.salida_file.write_text("existing content") comprobantes = [{"numero": 1, "fecha": "2023-06-01", "total": 100.50}] - escribir(comprobantes, self.salida_file) + escribir(comprobantes, str(self.salida_file)) with open(self.salida_file, "r") as f: result = json.load(f) - self.assertEqual(result, comprobantes) + assert result == comprobantes def test_escribir_datos_complejos(self): - # Caso de prueba: Escribir estructuras de datos complejas en un archivo JSON + # Escribir estructuras de datos complejas en un archivo JSON datos = { "nombre": "Juan", "edad": 30, "direccion": { "calle": "Av. ejemplo", "numero": 123, - "ciudad": "Buenos Aires" + "ciudad": "Buenos Aires", }, "telefonos": ["1234567890", "9876543210"], - "activo": True + "activo": True, } - escribir(datos, self.salida_file) + escribir(datos, str(self.salida_file)) with open(self.salida_file, "r") as f: result = json.load(f) - self.assertEqual(result, datos) + assert result == datos def test_escribir_datos_unicode(self): - # Caso de prueba: Escribir datos con caracteres Unicode en un archivo JSON + # Escribir datos con caracteres Unicode en un archivo JSON datos = {"nombre": "Juan", "apellido": "Pérez", "ciudad": "Córdoba"} - escribir(datos, self.salida_file) + escribir(datos, str(self.salida_file)) with open(self.salida_file, "r", encoding="utf-8") as f: result = json.load(f) - self.assertEqual(result, datos) + assert result == datos def test_escribir_datos_decimales(self): - # Caso de prueba: Escribir datos con objetos Decimal en un archivo JSON + # Escribir datos con objetos Decimal en un archivo JSON datos = {"precio": Decimal("10.50"), "cantidad": Decimal("5")} - escribir(datos, self.salida_file, default=str) + escribir(datos, str(self.salida_file), default=str) with open(self.salida_file, "r") as f: result = json.load(f) - self.assertEqual(result, {"precio": "10.50", "cantidad": "5"}) - -if __name__ == "__main__": - unittest.main() + assert result == {"precio": "10.50", "cantidad": "5"}