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