|
| 1 | +// Copyright 2026 The go-python 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 py_test |
| 6 | + |
| 7 | +import ( |
| 8 | + "os" |
| 9 | + "path/filepath" |
| 10 | + "testing" |
| 11 | + |
| 12 | + "github.com/go-python/gpython/py" |
| 13 | + _ "github.com/go-python/gpython/stdlib" |
| 14 | +) |
| 15 | + |
| 16 | +func TestRunWithNilModulePointer(t *testing.T) { |
| 17 | + for _, entry := range []string{"RunCode", "RunSrc", "RunFile"} { |
| 18 | + t.Run(entry, func(t *testing.T) { |
| 19 | + ctx := py.NewContext(py.DefaultContextOpts()) |
| 20 | + defer ctx.Close() |
| 21 | + src := "value = 42\n" |
| 22 | + var module *py.Module |
| 23 | + var err error |
| 24 | + switch entry { |
| 25 | + case "RunCode": |
| 26 | + var code *py.Code |
| 27 | + code, err = py.Compile(src, "<test>", py.ExecMode, 0, true) |
| 28 | + if err == nil { |
| 29 | + module, err = py.RunCode(ctx, code, "<test>", module) |
| 30 | + } |
| 31 | + case "RunSrc": |
| 32 | + module, err = py.RunSrc(ctx, src, "<test>", module) |
| 33 | + case "RunFile": |
| 34 | + path := filepath.Join(t.TempDir(), "test.py") |
| 35 | + if err = os.WriteFile(path, []byte(src), 0600); err == nil { |
| 36 | + module, err = py.RunFile(ctx, filepath.Base(path), py.CompileOpts{CurDir: filepath.Dir(path)}, module) |
| 37 | + } |
| 38 | + } |
| 39 | + if err != nil { |
| 40 | + t.Fatal(err) |
| 41 | + } |
| 42 | + if module == nil || module.Globals["value"] != py.Int(42) { |
| 43 | + t.Fatalf("expected a new module containing value = 42, got %v", module) |
| 44 | + } |
| 45 | + reused, err := py.RunSrc(ctx, "value += 1", "<reuse>", module) |
| 46 | + if err != nil { |
| 47 | + t.Fatal(err) |
| 48 | + } |
| 49 | + if reused != module || module.Globals["value"] != py.Int(43) { |
| 50 | + t.Fatal("expected the existing module and globals to be reused") |
| 51 | + } |
| 52 | + }) |
| 53 | + } |
| 54 | +} |
0 commit comments