repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Cce11/DestinatarioTest.php
tests/CfdiUtilsTests/Elements/Cce11/DestinatarioTest.php
<?php namespace CfdiUtilsTests\Elements\Cce11; use CfdiUtils\Elements\Cce11\Destinatario; use CfdiUtils\Elements\Cce11\Domicilio; use PHPUnit\Framework\TestCase; final class DestinatarioTest extends TestCase { public Destinatario $element; protected function setUp(): void { parent::setUp(); $this->element = new Destinatario(); } public function testConstructedObject(): void { $this->assertSame('cce11:Destinatario', $this->element->getElementName()); } public function testDomicilio(): void { // object is empty $this->assertCount(0, $this->element); // add insert first element $first = $this->element->addDomicilio(['id' => 'first']); $this->assertInstanceOf(Domicilio::class, $first); $this->assertSame('first', $first['id']); $this->assertCount(1, $this->element); // add insert second element and is not the same $second = $this->element->addDomicilio(['id' => 'second']); $this->assertSame('second', $second['id']); $this->assertCount(2, $this->element); $this->assertNotSame($first, $second); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Cce11/DomicilioTest.php
tests/CfdiUtilsTests/Elements/Cce11/DomicilioTest.php
<?php namespace CfdiUtilsTests\Elements\Cce11; use CfdiUtils\Elements\Cce11\Domicilio; use PHPUnit\Framework\TestCase; final class DomicilioTest extends TestCase { public Domicilio $element; protected function setUp(): void { parent::setUp(); $this->element = new Domicilio(); } public function testConstructedObject(): void { $this->assertSame('cce11:Domicilio', $this->element->getElementName()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Cce11/EmisorTest.php
tests/CfdiUtilsTests/Elements/Cce11/EmisorTest.php
<?php namespace CfdiUtilsTests\Elements\Cce11; use CfdiUtils\Elements\Cce11\Domicilio; use CfdiUtils\Elements\Cce11\Emisor; use PHPUnit\Framework\TestCase; final class EmisorTest extends TestCase { public Emisor $element; protected function setUp(): void { parent::setUp(); $this->element = new Emisor(); } public function testConstructedObject(): void { $this->assertSame('cce11:Emisor', $this->element->getElementName()); } public function testDomicilio(): void { // object is empty $this->assertCount(0, $this->element); // get retrieve and insert the element $first = $this->element->getDomicilio(); $this->assertInstanceOf(Domicilio::class, $first); $this->assertCount(1, $this->element); // get (again) retrieve the same element $this->assertSame($first, $this->element->getDomicilio()); $this->assertCount(1, $this->element); // add works with the same element $second = $this->element->addDomicilio(['foo' => 'bar']); $this->assertInstanceOf(Domicilio::class, $second); $this->assertCount(1, $this->element); $this->assertSame($second, $first); $this->assertSame('bar', $first['foo']); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Cce11/ReceptorTest.php
tests/CfdiUtilsTests/Elements/Cce11/ReceptorTest.php
<?php namespace CfdiUtilsTests\Elements\Cce11; use CfdiUtils\Elements\Cce11\Domicilio; use CfdiUtils\Elements\Cce11\Receptor; use PHPUnit\Framework\TestCase; final class ReceptorTest extends TestCase { public Receptor $element; protected function setUp(): void { parent::setUp(); $this->element = new Receptor(); } public function testConstructedObject(): void { $this->assertSame('cce11:Receptor', $this->element->getElementName()); } public function testDomicilio(): void { // object is empty $this->assertCount(0, $this->element); // get retrieve and insert the element $first = $this->element->getDomicilio(); $this->assertInstanceOf(Domicilio::class, $first); $this->assertCount(1, $this->element); // get (again) retrieve the same element $this->assertSame($first, $this->element->getDomicilio()); $this->assertCount(1, $this->element); // add works with the same element $second = $this->element->addDomicilio(['foo' => 'bar']); $this->assertInstanceOf(Domicilio::class, $second); $this->assertCount(1, $this->element); $this->assertSame($second, $first); $this->assertSame('bar', $first['foo']); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Cce11/ComercioExteriorTest.php
tests/CfdiUtilsTests/Elements/Cce11/ComercioExteriorTest.php
<?php namespace CfdiUtilsTests\Elements\Cce11; use CfdiUtils\Elements\Cce11\ComercioExterior; use CfdiUtils\Elements\Cce11\Destinatario; use CfdiUtils\Elements\Cce11\Emisor; use CfdiUtils\Elements\Cce11\Mercancia; use CfdiUtils\Elements\Cce11\Mercancias; use CfdiUtils\Elements\Cce11\Propietario; use CfdiUtils\Elements\Cce11\Receptor; use PHPUnit\Framework\TestCase; final class ComercioExteriorTest extends TestCase { public ComercioExterior $element; protected function setUp(): void { parent::setUp(); $this->element = new ComercioExterior(); } public function testConstructedObject(): void { $this->assertSame('cce11:ComercioExterior', $this->element->getElementName()); } public function testEmisor(): void { // object is empty $this->assertCount(0, $this->element); // get retrieve and insert the element $first = $this->element->getEmisor(); $this->assertInstanceOf(Emisor::class, $first); $this->assertCount(1, $this->element); // get (again) retrieve the same element $this->assertSame($first, $this->element->getEmisor()); $this->assertCount(1, $this->element); // add works with the same element $second = $this->element->addEmisor(['foo' => 'bar']); $this->assertInstanceOf(Emisor::class, $second); $this->assertCount(1, $this->element); $this->assertSame($second, $first); $this->assertSame('bar', $first['foo']); } public function testReceptor(): void { // object is empty $this->assertCount(0, $this->element); // get retrieve and insert the element $first = $this->element->getReceptor(); $this->assertInstanceOf(Receptor::class, $first); $this->assertCount(1, $this->element); // get (again) retrieve the same element $this->assertSame($first, $this->element->getReceptor()); $this->assertCount(1, $this->element); // add works with the same element $second = $this->element->addReceptor(['foo' => 'bar']); $this->assertInstanceOf(Receptor::class, $second); $this->assertCount(1, $this->element); $this->assertSame($second, $first); $this->assertSame('bar', $first['foo']); } public function testMercancias(): void { // object is empty $this->assertCount(0, $this->element); // get retrieve and insert the element $first = $this->element->getMercancias(); $this->assertInstanceOf(Mercancias::class, $first); $this->assertCount(1, $this->element); // get (again) retrieve the same element $this->assertSame($first, $this->element->getMercancias()); $this->assertCount(1, $this->element); // add works with the same element $second = $this->element->addMercancias(['foo' => 'bar']); $this->assertInstanceOf(Mercancias::class, $second); $this->assertCount(1, $this->element); $this->assertSame($second, $first); $this->assertSame('bar', $first['foo']); } public function testPropietario(): void { // object is empty $this->assertCount(0, $this->element); // add insert first element $first = $this->element->addPropietario(['id' => 'first']); $this->assertInstanceOf(Propietario::class, $first); $this->assertSame('first', $first['id']); $this->assertCount(1, $this->element); // add insert second element and is not the same $second = $this->element->addPropietario(['id' => 'second']); $this->assertSame('second', $second['id']); $this->assertCount(2, $this->element); $this->assertNotSame($first, $second); } public function testDestinatario(): void { // object is empty $this->assertCount(0, $this->element); // add insert first element $first = $this->element->addDestinatario(['id' => 'first']); $this->assertInstanceOf(Destinatario::class, $first); $this->assertSame('first', $first['id']); $this->assertCount(1, $this->element); // add insert second element and is not the same $second = $this->element->addDestinatario(['id' => 'second']); $this->assertSame('second', $second['id']); $this->assertCount(2, $this->element); $this->assertNotSame($first, $second); } public function testAddMercancia(): void { $mercancias = $this->element->getMercancias(); $first = $this->element->addMercancia(['foo' => 'bar']); $this->assertInstanceOf(Mercancia::class, $first); $this->assertCount(1, $mercancias); $this->assertSame('bar', $first['foo']); $this->assertSame($first, $mercancias->children()->get(0)); $second = $this->element->addMercancia(); $this->assertCount(2, $mercancias); $this->assertNotSame($first, $second); $this->assertSame($second, $mercancias->children()->get(1)); } public function testChildrenOrder(): void { // add in inverse order $this->element->getMercancias(); $this->element->addDestinatario(); $this->element->getReceptor(); $this->element->addPropietario(); $this->element->getEmisor(); // retrieve in correct order $this->assertInstanceOf(Emisor::class, $this->element->children()->get(0)); $this->assertInstanceOf(Propietario::class, $this->element->children()->get(1)); $this->assertInstanceOf(Receptor::class, $this->element->children()->get(2)); $this->assertInstanceOf(Destinatario::class, $this->element->children()->get(3)); $this->assertInstanceOf(Mercancias::class, $this->element->children()->get(4)); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Cce11/Traits/DomicilioTraitTest.php
tests/CfdiUtilsTests/Elements/Cce11/Traits/DomicilioTraitTest.php
<?php namespace CfdiUtilsTests\Elements\Cce11\Traits; use CfdiUtils\Elements\Cce11\Domicilio; use PHPUnit\Framework\TestCase; final class DomicilioTraitTest extends TestCase { public UseDomicilio $element; public function setUp(): void { parent::setUp(); $this->element = new UseDomicilio(); } public function testDomicilio(): void { // object is empty $this->assertCount(0, $this->element); // get retrieve and insert the element $first = $this->element->getDomicilio(); $this->assertInstanceOf(Domicilio::class, $first); $this->assertCount(1, $this->element); // get (again) retrieve the same element $this->assertSame($first, $this->element->getDomicilio()); $this->assertCount(1, $this->element); // add works with the same element $second = $this->element->addDomicilio(['foo' => 'bar']); $this->assertInstanceOf(Domicilio::class, $second); $this->assertCount(1, $this->element); $this->assertSame($second, $first); $this->assertSame('bar', $first['foo']); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Cce11/Traits/UseDomicilio.php
tests/CfdiUtilsTests/Elements/Cce11/Traits/UseDomicilio.php
<?php namespace CfdiUtilsTests\Elements\Cce11\Traits; use CfdiUtils\Elements\Cce11\Traits\DomicilioTrait; use CfdiUtils\Elements\Common\AbstractElement; final class UseDomicilio extends AbstractElement { use DomicilioTrait; public function getElementName(): string { return 'X'; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/NotariosPublicos10/NotariosPublicosTest.php
tests/CfdiUtilsTests/Elements/NotariosPublicos10/NotariosPublicosTest.php
<?php namespace CfdiUtilsTests\Elements\NotariosPublicos10; use CfdiUtils\Elements\NotariosPublicos10\DatosAdquiriente; use CfdiUtils\Elements\NotariosPublicos10\DatosAdquirienteCopSC; use CfdiUtils\Elements\NotariosPublicos10\DatosAdquirientesCopSC; use CfdiUtils\Elements\NotariosPublicos10\DatosEnajenante; use CfdiUtils\Elements\NotariosPublicos10\DatosEnajenanteCopSC; use CfdiUtils\Elements\NotariosPublicos10\DatosEnajenantesCopSC; use CfdiUtils\Elements\NotariosPublicos10\DatosNotario; use CfdiUtils\Elements\NotariosPublicos10\DatosOperacion; use CfdiUtils\Elements\NotariosPublicos10\DatosUnAdquiriente; use CfdiUtils\Elements\NotariosPublicos10\DatosUnEnajenante; use CfdiUtils\Elements\NotariosPublicos10\DescInmueble; use CfdiUtils\Elements\NotariosPublicos10\DescInmuebles; use CfdiUtils\Elements\NotariosPublicos10\NotariosPublicos; use CfdiUtilsTests\Elements\ElementTestCase; final class NotariosPublicosTest extends ElementTestCase { public function testNotariosPublicos(): void { $element = new NotariosPublicos(); $this->assertElementHasName($element, 'notariospublicos:NotariosPublicos'); $this->assertElementHasFixedAttributes($element, [ 'xmlns:notariospublicos' => 'http://www.sat.gob.mx/notariospublicos', 'xsi:schemaLocation' => 'http://www.sat.gob.mx/notariospublicos' . ' http://www.sat.gob.mx/sitio_internet/cfd/notariospublicos/notariospublicos.xsd', 'Version' => '1.0', ]); $this->assertElementHasChildSingle($element, DescInmuebles::class); $this->assertElementHasChildSingle($element, DatosOperacion::class); $this->assertElementHasChildSingle($element, DatosNotario::class); $this->assertElementHasChildSingle($element, DatosEnajenante::class); $this->assertElementHasChildSingle($element, DatosAdquiriente::class); } public function testDescInmuebles(): void { $element = new DescInmuebles(); $this->assertElementHasName($element, 'notariospublicos:DescInmuebles'); $this->assertElementHasChildMultiple($element, DescInmueble::class); } public function testDescInmueble(): void { $element = new DescInmueble(); $this->assertElementHasName($element, 'notariospublicos:DescInmueble'); } public function testDatosOperacion(): void { $element = new DatosOperacion(); $this->assertElementHasName($element, 'notariospublicos:DatosOperacion'); } public function testDatosNotario(): void { $element = new DatosNotario(); $this->assertElementHasName($element, 'notariospublicos:DatosNotario'); } public function testDatosEnajenante(): void { $element = new DatosEnajenante(); $this->assertElementHasName($element, 'notariospublicos:DatosEnajenante'); $this->assertElementHasChildSingle($element, DatosUnEnajenante::class); $this->assertElementHasChildSingle($element, DatosEnajenantesCopSC::class); } public function testDatosUnEnajenante(): void { $element = new DatosUnEnajenante(); $this->assertElementHasName($element, 'notariospublicos:DatosUnEnajenante'); } public function testDatosEnajenantesCopSC(): void { $element = new DatosEnajenantesCopSC(); $this->assertElementHasName($element, 'notariospublicos:DatosEnajenantesCopSC'); $this->assertElementHasChildMultiple($element, DatosEnajenanteCopSC::class); } public function testDatosEnajenanteCopSC(): void { $element = new DatosEnajenanteCopSC(); $this->assertElementHasName($element, 'notariospublicos:DatosEnajenanteCopSC'); } public function testDatosAdquiriente(): void { $element = new DatosAdquiriente(); $this->assertElementHasName($element, 'notariospublicos:DatosAdquiriente'); $this->assertElementHasChildSingle($element, DatosUnAdquiriente::class); $this->assertElementHasChildSingle($element, DatosAdquirientesCopSC::class); } public function testDatosUnAdquiriente(): void { $element = new DatosUnAdquiriente(); $this->assertElementHasName($element, 'notariospublicos:DatosUnAdquiriente'); } public function testDatosAdquirientesCopSC(): void { $element = new DatosAdquirientesCopSC(); $this->assertElementHasName($element, 'notariospublicos:DatosAdquirientesCopSC'); $this->assertElementHasChildMultiple($element, DatosAdquirienteCopSC::class); } public function testDatosAdquirienteCopSC(): void { $element = new DatosAdquirienteCopSC(); $this->assertElementHasName($element, 'notariospublicos:DatosAdquirienteCopSC'); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Cfdi40/ComprobanteTest.php
tests/CfdiUtilsTests/Elements/Cfdi40/ComprobanteTest.php
<?php namespace CfdiUtilsTests\Elements\Cfdi40; use CfdiUtils\Elements\Cfdi40\ACuentaTerceros; use CfdiUtils\Elements\Cfdi40\Addenda; use CfdiUtils\Elements\Cfdi40\CfdiRelacionado; use CfdiUtils\Elements\Cfdi40\CfdiRelacionados; use CfdiUtils\Elements\Cfdi40\Complemento; use CfdiUtils\Elements\Cfdi40\ComplementoConcepto; use CfdiUtils\Elements\Cfdi40\Comprobante; use CfdiUtils\Elements\Cfdi40\Concepto; use CfdiUtils\Elements\Cfdi40\ConceptoImpuestos; use CfdiUtils\Elements\Cfdi40\Conceptos; use CfdiUtils\Elements\Cfdi40\CuentaPredial; use CfdiUtils\Elements\Cfdi40\Emisor; use CfdiUtils\Elements\Cfdi40\Impuestos; use CfdiUtils\Elements\Cfdi40\InformacionAduanera; use CfdiUtils\Elements\Cfdi40\InformacionGlobal; use CfdiUtils\Elements\Cfdi40\Parte; use CfdiUtils\Elements\Cfdi40\Receptor; use CfdiUtils\Elements\Cfdi40\Retencion; use CfdiUtils\Elements\Cfdi40\Retenciones; use CfdiUtils\Elements\Cfdi40\Traslado; use CfdiUtils\Elements\Cfdi40\Traslados; use CfdiUtilsTests\Elements\ElementTestCase; final class ComprobanteTest extends ElementTestCase { public function testComprobante(): void { $element = new Comprobante(); $this->assertElementHasName($element, 'cfdi:Comprobante'); $this->assertElementHasOrder($element, [ 'cfdi:InformacionGlobal', 'cfdi:CfdiRelacionados', 'cfdi:Emisor', 'cfdi:Receptor', 'cfdi:Conceptos', 'cfdi:Impuestos', 'cfdi:Complemento', 'cfdi:Addenda', ]); $this->assertElementHasFixedAttributes($element, [ 'xmlns:cfdi' => 'http://www.sat.gob.mx/cfd/4', 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance', 'xsi:schemaLocation' => 'http://www.sat.gob.mx/cfd/4' . ' http://www.sat.gob.mx/sitio_internet/cfd/4/cfdv40.xsd', 'Version' => '4.0', ]); $this->assertElementHasChildSingle($element, InformacionGlobal::class); $this->assertElementHasChildMultiple($element, CfdiRelacionados::class); $this->assertElementHasChildSingle($element, Emisor::class); $this->assertElementHasChildSingle($element, Receptor::class); $this->assertElementHasChildSingle($element, Conceptos::class); $this->assertElementHasChildSingle($element, Impuestos::class); $this->assertElementHasChildSingleAddChild($element, Complemento::class); $this->assertElementHasChildSingleAddChild($element, Addenda::class); } public function testInformacionGlobal(): void { $element = new InformacionGlobal(); $this->assertElementHasName($element, 'cfdi:InformacionGlobal'); } public function testCfdiRelacionados(): void { $element = new CfdiRelacionados(); $this->assertElementHasName($element, 'cfdi:CfdiRelacionados'); $this->assertElementHasChildMultiple($element, CfdiRelacionado::class); } public function testCfdiRelacionado(): void { $element = new CfdiRelacionado(); $this->assertElementHasName($element, 'cfdi:CfdiRelacionado'); } public function testEmisor(): void { $element = new Emisor(); $this->assertElementHasName($element, 'cfdi:Emisor'); } public function testReceptor(): void { $element = new Receptor(); $this->assertElementHasName($element, 'cfdi:Receptor'); } public function testConceptos(): void { $element = new Conceptos(); $this->assertElementHasName($element, 'cfdi:Conceptos'); $this->assertElementHasChildMultiple($element, Concepto::class); } public function testConcepto(): void { $element = new Concepto(); $this->assertElementHasName($element, 'cfdi:Concepto'); $this->assertElementHasOrder($element, [ 'cfdi:Impuestos', 'cfdi:ACuentaTerceros', 'cfdi:InformacionAduanera', 'cfdi:CuentaPredial', 'cfdi:ComplementoConcepto', 'cfdi:Parte', ]); $this->assertElementHasChildSingle($element, ConceptoImpuestos::class, 'getImpuestos', 'addImpuestos'); $this->assertElementHasChildSingle($element, ACuentaTerceros::class); $this->assertElementHasChildMultiple($element, InformacionAduanera::class); $this->assertElementHasChildMultiple($element, CuentaPredial::class); $this->assertElementHasChildSingleAddChild($element, ComplementoConcepto::class); $this->assertElementHasChildMultiple($element, Parte::class); } public function testConceptoImpuestos(): void { $element = new ConceptoImpuestos(); $this->assertElementHasName($element, 'cfdi:Impuestos'); $this->assertElementHasOrder($element, [ 'cfdi:Traslados', 'cfdi:Retenciones', ]); $this->assertElementHasChildSingle($element, Traslados::class); $this->assertElementHasChildSingle($element, Retenciones::class); } public function testTraslados(): void { $element = new Traslados(); $this->assertElementHasName($element, 'cfdi:Traslados'); $this->assertElementHasChildMultiple($element, Traslado::class); } public function testTraslado(): void { $element = new Traslado(); $this->assertElementHasName($element, 'cfdi:Traslado'); } public function testRetenciones(): void { $element = new Retenciones(); $this->assertElementHasName($element, 'cfdi:Retenciones'); $this->assertElementHasChildMultiple($element, Retencion::class); } public function testRetencion(): void { $element = new Retencion(); $this->assertElementHasName($element, 'cfdi:Retencion'); } public function testACuentaTerceros(): void { $element = new ACuentaTerceros(); $this->assertElementHasName($element, 'cfdi:ACuentaTerceros'); } public function testInformacionAduanera(): void { $element = new InformacionAduanera(); $this->assertElementHasName($element, 'cfdi:InformacionAduanera'); } public function testCuentaPredial(): void { $element = new CuentaPredial(); $this->assertElementHasName($element, 'cfdi:CuentaPredial'); } public function testComplementoConcepto(): void { $element = new ComplementoConcepto(); $this->assertElementHasName($element, 'cfdi:ComplementoConcepto'); } public function testParte(): void { $element = new Parte(); $this->assertElementHasName($element, 'cfdi:Parte'); $this->assertElementHasChildMultiple($element, InformacionAduanera::class); } public function testImpuestos(): void { $element = new Impuestos(); $this->assertElementHasName($element, 'cfdi:Impuestos'); $this->assertElementHasOrder($element, [ 'cfdi:Retenciones', 'cfdi:Traslados', ]); $this->assertElementHasChildSingle($element, Retenciones::class); $this->assertElementHasChildSingle($element, Traslados::class); } public function testComplemento(): void { $element = new Complemento(); $this->assertElementHasName($element, 'cfdi:Complemento'); } public function testAddenda(): void { $element = new Addenda(); $this->assertElementHasName($element, 'cfdi:Addenda'); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Dividendos10/DividOUtilTest.php
tests/CfdiUtilsTests/Elements/Dividendos10/DividOUtilTest.php
<?php namespace CfdiUtilsTests\Elements\Dividendos10; use CfdiUtils\Elements\Dividendos10\DividOUtil; use PHPUnit\Framework\TestCase; final class DividOUtilTest extends TestCase { public DividOUtil $element; public function setUp(): void { parent::setUp(); $this->element = new DividOUtil(); } public function testGetElementName(): void { $this->assertSame('dividendos:DividOUtil', $this->element->getElementName()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Dividendos10/DividendosTest.php
tests/CfdiUtilsTests/Elements/Dividendos10/DividendosTest.php
<?php namespace CfdiUtilsTests\Elements\Dividendos10; use CfdiUtils\Elements\Dividendos10\Dividendos; use CfdiUtils\Elements\Dividendos10\DividOUtil; use CfdiUtils\Elements\Dividendos10\Remanente; use PHPUnit\Framework\TestCase; final class DividendosTest extends TestCase { public Dividendos $element; protected function setUp(): void { parent::setUp(); $this->element = new Dividendos(); } public function testGetElementName(): void { $this->assertSame('dividendos:Dividendos', $this->element->getElementName()); } public function testGetDividOUtil(): void { $this->assertNull($this->element->searchNode('dividendos:DividOUtil')); $child = $this->element->getDividOUtil(); $this->assertInstanceOf(DividOUtil::class, $child); $this->assertSame($child, $this->element->searchNode('dividendos:DividOUtil')); } public function testAddDividOUtil(): void { $first = $this->element->addDividOUtil(['Rfc' => 'FOO']); $this->assertInstanceOf(DividOUtil::class, $first); $this->assertSame('FOO', $first['Rfc']); $second = $this->element->addDividOUtil(['Rfc' => 'BAR']); $this->assertSame($first, $second); $this->assertSame('BAR', $first['Rfc']); } public function testGetRemanente(): void { $this->assertNull($this->element->searchNode('dividendos:Remanente')); $child = $this->element->getRemanente(); $this->assertInstanceOf(Remanente::class, $child); $this->assertSame($child, $this->element->searchNode('dividendos:Remanente')); } public function testAddRemanente(): void { $first = $this->element->addRemanente(['Rfc' => 'BAZ']); $this->assertInstanceOf(Remanente::class, $first); $this->assertSame('BAZ', $first['Rfc']); $second = $this->element->addRemanente(['Rfc' => 'BAR']); $this->assertSame($first, $second); $this->assertSame('BAR', $first['Rfc']); } public function testHasFixedAttributes(): void { $namespace = 'http://www.sat.gob.mx/esquemas/retencionpago/1/dividendos'; $this->assertSame('1.0', $this->element['Version']); $this->assertSame($namespace, $this->element['xmlns:dividendos']); $this->assertStringStartsWith($namespace . ' http://', $this->element['xsi:schemaLocation']); } public function testChildrenOrder(): void { // add in inverse order $this->element->getRemanente(); $this->element->getDividOUtil(); // retrieve in correct order $this->assertInstanceOf(DividOUtil::class, $this->element->children()->get(0)); $this->assertInstanceOf(Remanente::class, $this->element->children()->get(1)); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Dividendos10/RemanenteTest.php
tests/CfdiUtilsTests/Elements/Dividendos10/RemanenteTest.php
<?php namespace CfdiUtilsTests\Elements\Dividendos10; use CfdiUtils\Elements\Dividendos10\Remanente; use PHPUnit\Framework\TestCase; final class RemanenteTest extends TestCase { public Remanente $element; public function setUp(): void { parent::setUp(); $this->element = new Remanente(); } public function testGetElementName(): void { $this->assertSame('dividendos:Remanente', $this->element->getElementName()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Cfdi33/ConceptosTest.php
tests/CfdiUtilsTests/Elements/Cfdi33/ConceptosTest.php
<?php namespace CfdiUtilsTests\Elements\Cfdi33; use CfdiUtils\Elements\Cfdi33\Concepto; use CfdiUtils\Elements\Cfdi33\Conceptos; use PHPUnit\Framework\TestCase; final class ConceptosTest extends TestCase { public Conceptos $element; public function setUp(): void { parent::setUp(); $this->element = new Conceptos(); } public function testGetElementName(): void { $this->assertSame('cfdi:Conceptos', $this->element->getElementName()); } public function testAddConcepto(): void { // no childs $parent = $this->element; $this->assertCount(0, $parent); // add first child $first = $parent->addConcepto(['name' => 'first']); $this->assertInstanceOf(Concepto::class, $first); $this->assertSame('first', $first['name']); $this->assertCount(1, $parent); // add second child $parent->addConcepto(); $this->assertCount(2, $parent); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Cfdi33/TrasladoTest.php
tests/CfdiUtilsTests/Elements/Cfdi33/TrasladoTest.php
<?php namespace CfdiUtilsTests\Elements\Cfdi33; use CfdiUtils\Elements\Cfdi33\Traslado; use PHPUnit\Framework\TestCase; final class TrasladoTest extends TestCase { public Traslado $element; protected function setUp(): void { parent::setUp(); $this->element = new Traslado(); } public function testGetElementName(): void { $this->assertSame('cfdi:Traslado', $this->element->getElementName()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Cfdi33/AddendaTest.php
tests/CfdiUtilsTests/Elements/Cfdi33/AddendaTest.php
<?php namespace CfdiUtilsTests\Elements\Cfdi33; use CfdiUtils\Elements\Cfdi33\Addenda; use CfdiUtils\Nodes\Node; use PHPUnit\Framework\TestCase; final class AddendaTest extends TestCase { public Addenda $element; public function setUp(): void { parent::setUp(); $this->element = new Addenda(); } public function testGetElementName(): void { $this->assertSame('cfdi:Addenda', $this->element->getElementName()); } public function testAdd(): void { $this->assertCount(0, $this->element); $firstChild = new Node('first'); $addReturn = $this->element->add($firstChild); $this->assertSame($this->element, $addReturn); $this->assertCount(1, $this->element); $this->assertSame($firstChild, $this->element->searchNode('first')); $secondChild = new Node('second'); $this->element->add($secondChild); $this->assertCount(2, $this->element); $this->assertSame($secondChild, $this->element->searchNode('second')); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Cfdi33/ConceptoTest.php
tests/CfdiUtilsTests/Elements/Cfdi33/ConceptoTest.php
<?php namespace CfdiUtilsTests\Elements\Cfdi33; use CfdiUtils\Elements\Cfdi33\ComplementoConcepto; use CfdiUtils\Elements\Cfdi33\Concepto; use CfdiUtils\Elements\Cfdi33\ConceptoImpuestos; use CfdiUtils\Elements\Cfdi33\CuentaPredial; use CfdiUtils\Elements\Cfdi33\Impuestos; use CfdiUtils\Elements\Cfdi33\InformacionAduanera; use CfdiUtils\Elements\Cfdi33\Parte; use PHPUnit\Framework\TestCase; final class ConceptoTest extends TestCase { public Concepto $element; public function setUp(): void { parent::setUp(); $this->element = new Concepto(); } public function testGetImpuestos(): void { $this->assertNull($this->element->searchNode('cfdi:Impuestos')); $child = $this->element->getImpuestos(); $this->assertInstanceOf(ConceptoImpuestos::class, $child); $this->assertSame($child, $this->element->searchNode('cfdi:Impuestos')); } public function testGetCuentaPredial(): void { $this->assertNull($this->element->searchNode('cfdi:CuentaPredial')); $child = $this->element->getCuentaPredial(); $this->assertInstanceOf(CuentaPredial::class, $child); $this->assertSame($child, $this->element->searchNode('cfdi:CuentaPredial')); } public function testAddCuentaPredial(): void { $parent = $this->element; $this->assertCount(0, $parent); $first = $parent->addCuentaPredial(['id' => 'first']); $this->assertCount(1, $parent); $this->assertInstanceOf(CuentaPredial::class, $first); $this->assertSame('first', $parent->searchAttribute('cfdi:CuentaPredial', 'id')); $second = $parent->addCuentaPredial(['ID' => 'BAR']); $this->assertSame($first, $second); $this->assertSame('BAR', $first['ID']); } public function testGetComplementoConcepto(): void { $this->assertNull($this->element->searchNode('cfdi:ComplementoConcepto')); $child = $this->element->getComplementoConcepto(); $this->assertInstanceOf(ComplementoConcepto::class, $child); $this->assertSame($child, $this->element->searchNode('cfdi:ComplementoConcepto')); } public function testAddComplementoConcepto(): void { $parent = $this->element; $this->assertCount(0, $parent); $first = $parent->addComplementoConcepto(['ID' => '123AD']); $this->assertCount(1, $parent); $this->assertInstanceOf(ComplementoConcepto::class, $first); $this->assertSame('123AD', $first['ID']); $second = $parent->addComplementoConcepto(['ID' => 'BAR']); $this->assertSame($first, $second); $this->assertSame('BAR', $first['ID']); } public function testAddParte(): void { // no childs $parent = $this->element; $this->assertCount(0, $parent); // add first child $first = $parent->addParte(['name' => 'first']); $this->assertInstanceOf(Parte::class, $first); $this->assertSame('first', $first['name']); $this->assertCount(1, $parent); // add second child $parent->addParte(); $this->assertCount(2, $parent); } public function testMultiParte(): void { $node = $this->element; $this->assertCount(0, $node); $multiReturn = $node->multiParte( ['id' => 'first'], ['id' => 'second'] ); $this->assertSame($multiReturn, $node); $this->assertCount(2, $node); $this->assertSame('first', $node->searchAttribute('cfdi:Parte', 'id')); } public function testChildrenOrder(): void { // add in inverse order $this->element->addParte(); $this->element->getComplementoConcepto(); $this->element->getCuentaPredial(); $this->element->addInformacionAduanera(); $this->element->getImpuestos(); // retrieve in correct order $this->assertInstanceOf(Impuestos::class, $this->element->children()->get(0)); $this->assertInstanceOf(InformacionAduanera::class, $this->element->children()->get(1)); $this->assertInstanceOf(CuentaPredial::class, $this->element->children()->get(2)); $this->assertInstanceOf(ComplementoConcepto::class, $this->element->children()->get(3)); $this->assertInstanceOf(Parte::class, $this->element->children()->get(4)); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Cfdi33/CfdiRelacionadoTest.php
tests/CfdiUtilsTests/Elements/Cfdi33/CfdiRelacionadoTest.php
<?php namespace CfdiUtilsTests\Elements\Cfdi33; use CfdiUtils\Elements\Cfdi33\CfdiRelacionado; use PHPUnit\Framework\TestCase; final class CfdiRelacionadoTest extends TestCase { public CfdiRelacionado $element; protected function setUp(): void { parent::setUp(); $this->element = new CfdiRelacionado(); } public function testElementName(): void { $this->assertSame('cfdi:CfdiRelacionado', $this->element->getElementName()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Cfdi33/ComplementoTest.php
tests/CfdiUtilsTests/Elements/Cfdi33/ComplementoTest.php
<?php namespace CfdiUtilsTests\Elements\Cfdi33; use CfdiUtils\Elements\Cfdi33\Complemento; use CfdiUtils\Nodes\Node; use PHPUnit\Framework\TestCase; final class ComplementoTest extends TestCase { public Complemento $element; public function setUp(): void { parent::setUp(); $this->element = new Complemento(); } public function testGetElementName(): void { $this->assertSame('cfdi:Complemento', $this->element->getElementName()); } public function testAdd(): void { $this->assertCount(0, $this->element); $firstChild = new Node('first'); $addReturn = $this->element->add($firstChild); $this->assertSame($this->element, $addReturn); $this->assertCount(1, $this->element); $this->assertSame($firstChild, $this->element->searchNode('first')); $secondChild = new Node('second'); $this->element->add($secondChild); $this->assertCount(2, $this->element); $this->assertSame($secondChild, $this->element->searchNode('second')); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Cfdi33/TrasladosTest.php
tests/CfdiUtilsTests/Elements/Cfdi33/TrasladosTest.php
<?php namespace CfdiUtilsTests\Elements\Cfdi33; use CfdiUtils\Elements\Cfdi33\Traslado; use CfdiUtils\Elements\Cfdi33\Traslados; use PHPUnit\Framework\TestCase; final class TrasladosTest extends TestCase { public Traslados $element; protected function setUp(): void { parent::setUp(); $this->element = new Traslados(); } public function testGetElementName(): void { $this->assertSame('cfdi:Traslados', $this->element->getElementName()); } public function testAddTraslado(): void { $parent = $this->element; // no childs $this->assertCount(0, $parent); // add first child $first = $this->element->addTraslado(['name' => 'first']); $this->assertInstanceOf(Traslado::class, $first); $this->assertSame('first', $first['name']); $this->assertCount(1, $this->element); // add second child $second = $this->element->addTraslado(); $this->assertCount(2, $this->element); // test that first and second are not the same $this->assertNotSame($first, $second); } public function testMultiTraslado(): void { $node = $this->element; $this->assertCount(0, $node); $multiReturn = $node->multiTraslado( ['id' => 'first'], ['id' => 'second'] ); $this->assertSame($multiReturn, $node); $this->assertCount(2, $node); $this->assertSame('first', $node->searchAttribute('cfdi:Traslado', 'id')); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Cfdi33/CuentaPredialTest.php
tests/CfdiUtilsTests/Elements/Cfdi33/CuentaPredialTest.php
<?php namespace CfdiUtilsTests\Elements\Cfdi33; use CfdiUtils\Elements\Cfdi33\CuentaPredial; use PHPUnit\Framework\TestCase; final class CuentaPredialTest extends TestCase { public CuentaPredial $element; public function setUp(): void { parent::setUp(); $this->element = new CuentaPredial(); } public function testGetElementName(): void { $this->assertSame('cfdi:CuentaPredial', $this->element->getElementName()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Cfdi33/EmisorTest.php
tests/CfdiUtilsTests/Elements/Cfdi33/EmisorTest.php
<?php namespace CfdiUtilsTests\Elements\Cfdi33; use CfdiUtils\Elements\Cfdi33\Emisor; use PHPUnit\Framework\TestCase; final class EmisorTest extends TestCase { public Emisor $element; public function setUp(): void { parent::setUp(); $this->element = new Emisor(); } public function testGetElementName(): void { $this->assertSame('cfdi:Emisor', $this->element->getElementName()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Cfdi33/ParteTest.php
tests/CfdiUtilsTests/Elements/Cfdi33/ParteTest.php
<?php namespace CfdiUtilsTests\Elements\Cfdi33; use CfdiUtils\Elements\Cfdi33\Parte; use PHPUnit\Framework\TestCase; final class ParteTest extends TestCase { public Parte $element; protected function setUp(): void { parent::setUp(); $this->element = new Parte(); } public function testElementName(): void { $this->assertSame('cfdi:Parte', $this->element->getElementName()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Cfdi33/ComplementoConceptoTest.php
tests/CfdiUtilsTests/Elements/Cfdi33/ComplementoConceptoTest.php
<?php namespace CfdiUtilsTests\Elements\Cfdi33; use CfdiUtils\Elements\Cfdi33\ComplementoConcepto; use PHPUnit\Framework\TestCase; final class ComplementoConceptoTest extends TestCase { public ComplementoConcepto $element; public function setUp(): void { parent::setUp(); $this->element = new ComplementoConcepto(); } public function testGetElementName(): void { $this->assertSame('cfdi:ComplementoConcepto', $this->element->getElementName()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Cfdi33/ReceptorTest.php
tests/CfdiUtilsTests/Elements/Cfdi33/ReceptorTest.php
<?php namespace CfdiUtilsTests\Elements\Cfdi33; use CfdiUtils\Elements\Cfdi33\Receptor; use PHPUnit\Framework\TestCase; final class ReceptorTest extends TestCase { public Receptor $element; protected function setUp(): void { parent::setUp(); $this->element = new Receptor(); } public function testGetElementName(): void { $this->assertSame('cfdi:Receptor', $this->element->getElementName()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Cfdi33/RetencionesTest.php
tests/CfdiUtilsTests/Elements/Cfdi33/RetencionesTest.php
<?php namespace CfdiUtilsTests\Elements\Cfdi33; use CfdiUtils\Elements\Cfdi33\Retencion; use CfdiUtils\Elements\Cfdi33\Retenciones; use PHPUnit\Framework\TestCase; final class RetencionesTest extends TestCase { public Retenciones $element; protected function setUp(): void { parent::setUp(); $this->element = new Retenciones(); } public function testGetElementName(): void { $this->assertSame('cfdi:Retenciones', $this->element->getElementName()); } public function testAddRetencion(): void { $parent = $this->element; // no childs $this->assertCount(0, $parent); // add first child $first = $this->element->addRetencion(['name' => 'first']); $this->assertInstanceOf(Retencion::class, $first); $this->assertSame('first', $first['name']); $this->assertCount(1, $this->element); // add second child $second = $this->element->addRetencion(); $this->assertCount(2, $this->element); // test that first and second are not the same $this->assertNotSame($first, $second); } public function testMultiRetencion(): void { $node = $this->element; $this->assertCount(0, $node); $multiReturn = $node->multiRetencion( ['id' => 'first'], ['id' => 'second'] ); $this->assertSame($multiReturn, $node); $this->assertCount(2, $node); $this->assertSame('first', $node->searchAttribute('cfdi:Retencion', 'id')); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Cfdi33/ImpuestosOrderTest.php
tests/CfdiUtilsTests/Elements/Cfdi33/ImpuestosOrderTest.php
<?php namespace CfdiUtilsTests\Elements\Cfdi33; use CfdiUtils\Elements\Cfdi33\Comprobante; use CfdiUtils\Elements\Cfdi33\Concepto; use CfdiUtils\Elements\Cfdi33\ConceptoImpuestos; use CfdiUtils\Elements\Cfdi33\Impuestos; use PHPUnit\Framework\TestCase; final class ImpuestosOrderTest extends TestCase { public function testComprobanteImpuestosOrderIsRetencionesTraslados(): void { $comprobante = new Comprobante(); $impuestos = $comprobante->getImpuestos(); $this->assertInstanceOf(Impuestos::class, $impuestos); $expectedOrder = ['cfdi:Retenciones', 'cfdi:Traslados']; $this->assertSame($expectedOrder, $impuestos->getChildrenOrder()); } public function testConceptoImpuestosOrderIsTrasladosRetenciones(): void { $concepto = new Concepto(); $impuestos = $concepto->getImpuestos(); $this->assertInstanceOf(Impuestos::class, $impuestos); $this->assertInstanceOf(ConceptoImpuestos::class, $impuestos); $expectedOrder = ['cfdi:Traslados', 'cfdi:Retenciones']; $this->assertSame($expectedOrder, $impuestos->getChildrenOrder()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Cfdi33/ComprobanteTest.php
tests/CfdiUtilsTests/Elements/Cfdi33/ComprobanteTest.php
<?php namespace CfdiUtilsTests\Elements\Cfdi33; use CfdiUtils\Elements\Cfdi33\Addenda; use CfdiUtils\Elements\Cfdi33\CfdiRelacionado; use CfdiUtils\Elements\Cfdi33\CfdiRelacionados; use CfdiUtils\Elements\Cfdi33\Complemento; use CfdiUtils\Elements\Cfdi33\Comprobante; use CfdiUtils\Elements\Cfdi33\Concepto; use CfdiUtils\Elements\Cfdi33\Conceptos; use CfdiUtils\Elements\Cfdi33\Emisor; use CfdiUtils\Elements\Cfdi33\Impuestos; use CfdiUtils\Elements\Cfdi33\Receptor; use CfdiUtils\Nodes\Node; use PHPUnit\Framework\TestCase; final class ComprobanteTest extends TestCase { public Comprobante $element; protected function setUp(): void { parent::setUp(); $this->element = new Comprobante(); } public function testGetElementName(): void { $this->assertSame('cfdi:Comprobante', $this->element->getElementName()); } public function testGetCfdiRelacionados(): void { $this->assertNull($this->element->searchNode('cfdi:CfdiRelacionados')); $child = $this->element->getCfdiRelacionados(); $this->assertInstanceOf(CfdiRelacionados::class, $child); $this->assertSame($child, $this->element->searchNode('cfdi:CfdiRelacionados')); } public function testAddRelacionado(): void { $first = $this->element->addCfdiRelacionado(['UUID' => 'FOO']); $this->assertInstanceOf(CfdiRelacionado::class, $first); $this->assertSame('FOO', $first['UUID']); $this->assertCount(1, $this->element->getCfdiRelacionados()); } public function testMultiRelacionado(): void { $self = $this->element->multiCfdiRelacionado( ['UUID' => 'FOO'], ['UUID' => 'BAR'] ); $this->assertSame($this->element, $self); $this->assertCount(2, $this->element->getCfdiRelacionados()); $this->assertSame('FOO', $this->element->getCfdiRelacionados()->children()->get(0)['UUID']); $this->assertSame('BAR', $this->element->getCfdiRelacionados()->children()->get(1)['UUID']); } public function testGetEmisor(): void { $this->assertNull($this->element->searchNode('cfdi:Emisor')); $child = $this->element->getEmisor(); $this->assertInstanceOf(Emisor::class, $child); $this->assertSame($child, $this->element->searchNode('cfdi:Emisor')); } public function testAddEmisor(): void { $first = $this->element->addEmisor(['Rfc' => 'FOO']); $this->assertInstanceOf(Emisor::class, $first); $this->assertSame('FOO', $first['Rfc']); $second = $this->element->addEmisor(['Rfc' => 'BAR']); $this->assertSame($first, $second); $this->assertSame('BAR', $first['Rfc']); } public function testGetReceptor(): void { $this->assertNull($this->element->searchNode('cfdi:Receptor')); $child = $this->element->getReceptor(); $this->assertInstanceOf(Receptor::class, $child); $this->assertSame($child, $this->element->searchNode('cfdi:Receptor')); } public function testAddReceptor(): void { $first = $this->element->addReceptor(['Rfc' => 'BAZ']); $this->assertInstanceOf(Receptor::class, $first); $this->assertSame('BAZ', $first['Rfc']); $second = $this->element->addReceptor(['Rfc' => 'BAR']); $this->assertSame($first, $second); $this->assertSame('BAR', $first['Rfc']); } public function testGetConceptos(): void { $this->assertNull($this->element->searchNode('cfdi:Conceptos')); $child = $this->element->getConceptos(); $this->assertInstanceOf(Conceptos::class, $child); $this->assertSame($child, $this->element->searchNode('cfdi:Conceptos')); } public function testGetImpuestos(): void { $this->assertNull($this->element->searchNode('cfdi:Impuestos')); $child = $this->element->getImpuestos(); $this->assertInstanceOf(Impuestos::class, $child); $this->assertSame($child, $this->element->searchNode('cfdi:Impuestos')); } public function testAddImpuestos(): void { $first = $this->element->addImpuestos(['Foo' => 'Bar']); $this->assertInstanceOf(Impuestos::class, $first); $this->assertSame('Bar', $first['Foo']); $second = $this->element->addImpuestos(['Foo' => 'BAR']); $this->assertSame($first, $second); $this->assertSame('BAR', $first['Foo']); } public function testAddConcepto(): void { $this->assertCount(0, $this->element); $first = $this->element->addConcepto(['name' => 'FOO']); $this->assertInstanceOf(Concepto::class, $first); $this->assertSame('FOO', $first['name']); $this->assertCount(1, $this->element); } public function testGetComplemento(): void { $this->assertNull($this->element->searchNode('cfdi:Complemento')); $child = $this->element->getComplemento(); $this->assertInstanceOf(Complemento::class, $child); $this->assertSame($child, $this->element->searchNode('cfdi:Complemento')); } public function testAddComplemento(): void { $this->assertCount(0, $this->element); $child = new Node('first'); $addReturn = $this->element->addComplemento($child); $this->assertCount(1, $this->element); $this->assertSame($child, $this->element->searchNode('cfdi:Complemento', 'first')); $this->assertSame($addReturn, $this->element); } public function testGetAddenda(): void { $this->assertNull($this->element->searchNode('cfdi:Addenda')); $child = $this->element->getAddenda(); $this->assertInstanceOf(Addenda::class, $child); $this->assertSame($child, $this->element->searchNode('cfdi:Addenda')); } public function testAddAddenda(): void { $this->assertCount(0, $this->element); $child = new Node('first'); $addReturn = $this->element->addAddenda($child); $this->assertCount(1, $this->element); $this->assertSame($child, $this->element->searchNode('cfdi:Addenda', 'first')); $this->assertSame($addReturn, $this->element); } public function testHasFixedAttributes(): void { $namespace = 'http://www.sat.gob.mx/cfd/3'; $this->assertSame('3.3', $this->element['Version']); $this->assertSame($namespace, $this->element['xmlns:cfdi']); $this->assertStringStartsWith($namespace . ' http://', $this->element['xsi:schemaLocation']); $this->assertNotEmpty($this->element['xmlns:xsi']); } public function testChildrenOrder(): void { // add in inverse order $this->element->getAddenda(); $this->element->getComplemento(); $this->element->getImpuestos(); $this->element->getConceptos(); $this->element->getReceptor(); $this->element->getEmisor(); $this->element->getCfdiRelacionados(); // retrieve in correct order $this->assertInstanceOf(CfdiRelacionados::class, $this->element->children()->get(0)); $this->assertInstanceOf(Emisor::class, $this->element->children()->get(1)); $this->assertInstanceOf(Receptor::class, $this->element->children()->get(2)); $this->assertInstanceOf(Conceptos::class, $this->element->children()->get(3)); $this->assertInstanceOf(Impuestos::class, $this->element->children()->get(4)); $this->assertInstanceOf(Complemento::class, $this->element->children()->get(5)); $this->assertInstanceOf(Addenda::class, $this->element->children()->get(6)); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Cfdi33/CfdiRelacionadosTest.php
tests/CfdiUtilsTests/Elements/Cfdi33/CfdiRelacionadosTest.php
<?php namespace CfdiUtilsTests\Elements\Cfdi33; use CfdiUtils\Elements\Cfdi33\CfdiRelacionado; use CfdiUtils\Elements\Cfdi33\CfdiRelacionados; use PHPUnit\Framework\TestCase; final class CfdiRelacionadosTest extends TestCase { public CfdiRelacionados $element; protected function setUp(): void { parent::setUp(); $this->element = new CfdiRelacionados(); } public function testGetElementName(): void { $this->assertSame('cfdi:CfdiRelacionados', $this->element->getElementName()); } public function testAddCfdiRelacionado(): void { // no childs $this->assertCount(0, $this->element); // add first child $first = $this->element->addCfdiRelacionado(['name' => 'first']); $this->assertInstanceOf(CfdiRelacionado::class, $first); $this->assertSame('first', $first['name']); $this->assertCount(1, $this->element); // add second child $second = $this->element->addCfdiRelacionado(); $this->assertCount(2, $this->element); // test that first and second are not the same $this->assertNotSame($first, $second); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Cfdi33/RetencionTest.php
tests/CfdiUtilsTests/Elements/Cfdi33/RetencionTest.php
<?php namespace CfdiUtilsTests\Elements\Cfdi33; use CfdiUtils\Elements\Cfdi33\Retencion; use PHPUnit\Framework\TestCase; final class RetencionTest extends TestCase { public Retencion $element; protected function setUp(): void { parent::setUp(); $this->element = new Retencion(); } public function testGetElementName(): void { $this->assertSame('cfdi:Retencion', $this->element->getElementName()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Cfdi33/Traits/InformacionAduaneraTraitTest.php
tests/CfdiUtilsTests/Elements/Cfdi33/Traits/InformacionAduaneraTraitTest.php
<?php namespace CfdiUtilsTests\Elements\Cfdi33\Traits; use CfdiUtils\Elements\Cfdi33\InformacionAduanera; use PHPUnit\Framework\TestCase; final class InformacionAduaneraTraitTest extends TestCase { public function testAddInformacionAduanera(): void { // no childs $node = new UseInformacionAduanera('X'); $this->assertCount(0, $node); // add first child $first = $node->addInformacionAduanera(['name' => 'first']); $this->assertInstanceOf(InformacionAduanera::class, $first); $this->assertSame('first', $first['name']); $this->assertCount(1, $node); // add second child $node->addInformacionAduanera(); $this->assertCount(2, $node); } public function testMultiInformacionAduanera(): void { $node = new UseInformacionAduanera('X'); $this->assertCount(0, $node); $multiReturn = $node->multiInformacionAduanera( ['id' => 'first'], ['id' => 'second'] ); $this->assertSame($multiReturn, $node); $this->assertCount(2, $node); $this->assertSame('first', $node->searchAttribute('cfdi:InformacionAduanera', 'id')); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Cfdi33/Traits/ImpuestosTraitTest.php
tests/CfdiUtilsTests/Elements/Cfdi33/Traits/ImpuestosTraitTest.php
<?php namespace CfdiUtilsTests\Elements\Cfdi33\Traits; use CfdiUtils\Elements\Cfdi33\Impuestos; use CfdiUtils\Elements\Cfdi33\Retencion; use CfdiUtils\Elements\Cfdi33\Retenciones; use CfdiUtils\Elements\Cfdi33\Traslado; use CfdiUtils\Elements\Cfdi33\Traslados; use PHPUnit\Framework\TestCase; final class ImpuestosTraitTest extends TestCase { public UseImpuestos $element; public function setUp(): void { parent::setUp(); $this->element = new UseImpuestos(); } public function testGetImpuestos(): void { $this->assertNull($this->element->searchNode('cfdi:Impuestos')); $child = $this->element->getImpuestos(); $this->assertInstanceOf(Impuestos::class, $child); $this->assertSame($child, $this->element->searchNode('cfdi:Impuestos')); } public function testAddTraslado(): void { $this->assertNull($this->element->searchNode('cfdi:Impuestos', 'cfdi:Traslados', 'cfdi:Traslado')); $first = $this->element->addTraslado(['name' => 'first']); $this->assertInstanceOf(Traslado::class, $first); $this->assertSame('first', $first['name']); $this->assertSame($first, $this->element->searchNode('cfdi:Impuestos', 'cfdi:Traslados', 'cfdi:Traslado')); } public function testMultiTraslado(): void { $parent = $this->element->getImpuestos()->getTraslados(); $this->assertCount(0, $parent); $multiReturn = $this->element->multiTraslado( ['id' => 'first'], ['id' => 'second'] ); $this->assertSame($multiReturn, $this->element); $this->assertCount(2, $parent); $this->assertSame('first', $parent->searchAttribute('cfdi:Traslado', 'id')); } public function testAddRetencion(): void { $this->assertNull($this->element->searchNode('cfdi:Impuestos', 'cfdi:Retenciones', 'cfdi:Retencion')); $first = $this->element->addRetencion(['name' => 'first']); $this->assertInstanceOf(Retencion::class, $first); $this->assertSame('first', $first['name']); $this->assertSame($first, $this->element->searchNode('cfdi:Impuestos', 'cfdi:Retenciones', 'cfdi:Retencion')); } public function testMultiRetencion(): void { $parent = $this->element->getImpuestos()->getRetenciones(); $this->assertCount(0, $parent); $multiReturn = $this->element->multiRetencion( ['id' => 'first'], ['id' => 'second'] ); $this->assertSame($multiReturn, $this->element); $this->assertCount(2, $parent); $this->assertSame('first', $parent->searchAttribute('cfdi:Retencion', 'id')); } public function testChildrenOrder(): void { // add in inverse order $this->element->addRetencion(); $this->element->addTraslado(); // retrieve in correct order $impuestos = $this->element->getImpuestos(); $this->assertInstanceOf(Retenciones::class, $impuestos->children()->get(0)); $this->assertInstanceOf(Traslados::class, $impuestos->children()->get(1)); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Cfdi33/Traits/UseImpuestos.php
tests/CfdiUtilsTests/Elements/Cfdi33/Traits/UseImpuestos.php
<?php namespace CfdiUtilsTests\Elements\Cfdi33\Traits; use CfdiUtils\Elements\Cfdi33\Impuestos; use CfdiUtils\Elements\Cfdi33\Traits\ImpuestosTrait; use CfdiUtils\Elements\Common\AbstractElement; final class UseImpuestos extends AbstractElement { use ImpuestosTrait; public function getImpuestos(): Impuestos { return $this->helperGetOrAdd(new Impuestos()); } public function getElementName(): string { return 'X'; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Elements/Cfdi33/Traits/UseInformacionAduanera.php
tests/CfdiUtilsTests/Elements/Cfdi33/Traits/UseInformacionAduanera.php
<?php namespace CfdiUtilsTests\Elements\Cfdi33\Traits; use CfdiUtils\Elements\Cfdi33\Traits\InformacionAduaneraTrait; use CfdiUtils\Nodes\Node; final class UseInformacionAduanera extends Node { use InformacionAduaneraTrait; }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Utils/RegimenCapitalRemoverTest.php
tests/CfdiUtilsTests/Utils/RegimenCapitalRemoverTest.php
<?php namespace CfdiUtilsTests\Utils; use CfdiUtils\Utils\RegimenCapitalRemover; use CfdiUtilsTests\TestCase; final class RegimenCapitalRemoverTest extends TestCase { /** @return array<string, array{string, string}> */ public function providerMostCommonCases(): array { return [ 'SA' => ['EMPRESA PATITO', 'SA'], 'SA with extra space' => ['EMPRESA PATITO ', 'SA'], 'SA DE CV' => ['EMPRESA PATITO', 'SA DE CV'], 'SAB' => ['EMPRESA PATITO', 'SAB'], 'S DE RL' => ['EMPRESA PATITO', 'SAB'], ]; } /** @dataProvider providerMostCommonCases */ public function testMostCommonCases(string $expectedName, string $suffix): void { $fullname = sprintf('%s %s', $expectedName, $suffix); $expectedName = trim($expectedName); $remover = RegimenCapitalRemover::createDefault(); $removedName = $remover->remove($fullname); $this->assertSame($expectedName, $removedName); } public function testRemoveOnlyOneEntry(): void { // SA & SAB, both are suffixes. $fullname = 'AUDITORES SAB SA'; $expected = 'AUDITORES SAB'; $remover = RegimenCapitalRemover::createDefault(); $this->assertSame($expected, $remover->remove($fullname)); } public function testRemoveSapiDeCv(): void { // There are CSD (like 00001000000710061506) with "EMPRESA S A P I DE CV" $fullname = 'EMPRESA S A P I DE CV'; $expected = 'EMPRESA'; $remover = RegimenCapitalRemover::createDefault(); $this->assertSame($expected, $remover->remove($fullname)); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Utils/CurrencyDecimalsTest.php
tests/CfdiUtilsTests/Utils/CurrencyDecimalsTest.php
<?php namespace CfdiUtilsTests\Utils; use CfdiUtils\Utils\CurrencyDecimals; use CfdiUtilsTests\TestCase; final class CurrencyDecimalsTest extends TestCase { public function testCreateGeneric(): void { $curdec = new CurrencyDecimals('FOO', 2); $this->assertSame('FOO', $curdec->currency()); $this->assertSame(2, $curdec->decimals()); } /** * @testWith [""] * ["ÑÑÑ"] * ["XXXX"] */ public function testCreateWithEmptyCode(string $currency): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage('currency'); new CurrencyDecimals($currency, 2); } public function testCreateWithNegativeDecimals(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage('decimals'); new CurrencyDecimals('FOO', -1); } public function testDoesNotExceed(): void { $foo = new CurrencyDecimals('FOO', 3); $this->assertTrue($foo->doesNotExceedDecimals('1')); $this->assertTrue($foo->doesNotExceedDecimals('1.000')); $this->assertTrue($foo->doesNotExceedDecimals('1.999')); $this->assertFalse($foo->doesNotExceedDecimals('1.0001')); $this->assertFalse($foo->doesNotExceedDecimals('1.0000')); } public function testDecimalsCount(): void { $this->assertSame(0, CurrencyDecimals::decimalsCount('1')); $this->assertSame(0, CurrencyDecimals::decimalsCount('1.')); $this->assertSame(1, CurrencyDecimals::decimalsCount('1.0')); $this->assertSame(2, CurrencyDecimals::decimalsCount('1.00')); } public function testKnownCurrencyMexicanPeso(): void { $mxn = CurrencyDecimals::newFromKnownCurrencies('MXN'); $this->assertSame('MXN', $mxn->currency()); $this->assertSame(2, $mxn->decimals()); } public function testUnknownCurrency(): void { $this->expectException(\OutOfBoundsException::class); $this->expectExceptionMessage('not known'); CurrencyDecimals::newFromKnownCurrencies('FOO'); } public function testUnknownCurrencyWithDecimals(): void { $foo = CurrencyDecimals::newFromKnownCurrencies('FOO', 6); $this->assertSame('FOO', $foo->currency()); $this->assertSame(6, $foo->decimals()); } public function testKnownDecimalsMexicanPeso(): void { $this->assertSame(2, CurrencyDecimals::knownCurrencyDecimals('MXN')); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Utils/RfcTest.php
tests/CfdiUtilsTests/Utils/RfcTest.php
<?php namespace CfdiUtilsTests\Utils; use CfdiUtils\Utils\Rfc; use CfdiUtilsTests\TestCase; final class RfcTest extends TestCase { public function testCreateRfcPerson(): void { $input = 'COSC8001137NA'; $rfc = new Rfc($input); $this->assertSame($input, (string) $rfc); $this->assertFalse($rfc->isGeneric()); $this->assertFalse($rfc->isForeign()); $this->assertFalse($rfc->isMoral()); $this->assertTrue($rfc->isPerson()); $this->assertSame('A', $rfc->checkSum()); $this->assertTrue($rfc->checkSumMatch()); } public function testCreateRfcMoral(): void { $input = 'DIM8701081LA'; $rfc = new Rfc($input); $this->assertSame($input, (string) $rfc); $this->assertFalse($rfc->isGeneric()); $this->assertFalse($rfc->isForeign()); $this->assertTrue($rfc->isMoral()); $this->assertFalse($rfc->isPerson()); } public function testCreateWithForeign(): void { $rfc = new Rfc(Rfc::RFC_FOREIGN); $this->assertFalse($rfc->isGeneric()); $this->assertTrue($rfc->isForeign()); $this->assertFalse($rfc->isMoral()); $this->assertTrue($rfc->isPerson()); } public function testCreateWithGeneric(): void { $rfc = new Rfc(Rfc::RFC_GENERIC); $this->assertTrue($rfc->isGeneric()); $this->assertFalse($rfc->isForeign()); $this->assertFalse($rfc->isMoral()); $this->assertTrue($rfc->isPerson()); } public function testCreateDisallowGeneric(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage('público en general'); new Rfc(Rfc::RFC_GENERIC, Rfc::DISALLOW_GENERIC | Rfc::DISALLOW_FOREIGN); } public function testCreateDisallowForeign(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage('operaciones con extranjeros'); new Rfc(Rfc::RFC_FOREIGN, Rfc::DISALLOW_GENERIC | Rfc::DISALLOW_FOREIGN); } public function testCreateBadFormat(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage('formato'); new Rfc('COSC800113-7NA'); } public function testCreateBadDate(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage('fecha'); new Rfc('COSC8002317NA'); } public function testCreateBadDigit(): void { $rfc = new Rfc('COSC8001137N9'); $this->assertSame('A', $rfc->checkSum()); $this->assertFalse($rfc->checkSumMatch()); } public function testIsValid(): void { $this->assertTrue(Rfc::isValid('COSC8001137NA')); } public function testIsNotValid(): void { $this->assertFalse(Rfc::isValid('COSC8099137NA')); } public function testWithMultiByte(): void { $rfcMultiByte = 'AÑÑ801231JK0'; $expectedDate = strtotime('2080-12-31'); $this->assertSame($expectedDate, Rfc::obtainDate($rfcMultiByte)); $rfc = new Rfc($rfcMultiByte); $this->assertTrue($rfc->isMoral()); } public function testObtainDateLeapYears(): void { // valid leap year $expectedDate = strtotime('2000-02-29'); $this->assertSame($expectedDate, Rfc::obtainDate('XXX000229XX6')); // invalid leap year $this->assertSame(0, Rfc::obtainDate('XXX030229XX6')); } /** * @testWith [""] * ["ABCD010100AAA"] * ["ABCD010001AAA"] * ["ABCD010132AAA"] * ["ABCD010229AAA"] * ["ABCD000230AAA"] * ["ABCD0A0101AAA"] * ["ABCD010A01AAA"] * ["ABCD01010AAAA"] * ["ABCD-10123AAA"] */ public function testObtainDateWithInvalidInput(string $rfc): void { $this->assertSame(0, Rfc::obtainDate($rfc)); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Utils/SchemaLocationsTest.php
tests/CfdiUtilsTests/Utils/SchemaLocationsTest.php
<?php namespace CfdiUtilsTests\Utils; use CfdiUtils\Utils\SchemaLocations; use CfdiUtilsTests\TestCase; final class SchemaLocationsTest extends TestCase { public function testConstructorWithEmptyValue(): void { $schemaLocations = new SchemaLocations(); $this->assertSame([], $schemaLocations->pairs()); $this->assertCount(0, $schemaLocations); $this->assertTrue($schemaLocations->isEmpty()); } public function testConstructorWithValidValues(): void { $pairs = [ 'http://tempuri.org/my-foo' => 'http://tempuri.org/my-foo.xls', 'http://tempuri.org/my-bar' => 'http://tempuri.org/my-bar.xls', ]; $schemaLocations = new SchemaLocations($pairs); $this->assertSame($pairs, $schemaLocations->pairs()); $this->assertCount(2, $schemaLocations); $this->assertFalse($schemaLocations->isEmpty()); } public function testHasNamespace(): void { $pairs = [ 'http://tempuri.org/my-foo' => 'http://tempuri.org/my-foo.xls', 'http://tempuri.org/my-bar' => 'http://tempuri.org/my-bar.xls', ]; $schemaLocations = new SchemaLocations($pairs); $this->assertTrue($schemaLocations->has('http://tempuri.org/my-foo')); $this->assertFalse($schemaLocations->has('http://tempuri.org/my-xee')); } public function testAppendAndRemove(): void { $pairs = [ 'http://tempuri.org/my-foo' => 'http://tempuri.org/my-foo.xls', 'http://tempuri.org/my-bar' => 'http://tempuri.org/my-bar.xls', ]; $schemaLocations = new SchemaLocations($pairs); $schemaLocations->append('http://tempuri.org/my-xee', 'http://tempuri.org/my-xee.xls'); $this->assertTrue($schemaLocations->has('http://tempuri.org/my-xee')); $schemaLocations->remove('http://tempuri.org/my-xee'); $this->assertFalse($schemaLocations->has('http://tempuri.org/my-xee')); } public function testAsStringWithCompleteValues(): void { $pairs = [ 'http://tempuri.org/my-foo' => 'http://tempuri.org/my-foo.xls', 'http://tempuri.org/my-bar' => 'http://tempuri.org/my-bar.xls', ]; $schemaLocations = new SchemaLocations($pairs); $expected = 'http://tempuri.org/my-foo http://tempuri.org/my-foo.xls' . ' http://tempuri.org/my-bar http://tempuri.org/my-bar.xls'; $this->assertSame($expected, $schemaLocations->asString()); $this->assertFalse($schemaLocations->hasAnyNamespaceWithoutLocation()); } public function testAsStringWithIncompleteValues(): void { $pairs = [ 'http://tempuri.org/my-aaa' => '', 'http://tempuri.org/my-foo' => 'http://tempuri.org/my-foo.xls', 'http://tempuri.org/my-bbb' => '', 'http://tempuri.org/my-bar' => 'http://tempuri.org/my-bar.xls', 'http://tempuri.org/my-ccc' => '', ]; $schemaLocations = new SchemaLocations($pairs); $expected = 'http://tempuri.org/my-foo http://tempuri.org/my-foo.xls' . ' http://tempuri.org/my-bar http://tempuri.org/my-bar.xls'; $this->assertSame($expected, $schemaLocations->asString()); $this->assertTrue($schemaLocations->hasAnyNamespaceWithoutLocation()); $this->assertSame([ 'http://tempuri.org/my-aaa', 'http://tempuri.org/my-bbb', 'http://tempuri.org/my-ccc', ], $schemaLocations->getNamespacesWithoutLocation()); } public function testTraverse(): void { $pairs = [ 'http://tempuri.org/my-foo' => 'http://tempuri.org/my-foo.xls', 'http://tempuri.org/my-bar' => 'http://tempuri.org/my-bar.xls', ]; $schemaLocations = new SchemaLocations($pairs); $this->assertSame($pairs, iterator_to_array($schemaLocations)); } public function testConstructFromString(): void { $input = ' http://tempuri.org/my-foo http://tempuri.org/my-foo.xls ' . 'http://tempuri.org/my-bar http://tempuri.org/my-bar.xls '; $schemaLocations = SchemaLocations::fromString($input, false); $expected = [ 'http://tempuri.org/my-foo' => 'http://tempuri.org/my-foo.xls', 'http://tempuri.org/my-bar' => 'http://tempuri.org/my-bar.xls', ]; $this->assertSame($expected, $schemaLocations->pairs()); } public function testConstructFromStringWithOddContentsExcludingLast(): void { $input = 'http://tempuri.org/my-foo http://tempuri.org/my-foo.xls' . ' http://tempuri.org/my-bar http://tempuri.org/my-bar.xls' . ' http://tempuri.org/my-xee'; $schemaLocations = SchemaLocations::fromString($input, false); $this->assertFalse($schemaLocations->hasAnyNamespaceWithoutLocation()); $expected = [ 'http://tempuri.org/my-foo' => 'http://tempuri.org/my-foo.xls', 'http://tempuri.org/my-bar' => 'http://tempuri.org/my-bar.xls', ]; $this->assertSame($expected, $schemaLocations->pairs()); } public function testConstructFromStringWithOddContentsIncludingLast(): void { $input = 'http://tempuri.org/my-foo http://tempuri.org/my-foo.xls' . ' http://tempuri.org/my-bar http://tempuri.org/my-bar.xls' . ' http://tempuri.org/my-xee'; $schemaLocations = SchemaLocations::fromString($input, true); $this->assertTrue($schemaLocations->hasAnyNamespaceWithoutLocation()); $expected = [ 'http://tempuri.org/my-foo' => 'http://tempuri.org/my-foo.xls', 'http://tempuri.org/my-bar' => 'http://tempuri.org/my-bar.xls', 'http://tempuri.org/my-xee' => '', ]; $this->assertSame($expected, $schemaLocations->pairs()); } public function testConstructFromStringStrictXsd(): void { // source include spaces to ensure that is working properly $source = ' bleh foo foo.xsd bar baz zoo zoo.xsd baa xee xee.xsd bah '; $schemaLocations = SchemaLocations::fromStingStrictXsd($source); $this->assertSame(['bleh', 'bar', 'baz', 'baa', 'bah'], $schemaLocations->getNamespacesWithoutLocation()); $this->assertSame('foo foo.xsd zoo zoo.xsd xee xee.xsd', $schemaLocations->asString()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Utils/XmlTest.php
tests/CfdiUtilsTests/Utils/XmlTest.php
<?php namespace CfdiUtilsTests\Utils; use CfdiUtils\Utils\Xml; use CfdiUtilsTests\TestCase; use DOMDocument; final class XmlTest extends TestCase { public function testMethodNewDocumentContentWithInvalidXmlEncoding(): void { $invalidXml = mb_convert_encoding('<e a="ñ"></e>', 'ISO-8859-1', 'UTF-8'); // the ñ is a special character $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage('Cannot create a DOM Document from xml string' . PHP_EOL . 'XML Fatal [L: 1, C: 7]: Input is not proper UTF-8'); Xml::newDocumentContent($invalidXml); } public function testMethodDocumentElementWithoutRootElement(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage('DOM Document does not have root element'); Xml::documentElement(new DOMDocument()); } public function testMethodDocumentElementWithRootElement(): void { $document = new DOMDocument(); $root = $document->createElement('root'); $document->appendChild($root); $this->assertSame($root, Xml::documentElement($document)); } /** * @testWith ["", ""] * ["foo", "foo"] * ["&amp;", "&"] * ["&lt;", "<"] * ["&gt;", ">"] * ["'", "'"] * ["\"", "\""] * ["&amp;copy;", "&copy;"] * ["foo &amp; bar", "foo & bar"] */ public function testMethodCreateElement(string $expected, string $content): void { $elementName = 'element'; $document = Xml::newDocument(); $element = Xml::createElement($document, $elementName, $content); $document->appendChild($element); $this->assertSame($content, $element->textContent); $this->assertXmlStringEqualsXmlString( sprintf('<%1$s>%2$s</%1$s>', $elementName, $expected), $document->saveXML($element) ); } public function testMethodCreateElementWithBadName(): void { $document = Xml::newDocument(); $this->expectException(\LogicException::class); $this->expectExceptionMessage('Cannot create element'); Xml::createElement($document, ''); } /** * @testWith ["", ""] * ["foo", "foo"] * ["&amp;", "&"] * ["&lt;", "<"] * ["&gt;", ">"] * ["'", "'"] * ["\"", "\""] * ["&amp;copy;", "&copy;"] * ["foo &amp; bar", "foo & bar"] */ public function testMethodCreateElementNs(string $expected, string $content): void { $prefix = 'foo'; $namespaceURI = 'http://tempuri.org/'; $elementName = $prefix . ':element'; $document = Xml::newDocument(); $element = Xml::createElementNS($document, $namespaceURI, $elementName, $content); $document->appendChild($element); $this->assertSame($content, $element->textContent); $this->assertXmlStringEqualsXmlString( sprintf('<%1$s xmlns:%3$s="%4$s">%2$s</%1$s>', $elementName, $expected, $prefix, $namespaceURI), $document->saveXML($element) ); } public function testMethodCreateElementNsWithBadName(): void { $document = Xml::newDocument(); $this->expectException(\LogicException::class); $this->expectExceptionMessage('Cannot create element'); Xml::createElementNS($document, 'http://tempuri.org/', ''); } public function testMethodCreateElementNsWithBadUri(): void { $document = Xml::newDocument(); $this->expectException(\LogicException::class); $this->expectExceptionMessage('Cannot create element'); Xml::createElementNS($document, '', 'x:foo'); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Retenciones/RetencionesCreatorCommonMethodsTrait.php
tests/CfdiUtilsTests/Retenciones/RetencionesCreatorCommonMethodsTrait.php
<?php namespace CfdiUtilsTests\Retenciones; use CfdiUtils\Retenciones\RetencionesCreator10; use CfdiUtils\Retenciones\RetencionesCreator20; use LogicException; trait RetencionesCreatorCommonMethodsTrait { abstract public function createMinimalCreator(): RetencionesCreator10|RetencionesCreator20; public function testBuildCadenaDeOrigenWithoutXmlResolver(): void { $specimen = $this->createMinimalCreator(); $specimen->setXmlResolver(null); $this->expectException(LogicException::class); $this->expectExceptionMessage('Cannot build the cadena de origen since there is no xml resolver'); $specimen->buildCadenaDeOrigen(); } public function testBuildCadenaDeOrigenWithoutXsltBuilder(): void { $specimen = $this->createMinimalCreator(); $specimen->setXsltBuilder(null); $this->expectException(LogicException::class); $this->expectExceptionMessage('Cannot build the cadena de origen since there is no xslt builder'); $specimen->buildCadenaDeOrigen(); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Retenciones/RetencionesTest.php
tests/CfdiUtilsTests/Retenciones/RetencionesTest.php
<?php namespace CfdiUtilsTests\Retenciones; use CfdiUtils\CfdiCreateObjectException; use CfdiUtils\Retenciones\Retenciones; use CfdiUtils\Utils\Xml; use CfdiUtilsTests\TestCase; final class RetencionesTest extends TestCase { public const XML_MINIMAL_DEFINITION = <<<XML <retenciones:Retenciones xmlns:retenciones="http://www.sat.gob.mx/esquemas/retencionpago/1" Version="1.0"/> XML; public const XML_20_MINIMAL_DEFINITION = <<<XML <retenciones:Retenciones xmlns:retenciones="http://www.sat.gob.mx/esquemas/retencionpago/2" Version="2.0"/> XML; public function providerRetencionesVersionNamespace(): array { return [ '2.0' => ['2.0', 'http://www.sat.gob.mx/esquemas/retencionpago/2'], '1.0' => ['1.0', 'http://www.sat.gob.mx/esquemas/retencionpago/1'], ]; } public function testNewFromStringWithEmptyXml(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage('empty'); Retenciones::newFromString(''); } public function testNewFromStringWithInvalidXml(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage('Cannot create a DOM Document'); Retenciones::newFromString(' '); } /** @dataProvider providerRetencionesVersionNamespace */ public function testConstructWithoutNamespace(string $version, string $namespace): void { $exception = $this->captureException(function (): void { Retenciones::newFromString('<Retenciones ' . '/>'); }); $this->assertInstanceOf(CfdiCreateObjectException::class, $exception); /** @var CfdiCreateObjectException $exception */ $this->assertStringContainsString( 'namespace ' . $namespace, $exception->getExceptionByVersion($version)->getMessage() ); } /** @dataProvider providerRetencionesVersionNamespace */ public function testConstructWithEmptyDomDocument(string $version): void { $exception = $this->captureException(function (): void { new Retenciones(new \DOMDocument()); }); $this->assertInstanceOf(CfdiCreateObjectException::class, $exception); /** @var CfdiCreateObjectException $exception */ $this->assertStringContainsString( 'DOM Document does not have root element', $exception->getExceptionByVersion($version)->getMessage() ); } /** @dataProvider providerRetencionesVersionNamespace */ public function testInvalidCfdiRootIsNotComprobante(string $version, string $namespace): void { $exception = $this->captureException(function () use ($namespace): void { Retenciones::newFromString(sprintf('<retenciones:X xmlns:retenciones="%s"/>', $namespace)); }); $this->assertInstanceOf(CfdiCreateObjectException::class, $exception); /** @var CfdiCreateObjectException $exception */ $this->assertStringContainsString( 'Root element is not retenciones:Retenciones', $exception->getExceptionByVersion($version)->getMessage() ); } /** @dataProvider providerRetencionesVersionNamespace */ public function testInvalidCfdiRootIsPrefixedWithUnexpectedName(string $version, string $namespace): void { $exception = $this->captureException(function () use ($namespace): void { Retenciones::newFromString(sprintf('<x:Retenciones xmlns:x="%s"/>', $namespace)); }); $this->assertInstanceOf(CfdiCreateObjectException::class, $exception); /** @var CfdiCreateObjectException $exception */ $this->assertStringContainsString( "Prefix for namespace $namespace is not \"retenciones\"", $exception->getExceptionByVersion($version)->getMessage() ); } /** @dataProvider providerRetencionesVersionNamespace */ public function testInvalidCfdiRootPrefixDoesNotMatchWithNamespaceDeclaration( string $version, string $namespace, ): void { $exception = $this->captureException(function () use ($namespace): void { Retenciones::newFromString(sprintf('<x:Retenciones xmlns:retenciones="%s"/>', $namespace)); }); $this->assertInstanceOf(CfdiCreateObjectException::class, $exception); /** @var CfdiCreateObjectException $exception */ $this->assertStringContainsString( 'Root element is not retenciones:Retenciones', $exception->getExceptionByVersion($version)->getMessage() ); } public function testValid10(): void { $retencion = Retenciones::newFromString(self::XML_MINIMAL_DEFINITION); $this->assertEquals('1.0', $retencion->getVersion()); } public function testValida20(): void { $retencion = Retenciones::newFromString(self::XML_20_MINIMAL_DEFINITION); $this->assertEquals('2.0', $retencion->getVersion()); } public function testValid10WithXmlHeader(): void { $retencion = Retenciones::newFromString( '<?xml version="1.0" encoding="UTF-8" ?>' . PHP_EOL . self::XML_MINIMAL_DEFINITION ); $this->assertEquals('1.0', $retencion->getVersion()); } public function testVersion1980ReturnEmpty(): void { $retencion = Retenciones::newFromString( str_replace('Version="1.0"', 'Version="1980"', self::XML_MINIMAL_DEFINITION) ); $this->assertEmpty($retencion->getVersion()); } public function testVersionEmptyReturnEmpty(): void { $retencion = Retenciones::newFromString( str_replace('Version="1.0"', 'Version=""', self::XML_MINIMAL_DEFINITION) ); $this->assertEmpty($retencion->getVersion()); } public function testGetDocument(): void { $xml = self::XML_MINIMAL_DEFINITION; $document = Xml::newDocument(); $document->loadXML($xml); $retencion = new Retenciones($document); $retrieved = $retencion->getDocument(); $this->assertNotSame($document, $retrieved, 'The DOM Document must NOT be the same as constructed'); $this->assertXmlStringEqualsXmlString($xml, $retrieved->saveXML(), 'The DOM Documents should be equal'); } public function testGetSource(): void { $xml = self::XML_MINIMAL_DEFINITION; $retencion = Retenciones::newFromString($xml); $retrieved = $retencion->getSource(); $this->assertSame($xml, $retrieved); } public function testGetNode(): void { $retencion = Retenciones::newFromString(self::XML_MINIMAL_DEFINITION); $node = $retencion->getNode(); $this->assertSame($retencion->getVersion(), $node['Version']); } public function testGetQuickReader(): void { $retencion = Retenciones::newFromString(self::XML_MINIMAL_DEFINITION); $quickReader = $retencion->getQuickReader(); $this->assertSame($retencion->getVersion(), $quickReader['VERSION']); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Retenciones/RetencionesCreator20Test.php
tests/CfdiUtilsTests/Retenciones/RetencionesCreator20Test.php
<?php namespace CfdiUtilsTests\Retenciones; use CfdiUtils\CadenaOrigen\DOMBuilder; use CfdiUtils\Certificado\Certificado; use CfdiUtils\Elements\Dividendos10\Dividendos; use CfdiUtils\Retenciones\RetencionesCreator20; use CfdiUtilsTests\TestCase; final class RetencionesCreator20Test extends TestCase { use RetencionesCreatorCommonMethodsTrait; public function createMinimalCreator(): RetencionesCreator20 { return new RetencionesCreator20(); } public function testCreatePreCfdiWithAllCorrectValues(): void { $cerFile = $this->utilAsset('certs/EKU9003173C9.cer'); $pemFile = $this->utilAsset('certs/EKU9003173C9.key.pem'); $passPhrase = ''; $certificado = new Certificado($cerFile); $xmlResolver = $this->newResolver(); $xsltBuilder = new DOMBuilder(); // create object $creator = new RetencionesCreator20([ 'FechaExp' => '2022-01-13T14:15:16', 'CveRetenc' => '14', // Dividendos o utilidades distribuidos 'LugarExpRetenc' => '91778', ], $xmlResolver, $xsltBuilder, $certificado); $retenciones = $creator->retenciones(); // available on RET 2.0 $retenciones->addCfdiRetenRelacionados([ 'TipoRelacion' => '01', 'UUID' => '1474b7d3-61fc-41c4-a8b8-3f22e1161bb4', ]); $retenciones->addEmisor([ 'RfcE' => 'EKU9003173C9', 'NomDenRazSocE' => 'ESCUELA KEMPER URGATE', 'RegimenFiscalE' => '601', ]); $retenciones->getReceptor()->addExtranjero([ 'NumRegIdTribR' => '998877665544332211', 'NomDenRazSocR' => 'WORLD WIDE COMPANY INC', ]); $retenciones->addPeriodo(['MesIni' => '05', 'MesFin' => '05', 'Ejercicio' => '2021']); $retenciones->addTotales([ 'MontoTotOperacion' => '55578643', 'MontoTotGrav' => '0', 'MontoTotExent' => '55578643', 'MontoTotRet' => '0', 'UtilidadBimestral' => '0.1', 'ISRCorrespondiente' => '0.1', ]); $retenciones->addImpRetenidos([ 'BaseRet' => '0', 'ImpuestoRet' => '001', // same as CFDI 'TipoPagoRet' => '01', 'MontoRet' => '200.00', ]); $dividendos = new Dividendos(); $dividendos->addDividOUtil([ 'CveTipDivOUtil' => '06', // 06 - Proviene de CUFIN al 31 de diciembre 2013 'MontISRAcredRetMexico' => '0', 'MontISRAcredRetExtranjero' => '0', 'MontRetExtDivExt' => '0', 'TipoSocDistrDiv' => 'Sociedad Nacional', 'MontISRAcredNal' => '0', 'MontDivAcumNal' => '0', 'MontDivAcumExt' => '0', ]); $retenciones->addComplemento($dividendos); // verify properties $this->assertSame($xmlResolver, $creator->getXmlResolver()); $this->assertSame($xsltBuilder, $creator->getXsltBuilder()); // verify root node $root = $creator->retenciones(); $this->assertSame('2.0', $root['Version']); // put additional content using helpers $this->assertSame($certificado, $creator->getCertificado()); // it was placed on constructor also $creator->putCertificado($certificado); $creator->addSello('file://' . $pemFile, $passPhrase); // move sat definitions $creator->moveSatDefinitionsToRetenciones(); // validate $asserts = $creator->validate(); $this->assertGreaterThanOrEqual(1, $asserts->count()); $this->assertTrue($asserts->exists('XSD01')); $this->assertSame('', $asserts->get('XSD01')->getExplanation()); $this->assertFalse($asserts->hasErrors()); // check against known content /** @see tests/assets/retenciones/retenciones20.xml */ $this->assertXmlStringEqualsXmlFile($this->utilAsset('retenciones/retenciones20.xml'), $creator->asXml()); } public function testValidateIsCheckingAgainstXsdViolations(): void { $retencion = new RetencionesCreator20(); $retencion->setXmlResolver($this->newResolver()); $assert = $retencion->validate()->get('XSD01'); $this->assertTrue($assert->getStatus()->isError()); } public function testAddSelloFailsWithWrongPassPrase(): void { $pemFile = $this->utilAsset('certs/EKU9003173C9_password.key.pem'); $passPhrase = '_worng_passphrase_'; $retencion = new RetencionesCreator20(); $retencion->setXmlResolver($this->newResolver()); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Cannot open the private key'); $retencion->addSello('file://' . $pemFile, $passPhrase); } public function testAddSelloFailsWithWrongCertificado(): void { $cerFile = $this->utilAsset('certs/CSD09_AAA010101AAA.cer'); $pemFile = $this->utilAsset('certs/EKU9003173C9.key.pem'); $passPhrase = ''; $certificado = new Certificado($cerFile); $retencion = new RetencionesCreator20(); $retencion->setXmlResolver($this->newResolver()); $retencion->putCertificado($certificado); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('The private key does not belong to the current certificate'); $retencion->addSello('file://' . $pemFile, $passPhrase); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Retenciones/RetencionesCreator10Test.php
tests/CfdiUtilsTests/Retenciones/RetencionesCreator10Test.php
<?php namespace CfdiUtilsTests\Retenciones; use CfdiUtils\CadenaOrigen\DOMBuilder; use CfdiUtils\Certificado\Certificado; use CfdiUtils\Elements\Dividendos10\Dividendos; use CfdiUtils\Retenciones\RetencionesCreator10; use CfdiUtilsTests\TestCase; final class RetencionesCreator10Test extends TestCase { use RetencionesCreatorCommonMethodsTrait; public function createMinimalCreator(): RetencionesCreator10 { return new RetencionesCreator10(); } public function testCreatePreCfdiWithAllCorrectValues(): void { $cerFile = $this->utilAsset('certs/EKU9003173C9.cer'); $pemFile = $this->utilAsset('certs/EKU9003173C9.key.pem'); $passPhrase = ''; $certificado = new Certificado($cerFile); $xmlResolver = $this->newResolver(); $xsltBuilder = new DOMBuilder(); // create object $creator = new RetencionesCreator10([ 'FechaExp' => '2021-01-13T14:15:16-06:00', 'CveRetenc' => '14', // Dividendos o utilidades distribuidos ], $xmlResolver, $xsltBuilder); $retenciones = $creator->retenciones(); $retenciones->addEmisor([ 'RFCEmisor' => 'EKU9003173C9', 'NomDenRazSocE' => 'ESCUELA KEMPER URGATE SA DE CV', ]); $retenciones->getReceptor()->addExtranjero([ 'NumRegIdTrib' => '998877665544332211', 'NomDenRazSocR' => 'WORLD WIDE COMPANY INC', ]); $retenciones->addPeriodo(['MesIni' => '5', 'MesFin' => '5', 'Ejerc' => '2018']); $retenciones->addTotales([ 'montoTotOperacion' => '55578643', 'montoTotGrav' => '0', 'montoTotExent' => '55578643', 'montoTotRet' => '0', ]); $retenciones->addImpRetenidos([ 'BaseRet' => '0', 'Impuesto' => '01', // 01 - ISR 'montoRet' => '0', 'TipoPagoRet' => 'Pago provisional', ]); $dividendos = new Dividendos(); $dividendos->addDividOUtil([ 'CveTipDivOUtil' => '06', // 06 - Proviene de CUFIN al 31 de diciembre 2013 'MontISRAcredRetMexico' => '0', 'MontISRAcredRetExtranjero' => '0', 'MontRetExtDivExt' => '0', 'TipoSocDistrDiv' => 'Sociedad Nacional', 'MontISRAcredNal' => '0', 'MontDivAcumNal' => '0', 'MontDivAcumExt' => '0', ]); $retenciones->addComplemento($dividendos); // verify properties $this->assertSame($xmlResolver, $creator->getXmlResolver()); $this->assertSame($xsltBuilder, $creator->getXsltBuilder()); // verify root node $root = $creator->retenciones(); $this->assertSame('1.0', $root['Version']); // put additional content using helpers $creator->putCertificado($certificado); $creator->addSello('file://' . $pemFile, $passPhrase); // move sat definitions $creator->moveSatDefinitionsToRetenciones(); // validate $asserts = $creator->validate(); $this->assertGreaterThanOrEqual(1, $asserts->count()); $this->assertTrue($asserts->exists('XSD01')); $this->assertSame('', $asserts->get('XSD01')->getExplanation()); $this->assertFalse($asserts->hasErrors()); // check against known content /** @see tests/assets/retenciones/retenciones10.xml */ $this->assertXmlStringEqualsXmlFile($this->utilAsset('retenciones/retenciones10.xml'), $creator->asXml()); } public function testValidateIsCheckingAgainstXsdViolations(): void { $retencion = new RetencionesCreator10(); $retencion->setXmlResolver($this->newResolver()); $assert = $retencion->validate()->get('XSD01'); $this->assertTrue($assert->getStatus()->isError()); } public function testAddSelloFailsWithWrongPassPrase(): void { $pemFile = $this->utilAsset('certs/EKU9003173C9_password.key.pem'); $passPhrase = '_worng_passphrase_'; $retencion = new RetencionesCreator10(); $retencion->setXmlResolver($this->newResolver()); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Cannot open the private key'); $retencion->addSello('file://' . $pemFile, $passPhrase); } public function testAddSelloFailsWithWrongCertificado(): void { $cerFile = $this->utilAsset('certs/CSD09_AAA010101AAA.cer'); $pemFile = $this->utilAsset('certs/EKU9003173C9.key.pem'); $passPhrase = ''; $certificado = new Certificado($cerFile); $retencion = new RetencionesCreator10(); $retencion->setXmlResolver($this->newResolver()); $retencion->putCertificado($certificado); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('The private key does not belong to the current certificate'); $retencion->addSello('file://' . $pemFile, $passPhrase); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Retenciones/RetencionVersionTest.php
tests/CfdiUtilsTests/Retenciones/RetencionVersionTest.php
<?php namespace CfdiUtilsTests\Retenciones; use CfdiUtils\Nodes\Node; use CfdiUtils\Nodes\XmlNodeUtils; use CfdiUtils\Retenciones\RetencionVersion; use CfdiUtilsTests\TestCase; final class RetencionVersionTest extends TestCase { public function providerRetencionVersion(): array { return [ '2.0' => ['2.0', 'Version', '2.0'], '1.0' => ['1.0', 'Version', '1.0'], '2.0 bad case' => ['', 'version', '2.0'], '1.0 bad case' => ['', 'version', '1.0'], '2.0 non set' => ['', 'Version', null], '1.0 non set' => ['', 'Version', null], '2.0 empty' => ['', 'Version', ''], '1.0 empty' => ['', 'Version', ''], '2.0 wrong number' => ['', 'Version', '2.1'], '1.0 wrong number' => ['', 'Version', '2.1'], ]; } /** * @dataProvider providerRetencionVersion */ public function testRetencionVersion(string $expected, string $attribute, ?string $value): void { $node = new Node('retenciones', [$attribute => $value]); $cfdiVersion = new RetencionVersion(); $this->assertSame($expected, $cfdiVersion->getFromNode($node)); $this->assertSame($expected, $cfdiVersion->getFromXmlString(XmlNodeUtils::nodeToXmlString($node))); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Nodes/NodesTest.php
tests/CfdiUtilsTests/Nodes/NodesTest.php
<?php namespace CfdiUtilsTests\Nodes; use CfdiUtils\Nodes\Node; use CfdiUtils\Nodes\NodeInterface; use CfdiUtils\Nodes\Nodes; use CfdiUtilsTests\TestCase; final class NodesTest extends TestCase { public function testEmptyNodes(): void { $nodes = new Nodes(); $this->assertCount(0, $nodes); $this->assertNull($nodes->firstNodeWithName('non-existent')); } public function testConstructWithNodesArray(): void { $expected = [ new Node('foo'), new Node('bar'), ]; $nodes = new Nodes($expected); $this->assertCount(2, $nodes); foreach ($nodes as $index => $node) { $this->assertSame($expected[$index], $node); } } public function testManipulateTheCollection(): void { $first = new Node('first'); $second = new Node('second'); $nodes = new Nodes(); $nodes->add($first, $second); $this->assertCount(2, $nodes); $this->assertTrue($nodes->exists($first)); $this->assertTrue($nodes->exists($second)); $equalToFirst = new Node('foo'); $this->assertFalse($nodes->exists($equalToFirst)); // add an equal node $nodes->add($equalToFirst); $this->assertCount(3, $nodes); // add an identical node $nodes->add($equalToFirst); $this->assertCount(3, $nodes); // remove the node $nodes->remove($equalToFirst); $this->assertCount(2, $nodes); // remove the node again $nodes->remove($equalToFirst); $this->assertCount(2, $nodes); $this->assertNull($nodes->firstNodeWithName('foo')); $this->assertSame($first, $nodes->firstNodeWithName('first')); $this->assertSame($second, $nodes->firstNodeWithName('second')); } public function testAddFindRemove(): void { $root = new Node('root'); $nodes = $root->children(); $child = new Node('child'); $nodes->add($child); $this->assertTrue($nodes->exists($child)); $found = $root->searchNode('child'); $this->assertSame($child, $found); $nodes->remove($found); $this->assertFalse($nodes->exists($child)); } public function testFirstReturnsNull(): void { $nodes = new Nodes(); $this->assertNull($nodes->first()); } public function testImportFromArray(): void { $nodeOne = new Node('one'); $nodes = new Nodes(); $nodes->importFromArray([ $nodeOne, new Node('two'), new Node('three'), ]); $this->assertCount(3, $nodes); $this->assertSame($nodeOne, $nodes->first()); } public function testImportFromArrayWithNonNode(): void { $nodes = new Nodes(); $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('The element index 0 is not a NodeInterface object'); /** @var NodeInterface $specimen Override type to avoid problems with static analyser */ $specimen = new \stdClass(); /** @phpstan-ignore-line */ $nodes->importFromArray([$specimen]); } public function testGetThrowsExceptionWhenNotFound(): void { $nodes = new Nodes(); $this->expectException(\OutOfRangeException::class); $this->expectExceptionMessage('The index 0 does not exists'); $nodes->get(0); } public function testGetWithExistentElements(): void { $foo = new Node('foo'); $bar = new Node('bar'); $nodes = new Nodes([$foo, $bar]); $this->assertSame($foo, $nodes->get(0)); $this->assertSame($bar, $nodes->get(1)); // get after remove $nodes->remove($foo); $this->assertSame($bar, $nodes->get(0)); } public function testGetNodesByName(): void { $nodes = new Nodes(); $first = new Node('children'); $second = new Node('children'); $third = new Node('children'); $nodes->importFromArray([ $first, $second, $third, new Node('other'), ]); $this->assertCount(4, $nodes); $byName = $nodes->getNodesByName('children'); $this->assertCount(3, $byName); $this->assertTrue($byName->exists($first)); $this->assertTrue($byName->exists($second)); $this->assertTrue($byName->exists($third)); } public function testOrderedChildren(): void { $nodes = new Nodes([ new Node('foo'), new Node('bar'), new Node('baz'), ]); // test initial order $this->assertEquals( ['foo', 'bar', 'baz'], [$nodes->get(0)->name(), $nodes->get(1)->name(), $nodes->get(2)->name()] ); // sort previous values $nodes->setOrder(['baz', '', '0', 'foo', '', 'bar', 'baz']); $this->assertEquals(['baz', 'foo', 'bar'], $nodes->getOrder()); $this->assertEquals( ['baz', 'foo', 'bar'], [$nodes->get(0)->name(), $nodes->get(1)->name(), $nodes->get(2)->name()] ); // add other baz (inserted at the bottom) $nodes->add(new Node('baz', ['id' => 'second'])); $this->assertEquals( ['baz', 'baz', 'foo'], [$nodes->get(0)->name(), $nodes->get(1)->name(), $nodes->get(2)->name()] ); $this->assertEquals('second', $nodes->get(1)['id']); // add other not listed $notListed = new Node('yyy'); $nodes->add($notListed); $this->assertSame($notListed, $nodes->get(4)); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Nodes/XmlNodeUtilsTest.php
tests/CfdiUtilsTests/Nodes/XmlNodeUtilsTest.php
<?php namespace CfdiUtilsTests\Nodes; use CfdiUtils\Nodes\Node; use CfdiUtils\Nodes\XmlNodeUtils; use CfdiUtils\Utils\Xml; use CfdiUtilsTests\TestCase; final class XmlNodeUtilsTest extends TestCase { public function providerToNodeFromNode(): array { return [ 'simple-xml' => [$this->utilAsset('nodes/sample.xml')], 'with-texts-xml' => [$this->utilAsset('nodes/sample-with-texts.xml')], 'cfdi' => [$this->utilAsset('cfdi33-valid.xml')], ]; } public function testNodeToXmlStringXmlHeader(): void { $node = new Node('book', [], [ new Node('chapter', ['toc' => '1']), new Node('chapter', ['toc' => '2']), ]); $xmlString = XmlNodeUtils::nodeToXmlString($node, true); $this->assertStringStartsWith('<?xml version="1.0" encoding="UTF-8"?>', $xmlString); $xmlString = XmlNodeUtils::nodeToXmlString($node, false); $this->assertStringStartsWith('<book>', $xmlString); } /** * @dataProvider providerToNodeFromNode */ public function testExportFromFileAndExportAgain(string $filename): void { $source = strval(file_get_contents($filename)); $document = Xml::newDocumentContent($source); // create node from element $node = XmlNodeUtils::nodeFromXmlElement(Xml::documentElement($document)); // create element from node $element = XmlNodeUtils::nodeToXmlElement($node); $simpleXml = XmlNodeUtils::nodeToSimpleXmlElement($node); $xmlString = XmlNodeUtils::nodeToXmlString($node); // compare versus source $this->assertXmlStringEqualsXmlString($source, $element->ownerDocument->saveXML($element)); $this->assertXmlStringEqualsXmlString($source, (string) $simpleXml->asXML()); $this->assertXmlStringEqualsXmlString($source, $xmlString); } public function testImportFromSimpleXmlElement(): void { $xmlString = '<root id="1"><child id="2"></child></root>'; $simpleXml = new \SimpleXMLElement($xmlString); $node = XmlNodeUtils::nodeFromSimpleXmlElement($simpleXml); $this->assertCount(1, $node); $this->assertSame('1', $node['id']); $child = $node->children()->firstNodeWithName('child'); if (null === $child) { $this->fail('firstNodeWithName did not return a Node'); } else { $this->assertSame('2', $child['id']); $this->assertCount(0, $child); } } public function testImportXmlWithNamespaceWithoutPrefix(): void { $file = $this->utilAsset('xml-with-namespace-definitions-at-child-level.xml'); $node = XmlNodeUtils::nodeFromXmlString(file_get_contents($file) ?: ''); $inspected = $node->searchNode('base:Third', 'innerNS'); if (null === $inspected) { $this->fail('The specimen does not have the required test case'); } $this->assertSame('http://external.com/inner', $inspected['xmlns']); } public function testXmlWithValueWithSpecialChars(): void { $expectedValue = 'ampersand: &'; $content = '<root>ampersand: &amp;</root>'; $node = XmlNodeUtils::nodeFromXmlString($content); $this->assertSame($expectedValue, $node->value()); $this->assertSame($content, XmlNodeUtils::nodeToXmlString($node)); } public function testXmlWithValueWithInnerComment(): void { $expectedValue = 'ampersand: &'; $content = '<root>ampersand: <!-- comment -->&amp;</root>'; $expectedContent = '<root>ampersand: &amp;</root>'; $node = XmlNodeUtils::nodeFromXmlString($content); $this->assertSame($expectedValue, $node->value()); $this->assertSame($expectedContent, XmlNodeUtils::nodeToXmlString($node)); } public function testXmlWithValueWithInnerWhiteSpace(): void { $expectedValue = "\n\nfirst line\n\tsecond line\n\t third line \t\nfourth line\n\n"; $content = "<root>$expectedValue</root>"; $node = XmlNodeUtils::nodeFromXmlString($content); $this->assertSame($expectedValue, $node->value()); $this->assertSame($content, XmlNodeUtils::nodeToXmlString($node)); } public function testXmlWithValueWithInnerElement(): void { $expectedValue = 'ampersand: &'; $content = '<root>ampersand: <inner/>&amp;</root>'; $expectedContent = '<root><inner/>ampersand: &amp;</root>'; $node = XmlNodeUtils::nodeFromXmlString($content); $this->assertSame($expectedValue, $node->value()); $this->assertSame($expectedContent, XmlNodeUtils::nodeToXmlString($node)); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Nodes/AttributesTest.php
tests/CfdiUtilsTests/Nodes/AttributesTest.php
<?php namespace CfdiUtilsTests\Nodes; use CfdiUtils\Nodes\Attributes; use CfdiUtilsTests\TestCase; final class AttributesTest extends TestCase { public function testConstructWithoutArguments(): void { $attributes = new Attributes(); $this->assertCount(0, $attributes); } public function testConstructWithMembers(): void { $data = [ 'id' => 'sample', 'foo' => 'bar', ]; $attributes = new Attributes($data); $this->assertCount(2, $attributes); foreach ($data as $key => $value) { $this->assertTrue($attributes->exists($key)); $this->assertSame($value, $attributes->get($key)); } } public function providerSetMethodWithInvalidName(): array { return [ 'empty' => [''], 'white space' => [' '], ]; } /** * @dataProvider providerSetMethodWithInvalidName */ public function testSetMethodWithInvalidName(string $name): void { $attributes = new Attributes(); $this->expectException(\UnexpectedValueException::class); $attributes->set($name, ''); } public function testSetMethod(): void { $attributes = new Attributes(); // first $attributes->set('foo', 'bar'); $this->assertCount(1, $attributes); $this->assertSame('bar', $attributes->get('foo')); // second $attributes->set('lorem', 'ipsum'); $this->assertCount(2, $attributes); $this->assertSame('ipsum', $attributes->get('lorem')); // override $attributes->set('foo', 'BAR'); $this->assertCount(2, $attributes); $this->assertSame('BAR', $attributes->get('foo')); } public function providerSetWithInvalidNames(): array { return [ 'empty' => [''], 'white space' => [' '], 'digit' => ['0'], 'digit hyphen text' => ['0-foo'], 'hyphen' => ['-'], 'hyphen text' => ['-x'], 'inner space' => ['foo bar'], ]; } /** * @dataProvider providerSetWithInvalidNames */ public function testSetWithInvalidNames(string $name): void { $attributes = new Attributes(); $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage('invalid xml name'); $attributes->set($name, ''); } public function testGetMethodOnNonExistent(): void { $attributes = new Attributes(); $this->assertSame('', $attributes->get('foo')); } public function testRemove(): void { $attributes = new Attributes(); $attributes->set('foo', 'bar'); $attributes->remove('bar'); $this->assertCount(1, $attributes); $attributes->remove('foo'); $this->assertCount(0, $attributes); } public function testArrayAccess(): void { $attributes = new Attributes(); $attributes['id'] = 'sample'; $attributes['foo'] = 'foo foo foo'; $attributes['foo'] = 'bar'; // override $attributes['empty'] = ''; $this->assertCount(3, $attributes); // existent $this->assertTrue(isset($attributes['empty'])); $this->assertTrue(isset($attributes['id'])); $this->assertSame('sample', $attributes['id']); $this->assertSame('bar', $attributes['foo']); // non existent $this->assertFalse(isset($attributes['non-existent'])); $this->assertSame('', $attributes['non-existent']); // remove and check unset($attributes['foo']); $this->assertSame('', $attributes['foo']); } public function testIterator(): void { $data = [ 'foo' => 'bar', 'lorem' => 'ipsum', ]; $created = []; $attributes = new Attributes($data); foreach ($attributes as $key => $value) { $created[$key] = $value; } $this->assertEquals($data, $created); } public function testSetToNullPerformRemove(): void { $attributes = new Attributes([ 'foo' => 'bar', ]); $this->assertTrue($attributes->exists('foo')); $attributes['foo'] = null; $this->assertFalse($attributes->exists('foo')); } public function testImportWithNullPerformRemove(): void { $attributes = new Attributes([ 'set' => '1', 'importArray' => '1', 'offsetSet' => '1', 'constructor' => null, ]); $this->assertFalse($attributes->exists('constructor')); $this->assertCount(3, $attributes); $attributes->set('set', null); $this->assertFalse($attributes->exists('set')); $this->assertCount(2, $attributes); $attributes->importArray(['importArray' => null]); $this->assertFalse($attributes->exists('importArray')); $this->assertCount(1, $attributes); $attributes['offsetSet'] = null; $this->assertFalse($attributes->exists('offsetSet')); $this->assertCount(0, $attributes); } public function testImportWithInvalidValue(): void { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('Cannot convert value of attribute foo to string'); new Attributes([ 'foo' => [], ]); } public function testSetWithObjectToString(): void { $expectedValue = 'foo'; $toStringObject = new class ('foo') { public function __construct(private string $value) { } public function __toString(): string { return $this->value; } }; $attributes = new Attributes(['constructor' => $toStringObject]); $attributes['offsetSet'] = $toStringObject; $attributes->set('set', $toStringObject); $attributes->importArray(['importArray' => $toStringObject]); $this->assertEquals($expectedValue, $attributes->get('constructor')); $this->assertEquals($expectedValue, $attributes->get('offsetSet')); $this->assertEquals($expectedValue, $attributes->get('set')); $this->assertEquals($expectedValue, $attributes->get('importArray')); } public function testExportArray(): void { $attributes = new Attributes(); $attributes->set('foo', 'bar'); $this->assertEquals(['foo' => 'bar'], $attributes->exportArray()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Nodes/NodeNsDefinitionsMoverTest.php
tests/CfdiUtilsTests/Nodes/NodeNsDefinitionsMoverTest.php
<?php namespace CfdiUtilsTests\Nodes; use CfdiUtils\Nodes\NodeNsDefinitionsMover; use CfdiUtils\Nodes\XmlNodeUtils; use CfdiUtilsTests\TestCase; final class NodeNsDefinitionsMoverTest extends TestCase { public function testMoveDefinitionsWithFilter(): void { $inputFile = $this->utilAsset('xml-with-namespace-definitions-at-child-level.xml'); $input = XmlNodeUtils::nodeFromXmlString(file_get_contents($inputFile) ?: ''); $processor = new NodeNsDefinitionsMover(); // only process tempuri namespaces $processor->setNamespaceFilter( fn (string $namespace): bool => 'http://www.tempuri.org/' === strval(substr($namespace, 0, 23)) ); $processor->process($input); $expectedFile = $this->utilAsset('xml-with-namespace-definitions-at-root-level-filtered.xml'); $this->assertXmlStringEqualsXmlFile($expectedFile, XmlNodeUtils::nodeToXmlString($input)); } public function testMoveDefinitionsWithoutFilter(): void { $inputFile = $this->utilAsset('xml-with-namespace-definitions-at-child-level.xml'); $input = XmlNodeUtils::nodeFromXmlString(file_get_contents($inputFile) ?: ''); $processor = new NodeNsDefinitionsMover(); $processor->process($input); $expectedFile = $this->utilAsset('xml-with-namespace-definitions-at-root-level-all.xml'); $this->assertXmlStringEqualsXmlFile($expectedFile, XmlNodeUtils::nodeToXmlString($input)); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Nodes/NodeTest.php
tests/CfdiUtilsTests/Nodes/NodeTest.php
<?php namespace CfdiUtilsTests\Nodes; use CfdiUtils\Nodes\Node; use CfdiUtilsTests\TestCase; final class NodeTest extends TestCase { public function testConstructWithoutArguments(): void { $node = new Node('name'); $this->assertSame('name', $node->name()); $this->assertCount(0, $node->attributes()); $this->assertCount(0, $node->children()); $this->assertSame('', $node->value()); } public function testConstructWithArguments(): void { $dummyNode = new Node('dummy'); $attributes = ['foo' => 'bar']; $children = [$dummyNode]; $value = 'xee'; $node = new Node('name', $attributes, $children, $value); $this->assertSame('bar', $node->attributes()->get('foo')); $this->assertSame($dummyNode, $node->children()->firstNodeWithName('dummy')); $this->assertSame($value, $node->value()); } public function testConstructWithEmptyName(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage('invalid xml name'); new Node(''); } public function testConstructWithUntrimmedEmptyName(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage('invalid xml name'); new Node("\n \t \n"); } public function testConstructWithUntrimmedName(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage('invalid xml name'); new Node(' x '); } public function testSearchAttribute(): void { $node = new Node('root', ['level' => '1'], [ new Node('child', ['level' => '2'], [ new Node('grandchild', ['level' => '3.1']), new Node('grandchild', ['level' => '3.2']), ]), ]); $this->assertSame('1', $node->searchAttribute('level')); $this->assertSame('2', $node->searchAttribute('child', 'level')); $this->assertSame('3.1', $node->searchAttribute('child', 'grandchild', 'level')); $this->assertSame('', $node->searchAttribute('not-found-child', 'child', 'grandchild', 'level')); $this->assertSame('', $node->searchAttribute('not-found-attribute')); } public function testSearchNode(): void { $grandChildOne = new Node('grandchild', ['level' => '3.1']); $grandChildTwo = new Node('grandchild', ['level' => '3.2']); $child = new Node('child', ['level' => '2'], [$grandChildOne, $grandChildTwo]); $root = new Node('root', ['level' => '1'], [$child]); $this->assertSame($root, $root->searchNode()); $this->assertSame($child, $root->searchNode('child')); $this->assertSame($grandChildOne, $root->searchNode('child', 'grandchild')); $this->assertNull($root->searchNode('child', 'grandchild', 'not-found')); $this->assertNull($root->searchNode('not-found', 'child', 'grandchild')); $this->assertNull($root->searchNode('not-found')); } public function testSearchNodes(): void { $grandChildOne = new Node('grandchild', ['level' => '3.1']); $grandChildTwo = new Node('grandchild', ['level' => '3.2']); $child = new Node('child', ['level' => '2'], [$grandChildOne, $grandChildTwo]); $root = new Node('root', ['level' => '1'], [$child]); $nodesChild = $root->searchNodes('child'); $this->assertCount(1, $nodesChild); $this->assertSame($child, $nodesChild->first()); $nodesGrandChild = $root->searchNodes('child', 'grandchild'); $this->assertCount(2, $nodesGrandChild); $this->assertSame($grandChildOne, $nodesGrandChild->get(0)); $this->assertSame($grandChildTwo, $nodesGrandChild->get(1)); $this->assertCount(0, $root->searchNodes('child', 'grandchild', 'not-found')); $this->assertCount(0, $root->searchNodes('not-found', 'child', 'grandchild')); $this->assertCount(0, $root->searchNodes('not-found')); } public function testArrayAccessToAttributes(): void { $node = new Node('x'); $node['id'] = 'form'; $this->assertTrue(isset($node['id'])); $this->assertSame('form', $node['id']); $node['id'] = 'the-form'; $this->assertSame('the-form', $node['id']); unset($node['id']); $this->assertFalse(isset($node['id'])); $this->assertSame('', $node['id']); } public function testValueProperty(): void { $node = new Node('x'); $node->setValue('first'); $this->assertSame('first', $node->value()); $node->setValue('second'); $this->assertSame('second', $node->value()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Nodes/NodesSorterTest.php
tests/CfdiUtilsTests/Nodes/NodesSorterTest.php
<?php namespace CfdiUtilsTests\Nodes; use CfdiUtils\Nodes\Node; use CfdiUtils\Nodes\NodesSorter; use PHPUnit\Framework\TestCase; final class NodesSorterTest extends TestCase { public function testConstructWithNames(): void { $values = ['foo', 'bar', 'baz']; $sorter = new NodesSorter($values); $this->assertSame($values, $sorter->getOrder()); } public function testConstructWithoutNames(): void { $sorter = new NodesSorter(); $this->assertSame([], $sorter->getOrder()); } public function testParseNames(): void { $sorter = new NodesSorter(); // all invalid values $this->assertSame([], $sorter->parseNames([null, new \stdClass(), 0, false, ''])); // all valid values $this->assertSame(['foo', 'bar'], $sorter->parseNames(['foo', 'bar'])); // suplicated values $this->assertSame(['foo', 'bar', 'baz'], $sorter->parseNames(['foo', 'bar', 'bar', 'foo', 'baz'])); // mixed values $this->assertSame(['foo', 'bar'], $sorter->parseNames(['', 'foo', '', 'bar', '', 'foo'])); } public function testSetGetOrder(): void { $sorter = new NodesSorter(['foo', 'bar']); $this->assertSame(['foo', 'bar'], $sorter->getOrder()); // it change $this->assertTrue($sorter->setOrder(['bar', 'foo'])); $this->assertSame(['bar', 'foo'], $sorter->getOrder()); // it did not change $this->assertFalse($sorter->setOrder(['bar', 'foo'])); $this->assertSame(['bar', 'foo'], $sorter->getOrder()); } public function testOrder(): void { $foo1 = new Node('foo'); $foo2 = new Node('foo'); $bar = new Node('bar'); $baz = new Node('baz'); $yyy = new Node('yyy'); $order = ['baz', 'bar', 'foo']; $unsorted = [$yyy, $foo1, $foo2, $bar, $baz]; $expected = [$baz, $bar, $foo1, $foo2, $yyy]; $sorter = new NodesSorter($order); $sorted = $sorter->sort($unsorted); $this->assertSame($expected, $sorted); } public function testOrderPreservePosition(): void { $list = []; for ($i = 0; $i < 1000; $i++) { $list[] = new Node('foo'); } $sorter = new NodesSorter(['foo']); $this->assertSame($list, $sorter->sort($list)); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/PemPrivateKey/PemPrivateKeyTest.php
tests/CfdiUtilsTests/PemPrivateKey/PemPrivateKeyTest.php
<?php namespace CfdiUtilsTests\PemPrivateKey; use CfdiUtils\Certificado\Certificado; use CfdiUtils\PemPrivateKey\PemPrivateKey; use CfdiUtilsTests\TestCase; final class PemPrivateKeyTest extends TestCase { public function providerConstructWithBadArgument(): array { return [ 'empty' => [''], 'random content' => ['foo bar'], 'file://' => ['file://'], 'file without prefix' => [__FILE__], 'non-existent-file' => ['file://' . __DIR__ . '/non-existent-file'], 'existent but is a directory' => ['file://' . __DIR__], 'existent but invalid file' => ['file://' . __FILE__], 'cer file' => ['file://' . static::utilAsset('certs/EKU9003173C9.cer')], 'key not pem file' => ['file://' . static::utilAsset('certs/EKU9003173C9.key')], 'no footer' => ['-----BEGIN PRIVATE KEY-----XXXXX'], 'hidden url' => ['file://https://cdn.kernel.org/pub/linux/kernel/v4.x/linux-4.13.9.tar.xz'], ]; } /** * @dataProvider providerConstructWithBadArgument */ public function testConstructWithBadArgument(string $key): void { $this->expectException(\UnexpectedValueException::class); new PemPrivateKey($key); } public function testConstructWithKeyFile(): void { $keyfile = $this->utilAsset('certs/EKU9003173C9.key.pem'); $privateKey = new PemPrivateKey('file://' . $keyfile); $this->assertInstanceOf(PemPrivateKey::class, $privateKey); } public function testConstructWithKeyContents(): void { $keyfile = $this->utilAsset('certs/EKU9003173C9.key.pem'); $privateKey = new PemPrivateKey(strval(file_get_contents($keyfile))); $this->assertInstanceOf(PemPrivateKey::class, $privateKey); } public function testOpenAndClose(): void { $passPhrase = ''; $keyfile = $this->utilAsset('certs/EKU9003173C9.key.pem'); $privateKey = new PemPrivateKey(strval(file_get_contents($keyfile))); $this->assertFalse($privateKey->isOpen()); $this->assertTrue($privateKey->open($passPhrase)); $this->assertTrue($privateKey->isOpen()); $privateKey->close(); $this->assertFalse($privateKey->isOpen()); } public function testOpenWithBadKey(): void { $keyContents = "-----BEGIN PRIVATE KEY-----\nXXXXX\n-----END PRIVATE KEY-----"; $privateKey = new PemPrivateKey($keyContents); $this->assertFalse($privateKey->open('')); } public function testOpenWithIncorrectPassPhrase(): void { $passPhrase = 'dummy password'; $keyfile = $this->utilAsset('certs/EKU9003173C9_password.key.pem'); $privateKey = new PemPrivateKey(strval(file_get_contents($keyfile))); $this->assertFalse($privateKey->open($passPhrase)); $this->assertFalse($privateKey->isOpen()); } public function testOpenWithCorrectPassPhrase(): void { $passPhrase = '12345678a'; $keyfile = $this->utilAsset('certs/EKU9003173C9_password.key.pem'); $privateKey = new PemPrivateKey(strval(file_get_contents($keyfile))); $this->assertTrue($privateKey->open($passPhrase)); $this->assertTrue($privateKey->isOpen()); } public function testCloneOpenKey(): void { $keyfile = $this->utilAsset('certs/EKU9003173C9.key.pem'); $privateKey = new PemPrivateKey(strval(file_get_contents($keyfile))); $this->assertTrue($privateKey->open('')); $cloned = clone $privateKey; $this->assertFalse($cloned->isOpen()); $this->assertTrue($cloned->open('')); } public function testSerializeOpenKey(): void { $keyfile = $this->utilAsset('certs/EKU9003173C9.key.pem'); $privateKey = new PemPrivateKey(strval(file_get_contents($keyfile))); $this->assertTrue($privateKey->open('')); /** @var PemPrivateKey $serialized */ $serialized = unserialize(serialize($privateKey)); $this->assertFalse($serialized->isOpen()); $this->assertTrue($serialized->open('')); } public function testSignWithClosedKey(): void { $keyfile = $this->utilAsset('certs/EKU9003173C9.key.pem'); $privateKey = new PemPrivateKey(strval(file_get_contents($keyfile))); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('The private key is not open'); $privateKey->sign(''); } public function testSign(): void { // this signature was createrd using the following command: // echo -n lorem ipsum | openssl dgst -sha256 -sign EKU9003173C9.key.pem -out - | base64 -w 80 $keyfile = $this->utilAsset('certs/EKU9003173C9.key.pem'); $privateKey = new PemPrivateKey(strval(file_get_contents($keyfile))); $privateKey->open(''); $content = 'lorem ipsum'; $expectedSign = <<< EOC Dhtz+Ou926kNk0B9iv7MF+8ts2yfeuIJhB7/sfuUqCwbzWnpX9/CxWIWMXZOiF/jBU8tREoTh+claQKD wjkyjuaZX47hN7P9fklfxA5Sq258frhm0KQ7kPi9FTFjmTUhcHoc92+z6jfGVfNe8R7OFMnxzWKp03Gy IC1ewW0HOpmba445T2rSEyjUKZaClfdxbESkUFCeJbXCLsuE9LxoPiMp7zY+haV254fq2psIjTvt1xd8 Carv0WG58VC4IPTphedHj2SPb3YbikgxJZnCVu6vzf3MTrydZe65GAxoqaLecVzriQbbV90WMx/lkAT4 /wCuxjvmHDoghs4JtQdaCA== EOC; $sign = chunk_split(base64_encode($privateKey->sign($content, OPENSSL_ALGO_SHA256)), 80, "\n"); $this->assertEquals($expectedSign, rtrim($sign)); } public function testBelongsToWithClosedKey(): void { $keyfile = $this->utilAsset('certs/EKU9003173C9.key.pem'); $privateKey = new PemPrivateKey(strval(file_get_contents($keyfile))); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('The private key is not open'); $privateKey->belongsTo(''); } public function testBelongsTo(): void { $cerfile = $this->utilAsset('certs/EKU9003173C9.cer'); $keyfile = $this->utilAsset('certs/EKU9003173C9.key.pem'); $privateKey = new PemPrivateKey(strval(file_get_contents($keyfile))); $privateKey->open(''); $certificado = new Certificado($cerfile); $this->assertTrue($privateKey->belongsTo($certificado->getPemContents())); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/CadenaOrigen/DOMBuilderTest.php
tests/CfdiUtilsTests/CadenaOrigen/DOMBuilderTest.php
<?php namespace CfdiUtilsTests\CadenaOrigen; use CfdiUtils\CadenaOrigen\DOMBuilder; use CfdiUtils\CadenaOrigen\XsltBuilderInterface; final class DOMBuilderTest extends GenericBuilderTestCase { protected function createBuilder(): XsltBuilderInterface { return new DOMBuilder(); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/CadenaOrigen/XsltBuilderPropertyTest.php
tests/CfdiUtilsTests/CadenaOrigen/XsltBuilderPropertyTest.php
<?php namespace CfdiUtilsTests\CadenaOrigen; use CfdiUtils\CadenaOrigen\DOMBuilder; use CfdiUtils\CadenaOrigen\XsltBuilderPropertyInterface; use CfdiUtils\CadenaOrigen\XsltBuilderPropertyTrait; use CfdiUtilsTests\TestCase; final class XsltBuilderPropertyTest extends TestCase { public function testXsltBuilderPropertyWithoutSet(): void { $implementation = $this->createImplementation(); $this->assertFalse($implementation->hasXsltBuilder()); $this->expectException(\LogicException::class); $this->expectExceptionMessage('current xsltBuilder'); $implementation->getXsltBuilder(); } public function testXsltBuilderProperty(): void { $builder = new DOMBuilder(); $implementation = $this->createImplementation(); $implementation->setXsltBuilder($builder); $this->assertTrue($implementation->hasXsltBuilder()); $this->assertSame($builder, $implementation->getXsltBuilder()); $implementation->setXsltBuilder(null); $this->assertFalse($implementation->hasXsltBuilder()); } protected function createImplementation(): XsltBuilderPropertyInterface { return new class () implements XsltBuilderPropertyInterface { use XsltBuilderPropertyTrait; }; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/CadenaOrigen/GenkgoXslBuilderTest.php
tests/CfdiUtilsTests/CadenaOrigen/GenkgoXslBuilderTest.php
<?php namespace CfdiUtilsTests\CadenaOrigen; use CfdiUtils\CadenaOrigen\GenkgoXslBuilder; use CfdiUtils\CadenaOrigen\XsltBuilderInterface; use Genkgo\Xsl\XsltProcessor; final class GenkgoXslBuilderTest extends GenericBuilderTestCase { protected function setUp(): void { parent::setUp(); // IGNORE DEPRECATION ERRORS SINCE PHP 8.1 if (PHP_VERSION_ID >= 80100) { set_error_handler(fn (): bool => true, E_DEPRECATED); } if (! class_exists(XsltProcessor::class)) { $this->markTestSkipped('Genkgo/Xsl is not installed'); } } protected function tearDown(): void { if (PHP_VERSION_ID >= 80100) { restore_error_handler(); } parent::tearDown(); } protected function createBuilder(): XsltBuilderInterface { return new GenkgoXslBuilder(); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/CadenaOrigen/SaxonbCliBuilderTest.php
tests/CfdiUtilsTests/CadenaOrigen/SaxonbCliBuilderTest.php
<?php namespace CfdiUtilsTests\CadenaOrigen; use CfdiUtils\CadenaOrigen\SaxonbCliBuilder; use CfdiUtils\CadenaOrigen\XsltBuilderInterface; use CfdiUtils\CadenaOrigen\XsltBuildException; final class SaxonbCliBuilderTest extends GenericBuilderTestCase { protected function createBuilder(): XsltBuilderInterface { $executable = (string) getenv('saxonb-path'); if ('' === $executable) { $executable = '/usr/bin/saxonb-xslt'; } if (! is_executable($executable)) { $this->markTestSkipped("Cannot test since saxonb ($executable) is missing"); } return new SaxonbCliBuilder($executable); } public function testConstructorWithEmptyExecutable(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage('empty'); new SaxonbCliBuilder(''); } public function testWithNonExistentExecutable(): void { $builder = new SaxonbCliBuilder('/foo/bar'); $this->expectException(XsltBuildException::class); $this->expectExceptionMessage('does not exists'); $builder->build('x', 'y'); } public function testWithDirectory(): void { $builder = new SaxonbCliBuilder(__DIR__); $this->expectException(XsltBuildException::class); $this->expectExceptionMessage('directory'); $builder->build('x', 'y'); } public function testWithFile(): void { $builder = new SaxonbCliBuilder(__FILE__); $this->expectException(XsltBuildException::class); // this file could have executable permissions (because users!)... then change message if (is_executable(__FILE__)) { $this->expectExceptionMessage('Transformation error'); } else { $this->expectExceptionMessage('executable'); } $builder->build('x', 'y'); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/CadenaOrigen/CfdiDefaultLocationsTest.php
tests/CfdiUtilsTests/CadenaOrigen/CfdiDefaultLocationsTest.php
<?php namespace CfdiUtilsTests\CadenaOrigen; use CfdiUtils\CadenaOrigen\CfdiDefaultLocations; use CfdiUtilsTests\TestCase; final class CfdiDefaultLocationsTest extends TestCase { public function providerLocationByVersion(): array { return [ '3.2' => ['3.2', CfdiDefaultLocations::XSLT_32], '3.3' => ['3.3', CfdiDefaultLocations::XSLT_33], '4.0' => ['4.0', CfdiDefaultLocations::XSLT_40], ]; } /** @dataProvider providerLocationByVersion */ public function testLocationByVersion(string $version, string $location): void { $this->assertSame($location, CfdiDefaultLocations::location($version)); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/CadenaOrigen/GenericBuilderTestCase.php
tests/CfdiUtilsTests/CadenaOrigen/GenericBuilderTestCase.php
<?php namespace CfdiUtilsTests\CadenaOrigen; use CfdiUtils\CadenaOrigen\CfdiDefaultLocations; use CfdiUtils\CadenaOrigen\XsltBuilderInterface; use CfdiUtils\CadenaOrigen\XsltBuildException; use CfdiUtilsTests\TestCase; abstract class GenericBuilderTestCase extends TestCase { abstract protected function createBuilder(): XsltBuilderInterface; /** * The files cfdi33-real-cadenaorigen.txt was created using the command line util saxonb-xslt * available in debian in the package libsaxonb-java. * * saxonb-xslt -s:cfdi33-real.xml \ * -xsl:http://www.sat.gob.mx/sitio_internet/cfd/3/cadenaoriginal_3_3/cadenaoriginal_3_3.xslt \ * -warnings:silent > cfdi33-real-cadenaorigen.txt */ public function providerCfdiToCadenaOrigen(): array { return [ ['cfdi32-real.xml', 'cfdi32-real-cadenaorigen.txt', CfdiDefaultLocations::XSLT_32], ['cfdi33-real.xml', 'cfdi33-real-cadenaorigen.txt', CfdiDefaultLocations::XSLT_33], ]; } /** * @dataProvider providerCfdiToCadenaOrigen */ public function testCfdiToCadenaOrigen( string $xmlLocation, string $expectedTransformation, string $xsltLocation, ): void { $xsltLocation = $this->downloadResourceIfNotExists($xsltLocation); $xmlLocation = $this->utilAsset($xmlLocation); $expectedTransformation = $this->utilAsset($expectedTransformation); $builder = $this->createBuilder(); $cadenaOrigen = $builder->build(strval(file_get_contents($xmlLocation)), $xsltLocation); $this->assertSame( rtrim(strval(file_get_contents($expectedTransformation))), $cadenaOrigen, 'Xslt transformation returns an unexpected value' ); } public function testBuildWithEmptyXml(): void { $builder = $this->createBuilder(); $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage('empty'); $builder->build('', ''); } public function testBuildWithInvalidXml(): void { $builder = $this->createBuilder(); $this->expectException(XsltBuildException::class); $builder->build('not an xml', 'x'); } public function testBuildWithUndefinedXsltLocation(): void { $builder = $this->createBuilder(); $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage('Xslt location was not set'); $builder->build('<cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" version="3.2"' . '/>', ''); } public function testBuildWithInvalidXsltLocation(): void { $builder = $this->createBuilder(); $this->expectException(XsltBuildException::class); $builder->build('<cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" version="3.2"' . '/>', '/foo/bar'); } public function testBuildWithNonXsltContent(): void { $builder = $this->createBuilder(); $nonAnXsltFile = $this->utilAsset('simple-xml.xml'); $this->expectException(XsltBuildException::class); $builder->build( '<cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" version="3.2"' . '/>', $nonAnXsltFile ); } public function testBuildWithEmptyXslt(): void { $builder = $this->createBuilder(); $emptyXsltFile = $this->utilAsset('empty.xslt'); $this->expectException(XsltBuildException::class); $builder->build( '<cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" version="3.2"' . '/>', $emptyXsltFile ); } /** * This test require internet connection, not really required, run only if found errors * on method build using xslt files from internet */ public function skippedTestBuildWithRemoteResource(): void { $fileCfdi = $this->utilAsset('cfdi32-real.xml'); $fileExpectedCadenaOrigen = $this->utilAsset('cfdi32-real-cadenaorigen.txt'); $builder = $this->createBuilder(); $cadenaOrigen = $builder->build(strval(file_get_contents($fileCfdi)), CfdiDefaultLocations::XSLT_32); $this->assertStringEqualsFile($fileExpectedCadenaOrigen, $cadenaOrigen . PHP_EOL); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/OpenSSL/OpenSSLTest.php
tests/CfdiUtilsTests/OpenSSL/OpenSSLTest.php
<?php namespace CfdiUtilsTests\OpenSSL; use CfdiUtils\OpenSSL\OpenSSL; use CfdiUtils\OpenSSL\OpenSSLCallerException; use CfdiUtils\PemPrivateKey\PemPrivateKey; use CfdiUtilsTests\TestCase; final class OpenSSLTest extends TestCase { public function testCreateInstanceWithoutAnyArguments(): void { $openssl = new OpenSSL(); $this->assertSame('openssl', $openssl->getOpenSSLCommand()); } public function testCreateInstanceWithCaller(): void { $openssl = new OpenSSL('my-openssl-executable'); $this->assertSame('my-openssl-executable', $openssl->getOpenSSLCommand()); } public function testReadPemFile(): void { $pemcer = $this->utilAsset('certs/EKU9003173C9.cer.pem'); $openssl = new OpenSSL(); $pem = $openssl->readPemFile($pemcer); $this->assertTrue($pem->hasPublicKey()); $this->assertTrue($pem->hasCertificate()); $this->assertFalse($pem->hasPrivateKey()); } public function testCertificateConvertContentsDerToPem(): void { $openssl = new OpenSSL(); $cerFile = $this->utilAsset('certs/EKU9003173C9.cer'); $cerContents = strval(file_get_contents($cerFile)); $pemFile = $this->utilAsset('certs/EKU9003173C9.cer.pem'); $expected = $openssl->readPemFile($pemFile)->certificate(); $converted = $openssl->derCerConvertPhp($cerContents); $this->assertSame($expected, $converted); } public function testCertificateConvertFilesDerToPem(): void { $openssl = new OpenSSL(); $keyFile = $this->utilAsset('certs/EKU9003173C9.cer'); $cerContents = strval(file_get_contents($keyFile)); $pemFile = $this->utilAsset('certs/EKU9003173C9.cer.pem'); $expected = $openssl->readPemFile($pemFile)->certificate(); $converted = $openssl->derCerConvertInOut($cerContents); $this->assertSame($expected, $converted); } public function testPrivateKeyConvertDerToPem(): void { $openssl = new OpenSSL(); $cerFile = $this->utilAsset('certs/EKU9003173C9.key'); $pemFile = $this->utilAsset('certs/EKU9003173C9.key.pem'); $expected = $openssl->readPemFile($pemFile)->privateKey(); $converted = $openssl->derKeyConvertOut($cerFile, '12345678a'); $this->assertSame($expected, $converted, 'Converted key does not match'); } public function testPrivateKeyConvertDerToPemThrowsExceptionUsingInvalidPassPhrase(): void { $openssl = new OpenSSL(); $cerFile = $this->utilAsset('certs/EKU9003173C9.key'); $this->expectException(OpenSSLCallerException::class); $openssl->derKeyConvertOut($cerFile, 'invalid-passphrase'); } public function providerPrivateKeyProtectPem(): array { return [ 'protect' => ['certs/EKU9003173C9.key.pem', '', 'foo-bar-baz'], 'change' => ['certs/EKU9003173C9_password.key.pem', '12345678a', 'foo-bar-baz'], 'unprotect' => ['certs/EKU9003173C9_password.key.pem', '12345678a', ''], ]; } /** * @dataProvider providerPrivateKeyProtectPem */ public function testPrivateKeyProtectPem(string $pemFile, string $inPassPhrase, string $outPassPhrase): void { $openssl = new OpenSSL(); $pemFile = $this->utilAsset($pemFile); $pemContents = strval(file_get_contents($pemFile)); $converted = $openssl->pemKeyProtectInOut($pemContents, $inPassPhrase, $outPassPhrase); $privateKey = new PemPrivateKey($converted); $this->assertTrue($privateKey->open($outPassPhrase), 'Cannot open the generated private Key'); } /** * @testWith [""] * ["foo-bar-baz"] */ public function testPrivateKeyProtectDer(string $outPassPhrase): void { $derFile = 'certs/EKU9003173C9.key'; $inPassPhrase = '12345678a'; $openssl = new OpenSSL(); $derFile = $this->utilAsset($derFile); $converted = $openssl->derKeyProtectOut($derFile, $inPassPhrase, $outPassPhrase); $privateKey = new PemPrivateKey($converted); $this->assertTrue($privateKey->open($outPassPhrase), 'Cannot open the generated private Key'); } public function testPrivateKeyUnprotectPem(): void { $pemFile = $this->utilAsset('certs/EKU9003173C9_password.key.pem'); $pemContents = strval(file_get_contents($pemFile)); $inPassPhrase = '12345678a'; $openssl = new OpenSSL(); $converted = $openssl->pemKeyUnprotectInOut($pemContents, $inPassPhrase); $privateKey = new PemPrivateKey($converted); $this->assertTrue($privateKey->open(''), 'Cannot open the generated private Key'); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/OpenSSL/OpenSSLProtectedMethodCheckOutputFileTest.php
tests/CfdiUtilsTests/OpenSSL/OpenSSLProtectedMethodCheckOutputFileTest.php
<?php namespace CfdiUtilsTests\OpenSSL; use CfdiUtils\Internals\TemporaryFile; use CfdiUtils\OpenSSL\OpenSSL; use CfdiUtilsTests\TestCase; final class OpenSSLProtectedMethodCheckOutputFileTest extends TestCase { private function openSSL(): object { return new class () extends OpenSSL { public function checkOutputFile(string $path): void { parent::checkOutputFile($path); unset($path); // to avoid useless method overriding detected } }; } public function testValidOutputFileNonExistent(): void { $this->openSSL()->checkOutputFile(__DIR__ . '/non-existent'); $this->assertTrue(true, 'No exception thrown'); /** @phpstan-ignore-line */ } public function testValidOutputFileZeroSize(): void { $tempfile = TemporaryFile::create(); try { $this->openSSL()->checkOutputFile($tempfile); } finally { $tempfile->remove(); } $this->assertTrue(true, 'No exception thrown'); /** @phpstan-ignore-line */ } public function testThrowExceptionUsingEmptyFileName(): void { $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('argument is empty'); $this->openSSL()->checkOutputFile(''); } public function testThrowExceptionUsingNonExistentParentDirectory(): void { $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('not exists'); $this->openSSL()->checkOutputFile(__DIR__ . '/a/b/c'); } public function testThrowExceptionUsingDirectory(): void { $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('is a directory'); $this->openSSL()->checkOutputFile(__DIR__); } public function testThrowExceptionUsingZeroFile(): void { $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('not empty'); $this->openSSL()->checkOutputFile(__FILE__); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/OpenSSL/PemExtractorTest.php
tests/CfdiUtilsTests/OpenSSL/PemExtractorTest.php
<?php namespace CfdiUtilsTests\OpenSSL; use CfdiUtils\OpenSSL\PemExtractor; use CfdiUtilsTests\TestCase; final class PemExtractorTest extends TestCase { public function testExtractorWithEmptyContent(): void { $extractor = new PemExtractor(''); $this->assertSame('', $extractor->getContents()); $this->assertSame('', $extractor->extractCertificate()); $this->assertSame('', $extractor->extractPublicKey()); $this->assertSame('', $extractor->extractCertificate()); } public function providerCrLfAndLf(): array { return [ 'CRLF' => ["\r\n"], 'LF' => ["\n"], ]; } /** * @dataProvider providerCrLfAndLf */ public function testExtractorWithFakeContent(string $eol): void { // section contents must be base64 valid strings $info = str_replace(["\r", "\n"], ['[CR]', '[LF]'], $eol); $content = implode($eol, [ '-----BEGIN OTHER SECTION-----', 'OTHER SECTION', '-----END OTHER SECTION-----', '-----BEGIN CERTIFICATE-----', 'FOO+CERTIFICATE', '-----END CERTIFICATE-----', '-----BEGIN PUBLIC KEY-----', 'FOO+PUBLIC+KEY', '-----END PUBLIC KEY-----', '-----BEGIN PRIVATE KEY-----', 'FOO+PRIVATE+KEY', '-----END PRIVATE KEY-----', ]); $extractor = new PemExtractor($content); $this->assertSame($content, $extractor->getContents()); $this->assertStringContainsString( 'FOO+CERTIFICATE', $extractor->extractCertificate(), "Certificate using EOL $info was not extracted" ); $this->assertStringContainsString( 'FOO+PUBLIC+KEY', $extractor->extractPublicKey(), "Public Key using EOL $info was not extracted" ); $this->assertStringContainsString( 'FOO+PRIVATE+KEY', $extractor->extractPrivateKey(), "Private Key using EOL $info was not extracted" ); } public function testExtractCertificateWithPublicKey(): void { $pemcerpub = $this->utilAsset('certs/EKU9003173C9.cer.pem'); $contents = strval(file_get_contents($pemcerpub)); $extractor = new PemExtractor($contents); $this->assertSame($contents, $extractor->getContents()); $this->assertStringContainsString('PUBLIC KEY', $extractor->extractPublicKey()); $this->assertStringContainsString('CERTIFICATE', $extractor->extractCertificate()); } public function testExtractPrivateKey(): void { $pemkey = $this->utilAsset('certs/EKU9003173C9.key.pem'); $contents = strval(file_get_contents($pemkey)); $extractor = new PemExtractor($contents); $this->assertStringContainsString('PRIVATE KEY', $extractor->extractPrivateKey()); } public function testUsingBinaryFileExtractNothing(): void { $pemkey = $this->utilAsset('certs/EKU9003173C9.key'); $contents = strval(file_get_contents($pemkey)); $extractor = new PemExtractor($contents); $this->assertSame('', $extractor->extractCertificate()); $this->assertSame('', $extractor->extractPublicKey()); $this->assertSame('', $extractor->extractPrivateKey()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/OpenSSL/CallerTest.php
tests/CfdiUtilsTests/OpenSSL/CallerTest.php
<?php namespace CfdiUtilsTests\OpenSSL; use CfdiUtils\OpenSSL\Caller; use CfdiUtils\OpenSSL\OpenSSLCallerException; use CfdiUtils\OpenSSL\OpenSSLException; use CfdiUtilsTests\TestCase; use PHPUnit\Framework\MockObject\MockObject; use Symfony\Component\Process\Process; final class CallerTest extends TestCase { public function testConstructWithoutArguments(): void { $caller = new Caller(); $this->assertSame(Caller::DEFAULT_OPENSSL_EXECUTABLE, $caller->getExecutable()); } public function testConstructWithExecutableName(): void { $caller = new Caller('my-openssl'); $this->assertSame('my-openssl', $caller->getExecutable()); } public function testCallerWithNullCharacterOnTemplate(): void { if (in_array(PHP_OS_FAMILY, ['Windows', 'Unknown'])) { $this->markTestSkipped('Expected exception on non-windows systems'); } $caller = new Caller(); $this->expectException(OpenSSLException::class); $caller->call('?', ["\0"]); } private function createFakeCaller(string $command, int $exitCode, string $output, string $errors): Caller { /** @var MockObject&Process $process */ $process = $this->createMock(Process::class); $process->method('run')->willReturn($exitCode); $process->method('getCommandLine')->willReturn($command); $process->method('getOutput')->willReturn($output); $process->method('getErrorOutput')->willReturn($errors); return new class ($process) extends Caller { public function __construct(private Process $process) { parent::__construct('command'); } // change method visibility public function createProcess(array $command, array $environment): Process { return $this->process; } }; } public function testRunUsingMockedProcessExpectingError(): void { $caller = $this->createFakeCaller('command', 15, 'output', 'errors'); try { $caller->call('foo', []); $this->fail('Test did not throw a OpenSSLCallerException'); } catch (OpenSSLCallerException $exception) { $callResponse = $exception->getCallResponse(); $this->assertSame(15, $callResponse->exitStatus()); $this->assertSame('command', $callResponse->commandLine()); $this->assertSame('output', $callResponse->output()); $this->assertSame('errors', $callResponse->errors()); } } public function testRunUsingMockedProcessExpectingSuccess(): void { $caller = $this->createFakeCaller('openssl', 0, 'OK', ''); $callResponse = $caller->call('foo', []); $this->assertSame(0, $callResponse->exitStatus()); $this->assertSame('openssl', $callResponse->commandLine()); $this->assertSame('OK', $callResponse->output()); $this->assertSame('', $callResponse->errors()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/OpenSSL/OpenSSLProtectedMethodCheckInputFileTest.php
tests/CfdiUtilsTests/OpenSSL/OpenSSLProtectedMethodCheckInputFileTest.php
<?php namespace CfdiUtilsTests\OpenSSL; use CfdiUtils\Internals\TemporaryFile; use CfdiUtils\OpenSSL\OpenSSL; use CfdiUtilsTests\TestCase; final class OpenSSLProtectedMethodCheckInputFileTest extends TestCase { private function openSSL(): object { return new class () extends OpenSSL { public function checkInputFile(string $path): void { parent::checkInputFile($path); unset($path); // to avoid useless method overriding detected } }; } public function testValidInputFile(): void { $this->openSSL()->checkInputFile(__FILE__); $this->assertTrue(true, 'No exception thrown'); /** @phpstan-ignore-line */ } public function testThrowExceptionUsingEmptyFileName(): void { $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('argument is empty'); $this->openSSL()->checkInputFile(''); } public function testThrowExceptionUsingFileNonExistent(): void { $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('does not exists'); $this->openSSL()->checkInputFile(__DIR__ . '/not-found'); } public function testThrowExceptionUsingDirectory(): void { $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('is a directory'); $this->openSSL()->checkInputFile(__DIR__); } public function testThrowExceptionUsingZeroFile(): void { $tempfile = TemporaryFile::create(); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('is empty'); try { $this->openSSL()->checkInputFile($tempfile); } finally { $tempfile->remove(); } } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/OpenSSL/OpenSSLPropertyTest.php
tests/CfdiUtilsTests/OpenSSL/OpenSSLPropertyTest.php
<?php namespace CfdiUtilsTests\OpenSSL; use CfdiUtils\OpenSSL\OpenSSL; use CfdiUtils\OpenSSL\OpenSSLPropertyTrait; use CfdiUtilsTests\TestCase; final class OpenSSLPropertyTest extends TestCase { public function testCorrectImplementer(): void { $object = new class () { use OpenSSLPropertyTrait; public function __construct(?OpenSSL $openSSL = null) { $this->setOpenSSL($openSSL ?: new OpenSSL()); } }; $this->assertInstanceOf(OpenSSL::class, $object->getOpenSSL()); } public function testNotInstantiatedImplementer(): void { $object = new class () { use OpenSSLPropertyTrait; }; $this->expectException(\Error::class); /** * @noinspection PhpExpressionResultUnusedInspection * @phpstan-ignore-next-line */ $object->getOpenSSL(); } public function testWithDefaultSetterVisibility(): void { $object = new class () { use OpenSSLPropertyTrait; }; /** @phpstan-ignore-next-line */ $this->assertFalse(is_callable([$object, 'setOpenSSL']), 'setOpenSSL must not be public accesible'); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Cleaner/CleanerTest.php
tests/CfdiUtilsTests/Cleaner/CleanerTest.php
<?php namespace CfdiUtilsTests\Cleaner; use CfdiUtils\Cleaner\Cleaner; use CfdiUtils\Cleaner\CleanerException; use CfdiUtilsTests\TestCase; final class CleanerTest extends TestCase { public function testConstructorWithEmptyText(): void { $cleaner = new Cleaner(''); $this->expectException(CleanerException::class); $cleaner->load(''); } public function testConstructorWithNonCFDI(): void { $cleaner = new Cleaner(''); $this->expectException(CleanerException::class); $cleaner->load('<node></node>'); } public function testConstructorWithBadVersion(): void { $this->expectException(CleanerException::class); new Cleaner('<?xml version="1.0" encoding="UTF-8"?> <' . 'cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" version="3.15" /> '); } public function testConstructorWithoutInvalidXml(): void { $this->expectException(CleanerException::class); new Cleaner('<' . 'node>'); } public function testConstructorWithoutVersion(): void { $this->expectException(CleanerException::class); $this->expectExceptionMessage('version'); new Cleaner('<?xml version="1.0" encoding="UTF-8"?> <' . 'cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" /> '); } public function testConstructorWithMinimalCompatibilityVersion32(): void { $cleaner = new Cleaner('<?xml version="1.0" encoding="UTF-8"?> <' . 'cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" version="3.2" /> '); $this->assertInstanceOf(Cleaner::class, $cleaner, 'Cleaner created with minimum compatibility'); } public function testConstructorWithMinimalCompatibilityVersion33(): void { $cleaner = new Cleaner('<?xml version="1.0" encoding="UTF-8"?> <' . 'cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" Version="3.3" /> '); $this->assertInstanceOf(Cleaner::class, $cleaner, 'Cleaner created with minimum compatibility'); } public function testConstructorWithMinimalCompatibilityVersion40(): void { $cleaner = new Cleaner('<?xml version="1.0" encoding="UTF-8"?> <' . 'cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/4" Version="4.0" /> '); $this->assertInstanceOf(Cleaner::class, $cleaner, 'Cleaner created with minimum compatibility'); } public function testLoadWithDefaultBeforeLoadCleaner(): void { $withErrors = $this->utilAsset('cleaner/v32-dirty-errors.xml'); $justDirty = $this->utilAsset('cleaner/v32-dirty.xml'); $cleaner = new Cleaner(strval(file_get_contents($withErrors))); $this->assertXmlStringEqualsXmlFile( $justDirty, $cleaner->retrieveXml(), 'Compare that the document was cleaned before load' ); } public function testCleanOnDetail(): void { $basefile = $this->utilAsset('cleaner/v32-dirty.xml'); $step1 = $this->utilAsset('cleaner/v32-no-addenda.xml'); $step2 = $this->utilAsset('cleaner/v32-no-incomplete-schemalocations.xml'); $step3 = $this->utilAsset('cleaner/v32-no-nonsat-nodes.xml'); $step4 = $this->utilAsset('cleaner/v32-no-nonsat-schemalocations.xml'); $step5 = $this->utilAsset('cleaner/v32-no-nonsat-xmlns.xml'); $step6 = $this->utilAsset('cleaner/v32-schemalocations-replacements.xml'); foreach ([$basefile, $step1, $step3, $step2, $step4, $step5, $step6] as $filename) { $this->assertFileExists($basefile, "The file $filename for testing does not exists"); } $cleaner = new Cleaner(strval(file_get_contents($basefile))); $this->assertXmlStringEqualsXmlFile( $basefile, $cleaner->retrieveXml(), 'Compare that the document was loaded without modifications' ); $cleaner->removeAddenda(); $this->assertXmlStringEqualsXmlFile( $step1, $cleaner->retrieveXml(), 'Compare that addenda was removed' ); $cleaner->removeIncompleteSchemaLocations(); $this->assertXmlStringEqualsXmlFile( $step2, $cleaner->retrieveXml(), 'Compare that incomplete schemaLocations were removed' ); $cleaner->removeNonSatNSNodes(); $this->assertXmlStringEqualsXmlFile( $step3, $cleaner->retrieveXml(), 'Compare that non SAT nodes were removed' ); $cleaner->removeNonSatNSschemaLocations(); $this->assertXmlStringEqualsXmlFile( $step4, $cleaner->retrieveXml(), 'Compare that non SAT schemaLocations were removed' ); $cleaner->removeUnusedNamespaces(); $this->assertXmlStringEqualsXmlFile( $step5, $cleaner->retrieveXml(), 'Compare that xmlns definitions were removed' ); $cleaner->fixKnownSchemaLocationsXsdUrls(); $this->assertXmlStringEqualsXmlFile( $step6, $cleaner->retrieveXml(), 'Compare that schemaLocations definitions were changed' ); $this->assertXmlStringEqualsXmlFile( $step6, Cleaner::staticClean(strval(file_get_contents($basefile))), 'Check static method for cleaning is giving the same results as detailed execution' ); } public function testRetrieveDocumentReturnDifferentInstances(): void { $cleaner = new Cleaner('<?xml version="1.0" encoding="UTF-8"?> <' . 'cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" Version="3.3" /> '); $domFirst = $cleaner->retrieveDocument(); $domSecond = $cleaner->retrieveDocument(); $this->assertNotSame($domFirst, $domSecond); $this->assertXmlStringEqualsXmlString($domFirst->saveXML(), $domSecond->saveXML()); } public function testRemoveNonSatNSschemaLocationsWithNotEvenSchemaLocationContents(): void { $xmlContent = '<?xml version="1.0" encoding="UTF-8"?> <' . 'cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" Version="3.3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://example.com/foo http://example.com/foo.xsd http://example.com/bar" /> '; $cleaner = new Cleaner($xmlContent); $this->expectException(CleanerException::class); $this->expectExceptionMessage('must have even number of URIs'); $cleaner->removeNonSatNSschemaLocations(); } public function testRemoveNonSatNSschemaLocationsRemoveEmptySchemaLocation(): void { $xmlContent = '<?xml version="1.0" encoding="UTF-8"?> <' . 'cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" Version="3.3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://example.com/foo http://example.com/foo.xsd" /> '; $xmlExpectedContent = '<?xml version="1.0" encoding="UTF-8"?> <' . 'cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" Version="3.3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" /> '; $cleaner = new Cleaner($xmlContent); $cleaner->removeNonSatNSschemaLocations(); $this->assertXmlStringEqualsXmlString($xmlExpectedContent, $cleaner->retrieveXml()); } public function testCollapseComprobanteComplemento(): void { $source = <<<'EOT' <cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" Version="3.3"> <cfdi:Complemento><a/><b/></cfdi:Complemento> <cfdi:Complemento><c/><d/></cfdi:Complemento> <cfdi:Complemento><cfdi:Complemento info="malformed"/></cfdi:Complemento> <cfdi:Complemento><e/><f/></cfdi:Complemento> </cfdi:Comprobante> EOT; $expected = <<<'EOT' <cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" Version="3.3"> <cfdi:Complemento> <a/><b/> <c/><d/> <cfdi:Complemento info="malformed"/> <e/><f/> </cfdi:Complemento> </cfdi:Comprobante> EOT; $cleaner = new Cleaner($source); $cleaner->collapseComprobanteComplemento(); $this->assertXmlStringEqualsXmlString($expected, $cleaner->retrieveXml()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Cleaner/BeforeLoad/RemoveDuplicatedCfdi3NamespaceTest.php
tests/CfdiUtilsTests/Cleaner/BeforeLoad/RemoveDuplicatedCfdi3NamespaceTest.php
<?php namespace CfdiUtilsTests\Cleaner\BeforeLoad; use CfdiUtils\Cleaner\BeforeLoad\BeforeLoadCleanerInterface; use CfdiUtils\Cleaner\BeforeLoad\RemoveDuplicatedCfdi3Namespace; use CfdiUtilsTests\TestCase; final class RemoveDuplicatedCfdi3NamespaceTest extends TestCase { public function testImplementsBeforeLoadCleanerInterface(): void { $this->assertInstanceOf(BeforeLoadCleanerInterface::class, new RemoveDuplicatedCfdi3Namespace()); } public function testCleanWithValue(): void { $sample = '<cfdi:Comprobante xmlns="http://www.sat.gob.mx/cfd/3"' . ' xmlns:cfdi="http://www.sat.gob.mx/cfd/3"/>'; $expected = '<cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3"/>'; $cleaner = new RemoveDuplicatedCfdi3Namespace(); $this->assertSame($expected, $cleaner->clean($sample)); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Cleaner/BeforeLoad/ChangeXmlnsSchemaLocationTest.php
tests/CfdiUtilsTests/Cleaner/BeforeLoad/ChangeXmlnsSchemaLocationTest.php
<?php namespace CfdiUtilsTests\Cleaner\BeforeLoad; use CfdiUtils\Cleaner\BeforeLoad\BeforeLoadCleanerInterface; use CfdiUtils\Cleaner\BeforeLoad\ChangeXmlnsSchemaLocation; use CfdiUtilsTests\TestCase; final class ChangeXmlnsSchemaLocationTest extends TestCase { public function testImplementsBeforeLoadCleanerInterface(): void { $this->assertInstanceOf(BeforeLoadCleanerInterface::class, new ChangeXmlnsSchemaLocation()); } public function testCleanWithValue(): void { $sample = '<cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3"' . ' xmlns:schemaLocation="http://www.sat.gob.mx/cfd/3 location"/>'; $expected = '<cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3"' . ' xsi:schemaLocation="http://www.sat.gob.mx/cfd/3 location"/>'; $cleaner = new ChangeXmlnsSchemaLocation(); $this->assertSame($expected, $cleaner->clean($sample)); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Cleaner/BeforeLoad/BeforeLoadCleanerTest.php
tests/CfdiUtilsTests/Cleaner/BeforeLoad/BeforeLoadCleanerTest.php
<?php namespace CfdiUtilsTests\Cleaner\BeforeLoad; use CfdiUtils\Cleaner\BeforeLoad\BeforeLoadCleaner; use CfdiUtils\Cleaner\BeforeLoad\BeforeLoadCleanerInterface; use CfdiUtilsTests\TestCase; final class BeforeLoadCleanerTest extends TestCase { public function testImplementsBeforeLoadCleanerInterface(): void { $this->assertInstanceOf(BeforeLoadCleanerInterface::class, new BeforeLoadCleaner()); } public function testDefaultCleaners(): void { $cleaner = new BeforeLoadCleaner(); $this->assertEquals($cleaner->members(), BeforeLoadCleaner::defaultCleaners()); $this->assertCount(2, $cleaner->members()); } public function testCleanCallsCleaners(): void { $returnFoo = new class () implements BeforeLoadCleanerInterface { public function clean(string $content): string { return str_replace('foo', 'FOO', $content); } }; $returnBar = new class () implements BeforeLoadCleanerInterface { public function clean(string $content): string { return str_replace('bar', 'BAR', $content); } }; $cleaner = new BeforeLoadCleaner($returnFoo, $returnBar); $transformed = $cleaner->clean('foo bar baz'); $expected = 'FOO BAR baz'; $this->assertSame($expected, $transformed); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/SumasPagos20/CalculateFromCfdiCasesTest.php
tests/CfdiUtilsTests/SumasPagos20/CalculateFromCfdiCasesTest.php
<?php namespace CfdiUtilsTests\SumasPagos20; use CfdiUtils\Cfdi; use CfdiUtils\Nodes\NodeInterface; use CfdiUtils\SumasPagos20\Calculator; use CfdiUtils\SumasPagos20\Decimal; use CfdiUtils\SumasPagos20\Pago; use CfdiUtilsTests\TestCase; use LogicException; final class CalculateFromCfdiCasesTest extends TestCase { /** @return array<string, array{string}> */ public function providerPredefinedCfdi(): array { return [ /** * @see \CfdiUtilsTests\CreateComprobantePagos40CaseTest * @see file://tests/assets/created-cfdi40-pago20-valid.xml */ 'created-cfdi40-pago20-valid.xml' => [self::utilAsset('created-cfdi40-pago20-valid.xml')], /** * 1 pago MXN pagando a 4 doctos MXN con tasa 16, 0 y exento. * 1 pago USD pagando a 1 docto MXN con tasa 16. * * @see file://tests/assets/pagos20-calculator/001.xml */ 'pagos20-calculator/001.xml' => [self::utilAsset('pagos20-calculator/001.xml')], /** * 1 Pago en MXN, con 1 documento relacionado MXN, con impuestos: * - ISR Retenido * - IVA Retenido * - IVA Trasladado 16% * - IEPS Trasladado 53% * * @see file://tests/assets/pagos20-calculator/002.xml */ 'pagos20-calculator/002.xml' => [self::utilAsset('pagos20-calculator/002.xml')], /** * 2 Pago en MXN, con 1 documento relacionado MXN cada uno, con impuestos: * - IVA Retenido * - ISR Retenido * - IVA Trasladado 16% * * @see file://tests/assets/pagos20-calculator/003.xml */ 'pagos20-calculator/003.xml' => [self::utilAsset('pagos20-calculator/003.xml')], /** * 1 Pago en MXN, 43 documentos relacionados en USD con impuestos de traslado IVA 16% * El cálculo de la sumatoria de impuestos es sensible a truncado o redondeo * * @see file://tests/assets/pagos20-calculator/004.xml */ 'pagos20-calculator/004.xml' => [self::utilAsset('pagos20-calculator/004.xml')], /** * Este pago incluye únicamente CFDI que no son objetos de pago. No tiene impuestos. * * @see file://tests/assets/pagos20-calculator/005.xml */ 'pagos20-calculator/005.xml' => [self::utilAsset('pagos20-calculator/005.xml')], /** * 3 Pagos, cada uno con 1 documento relacionado, IVA16, IVA0 e IVA Exento * El cálculo de la sumatoria de impuestos es sensible a truncado o redondeo * * @see file://tests/assets/pagos20-calculator/006.xml */ 'pagos20-calculator/006.xml' => [self::utilAsset('pagos20-calculator/006.xml')], /** * 1 Pago, 38 documentos relacionados con IVA0 * * @see file://tests/assets/pagos20-calculator/007.xml */ 'pagos20-calculator/007.xml' => [self::utilAsset('pagos20-calculator/007.xml')], /** * 1 Pago, el monto (168168.00) es mayor al mínimo (168167.99), tiene IVA Retenido y Trasladado * El cálculo de la sumatoria de impuestos es sensible a truncado o redondeo * * @see file://tests/assets/pagos20-calculator/008.xml */ 'pagos20-calculator/008.xml' => [self::utilAsset('pagos20-calculator/008.xml')], ]; } /** @dataProvider providerPredefinedCfdi */ public function testPredefinedCfdi(string $cfdiFile): void { if (! file_exists($cfdiFile) || ! is_file($cfdiFile)) { throw new LogicException(sprintf('File %s does not exists', $cfdiFile)); } $cfdiContents = (string) file_get_contents($cfdiFile); $cfdi = Cfdi::newFromString($cfdiContents); $nodePagos = $cfdi->getNode()->searchNode('cfdi:Complemento', 'pago20:Pagos'); if (null === $nodePagos) { throw new LogicException(sprintf('File %s does not have a pago20:Pagos node', $cfdiFile)); } $calculator = new Calculator(); $pagos = $calculator->calculate($nodePagos); // echo PHP_EOL, json_encode($pagos, JSON_PRETTY_PRINT); // totales $nodeTotales = $nodePagos->searchNode('pago20:Totales'); $totales = $pagos->getTotales(); $this->assertSame($nodeTotales['MontoTotalPagos'], (string) $totales->getTotal()); $this->checkAttributeDecimal($nodeTotales, 'TotalRetencionesIVA', $totales->getRetencionIva()); $this->checkAttributeDecimal($nodeTotales, 'TotalRetencionesISR', $totales->getRetencionIsr()); $this->checkAttributeDecimal($nodeTotales, 'TotalRetencionesIEPS', $totales->getRetencionIeps()); $this->checkAttributeDecimal($nodeTotales, 'TotalTrasladosBaseIVA16', $totales->getTrasladoIva16Base()); $this->checkAttributeDecimal($nodeTotales, 'TotalTrasladosImpuestoIVA16', $totales->getTrasladoIva16Importe()); $this->checkAttributeDecimal($nodeTotales, 'TotalTrasladosBaseIVA8', $totales->getTrasladoIva08Base()); $this->checkAttributeDecimal($nodeTotales, 'TotalTrasladosImpuestoIVA8', $totales->getTrasladoIva08Importe()); $this->checkAttributeDecimal($nodeTotales, 'TotalTrasladosBaseIVA0', $totales->getTrasladoIva00Base()); $this->checkAttributeDecimal($nodeTotales, 'TotalTrasladosImpuestoIVA0', $totales->getTrasladoIva00Importe()); $this->checkAttributeDecimal($nodeTotales, 'TotalTrasladosBaseIVAExento', $totales->getTrasladoIvaExento()); $processedPagos = []; // pago@monto, pago/impuestos foreach ($nodePagos->searchNodes('pago20:Pago') as $index => $nodePago) { $pago = $pagos->getPago($index); $processedPagos[] = $pago; $this->assertTrue($pago->getMontoMinimo()->compareTo(new Decimal($nodePago['Monto'])) <= 0); $nodeRetenciones = $nodePago->searchNodes('pago20:ImpuestosP', 'pago20:RetencionesP', 'pago20:RetencionP'); foreach ($nodeRetenciones as $nodeRetencion) { $retencion = $pago->getImpuestos()->getRetencion($nodeRetencion['ImpuestoP']); $this->checkDecimalEquals($retencion->getImporte(), new Decimal($nodeRetencion['ImporteP'])); } $nodeTraslados = $nodePago->searchNodes('pago20:ImpuestosP', 'pago20:TrasladosP', 'pago20:TrasladoP'); foreach ($nodeTraslados as $nodeTraslado) { $traslado = $pago->getImpuestos()->getTraslado( $nodeTraslado['ImpuestoP'], $nodeTraslado['TipoFactorP'], $nodeTraslado['TasaOCuotaP'] ); $this->checkDecimalEquals($traslado->getBase(), new Decimal($nodeTraslado['BaseP'])); $this->checkDecimalEquals($traslado->getImporte(), new Decimal($nodeTraslado['ImporteP'])); } } // check the result does not have additional pago elements $missingPagos = array_filter( $pagos->getPagos(), fn (Pago $pago): bool => ! in_array($pago, $processedPagos, true) ); $this->assertSame([], $missingPagos, 'The result contains pagos that has not been processed'); } private function checkAttributeDecimal(NodeInterface $node, string $attribute, ?Decimal $value): void { if (! isset($node[$attribute])) { $this->assertNull($value, "Since attribute $attribute does not exists, then value must be null"); } else { $this->checkDecimalEquals( $value, new Decimal($node[$attribute]), "Attribute {$node->name()}@$attribute does not match with value" ); } } private function checkDecimalEquals(Decimal $expected, Decimal $value, string $message = ''): void { $this->assertTrue( 0 === $expected->compareTo($value), sprintf("%s\nExpected: %s Actual: %s", $message, $expected->getValue(), $value->getValue()) ); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/SumasPagos20/DecimalTest.php
tests/CfdiUtilsTests/SumasPagos20/DecimalTest.php
<?php namespace CfdiUtilsTests\SumasPagos20; use CfdiUtils\SumasPagos20\Decimal; use CfdiUtilsTests\TestCase; final class DecimalTest extends TestCase { /** @return array<array{Decimal, Decimal, int}> */ public function providerRound(): array { return [ [new Decimal('45740.35'), new Decimal('45740.3490'), 2], [new Decimal('1.23'), new Decimal('1.234'), 2], [new Decimal('1.24'), new Decimal('1.235'), 2], [new Decimal('1.24'), new Decimal('1.236'), 2], ]; } /** @dataProvider providerRound() */ public function testRound(Decimal $expected, Decimal $value, int $decimals): void { $this->assertSame(0, $expected->compareTo($value->round($decimals))); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/SumasPagos20/PagosWriterTest.php
tests/CfdiUtilsTests/SumasPagos20/PagosWriterTest.php
<?php declare(strict_types=1); namespace CfdiUtilsTests\SumasPagos20; use CfdiUtils\Elements\Pagos20\Pagos as ElementPagos20; use CfdiUtils\SumasPagos20\Calculator; use CfdiUtils\SumasPagos20\PagosWriter; use CfdiUtilsTests\TestCase; final class PagosWriterTest extends TestCase { public function testWritePagoWithOnlyOneExento(): void { $pagos = new ElementPagos20(); $pago = $pagos->addPago([ 'FechaPago' => '2025-06-24', 'FormaDePagoP' => '03', 'MonedaP' => 'MXN', 'TipoCambioP' => '1', 'Monto' => '10.00', ]); $pago->addDoctoRelacionado([ 'IdDocumento' => '00000000-1111-2222-3333-00000000000A', 'MonedaDR' => 'MXN', 'EquivalenciaDR' => '1', 'NumParcialidad' => '1', 'ImpSaldoAnt' => '4500.00', 'ImpPagado' => '10.00', 'ImpSaldoInsoluto' => '4490.00', 'ObjetoImpDR' => '02', ])->getImpuestosDR()->getTrasladosDR()->addTrasladoDR([ 'BaseDR' => '10.00', 'ImpuestoDR' => '002', 'TipoFactorDR' => 'Exento', ]); $calculator = new Calculator(2); $result = $calculator->calculate($pagos); $writer = new PagosWriter($pagos); $writer->writePago($pago, $result->getPago(0)); $traslado = $pagos->searchNode('pago20:Pago', 'pago20:ImpuestosP', 'pago20:TrasladosP', 'pago20:TrasladoP'); $this->assertFalse(isset($traslado['TasaOCuotaP'])); $this->assertFalse(isset($traslado['ImporteP'])); $this->assertSame('002', $traslado['ImpuestoP']); $this->assertSame('10.00', $traslado['BaseP']); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/SumasPagos20/CalculatorTest.php
tests/CfdiUtilsTests/SumasPagos20/CalculatorTest.php
<?php namespace CfdiUtilsTests\SumasPagos20; use CfdiUtils\Nodes\XmlNodeUtils; use CfdiUtils\SumasPagos20\Calculator; use CfdiUtils\SumasPagos20\Currencies; use CfdiUtilsTests\TestCase; final class CalculatorTest extends TestCase { public function testCalculatorDefaultProperties(): void { $calculator = new Calculator(); $this->assertSame(6, $calculator->getPaymentTaxesPrecision()); $this->assertInstanceOf(Currencies::class, $calculator->getCurrencies()); } public function testCalculatorProperties(): void { $precision = 4; $currencies = $this->createMock(Currencies::class); $calculator = new Calculator($precision, $currencies); $this->assertSame($precision, $calculator->getPaymentTaxesPrecision()); $this->assertSame($currencies, $calculator->getCurrencies()); } public function testCalculatorChangeProperties(): void { $calculator = new Calculator(); $precision = 4; $calculator->setPaymentTaxesPrecision($precision); $this->assertSame($precision, $calculator->getPaymentTaxesPrecision()); $currencies = $this->createMock(Currencies::class); $calculator->setCurrencies($currencies); $this->assertSame($currencies, $calculator->getCurrencies()); } public function testCalculateMinimal(): void { $xml = <<< XML <pago20:Pagos> <pago20:Pago MonedaP="MXN" TipoCambioP="1"> <pago20:DoctoRelacionado MonedaDR="MXN" EquivalenciaDR="1" ImpPagado="0.14"> <pago20:ImpuestosDR> <pago20:TrasladosDR> <pago20:TrasladoDR ImpuestoDR="002" TipoFactorDR="Tasa" TasaOCuotaDR="0.160000" BaseDR="0.123456789" ImporteDR="0.01975308624"/> </pago20:TrasladosDR> </pago20:ImpuestosDR> </pago20:DoctoRelacionado> </pago20:Pago> </pago20:Pagos> XML; $pagos = XmlNodeUtils::nodeFromXmlString($xml); $calculator = new Calculator(); $result = $calculator->calculate($pagos); $this->assertSame('0.14', (string) $result->getTotales()->getTotal()); $this->assertSame('0.12', (string) $result->getTotales()->getTrasladoIva16Base()); $this->assertSame('0.02', (string) $result->getTotales()->getTrasladoIva16Importe()); $impuesto = $result->getPago(0)->getImpuestos()->getTraslado('002', 'Tasa', '0.160000'); $this->assertSame('0.123457', (string) $impuesto->getBase()); $this->assertSame('0.019753', (string) $impuesto->getImporte()); $calculator = new Calculator(4); $result = $calculator->calculate($pagos); $impuesto = $result->getPago(0)->getImpuestos()->getTraslado('002', 'Tasa', '0.160000'); $this->assertSame('0.1235', (string) $impuesto->getBase()); $this->assertSame('0.0198', (string) $impuesto->getImporte()); } public function testCalculateTwoDocuments(): void { $xml = <<< XML <pago20:Pagos Version="2.0"> <pago20:Pago MonedaP="MXN" TipoCambioP="1"> <pago20:DoctoRelacionado ImpPagado="0.14" MonedaDR="MXN" EquivalenciaDR="1"> <pago20:ImpuestosDR> <pago20:TrasladosDR> <pago20:TrasladoDR ImpuestoDR="002" TipoFactorDR="Tasa" TasaOCuotaDR="0.160000" BaseDR="0.123456789" ImporteDR="0.01975308624"/> </pago20:TrasladosDR> </pago20:ImpuestosDR> </pago20:DoctoRelacionado> <pago20:DoctoRelacionado ImpPagado="1.43" MonedaDR="MXN" EquivalenciaDR="1"> <pago20:ImpuestosDR> <pago20:TrasladosDR> <pago20:TrasladoDR ImpuestoDR="002" TipoFactorDR="Tasa" TasaOCuotaDR="0.160000" BaseDR="1.23456789" ImporteDR="0.1975308624"/> </pago20:TrasladosDR> </pago20:ImpuestosDR> </pago20:DoctoRelacionado> </pago20:Pago> </pago20:Pagos> XML; $pagos = XmlNodeUtils::nodeFromXmlString($xml); $calculator = new Calculator(); $result = $calculator->calculate($pagos); $this->assertSame('1.57', (string) $result->getTotales()->getTotal()); $this->assertSame('1.36', (string) $result->getTotales()->getTrasladoIva16Base()); $this->assertSame('0.22', (string) $result->getTotales()->getTrasladoIva16Importe()); $impuesto = $result->getPago(0)->getImpuestos()->getTraslado('002', 'Tasa', '0.160000'); $this->assertSame('1.358025', (string) $impuesto->getBase()); $this->assertSame('0.217284', (string) $impuesto->getImporte()); } /** * In the following case, also Pago::monto is greater than Pago::montoMinimo */ public function testCalculatePaymentUsdDoctosMxnAndUsd(): void { $xml = <<< XML <pago20:Pagos Version="2.0"> <pago20:Pago MonedaP="USD" Monto="5.00" TipoCambioP="17.8945"> <pago20:DoctoRelacionado ImpPagado="0.14" MonedaDR="MXN" EquivalenciaDR="17.8945"> <pago20:ImpuestosDR> <pago20:TrasladosDR> <pago20:TrasladoDR ImpuestoDR="002" TipoFactorDR="Tasa" TasaOCuotaDR="0.160000" BaseDR="0.123456789" ImporteDR="0.01975308624"/> <pago20:TrasladoDR ImpuestoDR="002" TipoFactorDR="Tasa" TasaOCuotaDR="0.000000" BaseDR="0.123456789" ImporteDR="0"/> </pago20:TrasladosDR> </pago20:ImpuestosDR> </pago20:DoctoRelacionado> <pago20:DoctoRelacionado ImpPagado="1.43" MonedaDR="MXN" EquivalenciaDR="17.8945"> <pago20:ImpuestosDR> <pago20:TrasladosDR> <pago20:TrasladoDR ImpuestoDR="002" TipoFactorDR="Tasa" TasaOCuotaDR="0.160000" BaseDR="1.23456789" ImporteDR="0.1975308624"/> </pago20:TrasladosDR> </pago20:ImpuestosDR> </pago20:DoctoRelacionado> <pago20:DoctoRelacionado ImpPagado="4.01" MonedaDR="USD" EquivalenciaDR="1"> <pago20:ImpuestosDR> <pago20:TrasladosDR> <pago20:TrasladoDR ImpuestoDR="002" TipoFactorDR="Tasa" TasaOCuotaDR="0.160000" BaseDR="3.456789" ImporteDR="0.55308624"/> </pago20:TrasladosDR> </pago20:ImpuestosDR> </pago20:DoctoRelacionado> </pago20:Pago> </pago20:Pagos> XML; $pagos = XmlNodeUtils::nodeFromXmlString($xml); $calculator = new Calculator(); $result = $calculator->calculate($pagos); $expectedJson = <<< JSON { "totales": { "trasladoIva16Base": "63.22", "trasladoIva16Importe": "10.11", "trasladoIva00Base": "0.12", "trasladoIva00Importe": "0.00", "total": "89.47" }, "pagos": [ { "monto": "5.00", "montoMinimo": "4.09", "tipoCambioP": "17.8945", "impuestos": { "T:Traslado|I:002|F:Tasa|C:0.160000": { "tipo": "Traslado", "impuesto": "002", "tipoFactor": "Tasa", "tasaCuota": "0.160000", "base": "3.532680", "importe": "0.565229" }, "T:Traslado|I:002|F:Tasa|C:0.000000": { "tipo": "Traslado", "impuesto": "002", "tipoFactor": "Tasa", "tasaCuota": "0.000000", "base": "0.006899", "importe": "0.000000" } } } ] } JSON; $this->assertJsonStringEqualsJsonString($expectedJson, json_encode($result)); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/ConsultaCfdiSat/StatusResponseTest.php
tests/CfdiUtilsTests/ConsultaCfdiSat/StatusResponseTest.php
<?php namespace CfdiUtilsTests\ConsultaCfdiSat; use CfdiUtils\ConsultaCfdiSat\StatusResponse; use CfdiUtilsTests\TestCase; final class StatusResponseTest extends TestCase { public function testConsultaResponseExpectedOk(): void { $response = new StatusResponse( 'S - Comprobante obtenido satisfactoriamente', 'Vigente', 'Cancelable con autorización', 'En proceso', '200' ); $this->assertSame('S - Comprobante obtenido satisfactoriamente', $response->getCode()); $this->assertSame('Vigente', $response->getCfdi()); $this->assertTrue($response->responseWasOk()); $this->assertTrue($response->isVigente()); $this->assertFalse($response->isNotFound()); $this->assertFalse($response->isCancelled()); $this->assertSame('Cancelable con autorización', $response->getCancellable()); $this->assertSame('En proceso', $response->getCancellationStatus()); $this->assertSame('200', $response->getValidationEfos()); $this->assertFalse($response->isEfosListed()); } public function testConsultaResponseNotOk(): void { $response = new StatusResponse( 'N - 601: La expresión impresa proporcionada no es válida', 'No Encontrado', '', '', '', ); $this->assertSame('N - 601: La expresión impresa proporcionada no es válida', $response->getCode()); $this->assertSame('No Encontrado', $response->getCfdi()); $this->assertFalse($response->responseWasOk()); $this->assertFalse($response->isVigente()); $this->assertTrue($response->isNotFound()); $this->assertFalse($response->isCancelled()); } public function testConsultaResponseCancelled(): void { $response = new StatusResponse( 'S - Comprobante obtenido satisfactoriamente', 'Cancelado', '', '', '', ); $this->assertSame('S - Comprobante obtenido satisfactoriamente', $response->getCode()); $this->assertSame('Cancelado', $response->getCfdi()); $this->assertTrue($response->responseWasOk()); $this->assertFalse($response->isVigente()); $this->assertFalse($response->isNotFound()); $this->assertTrue($response->isCancelled()); } /** * @testWith ["200"] * @testWith ["201"] */ public function testIsEfosListedOk(string $efosNotListedStatus): void { $response = new StatusResponse( 'S - Comprobante obtenido satisfactoriamente', 'Vigente', 'Cancelable con autorización', 'En proceso', $efosNotListedStatus ); $this->assertSame($efosNotListedStatus, $response->getValidationEfos()); $this->assertFalse($response->isEfosListed()); } public function testIsEfosListedNotOk(): void { $efosListedStatus = '100'; $response = new StatusResponse( 'S - Comprobante obtenido satisfactoriamente', 'Vigente', 'Cancelable con autorización', 'En proceso', $efosListedStatus ); $this->assertSame($efosListedStatus, $response->getValidationEfos()); $this->assertTrue($response->isEfosListed()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/ConsultaCfdiSat/WebServiceTest.php
tests/CfdiUtilsTests/ConsultaCfdiSat/WebServiceTest.php
<?php namespace CfdiUtilsTests\ConsultaCfdiSat; use CfdiUtils\ConsultaCfdiSat\Config; use CfdiUtils\ConsultaCfdiSat\RequestParameters; use CfdiUtils\ConsultaCfdiSat\WebService; use CfdiUtilsTests\TestCase; use PHPUnit\Framework\MockObject\MockObject; final class WebServiceTest extends TestCase { public function testConstructWithNoConfig(): void { $config = new Config(); $ws = new WebService(); $this->assertEquals($config, $ws->getConfig()); $this->assertNotSame($config, $ws->getConfig()); } public function testConstructWithConfig(): void { $config = new Config(60, false); $ws = new WebService($config); $this->assertSame($config, $ws->getConfig()); } public function providerRequestWithBadRawResponse(): array { return [ 'response invalid' => [ null, 'The consulta web service did not return any result', ], 'CodigoEstatus missing' => [ (object) [], 'The consulta web service did not have expected ConsultaResult:CodigoEstatus', ], 'ConsultaResult:Estado missing' => [ (object) ['CodigoEstatus' => ''], 'The consulta web service did not have expected ConsultaResult:Estado', ], 'No exception' => [ (object) ['CodigoEstatus' => '', 'Estado' => ''], '', ], ]; } /** * @dataProvider providerRequestWithBadRawResponse */ public function testRequestWithBadRawResponse(?\stdClass $rawResponse, string $expectedMessage): void { /** @var WebService&MockObject $webService */ $webService = $this->getMockBuilder(WebService::class) ->setMethodsExcept(['request', 'requestExpression']) ->setMethods(['doRequestConsulta']) ->getMock(); // expects once as constraint because maybe $expectedMessage is empty $webService->expects($this->once())->method('doRequestConsulta')->willReturn($rawResponse); $validCfdi33Request = new RequestParameters( '3.3', 'POT9207213D6', 'DIM8701081LA', '2010.01', 'CEE4BE01-ADFA-4DEB-8421-ADD60F0BEDAC', '/OAgdg==' ); if ('' !== $expectedMessage) { $this->expectException(\RuntimeException::class); $this->expectExceptionMessage($expectedMessage); } $webService->request($validCfdi33Request); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/ConsultaCfdiSat/WebServiceConsumingTest.php
tests/CfdiUtilsTests/ConsultaCfdiSat/WebServiceConsumingTest.php
<?php namespace CfdiUtilsTests\ConsultaCfdiSat; use CfdiUtils\ConsultaCfdiSat\Config; use CfdiUtils\ConsultaCfdiSat\RequestParameters; use CfdiUtils\ConsultaCfdiSat\StatusResponse; use CfdiUtils\ConsultaCfdiSat\WebService; use CfdiUtilsTests\TestCase; use SoapClient; use SoapFault; /** * This test case is performing real request to SAT WebService. * * The problem is that since 2018-08 the service is failing on request, * and it makes the tests fail randomly. * * The workaround is to mark test skipped if we get a SoapFault when call * request or getSoapClient methods */ final class WebServiceConsumingTest extends TestCase { private function createWebServiceObject(): WebService { $config = new Config(5, true, ''); return new WebService($config); } private function tolerantRequest(RequestParameters $request): StatusResponse { $ws = $this->createWebServiceObject(); try { return $ws->request($request); } catch (SoapFault $exception) { $this->markTestSkipped("SAT Service: {$exception->getMessage()}"); } } private function tolerantSoapClient(WebService $ws): SoapClient { try { return $ws->getSoapClient(); } catch (SoapFault $exception) { $this->markTestSkipped("SAT Service: {$exception->getMessage()}"); } } public function testGetSoapClient(): void { $ws = $this->createWebServiceObject(); $soapClient = $this->tolerantSoapClient($ws); $this->assertSame($soapClient, $this->tolerantSoapClient($ws)); $ws->destroySoapClient(); $this->assertNotSame($soapClient, $this->tolerantSoapClient($ws)); } /** @requires PHP < 8.1 */ public function testSoapClientHasSettings(): void { $config = new Config(60, false, ''); $ws = new WebService($config); $soapClient = $this->tolerantSoapClient($ws); // check timeout /** @phpstan-ignore-next-line the variable is internal */ $this->assertSame(60, $soapClient->{'_connection_timeout'}); // check context /** @phpstan-ignore-next-line the variable is internal */ $context = $soapClient->{'_stream_context'}; $options = stream_context_get_options($context); $this->assertSame(false, $options['ssl']['verify_peer'] ?? null); } public function testValidDocumentVersion33(): void { $validCfdi33Request = new RequestParameters( '3.3', 'POT9207213D6', 'DIM8701081LA', '2010.01', 'CEE4BE01-ADFA-4DEB-8421-ADD60F0BEDAC', '/OAgdg==' ); $return = $this->tolerantRequest($validCfdi33Request); $this->assertStringStartsWith('S - ', $return->getCode()); $this->assertSame('Vigente', $return->getCfdi()); $this->assertSame('Cancelable con aceptación', $return->getCancellable()); $this->assertSame('', $return->getCancellationStatus()); $this->assertSame('200', $return->getValidationEfos()); } public function testValidDocumentVersion32(): void { $validCfdi32Request = new RequestParameters( '3.2', 'CTO021007DZ8', 'XAXX010101000', '4685.00', '80824F3B-323E-407B-8F8E-40D83FE2E69F' ); $return = $this->tolerantRequest($validCfdi32Request); $this->assertTrue($return->responseWasOk()); $this->assertTrue($return->isVigente()); $this->assertSame('Cancelable sin aceptación', $return->getCancellable()); $this->assertSame('', $return->getCancellationStatus()); $this->assertSame('200', $return->getValidationEfos()); } public function testConsumeWebServiceWithNotFoundDocument(): void { $invalidCfdi33Request = new RequestParameters( '3.3', 'POT9207213D6', 'DIM8701081LA', '1010.01', // only change the first digit of the total 'CEE4BE01-ADFA-4DEB-8421-ADD60F0BEDAC', '/OAgdg==' ); $return = $this->tolerantRequest($invalidCfdi33Request); // N - 601: La expresión impresa proporcionada no es válida. $this->assertStringStartsWith('N - 601', $return->getCode()); $this->assertStringStartsWith('No Encontrado', $return->getCfdi()); $this->assertFalse($return->responseWasOk()); $this->assertTrue($return->isNotFound()); $this->assertFalse($return->isEfosListed()); } public function testConsumeWebServiceWithCancelledDocument(): void { $invalidCfdi33Request = new RequestParameters( '3.3', 'DIM8701081LA', 'XEXX010101000', '8413.00', '3be40815-916c-4c91-84e2-6070d4bc3949', '...3f86Og==' ); $return = $this->tolerantRequest($invalidCfdi33Request); $this->assertTrue($return->responseWasOk()); $this->assertTrue($return->isCancelled()); $this->assertFalse($return->isEfosListed()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/ConsultaCfdiSat/RequestParametersTest.php
tests/CfdiUtilsTests/ConsultaCfdiSat/RequestParametersTest.php
<?php namespace CfdiUtilsTests\ConsultaCfdiSat; use CfdiUtils\Cfdi; use CfdiUtils\ConsultaCfdiSat\RequestParameters; use CfdiUtilsTests\TestCase; final class RequestParametersTest extends TestCase { public function testConstructorAndGetters(): void { $parameters = new RequestParameters( '3.3', 'EKU9003173C9', 'COSC8001137NA', '1,234.5678', 'CEE4BE01-ADFA-4DEB-8421-ADD60F0BEDAC', '0123456789' ); $this->assertSame('3.3', $parameters->getVersion()); $this->assertSame('EKU9003173C9', $parameters->getRfcEmisor()); $this->assertSame('COSC8001137NA', $parameters->getRfcReceptor()); $this->assertSame('1,234.5678', $parameters->getTotal()); $this->assertEqualsWithDelta(1234.5678, $parameters->getTotalFloat(), 0.0000001); $this->assertSame('CEE4BE01-ADFA-4DEB-8421-ADD60F0BEDAC', $parameters->getUuid()); $this->assertSame('0123456789', $parameters->getSello()); $expected40 = 'https://verificacfdi.facturaelectronica.sat.gob.mx/default.aspx' . '?id=CEE4BE01-ADFA-4DEB-8421-ADD60F0BEDAC' . '&re=EKU9003173C9' . '&rr=COSC8001137NA' . '&tt=1234.5678' . '&fe=23456789'; $this->assertSame($expected40, $parameters->expression()); $expected33 = 'https://verificacfdi.facturaelectronica.sat.gob.mx/default.aspx' . '?id=CEE4BE01-ADFA-4DEB-8421-ADD60F0BEDAC' . '&re=EKU9003173C9' . '&rr=COSC8001137NA' . '&tt=1234.5678' . '&fe=23456789'; $this->assertSame($expected33, $parameters->expression()); $expected32 = '' . '?re=EKU9003173C9' . '&rr=COSC8001137NA' . '&tt=0000001234.567800' . '&id=CEE4BE01-ADFA-4DEB-8421-ADD60F0BEDAC'; $parameters->setVersion('3.2'); $this->assertSame($expected32, $parameters->expression()); } public function testConstructorWithWrongVersion(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage('version'); new RequestParameters( '1.1', 'EKU9003173C9', 'COSC8001137NA', '1,234.5678', 'CEE4BE01-ADFA-4DEB-8421-ADD60F0BEDAC', '0123456789' ); } public function testCreateFromCfdiVersion32(): void { $cfdi = Cfdi::newFromString(strval(file_get_contents($this->utilAsset('cfdi32-real.xml')))); $parameters = RequestParameters::createFromCfdi($cfdi); $this->assertSame('3.2', $parameters->getVersion()); $this->assertSame('CTO021007DZ8', $parameters->getRfcEmisor()); $this->assertSame('XAXX010101000', $parameters->getRfcReceptor()); $this->assertSame('80824F3B-323E-407B-8F8E-40D83FE2E69F', $parameters->getUuid()); $this->assertStringEndsWith('YRbgmmVYiA==', $parameters->getSello()); $this->assertEqualsWithDelta(4685.00, $parameters->getTotalFloat(), 0.001); } public function testCreateFromCfdiVersion33(): void { $cfdi = Cfdi::newFromString(strval(file_get_contents($this->utilAsset('cfdi33-real.xml')))); $parameters = RequestParameters::createFromCfdi($cfdi); $this->assertSame('3.3', $parameters->getVersion()); $this->assertSame('POT9207213D6', $parameters->getRfcEmisor()); $this->assertSame('DIM8701081LA', $parameters->getRfcReceptor()); $this->assertSame('CEE4BE01-ADFA-4DEB-8421-ADD60F0BEDAC', $parameters->getUuid()); $this->assertStringEndsWith('XmE4/OAgdg==', $parameters->getSello()); $this->assertEqualsWithDelta(2010.01, $parameters->getTotalFloat(), 0.001); } public function testCreateFromCfdiVersion40(): void { $cfdi = Cfdi::newFromString(strval(file_get_contents($this->utilAsset('cfdi40-real.xml')))); $parameters = RequestParameters::createFromCfdi($cfdi); $this->assertSame('4.0', $parameters->getVersion()); $this->assertSame('ISD950921HE5', $parameters->getRfcEmisor()); $this->assertSame('COSC8001137NA', $parameters->getRfcReceptor()); $this->assertSame('C2832671-DA6D-11EF-A83D-00155D012007', $parameters->getUuid()); $this->assertStringEndsWith('FoYRhNjeNw==', $parameters->getSello()); $this->assertEqualsWithDelta(1000.00, $parameters->getTotalFloat(), 0.001); } /** * * @testWith ["9.123456", "9.123456"] * ["0.123456", "0.123456"] * ["1", "1.0"] * ["0.1", "0.1"] * ["1.1", "1.1"] * ["0", "0.0"] * ["0.1234567", "0.123457"] */ public function testExpressionTotalExamples(string $total, string $expected): void { $parameters = new RequestParameters( '3.3', 'EKU9003173C9', 'COSC8001137NA', $total, 'CEE4BE01-ADFA-4DEB-8421-ADD60F0BEDAC', '0123456789' ); $this->assertStringContainsString('&tt=' . $expected . '&', $parameters->expression()); } public function testRfcWithAmpersand(): void { /* * This is not an error. SAT is using XML encoding on URL instead of URL encoding, * this is why the ampersand `&` should be `&amp;` instead of `%26`, and `Ñ` is the same. */ $parameters = new RequestParameters( '3.3', 'Ñ&A010101AAA', 'Ñ&A991231AA0', '1,234.5678', 'CEE4BE01-ADFA-4DEB-8421-ADD60F0BEDAC', '0123456789' ); $this->assertSame('Ñ&A010101AAA', $parameters->getRfcEmisor()); $this->assertSame('Ñ&A991231AA0', $parameters->getRfcReceptor()); $expected32 = '?re=Ñ&amp;A010101AAA' . '&rr=Ñ&amp;A991231AA0' . '&tt=0000001234.567800' . '&id=CEE4BE01-ADFA-4DEB-8421-ADD60F0BEDAC'; $this->assertSame($expected32, $parameters->expressionVersion32()); $expected33 = 'https://verificacfdi.facturaelectronica.sat.gob.mx/default.aspx' . '?id=CEE4BE01-ADFA-4DEB-8421-ADD60F0BEDAC' . '&re=Ñ&amp;A010101AAA' . '&rr=Ñ&amp;A991231AA0' . '&tt=1234.5678' . '&fe=23456789'; $this->assertSame($expected33, $parameters->expressionVersion33()); // Same as CFDI 3.3 $this->assertSame($expected33, $parameters->expressionVersion40()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/ConsultaCfdiSat/ConfigTest.php
tests/CfdiUtilsTests/ConsultaCfdiSat/ConfigTest.php
<?php namespace CfdiUtilsTests\ConsultaCfdiSat; use CfdiUtils\ConsultaCfdiSat\Config; use CfdiUtilsTests\TestCase; final class ConfigTest extends TestCase { public function testConstructorDefaultValues(): void { $config = new Config(); $this->assertSame(10, $config->getTimeout()); $this->assertSame(true, $config->shouldVerifyPeer()); $this->assertSame($config::DEFAULT_SERVICE_URL, $config->getServiceUrl()); } public function testConstructorWithOtherData(): void { $config = new Config(99, false, 'foo'); $this->assertSame(99, $config->getTimeout()); $this->assertSame(false, $config->shouldVerifyPeer()); $this->assertSame('foo', $config->getServiceUrl()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/SumasConceptos/SumasConceptosWriter33Test.php
tests/CfdiUtilsTests/SumasConceptos/SumasConceptosWriter33Test.php
<?php namespace CfdiUtilsTests\SumasConceptos; use CfdiUtils\Elements\Cfdi33\Comprobante as Comprobante33; use CfdiUtils\SumasConceptos\SumasConceptos; use CfdiUtils\SumasConceptos\SumasConceptosWriter; use PHPUnit\Framework\TestCase; final class SumasConceptosWriter33Test extends TestCase { use SumasConceptosWriterTestTrait; public function createComprobante(array $attributes = []): Comprobante33 { return new Comprobante33($attributes); } public function testConstructor(): void { $precision = 6; $comprobante = $this->createComprobante(); $sumasConceptos = new SumasConceptos($comprobante, $precision); $writer = new SumasConceptosWriter($comprobante, $sumasConceptos, $precision); $this->assertSame($comprobante, $writer->getComprobante()); $this->assertSame($precision, $writer->getPrecision()); $this->assertSame($sumasConceptos, $writer->getSumasConceptos()); $this->assertSame(false, $writer->hasWriteImpuestoBase()); $this->assertSame(false, $writer->hasWriteExentos()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/SumasConceptos/SumasConceptosTest.php
tests/CfdiUtilsTests/SumasConceptos/SumasConceptosTest.php
<?php namespace CfdiUtilsTests\SumasConceptos; use CfdiUtils\Elements\Cfdi33\Comprobante; use CfdiUtils\Elements\ImpLocal10\ImpuestosLocales; use CfdiUtils\Nodes\Node; use CfdiUtils\SumasConceptos\SumasConceptos; use PHPUnit\Framework\TestCase; final class SumasConceptosTest extends TestCase { public function testConstructor(): void { $maxDiff = 0.0000001; $sc = new SumasConceptos(new Node('x')); $this->assertSame(2, $sc->getPrecision()); $this->assertEqualsWithDelta(0, $sc->getSubTotal(), $maxDiff); $this->assertEqualsWithDelta(0, $sc->getTotal(), $maxDiff); $this->assertEqualsWithDelta(0, $sc->getDescuento(), $maxDiff); $this->assertEqualsWithDelta(0, $sc->getImpuestosRetenidos(), $maxDiff); $this->assertEqualsWithDelta(0, $sc->getImpuestosTrasladados(), $maxDiff); $this->assertEqualsWithDelta(0, $sc->getLocalesImpuestosRetenidos(), $maxDiff); $this->assertEqualsWithDelta(0, $sc->getLocalesImpuestosTrasladados(), $maxDiff); $this->assertCount(0, $sc->getRetenciones()); $this->assertCount(0, $sc->getTraslados()); $this->assertCount(0, $sc->getExentos()); $this->assertCount(0, $sc->getLocalesRetenciones()); $this->assertCount(0, $sc->getLocalesTraslados()); $this->assertFalse($sc->hasRetenciones()); $this->assertFalse($sc->hasTraslados()); $this->assertFalse($sc->hasExentos()); $this->assertFalse($sc->hasLocalesRetenciones()); $this->assertFalse($sc->hasLocalesTraslados()); } public function providerWithConceptsDecimals(): array { /* * The case "tax uses 1 dec" 53.4 = round(35.6 + 17.8, 2) * The case "tax uses 6 dec" 53.33 = round(17.7776 + 35.5552, 2) */ return [ 'tax uses 1 dec' => [1, 333.33, 53.4, 386.73], 'tax uses 6 dec' => [6, 333.33, 53.33, 386.66], ]; } /** * @dataProvider providerWithConceptsDecimals */ public function testWithConceptsDecimals(int $taxDecimals, float $subtotal, float $traslados, float $total): void { $maxDiff = 0.0000001; $comprobante = new Comprobante(); $comprobante->addConcepto([ 'Importe' => '111.11', ])->addTraslado([ 'Base' => '111.11', 'Impuesto' => '002', 'TipoFactor' => 'Tasa', 'TasaOCuota' => '0.160000', 'Importe' => number_format(111.11 * 0.16, $taxDecimals, '.', ''), ]); $comprobante->addConcepto([ 'Importe' => '222.22', ])->addTraslado([ 'Base' => '222.22', 'Impuesto' => '002', 'TipoFactor' => 'Tasa', 'TasaOCuota' => '0.160000', 'Importe' => number_format(222.22 * 0.16, $taxDecimals, '.', ''), ]); $sc = new SumasConceptos($comprobante, 2); $this->assertEqualsWithDelta($subtotal, $sc->getSubTotal(), $maxDiff); $this->assertEqualsWithDelta($traslados, $sc->getImpuestosTrasladados(), $maxDiff); $this->assertEqualsWithDelta($total, $sc->getTotal(), $maxDiff); // these are zero $this->assertEqualsWithDelta(0, $sc->getDescuento(), $maxDiff); $this->assertEqualsWithDelta(0, $sc->getImpuestosRetenidos(), $maxDiff); $this->assertCount(0, $sc->getRetenciones()); $this->assertCount(0, $sc->getExentos()); } public function testWithImpuestosLocales(): void { $taxDecimals = 4; $maxDiff = 0.0000001; $comprobante = new Comprobante(); $comprobante->addConcepto([ 'Importe' => '111.11', ])->addTraslado([ 'Base' => '111.11', 'Impuesto' => '002', 'TipoFactor' => 'Tasa', 'TasaOCuota' => '0.160000', 'Importe' => number_format(111.11 * 0.16, $taxDecimals, '.', ''), ]); $comprobante->addConcepto([ 'Importe' => '222.22', ])->addTraslado([ 'Base' => '222.22', 'Impuesto' => '002', 'TipoFactor' => 'Tasa', 'TasaOCuota' => '0.160000', 'Importe' => number_format(222.22 * 0.16, $taxDecimals, '.', ''), ]); $impuestosLocales = new ImpuestosLocales(); $impuestosLocales->addTrasladoLocal([ 'ImpLocTrasladado' => 'IH', // fixed, taken from a sample, 'TasadeTraslado' => '2.5', 'Importe' => number_format(333.33 * 0.025, 2, '.', ''), ]); $comprobante->getComplemento()->add($impuestosLocales); $sc = new SumasConceptos($comprobante, 2); $this->assertCount(1, $sc->getTraslados()); $this->assertTrue($sc->hasTraslados()); $this->assertCount(1, $sc->getLocalesTraslados()); $this->assertEqualsWithDelta(333.33, $sc->getSubTotal(), $maxDiff); $this->assertEqualsWithDelta(53.33, $sc->getImpuestosTrasladados(), $maxDiff); $this->assertEqualsWithDelta(8.33, $sc->getLocalesImpuestosTrasladados(), $maxDiff); $this->assertEqualsWithDelta(333.33 + 53.33 + 8.33, $sc->getTotal(), $maxDiff); // these are zero $this->assertEqualsWithDelta(0, $sc->getDescuento(), $maxDiff); $this->assertEqualsWithDelta(0, $sc->getImpuestosRetenidos(), $maxDiff); $this->assertCount(0, $sc->getRetenciones()); $this->assertEqualsWithDelta(0, $sc->getLocalesImpuestosRetenidos(), $maxDiff); $this->assertCount(0, $sc->getLocalesRetenciones()); } public function testFoundAnyConceptWithDiscount(): void { $comprobante = new Comprobante(); $comprobante->addConcepto(['Importe' => '111.11']); $comprobante->addConcepto(['Importe' => '222.22']); $this->assertFalse((new SumasConceptos($comprobante))->foundAnyConceptWithDiscount()); // now add the attribute Descuento $comprobante->addConcepto(['Importe' => '333.33', 'Descuento' => '']); $this->assertTrue((new SumasConceptos($comprobante))->foundAnyConceptWithDiscount()); } public function testImpuestoImporteWithMoreDecimalsThanThePrecisionIsRounded(): void { $comprobante = new Comprobante(); $comprobante->addConcepto()->addTraslado([ 'Base' => '48.611106', 'Importe' => '7.777777', 'Impuesto' => '002', 'TipoFactor' => 'Tasa', 'TasaOCuota' => '0.160000', ]); $comprobante->addConcepto()->addTraslado([ 'Base' => '13.888888', 'Importe' => '2.222222', 'Impuesto' => '002', 'TipoFactor' => 'Tasa', 'TasaOCuota' => '0.160000', ]); $sumas = new SumasConceptos($comprobante, 3); $this->assertTrue($sumas->hasTraslados()); $this->assertEqualsWithDelta(10.0, $sumas->getImpuestosTrasladados(), 0.0001); $this->assertEqualsWithDelta(10.0, $sumas->getTraslados()['002:Tasa:0.160000']['Importe'], 0.0000001); $this->assertEqualsWithDelta(62.5, $sumas->getTraslados()['002:Tasa:0.160000']['Base'], 0.0000001); } public function testImpuestoWithTrasladosTasaAndExento(): void { $comprobante = new Comprobante(); $comprobante->addConcepto()->multiTraslado( [ 'Impuesto' => '002', 'TipoFactor' => 'Exento', 'Base' => '1000', ], [ 'Impuesto' => '002', 'TipoFactor' => 'Tasa', 'TasaOCuota' => '0.160000', 'Base' => '1000', 'Importe' => '160', ] ); $comprobante->addConcepto()->addTraslado([ 'Impuesto' => '002', 'TipoFactor' => 'Tasa', 'TasaOCuota' => '0.160000', 'Base' => '1000', 'Importe' => '160', ]); $comprobante->addConcepto()->addTraslado([ 'Impuesto' => '002', 'TipoFactor' => 'Exento', 'Base' => '234.56', ]); $sumas = new SumasConceptos($comprobante, 2); $this->assertTrue($sumas->hasTraslados()); $this->assertEqualsWithDelta(320.0, $sumas->getImpuestosTrasladados(), 0.001); $this->assertCount(1, $sumas->getTraslados()); $this->assertTrue($sumas->hasExentos()); $this->assertCount(1, $sumas->getExentos()); $this->assertEqualsWithDelta(1234.56, array_sum(array_column($sumas->getExentos(), 'Base')), 0.001); } public function testImpuestoWithTrasladosAndOnlyExentosWithoutBase(): void { $comprobante = new Comprobante(); $comprobante->addConcepto()->multiTraslado( ['Impuesto' => '002', 'TipoFactor' => 'Exento'] ); $comprobante->addConcepto()->multiTraslado( ['Impuesto' => '002', 'TipoFactor' => 'Exento'] ); $sumas = new SumasConceptos($comprobante, 2); $this->assertFalse($sumas->hasTraslados()); $this->assertEqualsWithDelta(0, $sumas->getImpuestosTrasladados(), 0.001); $this->assertCount(0, $sumas->getTraslados()); $this->assertTrue($sumas->hasExentos()); $this->assertEqualsWithDelta(0, array_sum(array_column($sumas->getExentos(), 'Base')), 0.001); } public function testImpuestoWithTrasladosAndOnlyExentosWithBase(): void { $comprobante = new Comprobante(); $comprobante->addConcepto()->multiTraslado( ['Impuesto' => '002', 'TipoFactor' => 'Exento', 'Base' => '123.45'], ); $comprobante->addConcepto()->multiTraslado( ['Impuesto' => '002', 'TipoFactor' => 'Exento', 'Base' => '543.21'], ['Impuesto' => '001', 'TipoFactor' => 'Exento', 'Base' => '100'], ); $comprobante->addConcepto()->multiTraslado( ['Impuesto' => '001', 'TipoFactor' => 'Exento', 'Base' => '150'], ); $sumas = new SumasConceptos($comprobante, 2); $this->assertFalse($sumas->hasTraslados()); $this->assertEqualsWithDelta(0, $sumas->getImpuestosTrasladados(), 0.001); $this->assertCount(0, $sumas->getTraslados()); $this->assertTrue($sumas->hasExentos()); $exentos001 = array_filter($sumas->getExentos(), fn (array $values): bool => '001' === $values['Impuesto']); $this->assertEqualsWithDelta(250.00, array_sum(array_column($exentos001, 'Base')), 0.001); $exentos002 = array_filter($sumas->getExentos(), fn (array $values): bool => '002' === $values['Impuesto']); $this->assertEqualsWithDelta(666.66, array_sum(array_column($exentos002, 'Base')), 0.001); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/SumasConceptos/SumasConceptosWriter40Test.php
tests/CfdiUtilsTests/SumasConceptos/SumasConceptosWriter40Test.php
<?php namespace CfdiUtilsTests\SumasConceptos; use CfdiUtils\Elements\Cfdi40\Comprobante as Comprobante40; use CfdiUtils\SumasConceptos\SumasConceptos; use CfdiUtils\SumasConceptos\SumasConceptosWriter; use PHPUnit\Framework\TestCase; final class SumasConceptosWriter40Test extends TestCase { use SumasConceptosWriterTestTrait; public function createComprobante(array $attributes = []): Comprobante40 { return new Comprobante40($attributes); } public function testConstructor(): void { $precision = 6; $comprobante = $this->createComprobante(); $sumasConceptos = new SumasConceptos($comprobante, $precision); $writer = new SumasConceptosWriter($comprobante, $sumasConceptos, $precision); $this->assertSame($comprobante, $writer->getComprobante()); $this->assertSame($precision, $writer->getPrecision()); $this->assertSame($sumasConceptos, $writer->getSumasConceptos()); $this->assertSame(true, $writer->hasWriteImpuestoBase()); $this->assertSame(true, $writer->hasWriteExentos()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/SumasConceptos/SumasConceptosWriterTestTrait.php
tests/CfdiUtilsTests/SumasConceptos/SumasConceptosWriterTestTrait.php
<?php namespace CfdiUtilsTests\SumasConceptos; use CfdiUtils\Elements\ImpLocal10\ImpuestosLocales; use CfdiUtils\Nodes\Node; use CfdiUtils\Nodes\XmlNodeUtils; use CfdiUtils\SumasConceptos\SumasConceptos; use CfdiUtils\SumasConceptos\SumasConceptosWriter; trait SumasConceptosWriterTestTrait { public function testFormat(): void { $precision = 6; $comprobante = $this->createComprobante(); $sumasConceptos = new SumasConceptos($comprobante, $precision); $writer = new SumasConceptosWriter($comprobante, $sumasConceptos, $precision); $this->assertSame('1.234566', $writer->format(1.2345664)); $this->assertSame('1.234567', $writer->format(1.2345665)); $this->assertSame('1.234567', $writer->format(1.2345674)); $this->assertSame('1.234568', $writer->format(1.2345675)); $this->assertSame('1.000000', $writer->format(1)); } public function testPutWithEmptyValues(): void { $precision = 2; $comprobante = $this->createComprobante(); $sumasConceptos = new SumasConceptos($comprobante, $precision); $writer = new SumasConceptosWriter($comprobante, $sumasConceptos, $precision); $writer->put(); $this->assertSame('0.00', $comprobante['SubTotal']); $this->assertFalse(isset($comprobante['Descuento'])); $this->assertSame('0.00', $comprobante['Total']); $this->assertNull($comprobante->searchNode('cfdi:Impuestos')); } public function testPutWithEmptyConceptosImpuestos(): void { $precision = 2; $comprobante = $this->createComprobante(); $comprobante->addConcepto([ 'Importe' => 1000, 'Descuento' => 1000, ]); $comprobante->addConcepto([ 'Importe' => 2000, 'Descuento' => 2000, ]); $sumasConceptos = new SumasConceptos($comprobante, $precision); $writer = new SumasConceptosWriter($comprobante, $sumasConceptos, $precision); $writer->put(); $this->assertSame('3000.00', $comprobante['SubTotal']); $this->assertSame('3000.00', $comprobante['Descuento']); $this->assertSame('0.00', $comprobante['Total']); $this->assertNull($comprobante->searchNode('cfdi:Impuestos')); } public function testPutWithZeroConceptosImpuestos(): void { $precision = 2; $comprobante = $this->createComprobante(); $comprobante->addConcepto([ 'Importe' => '1000', ])->addTraslado([ 'Base' => '1000', 'Impuesto' => '002', 'TipoFactor' => 'Tasa', 'TasaOCuota' => '0.000000', 'Importe' => '0', ]); $comprobante->addConcepto([ 'Importe' => '2000', ])->addTraslado([ 'Base' => '2000', 'Impuesto' => '002', 'TipoFactor' => 'Tasa', 'TasaOCuota' => '0.000000', 'Importe' => '0', ]); $sumasConceptos = new SumasConceptos($comprobante, $precision); $writer = new SumasConceptosWriter($comprobante, $sumasConceptos, $precision); $writer->put(); $this->assertSame('3000.00', $comprobante['SubTotal']); $this->assertFalse(isset($comprobante['Descuento'])); $this->assertSame('3000.00', $comprobante['Total']); $this->assertNotNull($comprobante->searchNode('cfdi:Impuestos')); $impuestos = $comprobante->getImpuestos(); $this->assertTrue(isset($impuestos['TotalImpuestosTrasladados'])); $this->assertSame('0.00', $impuestos['TotalImpuestosTrasladados']); $this->assertFalse(isset($impuestos['TotalImpuestosRetenidos'])); } public function testPutWithConceptosImpuestos(): void { $precision = 2; $comprobante = $this->createComprobante(); $comprobante->addConcepto([ 'Importe' => '2000', 'Descuento' => '1000', ])->addTraslado([ 'Base' => '1000', 'Impuesto' => '002', 'TipoFactor' => 'Tasa', 'TasaOCuota' => '0.160000', 'Importe' => '160', ]); $comprobante->addConcepto([ 'Importe' => '4000', 'Descuento' => '2000', ])->addTraslado([ 'Base' => '2000', 'Impuesto' => '002', 'TipoFactor' => 'Tasa', 'TasaOCuota' => '0.160000', 'Importe' => '320', ]); $sumasConceptos = new SumasConceptos($comprobante, $precision); $writer = new SumasConceptosWriter($comprobante, $sumasConceptos, $precision); $writer->put(); $this->assertSame('6000.00', $comprobante['SubTotal']); $this->assertSame('3000.00', $comprobante['Descuento']); $this->assertSame('3480.00', $comprobante['Total']); $this->assertNotNull($comprobante->searchNode('cfdi:Impuestos')); $impuestos = $comprobante->getImpuestos(); $this->assertTrue(isset($impuestos['TotalImpuestosTrasladados'])); $this->assertSame('480.00', $impuestos['TotalImpuestosTrasladados']); $this->assertFalse(isset($impuestos['TotalImpuestosRetenidos'])); } public function testDescuentoWithValueZeroExistsIfAConceptoHasDescuento(): void { $comprobante = $this->createComprobante(); $comprobante->addConcepto([]); // first concepto does not have Descuento $comprobante->addConcepto(['Descuento' => '']); // second concepto has Descuento $precision = 2; $sumasConceptos = new SumasConceptos($comprobante, $precision); $writer = new SumasConceptosWriter($comprobante, $sumasConceptos, $precision); $writer->put(); $this->assertSame('0.00', $comprobante['Descuento']); } public function testDescuentoNotSetIfAllConceptosDoesNotHaveDescuento(): void { $comprobante = $this->createComprobante(['Descuento' => '']); // set value with discount $comprobante->addConcepto(); // first concepto does not have Descuento $comprobante->addConcepto(); // second concepto does not have Descuento neither $precision = 2; $sumasConceptos = new SumasConceptos($comprobante, $precision); $writer = new SumasConceptosWriter($comprobante, $sumasConceptos, $precision); $writer->put(); // the Comprobante@Descuento attribute must not exist since there is no Descuento in concepts $this->assertFalse(isset($comprobante['Descuento'])); } public function testOnComplementoImpuestosImporteSumIsRoundedCfdi(): void { $comprobante = $this->createComprobante(); $comprobante->addConcepto()->multiTraslado( [ 'Base' => '48.611106', 'Importe' => '7.777777', 'Impuesto' => '002', 'TipoFactor' => 'Tasa', 'TasaOCuota' => '0.160000', ], [ 'Base' => '48.611106', 'Impuesto' => '002', 'TipoFactor' => 'Exento', ], ); $comprobante->addConcepto()->multiTraslado( [ 'Base' => '13.888888', 'Importe' => '2.222222', 'Impuesto' => '002', 'TipoFactor' => 'Tasa', 'TasaOCuota' => '0.160000', ], [ 'Base' => '13.888888', 'Impuesto' => '002', 'TipoFactor' => 'Exento', ], ); $precision = 3; $sumasConceptos = new SumasConceptos($comprobante, $precision); $writer = new SumasConceptosWriter($comprobante, $sumasConceptos, $precision); $writer->put(); $traslado = $comprobante->searchNode('cfdi:Impuestos', 'cfdi:Traslados', 'cfdi:Traslado'); $this->assertSame('10.000', $comprobante->searchAttribute('cfdi:Impuestos', 'TotalImpuestosTrasladados')); $this->assertSame('10.000', $traslado['Importe']); if ($writer->hasWriteImpuestoBase()) { $this->assertSame('62.500', $traslado['Base']); } else { $this->assertFalse(isset($traslado['Base'])); } if ($writer->hasWriteExentos()) { $exento = $comprobante->searchNodes('cfdi:Impuestos', 'cfdi:Traslados', 'cfdi:Traslado')->get(1); $this->assertSame('62.500', $exento['Base']); } } public function testConceptosOnlyWithTrasladosExentosDoesNotWriteTraslados(): void { $comprobante = $this->createComprobante(); $concepto = $comprobante->addConcepto(); $concepto->addTraslado(['Base' => '1000', 'Impuesto' => '002', 'TipoFactor' => 'Exento']); $concepto->addRetencion([ 'Base' => '1000.00', 'Impuesto' => '001', 'TipoFactor' => 'Tasa', 'TasaOCuota' => '0.04000', 'Importe' => '40.00', ]); $comprobante->addConcepto()->addTraslado(['Base' => '1000', 'Impuesto' => '002', 'TipoFactor' => 'Exento']); $precision = 2; $sumasConceptos = new SumasConceptos($comprobante, $precision); $writer = new SumasConceptosWriter($comprobante, $sumasConceptos, $precision); $writer->put(); $this->assertSame( $writer->hasWriteExentos(), $writer->hasWriteImpuestoBase(), 'When has to write "exentos" also has to write "impuesto base" and vice versa' ); if ($writer->hasWriteExentos()) { $expected = <<<EOT <cfdi:Impuestos TotalImpuestosRetenidos="40.00"> <cfdi:Retenciones> <cfdi:Retencion Impuesto="001" Importe="40.00"/> </cfdi:Retenciones> <cfdi:Traslados> <cfdi:Traslado Impuesto="002" Base="2000.00" TipoFactor="Exento"/> </cfdi:Traslados> </cfdi:Impuestos> EOT; } else { $expected = <<<EOT <cfdi:Impuestos TotalImpuestosRetenidos="40.00"> <cfdi:Retenciones> <cfdi:Retencion Impuesto="001" Importe="40.00"/> </cfdi:Retenciones> </cfdi:Impuestos> EOT; } $this->assertXmlStringEqualsXmlString($expected, XmlNodeUtils::nodeToXmlString($comprobante->getImpuestos())); } public function testSetRequiredImpLocalAttributes(): void { $comprobante = $this->createComprobante(); $impLocal = new ImpuestosLocales(); for ($i = 0; $i < 2; $i++) { $impLocal->addTrasladoLocal([ 'ImpLocTrasladado' => 'IH', 'Importe' => '27.43', 'TasadeTraslado' => '2.50', ]); $impLocal->addRetencionLocal([ 'ImpLocTrasladado' => 'IH', 'Importe' => '27.43', 'TasadeTraslado' => '2.50', ]); } $comprobante->addComplemento($impLocal); $precision = 2; $sumas = new SumasConceptos($comprobante, $precision); $writer = new SumasConceptosWriter($comprobante, $sumas, $precision); $writer->put(); $this->assertSame('54.86', $impLocal->attributes()->get('TotaldeRetenciones')); $this->assertSame('54.86', $impLocal->attributes()->get('TotaldeTraslados')); } public function testRemoveImpLocalComplementWhenIsEmptyAndPreservesOthersComplements(): void { $comprobante = $this->createComprobante(); $comprobante->addComplemento(new Node('other:PrimerComplemento')); $comprobante->addComplemento(new ImpuestosLocales()); $comprobante->addComplemento(new Node('other:UltimoComplemento')); $precision = 2; $sumas = new SumasConceptos($comprobante, $precision); $writer = new SumasConceptosWriter($comprobante, $sumas, $precision); $writer->put(); $this->assertCount(2, $comprobante->getComplemento()); $this->assertNotNull($comprobante->searchNode('cfdi:Complemento', 'other:PrimerComplemento')); $this->assertNotNull($comprobante->searchNode('cfdi:Complemento', 'other:UltimoComplemento')); $this->assertNull($comprobante->searchNode('cfdi:Complemento', 'implocal:ImpuestosLocales')); } public function testRemoveImpLocalComplementAndRemoveComplementoNodeWhenIsEmpty(): void { $comprobante = $this->createComprobante(); $comprobante->addComplemento(new ImpuestosLocales()); $precision = 2; $sumas = new SumasConceptos($comprobante, $precision); $writer = new SumasConceptosWriter($comprobante, $sumas, $precision); $writer->put(); $this->assertNull($comprobante->searchNode('cfdi:Complemento')); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/XmlResolver/XmlResolverPropertyTraitTest.php
tests/CfdiUtilsTests/XmlResolver/XmlResolverPropertyTraitTest.php
<?php namespace CfdiUtilsTests\XmlResolver; use CfdiUtils\XmlResolver\XmlResolver; use CfdiUtils\XmlResolver\XmlResolverPropertyInterface; use CfdiUtils\XmlResolver\XmlResolverPropertyTrait; use CfdiUtilsTests\TestCase; final class XmlResolverPropertyTraitTest extends TestCase { private XmlResolverPropertyInterface $specimen; protected function setUp(): void { parent::setUp(); $this->specimen = new class () implements XmlResolverPropertyInterface { use XmlResolverPropertyTrait; }; } public function testInitialState(): void { $this->assertFalse($this->specimen->hasXmlResolver()); } public function testGetterFailsOnInitialState(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('There is no current xmlResolver'); $this->specimen->getXmlResolver(); } public function testSetterToValueAndToNull(): void { $xmlResolver = new XmlResolver(); $this->specimen->setXmlResolver($xmlResolver); $this->assertTrue($this->specimen->hasXmlResolver()); $this->specimen->setXmlResolver(null); $this->assertFalse($this->specimen->hasXmlResolver()); } public function testGetterFailsAfterSettingResolverToNull(): void { $xmlResolver = new XmlResolver(); $this->specimen->setXmlResolver($xmlResolver); $this->assertTrue($this->specimen->hasXmlResolver()); $this->specimen->setXmlResolver(null); $this->expectException(\LogicException::class); $this->expectExceptionMessage('There is no current xmlResolver'); $this->specimen->getXmlResolver(); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/XmlResolver/XmlResolverTest.php
tests/CfdiUtilsTests/XmlResolver/XmlResolverTest.php
<?php namespace CfdiUtilsTests\XmlResolver; use CfdiUtils\Certificado\SatCertificateNumber; use CfdiUtils\XmlResolver\XmlResolver; use CfdiUtilsTests\TestCase; use Eclipxe\XmlResourceRetriever\Downloader\DownloaderInterface; final class XmlResolverTest extends TestCase { public function testConstructor(): void { $resolver = new XmlResolver(); $this->assertEquals($resolver->defaultLocalPath(), $resolver->getLocalPath()); $this->assertTrue($resolver->hasLocalPath()); $this->assertInstanceOf(DownloaderInterface::class, $resolver->getDownloader()); } public function testSetLocalPath(): void { $default = XmlResolver::defaultLocalPath(); $customPath = '/temporary/resources/'; // constructed $resolver = new XmlResolver(); $this->assertEquals($default, $resolver->getLocalPath()); $this->assertTrue($resolver->hasLocalPath()); // change to empty '' (disable) $resolver->setLocalPath(''); $this->assertEquals('', $resolver->getLocalPath()); $this->assertFalse($resolver->hasLocalPath()); // change to custom value $resolver->setLocalPath($customPath); $this->assertEquals($customPath, $resolver->getLocalPath()); $this->assertTrue($resolver->hasLocalPath()); // change to default value $resolver->setLocalPath(null); $this->assertEquals($default, $resolver->getLocalPath()); $this->assertTrue($resolver->hasLocalPath()); } public function testRetrieveWithoutLocalPath(): void { $resolver = new XmlResolver(''); $this->assertFalse($resolver->hasLocalPath()); $resource = 'http://example.com/schemas/example.xslt'; $this->assertEquals($resource, $resolver->resolve($resource)); } /* * This test will download xslt for cfdi 3.3 from * http://www.sat.gob.mx/sitio_internet/cfd/3/cadenaoriginal_3_3/cadenaoriginal_3_3.xslt * and all its relatives and put it in the default path of XmlResolver (project root + build + resources) */ public function testRetrieveWithDefaultLocalPath(): void { $resolver = new XmlResolver(); $this->assertTrue($resolver->hasLocalPath()); $endpoint = 'http://www.sat.gob.mx/sitio_internet/cfd/3/cadenaoriginal_3_3/cadenaoriginal_3_3.xslt'; $localResource = $resolver->resolve($endpoint); $this->assertNotEmpty($localResource); $this->assertFileExists($localResource); } public function testResolveThrowsExceptionWhenUnknownResourceIsSet(): void { $resolver = new XmlResolver(); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Unable to handle the resource'); $resolver->resolve('http://example.org/example.xml'); } public function providerObtainTypeFromUrl(): array { return [ 'xsd' => ['http://example.com/resource.xsd', XmlResolver::TYPE_XSD], 'xlst' => ['http://example.com/resource.xslt', XmlResolver::TYPE_XSLT], 'cer' => ['http://example.com/resource.cer', XmlResolver::TYPE_CER], 'unknown' => ['http://example.com/resource.xml', ''], 'empty' => ['', ''], 'end with xml but no extension' => ['http://example.com/xml', ''], ]; } /** * @dataProvider providerObtainTypeFromUrl */ public function testObtainTypeFromUrl(string $url, string $expectedType): void { $resolver = new XmlResolver(); $this->assertEquals($expectedType, $resolver->obtainTypeFromUrl($url)); } public function testResolveCerFileWithExistentFile(): void { // preinstall certificate to avoid the download $localPath = $this->installCertificate($this->utilAsset('certs/20001000000300022779.cer')); $certificateId = '20001000000300022779'; $cerNumber = new SatCertificateNumber($certificateId); $resolver = new XmlResolver(); $remoteUrl = $cerNumber->remoteUrl(); // this downloader will throw an exception if downloadTo is called $nullDownloader = new class () implements DownloaderInterface { public function downloadTo(string $source, string $destination): void { throw new \RuntimeException("$source will not be downloaded to $destination"); } }; // set the downloader into the resolver $resolver->setDownloader($nullDownloader); // call to resolve, it must not throw an exception $resolvedPath = $resolver->resolve($remoteUrl, $resolver::TYPE_CER); $this->assertSame($localPath, $resolvedPath); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Certificado/CertificadoTest.php
tests/CfdiUtilsTests/Certificado/CertificadoTest.php
<?php namespace CfdiUtilsTests\Certificado; use CfdiUtils\Certificado\Certificado; use CfdiUtilsTests\TestCase; final class CertificadoTest extends TestCase { public function testConstructWithValidExample(): void { // information checked using // openssl x509 -nameopt utf8,sep_multiline,lname -inform DER -noout -dates -serial -subject \ // -fingerprint -pubkey -in tests/assets/certs/EKU9003173C9.cer $expectedPublicKey = <<< EOD -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtmecO6n2GS0zL025gbHG QVxznPDICoXzR2uUngz4DqxVUC/w9cE6FxSiXm2ap8Gcjg7wmcZfm85EBaxCx/0J 2u5CqnhzIoGCdhBPuhWQnIh5TLgj/X6uNquwZkKChbNe9aeFirU/JbyN7Egia9oK H9KZUsodiM/pWAH00PCtoKJ9OBcSHMq8Rqa3KKoBcfkg1ZrgueffwRLws9yOcRWL b02sDOPzGIm/jEFicVYt2Hw1qdRE5xmTZ7AGG0UHs+unkGjpCVeJ+BEBn0JPLWVv DKHZAQMj6s5Bku35+d/MyATkpOPsGT/VTnsouxekDfikJD1f7A1ZpJbqDpkJnss3 vQIDAQAB -----END PUBLIC KEY----- EOD; $cerfile = $this->utilAsset('certs/EKU9003173C9.cer'); $certificado = new Certificado($cerfile); $this->assertSame($cerfile, $certificado->getFilename()); $certificateName = implode('', [ '/CN=ESCUELA KEMPER URGATE SA DE CV', '/name=ESCUELA KEMPER URGATE SA DE CV', '/O=ESCUELA KEMPER URGATE SA DE CV', '/x500UniqueIdentifier=EKU9003173C9 / VADA800927DJ3', '/serialNumber= / VADA800927HSRSRL05', '/OU=Sucursal 1', ]); $this->assertSame($certificateName, str_replace('\/', '/', $certificado->getCertificateName())); $this->assertSame('ESCUELA KEMPER URGATE SA DE CV', $certificado->getName()); $this->assertSame('ESCUELA KEMPER URGATE', $certificado->getName(true)); $this->assertSame('EKU9003173C9', $certificado->getRfc()); $this->assertSame('30001000000500003416', $certificado->getSerial()); $this->assertSame( '3330303031303030303030353030303033343136', $certificado->getSerialObject()->getHexadecimal() ); $this->assertSame(strtotime('2023-05-18T11:43:51+00:00'), $certificado->getValidFrom()); $this->assertSame(strtotime('2027-05-18T11:43:51+00:00'), $certificado->getValidTo()); $this->assertSame($expectedPublicKey, $certificado->getPubkey()); } public function testVerifyWithKnownData(): void { $dataFile = $this->utilAsset('certs/data-to-sign.txt'); $signatureFile = $this->utilAsset('certs/data-sha256.bin'); $certificadoFile = $this->utilAsset('certs/EKU9003173C9.cer'); $certificado = new Certificado($certificadoFile); $verify = $certificado->verify( str_replace("\r\n", "\n", strval(file_get_contents($dataFile))), strval(file_get_contents($signatureFile)) ); $this->assertTrue($verify); } public function testConstructUsingPemContents(): void { $pemfile = $this->utilAsset('certs/EKU9003173C9.cer.pem'); $contents = file_get_contents($pemfile) ?: ''; $fromFile = new Certificado($pemfile); $fromContents = new Certificado($contents); $this->assertSame($fromFile->getPemContents(), $fromContents->getPemContents()); } public function testVerifyWithInvalidData(): void { $dataFile = $this->utilAsset('certs/data-to-sign.txt'); $signatureFile = $this->utilAsset('certs/data-sha256.bin'); $certificadoFile = $this->utilAsset('certs/EKU9003173C9.cer'); $certificado = new Certificado($certificadoFile); $verify = $certificado->verify( strval(file_get_contents($dataFile)) . 'THIS IS MORE CONTENT!', strval(file_get_contents($signatureFile)) ); $this->assertFalse($verify); } public function testConstructWithUnreadableFile(): void { $badCertificateFile = $this->utilAsset(''); $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage('does not exists'); new Certificado($badCertificateFile); } public function testConstructWithEmptyFile(): void { $badCertificateFile = $this->utilAsset('empty.bin'); $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage('empty'); new Certificado($badCertificateFile); } public function testConstructWithNonExistentFile(): void { $badCertificateFile = $this->utilAsset('file-does-not-exists'); $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage('does not exists or is not readable'); new Certificado($badCertificateFile); } public function testConstructWithBadCertificate(): void { $badCertificateFile = $this->utilAsset('certs/certificate-with-error.pem'); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Cannot parse the certificate file'); new Certificado($badCertificateFile); } public function testConstructCertificateUsingPathThatIsBase64(): void { $workingdir = $this->utilAsset('certs/'); $previousPath = getcwd(); chdir($workingdir); try { $certificate = new Certificado('EKU9003173C9.cer'); $this->assertSame('30001000000500003416', $certificate->getSerial()); } finally { chdir($previousPath); } } public function testConstructWithDerCertificateContentsThrowsException(): void { $file = $this->utilAsset('certs/EKU9003173C9.cer'); $this->expectException(\UnexpectedValueException::class); new Certificado(file_get_contents($file) ?: ''); } public function testBelogsToReturnsTrueWithItsCertificate(): void { $certificateFile = $this->utilAsset('certs/EKU9003173C9.cer'); $pemKeyFile = $this->utilAsset('certs/EKU9003173C9.key.pem'); $certificate = new Certificado($certificateFile); $this->assertTrue($certificate->belongsTo($pemKeyFile)); } public function testBelogsToReturnsFalseWithOtherKey(): void { // the cer file is different from previous test $certificateFile = $this->utilAsset('certs/CSD09_AAA010101AAA.cer'); $pemKeyFile = $this->utilAsset('certs/EKU9003173C9.key.pem'); $certificate = new Certificado($certificateFile); $this->assertFalse($certificate->belongsTo($pemKeyFile)); } public function testBelongsToWithPasswordProtectedFile(): void { $certificateFile = $this->utilAsset('certs/EKU9003173C9.cer'); $pemKeyFile = $this->utilAsset('certs/EKU9003173C9_password.key.pem'); $certificate = new Certificado($certificateFile); $this->assertTrue($certificate->belongsTo($pemKeyFile, '12345678a')); } public function testBelongsToWithPasswordProtectedFileButWrongPassword(): void { $certificateFile = $this->utilAsset('certs/EKU9003173C9.cer'); $pemKeyFile = $this->utilAsset('certs/EKU9003173C9_password.key.pem'); $certificate = new Certificado($certificateFile); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Cannot open the private key file'); $certificate->belongsTo($pemKeyFile, 'xxxxxxxxx'); } public function testBelongsToWithEmptyFile(): void { $certificateFile = $this->utilAsset('certs/EKU9003173C9.cer'); $pemKeyFile = $this->utilAsset('empty.bin'); $certificate = new Certificado($certificateFile); $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage('is not a PEM private key'); $certificate->belongsTo($pemKeyFile); } public function testCanReadRfcFromCertificateWhenX500UniqueIdentifierOnlyContainsRfcAndNoCurp(): void { $certificateFile = $this->utilAsset('certs/00001000000301246267.cer'); $certificate = new Certificado($certificateFile); $this->assertEquals('SOMG790807J57', $certificate->getRfc()); } public function testGetSerialObjectReturnsACopyOfTheObjectInsteadTheSameObject(): void { // remove this test on version 3 when the object SerialNumber is immutable $certificateFile = $this->utilAsset('certs/EKU9003173C9.cer'); $certificate = new Certificado($certificateFile); $first = $certificate->getSerialObject(); $second = $certificate->getSerialObject(); $this->assertEquals($first, $second); $this->assertNotSame($first, $second); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Certificado/SerialNumberTest.php
tests/CfdiUtilsTests/Certificado/SerialNumberTest.php
<?php namespace CfdiUtilsTests\Certificado; use CfdiUtils\Certificado\SerialNumber; use PHPUnit\Framework\TestCase; final class SerialNumberTest extends TestCase { public function testAsDecimalAsAscii(): void { $input = '3330303031303030303030333030303233373038'; $expectedDecimal = '292233162870206001759766198425879490508935868472'; $expectedAscii = '30001000000300023708'; $serial = new SerialNumber($input); $this->assertSame($input, $serial->getHexadecimal()); $this->assertSame($expectedDecimal, $serial->asDecimal()); $this->assertSame($expectedAscii, $serial->asAscii()); } /** * @testWith ["3330303031303030303030333030303233373038", "30001000000300023708"] */ public function testLoadHexadecimal(string $input, string $expected): void { $serial = new SerialNumber(''); $serial->loadHexadecimal($input); $this->assertSame($input, $serial->getHexadecimal()); $this->assertSame($expected, $serial->asAscii()); } public function testLoadHexadecimalInvalidInput(): void { $serial = new SerialNumber(''); $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage('invalid characters'); $serial->loadHexadecimal('X'); } /** * @testWith ["0x3330303031303030303030333030303233373038", "30001000000300023708"] * ["292233162870206001759766198425879490508935868472", "30001000000300023708"] */ public function testLoadDecimal(string $input, string $expected): void { $serial = new SerialNumber(''); $serial->loadDecimal($input); $this->assertSame($expected, $serial->asAscii()); } /** * @testWith ["30001000000300023708", "3330303031303030303030333030303233373038"] */ public function testLoadAscii(string $input, string $expected): void { $serial = new SerialNumber(''); $serial->loadAscii($input); $this->assertSame($expected, $serial->getHexadecimal()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Certificado/SatCertificateNumberTest.php
tests/CfdiUtilsTests/Certificado/SatCertificateNumberTest.php
<?php namespace CfdiUtilsTests\Certificado; use CfdiUtils\Certificado\SatCertificateNumber; use CfdiUtilsTests\TestCase; final class SatCertificateNumberTest extends TestCase { public function providerValidNumbers(): array { return [ ['00000000000000000000'], ['98765432109876543210'], ]; } public function providerInvalidNumbers(): array { return [ 'empty' => [''], 'with-non-digits' => ['A0000000000000000000'], 'length 19' => ['0000000000000000000'], 'length 21' => ['000000000000000000000'], ]; } /** * @dataProvider providerValidNumbers */ public function testIsValidCertificateNumberWithCorrectValues(string $value): void { $this->assertSame(true, SatCertificateNumber::isValidCertificateNumber($value)); $number = new SatCertificateNumber($value); $this->assertSame($value, $number->number()); $this->assertStringEndsWith($value . '.cer', $number->remoteUrl()); } /** * @dataProvider providerInvalidNumbers */ public function testIsValidCertificateNumberWithIncorrectValues(string $value): void { $this->assertSame(false, SatCertificateNumber::isValidCertificateNumber($value)); $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage('The certificate number is not correct'); new SatCertificateNumber($value); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Certificado/CerRetrieverTest.php
tests/CfdiUtilsTests/Certificado/CerRetrieverTest.php
<?php namespace CfdiUtilsTests\Certificado; use CfdiUtils\Certificado\Certificado; use CfdiUtils\Certificado\SatCertificateNumber; use CfdiUtilsTests\TestCase; final class CerRetrieverTest extends TestCase { public function testRetrieveNonExistent(): void { // this certificate does not exists in the internet repository, it will fail to download $certificateId = '20001000000300022779'; $cerNumber = new SatCertificateNumber($certificateId); $retriever = $this->newResolver()->newCerRetriever(); $remoteUrl = $cerNumber->remoteUrl(); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage($remoteUrl); $retriever->retrieve($remoteUrl); } public function testRetrieveValidCertificate(): void { // NOTE: This certificate is valid until 2021-05-22 12:42:41 // after this date this test may fail $certificateId = '00001000000406258094'; $cerNumber = new SatCertificateNumber($certificateId); $retriever = $this->newResolver()->newCerRetriever(); $retriever->setDownloader(new CertificateDownloaderHelper()); $remoteUrl = $cerNumber->remoteUrl(); $localPath = $retriever->buildPath($remoteUrl); if (file_exists($localPath)) { unlink($localPath); } $this->assertFileDoesNotExist($localPath); $retriever->retrieve($remoteUrl); $this->assertFileExists($localPath); $certificate = new Certificado($localPath); $this->assertSame($certificateId, $certificate->getSerial()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Certificado/NodeCertificadoTest.php
tests/CfdiUtilsTests/Certificado/NodeCertificadoTest.php
<?php namespace CfdiUtilsTests\Certificado; use CfdiUtils\Certificado\NodeCertificado; use CfdiUtils\Internals\TemporaryFile; use CfdiUtils\Nodes\XmlNodeUtils; use CfdiUtilsTests\TestCase; final class NodeCertificadoTest extends TestCase { private function createNodeCertificado(string $contents): NodeCertificado { return new NodeCertificado(XmlNodeUtils::nodeFromXmlString($contents)); } public function testExtractWithWrongVersion(): void { $nodeCertificado = $this->createNodeCertificado( '<cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" Version="1.9.80"' . '/>' ); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Unsupported or unknown version'); $nodeCertificado->extract(); } public function testExtractWithEmptyCertificate(): void { $nodeCertificado = $this->createNodeCertificado( '<cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" Version="3.3"' . '/>' ); $this->assertEmpty($nodeCertificado->extract()); } public function testExtractWithMalformedBase64(): void { $nodeCertificado = $this->createNodeCertificado( '<cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" Version="3.3" Certificado="ñ"' . '/>' ); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('The certificado attribute is not a valid base64 encoded string'); $nodeCertificado->extract(); } public function testExtract(): void { $expectedExtract = 'foo'; $nodeCertificado = $this->createNodeCertificado( '<cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" Version="3.3" Certificado="Zm9v"' . '/>' ); $this->assertSame($expectedExtract, $nodeCertificado->extract()); } public function testSaveWithEmptyFilename(): void { $nodeCertificado = $this->createNodeCertificado( '<cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" Version="3.3" Certificado="Zm9v"' . '/>' ); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('The filename to store the certificate is empty'); $nodeCertificado->save(''); } public function testSaveWithEmptyCertificado(): void { $nodeCertificado = $this->createNodeCertificado( '<cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" Version="3.3"' . '/>' ); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('The certificado attribute is empty'); $nodeCertificado->save(__DIR__); } public function testSaveWithUnwritableFilename(): void { $nodeCertificado = $this->createNodeCertificado( '<cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" Version="3.3" Certificado="Zm9v"' . '/>' ); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Unable to write the certificate contents'); $nodeCertificado->save(__DIR__); } public function testSave(): void { $rawText = 'foo'; $base64 = base64_encode($rawText); $nodeCertificado = $this->createNodeCertificado(<<<XML <cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" Version="3.3" Certificado="$base64"/> XML); $temporaryFile = TemporaryFile::create(); $nodeCertificado->save($temporaryFile->getPath()); $this->assertStringEqualsFile($temporaryFile->getPath(), $rawText); $temporaryFile->remove(); } public function testObtain(): void { $cfdiSample = $this->utilAsset('cfdi32-real.xml'); $nodeCertificado = $this->createNodeCertificado(strval(file_get_contents($cfdiSample))); $certificate = $nodeCertificado->obtain(); $this->assertEmpty($certificate->getFilename()); $this->assertEquals('CTO021007DZ8', $certificate->getRfc()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Certificado/CertificadoPropertyTest.php
tests/CfdiUtilsTests/Certificado/CertificadoPropertyTest.php
<?php namespace CfdiUtilsTests\Certificado; use CfdiUtils\Certificado\Certificado; use CfdiUtils\Certificado\CertificadoPropertyInterface; use CfdiUtils\Certificado\CertificadoPropertyTrait; use CfdiUtilsTests\TestCase; final class CertificadoPropertyTest extends TestCase { public function testCertificadoProperty(): void { $implementation = new class () implements CertificadoPropertyInterface { use CertificadoPropertyTrait; }; $this->assertFalse($implementation->hasCertificado()); $certificado = new Certificado($this->utilAsset('certs/EKU9003173C9.cer')); $implementation->setCertificado($certificado); $this->assertTrue($implementation->hasCertificado()); $this->assertSame($certificado, $implementation->getCertificado()); $implementation->setCertificado(); $this->assertFalse($implementation->hasCertificado()); $this->expectException(\LogicException::class); $this->expectExceptionMessage('current certificado'); $implementation->getCertificado(); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Certificado/CertificateDownloaderHelper.php
tests/CfdiUtilsTests/Certificado/CertificateDownloaderHelper.php
<?php namespace CfdiUtilsTests\Certificado; use Eclipxe\XmlResourceRetriever\Downloader\DownloaderInterface; use Exception; /** * This class is a wrapper around PhpDownloader to retry the download if it fails (for any reason). * * The reason behind this is that the web server at https://rdc.sat.gob.mx/ * has issues, and sometimes it does not respond with the certificate file. * * @see https://www.phpcfdi.com/sat/problemas-conocidos/descarga-certificados/ */ final class CertificateDownloaderHelper implements DownloaderInterface { public const MAX_DOWNLOAD_ATTEMPTS = 8; public function downloadTo(string $source, string $destination): void { $attempt = 1; while (true) { try { $this->realDownloadTo($source, $destination); break; } catch (Exception $exception) { if (self::MAX_DOWNLOAD_ATTEMPTS === $attempt) { throw new Exception("Unable to download $source to $destination", 0, $exception); } $attempt = $attempt + 1; continue; } } } private function realDownloadTo(string $source, string $destination): void { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $source); curl_setopt($ch, CURLOPT_VERBOSE, false); // set to true to debug curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_setopt($ch, CURLOPT_HEADER, false); $result = (string) curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ('' === $result) { throw new Exception('Response is empty'); } if (! is_scalar($status)) { throw new Exception('Invalid status code'); } $status = (int) $status; if (200 !== $status) { throw new Exception('Status code is not 200'); } if (false === @file_put_contents($destination, $result)) { throw new Exception('Cannot save certificate on destination'); } } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Validate/AssertsTest.php
tests/CfdiUtilsTests/Validate/AssertsTest.php
<?php namespace CfdiUtilsTests\Validate; use CfdiUtils\Validate\Assert; use CfdiUtils\Validate\Asserts; use CfdiUtils\Validate\Status; use PHPUnit\Framework\TestCase; final class AssertsTest extends TestCase { public function testConstructor(): void { $asserts = new Asserts(); $this->assertInstanceOf(\Countable::class, $asserts); $this->assertInstanceOf(\Traversable::class, $asserts); $this->assertCount(0, $asserts); $this->assertSame(false, $asserts->hasErrors()); } public function testMustStop(): void { $asserts = new Asserts(); // initialized on false $this->assertSame(false, $asserts->mustStop()); // set to true return previous status false $this->assertSame(false, $asserts->mustStop(true)); // current status is true $this->assertSame(true, $asserts->mustStop()); // set true return current status true $this->assertSame(true, $asserts->mustStop(true)); // set false return current status true $this->assertSame(true, $asserts->mustStop(false)); // check again current status false $this->assertSame(false, $asserts->mustStop()); } public function testAddError(): void { $asserts = new Asserts(); $first = new Assert('TEST', 'test', Status::error()); $asserts->add($first); $this->assertCount(1, $asserts); $this->assertSame(true, $asserts->hasErrors()); $this->assertSame(true, $asserts->hasStatus(Status::error())); $this->assertSame($first, $asserts->getFirstStatus(Status::error())); $second = new Assert('TEST', 'test', Status::ok()); // this will set the new object in the index TEST without change the previous status $asserts->add($second); $this->assertCount(1, $asserts); $this->assertSame('test', $first->getTitle()); $this->assertEquals(Status::error(), $first->getStatus()); $this->assertNull($asserts->getFirstStatus(Status::error())); $this->assertSame($second, $asserts->getFirstStatus(Status::ok())); // this will not remove anything since this object will not be found $asserts->remove($first); $this->assertCount(1, $asserts); // but now it will remove it since the same object is in the collection $asserts->remove($second); $this->assertCount(0, $asserts); } public function testPutAndPutStatus(): void { $asserts = new Asserts(); // test insert by put $first = $asserts->put('X01'); $this->assertCount(1, $asserts); // test insert by put $second = $asserts->put('X02'); $this->assertCount(2, $asserts); // test insert by put on an existing key $retrievedOnOverride = $asserts->put('X01', 'title', Status::warn(), 'explanation'); $this->assertCount(2, $asserts); $this->assertSame($first, $retrievedOnOverride); $this->assertEquals('title', $first->getTitle()); $this->assertEquals('explanation', $first->getExplanation()); $this->assertEquals(Status::warn(), $first->getStatus()); $this->assertSame($first, $asserts->get('X01')); // test put status on an existing key $asserts->putStatus('X02', Status::ok(), 'baz baz baz'); $this->assertEquals('baz baz baz', $second->getExplanation()); $this->assertEquals(Status::ok(), $second->getStatus()); $this->assertSame($second, $asserts->get('X02')); // test put status on a non existing key $third = $asserts->putStatus('X03', Status::error(), 'third element'); $this->assertCount(3, $asserts); $this->assertEquals('', $third->getTitle()); $this->assertEquals('third element', $third->getExplanation()); $this->assertEquals(Status::error(), $third->getStatus()); $this->assertSame($third, $asserts->get('X03')); } public function testGetWithNotExistentStatus(): void { $asserts = new Asserts(); $this->expectException(\RuntimeException::class); $asserts->get('X02'); } public function testGetByStatus(): void { $oks = [ 'OK01' => Status::ok(), 'OK02' => Status::ok(), ]; $errors = [ 'ERROR01' => Status::error(), 'ERROR02' => Status::error(), ]; $warnings = [ 'WARN01' => Status::warn(), 'WARN02' => Status::warn(), ]; $nones = [ 'NONE01' => Status::none(), 'NONE02' => Status::none(), ]; $assertsContents = $oks + $errors + $warnings + $nones; $asserts = new Asserts(); foreach ($assertsContents as $code => $status) { $asserts->putStatus($code, $status); } $this->assertCount(8, $asserts); $this->assertEquals(array_keys($oks), array_keys($asserts->byStatus(Status::ok()))); $this->assertEquals(array_keys($errors), array_keys($asserts->byStatus(Status::error()))); $this->assertEquals(array_keys($warnings), array_keys($asserts->byStatus(Status::warn()))); $this->assertEquals(array_keys($nones), array_keys($asserts->byStatus(Status::none()))); $this->assertEquals(array_keys($oks), array_keys($asserts->oks())); $this->assertEquals(array_keys($errors), array_keys($asserts->errors())); $this->assertEquals(array_keys($warnings), array_keys($asserts->warnings())); $this->assertEquals(array_keys($nones), array_keys($asserts->nones())); } public function testRemoveByCode(): void { $asserts = new Asserts(); $asserts->putStatus('XXX'); $this->assertCount(1, $asserts); $asserts->removeByCode('FOO'); $this->assertCount(1, $asserts); $asserts->removeByCode('XXX'); $this->assertCount(0, $asserts); } public function testRemoveAll(): void { $asserts = new Asserts(); foreach (range(1, 5) as $i) { $asserts->putStatus(strval($i)); } $this->assertCount(5, $asserts); $asserts->removeAll(); $this->assertCount(0, $asserts); } public function testImport(): void { $source = new Asserts(); $source->mustStop(true); foreach (range(1, 5) as $i) { $source->putStatus(strval($i)); } $destination = new Asserts(); $destination->import($source); $this->assertCount(5, $destination); // when importing the assert objects are cloned (not the same but equal) $firstSource = $source->get('1'); $firstDestination = $destination->get('1'); $this->assertNotSame($firstSource, $firstDestination); $this->assertEquals($firstSource, $firstDestination); $this->assertSame($source->mustStop(), $destination->mustStop()); // import again but with muststop as false $source->mustStop(false); $destination->import($source); $this->assertCount(5, $destination); $this->assertSame($source->mustStop(), $destination->mustStop()); } public function testTraversable(): void { $asserts = new Asserts(); $first = $asserts->putStatus('first'); $second = $asserts->putStatus('second'); $third = $asserts->putStatus('third'); $currentAsserts = []; foreach ($asserts as $assert) { $currentAsserts[] = $assert; } $this->assertSame($first, $currentAsserts[0]); $this->assertSame($second, $currentAsserts[1]); $this->assertSame($third, $currentAsserts[2]); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Validate/Validate33TestCase.php
tests/CfdiUtilsTests/Validate/Validate33TestCase.php
<?php namespace CfdiUtilsTests\Validate; use CfdiUtils\Elements\Cfdi33\Comprobante; abstract class Validate33TestCase extends ValidateBaseTestCase { protected function setUp(): void { parent::setUp(); $this->comprobante = new Comprobante(); } /** * Use this function to allow code analysis tools to perform correctly */ protected function getComprobante(): Comprobante { if ($this->comprobante instanceof Comprobante) { return $this->comprobante; } throw new \RuntimeException('The current comprobante node is not a ' . Comprobante::class); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Validate/MultiValidatorFactoryTest.php
tests/CfdiUtilsTests/Validate/MultiValidatorFactoryTest.php
<?php namespace CfdiUtilsTests\Validate; use CfdiUtils\Validate\Discoverer; use CfdiUtils\Validate\MultiValidatorFactory; use CfdiUtils\Validate\Xml\XmlFollowSchema; use PHPUnit\Framework\TestCase; final class MultiValidatorFactoryTest extends TestCase { public function testConstructWithoutArguments(): void { $factory = new MultiValidatorFactory(); $this->assertInstanceOf(Discoverer::class, $factory->getDiscoverer()); } public function testConstructWithDiscoverer(): void { $discoverer = new Discoverer(); $factory = new MultiValidatorFactory($discoverer); $this->assertSame($discoverer, $factory->getDiscoverer()); } public function testCreated33ContainsAtLeastXsdValidator(): void { $factory = new MultiValidatorFactory(); $validator = $factory->newCreated33(); $this->assertFalse($validator->canValidateCfdiVersion('3.2')); $this->assertTrue($validator->canValidateCfdiVersion('3.3')); $hasXmlFollowSchema = false; foreach ($validator as $child) { if ($child instanceof XmlFollowSchema) { $hasXmlFollowSchema = true; } } $this->assertTrue($hasXmlFollowSchema, 'MultiValidator must implement known XmlFollowSchema'); } public function testReceived33ContainsAtLeastXsdValidator(): void { $factory = new MultiValidatorFactory(); $validator = $factory->newReceived33(); $this->assertFalse($validator->canValidateCfdiVersion('3.2')); $this->assertTrue($validator->canValidateCfdiVersion('3.3')); $hasXmlFollowSchema = false; foreach ($validator as $child) { if ($child instanceof XmlFollowSchema) { $hasXmlFollowSchema = true; } } $this->assertTrue($hasXmlFollowSchema, 'MultiValidator must implement known XmlFollowSchema'); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Validate/ValidateBaseTestCase.php
tests/CfdiUtilsTests/Validate/ValidateBaseTestCase.php
<?php namespace CfdiUtilsTests\Validate; use CfdiUtils\CadenaOrigen\DOMBuilder; use CfdiUtils\Certificado\Certificado; use CfdiUtils\Cfdi; use CfdiUtils\Nodes\Node; use CfdiUtils\Nodes\NodeInterface; use CfdiUtils\Validate\Assert; use CfdiUtils\Validate\Asserts; use CfdiUtils\Validate\Contracts\ValidatorInterface; use CfdiUtils\Validate\Hydrater; use CfdiUtils\Validate\Status; use CfdiUtilsTests\TestCase; abstract class ValidateBaseTestCase extends TestCase { protected ValidatorInterface $validator; protected NodeInterface $comprobante; protected Asserts $asserts; protected Hydrater $hydrater; protected function setUp(): void { parent::setUp(); $this->comprobante = new Node('root'); $this->asserts = new Asserts(); $this->hydrater = new Hydrater(); $this->hydrater->setXmlResolver($this->newResolver()); $this->hydrater->setXsltBuilder(new DOMBuilder()); } protected function setUpCertificado( array $comprobanteAttributes = [], array $emisorAttributes = [], string $certificateFile = '', ): void { $certificateFile = $certificateFile ?: $this->utilAsset('certs/EKU9003173C9.cer'); $certificado = new Certificado($certificateFile); $this->comprobante->addAttributes(array_merge([ 'Certificado' => $certificado->getPemContentsOneLine(), 'NoCertificado' => $certificado->getSerial(), ], $comprobanteAttributes)); $emisor = $this->comprobante->searchNode('cfdi:Emisor'); if (null === $emisor) { $emisor = new Node('cfdi:Emisor'); $this->comprobante->addChild($emisor); } $emisor->addAttributes(array_merge([ 'Nombre' => $certificado->getName(), 'Rfc' => $certificado->getRfc(), ], $emisorAttributes)); } protected function runValidate(): void { $this->validator->validate($this->comprobante, $this->asserts); } public function assertExplanationContainedInCode(string $expected, string $code): void { if (! $this->asserts->exists($code)) { $this->fail("Did not receive actual status for code '$code', it may not exists"); } $actualAssert = $this->asserts->get($code); $this->assertStringContainsString($expected, $actualAssert->getExplanation()); } protected function getAssertByCodeOrFail(string $code): Assert { if (! $this->asserts->exists($code)) { $this->fail("Did not receive actual status for code '$code', it may not exists"); } return $this->asserts->get($code); } public function assertStatusEqualsCode(Status $expected, string $code): void { $actualAssert = $this->getAssertByCodeOrFail($code); $this->assertStatusEqualsAssert($expected, $actualAssert); } public function assertStatusEqualsAssert(Status $expected, Assert $assert): void { $actual = $assert->getStatus(); $this->assertTrue( $expected->equalsTo($actual), "Status $actual for code {$assert->getCode()} does not match with status $expected" ); } public function assertStatusEqualsStatus(Status $expected, Status $current): void { $this->assertEquals($expected, $current, "Status $current does not match with status $expected"); } public function assertContainsCode(string $code): void { $this->assertTrue($this->asserts->exists($code)); } public function assertNotContainsCode(string $code): void { $this->assertFalse($this->asserts->exists($code)); } protected function setupCfdiFile(string $cfdifile): void { // setup hydrate and re-hydrate the validator $content = strval(file_get_contents($this->utilAsset($cfdifile))); $this->hydrater->setXmlString($content); $this->hydrater->hydrate($this->validator); // setup comprobante $cfdi = Cfdi::newFromString($content); $this->comprobante = $cfdi->getNode(); } /** * @deprecated Use only when developing test, remove after */ protected function printrAsserts(): void { echo PHP_EOL, 'Asserts count: ', $this->asserts->count(); foreach ($this->asserts as $assert) { echo PHP_EOL, vsprintf('%-10s %-8s %s => %s', [ $assert->getCode(), $assert->getStatus(), $assert->getTitle(), $assert->getExplanation(), ]); } echo PHP_EOL; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Validate/StatusTest.php
tests/CfdiUtilsTests/Validate/StatusTest.php
<?php namespace CfdiUtilsTests\Validate; use CfdiUtils\Validate\Status; use PHPUnit\Framework\TestCase; final class StatusTest extends TestCase { public function testConstructWithInvalidCode(): void { $this->expectException(\UnexpectedValueException::class); new Status('foo'); } public function testOk(): void { $statusOne = new Status(Status::STATUS_OK); $statusTwo = Status::ok(); $this->assertEquals($statusOne, $statusTwo); $this->assertTrue($statusOne->isOk()); $this->assertTrue($statusOne->equalsTo($statusTwo)); $this->assertFalse($statusOne->equalsTo(Status::none())); } public function testError(): void { $statusOne = new Status(Status::STATUS_ERROR); $statusTwo = Status::error(); $this->assertEquals($statusOne, $statusTwo); $this->assertTrue($statusOne->isError()); $this->assertTrue($statusOne->equalsTo($statusTwo)); $this->assertFalse($statusOne->equalsTo(Status::none())); } public function testWarning(): void { $statusOne = new Status(Status::STATUS_WARNING); $statusTwo = Status::warn(); $this->assertEquals($statusOne, $statusTwo); $this->assertTrue($statusOne->isWarning()); $this->assertTrue($statusOne->equalsTo($statusTwo)); $this->assertFalse($statusOne->equalsTo(Status::none())); } public function testNone(): void { $statusOne = new Status(Status::STATUS_NONE); $statusTwo = Status::none(); $this->assertEquals($statusOne, $statusTwo); $this->assertTrue($statusOne->isNone()); $this->assertTrue($statusOne->equalsTo($statusTwo)); $this->assertFalse($statusOne->equalsTo(Status::ok())); } public function testToString(): void { $status = Status::none(); $this->assertSame(Status::STATUS_NONE, (string) $status); } public function testConditionalCreation(): void { $this->assertEquals(Status::ok(), Status::when(true)); $this->assertNotEquals(Status::ok(), Status::when(false)); $this->assertEquals(Status::error(), Status::when(false)); $this->assertEquals(Status::warn(), Status::when(false, Status::warn())); } public function testComparableValue(): void { $this->assertGreaterThan(0, Status::ok()->compareTo(Status::none())); $this->assertGreaterThan(0, Status::none()->compareTo(Status::warn())); $this->assertGreaterThan(0, Status::warn()->compareTo(Status::error())); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Validate/DiscovererTest.php
tests/CfdiUtilsTests/Validate/DiscovererTest.php
<?php namespace CfdiUtilsTests\Validate; use CfdiUtils\Validate\Contracts\ValidatorInterface; use CfdiUtils\Validate\Discoverer; use PHPUnit\Framework\TestCase; final class DiscovererTest extends TestCase { public function testDiscoverInFolder(): void { $discoverer = new Discoverer(); $namespace = __NAMESPACE__ . '\FakeObjects'; $folder = __DIR__ . '/FakeObjects'; $discoverInFolder = $discoverer->discoverInFolder($namespace, $folder); $this->assertGreaterThanOrEqual(1, $discoverInFolder); foreach ($discoverInFolder as $discovered) { $this->assertInstanceOf(ValidatorInterface::class, $discovered); } } public function testDiscoverInFile(): void { $discoverer = new Discoverer(); $namespace = __NAMESPACE__ . '\FakeObjects'; $file = __DIR__ . '/FakeObjects/ImplementationDiscoverableCreateInterface.php'; $discovered = $discoverer->discoverInFile($namespace, $file); $this->assertNotNull($discovered); $this->assertInstanceOf(ValidatorInterface::class, $discovered); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Validate/AssertTest.php
tests/CfdiUtilsTests/Validate/AssertTest.php
<?php namespace CfdiUtilsTests\Validate; use CfdiUtils\Validate\Assert; use CfdiUtils\Validate\Status; use PHPUnit\Framework\TestCase; final class AssertTest extends TestCase { public function testConstructor(): void { $assert = new Assert('X'); $this->assertSame('X', $assert->getCode()); $this->assertSame('', $assert->getTitle()); $this->assertEquals(Status::none(), $assert->getStatus()); $this->assertSame('', $assert->getExplanation()); } public function testConstructorWithValues(): void { $assert = new Assert('CODE', 'Title', Status::ok(), 'Explanation'); $this->assertSame('CODE', $assert->getCode()); $this->assertSame('Title', $assert->getTitle()); $this->assertEquals(Status::ok(), $assert->getStatus()); $this->assertSame('Explanation', $assert->getExplanation()); } public function testConstructWithEmptyStatusThrowException(): void { $this->expectException(\UnexpectedValueException::class); new Assert(''); } public function testSetTitle(): void { $assert = new Assert('X'); $assert->setTitle('Title'); $this->assertSame('Title', $assert->getTitle()); } public function testSetStatusWithoutExplanation(): void { $assert = new Assert('X'); $assert->setExplanation('Explanation'); $expectedStatus = Status::ok(); $assert->setStatus(Status::ok()); $this->assertEquals($expectedStatus, $assert->getStatus()); $this->assertSame('Explanation', $assert->getExplanation()); } public function testSetStatusWithExplanation(): void { $assert = new Assert('X'); $assert->setExplanation('Explanation'); $expectedStatus = Status::ok(); $assert->setStatus(Status::ok(), 'Changed explanation'); $this->assertEquals($expectedStatus, $assert->getStatus()); $this->assertSame('Changed explanation', $assert->getExplanation()); } public function testSetExplanation(): void { $assert = new Assert('X'); $assert->setTitle('Explanation'); $this->assertSame('Explanation', $assert->getTitle()); } public function testToString(): void { $assert = new Assert('CODE', 'Title', Status::ok()); $value = (string) $assert; $this->assertStringContainsString('CODE', $value); $this->assertStringContainsString('Title', $value); $this->assertStringContainsString(Status::STATUS_OK, $value); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Validate/Validate40TestCase.php
tests/CfdiUtilsTests/Validate/Validate40TestCase.php
<?php namespace CfdiUtilsTests\Validate; use CfdiUtils\Elements\Cfdi40\Comprobante; abstract class Validate40TestCase extends ValidateBaseTestCase { protected function setUp(): void { parent::setUp(); $this->comprobante = new Comprobante(); } /** * Use this function to allow code analysis tools to perform correctly */ protected function getComprobante(): Comprobante { if ($this->comprobante instanceof Comprobante) { return $this->comprobante; } throw new \RuntimeException('The current comprobante node is not a ' . Comprobante::class); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Validate/MultiValidatorTest.php
tests/CfdiUtilsTests/Validate/MultiValidatorTest.php
<?php namespace CfdiUtilsTests\Validate; use CfdiUtils\Nodes\Node; use CfdiUtils\Validate\Asserts; use CfdiUtils\Validate\Hydrater; use CfdiUtils\Validate\MultiValidator; use CfdiUtils\Validate\Status; use CfdiUtilsTests\TestCase; use CfdiUtilsTests\Validate\FakeObjects\ImplementationRequireXmlResolverInterface; use CfdiUtilsTests\Validate\FakeObjects\ImplementationRequireXmlStringInterface; use CfdiUtilsTests\Validate\FakeObjects\ImplementationValidatorInterface; final class MultiValidatorTest extends TestCase { public function testConstruct(): void { $validator = new MultiValidator('3.2'); $this->assertInstanceOf(\Countable::class, $validator); $this->assertInstanceOf(\Traversable::class, $validator); $this->assertSame('3.2', $validator->getVersion()); $this->assertTrue($validator->canValidateCfdiVersion('3.2')); $this->assertFalse($validator->canValidateCfdiVersion('3.3')); $this->assertCount(0, $validator); } public function testValidate(): void { $validator = new MultiValidator('3.3'); $first = new ImplementationValidatorInterface(); $first->assertsToImport = new Asserts(); $first->assertsToImport->putStatus('FIRST', Status::ok()); $last = new ImplementationValidatorInterface(); $last->assertsToImport = new Asserts(); $last->assertsToImport->putStatus('LAST', Status::error()); $validator->addMulti(...[ $first, $last, ]); $asserts = new Asserts(); $validator->validate(new Node('sample'), $asserts); // test that all children has been executed /** @var ImplementationValidatorInterface $child */ foreach ($validator as $child) { $this->assertTrue($child->enterValidateMethod); } $this->assertCount(2, $asserts); $this->assertTrue($asserts->exists('FIRST')); $this->assertTrue($asserts->exists('LAST')); $this->assertFalse($asserts->mustStop()); } public function testValidateChangesMustStopFlag(): void { $first = new ImplementationValidatorInterface(); $first->onValidateSetMustStop = true; $last = new ImplementationValidatorInterface(); $asserts = new Asserts(); $multiValidator = new MultiValidator('3.3'); $multiValidator->add($first); $multiValidator->add($last); $multiValidator->validate(new Node('sample'), $asserts); // test that only first element was executed $this->assertTrue($asserts->mustStop()); $this->assertFalse($last->enterValidateMethod); } public function testValidateSkipsOtherVersions(): void { $first = new ImplementationValidatorInterface(); $last = new ImplementationValidatorInterface(); $last->version = '3.2'; $asserts = new Asserts(); $multiValidator = new MultiValidator('3.3'); $multiValidator->add($first); $multiValidator->add($last); $multiValidator->validate(new Node('sample'), $asserts); // test that only first element was executed $this->assertFalse($last->enterValidateMethod); } public function testHydrate(): void { $hydrater = new Hydrater(); $xmlString = '<root />'; $xmlResolver = $this->newResolver(); $hydrater->setXmlString($xmlString); $hydrater->setXmlResolver($xmlResolver); $requireXmlResolver = new ImplementationRequireXmlResolverInterface(); $requireXmlString = new ImplementationRequireXmlStringInterface(); $multiValidator = new MultiValidator('3.3'); $multiValidator->addMulti($requireXmlResolver, $requireXmlString); $multiValidator->hydrate($hydrater); $this->assertSame($requireXmlResolver->getXmlResolver(), $xmlResolver); $this->assertSame($requireXmlString->getXmlString(), $xmlString); } /* * Collection tests */ public function testAddAddMulti(): void { $validator = new MultiValidator('3.3'); $first = new ImplementationValidatorInterface(); $validator->add($first); $this->assertCount(1, $validator); $validator->addMulti(...[ new ImplementationValidatorInterface(), new ImplementationValidatorInterface(), new ImplementationValidatorInterface(), ]); $this->assertCount(4, $validator); } public function testExists(): void { $child = new ImplementationValidatorInterface(); $validator = new MultiValidator('3.3'); $validator->add($child); $this->assertTrue($validator->exists($child)); $this->assertFalse($validator->exists(new ImplementationValidatorInterface())); } public function testRemove(): void { $child = new ImplementationValidatorInterface(); $validator = new MultiValidator('3.3'); $validator->add($child); $this->assertTrue($validator->exists($child)); $validator->remove($child); $this->assertFalse($validator->exists($child)); $this->assertCount(0, $validator); } public function testRemoveAll(): void { $validator = new MultiValidator('3.3'); $validator->addMulti(...[ new ImplementationValidatorInterface(), new ImplementationValidatorInterface(), new ImplementationValidatorInterface(), ]); $this->assertCount(3, $validator); $validator->removeAll(); $this->assertCount(0, $validator); } public function testTraversable(): void { $validator = new MultiValidator('3.3'); $first = new ImplementationValidatorInterface(); $second = new ImplementationValidatorInterface(); $third = new ImplementationValidatorInterface(); $validator->addMulti(...[ $first, $second, $third, ]); $current = []; foreach ($validator as $item) { $current[] = $item; } $expected = [$first, $second, $third]; foreach ($expected as $index => $value) { $this->assertSame($value, $current[$index]); } } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Validate/HydraterTest.php
tests/CfdiUtilsTests/Validate/HydraterTest.php
<?php namespace CfdiUtilsTests\Validate; use CfdiUtils\Validate\Hydrater; use CfdiUtilsTests\TestCase; use CfdiUtilsTests\Validate\FakeObjects\ImplementationRequireXmlResolverInterface; use CfdiUtilsTests\Validate\FakeObjects\ImplementationRequireXmlStringInterface; final class HydraterTest extends TestCase { public function testHydrateXmlString(): void { $hydrater = new Hydrater(); $hydrater->setXmlString('<root />'); $this->assertSame('<root />', $hydrater->getXmlString()); $container = new ImplementationRequireXmlStringInterface(); $hydrater->hydrate($container); $this->assertSame($hydrater->getXmlString(), $container->getXmlString()); } public function testHydrateXmlResolver(): void { $hydrater = new Hydrater(); $xmlResolver = $this->newResolver(); $hydrater->setXmlResolver($xmlResolver); $this->assertSame($xmlResolver, $hydrater->getXmlResolver()); $container = new ImplementationRequireXmlResolverInterface(); $hydrater->hydrate($container); $this->assertSame($hydrater->getXmlResolver(), $container->getXmlResolver()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Validate/Xml/XmlFollowSchemaTest.php
tests/CfdiUtilsTests/Validate/Xml/XmlFollowSchemaTest.php
<?php namespace CfdiUtilsTests\Validate\Xml; use CfdiUtils\Cfdi; use CfdiUtils\Validate\Contracts\ValidatorInterface; use CfdiUtils\Validate\Status; use CfdiUtils\Validate\Xml\XmlFollowSchema; use CfdiUtilsTests\Validate\Validate33TestCase; final class XmlFollowSchemaTest extends Validate33TestCase { /** @var XmlFollowSchema */ protected ValidatorInterface $validator; protected function setUp(): void { parent::setUp(); $this->validator = new XmlFollowSchema(); $this->validator->setXmlResolver($this->newResolver()); } public function testUsingRealCfdi33(): void { $xmlContent = strval(file_get_contents($this->utilAsset('cfdi33-real.xml'))); $this->comprobante = Cfdi::newFromString($xmlContent)->getNode(); $this->runValidate(); $this->assertStatusEqualsCode(Status::ok(), 'XSD01'); } public function testWithMissingElement(): void { $xmlContent = strval(file_get_contents($this->utilAsset('cfdi33-real.xml'))); $comprobante = Cfdi::newFromString($xmlContent)->getNode(); $emisor = $comprobante->children()->firstNodeWithName('cfdi:Emisor'); if (null === $emisor) { throw new \LogicException('CFDI33 (real) does not contains an cfdi:Emisor node!'); } $comprobante->children()->remove($emisor); $this->comprobante = $comprobante; $this->runValidate(); $this->assertStatusEqualsCode(Status::error(), 'XSD01'); $this->assertStringContainsString('Emisor', $this->asserts->get('XSD01')->getExplanation()); } public function testWithXsdUriNotFound(): void { $xmlContent = strval(file_get_contents($this->utilAsset('cfdi33-real.xml'))); $xmlContent = str_replace( 'http://www.sat.gob.mx/sitio_internet/cfd/TimbreFiscalDigital/TimbreFiscalDigitalv11.xsd', 'http://www.sat.gob.mx/sitio_internet/not-found/TimbreFiscalDigital/TimbreFiscalDigitalv11.xsd', $xmlContent ); $this->comprobante = Cfdi::newFromString($xmlContent)->getNode(); $this->runValidate(); $this->assertStatusEqualsCode(Status::error(), 'XSD01'); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/Validate/Common/SelloDigitalCertificadoWithCfdiRegistroFiscalTrait.php
tests/CfdiUtilsTests/Validate/Common/SelloDigitalCertificadoWithCfdiRegistroFiscalTrait.php
<?php namespace CfdiUtilsTests\Validate\Common; use CfdiUtils\Elements\Tfd11\TimbreFiscalDigital; use CfdiUtils\Nodes\Node; use CfdiUtils\Validate\Status; trait SelloDigitalCertificadoWithCfdiRegistroFiscalTrait { public function testFailWhenHasNotCfdiRegistroFiscalAndCertificadosDoNotMatch(): void { $this->runValidate(); $this->assertStatusEqualsCode(Status::error(), 'SELLO03'); $this->assertStatusEqualsCode(Status::error(), 'SELLO04'); } public function testFailWhenHasNotCfdiRegistroFiscalAndCertificadosMatch(): void { $this->comprobante->addChild(new Node('cfdi:Complemento', [], [ new TimbreFiscalDigital(['NoCertificadoSAT' => '00001000000403258748']), ])); $this->runValidate(); $this->assertStatusEqualsCode(Status::error(), 'SELLO03'); $this->assertStatusEqualsCode(Status::error(), 'SELLO04'); } public function testFailWhenHasCfdiRegistroFiscalAndCertificadosDoNotMatch(): void { $this->comprobante->addChild(new Node('cfdi:Complemento', [], [ new Node('registrofiscal:CFDIRegistroFiscal'), ])); $this->runValidate(); $this->assertStatusEqualsCode(Status::error(), 'SELLO03'); $this->assertStatusEqualsCode(Status::error(), 'SELLO04'); } public function testPassWhenHasCfdiRegistroFiscalAndCertificadosMatch(): void { $this->comprobante->addChild(new Node('cfdi:Complemento', [], [ new Node('registrofiscal:CFDIRegistroFiscal'), new TimbreFiscalDigital(['NoCertificadoSAT' => '00001000000403258748']), ])); $this->runValidate(); $this->assertStatusEqualsCode(Status::none(), 'SELLO03'); $this->assertStatusEqualsCode(Status::none(), 'SELLO04'); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false