A tiny, local-first CLI that finds the files your AI coding agent actually needs — and packs them into a focused context.
| 1 | """Tests for token estimation.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | from pathlib import Path |
| 6 | |
| 7 | from agent_context.tokens import ( |
| 8 | estimate_tokens_from_bytes, |
| 9 | estimate_tokens_from_file, |
| 10 | estimate_tokens_from_text, |
| 11 | format_int, |
| 12 | ) |
| 13 | |
| 14 | |
| 15 | def test_empty_text(): |
| 16 | assert estimate_tokens_from_text("") == 0 |
| 17 | assert estimate_tokens_from_text(" \n\t") == 0 |
| 18 | |
| 19 | |
| 20 | def test_deterministic_estimation(): |
| 21 | text = "Hello, world! This is a short sample." |
| 22 | a = estimate_tokens_from_text(text) |
| 23 | b = estimate_tokens_from_text(text) |
| 24 | assert a == b |
| 25 | assert a == int(round(len(text.replace("\r\n", "\n")) / 4.0)) |
| 26 | |
| 27 | |
| 28 | def test_unicode(): |
| 29 | text = "こんにちは世界" # Japanese |
| 30 | tokens = estimate_tokens_from_text(text) |
| 31 | assert tokens >= 1 |
| 32 | |
| 33 | |
| 34 | def test_crlf_normalization(): |
| 35 | a = estimate_tokens_from_text("a\nb\nc") |
| 36 | b = estimate_tokens_from_text("a\r\nb\r\nc") |
| 37 | assert a == b |
| 38 | |
| 39 | |
| 40 | def test_bytes_and_file(tmp_path: Path): |
| 41 | path = tmp_path / "sample.txt" |
| 42 | content = "x" * 400 |
| 43 | path.write_text(content, encoding="utf-8") |
| 44 | assert estimate_tokens_from_file(path) == estimate_tokens_from_text(content) |
| 45 | assert estimate_tokens_from_bytes(content.encode()) == estimate_tokens_from_text(content) |
| 46 | |
| 47 | |
| 48 | def test_large_file_extrapolation(tmp_path: Path): |
| 49 | path = tmp_path / "big.txt" |
| 50 | # Write more than the sample window used for estimation. |
| 51 | chunk = ("word " * 100 + "\n") |
| 52 | path.write_text(chunk * 5000, encoding="utf-8") |
| 53 | tokens = estimate_tokens_from_file(path, max_bytes=8_000) |
| 54 | assert tokens > 1_000 |
| 55 | |
| 56 | |
| 57 | def test_missing_file(tmp_path: Path): |
| 58 | assert estimate_tokens_from_file(tmp_path / "nope.txt") == 0 |
| 59 | |
| 60 | |
| 61 | def test_format_int(): |
| 62 | assert format_int(1234) == "1,234" |