2161c201bcf96cedd3b1069e2fd94bad3490846f
lazy
Lazy is a helper tool when working with sqlx and sqlmock that generates mock data for unit tests based on the example struct.
RandomGenerate
Generates random data for basic types and slices to be used with sqlmock. Slices are given an arbitrary amount entries See Mocks for more information.
func RandomGenerate(m Config) (*Mock, error)
Config
type Config struct {
Query string
Example any
Keys []any
RowCount int
}
The Config struct is used to generate the data:
- Query the sql query that is being run in the function being tested
- Example represents the struct that will be used in the sql scan, this struct is used to detect which fields are expected in the query. Fields must have "db" tag to be parsed
- Keys primary keys to be hardcoded in mock rows, if needed. Primary keys are detected by tags in the example struct, see Tags for more information
- RowCount the amount of mock rows to be generated, if you are setting primary keys this number must be equal to the amount of keys supplied
Mocks
type Mock struct {
Query string
Columns []string
Rows [][]driver.Value
}
The Mock struct is returned by RandomGenerate:
- Query represents the query string expected by ExpectQuery. The original query is rebound using the bindvar type sqlx.AT
- Columns slice of expected column names for sqlmock.NewRows
- Rows represents the row data for AddRows
Tags
Struct tags are required on the example struct to generate the data
- lazy optional, set this tag to key to mark the primary key field on the example struct, if no Keys are provided in the Config struct this tag will be ignored
- db required for mock columns to be generated, columns will be based on tag value
Example
This program is a psuedo-code example of the mock generation. It takes the SqlResultsExample and uses it to generate two rows of mock data using the Keys (1, 6) as the Key, signified by the lazy tag. See Example output for the generated sql rows.
func ExampleTest() {
...
type SqlResultsExample struct {
Key string `db:"key" lazy:"key"`
Count int `db:"count"`
}
cfg := lazy.Config{
Query: "SELECT key, count FROM table WHERE key IN (?, ?)",
Example: SqlResultsExample{},
Keys: []any{ 1, 6 },
RowCount: 2,
}
mock, err := lazy.GenerateRandom(cfg)
if err != nil {
panic(err)
}
rows := sqlmock.NewRows(mock.Columns).AddRows(mock.Rows...)
sqlmock.ExpectQuery(mock.Query).WithArgs(1, 6).WillReturnRows(rows)
...
}
Example of mocked rows from ExampleTest
key | count |
---|---|
1 | 649018089772805963 |
6 | 1066940846275557682 |
Description
v1.1.0
Latest
Languages
Go
100%