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
282 * E.g. "CRM_Core_DAO_Activity".
283 * @param array $createParams
284 * @param string $expectedContent
285 * @dataProvider okCreateProvider
287 public function testCreate($testEntityClass, $createParams, $expectedContent) {
288 $entity = CRM_Core_DAO
::createTestObject($testEntityClass);
289 $entity_table = CRM_Core_DAO_AllCoreTables
::getTableForClass($testEntityClass);
290 $this->assertTrue(is_numeric($entity->id
));
292 $createResult = $this->callAPISuccess('Attachment', 'create', $createParams +
array(
293 'entity_table' => $entity_table,
294 'entity_id' => $entity->id
,
296 $fileId = $createResult['id'];
297 $this->assertTrue(is_numeric($fileId));
298 $this->assertEquals($entity_table, $createResult['values'][$fileId]['entity_table']);
299 $this->assertEquals($entity->id
, $createResult['values'][$fileId]['entity_id']);
300 $this->assertEquals('My test description', $createResult['values'][$fileId]['description']);
301 $this->assertRegExp('/\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d/', $createResult['values'][$fileId]['upload_date']);
302 $this->assertTrue(!isset($createResult['values'][$fileId]['content']));
303 $this->assertTrue(!empty($createResult['values'][$fileId]['url']));
304 $this->assertAttachmentExistence(TRUE, $createResult);
306 $getResult = $this->callAPISuccess('Attachment', 'get', array(
307 'entity_table' => $entity_table,
308 'entity_id' => $entity->id
,
310 $this->assertEquals(1, $getResult['count']);
311 foreach (array('id', 'entity_table', 'entity_id', 'url') as $field) {
312 $this->assertEquals($createResult['values'][$fileId][$field], $getResult['values'][$fileId][$field], "Expect field $field to match");
314 $this->assertTrue(!isset($getResult['values'][$fileId]['content']));
316 $getResult2 = $this->callAPISuccess('Attachment', 'get', array(
317 'entity_table' => $entity_table,
318 'entity_id' => $entity->id
,
319 'return' => array('content'),
321 $this->assertEquals($expectedContent, $getResult2['values'][$fileId]['content']);
322 foreach (array('id', 'entity_table', 'entity_id', 'url') as $field) {
323 $this->assertEquals($createResult['values'][$fileId][$field], $getResult['values'][$fileId][$field], "Expect field $field to match");
328 * @param $testEntityClass
329 * @param $createParams
330 * @param $expectedError
331 * @dataProvider badCreateProvider
333 public function testCreateFailure($testEntityClass, $createParams, $expectedError) {
334 $entity = CRM_Core_DAO
::createTestObject($testEntityClass);
335 $entity_table = CRM_Core_DAO_AllCoreTables
::getTableForClass($testEntityClass);
336 $this->assertTrue(is_numeric($entity->id
));
338 $createResult = $this->callAPIFailure('Attachment', 'create', $createParams +
array(
339 'entity_table' => $entity_table,
340 'entity_id' => $entity->id
,
342 $this->assertRegExp($expectedError, $createResult['error_message']);
346 * @param $testEntityClass
347 * @param $createParams
348 * @param $updateParams
349 * @param $expectedError
350 * @dataProvider badUpdateProvider
352 public function testCreateWithBadUpdate($testEntityClass, $createParams, $updateParams, $expectedError) {
353 $entity = CRM_Core_DAO
::createTestObject($testEntityClass);
354 $entity_table = CRM_Core_DAO_AllCoreTables
::getTableForClass($testEntityClass);
355 $this->assertTrue(is_numeric($entity->id
));
357 $createResult = $this->callAPISuccess('Attachment', 'create', $createParams +
array(
358 'entity_table' => $entity_table,
359 'entity_id' => $entity->id
,
361 $fileId = $createResult['id'];
362 $this->assertTrue(is_numeric($fileId));
364 $updateResult = $this->callAPIFailure('Attachment', 'create', $updateParams +
array(
367 $this->assertRegExp($expectedError, $updateResult['error_message']);
371 * If one submits a weird file name, it should be automatically converted
374 public function testCreateWithWeirdName() {
375 $entity = CRM_Core_DAO
::createTestObject('CRM_Activity_DAO_Activity');
376 $this->assertTrue(is_numeric($entity->id
));
378 $createResult = $this->callAPISuccess('Attachment', 'create', array(
379 'name' => self
::getFilePrefix() . 'weird:na"me.txt',
380 'mime_type' => 'text/plain',
381 'description' => 'My test description',
382 'content' => 'My test content',
383 'entity_table' => 'civicrm_activity',
384 'entity_id' => $entity->id
,
386 $fileId = $createResult['id'];
387 $this->assertTrue(is_numeric($fileId));
388 $this->assertEquals(self
::getFilePrefix() . 'weird_na_me.txt', $createResult['values'][$fileId]['name']);
393 * @param $expectedNames
394 * @dataProvider okGetProvider
396 public function testGet($getParams, $expectedNames) {
397 foreach (array(123, 456) as $entity_id) {
398 foreach (array('text/plain' => '.txt', 'text/csv' => '.csv') as $mime => $ext) {
399 $this->callAPISuccess('Attachment', 'create', array(
400 'name' => self
::getFilePrefix() . 'example_' . $entity_id . $ext,
401 'mime_type' => $mime,
402 'description' => 'My test description',
403 'content' => 'My test content',
404 'entity_table' => 'civicrm_activity',
405 'entity_id' => $entity_id,
410 $getResult = $this->callAPISuccess('Attachment', 'get', $getParams);
411 $actualNames = array_values(CRM_Utils_Array
::collect('name', $getResult['values']));
413 sort($expectedNames);
414 $this->assertEquals($expectedNames, $actualNames);
419 * @param $expectedError
420 * @dataProvider badGetProvider
422 public function testGetError($getParams, $expectedError) {
423 foreach (array(123, 456) as $entity_id) {
424 foreach (array('text/plain' => '.txt', 'text/csv' => '.csv') as $mime => $ext) {
425 $this->callAPISuccess('Attachment', 'create', array(
426 'name' => self
::getFilePrefix() . 'example_' . $entity_id . $ext,
427 'mime_type' => $mime,
428 'description' => 'My test description',
429 'content' => 'My test content',
430 'entity_table' => 'civicrm_activity',
431 'entity_id' => $entity_id,
436 $getResult = $this->callAPIFailure('Attachment', 'get', $getParams);
437 $this->assertRegExp($expectedError, $getResult['error_message']);
441 * Take the values from a "get", make a small change, and then send
442 * the full thing back in as an update ("create"). This ensures some
443 * consistency in the acceptable formats.
445 public function testGetThenUpdate() {
446 $entity = CRM_Core_DAO
::createTestObject('CRM_Activity_DAO_Activity');
447 $this->assertTrue(is_numeric($entity->id
));
449 $createResult = $this->callAPISuccess('Attachment', 'create', array(
450 'name' => self
::getFilePrefix() . 'getThenUpdate.txt',
451 'mime_type' => 'text/plain',
452 'description' => 'My test description',
453 'content' => 'My test content',
454 'entity_table' => 'civicrm_activity',
455 'entity_id' => $entity->id
,
457 $fileId = $createResult['id'];
458 $this->assertTrue(is_numeric($fileId));
459 $this->assertEquals(self
::getFilePrefix() . 'getThenUpdate.txt', $createResult['values'][$fileId]['name']);
460 $this->assertAttachmentExistence(TRUE, $createResult);
462 $getResult = $this->callAPISuccess('Attachment', 'get', array(
465 $this->assertTrue(is_array($getResult['values'][$fileId]));
467 $updateParams = $getResult['values'][$fileId];
468 $updateParams['description'] = 'new description';
469 $this->callAPISuccess('Attachment', 'create', $updateParams);
470 $this->assertAttachmentExistence(TRUE, $createResult);
474 * Create an attachment and delete using its ID. Assert that the records are correctly created and destroyed
475 * in the DB and the filesystem.
477 public function testDeleteByID() {
478 $entity = CRM_Core_DAO
::createTestObject('CRM_Activity_DAO_Activity');
479 $this->assertTrue(is_numeric($entity->id
));
481 foreach (array('first', 'second') as $n) {
482 $createResults[$n] = $this->callAPISuccess('Attachment', 'create', array(
483 'name' => self
::getFilePrefix() . 'testDeleteByID.txt',
484 'mime_type' => 'text/plain',
485 'content' => 'My test content',
486 'entity_table' => 'civicrm_activity',
487 'entity_id' => $entity->id
,
489 $this->assertTrue(is_numeric($createResults[$n]['id']));
490 $this->assertEquals(self
::getFilePrefix() . 'testDeleteByID.txt', $createResults[$n]['values'][$createResults[$n]['id']]['name']);
492 $this->assertAttachmentExistence(TRUE, $createResults['first']);
493 $this->assertAttachmentExistence(TRUE, $createResults['second']);
495 $this->callAPISuccess('Attachment', 'delete', array(
496 'id' => $createResults['first']['id'],
498 $this->assertAttachmentExistence(FALSE, $createResults['first']);
499 $this->assertAttachmentExistence(TRUE, $createResults['second']);
503 * Create an attachment and delete using its ID. Assert that the records are correctly created and destroyed
504 * in the DB and the filesystem.
506 public function testDeleteByEntity() {
507 // create 2 entities (keepme,delme) -- each with 2 attachments (first,second)
508 foreach (array('keepme', 'delme') as $e) {
509 $entities[$e] = CRM_Core_DAO
::createTestObject('CRM_Activity_DAO_Activity');
510 $this->assertTrue(is_numeric($entities[$e]->id
));
511 foreach (array('first', 'second') as $n) {
512 $createResults[$e][$n] = $this->callAPISuccess('Attachment', 'create', array(
513 'name' => self
::getFilePrefix() . 'testDeleteByEntity.txt',
514 'mime_type' => 'text/plain',
515 'content' => 'My test content',
516 'entity_table' => 'civicrm_activity',
517 'entity_id' => $entities[$e]->id
,
519 $this->assertTrue(is_numeric($createResults[$e][$n]['id']));
522 $this->assertAttachmentExistence(TRUE, $createResults['keepme']['first']);
523 $this->assertAttachmentExistence(TRUE, $createResults['keepme']['second']);
524 $this->assertAttachmentExistence(TRUE, $createResults['delme']['first']);
525 $this->assertAttachmentExistence(TRUE, $createResults['delme']['second']);
527 $this->callAPISuccess('Attachment', 'delete', array(
528 'entity_table' => 'civicrm_activity',
529 'entity_id' => $entities[$e]->id
,
531 $this->assertAttachmentExistence(TRUE, $createResults['keepme']['first']);
532 $this->assertAttachmentExistence(TRUE, $createResults['keepme']['second']);
533 $this->assertAttachmentExistence(FALSE, $createResults['delme']['first']);
534 $this->assertAttachmentExistence(FALSE, $createResults['delme']['second']);
537 protected function assertAttachmentExistence($exists, $apiResult) {
538 $fileId = $apiResult['id'];
539 $this->assertTrue(is_numeric($fileId));
540 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
541 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
542 1 => array($fileId, 'Int'),
544 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
545 1 => array($fileId, 'Int'),
549 protected function tmpFile($name) {
550 $tmpDir = sys_get_temp_dir();
551 $this->assertTrue($tmpDir && is_dir($tmpDir), 'Tmp dir must exist: ' . $tmpDir);
552 return $tmpDir . '/' . self
::getFilePrefix() . $name;
555 protected function cleanupFiles() {
556 $config = CRM_Core_Config
::singleton();
559 $config->customFileUploadDir
,
561 foreach ($dirs as $dir) {
562 $files = (array) glob($dir . "/" . self
::getFilePrefix() . "*");
563 foreach ($files as $file) {