craftcms / cms

Build bespoke content experiences with Craft.
https://craftcms.com
Other
3.2k stars 617 forks source link

Fix db transactions for Codeception Tests #15258

Open myleshyson opened 6 days ago

myleshyson commented 6 days ago

Description

Transactions not working in Codeception tests in Craft seems to be a long running issue. The problem stems from when Yii registers transaction listeners. Before each test, the Codeception Craft module sets up the Craft application. At that point, the initial PDO connection is made and cached in the Connection class. After the application is booted up, Yii then tries to register listeners on the Connection::EVENT_AFTER_OPEN event. The problem with that though is since Craft already opened a connection when being setup, those events are never fired.

This pull request aims to fix that by first closing the connection immediately after Craft is setup. Then before each test, open the connection again after Yii registers it's transaction handlers.

I tested this on a base craft 5 install using ddev and it works exactly as expected. I created a test that saved a user in the database. Before this change, my user persisted in the users table after tests were run. With this change, the user is not there after tests run.

Related issues

7615