Merge pull request #20360 from eileenmcnaughton/ppp
[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 }
160
161 /**
162 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
163 * @param string $entity
164 *
165 * @throws \API_Exception
166 */
167 protected function checkFields($entityClass, $entity) {
168 $fields = $entityClass::getFields(FALSE)
169 ->setIncludeCustom(FALSE)
170 ->execute()
171 ->indexBy('name');
172
173 $errMsg = sprintf('%s is missing required ID field', $entity);
174 $subset = ['data_type' => 'Integer'];
175
176 $this->assertArrayHasKey('data_type', $fields['id'], $errMsg);
177 $this->assertEquals('Integer', $fields['id']['data_type']);
178 }
179
180 /**
181 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
182 *
183 * @return array
184 *
185 * @throws \API_Exception
186 */
187 protected function checkActions($entityClass): array {
188 $actions = $entityClass::getActions(FALSE)
189 ->execute()
190 ->indexBy('name');
191
192 $this->assertNotEmpty($actions);
193 return (array) $actions;
194 }
195
196 /**
197 * @param string $entity
198 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
199 *
200 * @return mixed
201 */
202 protected function checkCreation($entity, $entityClass) {
203 $requiredParams = $this->creationParamProvider->getRequired($entity);
204 $createResult = $entityClass::create()
205 ->setValues($requiredParams)
206 ->setCheckPermissions(FALSE)
207 ->execute()
208 ->first();
209
210 $this->assertArrayHasKey('id', $createResult, "create missing ID");
211 $id = $createResult['id'];
212
213 $this->assertGreaterThanOrEqual(1, $id, "$entity ID not positive");
214
215 return $id;
216 }
217
218 /**
219 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
220 * @param int $id
221 */
222 protected function checkUpdateFailsFromCreate($entityClass, $id): void {
223 $exceptionThrown = '';
224 try {
225 $entityClass::create(FALSE)
226 ->addValue('id', $id)
227 ->execute();
228 }
229 catch (\API_Exception $e) {
230 $exceptionThrown = $e->getMessage();
231 }
232 $this->assertStringContainsString('id', $exceptionThrown);
233 }
234
235 /**
236 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
237 * @param int $id
238 * @param string $entity
239 */
240 protected function checkGet($entityClass, $id, $entity) {
241 $getResult = $entityClass::get(FALSE)
242 ->addWhere('id', '=', $id)
243 ->execute();
244
245 $errMsg = sprintf('Failed to fetch a %s after creation', $entity);
246 $this->assertEquals($id, $getResult->first()['id'], $errMsg);
247 $this->assertEquals(1, $getResult->count(), $errMsg);
248 }
249
250 /**
251 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
252 * @param int $id
253 * @param string $entity
254 */
255 protected function checkGetCount($entityClass, $id, $entity): void {
256 $getResult = $entityClass::get(FALSE)
257 ->addWhere('id', '=', $id)
258 ->selectRowCount()
259 ->execute();
260 $errMsg = sprintf('%s getCount failed', $entity);
261 $this->assertEquals(1, $getResult->count(), $errMsg);
262
263 $getResult = $entityClass::get(FALSE)
264 ->selectRowCount()
265 ->execute();
266 $errMsg = sprintf('%s getCount failed', $entity);
267 $this->assertGreaterThanOrEqual(1, $getResult->count(), $errMsg);
268 }
269
270 /**
271 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
272 */
273 protected function checkDeleteWithNoId($entityClass) {
274 $exceptionThrown = '';
275 try {
276 $entityClass::delete()
277 ->execute();
278 }
279 catch (\API_Exception $e) {
280 $exceptionThrown = $e->getMessage();
281 }
282 $this->assertStringContainsString('required', $exceptionThrown);
283 }
284
285 /**
286 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
287 */
288 protected function checkWrongParamType($entityClass) {
289 $exceptionThrown = '';
290 try {
291 $entityClass::get()
292 ->setDebug('not a bool')
293 ->execute();
294 }
295 catch (\API_Exception $e) {
296 $exceptionThrown = $e->getMessage();
297 }
298 $this->assertStringContainsString('debug', $exceptionThrown);
299 $this->assertStringContainsString('type', $exceptionThrown);
300 }
301
302 /**
303 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
304 * @param int $id
305 */
306 protected function checkDeletion($entityClass, $id) {
307 $deleteResult = $entityClass::delete(FALSE)
308 ->addWhere('id', '=', $id)
309 ->execute();
310
311 // should get back an array of deleted id
312 $this->assertEquals([['id' => $id]], (array) $deleteResult);
313 }
314
315 /**
316 * @param \Civi\Api4\Generic\AbstractEntity|string $entityClass
317 * @param int $id
318 * @param string $entity
319 */
320 protected function checkPostDelete($entityClass, $id, $entity) {
321 $getDeletedResult = $entityClass::get(FALSE)
322 ->addWhere('id', '=', $id)
323 ->execute();
324
325 $errMsg = sprintf('Entity "%s" was not deleted', $entity);
326 $this->assertEquals(0, count($getDeletedResult), $errMsg);
327 }
328
329 /**
330 * @param array $names
331 * List of entity names.
332 * Ex: ['Foo', 'Bar']
333 * @return array
334 * List of data-provider arguments, one for each entity-name.
335 * Ex: ['Foo' => ['Foo'], 'Bar' => ['Bar']]
336 */
337 protected function toDataProviderArray($names) {
338 sort($names);
339
340 $result = [];
341 foreach ($names as $name) {
342 $result[$name] = [$name];
343 }
344 return $result;
345 }
346
347 }