40 lines
1.6 KiB
Markdown
40 lines
1.6 KiB
Markdown
# lazy
|
|
|
|
Lazy is a helper tool when working with SQLx and sqlmock that generates mock data based on the result struct.
|
|
|
|
## GenerateRandomResults
|
|
This function expects the SQL query, the example response object, and an optional primary key to set.
|
|
|
|
<b>Query</b> The SQL query argument is taken and rebound using sqlx.AT bindvar type, this allows the returned query to be used directly in a sqlmock [ExpectQuery](https://pkg.go.dev/github.com/data-dog/go-sqlmock#Sqlmock.ExpectQuery) check.
|
|
|
|
<b>Example Object</b> The example object argument <u>must</u> be a struct and requires "db" tags. The db tags are then parsed and used to calculate the psuedo-random rows and values
|
|
|
|
<b>Primary Key</b> The optional primary key argument is used to hardcode a primary key field in the returned mocks, the primary key field in the example struct <u>must</u> have a test tag with the value "key"
|
|
```go
|
|
type Mock struct {
|
|
Field1 string `db:"field1" test:"key"`
|
|
}
|
|
```
|
|
|
|
## Example
|
|
```go
|
|
func Test() {
|
|
testArg := 123
|
|
query := `SELECT ...`
|
|
type results struct {
|
|
Field1 string `db:"field1" test:"key"`
|
|
Field2 int `db:"field2"`
|
|
}
|
|
|
|
rando, err := GenerateRandomResults(query, results{}, testArg)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
//the rando object will now have psuedo random values in all fields except for the field containing the test tag set to "key" that field will be hardcoded with the testArg to allow for unit tests to ensure the requested ID flows through
|
|
rows := sqlmock.NewRows(rando.Columns).AddRow(rando.Rows...)
|
|
mock.ExpectQuery(rando.Query).WithArgs(testArg).WillReturnRows(rows)
|
|
|
|
...
|
|
}
|
|
``` |