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

+80 -79
View File
@@ -1,35 +1,52 @@
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:dio/dio.dart';
import '../../config/app_config.dart';
import 'api_exception.dart';
import 'api_interceptors.dart';
/// 接口异常:code 为后端业务码,message 可直接展示。
class ApiException implements Exception {
const ApiException(this.code, this.message);
final int code;
final String message;
@override
String toString() => 'ApiException($code, $message)';
}
/// `ApiException` 从这里也能拿到:历史调用方一律 `import 'api_client.dart'`,不必改 import。
export 'api_exception.dart';
/// 后端统一响应壳 `{code, message, data}` 的解析入口。
///
/// 职责:
/// - 用 dio 发请求(`AuthHeaderInterceptor` 注入令牌与设备号,`EnvelopeInterceptor` 解包与映射错误码);
/// - 编排「401 → 刷新令牌 → 重发一次」——**刻意不放在拦截器里重发**,因为 dio 的排队拦截器
/// 在回调里再发起请求会把自己排到队尾,造成自锁。
class ApiClient {
ApiClient({
String? baseUrl,
http.Client? client,
HttpClientAdapter? adapter,
this.accessTokenReader,
this.tokenRefresher,
this.onUnauthorized,
this.deviceIdReader,
})
: baseUrl = baseUrl ?? AppConfig.apiBaseUrl,
_client = client ?? http.Client();
}) : baseUrl = baseUrl ?? AppConfig.apiBaseUrl {
_dio = Dio(
BaseOptions(
baseUrl: this.baseUrl,
connectTimeout: AppConfig.requestTimeout,
receiveTimeout: AppConfig.requestTimeout,
// 拿原始字节自己解码:后端消息是 UTF-8,且"不是 JSON 的响应体"要能被识别出来
responseType: ResponseType.bytes,
// 非 2xx 不抛异常:业务结果由响应体里的 code 表达(与旧实现一致)
validateStatus: (_) => true,
),
);
_dio.interceptors.addAll([
AuthHeaderInterceptor(
accessTokenReader: accessTokenReader,
deviceIdReader: deviceIdReader,
),
const EnvelopeInterceptor(),
]);
if (adapter != null) {
_dio.httpClientAdapter = adapter;
}
}
final String baseUrl;
final http.Client _client;
late final Dio _dio;
/// 取当前 access token(未登录返回 null)
final String? Function()? accessTokenReader;
@@ -44,7 +61,7 @@ class ApiClient {
final Future<String> Function()? deviceIdReader;
Future<Object?> get(String path, {Map<String, String>? query}) {
return _send('GET', path, query: query);
return _request('GET', path, query: query);
}
Future<Object?> post(
@@ -53,10 +70,16 @@ class ApiClient {
Map<String, String>? query,
bool skipAuthRetry = false,
}) {
return _send('POST', path, body: body, query: query, skipAuthRetry: skipAuthRetry);
return _request(
'POST',
path,
body: body,
query: query,
skipAuthRetry: skipAuthRetry,
);
}
Future<Object?> _send(
Future<Object?> _request(
String method,
String path, {
Object? body,
@@ -64,67 +87,45 @@ class ApiClient {
bool retried = false,
bool skipAuthRetry = false,
}) async {
final uri = Uri.parse(
'$baseUrl$path',
).replace(queryParameters: query?.isEmpty ?? true ? null : query);
final headers = await _headers(withBody: body != null);
final response = await (method == 'GET'
? _client.get(uri, headers: headers)
: _client.post(
uri,
headers: headers,
body: body == null ? null : jsonEncode(body),
))
.timeout(AppConfig.requestTimeout);
Map<String, dynamic> shell = const {};
final disableAuthRetry = skipAuthRetry || tokenRefresher == null;
try {
shell = (jsonDecode(utf8.decode(response.bodyBytes)) as Map)
.cast<String, dynamic>();
} catch (_) {
shell = const {};
}
final code = shell['code'] as int? ?? -1;
// 令牌过期:刷新一次再重试原请求;刷新失败就清登录态并抛给调用方
if (code == 401 && !retried && !skipAuthRetry && tokenRefresher != null) {
final refreshed = await tokenRefresher!.call();
if (refreshed) {
return _send(
method,
path,
body: body,
query: query,
retried: true,
skipAuthRetry: skipAuthRetry,
);
final response = await _dio.request<Object?>(
path,
data: body,
queryParameters: (query?.isEmpty ?? true) ? null : query,
options: Options(
method: method,
contentType: body == null ? null : Headers.jsonContentType,
extra: {
ApiRequestFlags.disableAuthRetry: disableAuthRetry,
ApiRequestFlags.retried: retried,
},
),
);
return response.data;
} on DioException catch (error) {
final cause = error.error;
if (cause is TokenExpiredException) {
final refreshed = await tokenRefresher?.call() ?? false;
if (refreshed) {
return _request(
method,
path,
body: body,
query: query,
retried: true,
skipAuthRetry: skipAuthRetry,
);
}
onUnauthorized?.call();
throw ApiException(401, cause.message ?? '登录已过期');
}
onUnauthorized?.call();
throw ApiException(401, shell['message'] as String? ?? '登录已过期');
if (cause is ApiException) {
throw cause;
}
rethrow;
}
if (code == -1) {
throw ApiException(response.statusCode, 'HTTP ${response.statusCode}');
}
if (code != 0) {
throw ApiException(code, shell['message'] as String? ?? '请求失败');
}
return shell['data'];
}
Future<Map<String, String>> _headers({required bool withBody}) async {
final headers = <String, String>{'Accept': 'application/json'};
if (withBody) headers['Content-Type'] = 'application/json';
final token = accessTokenReader?.call();
if (token != null && token.isNotEmpty) {
headers['Authorization'] = 'Bearer $token';
}
final deviceId = await deviceIdReader?.call();
if (deviceId != null && deviceId.isNotEmpty) {
headers['X-Device-Id'] = deviceId;
}
return headers;
}
void close() => _client.close();
void close() => _dio.close(force: true);
}
+15
View File
@@ -0,0 +1,15 @@
// Author: fruit.com.cn
/// 接口异常:code 为后端业务码,message 可直接展示。
///
/// 单独成文件是为了让 [ApiClient] 与拦截器都能引用它而不互相 import
/// (`api_client.dart` 会 `export` 本文件,历史调用方继续 `import 'api_client.dart'` 即可拿到它)。
class ApiException implements Exception {
const ApiException(this.code, this.message);
final int code;
final String message;
@override
String toString() => 'ApiException($code, $message)';
}
+133
View File
@@ -0,0 +1,133 @@
// Author: fruit.com.cn
import 'dart:convert';
import 'package:dio/dio.dart';
import 'api_exception.dart';
/// 请求级开关:放在 `RequestOptions.extra` 里,由 `ApiClient` 写入、拦截器读取。
class ApiRequestFlags {
const ApiRequestFlags._();
/// 本次请求不参与「401 → 刷新 → 重试」:刷新令牌自身、登出,以及没有刷新回调时。
static const String disableAuthRetry = 'app.auth.disableRetry';
/// 本次请求已经是刷新后的重试,见到它就不再刷新,避免无限循环。
static const String retried = 'app.auth.retried';
}
/// 内部信号:响应体里 `code == 401`,应当由 `ApiClient` 刷新令牌后重发一次。
///
/// 只在本层流转,不会漏给调用方 —— 调用方拿到的始终是 `ApiException`。
class TokenExpiredException implements Exception {
const TokenExpiredException(this.message);
/// 后端返回的提示语(可能为空),用于刷新失败时拼 `ApiException` 的消息。
final String? message;
}
/// 注入鉴权与设备标识请求头。
///
/// 每个请求都重新取一次令牌,所以刷新成功后重发的那次会自动带上新令牌。
class AuthHeaderInterceptor extends Interceptor {
AuthHeaderInterceptor({this.accessTokenReader, this.deviceIdReader});
/// 当前 access token;未登录返回 null 或空串。
final String? Function()? accessTokenReader;
/// 设备号(`X-Device-Id`):注册风控、下载绑定都用它。
final Future<String> Function()? deviceIdReader;
@override
Future<void> onRequest(
RequestOptions options,
RequestInterceptorHandler handler,
) async {
options.headers['Accept'] = 'application/json';
final token = accessTokenReader?.call();
if (token != null && token.isNotEmpty) {
options.headers['Authorization'] = 'Bearer $token';
}
final deviceId = await deviceIdReader?.call();
if (deviceId != null && deviceId.isNotEmpty) {
options.headers['X-Device-Id'] = deviceId;
}
handler.next(options);
}
}
/// 解包后端统一响应壳 `{code,message,data}`,并把业务码映射成异常。
///
/// 判定口径与旧的 `http` 实现逐条对齐:
/// - body 不是合法 JSON → 视为 `code = -1`,抛 `ApiException(状态码, 'HTTP <状态码>')`
/// - `code != 0` → 抛 `ApiException(code, message ?? '请求失败')`
/// - `code == 401` 且允许刷新 → 抛 [TokenExpiredException] 作为信号(由 `ApiClient` 刷新后重发)
class EnvelopeInterceptor extends Interceptor {
const EnvelopeInterceptor();
@override
void onResponse(
Response<dynamic> response,
ResponseInterceptorHandler handler,
) {
final options = response.requestOptions;
final shell = _decodeShell(response.data);
final code = shell['code'] as int? ?? -1;
final message = shell['message'] as String?;
final retried = options.extra[ApiRequestFlags.retried] == true;
final disableRetry =
options.extra[ApiRequestFlags.disableAuthRetry] == true;
if (code == 401 && !retried && !disableRetry) {
return handler.reject(
DioException(
requestOptions: options,
response: response,
type: DioExceptionType.badResponse,
error: TokenExpiredException(message),
),
true,
);
}
if (code == -1) {
final status = response.statusCode ?? -1;
return handler.reject(
DioException(
requestOptions: options,
response: response,
type: DioExceptionType.badResponse,
error: ApiException(status, 'HTTP $status'),
),
true,
);
}
if (code != 0) {
return handler.reject(
DioException(
requestOptions: options,
response: response,
type: DioExceptionType.badResponse,
error: ApiException(code, message ?? '请求失败'),
),
true,
);
}
response.data = shell['data'];
handler.next(response);
}
/// 统一按 UTF-8 解码:后端的中文提示语不能因为缺 charset 而乱码。
Map<String, dynamic> _decodeShell(Object? body) {
final text = switch (body) {
List<int> bytes => utf8.decode(bytes, allowMalformed: true),
String text => text,
_ => '',
};
try {
return (jsonDecode(text) as Map).cast<String, dynamic>();
} catch (_) {
return const {};
}
}
}
+24 -8
View File
@@ -89,6 +89,22 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.0.9"
dio:
dependency: "direct main"
description:
name: dio
sha256: "852ec3b48cc431ac04fff978413c541502b67ffc3e26921e74e3d994694192c1"
url: "https://pub.flutter-io.cn"
source: hosted
version: "5.11.1"
dio_web_adapter:
dependency: transitive
description:
name: dio_web_adapter
sha256: "3a1b2cd7be71086f38504956e3ebcd2837288d231ff454bafa78021244102bfc"
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.2.2"
fake_async:
dependency: transitive
description:
@@ -157,14 +173,6 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.15.7"
http:
dependency: "direct main"
description:
name: http
sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412"
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.6.0"
http_parser:
dependency: transitive
description:
@@ -253,6 +261,14 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.19.0"
mime:
dependency: transitive
description:
name: mime
sha256: bd47de35f07e27267e69c8c8b22edf9473bfee170a60d60fcc93730c5144b7f6
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.1.0"
nested:
dependency: transitive
description:
+2 -2
View File
@@ -34,8 +34,8 @@ dependencies:
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.8
# 只用官方 http:纯 Dart、体积小;不引 dio/代码生成/图片缓存,控制包体积
http: ^1.2.2
# 网络层用 dio(统一拦截器/超时/错误映射);纯 Dart 无原生插件,仍然不引代码生成与图片缓存库
dio: ^5.7.0
provider: ^6.1.5+1
video_player: ^2.14.0
shared_preferences: ^2.5.5
+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();
+6 -6
View File
@@ -1,7 +1,5 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:provider/provider.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';
@@ -13,6 +11,8 @@ import 'package:nontonki/core/data/services/auth_session_store.dart';
import 'package:nontonki/l10n/app_localizations.dart';
import 'package:nontonki/pages/auth/auth_view.dart';
import '../support/fake_http_adapter.dart';
/// 登录/注册页的可读证据:校验提示 + 登录/注册切换 + 未登录时不会去发请求。
void main() {
setUp(() {
@@ -26,7 +26,7 @@ void main() {
// 这个测试不联网:请求一律 500,正好用于验证"本地校验没过就不发请求"
ApiClient(
baseUrl: 'http://127.0.0.1:1',
client: MockClient((_) async => http.Response('{}', 500)),
adapter: FakeHttpAdapter((_) async => FakeHttpResponse('{}', 500)),
),
),
AuthSessionStore(),
@@ -45,7 +45,7 @@ void main() {
await tester.pumpAndSettle();
}
testWidgets('empty form shows the email error and stays on the page', (tester) async {
testWidgets('should show the email error and stay on the page when the form is empty', (tester) async {
await pumpAuthPage(tester);
expect(find.text('Welcome back'), findsOneWidget);
@@ -57,7 +57,7 @@ void main() {
expect(find.text('Welcome back'), findsOneWidget);
});
testWidgets('weak password is rejected locally', (tester) async {
testWidgets('should reject a weak password locally when only letters are typed', (tester) async {
await pumpAuthPage(tester);
await tester.enterText(find.byType(TextField).first, 'a@b.com');
@@ -68,7 +68,7 @@ void main() {
expect(find.text('Password needs both letters and numbers'), findsOneWidget);
});
testWidgets('switch link flips between sign in and sign up', (tester) async {
testWidgets('should flip between sign in and sign up when the switch link is tapped', (tester) async {
await pumpAuthPage(tester);
expect(find.text('Welcome back'), findsOneWidget);
+107
View File
@@ -0,0 +1,107 @@
// Author: fruit.com.cn
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:nontonki/core/data/remote/api_client.dart';
import '../support/fake_http_adapter.dart';
/// 网络层换 dio 之后,把「对外契约」逐条钉住:解包、错误码映射、请求头、查询参数、跳过重试。
void main() {
String envelope(Object? data, {int code = 0, String message = 'ok'}) {
return jsonEncode({'code': code, 'message': message, 'data': data});
}
test('should return the data field when the envelope code is zero', () async {
final adapter = FakeHttpAdapter(
(_) async => FakeHttpResponse(envelope({'id': 7})),
);
final client = ApiClient(baseUrl: 'http://127.0.0.1:8081', adapter: adapter);
final data = await client.get('/app/dramas/7');
expect((data as Map)['id'], 7);
});
test('should throw an ApiException carrying the server message when the envelope code is not zero', () async {
final adapter = FakeHttpAdapter(
(_) async => FakeHttpResponse(
envelope(null, code: 40001, message: '邮箱格式不正确'),
),
);
final client = ApiClient(baseUrl: 'http://127.0.0.1:8081', adapter: adapter);
await expectLater(
client.post('/app/auth/register', body: {'target': 'bad'}),
throwsA(
isA<ApiException>()
.having((e) => e.code, 'code', 40001)
.having((e) => e.message, 'message', '邮箱格式不正确'),
),
);
});
test('should map a body without envelope to an ApiException carrying the http status', () async {
final adapter = FakeHttpAdapter((_) async => FakeHttpResponse('oops', 502));
final client = ApiClient(baseUrl: 'http://127.0.0.1:8081', adapter: adapter);
await expectLater(
client.get('/app/home/feed'),
throwsA(
isA<ApiException>().having((e) => e.code, 'code', 502),
),
);
});
test('should send the bearer token and the device header when both are available', () async {
final adapter = FakeHttpAdapter((_) async => FakeHttpResponse(envelope(null)));
final client = ApiClient(
baseUrl: 'http://127.0.0.1:8081',
adapter: adapter,
accessTokenReader: () => 'token-1',
deviceIdReader: () async => 'device-9',
);
await client.get('/app/me');
final request = adapter.requests.single;
expect(request.headers['Authorization'], 'Bearer token-1');
expect(request.headers['X-Device-Id'], 'device-9');
expect(request.headers['Accept'], 'application/json');
});
test('should put the query map into the request uri', () async {
final adapter = FakeHttpAdapter((_) async => FakeHttpResponse(envelope(null)));
final client = ApiClient(baseUrl: 'http://127.0.0.1:8081', adapter: adapter);
await client.get('/app/search', query: {'keyword': '短剧', 'page': '2'});
final uri = adapter.requests.single.uri;
expect(uri.path, '/app/search');
expect(uri.queryParameters['keyword'], '短剧');
expect(uri.queryParameters['page'], '2');
});
test('should not refresh the token when the call opts out of auth retry', () async {
var refreshed = false;
final adapter = FakeHttpAdapter(
(_) async => FakeHttpResponse(envelope(null, code: 401, message: '登录已过期')),
);
final client = ApiClient(
baseUrl: 'http://127.0.0.1:8081',
adapter: adapter,
tokenRefresher: () async {
refreshed = true;
return true;
},
);
await expectLater(
client.post('/app/auth/refresh', body: {'refreshToken': 'r1'}, skipAuthRetry: true),
throwsA(isA<ApiException>().having((e) => e.code, 'code', 401)),
);
expect(refreshed, isFalse);
expect(adapter.requests, hasLength(1));
});
}
+34
View File
@@ -0,0 +1,34 @@
// Author: fruit.com.cn
import 'package:flutter_test/flutter_test.dart';
import 'package:nontonki/core/data/remote/api_client.dart';
import 'package:nontonki/core/data/remote/auth_api.dart';
/// 联调测试:直连本机客户端接口服务(8081)验证 **POST + JSON body + 错误码映射**。
///
/// 特意用"不存在的邮箱"登录:既能走完整的 POST 链路,又不会在库里留下测试数据。
/// 服务没启动时自动跳过,不影响日常 `flutter test`。
void main() {
final client = ApiClient(baseUrl: 'http://127.0.0.1:8081');
final api = AuthApi(client);
tearDownAll(client.close);
test('should surface a business error when signing in with an unknown email', () async {
try {
await api.login(
email: 'no-such-user-for-dio-check@example.com',
password: 'abcd1234',
deviceId: 'dio-check-device',
);
fail('不存在的邮箱不应该登录成功');
} on ApiException catch (error) {
// 关键点:错误码来自响应体(不是 HTTP 状态码),说明统一解包生效
expect(error.code, isNot(0));
expect(error.message, isNotEmpty);
} catch (_) {
markTestSkipped('客户端接口服务未启动,已跳过联调测试');
}
});
}
+46
View File
@@ -0,0 +1,46 @@
// Author: fruit.com.cn
import 'dart:convert';
import 'dart:typed_data';
import 'package:dio/dio.dart';
/// 假响应:[body] 会按 UTF-8 编码成字节,[statusCode] 默认 200。
class FakeHttpResponse {
FakeHttpResponse(this.body, [this.statusCode = 200]);
final String body;
final int statusCode;
}
/// dio 的测试替身:把请求交给回调处理,全程不联网。
///
/// 顺带记录每个收到的请求,测试可以直接断言"发了几次、带了什么头"。
class FakeHttpAdapter implements HttpClientAdapter {
FakeHttpAdapter(this.handler);
final Future<FakeHttpResponse> Function(RequestOptions options) handler;
/// 按顺序记录收到的请求,用于断言请求次数与请求头。
final List<RequestOptions> requests = [];
@override
Future<ResponseBody> fetch(
RequestOptions options,
Stream<Uint8List>? requestStream,
Future<void>? cancelFuture,
) async {
requests.add(options);
final response = await handler(options);
return ResponseBody.fromBytes(
utf8.encode(response.body),
response.statusCode,
headers: const {
'content-type': ['application/json; charset=utf-8'],
},
);
}
@override
void close({bool force = false}) {}
}