forked from ezsystems/ezpublish-api
/
BaseTest.php
720 lines (632 loc) · 23.9 KB
/
BaseTest.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
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
<?php
/**
* File containing the BaseTest class.
*
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
*/
namespace eZ\Publish\API\Repository\Tests;
use Doctrine\DBAL\Connection;
use eZ\Publish\API\Repository\Exceptions\ContentFieldValidationException;
use eZ\Publish\API\Repository\Tests\PHPUnitConstraint\ValidationErrorOccurs as PHPUnitConstraintValidationErrorOccurs;
use eZ\Publish\API\Repository\Values\Content\Location;
use EzSystems\EzPlatformSolrSearchEngine\Tests\SetupFactory\LegacySetupFactory as LegacySolrSetupFactory;
use PHPUnit\Framework\TestCase;
use eZ\Publish\API\Repository\Repository;
use eZ\Publish\API\Repository\Values\ValueObject;
use eZ\Publish\API\Repository\Values\User\Limitation\RoleLimitation;
use eZ\Publish\API\Repository\Values\User\Limitation\SubtreeLimitation;
use eZ\Publish\API\Repository\Values\User\UserGroup;
use eZ\Publish\Core\REST\Client\Sessionable;
use DateTime;
use ArrayObject;
use Exception;
use PDOException;
/**
* Base class for api specific tests.
*/
abstract class BaseTest extends TestCase
{
/**
* Maximum integer number accepted by the different backends.
*/
const DB_INT_MAX = 2147483647;
/**
* @var \eZ\Publish\API\Repository\Tests\SetupFactory
*/
private $setupFactory;
/**
* @var \eZ\Publish\API\Repository\Repository
*/
private $repository;
protected function setUp()
{
parent::setUp();
try {
// Use setup factory instance here w/o clearing data in case test don't need to
$repository = $this->getSetupFactory()->getRepository(false);
// Set session if we are testing the REST backend to make it
// possible to persist data in the memory backend during multiple
// requests.
if ($repository instanceof Sessionable) {
$repository->setSession($id = md5(microtime()));
}
} catch (PDOException $e) {
$this->fail(
'The communication with the database cannot be established. ' .
"This is required in order to perform the tests.\n\n" .
'Exception: ' . $e
);
} catch (Exception $e) {
$this->fail(
'Cannot create a repository with predefined user. ' .
'Check the UserService or RoleService implementation. ' .
PHP_EOL . PHP_EOL .
'Exception: ' . $e
);
}
}
/**
* Resets the temporary used repository between each test run.
*/
protected function tearDown()
{
$this->repository = null;
parent::tearDown();
}
/**
* Returns the ID generator, fitting to the repository implementation.
*
* @return \eZ\Publish\API\Repository\Tests\IdManager
*/
protected function getIdManager()
{
return $this->getSetupFactory()->getIdManager();
}
/**
* Generates a repository specific ID value.
*
* @param string $type
* @param mixed $rawId
*
* @return mixed
*/
protected function generateId($type, $rawId)
{
return $this->getIdManager()->generateId($type, $rawId);
}
/**
* Parses a repository specific ID value.
*
* @param string $type
* @param mixed $id
*
* @return mixed
*/
protected function parseId($type, $id)
{
return $this->getIdManager()->parseId($type, $id);
}
/**
* Returns a config setting provided by the setup factory.
*
* @param string $configKey
*
* @return mixed
*/
protected function getConfigValue($configKey)
{
return $this->getSetupFactory()->getConfigValue($configKey);
}
/**
* Tests if the currently tested api is based on a V4 implementation.
*
* @return bool
*/
protected function isVersion4()
{
return isset($_ENV['backendVersion']) && '4' === $_ENV['backendVersion'];
}
/**
* @param bool $initialInitializeFromScratch Only has an effect if set in first call within a test
*
* @return \eZ\Publish\API\Repository\Repository
*/
protected function getRepository($initialInitializeFromScratch = true)
{
if (null === $this->repository) {
$this->repository = $this->getSetupFactory()->getRepository($initialInitializeFromScratch);
}
return $this->repository;
}
/**
* @return \eZ\Publish\API\Repository\Tests\SetupFactory
*/
protected function getSetupFactory()
{
if (null === $this->setupFactory) {
$setupClass = getenv('setupFactory');
if (false === $setupClass) {
throw new \ErrorException(
'Missing mandatory environment variable "setupFactory", this should normally be set in the relevant phpunit-integration-*.xml file and refer to a setupFactory for the given StorageEngine/SearchEngine in use'
);
}
if (false === class_exists($setupClass)) {
throw new \ErrorException(
sprintf(
'Environment variable "setupFactory" does not reference an existing class: %s. Did you forget to install an package dependency?',
$setupClass
)
);
}
$this->setupFactory = new $setupClass();
}
return $this->setupFactory;
}
/**
* Asserts that properties given in $expectedValues are correctly set in
* $actualObject.
*
* @param mixed[] $expectedValues
* @param \eZ\Publish\API\Repository\Values\ValueObject $actualObject
*/
protected function assertPropertiesCorrect(array $expectedValues, ValueObject $actualObject)
{
foreach ($expectedValues as $propertyName => $propertyValue) {
if ($propertyValue instanceof ValueObject) {
$this->assertStructPropertiesCorrect($propertyValue, $actualObject->$propertyName);
} elseif (is_array($propertyValue)) {
foreach ($propertyValue as $key => $value) {
if ($value instanceof ValueObject) {
$this->assertStructPropertiesCorrect($value, $actualObject->$propertyName[$key]);
} else {
$this->assertPropertiesEqual("$propertyName\[$key\]", $value, $actualObject->$propertyName[$key]);
}
}
} else {
$this->assertPropertiesEqual($propertyName, $propertyValue, $actualObject->$propertyName);
}
}
}
/**
* Asserts that properties given in $expectedValues are correctly set in
* $actualObject.
*
* If the property type is array, it will be sorted before comparison.
*
* @TODO: introduced because of randomly failing tests, ref: https://jira.ez.no/browse/EZP-21734
*
* @param mixed[] $expectedValues
* @param \eZ\Publish\API\Repository\Values\ValueObject $actualObject
*/
protected function assertPropertiesCorrectUnsorted(array $expectedValues, ValueObject $actualObject)
{
foreach ($expectedValues as $propertyName => $propertyValue) {
if ($propertyValue instanceof ValueObject) {
$this->assertStructPropertiesCorrect($propertyValue, $actualObject->$propertyName);
} else {
$this->assertPropertiesEqual($propertyName, $propertyValue, $actualObject->$propertyName, true);
}
}
}
/**
* Asserts all properties from $expectedValues are correctly set in
* $actualObject. Additional (virtual) properties can be asserted using
* $additionalProperties.
*
* @param \eZ\Publish\API\Repository\Values\ValueObject $expectedValues
* @param \eZ\Publish\API\Repository\Values\ValueObject $actualObject
* @param array $propertyNames
*/
protected function assertStructPropertiesCorrect(ValueObject $expectedValues, ValueObject $actualObject, array $additionalProperties = array())
{
foreach ($expectedValues as $propertyName => $propertyValue) {
if ($propertyValue instanceof ValueObject) {
$this->assertStructPropertiesCorrect($propertyValue, $actualObject->$propertyName);
} else {
$this->assertPropertiesEqual($propertyName, $propertyValue, $actualObject->$propertyName);
}
}
foreach ($additionalProperties as $propertyName) {
$this->assertPropertiesEqual($propertyName, $expectedValues->$propertyName, $actualObject->$propertyName);
}
}
/**
* @see \eZ\Publish\API\Repository\Tests\BaseTest::assertPropertiesCorrectUnsorted()
*
* @param array $items An array of scalar values
*/
private function sortItems(array &$items)
{
$sorter = function ($a, $b) {
if (!is_scalar($a) || !is_scalar($b)) {
$this->fail('Wrong usage: method ' . __METHOD__ . ' accepts only an array of scalar values');
}
return strcmp($a, $b);
};
usort($items, $sorter);
}
private function assertPropertiesEqual($propertyName, $expectedValue, $actualValue, $sortArray = false)
{
if ($expectedValue instanceof ArrayObject) {
$expectedValue = $expectedValue->getArrayCopy();
} elseif ($expectedValue instanceof DateTime) {
$expectedValue = $expectedValue->format(DateTime::RFC850);
}
if ($actualValue instanceof ArrayObject) {
$actualValue = $actualValue->getArrayCopy();
} elseif ($actualValue instanceof DateTime) {
$actualValue = $actualValue->format(DateTime::RFC850);
}
if ($sortArray && is_array($actualValue) && is_array($expectedValue)) {
$this->sortItems($actualValue);
$this->sortItems($expectedValue);
}
$this->assertEquals(
$expectedValue,
$actualValue,
sprintf('Object property "%s" incorrect.', $propertyName)
);
}
/**
* Create a user in editor user group.
*
* @param string $login
*
* @return \eZ\Publish\API\Repository\Values\User\User
*/
protected function createUserVersion1($login = 'user')
{
$repository = $this->getRepository();
/* BEGIN: Inline */
// ID of the "Editors" user group in an eZ Publish demo installation
$editorsGroupId = 13;
$userService = $repository->getUserService();
// Instantiate a create struct with mandatory properties
$userCreate = $userService->newUserCreateStruct(
$login,
"{$login}@example.com",
'secret',
'eng-US'
);
$userCreate->enabled = true;
// Set some fields required by the user ContentType
$userCreate->setField('first_name', 'Example');
$userCreate->setField('last_name', 'User');
// Load parent group for the user
$group = $userService->loadUserGroup($editorsGroupId);
// Create a new user instance.
$user = $userService->createUser($userCreate, array($group));
/* END: Inline */
return $user;
}
/**
* Create a user in new user group with editor rights limited to Media Library (/1/48/).
*
* @uses ::createCustomUserVersion1()
*
* @return \eZ\Publish\API\Repository\Values\User\User
*/
protected function createMediaUserVersion1()
{
return $this->createCustomUserVersion1(
'Media Editor',
'Editor',
new SubtreeLimitation(array('limitationValues' => array('/1/43/')))
);
}
/**
* Create a user with new user group and assign a existing role (optionally with RoleLimitation).
*
* @param string $userGroupName Name of the new user group to create
* @param string $roleIdentifier Role identifier to assign to the new group
* @param RoleLimitation|null $roleLimitation
*
* @return \eZ\Publish\API\Repository\Values\User\User
*/
protected function createCustomUserVersion1($userGroupName, $roleIdentifier, RoleLimitation $roleLimitation = null)
{
return $this->createCustomUserWithLogin(
'user',
'user@example.com',
$userGroupName,
$roleIdentifier,
$roleLimitation
);
}
/**
* Create a user with new user group and assign a existing role (optionally with RoleLimitation).
*
* @param string $login User login
* @param string $email User e-mail
* @param string $userGroupName Name of the new user group to create
* @param string $roleIdentifier Role identifier to assign to the new group
* @param RoleLimitation|null $roleLimitation
* @return \eZ\Publish\API\Repository\Values\User\User
*/
protected function createCustomUserWithLogin(
$login,
$email,
$userGroupName,
$roleIdentifier,
RoleLimitation $roleLimitation = null
) {
$repository = $this->getRepository();
/* BEGIN: Inline */
// ID of the "Users" user group in an eZ Publish demo installation
$rootUsersGroupId = $this->generateId('location', 4);
$roleService = $repository->getRoleService();
$userService = $repository->getUserService();
// Get a group create struct
$userGroupCreate = $userService->newUserGroupCreateStruct('eng-US');
$userGroupCreate->setField('name', $userGroupName);
// Create new group with media editor rights
$userGroup = $userService->createUserGroup(
$userGroupCreate,
$userService->loadUserGroup($rootUsersGroupId)
);
$roleService->assignRoleToUserGroup(
$roleService->loadRoleByIdentifier($roleIdentifier),
$userGroup,
$roleLimitation
);
// Instantiate a create struct with mandatory properties
$userCreate = $userService->newUserCreateStruct(
$login,
$email,
'secret',
'eng-US'
);
$userCreate->enabled = true;
// Set some fields required by the user ContentType
$userCreate->setField('first_name', 'Example');
$userCreate->setField('last_name', ucfirst($login));
// Create a new user instance.
$user = $userService->createUser($userCreate, array($userGroup));
/* END: Inline */
return $user;
}
/**
* Create a user using given data.
*
* @param string $login
* @param string $firstName
* @param string $lastName
* @param \eZ\Publish\API\Repository\Values\User\UserGroup|null $userGroup optional user group, Editor by default
*
* @return \eZ\Publish\API\Repository\Values\User\User
*/
protected function createUser($login, $firstName, $lastName, UserGroup $userGroup = null)
{
$repository = $this->getRepository();
$userService = $repository->getUserService();
if (null === $userGroup) {
$userGroup = $userService->loadUserGroup(13);
}
// Instantiate a create struct with mandatory properties
$userCreate = $userService->newUserCreateStruct(
$login,
"{$login}@example.com",
'secret',
'eng-US'
);
$userCreate->enabled = true;
// Set some fields required by the user ContentType
$userCreate->setField('first_name', $firstName);
$userCreate->setField('last_name', $lastName);
// Create a new user instance.
$user = $userService->createUser($userCreate, array($userGroup));
return $user;
}
/**
* Only for internal use.
*
* Creates a \DateTime object for $timestamp in the current time zone
*
* @param int $timestamp
*
* @return \DateTime
*/
public function createDateTime($timestamp = null)
{
$dateTime = new \DateTime();
if ($timestamp !== null) {
$dateTime->setTimestamp($timestamp);
}
return $dateTime;
}
/**
* Calls given Repository's aggregated SearchHandler::refresh().
*
* Currently implemented only in Solr search engine.
*
* @param \eZ\Publish\API\Repository\Repository $repository
*/
protected function refreshSearch(Repository $repository)
{
$setupFactory = $this->getSetupFactory();
if (!$setupFactory instanceof LegacySolrSetupFactory) {
return;
}
while (true) {
$repositoryReflection = new \ReflectionObject($repository);
// If the repository is decorated, we need to recurse in the "repository" property
if (!$repositoryReflection->hasProperty('repository')) {
break;
}
$repositoryProperty = $repositoryReflection->getProperty('repository');
$repositoryProperty->setAccessible(true);
$repository = $repositoryProperty->getValue($repository);
}
$searchHandlerProperty = new \ReflectionProperty($repository, 'searchHandler');
$searchHandlerProperty->setAccessible(true);
/** @var \EzSystems\EzPlatformSolrSearchEngine\Handler $searchHandler */
$searchHandler = $searchHandlerProperty->getValue($repository);
$searchHandler->commit();
}
/**
* Create role of a given name with the given policies described by an array.
*
* @param $roleName
* @param array $policiesData [['module' => 'content', 'function' => 'read', 'limitations' => []]
*
* @return \eZ\Publish\API\Repository\Values\User\Role
*
* @throws \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
* @throws \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
* @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException
* @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException
*/
public function createRoleWithPolicies($roleName, array $policiesData)
{
$repository = $this->getRepository(false);
$roleService = $repository->getRoleService();
$roleCreateStruct = $roleService->newRoleCreateStruct($roleName);
foreach ($policiesData as $policyData) {
$policyCreateStruct = $roleService->newPolicyCreateStruct(
$policyData['module'],
$policyData['function']
);
if (isset($policyData['limitations'])) {
foreach ($policyData['limitations'] as $limitation) {
$policyCreateStruct->addLimitation($limitation);
}
}
$roleCreateStruct->addPolicy($policyCreateStruct);
}
$roleDraft = $roleService->createRole($roleCreateStruct);
$roleService->publishRoleDraft($roleDraft);
return $roleService->loadRole($roleDraft->id);
}
/**
* Create user and assign new role with the given policies.
*
* @param string $login
* @param array $policiesData list of policies in the form of <code>[ [ 'module' => 'name', 'function' => 'name'] ]</code>
*
* @return \eZ\Publish\API\Repository\Values\User\User
*
* @throws \Exception
*/
public function createUserWithPolicies($login, array $policiesData)
{
$repository = $this->getRepository(false);
$roleService = $repository->getRoleService();
$userService = $repository->getUserService();
$repository->beginTransaction();
try {
$userCreateStruct = $userService->newUserCreateStruct(
$login,
"{$login}@test.local",
$login,
'eng-GB'
);
$userCreateStruct->setField('first_name', $login);
$userCreateStruct->setField('last_name', $login);
$user = $userService->createUser($userCreateStruct, [$userService->loadUserGroup(4)]);
$role = $this->createRoleWithPolicies(uniqid('role_for_' . $login . '_'), $policiesData);
$roleService->assignRoleToUser($role, $user);
$repository->commit();
return $user;
} catch (\Exception $ex) {
$repository->rollback();
throw $ex;
}
}
/**
* @return \Doctrine\DBAL\Connection
*
* @throws \ErrorException
*/
protected function getRawDatabaseConnection()
{
$connection = $this
->getSetupFactory()
->getServiceContainer()->get('ezpublish.api.storage_engine.legacy.connection');
if (!$connection instanceof Connection) {
throw new \RuntimeException(
sprintf('Expected %s got %s', Connection::class, get_class($connection))
);
}
return $connection;
}
/**
* Executes the given callback passing raw Database Connection (\Doctrine\DBAL\Connection).
* Returns the result returned by the given callback.
*
* **Note**: The method clears the entire persistence cache pool.
*
* @throws \Exception
*
* @param callable $callback
*
* @return mixed the return result of the given callback
*/
public function performRawDatabaseOperation(callable $callback)
{
$repository = $this->getRepository(false);
$repository->beginTransaction();
try {
$callback(
$this->getRawDatabaseConnection()
);
$repository->commit();
} catch (Exception $e) {
$repository->rollback();
throw $e;
}
/** @var \Symfony\Component\Cache\Adapter\TagAwareAdapterInterface $cachePool */
$cachePool = $this
->getSetupFactory()
->getServiceContainer()->get('ezpublish.cache_pool');
$cachePool->clear();
}
/**
* Traverse all errors for all fields in all Translations to find expected one.
*
* @param \eZ\Publish\API\Repository\Exceptions\ContentFieldValidationException $exception
* @param string $expectedValidationErrorMessage
*/
protected function assertValidationErrorOccurs(
ContentFieldValidationException $exception,
$expectedValidationErrorMessage
) {
$constraint = new PHPUnitConstraintValidationErrorOccurs($expectedValidationErrorMessage);
self::assertThat($exception, $constraint);
}
/**
* Create 'folder' Content.
*
* @param array $names Folder names in the form of <code>['<language_code>' => '<name>']</code>
* @param int $parentLocationId
*
* @return \eZ\Publish\API\Repository\Values\Content\Content published Content
*
* @throws \eZ\Publish\API\Repository\Exceptions\ForbiddenException
* @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException
* @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException
*/
protected function createFolder(array $names, $parentLocationId)
{
$repository = $this->getRepository(false);
$contentService = $repository->getContentService();
$contentTypeService = $repository->getContentTypeService();
$locationService = $repository->getLocationService();
if (empty($names)) {
throw new \RuntimeException(sprintf('%s expects non-empty names list', __METHOD__));
}
$mainLanguageCode = array_keys($names)[0];
$struct = $contentService->newContentCreateStruct(
$contentTypeService->loadContentTypeByIdentifier('folder'),
$mainLanguageCode
);
foreach ($names as $languageCode => $translatedName) {
$struct->setField('name', $translatedName, $languageCode);
}
$contentDraft = $contentService->createContent(
$struct,
[$locationService->newLocationCreateStruct($parentLocationId)]
);
return $contentService->publishVersion($contentDraft->versionInfo);
}
}