From 8f8cae1d7d12e84dff36fadb0fb63a97835094f8 Mon Sep 17 00:00:00 2001 From: Luis Felipe Mileo Date: Mon, 10 Apr 2023 22:21:02 -0300 Subject: [PATCH] [IMP] Export test --- LICENSE | 2 +- nfselib/barueri/exportador.py | 88 +++++++++++++++++++++++++++++------ tests/test_exportador.py | 62 ++++++++++++++++++++++++ tests/test_nfselib_barueri.py | 6 +-- 4 files changed, 140 insertions(+), 18 deletions(-) create mode 100644 tests/test_exportador.py diff --git a/LICENSE b/LICENSE index 4264114..1a4c723 100644 --- a/LICENSE +++ b/LICENSE @@ -6,4 +6,4 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/nfselib/barueri/exportador.py b/nfselib/barueri/exportador.py index 457eacb..5a820cc 100644 --- a/nfselib/barueri/exportador.py +++ b/nfselib/barueri/exportador.py @@ -3,6 +3,17 @@ class CampoPosicional: def __init__(self, nome, valor, obrigatorio, tipo, tamanho, posicao_inicial, posicao_final): + """A class representing a positional field in a file. + + Args: + nome (str): The name of the field. + valor (Any): The value of the field. + obrigatorio (bool): Whether the field is required or not. + tipo (str): The type of the data ("ALFA" or "NUM"). + tamanho (int): The size of the field. + posicao_inicial (int): The starting position of the field. + posicao_final (int): The ending position of the field. + """ self.nome = nome self.valor = valor self.obrigatorio = obrigatorio @@ -12,56 +23,105 @@ def __init__(self, nome, valor, obrigatorio, tipo, tamanho, posicao_inicial, pos self.posicao_final = posicao_final def exportar(self): + """Formats and exports the field value based on its type. + + Returns: + str: The formatted field value. + """ if self.tipo == "ALFA": - formatado = str(self.valor).ljust(self.tamanho) + formatado = str(self.valor).ljust(self.tamanho) # Format the string as left-justified elif self.tipo == "NUM": - formatado = str(self.valor).rjust(self.tamanho, "0") + formatado = str(self.valor).rjust(self.tamanho, "0") # Format the string as right-justified with zeroes added to the left else: - raise ValueError(f"Tipo desconhecido: {self.tipo}") + raise ValueError(f"Tipo desconhecido: {self.tipo}") # Raise an error if the data type is unknown - return formatado[: self.tamanho] + return formatado[: self.tamanho] # Return only the first n characters of the formatted string based on the field size class Registro: - campos = [] + campos = [] # A list to store the fields in the record def exportar(self): + """Exports the record by concatenating its fields. + + Returns: + str: The concatenated fields. + """ return ''.join([campo.exportar() for campo in self.campos]) def __setattr__(self, name, value): + """Sets the value of a field in the record. + + Args: + name (str): The name of the field. + value (Any): The new value of the field. + + Raises: + AttributeError: If the field name is not recognized. + """ if name != "campos" and name in {campo.nome for campo in self.campos}: for campo in self.campos: if campo.nome == name: - campo.valor = value + campo.valor = value # Set the value of the field return - raise AttributeError(f"Campo desconhecido: {name}") super().__setattr__(name, value) def __getattr__(self, name): + """Gets the value of a field in the record. + + Args: + name (str): The name of the field. + + Raises: + AttributeError: If the field name is not recognized. + + Returns: + Any: The value of the field. + """ if name in {campo.nome for campo in self.campos}: for campo in self.campos: if campo.nome == name: - return campo.valor - raise AttributeError(f"Campo desconhecido: {name}") + return campo.valor # Return the value of the field + raise AttributeError(f"Campo desconhecido: {name}") # Raise an error if the field name is not recognized return super().__getattribute__(name) class Arquivo: def __init__(self, registros=None): + """Initializes a new file object. + + Args: + registros (list[Registro], optional): A list of records in the file. Defaults to None. + """ if registros is None: registros = [] - self.registros = registros + self.registros = registros # Initializes the list of records def adicionar_registro(self, registro): + """Adds a record to the file. + + Args: + registro (Registro): The record to be added. + """ self.registros.append(registro) def exportar_txt(self, caminho_arquivo): - with open(caminho_arquivo, "w") as arquivo: + """Exports the file as a text file. + + Args: + caminho_arquivo (str): The file path to save the exported file. + """ + with open(caminho_arquivo, "w") as arquivo: # Opens the file for writing for registro in self.registros: - arquivo.write(registro.exportar()) + arquivo.write(registro.exportar()) # Writes each record to the file def exportar(self): + """Exports the file as a string. + + Returns: + str: The concatenated records in the file. + """ texto = '' for registro in self.registros: - texto += registro.exportar() - return texto + texto += registro.exportar() # Concatenates the export of each record + return texto # Returns the concatenated result diff --git a/tests/test_exportador.py b/tests/test_exportador.py new file mode 100644 index 0000000..836f840 --- /dev/null +++ b/tests/test_exportador.py @@ -0,0 +1,62 @@ +import unittest + +from nfselib.barueri.exportador import Arquivo +from nfselib.barueri.exportador import CampoPosicional +from nfselib.barueri.exportador import Registro + + +class TestCampoPosicional(unittest.TestCase): + def test_exportar(self): + campo = CampoPosicional("nome", "valor", True, "ALFA", 10, 1, 10) + self.assertEqual(campo.exportar(), "valor ") + + +class TestRegistro(unittest.TestCase): + def test_campos(self): + registro = Registro() + campo_1 = CampoPosicional("campo1", "valor1", True, "NUM", 5, 1, 5) + campo_2 = CampoPosicional("campo2", "valor2", False, "ALFA", 10, 6, 15) + registro.campos = [campo_1, campo_2] + + # test __setattr__ + registro.campo1 = "new_value" + self.assertEqual(registro.campos[0].valor, "new_value") + + # test __getattr__ + self.assertEqual(registro.campo1, "new_value") + self.assertEqual(registro.campo2, "valor2") + + def test_exportar(self): + registro = Registro() + campo_1 = CampoPosicional("campo1", "12345", True, "NUM", 5, 1, 5) + campo_2 = CampoPosicional("campo2", "valor2", False, "ALFA", 10, 6, 15) + registro.campos = [campo_1, campo_2] + self.assertEqual(registro.exportar(), "12345valor2 ") + + +class TestArquivo(unittest.TestCase): + def test_adicionar_registro(self): + arquivo = Arquivo() + registro = Registro() + arquivo.adicionar_registro(registro) + self.assertEqual(len(arquivo.registros), 1) + self.assertEqual(arquivo.registros[0], registro) + + def test_exportar(self): + arquivo = Arquivo() + registro_1 = Registro() + campo_1_1 = CampoPosicional("campo1", "12345", True, "NUM", 5, 1, 5) + campo_1_2 = CampoPosicional("campo2", "valor2", False, "ALFA", 10, 6, 15) + registro_1.campos = [campo_1_1, campo_1_2] + + registro_2 = Registro() + campo_2_1 = CampoPosicional("campo1", "12345", True, "NUM", 5, 1, 5) + campo_2_2 = CampoPosicional("campo2", "valor4", False, "ALFA", 10, 6, 15) + registro_2.campos = [campo_2_1, campo_2_2] + + arquivo.registros = [registro_1, registro_2] + self.assertEqual(arquivo.exportar(), "12345valor2 12345valor4 ") + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_nfselib_barueri.py b/tests/test_nfselib_barueri.py index 015dcba..44ccd0f 100644 --- a/tests/test_nfselib_barueri.py +++ b/tests/test_nfselib_barueri.py @@ -22,6 +22,6 @@ def test_gerar_registro_tipo_1(): rps.exportar_txt("rps_teste.txt") # Lendo e imprimindo o conteúdo do arquivo TXT gerado - # with open("rps_teste.txt", "r") as arquivo: - # conteudo = arquivo.read() - # print(conteudo) + with open("rps_teste.txt", "r") as arquivo: + conteudo = arquivo.read() + print(conteudo)