-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTestCase.php
More file actions
600 lines (545 loc) · 22.1 KB
/
Copy pathTestCase.php
File metadata and controls
600 lines (545 loc) · 22.1 KB
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
<?php
declare(strict_types=1);
namespace MatchBot\Tests;
use DI\Container;
use DI\ContainerBuilder;
use Exception;
use MatchBot\Application\Messenger\DonationUpserted;
use MatchBot\Domain\ApplicationStatus;
use MatchBot\Domain\Campaign;
use MatchBot\Domain\CampaignFamily;
use MatchBot\Domain\CampaignStatistics;
use MatchBot\Domain\Charity;
use MatchBot\Domain\CharityResponseToOffer;
use MatchBot\Domain\Currency;
use MatchBot\Domain\DayOfMonth;
use MatchBot\Domain\Donation;
use MatchBot\Domain\DonationSequenceNumber;
use MatchBot\Domain\DonorName;
use MatchBot\Domain\EmailAddress;
use MatchBot\Domain\MetaCampaign;
use MatchBot\Domain\MetaCampaignSlug;
use MatchBot\Domain\Money;
use MatchBot\Domain\PaymentMethodType;
use MatchBot\Domain\PaymentServiceProvider;
use MatchBot\Domain\RegularGivingMandate;
use MatchBot\Domain\PersonId;
use MatchBot\Domain\RyftAccountId;
use MatchBot\Domain\Salesforce18Id;
use MatchBot\IntegrationTests\IntegrationTest;
use PHPUnit\Framework\TestCase as PHPUnitTestCase;
use Prophecy\Argument;
use Prophecy\PhpUnit\ProphecyTrait;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidInterface;
use Random\Randomizer;
use Redis;
use Slim\App;
use Slim\Factory\AppFactory;
use Slim\Psr7\Factory\StreamFactory;
use Slim\Psr7\Headers;
use Slim\Psr7\Request as SlimRequest;
use Slim\Psr7\Uri;
use Symfony\Component\Clock\ClockInterface;
use Symfony\Component\RateLimiter\RateLimiterFactory;
use Symfony\Component\RateLimiter\Storage\InMemoryStorage;
use MatchBot\Client;
/**
* @psalm-import-type SFCampaignApiResponse from Client\Campaign
*/
class TestCase extends PHPUnitTestCase
{
use ProphecyTrait;
/** @var SFCampaignApiResponse */
public const array CAMPAIGN_FROM_SALESFORCE = [
'id' => 'a05xxxxxxxxxxxxxxx',
'isMetaCampaign' => false,
'aims' => [0 => 'First Aim'],
'isPublished' => true,
'title' => 'Save Matchbot',
'video' => null,
'hidden' => false,
'quotes' => [],
'endDate' => '2095-08-01T00:00:00.000Z',
'problem' => 'Matchbot is threatened!',
'summary' => 'We can save matchbot',
'updates' => [],
'solution' => 'do the saving',
'bannerUri' => null,
'locations' => [['countryName' => 'United Kingdom', 'regionCode' => null]],
'isMatched' => true,
'parentRef' => null,
'startDate' => '2015-08-01T00:00:00.000Z',
'categories' => ['Education/Training/Employment', 'Religious'],
'championRef' => null,
'amountRaised' => 0.0,
'championName' => '',
'currencyCode' => 'GBP',
'beneficiaries' => ['Animals'],
'budgetDetails' => [
['amount' => 23.0, 'description' => 'Improve the code'],
['amount' => 23.0, 'description' => 'Improve the code'], // duplicate item to allow testing de-dupe code.
['amount' => 27.0, 'description' => 'Invent a new programing paradigm'],
],
'campaignCount' => null,
'donationCount' => 0,
'impactSummary' => null,
'impactReporting' => null,
'isRegularGiving' => false,
'isEmergencyIMF' => false,
'slug' => null,
'campaignFamily' => 'summerGive',
'matchFundsTotal' => 50.0,
'thankYouMessage' => 'Thank you for helping us save matchbot! We will be able to match twice as many bots now!',
'usesSharedFunds' => false,
'alternativeFundUse' => null,
'parentAmountRaised' => null,
'additionalImages' => [],
'matchFundsRemaining' => 50.0,
'parentDonationCount' => null,
'surplusDonationInfo' => '',
'parentUsesSharedFunds' => false,
'championOptInStatement' => '',
'totalAdjustment' => null,
'parentMatchFundsRemaining' => null,
'regularGivingCollectionEnd' => null,
'pinPosition' => null,
'championPagePinPosition' => null,
'relatedApplicationStatus' => null,
'relatedApplicationCharityResponseToOffer' => null,
'charity' => [
'id' => 'xxxxxxxxxxxxxxxxxx',
'name' => 'Society for the advancement of bots and matches',
'logoUri' => null,
'twitter' => null,
'website' => 'https://society-for-the-advancement-of-bots-and-matches.localhost',
'facebook' => 'https://www.facebook.com/botsAndMatches',
'linkedin' => 'https://www.linkedin.com/company/botsAndMatches',
'instagram' => 'https://www.instagram.com/botsAndMatches',
'phoneNumber' => null,
'emailAddress' => 'bots-and-matches@example.com',
'optInStatement' => null,
'regulatorNumber' => '1000000',
'regulatorRegion' => 'England and Wales',
'stripeAccountId' => 'acc_123456',
'ryftAccountId' => null,
'hmrcReferenceNumber' => null,
'giftAidOnboardingStatus' => 'Invited to Onboard',
]
];
/**
* @var SFCampaignApiResponse
*/
public const array META_CAMPAIGN_FROM_SALESFORCE = [
'id' => 'a05xxxxxxxxxxxxxxx',
'isMetaCampaign' => true,
'isPublished' => true,
'title' => 'This is a meta campaign',
'video' => null,
'hidden' => false,
'quotes' => [],
'endDate' => '2095-08-01T00:00:00.000Z',
'problem' => '',
'summary' => '',
'updates' => [],
'solution' => 'do the saving',
'bannerUri' => null,
// These properties aren't actually used on MetaCampaign but it's only tests affected and
// quicker to continue importing a shared type for now.
'locations' => [['countryName' => 'United Kingdom', 'regionCode' => null]],
'isMatched' => true,
'parentRef' => null,
'startDate' => '2015-08-01T00:00:00.000Z',
'categories' => ['Education/Training/Employment', 'Religious'],
'championRef' => null,
'amountRaised' => 0.0,
'championName' => '',
'currencyCode' => 'GBP',
'campaignCount' => null,
'donationCount' => 0,
'impactSummary' => null,
'impactReporting' => null,
'isRegularGiving' => false,
'isEmergencyIMF' => false,
'slug' => 'some-slug',
'campaignFamily' => 'summerGive',
'matchFundsTotal' => 50.0,
'thankYouMessage' => 'Thank you for helping us save matchbot! We will be able to match twice as many bots now!',
'usesSharedFunds' => false,
'alternativeFundUse' => null,
'parentAmountRaised' => null,
'additionalImages' => [],
'matchFundsRemaining' => 50.0,
'parentDonationCount' => null,
'surplusDonationInfo' => '',
'parentUsesSharedFunds' => false,
'championOptInStatement' => '',
'parentMatchFundsRemaining' => null,
'regularGivingCollectionEnd' => null,
'totalAdjustment' => 0.0,
'charity' => null,
'aims' => [],
'budgetDetails' => [],
'beneficiaries' => [],
];
/**
* @var array<0|1, ?App<ContainerInterface|null>> array of app instances with and without real redis. Each one may be
* initialised up to once per test.
*/
private array $appInstance = [0 => null, 1 => null];
public static function someMandate(): RegularGivingMandate
{
return new RegularGivingMandate(
PersonId::of(Uuid::MAX),
Money::fromPoundsGBP(1),
Salesforce18Id::ofCampaign('xxxxxxxxxxxxxxxxxx'),
Salesforce18Id::ofCharity('xxxxxxxxxxxxxxxxxx'),
false,
DayOfMonth::of(1),
);
}
public static function randomString(): string
{
return (new Randomizer())->getBytesFromString('abcdef01234567890', 18);
}
public function getContainer(): ContainerInterface
{
$container = $this->getAppInstance()->getContainer();
\assert($container !== null);
return $container;
}
/**
* @return App<ContainerInterface|null>
* @throws Exception
*/
protected function getAppInstance(bool $withRealRedis = false): App
{
$memoizedInstance = $this->appInstance[(int)$withRealRedis];
if ($memoizedInstance) {
// not sure what's wrong with return type
return $memoizedInstance; // @phpstan-ignore return.type
}
// Instantiate PHP-DI ContainerBuilder
$containerBuilder = new ContainerBuilder();
// Container intentionally not compiled for tests.
// Set up dependencies
$dependencies = require __DIR__ . '/../app/dependencies.php';
$dependencies($containerBuilder);
// Set up repositories
$repositories = require __DIR__ . '/../app/repositories.php';
$repositories($containerBuilder);
// Build PHP-DI Container instance
$container = $containerBuilder->build();
$container->set(
'donation-creation-rate-limiter-factory',
new RateLimiterFactory(['id' => 'test', 'policy' => 'no_limit'], new InMemoryStorage())
);
if (!$withRealRedis) {
// For unit tests, we need to stub out Redis so that rate limiting middleware doesn't
// crash trying to actually connect to REDIS_HOST "dummy-redis-hostname".
$redisProphecy = $this->prophesize(Redis::class);
$redisProphecy->isConnected()->willReturn(true);
$redisProphecy->mget(Argument::type('array'))->willReturn([]);
// symfony/cache Redis adapter apparently does something around prepping value-setting
// through a fancy pipeline() and calls this.
$redisProphecy->multi(Argument::any())->willReturn(true);
$redisProphecy
->setex(Argument::type('string'), 3600, Argument::type('string'))
->willReturn(true);
$redisProphecy->exec()->willReturn([]); // Commits the multi() operation.
$container->set(Redis::class, $redisProphecy->reveal());
}
// By default, tests don't get a real logger.
$container->set(LoggerInterface::class, new NullLogger());
$container->set(ClockInterface::class, new class implements ClockInterface
{
#[\Override] public function sleep(float|int $seconds): never
{
throw new \Exception("Please provide fake clock for your test");
}
#[\Override] public function now(): \DateTimeImmutable
{
// This always throws but I'm using an if condition to hide that from PhpStorm. Otherwise
// PhpStorm infers the return type as `never`, finds usages of the Interface in our prod code
// and somehow assumes they're calling this anon class and complains about dead code.
if (time() !== 1) {
throw new \Exception("Please provide fake clock for your test");
}
return new \DateTimeImmutable();
}
#[\Override] public function withTimeZone(\DateTimeZone|string $timezone): never
{
throw new \Exception("Please provide fake clock for your test");
}
});
// Instantiate the app
AppFactory::setContainer($container);
$app = AppFactory::create();
// Register routes
$routes = require __DIR__ . '/../app/routes.php';
$routes($app);
$app->addRoutingMiddleware();
// not sure what's wrong with assignment here
$this->appInstance[(int) $withRealRedis] = $app; // @phpstan-ignore assign.propertyType
// not sure what's wrong with return type.
return $app; // @phpstan-ignore return.type
}
/**
* @param string $method
* @param string $path
* @param string $bodyString
* @param array<string, string> $headers
* @param array<string, string> $serverParams
* @param array<string, string> $cookies
* @return Request
*/
public static function createRequest(
string $method,
string $path,
string $bodyString = '',
array $headers = [
'HTTP_ACCEPT' => 'application/json',
'HTTP_X-Forwarded-For' => '1.2.3.4', // Simulate ALB in unit tests by default.
],
array $serverParams = [],
array $cookies = []
): Request {
$uri = new Uri('', '', 80, $path);
$handle = fopen('php://temp', 'w+');
\assert($handle !== false);
if ($bodyString === '') {
$stream = (new StreamFactory())->createStreamFromResource($handle);
} else {
$stream = (new StreamFactory())->createStream($bodyString);
}
$h = new Headers();
foreach ($headers as $name => $value) {
$h->addHeader($name, $value);
}
return new SlimRequest($method, $uri, $h, $cookies, $serverParams, $stream);
}
public static function getMinimalCampaign(): Campaign
{
$charity = self::someCharity();
$charity->setTbgClaimingGiftAid(false);
$campaign = TestCase::someCampaign(
charity: $charity
);
$campaign->setIsMatched(false);
return $campaign;
}
/**
* Returns some random charity - use if you don't care about the details or will replace them with setters later.
* Introduced to replace many old calls to instantiate Charity with zero arguments.
*
* @param Salesforce18Id<Charity>|null $salesforceId
*/
public static function someCharity(
?string $stripeAccountId = null,
?Salesforce18Id $salesforceId = null,
string $name = 'Charity Name',
?string $phoneNumber = null,
?EmailAddress $emailAddress = null,
PaymentServiceProvider $psp = PaymentServiceProvider::Stripe,
): Charity {
return new Charity(
salesforceId: $salesforceId->value ?? ('123CharityId' . self::randomHex(3)),
charityName: $name,
stripeAccountId: $psp === PaymentServiceProvider::Stripe ? ($stripeAccountId ?? "stripe-account-id-" . self::randomHex()) : null,
ryftAccountId: $psp === PaymentServiceProvider::Ryft ? RyftAccountId::of("ac_aaaaaaaa-bbbb-aaaa-bbbb-aaaaaaaaaaaa") : null,
psp: $psp,
hmrcReferenceNumber: 'H' . self::randomHex(3),
giftAidOnboardingStatus: 'Onboarded',
regulator: 'CCEW',
regulatorNumber: 'Reg-no',
time: new \DateTime('2023-10-06T18:51:27'),
emailAddress: $emailAddress,
websiteUri: 'https://charityname.com',
logoUri: 'https://some-logo-host/charityname/logo.png',
phoneNumber: $phoneNumber,
rawData: self::CAMPAIGN_FROM_SALESFORCE['charity'],
);
}
/**
* @param bool $standalone
* @param ?Salesforce18Id<Campaign> $sfId
*/
public static function someCampaign(
?string $stripeAccountId = null,
?Salesforce18Id $sfId = null,
?Charity $charity = null,
bool $isRegularGiving = false,
?\DateTimeImmutable $regularGivingCollectionEnd = null,
?string $thankYouMessage = null,
?MetaCampaignSlug $metaCampaignSlug = null,
bool $isMatched = false,
?bool $charityRejected = false,
?Money $totalFundraisingTarget = null,
?Money $withMatchFundsTotal = null,
bool $standalone = false,
): Campaign {
$randomString = (new Randomizer())->getBytesFromString('abcdef', 7);
$sfId ??= Salesforce18Id::ofCampaign('1CampaignId' . $randomString);
if ($metaCampaignSlug === null && ! $standalone) {
$metaCampaignSlug = MetaCampaignSlug::of('dummy-metacampaign-slug');
}
$campaign = new Campaign(
$sfId,
metaCampaignSlug: $metaCampaignSlug?->slug,
charity: $charity ?? self::someCharity(stripeAccountId: $stripeAccountId),
startDate: new \DateTimeImmutable('2020-01-01'),
endDate: new \DateTimeImmutable('3000-01-01'),
isMatched: $isMatched,
isPublished: true,
name: 'someCampaign',
summary: 'Some Campaign Summary',
currencyCode: 'GBP',
isRegularGiving: $isRegularGiving,
pinPosition: null,
championPagePinPosition: null,
relatedApplicationStatus: $metaCampaignSlug === null ? null : ApplicationStatus::Approved,
relatedApplicationCharityResponseToOffer: $charityRejected ? CharityResponseToOffer::Rejected : CharityResponseToOffer::Accepted,
regularGivingCollectionEnd: $regularGivingCollectionEnd,
totalFundraisingTarget: $totalFundraisingTarget ?? Money::zero(),
thankYouMessage: $thankYouMessage,
rawData: self::CAMPAIGN_FROM_SALESFORCE,
hidden: false,
);
$campaign->setTestStatistics(new CampaignStatistics(
at: new \DateTimeImmutable('2020-01-01'),
campaign: $campaign,
donationSum: Money::zero(),
amountRaised: Money::zero(),
matchFundsUsed: Money::zero(),
matchFundsTotal: $withMatchFundsTotal ?? Money::zero(),
target: Money::zero(),
));
return $campaign;
}
/**
* @param numeric-string $amount
* @param numeric-string $tipAmount
*/
public static function someDonation(
?UuidInterface $uuid = null,
string $amount = '1',
string $currencyCode = 'GBP',
PaymentMethodType $paymentMethodType = PaymentMethodType::Card,
bool $giftAid = false,
?RegularGivingMandate $regularGivingMandate = null,
?Campaign $campaign = null,
string $tipAmount = '0',
?EmailAddress $emailAddress = null,
?DonorName $donorName = null,
bool $collected = false,
?string $transferId = null,
?int $mandateSequenceNumber = null,
?string $transactionId = null,
PaymentServiceProvider $psp = \MatchBot\Domain\PaymentServiceProvider::Stripe,
\DateTimeImmutable|null $createdAt = null,
): Donation {
$donation = new Donation(
amount: $amount,
currencyCode: $currencyCode,
paymentMethodType: $paymentMethodType,
campaign: $campaign ?? self::someCampaign(null, null, null, false, null, null, null, false, false, null, null, false),
charityComms: null,
championComms: null,
pspCustomerId: null,
psp: $psp,
optInTbgEmail: null,
donorName: $donorName,
emailAddress: $emailAddress,
countryCode: null,
tipAmount: $tipAmount,
mandate: $regularGivingMandate,
mandateSequenceNumber: is_int($mandateSequenceNumber) ? DonationSequenceNumber::of($mandateSequenceNumber) : null,
donorId: PersonId::of(Uuid::NIL),
giftAid: $giftAid,
tipGiftAid: null,
homeAddress: null,
homePostcode: null,
billingPostcode: null,
);
$donation->setUuid($uuid ?? Uuid::uuid4());
if (\is_string($transactionId)) {
$donation->setTransactionId($transactionId);
}
if ($collected) {
self::collectDonation(
$donation,
$transferId,
(int) (100.0 * ((float) $amount + (float) $tipAmount))
);
}
if ($createdAt) {
$reflection = new \ReflectionClass($donation);
$createdAtProperty = $reflection->getProperty('createdAt');
$createdAtProperty->setValue($donation, \DateTime::createFromInterface($createdAt));
}
return $donation;
}
protected static function collectDonation(Donation $donationResponse, ?string $transferId = null, int $totalPaidFractional = 100): void
{
$donationResponse->collectFromStripeCharge(
chargeId: 'testchargeid_' . self::randomString(),
totalPaidFractional: $totalPaidFractional,
transferId: $transferId ?? 'test_transfer_id_' . self::randomHex(),
cardBrand: null,
cardCountry: null,
originalFeeFractional: '0',
chargeCreationTimestamp: (int)(new \DateTimeImmutable('1970-01-01'))->format('U'),
);
}
public static function someUpsertedMessage(): DonationUpserted
{
$donation = self::someDonation();
$donation->setTransactionId('pi_1234');
return DonationUpserted::fromDonation($donation);
}
/**
* @param positive-int $num_bytes
*/
private static function randomHex(int $num_bytes=8): string
{
return bin2hex(random_bytes($num_bytes));
}
public static function randomPersonId(): PersonId
{
return PersonId::of(Uuid::uuid4()->toString());
}
public function diContainer(): Container
{
$container = $this->getAppInstance()->getContainer();
\assert($container instanceof Container);
return $container;
}
public static function getSalesforceAuthValue(string $body): string
{
$salesforceSecretKey = getenv('SALESFORCE_SECRET_KEY');
\assert(is_string($salesforceSecretKey));
return hash_hmac('sha256', $body, $salesforceSecretKey);
}
public static function someMetaCampaign(bool $isRegularGiving, bool $isEmergencyIMF, ?MetaCampaignSlug $slug = null, ?\DateTimeImmutable $startDate = null): MetaCampaign
{
return new MetaCampaign(
slug: $slug ?? MetaCampaignSlug::of('not-relevant-' . TestCase::randomHex()),
salesforceId: IntegrationTest::randomSalesForce18Id(MetaCampaign::class),
title: 'not relevant ' . TestCase::randomHex(),
currency: Currency::GBP,
hidden: false,
summary: 'not relevant',
bannerURI: null,
startDate: $startDate ?? new \DateTimeImmutable('1970'),
endDate: new \DateTimeImmutable('1970'),
isRegularGiving: $isRegularGiving,
isEmergencyIMF: $isEmergencyIMF,
totalAdjustment: Money::zero(),
campaignFamily: CampaignFamily::artsforImpact,
);
}
}