Skip to content
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

Custom Header and Response Status Check #18

Merged
merged 7 commits into from
Jan 11, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
18 changes: 16 additions & 2 deletions lib/src/internet_check_option.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
part of internet_connection_checker_plus;

typedef ResponseStatusFn = bool Function(http.Response response);

OutdatedGuy marked this conversation as resolved.
Show resolved Hide resolved
/// Options for checking the internet connectivity to an address.
///
/// This class provides a way to specify options for checking the connectivity
Expand Down Expand Up @@ -27,12 +29,17 @@ class InternetCheckOption {
/// final options = InternetCheckOption(
/// uri: Uri.parse('https://example.com'),
/// timeout: Duration(seconds: 5),
/// headers: {
/// 'Authorization': 'Bearer token',
/// },
/// );
/// ```
InternetCheckOption({
required this.uri,
this.timeout = const Duration(seconds: 3),
});
Map<String, String>? headers,
this.responseStatusFn,
}) : headers = headers ?? <String, String>{};
OutdatedGuy marked this conversation as resolved.
Show resolved Hide resolved

/// URI to check for connectivity. A HEAD request will be made to this URI.
///
Expand All @@ -50,11 +57,18 @@ class InternetCheckOption {
/// Defaults to 3 seconds.
final Duration timeout;

/// A map of additional headers to send with the request.
final Map<String, String> headers;

/// A callback to check expected response
final ResponseStatusFn? responseStatusFn;
OutdatedGuy marked this conversation as resolved.
Show resolved Hide resolved

@override
String toString() {
return 'InternetCheckOption(\n'
' uri: $uri,\n'
' timeout: $timeout\n'
' timeout: $timeout,\n'
' headers: ${headers.toString()}\n'
')';
}
}
12 changes: 10 additions & 2 deletions lib/src/internet_connection.dart
Original file line number Diff line number Diff line change
Expand Up @@ -127,11 +127,19 @@ class InternetConnection {
InternetCheckOption option,
) async {
try {
final response = await http.head(option.uri).timeout(option.timeout);
final response = await http
.head(
option.uri,
headers: option.headers,
OutdatedGuy marked this conversation as resolved.
Show resolved Hide resolved
)
.timeout(option.timeout);

ResponseStatusFn statusFn =
option.responseStatusFn ?? (response) => response.statusCode == 200;
OutdatedGuy marked this conversation as resolved.
Show resolved Hide resolved

return InternetCheckResult(
option: option,
isSuccess: response.statusCode == 200,
isSuccess: statusFn(response),
);
} catch (_) {
return InternetCheckResult(
Expand Down
36 changes: 36 additions & 0 deletions test/__mocks__/test_http_client.dart
OutdatedGuy marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import 'package:http/http.dart' as http;

typedef TestHttpResponseBuilder = http.Response Function(
http.BaseRequest request);

class TestHttpClient extends http.BaseClient {
TestHttpResponseBuilder? responseBuilder;

static Future<void> run(
Future<void> Function(TestHttpClient client) fn) async {
final client = TestHttpClient();
await http.runWithClient(
() => fn(client),
() => client,
);
}

static http.Response createResponse({String? body, int statusCode = 200}) =>
http.Response(body ?? '', statusCode);

@override
Future<http.StreamedResponse> send(http.BaseRequest request) async {
final response =
(responseBuilder ?? (req) => http.Response('', 200))(request);
return http.StreamedResponse(
Stream.value(response.bodyBytes),
response.statusCode,
contentLength: response.contentLength,
headers: response.headers,
isRedirect: response.isRedirect,
persistentConnection: response.persistentConnection,
reasonPhrase: response.reasonPhrase,
request: request,
);
}
}
3 changes: 2 additions & 1 deletion test/internet_check_option_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ void main() {

const expectedString = 'InternetCheckOption(\n'
' uri: https://example.com,\n'
' timeout: 0:00:05.000000\n'
' timeout: 0:00:05.000000,\n'
' headers: {}\n'
')';

expect(options.toString(), expectedString);
Expand Down
3 changes: 2 additions & 1 deletion test/internet_check_result_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ void main() {
String expectedString = 'InternetCheckResult(\n'
' option: InternetCheckOption(\n'
' uri: https://example.com,\n'
' timeout: 0:00:03.000000\n'
' timeout: 0:00:03.000000,\n'
' headers: {}\n'
' ),\n'
' isSuccess: true\n'
')';
Expand Down
51 changes: 51 additions & 0 deletions test/internet_connection_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import 'package:flutter_test/flutter_test.dart';

import 'package:internet_connection_checker_plus/internet_connection_checker_plus.dart';

import '__mocks__/test_http_client.dart';

void main() {
group('InternetConnection', () {
test('hasInternetAccess returns true for valid URIs', () async {
Expand All @@ -21,6 +23,55 @@ void main() {
expect(await checker.hasInternetAccess, false);
});

test('hasInternetAccess invoke responseStatusFn to determine success',
() async {
await TestHttpClient.run((client) async {
client.responseBuilder =
(req) => TestHttpClient.createResponse(statusCode: 500);
OutdatedGuy marked this conversation as resolved.
Show resolved Hide resolved
const expectedStatus = true;
final checker = InternetConnection.createInstance(
customCheckOptions: [
InternetCheckOption(
uri: Uri.parse('https://www.example.com/nonexistent-page'),
responseStatusFn: (response) => expectedStatus,
),
],
useDefaultOptions: false,
);

expect(await checker.hasInternetAccess, expectedStatus);
});
});

test('hasInternetAccess send custom header on request', () async {
await TestHttpClient.run((client) async {
const expectedStatus = true;
const expectedHeaders = {'Authorization': 'Bearer token'};

client.responseBuilder = (req) {
for (final header in expectedHeaders.entries) {
final key = header.key;
if (!req.headers.containsKey(key) ||
req.headers[key] != header.value) {
return TestHttpClient.createResponse(statusCode: 500);
}
}
return TestHttpClient.createResponse(statusCode: 200);
};
OutdatedGuy marked this conversation as resolved.
Show resolved Hide resolved
final checker = InternetConnection.createInstance(
customCheckOptions: [
InternetCheckOption(
uri: Uri.parse('https://www.example.com'),
headers: expectedHeaders,
),
],
useDefaultOptions: false,
);

expect(await checker.hasInternetAccess, expectedStatus);
});
});

test('main constructor returns the same instance', () {
final checker = InternetConnection();
expect(checker, InternetConnection());
Expand Down