Files
moonsource-linguoland/tests/linguoland/client_spec.lua
T
Garfield c737db3a0d ✅ (linguoland): 补上协议和进度测试
登录、书架和 xpointer 换 CFI 都有离线断言。
2026-11-27 00:51:41 +08:00

516 lines
16 KiB
Lua

--[[--
LinguoLand 登录、书架和进度协议。
@module tests.linguoland.client_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local JSON = require("support.json_stub")
package.loaded["json"] = JSON
package.loaded["l10n"] = {
apply = function() end,
get = function()
return function(msgid) return msgid end
end,
}
local cfg = { token = "test-token" }
local replaced, reloaded = 0, 0
local expired_msg
package.loaded["utils.settings"] = {
getSource = function() return cfg end,
saveSource = function() end,
}
package.loaded["source.auth"] = {
expired = function() return false end,
beginLogin = function() return function() return true end end,
ok = function() end,
expire = function(_id, msg)
expired_msg = msg
return msg
end,
}
package.loaded["source.logout"] = {
replaceLibrary = function(_id, commit)
replaced = replaced + 1
commit()
return true
end,
}
package.loaded["source.registry"] = {
reload = function() reloaded = reloaded + 1 end,
}
local meta_row
package.loaded["book.books_db"] = {
get = function() return { meta = { source = { storage_ref = "https://example/book.epub", shelf_entry_id = 9 } } } end,
setMeta = function(row) meta_row = row end,
}
local requests = {}
local function reply(_method, _url, _body)
return nil, "down"
end
package.loaded["http.request"] = {
get = function(url, opts, cb)
requests[#requests + 1] = { method = "GET", url = url, opts = opts }
cb(reply("GET", url, nil))
return { cancel = function() end }
end,
post = function(url, body, opts, cb)
requests[#requests + 1] = { method = "POST", url = url, body = body, opts = opts }
cb(reply("POST", url, body))
return { cancel = function() end }
end,
request = function(opts, cb)
requests[#requests + 1] = { method = opts.method, url = opts.url, opts = opts }
local raw, err, res = reply(opts.method, opts.url, nil)
if err or not res or not (tonumber(res.code) and tonumber(res.code) < 300) then
cb(res or { code = 500, body = raw }, err or "fail")
else
cb({ code = res.code, body = raw or "" }, nil)
end
return { cancel = function() end }
end,
ok = function(code)
local n = tonumber(code)
return n ~= nil and n >= 200 and n < 300
end,
}
local Client = require("moonsource_linguoland.client")
local Mapper = require("moonsource_linguoland.mapper")
Assert.eq(Client.token(), "test-token")
Assert.is_true(Client.isLoggedIn())
cfg.token = ""
Assert.is_false(Client.isLoggedIn())
cfg.token = "Bearer pasted"
Assert.eq(Client.token(), "pasted")
cfg.token = "test-token"
local function last()
return requests[#requests]
end
-- 书架走用户 token
requests = {}
local shelf_books, shelf_err
Client.getShelfAsync(function(books, err)
shelf_books, shelf_err = books, err
end)
Assert.eq(shelf_err, "down")
Assert.is_nil(shelf_books)
Assert.matches(last().url, "/api/v1/shelf$")
Assert.eq(last().opts.headers.Authorization, "Bearer test-token")
-- 未登录不打书架
cfg.token = ""
requests = {}
Client.getShelfAsync(function(_books, err) shelf_err = err end)
Assert.eq(shelf_err, "未登录")
Assert.eq(#requests, 0)
cfg.token = "test-token"
-- 密码原样提交,令牌字段是 access_token
requests = {}
reply = function(method, url)
if method == "POST" and url:find("/auth/login$") then
return '{"access_token":"acc","refresh_token":"ref"}'
end
return nil, "HTTP 401", { code = 401, body = '{"message":"邮箱或密码错误"}' }
end
local access, refresh, login_err
Client.loginAsync("[email protected]", " secret ", function(a, r, err)
access, refresh, login_err = a, r, err
end)
Assert.eq(access, "acc")
Assert.eq(refresh, "ref")
Assert.is_nil(login_err)
local login_body = JSON.decode(last().body)
Assert.eq(login_body.email, "[email protected]")
Assert.eq(login_body.password, " secret ")
Assert.is_nil(last().opts.headers.Authorization)
access, refresh, login_err = nil, nil, nil
reply = function()
return nil, "HTTP 401", { code = 401, body = '{"message":"邮箱或密码错误"}' }
end
Client.loginAsync("[email protected]", "nope", function(a, r, err)
access, refresh, login_err = a, r, err
end)
Assert.is_nil(access)
Assert.eq(login_err, "邮箱或密码错误")
Assert.is_nil(expired_msg)
-- 验证码用途是 LOGIN,短信带稳定 deviceId
reply = function() return "{}" end
requests = {}
local sent
Client.sendEmailCodeAsync("[email protected]", function(ok) sent = ok end)
Assert.is_true(sent)
Assert.eq(JSON.decode(last().body).purpose, "LOGIN")
Client.sendSmsCodeAsync("13800138000", function(ok) sent = ok end)
Assert.eq(JSON.decode(last().body).purpose, "LOGIN")
local first_device = JSON.decode(last().body)
requests = {}
Client.loginWithSmsCodeAsync("13800138000", "123456", function() end)
local sms_body = JSON.decode(requests[1].body)
Assert.eq(sms_body.purpose, nil)
Assert.eq(sms_body.code, "123456")
Assert.eq(sms_body.deviceId, cfg.device_id)
Assert.eq(#sms_body.deviceId >= 16, true)
Assert.eq(sms_body.phone, "13800138000")
-- sendSms 没有 deviceId 字段;登录这次必须和刚生成的一致
Assert.eq(first_device.phone, "13800138000")
-- 401 用 refresh 换票后重试,不把游客会话写成账号
cfg.refresh_token = "old-refresh"
local shelf_hits = 0
reply = function(method, url)
if method == "POST" and url:find("/auth/refresh$") then
return '{"access_token":"new-token","refresh_token":"new-refresh"}'
end
if method == "GET" and url:find("/api/v1/shelf$") then
shelf_hits = shelf_hits + 1
if shelf_hits == 1 then
return nil, "HTTP 401", { code = 401, body = '{"message":"Unauthorized"}' }
end
return '{"entries":[]}'
end
return nil, "down"
end
requests = {}
Client.getShelfAsync(function(books, err)
shelf_books, shelf_err = books, err
end)
Assert.is_nil(shelf_err)
Assert.len(shelf_books, 0)
Assert.eq(cfg.token, "new-token")
Assert.eq(cfg.refresh_token, "new-refresh")
Assert.eq(requests[#requests].opts.headers.Authorization, "Bearer new-token")
-- 没有 refresh 的 401 标失效,用服务端中文
cfg.token = "test-token"
cfg.refresh_token = nil
expired_msg = nil
reply = function()
return nil, "HTTP 401", { code = 401, body = '{"message":"登录已失效"}' }
end
Client.getShelfAsync(function(_books, err) shelf_err = err end)
Assert.eq(shelf_err, "登录已失效")
Assert.eq(expired_msg, "登录已失效")
-- 未登录书城走游客,不写入账号 token
cfg.token = ""
cfg.guest_token = nil
reply = function(method, url)
if method == "POST" and url:find("/auth/guest%-init$") then
return '{"access_token":"guest-token","refresh_token":"guest-refresh"}'
end
if method == "GET" and url:find("/api/v1/catalog$") then
return '{"items":[]}'
end
return nil, "down"
end
requests = {}
local catalog
Client.getCatalogAsync(function(books, err)
catalog, shelf_err = books, err
end)
Assert.is_nil(shelf_err)
Assert.len(catalog, 0)
Assert.eq(cfg.guest_token, "guest-token")
Assert.eq(cfg.token, "")
Assert.eq(cfg.account_id, nil)
Assert.matches(requests[1].url, "/auth/guest%-init$")
Assert.eq(JSON.decode(requests[1].body).deviceId, cfg.device_id)
-- 已登录书城不建游客
cfg.token = "test-token"
requests = {}
reply = function(_method, url)
if url:find("/api/v1/catalog$") then return '{"items":[]}' end
return nil, "down"
end
Client.getCatalogAsync(function(books, err) catalog, shelf_err = books, err end)
Assert.is_nil(shelf_err)
Assert.eq(#requests, 1)
Assert.eq(requests[1].opts.headers.Authorization, "Bearer test-token")
-- 换号走 replaceLibrary;同号只刷新令牌
cfg.token = "old"
cfg.account_id = "1"
replaced, reloaded = 0, 0
reply = function(_method, url)
if url:find("/auth/profile$") then return '{"id":9,"tier":"FREE"}' end
return nil, "down"
end
local committed, commit_err
Client.commitSession("brand-new", "r2", function(ok, err)
committed, commit_err = ok, err
end)
Assert.is_true(committed)
Assert.is_nil(commit_err)
Assert.eq(replaced, 1)
Assert.eq(cfg.account_id, "9")
Assert.eq(cfg.token, "brand-new")
Assert.eq(cfg.refresh_token, "r2")
replaced, reloaded = 0, 0
Client.commitSession("brand-new-2", "r3", function(ok) committed = ok end)
Assert.is_true(committed)
Assert.eq(replaced, 0)
Assert.eq(reloaded, 1)
Assert.eq(cfg.token, "brand-new-2")
-- 游客令牌不能当成登录
cfg.token = "keep"
local before = cfg.token
reply = function(_method, url)
if url:find("/auth/profile$") then return '{"id":3,"tier":"GUEST"}' end
return nil, "down"
end
Client.commitSession("guest-access", nil, function(ok, err)
committed, commit_err = ok, err
end)
Assert.is_false(committed)
Assert.eq(commit_err, "这是游客会话,请先在官网登录")
Assert.eq(cfg.token, before)
-- 进度是 0..1。大于 1 的旧百分数折回来。
cfg.token = "test-token"
cfg.refresh_token = nil
reply = function(_method, url)
if url:find("/reading%-progress/") then
return '{"progress":[{"locator":"epubcfi(/6/4)","percent":0.42}]}'
end
return nil, "down"
end
local progress
Client.getProgressAsync(166300, function(row, err)
progress, shelf_err = row, err
end)
Assert.is_nil(shelf_err)
Assert.eq(progress.percent, 0.42)
Assert.eq(progress.locator, "epubcfi(/6/4)")
Assert.matches(last().url, "/reading%-progress/by%-shelf%-entry/166300$")
reply = function() return '{"progress":{"percent":42}}' end
Client.getProgressAsync(1, function(row) progress = row end)
Assert.eq(progress.percent, 0.42)
-- 加入书架用 catalogId,并把书架条目写回元数据
meta_row = nil
reply = function() return '{"id":42}' end
local added
Client:addToShelfAsync("181", function(wire) added = wire end)
Assert.eq(added.id, 42)
Assert.eq(JSON.decode(last().body).catalogId, 181)
Assert.eq(meta_row.meta.source.shelf_entry_id, 42)
Assert.eq(meta_row.meta.source.storage_ref, "https://example/book.epub")
-- 删除用书架条目 id,不是书目 id
requests = {}
reply = function() return "", nil, { code = 204, body = "" } end
local removed
Client:removeFromShelfAsync("181", function(ok) removed = ok end)
Assert.is_true(removed)
Assert.matches(last().url, "/api/v1/shelf/9$")
Assert.eq(last().method, "DELETE")
-- 搜索
cfg.token = "test-token"
requests = {}
reply = function() return nil, "down" end
Client.searchAsync("oz", function() end)
Assert.matches(last().url, "/api/v1/catalog%?q=oz$")
requests = {}
local empty
Client.searchAsync("", function(books) empty = books end)
Assert.len(empty, 0)
Assert.eq(#requests, 0)
-- 合集
requests = {}
Client.getCollectionsAsync(function() end)
Assert.matches(last().url, "/api/v1/catalog/collections$")
Client.getCollectionBooksAsync(1, function() end)
Assert.matches(last().url, "/api/v1/catalog/collections/1$")
local books = Mapper.shelfBooks({
{
id = 166297,
origin = "CATALOG",
catalog = {
id = 1,
title = "Welcome to LinguoLand Reader",
author = "LinguoLand",
language = "en",
level = "BEGINNER",
format = "EPUB",
storageRef = "https://example/test.epub",
coverUrl = "https://example/1.jpg",
description = "欢迎短文",
},
},
{ id = 2, origin = "IMPORT" },
})
Assert.len(books, 1)
Assert.eq(books[1].stable_id, "1")
Assert.eq(books[1].title, "Welcome to LinguoLand Reader")
Assert.eq(books[1].authors, "LinguoLand")
Assert.eq(books[1].meta.language, "en")
Assert.eq(books[1].meta.source.shelf_entry_id, 166297)
Assert.eq(books[1].meta.source.storage_ref, "https://example/test.epub")
Assert.eq(books[1]._epub_url, "https://example/test.epub")
local null = function() end
books = Mapper.shelfBooks({
{
id = 9,
origin = "CATALOG",
titleOverride = null,
catalog = {
id = 1,
title = "Welcome",
author = "LinguoLand",
description = null,
coverUrl = "https://example/1.jpg",
},
},
})
Assert.eq(books[1].title, "Welcome")
Assert.eq(books[1].intro, "")
Assert.eq(books[1].cover, "https://example/1.jpg")
local saved_decode = JSON.decode
JSON.decode = function()
return {
entries = {
{
id = 9,
titleOverride = null,
catalog = {
id = 1,
title = "Welcome",
author = "LinguoLand",
description = null,
},
},
},
}
end
reply = function() return "{}" end
cfg.token = "test-token"
Client.getShelfAsync(function(rows, err)
books, shelf_err = rows, err
end)
JSON.decode = saved_decode
Assert.is_nil(shelf_err)
Assert.eq(books[1].title, "Welcome")
Assert.eq(books[1].intro, "")
books = Mapper.catalogBooks({
{
id = 181,
title = "The Thirty-Nine Steps",
author = "John Buchan",
language = "en",
level = "INTERMEDIATE",
format = "EPUB",
storageRef = "https://example/181.epub",
},
})
Assert.eq(books[1].stable_id, "181")
Assert.eq(books[1].meta.source.format, "EPUB")
Assert.eq(books[1].category, "INTERMEDIATE")
local groups = Mapper.collectionsToGroups({
{ id = 1, title = "给孩子的经典" },
{ id = 2, title = "绿野仙踪" },
})
Assert.eq(groups[1].id, "1")
Assert.eq(groups[1].title, "给孩子的经典")
Assert.eq(groups[2].title, "绿野仙踪")
-- 进度上传:locator 是 CFI,百分比保持 0..1,先读 updatedAt 再写
requests = {}
local pushed, push_err
reply = function(method)
if method == "GET" then
return '{"progress":{"percent":0.2,"locator":"epubcfi(/6/2!/4/2/1:1)","updatedAt":"2026-01-01T00:00:00Z"}}'
end
return '{"disposition":"accepted","progress":{"updatedAt":"2026-01-02T00:00:00Z"}}'
end
Client.putProgressAsync(9, "epubcfi(/6/2!/4/2/1:4)", 0.5, function(ok, err)
pushed, push_err = ok, err
end)
Assert.is_true(pushed)
Assert.is_nil(push_err)
Assert.eq(requests[1].method, "GET")
Assert.matches(requests[1].url, "/api/v1/reading%-progress/by%-shelf%-entry/9$")
Assert.eq(requests[2].method, "POST")
Assert.matches(requests[2].url, "/api/v1/reading%-progress$")
local push_body = JSON.decode(requests[2].body)
Assert.eq(push_body.shelfEntryId, 9)
Assert.eq(push_body.locator, "epubcfi(/6/2!/4/2/1:4)")
Assert.eq(push_body.percent, 0.5)
Assert.eq(push_body.baseUpdatedAt, "2026-01-01T00:00:00Z")
Assert.is_nil(push_body.anchor)
-- 没有旧进度就不带 baseUpdatedAt。防回滚也算这次已经交代过
requests = {}
reply = function(method)
if method == "GET" then return '{"progress":[]}' end
return '{"disposition":"preserved-anti-rollback","progress":{"updatedAt":"kept"}}'
end
Client.putProgressAsync(9, "epubcfi(/6/2!/4/2/1:0)", 0, function(ok)
pushed = ok
end)
Assert.is_true(pushed)
push_body = JSON.decode(requests[2].body)
Assert.eq(push_body.percent, 0)
Assert.is_nil(push_body.baseUpdatedAt)
-- 大于 1 的旧百分数折回 0..1,不能原样上传
requests = {}
reply = function(method)
if method == "GET" then return '{"progress":[]}' end
return '{"disposition":"preserved-stale-base","progress":{"updatedAt":"kept"}}'
end
Client.putProgressAsync(9, "epubcfi(/6/2!/4/2/1:1)", 50, function(ok)
pushed = ok
end)
Assert.is_true(pushed)
Assert.eq(JSON.decode(requests[2].body).percent, 0.5)
-- 没换成 CFI 不发请求
requests = {}
Client.putProgressAsync(9, "/body/DocFragment[1]/body/p/text().1", 0.5, function(ok, err)
pushed, push_err = ok, err
end)
Assert.is_nil(pushed)
Assert.eq(push_err, "位置换算失败")
Assert.eq(#requests, 0)
-- 服务端没收下,或者读进度失败:不算成功,也不再写
requests = {}
reply = function(method)
if method == "GET" then return '{"progress":[]}' end
return '{"disposition":"nope","progress":{"updatedAt":"kept"}}'
end
Client.putProgressAsync(9, "epubcfi(/6/2!/4/2/1:1)", 0.5, function(ok)
pushed = ok
end)
Assert.is_nil(pushed)
requests = {}
reply = function() return nil, "down" end
Client.putProgressAsync(9, "epubcfi(/6/2!/4/2/1:1)", 0.5, function(ok, err)
pushed, push_err = ok, err
end)
Assert.is_nil(pushed)
Assert.eq(push_err, "down")
Assert.eq(#requests, 1)
Assert.eq(requests[1].method, "GET")