Merge pull request #4764 from rohankatkar/CRM-15615
[civicrm-core.git] / tests / phpunit / api / v3 / AttachmentTest.php
CommitLineData
56154d36
TO
1<?php
2/**
3 * api_v3_AttachmentTest
4 *
5 * @copyright Copyright CiviCRM LLC (C) 2014
6 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html
7 * GNU Affero General Public License version 3
8 * @version $Id: ContactTest.php 31254 2010-12-15 10:09:29Z eileen $
9 * @package CiviCRM
10 *
11 * This file is part of CiviCRM
12 *
13 * CiviCRM is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU Affero General Public License
15 * as published by the Free Software Foundation; either version 3 of
16 * the License, or (at your option) any later version.
17 *
18 * CiviCRM is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU Affero General Public License for more details.
22 *
23 * You should have received a copy of the GNU Affero General Public
24 * License along with this program. If not, see
25 * <http://www.gnu.org/licenses/>.
26 */
27
28/**
29 * Include class definitions
30 */
31require_once 'CiviTest/CiviUnitTestCase.php';
32
33
34/**
35 * Test for the Attachment API
36 *
37 * @package CiviCRM_APIv3
38 * @subpackage API_Contact
39 */
40class api_v3_AttachmentTest extends CiviUnitTestCase {
41 protected static $filePrefix = NULL;
42
43 public static function getFilePrefix() {
44 if (!self::$filePrefix) {
45 self::$filePrefix = "test_" . CRM_Utils_String::createRandom(5, CRM_Utils_String::ALPHANUMERIC) . '_';
46 }
47 return self::$filePrefix;
48 }
49
50
51 protected function setUp() {
52 parent::setUp();
53 $this->useTransaction(TRUE);
54
55 $this->cleanupFiles();
56 file_put_contents($this->tmpFile('mytest.txt'), 'This comes from a file');
57 }
58
59 protected function tearDown() {
60 parent::tearDown();
61 $this->cleanupFiles();
62 \Civi\Core\Container::singleton(TRUE);
63 }
64
65 public function okCreateProvider() {
66 $cases = array(); // array($entityClass, $createParams, $expectedContent)
67
68 $cases[] = array(
69 'CRM_Activity_DAO_Activity',
70 array(
71 'name' => self::getFilePrefix() . 'exampleFromContent.txt',
72 'mime_type' => 'text/plain',
73 'description' => 'My test description',
74 'content' => 'My test content',
75 ),
76 'My test content',
77 );
78
79 $cases[] = array(
80 'CRM_Activity_DAO_Activity',
81 array(
82 'name' => self::getFilePrefix() . 'exampleWithEmptyContent.txt',
83 'mime_type' => 'text/plain',
84 'description' => 'My test description',
85 'content' => '',
86 ),
87 '',
88 );
89
90 $cases[] = array(
91 'CRM_Activity_DAO_Activity',
92 array(
93 'name' => self::getFilePrefix() . 'exampleFromMove.txt',
94 'mime_type' => 'text/plain',
95 'description' => 'My test description',
96 'options' => array(
97 'move-file' => $this->tmpFile('mytest.txt'),
98 )
99 ),
100 'This comes from a file',
101 );
102
103 return $cases;
104 }
105
106 public function badCreateProvider() {
107 $cases = array(); // array($entityClass, $createParams, $expectedError)
108
109 $cases[] = array(
110 'CRM_Activity_DAO_Activity',
111 array(
112 'id' => 12345,
113 'name' => self::getFilePrefix() . 'exampleFromContent.txt',
114 'mime_type' => 'text/plain',
115 'description' => 'My test description',
116 'content' => 'My test content',
117 ),
118 '/Invalid ID/',
119 );
120 $cases[] = array(
121 'CRM_Activity_DAO_Activity',
122 array(
123 'name' => self::getFilePrefix() . 'failedExample.txt',
124 'mime_type' => 'text/plain',
125 'description' => 'My test description',
126 ),
127 "/Mandatory key\\(s\\) missing from params array: 'id' or 'content' or 'options.move-file'/",
128 );
129 $cases[] = array(
130 'CRM_Activity_DAO_Activity',
131 array(
132 'name' => self::getFilePrefix() . 'failedExample.txt',
133 'mime_type' => 'text/plain',
134 'description' => 'My test description',
135 'content' => 'too much content',
136 'options' => array(
137 'move-file' => $this->tmpFile('too-much.txt')
138 ),
139 ),
140 "/'content' and 'options.move-file' are mutually exclusive/",
141 );
142 $cases[] = array(
143 'CRM_Activity_DAO_Activity',
144 array(
145 'name' => 'inv/alid.txt',
146 'mime_type' => 'text/plain',
147 'description' => 'My test description',
148 'content' => 'My test content',
149 ),
150 "/Malformed name/",
151 );
152 $cases[] = array(
153 'CRM_Core_DAO_Domain',
154 array(
155 'name' => self::getFilePrefix() . 'exampleFromContent.txt',
156 'mime_type' => 'text/plain',
157 'description' => 'My test description',
158 'content' => 'My test content',
159 ),
160 "/Unrecognized target entity/",
161 );
162
163 return $cases;
164 }
165
166 public function badUpdateProvider() {
167 $cases = array(); // array($entityClass, $createParams, $updateParams, $expectedError)
168
169 $readOnlyFields = array(
170 'name' => 'newname.txt',
171 'entity_table' => 'civicrm_domain',
172 'entity_id' => 5,
173 'upload_date' => '2010-11-12 13:14:15',
174 );
175 foreach ($readOnlyFields as $readOnlyField => $newValue) {
176 $cases[] = array(
177 'CRM_Activity_DAO_Activity',
178 array(
179 'name' => self::getFilePrefix() . 'exampleFromContent.txt',
180 'mime_type' => 'text/plain',
181 'description' => 'My test description',
182 'content' => 'My test content',
183 ),
184 array(
185 'check_permissions' => 1,
186 $readOnlyField => $newValue,
187 ),
188 "/Cannot modify $readOnlyField/"
189 );
190 }
191
192 return $cases;
193 }
194
195 public function okGetProvider() {
196 $cases = array(); // array($getParams, $expectedNames)
197
198 // Each search runs in a DB which contains these attachments:
199 // Activity #123: example_123.txt (text/plain) and example_123.csv (text/csv)
200 // Activity #456: example_456.txt (text/plain) and example_456.csv (text/csv)
201
202 $cases[] = array(
203 array('entity_table' => 'civicrm_activity'),
204 array(
205 self::getFilePrefix() . 'example_123.csv',
206 self::getFilePrefix() . 'example_123.txt',
207 self::getFilePrefix() . 'example_456.csv',
208 self::getFilePrefix() . 'example_456.txt',
209 ),
210 );
211 $cases[] = array(
212 array('entity_table' => 'civicrm_activity', 'mime_type' => 'text/plain'),
213 array(self::getFilePrefix() . 'example_123.txt', self::getFilePrefix() . 'example_456.txt'),
214 );
215 $cases[] = array(
216 array('entity_table' => 'civicrm_activity', 'entity_id' => '123'),
217 array(self::getFilePrefix() . 'example_123.txt', self::getFilePrefix() . 'example_123.csv'),
218 );
219 $cases[] = array(
220 array('entity_table' => 'civicrm_activity', 'entity_id' => '456'),
221 array(self::getFilePrefix() . 'example_456.txt', self::getFilePrefix() . 'example_456.csv'),
222 );
223 $cases[] = array(
224 array('entity_table' => 'civicrm_activity', 'entity_id' => '456', 'mime_type' => 'text/csv'),
225 array(self::getFilePrefix() . 'example_456.csv'),
226 );
227 $cases[] = array(
228 array('entity_table' => 'civicrm_activity', 'entity_id' => '456', 'mime_type' => 'text/html'),
229 array(),
230 );
231 $cases[] = array(
232 array('entity_table' => 'civicrm_activity', 'entity_id' => '999'),
233 array(),
234 );
235
236 return $cases;
237 }
238
239 public function badGetProvider() {
240 $cases = array(); // array($getParams, $expectedNames)
241
242 // Each search runs in a DB which contains these attachments:
243 // Activity #123: example_123.txt (text/plain) and example_123.csv (text/csv)
244 // Activity #456: example_456.txt (text/plain) and example_456.csv (text/csv)
245
246 $cases[] = array(
247 array('check_permissions' => 1, 'mime_type' => 'text/plain'),
248 "/Mandatory key\\(s\\) missing from params array: 'id' or 'entity_table'/",
249 );
250 $cases[] = array(
251 array('check_permissions' => 1, 'entity_id' => '123'),
252 "/Mandatory key\\(s\\) missing from params array: 'id' or 'entity_table'/",
253 );
254 $cases[] = array(
255 array('check_permissions' => 1),
256 "/Mandatory key\\(s\\) missing from params array: 'id' or 'entity_table'/",
257 );
258 $cases[] = array(
259 array('entity_table' => 'civicrm_activity', 'name' => 'example_456.csv'),
260 "/Get by name is not currently supported/",
261 );
262 $cases[] = array(
263 array('entity_table' => 'civicrm_activity', 'content' => 'test'),
264 "/Get by content is not currently supported/",
265 );
266 $cases[] = array(
267 array('entity_table' => 'civicrm_activity', 'path' => '/home/foo'),
268 "/Get by path is not currently supported/",
269 );
270 $cases[] = array(
271 array('entity_table' => 'civicrm_activity', 'url' => '/index.php'),
272 "/Get by url is not currently supported/",
273 );
274
275 return $cases;
276 }
277
278 /**
279 * Create an attachment using "content" and then "get" the attachment
280 *
281 * @param string $testEntityClass e.g. "CRM_Core_DAO_Activity"
282 * @param array $createParams
283 * @param string $expectedContent
284 * @dataProvider okCreateProvider
285 */
286 public function testCreate($testEntityClass, $createParams, $expectedContent) {
287 $entity = CRM_Core_DAO::createTestObject($testEntityClass);
288 $entity_table = CRM_Core_DAO_AllCoreTables::getTableForClass($testEntityClass);
289 $this->assertTrue(is_numeric($entity->id));
290
291 $createResult = $this->callAPISuccess('Attachment', 'create', $createParams + array(
292 'entity_table' => $entity_table,
293 'entity_id' => $entity->id,
294 ));
295 $fileId = $createResult['id'];
296 $this->assertTrue(is_numeric($fileId));
297 $this->assertEquals($entity_table, $createResult['values'][$fileId]['entity_table']);
298 $this->assertEquals($entity->id, $createResult['values'][$fileId]['entity_id']);
299 $this->assertEquals('My test description', $createResult['values'][$fileId]['description']);
300 $this->assertRegExp('/\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d/', $createResult['values'][$fileId]['upload_date']);
301 $this->assertTrue(!isset($createResult['values'][$fileId]['content']));
302 $this->assertTrue(!empty($createResult['values'][$fileId]['url']));
303 $this->assertAttachmentExistence(TRUE, $createResult);
304
305 $getResult = $this->callAPISuccess('Attachment', 'get', array(
306 'entity_table' => $entity_table,
307 'entity_id' => $entity->id,
308 ));
309 $this->assertEquals(1, $getResult['count']);
310 foreach (array('id', 'entity_table', 'entity_id', 'url') as $field) {
311 $this->assertEquals($createResult['values'][$fileId][$field], $getResult['values'][$fileId][$field], "Expect field $field to match");
312 }
313 $this->assertTrue(!isset($getResult['values'][$fileId]['content']));
314
315 $getResult2 = $this->callAPISuccess('Attachment', 'get', array(
316 'entity_table' => $entity_table,
317 'entity_id' => $entity->id,
318 'return' => array('content'),
319 ));
320 $this->assertEquals($expectedContent, $getResult2['values'][$fileId]['content']);
321 foreach (array('id', 'entity_table', 'entity_id', 'url') as $field) {
322 $this->assertEquals($createResult['values'][$fileId][$field], $getResult['values'][$fileId][$field], "Expect field $field to match");
323 }
324 }
325
326 /**
327 * @param $testEntityClass
328 * @param $createParams
329 * @param $expectedError
330 * @dataProvider badCreateProvider
331 */
332 public function testCreateFailure($testEntityClass, $createParams, $expectedError) {
333 $entity = CRM_Core_DAO::createTestObject($testEntityClass);
334 $entity_table = CRM_Core_DAO_AllCoreTables::getTableForClass($testEntityClass);
335 $this->assertTrue(is_numeric($entity->id));
336
337 $createResult = $this->callAPIFailure('Attachment', 'create', $createParams + array(
338 'entity_table' => $entity_table,
339 'entity_id' => $entity->id,
340 ));
341 $this->assertRegExp($expectedError, $createResult['error_message']);
342 }
343
344 /**
345 * @param $testEntityClass
346 * @param $createParams
347 * @param $updateParams
348 * @param $expectedError
349 * @dataProvider badUpdateProvider
350 */
351 public function testCreateWithBadUpdate($testEntityClass, $createParams, $updateParams, $expectedError) {
352 $entity = CRM_Core_DAO::createTestObject($testEntityClass);
353 $entity_table = CRM_Core_DAO_AllCoreTables::getTableForClass($testEntityClass);
354 $this->assertTrue(is_numeric($entity->id));
355
356 $createResult = $this->callAPISuccess('Attachment', 'create', $createParams + array(
357 'entity_table' => $entity_table,
358 'entity_id' => $entity->id,
359 ));
360 $fileId = $createResult['id'];
361 $this->assertTrue(is_numeric($fileId));
362
363 $updateResult = $this->callAPIFailure('Attachment', 'create', $updateParams + array(
364 'id' => $fileId,
365 ));
366 $this->assertRegExp($expectedError, $updateResult['error_message']);
367 }
368
369 /**
370 * If one submits a weird file name, it should be automatically converted
371 * to something safe.
372 */
373 public function testCreateWithWeirdName() {
374 $entity = CRM_Core_DAO::createTestObject('CRM_Activity_DAO_Activity');
375 $this->assertTrue(is_numeric($entity->id));
376
377 $createResult = $this->callAPISuccess('Attachment', 'create', array(
378 'name' => self::getFilePrefix() . 'weird:na"me.txt',
379 'mime_type' => 'text/plain',
380 'description' => 'My test description',
381 'content' => 'My test content',
382 'entity_table' => 'civicrm_activity',
383 'entity_id' => $entity->id,
384 ));
385 $fileId = $createResult['id'];
386 $this->assertTrue(is_numeric($fileId));
387 $this->assertEquals(self::getFilePrefix() . 'weird_na_me.txt', $createResult['values'][$fileId]['name']);
388 }
389
390 /**
391 * @param $getParams
392 * @param $expectedNames
393 * @dataProvider okGetProvider
394 */
395 public function testGet($getParams, $expectedNames) {
396 foreach (array(123, 456) as $entity_id) {
397 foreach (array('text/plain' => '.txt', 'text/csv' => '.csv') as $mime => $ext) {
398 $this->callAPISuccess('Attachment', 'create', array(
399 'name' => self::getFilePrefix() . 'example_' . $entity_id . $ext,
400 'mime_type' => $mime,
401 'description' => 'My test description',
402 'content' => 'My test content',
403 'entity_table' => 'civicrm_activity',
404 'entity_id' => $entity_id,
405 ));
406 }
407 }
408
409 $getResult = $this->callAPISuccess('Attachment', 'get', $getParams);
410 $actualNames = array_values(CRM_Utils_Array::collect('name', $getResult['values']));
411 sort($actualNames);
412 sort($expectedNames);
413 $this->assertEquals($expectedNames, $actualNames);
414 }
415
416 /**
417 * @param $getParams
418 * @param $expectedError
419 * @dataProvider badGetProvider
420 */
421 public function testGetError($getParams, $expectedError) {
422 foreach (array(123, 456) as $entity_id) {
423 foreach (array('text/plain' => '.txt', 'text/csv' => '.csv') as $mime => $ext) {
424 $this->callAPISuccess('Attachment', 'create', array(
425 'name' => self::getFilePrefix() . 'example_' . $entity_id . $ext,
426 'mime_type' => $mime,
427 'description' => 'My test description',
428 'content' => 'My test content',
429 'entity_table' => 'civicrm_activity',
430 'entity_id' => $entity_id,
431 ));
432 }
433 }
434
435 $getResult = $this->callAPIFailure('Attachment', 'get', $getParams);
436 $this->assertRegExp($expectedError, $getResult['error_message']);
437 }
438
439 /**
440 * Take the values from a "get", make a small change, and then send
441 * the full thing back in as an update ("create"). This ensures some
442 * consistency in the acceptable formats.
443 */
444 public function testGetThenUpdate() {
445 $entity = CRM_Core_DAO::createTestObject('CRM_Activity_DAO_Activity');
446 $this->assertTrue(is_numeric($entity->id));
447
448 $createResult = $this->callAPISuccess('Attachment', 'create', array(
449 'name' => self::getFilePrefix() . 'getThenUpdate.txt',
450 'mime_type' => 'text/plain',
451 'description' => 'My test description',
452 'content' => 'My test content',
453 'entity_table' => 'civicrm_activity',
454 'entity_id' => $entity->id,
455 ));
456 $fileId = $createResult['id'];
457 $this->assertTrue(is_numeric($fileId));
458 $this->assertEquals(self::getFilePrefix() . 'getThenUpdate.txt', $createResult['values'][$fileId]['name']);
459 $this->assertAttachmentExistence(TRUE, $createResult);
460
461 $getResult = $this->callAPISuccess('Attachment', 'get', array(
462 'id' => $fileId,
463 ));
464 $this->assertTrue(is_array($getResult['values'][$fileId]));
465
466 $updateParams = $getResult['values'][$fileId];
467 $updateParams['description'] = 'new description';
468 $this->callAPISuccess('Attachment', 'create', $updateParams);
469 $this->assertAttachmentExistence(TRUE, $createResult);
470 }
471
472 /**
473 * Create an attachment and delete using its ID. Assert that the records are correctly created and destroyed
474 * in the DB and the filesystem.
475 */
476 public function testDeleteByID() {
477 $entity = CRM_Core_DAO::createTestObject('CRM_Activity_DAO_Activity');
478 $this->assertTrue(is_numeric($entity->id));
479
480 foreach (array('first', 'second') as $n) {
481 $createResults[$n] = $this->callAPISuccess('Attachment', 'create', array(
482 'name' => self::getFilePrefix() . 'testDeleteByID.txt',
483 'mime_type' => 'text/plain',
484 'content' => 'My test content',
485 'entity_table' => 'civicrm_activity',
486 'entity_id' => $entity->id,
487 ));
488 $this->assertTrue(is_numeric($createResults[$n]['id']));
489 $this->assertEquals(self::getFilePrefix() . 'testDeleteByID.txt', $createResults[$n]['values'][$createResults[$n]['id']]['name']);
490 }
491 $this->assertAttachmentExistence(TRUE, $createResults['first']);
492 $this->assertAttachmentExistence(TRUE, $createResults['second']);
493
494 $this->callAPISuccess('Attachment', 'delete', array(
495 'id' => $createResults['first']['id'],
496 ));
497 $this->assertAttachmentExistence(FALSE, $createResults['first']);
498 $this->assertAttachmentExistence(TRUE, $createResults['second']);
499 }
500
501 /**
502 * Create an attachment and delete using its ID. Assert that the records are correctly created and destroyed
503 * in the DB and the filesystem.
504 */
505 public function testDeleteByEntity() {
506 // create 2 entities (keepme,delme) -- each with 2 attachments (first,second)
507 foreach (array('keepme', 'delme') as $e) {
508 $entities[$e] = CRM_Core_DAO::createTestObject('CRM_Activity_DAO_Activity');
509 $this->assertTrue(is_numeric($entities[$e]->id));
510 foreach (array('first', 'second') as $n) {
511 $createResults[$e][$n] = $this->callAPISuccess('Attachment', 'create', array(
512 'name' => self::getFilePrefix() . 'testDeleteByEntity.txt',
513 'mime_type' => 'text/plain',
514 'content' => 'My test content',
515 'entity_table' => 'civicrm_activity',
516 'entity_id' => $entities[$e]->id,
517 ));
518 $this->assertTrue(is_numeric($createResults[$e][$n]['id']));
519 }
520 }
521 $this->assertAttachmentExistence(TRUE, $createResults['keepme']['first']);
522 $this->assertAttachmentExistence(TRUE, $createResults['keepme']['second']);
523 $this->assertAttachmentExistence(TRUE, $createResults['delme']['first']);
524 $this->assertAttachmentExistence(TRUE, $createResults['delme']['second']);
525
526 $this->callAPISuccess('Attachment', 'delete', array(
527 'entity_table' => 'civicrm_activity',
528 'entity_id' => $entities[$e]->id,
529 ));
530 $this->assertAttachmentExistence(TRUE, $createResults['keepme']['first']);
531 $this->assertAttachmentExistence(TRUE, $createResults['keepme']['second']);
532 $this->assertAttachmentExistence(FALSE, $createResults['delme']['first']);
533 $this->assertAttachmentExistence(FALSE, $createResults['delme']['second']);
534 }
535
536 protected function assertAttachmentExistence($exists, $apiResult) {
537 $fileId = $apiResult['id'];
538 $this->assertTrue(is_numeric($fileId));
539 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
540 $this->assertDBQuery($exists ? 1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
541 1 => array($fileId, 'Int')
542 ));
543 $this->assertDBQuery($exists ? 1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
544 1 => array($fileId, 'Int')
545 ));
546 }
547
548 protected function tmpFile($name) {
549 $tmpDir = sys_get_temp_dir();
550 $this->assertTrue($tmpDir && is_dir($tmpDir), 'Tmp dir must exist: ' . $tmpDir);
551 return $tmpDir . '/' . self::getFilePrefix() . $name;
552 }
553
554 protected function cleanupFiles() {
555 $config = CRM_Core_Config::singleton();
556 $dirs = array(
557 sys_get_temp_dir(),
558 $config->customFileUploadDir,
559 );
560 foreach ($dirs as $dir) {
561 $files = (array) glob($dir . "/" . self::getFilePrefix() . "*");
562 foreach ($files as $file) {
563 unlink($file);
564 }
565
566 }
567 }
568}