Skip to content

Instantly share code, notes, and snippets.

@nxcco
Last active May 31, 2020 17:32
Show Gist options
  • Save nxcco/50c5bdee6a1bcb884fa7f08626c93686 to your computer and use it in GitHub Desktop.
Save nxcco/50c5bdee6a1bcb884fa7f08626c93686 to your computer and use it in GitHub Desktop.
This extension makes testing easier, regarding populating the fake database. Also, it adds a convenient way for checking whether the database was successfully modified by another function.
import 'dart:convert';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:cloud_firestore_mocks/cloud_firestore_mocks.dart';
import 'package:collection/collection.dart';
extension MockFirestoreTesting on MockFirestoreInstance {
/// Populates the [MockFirestoreInstance] with data from a JSON-String.
Future<void> populate(String jsonSource) async {
final Map<String, dynamic> sourceMap = json.decode(jsonSource);
for (var collectionEntry in sourceMap.entries) {
await _populate('${collectionEntry.key}', collectionEntry.value);
}
}
Future<void> _populate(String path, Map<String, dynamic> root) async {
Map<String, dynamic> data = {};
for (var entry in root.entries) {
final value = entry.value;
// If the value of the field is another map, run this function.
if (value is Map<String, dynamic>) {
_populate('$path/${entry.key}', value);
continue;
}
// Here, the analysis of each field is done.
if (value is String &&
value.contains(
RegExp(r'^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}$'))) {
data[entry.key] = value.toTimestamp();
continue;
}
data[entry.key] = value;
}
// If the data map is empty, this means that this root map is probably a collection.
if (data.isNotEmpty) {
await this.document('$path').setData(data, merge: true);
}
}
/// Checks if the structure of the [MockFirestoreInstance] database matches with a given JSON-String.
bool matchStructure(String jsonSource) {
final Map<String, dynamic> rootMap = json.decode(this.dump());
final Map<String, dynamic> jsonSourceMap = json.decode(jsonSource);
print('Expected:\n$jsonSource\n');
print('Actual:\n${this.dump()}\n');
return DeepCollectionEquality.unordered().equals(rootMap, jsonSourceMap);
}
}
extension Conversion on String {
Timestamp toTimestamp() {
int year = int.parse(this.substring(0, 4));
int month = int.parse(this.substring(5, 7));
int day = int.parse(this.substring(8, 10));
int hour = int.parse(this.substring(11, 13));
int minute = int.parse(this.substring(14, 16));
int second = int.parse(this.substring(17, 19));
int millisecond = int.parse(this.substring(20));
return Timestamp.fromDate(
DateTime(year, month, day, hour, minute, second, millisecond));
}
}
@nxcco
Copy link
Author

nxcco commented May 31, 2020

If anyone has an idea for getting the difference between the expected and the actual and printing it, i would really appreciate it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment