Giter Club home page Giter Club logo

Comments (11)

l3pp4rd avatar l3pp4rd commented on May 18, 2024

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.

mantzas avatar mantzas commented on May 18, 2024

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.

l3pp4rd avatar l3pp4rd commented on May 18, 2024

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.

mantzas avatar mantzas commented on May 18, 2024

Perfect. this work very nice. Fantastic library by the way!!!

from go-sqlmock.

l3pp4rd avatar l3pp4rd commented on May 18, 2024

thanks, have fun with the library ;)

from go-sqlmock.

mantzas avatar mantzas commented on May 18, 2024

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.

l3pp4rd avatar l3pp4rd commented on May 18, 2024

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.

mantzas avatar mantzas commented on May 18, 2024

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.

l3pp4rd avatar l3pp4rd commented on May 18, 2024

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.

mantzas avatar mantzas commented on May 18, 2024

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.

eoinahern avatar eoinahern commented on May 18, 2024

having trouble testing count with this library

from go-sqlmock.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.