File: extract_histograms_test.py

package info (click to toggle)
chromium 120.0.6099.224-1~deb11u1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 6,112,112 kB
  • sloc: cpp: 32,907,025; ansic: 8,148,123; javascript: 3,679,536; python: 2,031,248; asm: 959,718; java: 804,675; xml: 617,256; sh: 111,417; objc: 100,835; perl: 88,443; cs: 53,032; makefile: 29,579; fortran: 24,137; php: 21,162; tcl: 21,147; sql: 20,809; ruby: 17,735; pascal: 12,864; yacc: 8,045; lisp: 3,388; lex: 1,323; ada: 727; awk: 329; jsp: 267; csh: 117; exp: 43; sed: 37
file content (1012 lines) | stat: -rw-r--r-- 37,675 bytes parent folder | download
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
# Copyright 2017 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import logging
from parameterized import parameterized
import unittest
import xml.dom.minidom

import extract_histograms
import histogram_configuration_model

TEST_SUFFIX_OBSOLETION_XML_CONTENT = """
<histogram-configuration>
<histograms>
  <histogram name="Test.Test1" units="units" expires_after="2019-01-01">
    <owner>chrome-metrics-team@google.com</owner>
    <summary>
      Sample description.
    </summary>
  </histogram>
  <histogram name="Test.Test2" units="units" expires_after="2019-01-01">
    <owner>chrome-metrics-team@google.com</owner>
    <summary>
      Sample description.
    </summary>
  </histogram>
</histograms>
<histogram_suffixes_list>
  <histogram_suffixes name="NonObsoleteSuffix" separator="_">
    <suffix name="NonObsolete1" label="First non-obsolete suffix"/>
    <suffix name="NonObsolete2" label="Second non-obsolete suffix"/>
    <affected-histogram name="Test.Test1"/>
    <affected-histogram name="Test.Test2"/>
  </histogram_suffixes>

  <histogram_suffixes name="ObsoleteSuffixGroup" separator="_">
    <obsolete>This suffix group is obsolete</obsolete>
    <suffix name="ObsoleteSuffixGroup1" label="First obsolete suffix"/>
    <suffix name="ObsoleteSuffixGroup2" label="Second obsolete suffix"/>
    <affected-histogram name="Test.Test1"/>
  </histogram_suffixes>

  <histogram_suffixes name="ObsoleteSuffixNonObsoleteGroup" separator="_">
    <suffix name="ObsoleteSuffixNonObsoleteGroup1" label="Obsolete suffix">
      <obsolete>This suffix is obsolete</obsolete>
    </suffix>
    <suffix name="NonObsoleteSuffixNonObsoleteGroup2"
        label="Non obsolete suffix"/>
    <affected-histogram name="Test.Test2"/>
  </histogram_suffixes>

  <histogram_suffixes name="ObsoleteSuffixObsoleteGroup" separator="_">
    <obsolete>This suffix group is obsolete</obsolete>
    <suffix name="ObsoleteSuffixObsoleteGroup1" label="First obsolete suffix">
      <obsolete>This suffix is obsolete</obsolete>
    </suffix>
    <suffix name="NonObsoleteSuffixObsoleteGroup2"
        label="Second obsolete suffix"/>
    <affected-histogram name="Test.Test2"/>
  </histogram_suffixes>
</histogram_suffixes_list>
</histogram-configuration>
"""

TEST_BASE_HISTOGRAM_XML_CONTENT = """
<histogram-configuration>
<histograms>
  <histogram base="true" name="Test.Base" units="units"
      expires_after="2211-11-22">
    <owner>chrome-metrics-team@google.com</owner>
    <summary>
      Base histogram.
    </summary>
  </histogram>
  <histogram base="true" name="Test.Base.Obsolete" units="units"
      expires_after="2019-01-01">
    <owner>chrome-metrics-team@google.com</owner>
    <summary>
      Obsolete base histogram.
    </summary>
    <obsolete>
      The whole related set of histograms is obsolete!
    </obsolete>
  </histogram>
  <histogram base="false" name="Test.NotBase.Explicit" units="units"
      expires_after="2019-01-01">
    <owner>chrome-metrics-team@google.com</owner>
    <summary>
      Not a base histogram: base attribute explicitly set to "false".
    </summary>
  </histogram>
  <histogram name="Test.NotBase.Implicit" units="units"
      expires_after="M100">
    <owner>chrome-metrics-team@google.com</owner>
    <summary>
      Not a base histogram: no base attribute specified.
    </summary>
  </histogram>
</histograms>
<histogram_suffixes_list>
  <histogram_suffixes name="Suffixes" separator=".">
    <suffix base="true" name="BaseSuffix" label="A base suffix"/>
    <suffix name="NonBaseSuffix" label="A non-base suffix"/>
    <suffix name="ObsoleteSuffix" label="An obsolete suffix">
      <obsolete>This suffix is obsolete!</obsolete>
    </suffix>
    <affected-histogram name="Test.Base"/>
    <affected-histogram name="Test.Base.Obsolete"/>
  </histogram_suffixes>

  <histogram_suffixes name="SuffixesPlusPlus" separator=".">
    <suffix name="One" label="One suffix"/>
    <suffix name="Two" label="Another suffix"/>
    <affected-histogram name="Test.Base.BaseSuffix"/>
    <affected-histogram name="Test.Base.NonBaseSuffix"/>
  </histogram_suffixes>
</histogram_suffixes_list>
</histogram-configuration>
"""

TEST_HISTOGRAM_WITH_TOKENS = """
<histogram-configuration>
<histograms>
<histogram name="HistogramName.{Color}{Size}" expires_after="2017-10-16">
  <owner>me@chromium.org</owner>
  <summary>
    This is a histogram for button of {Color} color and {Size} size.
  </summary>
  <token key="Color">
    <variant name="red">
      <obsolete>
        Obsolete red
      </obsolete>
    </variant>
    <variant name="green">
      <owner>green@chromium.org</owner>
    </variant>
  </token>
  <token key="Size">
    <variant name="" summary="all"/>
    <variant name=".small" summary="small">
      <owner>small@chromium.org</owner>
      <obsolete>
        Obsolete small
      </obsolete>
    </variant>
    <variant name=".medium" summary="medium"/>
    <variant name=".large" summary="large"/>
  </token>
</histogram>
</histograms>
</histogram-configuration>
"""

TEST_HISTOGRAM_WITH_VARIANTS = """
<histogram-configuration>
<histograms>
<variants name="HistogramNameSize">
  <variant name="" summary="all"/>
  <variant name=".small" summary="small">
    <owner>small@chromium.org</owner>
    <obsolete>
      Obsolete small
    </obsolete>
  </variant>
  <variant name=".medium" summary="medium"/>
  <variant name=".large" summary="large"/>
</variants>

<histogram name="HistogramName.{Color}{Size}" expires_after="2017-10-16">
  <owner>me@chromium.org</owner>
  <summary>
    This is a histogram for button of {Color} color and {Size} size.
  </summary>
  <token key="Color">
    <variant name="red">
      <obsolete>
        Obsolete red
      </obsolete>
    </variant>
    <variant name="green">
      <owner>green@chromium.org</owner>
    </variant>
  </token>
  <token key="Size" variants="HistogramNameSize"/>
</histogram>
</histograms>
</histogram-configuration>
"""

TEST_HISTOGRAM_TOKENS_DUPLICATE = """
<histogram-configuration>
<histograms>
<histogram name="Histogram{Color}{Size}" units="things"
    expires_after="2017-10-16">
  <owner>me@chromium.org</owner>
  <summary>
    This is a histogram for button of {Color} color and {Size} size.
  </summary>
  <token key="Color">
    <variant name="" summary="all"/>
    <variant name=".red" summary="red"/>
    <variant name=".green" summary="green"/>
  </token>
  <token key="Size">
    <variant name="" summary="all"/>
    <variant name=".red" summary="red"/>
    <variant name=".small" summary="small"/>
    <variant name=".medium" summary="medium"/>
    <variant name=".large" summary="large"/>
  </token>
</histogram>
</histograms>
</histogram-configuration>
"""

TEST_HISTOGRAM_VARIANTS_DUPLICATE = """
<histogram-configuration>
<variants name="HistogramNameSize">
  <variant name="" summary="all"/>
  <variant name=".red" summary="red"/>
  <variant name=".small" summary="small"/>
  <variant name=".medium" summary="medium"/>
  <variant name=".large" summary="large"/>
</variants>

<histograms>
<histogram name="Histogram{Color}{Size}" units="things"
    expires_after="2017-10-16">
  <owner>me@chromium.org</owner>
  <summary>
    This is a histogram for button of {Color} color and {Size} size.
  </summary>
  <token key="Color">
    <variant name="" summary="all"/>
    <variant name=".red" summary="red"/>
    <variant name=".green" summary="green"/>
  </token>
  <token key="Size" variants="HistogramNameSize"/>
</histogram>
</histograms>
</histogram-configuration>
"""


TEST_HISTOGRAM_WITH_MIXED_VARIANTS = """
<histogram-configuration>
<histograms>
<variants name="HistogramNameSize">
  <variant name=".medium" summary="medium"/>
  <variant name=".large" summary="large"/>
</variants>

<histogram name="HistogramName.{Color}{Size}" expires_after="2017-10-16">
  <owner>me@chromium.org</owner>
  <summary>
    This is a histogram for button of {Color} color and {Size} size.
  </summary>
  <token key="Color">
    <variant name="red">
      <obsolete>
        Obsolete red
      </obsolete>
    </variant>
    <variant name="green">
      <owner>green@chromium.org</owner>
    </variant>
  </token>
  <token key="Size" variants="HistogramNameSize">
    <variant name="" summary="all"/>
    <variant name=".small" summary="small">
      <owner>small@chromium.org</owner>
      <obsolete>
        Obsolete small
      </obsolete>
    </variant>
  </token>
</histogram>
</histograms>
</histogram-configuration>
"""

class ExtractHistogramsTest(unittest.TestCase):

  def testSuffixObsoletion(self):
    histograms, had_errors = extract_histograms.ExtractHistogramsFromDom(
        xml.dom.minidom.parseString(TEST_SUFFIX_OBSOLETION_XML_CONTENT))
    self.assertFalse(had_errors)
    # Obsolete on suffixes doesn't affect the source histogram
    self.assertNotIn('obsolete', histograms['Test.Test1'])
    self.assertNotIn('obsolete', histograms['Test.Test2'])

    self.assertNotIn('obsolete', histograms['Test.Test1_NonObsolete1'])
    self.assertNotIn('obsolete', histograms['Test.Test1_NonObsolete2'])
    self.assertNotIn('obsolete', histograms['Test.Test2_NonObsolete1'])
    self.assertNotIn('obsolete', histograms['Test.Test2_NonObsolete2'])

    self.assertIn('obsolete', histograms['Test.Test1_ObsoleteSuffixGroup1'])
    self.assertIn('obsolete', histograms['Test.Test1_ObsoleteSuffixGroup2'])

    # Obsolete suffixes should apply to individual suffixes and not their group.
    self.assertIn('obsolete',
                  histograms['Test.Test2_ObsoleteSuffixNonObsoleteGroup1'])
    self.assertNotIn(
        'obsolete', histograms['Test.Test2_NonObsoleteSuffixNonObsoleteGroup2'])
    self.assertEqual(
        'This suffix is obsolete',
        histograms['Test.Test2_ObsoleteSuffixNonObsoleteGroup1']['obsolete'])

    # Obsolete suffix reasons should overwrite the suffix group's obsoletion
    # reason.
    self.assertIn('obsolete',
                  histograms['Test.Test2_ObsoleteSuffixObsoleteGroup1'])
    self.assertIn('obsolete',
                  histograms['Test.Test2_NonObsoleteSuffixObsoleteGroup2'])
    self.assertEqual(
        'This suffix is obsolete',
        histograms['Test.Test2_ObsoleteSuffixObsoleteGroup1']['obsolete'])
    self.assertEqual(
        'This suffix group is obsolete',
        histograms['Test.Test2_NonObsoleteSuffixObsoleteGroup2']['obsolete'])

  def testBaseHistograms(self):
    histograms, had_errors = extract_histograms.ExtractHistogramsFromDom(
        xml.dom.minidom.parseString(TEST_BASE_HISTOGRAM_XML_CONTENT))
    self.assertFalse(had_errors)
    # Base histograms are implicitly marked as obsolete.
    self.assertIn('obsolete', histograms['Test.Base'])
    self.assertIn('obsolete', histograms['Test.Base.Obsolete'])

    # Other histograms shouldn't be implicitly marked as obsolete.
    self.assertNotIn('obsolete', histograms['Test.NotBase.Explicit'])
    self.assertNotIn('obsolete', histograms['Test.NotBase.Implicit'])

    # Suffixes applied to base histograms shouldn't be marked as obsolete...
    self.assertNotIn('obsolete', histograms['Test.Base.NonBaseSuffix'])
    # ... unless the suffix is marked as obsolete,
    self.assertIn('obsolete', histograms['Test.Base.ObsoleteSuffix'])
    # ... or the suffix is a base suffix,
    self.assertIn('obsolete', histograms['Test.Base.BaseSuffix'])
    # ... or the base histogram is marked as obsolete,
    self.assertIn('obsolete', histograms['Test.Base.Obsolete.BaseSuffix'])
    self.assertIn('obsolete', histograms['Test.Base.Obsolete.NonBaseSuffix'])
    self.assertIn('obsolete', histograms['Test.Base.Obsolete.ObsoleteSuffix'])

    # It should be possible to have multiple levels of suffixes for base
    # histograms.
    self.assertNotIn('obsolete', histograms['Test.Base.BaseSuffix.One'])
    self.assertNotIn('obsolete', histograms['Test.Base.BaseSuffix.Two'])
    self.assertNotIn('obsolete', histograms['Test.Base.NonBaseSuffix.One'])
    self.assertNotIn('obsolete', histograms['Test.Base.NonBaseSuffix.Two'])

  def testExpiryFormat(self):
    chrome_histogram_pattern = """<histogram-configuration>

<histograms>

<histogram name="Histogram.Name" units="units" {}>
  <owner>SomeOne@google.com</owner>
  <summary>Summary</summary>
</histogram>

</histograms>

</histogram-configuration>
"""
    chrome_histogram_correct_expiry_date = chrome_histogram_pattern.format(
        'expires_after="2211-11-22"')
    _, had_errors = extract_histograms.ExtractHistogramsFromDom(
        xml.dom.minidom.parseString(chrome_histogram_correct_expiry_date))
    self.assertFalse(had_errors)

    chrome_histogram_wrong_expiry_date_format = chrome_histogram_pattern.format(
        'expires_after="2211/11/22"')
    _, had_errors = extract_histograms.ExtractHistogramsFromDom(
        xml.dom.minidom.parseString(chrome_histogram_wrong_expiry_date_format))
    self.assertTrue(had_errors)

    chrome_histogram_wrong_expiry_date_value = chrome_histogram_pattern.format(
        'expires_after="2211-22-11"')
    _, had_errors = extract_histograms.ExtractHistogramsFromDom(
        xml.dom.minidom.parseString(chrome_histogram_wrong_expiry_date_value))
    self.assertTrue(had_errors)

    chrome_histogram_correct_expiry_milestone = chrome_histogram_pattern.format(
        'expires_after="M22"')
    _, had_errors = extract_histograms.ExtractHistogramsFromDom(
        xml.dom.minidom.parseString(chrome_histogram_correct_expiry_milestone))
    self.assertFalse(had_errors)

    chrome_histogram_wrong_expiry_milestone = chrome_histogram_pattern.format(
        'expires_after="22"')
    _, had_errors = extract_histograms.ExtractHistogramsFromDom(
        xml.dom.minidom.parseString(chrome_histogram_wrong_expiry_milestone))
    self.assertTrue(had_errors)

    chrome_histogram_wrong_expiry_milestone = chrome_histogram_pattern.format(
        'expires_after="MM22"')
    _, had_errors = extract_histograms.ExtractHistogramsFromDom(
        xml.dom.minidom.parseString(chrome_histogram_wrong_expiry_milestone))
    self.assertTrue(had_errors)

    chrome_histogram_no_expiry = chrome_histogram_pattern.format('')
    _, had_errors = extract_histograms.ExtractHistogramsFromDom(
        xml.dom.minidom.parseString(chrome_histogram_no_expiry))
    self.assertTrue(had_errors)

  def testExpiryDateExtraction(self):
    chrome_histogram_pattern = """<histogram-configuration>

<histograms>

<histogram name="Histogram.Name" units="units" {}>
  <owner>SomeOne@google.com</owner>
  <summary>Summary</summary>
</histogram>

</histograms>

</histogram-configuration>
"""
    date_str = '2211-11-22'
    chrome_histogram_correct_expiry_date = chrome_histogram_pattern.format(
        'expires_after="{}"'.format(date_str))
    histograms, _ = extract_histograms.ExtractHistogramsFromDom(
        xml.dom.minidom.parseString(chrome_histogram_correct_expiry_date))
    histogram_content = histograms['Histogram.Name']
    self.assertIn('expires_after', histogram_content)
    self.assertEqual(date_str, histogram_content['expires_after'])

    milestone_str = 'M22'
    chrome_histogram_correct_expiry_milestone = chrome_histogram_pattern.format(
        'expires_after="{}"'.format(milestone_str))
    histograms, _ = extract_histograms.ExtractHistogramsFromDom(
        xml.dom.minidom.parseString(chrome_histogram_correct_expiry_milestone))
    histogram_content = histograms['Histogram.Name']
    self.assertIn('expires_after', histogram_content)
    self.assertEqual(milestone_str, histogram_content['expires_after'])

    chrome_histogram_no_expiry = chrome_histogram_pattern.format('')
    histograms, _ = extract_histograms.ExtractHistogramsFromDom(
        xml.dom.minidom.parseString(chrome_histogram_no_expiry))
    histogram_content = histograms['Histogram.Name']
    self.assertNotIn('expires_after', histogram_content)

  def testMultiParagraphSummary(self):
    multiple_paragraph_pattern = xml.dom.minidom.parseString("""
<histogram-configuration>
<histograms>
  <histogram name="MultiParagraphTest.Test1" units="units"
      expires_after="2019-01-01">
    <owner>chrome-metrics-team@google.com</owner>
    <summary>
      Sample description
      Sample description.
    </summary>
  </histogram>

  <histogram name="MultiParagraphTest.Test2" units="units"
      expires_after="2019-01-01">
    <owner>chrome-metrics-team@google.com</owner>
    <summary>
      Multi-paragraph sample description UI&gt;Browser.
      Words.

      Still multi-paragraph sample description.

      <!--Comments are allowed.-->

      Here.
    </summary>
  </histogram>
</histograms>
</histogram-configuration>
""")
    histograms, _ = extract_histograms._ExtractHistogramsFromXmlTree(
        multiple_paragraph_pattern, {})
    self.assertEqual(histograms['MultiParagraphTest.Test1']['summary'],
                     'Sample description Sample description.')
    self.assertEqual(
        histograms['MultiParagraphTest.Test2']['summary'],
        'Multi-paragraph sample description UI>Browser. Words.\n\n'
        'Still multi-paragraph sample description.\n\nHere.')

  def testComponentExtraction(self):
    """Checks that components are successfully extracted from histograms."""
    histogram = xml.dom.minidom.parseString("""
<histogram-configuration>
<histograms>
  <histogram name="Coffee" expires_after="2022-01-01">
    <owner>histogram_owner@google.com</owner>
    <summary>An ode to coffee.</summary>
    <component>Liquid&gt;Hot</component>
    <component>Caffeine</component>
  </histogram>
</histograms>

<histogram_suffixes_list>
  <histogram_suffixes name="Brand" separator=".">
    <suffix name="Dunkies" label="The coffee is from Dunkin."/>
    <affected-histogram name="Coffee"/>
  </histogram_suffixes>
</histogram_suffixes_list>
</histogram-configuration>
""")
    histograms, _ = extract_histograms.ExtractHistogramsFromDom(histogram)
    self.assertEqual(histograms['Coffee']['components'],
                     ['Liquid>Hot', 'Caffeine'])
    self.assertEqual(histograms['Coffee.Dunkies']['components'],
                     ['Liquid>Hot', 'Caffeine'])

  def testNewHistogramWithoutSummary(self):
    histogram_without_summary = xml.dom.minidom.parseString("""
<histogram-configuration>
<histograms>
 <histogram name="Test.Histogram" units="things" expires_after="2019-01-01">
   <owner>person@chromium.org</owner>
 </histogram>
</histograms>
</histogram-configuration>
""")
    _, have_errors = extract_histograms._ExtractHistogramsFromXmlTree(
        histogram_without_summary, {})
    self.assertTrue(have_errors)

  def testNewHistogramWithEmptySummary(self):
    histogram_with_empty_summary = xml.dom.minidom.parseString("""
<histogram-configuration>
<histograms>
 <histogram name="Test.Histogram" units="things" expires_after="2019-01-01">
   <owner>person@chromium.org</owner>
   <summary/>
 </histogram>
</histograms>
</histogram-configuration>
""")
    _, have_errors = extract_histograms._ExtractHistogramsFromXmlTree(
        histogram_with_empty_summary, {})
    self.assertTrue(have_errors)

  def testNewHistogramWithoutEnumOrUnit(self):
    histogram_without_enum_or_unit = xml.dom.minidom.parseString("""
<histogram-configuration>
<histograms>
 <histogram name="Test.Histogram" expires_after="2019-01-01">
  <owner>chrome-metrics-team@google.com</owner>
  <summary> This is a summary </summary>
 </histogram>
</histograms>
</histogram-configuration>
""")
    _, have_errors = extract_histograms._ExtractHistogramsFromXmlTree(
        histogram_without_enum_or_unit, {})
    self.assertTrue(have_errors)

  def testNewHistogramWithEnumAndUnit(self):
    histogram_with_enum_and_unit = xml.dom.minidom.parseString("""
<histogram-configuration>
<histograms>
 <histogram name="Test.Histogram" enum="MyEnumType" unit="things"
    expires_after="2019-01-01">
  <owner>chrome-metrics-team@google.com</owner>
  <summary> This is a summary </summary>
 </histogram>
</histograms>
</histogram-configuration>
""")
    _, have_errors = extract_histograms._ExtractHistogramsFromXmlTree(
        histogram_with_enum_and_unit, {})
    self.assertTrue(have_errors)

  def testEmptyEnum(self):
    empty_enum = xml.dom.minidom.parseString("""
<histogram-configuration>
<enums>
  <enum name="MyEnumType">
    <summary>This is an empty enum</summary>
  </enum>
</enums>
</histogram-configuration>
""")
    _, have_errors = extract_histograms.ExtractEnumsFromXmlTree(empty_enum)
    self.assertTrue(have_errors)

  def testNewHistogramWithEnum(self):
    histogram_with_enum = xml.dom.minidom.parseString("""
<histogram-configuration>
<enums>
  <enum name="MyEnumType">
    <summary>This is an example enum type</summary>
    <int value="1" label="FIRST_VALUE">This is the first value.</int>
    <int value="2" label="SECOND_VALUE">This is the second value.</int>
  </enum>
</enums>

<histograms>
 <histogram name="Test.Histogram.Enum" enum="MyEnumType"
    expires_after="2019-01-01">
  <owner>chrome-metrics-team@google.com</owner>
  <summary> This is a summary </summary>
 </histogram>
</histograms>
</histogram-configuration>
""")
    _, have_errors = extract_histograms.ExtractHistogramsFromDom(
        histogram_with_enum)
    self.assertFalse(have_errors)

  def testEnumWithDuplicateValues(self):
    bad_enum = xml.dom.minidom.parseString("""
<histogram-configuration>
<enums>
  <enum name="MyEnumType">
    <int value="1" label="FIRST_VALUE">This is the first value.</int>
    <int value="1" label="SECOND_VALUE">This is the second value.</int>
  </enum>
</enums>
</histogram-configuration>
""")
    _, have_errors = extract_histograms.ExtractEnumsFromXmlTree(bad_enum)
    self.assertTrue(have_errors)

  def testEnumWithDuplicateLabels(self):
    bad_enum = xml.dom.minidom.parseString("""
<histogram-configuration>
<enums>
  <enum name="MyEnumType">
    <int value="1" label="FIRST_VALUE">This is the first value.</int>
    <int value="2" label="FIRST_VALUE">This is the second value.</int>
  </enum>
</enums>
</histogram-configuration>
""")
    _, have_errors = extract_histograms.ExtractEnumsFromXmlTree(bad_enum)
    self.assertTrue(have_errors)

  def testNewHistogramWithUnits(self):
    histogram_with_units = xml.dom.minidom.parseString("""
<histogram-configuration>
<histograms>
 <histogram name="Test.Histogram" units="units" expires_after="2019-01-01">
  <owner>chrome-metrics-team@google.com</owner>
  <summary> This is a summary </summary>
 </histogram>
</histograms>
</histogram-configuration>
""")
    _, have_errors = extract_histograms._ExtractHistogramsFromXmlTree(
        histogram_with_units, {})
    self.assertFalse(have_errors)

  def testNewHistogramWithEmptyOwnerTag(self):
    histogram_with_empty_owner_tag = xml.dom.minidom.parseString("""
<histogram-configuration>
<histograms>
 <histogram name="Test.Histogram" units="things" expires_after="2019-01-01">
  <owner></owner>
  <summary> This is a summary </summary>
 </histogram>
</histograms>
</histogram-configuration>
""")
    _, have_errors = extract_histograms._ExtractHistogramsFromXmlTree(
        histogram_with_empty_owner_tag, {})
    self.assertTrue(have_errors)

  def testNewHistogramWithoutOwnerTag(self):
    histogram_without_owner_tag = xml.dom.minidom.parseString("""
<histogram-configuration>
<histograms>
 <histogram name="Test.Histogram" units="things" expires_after="2019-01-01">
  <summary> This is a summary </summary>
 </histogram>
</histograms>
</histogram-configuration>
""")
    _, have_errors = extract_histograms._ExtractHistogramsFromXmlTree(
        histogram_without_owner_tag, {})
    self.assertTrue(have_errors)

  def testNewHistogramWithCommaSeparatedOwners(self):
    histogram_with_comma_separated_owners = xml.dom.minidom.parseString("""
<histogram-configuration>
<histograms>
 <histogram name="Test.Histogram" units="things" expires_after="2019-01-01">
  <owner>cait@chromium.org, paul@chromium.org</owner>
  <summary> This is a summary </summary>
 </histogram>
</histograms>
</histogram-configuration>
""")
    _, have_errors = extract_histograms._ExtractHistogramsFromXmlTree(
        histogram_with_comma_separated_owners, {})
    self.assertTrue(have_errors)

  def testNewHistogramWithInvalidOwner(self):
    histogram_with_invalid_owner = xml.dom.minidom.parseString("""
<histogram-configuration>
<histograms>
 <histogram name="Test.Histogram" units="things" expires_after="2019-01-01">
  <owner>sarah</owner>
  <summary> This is a summary </summary>
 </histogram>
</histograms>
</histogram-configuration>
""")
    _, have_errors = extract_histograms._ExtractHistogramsFromXmlTree(
        histogram_with_invalid_owner, {})
    self.assertTrue(have_errors)

  def testNewHistogramWithOwnerPlaceHolder(self):
    histogram_with_owner_placeholder = xml.dom.minidom.parseString("""
<histogram-configuration>
<histograms>
 <histogram name="Test.Histogram" units="things" expires_after="2019-01-01">
  <owner> Please list the metric's owners. Add more owner tags as needed.
  </owner>
  <summary>
    <!-- Comments are fine -->
    This is a summary
    <!-- Comments are fine -->
  </summary>
 </histogram>
</histograms>
</histogram-configuration>
""")
    _, have_errors = extract_histograms._ExtractHistogramsFromXmlTree(
        histogram_with_owner_placeholder, {})
    self.assertFalse(have_errors)

  def testHistogramWithEscapeCharacters(self):
    histogram_with_owner_placeholder = xml.dom.minidom.parseString("""
<histogram-configuration>
<histograms>
 <histogram name="Test.Histogram" units="things" expires_after="2019-01-01">
  <owner> Please list the metric's owners. Add more owner tags as needed.
  </owner>
  <summary>This is a summary with &amp; and &quot; and &apos;</summary>
 </histogram>
</histograms>
</histogram-configuration>
""")
    hists, have_errors = extract_histograms._ExtractHistogramsFromXmlTree(
        histogram_with_owner_placeholder, {})
    self.assertFalse(have_errors)
    self.assertIn('Test.Histogram', hists)
    self.assertIn('summary', hists['Test.Histogram'])
    self.assertEqual('This is a summary with & and " and \'',
                     hists['Test.Histogram']['summary'])

  def testNewSuffixWithoutLabel(self):
    suffix_without_label = xml.dom.minidom.parseString("""
<histogram-configuration>
<histogram_suffixes_list>
  <histogram_suffixes name="Suffixes" separator=".">
    <suffix base="true" name="BaseSuffix"/>
  </histogram_suffixes>
</histogram_suffixes_list>
</histogram-configuration>
""")
    _, have_errors = extract_histograms.ExtractHistogramsFromDom(
        suffix_without_label)
    self.assertTrue(have_errors)

  def testNewSuffixWithLabel(self):
    suffix_with_label = xml.dom.minidom.parseString("""
<histogram-configuration>
<histogram_suffixes_list>
  <histogram_suffixes name="Suffixes" separator=".">
    <suffix base="true" name="BaseSuffix" label="Base"/>
  </histogram_suffixes>
</histogram_suffixes_list>
</histogram-configuration>
""")
    have_errors = extract_histograms._UpdateHistogramsWithSuffixes(
        suffix_with_label, {})
    self.assertFalse(have_errors)

  @parameterized.expand([
      ('InlineTokens', TEST_HISTOGRAM_WITH_TOKENS),
      ('InlineTokenAndOutOfLineVariants', TEST_HISTOGRAM_WITH_VARIANTS),
      ('MixedVariants', TEST_HISTOGRAM_WITH_MIXED_VARIANTS),
  ])
  def testUpdateNameWithTokens(self, _, input_xml):
    histogram_with_token = xml.dom.minidom.parseString(input_xml)
    histograms_dict, _ = extract_histograms._ExtractHistogramsFromXmlTree(
        histogram_with_token, {})
    histograms_dict, _ = extract_histograms._UpdateHistogramsWithTokens(
        histograms_dict)
    self.assertIn('HistogramName.red.small', histograms_dict)
    self.assertIn('HistogramName.green.small', histograms_dict)
    self.assertIn('HistogramName.red.medium', histograms_dict)
    self.assertIn('HistogramName.green.medium', histograms_dict)
    self.assertIn('HistogramName.red.large', histograms_dict)
    self.assertIn('HistogramName.green.large', histograms_dict)
    self.assertIn('HistogramName.red', histograms_dict)
    self.assertIn('HistogramName.green', histograms_dict)
    self.assertNotIn('HistogramName{Color}{Size}', histograms_dict)

    # Make sure generated histograms do not have tokens.
    self.assertNotIn('tokens', histograms_dict['HistogramName.red.small'])
    self.assertNotIn('tokens', histograms_dict['HistogramName.green.large'])

  @parameterized.expand([
      ('InlineTokens', TEST_HISTOGRAM_WITH_TOKENS),
      ('InlineTokenAndOutOfLineVariants', TEST_HISTOGRAM_WITH_VARIANTS),
      ('MixedVariants', TEST_HISTOGRAM_WITH_MIXED_VARIANTS),
  ])
  def testUpdateSummaryWithTokens(self, _, input_xml):
    histogram_with_token = xml.dom.minidom.parseString(input_xml)
    histograms_dict, _ = extract_histograms._ExtractHistogramsFromXmlTree(
        histogram_with_token, {})
    histograms_dict, _ = extract_histograms._UpdateHistogramsWithTokens(
        histograms_dict)
    # Use the variant's name to format the summary when the variant's summary
    # attribute is omitted.
    self.assertEqual(
        'This is a histogram for button of red color and small size.',
        histograms_dict['HistogramName.red.small']['summary'])
    self.assertEqual(
        'This is a histogram for button of green color and small size.',
        histograms_dict['HistogramName.green.small']['summary'])
    self.assertEqual(
        'This is a histogram for button of red color and medium size.',
        histograms_dict['HistogramName.red.medium']['summary'])
    self.assertEqual(
        'This is a histogram for button of green color and medium size.',
        histograms_dict['HistogramName.green.medium']['summary'])
    self.assertEqual(
        'This is a histogram for button of red color and large size.',
        histograms_dict['HistogramName.red.large']['summary'])
    self.assertEqual(
        'This is a histogram for button of green color and large size.',
        histograms_dict['HistogramName.green.large']['summary'])
    self.assertEqual(
        'This is a histogram for button of red color and all size.',
        histograms_dict['HistogramName.red']['summary'])
    self.assertEqual(
        'This is a histogram for button of green color and all size.',
        histograms_dict['HistogramName.green']['summary'])

  @parameterized.expand([
      ('InlineTokens', TEST_HISTOGRAM_WITH_TOKENS),
      ('InlineTokenAndOutOfLineVariants', TEST_HISTOGRAM_WITH_VARIANTS),
      ('MixedVariants', TEST_HISTOGRAM_WITH_MIXED_VARIANTS),
  ])
  def testUpdateWithTokenOwner(self, _, input_xml):
    histogram_with_token = xml.dom.minidom.parseString(input_xml)
    histograms_dict, _ = extract_histograms._ExtractHistogramsFromXmlTree(
        histogram_with_token, {})
    histograms_dict, _ = extract_histograms._UpdateHistogramsWithTokens(
        histograms_dict)

    self.assertEqual(['small@chromium.org'],
                     histograms_dict['HistogramName.red.small']['owners'])
    self.assertEqual(['me@chromium.org'],
                     histograms_dict['HistogramName.red.medium']['owners'])
    self.assertEqual(['me@chromium.org'],
                     histograms_dict['HistogramName.red.large']['owners'])
    self.assertEqual(['me@chromium.org'],
                     histograms_dict['HistogramName.red']['owners'])
    self.assertEqual(['green@chromium.org', 'small@chromium.org'],
                     histograms_dict['HistogramName.green.small']['owners'])
    self.assertEqual(['green@chromium.org'],
                     histograms_dict['HistogramName.green.medium']['owners'])
    self.assertEqual(['green@chromium.org'],
                     histograms_dict['HistogramName.green.large']['owners'])
    self.assertEqual(['green@chromium.org'],
                     histograms_dict['HistogramName.green']['owners'])

  @parameterized.expand([
      ('InlineTokens', TEST_HISTOGRAM_WITH_TOKENS),
      ('InlineTokenAndOutOfLineVariants', TEST_HISTOGRAM_WITH_VARIANTS),
      ('MixedVariants', TEST_HISTOGRAM_WITH_MIXED_VARIANTS),
  ])
  def testUpdateWithTokenObsolete(self, _, input_xml):
    histogram_with_token = xml.dom.minidom.parseString(input_xml)
    histograms_dict, _ = extract_histograms._ExtractHistogramsFromXmlTree(
        histogram_with_token, {})
    histograms_dict, _ = extract_histograms._UpdateHistogramsWithTokens(
        histograms_dict)

    # New histograms should inherit the obsolete reason of the last
    # obsolete token by order of appearance.
    self.assertEqual('Obsolete small',
                     histograms_dict['HistogramName.red.small']['obsolete'])
    self.assertEqual('Obsolete red',
                     histograms_dict['HistogramName.red.medium']['obsolete'])
    self.assertEqual('Obsolete red',
                     histograms_dict['HistogramName.red.large']['obsolete'])
    self.assertEqual('Obsolete red',
                     histograms_dict['HistogramName.red']['obsolete'])
    self.assertEqual('Obsolete small',
                     histograms_dict['HistogramName.green.small']['obsolete'])
    self.assertNotIn('obsolete', histograms_dict['HistogramName.green.medium'])
    self.assertNotIn('obsolete', histograms_dict['HistogramName.green.large'])
    self.assertNotIn('obsolete', histograms_dict['HistogramName.green'])

  @parameterized.expand([
      ('InlineTokens', TEST_HISTOGRAM_TOKENS_DUPLICATE),
      ('InlineTokenAndOutOfLineVariants', TEST_HISTOGRAM_VARIANTS_DUPLICATE),
  ])
  def testUpdateNameDuplicateVariant(self, _, input_xml):
    """Tests that if duplicate names are generated due to multiple tokens
    having the same variant and empty string variant, an error is reported."""
    histogram_with_duplicate_variant = xml.dom.minidom.parseString(input_xml)
    histograms_dict, _ = extract_histograms._ExtractHistogramsFromXmlTree(
        histogram_with_duplicate_variant, {})
    _, have_errors = extract_histograms._UpdateHistogramsWithTokens(
        histograms_dict)
    self.assertTrue(have_errors)

  def testVariantsNotExists(self):
    histogram_without_corresponding_variants = xml.dom.minidom.parseString("""
<histogram-configuration>
<histograms>
<histogram name="Histogram{Color}{SizeNone}" units="things"
    expires_after="2017-10-16">
  <owner>me@chromium.org</owner>
  <summary>
    This is a histogram for button of {Color} color and {SizeNone} size.
  </summary>
  <token key="Color">
    <variant name="" summary="all"/>
    <variant name=".red" summary="red"/>
    <variant name=".green" summary="green"/>
  </token>
  <token key="SizeNone" variants="HistogramNameSize"/>
</histogram>
</histograms>
</histogram-configuration>
""")
    _, have_errors = extract_histograms._ExtractHistogramsFromXmlTree(
        histogram_without_corresponding_variants, {})
    self.assertTrue(have_errors)

  def testSuffixCanExtendPatternedHistograms(self):
    patterned_suffix = ("""
        <histogram-configuration>
        <histograms>
          <histogram name="Test{Version}" units="things"
            expires_after="2017-10-16">
            <owner>chrome-metrics-team@google.com</owner>
            <summary>
              Sample description.
            </summary>
            <token key="Version">
              <variant name=".First"/>
              <variant name=".Last"/>
            </token>
          </histogram>
        </histograms>
        <histogram_suffixes_list>
          <histogram_suffixes name="ExtendPatternedHist" separator=".">
            <suffix name="Found" label="Extending patterned histograms."/>
            <affected-histogram name="Test.First"/>
            <affected-histogram name="Test.Last"/>
          </histogram_suffixes>
        </histogram_suffixes_list>
        </histogram-configuration>""")
    # Only when the histogram is first extended by the token, can the
    # histogram_suffixes find those affected histograms.
    histograms_dict, had_errors = extract_histograms.ExtractHistogramsFromDom(
        xml.dom.minidom.parseString(patterned_suffix))
    self.assertFalse(had_errors)
    self.assertIn('Test.First.Found', histograms_dict)
    self.assertIn('Test.Last.Found', histograms_dict)

  def testExtractImprovementDirection(self):
    histogram_name = 'Histogram.With.InterpretationTag'
    config = """
<histogram-configuration>

<histograms>

<histogram name="{histogram_name}" expires_after="M100" units="units">
  <owner>owner@chromium.org</owner>
  {improvement_tag}
  <summary>The improvement tag says a higher value is good!</summary>
</histogram>

</histograms>

</histogram-configuration>"""

    improvement_tag_good = '<improvement direction="HIGHER_IS_BETTER"/>'
    improvement_tag_bad = '<improvement>HIGHER_IS_BETTER</improvement>'

    config_good = config.format(histogram_name=histogram_name,
                                improvement_tag=improvement_tag_good)
    config_bad = config.format(histogram_name=histogram_name,
                               improvement_tag=improvement_tag_bad)

    histograms_dict, had_errors = extract_histograms.ExtractHistogramsFromDom(
        xml.dom.minidom.parseString(config_good))
    self.assertFalse(had_errors)
    self.assertIn(histogram_name, histograms_dict)
    self.assertIn('improvement', histograms_dict[histogram_name])
    self.assertEqual(
        histogram_configuration_model.IMPROVEMENT_DIRECTION_HIGHER_IS_BETTER,
        histograms_dict[histogram_name]['improvement'])

    histograms_dict, had_errors = extract_histograms.ExtractHistogramsFromDom(
        xml.dom.minidom.parseString(config_bad))
    self.assertTrue(had_errors)
    self.assertNotIn('improvement', histograms_dict[histogram_name])


if __name__ == "__main__":
  logging.basicConfig(level=logging.ERROR + 1)
  unittest.main()