-
-
Notifications
You must be signed in to change notification settings - Fork 28
/
PorterTest.php
511 lines (419 loc) · 18 KB
/
PorterTest.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
<?php
declare(strict_types=1);
namespace ScriptFUSIONTest\Integration;
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
use Mockery\MockInterface;
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
use ScriptFUSION\Async\Throttle\DualThrottle;
use ScriptFUSION\Porter\Cache\CacheUnavailableException;
use ScriptFUSION\Porter\Collection\CountablePorterRecords;
use ScriptFUSION\Porter\Collection\FilteredRecords;
use ScriptFUSION\Porter\Collection\PorterRecords;
use ScriptFUSION\Porter\Collection\ProviderRecords;
use ScriptFUSION\Porter\Collection\RecordCollection;
use ScriptFUSION\Porter\Connector\Connector;
use ScriptFUSION\Porter\Connector\DataSource;
use ScriptFUSION\Porter\Connector\ImportConnector;
use ScriptFUSION\Porter\Connector\Recoverable\RecoverableExceptionHandler;
use ScriptFUSION\Porter\Connector\Recoverable\StatelessRecoverableExceptionHandler;
use ScriptFUSION\Porter\ForeignResourceException;
use ScriptFUSION\Porter\ImportException;
use ScriptFUSION\Porter\IncompatibleResourceException;
use ScriptFUSION\Porter\Porter;
use ScriptFUSION\Porter\PorterAware;
use ScriptFUSION\Porter\Provider\Provider;
use ScriptFUSION\Porter\Provider\ProviderFactory;
use ScriptFUSION\Porter\Provider\Resource\ProviderResource;
use ScriptFUSION\Porter\Provider\Resource\SingleRecordResource;
use ScriptFUSION\Porter\ProviderNotFoundException;
use ScriptFUSION\Porter\Import\Import;
use ScriptFUSION\Porter\Import\StaticImport;
use ScriptFUSION\Porter\Transform\FilterTransformer;
use ScriptFUSION\Porter\Transform\Transformer;
use ScriptFUSION\Retry\FailingTooHardException;
use ScriptFUSIONTest\MockFactory;
use ScriptFUSIONTest\Stubs\TestRecoverableException;
use ScriptFUSIONTest\Stubs\TestRecoverableExceptionHandler;
use function Amp\async;
use function Amp\delay;
use function Amp\Future\await;
final class PorterTest extends TestCase
{
use MockeryPHPUnitIntegration;
private Porter $porter;
private Provider|MockInterface $provider;
private ProviderResource|MockInterface $resource;
private ProviderResource|MockInterface $singleResource;
private Connector|MockInterface $connector;
private Import $import;
private Import $singleImport;
private ContainerInterface|MockInterface $container;
protected function setUp(): void
{
parent::setUp();
$this->porter = new Porter($this->container = \Mockery::spy(ContainerInterface::class));
$this->registerProvider($this->provider = MockFactory::mockProvider());
$this->connector = $this->provider->getConnector();
$this->resource = MockFactory::mockResource($this->provider);
$this->import = new Import($this->resource);
$this->singleResource = MockFactory::mockSingleRecordResource($this->provider);
$this->singleImport = new Import($this->singleResource);
}
private function registerProvider(Provider $provider, string $name = null): void
{
$name ??= \get_class($provider);
$this->container
->shouldReceive('has')->with($name)->andReturn(true)
->shouldReceive('get')->with($name)->andReturn($provider)->byDefault()
;
}
/**
* Arranges for the current connector to throw an exception in the retry callback.
*/
private function arrangeConnectorException(\Exception $exception): void
{
$this->connector->shouldReceive('fetch')->andThrow($exception);
}
#region Import
/**
* Tests that the full import path, via connector, resource and provider, fetches a record correctly.
*/
public function testImport(): void
{
$records = $this->porter->import($this->import);
self::assertInstanceOf(PorterRecords::class, $records);
self::assertNotSame($this->import, $records->getImport(), 'Import was not cloned.');
self::assertSame(['foo'], $records->current());
/** @var ProviderRecords $previous */
self::assertInstanceOf(ProviderRecords::class, $previous = $records->getPreviousCollection());
self::assertNotSame($this->resource, $previous->getResource(), 'Resource was not cloned.');
}
/**
* Tests that when the resource is countable, the count is propagated to the outermost collection.
*/
public function testImportCountableRecords(): void
{
$records = $this->porter->import(
new StaticImport(new \ArrayIterator(range(1, $count = 10)))
);
// Innermost collection.
self::assertInstanceOf(\Countable::class, $first = $records->findFirstCollection());
self::assertCount($count, $first);
// Outermost collection.
self::assertInstanceOf(CountablePorterRecords::class, $records);
self::assertCount($count, $records);
}
/**
* Tests that when the resource is countable the count is lost when filtering is applied.
*/
public function testImportAndFilterCountableRecords(): void
{
$records = $this->porter->import(
(new StaticImport(
new \ArrayIterator(array_map(fn ($i) => [$i], range(1, 10)))
))->addTransformer(new FilterTransformer(fn () => true))
);
// Innermost collection.
self::assertInstanceOf(\Countable::class, $records->findFirstCollection());
// Outermost collection.
self::assertNotInstanceOf(\Countable::class, $records);
}
/**
* Tests that when importing multiple records, records may be rewound when the iterator supports this.
*/
public function testRewind(): void
{
$this->resource->shouldReceive('fetch')->andReturn(new \ArrayIterator([$i1 = ['foo'], $i2 = ['bar']]));
$records = $this->porter->import($this->import);
self::assertTrue($records->valid());
self::assertCount(2, $records);
self::assertSame($i1, $records->current());
$records->next();
self::assertSame($i2, $records->current());
$records->rewind();
self::assertSame($i1, $records->current());
}
/**
* Tests that when importing records implemented using deferred execution with generators, the generator runs up
* to the first suspension point instead of being paused at the start.
*/
public function testImportGenerator(): void
{
$this->resource->expects('fetch')->andReturnUsing(function () use (&$init): \Generator {
$init = true;
yield [];
});
$this->porter->import($this->import);
self::assertTrue($init);
}
/**
* Tests that when a Transformer is PorterAware it receives the Porter instance that invoked it.
*/
public function testPorterAwareTransformer(): void
{
$this->porter->import(
$this->import->addTransformer(
\Mockery::mock(implode(',', [Transformer::class, PorterAware::class]))
->shouldReceive('setPorter')
->with($this->porter)
->once()
->shouldReceive('transform')
->andReturn(\Mockery::spy(RecordCollection::class))
->getMock()
)
);
}
/**
* Tests that when provider name is specified in an import specification, its value is used instead of the default
* provider class name of the resource.
*/
public function testImportCustomProviderName(): void
{
$this->registerProvider(
$provider = clone $this->provider,
$providerName = 'foo'
);
$records = $this->porter->import(
(new Import(MockFactory::mockResource($provider, new \ArrayIterator([$output = ['bar']]))))
->setProviderName($providerName)
);
self::assertSame($output, $records->current());
}
/**
* Tests that when a resource does not return an iterator, an exception is thrown.
*/
public function testImportFailure(): void
{
$this->resource->shouldReceive('fetch')->andReturn(null);
$this->expectException(\TypeError::class);
$this->expectExceptionMessage(\get_class($this->resource));
$this->porter->import($this->import);
}
public function testImportUnregisteredProvider(): void
{
$this->expectException(ProviderNotFoundException::class);
$this->expectExceptionMessage($providerName = 'foo');
$this->expectExceptionCode(0);
$this->porter->import($this->import->setProviderName("\"$providerName\""));
}
/**
* Tests that when a resource's provider class name does not match the provider an exception is thrown.
*/
public function testImportForeignResource(): void
{
// Replace existing provider with a different one.
$this->registerProvider(MockFactory::mockProvider(), \get_class($this->provider));
$this->expectException(ForeignResourceException::class);
$this->porter->import($this->import);
}
/**
* Tests that when importing a single record resource, an exception is thrown.
*/
public function testImportSingle(): void
{
$this->expectException(IncompatibleResourceException::class);
$this->expectExceptionMessage('importOne()');
$this->porter->import($this->singleImport);
}
/**
* Tests that when a resource returns ProviderRecords, Porter does not wrap the collection again.
*/
public function testProviderRecordsNotDoubleWrapped(): void
{
$this->resource->shouldReceive('fetch')
->andReturn($records = new ProviderRecords(new \ArrayIterator([]), $this->resource));
$imported = $this->porter->import($this->import);
self::assertInstanceOf(PorterRecords::class, $imported);
self::assertSame($records, $imported->getPreviousCollection());
}
#endregion
#region Import one
public function testImportOne(): void
{
$result = $this->porter->importOne($this->singleImport);
self::assertSame(['foo'], $result);
}
public function testImportOneOfNone(): void
{
$this->singleResource->shouldReceive('fetch')->andReturn(new \EmptyIterator);
$result = $this->porter->importOne($this->singleImport);
self::assertNull($result);
}
public function testImportOneOfMany(): void
{
$this->singleResource->shouldReceive('fetch')->andReturn(new \ArrayIterator([['foo'], ['bar']]));
$this->expectException(ImportException::class);
$this->porter->importOne($this->singleImport);
}
/**
* Tests that when importing one from a resource not marked with SingleRecordResource, an exception is thrown.
*/
public function testImportOneNonSingle(): void
{
$this->expectException(IncompatibleResourceException::class);
$this->expectExceptionMessage(SingleRecordResource::class);
$this->porter->importOne(new Import(\Mockery::mock(ProviderResource::class)));
}
#endregion
#region Durability
/**
* Tests that when a connector throws the recoverable exception type, the connection attempt is retried once.
*/
public function testOneTry(): void
{
$this->arrangeConnectorException(new TestRecoverableException);
$this->expectException(FailingTooHardException::class);
$this->expectExceptionMessage('1');
$this->porter->import($this->import->setMaxFetchAttempts(1));
}
/**
* Tests that when a connector throws an exception type derived from the recoverable exception type, the connection
* is retried.
*/
public function testDerivedRecoverableException(): void
{
$this->arrangeConnectorException(new TestRecoverableException);
$this->expectException(FailingTooHardException::class);
$this->porter->import($this->import->setMaxFetchAttempts(1));
}
/**
* Tests that when a connector throws the recoverable exception type, the connection can be retried the default
* number of times (more than once).
*/
public function testDefaultTries(): void
{
$this->arrangeConnectorException(new TestRecoverableException);
// Speed up test by circumventing exponential backoff default handler.
$this->import->setRecoverableExceptionHandler(new TestRecoverableExceptionHandler);
$this->expectException(FailingTooHardException::class);
$this->expectExceptionMessage((string)Import::DEFAULT_FETCH_ATTEMPTS);
$this->porter->import($this->import);
}
/**
* Tests that when a connector throws a non-recoverable exception type, the connection is not retried.
*/
public function testUnrecoverableException(): void
{
// Subclass Exception so it's not an ancestor of any other exception.
$this->arrangeConnectorException($exception = \Mockery::mock(\Exception::class));
$this->expectException(\get_class($exception));
$this->porter->import($this->import);
}
/**
* Tests that when a custom fetch exception handler is specified and the connector throws a recoverable exception
* type, the handler is called on each retry.
*/
public function testCustomFetchExceptionHandler(): void
{
$this->import->setRecoverableExceptionHandler(
\Mockery::mock(RecoverableExceptionHandler::class)
->shouldReceive('initialize')
->once()
->shouldReceive('__invoke')
->times(Import::DEFAULT_FETCH_ATTEMPTS - 1)
->getMock()
);
$this->arrangeConnectorException(new TestRecoverableException);
$this->expectException(FailingTooHardException::class);
$this->porter->import($this->import);
}
/**
* Tests that when a provider fetch exception handler is specified and the connector throws a recoverable
* exception, the handler is called before the user handler.
*/
public function testCustomProviderFetchExceptionHandler(): void
{
$this->import->setRecoverableExceptionHandler(
new StatelessRecoverableExceptionHandler(static function (): void {
throw new \LogicException('This exception must not be thrown!');
})
);
$this->arrangeConnectorException($connectorException =
new TestRecoverableException('This exception is caught by the provider handler.'));
$this->resource
->shouldReceive('fetch')
->andReturnUsing(static function (ImportConnector $connector) use ($connectorException): \Generator {
$connector->setRecoverableExceptionHandler(new StatelessRecoverableExceptionHandler(
static function (\Exception $exception) use ($connectorException) {
self::assertSame($connectorException, $exception);
throw new \RuntimeException('This exception is thrown by the provider handler.');
}
));
yield $connector->fetch(\Mockery::mock(DataSource::class));
})
;
$this->expectException(\RuntimeException::class);
$this->porter->importOne($this->singleImport);
}
#endregion
public function testFilter(): void
{
$this->resource->shouldReceive('fetch')->andReturnUsing(
static function (): \Generator {
foreach (range(1, 10) as $integer) {
yield [$integer];
}
}
);
$records = $this->porter->import(
$this->import
->addTransformer(new FilterTransformer($filter = static function (array $record): int {
return $record[0] % 2;
}))
);
self::assertInstanceOf(PorterRecords::class, $records);
self::assertSame([[1], [3], [5], [7], [9]], iterator_to_array($records));
/** @var FilteredRecords $previous */
self::assertInstanceOf(FilteredRecords::class, $previous = $records->getPreviousCollection());
self::assertNotSame($previous->getFilter(), $filter, 'Filter was not cloned.');
}
/**
* Tests that when caching is required but a caching facility is unavailable, an exception is thrown.
*/
public function testCacheUnavailable(): void
{
$this->expectException(CacheUnavailableException::class);
$this->porter->import($this->import->enableCache());
}
#region Throttle
/**
* Tests that a working throttle implementation is invoked during fetch operations.
*/
public function testThrottle(): void
{
$this->import->setThrottle($throttle = new DualThrottle);
$throttle->setMaxConcurrency(1);
$records = async($this->porter->import(...), $this->import);
delay(0);
self::assertTrue($throttle->isThrottling());
$records->await();
self::assertFalse($throttle->isThrottling());
}
/**
* Tests that a working throttle implementation can be called from multiple fibers queueing excess operations.
*/
public function testThrottleConcurrentFibers(): void
{
$this->import->setThrottle($throttle = new DualThrottle);
$throttle->setMaxPerSecond(1);
$import = fn () => async($this->porter->import(...), $this->import)->await();
$start = microtime(true);
await([async($import), async($import), async($import)]);
self::assertGreaterThan(3, microtime(true) - $start);
}
#endregion
/**
* Tests that when a provider is fetched from the provider factory multiple times, the provider factory is only
* created once.
*/
public function testGetOrCreateProviderFactory(): void
{
$property = new \ReflectionProperty($this->porter, 'providerFactory');
$this->porter->import($spec = new StaticImport(new \EmptyIterator()));
self::assertInstanceOf(ProviderFactory::class, $factory1 = $property->getValue($this->porter));
$this->porter->import($spec);
self::assertInstanceOf(ProviderFactory::class, $factory2 = $property->getValue($this->porter));
self::assertSame($factory1, $factory2);
}
}