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 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
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,30 @@ final connection = InternetConnection.createInstance(
> On `web` platform, make sure the custom `Uri`s are not CORS blocked.
> Otherwise, the results may be inaccurate.

### 6. Add custom success criteria

The `InternetConnection` class can be configured to check custom `Uri`s for
internet connectivity using custom success criteria:

```dart
final connection = InternetConnection.createInstance(
customCheckOptions: [
InternetCheckOption(
uri: Uri.parse('https://example.com'),
responseStatusFn: (response) {
return response.statusCode >= 69 && response.statusCode < 169;
},
),
InternetCheckOption(
uri: Uri.parse('https://example2.com'),
responseStatusFn: (response) {
return response.statusCode >= 420 && response.statusCode < 1412;
},
),
],
);
```

#### Default `Uri`s

The `InternetConnection` class uses the following `Uri`s by default:
Expand Down
65 changes: 63 additions & 2 deletions lib/src/internet_check_option.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
part of internet_connection_checker_plus;

/// A Callback Function to decide whether the request succeeded or not.
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 +30,53 @@ class InternetCheckOption {
/// final options = InternetCheckOption(
/// uri: Uri.parse('https://example.com'),
/// timeout: Duration(seconds: 5),
/// headers: {
/// 'Authorization': 'Bearer token',
/// },
/// );
/// ```
///
/// *With custom `responseStatusFn` callback:*
///
/// ```dart
/// final options = InternetCheckOption(
/// uri: Uri.parse('https://example.com'),
/// timeout: Duration(seconds: 5),
/// headers: {
/// 'Authorization': 'Bearer token',
/// },
/// responseStatusFn: (response) {
/// return response.statusCode >= 200 && response.statusCode < 300,
/// },
/// );
/// ```
InternetCheckOption({
required this.uri,
this.timeout = const Duration(seconds: 3),
});
this.headers = const {},
ResponseStatusFn? responseStatusFn,
}) : responseStatusFn = responseStatusFn ?? defaultResponseStatusFn;

/// The default [responseStatusFn]. Success is considered if the status code
/// is `200`.
///
/// Update this in the `main` function to change the default
/// behaviour for all [uri] checks.
///
/// *Usage Example:*
///
/// ```dart
/// void main() {
/// InternetCheckOption.defaultResponseStatusFn = (response) {
/// return response.statusCode >= 200 && response.statusCode < 300;
/// };
///
/// runApp(MyApp());
/// }
/// ```
static ResponseStatusFn defaultResponseStatusFn = (response) {
return response.statusCode == 200;
};

/// URI to check for connectivity. A HEAD request will be made to this URI.
///
Expand All @@ -50,11 +94,28 @@ 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 custom callback function to decide whether the request succeeded or not.
///
/// It is useful if your [uri] returns `non-200` status code.
///
/// *Usage Example:*
///
/// ```dart
/// responseStatusFn: (response) {
/// return response.statusCode >= 200 && response.statusCode < 300;
/// }
/// ```
final ResponseStatusFn responseStatusFn;

@override
String toString() {
return 'InternetCheckOption(\n'
' uri: $uri,\n'
' timeout: $timeout\n'
' timeout: $timeout,\n'
' headers: ${headers.toString()}\n'
')';
}
}
6 changes: 4 additions & 2 deletions lib/src/internet_connection.dart
Original file line number Diff line number Diff line change
Expand Up @@ -127,11 +127,13 @@ 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)
.timeout(option.timeout);

return InternetCheckResult(
option: option,
isSuccess: response.statusCode == 200,
isSuccess: option.responseStatusFn(response),
);
} catch (_) {
return InternetCheckResult(
Expand Down
38 changes: 38 additions & 0 deletions test/__mocks__/test_http_client.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
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,
);
}
}
88 changes: 82 additions & 6 deletions test/internet_check_option_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,96 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:internet_connection_checker_plus/internet_connection_checker_plus.dart';

void main() {
test(
'InternetCheckOptions toString() should return correct string representation',
() {
group('InternetCheckOption', () {
test('toString() returns correct string representation', () {
final options = InternetCheckOption(
uri: Uri.parse('https://example.com'),
timeout: const Duration(seconds: 5),
);

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);
},
);
});

group('headers', () {
test('are empty if not set', () {
final options = InternetCheckOption(
uri: Uri.parse('https://example.com'),
);

expect(options.headers, {});
});

test('are set correctly', () {
const headers = {'key': 'value'};

final options = InternetCheckOption(
uri: Uri.parse('https://example.com'),
headers: headers,
);

expect(options.headers, headers);
});
});

group('responseStatusFn', () {
test('is equal to defaultResponseStatusFn if not set', () {
final options1 = InternetCheckOption(
uri: Uri.parse('https://example.com'),
);

expect(
options1.responseStatusFn,
equals(InternetCheckOption.defaultResponseStatusFn),
);
});

test('is set correctly', () {
customResponseStatusFn(response) => true;

final options1 = InternetCheckOption(
uri: Uri.parse('https://example.com'),
responseStatusFn: customResponseStatusFn,
);

expect(options1.responseStatusFn, equals(customResponseStatusFn));
expect(
options1.responseStatusFn,
isNot(equals(InternetCheckOption.defaultResponseStatusFn)),
);
});
});

group('defaultResponseStatusFn', () {
test('can be overriden', () {
final options = InternetCheckOption(
uri: Uri.parse('https://example.com'),
);

InternetCheckOption.defaultResponseStatusFn = (response) => true;

expect(
options.responseStatusFn,
isNot(equals(InternetCheckOption.defaultResponseStatusFn)),
);
});

test('override is used', () {
customResponseStatusFn(response) => true;

InternetCheckOption.defaultResponseStatusFn = customResponseStatusFn;

final options = InternetCheckOption(
uri: Uri.parse('https://example.com'),
);

expect(options.responseStatusFn, equals(customResponseStatusFn));
});
});
});
}
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
49 changes: 49 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,53 @@ void main() {
expect(await checker.hasInternetAccess, false);
});

test(
'hasInternetAccess invoke responseStatusFn to determine success',
() async {
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