mirror of
https://github.com/open-policy-agent/opa.git
synced 2026-08-13 03:42:35 -06:00
ast: fix String() of empty body (#8244)
This gave me a panic,
panic: runtime error: makeslice: cap out of range
when printing some PE results.
Signed-off-by: Stephan Renatus <stephan.renatus@gmail.com>
This commit is contained in:
@@ -91,6 +91,53 @@ func TestBodyEmptyJSON(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBodyStringAndStringLength(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
body Body
|
||||
wantLength int
|
||||
}{
|
||||
{
|
||||
name: "empty body",
|
||||
body: Body{},
|
||||
wantLength: len(""),
|
||||
},
|
||||
{
|
||||
name: "nil body",
|
||||
body: nil,
|
||||
wantLength: len(""),
|
||||
},
|
||||
{
|
||||
name: "single expression",
|
||||
body: MustParseBody("true"),
|
||||
wantLength: len("true"),
|
||||
},
|
||||
{
|
||||
name: "two expressions",
|
||||
body: MustParseBody("true; false"),
|
||||
wantLength: len("true; false"),
|
||||
},
|
||||
{
|
||||
name: "three expressions",
|
||||
body: MustParseBody("x = 1; y = 2; z = 3"),
|
||||
wantLength: len("x = 1; y = 2; z = 3"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
gotLength := tt.body.StringLength()
|
||||
if gotLength != tt.wantLength {
|
||||
t.Errorf("Body.StringLength() = %d, want %d (body: %q)", gotLength, tt.wantLength, tt.body.String())
|
||||
}
|
||||
|
||||
if gotLength < 0 {
|
||||
t.Errorf("Body.StringLength() returned negative value: %d", gotLength)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPackageEquals(t *testing.T) {
|
||||
pkg1 := &Package{Path: RefTerm(VarTerm("foo"), StringTerm("bar"), StringTerm("baz")).Value.(Ref)}
|
||||
pkg2 := &Package{Path: RefTerm(VarTerm("foo"), StringTerm("bar"), StringTerm("baz")).Value.(Ref)}
|
||||
|
||||
@@ -283,7 +283,7 @@ func (b Body) StringLength() (n int) {
|
||||
for _, expr := range b {
|
||||
n += expr.StringLength() + 2 // "; "
|
||||
}
|
||||
return n - 2 // minus last "; "
|
||||
return max(n-2, 0) // minus last "; " (if `n` isn't 0)
|
||||
}
|
||||
|
||||
func (e *Expr) StringLength() (n int) {
|
||||
|
||||
Reference in New Issue
Block a user