186 lines
8.5 KiB
Python
Executable File
186 lines
8.5 KiB
Python
Executable File
"""Uji parser ingestion dengan respons palsu (tanpa internet)."""
|
|
import json
|
|
from datetime import date
|
|
|
|
import config
|
|
from ingestion import gdelt, google_news, portals
|
|
from ingestion.common import build_record, media_from_url, parse_date_any, validate_record, write_records
|
|
|
|
RSS = """<?xml version="1.0"?><rss version="2.0"><channel>
|
|
<item><title>Karhutla Riau meluas - ANTARA News</title><link>https://news.google.com/rss/articles/abc?oc=5</link>
|
|
<pubDate>Mon, 02 Sep 2024 08:30:00 GMT</pubDate><description><a>Karhutla Riau meluas</a></description>
|
|
<source url="https://www.antaranews.com">ANTARA News</source></item></channel></rss>"""
|
|
|
|
HTML = """<html><head><meta property="og:title" content="Kabut Asap Selimuti Pekanbaru">
|
|
<meta property="article:published_time" content="2024-09-15T10:00:00+07:00"></head><body><article>
|
|
<p>Kabut asap tebal menyelimuti Kota Pekanbaru sejak pagi akibat karhutla di sekitar wilayah Riau.</p>
|
|
<p>Baca juga: berita lain</p></article></body></html>"""
|
|
|
|
|
|
class FakeResp:
|
|
def __init__(self, content=b"", text="", js=None):
|
|
self.content, self.text, self._js = content, text, js
|
|
|
|
status_code = 200
|
|
|
|
def raise_for_status(self): pass
|
|
def json(self):
|
|
if self._js is None:
|
|
raise ValueError("bukan json")
|
|
return self._js
|
|
|
|
|
|
class FakeSession:
|
|
def __init__(self, resp): self.resp = resp
|
|
def get(self, *a, **k): return self.resp
|
|
|
|
|
|
def test_parse_date():
|
|
assert parse_date_any("20240902T083000Z") == "2024-09-02T15:30:00"
|
|
assert parse_date_any("Mon, 02 Sep 2024 08:30:00 GMT") == "2024-09-02T15:30:00"
|
|
assert parse_date_any("bukan tanggal") is None
|
|
|
|
|
|
def test_media_from_url():
|
|
assert media_from_url("https://www.detik.com/x") == "Detik.com"
|
|
assert media_from_url("https://news.detik.com/x") == "Detik.com"
|
|
assert media_from_url("https://kompas.com/x") == "kompas.com"
|
|
|
|
|
|
def test_validate():
|
|
ok = build_record(judul="a", url="https://x.com/1", tanggal="2024-01-01T00:00:00", sumber="X", sumber_data="t")
|
|
assert validate_record(ok)[0]
|
|
assert validate_record({**ok, "tanggal_publikasi": None}) == (False, "tanggal_kosong_atau_tidak_terbaca")
|
|
|
|
|
|
def test_google_news_parse(monkeypatch):
|
|
monkeypatch.setattr("time.sleep", lambda s: None)
|
|
recs = list(google_news.collect(["karhutla"], date(2024, 9, 1), date(2024, 9, 3), FakeSession(FakeResp(content=RSS.encode())), 7))
|
|
assert recs[0]["judul"] == "Karhutla Riau meluas"
|
|
assert recs[0]["sumber"] == "ANTARA"
|
|
assert recs[0]["tanggal_publikasi"] == "2024-09-02T15:30:00"
|
|
|
|
|
|
def test_gdelt_parse(monkeypatch):
|
|
monkeypatch.setattr("time.sleep", lambda s: None)
|
|
js = {"articles": [{"url": "https://www.cnnindonesia.com/nasional/1", "title": "Karhutla Jambi", "seendate": "20240902T083000Z"}]}
|
|
recs = list(gdelt.collect(["karhutla"], date(2024, 9, 1), date(2024, 9, 3), FakeSession(FakeResp(js=js)), 7))
|
|
assert recs[0]["sumber"] == "CNN Indonesia" and recs[0]["tanggal_publikasi"] == "2024-09-02T15:30:00"
|
|
|
|
|
|
def test_fetch_article():
|
|
art = portals.fetch_article("https://x/1", FakeSession(FakeResp(text=HTML)))
|
|
assert art["judul"] == "Kabut Asap Selimuti Pekanbaru"
|
|
assert art["tanggal"] == "2024-09-15T10:00:00"
|
|
assert "Pekanbaru" in art["isi"] and "Baca juga" not in art["isi"]
|
|
|
|
|
|
def test_write_records_memisah_reject(tmp_path, monkeypatch):
|
|
monkeypatch.setattr(config, "RAW_LOCAL_DIR", tmp_path / "raw")
|
|
monkeypatch.setattr(config, "REPORT_DIR", tmp_path / "rep")
|
|
good = build_record(judul="a", url="https://x.com/1", tanggal="2024-03-05T10:00:00", sumber="X", sumber_data="t")
|
|
bad = build_record(judul="b", url="https://x.com/2", tanggal=None, sumber="X", sumber_data="t")
|
|
st = write_records([good, bad], "t", "run1")
|
|
assert st["valid"] == 1 and st["rejected"] == 1
|
|
f = tmp_path / "raw" / "t" / "2024-03" / "t_run1.jsonl"
|
|
assert json.loads(f.read_text().splitlines()[0])["judul"] == "a"
|
|
|
|
|
|
def test_gdelt_berhenti_bila_terus_gagal(monkeypatch):
|
|
import pytest
|
|
monkeypatch.setattr("time.sleep", lambda s: None)
|
|
|
|
class Bad(FakeResp):
|
|
status_code = 429
|
|
text = "Please limit requests to one every 5 seconds"
|
|
|
|
with pytest.raises(RuntimeError, match="berturut-turut"):
|
|
list(gdelt.collect(["karhutla"], date(2026, 10, 1), date(2026, 11, 4), FakeSession(Bad()), 7))
|
|
|
|
|
|
class RoutedSession:
|
|
"""Situs palsu: halaman pencarian, artikel normal, artikel tanpa tanggal, dan artikel 403."""
|
|
PAGES = {
|
|
"search": '<a href="https://www.antaranews.com/berita/111/karhutla-ok">a</a><a href="https://www.antaranews.com/berita/222/karhutla-nodate">b</a>'
|
|
'<a href="https://www.antaranews.com/berita/333/karhutla-blocked">c</a>',
|
|
"ok": HTML,
|
|
"nodate": "<html><head><meta property='og:title' content='Tanpa tanggal'></head><body><p>x</p></body></html>",
|
|
}
|
|
|
|
def get(self, url, **k):
|
|
class R:
|
|
status_code = 200
|
|
headers = {"content-type": "text/html"}
|
|
r = R()
|
|
r.url = url
|
|
if "search" in url:
|
|
r.text = self.PAGES["search"] if "page=1" in url else ""
|
|
elif url.endswith("/karhutla-ok"):
|
|
r.text = self.PAGES["ok"]
|
|
elif url.endswith("/karhutla-nodate"):
|
|
r.text = self.PAGES["nodate"]
|
|
else:
|
|
import requests
|
|
resp = requests.Response()
|
|
resp.status_code = 403
|
|
raise requests.HTTPError("403", response=resp)
|
|
r.raise_for_status = lambda: None
|
|
return r
|
|
|
|
|
|
def test_portal_collect_menghitung_alasan_gugur(monkeypatch, capsys):
|
|
monkeypatch.setattr("time.sleep", lambda s: None)
|
|
monkeypatch.setitem(portals.PORTALS["antara"], "search", "https://www.antaranews.com/search?q={q}&page={page}")
|
|
recs = list(portals.collect("antara", ["karhutla"], date(2024, 1, 1), date(2026, 11, 4), RoutedSession(), max_pages=2))
|
|
out = capsys.readouterr().out
|
|
assert len(recs) == 1 and recs[0]["sumber"] == "ANTARA"
|
|
assert "tanggal_tidak_terbaca" in out and "HTTP 403" in out and "diterima" in out
|
|
|
|
|
|
def test_debug_portal_berjalan(monkeypatch, tmp_path, capsys):
|
|
import config
|
|
from scripts import debug_portal
|
|
monkeypatch.setattr(config, "REPORT_DIR", tmp_path)
|
|
monkeypatch.setitem(portals.PORTALS["antara"], "search", "https://www.antaranews.com/search?q={q}&page={page}")
|
|
debug_portal.debug("antara", RoutedSession())
|
|
out = capsys.readouterr().out
|
|
assert "tautan artikel cocok pola: 3" in out and "3 lolos filter slug" in out
|
|
assert (tmp_path / "debug_antara_search.html").exists()
|
|
|
|
|
|
def test_tanggal_format_detik():
|
|
assert parse_date_any("2026/11/15 12:00:12") == "2026-11-15T12:00:12"
|
|
assert parse_date_any("15/11/2026 12:00") == "2026-11-15T12:00:00"
|
|
|
|
|
|
def test_extract_links_relatif_dan_absolut():
|
|
html = '<a href="/nasional/20261114093000-20-1234567/karhutla-riau">x</a><a href="https://www.cnnindonesia.com/nasional/20261113-1-2/abc">y</a>'
|
|
links = portals.extract_links(html, "https://www.cnnindonesia.com/search/?query=karhutla", portals.PORTALS["cnn"]["link_re"])
|
|
assert links == ["https://www.cnnindonesia.com/nasional/20261114093000-20-1234567/karhutla-riau"]
|
|
|
|
|
|
def test_slug_filter():
|
|
assert portals.slug_relevant("https://news.detik.com/berita/d-1/bertemu-menlu-bereskan-karhutla")
|
|
assert not portals.slug_relevant("https://news.detik.com/berita/d-2/tak-semua-konten-bisa-diblokir-komdigi")
|
|
|
|
|
|
def test_isi_artikel_antara_dengan_br():
|
|
kalimat = "Kebakaran lahan gambut di Kabupaten Sintang meluas akibat cuaca kering dan angin kencang di wilayah itu."
|
|
html = f"""<html><head><meta property="og:title" content="Judul"></head><body>
|
|
<div class="post-content clearfix">{kalimat}<br><br>{kalimat} Tim gabungan terus melakukan pemadaman.<br>Baca juga: lainnya yang tidak perlu ikut tersimpan<br>
|
|
<script>var x=1;</script></div></body></html>"""
|
|
art = portals.fetch_article("https://x/1", FakeSession(FakeResp(text=html)))
|
|
assert "Sintang" in art["isi"] and "Baca juga" not in art["isi"] and "var x" not in art["isi"]
|
|
|
|
|
|
def test_slug_api_hanya_kata_utuh():
|
|
assert portals.slug_relevant("https://x.com/nasional/1/video-api-masih-membara")
|
|
assert not portals.slug_relevant("https://x.com/nasional/1/rapi-dan-bersih-kota-ini")
|
|
|
|
|
|
def test_query_cnn_pakai_slug_tag():
|
|
cnn = portals.PORTALS["cnn"]
|
|
assert portals.query_for(cnn, "kebakaran hutan dan lahan") == "kebakaran-hutan-dan-lahan"
|
|
assert portals.query_for(portals.PORTALS["antara"], "kabut asap") == "kabut+asap"
|
|
assert cnn["search"].format(q="karhutla", page=2) == "https://www.cnnindonesia.com/tag/karhutla?page=2"
|