258 lines
10 KiB
Python
258 lines
10 KiB
Python
import io
|
||
import json
|
||
from datetime import datetime, timedelta, timezone
|
||
|
||
from bs4 import BeautifulSoup
|
||
from openpyxl import load_workbook
|
||
|
||
from hunter import create_app
|
||
from hunter.analysis import analyze_materials
|
||
from hunter.db import connect
|
||
from conftest import sign_in
|
||
|
||
|
||
def csrf(client):
|
||
client.get("/login")
|
||
with client.session_transaction() as session:
|
||
return session["csrf"]
|
||
|
||
|
||
def test_registration_login_and_hashed_password(client, app):
|
||
token = csrf(client)
|
||
response = client.post(
|
||
"/register",
|
||
data={"csrf": token, "email": "new@example.com", "password": "mock-password-456"},
|
||
)
|
||
assert response.status_code == 302
|
||
with connect(app.config["DATABASE"]) as db:
|
||
assert (
|
||
db.execute("SELECT password FROM users WHERE email='new@example.com'").fetchone()[0]
|
||
!= "mock-password-456"
|
||
)
|
||
assert (
|
||
client.post(
|
||
"/login",
|
||
data={"csrf": token, "email": "new@example.com", "password": "mock-password-456"},
|
||
).status_code
|
||
== 302
|
||
)
|
||
assert client.get("/").status_code == 200
|
||
|
||
|
||
def test_authentication_csrf_and_permissions(client):
|
||
assert client.get("/ideas").status_code == 302
|
||
assert (
|
||
client.post(
|
||
"/register", data={"email": "a@b.com", "password": "mock-long-password"}
|
||
).status_code
|
||
== 400
|
||
)
|
||
sign_in(client, "user")
|
||
assert client.get("/settings").status_code == 403
|
||
assert client.post("/refresh", data={"csrf": "mock-csrf"}).status_code == 403
|
||
assert client.post("/sources", data={"csrf": "mock-csrf"}).status_code == 403
|
||
assert client.post("/competitors", data={"csrf": "mock-csrf"}).status_code == 403
|
||
assert (
|
||
client.post("/user/1/role", data={"csrf": "mock-csrf", "role": "admin"}).status_code == 403
|
||
)
|
||
|
||
|
||
def test_main_sections_empty_states_and_languages(admin):
|
||
for path in (
|
||
"/",
|
||
"/trends",
|
||
"/ideas",
|
||
"/competitors",
|
||
"/analytics",
|
||
"/assistant",
|
||
"/sources",
|
||
"/saved",
|
||
"/history",
|
||
"/reports",
|
||
"/settings",
|
||
"/trend/AI",
|
||
):
|
||
response = admin.get(path)
|
||
assert response.status_code == 200, path
|
||
assert b"AI Trend" in response.data
|
||
for lang in ("ru", "kk", "en"):
|
||
assert admin.post("/language", data={"csrf": "mock-csrf", "lang": lang}).status_code == 302
|
||
response = admin.get("/")
|
||
assert f'lang="{lang}"'.encode() in response.data
|
||
assert admin.get("/trends?q=несуществующийзапрос").status_code == 200
|
||
assert admin.get("/analytics?days=not-a-number").status_code == 400
|
||
assert admin.get("/healthz").json == {"status": "ok"}
|
||
|
||
|
||
def test_competitor_summary_counts_sites_and_shows_last_detected_change(client, app):
|
||
sign_in(client, "user")
|
||
current = datetime.now(timezone.utc)
|
||
recent = (current - timedelta(days=1)).isoformat(timespec="seconds")
|
||
older = (current - timedelta(days=8)).isoformat(timespec="seconds")
|
||
with connect(app.config["DATABASE"]) as db:
|
||
db.executemany(
|
||
"INSERT INTO companies(name,url,status) VALUES(?,?,?)",
|
||
(
|
||
("Альфа", "https://alpha.example.com", "ok"),
|
||
("Бета", "https://beta.example.com", "error"),
|
||
("Гамма", "https://gamma.example.com", "pending"),
|
||
),
|
||
)
|
||
db.executemany(
|
||
"INSERT INTO changes(company_id,previous,current,created) VALUES(?,?,?,?)",
|
||
[(2, "Earlier", "Later", older)] + [(1, "Before", "After", recent)] * 51,
|
||
)
|
||
|
||
page = BeautifulSoup(client.get("/competitors").data, "html.parser")
|
||
cards = page.select("section[aria-labelledby=competitor-summary] .stat-card")
|
||
assert {
|
||
card.select_one(".stat-title").get_text(strip=True): card.strong.get_text(strip=True)
|
||
for card in cards
|
||
} == {
|
||
"Отслеживаемые сайты": "3",
|
||
"Ждут обновления": "1",
|
||
"С ошибкой обновления": "1",
|
||
"С изменениями за 7 суток": "1",
|
||
}
|
||
alpha, beta, gamma = page.select(".company-card")
|
||
assert alpha.time["datetime"] == recent
|
||
assert beta.time["datetime"] == older
|
||
assert "Изменения пока не обнаружены." in gamma.get_text()
|
||
assert len(page.select(".change-card")) == 50
|
||
|
||
|
||
def test_competitor_summary_without_sites(admin):
|
||
for lang, empty_state in (
|
||
("ru", "Сайты ещё не добавлены."),
|
||
("kk", "Сайттар әлі қосылмаған."),
|
||
("en", "No sites have been added yet."),
|
||
):
|
||
admin.post("/language", data={"csrf": "mock-csrf", "lang": lang})
|
||
page = BeautifulSoup(admin.get("/competitors").data, "html.parser")
|
||
summary = page.select_one("section[aria-labelledby=competitor-summary]")
|
||
assert summary.p.get_text(strip=True) == empty_state
|
||
|
||
|
||
def test_favorites_statuses_comments_cases_and_persistence(admin, app, material):
|
||
analyze_materials(app.config["DATABASE"])
|
||
with connect(app.config["DATABASE"]) as db:
|
||
item_id = db.execute("SELECT id FROM ideas").fetchone()[0]
|
||
path = f"/idea/{item_id}"
|
||
data = {"csrf": "mock-csrf"}
|
||
assert admin.get(path).status_code == 200
|
||
assert admin.post(f"/favorite/idea/{item_id}", data=data).status_code == 302
|
||
assert admin.post(path + "/state", data={**data, "status": "pilot_status"}).status_code == 302
|
||
assert (
|
||
admin.post(
|
||
path + "/comment", data={**data, "body": "<script>attack()</script>", "rating": "5"}
|
||
).status_code
|
||
== 302
|
||
)
|
||
assert b"<script>attack()</script>" in admin.get(path).data
|
||
assert admin.post(path + "/case", data=data).status_code == 302
|
||
assert "план проверки".encode() in admin.get(path).data
|
||
restarted = create_app(
|
||
{"TESTING": True, "SECRET_KEY": "mock-test-secret", "DATABASE": app.config["DATABASE"]}
|
||
)
|
||
second = restarted.test_client()
|
||
sign_in(second)
|
||
assert "Пилот в направлении".encode() in second.get("/saved").data
|
||
assert "Пилот в направлении".encode() in second.get("/history").data
|
||
assert "selected>Пилот".encode() in second.get(path).data
|
||
sign_in(admin, "user")
|
||
assert "Пилот в направлении".encode() not in admin.get("/saved").data
|
||
assert "attack()".encode() not in admin.get("/assistant").data
|
||
|
||
|
||
def test_search_filter_and_exports(admin, app, material):
|
||
analyze_materials(app.config["DATABASE"])
|
||
response = admin.get("/trends?q=умный&category=Smart+Home&country=US")
|
||
assert "Умный дом".encode() in response.data
|
||
filtered = BeautifulSoup(admin.get("/trends?category=Telecom").data, "html.parser")
|
||
assert not filtered.select(".signal-card")
|
||
excel = admin.get("/export.xlsx")
|
||
assert excel.status_code == 200
|
||
workbook = load_workbook(io.BytesIO(excel.data))
|
||
assert workbook["Signals"].max_row == 2
|
||
assert workbook["Ideas"].max_row == 2
|
||
assert admin.get("/idea/1/export.pdf").data.startswith(b"%PDF")
|
||
assert admin.get("/idea/999").status_code == 404
|
||
assert (
|
||
admin.post("/idea/1/state", data={"csrf": "mock-csrf", "status": "bogus"}).status_code
|
||
== 400
|
||
)
|
||
|
||
|
||
def test_settings_weights_validate_and_role_updates(admin, app):
|
||
invalid = dict(
|
||
csrf="mock-csrf",
|
||
interval=6,
|
||
demand=80,
|
||
revenue=25,
|
||
feasibility=20,
|
||
competition=15,
|
||
local_fit=15,
|
||
)
|
||
admin.post("/settings", data=invalid)
|
||
with connect(app.config["DATABASE"]) as db:
|
||
assert json.loads(
|
||
db.execute("SELECT value FROM settings WHERE key='weights'").fetchone()[0]
|
||
) == [25, 25, 20, 15, 15]
|
||
valid = {**invalid, "demand": 25}
|
||
admin.post("/settings", data=valid)
|
||
assert (
|
||
admin.post("/user/3/role", data={"csrf": "mock-csrf", "role": "analyst"}).status_code == 302
|
||
)
|
||
assert admin.post("/user/1/role", data={"csrf": "mock-csrf", "role": "user"}).status_code == 400
|
||
|
||
|
||
def test_translations_have_same_keys_and_no_missing_template_labels(admin):
|
||
from pathlib import Path
|
||
|
||
locale = [json.loads(path.read_text()) for path in Path("hunter/locales").glob("*.json")]
|
||
assert all(set(item) == set(locale[0]) for item in locale)
|
||
for route in ("/", "/settings", "/sources", "/competitors", "/assistant"):
|
||
soup = BeautifulSoup(admin.get(route).data, "html.parser")
|
||
assert not soup.select("script:not([src])")
|
||
for control in soup.select("input:not([type=hidden]),select,textarea"):
|
||
assert (
|
||
control.get("aria-label")
|
||
or control.find_parent("label")
|
||
or soup.find("label", attrs={"for": control.get("id")})
|
||
), route
|
||
|
||
|
||
def test_private_chat_and_persisted_case_do_not_leak_between_users(admin, app, material):
|
||
response = admin.post(
|
||
"/assistant",
|
||
data={"csrf": "mock-csrf", "question": "mock-private-question"},
|
||
follow_redirects=True,
|
||
)
|
||
assert b"mock-private-question" in response.data
|
||
sign_in(admin, "user")
|
||
assert b"mock-private-question" not in admin.get("/assistant").data
|
||
|
||
|
||
def test_browser_error_sdk_is_disabled_without_dsn(client, app):
|
||
assert b"vendor/sentry-" not in client.get("/login").data
|
||
app.config["PUBLIC_SENTRY_DSN"] = "https://mock-public@errors.example.com/1"
|
||
response = client.get("/login")
|
||
assert b"vendor/sentry-10.25.0.min.js" in response.data
|
||
assert "connect-src" in response.headers["Content-Security-Policy"]
|
||
assert "https://errors.example.com" in response.headers["Content-Security-Policy"]
|
||
|
||
|
||
def test_dollar_amounts_in_publisher_content_are_only_in_details(admin, app, material):
|
||
with connect(app.config["DATABASE"]) as db:
|
||
db.execute(
|
||
"UPDATE signals SET translated_title=?,summary=? WHERE id=?",
|
||
("Startup raises $62m", "A $1 billion round", material),
|
||
)
|
||
soup = BeautifulSoup(admin.get("/trends").data, "html.parser")
|
||
card = soup.select_one(".signal-card")
|
||
assert "$62" not in card.select_one("h3").get_text()
|
||
assert "$62" in card.select_one("details").get_text()
|
||
for node in card.select("details"):
|
||
node.decompose()
|
||
assert "$1" not in card.get_text()
|