DATA-DOG / go-sqlmock

Sql mock driver for golang to test database interactions
Other
6.05k stars 406 forks source link

Problem with ExpectQuery and ExpectPrepare regexp #229

Closed OtavioGallego closed 3 months ago

OtavioGallego commented 4 years ago

Hello!

First of all, I'd like to say that I'm really enjoying the library and it's really making my life easier when it comes to database testing. Thanks for that!

On the other hand, I have a few doubts about ExpectQuery and ExpectPrepare and how they work, I've looked in the docs and in the testing files but I did not find any information about it

Basically, what is the advantage of using the (.+) syntax as a part of the argument? And how to work around it properly?

For example, inside my social media personal project I have a posts table on the database and there are different functions to like and dislike such posts.

Keeping it simple, the update inside the like function goes like this: update posts set likes = likes + 1 where id = ?

Similarly, the update inside the dislike function goes like this: update posts set likes = likes - 1 where id = ?

The thing is, if inside my test I use update posts (.+) where id = ? as an argument to ExpectPrepare (followed by ExpectExec), how do I know that the update I'm expecting will be executed? If someone were to change the update inside the function to something like update posts set likes = 1000 where id = ?, the test would not notice it.

I did a bit of research and it turns out that (please correct me if I'm wrong) if I wanted to pass the full update inside ExpectPrepare, I would still have to pass it as a regular expression or otherwise I'd receive an error message saying could not match actual sql.

As I understand, the workaround would be something like: "update posts set likes \\= likes \\+ 1 where id \\= ?"

It looks ok in this specific case, but I also have another test case in which I have to test a complex query that uses join on 3 different tables, and to use a similar workaround as an argument to ExpectQuery would make the command extremely wordy and hard to understand.

Is there another way to do this? Am I missing something conceptual about the way that these Regular expressions should be used?

Thanks in advance!

shubinmi commented 4 years ago

I got unexpected behavior with ExpectQuery and ExpectPrepare too. Tables with names table_replacing and table_repl are equivalent to these methods. If the original query uses table_replacing but mock expect for table_repl then tests will be passed successfully anyway.

diegommm commented 3 months ago

Hi @OtavioGallego! sqlmock uses the standard library's regexp package, the (.+) snippet you mention is part of the regular expression language. Please, refer to that package for reference.

Thank you!