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