str:
"""Chuyển dữ liệu lịch thi JSON thành chuỗi ICS.
- Mặc định (full=False) chỉ đưa thông tin quan trọng (Môn, Ngày công bố);
- ẩn mã slot UUID, phòng thi, ghi chú và các trường phụ.
+ Mặc định (full=False) chỉ đưa thông tin quan trọng (Môn, Phòng thi, Ngày công bố);
+ ẩn mã slot UUID, ghi chú và các trường phụ.
Khi full=True đưa toàn bộ thông tin phụ vào sự kiện lịch.
"""
if not isinstance(data, dict) or not isinstance(data.get("data"), list):
@@ -239,15 +239,24 @@ def convert_schedule_to_ics(data: dict) -> str:
e.begin = start_dt
e.end = end_dt
+ room_no = session.get("roomNo")
+ room_str = room_no if isinstance(room_no, str) else ("" if room_no is None else str(room_no))
+ group_name = session.get("groupName")
+ group_str = group_name if isinstance(group_name, str) else ("" if group_name is None else str(group_name))
+ session_no = session.get("sessionNo")
+ session_str = "" if session_no is None else str(session_no)
+ lecturer = session.get("lecturer")
+ lecturer_str = lecturer if isinstance(lecturer, str) and lecturer else ("N/A" if lecturer is None or lecturer == "" else str(lecturer))
+
# Location
- e.location = session.get("roomNo", "")
-
+ e.location = room_str
+
# Description
desc = []
- desc.append(f"Group: {session.get('groupName', '')}")
- desc.append(f"Session: {session.get('sessionNo', '')}")
- desc.append(f"Lecturer: {session.get('lecturer', 'N/A')}")
- desc.append(f"Room: {session.get('roomNo', '')}")
+ desc.append(f"Group: {group_str}")
+ desc.append(f"Session: {session_str}")
+ desc.append(f"Lecturer: {lecturer_str}")
+ desc.append(f"Room: {room_str}")
if session.get("meetURL"):
desc.append(f"Meet URL: {session.get('meetURL')}")
diff --git a/tasks/phase0.md b/tasks/phase0.md
deleted file mode 100644
index 8ba937f..0000000
--- a/tasks/phase0.md
+++ /dev/null
@@ -1,42 +0,0 @@
-# Phase 0 — CI và artifact cho mốc v0.2.0
-
-PR theo dõi: [PR 2](https://github.com/WindowScary321/myfap-api-cli/pull/2). Mọi commit của phase này được push vào `feat/phase0-v0.2.0`; các comment ghi mốc kiểm tra, commit và kết quả CI.
-
-## Phạm vi
-
-Gia cố CI trước các phase sửa v1, OAuth/session và v2. Version package được chuẩn bị thành `0.2.0` trong PR này; chưa tạo tag, publish PyPI hoặc triển khai auto release của Phase 5. Kế hoạch migration uv `0.1.8` trong `tasks/plan.md` và `tasks/todo.md` là lịch sử đã hoàn tất, giữ nguyên.
-
-## Công việc
-
-- [x] Tách branch từ `origin/main`, tạo PR và đồng bộ version với lockfile.
-- [x] Thêm nhóm dependency CI đã khóa; chuyển marker greenlet vào metadata runtime sau khi tái hiện lỗi pip Windows/Python 3.9 cần compiler.
-- [x] Thêm artifact gate cho version, entry point, README/license, file allowlist và manifest SHA-256.
-- [x] Kiểm tra cả wheel/sdist trong venv riêng ngoài checkout bằng pip; chạy check/version/help và ép UTF-8 cho subprocess.
-- [x] Chuyển CI thành source matrix → build Ubuntu một lần → artifact matrix → gate cuối; hỗ trợ reusable workflow outputs.
-- [x] Pin action theo commit SHA, giữ quyền `contents: read` và tắt persist Git credential.
-- [x] Thêm unit test với archive giả, version/hash sai, đường dẫn nhạy cảm, symlink, smoke isolation và UTF-8.
-- [x] Xác nhận source và artifact trên cả bốn môi trường GitHub Actions; tiếp tục kiểm tra lại khi PR có commit mới.
-- [x] Ghi các mốc commit/kiểm tra bằng comment và tổng hợp bằng chứng trong PR.
-
-## Kiểm chứng
-
-- Unit suite local: 32 test pass sau phần mở rộng, gồm regression version và các case scope/ready. Thử đảo điều kiện kiểm manifest khiến test hash thất bại; khôi phục code và suite pass lại.
-- `uv build`, `twine check --strict`, artifact validation và actionlint pass.
-- Pip smoke thật trên Windows/Python 3.9 và 3.11 pass cho wheel lẫn sdist; bốn tổ hợp OS/Python trên GitHub Actions đều pass.
-- [Run CI 38852306858](https://github.com/WindowScary321/myfap-api-cli/actions/runs/38852306858) của commit `393ced9`: 10/10 job thành công. Kết quả commit mới nhất được cập nhật trong PR.
-
-## Giới hạn
-
-CI không đăng nhập FEID hoặc gọi API FAP thật. Allowlist chỉ chặn đường dẫn/file ngoài chính sách; không chứng minh được không có secret hoặc PII ẩn trong nội dung mã Python. Kết quả Phase 0 không xác nhận OAuth/API v1/v2 đã được sửa.
-
-## Mở rộng: docs/tasks chỉ lưu trong repository
-
-- [x] Thêm `scope` lấy danh sách tên path Git, không đọc nội dung hai thư mục. Rename được xét như delete/add để đổi tên từ code sang docs hoặc ngược lại vẫn chạy đầy đủ CI.
-- [x] Chỉ thay đổi `docs/**` hoặc `tasks/**`: bỏ qua source/build/smoke, không tạo artifact; `ready` vẫn trả success. Thay đổi code/mixed và mọi `workflow_call` chạy đủ gate.
-- [x] `ready` dùng `always()` nhưng xác minh trạng thái từng job, không che lỗi/cancel hoặc trạng thái không xác định.
-- [x] Sparse checkout chỉ giữ code/tests/helpers và file build; không checkout docs/tasks trong các job CI. README/license root vẫn được giữ.
-- [x] Dùng `MANIFEST.in` loại hai thư mục khi build full checkout; validator từ chối docs/tasks trong wheel và sdist.
-- [x] Bổ sung test docs-only/tasks-only, code/mixed, rename/delete, reusable call và gate lỗi; artifact giả kiểm tra cả hai định dạng.
-- Kết quả pipeline của commit mở rộng trên GitHub Actions được theo dõi trong check của PR; comment ghi link run và commit tương ứng.
-
-Phần mở rộng giữ nguyên runtime API, entry point, version và các workflow outputs artifact đã có. Không thêm tài liệu vào `package-data` hoặc `data-files`.
diff --git a/tasks/phase1.md b/tasks/phase1.md
deleted file mode 100644
index 212eb97..0000000
--- a/tasks/phase1.md
+++ /dev/null
@@ -1,52 +0,0 @@
-# Phase 1: sửa v1 và lỗi dữ liệu
-
-## Phạm vi
-
-Tiếp nối Phase 0 trên phiên bản `0.2.0`, branch `fix/phase1-v1-data`. API v1 vẫn là mặc định. Công việc gồm query, payload, chọn kỳ học, survey, học phí, stdout và parser. OAuth/session đầy đủ, adapter v2 và auto release thuộc các phase sau.
-
-**Trạng thái sau kiểm chứng API thật ngày 16/10/2026:** phần triển khai và kiểm thử offline đã xong; live còn ba command chưa hoạt động. Chi tiết nằm trong [báo cáo kiểm chứng live](../docs/phase1-live-verification.md).
-
-## Các bước và tiêu chí hoàn tất
-
-- [x] Chuyển mọi query v1 sang `params=`, gồm kiểm tra session và handshake login/refresh; giữ nguyên case từng trường và kiểm tra encoding bằng credential giả.
-- [x] Kiểm tra HTTP, JSON và body code riêng; bảo toàn envelope và kiểu `data`. Survey not-found không bị diễn giải thành hết phiên hay không còn survey bắt buộc.
-- [x] Chọn kỳ theo `startDate`, giữ thứ tự server khi trùng ngày; ngày lỗi yêu cầu `--semester`, flag explicit không gọi resolver tự động.
-- [x] Tách checksum survey theo contract của app: username trim/lower, campus rỗng, khóa riêng và giờ Việt Nam.
-- [x] Dùng route v1 `GeFeeByRoll` đã đối chiếu với APK; HTTP 404 là lỗi, giữ mọi dòng học phí và `IsPaid`.
-- [x] Giữ stdout chỉ có JSON/ICS khi dùng `--stdout`; log/lỗi đi stderr. `--date` suy ra năm khi thiếu `--year`.
-- [x] Thêm fixture tổng hợp HTML có rowspan/colspan và lịch ICS; chỉ sửa parser khi regression test tái hiện lỗi.
-- [x] Chạy regression trên Python 3.9/3.11, build wheel/sdist mới, Twine strict, artifact gate và cài thử ngoài checkout.
-- [x] Review độc lập, kiểm tra diff và nội dung tiếng Việt; mở draft PR, ghi kết quả kiểm tra qua comment, giữ trạng thái draft.
-- [x] Chạy command trực tiếp với session mẫu; kiểm chứng 20 route, chỉ lưu kết quả đã che dữ liệu.
-- [ ] Giải quyết code 201 của `news` và `other notification`; chưa kết luận đây là lỗi hết phiên.
-- [ ] Xác minh endpoint học phí v1 vì cả `GeFeeByRoll` và phép chẩn đoán `GetFeeByRoll` đều trả HTTP 404.
-
-## Cơ sở đối chiếu
-
-- Kế hoạch chi tiết: `PLAN-PHASES.md`, Phase 1, ở workspace phân tích.
-- Bản so sánh: `analysis/myfap-api-cli-comparison.md` và `analysis/endpoints.md`.
-- Contract v1: `analysis/modules/module_550.js`, gồm route học phí và helper survey.
-- HAR/SAZ ngày 14/10 chỉ xác nhận runtime v2 và survey. Không coi đây là kiểm thử live v1.
-
-Fixture dùng dữ liệu giả, không chứa token, authenKey, chữ ký thực hoặc thông tin cá nhân. `docs/` và `tasks/` chỉ phục vụ đọc trong repository, không thuộc wheel/sdist hoặc phạm vi kiểm tra code của CI.
-
-## Kiểm chứng
-
-Trước thay đổi có 32 unittest. Suite mới tái hiện lỗi query, thứ tự kỳ, học phí HTTP 404, survey, stdout, ngày/năm và rowspan trước khi sửa. Kết quả sau sửa:
-
-- 88 unittest ban đầu; sau bổ sung `--timeout` trong PR #4, suite có 96 test và pass Ubuntu/Windows × Python 3.9/3.11.
-- Mutation đảo thứ tự ngày và sửa sai bộ đếm rowspan đều bị regression test bắt.
-- ICS pass trên Python 3.9 không có `tzdata`, dùng `pytz` sẵn có.
-- Twine strict và artifact validator pass với wheel/sdist mới; pip cài được cả hai artifact trong hai venv riêng ngoài checkout.
-- Mã runtime trong artifact khớp source. `docs/`, `tasks/` và `tests/` không nằm trong artifact; fixture chỉ phục vụ CI từ checkout.
-- Validator tiếng Việt strict không có lỗi hoặc cảnh báo; diff không có lỗi whitespace. Đã review độc lập và đối chiếu giá trị credential/identity từ capture bằng script, chỉ xuất kết quả không trùng, không in giá trị.
-
-PR [#4](https://github.com/WindowScary321/myfap-api-cli/pull/4) đã merge vào branch Phase 1. [CI sau merge timeout](https://github.com/WindowScary321/myfap-api-cli/actions/runs/38875363915) pass cả 11 job trên commit `07fb289` của PR [#3](https://github.com/WindowScary321/myfap-api-cli/pull/3). Trạng thái review/merge do maintainer quyết định; không tự chuyển Ready for review hoặc merge.
-
-Kiểm chứng live trên commit đó: 25 lần chạy command, 22 exit 0 và 3 exit 1, phủ 20 route. Lịch, điểm chi tiết, điểm danh, thông tin, đơn từ, môn học và survey not-found đã có bằng chứng runtime v1. Ba lỗi còn lại được ghi riêng, không bỏ qua trong kết luận.
-
-## Giới hạn
-
-Đã kiểm thử server v1 qua CLI với một session mẫu, không đọc trực tiếp thư mục chứa session. Fixture survey thành công và học phí v1 vẫn là dữ liệu tổng hợp: live chỉ quan sát survey not-found và học phí HTTP 404. Chưa xác minh nhiều tài khoản/campus hoặc đối chiếu toàn bộ nội dung với app chính.
-
-Phase 2 tiếp tục xử lý token validation, campus binding, session lock/atomic write và refresh rotation. Phase 1 không triển khai adapter v2, auto release, tag hoặc publish PyPI. Rollback dùng revert các commit trong PR; không có migration dữ liệu.
diff --git a/tasks/phase2.md b/tasks/phase2.md
deleted file mode 100644
index c6691bc..0000000
--- a/tasks/phase2.md
+++ /dev/null
@@ -1,62 +0,0 @@
-# Phase 2: OAuth và session
-
-## Phạm vi và thứ tự
-
-Branch `feat/phase2-oauth-session` bắt đầu từ `main` sau PR #3. Giữ version `0.2.0`, API v1 và Playwright. PR riêng phải ở trạng thái draft; chỉ maintainer quyết định chuyển Ready for review hoặc merge.
-
-1. Phân loại lỗi theo version/operation/HTTP/body. Code 201 chưa rõ nghĩa không gây refresh/logout; đọc chỉ retry một lần khi có tín hiệu hết phiên rõ ràng.
-2. Kiểm tra callback chính xác, state/nonce và PKCE mới mỗi login. Dùng discovery và xác minh ID token RS256 bằng JWKS, issuer/audience/azp/exp/sub/nonce/at_hash.
-3. Lưu session atomic và dùng lock xuyên suốt read → refresh → persist. Lưu refresh token mới trước validation/handshake tiếp theo; lỗi sau rotation không được quay về token cũ.
-4. Chọn campus theo parameter → session → default khi login mới. Binding campus/version/account type phải hợp lệ trước request dữ liệu; identity lấy từ handshake, không decode access token để suy MSSV.
-5. Giữ timeout đã có cho discovery/JWKS/token/handshake/API. Kiểm tra offline, build và smoke artifact trước gate live riêng.
-
-## Hợp đồng giữa các phần
-
-- `errors.py`: lỗi an toàn, không chứa credential, response hoặc URL có query; phân loại theo context của operation.
-- `oidc.py`: discovery, login attempt, callback, token request và validation tách biệt để persist rotation trước bước có thể lỗi.
-- `storage.py`: đọc JSON, ghi atomic và khóa file; chỉ auth orchestration điều phối transaction.
-- `auth.py`: vòng đời OAuth/FAP session, binding, identity handshake và rotation; CLI không tự mở file session để refresh.
-- `api.py`: kiểm binding và retry đọc có giới hạn; payload/output hiện có được giữ nguyên.
-
-Các module mới phục vụ trust boundary và tránh circular import; không thêm framework hoặc adapter v2 trong Phase 2.
-
-## Checklist
-
-- [x] Regression cho hai body 201 và ma trận HTTP/body 401, App Check, timeout/5xx, read/write retry.
-- [x] Callback/OIDC có test âm về chữ ký, issuer, audience/azp, nonce, expiry và at_hash; refresh có thể thiếu ID token nhưng nếu có phải cùng subject.
-- [x] Session cũ thiếu version được hiểu là v1; đổi binding bị chặn trước HTTP dữ liệu, handshake lỗi không ghi nhầm binding.
-- [x] Atomic write và lock được kiểm bằng file tạm/process riêng trên Windows và Unix; không đọc session thật trong test offline.
-- [x] Test rotation chứng minh token mới được persist trước handshake và được giữ lại khi validation/handshake lỗi.
-- [x] Matrix Ubuntu/Windows × Python 3.9/3.11, wheel/sdist, Twine và smoke cài bằng pip pass tại commit triển khai `8a369d3`.
-- [x] Live gate ghi rõ phần đã kiểm chứng và phần còn thiếu trong [báo cáo](../docs/phase2-verification.md); đã kiểm campus ngoài tài khoản, phục hồi sau handshake fault injection và chỉ lưu metadata đã che dữ liệu.
-- [x] Review độc lập, kiểm tra tiếng Việt và scan credential/PII trước commit/push; comment từng mốc vào draft PR.
-
-Đã chạy 179 test trên Windows với Python 3.9.25 và 3.11: mỗi môi trường có 176 pass, 3 skip theo điều kiện hệ điều hành/quyền symlink. Build local qua Twine strict, artifact validator và smoke cài wheel/sdist bằng pip. [CI của commit triển khai](https://github.com/WindowScary321/myfap-api-cli/actions/runs/38895605533) đã pass toàn bộ 11 job, gồm đủ matrix; kết quả commit tài liệu cuối được cập nhật qua comment PR.
-
-Live đã xác nhận login mới, ID token validation, handshake, refresh, đọc JSON sau refresh và logout session tạm. News/notification vẫn trả body 201 và không gây refresh. Kiểm tra HCM bằng tài khoản chỉ có APHL trả body 201 và giữ nguyên session; trở lại APHL thành công. Refresh thật kèm timeout handshake được tạo cục bộ giữ token đã rotate; bỏ fault thì handshake và đọc kỳ thành công mà không exchange token lần hai. Chuyển campus thành công, FAP session tự hết hạn và đổi version chưa được xác nhận live; đổi version chờ Phase 3. PR vẫn giữ draft.
-
-## Giới hạn
-
-Không đọc, liệt kê, sao chép hoặc kiểm tra trực tiếp thư mục session cá nhân. Live chỉ chạy CLI theo luồng thông thường; không lưu token, identity, lịch học, bảng điểm hoặc raw response vào Git. Không phát lại HAR/SAZ.
-
-Phase 4 tiếp tục điều tra lỗi backend/contract của news, notification và fee; sửa phân loại 201 không làm các endpoint đó trở thành thành công. Binding chuyển v2 và live đổi API version hoàn tất khi có adapter Phase 3. Auto release vẫn thuộc Phase 5.
-
-## QoL bổ sung trong PR #5
-
-- [x] Bỏ `GetSemester` probe khỏi nạp session; chỉ tra kỳ khi command cần tự chọn kỳ hoặc chạy `semesters`. Các request dữ liệu giữ refresh/retry một lần trên HTTP 401.
-- [x] Buffer 30 giây để refresh access token sớm trước handshake/phục hồi binding; không kéo dài thời hạn token hoặc thay xác minh ID token.
-- [x] Logout dọn session và lock idle. POSIX kiểm lại inode sau acquire để process chờ không dùng khóa đã unlink; Windows giữ lock nếu process khác còn mở handle.
-- [x] Regression command-level về số request, biên buffer và cleanup có process chờ; 191 test chạy trên Windows/Python 3.9/3.11, mỗi môi trường 188 pass và 3 skip.
-- [x] Live QoL: `info student` không có `GetSemester`, `semesters` chỉ một request, `login` dùng session local và logout xóa session/lock tạm. CI commit mới được cập nhật qua comment PR; xem [báo cáo kiểm chứng](../docs/phase2-verification.md).
-
-## Sửa lỗi sau review PR #5
-
-- [x] Mở rộng expiry v1 cho 17 FAP read operation có `Authen`: body `201` cùng exact message `Token invalid` kích hoạt retry tối đa một lần. Public/survey, handshake, operation ghi và body 201 thiếu/sai message không refresh; news/notification rỗng vẫn là lỗi operation.
-- [x] Login mới không bị binding v2/donor đã lưu chặn; chỉ kế thừa campus. Lệnh đọc và tham số yêu cầu v2/donor rõ ràng vẫn bị chặn trong Phase 2.
-- [x] `myfap login` tự mở trình duyệt khi session cần xác thực lại hoặc binding không được hỗ trợ, thay vì yêu cầu gõ lại `--force`.
-- [x] Thêm leeway 30 giây khi xác minh `exp/iat/nbf` của ID token, tách biệt buffer refresh sớm access token. Giữ strict type/finite và mọi kiểm tra chữ ký/identity.
-- [x] Logout dọn JSON hỏng mà không parse nội dung, giữ lock và guard đường dẫn.
-- [x] Attendance kiểm tra cặp `--subjectcode/--classname` trước khi nạp session hoặc gọi HTTP.
-- [x] Gỡ dependency `pkce` không còn caller và đồng bộ lockfile.
-
-Các lỗi có regression RED trước sửa và GREEN sau sửa. Tổng hợp kết luận, nguồn APK và kết quả kiểm chứng tại [báo cáo review](../docs/phase2-review-fixes.md); CI của commit cuối được cập nhật trong comment PR.
diff --git a/tasks/phase3.md b/tasks/phase3.md
deleted file mode 100644
index b5d476e..0000000
--- a/tasks/phase3.md
+++ /dev/null
@@ -1,29 +0,0 @@
-# Phase 3: adapter API v2 tối thiểu
-
-Branch `feat/phase3-v2-adapter` bắt đầu từ `origin/main` tại `238c718`, sau khi PR #5 được merge. Version package giữ `0.2.0`. API v1 tiếp tục là mặc định; API v2 chỉ chạy khi được chọn bằng tham số hoặc đã được lưu trong session.
-
-## Phạm vi
-
-- Thêm option global `--api-version v1|v2` và tham số `api_version` cho các wrapper. Thứ tự chọn: tham số, session, mặc định v1. Không tự đổi version sau lỗi mạng hoặc backend.
-- Giữ wrapper và định dạng output hiện tại. V2 hỗ trợ luồng campuses → login → semesters → schedule; GetApiActive phục vụ chẩn đoán. Operation chưa có adapter báo chưa hỗ trợ trước HTTP; parity đầy đủ thuộc Phase 4.
-- Bootstrap dùng POST với JSON rỗng; handshake dùng FEID access token, request dữ liệu dùng FAP authenKey. Campus bootstrap theo từng operation, không lấy campus cố định cho toàn bộ request.
-- Chữ ký v2 dùng HMAC-SHA256 với khóa UTF-8, timestamp giây và padding `%3d` theo APK. Giữ nguyên query/signature v1 và survey.
-- Mọi request dùng timeout đã chọn và không follow redirect. Đọc chỉ retry một lần khi có tín hiệu hết phiên rõ; App Check là lỗi riêng. Không thêm thao tác ghi hoặc cơ chế né App Check.
-- Đổi campus/version phải handshake trước khi lưu binding mới. Giữ token đã rotate nếu bước sau lỗi; không gửi FAP credential của session v1 vào request dữ liệu v2.
-
-## Kiểm chứng
-
-- [x] Contract matrix ghi method/path/query/body/header, nguồn Bearer và signing identity, account type, read/write và retry. Ghi đủ các route v2 giữ query Authen, kể cả route chưa triển khai.
-- [x] Test chữ ký bằng dữ liệu giả, timestamp cố định; ngăn decode khóa hex và double-encoding padding.
-- [x] Test bootstrap, handshake, kỳ học query rỗng, schedule và lỗi unsupported; giữ regression v1.
-- [x] Test lựa chọn version, session legacy, chuyển v1/v2 hai chiều và rollback binding khi handshake lỗi.
-- [x] Test CLI, stdout, timeout, HTTP/body 401, App Check và retry dùng key/chữ ký mới.
-- [x] Local Windows/Python 3.9/3.11, build, Twine strict, artifact validator và pip smoke.
-- [x] Live bằng session tạm riêng: campuses → login → semesters → schedule. Chỉ ghi metadata đã che; phần chưa kiểm chứng phải được ghi rõ.
-- [x] Review độc lập và rà tiếng Việt cho tài liệu, commit, comment PR. PR giữ draft.
-
-Local chạy 261 test trên mỗi phiên bản Python: 257 pass, 4 skip theo điều kiện Windows. Matrix CI Ubuntu/Windows × Python 3.9/3.11 của commit cuối được xác nhận trong [checks PR #7](https://github.com/WindowScary321/myfap-api-cli/pull/7/checks) và comment sau khi hoàn tất.
-
-Live v2 thành công với campus HN sau khi người dùng xác nhận mã campus; lần APHL trả body 401 được ghi riêng. Đổi version và refresh v2 có fixture, chưa xác nhận live riêng. Xem [hướng dẫn version](../docs/api-versions.md), [contract](../docs/v2-contracts.md) và [báo cáo](../docs/phase3-verification.md).
-
-Không đọc trực tiếp thư mục session cá nhân, không đưa token, query có credential, raw response, lịch học hoặc điểm thật vào Git. Nguồn contract là tài liệu và module APK trong workspace; capture không được phát lại. Không tạo tag, publish hoặc chuyển mặc định sang v2 trong phase này.
diff --git a/tasks/phase4.md b/tasks/phase4.md
deleted file mode 100644
index c605759..0000000
--- a/tasks/phase4.md
+++ /dev/null
@@ -1,45 +0,0 @@
-# Phase 4: phủ các command đọc hiện có
-
-Nhánh `feat/phase4-command-parity` bắt đầu từ main tại `74dd8e5`, sau khi PR #7 được merge. Giữ version package `0.2.0`, Python >=3.9 và entry point hiện có. V1 tiếp tục là mặc định; v2 được chọn bằng option hoặc session.
-
-## Phạm vi triển khai
-
-- Phủ v2 cho lịch học, lịch tuần, điểm tổng hợp/chi tiết, lịch thi, điểm danh tổng hợp/chi tiết, đơn từ, news, thông tin sinh viên/campus, fee, subjects và các lệnh kiểm tra feedback/profile/notification hiện có.
-- Giữ host và checksum riêng của survey. Không biến trạng thái not-found thành danh sách rỗng hoặc kết luận không có khảo sát bắt buộc.
-- Giữ JSON/ICS, tên trường, lựa chọn kỳ học theo ngày và stdout sạch. Mọi request dùng timeout đã chọn, không follow redirect hoặc fallback version.
-- Giữ query theo từng operation, bao gồm CampusCode, Semester/semester, CourseId và bốn route hiện có vẫn mang Authen. Điểm danh chi tiết dùng GetCourseAttendance trên v2 và getCourseAttendance trên v1.
-- Credential/signature/legacy Authen phải được dựng lại khi retry sau refresh. Chỉ retry đọc một lần khi có tín hiệu expiry rõ; App Check, timeout, 403 và 5xx không kích refresh.
-- Bảng coverage phân biệt bằng chứng APK, capture, fixture, live thành công/thất bại và phần chưa kiểm chứng. HTTP 404 không tự chứng minh route đã ngừng hỗ trợ.
-
-Không thêm transcript, balance, ảnh, news search, GetVersion, form feedback hoặc thao tác ghi vào CLI trong phase này. Những route đó thuộc Phase 6. Không phát hành, tạo tag hay đổi mặc định sang v2.
-
-## Kiểm chứng
-
-- [x] Contract test ở biên HTTP và wrapper cho các route đọc v1/v2; dữ liệu fixture hoàn toàn tổng hợp.
-- [x] CLI test cho nhóm command hiện có, stdout JSON/ICS, capability, option và lỗi trước HTTP.
-- [x] Regression cho retry dùng key/checksum/Authen mới và giới hạn một lần.
-- [x] Kiểm tra ICS bằng dữ liệu tổng hợp và một reader độc lập; ghi rõ giới hạn của reader hiện tại nếu còn.
-- [x] Live trên session tạm riêng, không đọc thư mục session cá nhân. Chỉ giữ metadata đã lọc, không giữ lịch/điểm/hồ sơ hoặc credential thật trong Git.
-- [x] Chạy lại news, notification và fee của v1; ghi nguyên trạng lỗi còn lại và giới hạn theo version/campus. Không dùng CI xanh thay kết luận live.
-- [x] Review độc lập, kiểm tra tiếng Việt, test Python 3.9/3.11, build, Twine, artifact validator và pip smoke.
-- [x] Draft PR riêng, comment tiếng Việt sau các mốc quan trọng; maintainer quyết định Ready for review và merge.
-
-Đã có bằng chứng cho 8 mục trong phạm vi kiểm chứng hiện tại. Theo quyết định của người dùng ngày 19/10/2026, positive fee/survey được chuyển sang [TODO chờ dữ liệu phù hợp](todo.md#kiểm-chứng-hoãn-chờ-dữ-liệu-phù-hợp), không chặn chuyển sang Phase 5. Contract và CLI được kiểm tra tại `tests/test_phase4_transport.py`, `tests/test_api_v2.py`, `tests/test_cli_v2_capabilities.py` và các regression v1. Test ICS dùng reader `icalendar` độc lập. Kết quả live v2 HN đã ghi 21 operation khác nhau, 23 request và dọn session/lock tạm; xem [coverage Phase 4](../docs/phase4-coverage.md). Matrix Ubuntu/Windows × Python 3.9/3.11, build và cài artifact được ghi tại [checks PR #8](https://github.com/WindowScary321/myfap-api-cli/pull/8/checks).
-
-Đã chạy lại ba lệnh v1/APHL ngày 19/10/2026 với login mới: news/notification vẫn trả HTTP 200/body 201, fee vẫn trả HTTP 404; lệnh đối chứng đọc thông tin sinh viên đạt 200/200 trước và sau. Session và lock tạm đã dọn. Mục chạy lại live được đánh dấu vì đã có kết quả và giới hạn, không có nghĩa ba lỗi response đã được sửa. Xem [kết quả v1](../docs/phase4-coverage.md#chạy-lại-ba-lệnh-v1-ngày-19102026).
-
-Positive fee/survey được hoãn, schema live vẫn chưa kiểm chứng: fee v2 trả HTTP/body 200 chưa đủ để kết luận positive case, còn survey trả body 404. Các lỗi response v1 vẫn mở trong TODO; chưa có cơ sở suy ra body 201 là rỗng hợp lệ hoặc HTTP 404 là route ngừng hỗ trợ toàn bộ. Các ô đã đánh dấu không có nghĩa mọi route đều đã hoạt động hoặc toàn bộ schema live đã được xác nhận.
-
-Parser điểm đã được sửa cho cấu trúc ba cột `Item`, `Weight`, `Value` khi không có cột ghi chú, gồm cả dòng đầu tiên và dòng tiếp theo trong `rowspan`. Hàng ba `| ` theo fallback category/item/value cũ vẫn được giữ để tránh thay đổi output tương thích.
-
-Xuất ICS cũng đã xử lý khoảng trắng quanh dấu `-` và dấu ngoặc trong `slotTime`; regression xác nhận giờ bắt đầu/kết thúc không thay đổi. Hai lỗi parser được tái hiện và kiểm thử bằng dữ liệu tổng hợp, chưa dùng dữ liệu tài khoản thật trong lượt sửa này.
-
-Các bản sửa bổ sung xử lý bảng Rich trên stdout `cp1252`, cho `login` tự phục hồi session sai cấu trúc và thêm nhóm dependency `ci` vào hai bước sync/test của workflow publish. Việc này sửa lỗi thiếu `icalendar` trên runner sạch; pipeline tag → reusable CI → publish → smoke → GitHub Release của Phase 5 vẫn chưa được triển khai. Không chạy publish hoặc thay đổi trigger release trong lượt sửa này.
-
-Sau bàn giao 19/10/2026, đã sửa thêm refresh `invalid_grant` không đánh dấu cần đăng nhập lại, student session thiếu `mssv`/`email`, help trên stdout `cp1252` và ICS thiếu `DTSTAMP`. Bộ test có 313 case; các nhánh lỗi session dùng fixture. Live v2/HN đã xác nhận login, refresh, đọc dữ liệu và ICS có đủ `UID`/`DTSTAMP` UTC, sau đó dọn session/lock tạm. Xem [kết quả sau sửa](../docs/phase4-coverage.md#kiểm-chứng-sau-bàn-giao-ngày-19102026); không dùng kết quả này đóng các TODO live v1 hoặc positive fee/survey.
-
-## Quy tắc dữ liệu và thiết bị
-
-Fiddler và Android chỉ phục vụ đối chiếu luồng đọc đã được cho phép. Dữ liệu request/response hoặc màn hình được xử lý cục bộ; chỉ tên operation, method, HTTP/body code, kiểu dữ liệu và kết quả kiểm tra được xuất ra. Không replay token từ capture, không đọc hoặc in token bằng tool, không gửi dữ liệu cá nhân ra ngoài PC. Không thay proxy, certificate, quyền truy cập hoặc dữ liệu tài khoản nếu không cần cho phép thử.
-
-Các kết quả live chưa đạt vẫn phải được ghi trong coverage. Nếu backend chưa đáp ứng hoặc thiếu positive case, phạm vi phát hành cần maintainer quyết định; không đánh dấu parity đầy đủ chỉ từ fixture.
diff --git a/tasks/plan.md b/tasks/plan.md
deleted file mode 100644
index 81ef19f..0000000
--- a/tasks/plan.md
+++ /dev/null
@@ -1,21 +0,0 @@
-# Kế hoạch chuyển quy trình dev sang uv
-
-## Phạm vi
-
-Quản lý môi trường dev và dependencies bằng uv; sửa `myfap version` để đọc metadata của package `myfap`. Giữ setuptools, tên package và phạm vi Python >=3.9. Bump phiên bản lên 0.1.8 cho thay đổi này.
-
-## Thứ tự thực hiện
-
-1. Chọn Python 3.11 cho dev, tạo `uv.lock` và hướng dẫn README. Xác nhận `uv sync --locked` cài được package ở chế độ editable.
-2. Thêm regression test qua lệnh CLI `version`, xác nhận test thất bại trước khi sửa tên distribution và thành công sau khi sửa.
-3. Chuyển build CI sang uv, chạy test trên PR và giữ Trusted Publishing khi có release. Kiểm tra wheel và source distribution.
-4. Review diff, kiểm tra tiếng Việt, tạo hai commit theo phạm vi và mở PR mới kèm bình luận kết quả kiểm tra.
-
-## Rủi ro và cách kiểm tra
-
-- Dependencies hiện chỉ có giới hạn phiên bản tối thiểu: lockfile cố định các phiên bản đã resolve; kiểm tra cài đặt và CLI trên Python 3.9/3.11.
-- `greenlet` 3.2.5 thiếu wheel Python 3.9 trên Windows: giới hạn phiên bản qua cấu hình uv cho đúng môi trường này để tránh yêu cầu compiler C++.
-- Playwright cần browser riêng khi đăng nhập: ghi rõ Chrome/Edge và Firefox dự phòng trong README; test version không đăng nhập hay gọi API.
-- Môi trường dev và package phát hành khác nhau: kiểm tra `myfap version` cả sau editable install và sau cài wheel.
-
-Danh sách công việc và trạng thái nằm trong [todo.md](todo.md).
diff --git a/tests/test_auth_lifecycle.py b/tests/test_auth_lifecycle.py
index cd0afc2..b82fe4d 100644
--- a/tests/test_auth_lifecycle.py
+++ b/tests/test_auth_lifecycle.py
@@ -250,11 +250,13 @@ def test_login_recovers_invalid_json_or_schema_only_after_success(self):
with self.subTest(content=content):
self.path.write_text(content, encoding="utf-8")
before = self.path.read_bytes()
- auth = module.MyFapAuth(session_file=self.path)
+ # File hỏng không đọc được binding nên rơi vào mặc định v2: cần campus tường minh.
+ campus = "HN" if content in ('{"PRIVATE_SENTINEL":', '[]') else None
+ auth = module.MyFapAuth(campus=campus, session_file=self.path)
self._prepare_login(auth, before)
self.assertEqual(auth.login(), ("new-fake-key", "TEST000"))
auth._authorize.assert_called_once()
- self.assertEqual(auth.campus, "SAVED" if '"campus":"SAVED"' in content else "APHL")
+ self.assertEqual(auth.campus, "SAVED" if '"campus":"SAVED"' in content else (campus or "APHL"))
self.assertEqual(self.load_file()["oidc_subject"], "new-fake-subject")
def test_fresh_login_inherits_campus_and_version_but_resets_unsupported_account(self):
@@ -272,6 +274,17 @@ def test_fresh_login_inherits_campus_and_version_but_resets_unsupported_account(
stored = self.load_file()
self.assertEqual((stored["campus"], stored["api_version"], stored["account_type"]), ("SAVED", expected_version, "student"))
+ def test_login_rejects_invalid_stored_version_before_browser(self):
+ self.path.write_text(json.dumps({"campus": "TEST", "api_version": "invalid"}), encoding="utf-8")
+ before = self.path.read_bytes()
+ auth = module.MyFapAuth(session_file=self.path)
+ auth._authorize = Mock()
+ with self.assertRaises(module.AuthError):
+ auth.login()
+ auth._authorize.assert_not_called()
+ self.oidc.begin_login.assert_not_called()
+ self.assertEqual(self.path.read_bytes(), before)
+
def test_fresh_login_honors_explicit_parameters_without_fallback(self):
self.path.write_text(json.dumps({"campus": "SAVED", "api_version": "v2", "account_type": "donor"}), encoding="utf-8")
before = self.path.read_bytes()
@@ -330,7 +343,8 @@ def test_failed_login_preserves_invalid_session_bytes(self):
with self.subTest(content=content):
self.path.write_text(content, encoding="utf-8")
before = self.path.read_bytes()
- auth = module.MyFapAuth(session_file=self.path)
+ campus = "HN" if content == '{"PRIVATE_SENTINEL":' else None
+ auth = module.MyFapAuth(campus=campus, session_file=self.path)
auth._authorize = Mock(side_effect=module.AuthError("Đã hủy đăng nhập."))
self.oidc.begin_login.return_value = {"nonce": "fake-nonce"}
with self.assertRaises(module.AuthError):
@@ -338,6 +352,20 @@ def test_failed_login_preserves_invalid_session_bytes(self):
auth._authorize.assert_called_once()
self.assertEqual(self.path.read_bytes(), before)
+ def test_login_without_campus_on_broken_file_defaults_v2_and_requires_campus(self):
+ # Chính sách mặc định v2: file hỏng coi như chưa có session, guard campus chặn trước browser.
+ self.path.write_text('{"PRIVATE_SENTINEL":', encoding="utf-8")
+ before = self.path.read_bytes()
+ auth = module.MyFapAuth(session_file=self.path)
+ auth._authorize = Mock()
+ self.oidc.begin_login = Mock()
+ with self.assertRaises(module.SessionBindingError) as caught:
+ auth.login()
+ self.assertIn("--campus", str(caught.exception))
+ auth._authorize.assert_not_called()
+ self.oidc.begin_login.assert_not_called()
+ self.assertEqual(self.path.read_bytes(), before)
+
def test_login_does_not_ignore_session_path_or_permission_errors(self):
with patch.object(self.auth.store, "read", side_effect=module.SessionStoreError("PRIVATE_SENTINEL")):
with self.assertRaises(module.AuthError) as caught:
@@ -351,6 +379,16 @@ def test_handshake_rejects_wrong_account_or_ambiguous_identity(self):
self.auth.session.post.return_value = response({"code": "200", "data": rows})
self.assertFalse(self.refresh())
+ def test_init_rejects_empty_session_file_and_control_characters_in_campus(self):
+ for bad_session in ("", " ", "bad\npath"):
+ with self.subTest(session_file=bad_session):
+ with self.assertRaises(module.AuthError):
+ module.MyFapAuth(session_file=bad_session)
+ for bad_campus in ("HN\nEvil", "HN\x7f"):
+ with self.subTest(campus=bad_campus):
+ with self.assertRaises(module.AuthError):
+ module.MyFapAuth(campus=bad_campus)
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_auth_v2.py b/tests/test_auth_v2.py
index 20a1a9e..af0f08c 100644
--- a/tests/test_auth_v2.py
+++ b/tests/test_auth_v2.py
@@ -24,14 +24,16 @@ def setUp(self):
self.addCleanup(temporary.cleanup)
self.path = Path(temporary.name) / "session.json"
- def test_public_version_uses_parameter_then_session_then_v1(self):
+ def test_public_version_uses_parameter_then_session_then_default(self):
auth = module.MyFapAuth(session_file=self.path)
- self.assertEqual(auth.resolve_api_version(), "v1")
+ # Chưa có session: CLI mặc định v2.
+ self.assertEqual(auth.resolve_api_version(), "v2")
self.path.write_text(json.dumps({"api_version": "v2"}), encoding="utf-8")
self.assertEqual(auth.resolve_api_version(), "v2")
explicit = module.MyFapAuth(api_version="v1", session_file=self.path)
with patch.object(explicit.store, "read", side_effect=AssertionError("must not read")):
self.assertEqual(explicit.resolve_api_version(), "v1")
+ # Session tồn tại nhưng thiếu trường version là session v1 cũ: giữ v1.
self.path.write_text("{}", encoding="utf-8")
self.assertEqual(auth.resolve_api_version(), "v1")
diff --git a/tests/test_ci_scope.py b/tests/test_ci_scope.py
index baa9f62..04594a4 100644
--- a/tests/test_ci_scope.py
+++ b/tests/test_ci_scope.py
@@ -14,6 +14,7 @@
class ScopePolicyTests(unittest.TestCase):
def test_repository_only_changes_skip_checks(self):
for paths in ([], ["docs/Example.md"], ["tasks/phase0.md"],
+ ["docs/cli/Example.md", "docs/discovery/todo.md"],
["docs/old.md", "docs/new.md", "tasks/todo.md"]):
with self.subTest(paths=paths):
self.assertFalse(ci_scope.paths_require_checks(paths))
diff --git a/tests/test_cli_options.py b/tests/test_cli_options.py
index 5faebf0..e55c998 100644
--- a/tests/test_cli_options.py
+++ b/tests/test_cli_options.py
@@ -131,3 +131,37 @@ def test_common_options_do_not_leak_between_invocations(self):
result = self.runner.invoke(app, ["login", "-f"])
self.assertEqual(result.exit_code, 0, result.output)
self.assertEqual(self.MyFapAuth.call_args.kwargs, {"campus": None, "session_file": None, "api_version": None, "timeout": None})
+
+ def test_empty_or_conflicting_command_options_fail_before_auth(self):
+ cases = (
+ ["--config", "", "login"],
+ ["--campus", "", "campuses", "--api-version", "v2"],
+ ["login", "--campus", ""],
+ ["--campus", "HN", "login", "--campus", ""],
+ ["schedule", "--semester", "", "--stdout"],
+ ["schedule", "--semester", " ", "--stdout"],
+ ["schedule", "--output", ""],
+ ["marks", "--courseid", "", "--stdout"],
+ ["marks", "-cid", "123", "-s", "Fall2026", "--stdout"],
+ ["attendance", "-sc", "", "-cn", "", "--stdout"],
+ ["week-timetable", "--date", "", "--stdout"],
+ ["week-timetable", "--week", "0", "--stdout"],
+ ["week-timetable", "--year", "0", "--stdout"],
+ )
+ for command in cases:
+ with self.subTest(command=command):
+ self.MyFapAuth.reset_mock()
+ self.MyFapEssential.reset_mock()
+ self.MyFapClient.reset_mock()
+ result = self.runner.invoke(app, command)
+ self.assertNotEqual(result.exit_code, 0, result.output)
+ self.assertEqual(result.stdout, "")
+ self.assertNotIn("Traceback", result.stderr)
+ self.MyFapAuth.assert_not_called()
+ self.MyFapEssential.assert_not_called()
+ self.MyFapClient.assert_not_called()
+
+ def test_child_login_campus_overrides_invalid_parent_campus(self):
+ result = self.runner.invoke(app, ["--campus", "", "login", "--campus", "HN", "-f"])
+ self.assertEqual(result.exit_code, 0, result.output)
+ self.assertEqual(self.MyFapAuth.call_args.kwargs["campus"], "HN")
diff --git a/tests/test_cli_requests.py b/tests/test_cli_requests.py
index 20bfbd6..1d5ee4e 100644
--- a/tests/test_cli_requests.py
+++ b/tests/test_cli_requests.py
@@ -104,8 +104,12 @@ def test_login_recovers_invalid_session_schema_without_force(self):
with patch.object(self.auth, "_oidc"):
result = self.runner.invoke(app, ["login"])
self.assertEqual(result.exit_code, 1, result.output)
- browser.assert_called_once()
- self.assertIn("Đã hủy đăng nhập", result.stderr)
+ if stored.get("api_version") == "v3":
+ browser.assert_not_called()
+ self.assertIn("API version không hợp lệ", result.stderr)
+ else:
+ browser.assert_called_once()
+ self.assertIn("Đã hủy đăng nhập", result.stderr)
self.assertEqual(self.path.read_bytes(), before)
self.auth.session.get.assert_not_called()
diff --git a/tests/test_cli_version.py b/tests/test_cli_version.py
index fcb01be..649e6eb 100644
--- a/tests/test_cli_version.py
+++ b/tests/test_cli_version.py
@@ -19,6 +19,72 @@ class CLIVersionTests(unittest.TestCase):
def setUp(self):
self.runner = CliRunner(**RUNNER_OPTIONS)
+ def test_environment_version_selects_cli_backend(self):
+ with TemporaryDirectory() as temporary, patch("myfap.cli.MyFapEssential") as essential:
+ essential.return_value.get_campuses.return_value = []
+ result = self.runner.invoke(app, ["--config", str(Path(temporary) / "missing.json"), "campuses"], env={"MYFAP_API_VER": "v2"})
+ self.assertEqual(result.exit_code, 0, result.output)
+ self.assertEqual(essential.call_args.kwargs["api_version"], "v2")
+
+ def test_default_and_precedence_for_campuses(self):
+ with TemporaryDirectory() as temporary:
+ path = Path(temporary) / "session.json"
+ cases = [
+ (None, {}, [], "v2"),
+ ({}, {}, [], "v1"),
+ ({"api_version": "v1"}, {"MYFAP_API_VER": "v2"}, [], "v2"),
+ ({"api_version": "v2"}, {"MYFAP_API_VER": "v2"}, ["--api-version", "v1"], "v1"),
+ (None, {"MYFAP_API_VER": "invalid"}, ["--api-version", "v2"], "v2"),
+ ]
+ for stored, env, flags, expected in cases:
+ with self.subTest(stored=stored, env=env, flags=flags), patch("myfap.cli.MyFapEssential") as essential:
+ if path.exists():
+ path.unlink()
+ if stored is not None:
+ path.write_text(json.dumps(stored), encoding="utf-8")
+ essential.return_value.get_campuses.return_value = []
+ result = self.runner.invoke(app, ["--config", str(path), *flags, "campuses"], env={"MYFAP_API_VER": None, **env})
+ self.assertEqual(result.exit_code, 0, result.output)
+ self.assertEqual(essential.call_args.kwargs["api_version"], expected)
+
+ def test_invalid_environment_rejected_before_auth(self):
+ with patch("myfap.cli.get_auth") as auth:
+ result = self.runner.invoke(app, ["campuses"], env={"MYFAP_API_VER": "invalid"})
+ self.assertNotEqual(result.exit_code, 0)
+ self.assertIn("MYFAP_API_VER", Text.from_ansi(result.stderr).plain)
+ auth.assert_not_called()
+
+ def test_environment_precedence_for_nested_options_and_invocations(self):
+ cases = (
+ ({"MYFAP_API_VER": "v1"}, ["other", "--api-version", "v2", "balance", "--stdout"], "v2"),
+ ({"MYFAP_API_VER": "v2"}, ["--api-version", "v1", "other", "balance", "--stdout"], "v1"),
+ ({"MYFAP_API_VER": "bad"}, ["other", "balance", "--api-version", "v2", "--stdout"], "v2"),
+ )
+ for env, command, expected in cases:
+ with self.subTest(env=env, command=command), patch("myfap.cli.MyFapAuth") as auth, patch("myfap.cli.MyFapOther") as other:
+ auth.return_value.resolve_api_version.return_value = expected
+ auth.return_value.load_session.return_value = True
+ other.return_value.get_balance.return_value = {"code": "200", "data": []}
+ result = self.runner.invoke(app, command, env=env)
+ self.assertEqual(result.exit_code, 0, result.output)
+ self.assertEqual(auth.call_args.kwargs["api_version"], expected)
+
+ def test_fresh_default_login_requires_explicit_campus_before_network(self):
+ with TemporaryDirectory() as temporary, patch("requests.Session.request") as request, patch.object(MyFapAuth, "_authorize") as browser:
+ result = self.runner.invoke(app, ["--config", str(Path(temporary) / "new.json"), "login", "--force"], env={"MYFAP_API_VER": None})
+ self.assertEqual(result.exit_code, 1)
+ self.assertIn("--campus", Text.from_ansi(result.stderr).plain)
+ request.assert_not_called()
+ browser.assert_not_called()
+
+ def test_doctor_reports_environment_source_without_reading_session(self):
+ with patch("myfap.auth.MyFapAuth", side_effect=AssertionError("no auth")), patch("requests.Session.request", side_effect=AssertionError("no network")):
+ result = self.runner.invoke(app, ["doctor", "--stdout"], env={"MYFAP_API_VER": "v1"})
+ self.assertEqual(result.exit_code, 0, result.output)
+ report = json.loads(result.stdout)
+ self.assertEqual((report["api_version"], report["api_version_source"]), ("v1", "environment"))
+ self.assertEqual(report["session_validation"], "not_checked")
+
def test_global_version_reaches_login_and_nested_commands(self):
for args in (["login", "--force"], ["info", "student", "--stdout"], ["other", "survey", "--stdout"]):
with self.subTest(command=args), patch("myfap.cli.MyFapAuth") as factory, patch("myfap.cli.MyFapClient") as client, patch("myfap.cli.MyFapOther") as other:
diff --git a/tests/test_parsers.py b/tests/test_parsers.py
index bad246f..7498d9d 100644
--- a/tests/test_parsers.py
+++ b/tests/test_parsers.py
@@ -233,6 +233,18 @@ def test_overnight_slot_wraps_end_to_next_day(self):
self.assertEqual(event.end.datetime, datetime(2026, 10, 15, 17, 50, tzinfo=timezone.utc))
self.assertEqual((event.end.datetime - event.begin.datetime).total_seconds(), 80 * 60)
+ def test_null_optional_fields_do_not_render_literal_none(self):
+ data = json.loads((FIXTURES / "schedule_valid.json").read_text(encoding="utf-8"))
+ data["data"][0].update({"roomNo": None, "groupName": None, "sessionNo": None, "lecturer": None, "meetURL": None})
+
+ content = convert_schedule_to_ics(data)
+ event = next(iter(Calendar(content).events))
+
+ self.assertIsNone(event.location)
+ self.assertNotIn("LOCATION:", content)
+ self.assertNotIn("None", event.description)
+ self.assertIn("Lecturer: N/A", event.description)
+
def test_slot_without_separator_raises_clear_message(self):
data = json.loads((FIXTURES / "schedule_valid.json").read_text(encoding="utf-8"))
data["data"][0]["slotTime"] = "7:30"
@@ -344,6 +356,29 @@ def test_server_influenced_filename_stays_inside_output_dir(self):
content = json.loads((Path(temporary) / files[0]).read_text(encoding="utf-8"))
self.assertEqual(content, {"code": 200, "data": []})
+ def test_windows_forbidden_filename_characters_are_sanitized(self):
+ with TemporaryDirectory() as temporary, redirect_stderr(io.StringIO()):
+ save_output({"code": 200, "data": []}, "BangDiem_Fall:2026*?.json", temporary, False)
+ files = sorted(path.name for path in Path(temporary).iterdir())
+ self.assertEqual(files, ["BangDiem_Fall_2026__.json"])
+
+ def test_marks_pretty_parses_uppercase_table_tag(self):
+ from unittest.mock import Mock, patch
+ from typer.testing import CliRunner
+ from myfap.cli import app
+
+ with TemporaryDirectory() as temporary:
+ cfg = Path(temporary) / "session.json"
+ cfg.write_text(json.dumps({
+ "campus": "HN", "api_version": "v2", "account_type": "student",
+ "authen_key": "FAKE_V2_KEY", "mssv": "TEST000", "email": "sample@example.invalid",
+ }), encoding="utf-8")
+ html_upper = ""
+ with patch("requests.Session.request", return_value=Mock(status_code=200, json=Mock(return_value={"code": 200, "data": html_upper}))):
+ result = CliRunner().invoke(app, ["--config", str(cfg), "marks", "-cid", "123", "-p", "--stdout"])
+ self.assertEqual(result.exit_code, 0, result.output)
+ self.assertEqual(json.loads(result.stdout)["data"], [{"category": "", "item": "Q1", "weight": "10%", "value": "9"}])
+
def test_empty_schedule_returns_valid_empty_calendar(self):
data = json.loads((FIXTURES / "schedule_empty.json").read_text(encoding="utf-8"))
diff --git a/tests/test_phase6_doctor.py b/tests/test_phase6_doctor.py
index 63b635f..ece9ad0 100644
--- a/tests/test_phase6_doctor.py
+++ b/tests/test_phase6_doctor.py
@@ -6,7 +6,6 @@
import requests
from myfap import diagnostics, v2
-from myfap.api import READ_OPERATIONS
from myfap.errors import ApiError, ApiPayloadError
@@ -17,11 +16,11 @@ def test_local_defaults_do_not_construct_auth_or_touch_session_or_http(self):
patch("myfap.storage.SessionStore.lock", side_effect=AssertionError("no session lock")), \
patch("requests.Session.request", side_effect=AssertionError("no network")):
report = diagnostics.get_diagnostics()
- self.assertEqual(report["api_version"], "v1")
+ self.assertEqual(report["api_version"], "v2")
self.assertEqual(report["api_version_source"], "default")
self.assertIsNone(report["campus"])
self.assertEqual(report["session_validation"], "not_checked")
- self.assertEqual(report["available_operations"], sorted(READ_OPERATIONS))
+ self.assertEqual(report["available_operations"], sorted(v2.SUPPORTED_OPERATIONS | {"GetRequiredSurvey"}))
self.assertEqual(report["online_probe"], {"requested": False})
self.assertIsInstance(report["package_version"], str)
self.assertEqual(set(report), {"package_version", "api_version", "api_version_source", "campus", "available_operations", "session_validation", "online_probe"})
@@ -39,7 +38,7 @@ def test_local_explicit_version_and_campus_use_only_supplied_values(self):
def test_invalid_inputs_and_online_v1_fail_before_client_or_http(self):
for kwargs in ({"api_version": "v3"}, {"api_version": ""}, {"api_version": False},
{"campus": ""}, {"campus": " "}, {"campus": "TEST\nPRIVATE"},
- {"campus": 3}, {"online": True}, {"api_version": "v1", "online": True}):
+ {"campus": 3}, {"api_version": "v1", "online": True}):
with self.subTest(kwargs=kwargs), \
patch("myfap.api.MyFapEssential", side_effect=AssertionError("no client")), \
patch("requests.Session.request", side_effect=AssertionError("no network")):
diff --git a/tests/test_phase6_reads.py b/tests/test_phase6_reads.py
index 4d43569..bdf80a6 100644
--- a/tests/test_phase6_reads.py
+++ b/tests/test_phase6_reads.py
@@ -433,12 +433,24 @@ def test_feedbacks_preserves_empty_list(self):
def test_feedbacks_v1_is_rejected_before_http(self):
self.save_session("v1")
- with patch("requests.Session.request") as request:
+ with patch("myfap.auth.MyFapAuth.load_session") as load, patch("requests.Session.request") as request:
result = self.runner.invoke(app, ["--config", str(self.path), "other", "feedbacks", "--stdout"])
self.assertEqual(result.exit_code, 1)
self.assertEqual(result.stdout, "")
self.assertIn("GetStudentFeedbacks", Text.from_ansi(result.stderr).plain)
+ load.assert_not_called()
+ request.assert_not_called()
+
+ def test_feedbacks_v1_on_v2_session_preserves_session_without_handshake(self):
+ self.save_session("v2")
+ before = self.path.read_bytes()
+ with patch("requests.Session.request") as request:
+ result = self.runner.invoke(app, ["--config", str(self.path), "--api-version", "v1", "other", "feedbacks", "--stdout"])
+ self.assertEqual(result.exit_code, 1)
+ self.assertEqual(result.stdout, "")
+ self.assertIn("GetStudentFeedbacks", Text.from_ansi(result.stderr).plain)
request.assert_not_called()
+ self.assertEqual(self.path.read_bytes(), before)
class ExamsIcsCommandTests(unittest.TestCase):
|