✨ 初始提交:月读第三方书源插件集合

每个书源一个独立插件目录,含微信读书公众号订阅、书架导入等完整功能。

Co-authored-by: Copilot <[email protected]>
This commit is contained in:
GarfieldandCopilot committed 2026-11-16 12:08:03 +08:00
commit b41273ef9b
35 files changed
+4665

No files matched your search

+103
View File
@@ -0,0 +1,103 @@
--[[--
快看分类:官网动态题材、独立筛选、聚合分页与取消。
@module tests.moonsource_kuaikan.browse_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch, inject-field
local Assert = require("support.assert")
local JSON = require("support.json_stub")
package.loaded.json = JSON
local Mapper = require("moonsource_kuaikan.mapper")
local Request = require("http.request")
local calls, waiting, cancelled = {}, nil, {}
local failure
local function wire(page)
local rows = {}
for index = 1, page == 1 and 48 or 47 do
rows[index] = {
id = (page - 1) * 48 + index, title = "漫画 " .. index,
author_name = "作者", vertical_image_url = "https://img/cover.jpg",
}
end
return {
code = 200, total = 200,
hits = { topicCategories = { { tag_id = 0, title = "全部" }, { tagId = 20, title = "恋爱" } },
topicMessageList = rows },
}
end
Request.get = function(url, options, cb)
calls[#calls + 1] = url
Assert.is_nil(options.headers.Cookie)
local page = tonumber(url:match("page=(%d+)"))
if page == 2 and waiting then
waiting = cb
return { cancel = function() cancelled[page] = true end }
end
cb(page == 2 and failure or JSON.encode(wire(page)))
return { cancel = function() cancelled[page] = true end }
end
local Client = require("moonsource_kuaikan.client")
local source = require("moonsource_kuaikan.source").new()
local result, reason
source:browseAsync({ limit = 60 }, function(res, err) result, reason = res, err end)
Assert.is_nil(reason)
Assert.len(result.data, 60)
Assert.eq(result.data[49].stable_id, "49")
Assert.eq(result.data[1].authors, "作者")
Assert.len(calls, 2)
Assert.len(result.groups, 5)
Assert.eq(result.groups[1].chips[2].id, "20:1:0:0:1")
local node = "20:3:2:1:2"
local list, groups, more = Mapper.store(wire(2), node, 2)
Assert.len(list, 47)
Assert.is_true(more)
Assert.eq(groups[1].active, node)
Assert.eq(groups[1].chips[1].id, "0:3:2:1:2")
Assert.eq(groups[2].chips[2].id, "20:2:2:1:2")
Assert.eq(groups[3].chips[2].id, "20:3:1:1:2")
Assert.eq(groups[4].chips[3].id, "20:3:2:2:2")
Assert.eq(groups[5].chips[3].id, "20:3:2:1:3")
source:browseAsync({ node = node, limit = 12 }, function(res) result = res end)
Assert.len(result.data, 12)
Assert.matches(calls[#calls], "tag_id=20")
Assert.matches(calls[#calls], "label_dimension_origin=3")
Assert.matches(calls[#calls], "pay_status=2")
Assert.matches(calls[#calls], "update_status=1")
Assert.matches(calls[#calls], "sort=2")
local terminal = wire(3)
terminal.total = 100
Assert.is_false(select(3, Mapper.store(terminal, node, 3)))
terminal.hits.topicMessageList = {}
Assert.len(Mapper.store(terminal, node, 3), 0)
terminal.hits.topicMessageList = { { id = 1 } }
Assert.is_nil(Mapper.store(terminal, node, 3))
Assert.is_nil(Mapper.store({ code = 200, hits = {} }, node, 1))
Assert.eq(Mapper.storeNode("20:9:0:0:1"), "0:1:0:0:1")
Assert.eq(Mapper.storeNode("旧热门榜单"), "0:1:0:0:1")
failure = JSON.encode({ code = 500 })
result, reason = nil, nil
source:browseAsync({ limit = 60 }, function(res, err) result, reason = res, err end)
Assert.is_nil(result)
Assert.is_true(reason ~= nil)
failure = nil
waiting = true
local called = false
local handle = source:browseAsync({ limit = 60 }, function() called = true end)
handle.cancel()
Assert.is_true(cancelled[2])
Assert.is_nil(cancelled[1])
waiting(JSON.encode(wire(2)))
Assert.is_false(called)
Request.get = function(_url, _options, cb)
cb(nil, "network failure")
return { cancel = function() end }
end
Client.storeAsync(node, 1, function(books, err)
Assert.is_nil(books)
Assert.eq(err, "network failure")
end)
+92
View File
@@ -0,0 +1,92 @@
--[[--
快看章节:以服务端权限为准,分阶段取消不能覆盖在飞下载。
@module tests.moonsource_kuaikan.chapter_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch, inject-field
local Assert = require("support.assert")
local Stubs = require("support.stubs")
local Config = require("support.config")
local paths = {}
package.loaded["utils.paths"] = {
bookWorkDir = function() return Config.dir() .. "/kuaikan-chapter" end,
ensureBookWork = function() end,
ensureDir = function() end,
}
package.loaded["source.cbz"] = {
ready = function() return false end,
build = function(files, archive, _state, cb) paths = files; cb(archive) end,
}
package.loaded["utils.image"] = {
suffix = function() return ".jpg" end,
ok = function(path) return paths[path] == true end,
}
local fetched, pending, cancelled = false, nil, {}
package.loaded["moonsource_kuaikan.client"] = {
imagesAsync = function(_uid, cb)
fetched = true
cb({ "https://img/1.jpg", "https://img/2.jpg" })
return { cancel = function() cancelled.images = true end }
end,
}
package.loaded["http.request"] = {
download = function(_opts, path, cb)
pending = function(ok, err) paths[path] = ok; cb(ok, err) end
return { cancel = function() cancelled.download = true end }
end,
}
local Chapter = require("moonsource_kuaikan.chapter")
local called = false
local identity = { source_id = "ext.kuaikan", stable_id = "book" }
local handle = Chapter.materializeAsync(identity, { uid = "1", vip = true }, nil, function() called = true end)
Assert.is_true(fetched)
handle.cancel()
Assert.is_true(cancelled.download)
Assert.is_nil(cancelled.images)
pending(true)
Stubs.flush()
Assert.is_false(called)
paths = {}
local downloaded, progress, result = 0, {}, nil
require("http.request").download = function(_opts, path, cb)
downloaded = downloaded + 1
paths[path] = true
cb(true)
return { cancel = function() end }
end
Chapter.materializeAsync(identity, { uid = "1", vip = true }, function(done, total)
progress[#progress + 1] = { done, total }
end, function(path) result = path end)
Stubs.flush()
Assert.eq(downloaded, 2)
Assert.len(progress, 2)
Assert.eq(progress[2][1], 2)
Assert.eq(progress[2][2], 2)
Assert.matches(result, "/1%.cbz$")
Assert.len(paths, 2)
require("moonsource_kuaikan.client").imagesAsync = function(_uid, cb)
cb(nil, "本章未购买")
return { cancel = function() end }
end
Chapter.materializeAsync(identity, { uid = "2", vip = true }, nil, function(path, err)
Assert.is_nil(path)
Assert.eq(err, "本章未购买")
end)
-- 已有 CBZ 只复用缓存,不取页图、不重新组装。
require("source.cbz").ready = function() return true end
require("source.cbz").build = function() error("缓存 CBZ 不得重新组装") end
require("moonsource_kuaikan.client").imagesAsync = function() error("缓存命中不得下载页图") end
local cached
Chapter.materializeAsync(identity, { uid = "cached" }, nil, function(path) cached = path end)
Stubs.flush()
Assert.matches(cached, "/cached%.cbz$")
local cancelled_cache = false
local cached_handle = Chapter.materializeAsync(identity, { uid = "cached" }, nil,
function() cancelled_cache = true end)
cached_handle.cancel()
Stubs.flush()
Assert.is_false(cancelled_cache, "缓存交接也尊重取消")
+307
View File
@@ -0,0 +1,307 @@
--[[--
快看:签名、话题页目录、搜索和页图。
@module tests.moonsource_kuaikan.client_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
package.preload["json"] = function() return require("support.json_stub") end
local Assert = require("support.assert")
local Json = require("support.json_stub")
local Mapper = require("moonsource_kuaikan.mapper")
local Page = require("moonsource_kuaikan.page")
local html = [[
<script>window.__NUXT__=(function(z,a,b,c,d,e,f,g,h){z.nickname="翘摇";return {data:[{topicInfo:{id:a,title:b,cover_image_url:c,description:d,first_comic_id:h},comics:[{id:a,title:e,locked:f},{id:11,title:"第二话",locked:g}]}]}}({},9,"错撩","https:\u002F\u002Fc\u002Fa.jpg","简介","序章",false,true,42));</script>
]]
local page = Page.topic(html)
Assert.eq(page.nickname, "翘摇")
Assert.eq(page.info.id, 9)
Assert.eq(page.info.title, "错撩")
Assert.eq(page.info.cover_image_url, "https://c/a.jpg")
Assert.eq(page.info.first_comic_id, 42)
Assert.eq(#page.chapters, 2)
Assert.eq(page.chapters[1].title, "序章")
Assert.eq(page.chapters[1].locked, false)
Assert.eq(page.chapters[2].locked, true)
Assert.is_nil(Page.topic("<html></html>"))
local escaped = Page.topic(html:gsub("简介", "第一行\\n第二行\\t\\\"引号\\\""))
Assert.eq(escaped.info.description, '第一行\n第二行\t"引号"')
Assert.is_nil(Page.topic(html:gsub('title:"第二话"', 'title:')))
Assert.is_nil(Page.topic(html:gsub("true,42", "true,@")))
local detail = Mapper.detail(page.info, page.nickname)
Assert.eq(detail.stable_id, "9")
Assert.eq(detail.authors, "翘摇")
Assert.eq(detail.cover, "https://c/a.jpg")
Assert.eq(detail.source_id, "ext.kuaikan")
Assert.eq(detail.intro, "简介")
local toc = Mapper.chapters(page.chapters)
Assert.eq(#toc, 2)
Assert.eq(toc[1].uid, "9")
Assert.eq(toc[1].vip, false)
Assert.eq(toc[1].toc_version, Mapper.TOC_VERSION)
Assert.eq(toc[2].vip, true)
local found = Mapper.search({
code = 200,
data = { topics = { hit = { { id = 9, title = "错撩", user = { nickname = "翘摇" }, vertical_image_url = "https://img/a.webp" } } } },
})
Assert.eq(found[1].stable_id, "9")
Assert.eq(found[1].authors, "翘摇")
Assert.eq(found[1].cover, "https://img/a.webp")
Assert.is_nil(Mapper.search({ code = 403 }))
local home = Mapper.home({
code = 200,
data = { popularity_topics = { { id = 3, title = "榜上", cover_image_url = "https://img/b.webp" } } },
})
Assert.eq(home[1].stable_id, "3")
Assert.eq(home[1].cover, "https://img/b.webp")
local fav = Mapper.fav({
code = 200,
data = { total = 1, topics = { { id = 9, title = "错撩", user = { nickname = "翘摇" }, vertical_image_url = "https://img/a.webp" } } },
})
Assert.eq(fav[1].stable_id, "9")
Assert.eq(fav[1].title, "错撩")
Assert.eq(#Mapper.fav({ code = 200, data = { total = 0, topics = {} } }), 0)
Assert.is_nil(Mapper.fav({ code = 200, data = {} }))
local urls = Mapper.images({
code = 200,
data = { comic_info = { locked = false, comic_images = { { url = "https://img/1.jpg" }, { url = "https://img/2.jpg" } } } },
})
Assert.eq(#urls, 2)
Assert.eq(urls[1], "https://img/1.jpg")
Assert.eq(select(2, Mapper.images({ code = 200, data = { comic_info = { locked = true, comic_images = {} } } })), "locked")
Assert.eq(Mapper.images({ code = 200, data = { comic_info = { locked = false, comic_images = {
{ url = "https://img/original.jpg", url1280 = "https://img/large.jpg" },
{ url = "https://img/fallback.jpg", url1280 = "" },
} } } })[1], "https://img/large.jpg")
Assert.eq(Mapper.images({ code = 200, data = { comic_info = { comic_images = {
{ url = "https://img/fallback.jpg", url1280 = "" },
} } } })[1], "https://img/fallback.jpg")
Assert.is_nil(Mapper.fav({ code = 200, data = { total = 1, topics = { { id = 9 } } } }))
Assert.is_nil(Mapper.fav({ code = 200, data = { topics = {} } }))
local Client = require("moonsource_kuaikan.client")
local indexes = {}
for slot = 0, 15 do indexes[#indexes + 1] = slot end
Assert.eq(
Client.answer("1793924589213", indexes),
"MjAyMDA4MjBfMEIxdDJNM1Q0VTVsNmU3czhMOVgxMFAxMUkxMkYxM2oxNGYxNWNfMTc5MzkyNDU4OTIxM18zVDRVNWw2ZTdzOEw5WDEwUDExSTEyRjEzajE0ZjE1Yw=="
)
local requests, options = {}, {}
local cfg = { cookie = "session=saved" }
package.loaded["utils.settings"] = { getSource = function() return cfg end }
package.preload["http.request"] = function()
return {
header = function(res, name)
local headers = res and res.headers
return headers and headers[name]
end,
get = function(url, request_options, callback)
requests[#requests + 1] = url
options[#options + 1] = request_options
if url:find("/search/web/complex", 1, true) then
callback(Json.encode({ code = 200, data = { topics = { hit = { { id = 9, title = "错撩" } } } } }), nil, nil)
elseif url:find("/v2/pweb/fav/topics", 1, true) then
callback(Json.encode({ code = 200, data = { total = 1, topics = { { id = 9, title = "错撩" } } } }), nil, nil)
elseif url:find("/v2/pweb/home", 1, true) then
callback(Json.encode({ code = 200, data = { popularity_topics = { { id = 3, title = "榜上" } } } }), nil, nil)
elseif url:find("/web/topic/", 1, true) then
callback(html, nil, nil)
elseif url:find("/v1/aegis/", 1, true) then
callback("ok", nil, { headers = { ["set-cookie"] = "kk_s_t=1793924589213; Path=/" } })
elseif url:find("/v2/comments/comic/", 1, true) then
callback(Json.encode({
code = 200,
data = {
total = 80,
comments = {
{ replied_comment_id = 0, content = "好看", likes_count = 3, created_at_info = "2020-01-02 12:00", user = { nickname = "甲" } },
{ replied_comment_id = 9, content = "回复", user = { nickname = "乙" } },
},
},
}), nil, nil)
elseif url:find("/v2/pweb/comic/", 1, true) then
callback(Json.encode({ code = 200, data = { comic_info = { comic_images = { { url = "https://img/1.jpg" } } } } }), nil, nil)
else
callback(nil, "miss", nil)
end
return { cancel = function() end }
end,
}
end
package.loaded["http.request"] = nil
package.loaded["moonsource_kuaikan.client"] = nil
Client = require("moonsource_kuaikan.client")
local books
Client.searchAsync("错撩", function(list) books = list end)
Assert.eq(books[1].title, "错撩")
Assert.is_true(requests[#requests]:find("q=", 1, true) ~= nil)
Assert.is_nil(options[#options].headers.Cookie)
Assert.matches(options[#options].headers["User-Agent-PC"], "PCKuaikan/")
local ranked
Client.homeAsync(function(list) ranked = list end)
Assert.eq(ranked[1].stable_id, "3")
local fav_books
Client.favAsync(function(list) fav_books = list end)
Assert.eq(fav_books[1].title, "错撩")
Assert.is_true(requests[#requests]:find("/v2/pweb/fav/topics?since=0&limit=20", 1, true) ~= nil)
Assert.eq(options[#options].headers.Cookie, "session=saved")
Assert.eq(options[#options].cache_ttl, 0)
local loaded
Client.topicAsync("9", function(value) loaded = value end)
Assert.eq(#loaded.chapters, 2)
Assert.is_nil(options[#options].headers.Cookie)
local images
cfg.cookie = "session=saved; kk_s_t=stale"
Client.imagesAsync("9", function(list) images = list end)
Assert.eq(images[1], "https://img/1.jpg")
Assert.is_true(requests[#requests]:find("answer=", 1, true) ~= nil)
Assert.eq(options[#options].headers.Cookie, "session=saved; kk_s_t=1793924589213")
Assert.eq(options[#options].cache_ttl, 0)
Assert.eq(options[#options - 1].cache_ttl, 0)
Assert.is_nil(options[#options - 1].headers.Cookie)
Assert.eq(options[#options].headers.width, "564")
Assert.matches(options[#options].headers.Referer, "/webs/comic%-next/9")
local reviews, total = Mapper.comments({
code = 200,
data = {
total = 1,
comments = { { replied_comment_id = 0, content = "好看", user = { nickname = "甲" }, created_at_info = "2020-01-02 12:00", likes_count = 3 } },
},
})
Assert.eq(#reviews, 1)
Assert.eq(reviews[1].author, "甲")
Assert.eq(reviews[1].time, "2020-01-02")
Assert.eq(reviews[1].likes, 3)
Assert.eq(total, 1)
Assert.is_nil(Mapper.comments({ code = 200, data = {} }))
Assert.is_nil(Mapper.comments({ code = 200, data = { total = 1, comments = { {} } } }))
Assert.is_nil(Mapper.images({ code = 200, data = { comic_info = {
comic_images = { { url = "https://img/1.jpg" }, {} },
} } }))
local loaded_reviews, review_err, pages
Client.commentsAsync("9", function(items, err, count) loaded_reviews, review_err, pages = items, err, count end)
Assert.is_nil(review_err)
Assert.eq(#loaded_reviews, 1)
Assert.eq(loaded_reviews[1].text, "好看")
Assert.eq(pages, 2)
Assert.eq(requests[#requests]:find("/v2/comments/comic/42/order/score?offset=0&limit=50&total=true", 1, true) ~= nil, true)
Assert.is_nil(options[#options].headers.Cookie)
Client.commentPageAsync("42", 50, function(items) loaded_reviews = items end)
Assert.eq(#loaded_reviews, 1)
Assert.matches(requests[#requests], "offset=50")
local pending, cancelled = nil, {}
local Request = require("http.request")
Request.get = function(url, request_options, callback)
if url:find("/v1/aegis/", 1, true) then
callback("ok", nil, { headers = { ["set-cookie"] = "kk_s_t=test; Path=/" } })
return { cancel = function() cancelled.challenge = true end }
end
pending = callback
return { cancel = function() cancelled.content = true end }
end
local called = false
local handle = Client.imagesAsync("42", function() called = true end)
handle.cancel()
Assert.is_true(cancelled.content)
Assert.is_nil(cancelled.challenge)
pending(Json.encode({ code = 200, data = { comic_info = { comic_images = { { url = "https://img/1.jpg" } } } } }))
Assert.is_false(called)
Request.get = function(url, request_options, callback)
if url:find("/web/topic/", 1, true) then
callback(html)
return { cancel = function() cancelled.topic = true end }
end
pending = callback
return { cancel = function() cancelled.comments = true end }
end
handle = Client.commentsAsync("9", function() called = true end)
handle.cancel()
Assert.is_true(cancelled.comments)
Assert.is_nil(cancelled.topic)
pending(Json.encode({ code = 200, data = { total = 0, comments = {} } }))
Assert.is_false(called)
for _idx, response in ipairs({
{ raw = "not-json" }, { raw = Json.encode({ code = 400 }) }, { err = "network failure" },
}) do
Request.get = function(_url, _options, callback)
callback(response.raw, response.err)
return { cancel = function() end }
end
local offset_queries = {}
Request.get = function(url, request_options, callback)
offset_queries[#offset_queries + 1] = url:match("since=(%d+)")
Assert.eq(request_options.headers.Cookie, "session=fixed")
Assert.eq(request_options.cache_ttl, 0)
local offset = tonumber(offset_queries[#offset_queries])
local rows = offset == 0 and { { id = 1, title = "甲" }, { id = 2, title = "乙" } }
or { { id = 2, title = "乙" }, { id = 3, title = "丙" } }
callback(Json.encode({ code = 200, data = { total = 4, topics = rows } }))
return { cancel = function() end }
end
Client.favAsync(function(list, err)
Assert.is_nil(err)
Assert.len(list, 3)
Assert.eq(list[3].stable_id, "3")
end, "session=fixed")
Assert.eq(table.concat(offset_queries, ","), "0,2")
for _idx, failure in ipairs({
{ raw = "bad-json" }, { err = "offline" },
{ raw = Json.encode({ code = 200, data = { total = 4, topics = {} } }) },
{ raw = Json.encode({ code = 200, data = { total = 4, topics = { { id = 1, title = "甲" }, { id = 2, title = "乙" } } } }) },
}) do
Request.get = function(url, _options, callback)
if url:find("since=0", 1, true) then
callback(Json.encode({ code = 200, data = { total = 4, topics = {
{ id = 1, title = "甲" }, { id = 2, title = "乙" },
} } }))
else
callback(failure.raw, failure.err)
end
return { cancel = function() end }
end
Client.favAsync(function(list, err)
Assert.is_nil(list, "中间页失败不能发布半个书架")
Assert.is_true(type(err) == "string" and err ~= "")
end)
end
local shelf_cancelled
Request.get = function(url, _options, callback)
if url:find("since=0", 1, true) then
callback(Json.encode({ code = 200, data = { total = 2, topics = { { id = 1, title = "甲" } } } }))
return { cancel = function() error("不能取消已结束的首页") end }
end
pending = callback
return { cancel = function() shelf_cancelled = true end }
end
called = false
handle = Client.favAsync(function() called = true end)
handle.cancel()
Assert.is_true(shelf_cancelled)
pending(Json.encode({ code = 200, data = { total = 2, topics = { { id = 2, title = "乙" } } } }))
Assert.is_false(called)
Client.commentPageAsync("42", 0, function(items, err)
Assert.is_nil(items)
Assert.is_true(type(err) == "string" and err ~= "")
end)
end
+245
View File
@@ -0,0 +1,245 @@
--[[--
快看登录:官方账号校验、取消、旧账号迁移和受限微信回调。
@module tests.moonsource_kuaikan.login_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch, inject-field
local Assert = require("support.assert")
local JSON = require("support.json_stub")
local Text = require("utils.text")
package.loaded["json"] = JSON
local cfg, requests, saves = {}, {}, 0
local cleared = 0
package.loaded["source.logout"] = { clear = function(_id, clear)
clear(); cleared = cleared + 1; return true
end }
package.loaded["utils.settings"] = {
getSource = function() return cfg end,
saveSource = function() saves = saves + 1 end,
}
package.loaded["source.auth"] = { ok = function() end }
local Request = {
header = function(res, key) return res and res.headers and res.headers[key] end,
headerAll = function(res, key) return res and res.headers and res.headers[key] or {} end,
get = function(url, opts, cb)
local request = { url = url, opts = opts, cb = cb }
requests[#requests + 1] = request
return { cancel = function() request.cancelled = true end }
end,
}
package.loaded["http.request"] = Request
local Client = require("moonsource_kuaikan.client")
local Mapper = require("moonsource_kuaikan.mapper")
local Login = require("moonsource_kuaikan.login")
local function account(id, authenticate)
return JSON.encode({ code = 200, data = { user_info = { user_id = id, authenticate = authenticate or 1 } } })
end
local value, reason
local function answer(result, err) value, reason = result, err end
local function cookie(text)
local session = Login.new()
session:cookieAsync(text, answer)
return session, requests[#requests]
end
local session, request = cookie("Cookie: sid=first")
Assert.eq(request.url, Client.ACCOUNT_URL)
Assert.eq(request.opts.headers.Cookie, "sid=first")
Assert.eq(request.opts.cache_ttl, 0)
Assert.is_nil(request.url:find("sid", 1, true))
Assert.is_nil(cfg.cookie)
request.cb(account(7))
Assert.eq(value.user_id, "7")
Assert.eq(cfg.cookie, "sid=first")
Assert.is_true(cfg.logged_in)
Assert.eq(saves, 1)
for _idx, response in ipairs({
{ raw = "broken" }, { raw = account(0) }, { raw = account(7, 0) },
{ raw = JSON.encode({ code = 200, data = { user_info = {} } }) },
{ raw = account("7.1") }, { raw = JSON.encode({ code = 500 }) }, { err = "offline" },
}) do
session, request = cookie("sid=invalid")
request.cb(response.raw, response.err)
Assert.is_nil(value)
Assert.is_true(type(reason) == "string")
Assert.eq(cfg.cookie, "sid=first")
end
session, request = cookie("sid=other")
request.cb(account(8))
Assert.is_nil(reason)
Assert.eq(cfg.user_id, "8")
Assert.eq(cleared, 1)
local calls = 0
session = Login.new()
session:cookieAsync("sid=cancelled", function() calls = calls + 1 end)
request = requests[#requests]
session:cancel()
Assert.is_true(request.cancelled)
request.cb(account(7))
Assert.eq(calls, 0)
Assert.eq(cfg.cookie, "sid=other")
local _old, late = cookie("sid=old")
session, request = cookie("sid=latest")
request.cb(account(7))
late.cb(account(7))
Assert.eq(cfg.cookie, "sid=latest")
Assert.eq(reason, "登录状态已变化,请重试")
session, request = cookie("sid=after-logout")
cfg.cookie, cfg.user_id, cfg.logged_in = nil, nil, nil
Client.login_revision = Client.login_revision + 1
request.cb(account(7))
Assert.is_nil(cfg.cookie)
cfg = { cookie = "sid=legacy" }
session, request = cookie("sid=renewed")
local before = #requests
request.cb(account(7))
Assert.eq(#requests, before, "不再查询旧 Cookie")
Assert.eq(cfg.cookie, "sid=renewed")
Assert.eq(cfg.user_id, "7")
cfg = { cookie = "sid=legacy-other" }
session, request = cookie("sid=new")
request.cb(account(8))
Assert.eq(cfg.cookie, "sid=new")
Assert.eq(cfg.user_id, "8")
Assert.is_nil(reason)
cfg = { cookie = "sid=legacy-offline" }
session, request = cookie("sid=new")
request.cb(nil, "network")
Assert.eq(reason, "network")
Assert.eq(cfg.cookie, "sid=legacy-offline")
cfg = { cookie = "sid=legacy-expired" }
session, request = cookie("sid=new")
request.cb(account(8))
Assert.eq(cfg.user_id, "8")
Assert.eq(cfg.cookie, "sid=new", "旧账号失效不妨碍新账号登录")
Assert.is_nil(reason)
local redirect = "https://open.weixin.qq.com/connect/qrconnect?" .. Text.formEncode({
appid = "wx92ba65b18ed55877", scope = "snsapi_login", response_type = "code",
redirect_uri = Mapper.WECHAT_CALLBACK, state = "opaque+state",
})
Assert.eq(Mapper.qrLocation(redirect).state, "opaque+state")
Assert.is_nil(Mapper.qrLocation(redirect:gsub("wx92ba65b18ed55877", "wrong")))
Assert.is_nil(Mapper.qrLocation(redirect:gsub("open.weixin.qq.com", "evil.test")))
Assert.is_nil(Mapper.qrLocation(redirect .. "&state=another"))
Assert.eq(Mapper.qrStatus("window.wx_errcode=408; window.wx_code='';"), 408)
Assert.eq(Mapper.qrStatus(JSON.encode({ wx_errcode = 404 })), 404)
Assert.eq(select(2, Mapper.qrStatus(JSON.encode({ wx_errcode = 405, wx_code = "confirmed" }))), "confirmed")
Assert.is_nil(Mapper.qrStatus(JSON.encode({ wx_errcode = 405 })))
cfg = {}
session = Login.new()
local uuid
session:qrCreateAsync(function(id, err) uuid, reason = id, err end)
request = requests[#requests]
Assert.is_nil(request.opts.headers.Cookie)
request.cb(nil, "HTTP 302", { code = 302, headers = {
Location = redirect,
["Set-Cookie"] = { "nonce=anonymous; Domain=.kuaikanmanhua.com; Path=/",
"scoped=callback; Path=/v1/passport", "nested=api; PATH=/v2/",
"evil=blocked; Domain=evil.test; Path=/" },
} })
request = requests[#requests]
Assert.eq(request.url, redirect)
Assert.is_nil(request.opts.headers.Cookie)
Assert.eq(request.opts.cache_ttl, 0)
request.cb('<img src="/connect/qrcode/test-uuid">')
Assert.eq(uuid, "test-uuid")
session:qrPollAsync(uuid, nil, function(status) value = status end)
request = requests[#requests]
Assert.is_nil(request.opts.headers.Cookie)
request.cb("window.wx_errcode=408;")
Assert.eq(value, 408)
session:exchangeAsync("confirmed", answer)
request = requests[#requests]
Assert.matches(request.url, "^https://www%.kuaikanmanhua%.com/v1/passport/login/pc/user_wechat_login_check%?")
Assert.matches(request.url, "state=opaque%%2Bstate")
Assert.eq(request.opts.headers.Cookie, "nonce=anonymous; scoped=callback")
request.cb(nil, "HTTP 302", { code = 302, headers = {
Location = "/webs/loginh",
["Set-Cookie"] = { "sid=authorized; Domain=.kuaikanmanhua.com; Path=/",
"nonce=; Path=/; Max-Age=0" },
} })
request = requests[#requests]
Assert.eq(request.opts.headers.Cookie, "sid=authorized")
request.cb("<html>callback complete</html>")
Assert.eq(requests[#requests].opts.headers.Cookie, "nested=api; sid=authorized")
requests[#requests].cb(account(7))
Assert.eq(value.user_id, "7")
Assert.eq(cfg.cookie, "nested=api; sid=authorized")
Assert.is_nil(cfg.cookie:find("evil", 1, true))
Assert.is_nil(cfg.cookie:find("scoped", 1, true))
cfg = {}
session = Login.new()
session.state = "test"
session:exchangeAsync("code", answer)
request = requests[#requests]
local count = #requests
request.cb(nil, "HTTP 302", { code = 302, headers = { Location = "https://evil.test/" } })
Assert.eq(#requests, count)
Assert.eq(reason, "登录响应无效")
Assert.is_nil(cfg.cookie)
local original_get = Request.get
Request.get = function(url, opts, cb)
if url:find("/user_wechat_login?", 1, true) then
cb(nil, "HTTP 302", { code = 302, headers = { Location = redirect } })
return { cancel = function() error("cancelled completed initialization") end }
end
return original_get(url, opts, cb)
end
session = Login.new()
session:qrCreateAsync(function() calls = calls + 1 end)
request = requests[#requests]
session:cancel()
Assert.is_true(request.cancelled)
request.cb('<img src="/connect/qrcode/late">')
Assert.eq(calls, 0)
local expired
value, reason, expired = Client.accountResponse(nil, "HTTP 302", { code = 302, headers = { Location = "/webs/loginh?redirect=x" } })
Assert.is_true(expired)
value, reason, expired = Client.accountResponse(nil, "HTTP 302", { code = 302, headers = { Location = "/webs/loginhacker" } })
Assert.is_nil(expired)
Request.get = original_get
local expired_calls, image_calls = 0, 0
package.loaded["source.auth"] = {
ok = function() end,
expire = function() expired_calls = expired_calls + 1 end,
}
local function locked()
cfg = { cookie = "sid=reader", user_id = "7", logged_in = true }
local handle = Client.imagesAsync("locked", function(_urls, err) image_calls = image_calls + 1; reason = err end)
requests[#requests].cb("ok", nil, { headers = { ["set-cookie"] = { "kk_s_t=challenge; Path=/" } } })
requests[#requests].cb(JSON.encode({ code = 200, data = { comic_info = { locked = true } } }))
Assert.eq(requests[#requests].opts.headers.Cookie, "sid=reader")
return handle, requests[#requests]
end
local handle
handle, request = locked()
request.cb(account(7))
Assert.eq(reason, "本章未购买")
Assert.eq(expired_calls, 0)
handle, request = locked()
request.cb(account(0, 0))
Assert.eq(expired_calls, 1)
Assert.eq(reason, "快看登录已失效,请重新登录")
handle, request = locked()
cfg.cookie, cfg.user_id = "sid=new-account", "8"
request.cb(account(0, 0))
Assert.eq(expired_calls, 1)
Assert.eq(reason, "登录状态已变化,请重试")
handle, request = locked()
local before_calls = image_calls
handle.cancel()
Assert.is_true(request.cancelled)
request.cb(account(0, 0))
Assert.eq(image_calls, before_calls)
Assert.eq(expired_calls, 1)
+128
View File
@@ -0,0 +1,128 @@
--[[--
快看密码加密与短信登录会话:实际 Web 字段、错误、冷却、账号确认及阶段取消。
@module tests.moonsource_kuaikan.mobile_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch, inject-field
local Assert = require("support.assert")
local JSON = require("support.json_stub")
local Text = require("utils.text")
package.loaded["json"] = JSON
local cfg, requests, saves = { cookie = "sid=old", user_id = "7" }, {}, 0
package.loaded["utils.settings"] = {
getSource = function() return cfg end, saveSource = function() saves = saves + 1 end,
}
package.loaded["source.auth"] = { ok = function() end }
local Request = {
header = function() end,
headerAll = function(res) return res and res.cookies or {} end,
}
local function record(url, body, opts, cb)
local fields = {}
for key, value in (body or ""):gmatch("([^&=]+)=([^&]*)") do fields[Text.urlDecode(key)] = Text.urlDecode(value) end
local r = { url = url, body = body, fields = fields, opts = opts, cb = cb }
requests[#requests + 1] = r
return { cancel = function() r.cancelled = true end }
end
Request.get = function(url, opts, cb) return record(url, nil, opts, cb) end
Request.post = record
package.loaded["http.request"] = Request
local Mapper = require("moonsource_kuaikan.mapper")
local Client = require("moonsource_kuaikan.client")
local Login = require("moonsource_kuaikan.login")
local phone, proof = "+86-13800000000", { ticket = "captcha-proof", random = "random-proof" }
Assert.eq(Mapper.phone(" +86 ", "13800000000 "), phone)
Assert.eq(Mapper.phone("+852", "12345678"), "+852-12345678")
Assert.is_nil(Mapper.phone("+86", "12345678"))
Assert.is_nil(Mapper.phone("86", "13800000000"))
Assert.is_nil(Mapper.phone("+1", "12"))
local fields = Mapper.passwordFields(phone, " pass测试 😀 ", proof)
Assert.eq(fields.phone, "YhyUbUo+Y1hLLsQUeDEwwg==")
Assert.eq(fields.password, "DNsZnApMIYKSb60EXagwMryIBWUDl2peUULxGpgYDOQ=")
Assert.eq(fields.verify_provider, "tencent")
local good = JSON.encode({ code = 200 })
local account = JSON.encode({ code = 200, data = { user_info = { authenticate = 1, user_id = 7 } } })
local value, reason
local function answer(v, err) value, reason = v, err end
local session = Login.new()
session:passwordAsync(phone, " pass测试 😀 ", proof, answer)
local r = requests[#requests]
Assert.matches(r.url, "/v2/passport/pc/v2/mobile_pwd_login_encrypted$")
Assert.eq(r.opts.content_type, "application/x-www-form-urlencoded")
Assert.eq(r.opts.cache_ttl, 0)
Assert.is_nil(r.opts.headers.Cookie)
Assert.is_nil(r.body:find(phone, 1, true))
Assert.is_nil(r.body:find(Text.urlEncode(" pass测试 😀 "), 1, true))
Assert.eq(r.fields.password, fields.password)
r.cb(good, nil, { cookies = { "sid=new; Path=/" } })
Assert.eq(requests[#requests].url, Client.ACCOUNT_URL)
Assert.eq(cfg.cookie, "sid=old")
requests[#requests].cb(account)
Assert.eq(value.user_id, "7")
Assert.eq(cfg.cookie, "sid=new")
Assert.eq(saves, 1)
Assert.is_nil(cfg.password)
session = Login.new()
session:passwordAsync(phone, "bad", proof, answer)
r = requests[#requests]
r.cb(JSON.encode({ code = 400, message = "password refused" }))
Assert.is_nil(value)
Assert.eq(reason, "password refused")
Assert.eq(cfg.cookie, "sid=new")
for _idx, response in ipairs({ "broken", "[]", "{}", '{"code":200}' }) do
session:passwordAsync(phone, "test", proof, answer)
r = requests[#requests]
r.cb(response)
if response == '{"code":200}' then requests[#requests].cb(nil, "offline") end
Assert.is_nil(value)
Assert.is_true(type(reason) == "string")
Assert.eq(saves, 1)
end
cfg = {}
session = Login.new()
session:sendCodeAsync(phone, proof, answer)
r = requests[#requests]
Assert.matches(r.url, "/v2/passport/pc/v2/get_sms_code$")
Assert.eq(r.fields.phone, phone)
Assert.eq(r.fields.random, "random-proof")
r.cb(JSON.encode({ code = 400, message = "SMS refused" }))
Assert.is_nil(session.sms_phone)
Assert.eq(reason, "SMS refused")
session:sendCodeAsync(phone, proof, answer)
requests[#requests].cb(good, nil, { cookies = { "nonce=anonymous; Path=/" } })
Assert.is_true(value)
Assert.eq(session.sms_phone, phone)
local count = #requests
session:sendCodeAsync(phone, proof, answer)
Assert.eq(#requests, count)
Assert.eq(reason, "请稍后再获取验证码")
session:codeAsync("+86-13900000000", "123456", answer)
Assert.eq(#requests, count)
session:codeAsync(phone, "invalid", answer)
Assert.eq(#requests, count)
session:codeAsync(phone, "123456", answer)
r = requests[#requests]
Assert.matches(r.url, "/v2/passport/pc/mobile_code_login$")
Assert.eq(r.fields.code, "123456")
Assert.eq(r.opts.headers.Cookie, "nonce=anonymous")
r.cb(good, nil, { cookies = { "sid=sms; Path=/" } })
requests[#requests].cb(account)
Assert.eq(cfg.cookie, "nonce=anonymous; sid=sms")
Assert.is_nil(cfg.code)
local get = Request.get
Request.post = function(url, body, opts, cb)
cb(good, nil, { cookies = { "sid=sync; Path=/" } })
return { cancel = function() error("completed POST must not overwrite account request") end }
end
session = Login.new()
session:passwordAsync(phone, "test", proof, answer)
r = requests[#requests]
session:cancel()
Assert.is_true(r.cancelled)
r.cb(account)
Assert.eq(cfg.cookie, "nonce=anonymous; sid=sms")
Request.get = get
+69
View File
@@ -0,0 +1,69 @@
--[[--
快看源操作:命中旧缓存可离线开书,同步目录桩后取消仍指向章节任务。
@module tests.moonsource_kuaikan.operations_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch, inject-field
local Assert = require("support.assert")
local Stubs = require("support.stubs")
local Themed = require("support.theme_stubs")
Themed.install()
local toc = { { idx = 1, uid = "1", toc_version = 1 }, { idx = 2, uid = "2" } }
local connected, cached, touched = true, false, nil
package.loaded["source.toc"] = { read = function() return toc end }
package.loaded["ui/network/manager"] = { isConnected = function() return connected end }
package.loaded["book.progress_db"] = { get = function() return { chapter_idx = 2 } end }
package.loaded["book.store"] = {
touch = function(path, _identity, meta) touched = { path, meta.chapter_idx }; return true end,
}
local pending, cancelled = nil, {}
package.loaded["moonsource_kuaikan.chapter"] = {
existing = function(_identity, chapter) return cached and "/" .. chapter.uid .. ".cbz" or nil end,
materializeAsync = function(_identity, _chapter, _progress, cb)
pending = cb
return { cancel = function() cancelled.chapter = true end }
end,
prefetchAsync = function(_identity, _toc, from, count, _opts, cb)
Assert.eq(from, 0)
Assert.eq(count, 2)
pending = cb
return { cancel = function() cancelled.cache = true end }
end,
}
local source = require("moonsource_kuaikan.source").new()
source.loadTocAsync = function(_self, _identity, cb)
cb(toc)
return { cancel = function() cancelled.toc = true end }
end
local identity = { source_id = "ext.kuaikan", stable_id = "book" }
local called = false
local handle = source:openBookAsync(identity, nil, function() called = true end)
Stubs.flush()
handle.cancel()
Assert.is_true(cancelled.chapter)
Assert.is_nil(cancelled.toc)
Assert.is_true(Themed.last("progress_dialog").closed)
pending("/1.cbz")
Assert.is_false(called)
Assert.is_nil(touched)
handle = source:cacheAllChaptersAsync(identity, nil, function() called = true end)
handle.cancel()
Assert.is_true(cancelled.cache)
Assert.is_nil(cancelled.toc)
pending(2, 2, 0)
Assert.is_false(called)
connected, cached = false, true
local opened
source:openBookAsync(identity, nil, function(path) opened = path end)
Stubs.flush()
Assert.eq(opened, "/2.cbz")
Assert.eq(touched[2], 2)
cached = false
source:openBookAsync(identity, nil, function(path, err)
Assert.is_nil(path)
Assert.eq(err, "网络不可用,请先连接 Wi-Fi")
end)
Stubs.flush()
+109
View File
@@ -0,0 +1,109 @@
--[[--
快看手机号输入:官方格式、协议确认、密码原值、短信候选会话和取消。
@module tests.moonsource_kuaikan.phone_login_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch, inject-field
local Assert = require("support.assert")
local Themed = require("support.theme_stubs")
Themed.install()
local connected, cancelled, proof_submit, proof_done, proof_session = true, 0, nil, nil, nil
package.loaded["ui/network/manager"] = { isConnected = function() return connected end }
local sessions = {}
package.loaded["moonsource_kuaikan.login"] = {
new = function()
local session = {}
function session:cancel() cancelled = cancelled + 1 end
function session:passwordAsync(phone, password, proof, cb)
self.phone, self.password, self.proof, self.pending = phone, password, proof, cb
end
function session:sendCodeAsync(phone, proof, cb)
self.phone, self.proof, self.pending = phone, proof, cb
end
function session:codeAsync(phone, code, cb)
self.phone, self.code, self.pending = phone, code, cb
end
sessions[#sessions + 1] = session
return session
end,
}
package.loaded["moonsource_kuaikan.verify"] = {
new = function(session, submit, cb)
proof_session, proof_submit, proof_done = session, submit, cb
return { cancel = function() cancelled = cancelled + 1 end }
end,
}
local Phone = require("moonsource_kuaikan.phone_login")
local logged = 0
local function on_user() logged = logged + 1 end
local window = Phone.new("password", on_user)
window:start()
local input = Themed.last("input")
Assert.eq(input.title, "快看密码登录")
Assert.eq(input.fields[3].text_type, "password")
input.callback("+86", "13800000000", "")
Assert.eq(Themed.last("toast").text, "请输入密码")
input.callback("+86", "13800000000", " pass测试 ")
Assert.matches(Themed.last("confirm").text, "https://www%.kuaikanmanhua%.com/webs/agreement")
Themed.last("confirm").ok_callback()
Assert.is_true(input.closed)
Assert.eq(proof_session, window.session)
Assert.is_true(window.busy)
proof_submit({ ticket = "proof", random = "random" }, function() end)
Assert.eq(window.session.password, " pass测试 ")
Assert.eq(window.session.phone, "+86-13800000000")
proof_done(nil, "password refused")
Assert.eq(Themed.last("toast").text, "password refused")
Assert.is_nil(Themed.last("input").fields[3].text)
Assert.is_false(window.busy)
Themed.last("input").callback("+86", "13800000000", "new")
window:cancel()
proof_done({ user_id = "7" })
Assert.eq(logged, 0)
window = Phone.new("sms", on_user)
window:start()
input = Themed.last("input")
Assert.eq(input.title, "快看短信登录")
input.callback("+86", "13800000000", "123456")
Assert.matches(Themed.last("toast").text, "请先获取")
connected = false
input.actions[1].callback("+86", "13800000000")
Assert.eq(Themed.last("toast").text, "网络不可用,请先连接 Wi-Fi")
connected = true
input.actions[1].callback("+86", "123")
Assert.eq(Themed.last("toast").text, "请输入有效的手机号和国际区号")
input.actions[1].callback("+86", "13800000000")
Themed.last("confirm").ok_callback()
proof_submit({ ticket = "proof", random = "random" }, function() end)
Assert.eq(window.session.phone, "+86-13800000000")
window.session.sms_phone, window.session.sms_retry_at = "+86-13800000000", os.time() + 60
proof_done(true)
Assert.eq(Themed.last("toast").text, "验证码已发送")
input = Themed.last("input")
Assert.eq(input.fields[2].text, "13800000000")
input.actions[1].callback("+86", "13800000000")
Assert.eq(Themed.last("toast").text, "请稍后再获取验证码")
input.callback("+86", "13900000000", "123456")
Assert.matches(Themed.last("toast").text, "请先获取")
input.callback("+86", "13800000000", " 123456 ")
Assert.eq(window.session.code, "123456")
Assert.is_true(window.busy)
window.session.pending({ user_id = "7" })
Assert.eq(logged, 1)
Assert.is_true(input.closed)
Assert.is_true(cancelled > 0)
window = Phone.new("sms", on_user)
window:start()
window.session.sms_phone = "+86-13800000000"
input = Themed.last("input")
input.callback("+86", "13800000000", "123456")
local pending = window.session.pending
input:close()
pending({ user_id = "7" })
Assert.eq(logged, 1)
Assert.is_nil(window.dialog)
Assert.is_false(window.busy)
input.actions[1].callback("+86", "13800000000")
Assert.is_nil(window.verification)
+88
View File
@@ -0,0 +1,88 @@
--[[--
快看扫码窗口:已扫码、确认、拒绝、超时、刷新和关闭。
@module tests.moonsource_kuaikan.qrlogin_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch, inject-field
local Assert = require("support.assert")
local Stubs = require("support.stubs")
local Themed = require("support.theme_stubs")
Themed.install()
local sessions, connected = {}, true
package.loaded["ui/network/manager"] = { isConnected = function() return connected end }
package.loaded["moonsource_kuaikan.login"] = {
new = function()
local session = { cancels = 0, polls = 0 }
function session:cancel() self.cancels = self.cancels + 1 end
function session:qrCreateAsync(cb) self.created = cb end
function session:qrPollAsync(_uuid, _last, cb) self.polls = self.polls + 1; self.polled = cb end
function session:exchangeAsync(code, cb) self.code, self.exchanged = code, cb end
sessions[#sessions + 1] = session
return session
end,
}
local QR = require("moonsource_kuaikan.qrlogin")
local logged = 0
local window = QR.new(function() logged = logged + 1 end)
window:start()
local session = sessions[#sessions]
Assert.is_true(Themed.last("progress_dialog").shown)
session.created("uuid")
local dialog = Themed.last("qr")
Assert.eq(dialog.caption, "用微信扫一扫")
session.polled(404)
Assert.eq(Themed.last("toast").text, "已扫码,请在手机上确认")
Stubs.flush()
session.polled(405, "confirmed")
Assert.eq(session.code, "confirmed")
session.exchanged({ user_id = "7" })
Assert.eq(logged, 1)
Assert.is_true(dialog.closed)
Assert.is_nil(window.poll)
window:start()
session = sessions[#sessions]
window:cancel()
session.created("late")
Assert.is_nil(window.dialog)
Assert.eq(session.polls, 0)
window:start()
session = sessions[#sessions]
session.created("uuid")
dialog = Themed.last("qr")
dialog:close()
session.polled(405, "late")
Assert.is_nil(session.exchanged)
Assert.eq(logged, 1)
window:start()
session = sessions[#sessions]
session.created("uuid")
Themed.last("qr").actions[1].callback()
local refreshed = sessions[#sessions]
Assert.is_true(refreshed ~= session)
session.polled(405, "old")
Assert.is_nil(session.exchanged)
refreshed.created("new")
refreshed.polled(403)
Assert.eq(Themed.last("confirm").text, "已在微信中拒绝登录")
window:start()
session = sessions[#sessions]
session.created("uuid")
window.deadline = os.time() - 1
session.polled(408)
Stubs.flush()
Assert.eq(Themed.last("confirm").text, "二维码已过期")
window:start()
session = sessions[#sessions]
session.created("uuid")
connected = false
session.polled(408)
Stubs.flush()
Assert.eq(Themed.last("confirm").text, "网络不可用,请先连接 Wi-Fi")
local count = #sessions
window:start()
Assert.eq(#sessions, count)
Assert.eq(Themed.last("toast").text, "网络不可用,请先连接 Wi-Fi")
+72
View File
@@ -0,0 +1,72 @@
--[[-- 快看每话章评:原始行游标、章节隔离、离线与取消。 @module tests.moonsource_kuaikan.reviews_spec --]]
local Assert = require("support.assert")
local Stubs = require("support.stubs")
local JSON = require("support.json_stub")
package.loaded.json = JSON
local connected, requests, pending = true, {}, nil
package.loaded["ui/network/manager"] = { isConnected = function() return connected end }
---@type {code: integer, data: {total: integer, comments: {id: integer|string|table, content: string, replied_comment_id: integer, user?: table}[]}}
local result = { code = 200, data = { total = 4, comments = {
{ id = 1, content = "First", replied_comment_id = 0, user = { nickname = "Reader" } },
{ id = 2, content = "Reply", replied_comment_id = 1 },
{ id = 3, content = "Second", replied_comment_id = 0 },
} } }
package.loaded["http.request"] = {
get = function(url, opts, cb)
local request = { url = url, opts = opts }
requests[#requests + 1] = request
if pending then pending.cb, pending.request = cb, request
elseif url:find("offset=3", 1, true) then
cb(JSON.encode({ code = 200, data = { total = 4, comments = {
{ id = 4, content = "Last", replied_comment_id = 0 },
} } }))
else cb(JSON.encode(result)) end
return { cancel = function() request.cancelled = true end }
end,
}
local source = require("moonsource_kuaikan.source").new()
function source:loadTocAsync(_identity, cb)
cb({ { uid = "11", idx = 1, title = "One" }, { uid = "22", idx = 2, title = "Two" } })
return { cancel = function() end }
end
local identity = { source_id = "ext.kuaikan", stable_id = "review-test", chapter_idx = 1 }
local page, err
source:paragraphReviewPageAsync(identity, "chapter", 0, function(value, reason) page, err = value, reason end)
Assert.is_nil(err)
Assert.len(page.items, 2)
Assert.eq(page.items[1].id, "1")
Assert.eq(page.items[1].content, "First")
Assert.eq(page.max_idx, 3, "游标按原始三行推进,不按两个主楼推进")
Assert.is_true(page.more)
Assert.matches(requests[1].url, "/comic/11/")
Assert.is_nil(requests[1].opts.headers.Cookie)
source:paragraphReviewPageAsync(identity, "chapter", page.max_idx, function(value, reason) page, err = value, reason end)
Assert.is_nil(err)
Assert.eq(page.items[1].id, "4")
Assert.eq(page.max_idx, 4)
Assert.is_false(page.more)
connected = false
source:paragraphReviewPageAsync(identity, "chapter", 0, function(value, reason) page, err = value, reason end)
Stubs.flush()
Assert.is_nil(err)
Assert.len(page.items, 2)
identity.chapter_idx = 2
source:paragraphReviewPageAsync(identity, "chapter", 0, function(value, reason) page, err = value, reason end)
Stubs.flush()
Assert.is_nil(page)
Assert.eq(err, "未联网,无法加载段评")
connected, pending = true, {}
local called = false
local job = source:paragraphReviewPageAsync(identity, "chapter", 0, function() called = true end)
Assert.matches(pending.request.url, "/comic/22/")
job.cancel()
Assert.is_true(pending.request.cancelled)
pending.cb(JSON.encode(result))
Assert.is_false(called)
pending = nil
for _idx, invalid_id in ipairs({ {}, "" }) do
result.data.comments[1].id = invalid_id
source:paragraphReviewPageAsync(identity, "chapter", 0, function(value, reason) page, err = value, reason end)
Assert.is_nil(page)
Assert.eq(err, "响应无效", "坏 ID 不转换为 Lua 表地址或无身份评论")
end
+91
View File
@@ -0,0 +1,91 @@
--[[--
快看账号设置、浏览器域隔离和可取消 Cookie 校验。
@module tests.moonsource_kuaikan.setting_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch, inject-field
local Assert = require("support.assert")
local JSON = require("support.json_stub")
local Themed = require("support.theme_stubs")
Themed.install()
package.loaded["json"] = JSON
local cfg, requests, reloads, expired, connected = {}, {}, 0, false, true
package.loaded["utils.settings"] = { getSource = function() return cfg end, saveSource = function() end }
package.loaded["source.auth"] = { ok = function() expired = false end, expired = function() return expired end }
package.loaded["source.registry"] = { reload = function() reloads = reloads + 1 end }
package.loaded["ui/network/manager"] = { isConnected = function() return connected end }
package.loaded["ui.themes.widgets.row"] = { widget = function(opts) return opts end }
package.loaded["http.request"] = {
get = function(url, opts, cb)
local r = { url = url, opts = opts, cb = cb }
requests[#requests + 1] = r
return { cancel = function() r.cancelled = true end }
end,
header = function() end, headerAll = function() return {} end,
}
local Setting = require("moonsource_kuaikan.setting")
local answer = JSON.encode({ code = 200, data = { user_info = { authenticate = 1, user_id = 7 } } })
local ok, reason
Assert.eq(Setting.browser.check, "https://www.kuaikanmanhua.com/v2/pweb/user_info/get")
Assert.eq(Setting.browser.check_json.path, "data.user_info.authenticate")
Setting.browser.apply({ cookies = {
{ domain = ".kuaikanmanhua.com", path = "/", name = "sid", value = "parent" },
{ domain = "www.kuaikanmanhua.com", path = "/", name = "uid", value = "web" },
{ domain = "other.kuaikanmanhua.com", name = "sid", value = "other" },
{ domain = "kuaikanmanhua.com.evil.test", name = "sid", value = "evil" },
{ domain = "www.kuaikanmanhua.com", path = "/unrelated", name = "sid", value = "wrong-path" },
} }, function(value, err) ok, reason = value, err end)
Assert.eq(requests[#requests].opts.headers.Cookie, "sid=parent; uid=web")
requests[#requests].cb(answer)
Assert.is_true(ok)
Assert.eq(reloads, 1)
Assert.is_true(Setting.browser.isAuthorized())
expired = true
Assert.is_false(Setting.browser.isAuthorized())
expired = false
local rows = Setting.rows()
Assert.eq(rows[1](400).title, "快看漫画账号")
Assert.eq(rows[1](400).status, "已登录")
Assert.eq(#rows, 7)
local refreshes = 0
local review_rows = Setting.rows({ desktop = { updateView = function() refreshes = refreshes + 1 end } })
Assert.eq(review_rows[6](400).title, "章节评论")
Assert.is_false(review_rows[6](400).status_on)
review_rows[6](400).callback()
Assert.is_true(review_rows[6](400).status_on)
Assert.eq(refreshes, 1)
Assert.eq(rows[4](400).title, "密码登录")
Assert.eq(rows[5](400).title, "短信登录")
rows[3](400).callback()
Assert.eq(Themed.last("input").title, "快看登录 Cookie")
Themed.last("input").callback("sid=cancelled")
local r = requests[#requests]
Themed.last("progress_dialog").on_cancel()
Assert.is_true(r.cancelled)
r.cb(answer)
Assert.eq(reloads, 1)
Assert.eq(cfg.cookie, "sid=parent; uid=web")
connected = false
local count = #requests
rows[3](400).callback()
Themed.last("input").callback("sid=offline")
Assert.eq(#requests, count)
Assert.eq(Themed.last("toast").text, "网络不可用,请先连接 Wi-Fi")
local opened
package.loaded["utils.extension"] = {
call = function(name, path, title)
opened = { name = name, path = path, title = title }
return { close = function() end }
end,
}
Assert.eq(rows[2](400).title, "浏览器登录")
rows[2](400).callback()
Assert.eq(opened.name, "web.open_page")
Assert.eq(opened.path, "/cookie.html")
package.loaded["utils.extension"] = nil
Assert.is_true(require("moonsource_kuaikan.client").hasAccount())
for _index, row in ipairs(rows) do Assert.is_true(row(400).title ~= "快看云端同步") end
+109
View File
@@ -0,0 +1,109 @@
--[[--
快看书架:先校验账号再拉完整快照,失败与取消不写库。
@module tests.moonsource_kuaikan.shelf_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch, inject-field
package.preload["json"] = function() return require("support.json_stub") end
local Assert = require("support.assert")
local Stubs = require("support.stubs")
local Client = require("moonsource_kuaikan.client")
local Json = require("support.json_stub")
local connected = true
local cfg = { cookie = "session=current", user_id = "7" }
package.loaded["utils.settings"] = {
getSource = function() return cfg end,
get = function() return {} end,
saveSource = function() end,
}
package.loaded["ui/network/manager"] = { isConnected = function() return connected end }
local pending, cancelled, writes, expired = nil, nil, 0, false
package.loaded["source.auth"] = {
ok = function() end,
expire = function() expired = true end,
}
package.loaded["source.shelf"] = { syncAsync = function(id, remote, _mapper, opts, cb)
Assert.eq(id, "ext.kuaikan")
Assert.is_true(opts.force)
Assert.is_true(remote.writing)
return remote:shelfSyncAsync(function(books, err)
if not books then cb(nil, err); return end
writes = writes + 1
cb({ pulled = #books, pushed = 0, hidden = 0, conflicts = 0, skipped = false })
end)
end }
Client.loginRequestAsync = function(_url, cookie, cb)
Assert.eq(cookie, "session=current")
cb(Json.encode({ code = 200, data = { user_info = { authenticate = 1, user_id = 7 } } }))
return { cancel = function() error("已结束的校验不应覆盖书架句柄") end }
end
Client.favAsync = function(cb, cookie)
Assert.eq(cookie, "session=current")
pending = cb
return { cancel = function() cancelled = true end }
end
local source = require("moonsource_kuaikan.source").new()
local result, reason
local function done(value, err) result, reason = value, err end
local handle = source:syncBooksAsync({ force = true }, done)
pending({ { stable_id = "1", title = "甲" } })
Assert.eq(result.pulled, 1)
Assert.eq(writes, 1)
result = nil
handle = source:syncBooksAsync({ force = true }, done)
handle.cancel()
Assert.is_true(cancelled)
pending({ { stable_id = "2", title = "乙" } })
Assert.is_nil(result)
Assert.eq(writes, 1)
source:syncBooksAsync({ force = true }, done)
cfg = { cookie = "session=new", user_id = "8" }
pending({ { stable_id = "2", title = "乙" } })
Assert.eq(reason, "登录状态已变化,请重试")
Assert.eq(writes, 1)
cfg = { cookie = "session=current", user_id = "7" }
source:syncBooksAsync({ force = true }, done)
pending(nil, "offline")
Assert.eq(reason, "offline")
Assert.eq(writes, 1)
Client.loginRequestAsync = function(_url, _cookie, cb)
cb(Json.encode({ code = 200, data = { user_info = { authenticate = 0 } } }))
return { cancel = function() end }
end
source:syncBooksAsync({ force = true }, done)
Assert.is_true(expired)
Assert.eq(reason, "快看登录已失效,请重新登录")
Assert.eq(writes, 1)
connected = false
source:syncBooksAsync({ force = true }, done)
Stubs.flush()
Assert.eq(reason, "网络不可用,请先连接 Wi-Fi")
cfg = {}
source:syncBooksAsync(nil, done)
Stubs.flush()
Assert.is_true(result.skipped)
Assert.eq(result.reason, "not_logged_in")
source:syncBooksAsync({ dirty_only = true }, done)
Stubs.flush()
Assert.is_true(result.skipped)
connected = true
cfg = { cookie = "session=current" }
Client.loginRequestAsync = function(_url, _cookie, cb)
cb(Json.encode({ code = 200, data = { user_info = { authenticate = 1, user_id = 7 } } }))
return { cancel = function() end }
end
local legacy = require("moonsource_kuaikan.source").new()
legacy:syncBooksAsync({ force = true }, done)
pending({ { stable_id = "3", title = "丙" } })
Assert.eq(cfg.user_id, "7")
Assert.is_true(cfg.logged_in)
Assert.is_true(legacy:capabilities().shelf_push)
Assert.is_true(type(legacy.putProgressAsync) == "function")
+241
View File
@@ -0,0 +1,241 @@
--[[--
快看上行:账号归属、收藏读回确认、进度字段及取消。
@module tests.moonsource_kuaikan.sync_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch, inject-field
local Assert = require("support.assert")
local Stubs = require("support.stubs")
local JSON = require("support.json_stub")
package.loaded["json"] = JSON
local cfg = { cookie = "session=current; kk_s_t=old", user_id = "7" }
package.loaded["utils.settings"] = {
getSource = function() return cfg end, get = function() return {} end, saveSource = function() end,
}
package.loaded["ui/network/manager"] = { isConnected = function() return true end }
package.loaded["source.auth"] = { ok = function() end, currentAccount = require("source.auth").currentAccount }
local requests = {}
local function request(method, url, body, opts, cb)
local r = { method = method, url = url, body = body, opts = opts, cb = cb }
requests[#requests + 1] = r
return { cancel = function() r.cancelled = true end }
end
package.loaded["http.request"] = {
get = function(url, opts, cb) return request("GET", url, nil, opts, cb) end,
post = function(url, body, opts, cb) return request("POST", url, body, opts, cb) end,
request = function(opts, cb) return request(opts.method, opts.url, opts.body, opts, cb) end,
header = function(res, key) return res and res.headers and res.headers[key] end,
headerAll = function(res) return res and res.headers and res.headers.cookies or {} end,
}
local Client = require("moonsource_kuaikan.client")
local Text = require("utils.text")
local account = { code = 200, data = { user_info = { authenticate = 1, user_id = 7 } } }
local function reply(data, err)
local r = requests[#requests]
local body = type(data) == "string" and data or JSON.encode(data)
local res = { code = 200, body = body, headers = { cookies = { "kk_s_t=fresh; Path=/" } } }
if r.method == "DELETE" then r.cb(res, err) else r.cb(body, err, res) end
end
local ok, reason
local function done(value, err) ok, reason = value, err end
local remote = Client.newSync(true)
remote:checkAsync(function(value, err)
if not value then done(nil, err); return end
remote:addToShelfAsync("835", done)
end)
reply(account)
Assert.is_nil(requests[#requests].opts.headers.Cookie)
reply("callback_1({})")
local write = requests[#requests]
Assert.eq(write.method, "POST")
Assert.matches(write.url, "/web/topic/835/fav%?answer=")
Assert.matches(write.opts.headers.Cookie, "session=current")
Assert.matches(write.opts.headers.Cookie, "kk_s_t=fresh")
Assert.is_nil(write.opts.headers.Cookie:find("kk_s_t=old", 1, true))
reply({ code = 200 })
reply({ code = 200, data = { total = 0, topics = {} } })
Assert.is_nil(ok)
Assert.eq(reason, "快看收藏变更尚未确认")
Assert.eq(remote.push_error, reason)
remote = Client.newSync(true)
remote:removeFromShelfAsync("835", done)
reply("callback_1({})")
Assert.eq(requests[#requests].method, "DELETE")
reply({ code = 200 })
reply({ code = 200, data = { total = 0, topics = {} } })
Assert.is_true(ok)
remote = Client.newSync(true)
remote:addToShelfAsync("835", done)
reply("callback_1({})")
local count = #requests
reply(nil, "network failed")
Assert.eq(reason, "network failed")
Assert.eq(#requests, count)
remote = Client.newSync(true)
remote:addToShelfAsync("835", done)
local late = requests[#requests]
remote:cancel()
Assert.is_true(late.cancelled)
count = #requests
late.cb("challenge", nil, { headers = { cookies = { "kk_s_t=late; Path=/" } } })
Assert.eq(#requests, count)
remote = Client.newSync(true)
remote:addToShelfAsync("835", done)
cfg = { cookie = "session=new", user_id = "8" }
reply("callback_1({})")
Assert.eq(reason, "登录状态已变化,请重试")
cfg = { cookie = "session=current" }
local module = require("moonsource_kuaikan.source")
local readonly = module.new()
Assert.is_nil(readonly.putProgressAsync)
Assert.is_false(readonly:capabilities().shelf_push)
cfg.user_id = "7"
local source = module.new()
Assert.is_true(type(source.putProgressAsync) == "function")
Assert.is_true(source:capabilities().shelf_push)
local toc = { { idx = 1, uid = "10", title = "甲" }, { idx = 2, uid = "20", title = "乙" } }
source.loadTocAsync = function(_self, _identity, cb)
cb(toc)
return { cancel = function() error("已完成目录不得覆盖当前请求") end }
end
local identity = { source_id = "ext.kuaikan", stable_id = "9" }
local handle = source:putProgressAsync(identity,
{ fraction = 0.6875, chapter_idx = 2, chapter_fraction = 0.375, page = 3, total_pages = 8 }, done)
reply(account)
write = requests[#requests]
Assert.eq(write.method, "POST")
Assert.matches(write.url, "/v2/pweb/read/history/report$")
local payload = JSON.decode(Text.urlDecode(write.body:match("view_rate=([^&]+)")))
Assert.eq(#payload, 1)
Assert.eq(payload[1].topic_id, 9)
Assert.eq(payload[1].comic_id, 20)
Assert.eq(payload[1].read_count, 3)
Assert.eq(payload[1].max_read_count, 3)
Assert.eq(payload[1].total_count, 8)
Assert.eq(payload[1].read_time % 1000, 0)
Assert.eq(payload[1].max_read_count_time, payload[1].read_time)
reply({ code = 200 })
reply({ code = 200, data = { total = 1, topics = { { topic_id = 9, comic_id = 10, read_count = 99 } } } })
Assert.is_nil(ok)
Assert.eq(reason, "快看进度变更尚未确认")
handle = source:putProgressAsync(identity, { fraction = 1, chapter_idx = 2, page = 8, total_pages = 8 }, done)
reply(account)
write = requests[#requests]
handle:cancel()
Assert.is_true(write.cancelled)
source:getProgressAsync(identity, done)
reply(account)
reply({ code = 200, data = { total = 1, topics = { { topic_id = 9, comic_id = 20, read_count = 99 } } } })
Assert.eq(ok.chapter_idx, 2)
Assert.eq(ok.fraction, 0.5)
Assert.is_nil(ok.chapter_fraction)
Assert.is_nil(ok.page)
source:getProgressAsync(identity, function(value, err, meta)
ok, reason = value, err
Assert.is_true(meta.empty)
end)
reply(account)
reply({ code = 200, data = { total = 0, topics = {} } })
Assert.is_nil(ok)
Assert.is_nil(reason)
Stubs.flush()
local deleted, removed, added = true, 0, false
package.loaded["book.books_db"] = {
pendingDeleteIds = function() return deleted and { "30" } or {} end,
pendingShelfAddIds = function() return not added and { "9" } or {} end,
remove = function(_id, stable_id)
Assert.eq(stable_id, "30")
deleted, removed = false, removed + 1
return true
end,
markSynced = function(_id, stable_id) Assert.eq(stable_id, "9"); added = true; return true end,
}
source:syncBooksAsync({ dirty_only = true }, done)
reply(account)
reply("challenge")
reply({ code = 200 })
reply({ code = 200, data = { total = 1, topics = { { id = 30, title = "旧书" } } } })
reply("challenge")
reply({ code = 200 })
reply({ code = 200, data = { total = 2, topics = { { id = 30, title = "旧书" }, { id = 9, title = "新书" } } } })
Assert.eq(ok.pushed, 1)
Assert.eq(ok.push_error, "快看收藏变更尚未确认")
Assert.is_true(deleted)
Assert.eq(removed, 0)
Assert.is_true(added)
source:syncBooksAsync({ dirty_only = true }, done)
reply(account)
reply("challenge")
reply({ code = 200 })
reply({ code = 200, data = { total = 0, topics = {} } })
Stubs.flush()
Assert.is_false(deleted)
Assert.eq(removed, 1)
Assert.eq(ok.pushed, 1)
Assert.is_nil(ok.push_error)
local row = { stable_id = "9", chapter_idx = 2, fraction = 0.75, page = 4, total_pages = 8,
sync_status = 0, updated_at = 1 }
local confirmed = 0
package.loaded["book.progress_db"] = {
get = function() return row end,
unsynced = function() return { row } end,
markSynced = function(_id, stable_id, revision)
Assert.eq(stable_id, "9")
Assert.eq(revision, 1)
confirmed, row.sync_status = confirmed + 1, 1
return true
end,
}
source:syncProgressAsync({ dirty_only = true }, done)
Stubs.flush()
reply(account)
reply(nil, "network failed")
Assert.eq(row.sync_status, 0)
Assert.eq(confirmed, 0)
Assert.eq(ok.push_error, "network failed")
source:syncProgressAsync({ dirty_only = true }, done)
Stubs.flush()
reply(account)
reply({ code = 200 })
reply({ code = 200, data = { total = 1, topics = { { topic_id = 9, comic_id = 20 } } } })
Assert.eq(confirmed, 1)
Assert.eq(ok.pushed, 1)
Client.imagesAsync = function(uid, cb)
Assert.eq(uid, "20")
cb({ "https://images/1.jpg", "https://images/2.jpg" })
return { cancel = function() error("已完成的页图不得覆盖当前请求") end }
end
handle = source:putProgressAsync(identity, { fraction = 1 }, done)
reply(account)
write = requests[#requests]
payload = JSON.decode(Text.urlDecode(write.body:match("view_rate=([^&]+)")))
Assert.eq(payload[1].comic_id, 20)
Assert.eq(payload[1].read_count, 2)
Assert.eq(payload[1].total_count, 2)
handle:cancel()
Assert.is_true(write.cancelled)
local loads = 0
source.loadTocAsync = function(_self, _identity, cb, force)
loads = loads + 1
cb(force and toc or { toc[1] })
return { cancel = function() end }
end
source:getProgressAsync(identity, done)
reply(account)
reply({ code = 200, data = { total = 1, topics = { { topic_id = 9, comic_id = 20 } } } })
Assert.eq(loads, 2)
Assert.eq(ok.chapter_idx, 2)
+93
View File
@@ -0,0 +1,93 @@
--[[--
快看远程滑块:临时票据、敏感字段隔离、取消、拒绝应急票据与重复提交。
@module tests.moonsource_kuaikan.verify_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch, inject-field
local Assert = require("support.assert")
local Themed = require("support.theme_stubs")
Themed.install()
local Ext = require("utils.extension")
Ext.reset()
local timers = {}
package.loaded["ui/uimanager"] = {
scheduleIn = function(_ui, _delay, fn) timers[fn] = true end,
unschedule = function(_ui, fn) timers[fn] = nil end,
}
local path
Ext.add("web.open_page", function(url, _title, _text, opts)
path = url
return require("ui.themes.widgets.qr"):new{ close_callback = opts.close_callback }:show()
end)
local Verification = require("moonsource_kuaikan.verify")
local route = Ext.list("web.routes")[1]
local status, body, headers, completed, reason, submitted, proof, cancels = nil, nil, nil, nil, nil, nil, nil, 0
local function request(action, params, method)
route.handle(method or "POST", action, params, function(code, data, extra)
status, body, headers = code, data, extra
end)
end
local function start()
completed, reason = nil, nil
return Verification.new({ cancel = function() cancels = cancels + 1 end }, function(fields, cb)
proof, submitted = fields, cb
end, function(result, err) completed, reason = result, err end)
end
local verification = start()
local ticket = path:match("#(.+)$")
request("config", { ticket = ticket })
Assert.eq(status, 200)
Assert.eq(body.appid, "2034681882")
Assert.is_nil(body.phone)
Assert.is_nil(body.password)
Assert.is_nil(body.cookie)
Assert.eq(headers[1], "Cache-Control: no-store")
request("verify", { ticket = "invalid", captcha_ticket = "proof", randstr = "random" })
Assert.eq(status, 403)
for _idx, value in ipairs({ "", {}, "trerror_1001_x", string.rep("a", 4097) }) do
request("verify", { ticket = ticket, captcha_ticket = value, randstr = "random" })
Assert.eq(status, 400)
end
request("config", { ticket = ticket }, "GET")
Assert.eq(status, 405)
request("unknown", { ticket = ticket })
Assert.eq(status, 404)
request("verify", { ticket = ticket, captcha_ticket = "proof", randstr = "random", password = "ignored" })
Assert.eq(proof.ticket, "proof")
Assert.eq(proof.random, "random")
Assert.is_nil(proof.password)
request("verify", { ticket = ticket, captcha_ticket = "repeat", randstr = "random" })
Assert.eq(status, 409)
submitted({ user_id = "7" })
Assert.eq(status, 200)
Assert.is_true(body.ok)
Assert.is_nil(body.user_id)
Assert.eq(completed.user_id, "7")
Assert.is_nil(next(timers))
Assert.is_nil(verification.submit)
request("verify", { ticket = ticket, captcha_ticket = "replay", randstr = "random" })
Assert.eq(status, 403)
verification = start()
ticket = path:match("#(.+)$")
request("verify", { ticket = ticket, captcha_ticket = "proof", randstr = "random" })
submitted(nil, "private server detail")
Assert.eq(status, 400)
Assert.is_nil(body.error:find("private", 1, true))
Assert.eq(reason, "private server detail")
verification = start()
ticket = path:match("#(.+)$")
request("verify", { ticket = ticket, captcha_ticket = "proof", randstr = "random" })
verification.dialog:close()
submitted(true)
Assert.eq(status, 403)
Assert.is_nil(completed)
Assert.eq(reason, "验证已取消")
Assert.is_true(cancels > 0)
verification = start()
verification.expires = os.time() - 1
request("config", { ticket = verification.ticket })
Assert.eq(status, 403)
verification.timeout()
Assert.eq(reason, "验证已过期,请重新发起验证")
Assert.is_nil(next(timers))
+85
View File
@@ -0,0 +1,85 @@
'use strict';
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const source = fs.readFileSync(process.argv[2] + '/moonsource-kuaikan.koplugin/moonsource_kuaikan/web/kuaikan_verify.js', 'utf8');
async function page(options = {}) {
const nodes = Object.fromEntries(['title', 'instruction', 'status', 'retry', 'captcha']
.map(id => [id, { textContent: '', hidden: false }]));
const requests = [], scripts = [];
let callback, shows = 0;
const messages = { appid: '2034681882', title: 'Kuaikan', instruction: 'Slide',
pending: 'Submitting', success: 'Done', failure: 'Failed',
load_error: 'Load failed', cancelled: 'Cancelled', retry: 'Retry' };
const context = {
AbortController, setTimeout, clearTimeout,
location: { hash: '#fixture' },
window: {},
document: {
get cookie() { throw new Error('Must not read browser credentials'); },
getElementById: id => nodes[id],
createElement: () => ({ remove() { this.removed = true; } }),
head: { appendChild(script) {
scripts.push(script);
if (options.blocked) return script.onerror();
context.window.TencentCaptcha = function(element, appid, cb, opts) {
assert.equal(element, nodes.captcha);
assert.equal(appid, '2034681882');
assert.equal(opts.type, 'embed');
callback = cb;
this.show = () => { shows++; };
this.destroy = () => {};
};
script.onload();
} },
},
fetch: async (url, opts) => {
requests.push({ url, body: JSON.parse(opts.body) });
return {
ok: url.endsWith('/config') || !options.rejected,
json: async () => url.endsWith('/config') ? messages : options.rejected ? { error: 'Rejected' } : { ok: true },
};
},
};
await vm.runInNewContext(source, context);
return { nodes, requests, scripts, get callback() { return callback; }, get shows() { return shows; } };
}
(async () => {
let p = await page();
assert.equal(p.shows, 1);
await p.callback({ ret: 2 });
assert.equal(p.requests.length, 1);
assert.equal(p.nodes.status.textContent, 'Cancelled');
await p.callback({ ret: 0, ticket: 'trerror_1001_fixture', randstr: 'random' });
assert.equal(p.requests.length, 1, 'SDK emergency tickets are never sent');
await p.callback({ ret: 0, ticket: 'proof', randstr: 'random', errorCode: 1001 });
assert.equal(p.requests.length, 1);
await p.callback({ ret: 0, ticket: {}, randstr: 'random' });
assert.equal(p.requests.length, 1, 'Malformed SDK results do not start a login request');
await p.callback({ ret: 0, ticket: 'proof', randstr: 'random' });
assert.deepEqual(p.requests[1].body, { ticket: 'fixture', captcha_ticket: 'proof', randstr: 'random' });
assert.equal(p.nodes.status.textContent, 'Done');
assert.equal(p.nodes.captcha.hidden, true);
await p.callback({ ret: 0, ticket: 'late', randstr: 'random' });
assert.equal(p.requests.length, 2, 'Success cannot be replayed by a late SDK callback');
p = await page({ rejected: true });
await p.callback({ ret: 0, ticket: 'proof', randstr: 'random' });
assert.equal(p.nodes.status.textContent, 'Rejected');
assert.equal(p.nodes.retry.hidden, false);
await p.nodes.retry.onclick();
assert.equal(p.shows, 2);
assert.equal(p.requests[2].url, '/api/kuaikan_verify/config');
const opts = { blocked: true };
p = await page(opts);
assert.equal(p.nodes.status.textContent, 'Load failed');
assert.equal(p.requests.length, 1);
assert.equal(p.scripts[0].removed, true);
opts.blocked = false;
await p.nodes.retry.onclick();
assert.equal(p.shows, 1);
console.log('kuaikan web: OK');
})().catch(error => { console.error(error); process.exitCode = 1; });
+11
View File
@@ -0,0 +1,11 @@
--[[--
快看腾讯滑块网页回归,使用本机 Node,不增加外部依赖。
@module tests.moonsource_kuaikan.web_spec
--]]
local Assert = require("support.assert")
local here = debug.getinfo(1, "S").source:match("^@(.+)/[^/]+$") or "."
local root = here .. "/../.."
local pipe = assert(io.popen('node "' .. here .. '/web_spec.js" "' .. root .. '" 2>&1'))
local output = pipe:read("*a")
pipe:close()
Assert.is_true(output:find("kuaikan web: OK", 1, true) ~= nil, output)