4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC. All rights reserved. |
7 | This work is published under the GNU AGPLv3 license with some |
8 | permitted exceptions and without any warranty. For full license |
9 | and copyright information, see https://civicrm.org/licensing |
10 +--------------------------------------------------------------------+
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
20 namespace api\v
4\Entity
;
22 use api\v
4\Traits\CheckAccessTrait
;
23 use api\v
4\Traits\OptionCleanupTrait
;
24 use api\v
4\Traits\TableDropperTrait
;
25 use Civi\API\Exception\UnauthorizedException
;
26 use Civi\Api4\CustomField
;
27 use Civi\Api4\CustomGroup
;
29 use api\v
4\UnitTestCase
;
30 use Civi\Api4\Event\ValidateValuesEvent
;
31 use Civi\Api4\Service\Spec\CustomFieldSpec
;
32 use Civi\Api4\Service\Spec\FieldSpec
;
33 use Civi\Api4\Utils\CoreUtil
;
34 use Civi\Core\Event\PostEvent
;
35 use Civi\Core\Event\PreEvent
;
36 use Civi\Test\HookInterface
;
41 class ConformanceTest
extends UnitTestCase
implements HookInterface
{
44 use TableDropperTrait
;
45 use OptionCleanupTrait
{
46 setUp
as setUpOptionCleanup
;
50 * @var \api\v4\Service\TestCreationParameterProvider
52 protected $creationParamProvider;
55 * Set up baseline for testing
57 public function setUp(): void
{
58 // Enable all components
59 \CRM_Core_BAO_ConfigSetting
::enableAllComponents();
60 $this->setUpOptionCleanup();
61 $this->loadDataSet('CaseType');
62 $this->loadDataSet('ConformanceTest');
63 $this->creationParamProvider
= \Civi
::container()->get('test.param_provider');
65 $this->resetCheckAccess();
69 * @throws \API_Exception
70 * @throws \Civi\API\Exception\UnauthorizedException
72 public function tearDown(): void
{
73 CustomField
::delete()->addWhere('id', '>', 0)->execute();
74 CustomGroup
::delete()->addWhere('id', '>', 0)->execute();
79 'civicrm_participant',
83 $this->cleanup(['tablesToTruncate' => $tablesToTruncate]);
88 * Get entities to test.
90 * This is the hi-tech list as generated via Civi's runtime services. It
91 * is canonical, but relies on services that may not be available during
92 * early parts of PHPUnit lifecycle.
96 * @throws \API_Exception
97 * @throws \Civi\API\Exception\UnauthorizedException
99 public function getEntitiesHitech() {
100 // Ensure all components are enabled so their entities show up
101 foreach (array_keys(\CRM_Core_Component
::getComponents()) as $component) {
102 \CRM_Core_BAO_ConfigSetting
::enableComponent($component);
104 return $this->toDataProviderArray(Entity
::get(FALSE)->execute()->column('name'));
108 * Get entities to test.
110 * This is the low-tech list as generated by manual-overrides and direct inspection.
111 * It may be summoned at any time during PHPUnit lifecycle, but it may require
112 * occasional twiddling to give correct results.
116 public function getEntitiesLotech() {
118 $manual['remove'] = ['CustomValue'];
119 $manual['transform'] = ['CiviCase' => 'Case'];
122 $srcDir = dirname(__DIR__
, 5);
123 foreach ((array) glob("$srcDir/Civi/Api4/*.php") as $name) {
124 $fileName = basename($name, '.php');
125 $scanned[] = $manual['transform'][$fileName] ??
$fileName;
129 array_unique(array_merge($scanned, $manual['add'])),
133 return $this->toDataProviderArray($names);
137 * Ensure that "getEntitiesLotech()" (which is the 'dataProvider') is up to date
138 * with "getEntitiesHitech()" (which is a live feed available entities).
140 public function testEntitiesProvider() {
141 $this->assertEquals($this->getEntitiesHitech(), $this->getEntitiesLotech(), "The lo-tech list of entities does not match the hi-tech list. You probably need to update getEntitiesLotech().");
145 * @param string $entity
148 * @dataProvider getEntitiesLotech
150 * @throws \API_Exception
152 public function testConformance(string $entity): void
{
153 $entityClass = CoreUtil
::getApiClass($entity);
155 $this->checkEntityInfo($entityClass);
156 $actions = $this->checkActions($entityClass);
158 // Go no further if it's not a CRUD entity
159 if (array_diff(['get', 'create', 'update', 'delete'], array_keys($actions))) {
160 $this->markTestSkipped("The API \"$entity\" does not implement CRUD actions");
163 $this->checkFields($entityClass, $entity);
164 $this->checkCreationDenied($entity, $entityClass);
165 $id = $this->checkCreation($entity, $entityClass);
166 $this->checkGet($entityClass, $id, $entity);
167 $this->checkGetAllowed($entityClass, $id, $entity);
168 $this->checkGetCount($entityClass, $id, $entity);
169 $this->checkUpdateFailsFromCreate($entityClass, $id);
170 $this->checkWrongParamType($entityClass);
171 $this->checkDeleteWithNoId($entityClass);
172 $this->checkDeletionDenied($entityClass, $id, $entity);
173 $this->checkDeletionAllowed($entityClass, $id, $entity);
174 $this->checkPostDelete($entityClass, $id, $entity);
178 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
180 protected function checkEntityInfo($entityClass): void
{
181 $info = $entityClass::getInfo();
182 $this->assertNotEmpty($info['name']);
183 $this->assertNotEmpty($info['title']);
184 $this->assertNotEmpty($info['title_plural']);
185 $this->assertNotEmpty($info['type']);
186 $this->assertNotEmpty($info['description']);
187 $this->assertIsArray($info['primary_key']);
188 $this->assertNotEmpty($info['primary_key']);
189 $this->assertRegExp(';^\d\.\d+$;', $info['since']);
190 $this->assertContains($info['searchable'], ['primary', 'secondary', 'bridge', 'none']);
191 // Bridge must be between exactly 2 entities
192 if (in_array('EntityBridge', $info['type'], TRUE)) {
193 $this->assertCount(2, $info['bridge']);
198 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
199 * @param string $entity
201 * @throws \API_Exception
203 protected function checkFields($entityClass, $entity) {
204 $fields = $entityClass::getFields(FALSE)
205 ->addWhere('type', '=', 'Field')
209 $errMsg = sprintf('%s is missing required ID field', $entity);
210 $subset = ['data_type' => 'Integer'];
212 $this->assertArrayHasKey('data_type', $fields['id'], $errMsg);
213 $this->assertEquals('Integer', $fields['id']['data_type']);
215 // Ensure that the getFields (FieldSpec) format is generally consistent.
216 foreach ($fields as $field) {
217 $isNotNull = function($v) {
220 $class = empty($field['custom_field_id']) ? FieldSpec
::class : CustomFieldSpec
::class;
221 $spec = (new $class($field['name'], $field['entity']))->loadArray($field, TRUE);
223 array_filter($field, $isNotNull),
224 array_filter($spec->toArray(), $isNotNull)
230 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
234 * @throws \API_Exception
236 protected function checkActions($entityClass): array {
237 $actions = $entityClass::getActions(FALSE)
241 $this->assertNotEmpty($actions);
242 return (array) $actions;
246 * @param string $entity
247 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
251 protected function checkCreation($entity, $entityClass) {
252 $isReadOnly = $this->isReadOnly($entityClass);
255 $onValidate = function(ValidateValuesEvent
$e) use (&$hookLog) {
256 $hookLog[$e->getEntityName()][$e->getActionName()] = 1 +
($hookLog[$e->getEntityName()][$e->getActionName()] ??
0);
258 \Civi
::dispatcher()->addListener('civi.api4.validate', $onValidate);
259 \Civi
::dispatcher()->addListener('civi.api4.validate::' . $entity, $onValidate);
261 $this->setCheckAccessGrants(["{$entity}::create" => TRUE]);
262 $this->assertEquals(0, $this->checkAccessCounts
["{$entity}::create"]);
264 $requiredParams = $this->creationParamProvider
->getRequired($entity);
265 $createResult = $entityClass::create()
266 ->setValues($requiredParams)
267 ->setCheckPermissions(!$isReadOnly)
271 $this->assertArrayHasKey('id', $createResult, "create missing ID");
272 $id = $createResult['id'];
273 $this->assertGreaterThanOrEqual(1, $id, "$entity ID not positive");
275 $this->assertEquals(1, $this->checkAccessCounts
["{$entity}::create"]);
277 $this->resetCheckAccess();
279 $this->assertEquals(2, $hookLog[$entity]['create']);
280 \Civi
::dispatcher()->removeListener('civi.api4.validate', $onValidate);
281 \Civi
::dispatcher()->removeListener('civi.api4.validate::' . $entity, $onValidate);
287 * @param string $entity
288 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
292 protected function checkCreationDenied($entity, $entityClass) {
293 $this->setCheckAccessGrants(["{$entity}::create" => FALSE]);
294 $this->assertEquals(0, $this->checkAccessCounts
["{$entity}::create"]);
296 $requiredParams = $this->creationParamProvider
->getRequired($entity);
299 $entityClass::create()
300 ->setValues($requiredParams)
301 ->setCheckPermissions(TRUE)
304 $this->fail("{$entityClass}::create() should throw an authorization failure.");
306 catch (UnauthorizedException
$e) {
307 // OK, expected exception
309 if (!$this->isReadOnly($entityClass)) {
310 $this->assertEquals(1, $this->checkAccessCounts
["{$entity}::create"]);
312 $this->resetCheckAccess();
316 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
319 protected function checkUpdateFailsFromCreate($entityClass, $id): void
{
320 $exceptionThrown = '';
322 $entityClass::create(FALSE)
323 ->addValue('id', $id)
326 catch (\API_Exception
$e) {
327 $exceptionThrown = $e->getMessage();
329 $this->assertStringContainsString('id', $exceptionThrown);
333 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
335 * @param string $entity
337 protected function checkGet($entityClass, $id, $entity) {
338 $getResult = $entityClass::get(FALSE)
339 ->addWhere('id', '=', $id)
342 $errMsg = sprintf('Failed to fetch a %s after creation', $entity);
343 $this->assertEquals($id, $getResult->first()['id'], $errMsg);
344 $this->assertEquals(1, $getResult->count(), $errMsg);
348 * Use a permissioned request for `get()`, with access grnted
349 * via checkAccess event.
351 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
353 * @param string $entity
355 protected function checkGetAllowed($entityClass, $id, $entity) {
356 $this->setCheckAccessGrants(["{$entity}::get" => TRUE]);
357 $getResult = $entityClass::get()
358 ->addWhere('id', '=', $id)
361 $errMsg = sprintf('Failed to fetch a %s after creation', $entity);
362 $this->assertEquals($id, $getResult->first()['id'], $errMsg);
363 $this->assertEquals(1, $getResult->count(), $errMsg);
364 $this->resetCheckAccess();
368 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
370 * @param string $entity
372 protected function checkGetCount($entityClass, $id, $entity): void
{
373 $getResult = $entityClass::get(FALSE)
374 ->addWhere('id', '=', $id)
377 $errMsg = sprintf('%s getCount failed', $entity);
378 $this->assertEquals(1, $getResult->count(), $errMsg);
380 $getResult = $entityClass::get(FALSE)
383 $this->assertGreaterThanOrEqual(1, $getResult->count(), $errMsg);
387 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
389 protected function checkDeleteWithNoId($entityClass) {
391 $entityClass::delete()
393 $this->fail("$entityClass should require ID to delete.");
395 catch (\API_Exception
$e) {
401 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
403 protected function checkWrongParamType($entityClass) {
404 $exceptionThrown = '';
407 ->setDebug('not a bool')
410 catch (\API_Exception
$e) {
411 $exceptionThrown = $e->getMessage();
413 $this->assertStringContainsString('debug', $exceptionThrown);
414 $this->assertStringContainsString('type', $exceptionThrown);
418 * Delete an entity - while having a targeted grant (hook_civirm_checkAccess).
420 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
422 * @param string $entity
424 protected function checkDeletionAllowed($entityClass, $id, $entity) {
425 $this->setCheckAccessGrants(["{$entity}::delete" => TRUE]);
426 $this->assertEquals(0, $this->checkAccessCounts
["{$entity}::delete"]);
427 $isReadOnly = $this->isReadOnly($entityClass);
429 $deleteAction = $entityClass::delete()
430 ->setCheckPermissions(!$isReadOnly)
431 ->addWhere('id', '=', $id);
433 if (property_exists($deleteAction, 'useTrash')) {
434 $deleteAction->setUseTrash(FALSE);
437 $log = $this->withPrePostLogging(function() use (&$deleteAction, &$deleteResult) {
438 $deleteResult = $deleteAction->execute();
441 // We should have emitted an event.
442 $hookEntity = ($entity === 'Contact') ?
'Individual' : $entity; /* ooph */
443 $this->assertContains("pre.{$hookEntity}.delete", $log, "$entity should emit hook_civicrm_pre() for deletions");
444 $this->assertContains("post.{$hookEntity}.delete", $log, "$entity should emit hook_civicrm_post() for deletions");
446 // should get back an array of deleted id
447 $this->assertEquals([['id' => $id]], (array) $deleteResult);
449 $this->assertEquals(1, $this->checkAccessCounts
["{$entity}::delete"]);
451 $this->resetCheckAccess();
455 * Attempt to delete an entity while having explicitly denied permission (hook_civicrm_checkAccess).
457 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
459 * @param string $entity
461 protected function checkDeletionDenied($entityClass, $id, $entity) {
462 $this->setCheckAccessGrants(["{$entity}::delete" => FALSE]);
463 $this->assertEquals(0, $this->checkAccessCounts
["{$entity}::delete"]);
466 $entityClass::delete()
467 ->addWhere('id', '=', $id)
469 $this->fail("{$entity}::delete should throw an authorization failure.");
471 catch (UnauthorizedException
$e) {
475 if (!$this->isReadOnly($entityClass)) {
476 $this->assertEquals(1, $this->checkAccessCounts
["{$entity}::delete"]);
478 $this->resetCheckAccess();
482 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
484 * @param string $entity
486 protected function checkPostDelete($entityClass, $id, $entity) {
487 $getDeletedResult = $entityClass::get(FALSE)
488 ->addWhere('id', '=', $id)
491 $errMsg = sprintf('Entity "%s" was not deleted', $entity);
492 $this->assertEquals(0, count($getDeletedResult), $errMsg);
496 * @param array $names
497 * List of entity names.
500 * List of data-provider arguments, one for each entity-name.
501 * Ex: ['Foo' => ['Foo'], 'Bar' => ['Bar']]
503 protected function toDataProviderArray($names) {
507 foreach ($names as $name) {
508 $result[$name] = [$name];
514 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
517 protected function isReadOnly($entityClass) {
518 return in_array('ReadOnly', $entityClass::getInfo()['type'], TRUE);
522 * Temporarily enable logging for `hook_civicrm_pre` and `hook_civicrm_post`.
524 * @param callable $callable
525 * Run this function. Create a log while running this function.
527 * Log; list of times the hooks were called.
528 * Ex: ['pre.Event.delete', 'post.Event.delete']
530 protected function withPrePostLogging($callable): array {
533 $listen = function ($e) use (&$log) {
534 if ($e instanceof PreEvent
) {
535 $log[] = "pre.{$e->entity}.{$e->action}";
537 elseif ($e instanceof PostEvent
) {
538 $log[] = "post.{$e->entity}.{$e->action}";
543 \Civi
::dispatcher()->addListener('hook_civicrm_pre', $listen);
544 \Civi
::dispatcher()->addListener('hook_civicrm_post', $listen);
548 \Civi
::dispatcher()->removeListener('hook_civicrm_pre', $listen);
549 \Civi
::dispatcher()->removeListener('hook_civicrm_post', $listen);