Skip to content

chore: fix bugs and add more tests #169

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 41 additions & 41 deletions lib/extensions/base_request.dart
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import 'dart:convert';
import 'dart:convert' show Encoding;

import 'package:http/http.dart';
import 'package:http_interceptor/extensions/multipart_request.dart';
import 'package:http_interceptor/extensions/request.dart';
import 'package:http_interceptor/extensions/streamed_request.dart';
import 'package:http_interceptor/http/http_methods.dart';

import './multipart_request.dart';
import './request.dart';
import './streamed_request.dart';

/// Extends [BaseRequest] to provide copied instances.
extension BaseRequestCopyWith on BaseRequest {
/// Creates a new instance of [BaseRequest] based of on `this`. It copies
Expand All @@ -18,7 +17,7 @@ extension BaseRequestCopyWith on BaseRequest {
/// instance.
///
/// [stream] are only copied if `this` is a [StreamedRequest] instance.
BaseRequest copyWith({
Future<BaseRequest> copyWith({
HttpMethod? method,
Uri? url,
Map<String, String>? headers,
Expand All @@ -33,39 +32,40 @@ extension BaseRequestCopyWith on BaseRequest {
List<MultipartFile>? files,
// StreamedRequest only properties.
Stream<List<int>>? stream,
}) =>
switch (this) {
Request req => req.copyWith(
method: method,
url: url,
headers: headers,
body: body,
encoding: encoding,
followRedirects: followRedirects,
maxRedirects: maxRedirects,
persistentConnection: persistentConnection,
),
StreamedRequest req => req.copyWith(
method: method,
url: url,
headers: headers,
stream: stream,
followRedirects: followRedirects,
maxRedirects: maxRedirects,
persistentConnection: persistentConnection,
),
MultipartRequest req => req.copyWith(
method: method,
url: url,
headers: headers,
fields: fields,
files: files,
followRedirects: followRedirects,
maxRedirects: maxRedirects,
persistentConnection: persistentConnection,
),
_ => throw UnsupportedError(
'Cannot copy unsupported type of request $runtimeType',
),
};
}) async {
return switch (this) {
Request req => req.copyWith(
method: method,
url: url,
headers: headers,
body: body,
encoding: encoding,
followRedirects: followRedirects,
maxRedirects: maxRedirects,
persistentConnection: persistentConnection,
),
StreamedRequest req => await req.copyWith(
method: method,
url: url,
headers: headers,
stream: stream,
followRedirects: followRedirects,
maxRedirects: maxRedirects,
persistentConnection: persistentConnection,
),
MultipartRequest req => req.copyWith(
method: method,
url: url,
headers: headers,
fields: fields,
files: files,
followRedirects: followRedirects,
maxRedirects: maxRedirects,
persistentConnection: persistentConnection,
),
_ => throw UnsupportedError(
'Cannot copy unsupported type of request $runtimeType',
),
};
}
}
5 changes: 2 additions & 3 deletions lib/extensions/base_response_io.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@ import 'dart:io';
import 'package:http/http.dart';
import 'package:http/io_client.dart';
import 'package:http_interceptor/extensions/io_streamed_response.dart';

import './response.dart';
import './streamed_response.dart';
import 'package:http_interceptor/extensions/response.dart';
import 'package:http_interceptor/extensions/streamed_response.dart';

// Extends [BaseRequest] to provide copied instances.
extension BaseResponseCopyWith on BaseResponse {
Expand Down
5 changes: 2 additions & 3 deletions lib/extensions/base_response_none.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import 'package:http/http.dart';

import './response.dart';
import './streamed_response.dart';
import 'package:http_interceptor/extensions/response.dart';
import 'package:http_interceptor/extensions/streamed_response.dart';

// Extends [BaseRequest] to provide copied instances.
extension BaseResponseCopyWith on BaseResponse {
Expand Down
2 changes: 1 addition & 1 deletion lib/extensions/io_streamed_response.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import 'dart:io';
import 'dart:io' show HttpClientResponse;

import 'package:http/http.dart';
import 'package:http/io_client.dart';
Expand Down
2 changes: 1 addition & 1 deletion lib/extensions/request.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import 'dart:convert';
import 'dart:convert' show Encoding;

import 'package:http/http.dart';
import 'package:http_interceptor/http/http_methods.dart';
Expand Down
34 changes: 14 additions & 20 deletions lib/extensions/streamed_request.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,34 +5,28 @@ import 'package:http_interceptor/http/http_methods.dart';
extension StreamedRequestCopyWith on StreamedRequest {
/// Creates a new instance of [StreamedRequest] based of on `this`. It copies
/// all the properties and overrides the ones sent via parameters.
StreamedRequest copyWith({
Future<StreamedRequest> copyWith({
HttpMethod? method,
Uri? url,
Map<String, String>? headers,
Stream<List<int>>? stream,
bool? followRedirects,
int? maxRedirects,
bool? persistentConnection,
}) {
// Create a new StreamedRequest with the same method and URL
final StreamedRequest clonedRequest =
StreamedRequest(method?.asString ?? this.method, url ?? this.url)
..headers.addAll(headers ?? this.headers);
}) async {
final StreamedRequest clonedRequest = StreamedRequest(
method?.toString() ?? this.method,
url ?? this.url,
)
..followRedirects = followRedirects ?? this.followRedirects
..maxRedirects = maxRedirects ?? this.maxRedirects
..persistentConnection = persistentConnection ?? this.persistentConnection
..headers.addAll(headers ?? this.headers);

// Use a broadcast stream to allow multiple listeners
final Stream<List<int>> broadcastStream =
stream?.asBroadcastStream() ?? finalize().asBroadcastStream();

// Pipe the broadcast stream into the cloned request's sink
broadcastStream.listen(
(List<int> data) => clonedRequest.sink.add(data),
onDone: () => clonedRequest.sink.close(),
);

this.persistentConnection =
persistentConnection ?? this.persistentConnection;
this.followRedirects = followRedirects ?? this.followRedirects;
this.maxRedirects = maxRedirects ?? this.maxRedirects;
await for (List<int> chunk in stream ?? finalize()) {
clonedRequest.sink.add(chunk);
}
clonedRequest.sink.close();

return clonedRequest;
}
Expand Down
9 changes: 4 additions & 5 deletions lib/http/intercepted_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,9 @@ import 'dart:typed_data';
import 'package:http/http.dart';
import 'package:http_interceptor/extensions/base_request.dart';
import 'package:http_interceptor/extensions/uri.dart';

import '../models/interceptor_contract.dart';
import '../models/retry_policy.dart';
import 'http_methods.dart';
import 'package:http_interceptor/http/http_methods.dart';
import 'package:http_interceptor/models/interceptor_contract.dart';
import 'package:http_interceptor/models/retry_policy.dart';

typedef TimeoutCallback = FutureOr<StreamedResponse> Function();

Expand Down Expand Up @@ -397,7 +396,7 @@ class InterceptedClient extends BaseClient {

/// This internal function intercepts the request.
Future<BaseRequest> _interceptRequest(BaseRequest request) async {
BaseRequest interceptedRequest = request.copyWith();
BaseRequest interceptedRequest = await request.copyWith();
for (InterceptorContract interceptor in interceptors) {
if (await interceptor.shouldInterceptRequest(
request: interceptedRequest,
Expand Down
66 changes: 64 additions & 2 deletions test/extensions/base_reponse_test.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import 'dart:convert';

import 'package:http/io_client.dart';
import 'package:http_interceptor/http_interceptor.dart';
import 'package:test/test.dart';

Expand All @@ -8,8 +11,8 @@ main() {
final BaseResponse baseResponse = Response("{'foo': 'bar'}", 200);

// Act
final copiedBaseRequest = baseResponse.copyWith();
final copied = copiedBaseRequest as Response;
final copiedBaseResponse = baseResponse.copyWith();
final copied = copiedBaseResponse as Response;

// Assert
final response = baseResponse as Response;
Expand All @@ -22,5 +25,64 @@ main() {
expect(
copied.persistentConnection, equals(response.persistentConnection));
});

test('IOStreamedResponse is copied from BaseResponse', () {
// Arrange
final testRequest = Request('GET', Uri.parse('https://example.com'));
final testHeaders = {'Content-Type': 'application/json'};
final testStream = Stream.value(utf8.encode('test data'));
final testStatusCode = 200;
final testContentLength = 9; // 'test data'.length
final testIsRedirect = false;
final testPersistentConnection = true;
final testReasonPhrase = 'OK';

final BaseResponse baseResponse = IOStreamedResponse(
testStream,
testStatusCode,
contentLength: testContentLength,
request: testRequest,
headers: testHeaders,
isRedirect: testIsRedirect,
persistentConnection: testPersistentConnection,
reasonPhrase: testReasonPhrase,
);

// Act
final copiedBaseResponse = baseResponse.copyWith();

// Assert
final copied = copiedBaseResponse as IOStreamedResponse;
final response = baseResponse as IOStreamedResponse;
expect(copied.hashCode, isNot(equals(response.hashCode)));
expect(copied.statusCode, equals(response.statusCode));
expect(copied.contentLength, equals(response.contentLength));
expect(copied.request, equals(response.request));
expect(copied.headers, equals(response.headers));
expect(copied.isRedirect, equals(response.isRedirect));
expect(
copied.persistentConnection, equals(response.persistentConnection));
expect(copied.reasonPhrase, equals(response.reasonPhrase));
});

test('throws UnsupportedError for unsupported response type', () {
// Arrange
final unsupportedResponse = _UnsupportedResponse();

// Act & Assert
expect(
() => unsupportedResponse.copyWith(),
throwsA(isA<UnsupportedError>().having(
(e) => e.message,
'message',
'Cannot copy unsupported type of response _UnsupportedResponse',
)),
);
});
});
}

// Custom response type that doesn't extend any of the supported types
class _UnsupportedResponse extends BaseResponse {
_UnsupportedResponse() : super(200);
}
56 changes: 54 additions & 2 deletions test/extensions/base_request_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ import 'package:test/test.dart';

main() {
group('BaseRequest.copyWith: ', () {
test('Request is copied from BaseRequest', () {
test('Request is copied from BaseRequest', () async {
// Arrange
final BaseRequest baseRequest =
Request("GET", Uri.https("www.google.com", "/helloworld"))
..body = jsonEncode(<String, String>{'some_param': 'some value'});
final copiedBaseRequest = baseRequest.copyWith();
final copiedBaseRequest = await baseRequest.copyWith();

// Act
final copied = copiedBaseRequest as Request;
Expand All @@ -27,5 +27,57 @@ main() {
expect(copied.maxRedirects, equals(request.maxRedirects));
expect(copied.persistentConnection, equals(request.persistentConnection));
});

test('MultipartRequest is copied from BaseRequest', () {
// Arrange
final testUrl = Uri.parse('https://example.com');
final testHeaders = {'Content-Type': 'multipart/form-data'};
final testFields = {'field1': 'value1', 'field2': 'value2'};

final MultipartRequest multipartRequest =
MultipartRequest('POST', testUrl)
..headers.addAll(testHeaders)
..fields.addAll(testFields);

// Add a test file to the request
final testFileBytes = utf8.encode('test file content');
final testFile = MultipartFile.fromBytes(
'file',
testFileBytes,
filename: 'test.txt',
);
multipartRequest.files.add(testFile);

// Act
final copied = multipartRequest.copyWith();

// Assert
expect(copied.hashCode, isNot(equals(multipartRequest.hashCode)));
expect(copied.url, equals(multipartRequest.url));
expect(copied.method, equals(multipartRequest.method));
expect(copied.headers, equals(multipartRequest.headers));
expect(copied.fields, equals(multipartRequest.fields));
expect(copied.files.length, equals(multipartRequest.files.length));
});

test('throws UnsupportedError for unsupported request type', () {
// Arrange
final unsupportedRequest = _UnsupportedRequest();

// Act & Assert
expect(
() => unsupportedRequest.copyWith(),
throwsA(isA<UnsupportedError>().having(
(e) => e.message,
'message',
'Cannot copy unsupported type of request _UnsupportedRequest',
)),
);
});
});
}

// Custom request type that doesn't extend any of the supported types
class _UnsupportedRequest extends BaseRequest {
_UnsupportedRequest() : super('GET', Uri.parse('https://example.com'));
}
Loading
Loading