-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathParserTests.cs
1066 lines (953 loc) · 41.9 KB
/
ParserTests.cs
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
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using FluentAssertions;
using NUnit.Framework;
using PromQL.Parser.Ast;
using Superpower;
using Superpower.Model;
namespace PromQL.Parser.Tests
{
[TestFixture]
public class ParserTests
{
[SetUp]
public void SetUp()
{
AssertionOptions.AssertEquivalencyUsing(opts =>
opts.IncludingAllRuntimeProperties()
.Excluding(p => p.Name == "TextSpan")
);
}
[Test]
public void StringLiteralDoubleQuote() => Parse(Parser.StringLiteral, "\"A string\"")
.Should().Be(new StringLiteral('"', "A string", new TextSpan("\"A string\"")));
[Test]
public void StringLiteralDoubleQuoteEscaped() => Parse(Parser.StringLiteral, @"""\a\b\f\n\r\t\v\\\""""")
.Should().Be(new StringLiteral('"', "\a\b\f\n\r\t\v\\\"", new TextSpan(@"""\a\b\f\n\r\t\v\\\""""")));
[Test]
public void StringLiteralDoubleQuoteNewline() =>
Assert.Throws<ParseException>(() => Parse(Parser.StringLiteral, "\"\n\""));
[Test]
public void StringLiteralSingleQuote() => Parse(Parser.StringLiteral, "'A string'")
.Should().Be(new StringLiteral('\'', "A string", new TextSpan("'A string'")));
[Test]
public void StringLiteralSingleQuoteEscaped() => Parse(Parser.StringLiteral, @"'\a\b\f\n\r\t\v\\\''")
.Should().Be(new StringLiteral('\'', "\a\b\f\n\r\t\v\\\'", new TextSpan(@"'\a\b\f\n\r\t\v\\\''")));
[Test]
public void StringLiteralSingleQuoteNewline() =>
Assert.Throws<ParseException>(() => Parse(Parser.StringLiteral, "'\n'"));
[Test]
public void StringLiteralRaw() => Parse(Parser.StringLiteral, "`A string`")
.Should().Be(new StringLiteral('`', "A string", new TextSpan("`A string`")));
[Test]
public void StringLiteralRaw_Multiline() => Parse(Parser.StringLiteral, "`A\n string`")
.Should().Be(new StringLiteral('`', "A\n string", new TextSpan("`A\n string`")));
[Test]
public void StringLiteralRaw_NoEscapes() => Parse(Parser.StringLiteral, @"`\a\b\f\n\r\t\v`")
.Should().Be(new StringLiteral('`', @"\a\b\f\n\r\t\v", new TextSpan(@"`\a\b\f\n\r\t\v`")));
[Test]
[TestCase("2y52w365d25h10m30s100ms", "1460.01:10:30.100")]
[TestCase("60w", "420.00:00:00")]
[TestCase("48h", "2.00:00:00")]
[TestCase("70m", "01:10:00")]
[TestCase("180s", "00:03:00")]
[TestCase("500ms", "00:00:00.500")]
public void Duration(string input, string expected) => Parse(Parser.Duration, input)
.Should().Be(new Duration(TimeSpan.Parse(expected), new TextSpan(input)));
[Test]
[TestCase("1", 1.0)]
[TestCase("5.", 5.0)]
[TestCase("-5", -5.0)]
[TestCase(".5", 0.5)]
[TestCase("123.4567", 123.4567)]
[TestCase("1e-5", 0.00001)]
[TestCase("1e5", 100000)]
[TestCase("1.55E+5", 155000)]
public void Number(string input, double expected) => Parse(Parser.Number, input)
.Should().Be(new NumberLiteral(expected, new TextSpan(input)));
[Test]
[TestCase("nan")]
[TestCase("NaN")]
public void Number_NaN(string input) => Parse(Parser.Number, input)
.Should().Be(new NumberLiteral(double.NaN, new TextSpan(input)));
[Test]
[TestCase("Inf")]
[TestCase("+inf")]
public void Number_InfPos(string input) => Parse(Parser.Number, input)
.Should().Be(new NumberLiteral(double.PositiveInfinity, new TextSpan(input)));
[Test]
[TestCase("-Inf")]
[TestCase("-inf")]
public void Number_InfNeg(string input) => Parse(Parser.Number, input)
.Should().Be(new NumberLiteral(double.NegativeInfinity, new TextSpan(input)));
[Test]
[TestCaseSource(nameof(FunctionsAggregatesAndOperators))]
public void LabelValueMatcher_FunctionsOperatorsAndKeywords(string identifier) =>
Parse(Parser.LabelValueMatcher, identifier).Value.Should().Be(identifier);
[Test]
public void LabelMatchers_Empty()
{
const string input = "{}";
Parse(Parser.LabelMatchers, input)
.Should().Be(new LabelMatchers(ImmutableArray<LabelMatcher>.Empty, new TextSpan(input)));
}
[Test]
public void LabelMatchers_EmptyNoComma()
{
Assert.Throws<ParseException>(() => Parse(Parser.LabelMatchers, "{,}"));
}
[Test]
public void LabelMatchers_One()
{
const string input = "{blah=\"my_label\"}";
Parse(Parser.LabelMatchers, input)
.Should().BeEquivalentTo(
new LabelMatchers(new []
{
new LabelMatcher(
"blah",
Operators.LabelMatch.Equal,
new StringLiteral('"', "my_label", new TextSpan(input, new Position(6, 0, 0), 10)),
new TextSpan(input, new Position(1, 0, 0), 15)
)
}.ToImmutableArray(),
Span: new TextSpan(input)
)
);
}
[Test]
public void LabelMatchers_OneTrailingComma()
{
const string input = "{blah=\"my_label\" , }";
Parse(Parser.LabelMatchers, input)
.Should().BeEquivalentTo(
new LabelMatchers(
new[]
{
new LabelMatcher(
"blah",
Operators.LabelMatch.Equal,
new StringLiteral('"', "my_label", new TextSpan(input, new Position(6, 0, 0), 10)),
new TextSpan(input, new Position(1, 0, 0), 15)
),
}.ToImmutableArray(),
new TextSpan(input)
)
);
}
[Test]
public void LabelMatchers_Many()
{
Parse(Parser.LabelMatchers, "{ blah=\"my_label\", blah_123 != 'my_label', b123=~'label', b_!~'label' }")
.Should().BeEquivalentTo(
new LabelMatchers(
new []
{
new LabelMatcher("blah", Operators.LabelMatch.Equal, new StringLiteral('"', "my_label")),
new LabelMatcher("blah_123", Operators.LabelMatch.NotEqual, new StringLiteral('\'', "my_label")),
new LabelMatcher("b123", Operators.LabelMatch.Regexp, new StringLiteral('\'', "label")),
new LabelMatcher("b_", Operators.LabelMatch.NotRegexp, new StringLiteral('\'', "label"))
}.ToImmutableArray()
),
// Don't assert over parsed Span positions, will be tedious to specify all positions
cfg => cfg.Excluding(x => x.Name == "Span")
);
}
[Test]
public void VectorSelector_MetricIdentifier()
{
const string input = ":this_is_a_metric";
Parse(Parser.VectorSelector, input)
.Should().BeEquivalentTo(
new VectorSelector(new MetricIdentifier(input, new TextSpan(input)), new TextSpan(input))
);
}
[Test]
public void VectorSelector_MetricIdentifier_And_LabelMatchers()
{
const string input = ":this_is_a_metric { }";
Parse(Parser.VectorSelector, input)
.Should().BeEquivalentTo(
new VectorSelector(
new MetricIdentifier(":this_is_a_metric", new TextSpan(input, new Position(0, 0, 0), 17)),
new LabelMatchers(ImmutableArray<LabelMatcher>.Empty, new TextSpan(input, new Position(18, 0, 0), 3)),
new TextSpan(input)
)
);
}
[Test]
public void VectorSelector_LabelMatchers()
{
const string input = "{ }";
Parse(Parser.VectorSelector, input)
.Should().BeEquivalentTo(
new VectorSelector(
new LabelMatchers(ImmutableArray<LabelMatcher>.Empty, new TextSpan(input)),
new TextSpan(input)
)
);
}
[Test]
public void MatrixSelector()
{
var input = "metric { } [ 1m1s ]";
Parse(Parser.MatrixSelector, input)
.Should().Be(new MatrixSelector(
new VectorSelector(
new MetricIdentifier("metric", new TextSpan(input, Position.Zero, 6)),
new LabelMatchers(ImmutableArray<LabelMatcher>.Empty, new TextSpan(input, new Position(7, 0, 0), 3)),
new TextSpan(input, Position.Zero, 10)
),
new Duration(new TimeSpan(0, 1, 1), new TextSpan(input, new Position(13, 0, 0), 4)),
new TextSpan(input)
));
}
[Test]
public void Offset_Vector()
{
const string input = "metric { } offset 1m";
var expr = Parse(Parser.Expr, input);
var offsetExpr = expr.Should().BeOfType<OffsetExpr>().Subject;
offsetExpr.Expr.Should().BeOfType<VectorSelector>();
offsetExpr.Duration.Value.Should().Be(TimeSpan.FromMinutes(1));
offsetExpr.Span.Should().Be(new TextSpan(input));
}
[Test]
public void Offset_MatrixSelector()
{
const string input = "metric { } [ 1m1s ] offset -7m";
var expr = Parse(Parser.Expr, input);
var offsetExpr = expr.Should().BeOfType<OffsetExpr>().Subject;
offsetExpr.Expr.Should().BeOfType<MatrixSelector>();
offsetExpr.Duration.Value.Should().Be(TimeSpan.FromMinutes(-7));
offsetExpr.Span.Should().Be(new TextSpan(input));
}
[Test]
public void Offset_Subquery()
{
var input = "metric[ 1h:1m ] offset 1w";
var expr = Parse(Parser.Expr, input);
expr.Should().BeEquivalentTo(
new OffsetExpr(
new SubqueryExpr(
new VectorSelector(new MetricIdentifier("metric")),
new Duration(TimeSpan.FromHours(1)),
new Duration(TimeSpan.FromMinutes(1))
),
new Duration(TimeSpan.FromDays(7))
),
// Don't assert over parsed Span positions, will be tedious to specify all positions
cfg => cfg.Excluding(x => x.Name == "Span")
);
expr.Span.Should().Be(new TextSpan(input));
}
[Test]
[TestCase("time() offset 1m")]
[TestCase("avg(blah) offset 1m")]
[TestCase("'asdas' offset 1m")]
[TestCase("1 offset 1m")]
public void Offset_Invalid(string badQuery)
{
Assert.Throws<ParseException>(() => Parse(Parser.Expr, badQuery))
.Message.Should().Contain("offset modifier must be preceded by an instant vector selector or range vector selector or a subquery");
}
[Test]
public void Subquery_Offset()
{
const string input = "metric offset 1w [ 1h:1m ]";
var expr = Parse(Parser.Expr, input);
expr.Should().BeEquivalentTo(
new SubqueryExpr(
new OffsetExpr(
new VectorSelector(new MetricIdentifier("metric")),
new Duration(TimeSpan.FromDays(7))
),
new Duration(TimeSpan.FromHours(1)),
new Duration(TimeSpan.FromMinutes(1))
),
// Don't assert over parsed Span positions, will be tedious to specify all positions
cfg => cfg.Excluding(x => x.Name == "Span")
);
expr.Span.Should().Be(new TextSpan(input));
}
[Test]
public void ParenExpr_Empty()
{
Assert.Throws<ParseException>(() => Parse(Parser.Expr, " ( ) "));
}
[Test]
public void ParenExpr_MissingLeft()
{
Assert.Throws<ParseException>(() => Parse(Parser.Expr.AtEnd(), " ( 1 )) "));
}
[Test]
public void ParenExpr_MissingRight()
{
Assert.Throws<ParseException>(() => Parse(Parser.Expr, " (( 1 ) "));
}
[Test]
public void ParenExpr_Simple()
{
var input = " (1) ";
var parsed = Parse(Parser.Expr, input)
.Should().Be(
new ParenExpression(
new NumberLiteral(1.0, new TextSpan(input, new Position(2, 0, 0), 1)),
new TextSpan(input, new Position(1, 0, 0), 3)
)
);
}
[Test]
public void ParenExpr_Nested()
{
var input = "((1))";
var parsed = Parse(Parser.Expr, input)
.Should().Be(
new ParenExpression(
new ParenExpression(
new NumberLiteral(1.0, new TextSpan(input, new Position(2, 0, 0), 1)),
new TextSpan(input, new Position(1, 0, 0), 3)
),
new TextSpan(input)
)
);
}
[Test]
public void FunctionCall_Empty()
{
var input = "time ()";
Parse(Parser.FunctionCall, input)
.Should().Be(new FunctionCall(Functions.Map["time"], ImmutableArray<Expr>.Empty, new TextSpan(input)));
}
[Test]
public void FunctionCall_InvalidName()
{
Assert.Throws<ParseException>(() => Parse(Parser.Expr, "this_doesnt_exist ()"));
}
[Test]
public void FunctionCall_InvalidParameterCount()
{
Assert.Throws<ParseException>(() => Parse(Parser.Expr, "abs(-1, 1)"))
.Message.Contains("expected 1 argument(s)");
}
[Test]
public void FunctionCall_InvalidParameterCountVaradic()
{
Assert.Throws<ParseException>(() => Parse(Parser.Expr, "label_join(instant_vector, 'dst_label', 'separator')"))
.Message.Should().Contain("expected at least 4 argument(s)");
}
[Test]
[TestCase("hour()")]
[TestCase("hour(one)")]
[TestCase("hour(one, two)")]
[TestCase("label_join(instant_vector, 'dst_label', 'separator', 'one', 'two')")]
public void FunctionCall_Varadic(string query)
{
Parse(Parser.Expr, query).Should().BeOfType<FunctionCall>();
}
[Test]
public void FunctionCall_OneArg() => Parse(Parser.Expr, "abs (1)")
.Should().BeEquivalentTo(
new FunctionCall(Functions.Map["abs"], new Expr[] { new NumberLiteral(1.0) }.ToImmutableArray()),
// Don't assert over parsed Span positions, will be tedious to specify all positions
cfg => cfg.Excluding(x => x.Name == "Span")
);
[Test]
// NOTE: we do not validate the types of functions in the parser
public void FunctionCall_MultiArg() => Parse(Parser.Expr, "histogram_quantile (0.9, blah)")
.Should().BeEquivalentTo(
new FunctionCall(Functions.Map["histogram_quantile"], new Expr[] { new NumberLiteral(0.9), new VectorSelector(new MetricIdentifier("blah")) }.ToImmutableArray()),
// Don't assert over parsed Span positions, will be tedious to specify all positions
cfg => cfg.Excluding(x => x.Name == "Span")
);
[Test]
public void FunctionCall_SnakeCase() => Parse(Parser.Expr, "absent_over_time (metric_name )")
.Should().BeEquivalentTo(
new FunctionCall(Functions.Map["absent_over_time"], new Expr[] { new VectorSelector(new MetricIdentifier("metric_name")) }.ToImmutableArray()),
// Don't assert over parsed Span positions, will be tedious to specify all positions
cfg => cfg.Excluding(x => x.Name == "Span")
);
[Test]
public void UnaryExpr_Plus()
{
const string input = "+1";
Parse(Parser.UnaryExpr, input)
.Should().Be(
new UnaryExpr(
Operators.Unary.Add,
new NumberLiteral(1.0, new TextSpan(input, new Position(1, 0 , 0), 1)),
new TextSpan(input)
)
);
}
[Test]
public void UnaryExpr_Minus()
{
const string input = "-1";
Parse(Parser.UnaryExpr, input)
.Should().Be(
new UnaryExpr(
Operators.Unary.Sub,
new NumberLiteral(1.0, new TextSpan(input, new Position(1, 0 , 0), 1)),
new TextSpan(input)
)
);
}
[Test]
public void Expr()
{
Parse(Parser.Expr, "'a string'").Should().BeOfType<StringLiteral>();
Parse(Parser.Expr, "1").Should().BeOfType<NumberLiteral>();
Parse(Parser.Expr, "1 + 1").Should().BeOfType<BinaryExpr>();
Parse(Parser.Expr, "sum (some_expr)").Should().BeOfType<AggregateExpr>();
Parse(Parser.Expr, "some_expr[1d:]").Should().BeOfType<SubqueryExpr>();
Parse(Parser.Expr, "some_expr offset 1d").Should().BeOfType<OffsetExpr>();
Parse(Parser.Expr, "some_expr").Should().BeOfType<VectorSelector>();
Parse(Parser.Expr, "some_expr[1d]").Should().BeOfType<MatrixSelector>();
Parse(Parser.Expr, "+(1)").Should().BeOfType<UnaryExpr>();
Parse(Parser.Expr, "abs(-1)").Should().BeOfType<FunctionCall>();
}
[Test]
public void Expr_NumberWithSign()
{
// Make sure we don't parse this as a unary expression!
Parse(Parser.Expr, "+1").Should().Be(new NumberLiteral(1, new TextSpan("+1")));
Parse(Parser.Expr, "-1").Should().Be(new NumberLiteral(-1, new TextSpan("-1")));
}
[Test]
[TestCaseSource(nameof(FunctionsAggregatesAndOperators))]
public void Expr_FunctionMetricIdentifier(string input)
{
Parse(Parser.Expr, input).Should().BeOfType<VectorSelector>().Which
.MetricIdentifier.Value.Should().Be(input);
}
[Test]
public void Expr_NotKeywordMetricIdentifier()
{
Assert.Throws<ParseException>(() => Parse(Parser.Expr, "on {}"));
}
[Test]
public void Expr_NameKeywordWorkaround()
{
Parse(Parser.Expr, "{__name__='on'}").Should().BeEquivalentTo(
new VectorSelector(new LabelMatchers(new []
{
new LabelMatcher("__name__", Operators.LabelMatch.Equal, new StringLiteral('\'', "on"))
}.ToImmutableArray())),
// Don't assert over parsed Span positions, will be tedious to specify all positions
cfg => cfg.Excluding(x => x.Name == "Span")
);
}
[Test]
public void Expr_Complex()
{
var toParse =
"sum by(job, mode) (rate(node_cpu_seconds_total[1m])) / " +
"on(job) group_left sum by(job)(rate(node_cpu_seconds_total[1m]))";
Parse(Parser.Expr, toParse).Should().BeEquivalentTo(
new BinaryExpr(
new AggregateExpr(
Operators.Aggregates["sum"],
new FunctionCall(
Functions.Map["rate"],
new Expr[]{
new MatrixSelector(
new VectorSelector(new MetricIdentifier("node_cpu_seconds_total")),
new Duration(TimeSpan.FromMinutes(1))
)
}.ToImmutableArray()
),
null,
new []{"job", "mode"}.ToImmutableArray(),
false
),
new AggregateExpr(
Operators.Aggregates["sum"],
new FunctionCall(
Functions.Map["rate"],
new Expr[]{
new MatrixSelector(
new VectorSelector(new MetricIdentifier("node_cpu_seconds_total")),
new Duration(TimeSpan.FromMinutes(1))
)
}.ToImmutableArray()
),
null,
new []{ "job" }.ToImmutableArray(),
false
),
Operators.Binary.Div,
new VectorMatching(
Operators.VectorMatchCardinality.ManyToOne,
new [] { "job"}.ToImmutableArray(),
true,
ImmutableArray<string>.Empty,
false
)
),
// Don't assert over parsed Span positions, will be tedious to specify all positions
cfg => cfg.Excluding(x => x.Name == "Span")
);
}
// TODO probably need to expand upon our invalid test cases significantly
[Test]
public void Invalid_Expr()
{
Assert.Throws<ParseException>(() => Parse(Parser.Expr, "!= 'blah'"));
}
[Test]
public void Invalid_DurationExpr()
{
// Prior to this test, a very unhelpful error message would be returned (parsing would complain about an invalid
// opening parenthesis)
Assert.Throws<ParseException>(() => Parse(Parser.Expr, "sum(my_metric[window])")).Message
.Should().Be("Syntax error (line 1, column 15): unexpected identifier `window`, expected duration.");
}
[Test]
public void ParseExpression_With_Comments()
{
Parser.ParseExpression(" #some comment \n 1 \n # another comment!").Should().BeOfType<NumberLiteral>();
}
[Test]
public void GroupingLabels_Nothing()
{
Assert.Throws<ParseException>(() => Parse(Parser.GroupingLabels, " "));
}
[Test]
public void GroupingLabels_Empty() => Parse(Parser.GroupingLabels, " ( )")
.Value.Should().BeEmpty();
[Test]
public void GroupingLabels_One() => Parse(Parser.GroupingLabels, " ( one ) ")
.Value.Should().Equal("one");
[Test]
public void GroupingLabels_Many()
{
var parsed = Parse(Parser.GroupingLabels, " ( one, two, three ) ");
parsed.Value.Should().Equal("one", "two", "three");
parsed.Span.ToString().Should().Be("( one, two, three )");
}
[Test]
public void VectorMatching_Bool()
{
const string input = "bool";
Parse(Parser.VectorMatching, input)
.Should().BeEquivalentTo(new VectorMatching(
Operators.VectorMatchCardinality.OneToOne,
ImmutableArray<string>.Empty,
false,
ImmutableArray<string>.Empty,
true,
new TextSpan(input))
);
}
[Test]
public void VectorMatching_Ignoring()
{
const string input = "ignoring (one, two)";
Parse(Parser.VectorMatching, input)
.Should().BeEquivalentTo(new VectorMatching(
Operators.VectorMatchCardinality.OneToOne,
new[] {"one", "two"}.ToImmutableArray(),
false,
ImmutableArray<string>.Empty,
false,
new TextSpan(input))
);
}
[Test]
public void VectorMatching_On()
{
const string input = "on ()";
Parse(Parser.VectorMatching, input)
.Should().BeEquivalentTo(new VectorMatching(
Operators.VectorMatchCardinality.OneToOne,
ImmutableArray<string>.Empty,
true,
ImmutableArray<string>.Empty,
false,
new TextSpan(input))
);
}
[Test]
public void VectorMatching_Bool_On()
{
const string input = "bool on ()";
Parse(Parser.VectorMatching, input)
.Should().BeEquivalentTo(new VectorMatching(
Operators.VectorMatchCardinality.OneToOne,
ImmutableArray<string>.Empty,
true,
ImmutableArray<string>.Empty,
true,
new TextSpan(input)
)
);
}
[Test]
public void VectorMatching_GroupLeft()
{
const string input = "on () group_left ()";
Parse(Parser.VectorMatching, input)
.Should().BeEquivalentTo(new VectorMatching(
Operators.VectorMatchCardinality.ManyToOne,
ImmutableArray<string>.Empty,
true,
ImmutableArray<string>.Empty,
false,
new TextSpan(input)
)
);
}
[Test]
public void VectorMatching_GroupLeftEmpty()
{
const string input = "on () group_left";
Parse(Parser.VectorMatching, input)
.Should().BeEquivalentTo(new VectorMatching(
Operators.VectorMatchCardinality.ManyToOne,
ImmutableArray<string>.Empty,
true,
ImmutableArray<string>.Empty,
false,
new TextSpan(input))
);
}
[Test]
public void VectorMatching_GroupRight()
{
const string input = "on () group_right (one, two)";
Parse(Parser.VectorMatching, input)
.Should().BeEquivalentTo(
new VectorMatching(
Operators.VectorMatchCardinality.OneToMany,
ImmutableArray<string>.Empty,
true,
new []{ "one","two"}.ToImmutableArray(),
false,
new TextSpan(input)
)
);
}
[Test]
[TestCase("group_left ()")]
[TestCase("group_right (one)")]
public void VectorMatching_GroupInvalid(string input)
{
Assert.Throws<ParseException>(() => Parse(Parser.VectorMatching.AtEnd(), input));
}
[Test]
[TestCase("1 + 1", Operators.Binary.Add)]
[TestCase("1 - 1", Operators.Binary.Sub)]
[TestCase("1 * 1", Operators.Binary.Mul)]
[TestCase("1 / 1", Operators.Binary.Div)]
[TestCase("1 % 1", Operators.Binary.Mod)]
[TestCase("1 ^ 1", Operators.Binary.Pow)]
[TestCase("1 == 1", Operators.Binary.Eql)]
[TestCase("1 != 1", Operators.Binary.Neq)]
[TestCase("1 > 1", Operators.Binary.Gtr)]
[TestCase("1 < 1", Operators.Binary.Lss)]
[TestCase("1 >= 1", Operators.Binary.Gte)]
[TestCase("1 <= 1", Operators.Binary.Lte)]
[TestCase("1 and 1", Operators.Binary.And)]
[TestCase("1 or 1", Operators.Binary.Or)]
[TestCase("1 unless 1", Operators.Binary.Unless)]
public void BinaryExpr_Operators(string input, Operators.Binary expected)
{
var parsed = Parse(Parser.BinaryExpr, input).As<BinaryExpr>();
parsed.Operator.Should().Be(expected);
parsed.Span.Should().Be(new TextSpan(input));
}
[Test]
public void BinaryExpr_SimpleVector()
{
Parse(Parser.BinaryExpr, "metric_name + {label='one'}")
.Should().BeEquivalentTo(new BinaryExpr(
new VectorSelector(new MetricIdentifier("metric_name")),
new VectorSelector(new LabelMatchers(new []
{
new LabelMatcher("label", Operators.LabelMatch.Equal, new StringLiteral('\'', "one"))
}.ToImmutableArray())),
Operators.Binary.Add,
new VectorMatching()
),
// Don't assert over parsed Span positions, will be tedious to specify all positions
cfg => cfg.Excluding(x => x.Name == "Span")
);
}
[Test]
[TestCase("1 + 2 + 3")]
[TestCase("1 / 2 * 3")]
[TestCase("1 + 2 - 3")]
[TestCase("1 < 2 > 3")]
public void BinaryExpr_PrecedenceEqual(string input)
{
var result = Parse(Parser.BinaryExpr, input) as BinaryExpr;
result.RightHandSide.Should().Be(new NumberLiteral(3.0, new TextSpan(input, new Position(8, 0, 0), 1)));
var binExpr = result.LeftHandSide.Should().BeOfType<BinaryExpr>();
binExpr.Which.LeftHandSide.Should().Be(new NumberLiteral(1.0, new TextSpan(input, new Position(0, 0, 0), 1)));
binExpr.Which.RightHandSide.Should().Be(new NumberLiteral(2.0, new TextSpan(input, new Position(4, 0, 0), 1)));
}
[Test]
[TestCase("1 * 2 + 3")]
[TestCase("1 - 2 > 3")]
[TestCase("1 < 2 and 3")]
[TestCase("1 and 2 or 3")]
public void BinaryExpr_PrecedenceHigher(string input)
{
var result = Parse(Parser.BinaryExpr, input);
var binExpr = result.LeftHandSide.Should().BeOfType<BinaryExpr>();
binExpr.Which.LeftHandSide.Should().BeOfType<NumberLiteral>().Which.Value.Should().Be(1);
binExpr.Which.RightHandSide.Should().BeOfType<NumberLiteral>().Which.Value.Should().Be(2);
result.RightHandSide.Should().BeOfType<NumberLiteral>().Which.Value.Should().Be(3);
}
[Test]
[TestCase("1 - 2 / 3")]
[TestCase("1 <= 2 + 3")]
[TestCase("1 unless 2 >= 3")]
[TestCase("1 or 2 unless 3")]
public void BinaryExpr_PrecedenceLower(string input)
{
var result = Parse(Parser.BinaryExpr, input);
result.LeftHandSide.Should().BeOfType<NumberLiteral>().Which.Value.Should().Be(1);
var binExpr = result.RightHandSide.Should().BeOfType<BinaryExpr>();
binExpr.Which.LeftHandSide.Should().BeOfType<NumberLiteral>().Which.Value.Should().Be(2);
binExpr.Which.RightHandSide.Should().BeOfType<NumberLiteral>().Which.Value.Should().Be(3);
}
[Test]
public void BinaryExpr_Nested()
{
var result = Parse(Parser.BinaryExpr, "((1 + 2) + 3) + 4");
result.As<BinaryExpr>().LeftHandSide.Should().BeOfType<ParenExpression>().Which
.Expr.Should().BeOfType<BinaryExpr>().Which
.LeftHandSide.Should().BeOfType<ParenExpression>().Which
.Expr.Should().BeOfType<BinaryExpr>().Which
.LeftHandSide.Should().BeOfType<NumberLiteral>().Subject.Value.Should().Be(1);
}
[Test]
public void BinaryExpr_VectorMatching()
{
Parse(Parser.BinaryExpr, "1 > bool 2")
.Should().BeEquivalentTo(new BinaryExpr(
new NumberLiteral(1.0),
new NumberLiteral(2),
Operators.Binary.Gtr,
new VectorMatching(true)
),
// Don't assert over parsed Span positions, will be tedious to specify all positions
cfg => cfg.Excluding(x => x.Name == "Span")
);
}
[Test]
[TestCase("1 + bool 2")]
[TestCase("1 - bool 2")]
[TestCase("1 / bool 2")]
[TestCase("1 * bool 2")]
[TestCase("1 or bool 2")]
[TestCase("1 unless bool 2")]
[TestCase("1 and bool 2")]
[TestCase("1 > bool 1 or bool 1 < bool 1")]
public void BinaryExpr_BoolNonComparison(string query)
{
Assert.Throws<ParseException>(() => Parse(Parser.BinaryExpr, query))
.Message.Should().Contain("bool modifier can only be used on comparison operators");
}
[Test]
[TestCase("avg (blah)", "avg")]
[TestCase("bottomk (2, blah)", "bottomk")]
[TestCase("count (blah)", "count")]
[TestCase("count_values (blah, values)", "count_values")]
[TestCase("group (blah)", "group")]
[TestCase("max (blah)", "max")]
[TestCase("min (blah)", "min")]
[TestCase("quantile (0.5, blah)", "quantile")]
[TestCase("stddev (blah)", "stddev")]
[TestCase("stdvar (blah)", "stdvar")]
[TestCase("sum (blah)", "sum")]
[TestCase("topk (1, blah)", "topk")]
public void AggregateExpr_Operator(string input, string expected) => Parse(Parser.AggregateExpr, input)
.Operator.Name.Should().Be(expected);
[Test]
public void AggregateExpr_NoMod()
{
const string input = "sum (blah)";
var result = Parse(Parser.AggregateExpr, input);
result.Should().BeEquivalentTo(
new AggregateExpr(
Operators.Aggregates["sum"],
new VectorSelector(new MetricIdentifier("blah")),
null,
ImmutableArray<string>.Empty,
false
),
// Don't assert over parsed Span positions, will be tedious to specify all positions
cfg => cfg.Excluding(x => x.Name == "Span")
);
result.Span.Should().Be(new TextSpan(input));
}
[Test]
public void AggregateExpr_LeadingModBy()
{
const string input = "sum by (one, two) (blah)";
var result = Parse(Parser.AggregateExpr, input);
result.Should().BeEquivalentTo(
new AggregateExpr(
Operators.Aggregates["sum"],
new VectorSelector(new MetricIdentifier("blah")),
null,
new string[] {"one", "two"}.ToImmutableArray(),
false
),
// Don't assert over parsed Span positions, will be tedious to specify all positions
cfg => cfg.Excluding(x => x.Name == "Span")
);
result.Span.Should().Be(new TextSpan(input));
}
[Test]
public void AggregateExpr_TrailingModWithout()
{
const string input = "sum (blah) without (one)";
var result = Parse(Parser.AggregateExpr, input);
result.Should().BeEquivalentTo(
new AggregateExpr(
Operators.Aggregates["sum"],
new VectorSelector(new MetricIdentifier("blah")),
null,
new string[] {"one"}.ToImmutableArray(),
true
),
// Don't assert over parsed Span positions, will be tedious to specify all positions
cfg => cfg.Excluding(x => x.Name == "Span")
);
result.Span.Should().Be(new TextSpan(input));
}
[Test]
public void AggregateExpr_TwoArgs() => Parse(Parser.AggregateExpr, "quantile (0.5, blah)").Should().BeEquivalentTo(
new AggregateExpr(
Operators.Aggregates["quantile"],
new VectorSelector(new MetricIdentifier("blah")),
new NumberLiteral(0.5),
ImmutableArray<string>.Empty,
false
),
// Don't assert over parsed Span positions, will be tedious to specify all positions
cfg => cfg.Excluding(x => x.Name == "Span")
);
[Test]
public void AggregateExpr_OneArgs_InvalidFunc() =>
Assert.Throws<ParseException>(() => Parse(Parser.AggregateExpr, "quantile (blah)"))
.Message.Should().Contain("wrong number of arguments for aggregate expression provided, expected 2, got 1");
[Test]
public void AggregateExpr_TwoArgs_InvalidFunc() =>
Assert.Throws<ParseException>(() => Parse(Parser.AggregateExpr, "sum (0.5, blah)"))
.Message.Should().Contain("wrong number of arguments for aggregate expression provided, expected 1, got 2");
[Test]
public void AggregateExpr_LabelNameAggOp()
{
Parse(Parser.Expr, @"sum by (quantile) (test)").Should().BeOfType<AggregateExpr>();
}
[Test]
public void Subquery_WithStep()
{
const string input = "blah[1h:1m]";
var result = Parse(Parser.Expr, input);
result.Should().BeEquivalentTo(
new SubqueryExpr(
new VectorSelector(new MetricIdentifier("blah")),
new Duration(TimeSpan.FromHours(1)),
new Duration(TimeSpan.FromMinutes(1))
),
// Don't assert over parsed Span positions, will be tedious to specify all positions
cfg => cfg.Excluding(x => x.Name == "Span")
);
result.Span.Should().Be(new TextSpan(input));
}
[Test]
public void Subquery_WithoutStep()
{
const string input = "blah[1d:]";
var result = Parse(Parser.Expr, input);
result.Should().BeEquivalentTo(
new SubqueryExpr(
new VectorSelector(new MetricIdentifier("blah")),
new Duration(TimeSpan.FromDays(1)),
null
),
// Don't assert over parsed Span positions, will be tedious to specify all positions
cfg => cfg.Excluding(x => x.Name == "Span")
);
result.Span.Should().Be(new TextSpan(input));
}
[Test]
public void Subquery_Expressions()
{
Parse(Parser.Expr, "vector(1) [1h:]").Should().BeOfType<SubqueryExpr>().Which
.Expr.Should().BeOfType<FunctionCall>();
Parse(Parser.Expr, "1 + 1 [1h:]").Should().BeOfType<BinaryExpr>().Which
.RightHandSide.Should().BeOfType<SubqueryExpr>();
Parse(Parser.Expr, "(1 + 1) [1h:]").Should().BeOfType<SubqueryExpr>().Which
.Expr.Should().BeOfType<ParenExpression>();
Parse(Parser.Expr, "blah{} [1h:]").Should().BeOfType<SubqueryExpr>().Which
.Expr.Should().BeOfType<VectorSelector>();
}
public static T Parse<T>(TokenListParser<PromToken, T> parser, string input)
{
var tokens = new Tokenizer().Tokenize(input);