shlinkio /
shlink
| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace ShlinkioTest\Shlink\Core\Util; |
||
| 6 | |||
| 7 | use Doctrine\ORM\EntityManagerInterface; |
||
| 8 | use PHPUnit\Framework\TestCase; |
||
| 9 | use Prophecy\PhpUnit\ProphecyTrait; |
||
| 10 | use Prophecy\Prophecy\ObjectProphecy; |
||
| 11 | use RuntimeException; |
||
| 12 | use Shlinkio\Shlink\Core\Util\DoctrineBatchHelper; |
||
| 13 | |||
| 14 | class DoctrineBatchHelperTest extends TestCase |
||
| 15 | { |
||
| 16 | use ProphecyTrait; |
||
| 17 | |||
| 18 | private DoctrineBatchHelper $helper; |
||
| 19 | private ObjectProphecy $em; |
||
| 20 | |||
| 21 | protected function setUp(): void |
||
| 22 | { |
||
| 23 | $this->em = $this->prophesize(EntityManagerInterface::class); |
||
| 24 | $this->helper = new DoctrineBatchHelper($this->em->reveal()); |
||
| 25 | } |
||
| 26 | |||
| 27 | /** |
||
| 28 | * @test |
||
| 29 | * @dataProvider provideIterables |
||
| 30 | */ |
||
| 31 | public function entityManagerIsFlushedAndClearedTheExpectedAmountOfTimes( |
||
| 32 | array $iterable, |
||
| 33 | int $batchSize, |
||
| 34 | int $expectedCalls |
||
| 35 | ): void { |
||
| 36 | $wrappedIterable = $this->helper->wrapIterable($iterable, $batchSize); |
||
| 37 | |||
| 38 | foreach ($wrappedIterable as $item) { |
||
| 39 | // Iterable needs to be iterated for the logic to be invoked |
||
| 40 | } |
||
| 41 | |||
| 42 | $this->em->beginTransaction()->shouldHaveBeenCalledOnce(); |
||
| 43 | $this->em->commit()->shouldHaveBeenCalledOnce(); |
||
| 44 | $this->em->rollback()->shouldNotHaveBeenCalled(); |
||
| 45 | $this->em->flush()->shouldHaveBeenCalledTimes($expectedCalls); |
||
| 46 | $this->em->clear()->shouldHaveBeenCalledTimes($expectedCalls); |
||
| 47 | } |
||
| 48 | |||
| 49 | public function provideIterables(): iterable |
||
| 50 | { |
||
| 51 | yield [[], 100, 1]; |
||
| 52 | yield [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3, 4]; |
||
| 53 | yield [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 11, 1]; |
||
| 54 | } |
||
| 55 | |||
| 56 | /** @test */ |
||
| 57 | public function transactionIsRolledBackWhenAnErrorOccurs(): void |
||
| 58 | { |
||
| 59 | $flush = $this->em->flush()->willThrow(RuntimeException::class); |
||
| 60 | |||
| 61 | $wrappedIterable = $this->helper->wrapIterable([1, 2, 3], 1); |
||
| 62 | |||
| 63 | self::expectException(RuntimeException::class); |
||
|
0 ignored issues
–
show
Bug
Best Practice
introduced
by
Loading history...
|
|||
| 64 | $flush->shouldBeCalledOnce(); |
||
| 65 | $this->em->beginTransaction()->shouldBeCalledOnce(); |
||
| 66 | $this->em->commit()->shouldNotBeCalled(); |
||
| 67 | $this->em->rollback()->shouldBeCalledOnce(); |
||
| 68 | |||
| 69 | foreach ($wrappedIterable as $item) { |
||
| 70 | // Iterable needs to be iterated for the logic to be invoked |
||
| 71 | } |
||
| 72 | } |
||
| 73 | } |
||
| 74 |