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;
43 public static function getFilePrefix() {
44 if (!self
::$filePrefix) {
45 self
::$filePrefix = "test_" . CRM_Utils_String
::createRandom(5, CRM_Utils_String
::ALPHANUMERIC
) . '_';
47 return self
::$filePrefix;
51 protected function setUp() {
53 $this->useTransaction(TRUE);
55 $this->cleanupFiles();
56 file_put_contents($this->tmpFile('mytest.txt'), 'This comes from a file');
59 protected function tearDown() {
61 $this->cleanupFiles();
62 \Civi\Core\Container
::singleton(TRUE);
65 public function okCreateProvider() {
66 $cases = array(); // array($entityClass, $createParams, $expectedContent)
69 'CRM_Activity_DAO_Activity',
71 'name' => self
::getFilePrefix() . 'exampleFromContent.txt',
72 'mime_type' => 'text/plain',
73 'description' => 'My test description',
74 'content' => 'My test content',
80 'CRM_Activity_DAO_Activity',
82 'name' => self
::getFilePrefix() . 'exampleWithEmptyContent.txt',
83 'mime_type' => 'text/plain',
84 'description' => 'My test description',
91 'CRM_Activity_DAO_Activity',
93 'name' => self
::getFilePrefix() . 'exampleFromMove.txt',
94 'mime_type' => 'text/plain',
95 'description' => 'My test description',
97 'move-file' => $this->tmpFile('mytest.txt'),
100 'This comes from a file',
106 public function badCreateProvider() {
107 $cases = array(); // array($entityClass, $createParams, $expectedError)
110 'CRM_Activity_DAO_Activity',
113 'name' => self
::getFilePrefix() . 'exampleFromContent.txt',
114 'mime_type' => 'text/plain',
115 'description' => 'My test description',
116 'content' => 'My test content',
121 'CRM_Activity_DAO_Activity',
123 'name' => self
::getFilePrefix() . 'failedExample.txt',
124 'mime_type' => 'text/plain',
125 'description' => 'My test description',
127 "/Mandatory key\\(s\\) missing from params array: 'id' or 'content' or 'options.move-file'/",
130 'CRM_Activity_DAO_Activity',
132 'name' => self
::getFilePrefix() . 'failedExample.txt',
133 'mime_type' => 'text/plain',
134 'description' => 'My test description',
135 'content' => 'too much content',
137 'move-file' => $this->tmpFile('too-much.txt')
140 "/'content' and 'options.move-file' are mutually exclusive/",
143 'CRM_Activity_DAO_Activity',
145 'name' => 'inv/alid.txt',
146 'mime_type' => 'text/plain',
147 'description' => 'My test description',
148 'content' => 'My test content',
153 'CRM_Core_DAO_Domain',
155 'name' => self
::getFilePrefix() . 'exampleFromContent.txt',
156 'mime_type' => 'text/plain',
157 'description' => 'My test description',
158 'content' => 'My test content',
160 "/Unrecognized target entity/",
166 public function badUpdateProvider() {
167 $cases = array(); // array($entityClass, $createParams, $updateParams, $expectedError)
169 $readOnlyFields = array(
170 'name' => 'newname.txt',
171 'entity_table' => 'civicrm_domain',
173 'upload_date' => '2010-11-12 13:14:15',
175 foreach ($readOnlyFields as $readOnlyField => $newValue) {
177 'CRM_Activity_DAO_Activity',
179 'name' => self
::getFilePrefix() . 'exampleFromContent.txt',
180 'mime_type' => 'text/plain',
181 'description' => 'My test description',
182 'content' => 'My test content',
185 'check_permissions' => 1,
186 $readOnlyField => $newValue,
188 "/Cannot modify $readOnlyField/"
195 public function okGetProvider() {
196 $cases = array(); // array($getParams, $expectedNames)
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)
203 array('entity_table' => 'civicrm_activity'),
205 self
::getFilePrefix() . 'example_123.csv',
206 self
::getFilePrefix() . 'example_123.txt',
207 self
::getFilePrefix() . 'example_456.csv',
208 self
::getFilePrefix() . 'example_456.txt',
212 array('entity_table' => 'civicrm_activity', 'mime_type' => 'text/plain'),
213 array(self
::getFilePrefix() . 'example_123.txt', self
::getFilePrefix() . 'example_456.txt'),
216 array('entity_table' => 'civicrm_activity', 'entity_id' => '123'),
217 array(self
::getFilePrefix() . 'example_123.txt', self
::getFilePrefix() . 'example_123.csv'),
220 array('entity_table' => 'civicrm_activity', 'entity_id' => '456'),
221 array(self
::getFilePrefix() . 'example_456.txt', self
::getFilePrefix() . 'example_456.csv'),
224 array('entity_table' => 'civicrm_activity', 'entity_id' => '456', 'mime_type' => 'text/csv'),
225 array(self
::getFilePrefix() . 'example_456.csv'),
228 array('entity_table' => 'civicrm_activity', 'entity_id' => '456', 'mime_type' => 'text/html'),
232 array('entity_table' => 'civicrm_activity', 'entity_id' => '999'),
239 public function badGetProvider() {
240 $cases = array(); // array($getParams, $expectedNames)
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)
247 array('check_permissions' => 1, 'mime_type' => 'text/plain'),
248 "/Mandatory key\\(s\\) missing from params array: 'id' or 'entity_table'/",
251 array('check_permissions' => 1, 'entity_id' => '123'),
252 "/Mandatory key\\(s\\) missing from params array: 'id' or 'entity_table'/",
255 array('check_permissions' => 1),
256 "/Mandatory key\\(s\\) missing from params array: 'id' or 'entity_table'/",
259 array('entity_table' => 'civicrm_activity', 'name' => 'example_456.csv'),
260 "/Get by name is not currently supported/",
263 array('entity_table' => 'civicrm_activity', 'content' => 'test'),
264 "/Get by content is not currently supported/",
267 array('entity_table' => 'civicrm_activity', 'path' => '/home/foo'),
268 "/Get by path is not currently supported/",
271 array('entity_table' => 'civicrm_activity', 'url' => '/index.php'),
272 "/Get by url is not currently supported/",
279 * Create an attachment using "content" and then "get" the attachment
281 * @param string $testEntityClass e.g. "CRM_Core_DAO_Activity"
282 * @param array $createParams
283 * @param string $expectedContent
284 * @dataProvider okCreateProvider
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
));
291 $createResult = $this->callAPISuccess('Attachment', 'create', $createParams +
array(
292 'entity_table' => $entity_table,
293 'entity_id' => $entity->id
,
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);
305 $getResult = $this->callAPISuccess('Attachment', 'get', array(
306 'entity_table' => $entity_table,
307 'entity_id' => $entity->id
,
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");
313 $this->assertTrue(!isset($getResult['values'][$fileId]['content']));
315 $getResult2 = $this->callAPISuccess('Attachment', 'get', array(
316 'entity_table' => $entity_table,
317 'entity_id' => $entity->id
,
318 'return' => array('content'),
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");
327 * @param $testEntityClass
328 * @param $createParams
329 * @param $expectedError
330 * @dataProvider badCreateProvider
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
));
337 $createResult = $this->callAPIFailure('Attachment', 'create', $createParams +
array(
338 'entity_table' => $entity_table,
339 'entity_id' => $entity->id
,
341 $this->assertRegExp($expectedError, $createResult['error_message']);
345 * @param $testEntityClass
346 * @param $createParams
347 * @param $updateParams
348 * @param $expectedError
349 * @dataProvider badUpdateProvider
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
));
356 $createResult = $this->callAPISuccess('Attachment', 'create', $createParams +
array(
357 'entity_table' => $entity_table,
358 'entity_id' => $entity->id
,
360 $fileId = $createResult['id'];
361 $this->assertTrue(is_numeric($fileId));
363 $updateResult = $this->callAPIFailure('Attachment', 'create', $updateParams +
array(
366 $this->assertRegExp($expectedError, $updateResult['error_message']);
370 * If one submits a weird file name, it should be automatically converted
373 public function testCreateWithWeirdName() {
374 $entity = CRM_Core_DAO
::createTestObject('CRM_Activity_DAO_Activity');
375 $this->assertTrue(is_numeric($entity->id
));
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
,
385 $fileId = $createResult['id'];
386 $this->assertTrue(is_numeric($fileId));
387 $this->assertEquals(self
::getFilePrefix() . 'weird_na_me.txt', $createResult['values'][$fileId]['name']);
392 * @param $expectedNames
393 * @dataProvider okGetProvider
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,
409 $getResult = $this->callAPISuccess('Attachment', 'get', $getParams);
410 $actualNames = array_values(CRM_Utils_Array
::collect('name', $getResult['values']));
412 sort($expectedNames);
413 $this->assertEquals($expectedNames, $actualNames);
418 * @param $expectedError
419 * @dataProvider badGetProvider
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,
435 $getResult = $this->callAPIFailure('Attachment', 'get', $getParams);
436 $this->assertRegExp($expectedError, $getResult['error_message']);
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.
444 public function testGetThenUpdate() {
445 $entity = CRM_Core_DAO
::createTestObject('CRM_Activity_DAO_Activity');
446 $this->assertTrue(is_numeric($entity->id
));
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
,
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);
461 $getResult = $this->callAPISuccess('Attachment', 'get', array(
464 $this->assertTrue(is_array($getResult['values'][$fileId]));
466 $updateParams = $getResult['values'][$fileId];
467 $updateParams['description'] = 'new description';
468 $this->callAPISuccess('Attachment', 'create', $updateParams);
469 $this->assertAttachmentExistence(TRUE, $createResult);
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.
476 public function testDeleteByID() {
477 $entity = CRM_Core_DAO
::createTestObject('CRM_Activity_DAO_Activity');
478 $this->assertTrue(is_numeric($entity->id
));
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
,
488 $this->assertTrue(is_numeric($createResults[$n]['id']));
489 $this->assertEquals(self
::getFilePrefix() . 'testDeleteByID.txt', $createResults[$n]['values'][$createResults[$n]['id']]['name']);
491 $this->assertAttachmentExistence(TRUE, $createResults['first']);
492 $this->assertAttachmentExistence(TRUE, $createResults['second']);
494 $this->callAPISuccess('Attachment', 'delete', array(
495 'id' => $createResults['first']['id'],
497 $this->assertAttachmentExistence(FALSE, $createResults['first']);
498 $this->assertAttachmentExistence(TRUE, $createResults['second']);
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.
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
,
518 $this->assertTrue(is_numeric($createResults[$e][$n]['id']));
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']);
526 $this->callAPISuccess('Attachment', 'delete', array(
527 'entity_table' => 'civicrm_activity',
528 'entity_id' => $entities[$e]->id
,
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']);
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')
543 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
544 1 => array($fileId, 'Int')
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;
554 protected function cleanupFiles() {
555 $config = CRM_Core_Config
::singleton();
558 $config->customFileUploadDir
,
560 foreach ($dirs as $dir) {
561 $files = (array) glob($dir . "/" . self
::getFilePrefix() . "*");
562 foreach ($files as $file) {