TransactionalTest.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace lib\AppFramework\Db;
  8. use OCP\AppFramework\Db\TTransactional;
  9. use OCP\IDBConnection;
  10. use PHPUnit\Framework\MockObject\MockObject;
  11. use RuntimeException;
  12. use Test\TestCase;
  13. class TransactionalTest extends TestCase {
  14. /** @var IDBConnection|MockObject */
  15. private IDBConnection $db;
  16. protected function setUp(): void {
  17. parent::setUp();
  18. $this->db = $this->createMock(IDBConnection::class);
  19. }
  20. public function testAtomicRollback(): void {
  21. $test = new class($this->db) {
  22. use TTransactional;
  23. private IDBConnection $db;
  24. public function __construct(IDBConnection $db) {
  25. $this->db = $db;
  26. }
  27. public function fail(): void {
  28. $this->atomic(function () {
  29. throw new RuntimeException('nope');
  30. }, $this->db);
  31. }
  32. };
  33. $this->db->expects(self::once())
  34. ->method('beginTransaction');
  35. $this->db->expects(self::once())
  36. ->method('rollback');
  37. $this->db->expects(self::never())
  38. ->method('commit');
  39. $this->expectException(RuntimeException::class);
  40. $test->fail();
  41. }
  42. public function testAtomicCommit(): void {
  43. $test = new class($this->db) {
  44. use TTransactional;
  45. private IDBConnection $db;
  46. public function __construct(IDBConnection $db) {
  47. $this->db = $db;
  48. }
  49. public function succeed(): int {
  50. return $this->atomic(function () {
  51. return 3;
  52. }, $this->db);
  53. }
  54. };
  55. $this->db->expects(self::once())
  56. ->method('beginTransaction');
  57. $this->db->expects(self::never())
  58. ->method('rollback');
  59. $this->db->expects(self::once())
  60. ->method('commit');
  61. $result = $test->succeed();
  62. self::assertEquals(3, $result);
  63. }
  64. }