Skip to content

Commit

Permalink
Improve usage example and tests (#1933)
Browse files Browse the repository at this point in the history
<!-- Write down your pull request descriptions. -->

- Improve tests.
- Improve usage example for `Dio.download`.
- Remove unused code.
- Fix typo in `example/lib/download_with_trunks`.
- Replace the broken resource:
http://download.dcloud.net.cn/HBuilder.9.0.2.macosx_64.dmg.
- Disable the compression to assure the value of `total` argument of
`onReceiveProgress` is not `-1` in `example/lib/download`.

### New Pull Request Checklist

- [x] I have read the
[Documentation](https://pub.dev/documentation/dio/latest/)
- [x] I have searched for a similar pull request in the
[project](https://github.com/cfug/dio/pulls) and found none
- [x] I have updated this branch with the latest `main` branch to avoid
conflicts (via merge from master or rebase)
- [ ] I have added the required tests to prove the fix/feature I'm
adding
- [x] I have updated the documentation (if necessary)
- [x] I have run the tests without failures
- [ ] I have updated the `CHANGELOG.md` in the corresponding package

### Additional context and info (if any)

<!-- Provide more context and info about the PR. -->

There was no warning previously due to the default `dynamic` parameter
type.
  • Loading branch information
hgraceb authored Aug 11, 2023
1 parent 0854519 commit e04b791
Show file tree
Hide file tree
Showing 9 changed files with 24 additions and 67 deletions.
5 changes: 2 additions & 3 deletions dio/lib/src/dio.dart
Original file line number Diff line number Diff line change
Expand Up @@ -229,9 +229,8 @@ abstract class Dio {
/// headers: {HttpHeaders.acceptEncodingHeader: '*'}, // Disable gzip
/// ),
/// onReceiveProgress: (received, total) {
/// if (total != -1) {
/// print((received / total * 100).toStringAsFixed(0) + '%');
/// }
/// if (total <= 0) return;
/// print('percentage: ${(received / total * 100).toStringAsFixed(0)}%');
/// },
/// );
/// ```
Expand Down
19 changes: 5 additions & 14 deletions dio/test/download_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,8 @@ void main() {
tearDown(stopServer);
test('download1', () async {
const savePath = 'test/_download_test.md';
final dio = Dio();
dio.options.baseUrl = serverUrl.toString();
await dio.download(
'/download', savePath, // disable gzip
onReceiveProgress: (received, total) {
// ignore progress
},
);
final dio = Dio()..options.baseUrl = serverUrl.toString();
await dio.download('/download', savePath);

final f = File(savePath);
expect(f.readAsStringSync(), equals('I am a text file'));
Expand All @@ -29,11 +23,10 @@ void main() {

test('download2', () async {
const savePath = 'test/_download_test.md';
final dio = Dio();
dio.options.baseUrl = serverUrl.toString();
final dio = Dio()..options.baseUrl = serverUrl.toString();
await dio.downloadUri(
serverUrl.replace(path: '/download'),
(header) => savePath, // disable gzip
(header) => savePath,
);

final f = File(savePath);
Expand All @@ -43,8 +36,7 @@ void main() {

test('download error', () async {
const savePath = 'test/_download_test.md';
final dio = Dio();
dio.options.baseUrl = serverUrl.toString();
final dio = Dio()..options.baseUrl = serverUrl.toString();
Response response = await dio
.download('/error', savePath)
.catchError((e) => (e as DioException).response!);
Expand Down Expand Up @@ -73,7 +65,6 @@ void main() {
.catchError((e) => throw (e as DioException).type),
throwsA(DioExceptionType.receiveTimeout),
);
//print(r);
});

test('download cancellation', () async {
Expand Down
7 changes: 1 addition & 6 deletions dio/test/request_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -84,12 +84,7 @@ void main() {
);

// redirect test
response = await dio.get(
'/redirect',
onReceiveProgress: (received, total) {
// ignore progress
},
);
response = await dio.get('/redirect');
expect(response.isRedirect, true);
expect(response.redirects.length, 1);
final ri = response.redirects.first;
Expand Down
4 changes: 1 addition & 3 deletions dio/test/utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,7 @@ Future<void> startServer() async {
..contentLength = content.length
..write(content);

Future.delayed(Duration(milliseconds: 300), () {
response.close();
});
Future.delayed(Duration(milliseconds: 300), () => response.close());
return;
}

Expand Down
4 changes: 1 addition & 3 deletions example/lib/dio.dart
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,7 @@ void main() async {
'./example/xx.html',
queryParameters: {'a': 1},
onReceiveProgress: (received, total) {
if (total != -1) {
print('$received,$total');
}
print('received: $received, total: $total');
},
);

Expand Down
9 changes: 5 additions & 4 deletions example/lib/download.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import 'package:dio/dio.dart';
void main() async {
final dio = Dio();
dio.interceptors.add(LogInterceptor());
// Assure the value of total argument of onReceiveProgress is not -1.
dio.options.headers = {HttpHeaders.acceptEncodingHeader: '*'};
final url = 'https://pub.dev/static/hash-rhob5slb/img/pub-dev-logo.svg';
await download1(dio, url, './example/pub-dev-logo.svg');
await download1(dio, url, (headers) => './example/pub-dev-logo-1.svg');
Expand Down Expand Up @@ -51,8 +53,7 @@ Future download2(Dio dio, String url, String savePath) async {
}
}

void showDownloadProgress(received, total) {
if (total != -1) {
print((received / total * 100).toStringAsFixed(0) + '%');
}
void showDownloadProgress(int received, int total) {
if (total <= 0) return;
print('percentage: ${(received / total * 100).toStringAsFixed(0)}%');
}
14 changes: 5 additions & 9 deletions example/lib/download_with_trunks.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,20 @@ import 'dart:io';
import 'package:dio/dio.dart';

void main() async {
final url = 'http://download.dcloud.net.cn/HBuilder.9.0.2.macosx_64.dmg';
final savePath = './example/HBuilder.9.0.2.macosx_64.dmg';

// final url = "https://www.baidu.com/img/bdlogo.gif";
// final savePath = "./example/bg.gif";
final url = 'https://avatars.githubusercontent.com/u/0';
final savePath = './example/avatar.png';

await downloadWithChunks(
url,
savePath,
onReceiveProgress: (received, total) {
if (total != -1) {
print('${(received / total * 100).floor()}%');
}
if (total <= 0) return;
print('${(received / total * 100).floor()}%');
},
);
}

/// Downloading by spiting as file in chunks
/// Downloading by splitting as file in chunks
Future downloadWithChunks(
url,
savePath, {
Expand Down
15 changes: 3 additions & 12 deletions example/lib/formdata.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,6 @@ import 'dart:io';
import 'package:dio/dio.dart';
import 'package:dio/io.dart';

void showProgress(received, total) {
if (total != -1) {
print((received / total * 100).toStringAsFixed(0) + '%');
}
}

Future<FormData> formData1() async {
return FormData.fromMap({
'name': 'wendux',
Expand Down Expand Up @@ -92,7 +86,6 @@ void main() async {
final dio = Dio();
dio.options.baseUrl = 'http://localhost:3000/';
dio.interceptors.add(LogInterceptor());
// dio.interceptors.add(LogInterceptor(requestBody: true));
dio.httpClientAdapter = IOHttpClientAdapter(
createHttpClient: () {
final client = HttpClient();
Expand All @@ -116,13 +109,11 @@ void main() async {
print(utf8.decode(await data3.readAsBytes()));

response = await dio.post(
//"/upload",
'http://localhost:3000/upload',
data: data3,
onSendProgress: (received, total) {
if (total != -1) {
print('${(received / total * 100).toStringAsFixed(0)}%');
}
onSendProgress: (sent, total) {
if (total <= 0) return;
print('percentage: ${(sent / total * 100).toStringAsFixed(0)}%');
},
);
print(response);
Expand Down
14 changes: 1 addition & 13 deletions example_flutter_app/lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,21 +1,9 @@
import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

import 'http.dart'; // make dio as global top-level variable
import 'routes/request.dart';

// Must be top-level function
_parseAndDecode(String response) {
return jsonDecode(response);
}

parseJson(String text) {
return compute(_parseAndDecode, text);
}

void main() {
dio.interceptors.add(LogInterceptor());
runApp(MyApp());
Expand Down Expand Up @@ -91,7 +79,7 @@ class _MyHomePageState extends State<MyHomePage> {
child: SingleChildScrollView(
child: Text(_text),
),
)
),
],
),
),
Expand Down

0 comments on commit e04b791

Please sign in to comment.