「GoCN酷Go推荐」Gofakeit 数据生成工具
GoCN
共 9077字,需浏览 19分钟
·
2021-11-19 09:12
Gofakeit
是一款Go语言编写的随机数据生成工具,使用更易用的接口设计,可满足日常开发中绝大多数数据生成场景
Gofakeit
让您以更优雅的姿势生成测试数据。Gofakeit
内置160+函数,同时也很方便自定义。
功能
160+内置函数!!! 多个rand源 全局rand 支持struct tag 支持自定义函数 内置http server 内置command line tool 0依赖 高性能
安装
import "github.com/brianvoe/gofakeit/v6"
Usage
快速开始
import "github.com/brianvoe/gofakeit/v6"
gofakeit.Name() // Markus Moen
gofakeit.Email() // alaynawuckert@kozey.biz
gofakeit.Phone() // (570)245-7485
gofakeit.BS() // front-end
gofakeit.BeerName() // Duvel
gofakeit.Color() // MediumOrchid
gofakeit.Company() // Moen, Pagac and Wuckert
gofakeit.CreditCardNumber() // 4287271570245748
gofakeit.HackerPhrase() // Connecting the array won't do anything, we need to generate the haptic COM driver!
gofakeit.JobTitle() // Director
gofakeit.CurrencyShort() // USD切换Random源
Gofakeit
有多个rand源,默认是math.Rand
,并且使用互斥锁实现并发安全。// Uses crypto/rand(cryptographically secure) with mutext locking
faker := gofakeit.NewCrypto()
// Pass in your own random source
faker := gofakeit.NewCustom()如果你需要更高的性能,可以手动解除互斥锁,注意这不是并发安全
// Uses math/rand(Pseudo) with NO mutext locking
// More performant but not goroutine safe.
faker := gofakeit.NewUnlocked(0)全局设置rand 如果你需要全局替换rand源,只需要简单设置即可:
faker := gofakeit.NewCrypto()
gofakeit.SetGlobalFaker(faker)Struct 生成
Gofakeit
可以为struct生成随机数据,并且可以覆盖所有基本类型,还可以使用tag定制数据import "github.com/brianvoe/gofakeit/v6"
// Create structs with random injected data
type Foo struct {
Str string
Int int
Pointer *int
Name string `fake:"{firstname}"` // Any available function all lowercase
Sentence string `fake:"{sentence:3}"` // Can call with parameters
RandStr string `fake:"{randomstring:[hello,world]}"`
Number string `fake:"{number:1,10}"` // Comma separated for multiple values
Regex string `fake:"{regex:[abcdef]{5}}"` // Generate string from regex
Map map[string]int `fakesize:"2"`
Array []string `fakesize:"2"`
Bar Bar
Skip *string `fake:"skip"` // Set to "skip" to not generate data for
Created time.Time // Can take in a fake tag as well as a format tag
CreatedFormat time.Time `fake:"{year}-{month}-{day}" format:"2006-01-02"`
}
type Bar struct {
Name string
Number int
Float float32
}
// Pass your struct as a pointer
var f Foo
gofakeit.Struct(&f)
fmt.Println(f.Str) // hrukpttuezptneuvunh
fmt.Println(f.Int) // -7825289004089916589
fmt.Println(*f.Pointer) // -343806609094473732
fmt.Println(f.Name) // fred
fmt.Println(f.Sentence) // Record river mind.
fmt.Println(f.RandStr) // world
fmt.Println(f.Number) // 4
fmt.Println(f.Regex) // cbdfc
fmt.Println(f.Map) // map[PxLIo:52 lxwnqhqc:846]
fmt.Println(f.Array) // cbdfc
fmt.Printf("%+v", f.Bar) // {Name:QFpZ Number:-2882647639396178786 Float:1.7636692e+37}
fmt.Println(f.Skip) //
fmt.Println(f.Created.String()) // 1908-12-07 04:14:25.685339029 +0000 UTC自定义函数 你可以实现自己的生成函数,如果想要在http server和command line中使用,需要通过
AddFuncLookup
来实现自定义功能// Simple
gofakeit.AddFuncLookup("friendname", Info{
Category: "custom",
Description: "Random friend name",
Example: "bill",
Output: "string",
Generate: func(r *rand.Rand, m *MapParams, info *Info) (interface{}, error) {
return RandomString([]string{"bill", "bob", "sally"}), nil
},
})
// With Params
gofakeit.AddFuncLookup("jumbleword", Info{
Category: "jumbleword",
Description: "Take a word and jumple it up",
Example: "loredlowlh",
Output: "string",
Params: []Param{
{Field: "word", Type: "int", Description: "Word you want to jumble"},
},
Generate: func(r *rand.Rand, m *MapParams, info *Info) (interface{}, error) {
word, err := info.GetString(m, "word")
if err != nil {
return nil, err
}
split := strings.Split(word, "")
ShuffleStrings(split)
return strings.Join(split, ""), nil
},
})
type Foo struct {
FriendName string `fake:"{friendname}"`
JumbleWord string `fake:"{jumbleword:helloworld}"`
}
var f Foo
gofakeit.Struct(&f)
fmt.Printf("%s", f.FriendName) // bill
fmt.Printf("%s", f.JumbleWord) // loredlowlh
内置函数列表
File
JSON(jo *JSONOptions) ([]byte, error)
XML(xo *XMLOptions) ([]byte, error)
FileExtension() string
FileMimeType() string
Person
Person() *PersonInfo
Name() string
NamePrefix() string
NameSuffix() string
FirstName() string
LastName() string
Gender() string
SSN() string
Contact() *ContactInfo
Email() string
Phone() string
PhoneFormatted() string
Teams(peopleArray []string, teamsArray []string) map[string][]string
Generate
Struct(v interface{})
Slice(v interface{})
Map() map[string]interface{}
Generate(value string) string
Regex(value string) string
Auth
Username() string
Password(lower bool, upper bool, numeric bool, special bool, space bool, num int) string
Address
Address() *AddressInfo
City() string
Country() string
CountryAbr() string
State() string
StateAbr() string
Street() string
StreetName() string
StreetNumber() string
StreetPrefix() string
StreetSuffix() string
Zip() string
Latitude() float64
LatitudeInRange(min, max float64) (float64, error)
Longitude() float64
LongitudeInRange(min, max float64) (float64, error)
Game
Gamertag() string
Beer
BeerAlcohol() string
BeerBlg() string
BeerHop() string
BeerIbu() string
BeerMalt() string
BeerName() string
BeerStyle() string
BeerYeast() string
Car
Car() *CarInfo
CarMaker() string
CarModel() string
CarType() string
CarFuelType() string
CarTransmissionType() string
Words
Noun() string
Verb() string
Adverb() string
Preposition() string
Adjective() string
Word() string
Sentence(wordCount int) string
Paragraph(paragraphCount int, sentenceCount int, wordCount int, separator string) string
LoremIpsumWord() string
LoremIpsumSentence(wordCount int) string
LoremIpsumParagraph(paragraphCount int, sentenceCount int, wordCount int, separator string) string
Question() string
Quote() string
Phrase() string
Foods
Fruit() string
Vegetable() string
Breakfast() string
Lunch() string
Dinner() string
Snack() string
Dessert() string
Misc
Bool() bool
UUID() string
FlipACoin() string
ShuffleAnySlice(v interface{})
Colors
Color() string
HexColor() string
RGBColor() []int
SafeColor() string
Internet
URL() string
DomainName() string
DomainSuffix() string
IPv4Address() string
IPv6Address() string
MacAddress() string
HTTPStatusCode() string
HTTPStatusCodeSimple() int
LogLevel(logType string) string
HTTPMethod() string
HTTPVersion() string
UserAgent() string
ChromeUserAgent() string
FirefoxUserAgent() string
OperaUserAgent() string
SafariUserAgent() string
Date/Time
Date() time.Time
DateRange(start, end time.Time) time.Time
NanoSecond() int
Second() int
Minute() int
Hour() int
Month() int
MonthString() string
Day() int
WeekDay() string
Year() int
TimeZone() string
TimeZoneAbv() string
TimeZoneFull() string
TimeZoneOffset() float32
TimeZoneRegion() string
Payment
Price(min, max float64) float64
CreditCard() *CreditCardInfo
CreditCardCvv() string
CreditCardExp() string
CreditCardNumber(*CreditCardOptions) string
CreditCardType() string
Currency() *CurrencyInfo
CurrencyLong() string
CurrencyShort() string
AchRouting() string
AchAccount() string
BitcoinAddress() string
BitcoinPrivateKey() string
Company
BS() string
BuzzWord() string
Company() string
CompanySuffix() string
Job() *JobInfo
JobDescriptor() string
JobLevel() string
JobTitle() string
Hacker
HackerAbbreviation() string
HackerAdjective() string
Hackeringverb() string
HackerNoun() string
HackerPhrase() string
HackerVerb() string
Hipster
HipsterWord() string
HipsterSentence(wordCount int) string
HipsterParagraph(paragraphCount int, sentenceCount int, wordCount int, separator string) string
App
AppName() string
AppVersion() string
AppAuthor() string
Animal
PetName() string
Animal() string
AnimalType() string
FarmAnimal() string
Cat() string
Dog() string
Emoji
Emoji() string
EmojiDescription() string
EmojiCategory() string
EmojiAlias() string
EmojiTag() string
Language
Language() string
LanguageAbbreviation() string
ProgrammingLanguage() string
ProgrammingLanguageBest() string
Number
Number(min int, max int) int
Int8() int8
Int16() int16
Int32() int32
Int64() int64
Uint8() uint8
Uint16() uint16
Uint32() uint32
Uint64() uint64
Float32() float32
Float32Range(min, max float32) float32
Float64() float64
Float64Range(min, max float64) float64
ShuffleInts(a []int)
RandomInt(i []int) int
HexUint8() string
HexUint16() string
HexUint32() string
HexUint64() string
HexUint128() string
HexUint256() string
String
Digit() string
DigitN(n uint) string
Letter() string
LetterN(n uint) string
Lexify(str string) string
Numerify(str string) string
ShuffleStrings(a []string)
RandomString(a []string) string
《酷Go推荐》招募:
各位Gopher同学,最近我们社区打算推出一个类似GoCN每日新闻的新栏目《酷Go推荐》,主要是每周推荐一个库或者好的项目,然后写一点这个库使用方法或者优点之类的,这样可以真正的帮助到大家能够学习到
新的库,并且知道怎么用。
大概规则和每日新闻类似,如果报名人多的话每个人一个月轮到一次,欢迎大家报名!戳「阅读原文」,即可报名
扫码也可以加入 GoCN 的大家族哟~
评论