Comments (11)
hi, the time.Time
cannot be compared that simple. because it has a different memory address. You can create a time argument implementing Argument interface to compare time instances by their formats, or just as any value. Since I noticed that this question was raised few times before, I have added the example in README
from go-sqlmock.
I have followed the example but cannot get it working.
I have replaced the time with your example but still it did not work!
(Check out the project https://github.com/mantzas/incata and the test sql_writer_test.go)
from go-sqlmock.
In that case it means the reason is not the time.Time argument. but something else. The easiest way to find out - is to make an Any
type to match any argument and see which one is failing (sqlmock could write that in error as an improvement):
type Any struct{}
func (a Any) Match(v driver.Value) bool {
return true
}
Change one by one argument to Any{}
and see what happens. I found out that it was Event.SourceID
which is of uuid.UUID type. The reason why it is not matching is because this type when written to database value is converted to a simple string type - and sqlmock in your case tries to compare string
and uuid.UUID
interface.. which of course do not match. So your test should look like:
func TestSqlWriterWrite(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
defer db.Close()
ser := NewJSONSerializer()
database, _ := NewDbFinalized(db, MSSQL)
wr := NewSQLWriter(database, ser)
event := NewEvent(uuid.NewV4(), getTestData(), "TEST", 1)
payload, _ := ser.Serialize(event.Payload)
mock.ExpectExec("INSERT INTO Event").
WithArgs(event.SourceID.String(), event.Created, event.EventType, event.Version, payload).
WillReturnResult(sqlmock.NewResult(1, 1))
if err := wr.Write(*event); err != nil {
t.Errorf("error was not expected while writing event: %s", err)
}
// we make sure that all expectations were met
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expections: %s", err)
}
}
The time is actually matched by type in sqlmock, my mistake. But in case if you have a complex types to match as SQL arguments, Argument interface suits it well.
I will also have a look why it becomes a string and maybe it is a common sql library feature, sqlmock should match it the same way as database values get converted., something for improvement. Leave the issue open for now
from go-sqlmock.
Perfect. this work very nice. Fantastic library by the way!!!
from go-sqlmock.
thanks, have fun with the library ;)
from go-sqlmock.
Hi, i have another problem.
i cannot make Query to work(sql_reader_test.go). The test expects the query to be the following:
-
`SELECT
Id ,SourceId ,Created ,EventType ,Version ,Payload FROM Event WHERE SourceId = ?`.
-
the argument is of type uuid.UUID
i have setup the mock using the anytype wich returns always true but it still does not work.
what do i do wrong?
from go-sqlmock.
hi, ExpectQuery takes a regular expression string, not a string. so you either have to escape it properly, or simply use something like ExpectQuery('^SELECT (.*) FROM xxx")
its a regular expression.
from go-sqlmock.
yes i tried but it did not work!
this regex matches my query expression when using a online tool:
regex: ^SELECT (.) FROM Event WHERE SourceId = (.)
against the query: SELECT Id ,SourceId ,Created ,EventType ,Version ,Payload FROM Event WHERE SourceId = ?
still it does not work!
sql_reader_test.go:40: there were unfulfilled expections: there is a remaining expectation which was not matched: ExpectedQuery => expecting Query or QueryRow which:
- matches sql: '^SELECT (.) FROM Event WHERE SourceId = (.)'
- is with arguments:
0 - {}
what am i doing wrong?
from go-sqlmock.
Well you have to understand what you are doing @mantzas
func TestSqlReaderRead(t *testing.T) {
// t.Skip("Not working yet!!!")
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
defer db.Close()
var sourceID = uuid.NewV4()
rows := sqlmock.NewRows([]string{"Id", "SourceId", "Created", "EventType", "Version", "Payload"})
// rows.AddRow(columns...)
mock.ExpectQuery("SELECT").
WithArgs(sourceID.String()).
WillReturnRows(rows)
storage, _ := NewDbFinalized(db, MSSQL)
marshaller := NewJSONMarshaller()
reader := NewSQLReader(storage, marshaller)
_, err = reader.Read(sourceID)
if err != nil {
t.Fatalf("unexpected err: %s", err)
}
if err = mock.ExpectationsWereMet(); err != nil {
t.Fatalf("there were unfulfilled expections: %s", err)
}
}
You have to simulate everything with sqlmock, what you expect, what it will return. see tests in sqlmock or examples. I cannot help you and I won't, if you keep asking without even looking how the library works. sqlmock returns errors through your *sql,DB, so check for errors, that is what you must do usually in go programs and especially in your tests. Also I see that, sourceID you store is of custom type, you must implement methods to any custom database type, to convert it to bytes or string instead so sql.DB would be able to read and write it.
from go-sqlmock.
thanks very much, got it.
I looked only at the examples on your the Github page which had no Query sample, and did not look in the examples folder which had a query sample. Maybe you could add one at the front to.
will not bother you again!
from go-sqlmock.
having trouble testing count with this library
from go-sqlmock.
Related Issues (20)
- How to print go-sqlmock expected query?
- how to mock mock preload
- Getting 'Query: could not match actual sql' on identical queries HOT 2
- gordor.options PrefetchCount\FetchArraySize HOT 1
- please provide GORM example HOT 1
- using lowercase for installation
- feature: Add WithTxOptions() to ExpectBegin
- Issue with JSON Byte matching
- Unable to Mock Rows with `[]string` Type Using Custom ValueConverter HOT 2
- How can I make sqlmock not care about the order of arguments? HOT 1
- Even though I type mock.ExpectBegin(), I get db transaction begin error HOT 2
- "Issue Testing Row Scan Error with go-sqlmock: Uncovered Error Handling in Repository Function
- Improve panic output with rows.AddRow HOT 2
- test a call to a procedure
- How to mock an update with returning HOT 1
- Breaking change in v1.5.1 HOT 5
- Argument matching for queries using unpacked slices
- When expectedSQL is empty it is matching with any query HOT 1
- Mock columnsWithAlias HOT 1
- sqlmock panics when closing empty Rows object
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from go-sqlmock.