from pathlib import Path import pytest from bs4 import BeautifulSoup from jinja2 import Environment, FileSystemLoader from starlette.requests import Request from app.models import Employee, EmployeeNewsLink from app.services.admin_data import employee_detail_payload def test_employee_detail_template_is_human_readable(): template = Path("app/templates/employee_detail.html").read_text(encoding="utf-8") assert "Current data" not in template assert "
Tabs<" not in template
    assert "contacts.items" not in template
    assert "contacts.contact_items" in template
    assert "section.items" not in template
    assert "section.list_items" in template
    assert "Основная информация" in template
    assert "Контакты" in template
    assert "В новостях" in template
    assert "employee_view.news_links" in template
    assert "news.summary" in template
    assert "Разделы профиля" in template
    assert "graduation_theses" in template
    assert "Год защиты" in template
    assert "Parser version" not in template
    assert "First seen" not in template
    assert "Last seen" not in template
    assert "Dismissed at" not in template
    assert "Profile type" not in template
    assert "Profile ID" not in template
    assert "Впервые найден" in template
    assert "Последний раз найден" in template
    assert "Дата увольнения" in template
    assert "Тип профиля" in template
    assert "ID профиля" in template
    assert "Обновить данные" in template
    assert 'action="/admin/employees/{{ employee.id }}/refresh"' in template
    assert "Снапшоты" in template


@pytest.mark.parametrize("news_source", [None, "snapshot", "stored"])
@pytest.mark.parametrize("has_other_section", [False, True])
def test_employee_news_render_once_in_closed_disclosure(db_session, news_source, has_other_section):
    sections = [{"title": "Биография", "type": "generic", "paragraphs": ["Текст биографии"]}] if has_other_section else []
    if news_source:
        sections.append({"title": "В новостях", "type": "news",
                         "news_links": [{"title": "Новость из профиля", "url": "https://example.test/snapshot"}],
                         "paragraphs": ["Дублирующий текст новостей"]})
    employee = Employee(profile_key="staff:news", canonical_url="https://example.test/profile",
                        full_name="Тестовый сотрудник", status="active", current_data={"sections": sections})
    db_session.add(employee)
    db_session.flush()
    if news_source == "stored":
        db_session.add(EmployeeNewsLink(employee_id=employee.id, title="Сохранённая новость",
                                       url="https://example.test/stored", summary="Описание новости", source_hash="a" * 64))
        db_session.flush()
    template = Environment(loader=FileSystemLoader("app/templates"), autoescape=True).get_template("employee_detail.html")
    rendered = template.render(employee=employee, employee_view=employee_detail_payload(employee), snapshots=[],
                               request=Request({"type": "http", "scheme": "http", "headers": [],
                                                "path": f"/admin/employees/{employee.id}"}))
    soup = BeautifulSoup(rendered, "html.parser")
    assert not any(badge.get_text(strip=True) == "news" for badge in soup.select(".employee-section__type"))
    assert "Дублирующий текст новостей" not in rendered
    assert ("Текст биографии" in rendered) == has_other_section
    assert ("Разделы профиля не найдены." in rendered) == (not has_other_section)
    news = soup.select("details.employee-card__section--news")
    assert len(news) == (1 if news_source else 0)
    if news_source:
        assert not news[0].has_attr("open")
        assert news[0].summary.h3.get_text(strip=True) == "В новостях"
        expected_url = f"https://example.test/{'stored' if news_source == 'stored' else 'snapshot'}"
        assert [link["href"] for link in news[0].select("a")] == [expected_url]
        assert len(soup.select(f'a[href="{expected_url}"]')) == 1
        if news_source == "stored":
            assert "Описание новости" in news[0].get_text()
            assert "Новость из профиля" not in rendered