3 * api_v3_AttachmentTest
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 $
11 * This file is part of CiviCRM
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.
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.
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/>.
29 * Include class definitions
31 require_once 'CiviTest/CiviUnitTestCase.php';
35 * Test for the Attachment API
37 * @package CiviCRM_APIv3
38 * @subpackage API_Contact
40 class api_v3_AttachmentTest
extends CiviUnitTestCase
{
41 protected static $filePrefix = NULL;
46 public static function getFilePrefix() {
47 if (!self
::$filePrefix) {
48 self
::$filePrefix = "test_" . CRM_Utils_String
::createRandom(5, CRM_Utils_String
::ALPHANUMERIC
) . '_';
50 return self
::$filePrefix;
54 protected function setUp() {
56 $this->useTransaction(TRUE);
58 $this->cleanupFiles();
59 file_put_contents($this->tmpFile('mytest.txt'), 'This comes from a file');
62 protected function tearDown() {
64 $this->cleanupFiles();
65 \Civi\Core\Container
::singleton(TRUE);
71 public function okCreateProvider() {
72 $cases = array(); // array($entityClass, $createParams, $expectedContent)
75 'CRM_Activity_DAO_Activity',
77 'name' => self
::getFilePrefix() . 'exampleFromContent.txt',
78 'mime_type' => 'text/plain',
79 'description' => 'My test description',
80 'content' => 'My test content',
86 'CRM_Activity_DAO_Activity',
88 'name' => self
::getFilePrefix() . 'exampleWithEmptyContent.txt',
89 'mime_type' => 'text/plain',
90 'description' => 'My test description',
97 'CRM_Activity_DAO_Activity',
99 'name' => self
::getFilePrefix() . 'exampleFromMove.txt',
100 'mime_type' => 'text/plain',
101 'description' => 'My test description',
103 'move-file' => $this->tmpFile('mytest.txt'),
106 'This comes from a file',
115 public function badCreateProvider() {
116 $cases = array(); // array($entityClass, $createParams, $expectedError)
119 'CRM_Activity_DAO_Activity',
122 'name' => self
::getFilePrefix() . 'exampleFromContent.txt',
123 'mime_type' => 'text/plain',
124 'description' => 'My test description',
125 'content' => 'My test content',
130 'CRM_Activity_DAO_Activity',
132 'name' => self
::getFilePrefix() . 'failedExample.txt',
133 'mime_type' => 'text/plain',
134 'description' => 'My test description',
136 "/Mandatory key\\(s\\) missing from params array: 'id' or 'content' or 'options.move-file'/",
139 'CRM_Activity_DAO_Activity',
141 'name' => self
::getFilePrefix() . 'failedExample.txt',
142 'mime_type' => 'text/plain',
143 'description' => 'My test description',
144 'content' => 'too much content',
146 'move-file' => $this->tmpFile('too-much.txt'),
149 "/'content' and 'options.move-file' are mutually exclusive/",
152 'CRM_Activity_DAO_Activity',
154 'name' => 'inv/alid.txt',
155 'mime_type' => 'text/plain',
156 'description' => 'My test description',
157 'content' => 'My test content',
162 'CRM_Core_DAO_Domain',
164 'name' => self
::getFilePrefix() . 'exampleFromContent.txt',
165 'mime_type' => 'text/plain',
166 'description' => 'My test description',
167 'content' => 'My test content',
169 "/Unrecognized target entity/",
178 public function badUpdateProvider() {
179 $cases = array(); // array($entityClass, $createParams, $updateParams, $expectedError)
181 $readOnlyFields = array(
182 'name' => 'newname.txt',
183 'entity_table' => 'civicrm_domain',
185 'upload_date' => '2010-11-12 13:14:15',
187 foreach ($readOnlyFields as $readOnlyField => $newValue) {
189 'CRM_Activity_DAO_Activity',
191 'name' => self
::getFilePrefix() . 'exampleFromContent.txt',
192 'mime_type' => 'text/plain',
193 'description' => 'My test description',
194 'content' => 'My test content',
197 'check_permissions' => 1,
198 $readOnlyField => $newValue,
200 "/Cannot modify $readOnlyField/",
210 public function okGetProvider() {
211 $cases = array(); // array($getParams, $expectedNames)
213 // Each search runs in a DB which contains these attachments:
214 // Activity #123: example_123.txt (text/plain) and example_123.csv (text/csv)
215 // Activity #456: example_456.txt (text/plain) and example_456.csv (text/csv)
218 array('entity_table' => 'civicrm_activity'),
220 self
::getFilePrefix() . 'example_123.csv',
221 self
::getFilePrefix() . 'example_123.txt',
222 self
::getFilePrefix() . 'example_456.csv',
223 self
::getFilePrefix() . 'example_456.txt',
227 array('entity_table' => 'civicrm_activity', 'mime_type' => 'text/plain'),
228 array(self
::getFilePrefix() . 'example_123.txt', self
::getFilePrefix() . 'example_456.txt'),
231 array('entity_table' => 'civicrm_activity', 'entity_id' => '123'),
232 array(self
::getFilePrefix() . 'example_123.txt', self
::getFilePrefix() . 'example_123.csv'),
235 array('entity_table' => 'civicrm_activity', 'entity_id' => '456'),
236 array(self
::getFilePrefix() . 'example_456.txt', self
::getFilePrefix() . 'example_456.csv'),
239 array('entity_table' => 'civicrm_activity', 'entity_id' => '456', 'mime_type' => 'text/csv'),
240 array(self
::getFilePrefix() . 'example_456.csv'),
243 array('entity_table' => 'civicrm_activity', 'entity_id' => '456', 'mime_type' => 'text/html'),
247 array('entity_table' => 'civicrm_activity', 'entity_id' => '999'),
257 public function badGetProvider() {
258 $cases = array(); // array($getParams, $expectedNames)
260 // Each search runs in a DB which contains these attachments:
261 // Activity #123: example_123.txt (text/plain) and example_123.csv (text/csv)
262 // Activity #456: example_456.txt (text/plain) and example_456.csv (text/csv)
265 array('check_permissions' => 1, 'mime_type' => 'text/plain'),
266 "/Mandatory key\\(s\\) missing from params array: 'id' or 'entity_table'/",
269 array('check_permissions' => 1, 'entity_id' => '123'),
270 "/Mandatory key\\(s\\) missing from params array: 'id' or 'entity_table'/",
273 array('check_permissions' => 1),
274 "/Mandatory key\\(s\\) missing from params array: 'id' or 'entity_table'/",
277 array('entity_table' => 'civicrm_activity', 'name' => 'example_456.csv'),
278 "/Get by name is not currently supported/",
281 array('entity_table' => 'civicrm_activity', 'content' => 'test'),
282 "/Get by content is not currently supported/",
285 array('entity_table' => 'civicrm_activity', 'path' => '/home/foo'),
286 "/Get by path is not currently supported/",
289 array('entity_table' => 'civicrm_activity', 'url' => '/index.php'),
290 "/Get by url is not currently supported/",
297 * Create an attachment using "content" and then "get" the attachment
299 * @param string $testEntityClass
300 * E.g. "CRM_Core_DAO_Activity".
301 * @param array $createParams
302 * @param string $expectedContent
303 * @dataProvider okCreateProvider
305 public function testCreate($testEntityClass, $createParams, $expectedContent) {
306 $entity = CRM_Core_DAO
::createTestObject($testEntityClass);
307 $entity_table = CRM_Core_DAO_AllCoreTables
::getTableForClass($testEntityClass);
308 $this->assertTrue(is_numeric($entity->id
));
310 $createResult = $this->callAPISuccess('Attachment', 'create', $createParams +
array(
311 'entity_table' => $entity_table,
312 'entity_id' => $entity->id
,
314 $fileId = $createResult['id'];
315 $this->assertTrue(is_numeric($fileId));
316 $this->assertEquals($entity_table, $createResult['values'][$fileId]['entity_table']);
317 $this->assertEquals($entity->id
, $createResult['values'][$fileId]['entity_id']);
318 $this->assertEquals('My test description', $createResult['values'][$fileId]['description']);
319 $this->assertRegExp('/\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d/', $createResult['values'][$fileId]['upload_date']);
320 $this->assertTrue(!isset($createResult['values'][$fileId]['content']));
321 $this->assertTrue(!empty($createResult['values'][$fileId]['url']));
322 $this->assertAttachmentExistence(TRUE, $createResult);
324 $getResult = $this->callAPISuccess('Attachment', 'get', array(
325 'entity_table' => $entity_table,
326 'entity_id' => $entity->id
,
328 $this->assertEquals(1, $getResult['count']);
329 foreach (array('id', 'entity_table', 'entity_id', 'url') as $field) {
330 $this->assertEquals($createResult['values'][$fileId][$field], $getResult['values'][$fileId][$field], "Expect field $field to match");
332 $this->assertTrue(!isset($getResult['values'][$fileId]['content']));
334 $getResult2 = $this->callAPISuccess('Attachment', 'get', array(
335 'entity_table' => $entity_table,
336 'entity_id' => $entity->id
,
337 'return' => array('content'),
339 $this->assertEquals($expectedContent, $getResult2['values'][$fileId]['content']);
340 foreach (array('id', 'entity_table', 'entity_id', 'url') as $field) {
341 $this->assertEquals($createResult['values'][$fileId][$field], $getResult['values'][$fileId][$field], "Expect field $field to match");
346 * @param $testEntityClass
347 * @param $createParams
348 * @param $expectedError
349 * @dataProvider badCreateProvider
351 public function testCreateFailure($testEntityClass, $createParams, $expectedError) {
352 $entity = CRM_Core_DAO
::createTestObject($testEntityClass);
353 $entity_table = CRM_Core_DAO_AllCoreTables
::getTableForClass($testEntityClass);
354 $this->assertTrue(is_numeric($entity->id
));
356 $createResult = $this->callAPIFailure('Attachment', 'create', $createParams +
array(
357 'entity_table' => $entity_table,
358 'entity_id' => $entity->id
,
360 $this->assertRegExp($expectedError, $createResult['error_message']);
364 * @param $testEntityClass
365 * @param $createParams
366 * @param $updateParams
367 * @param $expectedError
368 * @dataProvider badUpdateProvider
370 public function testCreateWithBadUpdate($testEntityClass, $createParams, $updateParams, $expectedError) {
371 $entity = CRM_Core_DAO
::createTestObject($testEntityClass);
372 $entity_table = CRM_Core_DAO_AllCoreTables
::getTableForClass($testEntityClass);
373 $this->assertTrue(is_numeric($entity->id
));
375 $createResult = $this->callAPISuccess('Attachment', 'create', $createParams +
array(
376 'entity_table' => $entity_table,
377 'entity_id' => $entity->id
,
379 $fileId = $createResult['id'];
380 $this->assertTrue(is_numeric($fileId));
382 $updateResult = $this->callAPIFailure('Attachment', 'create', $updateParams +
array(
385 $this->assertRegExp($expectedError, $updateResult['error_message']);
389 * If one submits a weird file name, it should be automatically converted
392 public function testCreateWithWeirdName() {
393 $entity = CRM_Core_DAO
::createTestObject('CRM_Activity_DAO_Activity');
394 $this->assertTrue(is_numeric($entity->id
));
396 $createResult = $this->callAPISuccess('Attachment', 'create', array(
397 'name' => self
::getFilePrefix() . 'weird:na"me.txt',
398 'mime_type' => 'text/plain',
399 'description' => 'My test description',
400 'content' => 'My test content',
401 'entity_table' => 'civicrm_activity',
402 'entity_id' => $entity->id
,
404 $fileId = $createResult['id'];
405 $this->assertTrue(is_numeric($fileId));
406 $this->assertEquals(self
::getFilePrefix() . 'weird_na_me.txt', $createResult['values'][$fileId]['name']);
411 * @param $expectedNames
412 * @dataProvider okGetProvider
414 public function testGet($getParams, $expectedNames) {
415 foreach (array(123, 456) as $entity_id) {
416 foreach (array('text/plain' => '.txt', 'text/csv' => '.csv') as $mime => $ext) {
417 $this->callAPISuccess('Attachment', 'create', array(
418 'name' => self
::getFilePrefix() . 'example_' . $entity_id . $ext,
419 'mime_type' => $mime,
420 'description' => 'My test description',
421 'content' => 'My test content',
422 'entity_table' => 'civicrm_activity',
423 'entity_id' => $entity_id,
428 $getResult = $this->callAPISuccess('Attachment', 'get', $getParams);
429 $actualNames = array_values(CRM_Utils_Array
::collect('name', $getResult['values']));
431 sort($expectedNames);
432 $this->assertEquals($expectedNames, $actualNames);
437 * @param $expectedError
438 * @dataProvider badGetProvider
440 public function testGetError($getParams, $expectedError) {
441 foreach (array(123, 456) as $entity_id) {
442 foreach (array('text/plain' => '.txt', 'text/csv' => '.csv') as $mime => $ext) {
443 $this->callAPISuccess('Attachment', 'create', array(
444 'name' => self
::getFilePrefix() . 'example_' . $entity_id . $ext,
445 'mime_type' => $mime,
446 'description' => 'My test description',
447 'content' => 'My test content',
448 'entity_table' => 'civicrm_activity',
449 'entity_id' => $entity_id,
454 $getResult = $this->callAPIFailure('Attachment', 'get', $getParams);
455 $this->assertRegExp($expectedError, $getResult['error_message']);
459 * Take the values from a "get", make a small change, and then send
460 * the full thing back in as an update ("create"). This ensures some
461 * consistency in the acceptable formats.
463 public function testGetThenUpdate() {
464 $entity = CRM_Core_DAO
::createTestObject('CRM_Activity_DAO_Activity');
465 $this->assertTrue(is_numeric($entity->id
));
467 $createResult = $this->callAPISuccess('Attachment', 'create', array(
468 'name' => self
::getFilePrefix() . 'getThenUpdate.txt',
469 'mime_type' => 'text/plain',
470 'description' => 'My test description',
471 'content' => 'My test content',
472 'entity_table' => 'civicrm_activity',
473 'entity_id' => $entity->id
,
475 $fileId = $createResult['id'];
476 $this->assertTrue(is_numeric($fileId));
477 $this->assertEquals(self
::getFilePrefix() . 'getThenUpdate.txt', $createResult['values'][$fileId]['name']);
478 $this->assertAttachmentExistence(TRUE, $createResult);
480 $getResult = $this->callAPISuccess('Attachment', 'get', array(
483 $this->assertTrue(is_array($getResult['values'][$fileId]));
485 $updateParams = $getResult['values'][$fileId];
486 $updateParams['description'] = 'new description';
487 $this->callAPISuccess('Attachment', 'create', $updateParams);
488 $this->assertAttachmentExistence(TRUE, $createResult);
492 * Create an attachment and delete using its ID. Assert that the records are correctly created and destroyed
493 * in the DB and the filesystem.
495 public function testDeleteByID() {
496 $entity = CRM_Core_DAO
::createTestObject('CRM_Activity_DAO_Activity');
497 $this->assertTrue(is_numeric($entity->id
));
499 foreach (array('first', 'second') as $n) {
500 $createResults[$n] = $this->callAPISuccess('Attachment', 'create', array(
501 'name' => self
::getFilePrefix() . 'testDeleteByID.txt',
502 'mime_type' => 'text/plain',
503 'content' => 'My test content',
504 'entity_table' => 'civicrm_activity',
505 'entity_id' => $entity->id
,
507 $this->assertTrue(is_numeric($createResults[$n]['id']));
508 $this->assertEquals(self
::getFilePrefix() . 'testDeleteByID.txt', $createResults[$n]['values'][$createResults[$n]['id']]['name']);
510 $this->assertAttachmentExistence(TRUE, $createResults['first']);
511 $this->assertAttachmentExistence(TRUE, $createResults['second']);
513 $this->callAPISuccess('Attachment', 'delete', array(
514 'id' => $createResults['first']['id'],
516 $this->assertAttachmentExistence(FALSE, $createResults['first']);
517 $this->assertAttachmentExistence(TRUE, $createResults['second']);
521 * Create an attachment and delete using its ID. Assert that the records are correctly created and destroyed
522 * in the DB and the filesystem.
524 public function testDeleteByEntity() {
525 // create 2 entities (keepme,delme) -- each with 2 attachments (first,second)
526 foreach (array('keepme', 'delme') as $e) {
527 $entities[$e] = CRM_Core_DAO
::createTestObject('CRM_Activity_DAO_Activity');
528 $this->assertTrue(is_numeric($entities[$e]->id
));
529 foreach (array('first', 'second') as $n) {
530 $createResults[$e][$n] = $this->callAPISuccess('Attachment', 'create', array(
531 'name' => self
::getFilePrefix() . 'testDeleteByEntity.txt',
532 'mime_type' => 'text/plain',
533 'content' => 'My test content',
534 'entity_table' => 'civicrm_activity',
535 'entity_id' => $entities[$e]->id
,
537 $this->assertTrue(is_numeric($createResults[$e][$n]['id']));
540 $this->assertAttachmentExistence(TRUE, $createResults['keepme']['first']);
541 $this->assertAttachmentExistence(TRUE, $createResults['keepme']['second']);
542 $this->assertAttachmentExistence(TRUE, $createResults['delme']['first']);
543 $this->assertAttachmentExistence(TRUE, $createResults['delme']['second']);
545 $this->callAPISuccess('Attachment', 'delete', array(
546 'entity_table' => 'civicrm_activity',
547 'entity_id' => $entities[$e]->id
,
549 $this->assertAttachmentExistence(TRUE, $createResults['keepme']['first']);
550 $this->assertAttachmentExistence(TRUE, $createResults['keepme']['second']);
551 $this->assertAttachmentExistence(FALSE, $createResults['delme']['first']);
552 $this->assertAttachmentExistence(FALSE, $createResults['delme']['second']);
557 * @param array $apiResult
559 protected function assertAttachmentExistence($exists, $apiResult) {
560 $fileId = $apiResult['id'];
561 $this->assertTrue(is_numeric($fileId));
562 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
563 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
564 1 => array($fileId, 'Int'),
566 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
567 1 => array($fileId, 'Int'),
575 protected function tmpFile($name) {
576 $tmpDir = sys_get_temp_dir();
577 $this->assertTrue($tmpDir && is_dir($tmpDir), 'Tmp dir must exist: ' . $tmpDir);
578 return $tmpDir . '/' . self
::getFilePrefix() . $name;
581 protected function cleanupFiles() {
582 $config = CRM_Core_Config
::singleton();
585 $config->customFileUploadDir
,
587 foreach ($dirs as $dir) {
588 $files = (array) glob($dir . "/" . self
::getFilePrefix() . "*");
589 foreach ($files as $file) {