SearchKit - Improve descriptions for Relationship & GroupContact joins
[civicrm-core.git] / tests / phpunit / api / v4 / Entity / ConformanceTest.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC. All rights reserved. |
6 | |
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 +--------------------------------------------------------------------+
11 */
12
13 /**
14 *
15 * @package CRM
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 */
18
19
20 namespace api\v4\Entity;
21
22 use Civi\Api4\Entity;
23 use api\v4\UnitTestCase;
24 use Civi\Api4\Utils\CoreUtil;
25
26 /**
27 * @group headless
28 */
29 class ConformanceTest extends UnitTestCase {
30
31 use \api\v4\Traits\TableDropperTrait;
32 use \api\v4\Traits\OptionCleanupTrait {
33 setUp as setUpOptionCleanup;
34 }
35
36 /**
37 * @var \api\v4\Service\TestCreationParameterProvider
38 */
39 protected $creationParamProvider;
40
41 /**
42 * Set up baseline for testing
43 */
44 public function setUp(): void {
45 $tablesToTruncate = [
46 'civicrm_case_type',
47 'civicrm_custom_group',
48 'civicrm_custom_field',
49 'civicrm_group',
50 'civicrm_event',
51 'civicrm_participant',
52 ];
53 $this->dropByPrefix('civicrm_value_myfavorite');
54 $this->cleanup(['tablesToTruncate' => $tablesToTruncate]);
55 $this->setUpOptionCleanup();
56 $this->loadDataSet('CaseType');
57 $this->loadDataSet('ConformanceTest');
58 $this->creationParamProvider = \Civi::container()->get('test.param_provider');
59 parent::setUp();
60 }
61
62 /**
63 * Get entities to test.
64 *
65 * This is the hi-tech list as generated via Civi's runtime services. It
66 * is canonical, but relies on services that may not be available during
67 * early parts of PHPUnit lifecycle.
68 *
69 * @return array
70 *
71 * @throws \API_Exception
72 * @throws \Civi\API\Exception\UnauthorizedException
73 */
74 public function getEntitiesHitech() {
75 // Ensure all components are enabled so their entities show up
76 foreach (array_keys(\CRM_Core_Component::getComponents()) as $component) {
77 \CRM_Core_BAO_ConfigSetting::enableComponent($component);
78 }
79 return $this->toDataProviderArray(Entity::get(FALSE)->execute()->column('name'));
80 }
81
82 /**
83 * Get entities to test.
84 *
85 * This is the low-tech list as generated by manual-overrides and direct inspection.
86 * It may be summoned at any time during PHPUnit lifecycle, but it may require
87 * occasional twiddling to give correct results.
88 *
89 * @return array
90 */
91 public function getEntitiesLotech() {
92 $manual['add'] = [];
93 $manual['remove'] = ['CustomValue'];
94 $manual['transform'] = ['CiviCase' => 'Case'];
95
96 $scanned = [];
97 $srcDir = dirname(__DIR__, 5);
98 foreach ((array) glob("$srcDir/Civi/Api4/*.php") as $name) {
99 $fileName = basename($name, '.php');
100 $scanned[] = $manual['transform'][$fileName] ?? $fileName;
101 }
102
103 $names = array_diff(
104 array_unique(array_merge($scanned, $manual['add'])),
105 $manual['remove']
106 );
107
108 return $this->toDataProviderArray($names);
109 }
110
111 /**
112 * Ensure that "getEntitiesLotech()" (which is the 'dataProvider') is up to date
113 * with "getEntitiesHitech()" (which is a live feed available entities).
114 */
115 public function testEntitiesProvider() {
116 $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().");
117 }
118
119 /**
120 * @param string $entity
121 * Ex: 'Contact'
122 *
123 * @dataProvider getEntitiesLotech
124 *
125 * @throws \API_Exception
126 */
127 public function testConformance($entity): void {
128 $entityClass = CoreUtil::getApiClass($entity);
129
130 $this->checkEntityInfo($entityClass);
131 $actions = $this->checkActions($entityClass);
132
133 // Go no further if it's not a CRUD entity
134 if (array_diff(['get', 'create', 'update', 'delete'], array_keys($actions))) {
135 $this->markTestSkipped("The API \"$entity\" does not implement CRUD actions");
136 }
137
138 $this->checkFields($entityClass, $entity);
139 $id = $this->checkCreation($entity, $entityClass);
140 $this->checkGet($entityClass, $id, $entity);
141 $this->checkGetCount($entityClass, $id, $entity);
142 $this->checkUpdateFailsFromCreate($entityClass, $id);
143 $this->checkWrongParamType($entityClass);
144 $this->checkDeleteWithNoId($entityClass);
145 $this->checkDeletion($entityClass, $id);
146 $this->checkPostDelete($entityClass, $id, $entity);
147 }
148
149 /**
150 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
151 */
152 protected function checkEntityInfo($entityClass): void {
153 $info = $entityClass::getInfo();
154 $this->assertNotEmpty($info['name']);
155 $this->assertNotEmpty($info['title']);
156 $this->assertNotEmpty($info['title_plural']);
157 $this->assertNotEmpty($info['type']);
158 $this->assertNotEmpty($info['description']);
159 // Bridge must be between exactly 2 entities
160 if (in_array('EntityBridge', $info['type'], TRUE)) {
161 $this->assertCount(2, $info['bridge']);
162 }
163 }
164
165 /**
166 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
167 * @param string $entity
168 *
169 * @throws \API_Exception
170 */
171 protected function checkFields($entityClass, $entity) {
172 $fields = $entityClass::getFields(FALSE)
173 ->setIncludeCustom(FALSE)
174 ->execute()
175 ->indexBy('name');
176
177 $errMsg = sprintf('%s is missing required ID field', $entity);
178 $subset = ['data_type' => 'Integer'];
179
180 $this->assertArrayHasKey('data_type', $fields['id'], $errMsg);
181 $this->assertEquals('Integer', $fields['id']['data_type']);
182 }
183
184 /**
185 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
186 *
187 * @return array
188 *
189 * @throws \API_Exception
190 */
191 protected function checkActions($entityClass): array {
192 $actions = $entityClass::getActions(FALSE)
193 ->execute()
194 ->indexBy('name');
195
196 $this->assertNotEmpty($actions);
197 return (array) $actions;
198 }
199
200 /**
201 * @param string $entity
202 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
203 *
204 * @return mixed
205 */
206 protected function checkCreation($entity, $entityClass) {
207 $requiredParams = $this->creationParamProvider->getRequired($entity);
208 $createResult = $entityClass::create()
209 ->setValues($requiredParams)
210 ->setCheckPermissions(FALSE)
211 ->execute()
212 ->first();
213
214 $this->assertArrayHasKey('id', $createResult, "create missing ID");
215 $id = $createResult['id'];
216
217 $this->assertGreaterThanOrEqual(1, $id, "$entity ID not positive");
218
219 return $id;
220 }
221
222 /**
223 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
224 * @param int $id
225 */
226 protected function checkUpdateFailsFromCreate($entityClass, $id): void {
227 $exceptionThrown = '';
228 try {
229 $entityClass::create(FALSE)
230 ->addValue('id', $id)
231 ->execute();
232 }
233 catch (\API_Exception $e) {
234 $exceptionThrown = $e->getMessage();
235 }
236 $this->assertStringContainsString('id', $exceptionThrown);
237 }
238
239 /**
240 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
241 * @param int $id
242 * @param string $entity
243 */
244 protected function checkGet($entityClass, $id, $entity) {
245 $getResult = $entityClass::get(FALSE)
246 ->addWhere('id', '=', $id)
247 ->execute();
248
249 $errMsg = sprintf('Failed to fetch a %s after creation', $entity);
250 $this->assertEquals($id, $getResult->first()['id'], $errMsg);
251 $this->assertEquals(1, $getResult->count(), $errMsg);
252 }
253
254 /**
255 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
256 * @param int $id
257 * @param string $entity
258 */
259 protected function checkGetCount($entityClass, $id, $entity): void {
260 $getResult = $entityClass::get(FALSE)
261 ->addWhere('id', '=', $id)
262 ->selectRowCount()
263 ->execute();
264 $errMsg = sprintf('%s getCount failed', $entity);
265 $this->assertEquals(1, $getResult->count(), $errMsg);
266
267 $getResult = $entityClass::get(FALSE)
268 ->selectRowCount()
269 ->execute();
270 $errMsg = sprintf('%s getCount failed', $entity);
271 $this->assertGreaterThanOrEqual(1, $getResult->count(), $errMsg);
272 }
273
274 /**
275 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
276 */
277 protected function checkDeleteWithNoId($entityClass) {
278 $exceptionThrown = '';
279 try {
280 $entityClass::delete()
281 ->execute();
282 }
283 catch (\API_Exception $e) {
284 $exceptionThrown = $e->getMessage();
285 }
286 $this->assertStringContainsString('required', $exceptionThrown);
287 }
288
289 /**
290 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
291 */
292 protected function checkWrongParamType($entityClass) {
293 $exceptionThrown = '';
294 try {
295 $entityClass::get()
296 ->setDebug('not a bool')
297 ->execute();
298 }
299 catch (\API_Exception $e) {
300 $exceptionThrown = $e->getMessage();
301 }
302 $this->assertStringContainsString('debug', $exceptionThrown);
303 $this->assertStringContainsString('type', $exceptionThrown);
304 }
305
306 /**
307 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
308 * @param int $id
309 */
310 protected function checkDeletion($entityClass, $id) {
311 $deleteResult = $entityClass::delete(FALSE)
312 ->addWhere('id', '=', $id)
313 ->execute();
314
315 // should get back an array of deleted id
316 $this->assertEquals([['id' => $id]], (array) $deleteResult);
317 }
318
319 /**
320 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
321 * @param int $id
322 * @param string $entity
323 */
324 protected function checkPostDelete($entityClass, $id, $entity) {
325 $getDeletedResult = $entityClass::get(FALSE)
326 ->addWhere('id', '=', $id)
327 ->execute();
328
329 $errMsg = sprintf('Entity "%s" was not deleted', $entity);
330 $this->assertEquals(0, count($getDeletedResult), $errMsg);
331 }
332
333 /**
334 * @param array $names
335 * List of entity names.
336 * Ex: ['Foo', 'Bar']
337 * @return array
338 * List of data-provider arguments, one for each entity-name.
339 * Ex: ['Foo' => ['Foo'], 'Bar' => ['Bar']]
340 */
341 protected function toDataProviderArray($names) {
342 sort($names);
343
344 $result = [];
345 foreach ($names as $name) {
346 $result[$name] = [$name];
347 }
348 return $result;
349 }
350
351 }