Skip to content

Instantly share code, notes, and snippets.

@rerorero
Created October 5, 2018 11:55
Show Gist options
  • Save rerorero/82c22d191ac313fa4612ec40a9fc3326 to your computer and use it in GitHub Desktop.
Save rerorero/82c22d191ac313fa4612ec40a9fc3326 to your computer and use it in GitHub Desktop.
gopter-sample
package main
import (
"fmt"
"github.com/leanovate/gopter"
"github.com/leanovate/gopter/arbitrary"
"github.com/leanovate/gopter/gen"
"reflect"
)
type User struct {
Name string
Address []string
age int64
}
type Message struct{
From User
To []*User
Length int64
}
func main() {
userGen := gen.Struct(reflect.TypeOf(&User{}), map[string]gopter.Gen {
"Name": gen.AlphaString(),
"Address": gen.SliceOfN(5, gen.Identifier()),
//"age": gen.Int64Range(18,24), イケてないとこ1) private fieldは指定できない。以下のようにMap,FlatMapでやればなんとかなる
}).Map(func (value User) User {
age, _ := gen.Int64Range(18, 24).Sample()
value.age = age.(int64)
return value
})
// random sampling
user1, _ := userGen.Sample()
fmt.Printf("%+v\n", user1.(User))
msgGen := gen.Struct(reflect.TypeOf(&Message{}), map[string]gopter.Gen {
"From": userGen,
"To": gen.SliceOfN(3, gen.PtrOf(userGen)),
"Length": gen.Int64(),
})
// random sampling
msg1, _ := msgGen.Sample()
fmt.Printf("%+v\n", msg1.(Message))
// property based testing
arb := arbitrary.DefaultArbitraries()
arb.RegisterGen(userGen)
arb.RegisterGen(msgGen)
prop := gopter.NewProperties(nil)
prop.Property("test", arb.ForAll(func(msg Message) bool {
fmt.Printf("%+v\n", msg)
// test with msg ...
return msg.From.age >= 18
}))
prop.Run(gopter.ConsoleReporter(false))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment