在Go语言中生成有效的随机Faker值

huangapple go评论142阅读模式
英文:

Generate Valid Random Faker Values in Go

问题

我正在使用Validator包。我有以下结构体:

  1. type User struct {
  2. Name string `validate:"required"`
  3. Email string `validate:"required,email"`
  4. CreditCard string `validate:"credit_card"`
  5. Password string `validate:"min=8,max=255"`
  6. }

我该如何生成这些字段的有效随机值?

英文:

I am using Validator package. I have the next Struct:

  1. type User struct {
  2. Name string `validate:"required"`
  3. Email string `validate:"required,email"`
  4. CreditCard string `validate:"credit_card"`
  5. Password string `validate:"min=8,max=255"`
  6. }

What can I do to generate valid random values for thats fields?

答案1

得分: 3

你可以使用faker包。它具有FirstName()Email()CCNumber()等函数。你还可以在你的结构体中使用标签(onetwo)与该包一起使用。

英文:

You can use faker package. It has functions like FirstName(), Email(), CCNumber(). You can also use tags (one, two) with this package in your struct.

答案2

得分: 1

如果你正在编写测试,你可以使用Fuzzing(在Go 1.18中实现)。

代码看起来像这样:

  1. import "testing"
  2. func TestHello(f *testing.F) {
  3. // 在这里添加你的种子
  4. f.add("John", "john@test.com", "1234-5678-1234-5678", "@HelloWorld123")
  5. f.Fuzz(func(t *testing.T, name, email, creditCard, pass string) {
  6. // 在这里编写你的测试
  7. }))
  8. }

然后运行:

  1. $ go test -fuzz
英文:

If you're writing tests, you can use Fuzzing (implemented in Go 1.18).

Would look like this:

  1. import "testing"
  2. func TestHello(f *testing.F) {
  3. // Add your seeds here
  4. f.add("John", "john@test.com", "1234-5678-1234-5678", "@HelloWorld123")
  5. f.Fuzz(func(t *testing.T, name, email, creditCard, pass string) {
  6. // Write your test here
  7. }))
  8. }

Then run:

  1. $ go test -fuzz

huangapple
  • 本文由 发表于 2022年8月5日 00:12:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/73239144.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定