#!/usr/bin/env python3 import datetime import sys import unittest import uuid import lxml.etree as ET from io import BytesIO from pathlib import Path sys.path.append('..') from pycert import SATCertificate from comerciodigital import PACComercioDigital NAME = 'comercio' TEMPLATE_CFDI = """ """ class TestCfdi(object): def __init__(self): self._xml = '' self._make_cfdi() @property def xml(self): return self._xml.decode() def _make_cfdi(self): path = Path(__file__) path_cer = Path(path.parent).joinpath('certificados', f'{NAME}.cer') path_key = Path(path.parent).joinpath('certificados', f'{NAME}.enc') path_xslt = Path(path.parent).joinpath('xslt', 'cadena.xslt') cer = path_cer.read_bytes() key = path_key.read_bytes() self._cert = SATCertificate(cer, key) self._doc = ET.parse(BytesIO(TEMPLATE_CFDI.encode())) self._root = self._doc.getroot() self._root.attrib['Fecha'] = datetime.datetime.now().isoformat()[:19] self._root.attrib['NoCertificado'] = self._cert.serial_number self._root.attrib['Certificado'] = self._cert.cer_txt self._add_stamp(path_xslt) self._xml = ET.tostring(self._root, pretty_print=True, doctype='') return def _add_stamp(self, path_xslt): xslt = open(path_xslt, 'rb') transfor = ET.XSLT(ET.parse(xslt)) cadena = str(transfor(self._doc)).encode() stamp = self._cert.sign(cadena) self._root.attrib['Sello'] = stamp xslt.close() return class TestStamp(unittest.TestCase): def setUp(self): print(f'In method: {self._testMethodName}') self.pac = PACComercioDigital() def test_cfdi_stamp(self): cfdi = TestCfdi().xml result = self.pac.stamp(cfdi) cfdi_uuid = self.pac.cfdi_uuid self.assertFalse(bool(self.pac.error)) self.assertTrue(bool(uuid.UUID(cfdi_uuid))) if __name__ == '__main__': unittest.main()