first commit

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
kunkunxiaomaoandClaude committed 2026-11-16 20:45:22 +08:00
commit 9c5fef1a4d
412 files changed
+94582

No files matched your search

+27
View File
@@ -0,0 +1,27 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:sakura_mobile/src/core/api_client.dart';
void main() {
group('cloud API base URL normalization', () {
test('keeps valid http URL', () {
expect(
normalizeCloudBaseUrl('http://api.kunkunxiaomao.top:8000'),
'http://api.kunkunxiaomao.top:8000',
);
});
test('repairs missing slashes after scheme', () {
expect(
normalizeCloudBaseUrl('http:api.kunkunxiaomao.top:8000'),
'http://api.kunkunxiaomao.top:8000',
);
});
test('adds http scheme and strips api prefix', () {
expect(
normalizeCloudBaseUrl('api.kunkunxiaomao.top:8000/api/v1/'),
'http://api.kunkunxiaomao.top:8000',
);
});
});
}
@@ -0,0 +1,200 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sakura_mobile/src/core/legado_engine.dart';
import 'package:sakura_mobile/src/core/legado_models.dart';
import 'package:sakura_mobile/src/core/legado_rule_executor.dart';
import 'package:sakura_mobile/src/core/legado_toc_pagination.dart';
import 'package:sakura_mobile/src/core/online_shelf.dart';
import 'package:sakura_mobile/src/core/search_scheduler.dart';
import 'package:sakura_mobile/src/core/source_health.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('TOC 分页规则', () {
final resolver = TocPaginationResolver(LegadoRuleExecutor());
test('解析字段别名并渲染页码偏移', () {
final source = LegadoSource.fromJson({
'bookSourceName': '分页源',
'bookSourceUrl': 'https://example.com',
'ruleToc': {
'chapterList': '.list a',
'chapterUrl': 'a@href',
'nextUrl': '/catalog?page={{page+1}}',
},
});
expect(source.tocNextPageRule, '/catalog?page={{page+1}}');
expect(
resolver.resolveNextPage(
currentUrl: 'https://example.com/catalog?page=1',
currentHtml: '',
rule: source.tocNextPageRule,
pageIndex: 0,
),
'https://example.com/catalog?page=2',
);
});
test('支持 CSS、XPath、切片和 offset', () {
const html = '<a class="next" href="/list/2">下一页</a>';
expect(
resolver.resolveNextPage(
currentUrl: 'https://example.com/list/1',
currentHtml: html,
rule: 'class.next@href',
pageIndex: 1,
),
'https://example.com/list/2',
);
expect(
resolver.resolveNextPage(
currentUrl: 'https://example.com/list/1',
currentHtml: html,
rule: "//a[contains(text(),'下一页')]/@href",
pageIndex: 1,
),
'https://example.com/list/2',
);
expect(
resolver.resolveNextPage(
currentUrl: 'https://example.com/list/123.html',
currentHtml: '',
rule: '!0:-5',
pageIndex: 1,
),
'https://example.com/list/123',
);
expect(
resolver.resolveNextPage(
currentUrl: 'https://example.com/list?offset=50',
currentHtml: '',
rule: '/list?offset=50',
pageIndex: 1,
),
'https://example.com/list?offset=100',
);
});
});
group('搜索健康分与滑动窗口', () {
setUp(() => SharedPreferences.setMockInitialValues({}));
test('连续失败熔断,成功后恢复并记录延迟', () {
final health = SourceHealth(sourceId: 'a');
for (var i = 0; i < 5; i++) {
health.recordFailure(timeout: i.isEven);
}
expect(health.isUsable, isFalse);
health.recordSuccess(300);
expect(health.isUsable, isTrue);
expect(health.score, greaterThan(0));
});
test('滑动窗口先返回先完成的源', () async {
final engine = _FakeSearchEngine({
'slow': const Duration(milliseconds: 80),
'fast': const Duration(milliseconds: 5),
});
final scheduler = SearchScheduler(engine, SourceHealthStore());
final phases = await scheduler
.search('测试', [_source('slow'), _source('fast')])
.where((phase) => phase.items.isNotEmpty)
.toList();
expect(phases.first.items.first.sourceId, 'fast');
expect(phases.last.name, 'complete');
expect(phases.last.doneCount, 2);
});
test('在线搜索覆盖超过十个的全部已启用来源', () async {
final engine = _FakeSearchEngine(const {});
final scheduler = SearchScheduler(engine, SourceHealthStore());
final sources = List.generate(15, (index) => _source('source-$index'));
final phases = await scheduler.search('全量', sources).toList();
expect(phases.last.name, 'complete');
expect(phases.last.totalCount, 15);
expect(phases.last.doneCount, 15);
expect(phases.last.items, hasLength(15));
});
});
group('在线书架保存解耦', () {
setUp(() => SharedPreferences.setMockInitialValues({}));
test('只保存元数据、重复保存更新、支持移除', () async {
final store = OnlineShelfStore();
final first = OnlineShelfEntry(
sourceId: 'source',
sourceName: '示例源',
title: '第一版标题',
detailUrl: 'https://example.com/book/1',
savedAt: DateTime(2026, 6, 22),
);
await store.save(first);
await store.save(OnlineShelfEntry(
sourceId: first.sourceId,
sourceName: first.sourceName,
title: '更新后的标题',
detailUrl: first.detailUrl,
savedAt: DateTime(2026, 6, 22, 1),
));
expect(store.entries, hasLength(1));
expect(store.entries.single.title, '更新后的标题');
await store.save(OnlineShelfEntry(
sourceId: 'manga-source',
sourceName: '漫画源',
title: '在线漫画',
detailUrl: 'https://example.com/manga/1',
contentType: 'manga',
savedAt: DateTime(2026, 6, 23),
));
expect(store.entries.where((entry) => entry.isManga), hasLength(1));
expect(store.entries.where((entry) => entry.isNovel), hasLength(1));
final restored = OnlineShelfStore();
await restored.load();
expect(restored.entries, hasLength(2));
expect(
restored.entries.singleWhere((entry) => entry.isNovel).detailUrl,
first.detailUrl,
);
await restored.remove(first.id);
expect(restored.entries.single.isManga, isTrue);
});
});
}
LegadoSource _source(String id) => LegadoSource(
id: id,
name: id,
url: 'https://$id.example.com',
type: 0,
enabled: true,
searchUrl: '/search?q={{key}}',
searchListRule: '.result',
);
class _FakeSearchEngine extends LegadoEngine {
_FakeSearchEngine(this.delays);
final Map<String, Duration> delays;
@override
Future<List<UnifiedSearchResult>> search(
LegadoSource source,
String keyword, {
int page = 1,
}) async {
await Future<void>.delayed(delays[source.id] ?? Duration.zero);
return [
UnifiedSearchResult(
sourceId: source.id,
sourceName: source.name,
title: '$keyword-${source.id}',
detailUrl: '${source.url}/book',
),
];
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,139 @@
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:sakura_mobile/src/core/legado_engine.dart';
import 'package:sakura_mobile/src/core/legado_js_runner.dart';
import 'package:sakura_mobile/src/core/legado_rule_executor.dart';
import 'package:sakura_mobile/src/core/source_manager.dart';
void main() {
group('Legado 八阶段规则引擎', () {
const html = '''
<section class="comic">
<h1 class="title">测试漫画</h1>
<span class="author">樱花作者</span>
<div class="pages">
<img data-original="/images/001.jpg">
<img data-original="/images/002.jpg">
</div>
</section>
''';
test('@tag/@text/属性链、索引与备选规则', () {
final rules = LegadoRuleExecutor();
final images = rules.selectList(
html,
html,
'class.pages@tag.img@data-original',
baseUrl: 'https://example.com/book/',
);
expect(images, ['/images/001.jpg', '/images/002.jpg']);
expect(
rules.select(
html,
html,
'class.missing@text||class.title@text',
baseUrl: 'https://example.com',
),
'测试漫画',
);
expect(
rules.select(
html,
html,
'class.pages@tag.img.-1@data-original',
baseUrl: 'https://example.com',
),
'/images/002.jpg',
);
});
test('&& 拼接及 ##/### 净化', () {
final rules = LegadoRuleExecutor();
expect(
rules.select(
html,
html,
'class.title@text&&class.author@text',
baseUrl: 'https://example.com',
),
'测试漫画\n樱花作者',
);
expect(
rules.select(
'<p class="intro">简介:故事正文 广告</p>',
'<p class="intro">简介:故事正文 广告</p>',
'class.intro@text##^简介:|广告',
baseUrl: 'https://example.com',
),
'故事正文',
);
});
test('@put/@get 与 JSON URL 模板', () {
final rules = LegadoRuleExecutor();
const json = '{"name":"作品","id":"9527","chapter":"12"}';
expect(
rules.select(
json,
json,
r'$.name@put:{bid:id||book_id}',
baseUrl: 'https://example.com',
kind: 'json',
),
'作品',
);
expect(
rules.select(
json,
json,
r'https://example.com/book/@get:{bid}/{{$.chapter}}',
baseUrl: 'https://example.com',
),
'https://example.com/book/9527/12',
);
});
test('QuickJS 完整引擎执行标准 JavaScript', () {
final runner = LegadoJsRunner();
final output = runner.run(
script:
"result.split(',').map(x => '<img src=\"' + x + '\">').join('\\n')",
result: 'a.jpg,b.jpg',
rawHtml: '',
baseUrl: 'https://example.com',
context: <String, String>{},
);
expect(output, contains('a.jpg'));
expect(output, contains('b.jpg'));
});
test('解析用户 All.json 与远程 1012.json 全量样本', () {
final engine = LegadoEngine();
final samples = <File>[
File(r'C:\Users\LENOVO\Downloads\All.json'),
File(r'test\fixtures\yiciyuan_1012.json'),
];
final minimums = <int>[5, 150];
for (var index = 0; index < samples.length; index++) {
expect(samples[index].existsSync(), isTrue,
reason: '缺少真实书源样本 ${samples[index].path}');
final sources = engine.parseSources(samples[index].readAsStringSync());
expect(sources.length, greaterThan(minimums[index]));
expect(sources.any((source) => source.contentRule != null), isTrue);
}
});
test('兼容度检测识别 JS、上下文和不完整规则', () {
final engine = LegadoEngine();
final sources = engine.parseSources(
File(r'C:\Users\LENOVO\Downloads\All.json').readAsStringSync(),
);
final manager = SourceManager(engine: engine);
final infos = sources.map(manager.compatibilityFor).toList();
expect(infos.any((info) => info.hasJsRule), isTrue);
expect(infos.any((info) => info.hasPutGet), isTrue);
expect(infos.any((info) => info.searchOk), isTrue);
});
});
}
+344
View File
@@ -0,0 +1,344 @@
import 'dart:io';
import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:sakura_mobile/src/core/legado_engine.dart';
import 'package:sakura_mobile/src/core/legado_js_runner.dart';
import 'package:sakura_mobile/src/core/legado_models.dart';
import 'package:sakura_mobile/src/core/legado_rule_executor.dart';
import 'package:sakura_mobile/src/core/manga_image.dart';
void main() {
group('漫画图片规则', () {
test('拆分 Legado 图片 URL 与独立 headers', () {
final parsed = splitLegadoImageSpec(
'https://img.example.com/1.jpg,{"headers":{"Referer":"https://comic.example.com","Cookie":"a=1"}}',
);
expect(parsed.url, 'https://img.example.com/1.jpg');
expect(parsed.headers['Referer'], 'https://comic.example.com');
expect(parsed.headers['Cookie'], 'a=1');
});
test('过滤空值与占位图并清洗转义 URL', () {
expect(validateImageCandidate('', 'https://example.com').reason, 'empty');
expect(
validateImageCandidate('/images/loading.gif', 'https://example.com')
.reason,
'placeholder',
);
final candidate = validateImageCandidate(
r'https:\/\/img.example.com\/comic\u002F1.jpg',
'https://example.com/chapter',
);
expect(candidate.isValid, isTrue);
expect(candidate.url, 'https://img.example.com/comic/1.jpg');
});
test('PageImage 合并源 headers、章节 Referer 与图片专属 headers', () {
final page = buildPageImage(
raw:
'https://img.example.com/1.jpg,{"headers":{"Referer":"https://cdn.example.com","X-Image":"1"}}',
chapterUrl: 'https://comic.example.com/chapter/1',
index: 0,
sourceHeaders: const {'Cookie': 'session=1'},
userAgent: 'Sakura-Test',
);
expect(page, isNotNull);
expect(page!.headers['Cookie'], 'session=1');
expect(page.headers['User-Agent'], 'Sakura-Test');
expect(page.headers['Referer'], 'https://cdn.example.com');
expect(page.headers['X-Image'], '1');
});
test('识别图片魔数', () {
expect(isImageMagic([0xFF, 0xD8, 0xFF, 0x00]), isTrue);
expect(
isImageMagic([
0x52,
0x49,
0x46,
0x46,
0,
0,
0,
0,
0x57,
0x45,
0x42,
0x50,
]),
isTrue,
);
expect(isImageMagic([0x3C, 0x68, 0x74, 0x6D]), isFalse);
});
test('章节号支持小数番外与多种标题格式', () {
expect(extractMangaChapterNumber('第660.5回 番外'), 660.5);
expect(extractMangaChapterNumber('Ch.660'), 660);
expect(extractMangaChapterNumber('12话'), 12);
expect(extractMangaChapterNumber('序章'), isNull);
});
});
group('manga online source compatibility', () {
test('recognizes a mislabeled manga source using strong manga fields', () {
final source = LegadoSource.fromJson({
'bookSourceName': 'Example Manga',
'bookSourceUrl': 'https://manga.example.com',
'bookSourceType': 0,
'ruleSearch': {
'comicList': r'$.data[*]',
'comicName': r'$.title',
'comicUrl': r'$.url',
},
'ruleContent': {
'content': r'$.images[*]',
'imageStyle': 'FULL',
},
});
expect(source.isManga, isTrue);
});
test('does not reclassify an ordinary novel source', () {
final source = LegadoSource.fromJson({
'bookSourceName': 'Example Novel',
'bookSourceUrl': 'https://novel.example.com',
'bookSourceType': 0,
'ruleSearch': {'bookList': '.book', 'name': '.title@text'},
'ruleContent': {'content': '#content@text'},
});
expect(source.isNovel, isTrue);
});
test('splits inline Legado POST options from a manga search URL', () {
final spec = parseLegadoRequestSpec(
'/search,{"method":"POST","body":"q={{key}}","headers":{"X-App":"manga"}}',
);
expect(spec.url, '/search');
expect(spec.method, 'POST');
expect(spec.body, 'q={{key}}');
expect(spec.headers['X-App'], 'manga');
});
test('accepts common loose Legado request options', () {
final spec = parseLegadoRequestSpec(
"/search,{'method':'POST';'body':'q={{key}}','headers':'{os: pc}'}",
);
expect(spec.url, '/search');
expect(spec.method, 'POST');
expect(spec.body, 'q={{key}}');
expect(spec.headers['os'], 'pc');
});
test('provides common safe Legado variables and base64 helper to JS', () {
final output = LegadoJsRunner().run(
script:
"source.getKey() + '|' + key + '|' + page + '|' + java.base64Decode('5ryr55S7')",
result: '',
rawHtml: '<html></html>',
baseUrl: 'https://manga.example.com',
context: <String, String>{
'sourceUrl': 'https://manga.example.com',
'key': 'sakura',
'page': '3',
},
);
expect(output, 'https://manga.example.com|sakura|3|漫画');
final objectOutput = LegadoJsRunner().run(
script: 'result.title + "|" + result.comic_id',
result: '{"title":"Sakura","comic_id":42}',
rawHtml: '',
baseUrl: 'https://manga.example.com',
context: <String, String>{},
);
expect(objectOutput, 'Sakura|42');
}, skip: Platform.isWindows ? 'QuickJS desktop DLL is not bundled' : false);
test('manga search uses manga-style JSON fallback matching', () async {
final dio = Dio()
..httpClientAdapter = _FakeAdapter({
'https://manga.example.com/search?q=%E9%AD%94%E6%B3%95':
'{"data":[{"comic_name":"魔法少女","author":"Sakura","comic_url":"/comic/1","cover_url":"/cover.jpg"}]}',
});
final engine = LegadoEngine(http: dio);
const source = LegadoSource(
id: 'manga-json',
name: 'Manga JSON',
url: 'https://manga.example.com',
type: 2,
enabled: true,
searchUrl: '/search?q={{key}}',
searchListRule: r'$.missing[*]',
);
final results = await engine.search(source, '魔法');
expect(results, hasLength(1));
expect(results.single.title, '魔法少女');
expect(results.single.author, 'Sakura');
expect(results.single.detailUrl, 'https://manga.example.com/comic/1');
expect(results.single.coverUrl, 'https://manga.example.com/cover.jpg');
});
test('matches punctuated titles and builds a detail URL from comic ID',
() async {
final dio = Dio()
..httpClientAdapter = _FakeAdapter({
'https://manga.example.com/search?q=%E7%81%AB%E5%BD%B1%E5%BF%8D%E8%80%85':
'{"data":[{"comic_name":"火影忍者:疾风传(漫画)","comic_id":"77"}]}'
});
final engine = LegadoEngine(http: dio);
const source = LegadoSource(
id: 'manga-id',
name: 'Manga ID',
url: 'https://manga.example.com',
type: 2,
enabled: true,
searchUrl: '/search?q={{key}}',
searchListRule: r'$.missing[*]',
);
final results = await engine.search(source, '火影忍者');
expect(results, hasLength(1));
expect(results.single.detailUrl, 'https://manga.example.com/comic/77');
});
test('manga search uses manga-style HTML card fallback matching', () async {
final dio = Dio()
..httpClientAdapter = _FakeAdapter({
'https://manga.example.com/search?q=%E6%A8%B1%E8%8A%B1': '''
<div class="comic-card">
<a href="/manga/sakura" title="樱花漫画">
<img data-src="/sakura.webp" alt="樱花漫画">
</a>
<span class="author">花见</span>
</div>
''',
});
final engine = LegadoEngine(http: dio);
const source = LegadoSource(
id: 'manga-html',
name: 'Manga HTML',
url: 'https://manga.example.com',
type: 2,
enabled: true,
searchUrl: '/search?q={{key}}',
searchListRule: '.missing',
);
final results = await engine.search(source, '樱花');
expect(results, hasLength(1));
expect(results.single.title, '樱花漫画');
expect(results.single.author, '花见');
expect(
results.single.detailUrl, 'https://manga.example.com/manga/sakura');
expect(results.single.coverUrl, 'https://manga.example.com/sakura.webp');
});
});
group('novel Legado matching compatibility', () {
test('uses inline POST settings for a novel source', () async {
final adapter = _FakeAdapter({
'https://novel.example.com/search':
'{"data":[{"name":"龙族","author":"江南","url":"/book/1"}]}'
});
final engine = LegadoEngine(http: Dio()..httpClientAdapter = adapter);
const source = LegadoSource(
id: 'novel-post',
name: 'Novel POST',
url: 'https://novel.example.com',
type: 0,
enabled: true,
searchUrl: '/search,{"method":"POST","body":"q={{key}}"}',
searchListRule: r'$.data[*]',
searchNameRule: r'$.name',
searchAuthorRule: r'$.author',
searchDetailRule: r'$.url',
ruleKind: 'json',
);
final results = await engine.search(source, '龙族');
expect(results.single.title, '龙族');
expect(results.single.detailUrl, 'https://novel.example.com/book/1');
expect(adapter.methods, contains('POST'));
});
test('supports root JSON list rules used by Legado novel sources', () {
final rules = LegadoRuleExecutor();
const body =
'[{"name":"十宗罪","url":"/book/1"},{"name":"别的书","url":"/book/2"}]';
final fragments = rules.selectList(
body,
body,
r'$[*]',
baseUrl: 'https://novel.example.com',
kind: 'json',
);
expect(fragments, hasLength(2));
expect(
rules.select(
body,
fragments.first,
r'$.name',
baseUrl: 'https://novel.example.com',
kind: 'json',
),
'十宗罪',
);
});
test('supports text.xxx selector used by Legado toc rules', () {
final rules = LegadoRuleExecutor();
const html =
'<div class="toolbar"><a href="/all-chapters">查看全部章节</a></div>';
expect(
rules.select(
html,
html,
'text.查看全部章节@href',
baseUrl: 'https://novel.example.com',
),
'/all-chapters',
);
});
});
}
class _FakeAdapter implements HttpClientAdapter {
_FakeAdapter(this.responses);
final Map<String, String> responses;
final List<String> methods = <String>[];
@override
Future<ResponseBody> fetch(
RequestOptions options,
Stream<Uint8List>? requestStream,
Future<void>? cancelFuture,
) async {
methods.add(options.method.toUpperCase());
final body = responses[options.uri.toString()];
return ResponseBody.fromString(
body ?? 'not found',
body == null ? 404 : 200,
headers: {
Headers.contentTypeHeader: ['text/html; charset=utf-8'],
},
);
}
@override
void close({bool force = false}) {}
}
@@ -0,0 +1,95 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:sakura_mobile/src/core/legado_models.dart';
import 'package:sakura_mobile/src/core/legado_rule_parser.dart';
import 'package:sakura_mobile/src/core/online_cache.dart';
void main() {
group('在线书籍章节导航', () {
test('导入并序列化 BookInfo、TOC 与 Content 规则', () {
final source = LegadoSource.fromJson({
'bookSourceName': '测试源',
'bookSourceUrl': 'https://example.com',
'bookSourceType': 0,
'ruleBookInfo': {
'name': 'h1',
'author': '.author',
'coverUrl': '.cover@src',
'intro': '.intro',
'tocUrl': '.catalog@href',
},
'ruleToc': {
'chapterList': '.chapters li',
'chapterName': 'a',
'chapterUrl': 'a@href',
'nextTocUrl': '.next@href',
},
'ruleContent': {
'content': '#content',
'nextChapterUrl': '.next@href',
'prevChapterUrl': '.prev@href',
},
});
expect(source.bookInfoTocRule, '.catalog@href');
expect(source.tocListRule, '.chapters li');
expect(source.tocNextPageRule, '.next@href');
expect(source.contentRule, '#content');
final restored = LegadoSource.fromJson(source.toJson());
expect(restored.bookInfoNameRule, 'h1');
expect(restored.tocUrlRule, 'a@href');
expect(restored.contentNextRule, '.next@href');
});
test('CSS 规则能提取章节名称与相对链接', () {
const html = '''
<ul class="chapters">
<li><a href="/book/1.html">第一章 初遇</a></li>
<li><a href="/book/2.html">第二章 再会</a></li>
</ul>
''';
final parser = RuleParser(html, baseUrl: 'https://example.com/book/');
final rows = parser.selectList('.chapters li');
expect(rows, hasLength(2));
expect(parser.select(rows.first, 'a'), '第一章 初遇');
expect(parser.select(rows.first, 'a@href'), '/book/1.html');
});
test('会话缓存按书源和 URL 隔离', () {
final cache = OnlineContentCache();
const info = OnlineBookInfo(
title: '示例书',
tocUrl: 'https://example.com/toc',
sourceName: '测试源',
);
cache.putBookInfo('source-a', 'https://example.com/detail', info);
expect(
cache.getBookInfo('source-a', 'https://example.com/detail')?.title,
'示例书',
);
expect(
cache.getBookInfo('source-b', 'https://example.com/detail'),
isNull,
);
});
test('阅读记录 JSON 往返保持章节位置', () {
final record = OnlineReadingRecord(
sourceId: 'source-a',
sourceName: '测试源',
bookTitle: '示例书',
detailUrl: 'https://example.com/detail',
chapterUrl: 'https://example.com/chapter/3',
chapterTitle: '第三章',
chapterIndex: 2,
totalChapters: 20,
lastReadTime: DateTime(2026, 6, 21, 9),
);
final restored = OnlineReadingRecord.fromJson(record.toJson());
expect(restored.chapterIndex, 2);
expect(restored.chapterTitle, '第三章');
expect(restored.lastReadTime, DateTime(2026, 6, 21, 9));
});
});
}
@@ -0,0 +1,63 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:sakura_mobile/src/core/api_client.dart';
import 'package:sakura_mobile/src/core/legado_models.dart';
void main() {
group('在线解析兜底', () {
test('云端小说解析结果可以转为可阅读章节', () {
final parsed = OnlineParsedContent.fromJson({
'title': '龙族',
'kind': 'novel',
'cover': 'https://example.com/cover.jpg',
'chapters': [
{
'name': '第一章',
'url': 'https://example.com/read/1.html',
'content': '路明非站在雨里,故事从这里开始。',
'images': [],
}
],
});
final chapter = OnlineChapter(
title: parsed.chapters.first.name,
url: parsed.chapters.first.url!,
index: 1,
);
final content = OnlineChapterContent(
title: chapter.title,
textContent: parsed.chapters.first.content,
);
expect(parsed.title, '龙族');
expect(chapter.url, 'https://example.com/read/1.html');
expect(content.textContent, contains('路明非'));
});
test('云端漫画解析结果可以转为图片章节', () {
final parsed = OnlineParsedContent.fromJson({
'title': '一人之下',
'kind': 'manga',
'chapters': [
{
'name': '第1话',
'url': 'https://example.com/comic/1',
'images': [
'https://example.com/001.webp',
'https://example.com/002.webp',
],
}
],
});
final content = OnlineChapterContent(
title: parsed.chapters.first.name,
imageUrls: parsed.chapters.first.images,
);
expect(parsed.title, '一人之下');
expect(content.imageUrls, hasLength(2));
expect(content.imageUrls.first, endsWith('001.webp'));
});
});
}
+230
View File
@@ -0,0 +1,230 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:sakura_mobile/src/core/api_client.dart';
import 'package:sakura_mobile/src/core/legado_engine.dart';
import 'package:sakura_mobile/src/core/source_manager.dart';
import 'package:sakura_mobile/src/core/unified_search.dart';
import 'package:sakura_mobile/src/models/artwork.dart';
import 'package:sakura_mobile/src/models/novel.dart';
void main() {
group('在线搜索功能测试', () {
late SakuraApiClient api;
late SourceManager sourceManager;
late LegadoEngine engine;
late UnifiedSearch unifiedSearch;
setUp(() {
api = SakuraApiClient();
engine = LegadoEngine();
sourceManager = SourceManager(engine: engine);
unifiedSearch = UnifiedSearch(
api: api,
sourceManager: sourceManager,
engine: engine,
);
});
test('云库搜索十宗罪小说', () async {
final results =
await api.novels(search: '十宗罪');
final novels = results
.map((item) => Novel.fromJson(item as Map<String, dynamic>))
.toList();
print('');
print('========================================');
print('【云库搜索小说:十宗罪】');
print('找到 ${novels.length} 条结果');
for (final novel in novels) {
print(' - ${novel.title}');
print(' 作者: ${novel.author ?? "未知"}');
print(' 来源: ${novel.sourcePlatform}');
print(' 章节: ${novel.chapterTitle ?? novel.displayChapterTitle}');
if (novel.description?.isNotEmpty == true) {
print(' 简介: ${novel.description!.substring(0, novel.description!.length > 60 ? 60 : novel.description!.length)}...');
}
print('');
}
expect(novels.isNotEmpty, isTrue,
reason: '云库搜索"十宗罪"应返回至少一条结果');
});
test('云库搜索一人之下漫画', () async {
final results =
await api.gallery(search: '一人之下', contentType: 'manga');
final artworks = results
.map((item) => Artwork.fromJson(item as Map<String, dynamic>))
.toList();
print('');
print('========================================');
print('【云库搜索漫画:一人之下】');
print('找到 ${artworks.length} 条结果');
for (final artwork in artworks) {
print(' - ${artwork.title}');
print(' 作者: ${artwork.author ?? "未知"}');
print(' 类型: ${artwork.contentType}');
print(' 来源: ${artwork.sourcePlatform}');
print(' 标签: ${artwork.tags.join(", ")}');
print('');
}
expect(artworks.isNotEmpty, isTrue,
reason: '云库搜索"一人之下"漫画应返回至少一条结果');
});
test('统一搜索十宗罪 (小说模式)', () async {
print('');
print('========================================');
print('【统一搜索:十宗罪 (小说模式)】');
print('包含云库搜索 + 在线书源搜索');
print('');
final sections = await unifiedSearch.search(
query: '十宗罪',
mode: UnifiedSearchMode.novel,
);
var totalItems = 0;
for (final section in sections) {
print('--- ${section.title} (${section.items.length} 条) ---');
for (final item in section.items.take(5)) {
totalItems++;
print(' [$totalItems] ${item.title}');
print(' 来源: ${item.sourceName}');
print(' 作者: ${item.author ?? "未知"}');
if (item.isError) {
print(' 错误: ${item.errorMessage}');
}
if (item.isCloud) {
print(' 类型: 云库');
}
if (item.online != null) {
print(' 类型: 在线书源');
}
print('');
}
}
print('总共找到 $totalItems 条结果');
print('');
expect(sections.isNotEmpty, isTrue,
reason: '统一搜索"十宗罪"应返回至少一个结果分组');
expect(totalItems, greaterThan(0),
reason: '统一搜索"十宗罪"应返回至少一条结果');
});
test('统一搜索一人之下 (漫画模式)', () async {
print('');
print('========================================');
print('【统一搜索:一人之下 (漫画模式)】');
print('包含云库搜索 + 在线书源搜索');
print('');
final sections = await unifiedSearch.search(
query: '一人之下',
mode: UnifiedSearchMode.manga,
);
var totalItems = 0;
for (final section in sections) {
print('--- ${section.title} (${section.items.length} 条) ---');
for (final item in section.items.take(5)) {
totalItems++;
print(' [$totalItems] ${item.title}');
print(' 来源: ${item.sourceName}');
print(' 作者: ${item.author ?? "未知"}');
if (item.isError) {
print(' 错误: ${item.errorMessage}');
}
if (item.isCloud) {
print(' 类型: 云库');
}
if (item.online != null) {
print(' 类型: 在线书源');
}
print('');
}
}
print('总共找到 $totalItems 条结果');
print('');
expect(sections.isNotEmpty, isTrue,
reason: '统一搜索"一人之下"应返回至少一个结果分组');
expect(totalItems, greaterThan(0),
reason: '统一搜索"一人之下"应返回至少一条结果');
});
test('搜索功能可用性汇总', () async {
print('');
print('========================================');
print('【搜索功能可用性汇总】');
print('');
// Test cloud manga search
try {
final mangaResults =
await api.gallery(search: '一人之下', contentType: 'manga');
final mangaCount = mangaResults.length;
print('✅ 云库漫画搜索: 正常 (找到 $mangaCount 条)');
} catch (e) {
print('❌ 云库漫画搜索: 失败 ($e)');
}
// Test cloud novel search
try {
final novelResults = await api.novels(search: '十宗罪');
final novelCount = novelResults.length;
print('✅ 云库小说搜索: 正常 (找到 $novelCount 条)');
} catch (e) {
print('❌ 云库小说搜索: 失败 ($e)');
}
// Test online manga source search
try {
await sourceManager.initializeIfFirstRun();
final mangaSources = sourceManager.enabledMangaSources;
print('✅ 漫画在线书源: ${mangaSources.length} 个已启用');
if (mangaSources.isNotEmpty) {
final mangaOnlineResults =
await engine.searchAll(mangaSources, '一人之下');
final onlineMangaCount =
mangaOnlineResults.where((r) => !r.isError).length;
print('✅ 在线漫画搜索: 正常 (找到 $onlineMangaCount 条)');
}
} catch (e) {
print('❌ 在线漫画搜索: 失败 ($e)');
}
// Test online novel source search
try {
final novelSources = sourceManager.enabledNovelSources;
print('✅ 小说在线书源: ${novelSources.length} 个已启用');
if (novelSources.isNotEmpty) {
final novelOnlineResults =
await engine.searchAll(novelSources, '十宗罪');
final onlineNovelCount =
novelOnlineResults.where((r) => !r.isError).length;
print('✅ 在线小说搜索: 正常 (找到 $onlineNovelCount 条)');
}
} catch (e) {
print('❌ 在线小说搜索: 失败 ($e)');
}
// Test GBK encoding
try {
final gbkTest = '十宗罪';
final encoded = Uri.encodeQueryComponent(gbkTest);
print('✅ GBK 编码支持: 正常 (UTF-8 编码可用)');
} catch (e) {
print('❌ GBK 编码支持: 失败 ($e)');
}
print('');
print('========================================');
});
});
}
+10
View File
@@ -0,0 +1,10 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:sakura_mobile/src/app.dart';
void main() {
testWidgets('Sakura app boots', (tester) async {
await tester.pumpWidget(const ProviderScope(child: SakuraMobileApp()));
expect(find.text('Sakura Cloud'), findsOneWidget);
});
}