File size: 2,347 Bytes
ab773bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
"""
Chunking modülü testleri.
Çalıştırma: python tests/test_chunking.py
"""
import sys
import os

sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from src.chunking import chunk_text, chunk_articles, _WhitespaceTokenizer


def test_chunk_respects_size_and_overlap():
    tok = _WhitespaceTokenizer()
    text = " ".join([f"kelime{i}" for i in range(100)])  # 100 "token"
    chunks = chunk_text(text, chunk_size=30, overlap=10, tokenizer=tok)

    # Beklenen chunk sayısı: step=20, (100-30)/20 + 1 = 4.5 -> 5 chunk (üste yuvarlanır)
    assert len(chunks) >= 4, f"Beklenenden az chunk: {len(chunks)}"

    # İlk chunk'ın son 10 kelimesi, ikinci chunk'ın ilk 10 kelimesiyle örtüşmeli
    first_words = chunks[0].split()
    second_words = chunks[1].split()
    assert first_words[-10:] == second_words[:10], "Overlap doğru uygulanmamış"
    print("test_chunk_respects_size_and_overlap: OK")


def test_chunk_short_text_single_chunk():
    tok = _WhitespaceTokenizer()
    text = "kısa bir metin"
    chunks = chunk_text(text, chunk_size=100, overlap=10, tokenizer=tok)
    assert len(chunks) == 1
    assert chunks[0] == text
    print("test_chunk_short_text_single_chunk: OK")


def test_chunk_articles_preserves_metadata():
    articles = [
        {"url": "u1", "title": "t1", "__source": "s1", "text": "a b c d e f g h i j k l m n o"},
        {"url": "u2", "title": "t2", "__source": "s2", "text": "x y z"},
    ]
    chunks = chunk_articles(articles, chunk_size=5, overlap=2)
    assert all("url" in c and "chunk_text" in c and "chunk_id" in c for c in chunks)
    # parent_id doğru dağıtılmış mı?
    parent_ids = {c["parent_id"] for c in chunks}
    assert parent_ids == {0, 1}
    print("test_chunk_articles_preserves_metadata: OK")


def test_overlap_must_be_smaller_than_chunk_size():
    tok = _WhitespaceTokenizer()
    try:
        chunk_text("bir iki üç", chunk_size=5, overlap=5, tokenizer=tok)
        assert False, "ValueError bekleniyordu"
    except ValueError:
        pass
    print("test_overlap_must_be_smaller_than_chunk_size: OK")


if __name__ == "__main__":
    test_chunk_respects_size_and_overlap()
    test_chunk_short_text_single_chunk()
    test_chunk_articles_preserves_metadata()
    test_overlap_must_be_smaller_than_chunk_size()
    print("\nTüm testler geçti ✅")