"""Logo Yazılım 2021–2025 KAP dosyalarıyla uçtan uca testler.
Örnek dosyalar varsayılan olarak ../../Finansallar klasöründen okunur; KAP_SAMPLES ile değiştirilebilir.
"""
import glob
import io
import os
import pytest
SAMPLES = os.environ.get("KAP_SAMPLES", os.path.join(os.path.dirname(__file__), "..", "..", "Finansallar"))
FILES = sorted(glob.glob(os.path.join(SAMPLES, "*.xls")))
pytestmark = pytest.mark.skipif(not FILES, reason="Örnek KAP dosyaları bulunamadı")
os.environ.setdefault("ADMIN_PASSWORD", "test-sifre")
os.environ.setdefault("COOKIE_SECURE", "0")
@pytest.fixture(scope="module")
def analysis():
from app.analysis import build
from app.kap_parser import parse
return build([parse(open(f, "rb").read(), os.path.basename(f)) for f in FILES])
def sade(a, st):
return {r["id"]: r["values"] for r in a.sade[st]}
def test_years_and_units(analysis):
assert analysis.years == [2021, 2022, 2023, 2024, 2025]
assert analysis.base_year == 2020
# 2021 dosyası tam TL, diğerleri bin TL olarak açıklanmış
assert analysis.units == {2021: "TL", 2022: "bin TL", 2023: "bin TL", 2024: "bin TL", 2025: "bin TL"}
assert not analysis.warnings
def test_known_values_in_tl(analysis):
f = sade(analysis, "FDT")
assert f["NAKIT"][2021] == pytest.approx(259_390_060)
assert f["NAKIT"][2022] == pytest.approx(229_151_000)
assert f["AKTIF"][2025] == pytest.approx(8_322_175_000)
def test_balance_sheet_balances(analysis):
f = sade(analysis, "FDT")
for y in analysis.columns:
assert f["AKTIF"][y] == pytest.approx(f["PASIF"][y], abs=1)
assert f["DV"][y] + f["DUV"][y] == pytest.approx(f["AKTIF"][y], abs=1)
assert f["KVYK"][y] + f["UVYK"][y] + f["OZK"][y] == pytest.approx(f["PASIF"][y], abs=1)
def test_sade_rows_add_up_to_kap_totals(analysis):
from app.mapping import SADE, residual_parts
for st, spec in SADE.items():
v = sade(analysis, st)
for row in spec:
if row.get("calc", "").startswith("residual:"):
total = row["calc"].split(":")[1]
parts = residual_parts(spec, total, row["id"]) + [row["id"]]
for y in analysis.columns:
assert sum(v[p][y] for p in parts) == pytest.approx(v[total][y], abs=1)
def test_kz_flow(analysis):
k = sade(analysis, "KZ")
for y in analysis.years:
assert k["SATIS"][y] + k["SMM"][y] == pytest.approx(k["BRUT"][y], abs=1)
assert k["VOK"][y] + k["VERGI"][y] + k["DURD"][y] == pytest.approx(k["NETKAR"][y], abs=1)
assert k["EPS"][2025] == 16.0 # pay başına kazanç TL'dir, çarpılmaz
def test_missing_items_are_zero(analysis):
f = sade(analysis, "FDT")
assert f["SATAMAC"][2021] == 0 # yalnızca 2024'te var
assert f["SATAMAC"][2024] > 0
def test_ratios_scale_invariant(analysis):
from app.ratios import compute
base = compute(analysis.sade, analysis.columns, {})
doubled = compute(analysis.sade, analysis.columns, {y: 2.0 for y in analysis.columns})
for a, b in zip(base, doubled):
for y in analysis.years:
if a["unit"] == "TL":
assert b["values"][y] == pytest.approx(2 * a["values"][y])
elif a["values"][y] is not None:
assert b["values"][y] == pytest.approx(a["values"][y])
def test_ratio_formulas(analysis):
from app.ratios import compute
r = {x["id"]: x["values"] for x in compute(analysis.sade, analysis.columns, {})}
f, k = sade(analysis, "FDT"), sade(analysis, "KZ")
y = 2025
assert r["L1"][y] == pytest.approx(f["DV"][y] / f["KVYK"][y])
assert r["F1"][y] == pytest.approx((f["KVYK"][y] + f["UVYK"][y]) / f["AKTIF"][y])
assert r["D7"][y] == pytest.approx(k["SATIS"][y] / ((f["AKTIF"][y] + f["AKTIF"][2024]) / 2))
assert r["K1"][2021] == pytest.approx(k["NETKAR"][2021] / ((f["OZK"][2021] + f["OZK"][2020]) / 2))
assert r["B5"][y] == pytest.approx(360 / (k["SATIS"][y] / ((f["TA_KV"][y] + f["TA_KV"][2024]) / 2)))
def test_excel_export_opens(analysis):
from openpyxl import load_workbook
from app.excel_export import export
data = export(analysis, {2023: 1.5}, "J62", "Bilgisayar programlama", {"L1": {2023: 1.4}}, "## Başlık\nmetin")
wb = load_workbook(io.BytesIO(data))
assert wb.sheetnames == ["Bilgi", "Sade FDT", "Sade KZ", "Oranlar", "Detay FDT", "Detay KZ",
"Detay Nakit Akış", "Özkaynak Değişim", "BD-TCMB Karşılaştırma", "Yorum"]
ws = wb["Sade FDT"]
assert ws["E4"].value == 1.5 # 2023 çarpanı (B=2020, C=2021, D=2022, E=2023)
assert wb["Sade KZ"]["E4"].value == "='Sade FDT'!E4"
assert str(wb["Oranlar"]["D6"].value).startswith("=IFERROR(")
@pytest.fixture(scope="module")
def client(tmp_path_factory):
os.environ["DB_PATH"] = str(tmp_path_factory.mktemp("db") / "t.db")
from fastapi.testclient import TestClient
from app import db
db.DB_PATH = os.environ["DB_PATH"]
from app.main import app
db.init()
return TestClient(app)
def test_membership(client):
files = [("files", (os.path.basename(f), open(f, "rb").read(), "application/vnd.ms-excel")) for f in FILES]
# girişsiz analiz yok
assert client.post("/api/analyze", files=files).status_code == 401
# yayınlanan analizler girişsiz de açılır ve Excel'i indirilir
assert client.get("/api/saved").status_code == 200
assert client.get("/api/auth/me").json()["user"] is None
# kayıt kuralları
assert client.post("/api/auth/register", json={"username": "a", "password": "uzunsifre1"}).status_code == 400
assert client.post("/api/auth/register", json={"username": "ayse", "password": "kisa"}).status_code == 400
assert client.post("/api/auth/register", json={"username": "ayse", "password": "ayse"}).status_code == 400
r = client.post("/api/auth/register", json={"username": "ayse.k", "password": "uzunsifre1"})
assert r.status_code == 200, r.text
assert client.get("/api/auth/me").json()["user"] == {"username": "ayse.k"}
# aynı ad (büyük/küçük harf fark etmez) ikinci kez alınamaz
assert client.post("/api/auth/register", json={"username": "AYSE.K", "password": "uzunsifre2"}).status_code == 409
r = client.post("/api/analyze", files=files)
assert r.status_code == 200
sid = r.json()["id"]
# çıkış yapınca o analiz oturumu kullanılamaz
client.post("/api/auth/logout")
assert client.post(f"/api/analysis/{sid}/ratios", json={}).status_code == 401
# yanlış şifre, sonra doğru şifre
assert client.post("/api/auth/login", json={"username": "ayse.k", "password": "yanlis-sifre"}).status_code == 401
assert client.post("/api/auth/login", json={"username": "Ayse.K", "password": "uzunsifre1"}).status_code == 200
assert client.post(f"/api/analysis/{sid}/ratios", json={}).status_code == 200
# başka üye bu oturumu kullanamaz
client.post("/api/auth/logout")
client.post("/api/auth/register", json={"username": "mehmet", "password": "baskasifre9"})
assert client.post(f"/api/analysis/{sid}/ratios", json={}).status_code == 403
# test_api_flow bu üyeyle devam eder
def test_api_flow(client):
files = [("files", (os.path.basename(f), open(f, "rb").read(), "application/vnd.ms-excel")) for f in FILES]
r = client.post("/api/analyze", files=files)
assert r.status_code == 200, r.text
j = r.json()
assert j["years"] == [2021, 2022, 2023, 2024, 2025]
sid = j["id"]
r = client.post(f"/api/analysis/{sid}/ratios", json={"multipliers": {"2025": 1.2}, "sector": "J62"})
assert r.status_code == 200
assert len(r.json()["ratios"]) == 54
r = client.post(f"/api/analysis/{sid}/excel", json={"groups": ["oranlar"]})
assert r.status_code == 200 and r.content[:2] == b"PK"
# anahtar yokken yorum kapalı
assert client.get("/api/config").json()["deepseek"] is False
assert client.post(f"/api/analysis/{sid}/comment", json={}).status_code == 503
# birim elle değiştirilebilir
r = client.post(f"/api/analysis/{sid}/units", json={"units": {"2021": "bin TL"}})
assert r.json()["files"][0]["unit"] == "bin TL"
def test_bad_upload(client):
r = client.post("/api/analyze", files=[("files", ("x.xls", b"<html><body>merhaba</body></html>", "text/html"))])
assert r.status_code == 400
def test_admin(client):
assert client.get("/api/admin/settings").status_code == 401
assert client.post("/api/admin/login", json={"password": "yanlis"}).status_code == 401
r = client.post("/api/admin/login", json={"password": "test-sifre"})
assert r.status_code == 200
H = {"X-Requested-With": "kap"}
# CSRF başlığı olmadan yazma reddedilir
assert client.put("/api/admin/settings", json={"daily_limit": 5}).status_code == 403
r = client.put("/api/admin/settings", json={"deepseek_key": "sk-test1234abcd", "daily_limit": 5}, headers=H)
s = r.json()
assert s["has_key"] and s["key_hint"] == "••••abcd" and "sk-test" not in r.text
assert client.get("/api/config").json()["deepseek"] is True
r = client.put("/api/admin/sectors/J62/values", json={"values": [{"year": 2023, "ratio_id": "L1", "value": 1.38}]},
headers=H)
assert r.json()["values"]["L1"]["2023"] == 1.38
r = client.post("/api/admin/sectors/J62/csv", headers=H,
files={"file": ("s.csv", "oran_kodu;oran_adi;birim;2024\nF1;Kaldıraç;%;45,5\n".encode(), "text/csv")})
assert r.json()["imported"] == 1 and r.json()["values"]["F1"]["2024"] == 45.5
client.put("/api/admin/settings", json={"clear_key": True}, headers=H)
assert client.get("/api/config").json()["deepseek"] is False
def test_inflation_auto(client):
files = [("files", (os.path.basename(f), open(f, "rb").read(), "application/vnd.ms-excel")) for f in FILES]
sid = client.post("/api/analyze", files=files).json()["id"]
j = client.post(f"/api/analysis/{sid}/ratios", json={"mult_mode": "auto", "index_series": "TUFE"}).json()
m = j["multipliers"]
assert j["inflation"]["target"] == 2025
assert m["2025"] == pytest.approx(1.0)
assert m["2021"] == pytest.approx(3513.87 / 686.95) # KGK: hedef Aralık / ilgili Aralık
assert m["2020"] == pytest.approx(3513.87 / 504.81)
# hedef yıl değiştirilebilir, Yİ-ÜFE seçilebilir
m2 = client.post(f"/api/analysis/{sid}/ratios", json={"mult_mode": "auto", "index_series": "YIUFE",
"target_year": 2024}).json()["multipliers"]
assert m2["2024"] == pytest.approx(1.0) and m2["2022"] == pytest.approx(3746.52 / 2021.19)
# elle modda gönderilen çarpanlar kullanılır
m3 = client.post(f"/api/analysis/{sid}/ratios", json={"mult_mode": "manual", "multipliers": {"2023": 1.7}}).json()
assert m3["multipliers"]["2023"] == 1.7 and m3["multipliers"]["2024"] == 1.0 and m3["inflation"] is None
# Excel: katsayılar endeks sayfasına formülle bağlı
from openpyxl import load_workbook
r = client.post(f"/api/analysis/{sid}/excel", json={"mult_mode": "auto", "groups": ["sade_fdt"]})
wb = load_workbook(io.BytesIO(r.content))
assert "Enflasyon Katsayıları" in wb.sheetnames
assert wb["Sade FDT"]["C4"].value == "='Enflasyon Katsayıları'!$C$8"
assert wb["Enflasyon Katsayıları"]["B8"].value == 686.95
def test_seeded_j62_sector(client):
s = next(x for x in client.get("/api/config").json()["sectors"] if x["code"] == "J62")
assert s["years"] == [2019, 2020, 2021, 2022, 2023, 2024, 2025] and "TCMB" in s["source"]
from app import db
v = db.sector_values("J62")
assert v["L1"][2025] == pytest.approx(242.52, abs=0.01) # TCMB Q, yüzde
assert v["K1"].get(2021) is None # 2023 öncesi yayımlanmamış
def test_tcmb_import_file():
from app.tcmb_import import parse_kartil
from app.ratios import TCMB
p = os.path.join(os.path.dirname(__file__), "fixtures", "tcmb_62_KARTIL_GENEL_2023-2025.xlsx")
name, vals = parse_kartil(open(p, "rb").read())
assert name.startswith("Bilgisayar programlama")
assert {r["id"] for r in TCMB} == set(vals)
assert vals["L1"][2023] == pytest.approx(226.7748640040184)
assert vals["D7"][2024] == pytest.approx(1.098045553017807)
def test_tcmb_import_endpoint(client):
H = {"X-Requested-With": "kap"}
client.post("/api/admin/login", json={"password": "test-sifre"})
p = os.path.join(os.path.dirname(__file__), "fixtures", "tcmb_62_KARTIL_GENEL_2023-2025.xlsx")
r = client.post("/api/admin/sectors/C27/tcmb", headers=H, files={"file": ("62.xlsx", open(p, "rb").read())})
assert r.status_code == 200, r.text
assert r.json()["years"] == [2023, 2024, 2025] and r.json()["imported"] > 100
r = client.post("/api/admin/sectors/C27/tcmb", headers=H, files={"file": ("x.xlsx", b"bozuk")})
assert r.status_code == 400
def test_mapping_and_double_count_warning(client, monkeypatch):
files = [("files", (os.path.basename(f), open(f, "rb").read(), "application/vnd.ms-excel")) for f in FILES]
an = client.post("/api/analyze", files=files).json()
sid = an["id"]
keys = {c["label"]: c["key"] for c in an["unmapped"] if c["section"] == "dönen varlıklar"}
sade = lambda j, i: next(r for r in j["sade"]["FDT"] if r["id"] == i)["values"]
# Türev araçları finansal yatırımlara eşle: Diğer Dönen Varlıklar azalır, toplam değişmez
j = client.post(f"/api/analysis/{sid}/mapping", json={"items": [{"key": keys["Türev Araçlar"], "target": "FY_KV"}]}).json()
assert sade(j, "FY_KV")["2021"] == pytest.approx(sade(an, "FY_KV")["2021"] + 7_626_652, rel=1e-3)
assert sade(j, "DV")["2021"] == sade(an, "DV")["2021"]
assert sade(j, "DDV")["2021"] < sade(an, "DDV")["2021"]
assert "Türev Araçlar" not in [c["label"] for c in j["unmapped"] if c["section"] == "dönen varlıklar"]
# Alt kalemi üst kalemine tekrar eşlemek çift sayım → uyarı
child = next(c for c in an["unmapped"] if c["label"] == "İlişkili Olmayan Taraflara Diğer Borçlar"
and c["section"] == "kısa vadeli yükümlülükler")
assert child["parent"] == "Diğer Borçlar"
j = client.post(f"/api/analysis/{sid}/mapping", json={"items": [{"key": child["key"], "target": "DB_KV"}]}).json()
assert any("eksiye düştü" in w for w in j["warnings"])
# geçersiz hedef reddedilir; boş liste eşleştirmeleri kaldırır
assert client.post(f"/api/analysis/{sid}/mapping", json={"items": [{"key": child["key"], "target": "AKTIF"}]}).status_code == 400
# pasif kalemi aktif satıra eşlenemez
assert client.post(f"/api/analysis/{sid}/mapping", json={"items": [{"key": child["key"], "target": "FY_KV"}]}).status_code == 400
j = client.post(f"/api/analysis/{sid}/mapping", json={"items": []}).json()
assert j["mapping"] == [] and not j["warnings"]
# DeepSeek önerisi (DeepSeek taklit edilir): geçersiz hedefler ayıklanır
from app import deepseek, db
db.set_setting("deepseek_key", "sk-test")
async def fake(payload):
nos = {k["kalem"]: k["no"] for k in payload["kalemler"] if k["bolum"] in ("dönen varlıklar", "kısa vadeli yükümlülükler")}
nos["Türev Araçlar"] = next(k["no"] for k in payload["kalemler"] if k["kalem"] == "Türev Araçlar" and k["bolum"] == "dönen varlıklar")
return [{"no": nos["Türev Araçlar"], "karar": "hedef", "hedef": "FY_KV", "gerekce": "finansal araç"},
{"no": nos["İlişkili Olmayan Taraflara Diğer Borçlar"], "karar": "alt_kalem", "hedef": None},
{"no": 1, "karar": "hedef", "hedef": "UYDURMA"}]
monkeypatch.setattr(deepseek, "suggest_mapping", fake)
r = client.post(f"/api/analysis/{sid}/mapping/suggest").json()["suggestions"]
assert any(s["decision"] == "hedef" and s["target"] == "FY_KV" for s in r)
assert all(s["target"] in (None, "FY_KV") for s in r)
db.set_setting("deepseek_key", None)
def test_saved_analyses(client):
from openpyxl import load_workbook
items = client.get("/api/saved").json()["items"]
logo = next(i for i in items if i["id"] == "logo") # hazır yüklenen örnek
assert logo["years"] == [2021, 2022, 2023, 2024, 2025] and logo["sector"] == "J62"
j = client.post("/api/saved/logo/open").json()
assert j["analysis"]["years"] == [2021, 2022, 2023, 2024, 2025] and j["settings"]["sector"] == "J62"
r = client.get("/api/saved/logo/excel")
assert r.status_code == 200 and "Logo" in r.headers["content-disposition"]
wb = load_workbook(io.BytesIO(r.content))
assert "Oranlar" in wb.sheetnames
# sektör satırları dolu (J62 TCMB verisi)
vals = [c.value for row in wb["Oranlar"].iter_rows() for c in row if isinstance(c.value, float)]
assert vals
# admin olmadan yayınlanamaz
client.cookies.clear()
sid = j["analysis"]["id"]
assert client.post(f"/api/admin/saved?sid={sid}", json={"title": "x"},
headers={"X-Requested-With": "kap"}).status_code == 401
client.post("/api/admin/login", json={"password": "test-sifre"})
assert client.get("/api/config").json()["is_admin"] is True
H = {"X-Requested-With": "kap"}
r = client.post(f"/api/admin/saved?sid={sid}", headers=H,
json={"title": "Logo TÜFE düzeltmeli", "mult_mode": "auto", "sector": "J62", "comment": "deneme"})
assert r.status_code == 200, r.text
new_id = r.json()["id"]
assert new_id.startswith("logo-2021-2025")
j2 = client.post(f"/api/saved/{new_id}/open").json()
assert j2["settings"]["mult_mode"] == "auto" and j2["settings"]["comment"] == "deneme"
wb = load_workbook(io.BytesIO(client.get(f"/api/saved/{new_id}/excel").content))
assert "Enflasyon Katsayıları" in wb.sheetnames and "Yorum" in wb.sheetnames
client.delete(f"/api/admin/saved/{new_id}", headers=H)
assert new_id not in [i["id"] for i in client.get("/api/saved").json()["items"]]
assert client.post("/api/saved/yok/open").status_code == 404
def test_sheet_view(client):
assert client.get("/tablo").status_code == 200
j = client.get("/api/saved/logo/sheets").json()
names = [s["name"] for s in j["sheets"]]
assert names[:3] == ["Sade FDT", "Sade KZ", "Oranlar"] and "Detay Nakit Akış" in names
fdt = j["sheets"][0]["rows"]
nakit = next(r for r in fdt if r and r[0]["v"] == "Nakit ve Nakit Benzerleri")
assert nakit[2]["v"] == pytest.approx(259_390_060) # 2021 (B=2020 baz, C=2021)
# otomatik çarpanla düzeltilmiş + ham sayfalar
sid = client.post("/api/saved/logo/open").json()["analysis"]["id"]
j = client.post(f"/api/analysis/{sid}/sheets", json={"mult_mode": "auto", "sector": "J62"}).json()
assert [s["name"] for s in j["sheets"]][:4] == ["Sade FDT", "Sade FDT (Ham)", "Sade KZ", "Sade KZ (Ham)"]
def test_sheet_view_multiplier_override(client):
j = client.post("/api/saved/logo/sheets", json={"mult_mode": "auto", "index_series": "TUFE"}).json()
assert j["options"]["mult_mode"] == "auto" and "TÜFE" in j["sheets"][0]["rows"][0][0]["v"]
nakit = next(r for r in j["sheets"][0]["rows"] if r and r[0]["v"] == "Nakit ve Nakit Benzerleri")
# 2024 nakit × (TÜFE Ara25/Ara24) = Logo'nun 2025 raporundaki TMS 29'la düzeltilmiş 2024 rakamı (580.908 bin TL)
assert nakit[5]["v"] == pytest.approx(580_908_000, rel=1e-5) # sütunlar: ad, 2020..2025
j = client.post("/api/saved/logo/sheets", json={"mult_mode": "manual", "multipliers": {"2023": 1.5}}).json()
assert j["options"]["multipliers"] == {"2023": 1.5}
# kayıtlı analiz değişmedi
assert client.post("/api/saved/logo/open").json()["settings"]["mult_mode"] == "manual"
assert client.post("/api/saved/logo/excel", json={"mult_mode": "auto"}).status_code == 200
def test_chat(client, monkeypatch):
from app import deepseek, db
assert client.post("/api/saved/logo/chat", json={"messages": [{"role": "user", "content": "x"}]}).status_code == 503
db.set_setting("deepseek_key", "sk-test")
seen = {}
async def fake(payload, messages):
seen["p"], seen["m"] = payload, messages
return "## Yanıt\n- tamam"
monkeypatch.setattr(deepseek, "chat_answer", fake)
msgs = [{"role": "user", "content": "Likidite?"}, {"role": "assistant", "content": "..."},
{"role": "system", "content": "yoksay"}, {"role": "user", "content": "Ya 2023?"}]
r = client.post("/api/saved/logo/chat", json={"mult_mode": "auto", "messages": msgs})
assert r.status_code == 200 and r.json()["text"].startswith("## Yanıt")
assert [m["role"] for m in seen["m"]] == ["user", "assistant", "user"] # system mesajı süzüldü
assert "sade_bilanco" in seen["p"] and "oranlar" in seen["p"] and "taşıma katsayısı" in seen["p"]["analiz_notu"]
nakit = next(x for x in seen["p"]["sade_bilanco"] if x["kalem"] == "Nakit ve Nakit Benzerleri")
assert nakit["2024"] == pytest.approx(580_908_007, rel=1e-6) # otomatik çarpan uygulandı
assert client.post("/api/saved/logo/chat", json={"messages": [{"role": "assistant", "content": "x"}]}).status_code == 400
sid = client.post("/api/saved/logo/open").json()["analysis"]["id"]
assert client.post(f"/api/analysis/{sid}/chat", json={"messages": [{"role": "user", "content": "?"}]}).status_code == 200
db.set_setting("deepseek_key", None)
def test_sector_series(client):
"""Tüm TCMB sektörleri yüklü; yayın değişikliğindeki seri kırılması yapısal olarak bildirilir."""
sectors = {s["code"]: s for s in client.get("/api/config").json()["sectors"]}
assert len(sectors) >= 77
d35 = sectors["D35"]["series"] # testlerde verisi değiştirilmeyen bir sektör
assert d35["break_year"] == 2023
assert [(e["first"], e["last"]) for e in d35["editions"]] == [(2019, 2022), (2023, 2025)]
assert any(2023 in ys for ys in d35["from_old"].values()) # ilk yılın devir hızları eski yayından
# test_admin J62'ye CSV yükledi: hazır verinin kırılma bilgisi artık geçerli değil, temizlenmiş olmalı
assert sectors["J62"]["series"] is None
assert sectors["P85"]["name"] == "Eğitim" # kısa sektör adı doğru okunur
assert sectors["G45"]["series"]["break_year"] is None # yeni yayında yok, kırılma yok
Tüm kodlar
KAP Finansal Analiz
Şirketlerin finansal tablolarını yıllar arası analiz eden web uygulaması
Lisans bilgisi projenin LICENSE dosyasında.