Files
zugferd-service/tests/test_xml_formats.py
T
m3ta-chironandClaude Fable 5.2 fa9eaa4f82 feat: extract due date and buyer reference, require it on XRechnung
- CII: due_date is read from the payment due date (BT-9) instead of the
  delivery terms description, normalized to YYYY-MM-DD
- new field buyer_reference (BT-10, the Leitweg-ID) for CII and UBL
- /validate accepts an optional profile; on XRECHNUNG_* profiles a
  missing buyer reference is a critical error (BR-DE-15)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 18:33:08 +01:00

356 lines
13 KiB
Python
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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.buyer_reference == "04011000-12345-03"
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.buyer_reference == "04011000-12345-03"
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 TestBuyerReference:
"""BT-10 (Leitweg-ID) is mandatory on XRechnung invoices only."""
def _data_without_reference(self):
xml_data = extract_invoice(UBL_XML.read_bytes()).xml_data
xml_data.buyer_reference = None
return xml_data.model_dump()
def test_missing_on_xrechnung_is_critical(self):
request = ValidateRequest(
xml_data=self._data_without_reference(),
checks=["pflichtfelder"],
profile="XRECHNUNG_3.0",
)
validation = validate_invoice(request)
assert validation.is_valid is False
assert [e.field for e in validation.errors] == ["buyer_reference"]
@pytest.mark.parametrize("profile", [None, "EN16931", "PEPPOL_BIS_BILLING_3.0"])
def test_missing_on_other_profiles_is_fine(self, profile):
request = ValidateRequest(
xml_data=self._data_without_reference(),
checks=["pflichtfelder"],
profile=profile,
)
assert validate_invoice(request).errors == []
def test_present_on_xrechnung_passes(self):
result = extract_invoice(CII_XML.read_bytes())
request = ValidateRequest(
xml_data=result.xml_data.model_dump(),
checks=ALL_CHECKS,
profile=result.zugferd_profil,
)
assert validate_invoice(request).errors == []
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