unsloth/tests/test_raw_text.py
Daniel Han a56c959233
Add Studio PR-time CI: pin enforcement, frontend, backend, wheel smoke (#5298)
* Add Studio PR-time CI: pin enforcement, frontend, backend, wheel smoke

The repo currently has no PR-time CI; only release-desktop.yml (manual) and
stale.yml (issue pinger). studio/backend/tests/ has 35 test files (~860
tests collected) that never run automatically. Frontend lint/typecheck/build
scripts exist in package.json but are not gated on PRs either. This is the
gap that let 2026.5.1 ship with the broken Studio chat-history bundle.

Adds four ubuntu-latest workflows, all CPU-only and free for public repos:

studio-pin-enforce.yml
  Greps studio/frontend/package.json for caret/tilde ranges on the
  @assistant-ui surface (and assistant-stream). Blocks the exact regression
  vector that produced 2026.5.1 (^0.12.19 resolving to a breaking 0.12.28).

studio-frontend-ci.yml
  npm ci (strict lockfile), tree-clean check after, typecheck, vite build,
  bundle grep for the Studio unstable_Provider call site (<= 3 hits = OK,
  >= 4 = the 2026.5.1 regression), 75 MB dist budget, biome non-blocking.
  Uploads dist on failure.

studio-backend-ci.yml
  Runs the existing studio/backend/tests/ suite on Python 3.10/3.11/3.12.
  Excludes test_studio_api.py (live model + GGUF download) and
  llama_cpp_load_progress_live (spawns a real llama.cpp). Local run on this
  branch: 861 pass, 4 skipped, 5 deselected. ruff non-blocking.

wheel-smoke.yml
  python -m build, then verifies the produced wheel:
    - ships studio/frontend/package-lock.json
    - ships studio/frontend/dist/index.html
    - does NOT ship studio/frontend/node_modules/
    - does NOT ship studio/frontend/bun.lock
    - main JS bundle has < 4 unstable_Provider hits
  Then installs the wheel into a fresh venv with a lightweight dep set and
  imports studio.backend.main. Locally validated against the wheel built
  from this branch.

Each workflow has concurrency cancellation on the same ref. biome and ruff
are gated as non-blocking until the existing accumulated drift is cleared
(~470 biome errors today); remove the bypass in a follow-up.

Notes verified locally:

  - pin enforcement: PASS (carets dropped on this branch)
  - frontend npm ci -> typecheck -> build -> grep -> budget: PASS
  - bundle: 48 MB, hits=1
  - backend pytest: 861 pass, 1 GPU-pollution failure not reproducible on
    GPU-less runners (won't reproduce on ubuntu-latest)
  - wheel build: 13s, produces unsloth-2026.5.2-py3-none-any.whl
  - wheel content sanity: all five checks PASS

* CI: install full backend dep set + refine pytest filter for CPU runners

First CI run on PR #5298 surfaced two real gaps:

1. pytest collection failed at `import yaml` in utils/models/model_config.
   Locally my workspace venv had pyyaml from a transitive; CI's clean Python
   3.10/3.11/3.12 didn't, so collection hit ModuleNotFoundError on the very
   first test module. Same blew up the wheel-smoke `from studio.backend.main
   import app` step.

2. Once the import chain was complete, ~9 tests still failed because they
   exercise GPU-only paths or live transformers introspection that can't run
   on a GPU-less `ubuntu-latest` runner regardless of code correctness:
     - TestGpuAutoSelection
     - TestPreSpawnGpuResolution
     - TestPerGpuFitGuardAllCounts
     - TestTransformersIntrospection
     - test_returns_cuda_when_cuda_available
     - test_calls_cuda_cache_when_cuda

Fix:
- Backend CI installs `studio/backend/requirements/studio.txt` (the
  declared backend dep set) + the extras the import chain needs but
  studio.txt omits (python-multipart, sqlalchemy, cryptography, pyyaml,
  jinja2, mammoth, unpdf, requests, etc.) + torch CPU wheel + transformers.
- Refine the pytest -k filter to deselect the GPU/introspection-bound
  classes by name. Deselections are commented inline with the reason.
- wheel-smoke uses the same dep set so the import smoke matches.

Locally validated against the freshly-built unsloth-2026.5.2 wheel:
  831 passed, 5 skipped, 35 deselected, 0 failed in 47s
  Studio backend imports cleanly in a fresh venv after the wheel install.

* CI: collapse multiline pytest -k expression to a single line

YAML's | block-scalar fed the newlines verbatim into the -k argument and
pytest rejected it as 'Wrong expression passed to -k'. Same logical filter
on one line.

* CI: rename jobs so the GitHub UI shows what each check actually does

Adds a per-job 'name:' to all four workflows so the PR check list reads:

  Studio pin enforcement / @assistant-ui must be pinned exactly
  Studio frontend CI / Frontend build + bundle sanity
  Studio backend CI / Backend pytest (Python 3.10|3.11|3.12)
  Studio backend CI / Backend ruff lint (non-blocking)
  Wheel build + smoke / Wheel build + content sanity + import smoke

Instead of the default '<workflow> / <job-key>' which was opaque
('check', 'build', 'pytest (3.10)', 'ruff', 'wheel').

* CI: add Python 3.13 to backend pytest matrix

Verified locally: 831 backend tests pass under Python 3.13 with the same
filter set used for 3.10 / 3.11 / 3.12.

* CI: add Studio inference smoke + Tauri build smoke

Two new workflows. Both CPU-only, both free on `ubuntu-latest`.

studio-inference-smoke.yml
  The only workflow we have that proves "Studio actually works", as opposed
  to "the bundle parses" or "the imports succeed":
    - runs install.sh --local --no-torch (lean Studio install)
    - downloads unsloth/gemma-4-E2B-it-GGUF UD-IQ3_XXS into actions/cache
    - boots Studio in api-only mode
    - logs in with the bootstrap password, changes it, re-logs
    - POST /api/inference/load on the GGUF
    - POST /api/inference/chat/completions and asserts a non-empty
      assistant response
  Validated end-to-end locally on a fresh main install: model loaded,
  chat completion returned `Hello!` against the same GGUF the workflow
  uses.

studio-tauri-smoke.yml
  PR-time variant of release-desktop.yml. Linux-only debug build
  (`tauri build --debug --no-bundle`) on ubuntu-22.04. Catches
  src-tauri Cargo.toml / Rust source breakage, tauri.conf.json drift,
  and frontend-distDir wiring. Pinned to the same Tauri CLI version
  (2.10.1) as release-desktop.yml so CLI bumps surface in CI before
  they break the release pipeline. Mac and Windows desktop builds
  stay manual via release-desktop.yml because they need code-signing
  secrets.

* CI: use 'hf download' instead of deprecated 'huggingface-cli download'

huggingface_hub 1.13.0 dropped the huggingface-cli entrypoint. The
replacement is the 'hf' CLI shipped with the same package. Same args,
just s/huggingface-cli/hf/.

* CI: assert llama.cpp prebuilt path was used on ubuntu-latest

The inference-smoke job runs on ubuntu-latest (CPU-only, x86_64), which
is exactly the host shape that should pick up ggml-org/llama.cpp's
bin-ubuntu-x64.tar.gz prebuilt directly. If install.sh ever falls back
to a source build on this runner, the studio/setup.sh routing has
regressed and every CPU-only Linux user is paying a 3 minute compile
cost again.

Tee install.sh output to logs/install.log, then fail the job if the log
contains "falling back to source build" or is missing the success
marker "prebuilt installed and validated" / "prebuilt up to date and
validated".

Also include logs/install.log in the failure artifact so the prebuilt
diagnostics are uploaded alongside studio.log when the job fails.

* Tighten prebuilt-assertion comment in studio-inference-smoke

* CI: switch inference-smoke model to Qwen3.5-2B UD-IQ3_XXS

Drops the Gemma 4 E2B GGUF (~2.3 GB) for unsloth/Qwen3.5-2B-GGUF
(UD-IQ3_XXS, ~890 MiB). Cache-miss download is roughly a third of
what it was, and CPU inference on ubuntu-latest finishes well
inside the 25 minute job budget.

Verified locally: load via /api/inference/load returns
status=loaded, is_gguf=true, supports_reasoning=true,
supports_tools=true; chat completion returns a non-empty assistant
message ("Hello!").

* CI: add workflow_dispatch to inference-smoke for manual cache pre-warm

* CI: fold pin-enforce grep into studio-frontend-ci, drop standalone workflow

The "@assistant-ui must be pinned exactly" check was its own ~7 second
workflow, doing a single grep on studio/frontend/package.json. Move it
into studio-frontend-ci.yml as a pre-install step (right after
checkout, before any node setup so a violation fails fast). One fewer
top-level check row on every PR, same coverage.

Add a FIXME so this step is dropped once @assistant-ui/* and
assistant-stream leave 0.x: on 1.x, caret ranges are conventional and
this becomes overzealous.

* CI: add Repo tests (CPU) job, mirroring unsloth-zoo PR #624 conftest

The top-level tests/ tree was previously not run anywhere. 23 of its
files are CPU-friendly with the right harness: pure-Python helpers,
ast walks, installer logic, and CLI shape tests. Locally validated:
302 passed, 9 skipped, 12 deselected in ~7 seconds on Python 3.12.

Three pieces:

1. tests/conftest.py -- GPU-free harness, mirrors the conftest landed
   in unslothai/unsloth-zoo PR #624. Pre-loads unsloth_zoo.device_type
   and unsloth.device_type under a temporarily-mocked
   torch.cuda.is_available() so each module's @cache permanently
   captures "cuda" and the import chain succeeds on a CPU runner.
   Also stubs torch.cuda.get_device_capability /
   is_bf16_supported / mem_get_info, which unsloth/__init__.py and
   unsloth_zoo.temporary_patches probe at import time when
   DEVICE_TYPE == "cuda". On a real accelerator the harness is
   skipped and detection runs normally.

2. Two existing tests were leaking sys.modules state across the
   session because they injected stubs without an __spec__ and
   without restoration:

     - tests/test_raw_text.py shoved a "datasets" stub into
       sys.modules. transformers' import_utils later did
       importlib.util.find_spec("datasets") and got
       ValueError: datasets.__spec__ is None.

     - tests/python/test_fast_sentence_transformer_redirect_lifecycle.py
       shoved "transformers", "sentence_transformers", and
       "sentence_transformers.models" stubs in. Subsequent tests
       that did `import transformers` got the non-package stub.

   Fix: set __spec__ on stubs, plus an autouse fixture in the
   sentence-transformer test file that restores the three keys
   after each test.

3. .github/workflows/studio-backend-ci.yml gains a third job,
   `Repo tests (CPU)`, that installs the same dep set as the
   backend-pytest matrix (Python 3.12 only -- the tests are
   version-independent), exports PYTHONPATH=studio so tests/python/*
   can import install_python_stack, and runs the 23-file subset
   above with `-m 'not server and not e2e'`.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* CI: install unsloth_zoo for Repo CPU tests, harden conftest fallback

The CPU job at run 25422050018 broke at conftest collection: the
preload of unsloth.device_type pulled in `from unsloth_zoo.utils import
Version` and ubuntu-latest didn't have unsloth_zoo on the path because
it is an optional dep of unsloth. Two fixes:

1. Install unsloth_zoo>=2026.5.1 alongside the other deps in the Repo
   tests (CPU) job (it's also what unsloth's optional `huggingface`
   extra pins).

2. Wrap the body of _preload_device_type in conftest.py in a try/except
   so any import failure (missing prereq, broken module, etc.) cleanly
   returns False instead of aborting the entire collection. The caller
   already falls back to the stub device_type module on False, so the
   net behavior is "best effort: real device_type if possible, stub
   otherwise" instead of "abort the test session".

* kernels.utils: guard CUDA_STREAMS / XPU_STREAMS init for DEVICE_COUNT==0

When DEVICE_COUNT is 0 (CPU host: no visible NVIDIA / AMD / Intel GPU)
the dict comprehension {... for i in range(0)} was empty and the
subsequent max(_CUDA_STREAMS.keys()) raised
ValueError: max() iterable argument is empty
during module import. That made unsloth.kernels.utils unimportable on
any CPU runner, which in turn blocked all of tests/saving/**, three
top-level tests/test_*.py, and tests/qlora/test_unsloth_qlora_train_and_merge.py
from even collecting on CPU CI.

Wrap the per-device-index dict comprehension and max() machinery in
a DEVICE_COUNT > 0 guard. When DEVICE_COUNT is 0 fall back to empty
containers (CUDA_STREAMS = (), WEIGHT_BUFFERS = [], ABSMAX_BUFFERS = []).
The consumer functions further down in this module index these arrays
by device_index but only during real GPU work, so the empty fallbacks
never get touched on a CPU host.

GPU-safety verified locally: with 8 visible CUDA devices, CUDA_STREAMS
has 8 entries (identical to before this PR). With CUDA_VISIBLE_DEVICES=""
the module imports cleanly, CUDA_STREAMS is (), and the previously
blocked tests now collect (test_get_model_name passes 38 subtests,
test_resolve_model_class passes 9, test_model_registry collects all 8
parametrizations).

Same shape applied to the DEVICE_TYPE == "xpu" branch for symmetry.

* CI: switch Repo tests (CPU) to auto-discovery + isolate flakes

Three changes, locally validated end-to-end (779 passed, 11 skipped,
23 deselected, 0 failed across all three steps):

1. Repo tests (CPU, auto-discovered): replace the explicit 23-file
   list with `pytest tests/` plus a small set of `--ignore` and
   `--deselect` flags. New tests under tests/python, tests/studio
   (excluding the two state-sensitive files), and top-level
   tests/test_*.py are picked up automatically with no workflow edit.

   --ignore covers:
     - tests/qlora and tests/saving: GPU-bound by design
     - tests/utils: helpers folder, not tests
     - tests/sh: shell suite handled in its own step
     - two state-polluting hardware-spoof files (next step)
   -m 'not server and not e2e': honours markers already declared
     in tests/python/conftest.py
   --deselect: test_model_registration / test_all_model_registration
     hit huggingface_hub live; they belong on a network job

2. Hardware-spoof tests (state-sensitive, run in isolation):
   tests/studio/test_hardware_dispatch_matrix.py and
   tests/studio/test_is_mlx_dispatch_gate.py mutate module globals
   in studio.backend.utils.hardware.hardware (IS_ROCM, DEVICE) via
   their spoof fixtures, and the leak crosses file boundaries.
   Running them in their own pytest invocation avoids polluting the
   main sweep. Both pass cleanly in isolation: 28 passed, 1 skipped.

3. Shell installer tests: explicitly enumerated subset that does not
   depend on install.ps1 layout (test_install_host_defaults.sh has
   drifted; that's a separate followup).

Test fixes folded in to keep the run green:
  - tests/studio/install/test_rocm_support.py::TestAmdGpuMonitoring
    ::test_amd_primary_gpu_with_mock now clears
    HIP/ROCR/CUDA_VISIBLE_DEVICES via monkeypatch so
    _first_visible_amd_gpu_id() does not short-circuit when the runner
    sets CUDA_VISIBLE_DEVICES="" to suppress CUDA.
  - tests/studio/test_hardware_dispatch_matrix.py::spoof_hardware
    fixture now stubs torch.cuda.get_device_properties when
    cuda_available is True so detect_hardware()'s device_name probe
    does not call into _cuda_init() on a CPU runner.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* CI: install torchvision (CPU) so unsloth_zoo.vision_utils can import

Run 25430652224 collected three test modules that import unsloth and
crashed at unsloth_zoo/vision_utils.py:68 with
  ModuleNotFoundError: No module named 'torchvision'

unsloth_zoo.vision_utils unconditionally imports torchvision at module
scope, and unsloth.models._utils pulls vision_utils in. The Repo tests
(CPU) job installed torch from the CPU index but not torchvision, so
any test that imports unsloth.models.* failed at collection.

Add torchvision<0.26 to the same pip install --index-url
https://download.pytorch.org/whl/cpu line.

* CI: install bitsandbytes (CPU build) for unsloth.models._utils import

Run 25430982243 collected three test modules that import unsloth and
crashed at unsloth/models/_utils.py:1166 with
  ModuleNotFoundError: No module named 'bitsandbytes'

The bnb import there is unconditional. Recent bnb versions (>=0.45)
ship a CPU build so the wheel installs on a free Linux runner and the
import resolves; the kernels still raise on use but the module
collects, which is enough for these CPU tests.

Add 'bitsandbytes>=0.45' to the Repo tests (CPU) deps.

* CI: rename workflows + guard kernels.utils CPU-torch binding

Workflow renames (top-level `name:` keys; affects PR check rows):
  Studio backend CI    -> Backend CI
  Studio frontend CI   -> Frontend CI
  Studio inference smoke -> Studio GGUF CI
  Studio Tauri smoke   -> Studio Tauri CI
  Wheel build + smoke  -> Wheel CI

Backend CI's matrix job goes from "Backend pytest (Python 3.10)" to
just "(Python 3.10)" so the GitHub UI row reads
"Backend CI / (Python 3.10)" rather than the old verbose form.

Production guard for CPU torch (run 25431126138):

unsloth/kernels/utils.py:165 was an unconditional
  _gpu_getCurrentRawStream = torch._C._cuda_getCurrentRawStream
which raised AttributeError on a CPU-only torch wheel because the
compiled CUDA backend is absent. Three test modules (test_get_model_name,
test_model_registry, test_resolve_model_class) crashed at collection
because their import chain reaches this line.

Add a hasattr probe: when torch is built without CUDA, fall through to
a no-op binding that returns 0. _get_tensor_stream is only invoked
during real GPU work, so the no-op is never executed on a CPU host.

GPU-safety verified locally: with 8 visible CUDA devices the binding
still resolves to the real torch._C._cuda_getCurrentRawStream
(behaviour identical to before this PR). The XPU branch is untouched.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2026-05-06 04:41:57 -07:00

244 lines
9.5 KiB
Python

#!/usr/bin/env python3
"""
Minimal test for raw text training implementation.
Tests basic functionality without heavy dependencies.
"""
import sys
import os
import tempfile
from pathlib import Path
import importlib.util
# Mock the datasets module since it's not installed
class MockDataset:
def __init__(self, data_dict):
self.data = data_dict
self.column_names = list(data_dict.keys())
def __len__(self):
return len(next(iter(self.data.values())))
def __getitem__(self, idx):
if isinstance(idx, str):
# Allow accessing columns by name like dataset['text']
return self.data[idx]
elif isinstance(idx, int):
# Allow accessing individual rows by index
return {key: values[idx] for key, values in self.data.items()}
else:
raise TypeError(f"Invalid index type: {type(idx)}")
@classmethod
def from_dict(cls, data_dict):
return cls(data_dict)
# Mock datasets module. __spec__ must be set so importlib.util.find_spec
# does not raise ValueError when transformers' import_utils probes for
# the real `datasets` package later in the test session.
datasets_mock = type(sys)("datasets")
datasets_mock.__spec__ = importlib.util.spec_from_loader("datasets", loader = None)
datasets_mock.Dataset = MockDataset
sys.modules["datasets"] = datasets_mock
# Import the raw_text module directly to avoid unsloth/__init__.py dependencies
current_dir = os.path.dirname(__file__)
raw_text_path = os.path.join(
os.path.dirname(current_dir), "unsloth", "dataprep", "raw_text.py"
)
spec = importlib.util.spec_from_file_location("raw_text", raw_text_path)
raw_text_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(raw_text_module)
RawTextDataLoader = raw_text_module.RawTextDataLoader
TextPreprocessor = raw_text_module.TextPreprocessor
def test_raw_text_loader():
"""Test basic RawTextDataLoader functionality."""
# Mock tokenizer for testing
class MockTokenizer:
def __init__(self):
self.eos_token = "</s>"
self.eos_token_id = 2 # Mock EOS token ID
def __call__(self, text, return_tensors = None, add_special_tokens = False):
words = text.split()
token_ids = list(range(len(words)))
if return_tensors == "pt":
# Mock tensor-like object
class MockTensor:
def __init__(self, data):
self.data = data
def __getitem__(self, idx):
return self.data
def __len__(self):
return len(self.data)
def tolist(self):
return self.data
return {"input_ids": [MockTensor(token_ids)]}
return {"input_ids": token_ids}
def decode(self, token_ids, skip_special_tokens = False):
return " ".join([f"word_{i}" for i in token_ids])
# Create test file
test_content = "This is a test file for raw text training. " * 10
with tempfile.NamedTemporaryFile(mode = "w", suffix = ".txt", delete = False) as f:
f.write(test_content)
test_file = f.name
try:
# Test loader
tokenizer = MockTokenizer()
loader = RawTextDataLoader(tokenizer, chunk_size = 5, stride = 2)
# Test loading with text output (legacy mode)
text_dataset = loader.load_from_file(test_file, return_tokenized = False)
assert len(text_dataset) > 0, "Should create at least one chunk"
assert "text" in text_dataset.column_names, "Dataset should have 'text' column"
# Test loading with tokenized output (new efficient mode)
tokenized_dataset = loader.load_from_file(test_file, return_tokenized = True)
assert len(tokenized_dataset) > 0, "Should create at least one tokenized chunk"
assert (
"input_ids" in tokenized_dataset.column_names
), "Dataset should have 'input_ids' column"
assert (
"attention_mask" in tokenized_dataset.column_names
), "Dataset should have 'attention_mask' column"
# Verify tokenized data structure
first_sample = tokenized_dataset[0]
assert isinstance(first_sample["input_ids"], list), "input_ids should be a list"
assert isinstance(
first_sample["attention_mask"], list
), "attention_mask should be a list"
assert len(first_sample["input_ids"]) == len(
first_sample["attention_mask"]
), "input_ids and attention_mask should have same length"
# Verify labels field exists (for causal LM training)
assert (
"labels" in tokenized_dataset.column_names
), "Dataset should have 'labels' column"
assert (
first_sample["labels"] == first_sample["input_ids"]
), "labels should match input_ids"
# Test constructor validation
try:
bad_loader = RawTextDataLoader(tokenizer, chunk_size = 0, stride = 2)
assert False, "Should raise ValueError for chunk_size=0"
except ValueError as e:
assert "chunk_size must be positive" in str(e)
try:
bad_loader = RawTextDataLoader(tokenizer, chunk_size = 5, stride = 10)
assert False, "Should raise ValueError for stride >= chunk_size"
except ValueError as e:
assert "stride" in str(e) and "chunk_size" in str(e)
# Test preprocessor
preprocessor = TextPreprocessor()
clean_text = preprocessor.clean_text(" messy text \n\n\n ")
assert "messy text" in clean_text, "Should clean text properly"
paragraph_text = preprocessor.clean_text("Line 1\r\n\r\n\r\nLine 2")
assert (
paragraph_text == "Line 1\n\nLine 2"
), "Should preserve paragraph breaks while normalizing newlines"
# Non-ASCII horizontal whitespace separators (NBSP, thin space,
# ideographic space, narrow NBSP, em space, vertical tab, form feed)
# should be normalized to a single ASCII space, not deleted, otherwise
# adjacent words get silently fused together on HTML/PDF/OCR inputs.
unicode_whitespace_cases = [
("hello\u00a0world", "hello world"),
("hello\u202fworld", "hello world"),
("hello\u2009world", "hello world"),
("hello\u3000world", "hello world"),
("hello\u2002world", "hello world"),
("hello\x0bworld", "hello world"),
("hello\x0cworld", "hello world"),
]
for raw, expected in unicode_whitespace_cases:
assert preprocessor.clean_text(raw) == expected, (
f"Should normalize Unicode/control whitespace to a single space "
f"for {raw!r}"
)
# Mixed paragraph + Unicode whitespace realistic input
mixed = preprocessor.clean_text("Section\u00a01\r\n\r\nBody\ftext\u202fhere")
assert mixed == "Section 1\n\nBody text here", (
"Should preserve paragraph breaks and normalize Unicode "
"whitespace simultaneously"
)
# Tabs should collapse to a single space
assert preprocessor.clean_text("a\tb") == "a b"
assert preprocessor.clean_text("a\t\tb") == "a b"
# Spaces around newlines should be trimmed on both sides, even with
# multiple consecutive newlines
assert preprocessor.clean_text("foo \n\n bar") == "foo\n\nbar"
# Non-whitespace non-ASCII characters sitting between spaces should
# not leave an interior double space after being stripped. This
# guards the idempotence invariant too: without the extra collapse
# pass, "word1 (c) word2" first reduces to "word1 word2" and only
# becomes "word1 word2" on a second call.
assert preprocessor.clean_text("word1 \u00a9 word2") == "word1 word2"
assert preprocessor.clean_text("a \u00e9 b") == "a b"
assert preprocessor.clean_text("prefix \U0001f600 suffix") == "prefix suffix"
# Stripping a non-ASCII character adjacent to a newline must not
# leave a stray leading/trailing space on the neighbouring line.
assert preprocessor.clean_text("foo \u00e9\nbar") == "foo\nbar"
assert preprocessor.clean_text("foo\n\u00e9 bar") == "foo\nbar"
# The double-space collapse pass must not swallow a legitimate
# paragraph break when a non-ASCII char sits near it.
assert preprocessor.clean_text("a \u00a9\n\nb") == "a\n\nb"
# Idempotence: running clean_text twice should give the same result
idempotent_inputs = [
" messy text \n\n\n ",
"Line 1\r\n\r\n\r\nLine 2",
"hello\u00a0world",
"Section\u00a01\r\n\r\nBody\ftext\u202fhere",
"word1 \u00a9 word2",
"a \u00e9 b",
]
for raw in idempotent_inputs:
once = preprocessor.clean_text(raw)
twice = preprocessor.clean_text(once)
assert once == twice, f"clean_text should be idempotent for {raw!r}"
# Test validation
stats = preprocessor.validate_dataset(text_dataset)
assert stats["total_samples"] > 0, "Should count samples"
assert "warnings" in stats, "Should include warnings"
print("✅ All tests passed!")
return True
except Exception as e:
print(f"❌ Test failed: {e}")
return False
finally:
# Cleanup
os.unlink(test_file)
if __name__ == "__main__":
success = test_raw_text_loader()
sys.exit(0 if success else 1)