--[[-- moonsource_legadorule.parser 离线用例:搜索、详情、目录翻页、正文翻页与取消,http 走脚本化桩。 @module tests.legadorule.parser_spec --]] ---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch local Assert = require("support.assert") local pages, calls = {}, {} package.preload["http.request"] = function() local function respond(url, cb) calls[#calls + 1] = url local body = pages[url] if body == nil then return cb(nil, "HTTP 404", { code = 404 }) end cb(body, nil, { code = 200 }) end return { header = function() return nil end, get = function(url, _opts, cb) respond(url, cb) return { cancel = function() end } end, post = function(url, _body, _opts, cb) respond(url, cb) return { cancel = function() end } end, } end package.preload["http.cookie_jar"] = function() return { new = function() return {} end } end local Parser = require("moonsource_legadorule.parser") local Client = require("moonsource_legadorule.client") local rule = { bookSourceUrl = "https://a.com", searchUrl = "/s?q={{key}}", ruleSearch = { bookList = ".r li", name = "a@text", bookUrl = "a@href", author = "span@text##作者:" }, ruleBookInfo = { name = "h1@text", intro = ".intro@text", tocUrl = ".toc@href" }, ruleToc = { chapterList = ".c a", chapterName = "text", chapterUrl = "href", nextTocUrl = ".next@href" }, ruleContent = { content = "#t@html", nextContentUrl = ".np@href" }, } local function wait(fn) local a, b fn(function(x, y) a, b = x, y end) return a, b end pages["https://a.com/s?q=%E6%96%97"] = '' pages["https://a.com/b/1"] = '

斗破

简介
目录' pages["https://a.com/t/1"] = '
一二
' pages["https://a.com/t/2"] = '
三
' pages["https://a.com/c/1"] = '
第一段
第二段
下页' pages["https://a.com/c/1_2"] = '
第三段
下章' local P = Parser.new(rule, Client.new(rule)) -- 搜索:书名前缀、作者前缀被清理,同书地址去重。 local books, err = wait(function(cb) P:search("斗", 1, cb) end) Assert.is_nil(err) Assert.len(books, 2) Assert.eq(books[1].name, "斗破") Assert.eq(books[1].author, "天蚕") Assert.eq(books[1].bookUrl, "https://a.com/b/1") -- 详情 → 目录:跟随 nextTocUrl,遇到回环停止。 local book = wait(function(cb) P:detail(books[1].bookUrl, books[1], cb) end) Assert.eq(book.tocUrl, "https://a.com/t/1") Assert.eq(book.intro, "简介") local chapters = wait(function(cb) P:chapters(book, cb) end) Assert.len(chapters, 3) Assert.eq(chapters[3].url, "https://a.com/c/3") -- 正文:拼接分页,遇到下一章地址停止。 local content = wait(function(cb) P:content(chapters[1], book, chapters[2].url, cb) end) Assert.eq(content.text, "第一段\n第二段\n第三段") -- 错误如实上报:404 与 JS 规则。 local _, e = wait(function(cb) P:content({ title = "x", url = "https://a.com/none", baseUrl = "https://a.com", isVolume = false }, book, nil, cb) end) Assert.matches(e, "获取网页内容失败") local js = Parser.new({ bookSourceUrl = "https://a.com", searchUrl = "/s?q={{java.md5(key)}}" }, Client.new({})) local _r, e2 = wait(function(cb) js:search("x", 1, cb) end) Assert.matches(e2, "JS/WebView")