{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "cell-23-21-00",
   "metadata": {},
   "source": [
    "# 23-21 · Тестируем сканер и классификатор\n",
    "\n",
    "Практика к разделу [«Проверяем сканирование и классификацию»](../../site/chapters/glava-23/23-24-testy-skanirovaniya.html). Использует настоящий пакет `safesort`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "setup-23-21",
   "metadata": {},
   "source": [
    "## Reproducible local environment\n",
    "\n",
    "```bash\n",
    "git clone https://github.com/Cartesian-School/safesort.git\n",
    "cd safesort\n",
    "python3.14 -m venv .venv\n",
    "source .venv/bin/activate\n",
    "# Windows PowerShell: .venv\\Scripts\\Activate.ps1\n",
    "python -m pip install -U pip\n",
    "python -m pip install -e \".[dev]\"\n",
    "python -m pip install jupyter ipykernel\n",
    "python -m ipykernel install --user --name safesort-py314 --display-name \"SafeSort Python 3.14\"\n",
    "jupyter lab\n",
    "```\n",
    "\n",
    "Select the **SafeSort Python 3.14** kernel. The diagnostic cell below must\n",
    "point into this `.venv` and the cloned `src/safesort` tree."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "diagnostic-23-21",
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "import safesort\n",
    "\n",
    "print(sys.executable)\n",
    "print(safesort.__file__)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-23-21-03",
   "metadata": {},
   "source": [
    "## Цель\n",
    "\n",
    "Написать и запустить тесты в духе `projects/python/safesort/tests/test_scanner.py` и `test_classifier.py`: вложенные файлы, исключение каталога результата, пустой каталог и известные/неизвестные расширения."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-23-21-04",
   "metadata": {},
   "source": [
    "## Example"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-23-21-05",
   "metadata": {},
   "outputs": [],
   "source": [
    "import tempfile\n",
    "from pathlib import Path\n",
    "\n",
    "from safesort.config import Config, DEFAULT_EXTENSIONS\n",
    "from safesort.scanner import scan\n",
    "from safesort.classifier import classify\n",
    "\n",
    "\n",
    "def test_scan_finds_nested_files(tmp_path):\n",
    "    (tmp_path / \"a\").mkdir()\n",
    "    (tmp_path / \"a\" / \"otchet.pdf\").write_text(\"...\", encoding=\"utf-8\")\n",
    "    (tmp_path / \"photo.jpg\").write_text(\"...\", encoding=\"utf-8\")\n",
    "\n",
    "    files = scan(tmp_path, Config())\n",
    "    names = {f.path.name for f in files}\n",
    "    assert names == {\"otchet.pdf\", \"photo.jpg\"}\n",
    "\n",
    "\n",
    "def test_scan_skips_destination_directory(tmp_path):\n",
    "    (tmp_path / \"Sorted\" / \"documents\").mkdir(parents=True)\n",
    "    (tmp_path / \"Sorted\" / \"documents\" / \"staryj.pdf\").write_text(\"...\", encoding=\"utf-8\")\n",
    "\n",
    "    files = scan(tmp_path, Config())\n",
    "    assert files == []\n",
    "\n",
    "\n",
    "def test_scan_empty_directory_returns_empty_list(tmp_path):\n",
    "    files = scan(tmp_path, Config())\n",
    "    assert files == []\n",
    "\n",
    "\n",
    "def test_classify_known_extension():\n",
    "    assert classify(\".pdf\", DEFAULT_EXTENSIONS) == \"documents\"\n",
    "\n",
    "\n",
    "def test_classify_unknown_extension_is_other():\n",
    "    assert classify(\".xyz\", DEFAULT_EXTENSIONS) == \"other\"\n",
    "\n",
    "\n",
    "for test_func in (\n",
    "    test_scan_finds_nested_files,\n",
    "    test_scan_skips_destination_directory,\n",
    "    test_scan_empty_directory_returns_empty_list,\n",
    "):\n",
    "    with tempfile.TemporaryDirectory() as tmp:\n",
    "        test_func(Path(tmp))\n",
    "    print(f\"OK: {test_func.__name__}\")\n",
    "\n",
    "test_classify_known_extension()\n",
    "test_classify_unknown_extension_is_other()\n",
    "print(\"OK: test_classify_known_extension, test_classify_unknown_extension_is_other\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-23-21-06",
   "metadata": {},
   "source": [
    "## Starter\n",
    "\n",
    "Заполните отмеченное место. Неизменённый starter не проходит tests."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "task-23-21",
   "metadata": {
    "tags": [
     "exercise",
     "starter"
    ]
   },
   "outputs": [],
   "source": [
    "def test_scan_skips_symlinks(tmp_path):\n",
    "    # TODO: create a file and symlink, call scan(), inspect returned names.\n",
    "    raise NotImplementedError\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-23-21-08",
   "metadata": {},
   "source": [
    "## Task\n",
    "\n",
    "Допишите тест: реальный файл найден, symlink на него пропущен. Если symlink недоступен, тест может завершиться через return."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-23-21-09",
   "metadata": {},
   "source": [
    "## Tests\n",
    "\n",
    "Запустите после task cell: есть основной пример и хотя бы один крайний случай."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "tests-23-21",
   "metadata": {
    "tags": [
     "exercise-tests"
    ]
   },
   "outputs": [],
   "source": [
    "with tempfile.TemporaryDirectory() as tmp:\n",
    "    test_scan_skips_symlinks(Path(tmp))\n",
    "\n",
    "# Edge cases for the same feature boundary.\n",
    "with tempfile.TemporaryDirectory() as tmp:\n",
    "    assert scan(Path(tmp), Config()) == []\n",
    "assert classify(\".unknown\", DEFAULT_EXTENSIONS) == \"other\"\n",
    "print(\"Tests passed\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-23-21-11",
   "metadata": {},
   "source": [
    "## Hint\n",
    "\n",
    "Проверяйте `symlink_to()` отдельно; после scan сравните множество `f.path.name`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-23-21-12",
   "metadata": {},
   "source": [
    "## Solution\n",
    "\n",
    "<details><summary>Показать решение после собственной попытки</summary>\n",
    "\n",
    "```python\n",
    "def test_scan_skips_symlinks(tmp_path):\n",
    "    fajl = tmp_path / \"photo.jpg\"\n",
    "    fajl.write_text(\"...\", encoding=\"utf-8\")\n",
    "    ssylka = tmp_path / \"ssylka.jpg\"\n",
    "    try:\n",
    "        ssylka.symlink_to(fajl)\n",
    "    except (OSError, NotImplementedError):\n",
    "        return  # символические ссылки не поддерживаются в этом окружении\n",
    "\n",
    "    files = scan(tmp_path, Config())\n",
    "    names = {f.path.name for f in files}\n",
    "    assert \"ssylka.jpg\" not in names\n",
    "    assert \"photo.jpg\" in names\n",
    "\n",
    "\n",
    "with tempfile.TemporaryDirectory() as tmp:\n",
    "    test_scan_skips_symlinks(Path(tmp))\n",
    "print(\"OK: test_scan_skips_symlinks\")\n",
    "```\n",
    "\n",
    "</details>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Cartesian Python 3.14",
   "language": "python",
   "name": "cartesian-python314"
  },
  "language_info": {
   "name": "python",
   "version": "3.14.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
