[Dart💠] How to forgive a bit diffs in golden test

未分類

You will create the followign class.

import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';

class LocalFileComparatorWithThreshold extends LocalFileComparator {
  LocalFileComparatorWithThreshold(super.testFile, this.threshold);
  final double threshold;

  @override
  Future<bool> compare(Uint8List imageBytes, Uri golden) async {
    final result = await GoldenFileComparator.compareLists(
        imageBytes, await getGoldenBytes(golden));
    if (!result.passed && result.diffPercent <= threshold) {
      debugPrint(
          '[Info from Golden] A difference of ${result.diffPercent * 100}% was found,'
          'but it is acceptable since it is not greater'
          'than the threshold of ${threshold * 100}%');
      return true;
    }

    if (!result.passed) {
      final error = await generateFailureOutput(result, golden, basedir);
      throw FlutterError(error);
    }
    return result.passed;
  }
}

And then you will load this class in your test configuration.

Future<void> testExecutable(FutureOr<void> Function() testMain) async {
  if (goldenFileComparator is LocalFileComparator) {
    final testUrl = (goldenFileComparator as LocalFileComparator).basedir;
    goldenFileComparator =
        LocalFileComparatorWithThreshold(Uri.parse('$testUrl'), _threshold);

コメント

タイトルとURLをコピーしました