Skip to content

Commit

Permalink
refactor(storage): migrate example and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
pr-Mais committed Nov 22, 2021
1 parent 90bbe7b commit 0424012
Show file tree
Hide file tree
Showing 13 changed files with 164 additions and 163 deletions.
Expand Up @@ -22,13 +22,14 @@ Future<void> main() async {
await runZonedGuarded(() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: const FirebaseOptions(
apiKey: 'AIzaSyAHAsf51D0A407EklG1bs-5wA7EbyfNFg0',
appId: '1:448618578101:ios:2bc5c1fe2ec336f8ac3efc',
messagingSenderId: '448618578101',
authDomain: 'react-native-firebase-testing.firebaseapp.com',
projectId: 'react-native-firebase-testing',
));
options: const FirebaseOptions(
apiKey: 'AIzaSyAHAsf51D0A407EklG1bs-5wA7EbyfNFg0',
appId: '1:448618578101:ios:2bc5c1fe2ec336f8ac3efc',
messagingSenderId: '448618578101',
authDomain: 'react-native-firebase-testing.firebaseapp.com',
projectId: 'react-native-firebase-testing',
),
);
FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError;
runApp(MyApp());
}, (error, stackTrace) {
Expand Down
61 changes: 31 additions & 30 deletions packages/firebase_storage/firebase_storage/example/lib/main.dart
@@ -1,6 +1,3 @@
// ignore_for_file: require_trailing_commas
// @dart=2.9

import 'dart:async';
import 'dart:io' as io;

Expand All @@ -16,12 +13,16 @@ import 'save_as/save_as.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: const FirebaseOptions(
apiKey: 'AIzaSyAHAsf51D0A407EklG1bs-5wA7EbyfNFg0',
appId: '1:448618578101:ios:2bc5c1fe2ec336f8ac3efc',
messagingSenderId: '448618578101',
projectId: 'react-native-firebase-testing',
));
options: const FirebaseOptions(
apiKey: 'AIzaSyAHAsf51D0A407EklG1bs-5wA7EbyfNFg0',
appId: '1:448618578101:ios:2bc5c1fe2ec336f8ac3efc',
messagingSenderId: '448618578101',
projectId: 'react-native-firebase-testing',
iosClientId:
'448618578101-m53gtqfnqipj12pts10590l37npccd2r.apps.googleusercontent.com',
storageBucket: 'react-native-firebase-testing.appspot.com',
),
);
runApp(StorageExampleApp());
}

Expand All @@ -41,7 +42,7 @@ enum UploadType {
///
/// Returns a [MaterialApp].
class StorageExampleApp extends StatelessWidget {
StorageExampleApp({Key key}) : super(key: key);
StorageExampleApp({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
Expand All @@ -57,7 +58,7 @@ class StorageExampleApp extends StatelessWidget {
/// A StatefulWidget which keeps track of the current uploaded files.
class TaskManager extends StatefulWidget {
// ignore: public_member_api_docs
TaskManager({Key key}) : super(key: key);
TaskManager({Key? key}) : super(key: key);

@override
State<StatefulWidget> createState() {
Expand All @@ -70,12 +71,9 @@ class _TaskManager extends State<TaskManager> {

/// The user selects a file, and the task is added to the list.
Future<firebase_storage.UploadTask> uploadFile(PickedFile file) async {
if (file == null) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('No file was selected'),
));
return null;
}
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('No file was selected'),
));

firebase_storage.UploadTask uploadTask;

Expand Down Expand Up @@ -125,14 +123,16 @@ class _TaskManager extends State<TaskManager> {
});
break;
case UploadType.file:
PickedFile file =
PickedFile? file =
await ImagePicker().getImage(source: ImageSource.gallery);
firebase_storage.UploadTask task = await uploadFile(file);
if (task != null) {
if (file != null) {
firebase_storage.UploadTask task = await uploadFile(file);

setState(() {
_uploadTasks = [..._uploadTasks, task];
});
}

break;
case UploadType.clear:
setState(() {
Expand All @@ -151,7 +151,7 @@ class _TaskManager extends State<TaskManager> {
Future<void> _downloadBytes(firebase_storage.Reference ref) async {
final bytes = await ref.getData();
// Download...
await saveAsBytes(bytes, 'some-image.jpg');
await saveAsBytes(bytes!, 'some-image.jpg');
}

Future<void> _downloadLink(firebase_storage.Reference ref) async {
Expand Down Expand Up @@ -222,10 +222,10 @@ class _TaskManager extends State<TaskManager> {
itemBuilder: (context, index) => UploadTaskListTile(
task: _uploadTasks[index],
onDismissed: () => _removeTaskAtIndex(index),
onDownloadLink: () {
onDownloadLink: () async {
return _downloadLink(_uploadTasks[index].snapshot.ref);
},
onDownload: () {
onDownload: () async {
if (kIsWeb) {
return _downloadBytes(_uploadTasks[index].snapshot.ref);
} else {
Expand All @@ -242,11 +242,11 @@ class _TaskManager extends State<TaskManager> {
class UploadTaskListTile extends StatelessWidget {
// ignore: public_member_api_docs
const UploadTaskListTile({
Key key,
this.task,
this.onDismissed,
this.onDownload,
this.onDownloadLink,
Key? key,
required this.task,
required this.onDismissed,
required this.onDownload,
required this.onDownloadLink,
}) : super(key: key);

/// The [UploadTask].
Expand Down Expand Up @@ -275,11 +275,12 @@ class UploadTaskListTile extends StatelessWidget {
AsyncSnapshot<firebase_storage.TaskSnapshot> asyncSnapshot,
) {
Widget subtitle = const Text('---');
firebase_storage.TaskSnapshot snapshot = asyncSnapshot.data;
firebase_storage.TaskState state = snapshot?.state;
firebase_storage.TaskSnapshot? snapshot = asyncSnapshot.data;
firebase_storage.TaskState? state = snapshot?.state;

if (asyncSnapshot.hasError) {
if (asyncSnapshot.error is FirebaseException &&
// ignore: cast_nullable_to_non_nullable
(asyncSnapshot.error as FirebaseException).code == 'canceled') {
subtitle = const Text('Upload canceled.');
} else {
Expand Down
@@ -1,3 +1 @@
// ignore_for_file: require_trailing_commas
// @dart=2.9
export 'save_as_interface.dart' if (dart.library.html) 'save_as_html.dart';
@@ -1,6 +1,3 @@
// ignore_for_file: require_trailing_commas
// @dart=2.9

// ignore: avoid_web_libraries_in_flutter
import 'dart:html';
import 'dart:typed_data';
Expand All @@ -11,14 +8,14 @@ Element _ensureInitialized(String id) {
if (target == null) {
final Element targetElement = Element.tag('flt-x-file')..id = id;

querySelector('body').children.add(targetElement);
querySelector('body')?.children.add(targetElement);
target = targetElement;
}
return target;
}

AnchorElement _createAnchorElement(String href, String suggestedName) {
return AnchorElement(href: href)..download = suggestedName ?? 'download';
return AnchorElement(href: href)..download = suggestedName;
}

/// Add an element to a container and click it
Expand Down
@@ -1,5 +1,3 @@
// ignore_for_file: require_trailing_commas
// @dart=2.9
import 'dart:typed_data';

/// Present a dialog so the user can save as... a bunch of bytes.
Expand Down
Expand Up @@ -2,7 +2,7 @@ name: firebase_storage_example
description: Demonstrates how to use the firebase_storage plugin.

environment:
sdk: ">=2.12.0 <3.0.0"
sdk: '>=2.12.0 <3.0.0'

dependencies:
firebase_core:
Expand All @@ -29,7 +29,7 @@ dependency_overrides:
path: ../../firebase_storage_web

dev_dependencies:
drive: 0.1.0
drive: ^1.0.0-1.0.nullsafety.1
flutter_driver:
sdk: flutter
test: any
Expand Down
@@ -1,12 +1,7 @@
// ignore_for_file: require_trailing_commas
// @dart = 2.9

// Copyright 2020, the Chromium project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// @dart=2.9

import 'package:drive/drive.dart' as drive;
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_storage/firebase_storage.dart';
Expand All @@ -24,7 +19,8 @@ bool useEmulator = true;

void testsMain() {
setUpAll(() async {
await Firebase.initializeApp();
await Firebase.initializeApp(options: testDefaultOptions);

if (useEmulator) {
await FirebaseStorage.instance
.useStorageEmulator(testEmulatorHost, testEmulatorPort);
Expand Down
@@ -1,12 +1,7 @@
// ignore_for_file: require_trailing_commas
// @dart = 2.9

// Copyright 2020, the Chromium project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// @dart=2.9

import 'package:drive/drive_driver.dart' as drive;

void main() => drive.main();
@@ -1,6 +1,3 @@
// ignore_for_file: require_trailing_commas
// @dart = 2.9

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter_test/flutter_test.dart';
Expand All @@ -9,12 +6,12 @@ import 'test_utils.dart';

void runInstanceTests() {
group('$FirebaseStorage', () {
/*late*/ FirebaseStorage storage;
/*late*/ FirebaseApp secondaryApp;
/*late*/ FirebaseApp secondaryAppWithoutBucket;
late FirebaseStorage storage;
late FirebaseApp secondaryApp;
late FirebaseApp secondaryAppWithoutBucket;

setUpAll(() async {
await Firebase.initializeApp();
await Firebase.initializeApp(options: testDefaultOptions);
storage = FirebaseStorage.instance;
secondaryApp = await testInitializeSecondaryApp();
});
Expand Down Expand Up @@ -146,16 +143,20 @@ void runInstanceTests() {
});

test('throws an error if https url could not be parsed', () async {
try {
storage.refFromURL('https://invertase.io');
fail('Did not throw an Error.');
} catch (error) {
expect(
error.message,
expect(
() {
storage.refFromURL('https://invertase.io');
fail('Did not throw an Error.');
},
throwsA(
isA<AssertionError>().having(
(p0) => p0.message,
'assertion message',
contains(
"url could not be parsed, ensure it's a valid storage url"));
return;
}
"url could not be parsed, ensure it's a valid storage url"),
),
),
);
});

test('accepts a gs url without a fullPath', () async {
Expand All @@ -167,23 +168,33 @@ void runInstanceTests() {

test('throws an error if url does not start with gs:// or https://',
() async {
try {
storage.refFromURL('bs://foo/bar/cat.gif');
fail('Should have thrown an [AssertionError]');
} catch (error) {
expect(error.message,
contains("a url must start with 'gs://' or 'https://'"));
}
expect(
() {
storage.refFromURL('bs://foo/bar/cat.gif');
fail('Should have thrown an [AssertionError]');
},
throwsA(
isA<AssertionError>().having(
(p0) => p0.message,
'assertion message',
contains("a url must start with 'gs://' or 'https://'"),
),
),
);
});
});

group('setMaxOperationRetryTime', () {
test('should set', () async {
expect(storage.maxOperationRetryTime,
const Duration(milliseconds: 120000));
expect(
storage.maxOperationRetryTime,
const Duration(milliseconds: 120000),
);
storage.setMaxOperationRetryTime(const Duration(milliseconds: 100000));
expect(storage.maxOperationRetryTime,
const Duration(milliseconds: 100000));
expect(
storage.maxOperationRetryTime,
const Duration(milliseconds: 100000),
);
});
});

Expand Down
@@ -1,13 +1,10 @@
// ignore_for_file: require_trailing_commas
// @dart = 2.9

import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter_test/flutter_test.dart';

void runListResultTests() {
group('$ListResult', () {
/*late*/ FirebaseStorage storage;
/*late*/ ListResult result;
late FirebaseStorage storage;
late ListResult result;

setUpAll(() async {
storage = FirebaseStorage.instance;
Expand Down

0 comments on commit 0424012

Please sign in to comment.