summaryrefslogtreecommitdiffstats
path: root/webkit/tools/layout_tests/flakiness_dashboard.html
blob: fe45eb01df00daeedf1ae16013ca70dae5a5c5ab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
<!DOCTYPE HTML>
<html>

<head>
  <title>Webkit Layout Test History</title>
  <style>
    body {
      font-family: arial;
      font-size: 13px;
    }
    h2 {
      font-size: 16px;
      margin-bottom: .25em;
    }
    h3 {
      font-size: 13px;
      margin: 0;
    }
    #max-results-form {
      display: inline;
    }
    #max-results-input {
      width: 30px;
    }
    #tests-form {
      display: -webkit-box;
    }
    #tests-form > * {
      display: -webkit-box;
    }
    #tests-form > div {
      -webkit-box-flex: 0;
    }
    #tests-input {
      -webkit-box-flex: 1;
    }
    .test-link {
      white-space: normal;
    }
    .test-link, .options-container {
      padding: 0 2px;
    }
    .test-table {
      white-space: nowrap;
    }
    .test-table {
      width: 100%;
    }
    .test-table tr {
      border: 1px solid red;
      background-color: #E8E8E8;
    }
    .test-table tbody tr:hover {
      opacity: .7;
    }
    .test-table th {
      -webkit-user-select: none;
      -moz-user-select: none;
    }
    .link, .sortable .header-text {
      color: blue;
      text-decoration: underline;
      cursor: pointer;
    }
    .table-header-content,
    .table-header-content * {
      display: -webkit-box;
    }
    .table-header-content * {
      -webkit-box-flex: 1;
      cursor: pointer;
      white-space: normal;
    }
    .results {
      cursor: pointer;
      padding: 0;
      font-size: 10px;
      text-align: center;
    }
    #legend {
      position: fixed;
      top: 5px;
      right: 5px;
      width: 130px;
      border: 2px solid grey;
      background-color: white;
    }
    #legend-contents * {
      margin: 3px;
      padding: 0 2px;
    }
    body > div > :not(#legend) {
      margin-right: 145px;
    }
    #builders * {
      margin: 0 5px;
      display: inline-block;
      white-space: nowrap;
    }
    .test-table .wrong-expectations,
    .wrong-expectations {
      background-color: #afdaff;
    }
    .P {
      background-color: #8fdf5f;
    }
    .N {
      background-color: #e0b0ff;
    }
    .C {
      background-color: #ffc343;
    }
    .T {
      background-color: #fffc6c;
    }
    .I {
      background-color: #96f;
    }
    .S {
      background-color: #c6c;
    }
    .F {
      background-color: #e98080;
    }
    .O {
      background-color: #69f;
    }
    .merge {
      background-color: green;
    }
    :not(#legend-contents) > .merge {
      width: 1px;
    }
    .separator {
      border: 1px solid lightgray;
      height: 0px;
    }
    .different-platform {
      color: gray;
      font-size: 10px;
    }
    .current-builder {
      font-weight: bold;
    }
    #passing-tests {
      -webkit-column-count: 3;
      -webkit-column-gap: 25px;
      -webkit-column-rule: 1px dashed black;
      -moz-column-count: 3;
      -moz-column-gap: 25px;
      -moz-column-rule: 1px dashed black;
    }
    .not-found {
      color: red;
      font-size: large;
    }
    #loading-ui {
      display: none;
      position: fixed;
      top: 0;
      left: 0;
      background-color: yellow;
      padding: 5px;
      text-align: center;
      font-weight: bold;
    }
    #popup {
      background-color: white;
      z-index: 1;
      position: absolute;
      border: 3px solid grey;
      padding: 3px;
      -webkit-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.5);
      -moz-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.5);
      -webkit-border-radius: 5px;
      -moz-border-radius: 5px;
    }
    #popup > ul {
      margin: 0;
      padding-left: 20px;
    }
  </style>

  <script src="dashboards/dashboard_base.js"></script>
  <script>
  /**
   * @fileoverview Creates a dashboard for multiple runs of a given set of tests
   * on the buildbots. Pulls in JSONP-ish files with the results for running
   * tests on a given builder (i.e. ADD_RESULTS(json_here)) and the expectations
   * for all tests on all builders (i.e. ADD_EXPECTATIONS(json_here)).
   *
   * This shows flakiness of the tests as well as runtimes for slow tests.
   *
   * Also, each column in the dashboard is sortable.
   *
   * Currently, only webkit tests are supported, but adding other test types
   * should just require the following steps:
   *   -generate results.json and expectations.json for these tests
   *   -copy them to the appropriate location
   *   -add the builder name to the list of builders below.
   */

  //////////////////////////////////////////////////////////////////////////////
  // CONSTANTS
  //////////////////////////////////////////////////////////////////////////////
  var FORWARD = 'forward';
  var BACKWARD = 'backward';
  var TEST_URL_BASE_PATH =
      'http://trac.webkit.org/projects/webkit/browser/trunk/';
  var BUILDERS_BASE_PATH =
      'http://build.chromium.org/buildbot/waterfall/builders/';
  var TEST_RESULTS_BASE_PATH =
      'http://build.chromium.org/buildbot/layout_test_results/';
  var PLATFORMS = {'MAC': 'MAC', 'LINUX': 'LINUX', 'WIN': 'WIN'};
  var BUILD_TYPES = {'DEBUG': 'DBG', 'RELEASE': 'RELEASE'};
  var BASE_TABLE_HEADERS = ['bugs', 'modifiers', 'expectations', 'missing',
      'extra', 'slowest run', 'flakiness (numbers are runtimes in seconds)'];

  //////////////////////////////////////////////////////////////////////////////
  // Methods and objects from dashboard_base.js to override.
  //////////////////////////////////////////////////////////////////////////////
  function generatePage() {
    if (!currentState.tests && !('builder' in currentState)) {
      for (var builder in builders) {
        currentState.builder = builder;
        break;
      }
    }

    if (currentState.tests) {
      createTableHeadersArray('builder');
      generatePageForIndividualTests(currentState.tests.split(','));
    } else {
      createTableHeadersArray('test');
      generatePageForBuilder(currentState.builder);
    }

    $('max-results-input').value = currentState.maxResults;
    updateLegendDisplay();

    for (var builder in builders) {
      processTestResultsForBuilderAsync(builder);
    }
  }

  function handleValidHashParameter(key, value) {
    switch(key) {
      case 'tests':
        validateParameter(currentState, key, value,
            function() {
              return isValidName(value);
            });

        return true;

      case 'builder':
        validateParameter(currentState, key, value,
            function() {
              return value in builders;
            });

        return true;

      case 'sortColumn':
        validateParameter(currentState, key, value,
            function() {
              for (var i = 0; i < BASE_TABLE_HEADERS.length; i++) {
                if (value ==
                        getSortColumnFromTableHeader(BASE_TABLE_HEADERS[i]))
                  return true;
              }
              return value == 'test' || value == 'builder';
            });

        return true;

      case 'sortOrder':
        validateParameter(currentState, key, value,
            function() {
              return value == FORWARD || value == BACKWARD;
            });

        return true;

      case 'maxResults':
        validateParameter(currentState, key, value,
            function() {
              return value.match(/^\d+$/)
            });

        return true;

      case 'showWontFix':
      case 'showCorrectExpectations':
      case 'showFlaky':
      case 'showLegend':
      case 'showSkipped':
        currentState[key] = value == 'true';

        return true;

      default:
        return false;
    }
  }

  defaultStateValues = {
    sortOrder: BACKWARD,
    sortColumn: 'flakiness',
    showWontFix: false,
    showCorrectExpectations: false,
    showLegend: true,
    showFlaky: true,
    showSkipped: false,
    maxResults: 200,
  };

  //////////////////////////////////////////////////////////////////////////////
  // GLOBALS
  //////////////////////////////////////////////////////////////////////////////

  // Text to put inside the header for each column of the test table.
  var tableHeaders;
  var perBuilderPlatformAndBuildType = {};
  var perBuilderFailures = {};
  // Map of builder to arrays of tests that are listed in the expectations file
  // but have for that builder.
  var perBuilderWithExpectationsButNoFailures = {};
  // Map of builder to arrays of paths that are skipped. This shows the raw
  // path used in test_expectations.txt rather than the test path since we
  // don't actually have any data here for skipped tests.
  var perBuilderSkippedPaths = {};
  // Maps test path to an array of {builder, testResults} objects.
  var testToResultsMap = {};

  function createResultsObjectForTest(test) {
    return {
      test: test,
      // HTML for display of the results in the flakiness column
      html: '',
      flips: 0,
      slowestTime: 0,
      meetsExpectations: true,
      isWontFix: false,
      // Sorted string of missing expectations
      missing: '',
      // String of extra expectations (i.e. expectations that never occur).
      extra: '',
      // HTML for bug IDs for this test for all platforms
      bugsHTML: '',
      // HTML for expectations for this test for all platforms
      expectationsHTML: '',
      // HTML for modifiers for this test for all platforms
      modifiersHTML: '',
      rawResults: ''
    };
  }

  function getMatchingElement(stringToMatch, elementsMap) {
    for (var element in elementsMap) {
      if (stringContains(stringToMatch, elementsMap[element]))
        return element;
    }
  }

  /**
   * Returns whether the given string of modifiers applies to the platform and
   * build type of the given builder.
   */
  function hasPlatformAndBuildType(builderName, modifiers) {
    var platformAndBuildType = getPlatFormAndBuildType(builderName);
    var hasThisPlatform = stringContains(modifiers,
        platformAndBuildType.platform);
    var hasThisBuildType = stringContains(modifiers,
        platformAndBuildType.buildType);

    var hasAnyPlatform = anyKeyInString(PLATFORMS, modifiers);
    var hasAnyBuildType = anyKeyInString(BUILD_TYPES, modifiers);

    return (!hasAnyBuildType || hasThisBuildType) &&
        (!hasAnyPlatform || hasThisPlatform);
  }

  function getPlatFormAndBuildType(builderName) {
    if (!perBuilderPlatformAndBuildType[builderName]) {
      // If the build name does not contain a platform
      // or build type, assume Windows Release.
      var currentBuildUppercase = builderName.toUpperCase();
      var platform = getMatchingElement(currentBuildUppercase, PLATFORMS) ||
          'WIN';
      var buildType = getMatchingElement(currentBuildUppercase, BUILD_TYPES) ||
          'RELEASE';
      perBuilderPlatformAndBuildType[builderName] = {platform: platform,
          buildType: buildType};
    }
    return perBuilderPlatformAndBuildType[builderName];
  }

  /**
   * Returns whether any of the modifiers in the array have the correct
   * platform and build type for the given builder.
   */
  function getModifierThatHasPlatformAndBuildType(builderName, modifiersArray) {
    for (var i = 0; i < modifiersArray.length; i++) {
      if (hasPlatformAndBuildType(builderName, modifiersArray[i].modifiers))
        return modifiersArray[i];
    }
    return null;
  }

  /**
   * Returns the expectation string for the given single character result.
   * This string should match the expectations that are put into
   * test_expectations.py.
   *
   * For example, if we start explicitly listing IMAGE result failures,
   * this function should start returning 'IMAGE'.
   */
  function getExpectationsFileStringForResult(result) {
    // For the purposes of comparing against the expecations of a test,
    // consider image/simplified diff failures as just failures since
    // the test_expectations file doesn't treat them specially.
    if (result == 'F' || result == 'S' || result == 'I')
      return 'FAIL';

    if (result == 'N' || result == 'O')
      return '';

    return EXPECTATIONS_MAP[result];
  }

  // Map of all tests to true values. This is just so we can have the list of
  // all tests across all the builders.
  var allTests;

  /**
   * Returns a map of all tests to true values. This is just so we can have the
   * list of all tests across all the builders.
   */
  function getAllTests() {
    if (!allTests) {
      allTests = {};
      for (var builder in builders) {
        addTestsForBuilder(builder, allTests);
      }
    }
    return allTests;
  }

  /**
   * Adds all the tests for the given builder to the testMapToPopulate.
   */
  function addTestsForBuilder(builder, testMapToPopulate) {
    var tests = resultsByBuilder[builder].tests;
    for (var test in tests) {
      testMapToPopulate[test] = true;
    }
  }

  // Map of all tests to true values by platform and build type.
  // e.g. allTestsByPlatformAndBuildType['WIN']['DEBUG'] will have the union
  // of all tests run on the win-debug builders.
  var allTestsByPlatformAndBuildType = {};
  for (var platform in PLATFORMS) {
    allTestsByPlatformAndBuildType[platform] = {};
  }

  /**
   * Map of all tests to true values by platform and build type.
   * e.g. allTestsByPlatformAndBuildType['WIN']['DEBUG'] will have the union
   * of all tests run on the win-debug builders.
   */
  function getAllTestsWithSamePlatformAndBuildType(builder) {
    var buildInfo = getPlatFormAndBuildType(builder);
    var platform = buildInfo.platform;
    var buildType = buildInfo.buildType;

    if (!allTestsByPlatformAndBuildType[platform][buildType]) {
      var tests = {};
      for (var thisBuilder in builders) {
        var thisBuilderBuildInfo = getPlatFormAndBuildType(thisBuilder);
        if (thisBuilderBuildInfo.buildType == buildType &&
            thisBuilderBuildInfo.platform == platform) {
          addTestsForBuilder(thisBuilder, tests);
        }
      }
      allTestsByPlatformAndBuildType[platform][buildType] = tests;
    }

    return allTestsByPlatformAndBuildType[platform][buildType];
  }

  /**
   * Adds the given test and path to the appropriate objects depending on
   * whether the modifiers match the builders platform and buildType.
   */
  function addTestAndExpectations(test, prefixPath, builder, expectationsMap,
      expectations, testPrefixes, skippedPaths) {
    var modifiersForBuilder =
        getModifierThatHasPlatformAndBuildType(builder, expectations);

    if (!modifiersForBuilder)
      return false;

    if (getAllTestsWithSamePlatformAndBuildType(builder)[test]) {
      expectationsMap[test] = expectations;
      testPrefixes[test] = prefixPath;
    } else if (!stringContains(modifiersForBuilder.modifiers, 'WONTFIX')) {

      if (stringContains(modifiersForBuilder.modifiers, 'SKIP')) {
        skippedPaths[prefixPath] = true;
      } else if (!modifiersForBuilder.expectations.match(/^\s*PASS\s*$/)) {
        // Don't include skip tests here as they'll look the same as a test
        // that passes on all builders.
        // Also don't include tests that are only expected to pass, e.g.
        // SLOW : foo/bar/baz.html = PASS
        // TODO(ojan): Should we also exclude WONTFIX tests here?
        perBuilderWithExpectationsButNoFailures[builder].push(test);
      }
    }

    return true;
  }

  function addHTMLToIndividualOptionsArray(array, html, isCurrentPlatform) {
    if (html) {
      array.push('<div class="option' +
          (isCurrentPlatform ? '' : ' different-platform') + '">' + html +
          '</div>');
    }
  }

  function addHtmlToOptionsArrays(htmlArrays, expectations, modifiers, bugs,
      isCurrentPlatform) {
    addHTMLToIndividualOptionsArray(htmlArrays.expectations, expectations,
        isCurrentPlatform);
    addHTMLToIndividualOptionsArray(htmlArrays.modifiers, modifiers,
        isCurrentPlatform);
    addHTMLToIndividualOptionsArray(htmlArrays.bugs, getHtmlForBugs(bugs),
        isCurrentPlatform);
  }

  function processTestResultsForBuilderAsync(builder) {
    setTimeout(function() {
        processTestRunsForBuilder(builder);
      }, 0);
  }

  function processTestRunsForBuilder(builderName) {
    if (perBuilderFailures[builderName])
      return;

    var start = Date.now();

    var failures = [];
    var allTests = getAllTests();

    var expectationsMap = {};
    for (var test in allTests) {
      if (expectationsByTest[test])
        expectationsMap[test] = expectationsByTest[test];
    }

    var testPrefixes = {};
    perBuilderWithExpectationsButNoFailures[builderName] = [];
    var skippedPaths = {};
    for (var path in expectationsByTest) {
      var expectations = expectationsByTest[path];
      if (!isDirectory(path) &&
          addTestAndExpectations(path, path, builderName, expectationsMap,
              expectations, testPrefixes, skippedPaths)) {
        continue;
      }
      // Test path doesn't match a specific test, see if it prefix matches
      // any test.
      for (var test in allTests) {
        if (stringContains(test, path) &&
            (!testPrefixes[test] ||
             !stringContains(testPrefixes[test], path))) {
          addTestAndExpectations(test, path, builderName, expectationsMap,
              expectations, testPrefixes, skippedPaths);
        }
      }
    }

    perBuilderSkippedPaths[builderName] = [];
    for (var path in skippedPaths) {
      perBuilderSkippedPaths[builderName].push(path);
    }
    perBuilderSkippedPaths[builderName].sort();
    perBuilderWithExpectationsButNoFailures[builderName].sort();

    var allTestsForThisBuilder = resultsByBuilder[builderName].tests;
    for (var test in allTestsForThisBuilder) {
      var resultsForTest = createResultsObjectForTest(test);

      if (expectationsMap[test] && expectationsMap[test].length) {
        var expectationsArray = expectationsMap[test];
        var htmlArrays = {};
        htmlArrays.expectations = [];
        htmlArrays.modifiers = [];
        htmlArrays.bugs = [];

        var thisBuilderExpectations;
        var thisBuilderModifiers;
        for (var i = 0; i < expectationsArray.length; i++) {
          var modifiers = expectationsArray[i].modifiers;
          var bugs = modifiers.match(/BUG\d+/g);
          if (bugs) {
            for (var j = 0; j < bugs.length; j++) {
              modifiers = modifiers.replace(bugs[j], '');
            }
            modifiers = trimString(modifiers);
            bugs = bugs.join(' ');
          } else {
            bugs = '';
          }

          var expectations = expectationsArray[i].expectations;
          if (hasPlatformAndBuildType(builderName, modifiers)) {
            resultsForTest.bugs = bugs;
            resultsForTest.expectations = expectations;
            resultsForTest.modifiers = modifiers;
            // TODO(ojan): Also specially mark slow tests that should be marked
            // as slow or should have the slow modifier removed.
            resultsForTest.isWontFix = stringContains(modifiers, 'WONTFIX');
          } else {
            addHtmlToOptionsArrays(htmlArrays, expectations, modifiers, bugs,
                false);
          }
        }

        if (resultsForTest.expectations) {
          addHtmlToOptionsArrays(htmlArrays, resultsForTest.expectations,
              resultsForTest.modifiers, resultsForTest.bugs, true);
        }

        resultsForTest.bugsHTML +=
            htmlArrays.bugs.join('<div class=separator></div>');
        resultsForTest.expectationsHTML +=
            htmlArrays.expectations.join('<div class=separator></div>');
        resultsForTest.modifiersHTML +=
            htmlArrays.modifiers.join('<div class=separator></div>');
      }

      var rawTest = resultsByBuilder[builderName].tests[test];
      resultsForTest.rawTimes = rawTest.times;
      var rawResults = rawTest.results;
      resultsForTest.rawResults = rawResults;
      resultsForTest.flips = rawResults.length - 1;

      var unexpectedExpectations = [];
      var resultsMap = {}
      var numResultsSeen = 0;
      for (var i = 0;
           i < rawResults.length && numResultsSeen < currentState.maxResults;
           i++) {
        numResultsSeen += rawResults[i][0];
        var expectation = getExpectationsFileStringForResult(rawResults[i][1]);
        resultsMap[expectation] = true;
      }

      var expectationsArray = resultsForTest.expectations ?
          resultsForTest.expectations.split(' ') : [];
      var extraExpectations = expectationsArray.filter(
          function(element) {
              return element && !resultsMap[element] &&
                  !stringContains(element, 'BUG');
          });

      var missingExpectations = [];
      for (var result in resultsMap) {
        var hasExpectation = false;
        for (var i = 0; i < expectationsArray.length; i++) {
          if (result == expectationsArray[i])
            hasExpectation = true;
        }
        if (!hasExpectation)
          missingExpectations.push(result);
      }

      var times = resultsByBuilder[builderName].tests[test].times;
      var numResultsSeen = 0;
      for (var i = 0;
           i < times.length && numResultsSeen < currentState.maxResults;
           i++) {
        numResultsSeen += times[i][0];
        resultsForTest.slowestTime = Math.max(resultsForTest.slowestTime,
            times[i][1]);
      }

      if (resultsForTest.slowestTime && !resultsMap['TIMEOUT'] &&
          (!resultsForTest.expectations ||
           !stringContains(resultsForTest.expectations, 'TIMEOUT')) &&
          (!resultsForTest.modifiers ||
           !stringContains(resultsForTest.modifiers, 'SLOW'))) {
        missingExpectations.push('SLOW');
      }

      resultsForTest.meetsExpectations =
          !missingExpectations.length && !extraExpectations.length;
      resultsForTest.missing = missingExpectations.sort().join(' ');
      resultsForTest.extra = extraExpectations.sort().join(' ');

      failures.push(resultsForTest);

      if (!testToResultsMap[test])
        testToResultsMap[test] = [];
      testToResultsMap[test].push(
          {builder: builderName, results: resultsForTest});
    }

    perBuilderFailures[builderName] = failures;
    logTime('processTestRunsForBuilder: ' + builderName, start);
  }

  function hasExpectations(expectations, resultName) {
    if (resultName == 'NO DATA')
      return true;

    if (!expectations)
      return false;

    return stringContains(expectations, resultName);
  }

  var bugUrlPrefix = '<a href="http://';
  var bugUrlPostfix = '/$1">$1</a> ';
  var internalBugReplaceValue = bugUrlPrefix + 'b' + bugUrlPostfix;
  var externalBugReplaceValue = bugUrlPrefix + 'crbug.com' + bugUrlPostfix;

  /**
   * Returns the BUG modifiers linking to the bug.
   * Bugs with 4 or 5 digits are crbug.com bugs. Bugs with 6 or 7 digits
   * are internal google bugs.
   */
  function getHtmlForBugs(bugs) {
    bugs = bugs.replace(/BUG(\d{4})(\ |$)/g, externalBugReplaceValue);
    bugs = bugs.replace(/BUG(\d{5})(\ |$)/g, externalBugReplaceValue);
    bugs = bugs.replace(/BUG(\d{6})(\ |$)/g, internalBugReplaceValue);
    bugs = bugs.replace(/BUG(\d{7})(\ |$)/g, internalBugReplaceValue);
    return bugs;
  }

  function getLinkHTMLToOpenWindow(url, text) {
    return '<div class=link onclick="window.open(\'' + url + '\')">' + text +
        '</div>';
  }

  function createBlameListHTML(revisions, index, urlBase, separator, repo) {
    var thisRevision = revisions[index];
    if (!thisRevision)
      return '';

    var previousRevision = revisions[index + 1];
    if (previousRevision && previousRevision != thisRevision) {
      previousRevision++;
      return getLinkHTMLToOpenWindow(
          urlBase + thisRevision + separator + previousRevision,
          repo + ' blamelist r' + previousRevision + ':r' + thisRevision);
    } else {
      return 'At ' + repo + ' revision: ' + thisRevision;
    }
  }

  function showPopupForBuild(e, builder, index) {
    var html = '';

    var time = resultsByBuilder[builder].secondsSinceEpoch[index];
    if (time) {
      var date = new Date(time * 1000);
      html += date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
    }

    html += '<ul><li>' +
      createBlameListHTML(resultsByBuilder[builder].webkitRevision, index,
          'http://trac.webkit.org/log/?rev=', '&stop_rev=', 'WebKit') +
      '</li><li>' +
      createBlameListHTML(resultsByBuilder[builder].chromeRevision, index,
          'http://build.chromium.org/buildbot/perf/dashboard/ui/' +
          'changelog.html?url=/trunk/src&mode=html&range=', ':', 'Chrome') +
      '</li>';

    var chromeRevision = resultsByBuilder[builder].chromeRevision[index];
    if (chromeRevision) {
      html += '<li><a href="' + TEST_RESULTS_BASE_PATH + builders[builder] +
          '/' + chromeRevision + '/layout-test-results.zip' +
          '">layout-test-results.zip</a></li>';
    }

    var buildNumbers = resultsByBuilder[builder].buildNumbers;
    html += '<li>' +
        getLinkHTMLToOpenWindow(BUILDERS_BASE_PATH + builder + '/builds/' +
        buildNumbers[index], 'Build log and blamelist') + '</li></ul>';

    showPopup(e, html);
  }

  function showPopupForTest(e, test) {
    showPopup(e, getHTMLForIndividulTestOnAllBuilders(test));
  }

  function getHtmlForTestResults(test, builder) {
    var html = '';
    var results = test.rawResults.concat();
    var times = test.rawTimes.concat();
    var buildNumbers = resultsByBuilder[builder].buildNumbers;

    var indexToReplaceCurrentResult = -1;
    var indexToReplaceCurrentTime = -1;
    var currentResultArray, currentTimeArray, currentResult, innerHTML;
    var maxIndex = Math.min(buildNumbers.length, currentState.maxResults);
    for (var i = 0; i < maxIndex; i++) {
      if (i > indexToReplaceCurrentResult) {
        currentResultArray = results.shift();
        if (currentResultArray) {
          currentResult = currentResultArray[1];
          indexToReplaceCurrentResult += currentResultArray[0];
        } else {
          currentResult = 'N';
          indexToReplaceCurrentResult += buildNumbers.length;
        }
      }

      if (i > indexToReplaceCurrentTime) {
        currentTimeArray = times.shift();
        var currentTime = 0;
        if (currentResultArray) {
          currentTime = currentTimeArray[1];
          indexToReplaceCurrentTime += currentTimeArray[0];
        } else {
          indexToReplaceCurrentTime += buildNumbers.length;
        }
        innerHTML = currentTime || '&nbsp;';
      }

      html += '<td title="Click results for handy links." class="results ' +
          currentResult + '" onclick=\'showPopupForBuild(event, "' + builder +
          '",' + i + ')\'>' + innerHTML + '</td>';

      var webkitRevision = resultsByBuilder[builder].webkitRevision;
      var isWebkitMerge = webkitRevision[i + 1] &&
          webkitRevision[i] != webkitRevision[i + 1];
      if (isWebkitMerge)
        html += '<td class=merge></td>';
    }
    return html;
  }

  function getHTMLForTestsWithExpectationsButNoFailures(builder) {
    var tests = perBuilderWithExpectationsButNoFailures[builder];
    var skippedPaths = perBuilderSkippedPaths[builder];

    var html = '';
    if (tests.length || skippedPaths.length) {
      var buildInfo = getPlatFormAndBuildType(builder);
      html += '<h2>Expectations for ' + buildInfo.platform + '-' +
          buildInfo.buildType + ':</h2>';
    }

    if (tests.length) {
      html +=  '<h3>Have not failed in last ' +
          resultsByBuilder[builder].buildNumbers.length +
          ' runs.</h3><div id="passing-tests"><div>' +
          tests.join('</div><div>') + '</div></div>';
    }

    if (skippedPaths.length) {
      html += '<h3>' +
          getLinkHTMLToToggleState('showSkipped',
              'Skipped tests in text_expectations.txt') +
          '</h3>';

      if (currentState.showSkipped) {
        html += '<div id="passing-tests"><div>' +
          skippedPaths.join('</div><div>') + '</div></div>';
      }
    }
    return html;
  }

  /**
   * Returns true if a test should be considered flaky. Uses heuristics to
   * avoid common non-flaky cases.
   */
  function isTestFlaky(testResult) {
    return testResult.flips > 1 && !isFixedTest(testResult);
  }

  /**
   * Returns whether this tests results match the heuristic for new tests that
   * have been fixed. Specifically, a new test that fails a couple
   * times and then passes from then on would have results like PPPPFFFFNNNNN.
   * Where that middle part can be a series of F's, S's or I's for the
   * different types of failures.
   */
  function isFixedTest(testResult) {
    if (testResult.isFixedTest === undefined) {
      var results = testResult.rawResults;
      var isFixedTest = results[0][1] == 'P';
      var numResults = results[0][0];
      if (numResults < currentState.maxResults &&
          isFixedTest && results.length > 1) {
        // We don't care what the value of the second set of results is, just
        // how many results there are.
        numResults += results[1][0];
      }
      if (numResults < currentState.maxResults &&
          isFixedTest && results.length > 2) {
        isFixedTest = results.length == 3 && results[2][1] == 'N';
      }
      testResult.isFixedTest = isFixedTest;
    }
    return testResult.isFixedTest;
  }

  /**
   * Returns whether the test has passed continuously for at
   * least as many runs as we are showing results for.
   */
   function hasPassedInMaxRuns(testResult) {
     var results = testResult.rawResults;
     return results[0][1] == 'P' && results[0][0] >= currentState.maxResults;
   }

  /**
   * Returns whether we should exclude test results from the test table.
   * Note that we never want to exclude tests when we're in the individual
   * tests view of the dashboard since the user is explicitly listing tests
   * to view.
   */
  function shouldHideTest(testResult) {
    if (currentState.tests)
      return false;

    if (testResult.isWontFix && !currentState.showWontFix)
      return true;

     if (hasPassedInMaxRuns(testResult)) {
      // Hide tests that are passing.
      return true;
    }

    if ((testResult.meetsExpectations || isFixedTest(testResult)) &&
        !currentState.showCorrectExpectations) {
      // Only hide flaky tests that match their expectations if showFlaky
      // is false.
      return !currentState.showFlaky || !isTestFlaky(testResult);
    }

    return !currentState.showFlaky && isTestFlaky(testResult);
  }

  function getHTMLForSingleTestRow(test, builder, opt_isCrossBuilderView) {
    if (shouldHideTest(test)) {
      // The innerHTML call is considerably faster if we exclude the rows for
      // items we're not showing than if we hide them using display:none.
      return '';
    }

    // If opt_isCrossBuilderView is true, we're just viewing a single test
    // with results for many builders, so the first column is builder names
    // instead of test paths.
    var testCellHTML = opt_isCrossBuilderView ? builder :
      '<span class="link" onclick="showPopupForTest(event, \'' + test.test +
      '\');return false;">' + test.test + '</span>';

    return '<tr class="' +
      (test.meetsExpectations ? '' : 'wrong-expectations') +
      // TODO(ojan): If a test is a chrome/ or a pending/ test, point to
      // src.chromium.org instead of trac.webkit.org.
      '"><td class=test-link>' + testCellHTML +
      '</td><td class=options-container>' + test.bugsHTML +
      '</td><td class=options-container>' + test.modifiersHTML +
      '</td><td class=options-container>' + test.expectationsHTML +
      '</td><td>' + test.missing +
      '</td><td>' + test.extra +
      '</td><td>' + (test.slowestTime ? test.slowestTime + 's' : '') +
      '</td>' + getHtmlForTestResults(test, builder) + '</tr>';
  }

  function getSortColumnFromTableHeader(headerText) {
    return headerText.split(' ', 1)[0];
  }

  function getHTMLForTestTable(rowsHTML) {
    var html = '<table class=test-table><thead><tr>';
    for (var i = 0; i < tableHeaders.length; i++) {
      // Use the first word of the header title as the sortkey
      var thisSortValue = getSortColumnFromTableHeader(tableHeaders[i]);
      var arrowHTML = thisSortValue == currentState.sortColumn ?
          '<span class=' + currentState.sortOrder + '>' +
          (currentState.sortOrder == FORWARD ? '&uarr;' : '&darr;' ) +
          '</span>' :
          '';
      html += '<th sortValue=' + thisSortValue +
          // Extend last th through all the rest of the columns.
          (i == tableHeaders.length - 1 ? ' colspan=10000' : '') +
          // Extra span here is so flex boxing actually centers.
          // There's probably a better way to do this with CSS only though.
          '><div class=table-header-content><span></span>' + arrowHTML +
          '<span class=header-text>' + tableHeaders[i] + '</span>' +
          arrowHTML + '</div></th>';
    }
    return html + '</tr></thead><tbody>' + rowsHTML + '</tbody></table>';
  }

  function setFullPageHTML(html) {
    var startTime = Date.now();
    // InnerHTML to a div that's not in the document. This is
    // ~300ms faster in Safari 4 and Chrome 4 on mac.
    var div = document.createElement('div');
    div.innerHTML = html;
    document.body.innerHTML = '';
    document.body.appendChild(div);
    logTime('Time to innerHTML', startTime);
  }

  function getAlphanumericCompare(column, reverse) {
    return getReversibleCompareFunction(function(a, b) {
      // Put null entries at the bottom
      var a = a[column] ? String(a[column]) : 'z';
      var b = b[column] ? String(b[column]) : 'z';

      if (a < b)
        return -1;
      else if (a == b)
        return 0;
      else
        return 1;
    }, reverse);
  }

  function getNumericSort(column, reverse) {
    return getReversibleCompareFunction(function(a, b) {
      a = parseFloat(a[column]);
      b = parseFloat(b[column]);
      return a - b;
    }, reverse);
  }

  function getReversibleCompareFunction(compare, reverse) {
    return function(a, b) {
      return compare(reverse ? b : a, reverse ? a : b);
    }
  }

  function changeSort(e) {
    var target = e.currentTarget;
    e.preventDefault();

    var sortValue = target.getAttribute('sortValue');
    while (target && target.tagName != 'TABLE') {
      target = target.parentNode;
    }

    var sort = 'sortColumn';
    var orderKey = 'sortOrder';
    if (sortValue == currentState[sort] && currentState[orderKey] == FORWARD)
      order = BACKWARD;
    else
      order = FORWARD;

    setState(sort, sortValue, orderKey, order);
  }

  function sortTests(tests, column, order) {
    var resultsProperty, sortFunctionGetter;
    if (column == 'flakiness') {
      sortFunctionGetter = getNumericSort;
      resultsProperty = 'flips';
    } else if (column == 'slowest') {
      sortFunctionGetter = getNumericSort;
      resultsProperty = 'slowestTime';
    } else {
      sortFunctionGetter = getAlphanumericCompare;
      resultsProperty = column;
    }

    tests.sort(sortFunctionGetter(resultsProperty, order == BACKWARD));
  }

  function getHTMLForIndividulTestOnAllBuilders(test) {
    for (var builder in builders)
      processTestRunsForBuilder(builder);

    var testResults = testToResultsMap[test];
    if (testResults && testResults.length) {
      var tracURL = TEST_URL_BASE_PATH + test
      var html = getLinkHTMLToOpenWindow(tracURL, tracURL) +
          '<div><b>If a builder is not listed, that means the builder does ' +
          'run that test or all runs of the test passed.</b></div>';

      for (var j = 0; j < testResults.length; j++) {
        html += getHTMLForSingleTestRow(testResults[j].results,
            testResults[j].builder, true);
      }
      return getHTMLForTestTable(html);
    } else {
      return '<div class="not-found">Test not found. Either it does not ' +
          'exist or it passes on all platforms.</div>';
    }
  }

  function generatePageForIndividualTests(tests) {
    var html = getHTMLForNavBar();
    for (var i = 0; i < tests.length; i++) {
      html += '<h2>' + tests[i] + '</h2>' +
          getHTMLForIndividulTestOnAllBuilders(tests[i]);
    }
    setFullPageHTML(html);

    $('tests-input').value = currentState.tests;
  }

  function getHTMLForNavBar(opt_builderName) {
    var html = '<div id=builders>';
    for (var builder in builders) {
      var className = builder == opt_builderName ? 'current-builder' : 'link';
      html += '<span class=' + className +
          ' onclick=\'setState("builder", "' + builder + '")\'>' +
          builder + '</span>';
    }
    html += '</div>' +
        '<form id=tests-form ' +
        'onsubmit="setState(\'tests\', tests.value);return false;">' +
        '<div>Show tests on all platforms (slow): </div><input name=tests ' +
        'placeholder="LayoutTests/foo/bar.html,LayoutTests/foo/baz.html" ' +
        'id=tests-input></form>' +
        '<form id=max-results-form ' +
        'onsubmit="setState(\'maxResults\', maxResults.value);return false;"' +
        '><span>Number of results to show (max=500): </span>' +
        '<input name=maxResults id=max-results-input></form>' +
        '<div id="loading-ui">LOADING...</div><div id=legend>' +
        '<div id=legend-toggle>' + getLinkHTMLToToggleLegendDisplay() +
        '</div><div id=legend-contents>';

    for (var expectation in EXPECTATIONS_MAP) {
      html += '<div class=' + expectation + '>' +
          EXPECTATIONS_MAP[expectation] + '</div>';
    }
    return html + '<div class=wrong-expectations>WRONG EXPECTATIONS</div>' +
        '<div class=merge>WEBKIT MERGE</div></div></div>';
  }

  function getLinkHTMLToToggleState(key, linkText) {
    var isTrue = currentState[key];
    return '<span class=link onclick="setState(\'' + key + '\', ' + !isTrue +
        ')">' + (isTrue ? 'Hide' : 'Show') + ' ' + linkText + '</span>';
  }

  function generatePageForBuilder(builderName) {
    processTestRunsForBuilder(builderName);

    var tableRowsHTML = '';
    var results = perBuilderFailures[builderName];
    sortTests(results, currentState.sortColumn, currentState.sortOrder);
    for (var i = 0; i < results.length; i++) {
      tableRowsHTML += getHTMLForSingleTestRow(results[i], builderName);
    }

    var testsHTML = tableRowsHTML ? getHTMLForTestTable(tableRowsHTML) :
        '<div>No tests. Try showing tests with correct expectations.</div>';

    var html = getHTMLForNavBar(builderName) +
        getHTMLForTestsWithExpectationsButNoFailures(builderName) +
        '<h2>Failing tests</h2><div>' +
        getLinkHTMLToToggleState('showWontFix', 'WONTFIX tests') + ' | ' +
        getLinkHTMLToToggleState('showCorrectExpectations',
            'tests with correct expectations') + ' | ' +
        getLinkHTMLToToggleState('showFlaky', 'flaky tests') + ' | ' +
        '<b>All columns are sortable. | ' +
        'Flakiness reader order is newer --> older runs.</b></div>' +
        testsHTML;

    setFullPageHTML(html);

    var ths = document.getElementsByTagName('th');
    for (var i = 0; i < ths.length; i++) {
      ths[i].addEventListener('click', changeSort, false);
      ths[i].className = "sortable";
    }
  }

  function getLinkHTMLToToggleLegendDisplay() {
    return getLinkHTMLToToggleState('showLegend', 'Legend');
  }

  function updateLegendDisplay() {
    $('legend-contents').style.display = currentState.showLegend ? '' : 'none';
  }

  function createTableHeadersArray(firstColumnHeader) {
    tableHeaders = [firstColumnHeader].concat(BASE_TABLE_HEADERS);
  }

  /**
   * Clears the processed test state for perBuilderFailures.
   * TODO(ojan): This really should probably clear all the state we've
   * generated, but that's kind of a pain given the many global objects state is
   * stored in. There should probably be one global generatedState
   * object that all the generated state lives off of.
   */
  function clearProcessedTestState() {
    for (var builder in builders) {
      delete perBuilderFailures[builder];
      delete perBuilderPlatformAndBuildType[builder];
      delete perBuilderWithExpectationsButNoFailures[builder];
      delete perBuilderSkippedPaths[builder];
    }

    for (var key in testToResultsMap) {
      delete testToResultsMap[key]
    }
  }

  /**
   * Sets the page state and regenerates the page. Takes varargs of key, value
   * pairs.
   */
  function setState(key, value) {
    var keys = setQueryParameter.apply(null, arguments);
    var shouldRegeneratePage = true;
    for (var i = 0; i < keys.length; i++) {
      var key = keys[i];

      if (key != 'tests' && key != 'maxResults') {
        delete currentState.tests;
      }

      if (key == 'maxResults') {
        // Processing the test results JSON makes assumptions about the number
        // of results to show. This makes changing the number of maxResults slow
        // but is considerably easier than refactoring all the other code.
        clearProcessedTestState();
      }

      if (key == 'showLegend') {
        // No need to regenerate the page if only the legend's display is being
        // updated.
        shouldRegeneratePage = keys.length == 1;
        updateLegendDisplay();
        $('legend-toggle').innerHTML = getLinkHTMLToToggleLegendDisplay();
      }
    }

    if (shouldRegeneratePage)
      handleLocationChange();
  }


  </script>
</head>

<body></body>
</html>