micronaut-projects / micronaut-data

Ahead of Time Data Repositories
Apache License 2.0
467 stars 198 forks source link

Repository code running in another thread doesn't see changes made from test code #3058

Closed Nahuel92 closed 2 months ago

Nahuel92 commented 3 months ago

Issue description

Hi there!

I'm not sure if this is a bug or an expected behavior. To me, it sounds like a bug, but here's the description so that you can tell me if this is really a bug or my mistake:

I'm running my repository method in another thread as part of my service logic. It works well, but when I try to test it, test fails because it seems that the transaction made at test code is not visible to the repository code.

For this particular test case, I have to change data in a table before the subject under test is executed (but it can't be done via the @Sql annotation, it must be right before executing the code, the reason for this won't add to this discussion).

I spent a lot of time trying to identify the issue, and it all boils down to multithreading. In the example application you can find here:

https://github.com/Nahuel92/poc-projects/tree/master/micronaut/micronaut-data-test-tx-bug

I created tests with both examples (single/same thread and different/multithread approaches).

If that matters, I verified that the Transaction Level is the default (read committed).

Please let me know if my description is clear enough and/or if you need more examples or information. Thank you!!

P.D.: By the way, it would be awesome if we could annotate test methods with @Sql so that we can run specific scripts per test method.

dstepanov commented 3 months ago

That's because MicronautTest is opening one TX by default. More arguments for https://github.com/micronaut-projects/micronaut-test/issues/967

Nahuel92 commented 3 months ago

That's because MicronautTest is opening one TX by default. More arguments for micronaut-projects/micronaut-test#967

Hi dstepanov!!

I tried that, but then this exception is thrown by most tests: io.micronaut.data.connection.exceptions.NoConnectionException: Expected an existing connection, but none was found.

I can commit the change for you to see it in action.

graemerocher commented 3 months ago

this is by design, transactions are associated to the thread

dstepanov commented 3 months ago

You need to open a connection or a tx