feat: 账号可设置同时学习课程数并支持关闭代理
This commit is contained in:
+21
-2
@@ -17,7 +17,9 @@ from admin.users import (
|
||||
list_users,
|
||||
read_credentials,
|
||||
read_proxy,
|
||||
read_course_workers,
|
||||
read_study_start,
|
||||
set_course_workers,
|
||||
set_paused,
|
||||
set_proxy,
|
||||
set_study_start,
|
||||
@@ -49,8 +51,8 @@ class PauseBody(BaseModel):
|
||||
class AdminProxyBody(BaseModel):
|
||||
employee_ids: list[str]
|
||||
scheme: str
|
||||
host: str
|
||||
port: int
|
||||
host: str = ""
|
||||
port: int | None = None
|
||||
username: str = ""
|
||||
password: str | None = None
|
||||
|
||||
@@ -67,6 +69,11 @@ class AdminStudyStartBody(BaseModel):
|
||||
second: int
|
||||
|
||||
|
||||
class AdminCourseWorkersBody(BaseModel):
|
||||
employee_ids: list[str]
|
||||
workers: int
|
||||
|
||||
|
||||
def require_admin(request: Request) -> str:
|
||||
if not admin_session_active(request.cookies):
|
||||
raise HTTPException(status_code=401, detail="未登录")
|
||||
@@ -186,6 +193,18 @@ def get_user_study_start(employee_id: str, db: Session = Depends(get_db), _: str
|
||||
return read_study_start(db, employee_id)
|
||||
|
||||
|
||||
@admin_router.put("/users/course-workers")
|
||||
def put_users_course_workers(
|
||||
body: AdminCourseWorkersBody, db: Session = Depends(get_db), _: str = Depends(require_admin)
|
||||
) -> dict:
|
||||
return set_course_workers(db, body.employee_ids, body.workers)
|
||||
|
||||
|
||||
@admin_router.get("/users/{employee_id}/course-workers")
|
||||
def get_user_course_workers(employee_id: str, db: Session = Depends(get_db), _: str = Depends(require_admin)) -> dict:
|
||||
return read_course_workers(db, employee_id)
|
||||
|
||||
|
||||
@admin_router.get("/users/{employee_id}/credentials")
|
||||
def get_credentials(employee_id: str, db: Session = Depends(get_db), _: str = Depends(require_admin)) -> dict:
|
||||
return read_credentials(db, employee_id)
|
||||
|
||||
+23
-2
@@ -11,6 +11,10 @@ from sqlalchemy.orm import Session
|
||||
|
||||
from euniv.crypto import decrypt_secret
|
||||
from euniv.models import Account
|
||||
from euniv.course_workers import CourseWorkersError
|
||||
from euniv.course_workers import apply as apply_workers
|
||||
from euniv.course_workers import of as workers_of
|
||||
from euniv.course_workers import view_of as workers_view
|
||||
from euniv.proxy import ProxyError, apply, clear, summary_of, url_of, view_of
|
||||
from euniv.study_window import StudyWindowError
|
||||
from euniv.study_window import apply as apply_start
|
||||
@@ -76,6 +80,7 @@ def list_users(db: Session) -> list[dict]:
|
||||
"study_start_hour": int(account.study_start_hour or 0),
|
||||
"study_start_minute": int(account.study_start_minute or 0),
|
||||
"study_start_second": int(account.study_start_second or 0),
|
||||
"course_workers": workers_of(account),
|
||||
}
|
||||
for account in accounts
|
||||
]
|
||||
@@ -202,8 +207,8 @@ def set_proxy(
|
||||
db: Session,
|
||||
employee_ids: list[str],
|
||||
scheme: str,
|
||||
host: str,
|
||||
port: int,
|
||||
host: str = "",
|
||||
port: object = None,
|
||||
username: str = "",
|
||||
password: str | None = None,
|
||||
) -> dict:
|
||||
@@ -249,6 +254,22 @@ def set_study_start(
|
||||
return {"ok": True, "count": len(accounts)}
|
||||
|
||||
|
||||
def read_course_workers(db: Session, employee_id: str) -> dict:
|
||||
return workers_view(_require(db, employee_id))
|
||||
|
||||
|
||||
def set_course_workers(db: Session, employee_ids: list[str], workers: int) -> dict:
|
||||
accounts = _accounts_by_ids(db, employee_ids)
|
||||
try:
|
||||
for account in accounts:
|
||||
apply_workers(account, workers)
|
||||
except CourseWorkersError as exc:
|
||||
db.rollback()
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
db.commit()
|
||||
return {"ok": True, "count": len(accounts)}
|
||||
|
||||
|
||||
def delete_user(db: Session, employee_id: str) -> dict:
|
||||
account = _require(db, employee_id)
|
||||
db.delete(account)
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
"""账号同时学习的课程数。"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = "0010_course_workers"
|
||||
down_revision = "0009_study_start"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table("accounts") as batch:
|
||||
batch.add_column(sa.Column("course_workers", sa.Integer(), nullable=False, server_default="1"))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table("accounts") as batch:
|
||||
batch.drop_column("course_workers")
|
||||
+31
-2
@@ -40,8 +40,8 @@ class MonthlyTargetBody(_BaseModel):
|
||||
|
||||
class ProxyBody(_BaseModel):
|
||||
scheme: str
|
||||
host: str
|
||||
port: int
|
||||
host: str = ""
|
||||
port: int | None = None
|
||||
username: str = ""
|
||||
password: str | None = None
|
||||
|
||||
@@ -53,6 +53,10 @@ class StudyStartBody(_BaseModel):
|
||||
second: int
|
||||
|
||||
|
||||
class CourseWorkersBody(_BaseModel):
|
||||
workers: int
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
init_db()
|
||||
@@ -257,6 +261,31 @@ def put_study_start(body: StudyStartBody, request: Request, db: Session = Depend
|
||||
return view_of(account)
|
||||
|
||||
|
||||
@app.get("/api/settings/course-workers")
|
||||
def get_course_workers(request: Request, db: Session = Depends(get_db)) -> dict:
|
||||
from euniv.course_workers import view_of
|
||||
|
||||
account = db.get(Account, _signed_in(request, db))
|
||||
if account is None:
|
||||
raise HTTPException(status_code=401, detail="未登录")
|
||||
return view_of(account)
|
||||
|
||||
|
||||
@app.put("/api/settings/course-workers")
|
||||
def put_course_workers(body: CourseWorkersBody, request: Request, db: Session = Depends(get_db)) -> dict:
|
||||
from euniv.course_workers import CourseWorkersError, apply, view_of
|
||||
|
||||
account = db.get(Account, _signed_in(request, db))
|
||||
if account is None:
|
||||
raise HTTPException(status_code=401, detail="未登录")
|
||||
try:
|
||||
apply(account, body.workers)
|
||||
except CourseWorkersError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
db.commit()
|
||||
return view_of(account)
|
||||
|
||||
|
||||
@app.get("/api/settings/proxy")
|
||||
def get_proxy(request: Request, db: Session = Depends(get_db)) -> dict:
|
||||
from euniv.proxy import view_of
|
||||
|
||||
+42
-39
@@ -25,13 +25,13 @@ import httpx
|
||||
from sqlalchemy import select
|
||||
|
||||
from euniv.client import EUNIV, STUDY_API, USER_AGENT, EunivClient, SessionExpired, _load_cookies
|
||||
from euniv.course_workers import of as course_workers_of
|
||||
from euniv.models import Account, Course
|
||||
from euniv.study_window import window_open
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
_MAX_CONCURRENT_USERS = 8
|
||||
_MAX_COURSE_PER_USER = 1
|
||||
_HOURS_REFRESH_SECONDS = 300.0
|
||||
|
||||
_lock = threading.Lock()
|
||||
@@ -384,6 +384,23 @@ def _halted(global_stop: asyncio.Event, hours: HoursWatcher) -> bool:
|
||||
return global_stop.is_set() or hours.user_stop.is_set()
|
||||
|
||||
|
||||
class CourseCursor:
|
||||
"""多协程顺着同一份课程表往下领,每门课只被领取一次。"""
|
||||
|
||||
def __init__(self, courses: list) -> None:
|
||||
self._courses = list(courses)
|
||||
self._index = 0
|
||||
self._lock = asyncio.Lock()
|
||||
|
||||
async def take(self):
|
||||
async with self._lock:
|
||||
if self._index >= len(self._courses):
|
||||
return None
|
||||
item = self._courses[self._index]
|
||||
self._index += 1
|
||||
return item
|
||||
|
||||
|
||||
async def _study_video(session: StudySession, kid: str, pkg_id: str,
|
||||
interval: int, stop: asyncio.Event, hours: HoursWatcher) -> None:
|
||||
view = 0
|
||||
@@ -611,7 +628,9 @@ class AutoStudyWorker:
|
||||
proxy = url_of(row)
|
||||
except Exception:
|
||||
continue
|
||||
eligible.append((row.employee_id, target, password, credential, proxy))
|
||||
eligible.append(
|
||||
(row.employee_id, target, password, credential, proxy, course_workers_of(row))
|
||||
)
|
||||
|
||||
if not course_list:
|
||||
_set_status(running=False, message="没有可用的用户或课程")
|
||||
@@ -628,8 +647,8 @@ class AutoStudyWorker:
|
||||
|
||||
sem = asyncio.Semaphore(_MAX_CONCURRENT_USERS)
|
||||
tasks = [
|
||||
self._study_user(emp_id, target, pw, cred, proxy, course_list, intervals, auto_mode, sem)
|
||||
for emp_id, target, pw, cred, proxy in eligible
|
||||
self._study_user(emp_id, target, pw, cred, proxy, workers, course_list, intervals, auto_mode, sem)
|
||||
for emp_id, target, pw, cred, proxy, workers in eligible
|
||||
]
|
||||
results = await asyncio.gather(*tasks, return_exceptions=True)
|
||||
for emp_id_tuple, result in zip(eligible, results):
|
||||
@@ -641,12 +660,11 @@ class AutoStudyWorker:
|
||||
|
||||
async def _study_user(self, employee_id: str, target: int,
|
||||
password: str, credential: dict, proxy: str | None,
|
||||
course_list: list, intervals: dict,
|
||||
workers: int, course_list: list, intervals: dict,
|
||||
auto_mode: bool, sem: asyncio.Semaphore) -> None:
|
||||
assert self._async_stop is not None
|
||||
async with sem:
|
||||
_set_user_status(employee_id, state="准备", course="")
|
||||
max_courses = _MAX_COURSE_PER_USER
|
||||
loop = asyncio.get_event_loop()
|
||||
token, user_id, org_id, cookies = await loop.run_in_executor(
|
||||
None, _prepare_session, employee_id, password, credential, proxy)
|
||||
@@ -663,50 +681,34 @@ class AutoStudyWorker:
|
||||
return
|
||||
ticker = asyncio.create_task(hours.ticker(self._async_stop))
|
||||
try:
|
||||
if max_courses <= 1:
|
||||
await self._study_courses_serial(
|
||||
session, employee_id, course_list, intervals,
|
||||
auto_mode, hours, user_id, org_id)
|
||||
else:
|
||||
await self._study_courses_parallel(
|
||||
session, employee_id, course_list, intervals,
|
||||
auto_mode, hours, user_id, org_id, max_courses)
|
||||
await self._study_courses(
|
||||
session, employee_id, course_list, intervals,
|
||||
auto_mode, hours, user_id, org_id, workers)
|
||||
finally:
|
||||
ticker.cancel()
|
||||
with contextlib.suppress(asyncio.CancelledError):
|
||||
await ticker
|
||||
|
||||
async def _study_courses_serial(self, session: StudySession, employee_id: str,
|
||||
course_list: list, intervals: dict,
|
||||
auto_mode: bool, hours: HoursWatcher,
|
||||
user_id: str, org_id: str) -> None:
|
||||
async def _study_courses(self, session: StudySession, employee_id: str,
|
||||
course_list: list, intervals: dict,
|
||||
auto_mode: bool, hours: HoursWatcher,
|
||||
user_id: str, org_id: str, workers: int) -> None:
|
||||
"""N 个协程顺着课程表往下领,已完成的跳过,未完成的发心跳。"""
|
||||
assert self._async_stop is not None
|
||||
for path, title, kind in course_list:
|
||||
if _halted(self._async_stop, hours):
|
||||
return
|
||||
await self._study_one_course(
|
||||
session, employee_id, path, title, kind,
|
||||
intervals, auto_mode, hours, user_id, org_id)
|
||||
cursor = CourseCursor(course_list)
|
||||
count = max(1, min(8, int(workers or 1)))
|
||||
|
||||
async def _study_courses_parallel(self, session: StudySession, employee_id: str,
|
||||
course_list: list, intervals: dict,
|
||||
auto_mode: bool, hours: HoursWatcher,
|
||||
user_id: str, org_id: str,
|
||||
max_courses: int) -> None:
|
||||
"""同一用户同时学多门课。共享会话和学时监视。"""
|
||||
assert self._async_stop is not None
|
||||
course_sem = asyncio.Semaphore(max_courses)
|
||||
|
||||
async def guarded(path: str, title: str, kind: str) -> None:
|
||||
if _halted(self._async_stop, hours):
|
||||
return
|
||||
async with course_sem:
|
||||
async def worker() -> None:
|
||||
while not _halted(self._async_stop, hours):
|
||||
item = await cursor.take()
|
||||
if item is None:
|
||||
return
|
||||
path, title, kind = item
|
||||
await self._study_one_course(
|
||||
session, employee_id, path, title, kind,
|
||||
intervals, auto_mode, hours, user_id, org_id)
|
||||
|
||||
tasks = [guarded(p, t, k) for p, t, k in course_list]
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
await asyncio.gather(*(worker() for _ in range(count)))
|
||||
|
||||
async def _study_one_course(self, session: StudySession, employee_id: str,
|
||||
path: str, title: str, kind: str,
|
||||
@@ -754,6 +756,7 @@ class AutoStudyWorker:
|
||||
await _study_scorm(session, kid, "", interval, self._async_stop, hours,
|
||||
user_id, org_id)
|
||||
except SessionExpired:
|
||||
hours.user_stop.set()
|
||||
_set_user_status(employee_id, state="会话过期")
|
||||
log.info("用户 %s 会话过期", employee_id)
|
||||
except Exception as exc:
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
"""同一账号同时学习的课程数。默认 1,最多 8。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
DEFAULT = 1
|
||||
MAX = 8
|
||||
|
||||
|
||||
class CourseWorkersError(ValueError):
|
||||
"""同时学习课程数不符合要求。"""
|
||||
|
||||
|
||||
def validate(value: object) -> int:
|
||||
if not isinstance(value, int) or isinstance(value, bool) or not DEFAULT <= value <= MAX:
|
||||
raise CourseWorkersError(f"同时学习课程数须为 {DEFAULT} 到 {MAX} 的整数")
|
||||
return value
|
||||
|
||||
|
||||
def apply(account, value: object) -> None:
|
||||
account.course_workers = validate(value)
|
||||
|
||||
|
||||
def of(account) -> int:
|
||||
raw = int(getattr(account, "course_workers", DEFAULT) or DEFAULT)
|
||||
return max(DEFAULT, min(MAX, raw))
|
||||
|
||||
|
||||
def view_of(account) -> dict:
|
||||
workers = of(account)
|
||||
return {"workers": workers, "max": MAX, "recommended": workers == DEFAULT}
|
||||
@@ -56,3 +56,4 @@ class Account(Base):
|
||||
study_start_hour: Mapped[int] = mapped_column(nullable=False, default=0, server_default="0")
|
||||
study_start_minute: Mapped[int] = mapped_column(nullable=False, default=0, server_default="0")
|
||||
study_start_second: Mapped[int] = mapped_column(nullable=False, default=0, server_default="0")
|
||||
course_workers: Mapped[int] = mapped_column(nullable=False, default=1, server_default="1")
|
||||
|
||||
+12
-3
@@ -5,6 +5,7 @@ from __future__ import annotations
|
||||
from urllib.parse import quote, urlparse
|
||||
|
||||
SCHEMES = ("http", "https", "socks4", "socks5", "socks5h")
|
||||
OFF_SCHEMES = ("", "off", "none", "direct", "close")
|
||||
|
||||
|
||||
class ProxyError(ValueError):
|
||||
@@ -61,14 +62,19 @@ def validate_parts(scheme: str, host: str, port: object, username: str = "") ->
|
||||
return kind, address, port, user
|
||||
|
||||
|
||||
def is_off(scheme: str | None) -> bool:
|
||||
return (scheme or "").strip().lower() in OFF_SCHEMES
|
||||
|
||||
|
||||
def enabled(account) -> bool:
|
||||
return bool(account.proxy_scheme and account.proxy_host and account.proxy_port)
|
||||
|
||||
|
||||
def view_of(account) -> dict:
|
||||
on = enabled(account)
|
||||
return {
|
||||
"enabled": enabled(account),
|
||||
"scheme": account.proxy_scheme or "http",
|
||||
"enabled": on,
|
||||
"scheme": account.proxy_scheme if on else "off",
|
||||
"host": account.proxy_host or "",
|
||||
"port": int(account.proxy_port) if account.proxy_port else None,
|
||||
"username": account.proxy_username or "",
|
||||
@@ -99,7 +105,10 @@ def url_of(account) -> str | None:
|
||||
)
|
||||
|
||||
|
||||
def apply(account, scheme: str, host: str, port: object, username: str = "", password: str | None = None) -> None:
|
||||
def apply(account, scheme: str, host: str = "", port: object = None, username: str = "", password: str | None = None) -> None:
|
||||
if is_off(scheme):
|
||||
clear(account)
|
||||
return
|
||||
kind, address, number, user = validate_parts(scheme, host, port, username)
|
||||
if password is not None and len(str(password)) > 256:
|
||||
raise ProxyError("代理密码过长")
|
||||
|
||||
@@ -452,6 +452,7 @@ def test_check_skips_empty_credential_and_updates_saved_one() -> None:
|
||||
"study_start_hour",
|
||||
"study_start_minute",
|
||||
"study_start_second",
|
||||
"course_workers",
|
||||
}
|
||||
assert saved["has_credential"] is True
|
||||
assert saved["refresh_paused"] is False
|
||||
@@ -726,3 +727,67 @@ def test_admin_can_set_study_start_for_selected_users() -> None:
|
||||
assert two["study_start"] == "每月5日 16:08:09"
|
||||
detail = client.get("/api/admin/users/s1-user/study-start")
|
||||
assert detail.json()["day"] == 20
|
||||
|
||||
|
||||
def test_admin_can_set_course_workers_for_selected_users() -> None:
|
||||
_add_account("w1-user")
|
||||
_add_account("w2-user")
|
||||
api = _app()
|
||||
client = TestClient(api.app)
|
||||
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
|
||||
listed = client.get("/api/admin/users").json()
|
||||
one = next(item for item in listed if item["employee_id"] == "w1-user")
|
||||
assert one["course_workers"] == 1
|
||||
saved = client.put(
|
||||
"/api/admin/users/course-workers",
|
||||
json={"employee_ids": ["w1-user", "w2-user"], "workers": 4},
|
||||
)
|
||||
assert saved.status_code == 200
|
||||
assert saved.json()["count"] == 2
|
||||
listed = client.get("/api/admin/users").json()
|
||||
one = next(item for item in listed if item["employee_id"] == "w1-user")
|
||||
two = next(item for item in listed if item["employee_id"] == "w2-user")
|
||||
assert one["course_workers"] == 4
|
||||
assert two["course_workers"] == 4
|
||||
one_only = client.put(
|
||||
"/api/admin/users/course-workers",
|
||||
json={"employee_ids": ["w1-user"], "workers": 1},
|
||||
)
|
||||
assert one_only.status_code == 200
|
||||
listed = client.get("/api/admin/users").json()
|
||||
one = next(item for item in listed if item["employee_id"] == "w1-user")
|
||||
two = next(item for item in listed if item["employee_id"] == "w2-user")
|
||||
assert one["course_workers"] == 1
|
||||
assert two["course_workers"] == 4
|
||||
bad = client.put(
|
||||
"/api/admin/users/course-workers",
|
||||
json={"employee_ids": ["w1-user"], "workers": 9},
|
||||
)
|
||||
assert bad.status_code == 400
|
||||
detail = client.get("/api/admin/users/w1-user/course-workers")
|
||||
assert detail.json()["workers"] == 1
|
||||
|
||||
|
||||
def test_admin_can_turn_off_proxy_with_scheme() -> None:
|
||||
_add_account("off-user")
|
||||
api = _app()
|
||||
client = TestClient(api.app)
|
||||
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
|
||||
client.put(
|
||||
"/api/admin/users/proxy",
|
||||
json={"employee_ids": ["off-user"], "scheme": "http", "host": "10.0.0.1", "port": 8080},
|
||||
)
|
||||
listed = client.get("/api/admin/users").json()
|
||||
one = next(item for item in listed if item["employee_id"] == "off-user")
|
||||
assert one["has_proxy"] is True
|
||||
closed = client.put(
|
||||
"/api/admin/users/proxy",
|
||||
json={"employee_ids": ["off-user"], "scheme": "off"},
|
||||
)
|
||||
assert closed.status_code == 200
|
||||
listed = client.get("/api/admin/users").json()
|
||||
one = next(item for item in listed if item["employee_id"] == "off-user")
|
||||
assert one["has_proxy"] is False
|
||||
detail = client.get("/api/admin/users/off-user/proxy")
|
||||
assert detail.json()["enabled"] is False
|
||||
assert detail.json()["scheme"] == "off"
|
||||
|
||||
@@ -121,6 +121,7 @@ def test_login_stores_password_and_credential_only() -> None:
|
||||
"study_start_hour",
|
||||
"study_start_minute",
|
||||
"study_start_second",
|
||||
"course_workers",
|
||||
}
|
||||
|
||||
home = client.get("/api/home")
|
||||
@@ -456,6 +457,7 @@ def test_user_can_set_proxy_with_or_without_password() -> None:
|
||||
empty = client.get("/api/settings/proxy")
|
||||
assert empty.status_code == 200
|
||||
assert empty.json()["enabled"] is False
|
||||
assert empty.json()["scheme"] == "off"
|
||||
assert "password" not in empty.json()
|
||||
saved = client.put(
|
||||
"/api/settings/proxy",
|
||||
@@ -490,6 +492,30 @@ def test_user_can_set_proxy_with_or_without_password() -> None:
|
||||
cleared = client.delete("/api/settings/proxy")
|
||||
assert cleared.status_code == 200
|
||||
assert cleared.json()["enabled"] is False
|
||||
assert cleared.json()["scheme"] == "off"
|
||||
off = client.put("/api/settings/proxy", json={"scheme": "off"})
|
||||
assert off.status_code == 200
|
||||
assert off.json()["enabled"] is False
|
||||
assert off.json()["scheme"] == "off"
|
||||
|
||||
|
||||
def test_user_can_set_course_workers() -> None:
|
||||
import euniv.api as api_module
|
||||
import euniv.service as service_module
|
||||
|
||||
api_module.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store(
|
||||
db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts
|
||||
)
|
||||
client = TestClient(api_module.app)
|
||||
assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200
|
||||
empty = client.get("/api/settings/course-workers")
|
||||
assert empty.status_code == 200
|
||||
assert empty.json() == {"workers": 1, "max": 8, "recommended": True}
|
||||
saved = client.put("/api/settings/course-workers", json={"workers": 3})
|
||||
assert saved.status_code == 200
|
||||
assert saved.json() == {"workers": 3, "max": 8, "recommended": False}
|
||||
bad = client.put("/api/settings/course-workers", json={"workers": 9})
|
||||
assert bad.status_code == 400
|
||||
|
||||
|
||||
def test_user_can_set_monthly_study_start() -> None:
|
||||
|
||||
@@ -4,8 +4,9 @@ import pytest
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from euniv.autostudy import HoursWatcher, _parse_minutes, _study_video, wait_stop
|
||||
from euniv.proxy import ProxyError, build_proxy_url, parse_proxy
|
||||
from euniv.autostudy import CourseCursor, HoursWatcher, _parse_minutes, _study_video, wait_stop
|
||||
from euniv.course_workers import CourseWorkersError, of as workers_of, validate as validate_workers
|
||||
from euniv.proxy import ProxyError, apply as apply_proxy, build_proxy_url, parse_proxy, view_of as proxy_view
|
||||
from euniv.study_window import CN_TZ, StudyWindowError, validate_start, window_open
|
||||
|
||||
|
||||
@@ -192,3 +193,54 @@ def test_study_window_rejects_invalid_parts() -> None:
|
||||
validate_start(32, 0, 0, 0)
|
||||
with pytest.raises(StudyWindowError):
|
||||
validate_start(1, 24, 0, 0)
|
||||
|
||||
|
||||
def test_course_workers_default_and_range() -> None:
|
||||
class Account:
|
||||
course_workers = 1
|
||||
|
||||
assert workers_of(Account()) == 1
|
||||
assert validate_workers(8) == 8
|
||||
with pytest.raises(CourseWorkersError):
|
||||
validate_workers(0)
|
||||
with pytest.raises(CourseWorkersError):
|
||||
validate_workers(9)
|
||||
|
||||
|
||||
def test_course_cursor_hands_each_item_once() -> None:
|
||||
async def main() -> None:
|
||||
cursor = CourseCursor([("a", "A", "视频"), ("b", "B", "文档"), ("c", "C", "课程")])
|
||||
seen: list[str] = []
|
||||
|
||||
async def worker() -> None:
|
||||
while True:
|
||||
item = await cursor.take()
|
||||
if item is None:
|
||||
return
|
||||
seen.append(item[0])
|
||||
await asyncio.sleep(0)
|
||||
|
||||
await asyncio.gather(worker(), worker(), worker())
|
||||
assert sorted(seen) == ["a", "b", "c"]
|
||||
|
||||
asyncio.run(main())
|
||||
|
||||
|
||||
class _ProxyAccount:
|
||||
def __init__(self) -> None:
|
||||
self.proxy_scheme = "http"
|
||||
self.proxy_host = "10.0.0.1"
|
||||
self.proxy_port = 8080
|
||||
self.proxy_username = "u"
|
||||
self.proxy_password_cipher = "cipher"
|
||||
|
||||
|
||||
def test_proxy_off_scheme_clears_settings() -> None:
|
||||
account = _ProxyAccount()
|
||||
apply_proxy(account, "off")
|
||||
view = proxy_view(account)
|
||||
assert view["enabled"] is False
|
||||
assert view["scheme"] == "off"
|
||||
assert account.proxy_scheme == ""
|
||||
assert account.proxy_host == ""
|
||||
assert account.proxy_port is None
|
||||
|
||||
Reference in New Issue
Block a user