File: test_parser.py

package info (click to toggle)
glean-parser 15.0.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,260 kB
  • sloc: python: 7,033; ruby: 100; makefile: 87
file content (1235 lines) | stat: -rw-r--r-- 40,262 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
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
# -*- coding: utf-8 -*-

# Any copyright is dedicated to the Public Domain.
# http://creativecommons.org/publicdomain/zero/1.0/

from pathlib import Path
import json
import re
import textwrap

import pytest

from glean_parser import metrics
from glean_parser import parser

import util


ROOT = Path(__file__).parent


def test_parser():
    """Test the basics of parsing a single file."""
    all_metrics = parser.parse_objects(
        [ROOT / "data" / "core.yaml", ROOT / "data" / "pings.yaml"],
        config={"allow_reserved": True},
    )

    errs = list(all_metrics)
    assert len(errs) == 0

    for category_key, category_val in all_metrics.value.items():
        if category_key == "pings":
            continue
        for _metric_key, metric_val in category_val.items():
            assert isinstance(metric_val, metrics.Metric)
            assert isinstance(metric_val.lifetime, metrics.Lifetime)
            if getattr(metric_val, "labels", None) is not None:
                assert isinstance(metric_val.labels, set)

    pings = all_metrics.value["pings"]
    assert pings["custom-ping"].name == "custom-ping"
    assert pings["custom-ping"].include_client_id is False
    assert pings["really-custom-ping"].name == "really-custom-ping"
    assert pings["really-custom-ping"].include_client_id is True


def test_parser_invalid():
    """Test the basics of parsing a single file."""
    all_metrics = parser.parse_objects(ROOT / "data" / "invalid.yamlx")
    errors = list(all_metrics)
    assert len(errors) == 1
    assert "could not determine a constructor for the tag" in errors[0]


def test_parser_schema_violation():
    """1507792"""
    all_metrics = parser.parse_objects(ROOT / "data" / "schema-violation.yaml")
    errors = list(all_metrics)

    found_errors = set(
        re.sub(r"\s", "", str(error).split("\n", 1)[1].strip()) for error in errors
    )

    expected_errors = [
        """
        ```
        gleantest.lifetime:
          test_counter_inv_lt:
            lifetime: user2
        ```

        'user2' is not one of ['ping', 'user', 'application']

        Documentation for this node:
        Definesthelifetimeofthe metric. It must be one of the following values:

        - `ping` (default): The metric is reset each time it is sent in a ping.

        - `user`: The metric contains a property that is part of the user's
          profile and is never reset.

        - `application`: The metric contains a property that is related to the
          application, and is reset only at application restarts.
        """,
        """
        ```
        gleantest.foo:
          a: b
        ```

        'b' is not of type 'object'

        Documentation for this node:
            Describes a single metric.

            See https://mozilla.github.io/glean_parser/metrics-yaml.html
        """,
        """
        ```
        gleantest.with.way.too.long.category.name
        ...
        ```

        'gleantest.with.way.too.long.category.name' is not valid under any of
        the given schemas
        'gleantest.with.way.too.long.category.name' is too long
        'gleantest.with.way.too.long.category.name' is not one of
        ['$schema', '$tags']
        """,
        """
        ```
        gleantest.short.category:very_long_metric_name_this_is_too_long_as_well_since_it_has_sooooo_many_characters
        ```

        'very_long_metric_name_this_is_too_long_as_well_since_it_has_sooooo_many_characters' is not valid under any
        of the given schemas
        'very_long_metric_name_this_is_too_long_as_well_since_it_has_sooooo_many_characters' is too long
        """,  # noqa: E501 #
        """
        ```
        gleantest:
          test_event:
            type: event
        ```

        Missing required properties: bugs, data_reviews, description, expires,
        notification_emails

        Documentation for this node:
            Describes a single metric.

            See https://mozilla.github.io/glean_parser/metrics-yaml.html
        """,
        """
        ```
        gleantest.event:
            event_too_many_extras:
            extra_keys:
                key_1:
                description: Sample extra key
                type: string
                key_2:
                description: Sample extra key
                type: string
                key_3:
                description: Sample extra key
                type: string
                key_4:
                description: Sample extra key
                type: string
                key_5:
                description: Sample extra key
                type: string
                key_6:
                description: Sample extra key
                type: string
                key_7:
                description: Sample extra key
                type: string
                key_8:
                description: Sample extra key
                type: string
                key_9:
                description: Sample extra key
                type: string
                key_10:
                description: Sample extra key
                type: string
                key_11:
                description: Sample extra key
                type: string
                key_12:
                description: Sample extra key
                type: string
                key_13:
                description: Sample extra key
                type: string
                key_14:
                description: Sample extra key
                type: string
                key_15:
                description: Sample extra key
                type: string
                key_16:
                description: Sample extra key
                type: string
                key_17:
                description: Sample extra key
                type: string
                key_18:
                description: Sample extra key
                type: string
                key_19:
                description: Sample extra key
                type: string
                key_20:
                description: Sample extra key
                type: string
                key_21:
                description: Sample extra key
                type: string
                key_22:
                description: Sample extra key
                type: string
                key_23:
                description: Sample extra key
                type: string
                key_24:
                description: Sample extra key
                type: string
                key_25:
                description: Sample extra key
                type: string
                key_26:
                description: Sample extra key
                type: string
                key_27:
                description: Sample extra key
                type: string
                key_28:
                description: Sample extra key
                type: string
                key_29:
                description: Sample extra key
                type: string
                key_30:
                description: Sample extra key
                type: string
                key_31:
                description: Sample extra key
                type: string
                key_32:
                description: Sample extra key
                type: string
                key_33:
                description: Sample extra key
                type: string
                key_34:
                description: Sample extra key
                type: string
                key_35:
                description: Sample extra key
                type: string
                key_36:
                description: Sample extra key
                type: string
                key_37:
                description: Sample extra key
                type: string
                key_38:
                description: Sample extra key
                type: string
                key_39:
                description: Sample extra key
                type: string
                key_40:
                description: Sample extra key
                type: string
                key_41:
                description: Sample extra key
                type: string
                key_42:
                description: Sample extra key
                type: string
                key_43:
                description: Sample extra key
                type: string
                key_44:
                description: Sample extra key
                type: string
                key_45:
                description: Sample extra key
                type: string
                key_46:
                description: Sample extra key
                type: string
                key_47:
                description: Sample extra key
                type: string
                key_48:
                description: Sample extra key
                type: string
                key_49:
                description: Sample extra key
                type: string
                key_50:
                description: Sample extra key
                type: string
                key_51:
                description: Sample extra key
                type: string
        ```
        {'key_1': {'description': 'Sample extra key','type': 'string'},
        'key_2': {'description': 'Sample extra key','type': 'string'},
        'key_3': {'description': 'Sample extra key','type': 'string'},
        'key_4': {'description': 'Sample extra key','type': 'string'},
        'key_5': {'description': 'Sample extra key','type': 'string'},
        'key_6': {'description': 'Sample extra key','type': 'string'},
        'key_7': {'description': 'Sample extra key','type': 'string'},
        'key_8': {'description': 'Sample extra key','type': 'string'},
        'key_9': {'description': 'Sample extra key','type': 'string'},
        'key_10': {'description': 'Sample extra key','type': 'string'},
        'key_11': {'description': 'Sample extra key','type': 'string'},
        'key_12': {'description': 'Sample extra key','type': 'string'},
        'key_13': {'description': 'Sample extra key','type': 'string'},
        'key_14': {'description': 'Sample extra key','type': 'string'},
        'key_15': {'description': 'Sample extra key','type': 'string'},
        'key_16': {'description': 'Sample extra key','type': 'string'},
        'key_17': {'description': 'Sample extra key','type': 'string'},
        'key_18': {'description': 'Sample extra key','type': 'string'},
        'key_19': {'description': 'Sample extra key','type': 'string'},
        'key_20': {'description': 'Sample extra key','type': 'string'},
        'key_21': {'description': 'Sample extra key','type': 'string'},
        'key_22': {'description': 'Sample extra key','type': 'string'},
        'key_23': {'description': 'Sample extra key','type': 'string'},
        'key_24': {'description': 'Sample extra key','type': 'string'},
        'key_25': {'description': 'Sample extra key','type': 'string'},
        'key_26': {'description': 'Sample extra key','type': 'string'},
        'key_27': {'description': 'Sample extra key','type': 'string'},
        'key_28': {'description': 'Sample extra key','type': 'string'},
        'key_29': {'description': 'Sample extra key','type': 'string'},
        'key_30': {'description': 'Sample extra key','type': 'string'},
        'key_31': {'description': 'Sample extra key','type': 'string'},
        'key_32': {'description': 'Sample extra key','type': 'string'},
        'key_33': {'description': 'Sample extra key','type': 'string'},
        'key_34': {'description': 'Sample extra key','type': 'string'},
        'key_35': {'description': 'Sample extra key','type': 'string'},
        'key_36': {'description': 'Sample extra key','type': 'string'},
        'key_37': {'description': 'Sample extra key','type': 'string'},
        'key_38': {'description': 'Sample extra key','type': 'string'},
        'key_39': {'description': 'Sample extra key','type': 'string'},
        'key_40': {'description': 'Sample extra key','type': 'string'},
        'key_41': {'description': 'Sample extra key','type': 'string'},
        'key_42': {'description': 'Sample extra key','type': 'string'},
        'key_43': {'description': 'Sample extra key','type': 'string'},
        'key_44': {'description': 'Sample extra key','type': 'string'},
        'key_45': {'description': 'Sample extra key','type': 'string'},
        'key_46': {'description': 'Sample extra key','type': 'string'},
        'key_47': {'description': 'Sample extra key','type': 'string'},
        'key_48': {'description': 'Sample extra key','type': 'string'},
        'key_49': {'description': 'Sample extra key','type': 'string'},
        'key_50': {'description': 'Sample extra key','type': 'string'},
        'key_51': {'description': 'Sample extra key','type': 'string'}
        } has too many properties
        Documentation for this node:
            The acceptable keys on the "extra" object sent with events. This is an
            object mapping the key to an object containing metadata about the key.
            A maximum of 50 extra keys is allowed.
            This metadata object has the following keys:
                - `description`: **Required.** A description of the key.
            Valid when `type`_ is `event`.
        """,
    ]

    expected_errors = set(
        re.sub(r"\s", "", textwrap.indent(textwrap.dedent(x), "    ").strip())
        for x in expected_errors
    )

    # Compare errors 1-by-1 for better assertion message when it fails.
    found = sorted(list(found_errors))
    expected = sorted(list(expected_errors))

    for found_error, expected_error in zip(found, expected):
        assert found_error == expected_error


def test_parser_empty():
    """1507792: Get a good error message if the metrics.yaml file is empty."""
    all_metrics = parser.parse_objects(ROOT / "data" / "empty.yaml")
    errors = list(all_metrics)
    assert len(errors) == 1
    assert "file can not be empty" in errors[0]


def test_invalid_schema():
    all_metrics = parser.parse_objects([{"$schema": "This is wrong"}])
    errors = list(all_metrics)
    assert any("key must be one of" in str(e) for e in errors)


def test_merge_metrics():
    """Merge multiple metrics.yaml files"""
    contents = [
        {"category1": {"metric1": {}, "metric2": {}}, "category2": {"metric3": {}}},
        {"category1": {"metric4": {}}, "category3": {"metric5": {}}},
    ]
    contents = [util.add_required(x) for x in contents]

    all_metrics = parser.parse_objects(contents)
    list(all_metrics)
    all_metrics = all_metrics.value

    assert set(all_metrics["category1"].keys()) == set(
        ["metric1", "metric2", "metric4"]
    )
    assert set(all_metrics["category2"].keys()) == set(["metric3"])
    assert set(all_metrics["category3"].keys()) == set(["metric5"])


def test_merge_metrics_clash():
    """Merge multiple metrics.yaml files with conflicting metric names."""
    contents = [{"category1": {"metric1": {}}}, {"category1": {"metric1": {}}}]
    contents = [util.add_required(x) for x in contents]

    all_metrics = parser.parse_objects(contents)
    errors = list(all_metrics)
    assert len(errors) == 1
    assert "Duplicate metric name" in errors[0]


def test_snake_case_enforcement():
    """Expect exception if names aren't in snake case."""
    contents = [
        {"categoryWithCamelCase": {"metric": {}}},
        {"category": {"metricWithCamelCase": {}}},
    ]

    for content in contents:
        util.add_required(content)
        errors = list(parser._load_file(content, {}))
        assert len(errors) == 1


def test_multiple_errors():
    """Make sure that if there are multiple errors, we get all of them."""
    contents = [{"camelCaseName": {"metric": {"type": "unknown"}}}]

    contents = [util.add_required(x) for x in contents]
    metrics = parser.parse_objects(contents)
    errors = list(metrics)
    assert len(errors) == 2


def test_event_must_be_ping_lifetime():
    contents = [{"category": {"metric": {"type": "event", "lifetime": "user"}}}]

    contents = [util.add_required(x) for x in contents]
    all_metrics = parser.parse_objects(contents)
    errors = list(all_metrics)
    assert len(errors) == 1
    assert "Event metrics must have ping lifetime" in errors[0]


def test_parser_reserved():
    contents = [{"glean.baseline": {"metric": {"type": "string"}}}]

    contents = [util.add_required(x) for x in contents]
    all_metrics = parser.parse_objects(contents)
    errors = list(all_metrics)
    assert len(errors) == 1
    assert "For category 'glean.baseline'" in errors[0]

    all_metrics = parser.parse_objects(contents, {"allow_reserved": True})
    errors = list(all_metrics)
    assert len(errors) == 0


def invalid_in_category(name):
    return [{name: {"metric": {"type": "string"}}}]


def invalid_in_name(name):
    return [{"baseline": {name: {"type": "string"}}}]


def invalid_in_label(name):
    return [{"baseline": {"metric": {"type": "string", "labels": [name]}}}]


@pytest.mark.parametrize(
    "location", [invalid_in_category, invalid_in_name, invalid_in_label]
)
@pytest.mark.parametrize(
    "name",
    [
        "1" * 72,
        "Møøse",
    ],
)
def test_invalid_names(location, name):
    contents = location(name)
    contents = [util.add_required(x) for x in contents]
    all_metrics = parser.parse_objects(contents)
    errors = list(all_metrics)
    assert len(errors) == 1
    assert name in errors[0]


def test_duplicate_send_in_pings():
    """Test the basics of parsing a single file."""
    all_metrics = parser.parse_objects(
        [ROOT / "data" / "duplicate_send_in_ping.yaml"], config={"allow_reserved": True}
    )

    errs = list(all_metrics)
    assert len(errs) == 0

    metric = all_metrics.value["telemetry"]["test"]
    assert metric.send_in_pings == ["core", "metrics"]


def test_geckoview_only_on_valid_metrics():
    for metric in [
        "timing_distribution",
        "custom_distributiuon",
        "memory_distribution",
    ]:
        contents = [
            {"category1": {"metric1": {"type": metric, "gecko_datapoint": "FOO"}}}
        ]
        contents = [util.add_required(x) for x in contents]

    contents = [{"category1": {"metric1": {"type": "event", "gecko_datapoint": "FOO"}}}]
    contents = [util.add_required(x) for x in contents]

    all_metrics = parser.parse_objects(contents)
    errs = list(all_metrics)
    assert len(errs) == 1
    assert "is only allowed for" in str(errs[0])


def test_timing_distribution_unit_default():
    contents = [{"category1": {"metric1": {"type": "timing_distribution"}}}]
    contents = [util.add_required(x) for x in contents]

    all_metrics = parser.parse_objects(contents)
    errs = list(all_metrics)
    assert len(errs) == 0
    assert (
        all_metrics.value["category1"]["metric1"].time_unit
        == metrics.TimeUnit.nanosecond
    )


def test_all_pings_reserved():
    # send_in_pings: [all-pings] is only allowed for internal metrics
    contents = [
        {"category": {"metric": {"type": "string", "send_in_pings": ["all-pings"]}}}
    ]

    contents = [util.add_required(x) for x in contents]
    all_metrics = parser.parse_objects(contents)
    errors = list(all_metrics)
    assert len(errors) == 1
    assert "On instance category.metric" in errors[0]
    assert "Only internal metrics" in errors[0]

    all_metrics = parser.parse_objects(contents, {"allow_reserved": True})
    errors = list(all_metrics)
    assert len(errors) == 0

    # A custom ping called "all-pings" is not allowed
    contents = [{"all-pings": {"include_client_id": True}}]
    contents = [util.add_required_ping(x) for x in contents]
    all_pings = parser.parse_objects(contents)
    errors = list(all_pings)
    assert len(errors) == 1
    assert "is not allowed for 'all-pings'"


def test_custom_distribution():
    # Test plain custom_distribution, now also allowed generally
    contents = [
        {
            "category": {
                "metric": {
                    "type": "custom_distribution",
                    "range_min": 0,
                    "range_max": 60000,
                    "bucket_count": 100,
                    "histogram_type": "exponential",
                }
            }
        }
    ]

    contents = [util.add_required(x) for x in contents]
    all_metrics = parser.parse_objects(contents)
    errors = list(all_metrics)
    assert len(errors) == 0

    # Test that custom_distribution has required parameters
    contents = [
        {
            "category": {
                "metric": {
                    "type": "custom_distribution",
                    "gecko_datapoint": "FROM_GECKO",
                }
            }
        }
    ]

    contents = [util.add_required(x) for x in contents]
    all_metrics = parser.parse_objects(contents)
    errors = list(all_metrics)
    assert len(errors) == 1
    assert "`custom_distribution` is missing required parameters" in errors[0]

    # Test maximum bucket_count is enforced
    contents = [
        {
            "category": {
                "metric": {
                    "type": "custom_distribution",
                    "gecko_datapoint": "FROM_GECKO",
                    "range_max": 60000,
                    "bucket_count": 101,
                    "histogram_type": "exponential",
                }
            }
        }
    ]

    contents = [util.add_required(x) for x in contents]
    all_metrics = parser.parse_objects(contents)
    errors = list(all_metrics)
    assert len(errors) == 1
    assert "101 is greater than" in errors[0]

    # Test that correct usage
    contents = [
        {
            "category": {
                "metric": {
                    "type": "custom_distribution",
                    "range_max": 60000,
                    "bucket_count": 100,
                    "histogram_type": "exponential",
                }
            }
        }
    ]

    contents = [util.add_required(x) for x in contents]
    all_metrics = parser.parse_objects(contents)
    errors = list(all_metrics)
    assert len(errors) == 0
    distribution = all_metrics.value["category"]["metric"]
    assert distribution.range_min == 1
    assert distribution.range_max == 60000
    assert distribution.bucket_count == 100
    assert distribution.histogram_type == metrics.HistogramType.exponential


def test_memory_distribution():
    # Test that we get an error for a missing unit
    contents = [{"category": {"metric": {"type": "memory_distribution"}}}]

    contents = [util.add_required(x) for x in contents]
    all_metrics = parser.parse_objects(contents)
    errors = list(all_metrics)
    assert len(errors) == 1
    assert (
        "`memory_distribution` is missing required parameter `memory_unit`" in errors[0]
    )

    # Test that memory_distribution works
    contents = [
        {
            "category": {
                "metric": {"type": "memory_distribution", "memory_unit": "megabyte"}
            }
        }
    ]

    contents = [util.add_required(x) for x in contents]
    all_metrics = parser.parse_objects(contents)
    errors = list(all_metrics)
    assert len(errors) == 0
    assert len(all_metrics.value) == 1
    assert (
        all_metrics.value["category"]["metric"].memory_unit
        == metrics.MemoryUnit.megabyte
    )


def test_quantity():
    # Test that we get an error for a missing unit
    contents = [{"category": {"metric": {"type": "quantity"}}}]

    contents = [util.add_required(x) for x in contents]
    all_metrics = parser.parse_objects(contents)
    errors = list(all_metrics)
    assert len(errors) == 1
    assert any(
        "`quantity` is missing required parameter `unit`" in err for err in errors
    )

    # Test that quantity works
    contents = [
        {
            "category": {
                "metric": {
                    "type": "quantity",
                    "unit": "pixel",
                    "gecko_datapoint": "FOO",
                }
            }
        }
    ]

    contents = [util.add_required(x) for x in contents]
    all_metrics = parser.parse_objects(contents)
    errors = list(all_metrics)
    assert len(errors) == 0
    assert len(all_metrics.value) == 1
    assert all_metrics.value["category"]["metric"].unit == "pixel"


def test_do_not_disable_expired():
    # Test that we get an error for a missing unit and gecko_datapoint
    contents = [{"category": {"metric": {"type": "boolean", "expires": "1900-01-01"}}}]

    contents = [util.add_required(x) for x in contents]
    all_metrics = parser.parse_objects(contents, {"do_not_disable_expired": True})
    errors = list(all_metrics)
    assert len(errors) == 0

    metrics = all_metrics.value
    assert metrics["category"]["metric"].disabled is False


def test_send_in_pings_restrictions():
    """Test that invalid ping names are disallowed in `send_in_pings`."""
    all_metrics = parser.parse_objects(ROOT / "data" / "invalid-ping-names.yaml")
    errors = list(all_metrics)
    assert len(errors) == 1

    assert "'invalid_ping_name' does not match" in errors[0]


def test_tags():
    """Tests that tags can be specified."""
    all_metrics = parser.parse_objects(ROOT / "data" / "metric-with-tags.yaml")
    errors = list(all_metrics)

    assert errors == []
    assert len(all_metrics.value) == 1
    assert set(all_metrics.value["telemetry"]["client_id"].metadata.keys()) == set(
        ["tags"]
    )
    assert set(all_metrics.value["telemetry"]["client_id"].metadata["tags"]) == set(
        ["banana", "apple", "global_tag"]
    )


def test_custom_expires():
    contents = [
        {
            "category": {
                "metric": {
                    "type": "boolean",
                    "expires": "foo",
                },
                "metric2": {
                    "type": "boolean",
                    "expires": "bar",
                },
            }
        }
    ]
    contents = [util.add_required(x) for x in contents]

    all_metrics = parser.parse_objects(
        contents,
        {
            "custom_is_expired": lambda x: x == "foo",
            "custom_validate_expires": lambda x: x in ("foo", "bar"),
        },
    )

    errors = list(all_metrics)
    assert len(errors) == 0
    assert all_metrics.value["category"]["metric"].disabled is True
    assert all_metrics.value["category"]["metric2"].disabled is False

    with pytest.raises(ValueError):
        # Double-check that parsing without custom functions breaks
        all_metrics = parser.parse_objects(contents)
        errors = list(all_metrics)


def test_expire_by_major_version():
    failing_metrics = [
        {
            "category": {
                "metric_fail_date": {
                    "type": "boolean",
                    "expires": "1986-07-03",
                },
            }
        }
    ]
    failing_metrics = [util.add_required(x) for x in failing_metrics]

    with pytest.raises(ValueError):
        # Dates are not allowed if expiration by major version is enabled.
        all_metrics = parser.parse_objects(
            failing_metrics,
            {
                "expire_by_version": 15,
            },
        )
        errors = list(all_metrics)

    contents = [
        {
            "category": {
                "metric_expired_version": {
                    "type": "boolean",
                    "expires": 7,
                },
                "metric_expired_edge": {
                    "type": "boolean",
                    "expires": 15,
                },
                "metric_expired": {
                    "type": "boolean",
                    "expires": "expired",
                },
                "metric": {
                    "type": "boolean",
                    "expires": 18,
                },
            }
        }
    ]
    contents = [util.add_required(x) for x in contents]

    # Double-check that parsing without custom functions breaks
    all_metrics = parser.parse_objects(
        contents,
        {
            "expire_by_version": 15,
        },
    )
    errors = list(all_metrics)
    assert len(errors) == 0
    assert all_metrics.value["category"]["metric_expired_version"].disabled is True
    assert all_metrics.value["category"]["metric_expired_edge"].disabled is True
    assert all_metrics.value["category"]["metric_expired"].disabled is True
    assert all_metrics.value["category"]["metric"].disabled is False


def test_parser_mixed_expirations():
    """Validate that mixing expiration types fail"""
    with pytest.raises(ValueError):
        # Mixing expiration types must fail when expiring by version.
        all_metrics = parser.parse_objects(
            ROOT / "data" / "mixed-expirations.yaml",
            {
                "expire_by_version": 15,
            },
        )
        list(all_metrics)

    with pytest.raises(ValueError):
        # Mixing expiration types must fail when expiring by date.
        all_metrics = parser.parse_objects(ROOT / "data" / "mixed-expirations.yaml")
        list(all_metrics)


def test_expire_by_version_must_fail_if_disabled():
    failing_metrics = [
        {
            "category": {
                "metric_fail_date": {
                    "type": "boolean",
                    "expires": 99,
                },
            }
        }
    ]
    failing_metrics = [util.add_required(x) for x in failing_metrics]

    with pytest.raises(ValueError):
        # Versions are not allowed if expiration by major version is enabled.
        all_metrics = parser.parse_objects(failing_metrics)
        list(all_metrics)


def test_historical_versions():
    """
    Make sure we can load the correct version of the schema and it will
    correctly reject or not reject entries based on that.
    """

    # No issues:
    # * Bugs as numbers
    # * event extra keys don't have a type
    contents = [
        {
            "$schema": "moz://mozilla.org/schemas/glean/metrics/1-0-0",
            "category": {
                "metric": {
                    "type": "event",
                    "extra_keys": {"key_a": {"description": "foo"}},
                    "bugs": [42],
                }
            },
        }
    ]
    contents = [util.add_required(x) for x in contents]

    all_metrics = parser.parse_objects(contents)

    errors = list(all_metrics)
    assert len(errors) == 0

    # 1 issue:
    # * Bugs as numbers are disallowed
    #
    # events: not having a `type` is fine in version 2.
    contents = [
        {
            "$schema": "moz://mozilla.org/schemas/glean/metrics/2-0-0",
            "category": {
                "metric": {
                    "type": "event",
                    "extra_keys": {"key_a": {"description": "foo"}},
                    "bugs": [42],
                }
            },
        }
    ]
    contents = [util.add_required(x) for x in contents]

    all_metrics = parser.parse_objects(contents)

    errors = list(all_metrics)
    assert len(errors) == 1


def test_telemetry_mirror():
    """
    Ensure that telemetry_mirror makes it into the parsed metric definition.
    """

    all_metrics = parser.parse_objects(
        [ROOT / "data" / "telemetry_mirror.yaml"],
        config={"allow_reserved": False},
    )

    errs = list(all_metrics)
    assert len(errs) == 0

    assert (
        all_metrics.value["telemetry.mirrored"]["parses_fine"].telemetry_mirror
        == "telemetry.test.string_kind"
    )


def test_rates():
    """
    Ensure that `rate` metrics parse properly.
    """

    all_metrics = parser.parse_objects(
        [ROOT / "data" / "rate.yaml"],
        config={"allow_reserved": False},
    )

    errs = list(all_metrics)
    assert len(errs) == 0

    category = all_metrics.value["testing.rates"]
    assert category["has_internal_denominator"].type == "rate"
    assert (
        category["has_external_denominator"].type == "rate"
    )  # Hasn't been transformed to "numerator" yet
    assert (
        category["also_has_external_denominator"].type == "rate"
    )  # Hasn't been transformed to "numerator" yet
    assert (
        category["the_denominator"].type == "counter"
    )  # Hasn't been transformed to "denominator" yet


def test_ping_ordering():
    contents = parser.parse_objects(
        [ROOT / "data" / "pings.yaml"],
        config={"allow_reserved": False},
    )

    errs = list(contents)
    assert len(errs) == 0

    pings = list(contents.value["pings"].keys())

    assert pings == sorted(pings)


def test_metric_ordering():
    all_metrics = parser.parse_objects(
        [ROOT / "data" / "ordering.yaml"], config={"allow_reserved": False}
    )

    errs = list(all_metrics)
    assert len(errs) == 0

    category = all_metrics.value["testing.ordering"]

    assert len(category.values()) > 0
    test_metrics = [f"{m.category}.{m.name}" for m in category.values()]

    # Alphabetically ordered
    assert test_metrics == [
        "testing.ordering.a_second_test_metric",
        "testing.ordering.first_test_metric",
        "testing.ordering.third_test_metric",
    ]


def test_tag_ordering():
    all_metrics = parser.parse_objects(ROOT / "data" / "metric-with-tags.yaml")

    errs = list(all_metrics)
    assert len(errs) == 0

    tags = all_metrics.value["telemetry"]["client_id"].metadata["tags"]
    assert tags == sorted(tags)


def test_text_valid():
    """
    Ensure that `text` metrics parse properly.
    """

    all_metrics = parser.parse_objects(
        [ROOT / "data" / "text.yaml"],
        config={"allow_reserved": False},
    )

    errors = list(all_metrics)
    assert len(errors) == 0

    assert all_metrics.value["valid.text"]["lifetime"].lifetime == metrics.Lifetime.ping

    assert all_metrics.value["valid.text"]["sensitivity"].data_sensitivity == [
        metrics.DataSensitivity.stored_content
    ]


def test_text_invalid():
    """
    Ensure that `text` metrics parse properly.
    """

    all_metrics = parser.parse_objects(
        [ROOT / "data" / "text_invalid.yaml"],
        config={"allow_reserved": False},
    )

    errors = list(all_metrics)
    assert len(errors) == 3

    def compare(expected, found):
        return "".join(expected.split()) in "".join(found.split())

    for error in errors:
        if "sensitivity" in error:
            assert compare("'technical' is not one of", error)

        if "lifetime" in error:
            assert compare("'user' is not one of", error)

        if "builtin_pings" in error:
            assert compare("Built-in pings are not allowed", error)


def test_metadata_tags_sorted():
    all_metrics = parser.parse_objects(
        [
            util.add_required(
                {
                    "$tags": ["tag1"],
                    "category": {"metric": {"metadata": {"tags": ["tag2"]}}},
                }
            )
        ]
    )
    errors = list(all_metrics)
    assert len(errors) == 0
    assert all_metrics.value["category"]["metric"].disabled is False
    assert all_metrics.value["category"]["metric"].metadata["tags"] == ["tag1", "tag2"]


def test_no_lint_sorted():
    all_objects = parser.parse_objects(
        [
            util.add_required(
                {
                    "no_lint": ["lint1"],
                    "category": {"metric": {"no_lint": ["lint2"]}},
                }
            ),
            util.add_required_ping(
                {
                    "no_lint": ["lint1"],
                    "ping": {"no_lint": ["lint2"]},
                }
            ),
            {
                "$schema": parser.TAGS_ID,
                # no_lint is only valid at the top level for tags
                "no_lint": ["lint2", "lint1"],
                "tag": {"description": ""},
            },
        ]
    )
    errors = list(all_objects)
    assert len(errors) == 0
    assert all_objects.value["category"]["metric"].no_lint == ["lint1", "lint2"]
    assert all_objects.value["pings"]["ping"].no_lint == ["lint1", "lint2"]
    assert all_objects.value["tags"]["tag"].no_lint == ["lint1", "lint2"]


def test_no_internal_fields_exposed():
    """
    We accidentally exposed fields like `_config` and `_generate_enums` before.
    These ended up in probe-scraper output.

    We replicate the code probe-scraper uses
    and ensure we get the JSON we expect from it.
    """

    results = parser.parse_objects(
        [
            util.add_required(
                {
                    "category": {
                        "metric": {
                            "type": "event",
                            "extra_keys": {
                                "key_a": {"description": "desc-a", "type": "boolean"}
                            },
                        }
                    },
                }
            ),
        ]
    )
    errs = list(results)
    assert len(errs) == 0

    metrics = {
        metric.identifier(): metric.serialize()
        for category, probes in results.value.items()
        for probe_name, metric in probes.items()
    }

    expected = {
        "category.metric": {
            "bugs": ["http://bugzilla.mozilla.org/12345678"],
            "data_reviews": ["https://example.com/review/"],
            "defined_in": {"line": 3},
            "description": "DESCRIPTION...",
            "disabled": False,
            "expires": "never",
            "extra_keys": {"key_a": {"description": "desc-a", "type": "boolean"}},
            "gecko_datapoint": "",
            "lifetime": "ping",
            "metadata": {},
            "no_lint": [],
            "notification_emails": ["nobody@example.com"],
            "send_in_pings": ["events"],
            "type": "event",
            "version": 0,
        }
    }
    expected_json = json.dumps(expected, sort_keys=True, indent=2)

    out_json = json.dumps(
        metrics,
        sort_keys=True,
        indent=2,
    )
    assert expected_json == out_json


def test_object():
    structure = {"type": "array", "items": {"type": "number"}}
    contents = [{"category": {"metric": {"type": "object", "structure": structure}}}]

    contents = [util.add_required(x) for x in contents]
    all_metrics = parser.parse_objects(contents)
    errors = list(all_metrics)
    assert len(errors) == 0, errors
    assert len(all_metrics.value) == 1
    assert all_metrics.value["category"]["metric"]._generate_structure == structure


def test_object_invalid():
    contents = [{"category": {"metric": {"type": "object"}}}]

    contents = [util.add_required(x) for x in contents]
    all_metrics = parser.parse_objects(contents)
    errors = list(all_metrics)
    assert len(errors) == 1
    assert "`object` is missing required parameter `structure`" in errors[0]

    structure = {"type": "array", "items": {}}
    contents = [{"category": {"metric": {"type": "object", "structure": structure}}}]
    contents = [util.add_required(x) for x in contents]
    all_metrics = parser.parse_objects(contents)
    errors = list(all_metrics)
    assert len(errors) == 1
    assert "invalid or missing `type`" in errors[0]

    structure = {"type": "array", "items": {"type": "unknown"}}
    contents = [{"category": {"metric": {"type": "object", "structure": structure}}}]
    contents = [util.add_required(x) for x in contents]
    all_metrics = parser.parse_objects(contents)
    errors = list(all_metrics)
    assert len(errors) == 1
    assert "invalid or missing `type`" in errors[0]

    structure = {"type": "array", "properties": {}}
    contents = [{"category": {"metric": {"type": "object", "structure": structure}}}]
    contents = [util.add_required(x) for x in contents]
    all_metrics = parser.parse_objects(contents)
    errors = list(all_metrics)
    assert len(errors) == 1
    assert "`properties` not allowed in array structure" in errors[0]

    structure = {"type": "object", "items": {}}
    contents = [{"category": {"metric": {"type": "object", "structure": structure}}}]
    contents = [util.add_required(x) for x in contents]
    all_metrics = parser.parse_objects(contents)
    errors = list(all_metrics)
    assert len(errors) == 1
    assert "`items` not allowed in object structure" in errors[0]