forked from ezsystems/ezpublish-kernel
/
BaseTest.php
501 lines (438 loc) · 15.8 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
<?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 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\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) {
if (false === isset($_ENV['setupFactory'])) {
throw new \ErrorException(
'Missing mandatory setting $_ENV["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'
);
}
$setupClass = $_ENV['setupFactory'];
if (false === class_exists($setupClass)) {
throw new \ErrorException(
sprintf(
'$_ENV["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) {
$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) {
$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) {
$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
* @return \eZ\Publish\API\Repository\Values\User\User
*/
protected function createUser($login, $firstName, $lastName)
{
$repository = $this->getRepository();
$userService = $repository->getUserService();
$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();
}
}