generators

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Apr 14, 2024 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package generators used to create bson encoded random data.

Relevant documentation:

http://bsonspec.org/#/specification

It was created as part of mgodatagen, but may be used on its own.

Example
package main

import (
	"fmt"
	"log"

	"github.com/feliixx/mgodatagen/datagen/generators"
	"go.mongodb.org/mongo-driver/bson"
)

func main() {

	var content = map[string]generators.Config{
		"key": {
			Type:      generators.TypeString,
			MinLength: "3",
			MaxLength: "5",
		},
	}
	collInfo := generators.NewCollInfo(1, nil, 1, nil, nil)
	docGenerator, err := collInfo.NewDocumentGenerator(content)
	if err != nil {
		log.Fatal(err)
	}

	var doc struct {
		Key string `bson:"key"`
	}
	err = bson.Unmarshal(docGenerator.Generate(), &doc)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%+v", doc)
}
Output:

{Key:1jUK}

Index

Examples

Constants

View Source
const (
	TypeString          = "string"
	TypeInt             = "int"
	TypeLong            = "long"
	TypeDouble          = "double"
	TypeDecimal         = "decimal"
	TypeBoolean         = "boolean"
	TypeObjectID        = "objectId"
	TypeArray           = "array"
	TypeCoordinates     = "coordinates"
	TypeObject          = "object"
	TypeEnum            = "enum"
	TypeConstant        = "constant"
	TypeReference       = "reference"
	TypeAutoincrement   = "autoincrement"
	TypeBinary          = "binary"
	TypeDate            = "date"
	TypeUUID            = "uuid"
	TypeFaker           = "faker"
	TypeStringFromParts = "stringFromParts"

	// deprecated. Use 'TypeCoordinates' instead
	TypePosition = "position"
	// deprecated. Use 'TypeEnum' instead
	TypeFromArray = "fromArray"
	// deprecated. Use 'TypeReference' instead
	TypeRef = "ref"
)

available generator types, see https://github.com/feliixx/mgodatagen/blob/master/README.md#generator-types for details

View Source
const (
	TypeCountAggregator = "countAggregator"
	TypeValueAggregator = "valueAggregator"
	TypeBoundAggregator = "boundAggregator"
)

available aggregator types

View Source
const (
	MethodAnimal                  = "Animal"
	MethodAnimalType              = "AnimalType"
	MethodBS                      = "BS"
	MethodBeerAlcohol             = "BeerAlcohol"
	MethodBeerBlg                 = "BeerBlg"
	MethodBeerHop                 = "BeerHop"
	MethodBeerIbu                 = "BeerIbu"
	MethodBeerMalt                = "BeerMalt"
	MethodBeerName                = "BeerName"
	MethodBeerStyle               = "BeerStyle"
	MethodBeerYeast               = "BeerYeast"
	MethodBuzzWord                = "BuzzWord"
	MethodCarMaker                = "CarMaker"
	MethodCarModel                = "CarModel"
	MethodCat                     = "Cat"
	MethodChromeUserAgent         = "ChromeUserAgent"
	MethodCity                    = "City"
	MethodColor                   = "Color"
	MethodCompany                 = "Company"
	MethodCompanySuffix           = "CompanySuffix"
	MethodCountry                 = "Country"
	MethodCountryAbr              = "CountryAbr"
	MethodCreditCardCvv           = "CreditCardCvv"
	MethodCreditCardExp           = "CreditCardExp"
	MethodCreditCardType          = "CreditCardType"
	MethodCurrencyLong            = "CurrencyLong"
	MethodCurrencyShort           = "CurrencyShort"
	MethodDog                     = "Dog"
	MethodDomainName              = "DomainName"
	MethodDomainSuffix            = "DomainSuffix"
	MethodEmail                   = "Email"
	MethodEmoji                   = "Emoji"
	MethodEmojiAlias              = "EmojiAlias"
	MethodEmojiCategory           = "EmojiCategory"
	MethodEmojiDescription        = "EmojiDescription"
	MethodEmojiTag                = "EmojiTag"
	MethodFileExtension           = "FileExtension"
	MethodFarmAnimal              = "FarmAnimal"
	MethodFirefoxUserAgent        = "FirefoxUserAgent"
	MethodFirstName               = "FirstName"
	MethodCarFuelType             = "CarFuelType"
	MethodGender                  = "Gender"
	MethodHTTPMethod              = "HTTPMethod"
	MethodHackerAbbreviation      = "HackerAbbreviation"
	MethodHackerAdjective         = "HackerAdjective"
	MethodHackeringVerb           = "HackeringVerb"
	MethodHackerNoun              = "HackerNoun"
	MethodHackerPhrase            = "HackerPhrase"
	MethodHackerVerb              = "HackerVerb"
	MethodHexColor                = "HexColor"
	MethodHipsterWord             = "HipsterWord"
	MethodIPv4Address             = "IPv4Address"
	MethodIPv6Address             = "IPv6Address"
	MethodJobDescriptor           = "JobDescriptor"
	MethodJobLevel                = "JobLevel"
	MethodJobTitle                = "JobTitle"
	MethodLanguage                = "Language"
	MethodLanguageAbbreviation    = "LanguageAbbreviation"
	MethodLastName                = "LastName"
	MethodLetter                  = "Letter"
	MethodMacAddress              = "MacAddress"
	MethodFileMimeType            = "FileMimeType"
	MethodMonth                   = "Month"
	MethodName                    = "Name"
	MethodNamePrefix              = "NamePrefix"
	MethodNameSuffix              = "NameSuffix"
	MethodOperaUserAgent          = "OperaUserAgent"
	MethodPetName                 = "PetName"
	MethodPhone                   = "Phone"
	MethodPhoneFormatted          = "PhoneFormatted"
	MethodProgrammingLanguage     = "ProgrammingLanguage"
	MethodProgrammingLanguageBest = "ProgrammingLanguageBest"
	MethodQuestion                = "Question"
	MethodQuote                   = "Quote"
	MethodSSN                     = "SSN"
	MethodSafariUserAgent         = "SafariUserAgent"
	MethodSafeColor               = "SafeColor"
	MethodState                   = "State"
	MethodStateAbr                = "StateAbr"
	MethodStreet                  = "Street"
	MethodStreetName              = "StreetName"
	MethodStreetNumber            = "StreetNumber"
	MethodStreetPrefix            = "StreetPrefix"
	MethodStreetSuffix            = "StreetSuffix"
	MethodTimeZone                = "TimeZone"
	MethodTimeZoneAbv             = "TimeZoneAbv"
	MethodTimeZoneFull            = "TimeZoneFull"
	MethodCarTransmissionType     = "CarTransmissionType"
	MethodURL                     = "URL"
	MethodUserAgent               = "UserAgent"
	MethodUsername                = "Username"
	MethodCarType                 = "CarType"
	MethodWeekDay                 = "WeekDay"
	MethodWord                    = "Word"
	MethodZip                     = "Zip"
)

available faker methods

Variables

This section is empty.

Functions

This section is empty.

Types

type Aggregator

type Aggregator interface {
	// returns the aggregator query
	Query() bson.M
	// if the query use a `local` field prefixed with "$$",
	// this method should return the name of this field
	LocalVar() string
	// returns an update operation to run
	//
	// for example:
	//
	//  { "_id": 1 }, { "$set": { "newField": ["a", "c", "f"] } }
	Update(session *mongo.Client, value any) ([2]bson.M, error)
}

Aggregator is a type of generator that use another collection to compute aggregation on it

type CollInfo

type CollInfo struct {
	// number of document in the collection
	Count int
	// MongoDB version
	Version []int
	// seed for random generation
	Seed uint64
	// contains filtered or unexported fields
}

CollInfo stores global info on the collection to generate

func NewCollInfo

func NewCollInfo(count int, version []int, seed uint64, mapRef map[int][][]byte, mapRefType map[int]bsontype.Type) *CollInfo

NewCollInfo returns a new CollInfo. mapRef is a map holding bson-encoded values for references fields. mapRefType is a map holding bson type for references fields.

func (*CollInfo) NewAggregatorSlice

func (ci *CollInfo) NewAggregatorSlice(content map[string]Config) ([]Aggregator, error)

NewAggregatorSlice creates a slice of Aggregator from a map of Config

func (*CollInfo) NewDocumentGenerator

func (ci *CollInfo) NewDocumentGenerator(content map[string]Config) (*DocumentGenerator, error)

NewDocumentGenerator creates an object generator to generate valid bson documents

type Config

type Config struct {
	// Type of object to generate, required
	Type string `json:"type"`
	// Percentage of documents that won't contains this field, optional
	NullPercentage int `json:"nullPercentage"`
	// Maximum number of distinct value for this field, optional
	MaxDistinctValue int `json:"maxDistinctValue"`
	// For `string` type only. If set to 'true', string will be unique
	Unique bool `json:"unique"`
	// For `string` and `binary` type only. Specify the Min length of the object to generate
	MinLength json.Number `json:"minLength"`
	// For `string` and `binary` type only. Specify the Max length of the object to generate
	MaxLength json.Number `json:"maxLength"`
	// For `int`, `long` or `double` only. Lower bound for number to generate
	Min json.Number `json:"min"`
	// For `int`, `long` or `double` only. Higher bound for number to generate
	Max json.Number `json:"max"`
	// For `array` only. Config to fill the array. Need to
	// pass a pointer here to avoid 'invalid recursive type' error
	ArrayContent *Config `json:"arrayContent"`
	// For `object` only. List of GeneratorJSON to generate the content
	// of the object
	ObjectContent map[string]Config `json:"objectContent"`
	// For `enum` ( formerly `fromArray`) only. If specified, the generator
	// pick one of the item of the array
	Values []any
	// For `fromArray` only. If set to true, items are picked from the array in random order
	RandomOrder bool `json:"randomOrder"`
	// For `date` only. Lower bound for the date to generate
	StartDate time.Time `json:"startDate"`
	// For `date` only. Higher bound for the date to generate
	EndDate time.Time `json:"endDate"`
	// For `constant` type only. Value of the constant field
	ConstVal any `json:"constVal"`
	// For `autoincrement` type only. Start value
	Start json.Number `json:"start"`
	// For `autoincrement` type only. Type of the field, must be one of [ 'int', 'long' ]
	AutoType string `json:"autoType"`
	// For `faker` type only. Method to use
	Method string `json:"method"`
	// for `stringFromParts` type only. Generators used to create the string
	Parts []Config `json:"parts"`
	// For `reference` type only. Used to retrieve the array storing the value
	// for this field
	ID int `json:"id"`
	// For `reference` type only. generator for the field
	RefContent *Config `json:"refContent"`
	// For `uuid` type only. Type of the field, must be one of [ 'string', 'binary' ]
	UUIDFormat string `json:"format"`
	// For `countAggregator`, `boundAggregator` and `valueAggregator` only
	Collection string `json:"collection"`
	// For `countAggregator`, `boundAggregator` and `valueAggregator` only
	Database string `json:"database"`
	// For `boundAggregator` and `valueAggregator` only
	Field string `json:"field"`
	// For `countAggregator`, `boundAggregator` and `valueAggregator` only
	Query bson.M `json:"query"`

	// Deprecated. Use 'Min' instead
	MinInt int32 `json:"minInt"`
	// Deprecated. Use 'Max' instead
	MaxInt int32 `json:"maxInt"`
	// Deprecated. Use 'Min' instead
	MinLong int64 `json:"minLong"`
	// Deprecated. Use 'Max' instead
	MaxLong int64 `json:"maxLong"`
	// Deprecated. Use 'Min' instead
	MinDouble float64 `json:"minDouble"`
	// Deprecated. Use 'Max' instead
	MaxDouble float64 `json:"maxDouble"`
	// Deprecated. Use 'start' instead
	StartInt int32 `json:"startInt"`
	// Deprecated. Use 'start' instead
	StartLong int64 `json:"startLong"`
	// Deprecated. Use 'MinLength' and 'MaxLength' instead
	Size int `json:"size"`
	// Deprecated. Use 'Values' instead
	In []any `json:"in"`
}

Config struct containing all possible options

type DocBuffer

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

DocBuffer is a wrapper around a slice of bytes. It provides method similar to bytes.Buffer, plus a specific method WriteAt() to write at a specific position of the underlying slice of bytes

func NewDocBuffer

func NewDocBuffer() *DocBuffer

NewDocBuffer returns a new DocBuffer

func (*DocBuffer) Bytes

func (e *DocBuffer) Bytes() []byte

Bytes returns the content of the buffer. The resulting slice of should be copied before being used, otherwise it's content may be change

func (*DocBuffer) Len

func (e *DocBuffer) Len() int

Len returns the length of the buffer

func (*DocBuffer) Reserve

func (e *DocBuffer) Reserve()

Reserve appends 4 bytes to the buffer

func (*DocBuffer) Truncate

func (e *DocBuffer) Truncate(n int)

Truncate discards all but the first n bytes from the buffer

func (*DocBuffer) Write

func (e *DocBuffer) Write(b []byte)

Write appends bytes to the buffer

func (*DocBuffer) WriteAt

func (e *DocBuffer) WriteAt(off int, b []byte)

WriteAt writes bytes to the buffer at a specific position. This method will panic if off is greater than the length of the buffer, or if b is larger than the buffer

func (*DocBuffer) WriteSingleByte

func (e *DocBuffer) WriteSingleByte(b byte)

WriteSingleByte appends a single byte to the buffer

func (*DocBuffer) WriteString added in v0.11.0

func (e *DocBuffer) WriteString(s string)

type DocumentGenerator

type DocumentGenerator struct {
	// Buffer holds the document bytes
	Buffer *DocBuffer
	// list of all generators used to create the document. The resulting document
	// will have n keys where 0 < n < len(Generators)
	Generators []Generator
}

DocumentGenerator is a Generator for creating random bson documents

func (*DocumentGenerator) Add

func (g *DocumentGenerator) Add(generator Generator)

Add append a new Generator to the DocumentGenerator. The generator EncodeValue() method must write to the same DocBuffer as the DocumentGenerator g

func (*DocumentGenerator) Generate

func (g *DocumentGenerator) Generate() []byte

Generate creates a new bson document and returns it as a slice of bytes

type Generator

type Generator interface {
	// Key returns the element key
	Key() []byte
	// Type returns the bson type of the element as defined in bson spec: http://bsonspec.org/
	Type() bsontype.Type
	// Exists returns true if the generation should be performed.
	Exists() bool
	// EncodeValue encodes a random value in bson and write it to a DocBuffer
	EncodeValue()
	// EncodeToString encodes a random value as a string and write it to a DocBuffer
	EncodeValueAsString()
}

Generator is an interface for generator that can be used to generate random value of a specific type, and encode them in bson format

Jump to

Keyboard shortcuts

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