|
| 1 | +// Copyright 2013 The Flutter Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a BSD-style license that can be |
| 3 | +// found in the LICENSE file. |
| 4 | + |
| 5 | +import 'package:flutter/foundation.dart'; |
| 6 | +import 'package:flutter_test/flutter_test.dart'; |
| 7 | + |
| 8 | +/// Sets [_TolerantGoldenFileComparator] as the default golden file comparator |
| 9 | +/// in tests. |
| 10 | +void setUpTolerantComparator( |
| 11 | + {required String testPath, required double precisionTolerance}) { |
| 12 | + final GoldenFileComparator oldComparator = goldenFileComparator; |
| 13 | + final _TolerantGoldenFileComparator newComparator = |
| 14 | + _TolerantGoldenFileComparator(Uri.parse(testPath), |
| 15 | + precisionTolerance: precisionTolerance); |
| 16 | + |
| 17 | + goldenFileComparator = newComparator; |
| 18 | + |
| 19 | + addTearDown(() => goldenFileComparator = oldComparator); |
| 20 | +} |
| 21 | + |
| 22 | +class _TolerantGoldenFileComparator extends LocalFileComparator { |
| 23 | + _TolerantGoldenFileComparator( |
| 24 | + super.testFile, { |
| 25 | + required double precisionTolerance, |
| 26 | + }) : assert( |
| 27 | + 0 <= precisionTolerance && precisionTolerance <= 1, |
| 28 | + 'precisionTolerance must be between 0 and 1', |
| 29 | + ), |
| 30 | + _precisionTolerance = precisionTolerance; |
| 31 | + |
| 32 | + /// How much the golden image can differ from the test image. |
| 33 | + /// |
| 34 | + /// It is expected to be between 0 and 1. Where 0 is no difference (the same image) |
| 35 | + /// and 1 is the maximum difference (completely different images). |
| 36 | + final double _precisionTolerance; |
| 37 | + |
| 38 | + @override |
| 39 | + Future<bool> compare(Uint8List imageBytes, Uri golden) async { |
| 40 | + final ComparisonResult result = await GoldenFileComparator.compareLists( |
| 41 | + imageBytes, |
| 42 | + await getGoldenBytes(golden), |
| 43 | + ); |
| 44 | + |
| 45 | + final bool passed = |
| 46 | + result.passed || result.diffPercent <= _precisionTolerance; |
| 47 | + if (passed) { |
| 48 | + result.dispose(); |
| 49 | + return true; |
| 50 | + } |
| 51 | + |
| 52 | + final String error = await generateFailureOutput(result, golden, basedir); |
| 53 | + result.dispose(); |
| 54 | + throw FlutterError(error); |
| 55 | + } |
| 56 | +} |
0 commit comments