1

I'm using mysql in a node project.

I would like to unit test a javascript function that makes an sql transaction. If the transaction becomes the victim of a lock monitor, the function has code that handles the failure.

Or does it?

Because I'm unit testing, I'm only making one transaction at a time on a local database, so there's never going to be a deadlock, right? How can I test the deadlock handling if it's never going to happen? Is there a way I can force it to happen?

Example:

thisMustBeDoneBeforeTheQuery();
connection.queryAsync(/*This is an update*/).catch(function(err) {
    undoThatStuffIDidBeforeTheQuery();
    // I hope that function worked, because my unit tests can't
    // make a deadlock happen, so I can't know for sure.
}
Christopher Waugh
  • 441
  • 1
  • 4
  • 15
  • You should mock away the database stuff and in a test case fake the deadlock error. Then you can test for the validity of your error code. It depends on your use-case. Unit tests dealing with a persistence layer can become quite irky to setup. It also depends on how your code looks like for the proper testing strategy. – k0pernikus Sep 25 '17 at 14:09
  • Related: https://stackoverflow.com/questions/8389149/how-do-you-mock-mysql-without-an-orm-in-node-js – k0pernikus Sep 25 '17 at 14:11
  • It seems like mocking SQL might work. I'll give it a try. – Christopher Waugh Sep 25 '17 at 15:16

1 Answers1

0

What is the essential behavior that your tests need to guard or verify?? Do you need to test your mysql driver? Or MySql itself? I think @k0pernikus Identified the highest value test:

Assuming that the database client results in an exception because of a deadlock, how does your application code handle it?

You should be able to pretty easily create a test harness using a mocking library or Dependency Injection and test stubs to simulate the client driver returning a deadlock exception. This shouldn't require any interaction with mysql, beyond the initial investigation to see what the return code/error exception propagation looks like for your mysql client driver.

This isn't a 100% perfect test, and still leaves your vulnerable in the case the mysql client library changes.


Reproducing concurrent issues deterministically is often times extremely difficult because of timing. But using SELECT ... FOR UPDATE and multiple transactions should be able to deterministically reproduce a deadlock on mysql, to verify your client libraries code.

dm03514
  • 54,664
  • 18
  • 108
  • 145