-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdsl-parser_test.go
More file actions
1708 lines (1455 loc) · 44.8 KB
/
dsl-parser_test.go
File metadata and controls
1708 lines (1455 loc) · 44.8 KB
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
package watch
import (
"encoding/json"
"testing"
)
func TestLexer(t *testing.T) {
input := `rule HighValueTransaction {
description "Detect high value transactions"
when amount > 5000 and metadata.kyc_tier == 1
then review
score 0.8
reason "High value transaction from low KYC tier"
}`
lexer := NewLexer(input)
expectedTokens := []struct {
expectedType TokenType
expectedLiteral string
}{
{RULE, "rule"},
{IDENTIFIER, "HighValueTransaction"},
{LBRACE, "{"},
{NEWLINE, "\\n"},
{DESCRIPTION, "description"},
{STRING, "Detect high value transactions"},
{NEWLINE, "\\n"},
{WHEN, "when"},
{IDENTIFIER, "amount"},
{GT, ">"},
{NUMBER, "5000"},
{AND, "and"},
{IDENTIFIER, "metadata"},
{DOT, "."},
{IDENTIFIER, "kyc_tier"},
{EQ, "=="},
{NUMBER, "1"},
{NEWLINE, "\\n"},
{THEN, "then"},
{IDENTIFIER, "review"},
{NEWLINE, "\\n"},
{IDENTIFIER, "score"},
{NUMBER, "0.8"},
{NEWLINE, "\\n"},
{IDENTIFIER, "reason"},
{STRING, "High value transaction from low KYC tier"},
{NEWLINE, "\\n"},
{RBRACE, "}"},
{EOF, ""},
}
for i, tt := range expectedTokens {
tok, err := lexer.NextToken()
if err != nil {
t.Fatalf("lexer error at token %d: %v", i, err)
}
if tok.Type != tt.expectedType {
t.Fatalf("token %d - wrong token type. expected=%q, got=%q",
i, tt.expectedType, tok.Type)
}
if tok.Literal != tt.expectedLiteral {
t.Fatalf("token %d - wrong literal. expected=%q, got=%q",
i, tt.expectedLiteral, tok.Literal)
}
}
}
func TestLexerOperators(t *testing.T) {
input := `== != > >= < <= + ( ) { } , : . $`
lexer := NewLexer(input)
expectedTokens := []TokenType{
EQ, NE, GT, GTE, LT, LTE, PLUS, LPAREN, RPAREN,
LBRACE, RBRACE, COMMA, COLON, DOT, DOLLAR, EOF,
}
for i, expectedType := range expectedTokens {
tok, err := lexer.NextToken()
if err != nil {
t.Fatalf("lexer error at token %d: %v", i, err)
}
if tok.Type != expectedType {
t.Fatalf("token %d - wrong token type. expected=%q, got=%q",
i, expectedType, tok.Type)
}
}
}
func TestLexerStrings(t *testing.T) {
tests := []struct {
input string
expected string
hasError bool
}{
{`"hello world"`, "hello world", false},
{`"escaped \"quote\""`, `escaped \"quote\"`, false},
{`"unterminated string`, "", true},
{`""`, "", false},
}
for _, tt := range tests {
lexer := NewLexer(tt.input)
tok, err := lexer.NextToken()
if tt.hasError {
if err == nil {
t.Errorf("expected error for input %q, but got none", tt.input)
}
continue
}
if err != nil {
t.Errorf("unexpected error for input %q: %v", tt.input, err)
continue
}
if tok.Type != STRING {
t.Errorf("expected STRING token, got %s", tok.Type)
continue
}
if tok.Literal != tt.expected {
t.Errorf("expected literal %q, got %q", tt.expected, tok.Literal)
}
}
}
func TestLexerNumbers(t *testing.T) {
tests := []struct {
input string
expected string
}{
{"123", "123"},
{"123.456", "123.456"},
{"0", "0"},
{"0.0", "0.0"},
}
for _, tt := range tests {
lexer := NewLexer(tt.input)
tok, err := lexer.NextToken()
if err != nil {
t.Errorf("unexpected error for input %q: %v", tt.input, err)
continue
}
if tok.Type != NUMBER {
t.Errorf("expected NUMBER token, got %s", tok.Type)
continue
}
if tok.Literal != tt.expected {
t.Errorf("expected literal %q, got %q", tt.expected, tok.Literal)
}
}
}
func TestParserSimpleRule(t *testing.T) {
input := `rule TestRule {
description "A test rule"
when amount > 1000
then block
score 0.9
reason "Amount too high"
}`
lexer := NewLexer(input)
parser := NewParser(lexer)
rule, errors := parser.ParseRule()
if len(errors) > 0 {
t.Fatalf("parser errors: %v", errors)
}
if rule == nil {
t.Fatal("expected rule, got nil")
}
// Check rule name
if rule.Name.Value != "TestRule" {
t.Errorf("expected rule name 'TestRule', got %q", rule.Name.Value)
}
// Check description
if rule.Description == nil || rule.Description.Value != "A test rule" {
t.Errorf("expected description 'A test rule', got %v", rule.Description)
}
// Check when condition
if rule.When == nil {
t.Error("expected when condition, got nil")
}
// Check then action
if rule.Then.Verdict != "block" {
t.Errorf("expected verdict 'block', got %q", rule.Then.Verdict)
}
if rule.Then.Score.Value != 0.9 {
t.Errorf("expected score 0.9, got %f", rule.Then.Score.Value)
}
if rule.Then.Reason.Value != "Amount too high" {
t.Errorf("expected reason 'Amount too high', got %q", rule.Then.Reason.Value)
}
}
func TestParserMultipleConditions(t *testing.T) {
input := `rule MultiCondition {
when amount > 1000 and metadata.type == "transfer" and status != "pending"
then review
}`
lexer := NewLexer(input)
parser := NewParser(lexer)
rule, errors := parser.ParseRule()
if len(errors) > 0 {
t.Fatalf("parser errors: %v", errors)
}
if rule == nil {
t.Fatal("expected rule, got nil")
}
// Should have a logical expression with nested AND conditions
if rule.When == nil {
t.Error("expected when condition, got nil")
}
}
func TestParserFieldPaths(t *testing.T) {
input := `rule FieldPathTest {
when metadata.user.id == "123"
then allow
}`
lexer := NewLexer(input)
parser := NewParser(lexer)
rule, errors := parser.ParseRule()
if len(errors) > 0 {
t.Fatalf("parser errors: %v", errors)
}
if rule == nil {
t.Fatal("expected rule, got nil")
}
// Check that we parsed the field path correctly
if rule.When == nil {
t.Error("expected when condition, got nil")
return
}
// The condition should be an infix expression with a field path on the left
condition := rule.When
if infixExpr, ok := condition.(*InfixExpression); ok {
if fieldPath, ok := infixExpr.Left.(*FieldPath); ok {
expectedParts := []string{"metadata", "user", "id"}
if len(fieldPath.Parts) != len(expectedParts) {
t.Errorf("expected %d field path parts, got %d", len(expectedParts), len(fieldPath.Parts))
}
for i, part := range fieldPath.Parts {
if part != expectedParts[i] {
t.Errorf("expected field path part %d to be %q, got %q", i, expectedParts[i], part)
}
}
} else {
t.Errorf("expected field path on left side of condition, got %T", infixExpr.Left)
}
} else {
t.Errorf("expected infix expression, got %T", condition)
}
}
func TestParserVariables(t *testing.T) {
input := `rule VariableTest {
when source == $current.source
then block
}`
lexer := NewLexer(input)
parser := NewParser(lexer)
rule, errors := parser.ParseRule()
if len(errors) > 0 {
t.Fatalf("parser errors: %v", errors)
}
if rule == nil {
t.Fatal("expected rule, got nil")
}
// Check that we parsed the variable correctly
condition := rule.When
if infixExpr, ok := condition.(*InfixExpression); ok {
if variable, ok := infixExpr.Right.(*Variable); ok {
if variable.Name != "current.source" {
t.Errorf("expected variable name 'current.source', got %q", variable.Name)
}
} else {
t.Errorf("expected variable on right side of condition, got %T", infixExpr.Right)
}
}
}
func TestParserArrayLiterals(t *testing.T) {
input := `rule ArrayTest {
when status in ("pending", "processing", "failed")
then review
}`
lexer := NewLexer(input)
parser := NewParser(lexer)
rule, errors := parser.ParseRule()
if len(errors) > 0 {
t.Fatalf("parser errors: %v", errors)
}
if rule == nil {
t.Fatal("expected rule, got nil")
}
// Check that we parsed the array correctly
condition := rule.When
if infixExpr, ok := condition.(*InfixExpression); ok {
if arrayLit, ok := infixExpr.Right.(*ArrayLiteral); ok {
if len(arrayLit.Elements) != 3 {
t.Errorf("expected 3 array elements, got %d", len(arrayLit.Elements))
}
} else {
t.Errorf("expected array literal on right side of condition, got %T", infixExpr.Right)
}
}
}
func TestParserErrors(t *testing.T) {
tests := []struct {
name string
input string
}{
{
"missing rule name",
`rule {
when amount > 1000
then block
}`,
},
{
"missing when clause",
`rule Test {
then block
}`,
},
{
"missing then clause",
`rule Test {
when amount > 1000
}`,
},
{
"invalid verdict",
`rule Test {
when amount > 1000
then invalid_verdict
}`,
},
{
"unterminated string",
`rule Test {
description "unterminated
when amount > 1000
then block
}`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
lexer := NewLexer(tt.input)
parser := NewParser(lexer)
_, errors := parser.ParseRule()
if len(errors) == 0 {
t.Errorf("expected parse errors for %s, but got none", tt.name)
}
})
}
}
func TestCompileWatchScriptWithParser(t *testing.T) {
input := `rule HighValueTransaction {
description "Detect high value transactions"
when amount > 5000 and metadata.kyc_tier == 1
then review
score 0.8
reason "High value transaction from low KYC tier"
}`
ruleName, description, ruleJSON, err := CompileWatchScript(input)
if err != nil {
t.Fatalf("compilation error: %v", err)
}
// Check extracted values
if ruleName != "HighValueTransaction" {
t.Errorf("expected rule name 'HighValueTransaction', got %q", ruleName)
}
if description != "Detect high value transactions" {
t.Errorf("expected description 'Detect high value transactions', got %q", description)
}
// Check that JSON is valid
var rule Rule
if err := json.Unmarshal([]byte(ruleJSON), &rule); err != nil {
t.Fatalf("invalid JSON output: %v", err)
}
// Check rule structure
if rule.Then.Verdict != "review" {
t.Errorf("expected verdict 'review', got %q", rule.Then.Verdict)
}
if rule.Then.Score != 0.8 {
t.Errorf("expected score 0.8, got %f", rule.Then.Score)
}
if rule.Then.Reason != "High value transaction from low KYC tier" {
t.Errorf("expected reason 'High value transaction from low KYC tier', got %q", rule.Then.Reason)
}
// Should have 2 conditions (amount > 5000 and metadata.kyc_tier == 1)
if len(rule.When) != 2 {
t.Errorf("expected 2 when conditions, got %d", len(rule.When))
}
}
func TestCompileWatchScriptWithParserComplexConditions(t *testing.T) {
input := `rule ComplexRule {
description "Complex rule with various conditions"
when amount >= 10000 and status != "completed" and metadata.type in ("transfer", "withdrawal")
then block
score 0.95
reason "Suspicious high-value incomplete transaction"
}`
ruleName, _, ruleJSON, err := CompileWatchScript(input)
if err != nil {
t.Fatalf("compilation error: %v", err)
}
// Check extracted values
if ruleName != "ComplexRule" {
t.Errorf("expected rule name 'ComplexRule', got %q", ruleName)
}
// Check that JSON is valid
var rule Rule
if err := json.Unmarshal([]byte(ruleJSON), &rule); err != nil {
t.Fatalf("invalid JSON output: %v", err)
}
// Should have 3 conditions
if len(rule.When) != 3 {
t.Errorf("expected 3 when conditions, got %d", len(rule.When))
}
}
func TestParserLineNumbers(t *testing.T) {
input := `rule Test {
when amount > 1000
then invalid_verdict
}`
lexer := NewLexer(input)
parser := NewParser(lexer)
_, errors := parser.ParseRule()
if len(errors) == 0 {
t.Fatal("expected parse errors, but got none")
}
// Check that error has line number information
for _, err := range errors {
if err.Line == 0 {
t.Errorf("expected line number in error, got 0")
}
if err.Column == 0 {
t.Errorf("expected column number in error, got 0")
}
}
}
func TestParserWithoutRuleKeyword(t *testing.T) {
input := `TestRule {
description "Test without rule keyword"
when amount > 1000
then block
}`
lexer := NewLexer(input)
parser := NewParser(lexer)
rule, errors := parser.ParseRule()
if len(errors) > 0 {
t.Fatalf("parser errors: %v", errors)
}
if rule == nil {
t.Fatal("expected rule, got nil")
}
if rule.Name.Value != "TestRule" {
t.Errorf("expected rule name 'TestRule', got %q", rule.Name.Value)
}
}
func TestParserDefaultValues(t *testing.T) {
input := `rule DefaultTest {
when amount > 1000
then review
}`
lexer := NewLexer(input)
parser := NewParser(lexer)
rule, errors := parser.ParseRule()
if len(errors) > 0 {
t.Fatalf("parser errors: %v", errors)
}
if rule == nil {
t.Fatal("expected rule, got nil")
}
// Check default values
if rule.Then.Score.Value != 0.0 {
t.Errorf("expected default score 0.0, got %f", rule.Then.Score.Value)
}
if rule.Then.Reason.Value != "No reason provided" {
t.Errorf("expected default reason 'No reason provided', got %q", rule.Then.Reason.Value)
}
}
// Benchmark tests
func BenchmarkLexer(b *testing.B) {
input := `rule HighValueTransaction {
description "Detect high value transactions"
when amount > 5000 and metadata.kyc_tier == 1 and status != "pending"
then review
score 0.8
reason "High value transaction from low KYC tier"
}`
b.ResetTimer()
for i := 0; i < b.N; i++ {
lexer := NewLexer(input)
for {
tok, _ := lexer.NextToken()
if tok.Type == EOF {
break
}
}
}
}
func BenchmarkParser(b *testing.B) {
input := `rule HighValueTransaction {
description "Detect high value transactions"
when amount > 5000 and metadata.kyc_tier == 1 and status != "pending"
then review
score 0.8
reason "High value transaction from low KYC tier"
}`
b.ResetTimer()
for i := 0; i < b.N; i++ {
lexer := NewLexer(input)
parser := NewParser(lexer)
parser.ParseRule()
}
}
func BenchmarkCompileWatchScriptWithParser(b *testing.B) {
input := `rule HighValueTransaction {
description "Detect high value transactions"
when amount > 5000 and metadata.kyc_tier == 1 and status != "pending"
then review
score 0.8
reason "High value transaction from low KYC tier"
}`
b.ResetTimer()
for i := 0; i < b.N; i++ {
CompileWatchScript(input)
}
}
// Test comparison with old regex-based compiler
func TestParserOrConditions(t *testing.T) {
input := `rule OrTest {
when amount > 1000 or status == "suspicious"
then review
}`
lexer := NewLexer(input)
parser := NewParser(lexer)
rule, errors := parser.ParseRule()
if len(errors) > 0 {
t.Fatalf("parser errors: %v", errors)
}
if rule == nil {
t.Fatal("expected rule, got nil")
}
// Check that we parsed the OR condition correctly
if rule.When == nil {
t.Fatal("expected when condition, got nil")
}
// The condition should be a logical expression
if logicalExpr, ok := rule.When.(*LogicalExpression); ok {
if logicalExpr.Operator != "or" {
t.Errorf("expected OR operator, got %q", logicalExpr.Operator)
}
} else {
t.Errorf("expected logical expression, got %T", rule.When)
}
}
func TestParserComplexLogicalConditions(t *testing.T) {
input := `rule ComplexLogical {
when amount > 1000 and status == "pending" or metadata.type == "urgent"
then block
}`
lexer := NewLexer(input)
parser := NewParser(lexer)
rule, errors := parser.ParseRule()
if len(errors) > 0 {
t.Fatalf("parser errors: %v", errors)
}
if rule == nil {
t.Fatal("expected rule, got nil")
}
// Should parse as: (amount > 1000 and status == "pending") or metadata.type == "urgent"
// Due to left-associativity
if logicalExpr, ok := rule.When.(*LogicalExpression); ok {
if logicalExpr.Operator != "or" {
t.Errorf("expected top-level OR operator, got %q", logicalExpr.Operator)
}
// Left side should be another logical expression (AND)
if leftLogical, ok := logicalExpr.Left.(*LogicalExpression); ok {
if leftLogical.Operator != "and" {
t.Errorf("expected left side to be AND, got %q", leftLogical.Operator)
}
} else {
t.Errorf("expected left side to be logical expression, got %T", logicalExpr.Left)
}
} else {
t.Errorf("expected logical expression, got %T", rule.When)
}
}
func TestLexerOrToken(t *testing.T) {
input := `amount > 1000 or status == "pending"`
lexer := NewLexer(input)
expectedTokens := []TokenType{
IDENTIFIER, GT, NUMBER, OR, IDENTIFIER, EQ, STRING, EOF,
}
for i, expectedType := range expectedTokens {
tok, err := lexer.NextToken()
if err != nil {
t.Fatalf("lexer error at token %d: %v", i, err)
}
if tok.Type != expectedType {
t.Fatalf("token %d - wrong token type. expected=%q, got=%q",
i, expectedType, tok.Type)
}
}
}
func TestCompileWatchScriptWithOrConditions(t *testing.T) {
input := `rule OrConditionTest {
description "Test OR conditions"
when amount > 5000 or status == "suspicious" or metadata.risk_level == "high"
then block
score 0.9
reason "High risk transaction"
}`
ruleName, description, ruleJSON, err := CompileWatchScript(input)
if err != nil {
t.Fatalf("compilation error: %v", err)
}
// Check extracted values
if ruleName != "OrConditionTest" {
t.Errorf("expected rule name 'OrConditionTest', got %q", ruleName)
}
if description != "Test OR conditions" {
t.Errorf("expected description 'Test OR conditions', got %q", description)
}
// Check that JSON is valid
var rule Rule
if err := json.Unmarshal([]byte(ruleJSON), &rule); err != nil {
t.Fatalf("invalid JSON output: %v", err)
}
// Check rule structure
if rule.Then.Verdict != "block" {
t.Errorf("expected verdict 'block', got %q", rule.Then.Verdict)
}
if rule.Then.Score != 0.9 {
t.Errorf("expected score 0.9, got %f", rule.Then.Score)
}
// Should have at least one condition (the logical expression)
if len(rule.When) == 0 {
t.Error("expected at least one when condition")
}
}
func TestCompileWatchScriptMixedAndOr(t *testing.T) {
input := `rule MixedLogical {
when amount > 1000 and status != "completed" or metadata.urgent == true
then review
}`
_, _, ruleJSON, err := CompileWatchScript(input)
if err != nil {
t.Fatalf("compilation error: %v", err)
}
// Check that JSON is valid
var rule Rule
if err := json.Unmarshal([]byte(ruleJSON), &rule); err != nil {
t.Fatalf("invalid JSON output: %v", err)
}
// Should have at least one condition
if len(rule.When) == 0 {
t.Error("expected at least one when condition")
}
}
func TestParserFunctionCallsWithNamedArguments(t *testing.T) {
input := `rule BlockWhenPreviousTransactionFailed {
description "Block when previous transaction failed for same source"
when previous_transaction(
within: "PT1H",
match: {
status: "failed",
source: "$current.source"
}
)
and amount > 700000
then block
score 1.0
}`
lexer := NewLexer(input)
parser := NewParser(lexer)
rule, errors := parser.ParseRule()
if len(errors) > 0 {
for _, err := range errors {
t.Logf("Parse error: %v", err)
}
t.Fatalf("parser errors: %v", errors)
}
if rule == nil {
t.Fatal("expected rule, got nil")
}
// Check rule name
if rule.Name.Value != "BlockWhenPreviousTransactionFailed" {
t.Errorf("expected rule name 'BlockWhenPreviousTransactionFailed', got %q", rule.Name.Value)
}
// Check description
if rule.Description == nil || rule.Description.Value != "Block when previous transaction failed for same source" {
t.Errorf("expected description 'Block when previous transaction failed for same source', got %v", rule.Description)
}
// Check when condition - should be a logical expression with AND
if rule.When == nil {
t.Fatal("expected when condition, got nil")
}
if logicalExpr, ok := rule.When.(*LogicalExpression); ok {
if logicalExpr.Operator != "and" {
t.Errorf("expected AND operator, got %q", logicalExpr.Operator)
}
// Left side should be a function call
if funcCall, ok := logicalExpr.Left.(*FunctionCall); ok {
if funcCall.Name != "previous_transaction" {
t.Errorf("expected function name 'previous_transaction', got %q", funcCall.Name)
}
// Should have 2 arguments: within and match
if len(funcCall.Arguments) != 2 {
t.Errorf("expected 2 function arguments, got %d", len(funcCall.Arguments))
}
// Check first argument (within: "PT1H")
if namedArg, ok := funcCall.Arguments[0].(*NamedArgument); ok {
if namedArg.Name != "within" {
t.Errorf("expected first argument name 'within', got %q", namedArg.Name)
}
if stringLit, ok := namedArg.Value.(*StringLiteral); ok {
if stringLit.Value != "PT1H" {
t.Errorf("expected within value 'PT1H', got %q", stringLit.Value)
}
} else {
t.Errorf("expected string literal for within value, got %T", namedArg.Value)
}
} else {
t.Errorf("expected first argument to be named argument, got %T", funcCall.Arguments[0])
}
// Check second argument (match: {...})
if namedArg, ok := funcCall.Arguments[1].(*NamedArgument); ok {
if namedArg.Name != "match" {
t.Errorf("expected second argument name 'match', got %q", namedArg.Name)
}
if objLit, ok := namedArg.Value.(*ObjectLiteral); ok {
if len(objLit.Pairs) != 2 {
t.Errorf("expected 2 object pairs, got %d", len(objLit.Pairs))
}
// Check that status and source keys exist
if _, exists := objLit.Pairs["status"]; !exists {
t.Error("expected 'status' key in match object")
}
if _, exists := objLit.Pairs["source"]; !exists {
t.Error("expected 'source' key in match object")
}
} else {
t.Errorf("expected object literal for match value, got %T", namedArg.Value)
}
} else {
t.Errorf("expected second argument to be named argument, got %T", funcCall.Arguments[1])
}
} else {
t.Errorf("expected left side to be function call, got %T", logicalExpr.Left)
}
// Right side should be amount > 700000
if infixExpr, ok := logicalExpr.Right.(*InfixExpression); ok {
if infixExpr.Operator != ">" {
t.Errorf("expected > operator, got %q", infixExpr.Operator)
}
} else {
t.Errorf("expected right side to be infix expression, got %T", logicalExpr.Right)
}
} else {
t.Errorf("expected logical expression, got %T", rule.When)
}
// Check then action
if rule.Then.Verdict != "block" {
t.Errorf("expected verdict 'block', got %q", rule.Then.Verdict)
}
if rule.Then.Score.Value != 1.0 {
t.Errorf("expected score 1.0, got %f", rule.Then.Score.Value)
}
}
func TestCompileBlockIfPreviousFailedScript(t *testing.T) {
input := `rule BlockWhenPreviousTransactionFailed {
description "Block when previous transaction failed for same source"
when previous_transaction(
within: "PT1H",
match: {
status: "failed",
source: "$current.source"
}
)
and amount > 700000
then block
score 1.0
}`
ruleName, description, ruleJSON, err := CompileWatchScript(input)
if err != nil {
t.Fatalf("compilation error: %v", err)
}
// Check extracted values
if ruleName != "BlockWhenPreviousTransactionFailed" {
t.Errorf("expected rule name 'BlockWhenPreviousTransactionFailed', got %q", ruleName)
}
if description != "Block when previous transaction failed for same source" {
t.Errorf("expected description 'Block when previous transaction failed for same source', got %q", description)
}
// Check that JSON is valid
var rule Rule
if err := json.Unmarshal([]byte(ruleJSON), &rule); err != nil {
t.Fatalf("invalid JSON output: %v", err)
}
// Check rule structure
if rule.Then.Verdict != "block" {
t.Errorf("expected verdict 'block', got %q", rule.Then.Verdict)
}
if rule.Then.Score != 1.0 {
t.Errorf("expected score 1.0, got %f", rule.Then.Score)
}
// Should have conditions
if len(rule.When) == 0 {
t.Fatal("expected at least one when condition")
}
// Parser must emit "previous_transaction" (not "function_comparison") so the interpreter evaluates it.
var foundPrevTx bool
for _, raw := range rule.When {
var probe struct {
Type string `json:"type"`
}
_ = json.Unmarshal(raw, &probe)
if probe.Type == "previous_transaction" {
foundPrevTx = true
var pc struct {
TimeWindow string `json:"time_window"`
Match map[string]interface{} `json:"match"`
}
_ = json.Unmarshal(raw, &pc)
if pc.TimeWindow != "PT1H" {
t.Errorf("expected time_window PT1H, got %q", pc.TimeWindow)
}
if pc.Match["source"] != "$current.source" || pc.Match["status"] != "failed" {
t.Errorf("expected match source=$current.source, status=failed; got %v", pc.Match)
}
break
}
if probe.Type == "logical" {
var l struct {
Left json.RawMessage `json:"left"`
}
_ = json.Unmarshal(raw, &l)
if len(l.Left) > 0 {
var inner struct {
Type string `json:"type"`
}
_ = json.Unmarshal(l.Left, &inner)
if inner.Type == "previous_transaction" {
foundPrevTx = true
var pc struct {
TimeWindow string `json:"time_window"`
Match map[string]interface{} `json:"match"`
}
_ = json.Unmarshal(l.Left, &pc)
if pc.TimeWindow != "PT1H" {
t.Errorf("expected time_window PT1H, got %q", pc.TimeWindow)
}
break
}
}
}
}
if !foundPrevTx {
t.Errorf("expected a previous_transaction condition in when; got: %s", ruleJSON)
}
t.Logf("Generated JSON: %s", ruleJSON)
}