"""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"""
urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0
GS-0815
2026-03-01
381
EUR
Beispiel Handel
123/456/78901
FC
Muster Kunde GmbH
58
2026-03-15
3.80
20.00
3.80
S19
20.00
20.00
23.80
23.80
1
200
20.00
Schrauben M6
K-77
S19
10.00
100
"""
@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"")
assert exc_info.value.error_code == "invalid_xml"
def test_foreign_xml(self):
with pytest.raises(ExtractionError) as exc_info:
extract_invoice(b"no invoice")
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']>'.encode()
xml = UBL_XML.read_bytes()
declaration_end = xml.index(b"?>") + 2
xml = xml[:declaration_end] + doctype + xml[declaration_end:]
xml = xml.replace(b"123456XX", b"&xxe;", 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"" + b" " * (10 * 1024 * 1024) + b"")
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