go-sqlmock icon indicating copy to clipboard operation
go-sqlmock copied to clipboard

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

Open ns-tdemelocosta opened this issue 2 years ago • 2 comments
trafficstars

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))
	}
}
  1. Use the custom converter when creating the mock database:
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/[email protected]/rows.go:178 +0x2a4
FAIL

Additional Context:

  • I'm trying to simulate the behavior of PostgreSQL's text[] field.
  • I've referred to a GitHub conversation which suggested using a custom ValueConverter, but I'm still facing the issue.

ns-tdemelocosta avatar Aug 12 '23 03:08 ns-tdemelocosta

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

IvoGoman avatar Aug 16 '23 22:08 IvoGoman

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

ns-tdemelocosta avatar Aug 16 '23 23:08 ns-tdemelocosta