| 1 |
// Copyright 2017 The Bazel Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
package starlark_test |
| 6 |
|
| 7 |
import ( |
| 8 |
"bytes" |
| 9 |
"errors" |
| 10 |
"fmt" |
| 11 |
"math" |
| 12 |
"os" |
| 13 |
"os/exec" |
| 14 |
"path/filepath" |
| 15 |
"reflect" |
| 16 |
"sort" |
| 17 |
"strings" |
| 18 |
"testing" |
| 19 |
|
| 20 |
"go.starlark.net/internal/chunkedfile" |
| 21 |
"go.starlark.net/lib/json" |
| 22 |
starlarkmath "go.starlark.net/lib/math" |
| 23 |
starlarkproto "go.starlark.net/lib/proto" |
| 24 |
"go.starlark.net/lib/time" |
| 25 |
"go.starlark.net/starlark" |
| 26 |
"go.starlark.net/starlarkstruct" |
| 27 |
"go.starlark.net/starlarktest" |
| 28 |
"go.starlark.net/syntax" |
| 29 |
"google.golang.org/protobuf/proto" |
| 30 |
"google.golang.org/protobuf/reflect/protodesc" |
| 31 |
|
| 32 |
"google.golang.org/protobuf/types/descriptorpb" |
| 33 |
) |
| 34 |
|
| 35 |
// A test may enable non-standard options by containing (e.g.) "option:recursion". |
| 36 |
func getOptions(src string) *syntax.FileOptions { |
| 37 |
return &syntax.FileOptions{ |
| 38 |
Set: option(src, "set"), |
| 39 |
While: option(src, "while"), |
| 40 |
TopLevelControl: option(src, "toplevelcontrol"), |
| 41 |
GlobalReassign: option(src, "globalreassign"), |
| 42 |
LoadBindsGlobally: option(src, "loadbindsglobally"), |
| 43 |
Recursion: option(src, "recursion"), |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
func option(chunk, name string) bool { |
| 48 |
return strings.Contains(chunk, "option:"+name) |
| 49 |
} |
| 50 |
|
| 51 |
func TestEvalExpr(t *testing.T) { |
| 52 |
// This is mostly redundant with the new *.star tests. |
| 53 |
// TODO(adonovan): move checks into *.star files and |
| 54 |
// reduce this to a mere unit test of starlark.Eval. |
| 55 |
thread := new(starlark.Thread) |
| 56 |
for _, test := range []struct{ src, want string }{ |
| 57 |
{`123`, `123`}, |
| 58 |
{`-1`, `-1`}, |
| 59 |
{`"a"+"b"`, `"ab"`}, |
| 60 |
{`1+2`, `3`}, |
| 61 |
|
| 62 |
// lists |
| 63 |
{`[]`, `[]`}, |
| 64 |
{`[1]`, `[1]`}, |
| 65 |
{`[1,]`, `[1]`}, |
| 66 |
{`[1, 2]`, `[1, 2]`}, |
| 67 |
{`[2 * x for x in [1, 2, 3]]`, `[2, 4, 6]`}, |
| 68 |
{`[2 * x for x in [1, 2, 3] if x > 1]`, `[4, 6]`}, |
| 69 |
{`[(x, y) for x in [1, 2] for y in [3, 4]]`, |
| 70 |
`[(1, 3), (1, 4), (2, 3), (2, 4)]`}, |
| 71 |
{`[(x, y) for x in [1, 2] if x == 2 for y in [3, 4]]`, |
| 72 |
`[(2, 3), (2, 4)]`}, |
| 73 |
// tuples |
| 74 |
{`()`, `()`}, |
| 75 |
{`(1)`, `1`}, |
| 76 |
{`(1,)`, `(1,)`}, |
| 77 |
{`(1, 2)`, `(1, 2)`}, |
| 78 |
{`(1, 2, 3, 4, 5)`, `(1, 2, 3, 4, 5)`}, |
| 79 |
{`1, 2`, `(1, 2)`}, |
| 80 |
// dicts |
| 81 |
{`{}`, `{}`}, |
| 82 |
{`{"a": 1}`, `{"a": 1}`}, |
| 83 |
{`{"a": 1,}`, `{"a": 1}`}, |
| 84 |
|
| 85 |
// conditional |
| 86 |
{`1 if 3 > 2 else 0`, `1`}, |
| 87 |
{`1 if "foo" else 0`, `1`}, |
| 88 |
{`1 if "" else 0`, `0`}, |
| 89 |
|
| 90 |
// indexing |
| 91 |
{`["a", "b"][0]`, `"a"`}, |
| 92 |
{`["a", "b"][1]`, `"b"`}, |
| 93 |
{`("a", "b")[0]`, `"a"`}, |
| 94 |
{`("a", "b")[1]`, `"b"`}, |
| 95 |
{`"aΩb"[0]`, `"a"`}, |
| 96 |
{`"aΩb"[1]`, `"\xce"`}, |
| 97 |
{`"aΩb"[3]`, `"b"`}, |
| 98 |
{`{"a": 1}["a"]`, `1`}, |
| 99 |
{`{"a": 1}["b"]`, `key "b" not in dict`}, |
| 100 |
{`{}[[]]`, `unhashable type: list`}, |
| 101 |
{`{"a": 1}[[]]`, `unhashable type: list`}, |
| 102 |
{`[x for x in range(3)]`, "[0, 1, 2]"}, |
| 103 |
} { |
| 104 |
var got string |
| 105 |
if v, err := starlark.Eval(thread, "<expr>", test.src, nil); err != nil { |
| 106 |
got = err.Error() |
| 107 |
} else { |
| 108 |
got = v.String() |
| 109 |
} |
| 110 |
if got != test.want { |
| 111 |
t.Errorf("eval %s = %s, want %s", test.src, got, test.want) |
| 112 |
} |
| 113 |
} |
| 114 |
} |
| 115 |
|
| 116 |
func TestExecFile(t *testing.T) { |
| 117 |
testdata := starlarktest.DataFile("starlark", ".") |
| 118 |
thread := &starlark.Thread{Load: load} |
| 119 |
starlarktest.SetReporter(thread, t) |
| 120 |
|
| 121 |
// This proto is used for the proto.star tests. It's generated by running: |
| 122 |
// protoc --descriptor_set_out=test.fds test.proto |
| 123 |
data, err := os.ReadFile("testdata/proto/test.fds") |
| 124 |
if err != nil { |
| 125 |
t.Fatal(err) |
| 126 |
} |
| 127 |
fds := &descriptorpb.FileDescriptorSet{} |
| 128 |
if err := proto.Unmarshal(data, fds); err != nil { |
| 129 |
t.Fatal(err) |
| 130 |
} |
| 131 |
pool, err := protodesc.NewFiles(fds) |
| 132 |
if err != nil { |
| 133 |
t.Fatal(err) |
| 134 |
} |
| 135 |
starlarkproto.SetPool(thread, pool) |
| 136 |
|
| 137 |
for _, file := range []string{ |
| 138 |
"testdata/assign.star", |
| 139 |
"testdata/bool.star", |
| 140 |
"testdata/builtins.star", |
| 141 |
"testdata/bytes.star", |
| 142 |
"testdata/control.star", |
| 143 |
"testdata/dict.star", |
| 144 |
"testdata/float.star", |
| 145 |
"testdata/function.star", |
| 146 |
"testdata/int.star", |
| 147 |
"testdata/json.star", |
| 148 |
"testdata/list.star", |
| 149 |
"testdata/math.star", |
| 150 |
"testdata/misc.star", |
| 151 |
"testdata/proto.star", |
| 152 |
"testdata/set.star", |
| 153 |
"testdata/string.star", |
| 154 |
"testdata/time.star", |
| 155 |
"testdata/tuple.star", |
| 156 |
"testdata/recursion.star", |
| 157 |
"testdata/module.star", |
| 158 |
"testdata/while.star", |
| 159 |
} { |
| 160 |
filename := filepath.Join(testdata, file) |
| 161 |
for _, chunk := range chunkedfile.Read(filename, t) { |
| 162 |
predeclared := starlark.StringDict{ |
| 163 |
"hasfields": starlark.NewBuiltin("hasfields", newHasFields), |
| 164 |
"fibonacci": fib{}, |
| 165 |
"struct": starlark.NewBuiltin("struct", starlarkstruct.Make), |
| 166 |
} |
| 167 |
|
| 168 |
opts := getOptions(chunk.Source) |
| 169 |
_, err := starlark.ExecFileOptions(opts, thread, filename, chunk.Source, predeclared) |
| 170 |
switch err := err.(type) { |
| 171 |
case *starlark.EvalError: |
| 172 |
found := false |
| 173 |
for i := range err.CallStack { |
| 174 |
posn := err.CallStack.At(i).Pos |
| 175 |
if posn.Filename() == filename { |
| 176 |
chunk.GotError(int(posn.Line), err.Error()) |
| 177 |
found = true |
| 178 |
break |
| 179 |
} |
| 180 |
} |
| 181 |
if !found { |
| 182 |
t.Error(err.Backtrace()) |
| 183 |
} |
| 184 |
case nil: |
| 185 |
// success |
| 186 |
default: |
| 187 |
t.Errorf("\n%s", err) |
| 188 |
} |
| 189 |
chunk.Done() |
| 190 |
} |
| 191 |
} |
| 192 |
} |
| 193 |
|
| 194 |
// A fib is an iterable value representing the infinite Fibonacci sequence. |
| 195 |
type fib struct{} |
| 196 |
|
| 197 |
func (t fib) Freeze() {} |
| 198 |
func (t fib) String() string { return "fib" } |
| 199 |
func (t fib) Type() string { return "fib" } |
| 200 |
func (t fib) Truth() starlark.Bool { return true } |
| 201 |
func (t fib) Hash() (uint32, error) { return 0, fmt.Errorf("fib is unhashable") } |
| 202 |
func (t fib) Iterate() starlark.Iterator { return &fibIterator{0, 1} } |
| 203 |
|
| 204 |
type fibIterator struct{ x, y int } |
| 205 |
|
| 206 |
func (it *fibIterator) Next(p *starlark.Value) bool { |
| 207 |
*p = starlark.MakeInt(it.x) |
| 208 |
it.x, it.y = it.y, it.x+it.y |
| 209 |
return true |
| 210 |
} |
| 211 |
func (it *fibIterator) Done() {} |
| 212 |
|
| 213 |
// load implements the 'load' operation as used in the evaluator tests. |
| 214 |
func load(thread *starlark.Thread, module string) (starlark.StringDict, error) { |
| 215 |
if module == "assert.star" { |
| 216 |
return starlarktest.LoadAssertModule() |
| 217 |
} |
| 218 |
if module == "json.star" { |
| 219 |
return starlark.StringDict{"json": json.Module}, nil |
| 220 |
} |
| 221 |
if module == "time.star" { |
| 222 |
return starlark.StringDict{"time": time.Module}, nil |
| 223 |
} |
| 224 |
if module == "math.star" { |
| 225 |
return starlark.StringDict{"math": starlarkmath.Module}, nil |
| 226 |
} |
| 227 |
if module == "proto.star" { |
| 228 |
return starlark.StringDict{"proto": starlarkproto.Module}, nil |
| 229 |
} |
| 230 |
|
| 231 |
// TODO(adonovan): test load() using this execution path. |
| 232 |
filename := filepath.Join(filepath.Dir(thread.CallFrame(0).Pos.Filename()), module) |
| 233 |
return starlark.ExecFile(thread, filename, nil, nil) |
| 234 |
} |
| 235 |
|
| 236 |
func newHasFields(thread *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { |
| 237 |
if len(args)+len(kwargs) > 0 { |
| 238 |
return nil, fmt.Errorf("%s: unexpected arguments", b.Name()) |
| 239 |
} |
| 240 |
return &hasfields{attrs: make(map[string]starlark.Value)}, nil |
| 241 |
} |
| 242 |
|
| 243 |
// hasfields is a test-only implementation of HasAttrs. |
| 244 |
// It permits any field to be set. |
| 245 |
// Clients will likely want to provide their own implementation, |
| 246 |
// so we don't have any public implementation. |
| 247 |
type hasfields struct { |
| 248 |
attrs starlark.StringDict |
| 249 |
frozen bool |
| 250 |
} |
| 251 |
|
| 252 |
var ( |
| 253 |
_ starlark.HasAttrs = (*hasfields)(nil) |
| 254 |
_ starlark.HasBinary = (*hasfields)(nil) |
| 255 |
) |
| 256 |
|
| 257 |
func (hf *hasfields) String() string { return "hasfields" } |
| 258 |
func (hf *hasfields) Type() string { return "hasfields" } |
| 259 |
func (hf *hasfields) Truth() starlark.Bool { return true } |
| 260 |
func (hf *hasfields) Hash() (uint32, error) { return 42, nil } |
| 261 |
|
| 262 |
func (hf *hasfields) Freeze() { |
| 263 |
if !hf.frozen { |
| 264 |
hf.frozen = true |
| 265 |
for _, v := range hf.attrs { |
| 266 |
v.Freeze() |
| 267 |
} |
| 268 |
} |
| 269 |
} |
| 270 |
|
| 271 |
func (hf *hasfields) Attr(name string) (starlark.Value, error) { return hf.attrs[name], nil } |
| 272 |
|
| 273 |
func (hf *hasfields) SetField(name string, val starlark.Value) error { |
| 274 |
if hf.frozen { |
| 275 |
return fmt.Errorf("cannot set field on a frozen hasfields") |
| 276 |
} |
| 277 |
if strings.HasPrefix(name, "no") { // for testing |
| 278 |
return starlark.NoSuchAttrError(fmt.Sprintf("no .%s field", name)) |
| 279 |
} |
| 280 |
hf.attrs[name] = val |
| 281 |
return nil |
| 282 |
} |
| 283 |
|
| 284 |
func (hf *hasfields) AttrNames() []string { |
| 285 |
names := make([]string, 0, len(hf.attrs)) |
| 286 |
for key := range hf.attrs { |
| 287 |
names = append(names, key) |
| 288 |
} |
| 289 |
sort.Strings(names) |
| 290 |
return names |
| 291 |
} |
| 292 |
|
| 293 |
func (hf *hasfields) Binary(op syntax.Token, y starlark.Value, side starlark.Side) (starlark.Value, error) { |
| 294 |
// This method exists so we can exercise 'list += x' |
| 295 |
// where x is not Iterable but defines list+x. |
| 296 |
if op == syntax.PLUS { |
| 297 |
if _, ok := y.(*starlark.List); ok { |
| 298 |
return starlark.MakeInt(42), nil // list+hasfields is 42 |
| 299 |
} |
| 300 |
} |
| 301 |
return nil, nil |
| 302 |
} |
| 303 |
|
| 304 |
func TestParameterPassing(t *testing.T) { |
| 305 |
const filename = "parameters.go" |
| 306 |
const src = ` |
| 307 |
def a(): |
| 308 |
return |
| 309 |
def b(a, b): |
| 310 |
return a, b |
| 311 |
def c(a, b=42): |
| 312 |
return a, b |
| 313 |
def d(*args): |
| 314 |
return args |
| 315 |
def e(**kwargs): |
| 316 |
return kwargs |
| 317 |
def f(a, b=42, *args, **kwargs): |
| 318 |
return a, b, args, kwargs |
| 319 |
def g(a, b=42, *args, c=123, **kwargs): |
| 320 |
return a, b, args, c, kwargs |
| 321 |
def h(a, b=42, *, c=123, **kwargs): |
| 322 |
return a, b, c, kwargs |
| 323 |
def i(a, b=42, *, c, d=123, e, **kwargs): |
| 324 |
return a, b, c, d, e, kwargs |
| 325 |
def j(a, b=42, *args, c, d=123, e, **kwargs): |
| 326 |
return a, b, args, c, d, e, kwargs |
| 327 |
` |
| 328 |
|
| 329 |
thread := new(starlark.Thread) |
| 330 |
globals, err := starlark.ExecFile(thread, filename, src, nil) |
| 331 |
if err != nil { |
| 332 |
t.Fatal(err) |
| 333 |
} |
| 334 |
|
| 335 |
// All errors are dynamic; see resolver for static errors. |
| 336 |
for _, test := range []struct{ src, want string }{ |
| 337 |
// a() |
| 338 |
{`a()`, `None`}, |
| 339 |
{`a(1)`, `function a accepts no arguments (1 given)`}, |
| 340 |
|
| 341 |
// b(a, b) |
| 342 |
{`b()`, `function b missing 2 arguments (a, b)`}, |
| 343 |
{`b(1)`, `function b missing 1 argument (b)`}, |
| 344 |
{`b(a=1)`, `function b missing 1 argument (b)`}, |
| 345 |
{`b(b=1)`, `function b missing 1 argument (a)`}, |
| 346 |
{`b(1, 2)`, `(1, 2)`}, |
| 347 |
{`b`, `<function b>`}, // asserts that b's parameter b was treated as a local variable |
| 348 |
{`b(1, 2, 3)`, `function b accepts 2 positional arguments (3 given)`}, |
| 349 |
{`b(1, b=2)`, `(1, 2)`}, |
| 350 |
{`b(1, a=2)`, `function b got multiple values for parameter "a"`}, |
| 351 |
{`b(1, x=2)`, `function b got an unexpected keyword argument "x"`}, |
| 352 |
{`b(a=1, b=2)`, `(1, 2)`}, |
| 353 |
{`b(b=1, a=2)`, `(2, 1)`}, |
| 354 |
{`b(b=1, a=2, x=1)`, `function b got an unexpected keyword argument "x"`}, |
| 355 |
{`b(x=1, b=1, a=2)`, `function b got an unexpected keyword argument "x"`}, |
| 356 |
|
| 357 |
// c(a, b=42) |
| 358 |
{`c()`, `function c missing 1 argument (a)`}, |
| 359 |
{`c(1)`, `(1, 42)`}, |
| 360 |
{`c(1, 2)`, `(1, 2)`}, |
| 361 |
{`c(1, 2, 3)`, `function c accepts at most 2 positional arguments (3 given)`}, |
| 362 |
{`c(1, b=2)`, `(1, 2)`}, |
| 363 |
{`c(1, a=2)`, `function c got multiple values for parameter "a"`}, |
| 364 |
{`c(a=1, b=2)`, `(1, 2)`}, |
| 365 |
{`c(b=1, a=2)`, `(2, 1)`}, |
| 366 |
|
| 367 |
// d(*args) |
| 368 |
{`d()`, `()`}, |
| 369 |
{`d(1)`, `(1,)`}, |
| 370 |
{`d(1, 2)`, `(1, 2)`}, |
| 371 |
{`d(1, 2, k=3)`, `function d got an unexpected keyword argument "k"`}, |
| 372 |
{`d(args=[])`, `function d got an unexpected keyword argument "args"`}, |
| 373 |
|
| 374 |
// e(**kwargs) |
| 375 |
{`e()`, `{}`}, |
| 376 |
{`e(1)`, `function e accepts 0 positional arguments (1 given)`}, |
| 377 |
{`e(k=1)`, `{"k": 1}`}, |
| 378 |
{`e(kwargs={})`, `{"kwargs": {}}`}, |
| 379 |
|
| 380 |
// f(a, b=42, *args, **kwargs) |
| 381 |
{`f()`, `function f missing 1 argument (a)`}, |
| 382 |
{`f(0)`, `(0, 42, (), {})`}, |
| 383 |
{`f(0)`, `(0, 42, (), {})`}, |
| 384 |
{`f(0, 1)`, `(0, 1, (), {})`}, |
| 385 |
{`f(0, 1, 2)`, `(0, 1, (2,), {})`}, |
| 386 |
{`f(0, 1, 2, 3)`, `(0, 1, (2, 3), {})`}, |
| 387 |
{`f(a=0)`, `(0, 42, (), {})`}, |
| 388 |
{`f(0, b=1)`, `(0, 1, (), {})`}, |
| 389 |
{`f(0, a=1)`, `function f got multiple values for parameter "a"`}, |
| 390 |
{`f(0, b=1, c=2)`, `(0, 1, (), {"c": 2})`}, |
| 391 |
|
| 392 |
// g(a, b=42, *args, c=123, **kwargs) |
| 393 |
{`g()`, `function g missing 1 argument (a)`}, |
| 394 |
{`g(0)`, `(0, 42, (), 123, {})`}, |
| 395 |
{`g(0, 1)`, `(0, 1, (), 123, {})`}, |
| 396 |
{`g(0, 1, 2)`, `(0, 1, (2,), 123, {})`}, |
| 397 |
{`g(0, 1, 2, 3)`, `(0, 1, (2, 3), 123, {})`}, |
| 398 |
{`g(a=0)`, `(0, 42, (), 123, {})`}, |
| 399 |
{`g(0, b=1)`, `(0, 1, (), 123, {})`}, |
| 400 |
{`g(0, a=1)`, `function g got multiple values for parameter "a"`}, |
| 401 |
{`g(0, b=1, c=2, d=3)`, `(0, 1, (), 2, {"d": 3})`}, |
| 402 |
|
| 403 |
// h(a, b=42, *, c=123, **kwargs) |
| 404 |
{`h()`, `function h missing 1 argument (a)`}, |
| 405 |
{`h(0)`, `(0, 42, 123, {})`}, |
| 406 |
{`h(0, 1)`, `(0, 1, 123, {})`}, |
| 407 |
{`h(0, 1, 2)`, `function h accepts at most 2 positional arguments (3 given)`}, |
| 408 |
{`h(a=0)`, `(0, 42, 123, {})`}, |
| 409 |
{`h(0, b=1)`, `(0, 1, 123, {})`}, |
| 410 |
{`h(0, a=1)`, `function h got multiple values for parameter "a"`}, |
| 411 |
{`h(0, b=1, c=2)`, `(0, 1, 2, {})`}, |
| 412 |
{`h(0, b=1, d=2)`, `(0, 1, 123, {"d": 2})`}, |
| 413 |
{`h(0, b=1, c=2, d=3)`, `(0, 1, 2, {"d": 3})`}, |
| 414 |
|
| 415 |
// i(a, b=42, *, c, d=123, e, **kwargs) |
| 416 |
{`i()`, `function i missing 3 arguments (a, c, e)`}, |
| 417 |
{`i(0)`, `function i missing 2 arguments (c, e)`}, |
| 418 |
{`i(0, 1)`, `function i missing 2 arguments (c, e)`}, |
| 419 |
{`i(0, 1, 2)`, `function i accepts at most 2 positional arguments (3 given)`}, |
| 420 |
{`i(0, 1, e=2)`, `function i missing 1 argument (c)`}, |
| 421 |
{`i(0, 1, 2, 3)`, `function i accepts at most 2 positional arguments (4 given)`}, |
| 422 |
{`i(a=0)`, `function i missing 2 arguments (c, e)`}, |
| 423 |
{`i(0, b=1)`, `function i missing 2 arguments (c, e)`}, |
| 424 |
{`i(0, a=1)`, `function i got multiple values for parameter "a"`}, |
| 425 |
{`i(0, b=1, c=2)`, `function i missing 1 argument (e)`}, |
| 426 |
{`i(0, b=1, d=2)`, `function i missing 2 arguments (c, e)`}, |
| 427 |
{`i(0, b=1, c=2, d=3)`, `function i missing 1 argument (e)`}, |
| 428 |
{`i(0, b=1, c=2, d=3, e=4)`, `(0, 1, 2, 3, 4, {})`}, |
| 429 |
{`i(0, 1, b=1, c=2, d=3, e=4)`, `function i got multiple values for parameter "b"`}, |
| 430 |
|
| 431 |
// j(a, b=42, *args, c, d=123, e, **kwargs) |
| 432 |
{`j()`, `function j missing 3 arguments (a, c, e)`}, |
| 433 |
{`j(0)`, `function j missing 2 arguments (c, e)`}, |
| 434 |
{`j(0, 1)`, `function j missing 2 arguments (c, e)`}, |
| 435 |
{`j(0, 1, 2)`, `function j missing 2 arguments (c, e)`}, |
| 436 |
{`j(0, 1, e=2)`, `function j missing 1 argument (c)`}, |
| 437 |
{`j(0, 1, 2, 3)`, `function j missing 2 arguments (c, e)`}, |
| 438 |
{`j(a=0)`, `function j missing 2 arguments (c, e)`}, |
| 439 |
{`j(0, b=1)`, `function j missing 2 arguments (c, e)`}, |
| 440 |
{`j(0, a=1)`, `function j got multiple values for parameter "a"`}, |
| 441 |
{`j(0, b=1, c=2)`, `function j missing 1 argument (e)`}, |
| 442 |
{`j(0, b=1, d=2)`, `function j missing 2 arguments (c, e)`}, |
| 443 |
{`j(0, b=1, c=2, d=3)`, `function j missing 1 argument (e)`}, |
| 444 |
{`j(0, b=1, c=2, d=3, e=4)`, `(0, 1, (), 2, 3, 4, {})`}, |
| 445 |
{`j(0, 1, b=1, c=2, d=3, e=4)`, `function j got multiple values for parameter "b"`}, |
| 446 |
{`j(0, 1, 2, c=3, e=4)`, `(0, 1, (2,), 3, 123, 4, {})`}, |
| 447 |
} { |
| 448 |
var got string |
| 449 |
if v, err := starlark.Eval(thread, "<expr>", test.src, globals); err != nil { |
| 450 |
got = err.Error() |
| 451 |
} else { |
| 452 |
got = v.String() |
| 453 |
} |
| 454 |
if got != test.want { |
| 455 |
t.Errorf("eval %s = %s, want %s", test.src, got, test.want) |
| 456 |
} |
| 457 |
} |
| 458 |
} |
| 459 |
|
| 460 |
// TestPrint ensures that the Starlark print function calls |
| 461 |
// Thread.Print, if provided. |
| 462 |
func TestPrint(t *testing.T) { |
| 463 |
const src = ` |
| 464 |
print("hello") |
| 465 |
def f(): print("hello", "world", sep=", ") |
| 466 |
f() |
| 467 |
` |
| 468 |
buf := new(bytes.Buffer) |
| 469 |
print := func(thread *starlark.Thread, msg string) { |
| 470 |
caller := thread.CallFrame(1) |
| 471 |
fmt.Fprintf(buf, "%s: %s: %s\n", caller.Pos, caller.Name, msg) |
| 472 |
} |
| 473 |
thread := &starlark.Thread{Print: print} |
| 474 |
if _, err := starlark.ExecFile(thread, "foo.star", src, nil); err != nil { |
| 475 |
t.Fatal(err) |
| 476 |
} |
| 477 |
want := "foo.star:2:6: <toplevel>: hello\n" + |
| 478 |
"foo.star:3:15: f: hello, world\n" |
| 479 |
if got := buf.String(); got != want { |
| 480 |
t.Errorf("output was %s, want %s", got, want) |
| 481 |
} |
| 482 |
} |
| 483 |
|
| 484 |
func reportEvalError(tb testing.TB, err error) { |
| 485 |
if err, ok := err.(*starlark.EvalError); ok { |
| 486 |
tb.Fatal(err.Backtrace()) |
| 487 |
} |
| 488 |
tb.Fatal(err) |
| 489 |
} |
| 490 |
|
| 491 |
// TestInt exercises the Int.Int64 and Int.Uint64 methods. |
| 492 |
// If we can move their logic into math/big, delete this test. |
| 493 |
func TestInt(t *testing.T) { |
| 494 |
one := starlark.MakeInt(1) |
| 495 |
|
| 496 |
for _, test := range []struct { |
| 497 |
i starlark.Int |
| 498 |
wantInt64 string |
| 499 |
wantUint64 string |
| 500 |
}{ |
| 501 |
{starlark.MakeInt64(math.MinInt64).Sub(one), "error", "error"}, |
| 502 |
{starlark.MakeInt64(math.MinInt64), "-9223372036854775808", "error"}, |
| 503 |
{starlark.MakeInt64(-1), "-1", "error"}, |
| 504 |
{starlark.MakeInt64(0), "0", "0"}, |
| 505 |
{starlark.MakeInt64(1), "1", "1"}, |
| 506 |
{starlark.MakeInt64(math.MaxInt64), "9223372036854775807", "9223372036854775807"}, |
| 507 |
{starlark.MakeUint64(math.MaxUint64), "error", "18446744073709551615"}, |
| 508 |
{starlark.MakeUint64(math.MaxUint64).Add(one), "error", "error"}, |
| 509 |
} { |
| 510 |
gotInt64, gotUint64 := "error", "error" |
| 511 |
if i, ok := test.i.Int64(); ok { |
| 512 |
gotInt64 = fmt.Sprint(i) |
| 513 |
} |
| 514 |
if u, ok := test.i.Uint64(); ok { |
| 515 |
gotUint64 = fmt.Sprint(u) |
| 516 |
} |
| 517 |
if gotInt64 != test.wantInt64 { |
| 518 |
t.Errorf("(%s).Int64() = %s, want %s", test.i, gotInt64, test.wantInt64) |
| 519 |
} |
| 520 |
if gotUint64 != test.wantUint64 { |
| 521 |
t.Errorf("(%s).Uint64() = %s, want %s", test.i, gotUint64, test.wantUint64) |
| 522 |
} |
| 523 |
} |
| 524 |
} |
| 525 |
|
| 526 |
func backtrace(t *testing.T, err error) string { |
| 527 |
switch err := err.(type) { |
| 528 |
case *starlark.EvalError: |
| 529 |
return err.Backtrace() |
| 530 |
case nil: |
| 531 |
t.Fatalf("ExecFile succeeded unexpectedly") |
| 532 |
default: |
| 533 |
t.Fatalf("ExecFile failed with %v, wanted *EvalError", err) |
| 534 |
} |
| 535 |
panic("unreachable") |
| 536 |
} |
| 537 |
|
| 538 |
func TestBacktrace(t *testing.T) { |
| 539 |
// This test ensures continuity of the stack of active Starlark |
| 540 |
// functions, including propagation through built-ins such as 'min'. |
| 541 |
const src = ` |
| 542 |
def f(x): return 1//x |
| 543 |
def g(x): return f(x) |
| 544 |
def h(): return min([1, 2, 0], key=g) |
| 545 |
def i(): return h() |
| 546 |
i() |
| 547 |
` |
| 548 |
thread := new(starlark.Thread) |
| 549 |
_, err := starlark.ExecFile(thread, "crash.star", src, nil) |
| 550 |
const want = `Traceback (most recent call last): |
| 551 |
crash.star:6:2: in <toplevel> |
| 552 |
crash.star:5:18: in i |
| 553 |
crash.star:4:20: in h |
| 554 |
<builtin>: in min |
| 555 |
crash.star:3:19: in g |
| 556 |
crash.star:2:19: in f |
| 557 |
Error: floored division by zero` |
| 558 |
if got := backtrace(t, err); got != want { |
| 559 |
t.Errorf("error was %s, want %s", got, want) |
| 560 |
} |
| 561 |
|
| 562 |
// Additionally, ensure that errors originating in |
| 563 |
// Starlark and/or Go each have an accurate frame. |
| 564 |
// The topmost frame, if built-in, is not shown, |
| 565 |
// but the name of the built-in function is shown |
| 566 |
// as "Error in fn: ...". |
| 567 |
// |
| 568 |
// This program fails in Starlark (f) if x==0, |
| 569 |
// or in Go (string.join) if x is non-zero. |
| 570 |
const src2 = ` |
| 571 |
def f(): ''.join([1//i]) |
| 572 |
f() |
| 573 |
` |
| 574 |
for i, want := range []string{ |
| 575 |
0: `Traceback (most recent call last): |
| 576 |
crash.star:3:2: in <toplevel> |
| 577 |
crash.star:2:20: in f |
| 578 |
Error: floored division by zero`, |
| 579 |
1: `Traceback (most recent call last): |
| 580 |
crash.star:3:2: in <toplevel> |
| 581 |
crash.star:2:17: in f |
| 582 |
Error in join: join: in list, want string, got int`, |
| 583 |
} { |
| 584 |
globals := starlark.StringDict{"i": starlark.MakeInt(i)} |
| 585 |
_, err := starlark.ExecFile(thread, "crash.star", src2, globals) |
| 586 |
if got := backtrace(t, err); got != want { |
| 587 |
t.Errorf("error was %s, want %s", got, want) |
| 588 |
} |
| 589 |
} |
| 590 |
} |
| 591 |
|
| 592 |
func TestLoadBacktrace(t *testing.T) { |
| 593 |
// This test ensures that load() does NOT preserve stack traces, |
| 594 |
// but that API callers can get them with Unwrap(). |
| 595 |
// For discussion, see: |
| 596 |
// https://github.com/google/starlark-go/pull/244 |
| 597 |
const src = ` |
| 598 |
load('crash.star', 'x') |
| 599 |
` |
| 600 |
const loadedSrc = ` |
| 601 |
def f(x): |
| 602 |
return 1 // x |
| 603 |
|
| 604 |
f(0) |
| 605 |
` |
| 606 |
thread := new(starlark.Thread) |
| 607 |
thread.Load = func(t *starlark.Thread, module string) (starlark.StringDict, error) { |
| 608 |
return starlark.ExecFile(new(starlark.Thread), module, loadedSrc, nil) |
| 609 |
} |
| 610 |
_, err := starlark.ExecFile(thread, "root.star", src, nil) |
| 611 |
|
| 612 |
const want = `Traceback (most recent call last): |
| 613 |
root.star:2:1: in <toplevel> |
| 614 |
Error: cannot load crash.star: floored division by zero` |
| 615 |
if got := backtrace(t, err); got != want { |
| 616 |
t.Errorf("error was %s, want %s", got, want) |
| 617 |
} |
| 618 |
|
| 619 |
unwrapEvalError := func(err error) *starlark.EvalError { |
| 620 |
var result *starlark.EvalError |
| 621 |
for { |
| 622 |
if evalErr, ok := err.(*starlark.EvalError); ok { |
| 623 |
result = evalErr |
| 624 |
} |
| 625 |
|
| 626 |
err = errors.Unwrap(err) |
| 627 |
if err == nil { |
| 628 |
break |
| 629 |
} |
| 630 |
} |
| 631 |
return result |
| 632 |
} |
| 633 |
|
| 634 |
unwrappedErr := unwrapEvalError(err) |
| 635 |
const wantUnwrapped = `Traceback (most recent call last): |
| 636 |
crash.star:5:2: in <toplevel> |
| 637 |
crash.star:3:12: in f |
| 638 |
Error: floored division by zero` |
| 639 |
if got := backtrace(t, unwrappedErr); got != wantUnwrapped { |
| 640 |
t.Errorf("error was %s, want %s", got, wantUnwrapped) |
| 641 |
} |
| 642 |
|
| 643 |
} |
| 644 |
|
| 645 |
// TestRepeatedExec parses and resolves a file syntax tree once then |
| 646 |
// executes it repeatedly with different values of its predeclared variables. |
| 647 |
func TestRepeatedExec(t *testing.T) { |
| 648 |
predeclared := starlark.StringDict{"x": starlark.None} |
| 649 |
_, prog, err := starlark.SourceProgram("repeat.star", "y = 2 * x", predeclared.Has) |
| 650 |
if err != nil { |
| 651 |
t.Fatal(err) |
| 652 |
} |
| 653 |
|
| 654 |
for _, test := range []struct { |
| 655 |
x, want starlark.Value |
| 656 |
}{ |
| 657 |
{x: starlark.MakeInt(42), want: starlark.MakeInt(84)}, |
| 658 |
{x: starlark.String("mur"), want: starlark.String("murmur")}, |
| 659 |
{x: starlark.Tuple{starlark.None}, want: starlark.Tuple{starlark.None, starlark.None}}, |
| 660 |
} { |
| 661 |
predeclared["x"] = test.x // update the values in dictionary |
| 662 |
thread := new(starlark.Thread) |
| 663 |
if globals, err := prog.Init(thread, predeclared); err != nil { |
| 664 |
t.Errorf("x=%v: %v", test.x, err) // exec error |
| 665 |
} else if eq, err := starlark.Equal(globals["y"], test.want); err != nil { |
| 666 |
t.Errorf("x=%v: %v", test.x, err) // comparison error |
| 667 |
} else if !eq { |
| 668 |
t.Errorf("x=%v: got y=%v, want %v", test.x, globals["y"], test.want) |
| 669 |
} |
| 670 |
} |
| 671 |
} |
| 672 |
|
| 673 |
// TestEmptyFilePosition ensures that even Programs |
| 674 |
// from empty files have a valid position. |
| 675 |
func TestEmptyPosition(t *testing.T) { |
| 676 |
var predeclared starlark.StringDict |
| 677 |
for _, content := range []string{"", "empty = False"} { |
| 678 |
_, prog, err := starlark.SourceProgram("hello.star", content, predeclared.Has) |
| 679 |
if err != nil { |
| 680 |
t.Fatal(err) |
| 681 |
} |
| 682 |
if got, want := prog.Filename(), "hello.star"; got != want { |
| 683 |
t.Errorf("Program.Filename() = %q, want %q", got, want) |
| 684 |
} |
| 685 |
} |
| 686 |
} |
| 687 |
|
| 688 |
// TestUnpackUserDefined tests that user-defined |
| 689 |
// implementations of starlark.Value may be unpacked. |
| 690 |
func TestUnpackUserDefined(t *testing.T) { |
| 691 |
// success |
| 692 |
want := new(hasfields) |
| 693 |
var x *hasfields |
| 694 |
if err := starlark.UnpackArgs("unpack", starlark.Tuple{want}, nil, "x", &x); err != nil { |
| 695 |
t.Errorf("UnpackArgs failed: %v", err) |
| 696 |
} |
| 697 |
if x != want { |
| 698 |
t.Errorf("for x, got %v, want %v", x, want) |
| 699 |
} |
| 700 |
|
| 701 |
// failure |
| 702 |
err := starlark.UnpackArgs("unpack", starlark.Tuple{starlark.MakeInt(42)}, nil, "x", &x) |
| 703 |
if want := "unpack: for parameter x: got int, want hasfields"; fmt.Sprint(err) != want { |
| 704 |
t.Errorf("unpack args error = %q, want %q", err, want) |
| 705 |
} |
| 706 |
} |
| 707 |
|
| 708 |
type optionalStringUnpacker struct { |
| 709 |
str string |
| 710 |
isSet bool |
| 711 |
} |
| 712 |
|
| 713 |
func (o *optionalStringUnpacker) Unpack(v starlark.Value) error { |
| 714 |
s, ok := starlark.AsString(v) |
| 715 |
if !ok { |
| 716 |
return fmt.Errorf("got %s, want string", v.Type()) |
| 717 |
} |
| 718 |
o.str = s |
| 719 |
o.isSet = ok |
| 720 |
return nil |
| 721 |
} |
| 722 |
|
| 723 |
func TestUnpackCustomUnpacker(t *testing.T) { |
| 724 |
a := optionalStringUnpacker{} |
| 725 |
wantA := optionalStringUnpacker{str: "a", isSet: true} |
| 726 |
b := optionalStringUnpacker{str: "b"} |
| 727 |
wantB := optionalStringUnpacker{str: "b"} |
| 728 |
|
| 729 |
// Success |
| 730 |
if err := starlark.UnpackArgs("unpack", starlark.Tuple{starlark.String("a")}, nil, "a?", &a, "b?", &b); err != nil { |
| 731 |
t.Errorf("UnpackArgs failed: %v", err) |
| 732 |
} |
| 733 |
if a != wantA { |
| 734 |
t.Errorf("for a, got %v, want %v", a, wantA) |
| 735 |
} |
| 736 |
if b != wantB { |
| 737 |
t.Errorf("for b, got %v, want %v", b, wantB) |
| 738 |
} |
| 739 |
|
| 740 |
// failure |
| 741 |
err := starlark.UnpackArgs("unpack", starlark.Tuple{starlark.MakeInt(42)}, nil, "a", &a) |
| 742 |
if want := "unpack: for parameter a: got int, want string"; fmt.Sprint(err) != want { |
| 743 |
t.Errorf("unpack args error = %q, want %q", err, want) |
| 744 |
} |
| 745 |
} |
| 746 |
|
| 747 |
func TestUnpackNoneCoalescing(t *testing.T) { |
| 748 |
a := optionalStringUnpacker{str: "a"} |
| 749 |
wantA := optionalStringUnpacker{str: "a", isSet: false} |
| 750 |
b := optionalStringUnpacker{str: "b"} |
| 751 |
wantB := optionalStringUnpacker{str: "b", isSet: false} |
| 752 |
|
| 753 |
// Success |
| 754 |
args := starlark.Tuple{starlark.None} |
| 755 |
kwargs := []starlark.Tuple{starlark.Tuple{starlark.String("b"), starlark.None}} |
| 756 |
if err := starlark.UnpackArgs("unpack", args, kwargs, "a??", &a, "b??", &a); err != nil { |
| 757 |
t.Errorf("UnpackArgs failed: %v", err) |
| 758 |
} |
| 759 |
if a != wantA { |
| 760 |
t.Errorf("for a, got %v, want %v", a, wantA) |
| 761 |
} |
| 762 |
if b != wantB { |
| 763 |
t.Errorf("for b, got %v, want %v", b, wantB) |
| 764 |
} |
| 765 |
|
| 766 |
// failure |
| 767 |
err := starlark.UnpackArgs("unpack", starlark.Tuple{starlark.MakeInt(42)}, nil, "a??", &a) |
| 768 |
if want := "unpack: for parameter a: got int, want string"; fmt.Sprint(err) != want { |
| 769 |
t.Errorf("unpack args error = %q, want %q", err, want) |
| 770 |
} |
| 771 |
|
| 772 |
err = starlark.UnpackArgs("unpack", nil, []starlark.Tuple{ |
| 773 |
starlark.Tuple{starlark.String("a"), starlark.None}, |
| 774 |
starlark.Tuple{starlark.String("a"), starlark.None}, |
| 775 |
}, "a??", &a) |
| 776 |
if want := "unpack: got multiple values for keyword argument \"a\""; fmt.Sprint(err) != want { |
| 777 |
t.Errorf("unpack args error = %q, want %q", err, want) |
| 778 |
} |
| 779 |
} |
| 780 |
|
| 781 |
func TestUnpackRequiredAfterOptional(t *testing.T) { |
| 782 |
// Assert 'c' is implicitly optional |
| 783 |
var a, b, c string |
| 784 |
args := starlark.Tuple{starlark.String("a")} |
| 785 |
if err := starlark.UnpackArgs("unpack", args, nil, "a", &a, "b?", &b, "c", &c); err != nil { |
| 786 |
t.Errorf("UnpackArgs failed: %v", err) |
| 787 |
} |
| 788 |
} |
| 789 |
|
| 790 |
func TestAsInt(t *testing.T) { |
| 791 |
for _, test := range []struct { |
| 792 |
val starlark.Value |
| 793 |
ptr any |
| 794 |
want string |
| 795 |
}{ |
| 796 |
{starlark.MakeInt(42), new(int32), "42"}, |
| 797 |
{starlark.MakeInt(-1), new(int32), "-1"}, |
| 798 |
// Use Lsh not 1<<40 as the latter exceeds int if GOARCH=386. |
| 799 |
{starlark.MakeInt(1).Lsh(40), new(int32), "1099511627776 out of range (want value in signed 32-bit range)"}, |
| 800 |
{starlark.MakeInt(-1).Lsh(40), new(int32), "-1099511627776 out of range (want value in signed 32-bit range)"}, |
| 801 |
|
| 802 |
{starlark.MakeInt(42), new(uint16), "42"}, |
| 803 |
{starlark.MakeInt(0xffff), new(uint16), "65535"}, |
| 804 |
{starlark.MakeInt(0x10000), new(uint16), "65536 out of range (want value in unsigned 16-bit range)"}, |
| 805 |
{starlark.MakeInt(-1), new(uint16), "-1 out of range (want value in unsigned 16-bit range)"}, |
| 806 |
} { |
| 807 |
var got string |
| 808 |
if err := starlark.AsInt(test.val, test.ptr); err != nil { |
| 809 |
got = err.Error() |
| 810 |
} else { |
| 811 |
got = fmt.Sprint(reflect.ValueOf(test.ptr).Elem().Interface()) |
| 812 |
} |
| 813 |
if got != test.want { |
| 814 |
t.Errorf("AsInt(%s, %T): got %q, want %q", test.val, test.ptr, got, test.want) |
| 815 |
} |
| 816 |
} |
| 817 |
} |
| 818 |
|
| 819 |
func TestDocstring(t *testing.T) { |
| 820 |
globals, _ := starlark.ExecFile(&starlark.Thread{}, "doc.star", ` |
| 821 |
def somefunc(): |
| 822 |
"somefunc doc" |
| 823 |
return 0 |
| 824 |
`, nil) |
| 825 |
|
| 826 |
if globals["somefunc"].(*starlark.Function).Doc() != "somefunc doc" { |
| 827 |
t.Fatal("docstring not found") |
| 828 |
} |
| 829 |
} |
| 830 |
|
| 831 |
func TestFunction_Globals(t *testing.T) { |
| 832 |
predeclared := starlark.StringDict{ |
| 833 |
"predecl": starlark.String("foo"), |
| 834 |
} |
| 835 |
globals, _ := starlark.ExecFile(&starlark.Thread{}, "func.star", ` |
| 836 |
def somefunc(): |
| 837 |
return predecl |
| 838 |
`, predeclared) |
| 839 |
|
| 840 |
fn := globals["somefunc"].(*starlark.Function) |
| 841 |
fnGlobals := fn.Globals() |
| 842 |
if !reflect.DeepEqual(fnGlobals, globals) { |
| 843 |
t.Errorf("somefunc.Globals(): got %q, want %q", fnGlobals, globals) |
| 844 |
} |
| 845 |
fnGlobals["shouldnt_appear"] = starlark.String("something_new") |
| 846 |
if globals.Has("shouldnt_appear") { |
| 847 |
t.Errorf("somefunc.Globals(): Globals() reflected onto ExecFile's returned globals") |
| 848 |
} |
| 849 |
} |
| 850 |
|
| 851 |
func TestFunction_Module(t *testing.T) { |
| 852 |
predeclared := starlark.StringDict{ |
| 853 |
"predecl": starlark.String("foo"), |
| 854 |
} |
| 855 |
globals, _ := starlark.ExecFile(&starlark.Thread{}, "func.star", ` |
| 856 |
def somefunc1(): |
| 857 |
return predecl |
| 858 |
|
| 859 |
def somefunc2(): |
| 860 |
return 42 |
| 861 |
`, predeclared) |
| 862 |
|
| 863 |
fn1 := globals["somefunc1"].(*starlark.Function) |
| 864 |
fn2 := globals["somefunc2"].(*starlark.Function) |
| 865 |
if fn1.Module() != fn2.Module() { |
| 866 |
t.Errorf("somefunc1 and somefunc2 have different modules: %p vs. %p", fn1.Module(), fn2.Module()) |
| 867 |
} |
| 868 |
|
| 869 |
module := fn1.Module() |
| 870 |
|
| 871 |
moduleGlobals := module.Globals() |
| 872 |
if !reflect.DeepEqual(moduleGlobals, globals) { |
| 873 |
t.Errorf("module.Globals(): got %q, want %q", moduleGlobals, globals) |
| 874 |
} |
| 875 |
moduleGlobals["shouldnt_appear"] = starlark.String("something_new") |
| 876 |
if globals.Has("shouldnt_appear") { |
| 877 |
t.Errorf("module.Globals(): Globals() reflected onto ExecFile's returned globals") |
| 878 |
} |
| 879 |
|
| 880 |
modulePredeclared := module.Predeclared() |
| 881 |
if reflect.ValueOf(modulePredeclared).UnsafePointer() != reflect.ValueOf(predeclared).UnsafePointer() { |
| 882 |
t.Errorf("module.Predeclared(): got %p=%q, want %p=%q", modulePredeclared, modulePredeclared, predeclared, predeclared) |
| 883 |
} |
| 884 |
} |
| 885 |
|
| 886 |
func TestFrameLocals(t *testing.T) { |
| 887 |
// trace prints a nice stack trace including argument |
| 888 |
// values of calls to Starlark functions. |
| 889 |
trace := func(thread *starlark.Thread) string { |
| 890 |
buf := new(bytes.Buffer) |
| 891 |
for i := 0; i < thread.CallStackDepth(); i++ { |
| 892 |
fr := thread.DebugFrame(i) |
| 893 |
fmt.Fprintf(buf, "%s(", fr.Callable().Name()) |
| 894 |
if fn, ok := fr.Callable().(*starlark.Function); ok { |
| 895 |
for i := 0; i < fn.NumParams(); i++ { |
| 896 |
if i > 0 { |
| 897 |
buf.WriteString(", ") |
| 898 |
} |
| 899 |
name, _ := fn.Param(i) |
| 900 |
_, v := fr.Local(i) |
| 901 |
fmt.Fprintf(buf, "%s=%s", name, v) |
| 902 |
} |
| 903 |
} else { |
| 904 |
buf.WriteString("...") // a built-in function |
| 905 |
} |
| 906 |
buf.WriteString(")\n") |
| 907 |
} |
| 908 |
return buf.String() |
| 909 |
} |
| 910 |
|
| 911 |
var got string |
| 912 |
builtin := func(thread *starlark.Thread, _ *starlark.Builtin, _ starlark.Tuple, _ []starlark.Tuple) (starlark.Value, error) { |
| 913 |
got = trace(thread) |
| 914 |
return starlark.None, nil |
| 915 |
} |
| 916 |
predeclared := starlark.StringDict{ |
| 917 |
"builtin": starlark.NewBuiltin("builtin", builtin), |
| 918 |
} |
| 919 |
_, err := starlark.ExecFile(&starlark.Thread{}, "foo.star", ` |
| 920 |
def f(x, y): builtin() |
| 921 |
def g(z): f(z, z*z) |
| 922 |
g(7) |
| 923 |
`, predeclared) |
| 924 |
if err != nil { |
| 925 |
t.Errorf("ExecFile failed: %v", err) |
| 926 |
} |
| 927 |
|
| 928 |
var want = ` |
| 929 |
builtin(...) |
| 930 |
f(x=7, y=49) |
| 931 |
g(z=7) |
| 932 |
<toplevel>() |
| 933 |
`[1:] |
| 934 |
if got != want { |
| 935 |
t.Errorf("got <<%s>>, want <<%s>>", got, want) |
| 936 |
} |
| 937 |
} |
| 938 |
|
| 939 |
type badType string |
| 940 |
|
| 941 |
func (b *badType) String() string { return "badType" } |
| 942 |
func (b *badType) Type() string { return "badType:" + string(*b) } // panics if b==nil |
| 943 |
func (b *badType) Truth() starlark.Bool { return true } |
| 944 |
func (b *badType) Hash() (uint32, error) { return 0, nil } |
| 945 |
func (b *badType) Freeze() {} |
| 946 |
|
| 947 |
var _ starlark.Value = new(badType) |
| 948 |
|
| 949 |
type badType2 string |
| 950 |
|
| 951 |
func (b badType2) String() string { return "badType2" } |
| 952 |
func (b badType2) Type() string { return "badType2" } |
| 953 |
func (b badType2) Truth() starlark.Bool { return true } |
| 954 |
func (b badType2) Hash() (uint32, error) { return 0, nil } |
| 955 |
func (b badType2) Freeze() {} |
| 956 |
|
| 957 |
var _ starlark.Value = new(badType) |
| 958 |
|
| 959 |
// TestUnpackErrorBadType verifies that the Unpack functions fail |
| 960 |
// gracefully when a parameter's default value's Type method panics. |
| 961 |
func TestUnpackErrorBadType(t *testing.T) { |
| 962 |
var v1 *badType |
| 963 |
var v2 badType2 |
| 964 |
for _, test := range []struct { |
| 965 |
ptr any |
| 966 |
want string |
| 967 |
}{ |
| 968 |
{&v1, "got NoneType, want *starlark_test.badType"}, // Go type name: (*badType)(nil).Type() panics |
| 969 |
{&v2, "got NoneType, want badType"}, // Starlark type name: badType2{}.Type() works |
| 970 |
} { |
| 971 |
err := starlark.UnpackArgs("f", starlark.Tuple{starlark.None}, nil, "x", test.ptr) |
| 972 |
if err == nil { |
| 973 |
t.Errorf("UnpackArgs succeeded unexpectedly") |
| 974 |
continue |
| 975 |
} |
| 976 |
if !strings.Contains(err.Error(), test.want) { |
| 977 |
t.Errorf("UnpackArgs error %q does not contain %q", err, test.want) |
| 978 |
} |
| 979 |
} |
| 980 |
} |
| 981 |
|
| 982 |
// Regression test for github.com/google/starlark-go/issues/233. |
| 983 |
func TestREPLChunk(t *testing.T) { |
| 984 |
thread := new(starlark.Thread) |
| 985 |
globals := make(starlark.StringDict) |
| 986 |
exec := func(src string) { |
| 987 |
f, err := syntax.Parse("<repl>", src, 0) |
| 988 |
if err != nil { |
| 989 |
t.Fatal(err) |
| 990 |
} |
| 991 |
if err := starlark.ExecREPLChunk(f, thread, globals); err != nil { |
| 992 |
t.Fatal(err) |
| 993 |
} |
| 994 |
} |
| 995 |
|
| 996 |
exec("x = 0; y = 0") |
| 997 |
if got, want := fmt.Sprintf("%v %v", globals["x"], globals["y"]), "0 0"; got != want { |
| 998 |
t.Fatalf("chunk1: got %s, want %s", got, want) |
| 999 |
} |
| 1000 |
|
| 1001 |
exec("x += 1; y = y + 1") |
| 1002 |
if got, want := fmt.Sprintf("%v %v", globals["x"], globals["y"]), "1 1"; got != want { |
| 1003 |
t.Fatalf("chunk2: got %s, want %s", got, want) |
| 1004 |
} |
| 1005 |
} |
| 1006 |
|
| 1007 |
func TestCancel(t *testing.T) { |
| 1008 |
// A thread cancelled before it begins executes no code. |
| 1009 |
{ |
| 1010 |
thread := new(starlark.Thread) |
| 1011 |
thread.Cancel("nope") |
| 1012 |
_, err := starlark.ExecFile(thread, "precancel.star", `x = 1//0`, nil) |
| 1013 |
if fmt.Sprint(err) != "Starlark computation cancelled: nope" { |
| 1014 |
t.Errorf("execution returned error %q, want cancellation", err) |
| 1015 |
} |
| 1016 |
|
| 1017 |
// cancellation is sticky |
| 1018 |
_, err = starlark.ExecFile(thread, "precancel.star", `x = 1//0`, nil) |
| 1019 |
if fmt.Sprint(err) != "Starlark computation cancelled: nope" { |
| 1020 |
t.Errorf("execution returned error %q, want cancellation", err) |
| 1021 |
} |
| 1022 |
} |
| 1023 |
// A thread cancelled during a built-in executes no more code. |
| 1024 |
{ |
| 1025 |
thread := new(starlark.Thread) |
| 1026 |
predeclared := starlark.StringDict{ |
| 1027 |
"stopit": starlark.NewBuiltin("stopit", func(thread *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { |
| 1028 |
thread.Cancel(fmt.Sprint(args[0])) |
| 1029 |
return starlark.None, nil |
| 1030 |
}), |
| 1031 |
} |
| 1032 |
_, err := starlark.ExecFile(thread, "stopit.star", `msg = 'nope'; stopit(msg); x = 1//0`, predeclared) |
| 1033 |
if fmt.Sprint(err) != `Starlark computation cancelled: "nope"` { |
| 1034 |
t.Errorf("execution returned error %q, want cancellation", err) |
| 1035 |
} |
| 1036 |
} |
| 1037 |
} |
| 1038 |
|
| 1039 |
func TestExecutionSteps(t *testing.T) { |
| 1040 |
// A Thread records the number of computation steps. |
| 1041 |
thread := new(starlark.Thread) |
| 1042 |
countSteps := func(n int) (uint64, error) { |
| 1043 |
predeclared := starlark.StringDict{"n": starlark.MakeInt(n)} |
| 1044 |
steps0 := thread.ExecutionSteps() |
| 1045 |
_, err := starlark.ExecFile(thread, "steps.star", `squares = [x*x for x in range(n)]`, predeclared) |
| 1046 |
return thread.ExecutionSteps() - steps0, err |
| 1047 |
} |
| 1048 |
steps100, err := countSteps(1000) |
| 1049 |
if err != nil { |
| 1050 |
t.Errorf("execution failed: %v", err) |
| 1051 |
} |
| 1052 |
steps10000, err := countSteps(100000) |
| 1053 |
if err != nil { |
| 1054 |
t.Errorf("execution failed: %v", err) |
| 1055 |
} |
| 1056 |
if ratio := float64(steps10000) / float64(steps100); ratio < 99 || ratio > 101 { |
| 1057 |
t.Errorf("computation steps did not increase linearly: f(100)=%d, f(10000)=%d, ratio=%g, want ~100", steps100, steps10000, ratio) |
| 1058 |
} |
| 1059 |
|
| 1060 |
// Exceeding the step limit causes cancellation. |
| 1061 |
thread.SetMaxExecutionSteps(1000) |
| 1062 |
_, err = countSteps(1000) |
| 1063 |
if fmt.Sprint(err) != "Starlark computation cancelled: too many steps" { |
| 1064 |
t.Errorf("execution returned error %q, want cancellation", err) |
| 1065 |
} |
| 1066 |
|
| 1067 |
thread.Steps = 0 |
| 1068 |
thread.Uncancel() |
| 1069 |
_, err = countSteps(1) |
| 1070 |
if err != nil { |
| 1071 |
t.Errorf("execution returned error %q, want nil", err) |
| 1072 |
} |
| 1073 |
} |
| 1074 |
|
| 1075 |
// TestDeps fails if the interpreter proper (not the REPL, etc) sprouts new external dependencies. |
| 1076 |
// We may expand the list of permitted dependencies, but should do so deliberately, not casually. |
| 1077 |
func TestDeps(t *testing.T) { |
| 1078 |
cmd := exec.Command("go", "list", "-deps") |
| 1079 |
out, err := cmd.Output() |
| 1080 |
if err != nil { |
| 1081 |
t.Skipf("'go list' failed: %s", err) |
| 1082 |
} |
| 1083 |
for pkg := range strings.SplitSeq(string(out), "\n") { |
| 1084 |
// Does pkg have form "domain.name/dir"? |
| 1085 |
slash := strings.IndexByte(pkg, '/') |
| 1086 |
dot := strings.IndexByte(pkg, '.') |
| 1087 |
if 0 < dot && dot < slash { |
| 1088 |
if strings.HasPrefix(pkg, "go.starlark.net/") || |
| 1089 |
strings.HasPrefix(pkg, "golang.org/x/sys/") { |
| 1090 |
continue // permitted dependencies |
| 1091 |
} |
| 1092 |
t.Errorf("new interpreter dependency: %s", pkg) |
| 1093 |
} |
| 1094 |
} |
| 1095 |
} |
| 1096 |
|
| 1097 |
// TestPanicSafety ensures that a panic from an application-defined |
| 1098 |
// built-in may traverse the interpreter safely; see issue #411. |
| 1099 |
func TestPanicSafety(t *testing.T) { |
| 1100 |
predeclared := starlark.StringDict{ |
| 1101 |
"panic": starlark.NewBuiltin("panic", func(thread *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { |
| 1102 |
panic(args[0]) |
| 1103 |
}), |
| 1104 |
"list": starlark.NewList([]starlark.Value{starlark.MakeInt(0)}), |
| 1105 |
} |
| 1106 |
|
| 1107 |
// This program is executed twice, using the same Thread, |
| 1108 |
// and panics both times, with values 1 and 2, while |
| 1109 |
// main is on the stack and a for-loop is active. |
| 1110 |
// |
| 1111 |
// It mutates list, a predeclared variable. |
| 1112 |
// This operation would fail if the previous |
| 1113 |
// for-loop failed to close its iterator during the panic. |
| 1114 |
// |
| 1115 |
// It also calls main a second time without recursion enabled. |
| 1116 |
// This operation would fail if the previous |
| 1117 |
// call failed to pop main from the stack during the panic. |
| 1118 |
const src = ` |
| 1119 |
list[0] += 1 |
| 1120 |
|
| 1121 |
def main(): |
| 1122 |
for x in list: |
| 1123 |
panic(x) |
| 1124 |
|
| 1125 |
main() |
| 1126 |
` |
| 1127 |
thread := new(starlark.Thread) |
| 1128 |
for _, i := range []int{1, 2} { |
| 1129 |
// Use a func to limit the scope of recover. |
| 1130 |
func() { |
| 1131 |
defer func() { |
| 1132 |
if got := fmt.Sprint(recover()); got != fmt.Sprint(i) { |
| 1133 |
t.Fatalf("recover: got %v, want %v", got, i) |
| 1134 |
} |
| 1135 |
}() |
| 1136 |
v, err := starlark.ExecFile(thread, "panic.star", src, predeclared) |
| 1137 |
if err != nil { |
| 1138 |
t.Fatalf("ExecFile returned error %q, expected panic", err) |
| 1139 |
} else { |
| 1140 |
t.Fatalf("ExecFile returned %v, expected panic", v) |
| 1141 |
} |
| 1142 |
}() |
| 1143 |
} |
| 1144 |
} |
| 1145 |
|
| 1146 |
func TestDebugFrame(t *testing.T) { |
| 1147 |
predeclared := starlark.StringDict{ |
| 1148 |
"env": starlark.NewBuiltin("env", func(thread *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { |
| 1149 |
if thread.CallStackDepth() < 2 { |
| 1150 |
return nil, fmt.Errorf("env must not be called directly") |
| 1151 |
} |
| 1152 |
fr := thread.DebugFrame(1) // parent |
| 1153 |
fn, ok := fr.Callable().(*starlark.Function) |
| 1154 |
if !ok { |
| 1155 |
return nil, fmt.Errorf("env must be called from a Starlark function") |
| 1156 |
} |
| 1157 |
dict := starlark.NewDict(0) |
| 1158 |
for i := 0; i < fr.NumLocals(); i++ { |
| 1159 |
bind, val := fr.Local(i) |
| 1160 |
if val == nil { |
| 1161 |
continue |
| 1162 |
} |
| 1163 |
dict.SetKey(starlark.String(bind.Name), val) // ignore error |
| 1164 |
} |
| 1165 |
for i := 0; i < fn.NumFreeVars(); i++ { |
| 1166 |
bind, val := fn.FreeVar(i) |
| 1167 |
dict.SetKey(starlark.String(bind.Name), val) // ignore error |
| 1168 |
} |
| 1169 |
dict.Freeze() |
| 1170 |
return dict, nil |
| 1171 |
}), |
| 1172 |
} |
| 1173 |
const src = ` |
| 1174 |
e = [None] |
| 1175 |
|
| 1176 |
def f(p): |
| 1177 |
outer = 3 |
| 1178 |
def g(q): |
| 1179 |
inner = outer + 1 |
| 1180 |
e[0] = env() # {"q": 2, "inner": 4, "outer": 3} |
| 1181 |
inner2 = None # not defined at call to env() |
| 1182 |
g(2) |
| 1183 |
|
| 1184 |
f(1) |
| 1185 |
` |
| 1186 |
thread := new(starlark.Thread) |
| 1187 |
m, err := starlark.ExecFile(thread, "env.star", src, predeclared) |
| 1188 |
if err != nil { |
| 1189 |
t.Fatalf("ExecFile returned error %q, expected panic", err) |
| 1190 |
} |
| 1191 |
got := m["e"].(*starlark.List).Index(0).String() |
| 1192 |
want := `{"q": 2, "inner": 4, "outer": 3}` |
| 1193 |
if got != want { |
| 1194 |
t.Errorf("env() returned %s, want %s", got, want) |
| 1195 |
} |
| 1196 |
} |
| 1197 |
|
| 1198 |
func TestUnpackArgsOptionalInference(t *testing.T) { |
| 1199 |
// success |
| 1200 |
kwargs := []starlark.Tuple{ |
| 1201 |
{starlark.String("x"), starlark.MakeInt(1)}, |
| 1202 |
{starlark.String("y"), starlark.MakeInt(2)}, |
| 1203 |
} |
| 1204 |
var x, y, z int |
| 1205 |
if err := starlark.UnpackArgs("unpack", nil, kwargs, |
| 1206 |
"x", &x, "y?", &y, "z", &z); err != nil { |
| 1207 |
t.Errorf("UnpackArgs failed: %v", err) |
| 1208 |
} |
| 1209 |
got := fmt.Sprintf("x=%d y=%d z=%d", x, y, z) |
| 1210 |
want := "x=1 y=2 z=0" |
| 1211 |
if got != want { |
| 1212 |
t.Errorf("got %s, want %s", got, want) |
| 1213 |
} |
| 1214 |
|
| 1215 |
// success |
| 1216 |
args := starlark.Tuple{starlark.MakeInt(1), starlark.MakeInt(2)} |
| 1217 |
x = 0 |
| 1218 |
y = 0 |
| 1219 |
z = 0 |
| 1220 |
if err := starlark.UnpackArgs("unpack", args, nil, |
| 1221 |
"x", &x, "y?", &y, "z", &z); err != nil { |
| 1222 |
t.Errorf("UnpackArgs failed: %v", err) |
| 1223 |
} |
| 1224 |
got = fmt.Sprintf("x=%d y=%d z=%d", x, y, z) |
| 1225 |
want = "x=1 y=2 z=0" |
| 1226 |
if got != want { |
| 1227 |
t.Errorf("got %s, want %s", got, want) |
| 1228 |
} |
| 1229 |
} |
| 1230 |
|
| 1231 |
func TestUnpackArgNoEscape(t *testing.T) { |
| 1232 |
var s starlark.String |
| 1233 |
|
| 1234 |
// The internal Unpack*NoEscape variants |
| 1235 |
// must not allocate in the common case (success). |
| 1236 |
n := testing.AllocsPerRun(100, func() { |
| 1237 |
var x string // must not escape |
| 1238 |
|
| 1239 |
if err := starlark.UnpackArgNoEscape(s, &s); err != nil { |
| 1240 |
t.Fatal(err) |
| 1241 |
} |
| 1242 |
if err := starlark.UnpackPositionalArgsNoEscape("fn", starlark.Tuple{s}, nil, 1, &x); err != nil { |
| 1243 |
t.Fatal(err) |
| 1244 |
} |
| 1245 |
}) |
| 1246 |
if n > 0 { |
| 1247 |
t.Errorf("AllocsPerRun = %v, want none", n) |
| 1248 |
} |
| 1249 |
} |