tests

package
v0.3.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 26, 2026 License: MIT Imports: 30 Imported by: 0

Documentation

Overview

Example (RouteSharedMemory)
root, err := fs.Sub(fixturesFS, "fixtures/routing")
if err != nil {
	fmt.Println(err)
	return
}

shm := core.NewSharedMemory()
mux := http.NewServeMux()
err = annotations.NewRoute(root, annotations.WithRuntimeFunc(func(rt *runner.Runtime) {
	rt.SetContext(core.SharedMemoryContext(rt.Context(), shm))
	rt.RegisterConstructor("SharedMemory", core.NewSharedMemoryBinding)
})).RegisterMux(mux)
if err != nil {
	fmt.Println(err)
	return
}

post := httptest.NewRequest(http.MethodPost, "/kv/color", strings.NewReader("value=blue"))
post.Header.Set("Content-Type", "application/x-www-form-urlencoded")
postRR := httptest.NewRecorder()
mux.ServeHTTP(postRR, post)
fmt.Println(postRR.Body.String())

getRR := httptest.NewRecorder()
mux.ServeHTTP(getRR, httptest.NewRequest(http.MethodGet, "/kv/color", nil))
fmt.Println(getRR.Body.String())

statsRR := httptest.NewRecorder()
mux.ServeHTTP(statsRR, httptest.NewRequest(http.MethodGet, "/stats/requests", nil))
fmt.Println(statsRR.Body.String())
Output:
ok
blue
2

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrRunnerUnavailable = errors.New("runner unavailable")

ErrRunnerUnavailable reports that a runner cannot execute on this machine, which is a skip rather than a failure. The php runner returns it when no php binary is installed.

Runners lists every backend the test matrix covers, in report order.

Functions

func BindingFunc added in v0.2.5

func BindingFunc(name string) any

BindingFunc returns the raw (unregistered, unadapted) Go function behind a binding name, so benchmarks can measure the reflection return path on its own.

func BindingFuncs added in v0.2.5

func BindingFuncs() map[string]any

BindingFuncs returns the example bindings keyed by the PHP name they are registered under.

func RegisterBindings added in v0.2.5

func RegisterBindings(rt *runner.Runtime)

RegisterBindings installs the example bindings. It is passed to stdlib.Register as an extra installer, the same way a host contributes its own symbols.

func ResetCaches added in v0.2.1

func ResetCaches()

ResetCaches clears all global shared caches between test suites.

func TestMain added in v0.2.0

func TestMain(m *testing.M)

func WriteHTMLReport added in v0.2.1

func WriteHTMLReport(w io.Writer, results []*TestResult) error

WriteHTMLReport outputs an HTML report of the test results.

func WriteJSONReport added in v0.2.1

func WriteJSONReport(w io.Writer, results []*TestResult) error

WriteJSONReport outputs a JSON report of the test results.

Types

type BindingRecord added in v0.2.5

type BindingRecord struct {
	ID   int64
	Name string
}

BindingRecord is a plain Go struct handed to PHP as an object. Property access goes through runner.helperGet, which reads exported fields by reflection (case-insensitively), so `$r->name` and `$r->Name` both resolve.

func (BindingRecord) Label added in v0.2.5

func (r BindingRecord) Label() string

Label is an exported method so tests can exercise `$r->label()` dispatch on a forwarded Go value.

type Fixture added in v0.2.1

type Fixture struct {
	Name        string          `yaml:"name"`
	Description string          `yaml:"description"`
	Error       string          `yaml:"error"`   // optional: expected uncaught error substring
	Stdin       string          `yaml:"stdin"`   // optional: top-level stdin contents
	Options     runner.Options  `yaml:"options"` // optional: runtime options for both engines (memory_limit, ...)
	Root        string          `yaml:"root"`    // optional: include root, relative to the fixture's own directory
	Runner      FixtureRunners  `yaml:"runner"`  // optional: runners the fixture opts out of
	Request     FixtureRequest  `yaml:"request"`
	Response    FixtureResponse `yaml:"response"`

	PHP      string `yaml:"-"`
	Expected string `yaml:"-"`
	Path     string `yaml:"-"`
	// contains filtered or unexported fields
}

Fixture is the parsed representation of a .phpt test file.

func FindFixtures added in v0.2.1

func FindFixtures(paths []string) ([]*Fixture, error)

FindFixtures locates all .phpt files in the specified paths (files or directories).

func ParseFixture added in v0.2.1

func ParseFixture(data []byte, path ...string) (*Fixture, error)

ParseFixture splits a .phpt file into its three sections and parses the YAML metadata.

func (*Fixture) RootDir added in v0.3.3

func (f *Fixture) RootDir() string

RootDir returns the directory a fixture's includes resolve against. That is the directory holding it, which is also where the php runner executes, unless the fixture named another one with `root:`.

func (*Fixture) Runs added in v0.3.0

func (f *Fixture) Runs(r Runner) bool

Runs reports whether the fixture is checked against r.

func (*Fixture) SetRootFS added in v0.3.3

func (f *Fixture) SetRootFS(root fs.FS)

SetRootFS binds the filesystem a fixture's includes resolve against. The directory holding the .phpt is the right answer for every caller: it is what the php runner uses as its working directory, so all three runners resolve a relative include to the same file.

type FixtureRequest added in v0.2.1

type FixtureRequest struct {
	Args    any               `yaml:"args"` // map[string]string or []string or scalar
	Get     map[string]string `yaml:"get"`
	Post    map[string]string `yaml:"post"`
	Cookie  map[string]string `yaml:"cookie"`
	Env     map[string]string `yaml:"env"`
	Headers map[string]string `yaml:"headers"`
	Stdin   string            `yaml:"stdin"`
	Body    string            `yaml:"body"`
}

FixtureRequest contains request data exposed to PHP as superglobals.

type FixtureResponse added in v0.2.1

type FixtureResponse struct {
	Headers map[string]string `yaml:"headers"`
}

FixtureResponse contains expected response assertions.

type FixtureRunners added in v0.3.0

type FixtureRunners struct {
	Flatstack *bool `yaml:"flatstack"`
	PHP       *bool `yaml:"php"`
}

FixtureRunners opts a fixture out of individual runners. An absent field means the runner is used; the default runtime can not be opted out of because it defines the fixture's expected output.

type Record

type Record struct {
	Key   string
	Value string
}

Record is a rich value type returned to PHP. Its exported fields are read from PHP via property access (`$rec->key`, `$rec->value`), matched case-insensitively.

type Runner added in v0.3.0

type Runner string

Runner names an execution backend a fixture can be checked against.

const (
	// RunnerFlatstack executes the fixture through the flat bytecode runtime,
	// which falls back to the compatibility interpreter for unsupported syntax.
	RunnerFlatstack Runner = "flatstack"

	// RunnerRuntime executes the fixture through the default interpreter.
	RunnerRuntime Runner = "runtime"

	// RunnerPHP executes the fixture through the php binary found in PATH.
	RunnerPHP Runner = "php"
)

type Storage

type Storage interface {
	Set(ctx context.Context, key, value string)
	Get(ctx context.Context, key string) (Record, error)
	All(ctx context.Context) ([]Record, error)
	Len() int64
	Tenant() string
}

Storage is a host-provided key/value capability whose context parameters are supplied automatically when PHP invokes its methods.

Example
ctx := context.WithValue(context.Background(), tenantKey, "acme")
storage, err := NewStorage(ctx)
if err != nil {
	fmt.Println(err)
	return
}

storage.Set(ctx, "color", "blue")
record, err := storage.Get(ctx, "color")
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(storage.Tenant())
fmt.Println(record.Key, record.Value)
fmt.Println(storage.Len())
Output:
acme
color blue
1

func NewFailStorage

func NewFailStorage(ctx context.Context) (Storage, error)

NewFailStorage is a constructor that always fails, used to exercise the thrown-error path of `new`.

func NewStorage

func NewStorage(ctx context.Context) (Storage, error)

NewStorage is the constructor registered for `new Storage`. Its first parameter is a context.Context, filled in automatically by the runner, so PHP calls `new Storage` with no arguments.

type TestResult added in v0.2.1

type TestResult struct {
	Name          string `json:"name"`
	Description   string `json:"description"`
	Path          string `json:"path"`
	Passed        bool   `json:"passed"`
	DurationMs    int64  `json:"duration_ms"`
	FailureReason string `json:"failure_reason,omitempty"`
	GotOutput     string `json:"got_output,omitempty"`
	WantOutput    string `json:"want_output,omitempty"`
	Error         string `json:"error,omitempty"`
	Runner        Runner `json:"runner,omitempty"`
	Skipped       bool   `json:"skipped,omitempty"`
}

TestResult carries execution outcome for a single fixture.

func RunFixture added in v0.2.1

func RunFixture(ctx context.Context, f *Fixture) *TestResult

RunFixture executes a single fixture against the default runtime.

func RunFixtureOn added in v0.3.0

func RunFixtureOn(ctx context.Context, f *Fixture, r Runner) *TestResult

RunFixtureOn executes a single fixture against one runner. Every runner is held to the same expected output; the runner only decides how the source is executed.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL