From e77aaa74a727bcafe17479bd62a25d360e7bdaa5 Mon Sep 17 00:00:00 2001 From: Danimar Ribeiro Date: Sat, 17 Sep 2016 09:21:03 -0300 Subject: [PATCH] Adding unit tests --- pytrustnfe/Servidores.py | 2 +- pytrustnfe/test/XMLs/jinja_remove_empty.xml | 1 + pytrustnfe/test/XMLs/jinja_result.xml | 1 + pytrustnfe/test/XMLs/jinja_template.xml | 6 ++ pytrustnfe/test/test_certificado.py | 20 +++++++ pytrustnfe/test/test_servidores.py | 42 ++++++++++++++ pytrustnfe/test/test_utils.py | 8 ++- pytrustnfe/test/test_xml.py | 26 +++++++++ pytrustnfe/test/test_xml_serializacao.py | 88 ++++++++++------------------- pytrustnfe/utils.py | 17 ++---- pytrustnfe/xml/__init__.py | 27 --------- pytrustnfe/xml/filters.py | 3 +- 12 files changed, 141 insertions(+), 100 deletions(-) create mode 100644 pytrustnfe/test/XMLs/jinja_remove_empty.xml create mode 100644 pytrustnfe/test/XMLs/jinja_result.xml create mode 100644 pytrustnfe/test/XMLs/jinja_template.xml create mode 100644 pytrustnfe/test/test_servidores.py create mode 100644 pytrustnfe/test/test_xml.py diff --git a/pytrustnfe/Servidores.py b/pytrustnfe/Servidores.py index a0c780a..69781a7 100644 --- a/pytrustnfe/Servidores.py +++ b/pytrustnfe/Servidores.py @@ -111,7 +111,7 @@ METODO_WS = { SVRS = { NFE_AMBIENTE_PRODUCAO: { - 'servidor': 'nfe.sefazvirtual.rs.gov.br', + 'servidor': 'nfe.svrs.rs.gov.br', WS_NFE_RECEPCAO_EVENTO: 'ws/recepcaoevento/recepcaoevento.asmx', WS_NFE_AUTORIZACAO: 'ws/NfeAutorizacao/NfeAutorizacao.asmx', WS_NFE_RET_AUTORIZACAO: 'ws/NfeRetAutorizacao/NfeRetAutorizacao.asmx', diff --git a/pytrustnfe/test/XMLs/jinja_remove_empty.xml b/pytrustnfe/test/XMLs/jinja_remove_empty.xml new file mode 100644 index 0000000..631bac8 --- /dev/null +++ b/pytrustnfe/test/XMLs/jinja_remove_empty.xml @@ -0,0 +1 @@ +oiolacomovai diff --git a/pytrustnfe/test/XMLs/jinja_result.xml b/pytrustnfe/test/XMLs/jinja_result.xml new file mode 100644 index 0000000..ace8e28 --- /dev/null +++ b/pytrustnfe/test/XMLs/jinja_result.xml @@ -0,0 +1 @@ +oiolacomovai diff --git a/pytrustnfe/test/XMLs/jinja_template.xml b/pytrustnfe/test/XMLs/jinja_template.xml new file mode 100644 index 0000000..369517c --- /dev/null +++ b/pytrustnfe/test/XMLs/jinja_template.xml @@ -0,0 +1,6 @@ + + {{ tag1 }} + {{ tag2 }} + + {{ tag3 }} + diff --git a/pytrustnfe/test/test_certificado.py b/pytrustnfe/test/test_certificado.py index 6330590..2e7f248 100644 --- a/pytrustnfe/test/test_certificado.py +++ b/pytrustnfe/test/test_certificado.py @@ -7,6 +7,8 @@ Created on Jun 14, 2015 import unittest import os import os.path +from pytrustnfe.certificado import Certificado +from pytrustnfe.certificado import save_cert_key from pytrustnfe.certificado import extract_cert_and_key_from_pfx CHAVE = '-----BEGIN PRIVATE KEY-----\n' \ @@ -52,6 +54,24 @@ class test_assinatura(unittest.TestCase): self.assertEqual(key, CHAVE, 'Chave gerada inválida') self.assertEqual(cert, CERTIFICADO, 'Certificado inválido') + def test_save_pfx(self): + pfx_source = open(os.path.join(self.caminho, 'teste.pfx'), 'r').read() + pfx = Certificado(pfx_source, '123') + path = pfx.save_pfx() + saved = open(path, 'r').read() + self.assertEqual(pfx_source, saved, + 'Arquivo pfx salvo não bate com arquivo lido') + + def test_save_cert_and_key(self): + dir_pfx = open(os.path.join(self.caminho, 'teste.pfx'), 'r').read() + cert, key = extract_cert_and_key_from_pfx(dir_pfx, '123456') + cert_path, key_path = save_cert_key(cert, key) + cert_saved = open(cert_path, 'r').read() + key_saved = open(key_path, 'r').read() + self.assertEqual( + cert, cert_saved, 'Certificado não corresponde ao original') + self.assertEqual(key, key_saved, 'Chave não corresponde ao original') + def test_pfx_nao_existe(self): self.assertRaises(Exception, extract_cert_and_key_from_pfx, 'file.pfx', '123456') diff --git a/pytrustnfe/test/test_servidores.py b/pytrustnfe/test/test_servidores.py new file mode 100644 index 0000000..e3a580c --- /dev/null +++ b/pytrustnfe/test/test_servidores.py @@ -0,0 +1,42 @@ +# coding=utf-8 +''' +Created on Jun 14, 2015 + +@author: danimar +''' +import unittest +from pytrustnfe.Servidores import localizar_url + +url_ba = 'https://nfe.sefaz.ba.gov.br/webservices/NfeAutorizacao/NfeAutoriza\ +cao.asmx' + +url_sp = 'https://nfe.fazenda.sp.gov.br/ws/nfeautorizacao.asmx' + +url_sc = 'https://nfe.svrs.rs.gov.br/ws/NfeAutorizacao/NfeAutorizacao.asmx' + +url_rs = 'https://nfe.sefaz.rs.gov.br/ws/NfeAutorizacao/NFeAutorizacao.asmx' + +url_cad_rs = 'https://cad.sefazrs.rs.gov.br/ws/cadconsultacadastro/cadcon\ +sultacadastro2.asmx' + +url_cad_sc = 'https://cad.svrs.rs.gov.br/ws/CadConsultaCadastro/CadConsult\ +aCadastro2.asmx' + + +class test_servidores(unittest.TestCase): + + def test_localizar_url(self): + url = localizar_url('NfeAutorizacao', '29', ambiente=1) + self.assertEqual(url, url_ba) + url = localizar_url('NfeAutorizacao', '35', ambiente=1) + self.assertEqual(url, url_sp) + url = localizar_url('NfeAutorizacao', '42', ambiente=1) + self.assertEqual(url, url_sc) + url = localizar_url('NfeAutorizacao', '43', ambiente=1) + self.assertEqual(url, url_rs) + + url = localizar_url('NfeConsultaCadastro', '43', ambiente=2) + self.assertEqual(url, url_cad_rs) + + url = localizar_url('NfeConsultaCadastro', '42', ambiente=2) + self.assertEqual(url, url_cad_sc) diff --git a/pytrustnfe/test/test_utils.py b/pytrustnfe/test/test_utils.py index 1bb3a56..64cf1fa 100644 --- a/pytrustnfe/test/test_utils.py +++ b/pytrustnfe/test/test_utils.py @@ -8,7 +8,7 @@ import unittest import datetime from pytrustnfe.utils import date_tostring, datetime_tostring, \ gerar_chave -from pytrustnfe.utils import ChaveNFe +from pytrustnfe.utils import ChaveNFe, CabecalhoSoap class test_utils(unittest.TestCase): @@ -18,6 +18,12 @@ class test_utils(unittest.TestCase): 'tipo': 0, 'codigo': '26730161' } + def test_cabecalho_soap(self): + head = CabecalhoSoap(versao=1, estado='SC', soap_action='Autorizacao') + self.assertEqual(head.versao, 1) + self.assertEqual(head.estado, 'SC') + self.assertEqual(head.soap_action, 'Autorizacao') + def test_date_tostring(self): hoje = datetime.date.today() data = date_tostring(hoje) diff --git a/pytrustnfe/test/test_xml.py b/pytrustnfe/test/test_xml.py new file mode 100644 index 0000000..eb1b2a4 --- /dev/null +++ b/pytrustnfe/test/test_xml.py @@ -0,0 +1,26 @@ +# coding=utf-8 +''' +Created on Jun 14, 2015 + +@author: danimar +''' +import unittest +from datetime import datetime +from pytrustnfe.xml.filters import normalize_str +from pytrustnfe.xml.filters import format_percent +from pytrustnfe.xml.filters import format_date +from pytrustnfe.xml.filters import format_datetime + + +class test_xmlfilters(unittest.TestCase): + + def test_xmlfilters(self): + word = normalize_str('ação café pó pá veêm') + self.assertEqual(word, 'acao cafe po pa veem') + self.assertEqual(1.5, format_percent(150)) + self.assertEqual('aa', format_date('aa')) + self.assertEqual('aa', format_datetime('aa')) + + dt = datetime(2016, 9, 17, 12, 12, 12) + self.assertEqual('2016-09-17', format_date(dt.date())) + self.assertEqual('2016-09-17T12:12:12', format_datetime(dt)) diff --git a/pytrustnfe/test/test_xml_serializacao.py b/pytrustnfe/test/test_xml_serializacao.py index 98c0dca..64d0a2a 100644 --- a/pytrustnfe/test/test_xml_serializacao.py +++ b/pytrustnfe/test/test_xml_serializacao.py @@ -1,65 +1,37 @@ # coding=utf-8 +import os.path import unittest -from unittest import skip - - -XML_TESTE = ''\ - '1'\ - '1'\ - ''\ - ''\ - ''\ - '32'\ - '0001'\ - 'Venda de mercadorias'\ - ''\ - ''\ - ''\ - '' - -XML_LIST = ''\ - ''\ - '1'\ - '21-06-2015'\ - '123.00'\ - ''\ - ''\ - '2'\ - '21-07-2015'\ - '123.00'\ - ''\ - '' +from lxml import etree +from pytrustnfe.xml import render_xml +from pytrustnfe.xml import sanitize_response class test_xml_serializacao(unittest.TestCase): - @skip('Pulando') - def test_serializacao(self): - t = DynamicXml("enviNFe") - t(versao="3.10") - t.idLote = "1" - t.indSinc = "1" - t.NFe.infNFe(versao="3.10", Id="NFe456465465465465654652123564878") - t.NFe.infNFe.ide.cUF = "32" - t.NFe.infNFe.ide.cNF = "0001" - t.NFe.infNFe.ide.natOp = "Venda de mercadorias" - - xml = t.render() - self.assertEqual(xml, XML_TESTE, "Geração de xml com problemas") - - @skip('Pulando') - def test_list_serializacao(self): - t = DynamicXml("cobr") - t.dup[0](item="1") - t.dup[0].nDup = '1' - t.dup[0].dVenc = '21-06-2015' - t.dup[0].vDup = '123.00' - t.dup[1](item="2") - t.dup[1].nDup = '2' - t.dup[1].dVenc = '21-07-2015' - t.dup[1].vDup = '123.00' - - xml = t.render() - self.assertEqual(xml, XML_LIST, - "Xml com lista de valores sendo gerado incorretamnte") + def test_serializacao_default(self): + path = os.path.join(os.path.dirname(__file__), 'XMLs') + xml = render_xml(path, 'jinja_template.xml', False, tag1='oi', + tag2='ola', tag3='comovai') + + result = open(os.path.join(path, 'jinja_result.xml'), 'r').read() + self.assertEqual(xml + '\n', result) + + def test_serializacao_remove_empty(self): + path = os.path.join(os.path.dirname(__file__), 'XMLs') + xmlElem = render_xml(path, 'jinja_template.xml', True, tag1='oi', + tag2='ola', tag3='comovai') + xml = etree.tostring(xmlElem) + result = open(os.path.join(path, 'jinja_remove_empty.xml'), 'r').read() + self.assertEqual(xml + '\n', result) + + def test_sanitize_response(self): + path = os.path.join(os.path.dirname(__file__), 'XMLs') + xml_to_clear = open(os.path.join(path, 'jinja_result.xml'), 'r').read() + xml, obj = sanitize_response(xml_to_clear) + + self.assertEqual(xml, xml_to_clear) + self.assertEqual(obj.tpAmb, 'oi') + self.assertEqual(obj.CNPJ, 'ola') + self.assertEqual(obj.indNFe, '') + self.assertEqual(obj.indEmi, 'comovai') diff --git a/pytrustnfe/utils.py b/pytrustnfe/utils.py index 2549d0b..4465979 100644 --- a/pytrustnfe/utils.py +++ b/pytrustnfe/utils.py @@ -47,18 +47,15 @@ def datetime_tostring(data): return data.strftime("%d-%m-%y %H:%M:%S") -def gerar_consulta_recibo(recibo): - return {'tpAmb': recibo.tpAmb, 'nRec': recibo.infRec.nRec} - - def gerar_chave(obj_chave, prefix=None): assert isinstance(obj_chave, ChaveNFe), "Objeto deve ser do tipo ChaveNFe" obj_chave.validar() - chave_parcial = "%s%s%s%s%s%09d%d%s" % (obj_chave.estado, obj_chave.emissao, - obj_chave.cnpj, obj_chave.modelo, - obj_chave.serie.zfill(3), obj_chave.numero, - obj_chave.tipo, obj_chave.codigo) + chave_parcial = "%s%s%s%s%s%09d%d%s" % ( + obj_chave.estado, obj_chave.emissao, + obj_chave.cnpj, obj_chave.modelo, + obj_chave.serie.zfill(3), obj_chave.numero, + obj_chave.tipo, obj_chave.codigo) soma = 0 contador = 2 for c in reversed(chave_parcial): @@ -70,7 +67,3 @@ def gerar_chave(obj_chave, prefix=None): if prefix: return prefix + chave_parcial + str(dv) return chave_parcial + str(dv) - - -def descompacta_nfe_distribuicao(xml): - pass diff --git a/pytrustnfe/xml/__init__.py b/pytrustnfe/xml/__init__.py index c345de5..b85f4b7 100644 --- a/pytrustnfe/xml/__init__.py +++ b/pytrustnfe/xml/__init__.py @@ -55,30 +55,3 @@ def sanitize_response(response): elem.tag = elem.tag[i+1:] objectify.deannotate(tree, cleanup_namespaces=True) return response, objectify.fromstring(etree.tostring(tree)) - - -def valida_schema(xml, arquivo_xsd): - '''Função que valida um XML usando lxml do Python via arquivo XSD''' - # Carrega o esquema XML do arquivo XSD - xsd = etree.XMLSchema(file=arquivo_xsd) - # Converte o XML passado em XML do lxml - xml = etree.fromstring(str(xml)) - # Verifica a validade do xml - erros = [] - if not xsd(xml): - # Caso tenha erros, cria uma lista de erros - for erro in xsd.error_log: - erros.append({ - 'message': erro.message, - 'domain': erro.domain, - 'type': erro.type, - 'level': erro.level, - 'line': erro.line, - 'column': erro.column, - 'filename': erro.filename, - 'domain_name': erro.domain_name, - 'type_name': erro.type_name, - 'level_name': erro.level_name - }) - # Retorna os erros, sendo uma lista vazia caso não haja erros - return erros diff --git a/pytrustnfe/xml/filters.py b/pytrustnfe/xml/filters.py index 57012f3..b65d98d 100644 --- a/pytrustnfe/xml/filters.py +++ b/pytrustnfe/xml/filters.py @@ -3,6 +3,7 @@ # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from decimal import Decimal +from datetime import date from datetime import datetime from unicodedata import normalize @@ -41,6 +42,6 @@ def format_date(value): Format date """ dt_format = '%Y-%m-%d' - if isinstance(value, datetime): + if isinstance(value, date): return value.strftime(dt_format) return value