88 lines
2.3 KiB
Dart
88 lines
2.3 KiB
Dart
import 'dart:async';
|
|
import 'dart:convert';
|
|
|
|
import 'package:dio/dio.dart';
|
|
import 'package:flutter_test/flutter_test.dart';
|
|
import 'package:yx_tracking_flutter/src/config/analytics_config.dart';
|
|
import 'package:yx_tracking_flutter/src/network/http_client.dart';
|
|
|
|
class _FakeAdapter implements HttpClientAdapter {
|
|
RequestOptions? lastOptions;
|
|
Object? lastData;
|
|
|
|
@override
|
|
void close({bool force = false}) {}
|
|
|
|
@override
|
|
Future<ResponseBody> fetch(
|
|
RequestOptions options,
|
|
Stream<List<int>>? requestStream,
|
|
Future<void>? cancelFuture,
|
|
) async {
|
|
lastOptions = options;
|
|
lastData = options.data;
|
|
return ResponseBody.fromString(
|
|
jsonEncode(<String, Object?>{'ok': true}),
|
|
200,
|
|
headers: <String, List<String>>{
|
|
Headers.contentTypeHeader: <String>[Headers.jsonContentType],
|
|
},
|
|
);
|
|
}
|
|
}
|
|
|
|
AnalyticsConfig _config(String baseUrl) {
|
|
return AnalyticsConfig(
|
|
systemCode: 'SYS',
|
|
endpointBaseUrl: baseUrl,
|
|
);
|
|
}
|
|
|
|
void main() {
|
|
group('HttpClient', () {
|
|
test('会规范化 baseUrl 并使用自定义 adapter', () async {
|
|
final adapter = _FakeAdapter();
|
|
final client = HttpClient(
|
|
_config('https://example.com/'),
|
|
httpClientAdapter: adapter,
|
|
);
|
|
|
|
expect(client.dio.options.baseUrl, 'https://example.com');
|
|
|
|
final response = await client.get<Map<String, dynamic>>('/ping');
|
|
|
|
expect(response.statusCode, 200);
|
|
expect(adapter.lastOptions?.path, '/ping');
|
|
});
|
|
|
|
test('headers 为空时不会创建 Options', () async {
|
|
final adapter = _FakeAdapter();
|
|
final client = HttpClient(
|
|
_config('https://example.com'),
|
|
httpClientAdapter: adapter,
|
|
);
|
|
|
|
await client.post<Object?>('/no-headers', data: <String, Object?>{});
|
|
|
|
expect(adapter.lastOptions?.headers, isNot(contains('x-test')));
|
|
});
|
|
|
|
test('会把 headers 透传到请求', () async {
|
|
final adapter = _FakeAdapter();
|
|
final client = HttpClient(
|
|
_config('https://example.com'),
|
|
httpClientAdapter: adapter,
|
|
);
|
|
|
|
await client.post<Object?>(
|
|
'/with-headers',
|
|
data: <String, Object?>{'a': 1},
|
|
headers: <String, Object?>{'x-test': '1'},
|
|
);
|
|
|
|
expect(adapter.lastOptions?.headers['x-test'], '1');
|
|
expect(adapter.lastData, <String, Object?>{'a': 1});
|
|
});
|
|
});
|
|
}
|