fakefy

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package fakefy makes fake values that look like real data: from a JSON Schema, and from the name of the field the schema describes. A value it returns validates against the schema it was made from, as JSON, unless the schema uses a keyword fakefy doesn't read: not, if, then, else, contains, propertyNames, dependentRequired, dependentSchemas, unevaluatedItems and unevaluatedProperties, and patternProperties but for the required properties they name. A oneOf whose branches overlap may also make a value two of them match, which a schema fakefy checks its values against refuses, so it fails with ErrUnsatisfiable instead.

A Faker given a seed makes the same values in the same order, so tools that write fake data to files, such as mock generators, write the same bytes on every run.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrUnsatisfiable is wrapped by the error of a schema no value satisfies, such as one whose minimum is above its
	// maximum, a false schema, or one whose required properties nest without end.
	ErrUnsatisfiable = errors.New("fakefy: no value satisfies the schema")

	// ErrUnresolved is wrapped by the error of a $ref that names no schema of the document.
	ErrUnresolved = errors.New("fakefy: unresolved $ref")

	// ErrInvalid is wrapped by the error of a schema that isn't one, such as a number where a schema goes, or a
	// pattern that doesn't compile.
	ErrInvalid = errors.New("fakefy: invalid schema")
)

Functions

This section is empty.

Types

type Defs

type Defs struct {
	// contains filtered or unexported fields
}

Defs holds schemas that the schemas of many values name under $defs, such as the shared schemas of an OpenAPI document, for every Faker given WithDefs to share. A Faker checks each value against its schema, which it compiles: with Defs, the schemas of Defs compile once, not once for each value whose schema reaches them, which keeps a large document whose schemas reach one another from taking minutes. Defs is safe for concurrent use. It keeps schemas, and the caller must not change them while it uses Defs. It keeps what it compiles for each value too, so one Defs serves the values of one document, not a long-lived process.

func NewDefs

func NewDefs(schemas map[string]any) *Defs

NewDefs creates a Defs of schemas, by name, and compiles them.

type Faker

type Faker struct {
	// contains filtered or unexported fields
}

Faker makes fake values. A Faker is not safe for concurrent use.

func New

func New(opts ...Option) *Faker

New creates a Faker.

func (*Faker) Field

func (f *Faker) Field(name string, schema map[string]any) (any, error)

Field returns a value for schema, as Faker.Schema does, for a field called name, such as a property, a query parameter or a header: the name picks among the values the schema allows, so an email field gets an email address.

func (*Faker) Schema

func (f *Faker) Schema(schema map[string]any) (any, error)

Schema returns a value for schema, a JSON Schema as decoded JSON or YAML: objects are map[string]any, and numbers any Go number or a json.Number. The value is decoded JSON too: map[string]any, []any, string, int64 for an integer, float64, bool or nil, or a number of the schema as the schema has it, when neither an int64 nor a float64 holds it exactly. It shares nothing with schema, so the caller may change it.

A value comes from the first of const, examples, example, default and enum the schema has; then from its format, such as email or date-time; then from the name of its field, such as createdAt or price; then from its type and bounds. A $ref resolves within schema, or to a schema of the Defs of WithDefs, allOf merges its schemas, and oneOf and anyOf take one of their branches, setting an OpenAPI discriminator's property to name it, unless the branch fixes its value. Of a list of types, the first a value satisfies wins, null last, or first from four levels down, so a nullable schema that nests itself ends. An optional property or item no value satisfies is left out.

A schema that compiles as JSON Schema 2020-12, or as draft 4, as OpenAPI 3.0 writes one, checks each value, formats too: one that doesn't validate, such as an example the rest of the schema breaks, is made again, from the schema's examples, then without them, up to 20 times. A schema whose examples leave no value, such as unique items an example repeats, is made without them.

The error wraps ErrUnsatisfiable, ErrUnresolved or ErrInvalid, naming the place in the value it stopped at.

Example
package main

import (
	"encoding/json/v2"
	"fmt"

	"github.com/caffeine-projects/vlatte/fakefy"
)

func main() {
	schema := map[string]any{
		"type":     "object",
		"required": []any{"id", "name", "email"},
		"properties": map[string]any{
			"id":        map[string]any{"type": "string", "format": "uuid"},
			"name":      map[string]any{"type": "string"},
			"email":     map[string]any{"type": "string"},
			"age":       map[string]any{"type": "integer", "minimum": 18},
			"createdAt": map[string]any{"type": "string"},
			"status":    map[string]any{"enum": []any{"ACTIVE", "BLOCKED"}},
		},
	}

	v, err := fakefy.New(fakefy.WithSeed(42)).Schema(schema)
	if err != nil {
		fmt.Println(err)
		return
	}

	b, _ := json.Marshal(v, json.Deterministic(true))
	fmt.Println(string(b))
}
Output:
{"age":48,"createdAt":"2023-05-16T04:47:06Z","email":"alan.baker@example.com","id":"15a4b87c-c8a8-438b-a879-b539a822e70c","name":"Daniel","status":"ACTIVE"}

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option configures a Faker.

func WithDefs

func WithDefs(d *Defs) Option

WithDefs has a $ref to #/$defs/name resolve, past the schema's own $defs, to the schema d holds by that name, as though the schema's $defs held it: the values are those of the schema with the schemas it reaches added to its $defs.

func WithSeed

func WithSeed(seed uint64) Option

WithSeed makes the Faker's values depend on seed alone: two Fakers with one seed make the same values in the same order. Without it, each Faker makes values of its own.

Jump to

Keyboard shortcuts

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