Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

patch function Scan to support int,int8,int16,int32 (#1) #142

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

corelmax
Copy link

if i have an table on RDBMS and i need to query it and map to struct looks like this

type Data struct {
 A decimal.Decimal
 B decimal.Decimal
 C decimal.Decimal
}

and i don't want to test with actual connection to database. so i create SqlRows implementation like this

// Scan ...
func (inst *MockScanner) Scan(src ...interface{}) error {
	for i, d := range src {
		switch d := d.(type) {
		case *int:
			*d = inst.data[i].(int)
		case *string:
			*d = inst.data[i].(string)
		case *float32:
			*d = inst.data[i].(float32)
		case *float64:
			*d = inst.data[i].(float64)
		default:
			if scanner, ok := d.(sql.Scanner); ok {
				if err := scanner.Scan(inst.data[i]); err != nil {
					return err
				}
			}
		}
	}

	return nil
}

then, i create function like this

func MapData(rows *sql.SqlRows) (*Data, error) {
  var out Data
  err := rows.Scan(&out.A, &out.B, &out.C)
  return &out, err
}

So, I able to test this function without actual query on database like this

mock := NewMockScanner(1, 2, 3) // now support int. so, it doesn't need to be NewMockScanner(int64(1), ...) or NewMockScanner(decimal.NewFromFloat(1), ...) 
out,err := MapData(mock)
So(out.A, ShouldEqual, decimal.NewFromFloat(1))
...

someone might think this is pointless. but, if someone have to deal with bank's project and need to write some tests for function which deal with hundred of fields (and all of them have to be mocked), this should made a point.

* add tests for int8,int32 and int64 

* implement Scan to support int8, int16, int32

* also support for int natural
Copy link
Member

@njason njason left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One small ask, otherwise looks good.

case int:
// also better to implement to support all type of int.
// profitable to create another abstract layer for testing
// data access with no depends on real RDBMS.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you remove this comment, it seems unnecessary.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants