/extract now accepts all EN 16931 e-invoices, not only ZUGFeRD PDFs:
- plain XML files via the new xml_base64 field; XML sent as pdf_base64
is detected from the content
- UBL 2.1 Invoice and CreditNote (XRechnung UBL, Peppol BIS Billing) via
the new src/ubl_parser.py, also when embedded in a PDF
- new response field xml_syntax ("CII" or "UBL")
- CII invoice dates are normalized to YYYY-MM-DD, matching UBL
- XRechnung profiles are detected from the specification identifier,
independent of the factur-x version (6.x reports them as EN16931)
- untrusted XML is parsed without entity or DTD resolution (XXE)
Fixtures: KoSIT XRechnung test-suite case 01.01a in CII and UBL.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
314 lines
12 KiB
Python
314 lines
12 KiB
Python
"""Tests for plain-XML e-invoices and UBL syntax.
|
||
|
||
Fixtures in tests/fixtures/xml/ are official KoSIT XRechnung test-suite
|
||
business cases: the same invoice once in CII and once in UBL syntax.
|
||
"""
|
||
|
||
import base64
|
||
import re
|
||
from io import BytesIO
|
||
from pathlib import Path
|
||
|
||
import pytest
|
||
from fastapi.testclient import TestClient
|
||
from pypdf import PdfWriter
|
||
|
||
from src.extractor import (
|
||
ExtractionError,
|
||
extract_from_xml,
|
||
extract_invoice,
|
||
extract_zugferd,
|
||
)
|
||
from src.main import app
|
||
from src.models import ValidateRequest
|
||
from src.validator import validate_invoice
|
||
|
||
XML_FIXTURES = Path(__file__).parent / "fixtures" / "xml"
|
||
CII_XML = XML_FIXTURES / "xrechnung_01.01a_cii.xml"
|
||
UBL_XML = XML_FIXTURES / "xrechnung_01.01a_ubl.xml"
|
||
ALL_CHECKS = ["pflichtfelder", "betraege", "ustid", "pdf_abgleich"]
|
||
|
||
CREDIT_NOTE_XML = b"""<?xml version="1.0" encoding="UTF-8"?>
|
||
<CreditNote xmlns="urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2"
|
||
xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2"
|
||
xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2">
|
||
<cbc:CustomizationID>urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0</cbc:CustomizationID>
|
||
<cbc:ID>GS-0815</cbc:ID>
|
||
<cbc:IssueDate>2026-03-01</cbc:IssueDate>
|
||
<cbc:CreditNoteTypeCode>381</cbc:CreditNoteTypeCode>
|
||
<cbc:DocumentCurrencyCode>EUR</cbc:DocumentCurrencyCode>
|
||
<cac:AccountingSupplierParty><cac:Party>
|
||
<cac:PartyName><cbc:Name>Beispiel Handel</cbc:Name></cac:PartyName>
|
||
<cac:PartyTaxScheme>
|
||
<cbc:CompanyID>123/456/78901</cbc:CompanyID>
|
||
<cac:TaxScheme><cbc:ID>FC</cbc:ID></cac:TaxScheme>
|
||
</cac:PartyTaxScheme>
|
||
</cac:Party></cac:AccountingSupplierParty>
|
||
<cac:AccountingCustomerParty><cac:Party>
|
||
<cac:PartyLegalEntity>
|
||
<cbc:RegistrationName>Muster Kunde GmbH</cbc:RegistrationName>
|
||
</cac:PartyLegalEntity>
|
||
</cac:Party></cac:AccountingCustomerParty>
|
||
<cac:PaymentMeans>
|
||
<cbc:PaymentMeansCode>58</cbc:PaymentMeansCode>
|
||
<cbc:PaymentDueDate>2026-03-15</cbc:PaymentDueDate>
|
||
</cac:PaymentMeans>
|
||
<cac:TaxTotal>
|
||
<cbc:TaxAmount currencyID="EUR">3.80</cbc:TaxAmount>
|
||
<cac:TaxSubtotal>
|
||
<cbc:TaxableAmount currencyID="EUR">20.00</cbc:TaxableAmount>
|
||
<cbc:TaxAmount currencyID="EUR">3.80</cbc:TaxAmount>
|
||
<cac:TaxCategory><cbc:ID>S</cbc:ID><cbc:Percent>19</cbc:Percent></cac:TaxCategory>
|
||
</cac:TaxSubtotal>
|
||
</cac:TaxTotal>
|
||
<cac:LegalMonetaryTotal>
|
||
<cbc:LineExtensionAmount currencyID="EUR">20.00</cbc:LineExtensionAmount>
|
||
<cbc:TaxExclusiveAmount currencyID="EUR">20.00</cbc:TaxExclusiveAmount>
|
||
<cbc:TaxInclusiveAmount currencyID="EUR">23.80</cbc:TaxInclusiveAmount>
|
||
<cbc:PayableAmount currencyID="EUR">23.80</cbc:PayableAmount>
|
||
</cac:LegalMonetaryTotal>
|
||
<cac:CreditNoteLine>
|
||
<cbc:ID>1</cbc:ID>
|
||
<cbc:CreditedQuantity unitCode="H87">200</cbc:CreditedQuantity>
|
||
<cbc:LineExtensionAmount currencyID="EUR">20.00</cbc:LineExtensionAmount>
|
||
<cac:Item>
|
||
<cbc:Name>Schrauben M6</cbc:Name>
|
||
<cac:BuyersItemIdentification><cbc:ID>K-77</cbc:ID></cac:BuyersItemIdentification>
|
||
<cac:ClassifiedTaxCategory><cbc:ID>S</cbc:ID><cbc:Percent>19</cbc:Percent></cac:ClassifiedTaxCategory>
|
||
</cac:Item>
|
||
<cac:Price>
|
||
<cbc:PriceAmount currencyID="EUR">10.00</cbc:PriceAmount>
|
||
<cbc:BaseQuantity unitCode="H87">100</cbc:BaseQuantity>
|
||
</cac:Price>
|
||
</cac:CreditNoteLine>
|
||
</CreditNote>
|
||
"""
|
||
|
||
|
||
@pytest.fixture
|
||
def client():
|
||
return TestClient(app)
|
||
|
||
|
||
def _validate(xml_data):
|
||
request = ValidateRequest(
|
||
xml_data=xml_data.model_dump(), pdf_text=None, checks=ALL_CHECKS
|
||
)
|
||
return validate_invoice(request)
|
||
|
||
|
||
class TestPlainXml:
|
||
"""Plain XML files (no PDF container) in both syntaxes."""
|
||
|
||
def test_cii_xml(self):
|
||
result = extract_invoice(CII_XML.read_bytes())
|
||
|
||
assert result.is_zugferd is True
|
||
assert result.xml_syntax == "CII"
|
||
assert result.zugferd_profil == "XRECHNUNG_3.0"
|
||
assert result.pdf_text is None
|
||
assert result.extraction_meta.pages == 0
|
||
assert result.extraction_meta.xml_attachment_name is None
|
||
assert result.xml_data.invoice_number == "123456XX"
|
||
assert result.xml_data.invoice_date == "2016-04-04"
|
||
assert result.xml_data.totals.gross == pytest.approx(336.9)
|
||
|
||
def test_ubl_xml(self):
|
||
result = extract_invoice(UBL_XML.read_bytes())
|
||
|
||
assert result.is_zugferd is True
|
||
assert result.xml_syntax == "UBL"
|
||
assert result.zugferd_profil == "XRECHNUNG_3.0"
|
||
assert result.xml_raw.lstrip().startswith("<")
|
||
|
||
data = result.xml_data
|
||
assert data.invoice_number == "123456XX"
|
||
assert data.invoice_date == "2016-04-04"
|
||
assert data.currency == "EUR"
|
||
assert data.supplier.name == "[Seller name]"
|
||
assert data.supplier.vat_id == "DE 123456789"
|
||
assert data.supplier.postal_code == "12345"
|
||
assert data.supplier.country == "DE"
|
||
assert data.supplier.email == "seller@email.de"
|
||
assert data.buyer.name == "[Buyer name]"
|
||
assert data.payment_terms.iban == "DE79000000001234567890"
|
||
|
||
assert len(data.line_items) == 2
|
||
first = data.line_items[0]
|
||
assert first.article_number == "246"
|
||
assert first.quantity == 1
|
||
assert first.unit == "XPP"
|
||
assert first.unit_price == pytest.approx(288.79)
|
||
assert first.line_total == pytest.approx(288.79)
|
||
assert first.vat_rate == 7
|
||
|
||
assert data.totals.line_total_sum == pytest.approx(314.86)
|
||
assert data.totals.net == pytest.approx(314.86)
|
||
assert data.totals.vat_total == pytest.approx(22.04)
|
||
assert data.totals.gross == pytest.approx(336.9)
|
||
assert len(data.totals.vat_breakdown) == 1
|
||
assert data.totals.vat_breakdown[0].rate == 7
|
||
|
||
def test_ubl_and_cii_yield_same_invoice(self):
|
||
"""The same business case must parse identically from both syntaxes."""
|
||
cii = extract_invoice(CII_XML.read_bytes()).xml_data.model_dump()
|
||
ubl = extract_invoice(UBL_XML.read_bytes()).xml_data.model_dump()
|
||
|
||
# The note's subject-code prefix is carried differently by syntax
|
||
cii.pop("notes")
|
||
ubl.pop("notes")
|
||
assert ubl == cii
|
||
|
||
@pytest.mark.parametrize("path", [CII_XML, UBL_XML])
|
||
def test_validation_passes(self, path):
|
||
validation = _validate(extract_invoice(path.read_bytes()).xml_data)
|
||
|
||
assert validation.errors == []
|
||
assert validation.is_valid is True
|
||
|
||
def test_utf8_bom_is_accepted(self):
|
||
result = extract_invoice(b"\xef\xbb\xbf" + UBL_XML.read_bytes())
|
||
|
||
assert result.xml_syntax == "UBL"
|
||
assert not result.xml_raw.startswith("")
|
||
|
||
|
||
class TestUblCreditNote:
|
||
"""UBL CreditNote uses its own line and quantity element names."""
|
||
|
||
def test_credit_note(self):
|
||
result = extract_invoice(CREDIT_NOTE_XML)
|
||
|
||
assert result.xml_syntax == "UBL"
|
||
assert result.zugferd_profil == "PEPPOL_BIS_BILLING_3.0"
|
||
|
||
data = result.xml_data
|
||
assert data.invoice_number == "GS-0815"
|
||
assert data.due_date == "2026-03-15"
|
||
assert data.supplier.name == "Beispiel Handel"
|
||
assert data.supplier.vat_id is None
|
||
assert data.supplier.tax_number == "123/456/78901"
|
||
assert data.buyer.name == "Muster Kunde GmbH"
|
||
assert data.payment_terms is None
|
||
|
||
assert len(data.line_items) == 1
|
||
line = data.line_items[0]
|
||
assert line.article_number_buyer == "K-77"
|
||
assert line.quantity == 200
|
||
# Price 10.00 per base quantity 100
|
||
assert line.unit_price == pytest.approx(0.10)
|
||
assert line.line_total == pytest.approx(20.0)
|
||
|
||
def test_credit_note_validation_passes(self):
|
||
validation = _validate(extract_invoice(CREDIT_NOTE_XML).xml_data)
|
||
|
||
assert validation.errors == []
|
||
|
||
|
||
class TestUblInPdf:
|
||
"""A PDF may carry a UBL invoice as attachment."""
|
||
|
||
def test_ubl_attachment(self):
|
||
writer = PdfWriter()
|
||
writer.add_blank_page(width=72, height=72)
|
||
writer.add_attachment("xrechnung.xml", UBL_XML.read_bytes())
|
||
output = BytesIO()
|
||
writer.write(output)
|
||
|
||
result = extract_invoice(output.getvalue())
|
||
|
||
assert result.is_zugferd is True
|
||
assert result.xml_syntax == "UBL"
|
||
assert result.extraction_meta.xml_attachment_name == "xrechnung.xml"
|
||
assert result.extraction_meta.pages == 1
|
||
assert result.xml_data.invoice_number == "123456XX"
|
||
|
||
def test_xrechnung_pdf_reports_xrechnung_profile(self):
|
||
"""Must hold for every factur-x version (6.x maps it to EN16931)."""
|
||
pdf_bytes = Path("tests/fixtures/validXRechnung.pdf").read_bytes()
|
||
|
||
assert extract_invoice(pdf_bytes).zugferd_profil.startswith("XRECHNUNG_")
|
||
|
||
def test_zugferd_pdf_reports_cii(self):
|
||
pdf_bytes = Path("tests/fixtures/EN16931_Einfach.pdf").read_bytes()
|
||
|
||
result = extract_zugferd(pdf_bytes)
|
||
assert result.xml_syntax == "CII"
|
||
# CII dates (format 102, YYYYMMDD) are normalized to ISO notation
|
||
assert re.fullmatch(r"\d{4}-\d{2}-\d{2}", result.xml_data.invoice_date)
|
||
assert extract_invoice(pdf_bytes).zugferd_profil == "EN16931"
|
||
|
||
|
||
class TestXmlErrors:
|
||
"""Malformed, foreign and hostile XML."""
|
||
|
||
def test_malformed_xml(self):
|
||
with pytest.raises(ExtractionError) as exc_info:
|
||
extract_invoice(b"<?xml version='1.0'?><Invoice><unclosed>")
|
||
|
||
assert exc_info.value.error_code == "invalid_xml"
|
||
|
||
def test_foreign_xml(self):
|
||
with pytest.raises(ExtractionError) as exc_info:
|
||
extract_invoice(b"<html><body>no invoice</body></html>")
|
||
|
||
assert exc_info.value.error_code == "unsupported_xml_format"
|
||
|
||
def test_external_entities_are_not_resolved(self, tmp_path):
|
||
secret = tmp_path / "secret.txt"
|
||
secret.write_text("TOP-SECRET-CONTENT")
|
||
doctype = f'<!DOCTYPE x [<!ENTITY xxe SYSTEM "file://{secret}">]>'.encode()
|
||
xml = UBL_XML.read_bytes()
|
||
declaration_end = xml.index(b"?>") + 2
|
||
xml = xml[:declaration_end] + doctype + xml[declaration_end:]
|
||
xml = xml.replace(b"<cbc:ID>123456XX</cbc:ID>", b"<cbc:ID>&xxe;</cbc:ID>", 1)
|
||
|
||
result = extract_from_xml(xml)
|
||
|
||
assert "TOP-SECRET-CONTENT" not in result.model_dump_json()
|
||
|
||
def test_file_too_large(self):
|
||
with pytest.raises(ExtractionError) as exc_info:
|
||
extract_invoice(b"<a>" + b" " * (10 * 1024 * 1024) + b"</a>")
|
||
|
||
assert exc_info.value.error_code == "file_too_large"
|
||
|
||
|
||
class TestExtractEndpointXml:
|
||
"""POST /extract with plain XML."""
|
||
|
||
def test_xml_base64(self, client):
|
||
payload = {"xml_base64": base64.b64encode(UBL_XML.read_bytes()).decode()}
|
||
response = client.post("/extract", json=payload)
|
||
|
||
assert response.status_code == 200
|
||
data = response.json()
|
||
assert data["is_zugferd"] is True
|
||
assert data["xml_syntax"] == "UBL"
|
||
assert data["zugferd_profil"] == "XRECHNUNG_3.0"
|
||
assert data["xml_data"]["invoice_number"] == "123456XX"
|
||
|
||
def test_xml_in_pdf_field_is_detected(self, client):
|
||
"""Clients that only know pdf_base64 can send XML through it."""
|
||
payload = {"pdf_base64": base64.b64encode(CII_XML.read_bytes()).decode()}
|
||
response = client.post("/extract", json=payload)
|
||
|
||
assert response.status_code == 200
|
||
assert response.json()["xml_syntax"] == "CII"
|
||
|
||
def test_pdf_in_xml_field_is_rejected(self, client):
|
||
pdf_bytes = Path("tests/fixtures/EN16931_Einfach.pdf").read_bytes()
|
||
payload = {"xml_base64": base64.b64encode(pdf_bytes).decode()}
|
||
response = client.post("/extract", json=payload)
|
||
|
||
assert response.status_code == 400
|
||
assert response.json()["error"] == "invalid_xml"
|
||
|
||
def test_no_file(self, client):
|
||
assert client.post("/extract", json={}).status_code == 422
|
||
|
||
def test_both_files(self, client):
|
||
payload = {"pdf_base64": "QQ==", "xml_base64": "QQ=="}
|
||
|
||
assert client.post("/extract", json=payload).status_code == 422
|