Skip to content

Commit

Permalink
[IMP] Export test
Browse files Browse the repository at this point in the history
  • Loading branch information
mileo committed Apr 11, 2023
1 parent f542c9b commit 8f8cae1
Show file tree
Hide file tree
Showing 4 changed files with 140 additions and 18 deletions.
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
Expand Up @@ -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.
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.
88 changes: 74 additions & 14 deletions nfselib/barueri/exportador.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
62 changes: 62 additions & 0 deletions tests/test_exportador.py
Original file line number Diff line number Diff line change
@@ -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()
6 changes: 3 additions & 3 deletions tests/test_nfselib_barueri.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

0 comments on commit 8f8cae1

Please sign in to comment.