更新测试案例

This commit is contained in:
Happi (哈比)
2026-03-09 13:03:44 +08:00
parent 56112e1fe3
commit 7b78da86e7
11 changed files with 721 additions and 278 deletions

View File

@@ -1,118 +1,154 @@
import 'dart:math';
import 'package:drift/drift.dart';
import 'package:flutter/material.dart';
import 'package:im_app/app/di/db_provider.dart';
import 'package:im_app/data/local/drift/app_database.dart';
import 'package:im_app/domain/entities/user.dart';
import 'package:im_app/domain/presentation/di/user_provider.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'chat_db_test_view_model.g.dart';
class TestResult {
final String title;
final String subtitle;
final String duration;
TestResult({
required this.title,
required this.subtitle,
required this.duration,
});
}
class ChatDbTestState {
final bool testStarted;
final List<TestResult> testResults;
final List<User> users;
final String currentState;
final bool hasMore;
final int currentPage;
final int totalCount;
const ChatDbTestState({
this.testStarted = false,
this.testResults = const [],
this.users = const [],
this.currentState = '',
this.hasMore = true,
this.currentPage = 0,
this.totalCount = 0,
});
ChatDbTestState copyWith({
bool? testStarted,
List<TestResult>? testResults,
List<User>? users,
String? currentState,
bool? hasMore,
int? currentPage,
int? totalCount,
}) => ChatDbTestState(
testStarted: testStarted ?? this.testStarted,
testResults: testResults ?? this.testResults,
users: users ?? this.users,
currentState: currentState ?? this.currentState,
hasMore: hasMore ?? this.hasMore,
currentPage: currentPage ?? this.currentPage,
totalCount: totalCount ?? this.totalCount,
);
}
@riverpod
class ChatDbTestViewModel extends _$ChatDbTestViewModel {
final _random = Random();
bool _isTesting = false;
static const _pageSize = 50;
@override
ChatDbTestState build() {
// 这里就是 onInit
final List<TestResult> testResults = List.generate(
1000,
(i) => TestResult(
title: '用户 ${Random().nextInt(9999)}',
subtitle: 'uid: ${Random().nextInt(999999)}',
duration: '${Random().nextInt(500)}ms',
),
);
return ChatDbTestState(testResults: testResults);
Future.microtask(() => _loadNextPage(reset: true));
return const ChatDbTestState(currentState: '加载中...');
}
// ── 导航Demo 按钮,正式开发后随 UI 一并替换) ──────────────────────────
// ── 分页 ──────────────────────────────────────────────────────────────────
Future<void> _loadNextPage({bool reset = false}) async {
if (!state.hasMore && !reset) return;
final repo = ref.read(userRepositoryProvider);
final page = reset ? 0 : state.currentPage;
final offset = page * _pageSize;
final results = await Future.wait([
repo.getUsers(offset: offset, limit: _pageSize),
repo.countUsers(),
]);
if (!ref.mounted) return;
final newUsers = results[0] as List<User>;
final total = results[1] as int;
state = state.copyWith(
users: reset ? newUsers : [...state.users, ...newUsers],
currentPage: page + 1,
hasMore: newUsers.length >= _pageSize,
totalCount: total,
currentState: reset && newUsers.isEmpty ? '暂无数据' : '空闲 (共 $total 条)',
);
}
/// Called by ListView when reaching the end
void loadMore() {
if (!state.hasMore || state.testStarted) return;
_loadNextPage();
}
// ── 测试 ──────────────────────────────────────────────────────────────────
/// 开始测试
void startDBTest(BuildContext context) {
_isTesting = true;
state = state.copyWith(testStarted: true, currentState: '开始测试');
_testDBInsert();
}
/// 结束测试
void stopDBTest(BuildContext context) {
_isTesting = false;
state = state.copyWith(testStarted: false, currentState: '结束测试');
}
Future<void> _testDBInsert() async {
final db = ref.read(storageSdkProvider);
final repo = ref.read(userRepositoryProvider);
const count = 10000;
const chunkSize = 50;
const chunkSize = 200;
final stopwatch = Stopwatch()..start();
debugPrint('开始测试: $count 条,每批 $chunkSize');
final workingList = List<User>.from(state.users);
int completed = 0;
for (var i = 0; i < count; i += chunkSize) {
while (completed < count) {
if (!_isTesting) break;
final chunk = List.generate(
chunkSize.clamp(0, count - i),
(j) => UsersCompanion.insert(
uid: i + j,
nickname: Value('User ${i + j}'),
min(chunkSize, count - completed),
(_) => User(
uid: _random.nextInt(999999),
nickname: 'User ${_random.nextInt(9999)}',
),
);
await db.batchInsertOrReplace<DriftUser>(chunk);
await repo.saveUsers(chunk);
completed += chunk.length;
workingList.addAll(chunk);
// 让出主线程
await Future.delayed(Duration.zero);
debugPrint(
'已完成: $completed / $count (${stopwatch.elapsedMilliseconds}ms)',
);
debugPrint('已完成: $completed / $count (${stopwatch.elapsedMilliseconds}ms)');
// 更新 UI 状态
if (ref.mounted) {
state = state.copyWith(
users: List.unmodifiable(workingList),
currentState: '已插入 $completed / $count',
);
}
}
debugPrint('全部完成: ${stopwatch.elapsedMilliseconds}ms');
_isTesting = false;
final elapsed = stopwatch.elapsedMilliseconds;
debugPrint('全部完成: ${elapsed}ms');
if (ref.mounted) {
final total = await repo.countUsers();
state = state.copyWith(
testStarted: false,
currentState: '完成!共 $count 条,耗时 ${stopwatch.elapsedMilliseconds}ms',
totalCount: total,
currentState: '完成!共 $total 条,耗时 ${elapsed}ms',
);
}
}
}
}