DATA-DOG / go-sqlmock

Sql mock driver for golang to test database interactions
Other
6.09k stars 408 forks source link

Unable to Mock Rows with `[]string` Type Using Custom ValueConverter #319

Closed ns-tdemelocosta closed 3 months ago

ns-tdemelocosta commented 1 year ago

Description:

I'm trying to mock a database query that returns rows containing a column of type []string (analogous to PostgreSQL's text[] field). However, even after implementing a custom ValueConverter to handle the []string type, I'm encountering a panic when adding rows with this type using sqlmock.NewRows(...).AddRow(...).

Error:

panic: row #1, column #3 ("obfuscation_fields") type []string: unsupported type []string, a slice of string

Steps to Reproduce:

  1. Create a custom ValueConverter to handle the []string type:
    
    type CustomConverter struct{}

func (s CustomConverter) ConvertValue(v interface{}) (driver.Value, error) { switch v.(type) { case string: return v.(string), nil case []string: return v.([]string), nil case int: return v.(int), nil default: return nil, errors.New(fmt.Sprintf("cannot convert %T with value %v", v, v)) } }


2. Use the custom converter when creating the mock database:
```go
db, mock, err := sqlmock.New(sqlmock.ValueConverterOption(CustomConverter{}))
  1. Mock a query that returns rows with a []string column:
    rows := sqlmock.NewRows([]string{"obfuscation_fields"}).
    AddRow([]string{"of1", "of2"})

Expected Behavior: The mock should be able to handle rows with a []string column without any issues.

Actual Behavior: A panic occurs indicating that the []string type is unsupported.

panic: row #1, column #3 ("obfuscation_fields") type []string: unsupported type []string, a slice of string [recovered]

goroutine 39 [running]:
testing.tRunner.func1.2({0x100693620, 0x1400018acd0})
    /opt/homebrew/opt/go/libexec/src/testing/testing.go:1526 +0x1c8
testing.tRunner.func1()
    /opt/homebrew/opt/go/libexec/src/testing/testing.go:1529 +0x384
panic({0x100693620, 0x1400018acd0})
    /opt/homebrew/opt/go/libexec/src/runtime/panic.go:884 +0x204
github.com/DATA-DOG/go-sqlmock.(*Rows).AddRow(0x140001c6c00, {0x14000188e98, 0xc, 0x1001417a3?})
    /Users/tdemelocosta/go/pkg/mod/github.com/!d!a!t!a-!d!o!g/go-sqlmock@v1.5.0/rows.go:178 +0x2a4
FAIL

Additional Context:

IvoGoman commented 1 year ago

In step 3. you are calling sqlmock.NewRows(..), which is using the driver.DefaultParameterConverter and causes the panic. Using mock.NewRows(..) should give you the expected results: https://go.dev/play/p/7ZSsBDGeMtt

ns-tdemelocosta commented 1 year ago

Thank you @IvoGoman . It works, I'm almost ashamed of this mistake nobody I've shown the code was able to figure out.