示例工程 ch13-network

ch13-network/test/posts_api_test.dart

dart · 10 KB

import 'dart:async';
import 'dart:convert';
import 'dart:io';
 
import 'package:ch13_network/src/api_exception.dart';
import 'package:ch13_network/src/post.dart';
import 'package:ch13_network/src/posts_api.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
 
/// 一段合法的 /posts 响应。
String postsJson(int count) => jsonEncode(<Map<String, Object?>>[
      for (var i = 1; i <= count; i++)
        <String, Object?>{
          'id': i,
          'userId': 1,
          'title': 'title $i',
          'body': 'body $i',
        },
    ]);
 
PostsApi apiWith(http.Client client, {int maxRetries = 2, Duration? timeout}) => PostsApi(
      client: client,
      baseUrl: 'https://example.test',
      maxRetries: maxRetries,
      retryDelay: const Duration(milliseconds: 1),
      timeout: timeout ?? const Duration(seconds: 2),
    );
 
void main() {
  group('错误分类与文案', () {
    test('userMessage 把异常翻译成用户能看懂的话', () {
      expect(const NetworkException('x').userMessage, contains('网络'));
      expect(const ApiTimeoutException('x').userMessage, contains('超时'));
      expect(const HttpStatusException(401, '').userMessage, contains('登录'));
      expect(const HttpStatusException(404, '').userMessage, contains('不存在'));
      expect(const HttpStatusException(500, '').userMessage, contains('服务器'));
      expect(const ParseException('x').userMessage, contains('数据格式'));
    });
 
    test('可重试判定:5xx 与 429 重试,4xx 不重试', () {
      expect(const HttpStatusException(500, '').isRetryable, isTrue);
      expect(const HttpStatusException(429, '').isRetryable, isTrue);
      expect(const HttpStatusException(404, '').isRetryable, isFalse);
      expect(const HttpStatusException(400, '').isRetryable, isFalse);
    });
  });
 
  group('http:成功路径', () {
    test('fetchPosts 解析数组并构造模型', () async {
      var calls = 0;
      final MockClient client = MockClient((http.Request request) async {
        calls++;
        expect(request.url.path, '/posts');
        expect(request.url.queryParameters['_limit'], '2');
        expect(request.headers['Accept'], 'application/json');
        return http.Response(postsJson(2), 200, headers: <String, String>{
          'content-type': 'application/json; charset=utf-8',
        });
      });
 
      final List<Post> posts = await apiWith(client).fetchPosts(limit: 2);
      expect(posts, hasLength(2));
      expect(posts.first.title, 'title 1');
      expect(posts.first.id, 1);
      expect(calls, 1);
    });
 
    test('fetchPost 解析单个对象', () async {
      final MockClient client = MockClient((http.Request request) async {
        expect(request.url.path, '/posts/7');
        return http.Response(
          jsonEncode(<String, Object?>{'id': 7, 'userId': 2, 'title': 't7', 'body': 'b7'}),
          200,
        );
      });
 
      final Post post = await apiWith(client).fetchPost(7);
      expect(post.id, 7);
      expect(post.userId, 2);
    });
 
    test('createPost 发送 JSON 并解析返回 id', () async {
      final MockClient client = MockClient((http.Request request) async {
        expect(request.method, 'POST');
        expect(request.headers['Content-Type'], contains('application/json'));
        final Map<String, Object?> sent =
            jsonDecode(request.body) as Map<String, Object?>;
        expect(sent['title'], 'hello');
        return http.Response(jsonEncode(<String, Object?>{'id': 101}), 201);
      });
 
      final int id = await apiWith(client).createPost(title: 'hello', body: 'world');
      expect(id, 101);
    });
 
    test('PUT 替换资源', () async {
      final MockClient client = MockClient((http.Request request) async {
        expect(request.method, 'PUT');
        expect(request.url.path, '/posts/7');
        final Map<String, Object?> sent = jsonDecode(request.body) as Map<String, Object?>;
        expect(sent['title'], 'new title');
        return http.Response(
          jsonEncode(<String, Object?>{'id': 7, 'userId': 1, 'title': 'new title', 'body': 'b'}),
          200,
        );
      });
 
      final Post post = await apiWith(client).replacePost(id: 7, title: 'new title', body: 'b');
      expect(post.id, 7);
      expect(post.title, 'new title');
    });
 
    test('DELETE 删除资源', () async {
      var calls = 0;
      final MockClient client = MockClient((http.Request request) async {
        calls++;
        expect(request.method, 'DELETE');
        expect(request.url.path, '/posts/9');
        return http.Response('', 204);
      });
 
      await apiWith(client).deletePost(9);
      expect(calls, 1);
    });
 
    test('UTF-8 中文按 bodyBytes 解码,不受错误 charset 影响', () async {
      final MockClient client = MockClient((http.Request request) async {
        // 故意声明一个错误的 charset,验证我们用 utf8.decode(bodyBytes)
        return http.Response.bytes(
          utf8.encode(jsonEncode(<String, Object?>{'id': 1, 'title': '中文标题', 'body': ''})),
          200,
          headers: <String, String>{'content-type': 'application/json; charset=latin1'},
        );
      });
 
      final Post post = await apiWith(client).fetchPost(1);
      expect(post.title, '中文标题');
    });
  });
 
  group('http:失败与重试', () {
    test('5xx 会重试,最终成功', () async {
      var calls = 0;
      final MockClient client = MockClient((http.Request request) async {
        calls++;
        if (calls < 3) return http.Response('boom', 500);
        return http.Response(postsJson(1), 200);
      });
 
      final List<Post> posts = await apiWith(client).fetchPosts();
      expect(posts, hasLength(1));
      expect(calls, 3); // 第一次 + 两次重试
    });
 
    test('重试次数用尽后抛 HttpStatusException', () async {
      var calls = 0;
      final MockClient client = MockClient((http.Request request) async {
        calls++;
        return http.Response('boom', 503);
      });
 
      await expectLater(
        apiWith(client, maxRetries: 1).fetchPosts(),
        throwsA(isA<HttpStatusException>().having((HttpStatusException e) => e.statusCode, 'status', 503)),
      );
      expect(calls, 2); // 1 次 + maxRetries(1)
    });
 
    test('404 不重试,直接抛', () async {
      var calls = 0;
      final MockClient client = MockClient((http.Request request) async {
        calls++;
        return http.Response('not found', 404);
      });
 
      await expectLater(
        apiWith(client).fetchPosts(),
        throwsA(isA<HttpStatusException>().having((HttpStatusException e) => e.statusCode, 'status', 404)),
      );
      expect(calls, 1);
    });
 
    test('连不上(SocketException)→ NetworkException', () async {
      final MockClient client = MockClient((http.Request request) async {
        throw const SocketException('Connection refused');
      });
 
      await expectLater(
        apiWith(client, maxRetries: 0).fetchPost(1),
        throwsA(isA<NetworkException>()),
      );
    });
 
    test('超时 → ApiTimeoutException', () async {
      final MockClient client = MockClient((http.Request request) async {
        await Future<void>.delayed(const Duration(milliseconds: 200));
        return http.Response(postsJson(1), 200);
      });
 
      await expectLater(
        apiWith(client, maxRetries: 0, timeout: const Duration(milliseconds: 20)).fetchPosts(),
        throwsA(isA<ApiTimeoutException>()),
      );
    });
 
    test('非法 JSON → ParseException', () async {
      final MockClient client = MockClient((http.Request request) async {
        return http.Response('<html>502 Bad Gateway</html>', 200);
      });
 
      await expectLater(
        apiWith(client, maxRetries: 0).fetchPosts(),
        throwsA(isA<ParseException>()),
      );
    });
 
    test('结构不对(顶层是对象)→ ParseException', () async {
      final MockClient client = MockClient((http.Request request) async {
        return http.Response('{"id":1}', 200);
      });
 
      await expectLater(
        apiWith(client).fetchPosts(),
        throwsA(isA<ParseException>()),
      );
    });
 
    test('单条记录字段类型错误 → ParseException 带下标', () async {
      final MockClient client = MockClient((http.Request request) async {
        return http.Response('[{"id": "not-a-number"}]', 200);
      });
 
      await expectLater(
        apiWith(client).fetchPosts(),
        throwsA(isA<ParseException>()
            .having((ParseException e) => e.message, 'message', contains('第 0 条'))),
      );
    });
  });
 
  group('流式下载', () {
    test('逐块回调进度,total 来自 content-length', () async {
      final _ChunkedClient client = _ChunkedClient(<List<int>>[
        utf8.encode('hello '),
        utf8.encode('dart '),
        utf8.encode('stream'),
      ], totalBytes: 17);
 
      final List<String> progress = <String>[];
      final List<int> bytes = await apiWith(client).download(
        Uri.parse('https://example.test/big'),
        onProgress: (int received, int? total) => progress.add('$received/$total'),
      );
 
      expect(utf8.decode(bytes), 'hello dart stream');
      expect(progress, <String>['6/17', '11/17', '17/17']);
    });
 
    test('可以提前停止消费(模拟取消)', () async {
      final _ChunkedClient client = _ChunkedClient(<List<int>>[
        utf8.encode('aaaa'),
        utf8.encode('bbbb'),
        utf8.encode('cccc'),
      ], totalBytes: 12);
 
      final List<int> bytes = await apiWith(client).download(
        Uri.parse('https://example.test/big'),
        cancelAfterBytes: 4,
      );
      expect(utf8.decode(bytes), 'aaaa');
    });
 
    test('非 2xx 抛 HttpStatusException', () async {
      final _ChunkedClient client = _ChunkedClient(<List<int>>[], statusCode: 500);
      await expectLater(
        apiWith(client).download(Uri.parse('https://example.test/x')),
        throwsA(isA<HttpStatusException>()),
      );
    });
  });
}
 
/// 一个会分块返回的假客户端:`MockClient` 只支持整体响应,测进度不够用。
class _ChunkedClient extends http.BaseClient {
  _ChunkedClient(this.chunks, {this.totalBytes, this.statusCode = 200});
 
  final List<List<int>> chunks;
  final int? totalBytes;
  final int statusCode;
 
  @override
  Future<http.StreamedResponse> send(http.BaseRequest request) async {
    return http.StreamedResponse(
      Stream<List<int>>.fromIterable(chunks),
      statusCode,
      contentLength: totalBytes,
      request: request,
    );
  }
}