refactor(client): 网络层由官方 http 换成 dio(对外行为不变)

为什么:权威文档(AGENTS.md / CODING_STANDARDS.md)强制网络层用 dio,差异清单 A 组第 1 题
用户裁定选 A;原来用官方 http 是在无文档状态下按口头要求选的。

- ApiClient 改用 dio + BaseOptions(validateStatus 恒真、8s 超时、ResponseType.bytes 自行 UTF-8 解码)
- 新增 AuthHeaderInterceptor(Authorization / X-Device-Id)与 EnvelopeInterceptor
  (解包 {code,message,data} + 错误码映射 + 401 判定)
- 401 → 刷新 → 重发一次在 ApiClient 里编排,刻意不放在拦截器内重发:dio 的排队拦截器
  在回调里再发请求会自锁
- 接口层(auth_api/catalog_api)签名、全部 controller/logic/page 未改动
- 测试:新增假 dio adapter 替代 MockClient,断言口径一条未改;用例名改为 should_<期望>_when_<条件>;
  新增 api_client_test(解包/错误映射/请求头/查询参数/跳过重试)与 live_auth_test(真实后端 POST 链路)
- pubspec:加 dio、移除已无引用的 http
- 实测:dart analyze lib test 零告警;flutter test 155 全过;真实联调(8081)GET/POST 链路均通
This commit is contained in:
Vicky committed 2026-10-16 09:30:46 +08:00
1 parent ae49b10407
commit 1853e1845c
10 files changed
+508 -143

No files matched your search

+61 -48
View File
@@ -1,8 +1,6 @@
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
@@ -12,23 +10,18 @@ import 'package:nontonki/core/data/remote/auth_api.dart';
import 'package:nontonki/core/data/services/auth_controller.dart';
import 'package:nontonki/core/data/services/auth_session_store.dart';
/// 用假的 http.Client 覆盖三条关键路径:注册成功、401 → 刷新 → 重试、刷新失败 → 清会话。
import '../support/fake_http_adapter.dart';
/// 用假的 dio adapter 覆盖四条关键路径:注册成功、401 → 刷新 → 重试、刷新失败 → 清会话、登出。
///
/// 网络层从 http 换成 dio 后,这里的**断言口径一条没变**,只是注入方式从
/// `http.testing.MockClient` 换成 `FakeHttpAdapter`。
void main() {
setUp(() {
SharedPreferencesAsyncPlatform.instance =
InMemorySharedPreferencesAsync.empty();
});
/// http.Response(String) 默认按 Latin-1 编码,中文消息会直接抛
/// "Contains invalid characters" —— 统一用 UTF-8 字节构造。
http.Response jsonResponse(String body, [int statusCode = 200]) {
return http.Response.bytes(
utf8.encode(body),
statusCode,
headers: const {'content-type': 'application/json; charset=utf-8'},
);
}
String tokenBody({
required String accessToken,
required String refreshToken,
@@ -48,12 +41,12 @@ void main() {
ApiClient clientWith(
AuthController Function() auth, {
required MockClient httpClient,
required FakeHttpAdapter adapter,
}) {
final store = AuthSessionStore();
return ApiClient(
baseUrl: 'http://127.0.0.1:8081',
client: httpClient,
adapter: adapter,
accessTokenReader: () => auth().accessToken,
tokenRefresher: () => auth().refresh(),
onUnauthorized: () => auth().clear(),
@@ -61,16 +54,19 @@ void main() {
);
}
test('register stores session and exposes signed-in state', () async {
test('should store the session and expose a signed-in state when register succeeds', () async {
late AuthController auth;
final mock = MockClient((request) async {
expect(request.url.path, '/app/auth/register');
expect(request.headers['X-Device-Id'], isNotEmpty);
expect(request.headers.containsKey('Authorization'), isFalse);
return jsonResponse(tokenBody(accessToken: 'a1', refreshToken: 'r1'));
final adapter = FakeHttpAdapter((options) async {
expect(options.uri.path, '/app/auth/register');
expect(options.headers['X-Device-Id'], isNotEmpty);
expect(options.headers.containsKey('Authorization'), isFalse);
return FakeHttpResponse(tokenBody(accessToken: 'a1', refreshToken: 'r1'));
});
final store = AuthSessionStore();
auth = AuthController(AuthApi(clientWith(() => auth, httpClient: mock)), store);
auth = AuthController(
AuthApi(clientWith(() => auth, adapter: adapter)),
store,
);
expect(auth.isSignedIn, isFalse);
await auth.register(email: 'a@b.com', password: 'abcd1234');
@@ -81,72 +77,89 @@ void main() {
expect((await AuthSessionStore().read())?.refreshToken, 'r1');
});
test('401 triggers refresh once and retries with the new token', () async {
test('should refresh once and retry with the new token when a response carries code 401', () async {
var calls = 0;
late AuthController auth;
final mock = MockClient((request) async {
final adapter = FakeHttpAdapter((options) async {
calls++;
if (request.url.path == '/app/auth/refresh') {
return jsonResponse(tokenBody(accessToken: 'a2', refreshToken: 'r2'));
if (options.uri.path == '/app/auth/refresh') {
return FakeHttpResponse(tokenBody(accessToken: 'a2', refreshToken: 'r2'));
}
if (request.url.path != '/app/me') {
if (options.uri.path != '/app/me') {
// 注册等其它请求:直接发第一版令牌
return jsonResponse(tokenBody(accessToken: 'a1', refreshToken: 'r1'));
return FakeHttpResponse(tokenBody(accessToken: 'a1', refreshToken: 'r1'));
}
final token = request.headers['Authorization'];
final token = options.headers['Authorization'];
if (token == 'Bearer a1') {
return jsonResponse(
return FakeHttpResponse(
jsonEncode({'code': 401, 'message': '未登录或登录已过期', 'data': null}),
);
}
expect(token, 'Bearer a2');
return jsonResponse(jsonEncode({'code': 0, 'message': 'ok', 'data': {'hit': true}}));
return FakeHttpResponse(
jsonEncode({
'code': 0,
'message': 'ok',
'data': {'hit': true},
}),
);
});
final store = AuthSessionStore();
auth = AuthController(AuthApi(clientWith(() => auth, httpClient: mock)), store);
auth = AuthController(
AuthApi(clientWith(() => auth, adapter: adapter)),
store,
);
await auth.register(email: 'a@b.com', password: 'abcd1234');
calls = 0;
final api = clientWith(() => auth, httpClient: mock);
final api = clientWith(() => auth, adapter: adapter);
final data = await api.get('/app/me');
expect((data as Map)['hit'], isTrue);
expect(calls, 3); // 原请求(401) + 刷新 + 重试
expect(auth.accessToken, 'a2');
});
test('refresh failure clears the session (401 handling)', () async {
test('should clear the session when the refresh itself fails', () async {
late AuthController auth;
final mock = MockClient((request) async {
if (request.url.path == '/app/auth/refresh') {
return jsonResponse(jsonEncode({'code': 401, 'message': '登录已过期', 'data': null}));
final adapter = FakeHttpAdapter((options) async {
if (options.uri.path == '/app/auth/refresh') {
return FakeHttpResponse(
jsonEncode({'code': 401, 'message': '登录已过期', 'data': null}),
);
}
if (request.url.path == '/app/auth/register') {
return jsonResponse(tokenBody(accessToken: 'a1', refreshToken: 'r1'));
if (options.uri.path == '/app/auth/register') {
return FakeHttpResponse(tokenBody(accessToken: 'a1', refreshToken: 'r1'));
}
return jsonResponse(
return FakeHttpResponse(
jsonEncode({'code': 401, 'message': '未登录或登录已过期', 'data': null}),
);
});
final store = AuthSessionStore();
auth = AuthController(AuthApi(clientWith(() => auth, httpClient: mock)), store);
auth = AuthController(
AuthApi(clientWith(() => auth, adapter: adapter)),
store,
);
await auth.register(email: 'a@b.com', password: 'abcd1234');
final api = clientWith(() => auth, httpClient: mock);
final api = clientWith(() => auth, adapter: adapter);
await expectLater(api.get('/app/me'), throwsA(isA<ApiException>()));
expect(auth.isSignedIn, isFalse);
expect(await AuthSessionStore().read(), isNull);
});
test('signOut clears local session even if the server call fails', () async {
test('should clear the local session when sign out hits a server error', () async {
late AuthController auth;
final mock = MockClient((request) async {
if (request.url.path == '/app/auth/logout') {
return jsonResponse('{}', 500);
final adapter = FakeHttpAdapter((options) async {
if (options.uri.path == '/app/auth/logout') {
return FakeHttpResponse('{}', 500);
}
return jsonResponse(tokenBody(accessToken: 'a1', refreshToken: 'r1'));
return FakeHttpResponse(tokenBody(accessToken: 'a1', refreshToken: 'r1'));
});
final store = AuthSessionStore();
auth = AuthController(AuthApi(clientWith(() => auth, httpClient: mock)), store);
auth = AuthController(
AuthApi(clientWith(() => auth, adapter: adapter)),
store,
);
await auth.register(email: 'a@b.com', password: 'abcd1234');
await auth.signOut();