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