|
1 | | -"""Tests for session mutation functions (rename_session, delete_session, tag_session).""" |
| 1 | +"""Tests for session mutation functions (rename_session, tag_session).""" |
2 | 2 |
|
3 | 3 | from __future__ import annotations |
4 | 4 |
|
|
9 | 9 |
|
10 | 10 | import pytest |
11 | 11 |
|
12 | | -from claude_agent_sdk import list_sessions, rename_session |
13 | | -from claude_agent_sdk._internal.session_mutations import _try_append |
| 12 | +from claude_agent_sdk import list_sessions, rename_session, tag_session |
| 13 | +from claude_agent_sdk._internal.session_mutations import ( |
| 14 | + _sanitize_unicode, |
| 15 | + _try_append, |
| 16 | +) |
14 | 17 | from claude_agent_sdk._internal.sessions import _sanitize_path |
15 | 18 |
|
16 | 19 | # --------------------------------------------------------------------------- |
@@ -253,3 +256,201 @@ def test_compact_json_format(self, claude_config_dir: Path, tmp_path: Path): |
253 | 256 | assert lines[-1] == ( |
254 | 257 | f'{{"type":"custom-title","customTitle":"Title","sessionId":"{sid}"}}' |
255 | 258 | ) |
| 259 | + |
| 260 | + |
| 261 | +# --------------------------------------------------------------------------- |
| 262 | +# tag_session() tests |
| 263 | +# --------------------------------------------------------------------------- |
| 264 | + |
| 265 | + |
| 266 | +class TestTagSession: |
| 267 | + """Tests for tag_session().""" |
| 268 | + |
| 269 | + def test_invalid_session_id_raises(self, claude_config_dir: Path): |
| 270 | + """Non-UUID session_id raises ValueError.""" |
| 271 | + with pytest.raises(ValueError, match="Invalid session_id"): |
| 272 | + tag_session("not-a-uuid", "tag") |
| 273 | + with pytest.raises(ValueError, match="Invalid session_id"): |
| 274 | + tag_session("", "tag") |
| 275 | + |
| 276 | + def test_empty_tag_raises(self, claude_config_dir: Path, tmp_path: Path): |
| 277 | + """Empty or whitespace-only tag raises ValueError.""" |
| 278 | + project_path = str(tmp_path / "proj") |
| 279 | + Path(project_path).mkdir(parents=True) |
| 280 | + project_dir = _make_project_dir( |
| 281 | + claude_config_dir, os.path.realpath(project_path) |
| 282 | + ) |
| 283 | + sid, _ = _make_session_file(project_dir) |
| 284 | + |
| 285 | + with pytest.raises(ValueError, match="tag must be non-empty"): |
| 286 | + tag_session(sid, "", directory=project_path) |
| 287 | + with pytest.raises(ValueError, match="tag must be non-empty"): |
| 288 | + tag_session(sid, " ", directory=project_path) |
| 289 | + |
| 290 | + def test_session_not_found_raises(self, claude_config_dir: Path, tmp_path: Path): |
| 291 | + """Session not found raises FileNotFoundError.""" |
| 292 | + project_path = str(tmp_path / "proj") |
| 293 | + Path(project_path).mkdir(parents=True) |
| 294 | + _make_project_dir(claude_config_dir, os.path.realpath(project_path)) |
| 295 | + |
| 296 | + sid = str(uuid.uuid4()) |
| 297 | + with pytest.raises(FileNotFoundError): |
| 298 | + tag_session(sid, "tag", directory=project_path) |
| 299 | + |
| 300 | + def test_appends_tag_entry(self, claude_config_dir: Path, tmp_path: Path): |
| 301 | + """tag_session appends a {type:'tag'} JSON line.""" |
| 302 | + project_path = str(tmp_path / "proj") |
| 303 | + Path(project_path).mkdir(parents=True) |
| 304 | + project_dir = _make_project_dir( |
| 305 | + claude_config_dir, os.path.realpath(project_path) |
| 306 | + ) |
| 307 | + sid, file_path = _make_session_file(project_dir) |
| 308 | + |
| 309 | + tag_session(sid, "experiment", directory=project_path) |
| 310 | + |
| 311 | + lines = file_path.read_text().strip().split("\n") |
| 312 | + entry = json.loads(lines[-1]) |
| 313 | + assert entry["type"] == "tag" |
| 314 | + assert entry["tag"] == "experiment" |
| 315 | + assert entry["sessionId"] == sid |
| 316 | + |
| 317 | + def test_tag_trimmed(self, claude_config_dir: Path, tmp_path: Path): |
| 318 | + """Leading/trailing whitespace is stripped from tag.""" |
| 319 | + project_path = str(tmp_path / "proj") |
| 320 | + Path(project_path).mkdir(parents=True) |
| 321 | + project_dir = _make_project_dir( |
| 322 | + claude_config_dir, os.path.realpath(project_path) |
| 323 | + ) |
| 324 | + sid, file_path = _make_session_file(project_dir) |
| 325 | + |
| 326 | + tag_session(sid, " my-tag ", directory=project_path) |
| 327 | + |
| 328 | + lines = file_path.read_text().strip().split("\n") |
| 329 | + entry = json.loads(lines[-1]) |
| 330 | + assert entry["tag"] == "my-tag" |
| 331 | + |
| 332 | + def test_none_clears_tag(self, claude_config_dir: Path, tmp_path: Path): |
| 333 | + """Passing None appends an empty-string tag entry (clears tag).""" |
| 334 | + project_path = str(tmp_path / "proj") |
| 335 | + Path(project_path).mkdir(parents=True) |
| 336 | + project_dir = _make_project_dir( |
| 337 | + claude_config_dir, os.path.realpath(project_path) |
| 338 | + ) |
| 339 | + sid, file_path = _make_session_file(project_dir) |
| 340 | + |
| 341 | + tag_session(sid, "original-tag", directory=project_path) |
| 342 | + tag_session(sid, None, directory=project_path) |
| 343 | + |
| 344 | + lines = file_path.read_text().strip().split("\n") |
| 345 | + # Last entry is the clear |
| 346 | + entry = json.loads(lines[-1]) |
| 347 | + assert entry["type"] == "tag" |
| 348 | + assert entry["tag"] == "" |
| 349 | + assert entry["sessionId"] == sid |
| 350 | + |
| 351 | + def test_last_wins(self, claude_config_dir: Path, tmp_path: Path): |
| 352 | + """Multiple tag calls — last one lands at EOF.""" |
| 353 | + project_path = str(tmp_path / "proj") |
| 354 | + Path(project_path).mkdir(parents=True) |
| 355 | + project_dir = _make_project_dir( |
| 356 | + claude_config_dir, os.path.realpath(project_path) |
| 357 | + ) |
| 358 | + sid, file_path = _make_session_file(project_dir) |
| 359 | + |
| 360 | + tag_session(sid, "first", directory=project_path) |
| 361 | + tag_session(sid, "second", directory=project_path) |
| 362 | + tag_session(sid, "third", directory=project_path) |
| 363 | + |
| 364 | + lines = file_path.read_text().strip().split("\n") |
| 365 | + entry = json.loads(lines[-1]) |
| 366 | + assert entry["tag"] == "third" |
| 367 | + # All three tag entries present in file |
| 368 | + tag_lines = [ |
| 369 | + json.loads(line) for line in lines if json.loads(line).get("type") == "tag" |
| 370 | + ] |
| 371 | + assert len(tag_lines) == 3 |
| 372 | + |
| 373 | + def test_compact_json_format(self, claude_config_dir: Path, tmp_path: Path): |
| 374 | + """Appended JSON uses compact separators matching CLI.""" |
| 375 | + project_path = str(tmp_path / "proj") |
| 376 | + Path(project_path).mkdir(parents=True) |
| 377 | + project_dir = _make_project_dir( |
| 378 | + claude_config_dir, os.path.realpath(project_path) |
| 379 | + ) |
| 380 | + sid, file_path = _make_session_file(project_dir) |
| 381 | + |
| 382 | + tag_session(sid, "mytag", directory=project_path) |
| 383 | + |
| 384 | + lines = file_path.read_text().strip().split("\n") |
| 385 | + assert lines[-1] == f'{{"type":"tag","tag":"mytag","sessionId":"{sid}"}}' |
| 386 | + |
| 387 | + def test_unicode_sanitization(self, claude_config_dir: Path, tmp_path: Path): |
| 388 | + """Tag is sanitized: zero-width chars stripped.""" |
| 389 | + project_path = str(tmp_path / "proj") |
| 390 | + Path(project_path).mkdir(parents=True) |
| 391 | + project_dir = _make_project_dir( |
| 392 | + claude_config_dir, os.path.realpath(project_path) |
| 393 | + ) |
| 394 | + sid, file_path = _make_session_file(project_dir) |
| 395 | + |
| 396 | + # Tag with zero-width space and BOM embedded |
| 397 | + dirty_tag = "clean\u200btag\ufeff" |
| 398 | + tag_session(sid, dirty_tag, directory=project_path) |
| 399 | + |
| 400 | + lines = file_path.read_text().strip().split("\n") |
| 401 | + entry = json.loads(lines[-1]) |
| 402 | + assert entry["tag"] == "cleantag" |
| 403 | + |
| 404 | + def test_sanitization_rejects_pure_invisible( |
| 405 | + self, claude_config_dir: Path, tmp_path: Path |
| 406 | + ): |
| 407 | + """Tag that is only zero-width chars is rejected.""" |
| 408 | + project_path = str(tmp_path / "proj") |
| 409 | + Path(project_path).mkdir(parents=True) |
| 410 | + project_dir = _make_project_dir( |
| 411 | + claude_config_dir, os.path.realpath(project_path) |
| 412 | + ) |
| 413 | + sid, _ = _make_session_file(project_dir) |
| 414 | + |
| 415 | + with pytest.raises(ValueError, match="tag must be non-empty"): |
| 416 | + tag_session(sid, "\u200b\u200c\ufeff", directory=project_path) |
| 417 | + |
| 418 | + |
| 419 | +class TestSanitizeUnicode: |
| 420 | + """Tests for the _sanitize_unicode helper.""" |
| 421 | + |
| 422 | + def test_passthrough_clean_string(self): |
| 423 | + """Clean strings pass through unchanged.""" |
| 424 | + assert _sanitize_unicode("hello") == "hello" |
| 425 | + assert _sanitize_unicode("tag-with-dashes_123") == "tag-with-dashes_123" |
| 426 | + |
| 427 | + def test_strips_zero_width(self): |
| 428 | + """Zero-width spaces/joiners are stripped.""" |
| 429 | + assert _sanitize_unicode("a\u200bb") == "ab" |
| 430 | + assert _sanitize_unicode("a\u200cb") == "ab" # zero-width non-joiner |
| 431 | + assert _sanitize_unicode("a\u200db") == "ab" # zero-width joiner |
| 432 | + |
| 433 | + def test_strips_bom(self): |
| 434 | + """Byte order mark is stripped.""" |
| 435 | + assert _sanitize_unicode("\ufeffhello") == "hello" |
| 436 | + |
| 437 | + def test_strips_directional_marks(self): |
| 438 | + """LTR/RTL marks and isolates are stripped.""" |
| 439 | + assert _sanitize_unicode("a\u202ab\u202cc") == "abc" |
| 440 | + assert _sanitize_unicode("a\u2066b\u2069c") == "abc" |
| 441 | + |
| 442 | + def test_strips_private_use(self): |
| 443 | + """Private use area characters are stripped.""" |
| 444 | + assert _sanitize_unicode("a\ue000b") == "ab" |
| 445 | + assert _sanitize_unicode("a\uf8ffb") == "ab" |
| 446 | + |
| 447 | + def test_nfkc_normalization(self): |
| 448 | + """NFKC normalization is applied (composed chars).""" |
| 449 | + # Fullwidth 'A' → ASCII 'A' |
| 450 | + assert _sanitize_unicode("\uff21") == "A" |
| 451 | + |
| 452 | + def test_iterative_converges(self): |
| 453 | + """Handles multi-pass cases safely (max 10 iterations).""" |
| 454 | + # A string that needs multiple passes still converges |
| 455 | + result = _sanitize_unicode("a" + "\u200b" * 20 + "b") |
| 456 | + assert result == "ab" |
0 commit comments