Fixtures
A fixture is a plain YAML file with the ability to use text/templateopen in new window expressions to generate values. Bun unmarshals YAML data into Go models using and then saves the model in a database.
Here is how a fixture for a User model might look like:
- model: User
rows:
- _id: smith
name: John Smith
email: john@smith.com
- _id: doe
name: Jonh Doe
email: john@doe.com
created_at: '{{ now }}'
rows:
- name: "{{ $.User.smith.Name }}'s Org"
owner_id: '{{ $.User.smith.ID }}'
- name: "{{ $.User.doe.Name }}'s Org"
Assuming the fixture is stored in testdata/fixture.yml
, you can load it with the following code:
By using fixture.WithRecreateTables()
option, you can make bun drop existing tables and replace them with new ones. Or you can use fixture.WithTruncateTables()
option to truncate tables.
fixture := dbfixture.New(db, dbfixture.WithRecreateTables())
fixture := dbfixture.New(db, dbfixture.WithTruncateTables())
Later you can retrieve the loaded models using Row
and methods:
fmt.Println("Smith", fixture.MustRow("User.smith").(*User))
You can also retrieve rows without _id
field by a primary key:
type User struct {
ID int64 `bun:",pk,autoincrement"`
Params UserParams `bun:"type:jsonb"`
}
type UserParams struct {
Param1 string `yaml:"param1"`
You can find the source code for the example above on GitHubopen in new window.