Conghao97's picture tcftrees's picture
ProgramGen release
d086025
Raw History Blame Contribute Delete
48.3 kB
diff --git a/test/test_config.py b/test/test_config.py new file mode 100644 --- /dev/null +++ b/test/test_config.py @@ -0,0 +1,55 @@ +import pytest + +from netto.config import TaxConfig + + +def test_taxconfig_defaults(): + """Test that TaxConfig uses correct default values""" + config = TaxConfig() + assert config.year == 2025 + assert config.has_children is False + assert config.is_married is False + assert config.extra_health_insurance is None # year-specific average + assert config.church_tax == 0.09 + + +def test_taxconfig_custom_values(): + """Test creating TaxConfig with custom values""" + config = TaxConfig( + year=2025, + has_children=True, + is_married=True, + extra_health_insurance=0.02, + church_tax=0.08, + ) + assert config.year == 2025 + assert config.has_children is True + assert config.is_married is True + assert config.extra_health_insurance == 0.02 + assert config.church_tax == 0.08 + + +def test_taxconfig_validation_year_range(): + """Test that year validation works""" + with pytest.raises(ValueError): + TaxConfig(year=2017) # Too early + with pytest.raises(ValueError): + TaxConfig(year=2033) # Too late + + +def test_taxconfig_validation_negative_rates(): + """Test that negative rates are rejected""" + with pytest.raises(ValueError): + TaxConfig(extra_health_insurance=-0.01) + with pytest.raises(ValueError): + TaxConfig(church_tax=-0.01) + + +def test_taxconfig_validation_type_errors(): + """Test that type validation works""" + with pytest.raises(TypeError): + TaxConfig(year="2022") # String instead of int + with pytest.raises(TypeError): + TaxConfig(has_children="True") # String instead of bool + with pytest.raises(TypeError): + TaxConfig(is_married=1) # Int instead of bool diff --git a/test/test_data_loader.py b/test/test_data_loader.py new file mode 100644 --- /dev/null +++ b/test/test_data_loader.py @@ -0,0 +1,447 @@ +import pytest +from pydantic import ValidationError + +from netto.data_loader import ( + Deductions, + PensionFactor, + SocialSecurity, + SocialSecurityEntry, + SoliCurve, + TaxBracket, + TaxCurve, + correction_factor_pensions, + deductions, + load_all_deductions, + load_all_pension_factors, + load_all_social_security, + load_all_soli, + load_all_tax_curves, + load_deductions, + load_pension_factor, + load_social_security, + load_soli, + load_tax_curve, + social_security_curve, + soli_curve, + tax_curve, +) + +# Tests for Pydantic Models + + +def test_tax_bracket_valid(): + """Test creating a valid TaxBracket""" + bracket = TaxBracket(step=10000, rate=0.14, const=[100, 200]) + assert bracket.step == 10000 + assert bracket.rate == 0.14 + assert bracket.const == [100, 200] + + +def test_tax_bracket_no_const(): + """Test creating TaxBracket without const""" + bracket = TaxBracket(step=10000, rate=0.0) + assert bracket.step == 10000 + assert bracket.rate == 0.0 + assert bracket.const is None + + +def test_tax_bracket_invalid_step(): + """Test that TaxBracket rejects invalid step values""" + with pytest.raises(ValidationError): + TaxBracket(step=0, rate=0.14) # step must be > 0 + with pytest.raises(ValidationError): + TaxBracket(step=-100, rate=0.14) # negative not allowed + + +def test_tax_bracket_invalid_rate(): + """Test that TaxBracket rejects invalid rate values""" + with pytest.raises(ValidationError): + TaxBracket(step=10000, rate=-0.1) # negative not allowed + with pytest.raises(ValidationError): + TaxBracket(step=10000, rate=1.5) # > 1 not allowed + + +def test_tax_bracket_empty_const(): + """Test that TaxBracket rejects empty const array""" + with pytest.raises(ValidationError): + TaxBracket(step=10000, rate=0.14, const=[]) + + +def test_tax_curve_valid(): + """Test creating a valid TaxCurve""" + curve = TaxCurve( + year=2022, + brackets={ + "0": TaxBracket(step=10347, rate=0.0), + "1": TaxBracket(step=14927, rate=0.14, const=[995.21, 1400]), + "2": TaxBracket(step=58597, rate=0.2397, const=[208.85, 2397, 950.96]), + "3": TaxBracket(step=277826, rate=0.42, const=[0.42, 9336.45]), + }, + ) + assert curve.year == 2022 + assert len(curve.brackets) == 4 + + +def test_tax_curve_invalid_brackets(): + """Test that TaxCurve requires exactly 4 brackets""" + with pytest.raises(ValidationError): + TaxCurve( + year=2022, + brackets={ + "0": TaxBracket(step=10000, rate=0.0), + "1": TaxBracket(step=20000, rate=0.14), + }, + ) + + +def test_tax_curve_invalid_year(): + """Test that TaxCurve validates year range""" + with pytest.raises(ValidationError): + TaxCurve( + year=2015, # Too early + brackets={ + "0": TaxBracket(step=10000, rate=0.0), + "1": TaxBracket(step=20000, rate=0.14), + "2": TaxBracket(step=30000, rate=0.24), + "3": TaxBracket(step=40000, rate=0.42), + }, + ) + + +def test_social_security_entry_valid(): + """Test creating a valid SocialSecurityEntry""" + entry = SocialSecurityEntry(limit=84600, rate=0.093) + assert entry.limit == 84600 + assert entry.rate == 0.093 + assert entry.extra is None + + +def test_social_security_entry_with_extra(): + """Test creating SocialSecurityEntry with extra rate""" + entry = SocialSecurityEntry(limit=58050, rate=0.073, extra=0.0035) + assert entry.limit == 58050 + assert entry.rate == 0.073 + assert entry.extra == 0.0035 + + +def test_social_security_entry_invalid_limit(): + """Test that SocialSecurityEntry validates limit""" + with pytest.raises(ValidationError): + SocialSecurityEntry(limit=0, rate=0.093) # Must be > 0 + with pytest.raises(ValidationError): + SocialSecurityEntry(limit=-1000, rate=0.093) # Negative not allowed + + +def test_social_security_valid(): + """Test creating a valid SocialSecurity""" + social_sec = SocialSecurity( + year=2022, + pension=SocialSecurityEntry(limit=84600, rate=0.093), + unemployment=SocialSecurityEntry(limit=84600, rate=0.012), + health=SocialSecurityEntry(limit=58050, rate=0.073, extra=0.007), + nursing=SocialSecurityEntry(limit=58050, rate=0.01525, extra=0.0035), + ) + assert social_sec.year == 2022 + assert social_sec.pension.limit == 84600 + assert social_sec.health.extra == 0.007 + + +def test_soli_curve_valid(): + """Test creating a valid SoliCurve""" + soli = SoliCurve( + year=2022, start_taxable_income=16956, start_fraction=0.119, end_rate=0.055 + ) + assert soli.year == 2022 + assert soli.start_taxable_income == 16956 + assert soli.start_fraction == 0.119 + assert soli.end_rate == 0.055 + + +def test_pension_factor_valid(): + """Test creating a valid PensionFactor""" + factor = PensionFactor(year=2022, factor=0.88) + assert factor.year == 2022 + assert factor.factor == 0.88 + + +def test_pension_factor_invalid_factor(): + """Test that PensionFactor validates factor range""" + with pytest.raises(ValidationError): + PensionFactor(year=2022, factor=-0.1) # Negative not allowed + with pytest.raises(ValidationError): + PensionFactor(year=2022, factor=1.5) # > 1 not allowed + + +def test_deductions_valid(): + """Test creating a valid Deductions model""" + deductions_model = Deductions( + year=2022, werbungskosten_pauschbetrag=1200, sonderausgaben_pauschbetrag=36 + ) + assert deductions_model.year == 2022 + assert deductions_model.werbungskosten_pauschbetrag == 1200 + assert deductions_model.sonderausgaben_pauschbetrag == 36 + + +def test_deductions_invalid_values(): + """Test that Deductions rejects negative values""" + with pytest.raises(ValidationError): + Deductions( + year=2022, werbungskosten_pauschbetrag=-1, sonderausgaben_pauschbetrag=36 + ) + with pytest.raises(ValidationError): + Deductions( + year=2022, werbungskosten_pauschbetrag=1200, sonderausgaben_pauschbetrag=-1 + ) + + +# Tests for individual load functions + + +@pytest.mark.parametrize("year", list(range(2018, 2033))) +def test_load_tax_curve(year): + """Test loading tax curve for available years""" + curve = load_tax_curve(year) + assert isinstance(curve, dict) + assert len(curve) == 4 + assert all(k in [0, 1, 2, 3] for k in curve.keys()) + assert all("step" in v and "rate" in v for v in curve.values()) + + +def test_load_tax_curve_missing_year(): + """Test that loading tax curve for missing year raises FileNotFoundError""" + with pytest.raises(FileNotFoundError): + load_tax_curve(2035) + + +@pytest.mark.parametrize("year", list(range(2018, 2033))) +def test_load_social_security(year): + """Test loading social security for available years""" + social_sec = load_social_security(year) + assert isinstance(social_sec, dict) + assert "pension" in social_sec + assert "unemployment" in social_sec + assert "health" in social_sec + assert "nursing" in social_sec + + +def test_load_social_security_not_implemented(): + """Test that loading social security for 2033+ raises NotImplementedError""" + with pytest.raises(NotImplementedError): + load_social_security(2033) + + +def test_load_social_security_missing_year(): + """Test that loading social security for missing year raises FileNotFoundError""" + with pytest.raises(FileNotFoundError): + load_social_security(2015) + + +@pytest.mark.parametrize("year", list(range(2018, 2033))) +def test_load_soli(year): + """Test loading solidarity tax data for available years""" + soli = load_soli(year) + assert isinstance(soli, dict) + assert "start_taxable_income" in soli + assert "start_fraction" in soli + assert "end_rate" in soli + + +def test_load_soli_missing_year(): + """Test that loading soli for missing year raises FileNotFoundError""" + with pytest.raises(FileNotFoundError): + load_soli(2035) + + +@pytest.mark.parametrize("year", list(range(2018, 2033))) +def test_load_pension_factor(year): + """Test loading pension factor for available years""" + factor = load_pension_factor(year) + assert isinstance(factor, float) + assert 0 <= factor <= 1 + + +def test_load_pension_factor_missing_year(): + """Test that loading pension factor for missing year raises FileNotFoundError""" + with pytest.raises(FileNotFoundError): + load_pension_factor(2035) + + +@pytest.mark.parametrize( + "year,expected_werbungskosten", + [ + (2018, 1000), + (2019, 1000), + (2020, 1000), + (2021, 1000), + (2022, 1200), + (2023, 1230), + (2024, 1230), + (2025, 1230), + (2026, 1230), + ], +) +def test_load_deductions(year, expected_werbungskosten): + """Test loading deductions with year-specific Werbungskosten-Pauschbetrag""" + deductions_data = load_deductions(year) + assert deductions_data["werbungskosten_pauschbetrag"] == expected_werbungskosten + assert deductions_data["sonderausgaben_pauschbetrag"] == 36 + + +def test_load_deductions_missing_year(): + """Test that loading deductions for missing year raises FileNotFoundError""" + with pytest.raises(FileNotFoundError): + load_deductions(2035) + + +# Tests for bulk load functions + + +def test_load_all_tax_curves(): + """Test loading all tax curves""" + curves = load_all_tax_curves() + assert isinstance(curves, dict) + assert len(curves) >= 8 # At least 2018-2025 + for year, curve in curves.items(): + assert isinstance(year, int) + assert isinstance(curve, dict) + assert len(curve) == 4 + + +def test_load_all_social_security(): + """Test loading all social security data""" + social_security_data = load_all_social_security() + assert isinstance(social_security_data, dict) + assert len(social_security_data) >= 15 # At least 2018-2032 + + +def test_load_all_soli(): + """Test loading all solidarity tax data""" + soli_data = load_all_soli() + assert isinstance(soli_data, dict) + assert len(soli_data) >= 8 # At least 2018-2025 + for year, soli in soli_data.items(): + assert isinstance(year, int) + assert isinstance(soli, dict) + + +def test_load_all_pension_factors(): + """Test loading all pension factors""" + factors = load_all_pension_factors() + assert isinstance(factors, dict) + assert len(factors) >= 8 # At least 2018-2025 + for year, factor in factors.items(): + assert isinstance(year, int) + assert isinstance(factor, float) + assert 0 <= factor <= 1 + + +# Tests for module-level variables + + +def test_module_tax_curve(): + """Test that tax_curve is loaded at module level""" + assert isinstance(tax_curve, dict) + assert len(tax_curve) >= 8 + assert 2022 in tax_curve + assert len(tax_curve[2022]) == 4 + + +def test_module_social_security_curve(): + """Test that social_security_curve is loaded at module level""" + assert isinstance(social_security_curve, dict) + assert len(social_security_curve) >= 8 + assert 2022 in social_security_curve + assert "pension" in social_security_curve[2022] + + +def test_module_soli_curve(): + """Test that soli_curve is loaded at module level""" + assert isinstance(soli_curve, dict) + assert len(soli_curve) >= 8 + assert 2022 in soli_curve + assert "start_taxable_income" in soli_curve[2022] + + +def test_module_correction_factor_pensions(): + """Test that correction_factor_pensions is loaded at module level""" + assert isinstance(correction_factor_pensions, dict) + assert len(correction_factor_pensions) >= 8 + assert 2022 in correction_factor_pensions + assert isinstance(correction_factor_pensions[2022], float) + + +def test_load_all_deductions(): + """Test loading all deductions data""" + deductions_data = load_all_deductions() + assert isinstance(deductions_data, dict) + assert len(deductions_data) >= 15 # At least 2018-2032 + for year, entry in deductions_data.items(): + assert isinstance(year, int) + assert "werbungskosten_pauschbetrag" in entry + assert "sonderausgaben_pauschbetrag" in entry + + +def test_module_deductions(): + """Test that deductions is loaded at module level""" + assert isinstance(deductions, dict) + assert 2022 in deductions + assert deductions[2022]["werbungskosten_pauschbetrag"] == 1200 + + +# Integration tests + + +def test_tax_curve_structure_2022(): + """Test that 2022 tax curve has expected structure""" + curve_2022 = load_tax_curve(2022) + + # Bracket 0: Basic allowance + assert curve_2022[0]["step"] == 10347 + assert curve_2022[0]["rate"] == 0.14 + + # Bracket 1: Progressive zone 1 + assert curve_2022[1]["step"] == 14926 + assert curve_2022[1]["rate"] == 0.2397 + assert curve_2022[1]["const"] is not None + + # Bracket 2: Progressive zone 2 + assert curve_2022[2]["step"] == 58596 + assert curve_2022[2]["rate"] == 0.42 + assert curve_2022[2]["const"] is not None + + # Bracket 3: Top rate + assert curve_2022[3]["step"] == 277826 + assert curve_2022[3]["rate"] == 0.45 + + +def test_social_security_structure_2022(): + """Test that 2022 social security has expected structure""" + ss_2022 = load_social_security(2022) + + # Pension insurance + assert ss_2022["pension"]["limit"] == 84600 + assert ss_2022["pension"]["rate"] == 0.093 + + # Health insurance + assert ss_2022["health"]["limit"] == 58050 + assert ss_2022["health"]["rate"] == 0.073 + + # Nursing insurance + assert ss_2022["nursing"]["limit"] == 58050 + assert ss_2022["nursing"]["rate"] == 0.01525 + + +def test_soli_structure_2022(): + """Test that 2022 soli has expected structure""" + soli_2022 = load_soli(2022) + + assert soli_2022["start_taxable_income"] == 16956 + assert soli_2022["start_fraction"] == 0.119 + assert soli_2022["end_rate"] == 0.055 + + +def test_pension_factor_value_2022(): + """Test that 2022 pension factor has expected value""" + factor_2022 = load_pension_factor(2022) + + assert factor_2022 == 0.88 diff --git a/test/test_main.py b/test/test_main.py new file mode 100644 --- /dev/null +++ b/test/test_main.py @@ -0,0 +1,197 @@ +from io import StringIO +from unittest.mock import patch + +import pytest + +import netto.main as main +from netto.config import TaxConfig + + +@pytest.fixture +def default_config(): + """Fixture providing default config for tests""" + return TaxConfig( + year=2022, extra_health_insurance=0.014, church_tax=0.09, has_children=False + ) + + +@pytest.fixture +def alternate_config(): + """Fixture providing alternate config for tests""" + return TaxConfig( + year=2022, extra_health_insurance=0.015, church_tax=0.0, has_children=True + ) + + +@pytest.mark.parametrize( + "salary,expected", + [ + (0, 0), + (30000, 20554.38), + (60000, 35796.68), + (90000, 49956.92), + (120000, 64965.08), + ], +) +def test_calc_netto_with_default_config(salary, expected, default_config): + """Test calc_netto with various salaries using default config""" + result = main.calc_netto(salary, config=default_config) + assert abs(result - expected) < 1 + + +@pytest.mark.parametrize( + "salary,expected", + [ + (30000, 20894.58), + (60000, 36909.71), + (90000, 52091.39), + (120000, 68238.23), + ], +) +def test_calc_netto_with_alternate_config(salary, expected, alternate_config): + """Test calc_netto with alternate config (no church tax, with children)""" + result = main.calc_netto(salary, config=alternate_config) + assert abs(result - expected) < 1 + + +@pytest.mark.parametrize( + "desired_netto,expected_gross", + [ + (20894.58, 30000), + (36909.71, 60000), + (52091.39, 90000), + (68238.23, 120000), + ], +) +def test_calc_inverse_netto(desired_netto, expected_gross, alternate_config): + """Test inverse netto calculation""" + result = main.calc_inverse_netto(desired_netto, config=alternate_config) + assert abs(result - expected_gross) <= 1 + + +def test_calc_inverse_netto_roundtrip(alternate_config): + """Test that calc_inverse_netto and calc_netto are inverses""" + salary = 10000 + netto = main.calc_netto(salary, config=alternate_config) + gross = main.calc_inverse_netto(netto, config=alternate_config) + assert gross == salary + + +@pytest.fixture +def married_config(): + """Fixture providing a married config for tests""" + return TaxConfig(year=2025, is_married=True, church_tax=0.0) + + +@pytest.mark.parametrize( + "salary,expected", + [ + (50000, 36263.40), + (100000, 67016.96), + (150000, 98603.98), # income tax 33940 is below married soli threshold 39900 + (250000, 152445.93), + ], +) +def test_calc_netto_married(salary, expected, married_config): + """Test married netto (splitting tariff, doubled soli threshold)""" + result = main.calc_netto(salary, config=married_config) + assert abs(result - expected) < 1 + + +def test_calc_netto_married_higher_than_single(married_config): + """Splitting must never yield less netto than the single tariff""" + single_config = TaxConfig(year=2025, church_tax=0.0) + for salary in [30000, 60000, 100000, 150000, 250000]: + assert main.calc_netto(salary, config=married_config) >= main.calc_netto( + salary, config=single_config + ) + + +def test_calc_netto_dual_income(married_config): + """Test household netto for a dual-income married couple""" + result = main.calc_netto(80000, config=married_config, partner_salary=80000) + assert abs(result - 96345.38) < 1 + + +def test_calc_netto_dual_income_pays_more_social_security(married_config): + """Same household income, but two earners below the contribution ceilings + pay more social security than a single earner above them""" + single_earner = main.calc_netto(160000, config=married_config) + dual_earner = main.calc_netto(80000, config=married_config, partner_salary=80000) + assert dual_earner < single_earner + + +def test_calc_netto_partner_salary_zero_equals_single_earner(married_config): + """partner_salary=0 must behave exactly like the single-earner call""" + assert main.calc_netto( + 100000, config=married_config, partner_salary=0 + ) == main.calc_netto(100000, config=married_config) + + +def test_calc_netto_partner_salary_requires_married(default_config): + """partner_salary without is_married must raise""" + with pytest.raises(ValueError, match="is_married"): + main.calc_netto(50000, config=default_config, partner_salary=10000) + + +def test_calc_netto_negative_partner_salary(married_config): + """Negative partner_salary must raise""" + with pytest.raises(ValueError, match="non-negative"): + main.calc_netto(50000, config=married_config, partner_salary=-1) + + +def test_calc_inverse_netto_dual_income_roundtrip(married_config): + """Inverse calculation with a fixed partner salary recovers the gross salary""" + netto = main.calc_netto(80000, config=married_config, partner_salary=50000) + gross = main.calc_inverse_netto(netto, config=married_config, partner_salary=50000) + assert abs(gross - 80000) <= 1 + + +def test_calc_inverse_netto_partner_already_covers_desired(married_config): + """A desired netto already reached by the partner salary alone must raise""" + with pytest.raises(ValueError, match="partner salary alone"): + main.calc_inverse_netto(20000, config=married_config, partner_salary=100000) + + +@pytest.mark.parametrize("year", list(range(2018, 2033))) +def test_calc_netto_all_years_smoke(year): + """calc_netto must produce a plausible result for every supported year, + including the 2027-2032 forecast years""" + config = TaxConfig(year=year, church_tax=0.0) + netto = main.calc_netto(60000, config=config) + assert 30000 < netto < 60000 + + +@patch("sys.stdout", new_callable=StringIO) +def test_verbose_print(mock_stdout, default_config): + """Test that verbose mode prints expected output""" + main.calc_netto(0, verbose=True, config=default_config) + actual_output = mock_stdout.getvalue().strip() + expected_output = ( + "Yearly Evaluation:\n" + + f"Income Tax: {0.0:>12}\n" + + f"Soli: {0.0:>12}\n" + + f"Church Tax: {0.0:>12}\n" + + f"Social Security: {0.0:>12}" + ) + assert actual_output == expected_output + + +def test_calc_netto_with_default_none_config(): + """Test that calc_netto works when config=None (uses default TaxConfig)""" + result = main.calc_netto(30000) + # Should use default TaxConfig (year=2022, etc.) + assert isinstance(result, float) + assert result > 0 + + +def test_calc_inverse_netto_with_default_none_config(): + """Test that calc_inverse_netto works when config=None (uses default TaxConfig)""" + # Use a value that we know works well with Newton's method + # Use explicit year=2022 for stable test behavior + result = main.calc_inverse_netto(30000, config=TaxConfig(year=2022)) + # Should use default TaxConfig + assert isinstance(result, int | float) + assert result > 0 + # Verify the result makes sense (gross should be higher than net) + assert result > 30000 diff --git a/test/test_social_security.py b/test/test_social_security.py new file mode 100644 --- /dev/null +++ b/test/test_social_security.py @@ -0,0 +1,251 @@ +import pytest + +import netto.social_security as social_security +from netto.config import TaxConfig + + +@pytest.fixture +def default_config(): + """Fixture providing default config for tests""" + return TaxConfig( + year=2022, extra_health_insurance=0.014, church_tax=0.09, has_children=False + ) + + +@pytest.mark.parametrize( + "salary,expected", + [ + (0, 0), + (10000, 0.093), + (84600, 0.093), + (84601, 0), + (100000, 0), + ], +) +def test_get_rate_pension(salary, expected, default_config): + """Test pension rate calculation""" + result = social_security.get_rate_pension(salary, default_config) + assert result == expected + + +@pytest.mark.parametrize( + "salary,expected", + [ + (0, 0), + (10000, 0.08), + (58050, 0.08), + (58051, 0), + (100000, 0), + ], +) +def test_get_rate_health(salary, expected, default_config): + """Test health insurance rate calculation""" + result = social_security.get_rate_health(salary, default_config) + assert result == expected + + +@pytest.mark.parametrize( + "salary,expected", + [ + (0, 0), + (10000, 0.093 * 10000), + (84600, 0.093 * 84600), + (84601, 0.093 * 84600), + (100000, 0.093 * 84600), + ], +) +def test_calc_insurance_pension(salary, expected, default_config): + """Test pension insurance calculation""" + result = social_security.calc_insurance_pension(salary, default_config) + assert result == expected + + +@pytest.mark.parametrize( + "salary,expected", + [ + (0, 0), + (10000, 0.08 * 10000), + (58050, 0.08 * 58050), + (58051, 0.08 * 58050), + (100000, 0.08 * 58050), + ], +) +def test_calc_insurance_health(salary, expected, default_config): + """Test health insurance calculation""" + result = social_security.calc_insurance_health(salary, default_config) + assert result == expected + + +def test_calc_deductible_social_security(default_config): + """Test deductible social security calculation""" + assert social_security.calc_deductible_social_security(0, default_config) == 0 + # https://www.lohn-info.de/vorsorgepauschale.html + assert ( + social_security.calc_deductible_social_security(30000, default_config) + == 2456 + 2310 + 563 + ) + + +@pytest.mark.parametrize( + "salary", [0, 10000, 20000, 30000, 40000, 50000, 60000, 70000, 80000, 90000, 100000] +) +def test_sameness_of_calc_social_security(salary, default_config): + """Test that both social security calculation methods give same results""" + result_direct = social_security.calc_social_security(salary, default_config) + result_integration = social_security.calc_social_security_by_integration( + salary, default_config + ) + assert result_direct == result_integration + + +@pytest.mark.parametrize( + "salary", [0, 10000, 20000, 30000, 40000, 50000, 60000, 70000, 80000, 90000, 100000] +) +def test_sameness_of_calc_social_security_different_config(salary): + """Test social security calculation with different config""" + config = TaxConfig(extra_health_insurance=0.015, has_children=True) + result_direct = social_security.calc_social_security(salary, config) + result_integration = social_security.calc_social_security_by_integration( + salary, config + ) + assert abs(result_direct - result_integration) < 0.02 + + +@pytest.mark.parametrize( + "salary,expected", + [ + (0, 0), + (10000, 0.0805), + (58050, 0.0805), + (58051, 0), + (100000, 0), + ], +) +def test_get_rate_health_different_config(salary, expected): + """Test health rate with different extra health insurance""" + config = TaxConfig(year=2022, extra_health_insurance=0.015) + result = social_security.get_rate_health(salary, config) + assert abs(result - expected) < 0.0001 + + +@pytest.mark.parametrize( + "salary,expected", + [ + (0, 0), + (10000, 0.01875), + (58050, 0.01875), + (58051, 0), + (100000, 0), + ], +) +def test_get_rate_nursing_no_children(salary, expected): + """Test nursing rate without children (includes extra rate)""" + config = TaxConfig(year=2022, has_children=False) + result = social_security.get_rate_nursing(salary, config) + assert result == expected + + +@pytest.mark.parametrize( + "salary,expected", + [ + (0, 0), + (10000, 0.01525), + (58050, 0.01525), + (58051, 0), + (100000, 0), + ], +) +def test_get_rate_nursing_with_children(salary, expected): + """Test nursing rate with children (no extra rate)""" + config = TaxConfig(year=2022, has_children=True) + result = social_security.get_rate_nursing(salary, config) + assert result == expected + + +@pytest.mark.parametrize( + "year,average_zusatzbeitrag", + [ + (2018, 0.010), + (2022, 0.013), + (2024, 0.017), + (2025, 0.025), + (2026, 0.029), + (2032, 0.035), # forecast + ], +) +def test_get_rate_health_uses_year_average(year, average_zusatzbeitrag): + """With extra_health_insurance=None, the official year-specific average + Zusatzbeitrag from the data files applies (employee pays half)""" + config = TaxConfig(year=year) + result = social_security.get_rate_health(10000, config) + assert result == pytest.approx(0.073 + average_zusatzbeitrag / 2) + + +def test_get_rate_health_config_overrides_year_average(): + """An explicit extra_health_insurance overrides the year average""" + config = TaxConfig(year=2026, extra_health_insurance=0.019) + result = social_security.get_rate_health(10000, config) + assert result == pytest.approx(0.073 + 0.019 / 2) + + +def test_get_rate_health_zero_override_is_honored(): + """extra_health_insurance=0.0 means no Zusatzbeitrag, not 'use average'""" + config = TaxConfig(year=2026, extra_health_insurance=0.0) + result = social_security.get_rate_health(10000, config) + assert result == pytest.approx(0.073) + + +def test_get_rate_pension_with_default_none_config(): + """Test that get_rate_pension works when config=None""" + result = social_security.get_rate_pension(50000) + assert isinstance(result, float) + assert result >= 0 + + +def test_get_rate_unemployment_with_default_none_config(): + """Test that get_rate_unemployment works when config=None""" + result = social_security.get_rate_unemployment(50000) + assert isinstance(result, float) + assert result >= 0 + + +def test_get_rate_health_with_default_none_config(): + """Test that get_rate_health works when config=None""" + result = social_security.get_rate_health(50000) + assert isinstance(result, float) + assert result >= 0 + + +def test_get_rate_nursing_with_default_none_config(): + """Test that get_rate_nursing works when config=None""" + result = social_security.get_rate_nursing(50000) + assert isinstance(result, float) + assert result >= 0 + + +def test_calc_insurance_pension_with_default_none_config(): + """Test that calc_insurance_pension works when config=None""" + result = social_security.calc_insurance_pension(50000) + assert isinstance(result, float) + assert result >= 0 + + +def test_calc_insurance_health_with_default_none_config(): + """Test that calc_insurance_health works when config=None""" + result = social_security.calc_insurance_health(50000) + assert isinstance(result, float) + assert result >= 0 + + +def test_calc_social_security_with_default_none_config(): + """Test that calc_social_security works when config=None""" + result = social_security.calc_social_security(50000) + assert isinstance(result, float) + assert result >= 0 + + +def test_calc_deductible_social_security_with_default_none_config(): + """Test that calc_deductible_social_security works when config=None""" + result = social_security.calc_deductible_social_security(50000) + assert isinstance(result, int | float) + assert result >= 0 diff --git a/test/test_taxes_children.py b/test/test_taxes_children.py new file mode 100644 --- /dev/null +++ b/test/test_taxes_children.py @@ -0,0 +1,147 @@ +import pytest + +import netto.main as main +import netto.social_security as social_security +import netto.taxes_children as taxes_children +import netto.taxes_income as taxes_income +from netto.config import TaxConfig + + +@pytest.fixture +def married_two_kids(): + """Married couple with two children, no church tax, 2026""" + return TaxConfig(year=2026, is_married=True, num_children=2, church_tax=0.0) + + +@pytest.fixture +def married_childless_reference(): + """Same as married_two_kids but children only via has_children + (nursing surcharge removed, no Kindergeld/Freibetrag)""" + return TaxConfig(year=2026, is_married=True, has_children=True, church_tax=0.0) + + +@pytest.mark.parametrize( + "year,expected_per_child", + [ + (2018, 2328), + (2019, 2388), # July increase: 6 x 194 + 6 x 204 + (2023, 3000), + (2025, 3060), + (2026, 3108), + ], +) +def test_calc_kindergeld_per_year(year, expected_per_child): + """Kindergeld matches the official yearly amounts (first/second child)""" + config = TaxConfig(year=year, num_children=1) + assert taxes_children.calc_kindergeld(config) == expected_per_child + + +def test_calc_kindergeld_scales_with_children(): + config = TaxConfig(year=2026, num_children=3) + assert taxes_children.calc_kindergeld(config) == 3 * 3108 + + +def test_calc_kindergeld_zero_without_children(): + assert taxes_children.calc_kindergeld(TaxConfig(year=2026)) == 0 + + +def test_child_allowance_halved_for_singles(): + """Single parents get half the allowance (other half belongs to the + other parent)""" + married = TaxConfig(year=2026, is_married=True, num_children=1) + single = TaxConfig(year=2026, num_children=1) + assert taxes_children.calc_child_allowance_per_child(married) == 9756 + assert taxes_children.calc_child_allowance_per_child(single) == 9756 / 2 + + +def test_guenstigerpruefung_kindergeld_wins_at_low_income( + married_two_kids, married_childless_reference +): + """At low income the allowance relief is below the Kindergeld, so the + net benefit is exactly the Kindergeld""" + netto_kids = main.calc_netto(30000, config=married_two_kids) + netto_ref = main.calc_netto(30000, config=married_childless_reference) + kindergeld = taxes_children.calc_kindergeld(married_two_kids) + assert netto_kids - netto_ref == pytest.approx(kindergeld, abs=0.02) + + +def test_guenstigerpruefung_freibetrag_wins_at_high_income( + married_two_kids, married_childless_reference +): + """At high income the allowance relief exceeds the Kindergeld, so the + net benefit is larger than the Kindergeld""" + netto_kids = main.calc_netto(150000, config=married_two_kids, partner_salary=80000) + netto_ref = main.calc_netto( + 150000, config=married_childless_reference, partner_salary=80000 + ) + kindergeld = taxes_children.calc_kindergeld(married_two_kids) + assert netto_kids - netto_ref > kindergeld + + +def test_child_benefit_never_below_kindergeld( + married_two_kids, married_childless_reference +): + """The Günstigerprüfung guarantees at least the Kindergeld""" + kindergeld = taxes_children.calc_kindergeld(married_two_kids) + for salary in [0, 20000, 50000, 100000, 200000, 400000]: + netto_kids = main.calc_netto(salary, config=married_two_kids) + netto_ref = main.calc_netto(salary, config=married_childless_reference) + assert netto_kids - netto_ref >= kindergeld - 0.02 + + +def test_soli_and_church_tax_use_fictitious_tax(): + """Soli and church tax are based on the income tax with child + allowances deducted, which is lower than the regular income tax""" + config = TaxConfig(year=2026, is_married=True, num_children=2) + taxable_income = 200000 + income_tax = taxes_income.calc_income_tax_by_integration(taxable_income, config) + assessed, fictitious = taxes_children.apply_guenstigerpruefung( + taxable_income, income_tax, config + ) + assert fictitious < income_tax + # at this income the Freibetrag wins, so the assessed tax reflects the + # allowance deduction plus the Kindergeld Hinzurechnung + kindergeld = taxes_children.calc_kindergeld(config) + assert assessed == pytest.approx(fictitious + kindergeld, abs=0.02) + + +def test_apply_guenstigerpruefung_no_children_passthrough(): + config = TaxConfig(year=2026, is_married=True) + assessed, fictitious = taxes_children.apply_guenstigerpruefung( + 100000, 25000.0, config + ) + assert assessed == 25000.0 + assert fictitious == 25000.0 + + +def test_num_children_implies_has_children(): + """num_children > 0 removes the nursing childless surcharge""" + config = TaxConfig(year=2026, num_children=2) + assert config.has_children is True + reference = TaxConfig(year=2026, has_children=True) + assert social_security.calc_social_security( + 50000, config + ) == social_security.calc_social_security(50000, reference) + + +def test_zero_gross_yields_kindergeld(married_two_kids): + """A household without salary still receives the Kindergeld""" + assert main.calc_netto(0, config=married_two_kids) == pytest.approx( + taxes_children.calc_kindergeld(married_two_kids) + ) + + +def test_num_children_validation(): + with pytest.raises(ValueError): + TaxConfig(num_children=-1) + with pytest.raises(TypeError): + TaxConfig(num_children=2.0) + with pytest.raises(TypeError): + TaxConfig(num_children=True) + + +def test_forecast_years_have_child_data(): + """Child benefits are available for all supported years incl. forecasts""" + for year in range(2018, 2033): + config = TaxConfig(year=year, num_children=1) + assert taxes_children.calc_kindergeld(config) > 0 diff --git a/test/test_taxes_income.py b/test/test_taxes_income.py new file mode 100644 --- /dev/null +++ b/test/test_taxes_income.py @@ -0,0 +1,178 @@ +import pytest + +import netto.taxes_income as taxes_income +from netto.config import TaxConfig + + +@pytest.fixture +def default_config(): + """Fixture providing default config for tests""" + return TaxConfig( + year=2022, extra_health_insurance=0.014, church_tax=0.09, has_children=False + ) + + +@pytest.mark.parametrize( + "taxable_income,expected_rate", + [ + (-1000, 0), + (0, 0), + (10346, 0), + (10347, 0.14), + (14926, 0.2397), + (58596, 0.42), + (58597, 0.42), + (100000, 0.42), + (277826, 0.45), + (277827, 0.45), + ], +) +def test_get_marginal_tax_rate(taxable_income, expected_rate, default_config): + """Test marginal tax rate calculation for various income levels""" + result = taxes_income.get_marginal_tax_rate(taxable_income, default_config) + assert result == expected_rate + + +@pytest.mark.parametrize( + "taxable_income,expected_rate", + [ + (10346, 0), + (10347, 0), + (10346 * 2, 0), + (10347 * 2, 0.14), + ], +) +def test_get_marginal_tax_rate_married(taxable_income, expected_rate): + """Test marginal tax rate for married couples (doubled brackets)""" + config = TaxConfig(year=2022, is_married=True) + result = taxes_income.get_marginal_tax_rate(taxable_income, config) + assert result == expected_rate + + +@pytest.mark.parametrize( + "taxable_income", + [ + 12000, + 0, + 10000, + 20000, + 30000, + 40000, + 50000, + 60000, + 70000, + 80000, + 90000, + 100000, + 300000, + ], +) +def test_sameness_of_calc_income_tax_methods(taxable_income, default_config): + """Test that both income tax calculation methods give similar results""" + result_direct = taxes_income.calc_income_tax(taxable_income, default_config) + result_integration = taxes_income.calc_income_tax_by_integration( + taxable_income, default_config + ) + assert abs(result_direct - result_integration) < 0.1 + + +@pytest.mark.parametrize( + "taxable_income", [10000, 30000, 60000, 100000, 200000, 600000] +) +def test_calc_income_tax_married_equals_splitting(taxable_income, default_config): + """Married income tax must equal the official splitting tariff: 2 * T(zvE/2)""" + married_config = TaxConfig(year=2022, is_married=True) + result = taxes_income.calc_income_tax(taxable_income, married_config) + expected = 2 * taxes_income.calc_income_tax(taxable_income / 2, default_config) + assert result == pytest.approx(expected) + + +@pytest.mark.parametrize("year", list(range(2018, 2033))) +def test_income_tax_methods_agree_all_years(year): + """The exact formula and the integration method must agree for every + supported year - this cross-checks the polynomial coefficients against + the bracket boundaries in the data files""" + config = TaxConfig(year=year, church_tax=0.0) + for taxable_income in [15000, 40000, 80000, 300000]: + direct = taxes_income.calc_income_tax(taxable_income, config) + integrated = taxes_income.calc_income_tax_by_integration(taxable_income, config) + assert abs(direct - integrated) < 2, ( + f"year {year}, taxable income {taxable_income}: " + f"formula {direct} vs integration {integrated}" + ) + + +@pytest.mark.parametrize("taxable_income", [0, 20000, 50000, 100000, 300000]) +def test_sameness_of_calc_income_tax_methods_married(taxable_income): + """Both income tax calculation methods must agree for married couples""" + married_config = TaxConfig(year=2022, is_married=True) + result_direct = taxes_income.calc_income_tax(taxable_income, married_config) + result_integration = taxes_income.calc_income_tax_by_integration( + taxable_income, married_config + ) + assert abs(result_direct - result_integration) < 0.5 + + +@pytest.mark.parametrize( + "year,expected", + [ + (2018, 48964), # 50000 - 1000 (Werbungskosten) - 36 (Sonderausgaben) + (2021, 48964), + (2022, 48764), # Werbungskosten-Pauschbetrag raised to 1200 + (2023, 48734), # Werbungskosten-Pauschbetrag raised to 1230 + (2025, 48734), + ], +) +def test_calc_taxable_income_year_aware_lump_sums(year, expected): + """Test that lump-sum deductions match the year-specific Pauschbeträge""" + config = TaxConfig(year=year) + result = taxes_income.calc_taxable_income(50000, 0, config=config) + assert result == expected + + +def test_calc_taxable_income_married_doubles_sonderausgaben(): + """Married couples get the doubled Sonderausgaben-Pauschbetrag (72 instead of 36)""" + config = TaxConfig(year=2025, is_married=True) + result = taxes_income.calc_taxable_income(50000, 0, config=config) + assert result == 48698 # 50000 - 1230 - 72 + + +def test_calc_taxable_income_dual_earner(): + """Each earner gets their own Werbungskosten-Pauschbetrag""" + config = TaxConfig(year=2025, is_married=True) + result = taxes_income.calc_taxable_income( + 50000, 0, config=config, partner_salary=40000 + ) + assert result == 87468 # (50000 - 1230) + (40000 - 1230) - 72 + + +def test_calc_taxable_income_partner_below_pauschbetrag(): + """The partner's Werbungskosten deduction cannot exceed their income""" + config = TaxConfig(year=2025, is_married=True) + result = taxes_income.calc_taxable_income( + 50000, 0, config=config, partner_salary=500 + ) + assert result == 48698 # partner income fully offset by the lump sum + + +def test_get_marginal_tax_rate_with_default_none_config(): + """Test that get_marginal_tax_rate works when config=None""" + result = taxes_income.get_marginal_tax_rate(50000) + assert isinstance(result, float) + assert 0 <= result <= 1 + + +def test_calc_income_tax_with_default_none_config(): + """Test that calc_income_tax works when config=None""" + # Use explicit year=2022 since calc_income_tax requires const values + # which are not available for 2023-2025 + result = taxes_income.calc_income_tax(50000, config=TaxConfig(year=2022)) + assert isinstance(result, float) + assert result >= 0 + + +def test_calc_income_tax_by_integration_with_default_none_config(): + """Test that calc_income_tax_by_integration works when config=None""" + result = taxes_income.calc_income_tax_by_integration(50000) + assert isinstance(result, float) + assert result >= 0 diff --git a/test/test_taxes_other.py b/test/test_taxes_other.py new file mode 100644 --- /dev/null +++ b/test/test_taxes_other.py @@ -0,0 +1,109 @@ +import pytest + +import netto.taxes_other as taxes_other +from netto.config import TaxConfig + + +@pytest.fixture +def default_config(): + """Fixture providing default config for tests""" + return TaxConfig( + year=2022, extra_health_insurance=0.014, church_tax=0.09, has_children=False + ) + + +@pytest.mark.parametrize( + "income_tax,expected", + [ + (-1000, 0), + (0, 0), + (16956, 0), + (100000, 5500), + ], +) +def test_calc_soli_exact(income_tax, expected, default_config): + """Test solidarity tax calculation with exact values""" + result = taxes_other.calc_soli(income_tax, default_config) + assert result == expected + + +@pytest.mark.parametrize( + "income_tax,expected", + [ + (16957, 0.119), + (17514.96, 66.48), + (26913.96, 1185.0), + ], +) +def test_calc_soli_approximate(income_tax, expected, default_config): + """Test solidarity tax calculation with approximate values""" + result = taxes_other.calc_soli(income_tax, default_config) + assert abs(result - expected) < 0.1 + + +@pytest.mark.parametrize( + "income_tax,expected", + [ + (-1000, 0), + (0, 0), + (10000, 900), + ], +) +def test_calc_church_tax(income_tax, expected, default_config): + """Test church tax calculation""" + result = taxes_other.calc_church_tax(income_tax, default_config) + assert result == expected + + +@pytest.mark.parametrize( + "income_tax,expected", + [ + (33912, 0), # doubled exemption threshold (2 * 16956) for joint assessment + (33913, 0.12), + (40000, 724.47), + (100000, 5500), # capped at 5.5% regardless of marital status + ], +) +def test_calc_soli_married(income_tax, expected): + """Test that the soli exemption threshold doubles for married couples""" + config = TaxConfig(year=2022, is_married=True) + result = taxes_other.calc_soli(income_tax, config) + assert abs(result - expected) < 0.01 + + +@pytest.mark.parametrize( + "income_tax,expected", + [ + (1944, 0), # doubled exemption threshold (2 * 972) pre-2021 + (2000, 11.2), + (100000, 5500), + ], +) +def test_calc_soli_married_pre_2021(income_tax, expected): + """Test married soli threshold doubling with pre-2021 parameters""" + config = TaxConfig(year=2018, is_married=True) + result = taxes_other.calc_soli(income_tax, config) + assert abs(result - expected) < 0.01 + + +def test_calc_soli_married_below_single_threshold_zone(default_config): + """A tax amount above the single but below the married threshold + must yield soli for singles but none for married couples""" + income_tax = 30000 # 2022: single threshold 16956, married threshold 33912 + married_config = TaxConfig(year=2022, is_married=True) + assert taxes_other.calc_soli(income_tax, default_config) > 0 + assert taxes_other.calc_soli(income_tax, married_config) == 0 + + +def test_calc_soli_with_default_none_config(): + """Test that calc_soli works when config=None""" + result = taxes_other.calc_soli(10000) + assert isinstance(result, float) + assert result >= 0 + + +def test_calc_church_tax_with_default_none_config(): + """Test that calc_church_tax works when config=None""" + result = taxes_other.calc_church_tax(10000) + assert isinstance(result, float) + assert result >= 0
diff --git a/test/test_config.py b/test/test_config.py
new file mode 100644
--- /dev/null
+++ b/test/test_config.py
@@ -0,0 +1,55 @@
+import pytest
+
+from netto.config import TaxConfig
+
+
+def test_taxconfig_defaults():
+ """Test that TaxConfig uses correct default values"""
+ config = TaxConfig()
+ assert config.year == 2025
+ assert config.has_children is False
+ assert config.is_married is False
+ assert config.extra_health_insurance is None # year-specific average
+ assert config.church_tax == 0.09
+
+
+def test_taxconfig_custom_values():
+ """Test creating TaxConfig with custom values"""
+ config = TaxConfig(
+ year=2025,
+ has_children=True,
+ is_married=True,
+ extra_health_insurance=0.02,
+ church_tax=0.08,
+ )
+ assert config.year == 2025
+ assert config.has_children is True
+ assert config.is_married is True
+ assert config.extra_health_insurance == 0.02
+ assert config.church_tax == 0.08
+
+
+def test_taxconfig_validation_year_range():
+ """Test that year validation works"""
+ with pytest.raises(ValueError):
+ TaxConfig(year=2017) # Too early
+ with pytest.raises(ValueError):
+ TaxConfig(year=2033) # Too late
+
+
+def test_taxconfig_validation_negative_rates():
+ """Test that negative rates are rejected"""
+ with pytest.raises(ValueError):
+ TaxConfig(extra_health_insurance=-0.01)
+ with pytest.raises(ValueError):
+ TaxConfig(church_tax=-0.01)
+
+
+def test_taxconfig_validation_type_errors():
+ """Test that type validation works"""
+ with pytest.raises(TypeError):
+ TaxConfig(year="2022") # String instead of int
+ with pytest.raises(TypeError):
+ TaxConfig(has_children="True") # String instead of bool
+ with pytest.raises(TypeError):
+ TaxConfig(is_married=1) # Int instead of bool
diff --git a/test/test_data_loader.py b/test/test_data_loader.py
new file mode 100644
--- /dev/null
+++ b/test/test_data_loader.py
@@ -0,0 +1,447 @@
+import pytest
+from pydantic import ValidationError
+
+from netto.data_loader import (
+ Deductions,
+ PensionFactor,
+ SocialSecurity,
+ SocialSecurityEntry,
+ SoliCurve,
+ TaxBracket,
+ TaxCurve,
+ correction_factor_pensions,
+ deductions,
+ load_all_deductions,
+ load_all_pension_factors,
+ load_all_social_security,
+ load_all_soli,
+ load_all_tax_curves,
+ load_deductions,
+ load_pension_factor,
+ load_social_security,
+ load_soli,
+ load_tax_curve,
+ social_security_curve,
+ soli_curve,
+ tax_curve,
+)
+
+# Tests for Pydantic Models
+
+
+def test_tax_bracket_valid():
+ """Test creating a valid TaxBracket"""
+ bracket = TaxBracket(step=10000, rate=0.14, const=[100, 200])
+ assert bracket.step == 10000