| 1 |
// Copyright 2022 Google LLC |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
package parser |
| 16 |
|
| 17 |
import ( |
| 18 |
"testing" |
| 19 |
|
| 20 |
"github.com/google/cel-go/common" |
| 21 |
"github.com/google/cel-go/common/ast" |
| 22 |
|
| 23 |
"google.golang.org/protobuf/proto" |
| 24 |
) |
| 25 |
|
| 26 |
func TestExprHelperCopy(t *testing.T) { |
| 27 |
src := common.NewStringSource( |
| 28 |
`noop([1, 2, 3].map(i, Msg{first: 1 + 2, second: a.b, third: {true: true}}))`, |
| 29 |
"") |
| 30 |
p, err := NewParser( |
| 31 |
PopulateMacroCalls(true), |
| 32 |
Macros( |
| 33 |
MapMacro, |
| 34 |
NewGlobalMacro("noop", 1, |
| 35 |
func(eh ExprHelper, target ast.Expr, args []ast.Expr) (ast.Expr, *common.Error) { |
| 36 |
return eh.Copy(args[0]), nil |
| 37 |
}, |
| 38 |
), |
| 39 |
), |
| 40 |
) |
| 41 |
if err != nil { |
| 42 |
t.Fatalf("NewParser() failed: %v", err) |
| 43 |
} |
| 44 |
parsed, errs := p.Parse(src) |
| 45 |
if errs != nil && len(errs.GetErrors()) != 0 { |
| 46 |
t.Fatalf("p.Parse(%v) failed: %v", src, errs.ToDisplayString()) |
| 47 |
} |
| 48 |
// id generation is consistent between runs, and in this case '27' refers to the |
| 49 |
// macro expression that's the sole argument to the noop() macro. |
| 50 |
macroTarget, found := parsed.SourceInfo().GetMacroCall(27) |
| 51 |
if !found { |
| 52 |
t.Fatal("GetMacroCall(27) failed to find call") |
| 53 |
} |
| 54 |
macroExpr, err := ast.ExprToProto(macroTarget) |
| 55 |
if err != nil { |
| 56 |
t.Fatalf("ast.ExprToProto() failed: %v", err) |
| 57 |
} |
| 58 |
protoExpr, err := ast.ExprToProto(parsed.Expr()) |
| 59 |
if err != nil { |
| 60 |
t.Fatalf("ast.ExprToProto() failed: %v", err) |
| 61 |
} |
| 62 |
if proto.Equal(protoExpr, macroExpr) { |
| 63 |
t.Errorf("Copy() failed to provide a unique ids: %v", macroExpr) |
| 64 |
} |
| 65 |
} |