skiaperf_test.dart 16.1 KB
Newer Older
1 2 3 4 5 6 7 8
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

@Timeout(Duration(seconds: 3600))

import 'dart:convert';

9 10 11 12 13 14
import 'package:gcloud/storage.dart';
import 'package:googleapis/storage/v1.dart' show DetailedApiRequestError;
import 'package:googleapis_auth/auth_io.dart';
import 'package:metrics_center/src/github_helper.dart';
import 'package:mockito/mockito.dart';

15 16 17 18 19
import 'package:metrics_center/src/common.dart';
import 'package:metrics_center/src/flutter.dart';
import 'package:metrics_center/src/skiaperf.dart';

import 'common.dart';
20 21 22 23 24 25 26
import 'utility.dart';

class MockBucket extends Mock implements Bucket {}

class MockObjectInfo extends Mock implements ObjectInfo {}

class MockGithubHelper extends Mock implements GithubHelper {}
27

28
Future<void> main() async {
29 30 31 32
  const double kValue1 = 1.0;
  const double kValue2 = 2.0;

  const String kFrameworkRevision1 = '9011cece2595447eea5dd91adaa241c1c9ef9a33';
33 34
  const String kEngineRevision1 = '617938024315e205f26ed72ff0f0647775fa6a71';
  const String kEngineRevision2 = '5858519139c22484aaff1cf5b26bdf7951259344';
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
  const String kTaskName = 'analyzer_benchmark';
  const String kMetric1 = 'flutter_repo_batch_maximum';
  const String kMetric2 = 'flutter_repo_watch_maximum';

  final MetricPoint cocoonPointRev1Metric1 = MetricPoint(
    kValue1,
    const <String, String>{
      kGithubRepoKey: kFlutterFrameworkRepo,
      kGitRevisionKey: kFrameworkRevision1,
      kNameKey: kTaskName,
      kSubResultKey: kMetric1,
      kUnitKey: 's',
    },
  );

  final MetricPoint cocoonPointRev1Metric2 = MetricPoint(
    kValue2,
    const <String, String>{
      kGithubRepoKey: kFlutterFrameworkRepo,
      kGitRevisionKey: kFrameworkRevision1,
      kNameKey: kTaskName,
      kSubResultKey: kMetric2,
      kUnitKey: 's',
    },
  );

  final MetricPoint cocoonPointBetaRev1Metric1 = MetricPoint(
    kValue1,
    const <String, String>{
      kGithubRepoKey: kFlutterFrameworkRepo,
      kGitRevisionKey: kFrameworkRevision1,
      kNameKey: 'beta/$kTaskName',
      kSubResultKey: kMetric1,
      kUnitKey: 's',
      'branch': 'beta',
    },
  );

  final MetricPoint cocoonPointBetaRev1Metric1BadBranch = MetricPoint(
    kValue1,
    const <String, String>{
      kGithubRepoKey: kFlutterFrameworkRepo,
      kGitRevisionKey: kFrameworkRevision1,
      kNameKey: kTaskName,
      kSubResultKey: kMetric1,
      kUnitKey: 's',

      // If we only add this 'branch' tag without changing the test or sub-result name, an exception
      // would be thrown as Skia Perf currently only supports the same set of tags for a pair of
      // kNameKey and kSubResultKey values. So to support branches, one also has to add the branch
      // name to the test name.
      'branch': 'beta',
    },
  );

  const String engineMetricName = 'BM_PaintRecordInit';
  const String engineRevision = 'ca799fa8b2254d09664b78ee80c43b434788d112';
  const double engineValue1 = 101;
  const double engineValue2 = 102;

  final FlutterEngineMetricPoint enginePoint1 = FlutterEngineMetricPoint(
    engineMetricName,
    engineValue1,
    engineRevision,
    moreTags: const <String, String>{
      kSubResultKey: 'cpu_time',
      kUnitKey: 'ns',
      'date': '2019-12-17 15:14:14',
      'num_cpus': '56',
      'mhz_per_cpu': '2594',
      'cpu_scaling_enabled': 'true',
      'library_build_type': 'release',
    },
  );

  final FlutterEngineMetricPoint enginePoint2 = FlutterEngineMetricPoint(
    engineMetricName,
    engineValue2,
    engineRevision,
    moreTags: const <String, String>{
      kSubResultKey: 'real_time',
      kUnitKey: 'ns',
      'date': '2019-12-17 15:14:14',
      'num_cpus': '56',
      'mhz_per_cpu': '2594',
      'cpu_scaling_enabled': 'true',
      'library_build_type': 'release',
    },
  );

  test('Throw if invalid points are converted to SkiaPoint', () {
    final MetricPoint noGithubRepoPoint = MetricPoint(
      kValue1,
      const <String, String>{
        kGitRevisionKey: kFrameworkRevision1,
        kNameKey: kTaskName,
      },
    );

    final MetricPoint noGitRevisionPoint = MetricPoint(
      kValue1,
      const <String, String>{
        kGithubRepoKey: kFlutterFrameworkRepo,
        kNameKey: kTaskName,
      },
    );

    final MetricPoint noTestNamePoint = MetricPoint(
      kValue1,
      const <String, String>{
        kGithubRepoKey: kFlutterFrameworkRepo,
        kGitRevisionKey: kFrameworkRevision1,
      },
    );

    expect(() => SkiaPerfPoint.fromPoint(noGithubRepoPoint), throwsA(anything));
    expect(
        () => SkiaPerfPoint.fromPoint(noGitRevisionPoint), throwsA(anything));
    expect(() => SkiaPerfPoint.fromPoint(noTestNamePoint), throwsA(anything));
  });

  test('Correctly convert a metric point from cocoon to SkiaPoint', () {
    final SkiaPerfPoint skiaPoint1 =
        SkiaPerfPoint.fromPoint(cocoonPointRev1Metric1);
    expect(skiaPoint1, isNotNull);
    expect(skiaPoint1.testName, equals(kTaskName));
    expect(skiaPoint1.subResult, equals(kMetric1));
    expect(skiaPoint1.value, equals(cocoonPointRev1Metric1.value));
    expect(skiaPoint1.jsonUrl, isNull); // Not inserted yet
  });

  test('Cocoon points correctly encode into Skia perf json format', () {
    final SkiaPerfPoint p1 = SkiaPerfPoint.fromPoint(cocoonPointRev1Metric1);
    final SkiaPerfPoint p2 = SkiaPerfPoint.fromPoint(cocoonPointRev1Metric2);
    final SkiaPerfPoint p3 =
        SkiaPerfPoint.fromPoint(cocoonPointBetaRev1Metric1);

    const JsonEncoder encoder = JsonEncoder.withIndent('  ');

    expect(
        encoder
            .convert(SkiaPerfPoint.toSkiaPerfJson(<SkiaPerfPoint>[p1, p2, p3])),
        equals('''
{
  "gitHash": "9011cece2595447eea5dd91adaa241c1c9ef9a33",
  "results": {
    "analyzer_benchmark": {
      "default": {
        "flutter_repo_batch_maximum": 1.0,
        "options": {
          "unit": "s"
        },
        "flutter_repo_watch_maximum": 2.0
      }
    },
    "beta/analyzer_benchmark": {
      "default": {
        "flutter_repo_batch_maximum": 1.0,
        "options": {
          "branch": "beta",
          "unit": "s"
        }
      }
    }
  }
}'''));
  });

  test('Engine metric points correctly encode into Skia perf json format', () {
    const JsonEncoder encoder = JsonEncoder.withIndent('  ');
    expect(
      encoder.convert(SkiaPerfPoint.toSkiaPerfJson(<SkiaPerfPoint>[
        SkiaPerfPoint.fromPoint(enginePoint1),
        SkiaPerfPoint.fromPoint(enginePoint2),
      ])),
      equals(
        '''
{
  "gitHash": "ca799fa8b2254d09664b78ee80c43b434788d112",
  "results": {
    "BM_PaintRecordInit": {
      "default": {
        "cpu_time": 101.0,
        "options": {
          "cpu_scaling_enabled": "true",
          "library_build_type": "release",
          "mhz_per_cpu": "2594",
          "num_cpus": "56",
          "unit": "ns"
        },
        "real_time": 102.0
      }
    }
  }
}''',
      ),
    );
  });

  test(
      'Throw if engine points with the same test name but different options are converted to '
      'Skia perf points', () {
    final FlutterEngineMetricPoint enginePoint1 = FlutterEngineMetricPoint(
      'BM_PaintRecordInit',
      101,
      'ca799fa8b2254d09664b78ee80c43b434788d112',
      moreTags: const <String, String>{
        kSubResultKey: 'cpu_time',
        kUnitKey: 'ns',
        'cpu_scaling_enabled': 'true',
      },
    );
    final FlutterEngineMetricPoint enginePoint2 = FlutterEngineMetricPoint(
      'BM_PaintRecordInit',
      102,
      'ca799fa8b2254d09664b78ee80c43b434788d112',
      moreTags: const <String, String>{
        kSubResultKey: 'real_time',
        kUnitKey: 'ns',
        'cpu_scaling_enabled': 'false',
      },
    );

    const JsonEncoder encoder = JsonEncoder.withIndent('  ');
    expect(
      () => encoder.convert(SkiaPerfPoint.toSkiaPerfJson(<SkiaPerfPoint>[
        SkiaPerfPoint.fromPoint(enginePoint1),
        SkiaPerfPoint.fromPoint(enginePoint2),
      ])),
      throwsA(anything),
    );
  });

  test(
      'Throw if two Cocoon metric points with the same name and subResult keys '
      'but different options are converted to Skia perf points', () {
    final SkiaPerfPoint p1 = SkiaPerfPoint.fromPoint(cocoonPointRev1Metric1);
    final SkiaPerfPoint p2 =
        SkiaPerfPoint.fromPoint(cocoonPointBetaRev1Metric1BadBranch);

    expect(
      () => SkiaPerfPoint.toSkiaPerfJson(<SkiaPerfPoint>[p1, p2]),
      throwsA(anything),
    );
  });
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481

  test('SkiaPerfGcsAdaptor computes name correctly', () async {
    final MockGithubHelper mockHelper = MockGithubHelper();
    when(mockHelper.getCommitDateTime(
            kFlutterFrameworkRepo, kFrameworkRevision1))
        .thenAnswer((_) => Future<DateTime>.value(DateTime(2019, 12, 4, 23)));
    expect(
      await SkiaPerfGcsAdaptor.comptueObjectName(
        kFlutterFrameworkRepo,
        kFrameworkRevision1,
        githubHelper: mockHelper,
      ),
      equals('flutter-flutter/2019/12/04/23/$kFrameworkRevision1/values.json'),
    );
    when(mockHelper.getCommitDateTime(kFlutterEngineRepo, kEngineRevision1))
        .thenAnswer((_) => Future<DateTime>.value(DateTime(2019, 12, 3, 20)));
    expect(
      await SkiaPerfGcsAdaptor.comptueObjectName(
        kFlutterEngineRepo,
        kEngineRevision1,
        githubHelper: mockHelper,
      ),
      equals('flutter-engine/2019/12/03/20/$kEngineRevision1/values.json'),
    );
    when(mockHelper.getCommitDateTime(kFlutterEngineRepo, kEngineRevision2))
        .thenAnswer((_) => Future<DateTime>.value(DateTime(2020, 1, 3, 15)));
    expect(
      await SkiaPerfGcsAdaptor.comptueObjectName(
        kFlutterEngineRepo,
        kEngineRevision2,
        githubHelper: mockHelper,
      ),
      equals('flutter-engine/2020/01/03/15/$kEngineRevision2/values.json'),
    );
  });

  test('Successfully read mock GCS that fails 1st time with 504', () async {
    final MockBucket testBucket = MockBucket();
    final SkiaPerfGcsAdaptor skiaPerfGcs = SkiaPerfGcsAdaptor(testBucket);

    final String testObjectName = await SkiaPerfGcsAdaptor.comptueObjectName(
        kFlutterFrameworkRepo, kFrameworkRevision1);

    final List<SkiaPerfPoint> writePoints = <SkiaPerfPoint>[
      SkiaPerfPoint.fromPoint(cocoonPointRev1Metric1),
    ];
    final String skiaPerfJson =
        jsonEncode(SkiaPerfPoint.toSkiaPerfJson(writePoints));
    await skiaPerfGcs.writePoints(testObjectName, writePoints);
    verify(testBucket.writeBytes(testObjectName, utf8.encode(skiaPerfJson)));

    // Emulate the first network request to fail with 504.
    when(testBucket.info(testObjectName))
        .thenThrow(DetailedApiRequestError(504, 'Test Failure'));

    final MockObjectInfo mockObjectInfo = MockObjectInfo();
    when(mockObjectInfo.downloadLink)
        .thenReturn(Uri.https('test.com', 'mock.json'));
    when(testBucket.info(testObjectName))
        .thenAnswer((_) => Future<ObjectInfo>.value(mockObjectInfo));
    when(testBucket.read(testObjectName))
        .thenAnswer((_) => Stream<List<int>>.value(utf8.encode(skiaPerfJson)));

    final List<SkiaPerfPoint> readPoints =
        await skiaPerfGcs.readPoints(testObjectName);
    expect(readPoints.length, equals(1));
    expect(readPoints[0].testName, kTaskName);
    expect(readPoints[0].subResult, kMetric1);
    expect(readPoints[0].value, kValue1);
    expect(readPoints[0].githubRepo, kFlutterFrameworkRepo);
    expect(readPoints[0].gitHash, kFrameworkRevision1);
    expect(readPoints[0].jsonUrl, 'https://test.com/mock.json');
  });

  test('Return empty list if the GCS file does not exist', () async {
    final MockBucket testBucket = MockBucket();
    final SkiaPerfGcsAdaptor skiaPerfGcs = SkiaPerfGcsAdaptor(testBucket);
    final String testObjectName = await SkiaPerfGcsAdaptor.comptueObjectName(
        kFlutterFrameworkRepo, kFrameworkRevision1);
    when(testBucket.info(testObjectName))
        .thenThrow(Exception('No such object'));
    expect((await skiaPerfGcs.readPoints(testObjectName)).length, 0);
  });

  // The following is for integration tests.
  Bucket testBucket;
  final Map<String, dynamic> credentialsJson = getTestGcpCredentialsJson();
  if (credentialsJson != null) {
    final ServiceAccountCredentials credentials =
        ServiceAccountCredentials.fromJson(credentialsJson);

    final AutoRefreshingAuthClient client =
        await clientViaServiceAccount(credentials, Storage.SCOPES);
    final Storage storage =
        Storage(client, credentialsJson['project_id'] as String);

    const String kTestBucketName = 'flutter-skia-perf-test';

    assert(await storage.bucketExists(kTestBucketName));
    testBucket = storage.bucket(kTestBucketName);
  }

  Future<void> skiaPerfGcsAdapterIntegrationTest() async {
    final SkiaPerfGcsAdaptor skiaPerfGcs = SkiaPerfGcsAdaptor(testBucket);

    final String testObjectName = await SkiaPerfGcsAdaptor.comptueObjectName(
        kFlutterFrameworkRepo, kFrameworkRevision1);

    await skiaPerfGcs.writePoints(testObjectName, <SkiaPerfPoint>[
      SkiaPerfPoint.fromPoint(cocoonPointRev1Metric1),
      SkiaPerfPoint.fromPoint(cocoonPointRev1Metric2),
    ]);

    final List<SkiaPerfPoint> points =
        await skiaPerfGcs.readPoints(testObjectName);
    expect(points.length, equals(2));
    expectSetMatch(
        points.map((SkiaPerfPoint p) => p.testName), <String>[kTaskName]);
    expectSetMatch(points.map((SkiaPerfPoint p) => p.subResult),
        <String>[kMetric1, kMetric2]);
    expectSetMatch(
        points.map((SkiaPerfPoint p) => p.value), <double>[kValue1, kValue2]);
    expectSetMatch(points.map((SkiaPerfPoint p) => p.githubRepo),
        <String>[kFlutterFrameworkRepo]);
    expectSetMatch(points.map((SkiaPerfPoint p) => p.gitHash),
        <String>[kFrameworkRevision1]);
    for (int i = 0; i < 2; i += 1) {
      expect(points[0].jsonUrl, startsWith('https://'));
    }
  }

  Future<void> skiaPerfGcsIntegrationTestWithEnginePoints() async {
    final SkiaPerfGcsAdaptor skiaPerfGcs = SkiaPerfGcsAdaptor(testBucket);

    final String testObjectName = await SkiaPerfGcsAdaptor.comptueObjectName(
        kFlutterEngineRepo, engineRevision);

    await skiaPerfGcs.writePoints(testObjectName, <SkiaPerfPoint>[
      SkiaPerfPoint.fromPoint(enginePoint1),
      SkiaPerfPoint.fromPoint(enginePoint2),
    ]);

    final List<SkiaPerfPoint> points =
        await skiaPerfGcs.readPoints(testObjectName);
    expect(points.length, equals(2));
    expectSetMatch(
      points.map((SkiaPerfPoint p) => p.testName),
      <String>[engineMetricName, engineMetricName],
    );
    expectSetMatch(
      points.map((SkiaPerfPoint p) => p.value),
      <double>[engineValue1, engineValue2],
    );
    expectSetMatch(
      points.map((SkiaPerfPoint p) => p.githubRepo),
      <String>[kFlutterEngineRepo],
    );
    expectSetMatch(
        points.map((SkiaPerfPoint p) => p.gitHash), <String>[engineRevision]);
    for (int i = 0; i < 2; i += 1) {
      expect(points[0].jsonUrl, startsWith('https://'));
    }
  }

  // To run the following integration tests, there must be a valid Google Cloud
  // Project service account credentials in secret/test_gcp_credentials.json so
  // `testBucket` won't be null. Currently, these integration tests are skipped
  // in the CI, and only verified locally.
  test(
    'SkiaPerfGcsAdaptor passes integration test with Google Cloud Storage',
    skiaPerfGcsAdapterIntegrationTest,
    skip: testBucket == null,
  );

  test(
    'SkiaPerfGcsAdaptor integration test with engine points',
    skiaPerfGcsIntegrationTestWithEnginePoints,
    skip: testBucket == null,
  );

  test(
    'SkiaPerfGcsAdaptor integration test for name computations',
    () async {
      expect(
        await SkiaPerfGcsAdaptor.comptueObjectName(
            kFlutterFrameworkRepo, kFrameworkRevision1),
        equals(
            'flutter-flutter/2019/12/04/23/$kFrameworkRevision1/values.json'),
      );
      expect(
        await SkiaPerfGcsAdaptor.comptueObjectName(
            kFlutterEngineRepo, kEngineRevision1),
        equals('flutter-engine/2019/12/03/20/$kEngineRevision1/values.json'),
      );
      expect(
        await SkiaPerfGcsAdaptor.comptueObjectName(
            kFlutterEngineRepo, kEngineRevision2),
        equals('flutter-engine/2020/01/03/15/$kEngineRevision2/values.json'),
      );
    },
    skip: testBucket == null,
  );
482
}