file.test 110 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782
  1. <?php
  2. /**
  3. * @file
  4. * This provides SimpleTests for the core file handling functionality.
  5. * These include FileValidateTest and FileSaveTest.
  6. */
  7. /**
  8. * Helper validator that returns the $errors parameter.
  9. */
  10. function file_test_validator($file, $errors) {
  11. return $errors;
  12. }
  13. /**
  14. * Helper function for testing file_scan_directory().
  15. *
  16. * Each time the function is called the file is stored in a static variable.
  17. * When the function is called with no $filepath parameter, the results are
  18. * returned.
  19. *
  20. * @param $filepath
  21. * File path
  22. * @return
  23. * If $filepath is NULL, an array of all previous $filepath parameters
  24. */
  25. function file_test_file_scan_callback($filepath = NULL) {
  26. $files = &drupal_static(__FUNCTION__, array());
  27. if (isset($filepath)) {
  28. $files[] = $filepath;
  29. }
  30. else {
  31. return $files;
  32. }
  33. }
  34. /**
  35. * Reset static variables used by file_test_file_scan_callback().
  36. */
  37. function file_test_file_scan_callback_reset() {
  38. drupal_static_reset('file_test_file_scan_callback');
  39. }
  40. /**
  41. * Base class for file tests that adds some additional file specific
  42. * assertions and helper functions.
  43. */
  44. class FileTestCase extends DrupalWebTestCase {
  45. /**
  46. * Check that two files have the same values for all fields other than the
  47. * timestamp.
  48. *
  49. * @param $before
  50. * File object to compare.
  51. * @param $after
  52. * File object to compare.
  53. */
  54. function assertFileUnchanged($before, $after) {
  55. $this->assertEqual($before->fid, $after->fid, t('File id is the same: %file1 == %file2.', array('%file1' => $before->fid, '%file2' => $after->fid)), 'File unchanged');
  56. $this->assertEqual($before->uid, $after->uid, t('File owner is the same: %file1 == %file2.', array('%file1' => $before->uid, '%file2' => $after->uid)), 'File unchanged');
  57. $this->assertEqual($before->filename, $after->filename, t('File name is the same: %file1 == %file2.', array('%file1' => $before->filename, '%file2' => $after->filename)), 'File unchanged');
  58. $this->assertEqual($before->uri, $after->uri, t('File path is the same: %file1 == %file2.', array('%file1' => $before->uri, '%file2' => $after->uri)), 'File unchanged');
  59. $this->assertEqual($before->filemime, $after->filemime, t('File MIME type is the same: %file1 == %file2.', array('%file1' => $before->filemime, '%file2' => $after->filemime)), 'File unchanged');
  60. $this->assertEqual($before->filesize, $after->filesize, t('File size is the same: %file1 == %file2.', array('%file1' => $before->filesize, '%file2' => $after->filesize)), 'File unchanged');
  61. $this->assertEqual($before->status, $after->status, t('File status is the same: %file1 == %file2.', array('%file1' => $before->status, '%file2' => $after->status)), 'File unchanged');
  62. }
  63. /**
  64. * Check that two files are not the same by comparing the fid and filepath.
  65. *
  66. * @param $file1
  67. * File object to compare.
  68. * @param $file2
  69. * File object to compare.
  70. */
  71. function assertDifferentFile($file1, $file2) {
  72. $this->assertNotEqual($file1->fid, $file2->fid, t('Files have different ids: %file1 != %file2.', array('%file1' => $file1->fid, '%file2' => $file2->fid)), 'Different file');
  73. $this->assertNotEqual($file1->uri, $file2->uri, t('Files have different paths: %file1 != %file2.', array('%file1' => $file1->uri, '%file2' => $file2->uri)), 'Different file');
  74. }
  75. /**
  76. * Check that two files are the same by comparing the fid and filepath.
  77. *
  78. * @param $file1
  79. * File object to compare.
  80. * @param $file2
  81. * File object to compare.
  82. */
  83. function assertSameFile($file1, $file2) {
  84. $this->assertEqual($file1->fid, $file2->fid, t('Files have the same ids: %file1 == %file2.', array('%file1' => $file1->fid, '%file2-fid' => $file2->fid)), 'Same file');
  85. $this->assertEqual($file1->uri, $file2->uri, t('Files have the same path: %file1 == %file2.', array('%file1' => $file1->uri, '%file2' => $file2->uri)), 'Same file');
  86. }
  87. /**
  88. * Helper function to test the permissions of a file.
  89. *
  90. * @param $filepath
  91. * String file path.
  92. * @param $expected_mode
  93. * Octal integer like 0664 or 0777.
  94. * @param $message
  95. * Optional message.
  96. */
  97. function assertFilePermissions($filepath, $expected_mode, $message = NULL) {
  98. // Clear out PHP's file stat cache to be sure we see the current value.
  99. clearstatcache();
  100. // Mask out all but the last three octets.
  101. $actual_mode = fileperms($filepath) & 0777;
  102. // PHP on Windows has limited support for file permissions. Usually each of
  103. // "user", "group" and "other" use one octal digit (3 bits) to represent the
  104. // read/write/execute bits. On Windows, chmod() ignores the "group" and
  105. // "other" bits, and fileperms() returns the "user" bits in all three
  106. // positions. $expected_mode is updated to reflect this.
  107. if (substr(PHP_OS, 0, 3) == 'WIN') {
  108. // Reset the "group" and "other" bits.
  109. $expected_mode = $expected_mode & 0700;
  110. // Shift the "user" bits to the "group" and "other" positions also.
  111. $expected_mode = $expected_mode | $expected_mode >> 3 | $expected_mode >> 6;
  112. }
  113. if (!isset($message)) {
  114. $message = t('Expected file permission to be %expected, actually were %actual.', array('%actual' => decoct($actual_mode), '%expected' => decoct($expected_mode)));
  115. }
  116. $this->assertEqual($actual_mode, $expected_mode, $message);
  117. }
  118. /**
  119. * Helper function to test the permissions of a directory.
  120. *
  121. * @param $directory
  122. * String directory path.
  123. * @param $expected_mode
  124. * Octal integer like 0664 or 0777.
  125. * @param $message
  126. * Optional message.
  127. */
  128. function assertDirectoryPermissions($directory, $expected_mode, $message = NULL) {
  129. // Clear out PHP's file stat cache to be sure we see the current value.
  130. clearstatcache();
  131. // Mask out all but the last three octets.
  132. $actual_mode = fileperms($directory) & 0777;
  133. // PHP on Windows has limited support for file permissions. Usually each of
  134. // "user", "group" and "other" use one octal digit (3 bits) to represent the
  135. // read/write/execute bits. On Windows, chmod() ignores the "group" and
  136. // "other" bits, and fileperms() returns the "user" bits in all three
  137. // positions. $expected_mode is updated to reflect this.
  138. if (substr(PHP_OS, 0, 3) == 'WIN') {
  139. // Reset the "group" and "other" bits.
  140. $expected_mode = $expected_mode & 0700;
  141. // Shift the "user" bits to the "group" and "other" positions also.
  142. $expected_mode = $expected_mode | $expected_mode >> 3 | $expected_mode >> 6;
  143. }
  144. if (!isset($message)) {
  145. $message = t('Expected directory permission to be %expected, actually were %actual.', array('%actual' => decoct($actual_mode), '%expected' => decoct($expected_mode)));
  146. }
  147. $this->assertEqual($actual_mode, $expected_mode, $message);
  148. }
  149. /**
  150. * Create a directory and assert it exists.
  151. *
  152. * @param $path
  153. * Optional string with a directory path. If none is provided, a random
  154. * name in the site's files directory will be used.
  155. * @return
  156. * The path to the directory.
  157. */
  158. function createDirectory($path = NULL) {
  159. // A directory to operate on.
  160. if (!isset($path)) {
  161. $path = file_default_scheme() . '://' . $this->randomName();
  162. }
  163. $this->assertTrue(drupal_mkdir($path) && is_dir($path), t('Directory was created successfully.'));
  164. return $path;
  165. }
  166. /**
  167. * Create a file and save it to the files table and assert that it occurs
  168. * correctly.
  169. *
  170. * @param $filepath
  171. * Optional string specifying the file path. If none is provided then a
  172. * randomly named file will be created in the site's files directory.
  173. * @param $contents
  174. * Optional contents to save into the file. If a NULL value is provided an
  175. * arbitrary string will be used.
  176. * @param $scheme
  177. * Optional string indicating the stream scheme to use. Drupal core includes
  178. * public, private, and temporary. The public wrapper is the default.
  179. * @return
  180. * File object.
  181. */
  182. function createFile($filepath = NULL, $contents = NULL, $scheme = NULL) {
  183. if (!isset($filepath)) {
  184. // Prefix with non-latin characters to ensure that all file-related
  185. // tests work with international filenames.
  186. $filepath = 'Файл для тестирования ' . $this->randomName();
  187. }
  188. if (!isset($scheme)) {
  189. $scheme = file_default_scheme();
  190. }
  191. $filepath = $scheme . '://' . $filepath;
  192. if (!isset($contents)) {
  193. $contents = "file_put_contents() doesn't seem to appreciate empty strings so let's put in some data.";
  194. }
  195. file_put_contents($filepath, $contents);
  196. $this->assertTrue(is_file($filepath), t('The test file exists on the disk.'), 'Create test file');
  197. $file = new stdClass();
  198. $file->uri = $filepath;
  199. $file->filename = drupal_basename($file->uri);
  200. $file->filemime = 'text/plain';
  201. $file->uid = 1;
  202. $file->timestamp = REQUEST_TIME;
  203. $file->filesize = filesize($file->uri);
  204. $file->status = 0;
  205. // Write the record directly rather than calling file_save() so we don't
  206. // invoke the hooks.
  207. $this->assertNotIdentical(drupal_write_record('file_managed', $file), FALSE, t('The file was added to the database.'), 'Create test file');
  208. return $file;
  209. }
  210. }
  211. /**
  212. * Base class for file tests that use the file_test module to test uploads and
  213. * hooks.
  214. */
  215. class FileHookTestCase extends FileTestCase {
  216. function setUp() {
  217. // Install file_test module
  218. parent::setUp('file_test');
  219. // Clear out any hook calls.
  220. file_test_reset();
  221. }
  222. /**
  223. * Assert that all of the specified hook_file_* hooks were called once, other
  224. * values result in failure.
  225. *
  226. * @param $expected
  227. * Array with string containing with the hook name, e.g. 'load', 'save',
  228. * 'insert', etc.
  229. */
  230. function assertFileHooksCalled($expected) {
  231. // Determine which hooks were called.
  232. $actual = array_keys(array_filter(file_test_get_all_calls()));
  233. // Determine if there were any expected that were not called.
  234. $uncalled = array_diff($expected, $actual);
  235. if (count($uncalled)) {
  236. $this->assertTrue(FALSE, t('Expected hooks %expected to be called but %uncalled was not called.', array('%expected' => implode(', ', $expected), '%uncalled' => implode(', ', $uncalled))));
  237. }
  238. else {
  239. $this->assertTrue(TRUE, t('All the expected hooks were called: %expected', array('%expected' => empty($expected) ? t('(none)') : implode(', ', $expected))));
  240. }
  241. // Determine if there were any unexpected calls.
  242. $unexpected = array_diff($actual, $expected);
  243. if (count($unexpected)) {
  244. $this->assertTrue(FALSE, t('Unexpected hooks were called: %unexpected.', array('%unexpected' => empty($unexpected) ? t('(none)') : implode(', ', $unexpected))));
  245. }
  246. else {
  247. $this->assertTrue(TRUE, t('No unexpected hooks were called.'));
  248. }
  249. }
  250. /**
  251. * Assert that a hook_file_* hook was called a certain number of times.
  252. *
  253. * @param $hook
  254. * String with the hook name, e.g. 'load', 'save', 'insert', etc.
  255. * @param $expected_count
  256. * Optional integer count.
  257. * @param $message
  258. * Optional translated string message.
  259. */
  260. function assertFileHookCalled($hook, $expected_count = 1, $message = NULL) {
  261. $actual_count = count(file_test_get_calls($hook));
  262. if (!isset($message)) {
  263. if ($actual_count == $expected_count) {
  264. $message = t('hook_file_@name was called correctly.', array('@name' => $hook));
  265. }
  266. elseif ($expected_count == 0) {
  267. $message = format_plural($actual_count, 'hook_file_@name was not expected to be called but was actually called once.', 'hook_file_@name was not expected to be called but was actually called @count times.', array('@name' => $hook, '@count' => $actual_count));
  268. }
  269. else {
  270. $message = t('hook_file_@name was expected to be called %expected times but was called %actual times.', array('@name' => $hook, '%expected' => $expected_count, '%actual' => $actual_count));
  271. }
  272. }
  273. $this->assertEqual($actual_count, $expected_count, $message);
  274. }
  275. }
  276. /**
  277. * This will run tests against the file_space_used() function.
  278. */
  279. class FileSpaceUsedTest extends FileTestCase {
  280. public static function getInfo() {
  281. return array(
  282. 'name' => 'File space used tests',
  283. 'description' => 'Tests the file_space_used() function.',
  284. 'group' => 'File API',
  285. );
  286. }
  287. function setUp() {
  288. parent::setUp();
  289. // Create records for a couple of users with different sizes.
  290. $file = array('uid' => 2, 'uri' => 'public://example1.txt', 'filesize' => 50, 'status' => FILE_STATUS_PERMANENT);
  291. drupal_write_record('file_managed', $file);
  292. $file = array('uid' => 2, 'uri' => 'public://example2.txt', 'filesize' => 20, 'status' => FILE_STATUS_PERMANENT);
  293. drupal_write_record('file_managed', $file);
  294. $file = array('uid' => 3, 'uri' => 'public://example3.txt', 'filesize' => 100, 'status' => FILE_STATUS_PERMANENT);
  295. drupal_write_record('file_managed', $file);
  296. $file = array('uid' => 3, 'uri' => 'public://example4.txt', 'filesize' => 200, 'status' => FILE_STATUS_PERMANENT);
  297. drupal_write_record('file_managed', $file);
  298. // Now create some non-permanent files.
  299. $file = array('uid' => 2, 'uri' => 'public://example5.txt', 'filesize' => 1, 'status' => 0);
  300. drupal_write_record('file_managed', $file);
  301. $file = array('uid' => 3, 'uri' => 'public://example6.txt', 'filesize' => 3, 'status' => 0);
  302. drupal_write_record('file_managed', $file);
  303. }
  304. /**
  305. * Test different users with the default status.
  306. */
  307. function testFileSpaceUsed() {
  308. // Test different users with default status.
  309. $this->assertEqual(file_space_used(2), 70);
  310. $this->assertEqual(file_space_used(3), 300);
  311. $this->assertEqual(file_space_used(), 370);
  312. // Test the status fields
  313. $this->assertEqual(file_space_used(NULL, 0), 4);
  314. $this->assertEqual(file_space_used(NULL, FILE_STATUS_PERMANENT), 370);
  315. // Test both the user and status.
  316. $this->assertEqual(file_space_used(1, 0), 0);
  317. $this->assertEqual(file_space_used(1, FILE_STATUS_PERMANENT), 0);
  318. $this->assertEqual(file_space_used(2, 0), 1);
  319. $this->assertEqual(file_space_used(2, FILE_STATUS_PERMANENT), 70);
  320. $this->assertEqual(file_space_used(3, 0), 3);
  321. $this->assertEqual(file_space_used(3, FILE_STATUS_PERMANENT), 300);
  322. }
  323. }
  324. /**
  325. * This will run tests against the file validation functions (file_validate_*).
  326. */
  327. class FileValidatorTest extends DrupalWebTestCase {
  328. public static function getInfo() {
  329. return array(
  330. 'name' => 'File validator tests',
  331. 'description' => 'Tests the functions used to validate uploaded files.',
  332. 'group' => 'File API',
  333. );
  334. }
  335. function setUp() {
  336. parent::setUp();
  337. $this->image = new stdClass();
  338. $this->image->uri = 'misc/druplicon.png';
  339. $this->image->filename = drupal_basename($this->image->uri);
  340. $this->non_image = new stdClass();
  341. $this->non_image->uri = 'misc/jquery.js';
  342. $this->non_image->filename = drupal_basename($this->non_image->uri);
  343. }
  344. /**
  345. * Test the file_validate_extensions() function.
  346. */
  347. function testFileValidateExtensions() {
  348. $file = new stdClass();
  349. $file->filename = 'asdf.txt';
  350. $errors = file_validate_extensions($file, 'asdf txt pork');
  351. $this->assertEqual(count($errors), 0, t('Valid extension accepted.'), 'File');
  352. $file->filename = 'asdf.txt';
  353. $errors = file_validate_extensions($file, 'exe png');
  354. $this->assertEqual(count($errors), 1, t('Invalid extension blocked.'), 'File');
  355. }
  356. /**
  357. * This ensures a specific file is actually an image.
  358. */
  359. function testFileValidateIsImage() {
  360. $this->assertTrue(file_exists($this->image->uri), t('The image being tested exists.'), 'File');
  361. $errors = file_validate_is_image($this->image);
  362. $this->assertEqual(count($errors), 0, t('No error reported for our image file.'), 'File');
  363. $this->assertTrue(file_exists($this->non_image->uri), t('The non-image being tested exists.'), 'File');
  364. $errors = file_validate_is_image($this->non_image);
  365. $this->assertEqual(count($errors), 1, t('An error reported for our non-image file.'), 'File');
  366. }
  367. /**
  368. * This ensures the resolution of a specific file is within bounds.
  369. * The image will be resized if it's too large.
  370. */
  371. function testFileValidateImageResolution() {
  372. // Non-images.
  373. $errors = file_validate_image_resolution($this->non_image);
  374. $this->assertEqual(count($errors), 0, t("Shouldn't get any errors for a non-image file."), 'File');
  375. $errors = file_validate_image_resolution($this->non_image, '50x50', '100x100');
  376. $this->assertEqual(count($errors), 0, t("Don't check the resolution on non files."), 'File');
  377. // Minimum size.
  378. $errors = file_validate_image_resolution($this->image);
  379. $this->assertEqual(count($errors), 0, t('No errors for an image when there is no minimum or maximum resolution.'), 'File');
  380. $errors = file_validate_image_resolution($this->image, 0, '200x1');
  381. $this->assertEqual(count($errors), 1, t("Got an error for an image that wasn't wide enough."), 'File');
  382. $errors = file_validate_image_resolution($this->image, 0, '1x200');
  383. $this->assertEqual(count($errors), 1, t("Got an error for an image that wasn't tall enough."), 'File');
  384. $errors = file_validate_image_resolution($this->image, 0, '200x200');
  385. $this->assertEqual(count($errors), 1, t('Small images report an error.'), 'File');
  386. // Maximum size.
  387. if (image_get_toolkit()) {
  388. // Copy the image so that the original doesn't get resized.
  389. copy('misc/druplicon.png', 'temporary://druplicon.png');
  390. $this->image->uri = 'temporary://druplicon.png';
  391. $errors = file_validate_image_resolution($this->image, '10x5');
  392. $this->assertEqual(count($errors), 0, t('No errors should be reported when an oversized image can be scaled down.'), 'File');
  393. $info = image_get_info($this->image->uri);
  394. $this->assertTrue($info['width'] <= 10, t('Image scaled to correct width.'), 'File');
  395. $this->assertTrue($info['height'] <= 5, t('Image scaled to correct height.'), 'File');
  396. drupal_unlink('temporary://druplicon.png');
  397. }
  398. else {
  399. // TODO: should check that the error is returned if no toolkit is available.
  400. $errors = file_validate_image_resolution($this->image, '5x10');
  401. $this->assertEqual(count($errors), 1, t("Oversize images that can't be scaled get an error."), 'File');
  402. }
  403. }
  404. /**
  405. * This will ensure the filename length is valid.
  406. */
  407. function testFileValidateNameLength() {
  408. // Create a new file object.
  409. $file = new stdClass();
  410. // Add a filename with an allowed length and test it.
  411. $file->filename = str_repeat('x', 240);
  412. $this->assertEqual(strlen($file->filename), 240);
  413. $errors = file_validate_name_length($file);
  414. $this->assertEqual(count($errors), 0, t('No errors reported for 240 length filename.'), 'File');
  415. // Add a filename with a length too long and test it.
  416. $file->filename = str_repeat('x', 241);
  417. $errors = file_validate_name_length($file);
  418. $this->assertEqual(count($errors), 1, t('An error reported for 241 length filename.'), 'File');
  419. // Add a filename with an empty string and test it.
  420. $file->filename = '';
  421. $errors = file_validate_name_length($file);
  422. $this->assertEqual(count($errors), 1, t('An error reported for 0 length filename.'), 'File');
  423. }
  424. /**
  425. * Test file_validate_size().
  426. */
  427. function testFileValidateSize() {
  428. global $user;
  429. $original_user = $user;
  430. drupal_save_session(FALSE);
  431. // Run these test as uid = 1.
  432. $user = user_load(1);
  433. $file = new stdClass();
  434. $file->filesize = 999999;
  435. $errors = file_validate_size($file, 1, 1);
  436. $this->assertEqual(count($errors), 0, t('No size limits enforced on uid=1.'), 'File');
  437. // Run these tests as a regular user.
  438. $user = $this->drupalCreateUser();
  439. // Create a file with a size of 1000 bytes, and quotas of only 1 byte.
  440. $file = new stdClass();
  441. $file->filesize = 1000;
  442. $errors = file_validate_size($file, 0, 0);
  443. $this->assertEqual(count($errors), 0, t('No limits means no errors.'), 'File');
  444. $errors = file_validate_size($file, 1, 0);
  445. $this->assertEqual(count($errors), 1, t('Error for the file being over the limit.'), 'File');
  446. $errors = file_validate_size($file, 0, 1);
  447. $this->assertEqual(count($errors), 1, t('Error for the user being over their limit.'), 'File');
  448. $errors = file_validate_size($file, 1, 1);
  449. $this->assertEqual(count($errors), 2, t('Errors for both the file and their limit.'), 'File');
  450. $user = $original_user;
  451. drupal_save_session(TRUE);
  452. }
  453. }
  454. /**
  455. * Tests the file_unmanaged_save_data() function.
  456. */
  457. class FileUnmanagedSaveDataTest extends FileTestCase {
  458. public static function getInfo() {
  459. return array(
  460. 'name' => 'Unmanaged file save data',
  461. 'description' => 'Tests the unmanaged file save data function.',
  462. 'group' => 'File API',
  463. );
  464. }
  465. /**
  466. * Test the file_unmanaged_save_data() function.
  467. */
  468. function testFileSaveData() {
  469. $contents = $this->randomName(8);
  470. // No filename.
  471. $filepath = file_unmanaged_save_data($contents);
  472. $this->assertTrue($filepath, t('Unnamed file saved correctly.'));
  473. $this->assertEqual(file_uri_scheme($filepath), file_default_scheme(), t("File was placed in Drupal's files directory."));
  474. $this->assertEqual($contents, file_get_contents($filepath), t('Contents of the file are correct.'));
  475. // Provide a filename.
  476. $filepath = file_unmanaged_save_data($contents, 'public://asdf.txt', FILE_EXISTS_REPLACE);
  477. $this->assertTrue($filepath, t('Unnamed file saved correctly.'));
  478. $this->assertEqual('asdf.txt', drupal_basename($filepath), t('File was named correctly.'));
  479. $this->assertEqual($contents, file_get_contents($filepath), t('Contents of the file are correct.'));
  480. $this->assertFilePermissions($filepath, variable_get('file_chmod_file', 0664));
  481. }
  482. }
  483. /**
  484. * Tests the file_unmanaged_save_data() function on remote filesystems.
  485. */
  486. class RemoteFileUnmanagedSaveDataTest extends FileUnmanagedSaveDataTest {
  487. public static function getInfo() {
  488. $info = parent::getInfo();
  489. $info['group'] = 'File API (remote)';
  490. return $info;
  491. }
  492. function setUp() {
  493. parent::setUp('file_test');
  494. variable_set('file_default_scheme', 'dummy-remote');
  495. }
  496. }
  497. /**
  498. * Test the file_save_upload() function.
  499. */
  500. class FileSaveUploadTest extends FileHookTestCase {
  501. /**
  502. * An image file path for uploading.
  503. */
  504. protected $image;
  505. /**
  506. * A PHP file path for upload security testing.
  507. */
  508. protected $phpfile;
  509. /**
  510. * The largest file id when the test starts.
  511. */
  512. protected $maxFidBefore;
  513. public static function getInfo() {
  514. return array(
  515. 'name' => 'File uploading',
  516. 'description' => 'Tests the file uploading functions.',
  517. 'group' => 'File API',
  518. );
  519. }
  520. function setUp() {
  521. parent::setUp();
  522. $account = $this->drupalCreateUser(array('access content'));
  523. $this->drupalLogin($account);
  524. $image_files = $this->drupalGetTestFiles('image');
  525. $this->image = current($image_files);
  526. list(, $this->image_extension) = explode('.', $this->image->filename);
  527. $this->assertTrue(is_file($this->image->uri), t("The image file we're going to upload exists."));
  528. $this->phpfile = current($this->drupalGetTestFiles('php'));
  529. $this->assertTrue(is_file($this->phpfile->uri), t("The PHP file we're going to upload exists."));
  530. $this->maxFidBefore = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
  531. // Upload with replace to guarantee there's something there.
  532. $edit = array(
  533. 'file_test_replace' => FILE_EXISTS_REPLACE,
  534. 'files[file_test_upload]' => drupal_realpath($this->image->uri),
  535. );
  536. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  537. $this->assertResponse(200, t('Received a 200 response for posted test file.'));
  538. $this->assertRaw(t('You WIN!'), t('Found the success message.'));
  539. // Check that the correct hooks were called then clean out the hook
  540. // counters.
  541. $this->assertFileHooksCalled(array('validate', 'insert'));
  542. file_test_reset();
  543. }
  544. /**
  545. * Test the file_save_upload() function.
  546. */
  547. function testNormal() {
  548. $max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
  549. $this->assertTrue($max_fid_after > $this->maxFidBefore, t('A new file was created.'));
  550. $file1 = file_load($max_fid_after);
  551. $this->assertTrue($file1, t('Loaded the file.'));
  552. // MIME type of the uploaded image may be either image/jpeg or image/png.
  553. $this->assertEqual(substr($file1->filemime, 0, 5), 'image', 'A MIME type was set.');
  554. // Reset the hook counters to get rid of the 'load' we just called.
  555. file_test_reset();
  556. // Upload a second file.
  557. $max_fid_before = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
  558. $image2 = current($this->drupalGetTestFiles('image'));
  559. $edit = array('files[file_test_upload]' => drupal_realpath($image2->uri));
  560. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  561. $this->assertResponse(200, t('Received a 200 response for posted test file.'));
  562. $this->assertRaw(t('You WIN!'));
  563. $max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
  564. // Check that the correct hooks were called.
  565. $this->assertFileHooksCalled(array('validate', 'insert'));
  566. $file2 = file_load($max_fid_after);
  567. $this->assertTrue($file2);
  568. // MIME type of the uploaded image may be either image/jpeg or image/png.
  569. $this->assertEqual(substr($file2->filemime, 0, 5), 'image', 'A MIME type was set.');
  570. // Load both files using file_load_multiple().
  571. $files = file_load_multiple(array($file1->fid, $file2->fid));
  572. $this->assertTrue(isset($files[$file1->fid]), t('File was loaded successfully'));
  573. $this->assertTrue(isset($files[$file2->fid]), t('File was loaded successfully'));
  574. // Upload a third file to a subdirectory.
  575. $image3 = current($this->drupalGetTestFiles('image'));
  576. $image3_realpath = drupal_realpath($image3->uri);
  577. $dir = $this->randomName();
  578. $edit = array(
  579. 'files[file_test_upload]' => $image3_realpath,
  580. 'file_subdir' => $dir,
  581. );
  582. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  583. $this->assertResponse(200, t('Received a 200 response for posted test file.'));
  584. $this->assertRaw(t('You WIN!'));
  585. $this->assertTrue(is_file('temporary://' . $dir . '/' . trim(drupal_basename($image3_realpath))));
  586. // Check that file_load_multiple() with no arguments returns FALSE.
  587. $this->assertFalse(file_load_multiple(), t('No files were loaded.'));
  588. }
  589. /**
  590. * Test extension handling.
  591. */
  592. function testHandleExtension() {
  593. // The file being tested is a .gif which is in the default safe list
  594. // of extensions to allow when the extension validator isn't used. This is
  595. // implicitly tested at the testNormal() test. Here we tell
  596. // file_save_upload() to only allow ".foo".
  597. $extensions = 'foo';
  598. $edit = array(
  599. 'file_test_replace' => FILE_EXISTS_REPLACE,
  600. 'files[file_test_upload]' => drupal_realpath($this->image->uri),
  601. 'extensions' => $extensions,
  602. );
  603. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  604. $this->assertResponse(200, t('Received a 200 response for posted test file.'));
  605. $message = t('Only files with the following extensions are allowed:') . ' <em class="placeholder">' . $extensions . '</em>';
  606. $this->assertRaw($message, t('Can\'t upload a disallowed extension'));
  607. $this->assertRaw(t('Epic upload FAIL!'), t('Found the failure message.'));
  608. // Check that the correct hooks were called.
  609. $this->assertFileHooksCalled(array('validate'));
  610. // Reset the hook counters.
  611. file_test_reset();
  612. $extensions = 'foo ' . $this->image_extension;
  613. // Now tell file_save_upload() to allow the extension of our test image.
  614. $edit = array(
  615. 'file_test_replace' => FILE_EXISTS_REPLACE,
  616. 'files[file_test_upload]' => drupal_realpath($this->image->uri),
  617. 'extensions' => $extensions,
  618. );
  619. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  620. $this->assertResponse(200, t('Received a 200 response for posted test file.'));
  621. $this->assertNoRaw(t('Only files with the following extensions are allowed:'), t('Can upload an allowed extension.'));
  622. $this->assertRaw(t('You WIN!'), t('Found the success message.'));
  623. // Check that the correct hooks were called.
  624. $this->assertFileHooksCalled(array('validate', 'load', 'update'));
  625. // Reset the hook counters.
  626. file_test_reset();
  627. // Now tell file_save_upload() to allow any extension.
  628. $edit = array(
  629. 'file_test_replace' => FILE_EXISTS_REPLACE,
  630. 'files[file_test_upload]' => drupal_realpath($this->image->uri),
  631. 'allow_all_extensions' => TRUE,
  632. );
  633. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  634. $this->assertResponse(200, t('Received a 200 response for posted test file.'));
  635. $this->assertNoRaw(t('Only files with the following extensions are allowed:'), t('Can upload any extension.'));
  636. $this->assertRaw(t('You WIN!'), t('Found the success message.'));
  637. // Check that the correct hooks were called.
  638. $this->assertFileHooksCalled(array('validate', 'load', 'update'));
  639. }
  640. /**
  641. * Test dangerous file handling.
  642. */
  643. function testHandleDangerousFile() {
  644. // Allow the .php extension and make sure it gets renamed to .txt for
  645. // safety. Also check to make sure its MIME type was changed.
  646. $edit = array(
  647. 'file_test_replace' => FILE_EXISTS_REPLACE,
  648. 'files[file_test_upload]' => drupal_realpath($this->phpfile->uri),
  649. 'is_image_file' => FALSE,
  650. 'extensions' => 'php',
  651. );
  652. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  653. $this->assertResponse(200, t('Received a 200 response for posted test file.'));
  654. $message = t('For security reasons, your upload has been renamed to') . ' <em class="placeholder">' . $this->phpfile->filename . '.txt' . '</em>';
  655. $this->assertRaw($message, t('Dangerous file was renamed.'));
  656. $this->assertRaw(t('File MIME type is text/plain.'), t('Dangerous file\'s MIME type was changed.'));
  657. $this->assertRaw(t('You WIN!'), t('Found the success message.'));
  658. // Check that the correct hooks were called.
  659. $this->assertFileHooksCalled(array('validate', 'insert'));
  660. // Ensure dangerous files are not renamed when insecure uploads is TRUE.
  661. // Turn on insecure uploads.
  662. variable_set('allow_insecure_uploads', 1);
  663. // Reset the hook counters.
  664. file_test_reset();
  665. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  666. $this->assertResponse(200, t('Received a 200 response for posted test file.'));
  667. $this->assertNoRaw(t('For security reasons, your upload has been renamed'), t('Found no security message.'));
  668. $this->assertRaw(t('File name is !filename', array('!filename' => $this->phpfile->filename)), t('Dangerous file was not renamed when insecure uploads is TRUE.'));
  669. $this->assertRaw(t('You WIN!'), t('Found the success message.'));
  670. // Check that the correct hooks were called.
  671. $this->assertFileHooksCalled(array('validate', 'insert'));
  672. // Turn off insecure uploads.
  673. variable_set('allow_insecure_uploads', 0);
  674. }
  675. /**
  676. * Test file munge handling.
  677. */
  678. function testHandleFileMunge() {
  679. // Ensure insecure uploads are disabled for this test.
  680. variable_set('allow_insecure_uploads', 0);
  681. $this->image = file_move($this->image, $this->image->uri . '.foo.' . $this->image_extension);
  682. // Reset the hook counters to get rid of the 'move' we just called.
  683. file_test_reset();
  684. $extensions = $this->image_extension;
  685. $edit = array(
  686. 'files[file_test_upload]' => drupal_realpath($this->image->uri),
  687. 'extensions' => $extensions,
  688. );
  689. $munged_filename = $this->image->filename;
  690. $munged_filename = substr($munged_filename, 0, strrpos($munged_filename, '.'));
  691. $munged_filename .= '_.' . $this->image_extension;
  692. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  693. $this->assertResponse(200, t('Received a 200 response for posted test file.'));
  694. $this->assertRaw(t('For security reasons, your upload has been renamed'), t('Found security message.'));
  695. $this->assertRaw(t('File name is !filename', array('!filename' => $munged_filename)), t('File was successfully munged.'));
  696. $this->assertRaw(t('You WIN!'), t('Found the success message.'));
  697. // Check that the correct hooks were called.
  698. $this->assertFileHooksCalled(array('validate', 'insert'));
  699. // Ensure we don't munge files if we're allowing any extension.
  700. // Reset the hook counters.
  701. file_test_reset();
  702. $edit = array(
  703. 'files[file_test_upload]' => drupal_realpath($this->image->uri),
  704. 'allow_all_extensions' => TRUE,
  705. );
  706. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  707. $this->assertResponse(200, t('Received a 200 response for posted test file.'));
  708. $this->assertNoRaw(t('For security reasons, your upload has been renamed'), t('Found no security message.'));
  709. $this->assertRaw(t('File name is !filename', array('!filename' => $this->image->filename)), t('File was not munged when allowing any extension.'));
  710. $this->assertRaw(t('You WIN!'), t('Found the success message.'));
  711. // Check that the correct hooks were called.
  712. $this->assertFileHooksCalled(array('validate', 'insert'));
  713. }
  714. /**
  715. * Test renaming when uploading over a file that already exists.
  716. */
  717. function testExistingRename() {
  718. $edit = array(
  719. 'file_test_replace' => FILE_EXISTS_RENAME,
  720. 'files[file_test_upload]' => drupal_realpath($this->image->uri)
  721. );
  722. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  723. $this->assertResponse(200, t('Received a 200 response for posted test file.'));
  724. $this->assertRaw(t('You WIN!'), t('Found the success message.'));
  725. // Check that the correct hooks were called.
  726. $this->assertFileHooksCalled(array('validate', 'insert'));
  727. }
  728. /**
  729. * Test replacement when uploading over a file that already exists.
  730. */
  731. function testExistingReplace() {
  732. $edit = array(
  733. 'file_test_replace' => FILE_EXISTS_REPLACE,
  734. 'files[file_test_upload]' => drupal_realpath($this->image->uri)
  735. );
  736. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  737. $this->assertResponse(200, t('Received a 200 response for posted test file.'));
  738. $this->assertRaw(t('You WIN!'), t('Found the success message.'));
  739. // Check that the correct hooks were called.
  740. $this->assertFileHooksCalled(array('validate', 'load', 'update'));
  741. }
  742. /**
  743. * Test for failure when uploading over a file that already exists.
  744. */
  745. function testExistingError() {
  746. $edit = array(
  747. 'file_test_replace' => FILE_EXISTS_ERROR,
  748. 'files[file_test_upload]' => drupal_realpath($this->image->uri)
  749. );
  750. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  751. $this->assertResponse(200, t('Received a 200 response for posted test file.'));
  752. $this->assertRaw(t('Epic upload FAIL!'), t('Found the failure message.'));
  753. // Check that the no hooks were called while failing.
  754. $this->assertFileHooksCalled(array());
  755. }
  756. /**
  757. * Test for no failures when not uploading a file.
  758. */
  759. function testNoUpload() {
  760. $this->drupalPost('file-test/upload', array(), t('Submit'));
  761. $this->assertNoRaw(t('Epic upload FAIL!'), t('Failure message not found.'));
  762. }
  763. }
  764. /**
  765. * Test the file_save_upload() function on remote filesystems.
  766. */
  767. class RemoteFileSaveUploadTest extends FileSaveUploadTest {
  768. public static function getInfo() {
  769. $info = parent::getInfo();
  770. $info['group'] = 'File API (remote)';
  771. return $info;
  772. }
  773. function setUp() {
  774. parent::setUp('file_test');
  775. variable_set('file_default_scheme', 'dummy-remote');
  776. }
  777. }
  778. /**
  779. * Directory related tests.
  780. */
  781. class FileDirectoryTest extends FileTestCase {
  782. public static function getInfo() {
  783. return array(
  784. 'name' => 'File paths and directories',
  785. 'description' => 'Tests operations dealing with directories.',
  786. 'group' => 'File API',
  787. );
  788. }
  789. /**
  790. * Test directory handling functions.
  791. */
  792. function testFileCheckDirectoryHandling() {
  793. // A directory to operate on.
  794. $directory = file_default_scheme() . '://' . $this->randomName() . '/' . $this->randomName();
  795. $this->assertFalse(is_dir($directory), t('Directory does not exist prior to testing.'));
  796. // Non-existent directory.
  797. $this->assertFalse(file_prepare_directory($directory, 0), t('Error reported for non-existing directory.'), 'File');
  798. // Make a directory.
  799. $this->assertTrue(file_prepare_directory($directory, FILE_CREATE_DIRECTORY), t('No error reported when creating a new directory.'), 'File');
  800. // Make sure directory actually exists.
  801. $this->assertTrue(is_dir($directory), t('Directory actually exists.'), 'File');
  802. if (substr(PHP_OS, 0, 3) != 'WIN') {
  803. // PHP on Windows doesn't support any kind of useful read-only mode for
  804. // directories. When executing a chmod() on a directory, PHP only sets the
  805. // read-only flag, which doesn't prevent files to actually be written
  806. // in the directory on any recent version of Windows.
  807. // Make directory read only.
  808. @drupal_chmod($directory, 0444);
  809. $this->assertFalse(file_prepare_directory($directory, 0), t('Error reported for a non-writeable directory.'), 'File');
  810. // Test directory permission modification.
  811. $this->assertTrue(file_prepare_directory($directory, FILE_MODIFY_PERMISSIONS), t('No error reported when making directory writeable.'), 'File');
  812. }
  813. // Test that the directory has the correct permissions.
  814. $this->assertDirectoryPermissions($directory, variable_get('file_chmod_directory', 0775));
  815. // Remove .htaccess file to then test that it gets re-created.
  816. @drupal_unlink(file_default_scheme() . '://.htaccess');
  817. $this->assertFalse(is_file(file_default_scheme() . '://.htaccess'), t('Successfully removed the .htaccess file in the files directory.'), 'File');
  818. file_ensure_htaccess();
  819. $this->assertTrue(is_file(file_default_scheme() . '://.htaccess'), t('Successfully re-created the .htaccess file in the files directory.'), 'File');
  820. // Verify contents of .htaccess file.
  821. $file = file_get_contents(file_default_scheme() . '://.htaccess');
  822. $this->assertEqual($file, "SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006\nOptions None\nOptions +FollowSymLinks", t('The .htaccess file contains the proper content.'), 'File');
  823. }
  824. /**
  825. * This will take a directory and path, and find a valid filepath that is not
  826. * taken by another file.
  827. */
  828. function testFileCreateNewFilepath() {
  829. // First we test against an imaginary file that does not exist in a
  830. // directory.
  831. $basename = 'xyz.txt';
  832. $directory = 'misc';
  833. $original = $directory . '/' . $basename;
  834. $path = file_create_filename($basename, $directory);
  835. $this->assertEqual($path, $original, t('New filepath %new equals %original.', array('%new' => $path, '%original' => $original)), 'File');
  836. // Then we test against a file that already exists within that directory.
  837. $basename = 'druplicon.png';
  838. $original = $directory . '/' . $basename;
  839. $expected = $directory . '/druplicon_0.png';
  840. $path = file_create_filename($basename, $directory);
  841. $this->assertEqual($path, $expected, t('Creating a new filepath from %original equals %new.', array('%new' => $path, '%original' => $original)), 'File');
  842. // @TODO: Finally we copy a file into a directory several times, to ensure a properly iterating filename suffix.
  843. }
  844. /**
  845. * This will test the filepath for a destination based on passed flags and
  846. * whether or not the file exists.
  847. *
  848. * If a file exists, file_destination($destination, $replace) will either
  849. * return:
  850. * - the existing filepath, if $replace is FILE_EXISTS_REPLACE
  851. * - a new filepath if FILE_EXISTS_RENAME
  852. * - an error (returning FALSE) if FILE_EXISTS_ERROR.
  853. * If the file doesn't currently exist, then it will simply return the
  854. * filepath.
  855. */
  856. function testFileDestination() {
  857. // First test for non-existent file.
  858. $destination = 'misc/xyz.txt';
  859. $path = file_destination($destination, FILE_EXISTS_REPLACE);
  860. $this->assertEqual($path, $destination, t('Non-existing filepath destination is correct with FILE_EXISTS_REPLACE.'), 'File');
  861. $path = file_destination($destination, FILE_EXISTS_RENAME);
  862. $this->assertEqual($path, $destination, t('Non-existing filepath destination is correct with FILE_EXISTS_RENAME.'), 'File');
  863. $path = file_destination($destination, FILE_EXISTS_ERROR);
  864. $this->assertEqual($path, $destination, t('Non-existing filepath destination is correct with FILE_EXISTS_ERROR.'), 'File');
  865. $destination = 'misc/druplicon.png';
  866. $path = file_destination($destination, FILE_EXISTS_REPLACE);
  867. $this->assertEqual($path, $destination, t('Existing filepath destination remains the same with FILE_EXISTS_REPLACE.'), 'File');
  868. $path = file_destination($destination, FILE_EXISTS_RENAME);
  869. $this->assertNotEqual($path, $destination, t('A new filepath destination is created when filepath destination already exists with FILE_EXISTS_RENAME.'), 'File');
  870. $path = file_destination($destination, FILE_EXISTS_ERROR);
  871. $this->assertEqual($path, FALSE, t('An error is returned when filepath destination already exists with FILE_EXISTS_ERROR.'), 'File');
  872. }
  873. /**
  874. * Ensure that the file_directory_temp() function always returns a value.
  875. */
  876. function testFileDirectoryTemp() {
  877. // Start with an empty variable to ensure we have a clean slate.
  878. variable_set('file_temporary_path', '');
  879. $tmp_directory = file_directory_temp();
  880. $this->assertEqual(empty($tmp_directory), FALSE, t('file_directory_temp() returned a non-empty value.'));
  881. $setting = variable_get('file_temporary_path', '');
  882. $this->assertEqual($setting, $tmp_directory, t("The 'file_temporary_path' variable has the same value that file_directory_temp() returned."));
  883. }
  884. }
  885. /**
  886. * Directory related tests.
  887. */
  888. class RemoteFileDirectoryTest extends FileDirectoryTest {
  889. public static function getInfo() {
  890. $info = parent::getInfo();
  891. $info['group'] = 'File API (remote)';
  892. return $info;
  893. }
  894. function setUp() {
  895. parent::setUp('file_test');
  896. variable_set('file_default_scheme', 'dummy-remote');
  897. }
  898. }
  899. /**
  900. * Tests the file_scan_directory() function.
  901. */
  902. class FileScanDirectoryTest extends FileTestCase {
  903. public static function getInfo() {
  904. return array(
  905. 'name' => 'File scan directory',
  906. 'description' => 'Tests the file_scan_directory() function.',
  907. 'group' => 'File API',
  908. );
  909. }
  910. function setUp() {
  911. parent::setUp();
  912. $this->path = drupal_get_path('module', 'simpletest') . '/files';
  913. }
  914. /**
  915. * Check the format of the returned values.
  916. */
  917. function testReturn() {
  918. // Grab a listing of all the JavaSscript files and check that they're
  919. // passed to the callback.
  920. $all_files = file_scan_directory($this->path, '/^javascript-/');
  921. ksort($all_files);
  922. $this->assertEqual(2, count($all_files), t('Found two, expected javascript files.'));
  923. // Check the first file.
  924. $file = reset($all_files);
  925. $this->assertEqual(key($all_files), $file->uri, t('Correct array key was used for the first returned file.'));
  926. $this->assertEqual($file->uri, $this->path . '/javascript-1.txt', t('First file name was set correctly.'));
  927. $this->assertEqual($file->filename, 'javascript-1.txt', t('First basename was set correctly'));
  928. $this->assertEqual($file->name, 'javascript-1', t('First name was set correctly.'));
  929. // Check the second file.
  930. $file = next($all_files);
  931. $this->assertEqual(key($all_files), $file->uri, t('Correct array key was used for the second returned file.'));
  932. $this->assertEqual($file->uri, $this->path . '/javascript-2.script', t('Second file name was set correctly.'));
  933. $this->assertEqual($file->filename, 'javascript-2.script', t('Second basename was set correctly'));
  934. $this->assertEqual($file->name, 'javascript-2', t('Second name was set correctly.'));
  935. }
  936. /**
  937. * Check that the callback function is called correctly.
  938. */
  939. function testOptionCallback() {
  940. // When nothing is matched nothing should be passed to the callback.
  941. $all_files = file_scan_directory($this->path, '/^NONEXISTINGFILENAME/', array('callback' => 'file_test_file_scan_callback'));
  942. $this->assertEqual(0, count($all_files), t('No files were found.'));
  943. $results = file_test_file_scan_callback();
  944. file_test_file_scan_callback_reset();
  945. $this->assertEqual(0, count($results), t('No files were passed to the callback.'));
  946. // Grab a listing of all the JavaSscript files and check that they're
  947. // passed to the callback.
  948. $all_files = file_scan_directory($this->path, '/^javascript-/', array('callback' => 'file_test_file_scan_callback'));
  949. $this->assertEqual(2, count($all_files), t('Found two, expected javascript files.'));
  950. $results = file_test_file_scan_callback();
  951. file_test_file_scan_callback_reset();
  952. $this->assertEqual(2, count($results), t('Files were passed to the callback.'));
  953. }
  954. /**
  955. * Check that the no-mask parameter is honored.
  956. */
  957. function testOptionNoMask() {
  958. // Grab a listing of all the JavaSscript files.
  959. $all_files = file_scan_directory($this->path, '/^javascript-/');
  960. $this->assertEqual(2, count($all_files), t('Found two, expected javascript files.'));
  961. // Now use the nomast parameter to filter out the .script file.
  962. $filtered_files = file_scan_directory($this->path, '/^javascript-/', array('nomask' => '/.script$/'));
  963. $this->assertEqual(1, count($filtered_files), t('Filtered correctly.'));
  964. }
  965. /**
  966. * Check that key parameter sets the return value's key.
  967. */
  968. function testOptionKey() {
  969. // "filename", for the path starting with $dir.
  970. $expected = array($this->path . '/javascript-1.txt', $this->path . '/javascript-2.script');
  971. $actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array('key' => 'filepath')));
  972. sort($actual);
  973. $this->assertEqual($expected, $actual, t('Returned the correct values for the filename key.'));
  974. // "basename", for the basename of the file.
  975. $expected = array('javascript-1.txt', 'javascript-2.script');
  976. $actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array('key' => 'filename')));
  977. sort($actual);
  978. $this->assertEqual($expected, $actual, t('Returned the correct values for the basename key.'));
  979. // "name" for the name of the file without an extension.
  980. $expected = array('javascript-1', 'javascript-2');
  981. $actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array('key' => 'name')));
  982. sort($actual);
  983. $this->assertEqual($expected, $actual, t('Returned the correct values for the name key.'));
  984. // Invalid option that should default back to "filename".
  985. $expected = array($this->path . '/javascript-1.txt', $this->path . '/javascript-2.script');
  986. $actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array('key' => 'INVALID')));
  987. sort($actual);
  988. $this->assertEqual($expected, $actual, t('An invalid key defaulted back to the default.'));
  989. }
  990. /**
  991. * Check that the recurse option decends into subdirectories.
  992. */
  993. function testOptionRecurse() {
  994. $files = file_scan_directory(drupal_get_path('module', 'simpletest'), '/^javascript-/', array('recurse' => FALSE));
  995. $this->assertTrue(empty($files), t("Without recursion couldn't find javascript files."));
  996. $files = file_scan_directory(drupal_get_path('module', 'simpletest'), '/^javascript-/', array('recurse' => TRUE));
  997. $this->assertEqual(2, count($files), t('With recursion we found the expected javascript files.'));
  998. }
  999. /**
  1000. * Check that the min_depth options lets us ignore files in the starting
  1001. * directory.
  1002. */
  1003. function testOptionMinDepth() {
  1004. $files = file_scan_directory($this->path, '/^javascript-/', array('min_depth' => 0));
  1005. $this->assertEqual(2, count($files), t('No minimum-depth gets files in current directory.'));
  1006. $files = file_scan_directory($this->path, '/^javascript-/', array('min_depth' => 1));
  1007. $this->assertTrue(empty($files), t("Minimum-depth of 1 successfully excludes files from current directory."));
  1008. }
  1009. }
  1010. /**
  1011. * Tests the file_scan_directory() function on remote filesystems.
  1012. */
  1013. class RemoteFileScanDirectoryTest extends FileScanDirectoryTest {
  1014. public static function getInfo() {
  1015. $info = parent::getInfo();
  1016. $info['group'] = 'File API (remote)';
  1017. return $info;
  1018. }
  1019. function setUp() {
  1020. parent::setUp('file_test');
  1021. variable_set('file_default_scheme', 'dummy-remote');
  1022. }
  1023. }
  1024. /**
  1025. * Deletion related tests.
  1026. */
  1027. class FileUnmanagedDeleteTest extends FileTestCase {
  1028. public static function getInfo() {
  1029. return array(
  1030. 'name' => 'Unmanaged file delete',
  1031. 'description' => 'Tests the unmanaged file delete function.',
  1032. 'group' => 'File API',
  1033. );
  1034. }
  1035. /**
  1036. * Delete a normal file.
  1037. */
  1038. function testNormal() {
  1039. // Create a file for testing
  1040. $file = $this->createFile();
  1041. // Delete a regular file
  1042. $this->assertTrue(file_unmanaged_delete($file->uri), t('Deleted worked.'));
  1043. $this->assertFalse(file_exists($file->uri), t('Test file has actually been deleted.'));
  1044. }
  1045. /**
  1046. * Try deleting a missing file.
  1047. */
  1048. function testMissing() {
  1049. // Try to delete a non-existing file
  1050. $this->assertTrue(file_unmanaged_delete(file_default_scheme() . '/' . $this->randomName()), t('Returns true when deleting a non-existent file.'));
  1051. }
  1052. /**
  1053. * Try deleting a directory.
  1054. */
  1055. function testDirectory() {
  1056. // A directory to operate on.
  1057. $directory = $this->createDirectory();
  1058. // Try to delete a directory
  1059. $this->assertFalse(file_unmanaged_delete($directory), t('Could not delete the delete directory.'));
  1060. $this->assertTrue(file_exists($directory), t('Directory has not been deleted.'));
  1061. }
  1062. }
  1063. /**
  1064. * Deletion related tests on remote filesystems.
  1065. */
  1066. class RemoteFileUnmanagedDeleteTest extends FileUnmanagedDeleteTest {
  1067. public static function getInfo() {
  1068. $info = parent::getInfo();
  1069. $info['group'] = 'File API (remote)';
  1070. return $info;
  1071. }
  1072. function setUp() {
  1073. parent::setUp('file_test');
  1074. variable_set('file_default_scheme', 'dummy-remote');
  1075. }
  1076. }
  1077. /**
  1078. * Deletion related tests.
  1079. */
  1080. class FileUnmanagedDeleteRecursiveTest extends FileTestCase {
  1081. public static function getInfo() {
  1082. return array(
  1083. 'name' => 'Unmanaged recursive file delete',
  1084. 'description' => 'Tests the unmanaged file delete recursive function.',
  1085. 'group' => 'File API',
  1086. );
  1087. }
  1088. /**
  1089. * Delete a normal file.
  1090. */
  1091. function testSingleFile() {
  1092. // Create a file for testing
  1093. $filepath = file_default_scheme() . '://' . $this->randomName();
  1094. file_put_contents($filepath, '');
  1095. // Delete the file.
  1096. $this->assertTrue(file_unmanaged_delete_recursive($filepath), t('Function reported success.'));
  1097. $this->assertFalse(file_exists($filepath), t('Test file has been deleted.'));
  1098. }
  1099. /**
  1100. * Try deleting an empty directory.
  1101. */
  1102. function testEmptyDirectory() {
  1103. // A directory to operate on.
  1104. $directory = $this->createDirectory();
  1105. // Delete the directory.
  1106. $this->assertTrue(file_unmanaged_delete_recursive($directory), t('Function reported success.'));
  1107. $this->assertFalse(file_exists($directory), t('Directory has been deleted.'));
  1108. }
  1109. /**
  1110. * Try deleting a directory with some files.
  1111. */
  1112. function testDirectory() {
  1113. // A directory to operate on.
  1114. $directory = $this->createDirectory();
  1115. $filepathA = $directory . '/A';
  1116. $filepathB = $directory . '/B';
  1117. file_put_contents($filepathA, '');
  1118. file_put_contents($filepathB, '');
  1119. // Delete the directory.
  1120. $this->assertTrue(file_unmanaged_delete_recursive($directory), t('Function reported success.'));
  1121. $this->assertFalse(file_exists($filepathA), t('Test file A has been deleted.'));
  1122. $this->assertFalse(file_exists($filepathB), t('Test file B has been deleted.'));
  1123. $this->assertFalse(file_exists($directory), t('Directory has been deleted.'));
  1124. }
  1125. /**
  1126. * Try deleting subdirectories with some files.
  1127. */
  1128. function testSubDirectory() {
  1129. // A directory to operate on.
  1130. $directory = $this->createDirectory();
  1131. $subdirectory = $this->createDirectory($directory . '/sub');
  1132. $filepathA = $directory . '/A';
  1133. $filepathB = $subdirectory . '/B';
  1134. file_put_contents($filepathA, '');
  1135. file_put_contents($filepathB, '');
  1136. // Delete the directory.
  1137. $this->assertTrue(file_unmanaged_delete_recursive($directory), t('Function reported success.'));
  1138. $this->assertFalse(file_exists($filepathA), t('Test file A has been deleted.'));
  1139. $this->assertFalse(file_exists($filepathB), t('Test file B has been deleted.'));
  1140. $this->assertFalse(file_exists($subdirectory), t('Subdirectory has been deleted.'));
  1141. $this->assertFalse(file_exists($directory), t('Directory has been deleted.'));
  1142. }
  1143. }
  1144. /**
  1145. * Deletion related tests on remote filesystems.
  1146. */
  1147. class RemoteFileUnmanagedDeleteRecursiveTest extends FileUnmanagedDeleteRecursiveTest {
  1148. public static function getInfo() {
  1149. $info = parent::getInfo();
  1150. $info['group'] = 'File API (remote)';
  1151. return $info;
  1152. }
  1153. function setUp() {
  1154. parent::setUp('file_test');
  1155. variable_set('file_default_scheme', 'dummy-remote');
  1156. }
  1157. }
  1158. /**
  1159. * Unmanaged move related tests.
  1160. */
  1161. class FileUnmanagedMoveTest extends FileTestCase {
  1162. public static function getInfo() {
  1163. return array(
  1164. 'name' => 'Unmanaged file moving',
  1165. 'description' => 'Tests the unmanaged file move function.',
  1166. 'group' => 'File API',
  1167. );
  1168. }
  1169. /**
  1170. * Move a normal file.
  1171. */
  1172. function testNormal() {
  1173. // Create a file for testing
  1174. $file = $this->createFile();
  1175. // Moving to a new name.
  1176. $desired_filepath = 'public://' . $this->randomName();
  1177. $new_filepath = file_unmanaged_move($file->uri, $desired_filepath, FILE_EXISTS_ERROR);
  1178. $this->assertTrue($new_filepath, t('Move was successful.'));
  1179. $this->assertEqual($new_filepath, $desired_filepath, t('Returned expected filepath.'));
  1180. $this->assertTrue(file_exists($new_filepath), t('File exists at the new location.'));
  1181. $this->assertFalse(file_exists($file->uri), t('No file remains at the old location.'));
  1182. $this->assertFilePermissions($new_filepath, variable_get('file_chmod_file', 0664));
  1183. // Moving with rename.
  1184. $desired_filepath = 'public://' . $this->randomName();
  1185. $this->assertTrue(file_exists($new_filepath), t('File exists before moving.'));
  1186. $this->assertTrue(file_put_contents($desired_filepath, ' '), t('Created a file so a rename will have to happen.'));
  1187. $newer_filepath = file_unmanaged_move($new_filepath, $desired_filepath, FILE_EXISTS_RENAME);
  1188. $this->assertTrue($newer_filepath, t('Move was successful.'));
  1189. $this->assertNotEqual($newer_filepath, $desired_filepath, t('Returned expected filepath.'));
  1190. $this->assertTrue(file_exists($newer_filepath), t('File exists at the new location.'));
  1191. $this->assertFalse(file_exists($new_filepath), t('No file remains at the old location.'));
  1192. $this->assertFilePermissions($newer_filepath, variable_get('file_chmod_file', 0664));
  1193. // TODO: test moving to a directory (rather than full directory/file path)
  1194. // TODO: test creating and moving normal files (rather than streams)
  1195. }
  1196. /**
  1197. * Try to move a missing file.
  1198. */
  1199. function testMissing() {
  1200. // Move non-existent file.
  1201. $new_filepath = file_unmanaged_move($this->randomName(), $this->randomName());
  1202. $this->assertFalse($new_filepath, t('Moving a missing file fails.'));
  1203. }
  1204. /**
  1205. * Try to move a file onto itself.
  1206. */
  1207. function testOverwriteSelf() {
  1208. // Create a file for testing.
  1209. $file = $this->createFile();
  1210. // Move the file onto itself without renaming shouldn't make changes.
  1211. $new_filepath = file_unmanaged_move($file->uri, $file->uri, FILE_EXISTS_REPLACE);
  1212. $this->assertFalse($new_filepath, t('Moving onto itself without renaming fails.'));
  1213. $this->assertTrue(file_exists($file->uri), t('File exists after moving onto itself.'));
  1214. // Move the file onto itself with renaming will result in a new filename.
  1215. $new_filepath = file_unmanaged_move($file->uri, $file->uri, FILE_EXISTS_RENAME);
  1216. $this->assertTrue($new_filepath, t('Moving onto itself with renaming works.'));
  1217. $this->assertFalse(file_exists($file->uri), t('Original file has been removed.'));
  1218. $this->assertTrue(file_exists($new_filepath), t('File exists after moving onto itself.'));
  1219. }
  1220. }
  1221. /**
  1222. * Unmanaged move related tests on remote filesystems.
  1223. */
  1224. class RemoteFileUnmanagedMoveTest extends FileUnmanagedMoveTest {
  1225. public static function getInfo() {
  1226. $info = parent::getInfo();
  1227. $info['group'] = 'File API (remote)';
  1228. return $info;
  1229. }
  1230. function setUp() {
  1231. parent::setUp('file_test');
  1232. variable_set('file_default_scheme', 'dummy-remote');
  1233. }
  1234. }
  1235. /**
  1236. * Unmanaged copy related tests.
  1237. */
  1238. class FileUnmanagedCopyTest extends FileTestCase {
  1239. public static function getInfo() {
  1240. return array(
  1241. 'name' => 'Unmanaged file copying',
  1242. 'description' => 'Tests the unmanaged file copy function.',
  1243. 'group' => 'File API',
  1244. );
  1245. }
  1246. /**
  1247. * Copy a normal file.
  1248. */
  1249. function testNormal() {
  1250. // Create a file for testing
  1251. $file = $this->createFile();
  1252. // Copying to a new name.
  1253. $desired_filepath = 'public://' . $this->randomName();
  1254. $new_filepath = file_unmanaged_copy($file->uri, $desired_filepath, FILE_EXISTS_ERROR);
  1255. $this->assertTrue($new_filepath, t('Copy was successful.'));
  1256. $this->assertEqual($new_filepath, $desired_filepath, t('Returned expected filepath.'));
  1257. $this->assertTrue(file_exists($file->uri), t('Original file remains.'));
  1258. $this->assertTrue(file_exists($new_filepath), t('New file exists.'));
  1259. $this->assertFilePermissions($new_filepath, variable_get('file_chmod_file', 0664));
  1260. // Copying with rename.
  1261. $desired_filepath = 'public://' . $this->randomName();
  1262. $this->assertTrue(file_put_contents($desired_filepath, ' '), t('Created a file so a rename will have to happen.'));
  1263. $newer_filepath = file_unmanaged_copy($file->uri, $desired_filepath, FILE_EXISTS_RENAME);
  1264. $this->assertTrue($newer_filepath, t('Copy was successful.'));
  1265. $this->assertNotEqual($newer_filepath, $desired_filepath, t('Returned expected filepath.'));
  1266. $this->assertTrue(file_exists($file->uri), t('Original file remains.'));
  1267. $this->assertTrue(file_exists($newer_filepath), t('New file exists.'));
  1268. $this->assertFilePermissions($newer_filepath, variable_get('file_chmod_file', 0664));
  1269. // TODO: test copying to a directory (rather than full directory/file path)
  1270. // TODO: test copying normal files using normal paths (rather than only streams)
  1271. }
  1272. /**
  1273. * Copy a non-existent file.
  1274. */
  1275. function testNonExistent() {
  1276. // Copy non-existent file
  1277. $desired_filepath = $this->randomName();
  1278. $this->assertFalse(file_exists($desired_filepath), t("Randomly named file doesn't exists."));
  1279. $new_filepath = file_unmanaged_copy($desired_filepath, $this->randomName());
  1280. $this->assertFalse($new_filepath, t('Copying a missing file fails.'));
  1281. }
  1282. /**
  1283. * Copy a file onto itself.
  1284. */
  1285. function testOverwriteSelf() {
  1286. // Create a file for testing
  1287. $file = $this->createFile();
  1288. // Copy the file onto itself with renaming works.
  1289. $new_filepath = file_unmanaged_copy($file->uri, $file->uri, FILE_EXISTS_RENAME);
  1290. $this->assertTrue($new_filepath, t('Copying onto itself with renaming works.'));
  1291. $this->assertNotEqual($new_filepath, $file->uri, t('Copied file has a new name.'));
  1292. $this->assertTrue(file_exists($file->uri), t('Original file exists after copying onto itself.'));
  1293. $this->assertTrue(file_exists($new_filepath), t('Copied file exists after copying onto itself.'));
  1294. $this->assertFilePermissions($new_filepath, variable_get('file_chmod_file', 0664));
  1295. // Copy the file onto itself without renaming fails.
  1296. $new_filepath = file_unmanaged_copy($file->uri, $file->uri, FILE_EXISTS_ERROR);
  1297. $this->assertFalse($new_filepath, t('Copying onto itself without renaming fails.'));
  1298. $this->assertTrue(file_exists($file->uri), t('File exists after copying onto itself.'));
  1299. // Copy the file into same directory without renaming fails.
  1300. $new_filepath = file_unmanaged_copy($file->uri, drupal_dirname($file->uri), FILE_EXISTS_ERROR);
  1301. $this->assertFalse($new_filepath, t('Copying onto itself fails.'));
  1302. $this->assertTrue(file_exists($file->uri), t('File exists after copying onto itself.'));
  1303. // Copy the file into same directory with renaming works.
  1304. $new_filepath = file_unmanaged_copy($file->uri, drupal_dirname($file->uri), FILE_EXISTS_RENAME);
  1305. $this->assertTrue($new_filepath, t('Copying into same directory works.'));
  1306. $this->assertNotEqual($new_filepath, $file->uri, t('Copied file has a new name.'));
  1307. $this->assertTrue(file_exists($file->uri), t('Original file exists after copying onto itself.'));
  1308. $this->assertTrue(file_exists($new_filepath), t('Copied file exists after copying onto itself.'));
  1309. $this->assertFilePermissions($new_filepath, variable_get('file_chmod_file', 0664));
  1310. }
  1311. }
  1312. /**
  1313. * Unmanaged copy related tests on remote filesystems.
  1314. */
  1315. class RemoteFileUnmanagedCopyTest extends FileUnmanagedCopyTest {
  1316. public static function getInfo() {
  1317. $info = parent::getInfo();
  1318. $info['group'] = 'File API (remote)';
  1319. return $info;
  1320. }
  1321. function setUp() {
  1322. parent::setUp('file_test');
  1323. variable_set('file_default_scheme', 'dummy-remote');
  1324. }
  1325. }
  1326. /**
  1327. * Deletion related tests.
  1328. */
  1329. class FileDeleteTest extends FileHookTestCase {
  1330. public static function getInfo() {
  1331. return array(
  1332. 'name' => 'File delete',
  1333. 'description' => 'Tests the file delete function.',
  1334. 'group' => 'File API',
  1335. );
  1336. }
  1337. /**
  1338. * Tries deleting a normal file (as opposed to a directory, symlink, etc).
  1339. */
  1340. function testUnused() {
  1341. $file = $this->createFile();
  1342. // Check that deletion removes the file and database record.
  1343. $this->assertTrue(is_file($file->uri), t('File exists.'));
  1344. $this->assertIdentical(file_delete($file), TRUE, t('Delete worked.'));
  1345. $this->assertFileHooksCalled(array('delete'));
  1346. $this->assertFalse(file_exists($file->uri), t('Test file has actually been deleted.'));
  1347. $this->assertFalse(file_load($file->fid), t('File was removed from the database.'));
  1348. }
  1349. /**
  1350. * Tries deleting a file that is in use.
  1351. */
  1352. function testInUse() {
  1353. $file = $this->createFile();
  1354. file_usage_add($file, 'testing', 'test', 1);
  1355. file_usage_add($file, 'testing', 'test', 1);
  1356. file_usage_delete($file, 'testing', 'test', 1);
  1357. file_delete($file);
  1358. $usage = file_usage_list($file);
  1359. $this->assertEqual($usage['testing']['test'], array(1 => 1), t('Test file is still in use.'));
  1360. $this->assertTrue(file_exists($file->uri), t('File still exists on the disk.'));
  1361. $this->assertTrue(file_load($file->fid), t('File still exists in the database.'));
  1362. // Clear out the call to hook_file_load().
  1363. file_test_reset();
  1364. file_usage_delete($file, 'testing', 'test', 1);
  1365. file_delete($file);
  1366. $usage = file_usage_list($file);
  1367. $this->assertFileHooksCalled(array('delete'));
  1368. $this->assertTrue(empty($usage), t('File usage data was removed.'));
  1369. $this->assertFalse(file_exists($file->uri), t('File has been deleted after its last usage was removed.'));
  1370. $this->assertFalse(file_load($file->fid), t('File was removed from the database.'));
  1371. }
  1372. }
  1373. /**
  1374. * Move related tests
  1375. */
  1376. class FileMoveTest extends FileHookTestCase {
  1377. public static function getInfo() {
  1378. return array(
  1379. 'name' => 'File moving',
  1380. 'description' => 'Tests the file move function.',
  1381. 'group' => 'File API',
  1382. );
  1383. }
  1384. /**
  1385. * Move a normal file.
  1386. */
  1387. function testNormal() {
  1388. $contents = $this->randomName(10);
  1389. $source = $this->createFile(NULL, $contents);
  1390. $desired_filepath = 'public://' . $this->randomName();
  1391. // Clone the object so we don't have to worry about the function changing
  1392. // our reference copy.
  1393. $result = file_move(clone $source, $desired_filepath, FILE_EXISTS_ERROR);
  1394. // Check the return status and that the contents changed.
  1395. $this->assertTrue($result, t('File moved successfully.'));
  1396. $this->assertFalse(file_exists($source->uri));
  1397. $this->assertEqual($contents, file_get_contents($result->uri), t('Contents of file correctly written.'));
  1398. // Check that the correct hooks were called.
  1399. $this->assertFileHooksCalled(array('move', 'load', 'update'));
  1400. // Make sure we got the same file back.
  1401. $this->assertEqual($source->fid, $result->fid, t("Source file id's' %fid is unchanged after move.", array('%fid' => $source->fid)));
  1402. // Reload the file from the database and check that the changes were
  1403. // actually saved.
  1404. $loaded_file = file_load($result->fid, TRUE);
  1405. $this->assertTrue($loaded_file, t('File can be loaded from the database.'));
  1406. $this->assertFileUnchanged($result, $loaded_file);
  1407. }
  1408. /**
  1409. * Test renaming when moving onto a file that already exists.
  1410. */
  1411. function testExistingRename() {
  1412. // Setup a file to overwrite.
  1413. $contents = $this->randomName(10);
  1414. $source = $this->createFile(NULL, $contents);
  1415. $target = $this->createFile();
  1416. $this->assertDifferentFile($source, $target);
  1417. // Clone the object so we don't have to worry about the function changing
  1418. // our reference copy.
  1419. $result = file_move(clone $source, $target->uri, FILE_EXISTS_RENAME);
  1420. // Check the return status and that the contents changed.
  1421. $this->assertTrue($result, t('File moved successfully.'));
  1422. $this->assertFalse(file_exists($source->uri));
  1423. $this->assertEqual($contents, file_get_contents($result->uri), t('Contents of file correctly written.'));
  1424. // Check that the correct hooks were called.
  1425. $this->assertFileHooksCalled(array('move', 'load', 'update'));
  1426. // Compare the returned value to what made it into the database.
  1427. $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
  1428. // The target file should not have been altered.
  1429. $this->assertFileUnchanged($target, file_load($target->fid, TRUE));
  1430. // Make sure we end up with two distinct files afterwards.
  1431. $this->assertDifferentFile($target, $result);
  1432. // Compare the source and results.
  1433. $loaded_source = file_load($source->fid, TRUE);
  1434. $this->assertEqual($loaded_source->fid, $result->fid, t("Returned file's id matches the source."));
  1435. $this->assertNotEqual($loaded_source->uri, $source->uri, t("Returned file path has changed from the original."));
  1436. }
  1437. /**
  1438. * Test replacement when moving onto a file that already exists.
  1439. */
  1440. function testExistingReplace() {
  1441. // Setup a file to overwrite.
  1442. $contents = $this->randomName(10);
  1443. $source = $this->createFile(NULL, $contents);
  1444. $target = $this->createFile();
  1445. $this->assertDifferentFile($source, $target);
  1446. // Clone the object so we don't have to worry about the function changing
  1447. // our reference copy.
  1448. $result = file_move(clone $source, $target->uri, FILE_EXISTS_REPLACE);
  1449. // Look at the results.
  1450. $this->assertEqual($contents, file_get_contents($result->uri), t('Contents of file were overwritten.'));
  1451. $this->assertFalse(file_exists($source->uri));
  1452. $this->assertTrue($result, t('File moved successfully.'));
  1453. // Check that the correct hooks were called.
  1454. $this->assertFileHooksCalled(array('move', 'update', 'delete', 'load'));
  1455. // Reload the file from the database and check that the changes were
  1456. // actually saved.
  1457. $loaded_result = file_load($result->fid, TRUE);
  1458. $this->assertFileUnchanged($result, $loaded_result);
  1459. // Check that target was re-used.
  1460. $this->assertSameFile($target, $loaded_result);
  1461. // Source and result should be totally different.
  1462. $this->assertDifferentFile($source, $loaded_result);
  1463. }
  1464. /**
  1465. * Test replacement when moving onto itself.
  1466. */
  1467. function testExistingReplaceSelf() {
  1468. // Setup a file to overwrite.
  1469. $contents = $this->randomName(10);
  1470. $source = $this->createFile(NULL, $contents);
  1471. // Copy the file over itself. Clone the object so we don't have to worry
  1472. // about the function changing our reference copy.
  1473. $result = file_move(clone $source, $source->uri, FILE_EXISTS_REPLACE);
  1474. $this->assertFalse($result, t('File move failed.'));
  1475. $this->assertEqual($contents, file_get_contents($source->uri), t('Contents of file were not altered.'));
  1476. // Check that no hooks were called while failing.
  1477. $this->assertFileHooksCalled(array());
  1478. // Load the file from the database and make sure it is identical to what
  1479. // was returned.
  1480. $this->assertFileUnchanged($source, file_load($source->fid, TRUE));
  1481. }
  1482. /**
  1483. * Test that moving onto an existing file fails when FILE_EXISTS_ERROR is
  1484. * specified.
  1485. */
  1486. function testExistingError() {
  1487. $contents = $this->randomName(10);
  1488. $source = $this->createFile();
  1489. $target = $this->createFile(NULL, $contents);
  1490. $this->assertDifferentFile($source, $target);
  1491. // Clone the object so we don't have to worry about the function changing
  1492. // our reference copy.
  1493. $result = file_move(clone $source, $target->uri, FILE_EXISTS_ERROR);
  1494. // Check the return status and that the contents did not change.
  1495. $this->assertFalse($result, t('File move failed.'));
  1496. $this->assertTrue(file_exists($source->uri));
  1497. $this->assertEqual($contents, file_get_contents($target->uri), t('Contents of file were not altered.'));
  1498. // Check that no hooks were called while failing.
  1499. $this->assertFileHooksCalled(array());
  1500. // Load the file from the database and make sure it is identical to what
  1501. // was returned.
  1502. $this->assertFileUnchanged($source, file_load($source->fid, TRUE));
  1503. $this->assertFileUnchanged($target, file_load($target->fid, TRUE));
  1504. }
  1505. }
  1506. /**
  1507. * Copy related tests.
  1508. */
  1509. class FileCopyTest extends FileHookTestCase {
  1510. public static function getInfo() {
  1511. return array(
  1512. 'name' => 'File copying',
  1513. 'description' => 'Tests the file copy function.',
  1514. 'group' => 'File API',
  1515. );
  1516. }
  1517. /**
  1518. * Test file copying in the normal, base case.
  1519. */
  1520. function testNormal() {
  1521. $contents = $this->randomName(10);
  1522. $source = $this->createFile(NULL, $contents);
  1523. $desired_uri = 'public://' . $this->randomName();
  1524. // Clone the object so we don't have to worry about the function changing
  1525. // our reference copy.
  1526. $result = file_copy(clone $source, $desired_uri, FILE_EXISTS_ERROR);
  1527. // Check the return status and that the contents changed.
  1528. $this->assertTrue($result, t('File copied successfully.'));
  1529. $this->assertEqual($contents, file_get_contents($result->uri), t('Contents of file were copied correctly.'));
  1530. // Check that the correct hooks were called.
  1531. $this->assertFileHooksCalled(array('copy', 'insert'));
  1532. $this->assertDifferentFile($source, $result);
  1533. $this->assertEqual($result->uri, $desired_uri, t('The copied file object has the desired filepath.'));
  1534. $this->assertTrue(file_exists($source->uri), t('The original file still exists.'));
  1535. $this->assertTrue(file_exists($result->uri), t('The copied file exists.'));
  1536. // Reload the file from the database and check that the changes were
  1537. // actually saved.
  1538. $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
  1539. }
  1540. /**
  1541. * Test renaming when copying over a file that already exists.
  1542. */
  1543. function testExistingRename() {
  1544. // Setup a file to overwrite.
  1545. $contents = $this->randomName(10);
  1546. $source = $this->createFile(NULL, $contents);
  1547. $target = $this->createFile();
  1548. $this->assertDifferentFile($source, $target);
  1549. // Clone the object so we don't have to worry about the function changing
  1550. // our reference copy.
  1551. $result = file_copy(clone $source, $target->uri, FILE_EXISTS_RENAME);
  1552. // Check the return status and that the contents changed.
  1553. $this->assertTrue($result, t('File copied successfully.'));
  1554. $this->assertEqual($contents, file_get_contents($result->uri), t('Contents of file were copied correctly.'));
  1555. $this->assertNotEqual($result->uri, $source->uri, t('Returned file path has changed from the original.'));
  1556. // Check that the correct hooks were called.
  1557. $this->assertFileHooksCalled(array('copy', 'insert'));
  1558. // Load all the affected files to check the changes that actually made it
  1559. // to the database.
  1560. $loaded_source = file_load($source->fid, TRUE);
  1561. $loaded_target = file_load($target->fid, TRUE);
  1562. $loaded_result = file_load($result->fid, TRUE);
  1563. // Verify that the source file wasn't changed.
  1564. $this->assertFileUnchanged($source, $loaded_source);
  1565. // Verify that what was returned is what's in the database.
  1566. $this->assertFileUnchanged($result, $loaded_result);
  1567. // Make sure we end up with three distinct files afterwards.
  1568. $this->assertDifferentFile($loaded_source, $loaded_target);
  1569. $this->assertDifferentFile($loaded_target, $loaded_result);
  1570. $this->assertDifferentFile($loaded_source, $loaded_result);
  1571. }
  1572. /**
  1573. * Test replacement when copying over a file that already exists.
  1574. */
  1575. function testExistingReplace() {
  1576. // Setup a file to overwrite.
  1577. $contents = $this->randomName(10);
  1578. $source = $this->createFile(NULL, $contents);
  1579. $target = $this->createFile();
  1580. $this->assertDifferentFile($source, $target);
  1581. // Clone the object so we don't have to worry about the function changing
  1582. // our reference copy.
  1583. $result = file_copy(clone $source, $target->uri, FILE_EXISTS_REPLACE);
  1584. // Check the return status and that the contents changed.
  1585. $this->assertTrue($result, t('File copied successfully.'));
  1586. $this->assertEqual($contents, file_get_contents($result->uri), t('Contents of file were overwritten.'));
  1587. $this->assertDifferentFile($source, $result);
  1588. // Check that the correct hooks were called.
  1589. $this->assertFileHooksCalled(array('load', 'copy', 'update'));
  1590. // Load all the affected files to check the changes that actually made it
  1591. // to the database.
  1592. $loaded_source = file_load($source->fid, TRUE);
  1593. $loaded_target = file_load($target->fid, TRUE);
  1594. $loaded_result = file_load($result->fid, TRUE);
  1595. // Verify that the source file wasn't changed.
  1596. $this->assertFileUnchanged($source, $loaded_source);
  1597. // Verify that what was returned is what's in the database.
  1598. $this->assertFileUnchanged($result, $loaded_result);
  1599. // Target file was reused for the result.
  1600. $this->assertFileUnchanged($loaded_target, $loaded_result);
  1601. }
  1602. /**
  1603. * Test that copying over an existing file fails when FILE_EXISTS_ERROR is
  1604. * specified.
  1605. */
  1606. function testExistingError() {
  1607. $contents = $this->randomName(10);
  1608. $source = $this->createFile();
  1609. $target = $this->createFile(NULL, $contents);
  1610. $this->assertDifferentFile($source, $target);
  1611. // Clone the object so we don't have to worry about the function changing
  1612. // our reference copy.
  1613. $result = file_copy(clone $source, $target->uri, FILE_EXISTS_ERROR);
  1614. // Check the return status and that the contents were not changed.
  1615. $this->assertFalse($result, t('File copy failed.'));
  1616. $this->assertEqual($contents, file_get_contents($target->uri), t('Contents of file were not altered.'));
  1617. // Check that the correct hooks were called.
  1618. $this->assertFileHooksCalled(array());
  1619. $this->assertFileUnchanged($source, file_load($source->fid, TRUE));
  1620. $this->assertFileUnchanged($target, file_load($target->fid, TRUE));
  1621. }
  1622. }
  1623. /**
  1624. * Tests the file_load() function.
  1625. */
  1626. class FileLoadTest extends FileHookTestCase {
  1627. public static function getInfo() {
  1628. return array(
  1629. 'name' => 'File loading',
  1630. 'description' => 'Tests the file_load() function.',
  1631. 'group' => 'File API',
  1632. );
  1633. }
  1634. /**
  1635. * Try to load a non-existent file by fid.
  1636. */
  1637. function testLoadMissingFid() {
  1638. $this->assertFalse(file_load(-1), t("Try to load an invalid fid fails."));
  1639. $this->assertFileHooksCalled(array());
  1640. }
  1641. /**
  1642. * Try to load a non-existent file by URI.
  1643. */
  1644. function testLoadMissingFilepath() {
  1645. $files = file_load_multiple(array(), array('uri' => 'foobar://misc/druplicon.png'));
  1646. $this->assertFalse(reset($files), t("Try to load a file that doesn't exist in the database fails."));
  1647. $this->assertFileHooksCalled(array());
  1648. }
  1649. /**
  1650. * Try to load a non-existent file by status.
  1651. */
  1652. function testLoadInvalidStatus() {
  1653. $files = file_load_multiple(array(), array('status' => -99));
  1654. $this->assertFalse(reset($files), t("Trying to load a file with an invalid status fails."));
  1655. $this->assertFileHooksCalled(array());
  1656. }
  1657. /**
  1658. * Load a single file and ensure that the correct values are returned.
  1659. */
  1660. function testSingleValues() {
  1661. // Create a new file object from scratch so we know the values.
  1662. $file = $this->createFile('druplicon.txt', NULL, 'public');
  1663. $by_fid_file = file_load($file->fid);
  1664. $this->assertFileHookCalled('load');
  1665. $this->assertTrue(is_object($by_fid_file), t('file_load() returned an object.'));
  1666. $this->assertEqual($by_fid_file->fid, $file->fid, t("Loading by fid got the same fid."), 'File');
  1667. $this->assertEqual($by_fid_file->uri, $file->uri, t("Loading by fid got the correct filepath."), 'File');
  1668. $this->assertEqual($by_fid_file->filename, $file->filename, t("Loading by fid got the correct filename."), 'File');
  1669. $this->assertEqual($by_fid_file->filemime, $file->filemime, t("Loading by fid got the correct MIME type."), 'File');
  1670. $this->assertEqual($by_fid_file->status, $file->status, t("Loading by fid got the correct status."), 'File');
  1671. $this->assertTrue($by_fid_file->file_test['loaded'], t('file_test_file_load() was able to modify the file during load.'));
  1672. }
  1673. /**
  1674. * This will test loading file data from the database.
  1675. */
  1676. function testMultiple() {
  1677. // Create a new file object.
  1678. $file = $this->createFile('druplicon.txt', NULL, 'public');
  1679. // Load by path.
  1680. file_test_reset();
  1681. $by_path_files = file_load_multiple(array(), array('uri' => $file->uri));
  1682. $this->assertFileHookCalled('load');
  1683. $this->assertEqual(1, count($by_path_files), t('file_load_multiple() returned an array of the correct size.'));
  1684. $by_path_file = reset($by_path_files);
  1685. $this->assertTrue($by_path_file->file_test['loaded'], t('file_test_file_load() was able to modify the file during load.'));
  1686. $this->assertEqual($by_path_file->fid, $file->fid, t("Loading by filepath got the correct fid."), 'File');
  1687. // Load by fid.
  1688. file_test_reset();
  1689. $by_fid_files = file_load_multiple(array($file->fid), array());
  1690. $this->assertFileHookCalled('load');
  1691. $this->assertEqual(1, count($by_fid_files), t('file_load_multiple() returned an array of the correct size.'));
  1692. $by_fid_file = reset($by_fid_files);
  1693. $this->assertTrue($by_fid_file->file_test['loaded'], t('file_test_file_load() was able to modify the file during load.'));
  1694. $this->assertEqual($by_fid_file->uri, $file->uri, t("Loading by fid got the correct filepath."), 'File');
  1695. }
  1696. }
  1697. /**
  1698. * Tests the file_save() function.
  1699. */
  1700. class FileSaveTest extends FileHookTestCase {
  1701. public static function getInfo() {
  1702. return array(
  1703. 'name' => 'File saving',
  1704. 'description' => 'Tests the file_save() function.',
  1705. 'group' => 'File API',
  1706. );
  1707. }
  1708. function testFileSave() {
  1709. // Create a new file object.
  1710. $file = array(
  1711. 'uid' => 1,
  1712. 'filename' => 'druplicon.txt',
  1713. 'uri' => 'public://druplicon.txt',
  1714. 'filemime' => 'text/plain',
  1715. 'timestamp' => 1,
  1716. 'status' => FILE_STATUS_PERMANENT,
  1717. );
  1718. $file = (object) $file;
  1719. file_put_contents($file->uri, 'hello world');
  1720. // Save it, inserting a new record.
  1721. $saved_file = file_save($file);
  1722. // Check that the correct hooks were called.
  1723. $this->assertFileHooksCalled(array('insert'));
  1724. $this->assertNotNull($saved_file, t("Saving the file should give us back a file object."), 'File');
  1725. $this->assertTrue($saved_file->fid > 0, t("A new file ID is set when saving a new file to the database."), 'File');
  1726. $loaded_file = db_query('SELECT * FROM {file_managed} f WHERE f.fid = :fid', array(':fid' => $saved_file->fid))->fetch(PDO::FETCH_OBJ);
  1727. $this->assertNotNull($loaded_file, t("Record exists in the database."));
  1728. $this->assertEqual($loaded_file->status, $file->status, t("Status was saved correctly."));
  1729. $this->assertEqual($saved_file->filesize, filesize($file->uri), t("File size was set correctly."), 'File');
  1730. $this->assertTrue($saved_file->timestamp > 1, t("File size was set correctly."), 'File');
  1731. // Resave the file, updating the existing record.
  1732. file_test_reset();
  1733. $saved_file->status = 7;
  1734. $resaved_file = file_save($saved_file);
  1735. // Check that the correct hooks were called.
  1736. $this->assertFileHooksCalled(array('load', 'update'));
  1737. $this->assertEqual($resaved_file->fid, $saved_file->fid, t("The file ID of an existing file is not changed when updating the database."), 'File');
  1738. $this->assertTrue($resaved_file->timestamp >= $saved_file->timestamp, t("Timestamp didn't go backwards."), 'File');
  1739. $loaded_file = db_query('SELECT * FROM {file_managed} f WHERE f.fid = :fid', array(':fid' => $saved_file->fid))->fetch(PDO::FETCH_OBJ);
  1740. $this->assertNotNull($loaded_file, t("Record still exists in the database."), 'File');
  1741. $this->assertEqual($loaded_file->status, $saved_file->status, t("Status was saved correctly."));
  1742. // Try to insert a second file with the same name apart from case insensitivity
  1743. // to ensure the 'uri' index allows for filenames with different cases.
  1744. $file = (object) array(
  1745. 'uid' => 1,
  1746. 'filename' => 'DRUPLICON.txt',
  1747. 'uri' => 'public://DRUPLICON.txt',
  1748. 'filemime' => 'text/plain',
  1749. 'timestamp' => 1,
  1750. 'status' => FILE_STATUS_PERMANENT,
  1751. );
  1752. file_put_contents($file->uri, 'hello world');
  1753. file_save($file);
  1754. }
  1755. }
  1756. /**
  1757. * Tests file usage functions.
  1758. */
  1759. class FileUsageTest extends FileTestCase {
  1760. public static function getInfo() {
  1761. return array(
  1762. 'name' => 'File usage',
  1763. 'description' => 'Tests the file usage functions.',
  1764. 'group' => 'File',
  1765. );
  1766. }
  1767. /**
  1768. * Tests file_usage_list().
  1769. */
  1770. function testGetUsage() {
  1771. $file = $this->createFile();
  1772. db_insert('file_usage')
  1773. ->fields(array(
  1774. 'fid' => $file->fid,
  1775. 'module' => 'testing',
  1776. 'type' => 'foo',
  1777. 'id' => 1,
  1778. 'count' => 1
  1779. ))
  1780. ->execute();
  1781. db_insert('file_usage')
  1782. ->fields(array(
  1783. 'fid' => $file->fid,
  1784. 'module' => 'testing',
  1785. 'type' => 'bar',
  1786. 'id' => 2,
  1787. 'count' => 2
  1788. ))
  1789. ->execute();
  1790. $usage = file_usage_list($file);
  1791. $this->assertEqual(count($usage['testing']), 2, t('Returned the correct number of items.'));
  1792. $this->assertTrue(isset($usage['testing']['foo'][1]), t('Returned the correct id.'));
  1793. $this->assertTrue(isset($usage['testing']['bar'][2]), t('Returned the correct id.'));
  1794. $this->assertEqual($usage['testing']['foo'][1], 1, t('Returned the correct count.'));
  1795. $this->assertEqual($usage['testing']['bar'][2], 2, t('Returned the correct count.'));
  1796. }
  1797. /**
  1798. * Tests file_usage_add().
  1799. */
  1800. function testAddUsage() {
  1801. $file = $this->createFile();
  1802. file_usage_add($file, 'testing', 'foo', 1);
  1803. // Add the file twice to ensure that the count is incremented rather than
  1804. // creating additional records.
  1805. file_usage_add($file, 'testing', 'bar', 2);
  1806. file_usage_add($file, 'testing', 'bar', 2);
  1807. $usage = db_select('file_usage', 'f')
  1808. ->fields('f')
  1809. ->condition('f.fid', $file->fid)
  1810. ->execute()
  1811. ->fetchAllAssoc('id');
  1812. $this->assertEqual(count($usage), 2, t('Created two records'));
  1813. $this->assertEqual($usage[1]->module, 'testing', t('Correct module'));
  1814. $this->assertEqual($usage[2]->module, 'testing', t('Correct module'));
  1815. $this->assertEqual($usage[1]->type, 'foo', t('Correct type'));
  1816. $this->assertEqual($usage[2]->type, 'bar', t('Correct type'));
  1817. $this->assertEqual($usage[1]->count, 1, t('Correct count'));
  1818. $this->assertEqual($usage[2]->count, 2, t('Correct count'));
  1819. }
  1820. /**
  1821. * Tests file_usage_delete().
  1822. */
  1823. function testRemoveUsage() {
  1824. $file = $this->createFile();
  1825. db_insert('file_usage')
  1826. ->fields(array(
  1827. 'fid' => $file->fid,
  1828. 'module' => 'testing',
  1829. 'type' => 'bar',
  1830. 'id' => 2,
  1831. 'count' => 3,
  1832. ))
  1833. ->execute();
  1834. // Normal decrement.
  1835. file_usage_delete($file, 'testing', 'bar', 2);
  1836. $count = db_select('file_usage', 'f')
  1837. ->fields('f', array('count'))
  1838. ->condition('f.fid', $file->fid)
  1839. ->execute()
  1840. ->fetchField();
  1841. $this->assertEqual(2, $count, t('The count was decremented correctly.'));
  1842. // Multiple decrement and removal.
  1843. file_usage_delete($file, 'testing', 'bar', 2, 2);
  1844. $count = db_select('file_usage', 'f')
  1845. ->fields('f', array('count'))
  1846. ->condition('f.fid', $file->fid)
  1847. ->execute()
  1848. ->fetchField();
  1849. $this->assertIdentical(FALSE, $count, t('The count was removed entirely when empty.'));
  1850. // Non-existent decrement.
  1851. file_usage_delete($file, 'testing', 'bar', 2);
  1852. $count = db_select('file_usage', 'f')
  1853. ->fields('f', array('count'))
  1854. ->condition('f.fid', $file->fid)
  1855. ->execute()
  1856. ->fetchField();
  1857. $this->assertIdentical(FALSE, $count, t('Decrementing non-exist record complete.'));
  1858. }
  1859. }
  1860. /**
  1861. * Tests the file_validate() function..
  1862. */
  1863. class FileValidateTest extends FileHookTestCase {
  1864. public static function getInfo() {
  1865. return array(
  1866. 'name' => 'File validate',
  1867. 'description' => 'Tests the file_validate() function.',
  1868. 'group' => 'File API',
  1869. );
  1870. }
  1871. /**
  1872. * Test that the validators passed into are checked.
  1873. */
  1874. function testCallerValidation() {
  1875. $file = $this->createFile();
  1876. // Empty validators.
  1877. $this->assertEqual(file_validate($file, array()), array(), t('Validating an empty array works successfully.'));
  1878. $this->assertFileHooksCalled(array('validate'));
  1879. // Use the file_test.module's test validator to ensure that passing tests
  1880. // return correctly.
  1881. file_test_reset();
  1882. file_test_set_return('validate', array());
  1883. $passing = array('file_test_validator' => array(array()));
  1884. $this->assertEqual(file_validate($file, $passing), array(), t('Validating passes.'));
  1885. $this->assertFileHooksCalled(array('validate'));
  1886. // Now test for failures in validators passed in and by hook_validate.
  1887. file_test_reset();
  1888. file_test_set_return('validate', array('Epic fail'));
  1889. $failing = array('file_test_validator' => array(array('Failed', 'Badly')));
  1890. $this->assertEqual(file_validate($file, $failing), array('Failed', 'Badly', 'Epic fail'), t('Validating returns errors.'));
  1891. $this->assertFileHooksCalled(array('validate'));
  1892. }
  1893. }
  1894. /**
  1895. * Tests the file_save_data() function.
  1896. */
  1897. class FileSaveDataTest extends FileHookTestCase {
  1898. public static function getInfo() {
  1899. return array(
  1900. 'name' => 'File save data',
  1901. 'description' => 'Tests the file save data function.',
  1902. 'group' => 'File API',
  1903. );
  1904. }
  1905. /**
  1906. * Test the file_save_data() function when no filename is provided.
  1907. */
  1908. function testWithoutFilename() {
  1909. $contents = $this->randomName(8);
  1910. $result = file_save_data($contents);
  1911. $this->assertTrue($result, t('Unnamed file saved correctly.'));
  1912. $this->assertEqual(file_default_scheme(), file_uri_scheme($result->uri), t("File was placed in Drupal's files directory."));
  1913. $this->assertEqual($result->filename, drupal_basename($result->uri), t("Filename was set to the file's basename."));
  1914. $this->assertEqual($contents, file_get_contents($result->uri), t('Contents of the file are correct.'));
  1915. $this->assertEqual($result->filemime, 'application/octet-stream', t('A MIME type was set.'));
  1916. $this->assertEqual($result->status, FILE_STATUS_PERMANENT, t("The file's status was set to permanent."));
  1917. // Check that the correct hooks were called.
  1918. $this->assertFileHooksCalled(array('insert'));
  1919. // Verify that what was returned is what's in the database.
  1920. $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
  1921. }
  1922. /**
  1923. * Test the file_save_data() function when a filename is provided.
  1924. */
  1925. function testWithFilename() {
  1926. $contents = $this->randomName(8);
  1927. // Using filename with non-latin characters.
  1928. $filename = 'Текстовый файл.txt';
  1929. $result = file_save_data($contents, 'public://' . $filename);
  1930. $this->assertTrue($result, t('Unnamed file saved correctly.'));
  1931. $this->assertEqual('public', file_uri_scheme($result->uri), t("File was placed in Drupal's files directory."));
  1932. $this->assertEqual($filename, drupal_basename($result->uri), t('File was named correctly.'));
  1933. $this->assertEqual($contents, file_get_contents($result->uri), t('Contents of the file are correct.'));
  1934. $this->assertEqual($result->filemime, 'text/plain', t('A MIME type was set.'));
  1935. $this->assertEqual($result->status, FILE_STATUS_PERMANENT, t("The file's status was set to permanent."));
  1936. // Check that the correct hooks were called.
  1937. $this->assertFileHooksCalled(array('insert'));
  1938. // Verify that what was returned is what's in the database.
  1939. $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
  1940. }
  1941. /**
  1942. * Test file_save_data() when renaming around an existing file.
  1943. */
  1944. function testExistingRename() {
  1945. // Setup a file to overwrite.
  1946. $existing = $this->createFile();
  1947. $contents = $this->randomName(8);
  1948. $result = file_save_data($contents, $existing->uri, FILE_EXISTS_RENAME);
  1949. $this->assertTrue($result, t("File saved successfully."));
  1950. $this->assertEqual('public', file_uri_scheme($result->uri), t("File was placed in Drupal's files directory."));
  1951. $this->assertEqual($result->filename, $existing->filename, t("Filename was set to the basename of the source, rather than that of the renamed file."));
  1952. $this->assertEqual($contents, file_get_contents($result->uri), t("Contents of the file are correct."));
  1953. $this->assertEqual($result->filemime, 'application/octet-stream', t("A MIME type was set."));
  1954. $this->assertEqual($result->status, FILE_STATUS_PERMANENT, t("The file's status was set to permanent."));
  1955. // Check that the correct hooks were called.
  1956. $this->assertFileHooksCalled(array('insert'));
  1957. // Ensure that the existing file wasn't overwritten.
  1958. $this->assertDifferentFile($existing, $result);
  1959. $this->assertFileUnchanged($existing, file_load($existing->fid, TRUE));
  1960. // Verify that was returned is what's in the database.
  1961. $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
  1962. }
  1963. /**
  1964. * Test file_save_data() when replacing an existing file.
  1965. */
  1966. function testExistingReplace() {
  1967. // Setup a file to overwrite.
  1968. $existing = $this->createFile();
  1969. $contents = $this->randomName(8);
  1970. $result = file_save_data($contents, $existing->uri, FILE_EXISTS_REPLACE);
  1971. $this->assertTrue($result, t('File saved successfully.'));
  1972. $this->assertEqual('public', file_uri_scheme($result->uri), t("File was placed in Drupal's files directory."));
  1973. $this->assertEqual($result->filename, $existing->filename, t('Filename was set to the basename of the existing file, rather than preserving the original name.'));
  1974. $this->assertEqual($contents, file_get_contents($result->uri), t('Contents of the file are correct.'));
  1975. $this->assertEqual($result->filemime, 'application/octet-stream', t('A MIME type was set.'));
  1976. $this->assertEqual($result->status, FILE_STATUS_PERMANENT, t("The file's status was set to permanent."));
  1977. // Check that the correct hooks were called.
  1978. $this->assertFileHooksCalled(array('load', 'update'));
  1979. // Verify that the existing file was re-used.
  1980. $this->assertSameFile($existing, $result);
  1981. // Verify that what was returned is what's in the database.
  1982. $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
  1983. }
  1984. /**
  1985. * Test that file_save_data() fails overwriting an existing file.
  1986. */
  1987. function testExistingError() {
  1988. $contents = $this->randomName(8);
  1989. $existing = $this->createFile(NULL, $contents);
  1990. // Check the overwrite error.
  1991. $result = file_save_data('asdf', $existing->uri, FILE_EXISTS_ERROR);
  1992. $this->assertFalse($result, t('Overwriting a file fails when FILE_EXISTS_ERROR is specified.'));
  1993. $this->assertEqual($contents, file_get_contents($existing->uri), t('Contents of existing file were unchanged.'));
  1994. // Check that no hooks were called while failing.
  1995. $this->assertFileHooksCalled(array());
  1996. // Ensure that the existing file wasn't overwritten.
  1997. $this->assertFileUnchanged($existing, file_load($existing->fid, TRUE));
  1998. }
  1999. }
  2000. /**
  2001. * Tests for download/file transfer functions.
  2002. */
  2003. class FileDownloadTest extends FileTestCase {
  2004. public static function getInfo() {
  2005. return array(
  2006. 'name' => 'File download',
  2007. 'description' => 'Tests for file download/transfer functions.',
  2008. 'group' => 'File API',
  2009. );
  2010. }
  2011. function setUp() {
  2012. parent::setUp('file_test');
  2013. // Clear out any hook calls.
  2014. file_test_reset();
  2015. }
  2016. /**
  2017. * Test the public file transfer system.
  2018. */
  2019. function testPublicFileTransfer() {
  2020. // Test generating an URL to a created file.
  2021. $file = $this->createFile();
  2022. $url = file_create_url($file->uri);
  2023. // URLs can't contain characters outside the ASCII set so $filename has to be
  2024. // encoded.
  2025. $filename = $GLOBALS['base_url'] . '/' . file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath() . '/' . rawurlencode($file->filename);
  2026. $this->assertEqual($filename, $url, t('Correctly generated a URL for a created file.'));
  2027. $this->drupalHead($url);
  2028. $this->assertResponse(200, t('Confirmed that the generated URL is correct by downloading the created file.'));
  2029. // Test generating an URL to a shipped file (i.e. a file that is part of
  2030. // Drupal core, a module or a theme, for example a JavaScript file).
  2031. $filepath = 'misc/jquery.js';
  2032. $url = file_create_url($filepath);
  2033. $this->assertEqual($GLOBALS['base_url'] . '/' . $filepath, $url, t('Correctly generated a URL for a shipped file.'));
  2034. $this->drupalHead($url);
  2035. $this->assertResponse(200, t('Confirmed that the generated URL is correct by downloading the shipped file.'));
  2036. }
  2037. /**
  2038. * Test the private file transfer system.
  2039. */
  2040. function testPrivateFileTransfer() {
  2041. // Set file downloads to private so handler functions get called.
  2042. // Create a file.
  2043. $contents = $this->randomName(8);
  2044. $file = $this->createFile(NULL, $contents, 'private');
  2045. $url = file_create_url($file->uri);
  2046. // Set file_test access header to allow the download.
  2047. file_test_set_return('download', array('x-foo' => 'Bar'));
  2048. $this->drupalGet($url);
  2049. $headers = $this->drupalGetHeaders();
  2050. $this->assertEqual($headers['x-foo'], 'Bar', t('Found header set by file_test module on private download.'));
  2051. $this->assertResponse(200, t('Correctly allowed access to a file when file_test provides headers.'));
  2052. // Test that the file transfered correctly.
  2053. $this->assertEqual($contents, $this->content, t('Contents of the file are correct.'));
  2054. // Deny access to all downloads via a -1 header.
  2055. file_test_set_return('download', -1);
  2056. $this->drupalHead($url);
  2057. $this->assertResponse(403, t('Correctly denied access to a file when file_test sets the header to -1.'));
  2058. // Try non-existent file.
  2059. $url = file_create_url('private://' . $this->randomName());
  2060. $this->drupalHead($url);
  2061. $this->assertResponse(404, t('Correctly returned 404 response for a non-existent file.'));
  2062. }
  2063. /**
  2064. * Test file_create_url().
  2065. */
  2066. function testFileCreateUrl() {
  2067. global $base_url;
  2068. // Tilde (~) is excluded from this test because it is encoded by
  2069. // rawurlencode() in PHP 5.2 but not in PHP 5.3, as per RFC 3986.
  2070. // @see http://www.php.net/manual/en/function.rawurlencode.php#86506
  2071. $basename = " -._!$'\"()*@[]?&+%#,;=:\n\x00" . // "Special" ASCII characters.
  2072. "%23%25%26%2B%2F%3F" . // Characters that look like a percent-escaped string.
  2073. "éøïвβ中國書۞"; // Characters from various non-ASCII alphabets.
  2074. $basename_encoded = '%20-._%21%24%27%22%28%29%2A%40%5B%5D%3F%26%2B%25%23%2C%3B%3D%3A__' .
  2075. '%2523%2525%2526%252B%252F%253F' .
  2076. '%C3%A9%C3%B8%C3%AF%D0%B2%CE%B2%E4%B8%AD%E5%9C%8B%E6%9B%B8%DB%9E';
  2077. $this->checkUrl('public', '', $basename, $base_url . '/' . file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath() . '/' . $basename_encoded);
  2078. $this->checkUrl('private', '', $basename, $base_url . '/system/files/' . $basename_encoded);
  2079. $this->checkUrl('private', '', $basename, $base_url . '/?q=system/files/' . $basename_encoded, '0');
  2080. }
  2081. /**
  2082. * Download a file from the URL generated by file_create_url().
  2083. *
  2084. * Create a file with the specified scheme, directory and filename; check that
  2085. * the URL generated by file_create_url() for the specified file equals the
  2086. * specified URL; fetch the URL and then compare the contents to the file.
  2087. *
  2088. * @param $scheme
  2089. * A scheme, e.g. "public"
  2090. * @param $directory
  2091. * A directory, possibly ""
  2092. * @param $filename
  2093. * A filename
  2094. * @param $expected_url
  2095. * The expected URL
  2096. * @param $clean_url
  2097. * The value of the clean_url setting
  2098. */
  2099. private function checkUrl($scheme, $directory, $filename, $expected_url, $clean_url = '1') {
  2100. variable_set('clean_url', $clean_url);
  2101. // Convert $filename to a valid filename, i.e. strip characters not
  2102. // supported by the filesystem, and create the file in the specified
  2103. // directory.
  2104. $filepath = file_create_filename($filename, $directory);
  2105. $directory_uri = $scheme . '://' . dirname($filepath);
  2106. file_prepare_directory($directory_uri, FILE_CREATE_DIRECTORY);
  2107. $file = $this->createFile($filepath, NULL, $scheme);
  2108. $url = file_create_url($file->uri);
  2109. $this->assertEqual($url, $expected_url, t('Generated URL matches expected URL.'));
  2110. if ($scheme == 'private') {
  2111. // Tell the implementation of hook_file_download() in file_test.module
  2112. // that this file may be downloaded.
  2113. file_test_set_return('download', array('x-foo' => 'Bar'));
  2114. }
  2115. $this->drupalGet($url);
  2116. if ($this->assertResponse(200) == 'pass') {
  2117. $this->assertRaw(file_get_contents($file->uri), t('Contents of the file are correct.'));
  2118. }
  2119. file_delete($file);
  2120. }
  2121. }
  2122. /**
  2123. * Tests for file URL rewriting.
  2124. */
  2125. class FileURLRewritingTest extends FileTestCase {
  2126. public static function getInfo() {
  2127. return array(
  2128. 'name' => 'File URL rewriting',
  2129. 'description' => 'Tests for file URL rewriting.',
  2130. 'group' => 'File',
  2131. );
  2132. }
  2133. function setUp() {
  2134. parent::setUp('file_test');
  2135. }
  2136. /**
  2137. * Test the generating of rewritten shipped file URLs.
  2138. */
  2139. function testShippedFileURL() {
  2140. // Test generating an URL to a shipped file (i.e. a file that is part of
  2141. // Drupal core, a module or a theme, for example a JavaScript file).
  2142. // Test alteration of file URLs to use a CDN.
  2143. variable_set('file_test_hook_file_url_alter', 'cdn');
  2144. $filepath = 'misc/jquery.js';
  2145. $url = file_create_url($filepath);
  2146. $this->assertEqual(FILE_URL_TEST_CDN_1 . '/' . $filepath, $url, t('Correctly generated a CDN URL for a shipped file.'));
  2147. $filepath = 'misc/favicon.ico';
  2148. $url = file_create_url($filepath);
  2149. $this->assertEqual(FILE_URL_TEST_CDN_2 . '/' . $filepath, $url, t('Correctly generated a CDN URL for a shipped file.'));
  2150. // Test alteration of file URLs to use root-relative URLs.
  2151. variable_set('file_test_hook_file_url_alter', 'root-relative');
  2152. $filepath = 'misc/jquery.js';
  2153. $url = file_create_url($filepath);
  2154. $this->assertEqual(base_path() . '/' . $filepath, $url, t('Correctly generated a root-relative URL for a shipped file.'));
  2155. $filepath = 'misc/favicon.ico';
  2156. $url = file_create_url($filepath);
  2157. $this->assertEqual(base_path() . '/' . $filepath, $url, t('Correctly generated a root-relative URL for a shipped file.'));
  2158. // Test alteration of file URLs to use protocol-relative URLs.
  2159. variable_set('file_test_hook_file_url_alter', 'protocol-relative');
  2160. $filepath = 'misc/jquery.js';
  2161. $url = file_create_url($filepath);
  2162. $this->assertEqual('/' . base_path() . '/' . $filepath, $url, t('Correctly generated a protocol-relative URL for a shipped file.'));
  2163. $filepath = 'misc/favicon.ico';
  2164. $url = file_create_url($filepath);
  2165. $this->assertEqual('/' . base_path() . '/' . $filepath, $url, t('Correctly generated a protocol-relative URL for a shipped file.'));
  2166. }
  2167. /**
  2168. * Test the generating of rewritten public created file URLs.
  2169. */
  2170. function testPublicCreatedFileURL() {
  2171. // Test generating an URL to a created file.
  2172. // Test alteration of file URLs to use a CDN.
  2173. variable_set('file_test_hook_file_url_alter', 'cdn');
  2174. $file = $this->createFile();
  2175. $url = file_create_url($file->uri);
  2176. $public_directory_path = file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath();
  2177. $this->assertEqual(FILE_URL_TEST_CDN_2 . '/' . $public_directory_path . '/' . $file->filename, $url, t('Correctly generated a CDN URL for a created file.'));
  2178. // Test alteration of file URLs to use root-relative URLs.
  2179. variable_set('file_test_hook_file_url_alter', 'root-relative');
  2180. $file = $this->createFile();
  2181. $url = file_create_url($file->uri);
  2182. $this->assertEqual(base_path() . '/' . $public_directory_path . '/' . $file->filename, $url, t('Correctly generated a root-relative URL for a created file.'));
  2183. // Test alteration of file URLs to use a protocol-relative URLs.
  2184. variable_set('file_test_hook_file_url_alter', 'protocol-relative');
  2185. $file = $this->createFile();
  2186. $url = file_create_url($file->uri);
  2187. $this->assertEqual('/' . base_path() . '/' . $public_directory_path . '/' . $file->filename, $url, t('Correctly generated a protocol-relative URL for a created file.'));
  2188. }
  2189. }
  2190. /**
  2191. * Tests for file_munge_filename() and file_unmunge_filename().
  2192. */
  2193. class FileNameMungingTest extends FileTestCase {
  2194. public static function getInfo() {
  2195. return array(
  2196. 'name' => 'File naming',
  2197. 'description' => 'Test filename munging and unmunging.',
  2198. 'group' => 'File API',
  2199. );
  2200. }
  2201. function setUp() {
  2202. parent::setUp();
  2203. $this->bad_extension = 'php';
  2204. $this->name = $this->randomName() . '.' . $this->bad_extension . '.txt';
  2205. }
  2206. /**
  2207. * Create a file and munge/unmunge the name.
  2208. */
  2209. function testMunging() {
  2210. // Disable insecure uploads.
  2211. variable_set('allow_insecure_uploads', 0);
  2212. $munged_name = file_munge_filename($this->name, '', TRUE);
  2213. $messages = drupal_get_messages();
  2214. $this->assertTrue(in_array(t('For security reasons, your upload has been renamed to %filename.', array('%filename' => $munged_name)), $messages['status']), t('Alert properly set when a file is renamed.'));
  2215. $this->assertNotEqual($munged_name, $this->name, t('The new filename (%munged) has been modified from the original (%original)', array('%munged' => $munged_name, '%original' => $this->name)));
  2216. }
  2217. /**
  2218. * Tests munging with a null byte in the filename.
  2219. */
  2220. function testMungeNullByte() {
  2221. $prefix = $this->randomName();
  2222. $filename = $prefix . '.' . $this->bad_extension . "\0.txt";
  2223. $this->assertEqual(file_munge_filename($filename, ''), $prefix . '.' . $this->bad_extension . '_.txt', 'A filename with a null byte is correctly munged to remove the null byte.');
  2224. }
  2225. /**
  2226. * If the allow_insecure_uploads variable evaluates to true, the file should
  2227. * come out untouched, no matter how evil the filename.
  2228. */
  2229. function testMungeIgnoreInsecure() {
  2230. variable_set('allow_insecure_uploads', 1);
  2231. $munged_name = file_munge_filename($this->name, '');
  2232. $this->assertIdentical($munged_name, $this->name, t('The original filename (%original) matches the munged filename (%munged) when insecure uploads are enabled.', array('%munged' => $munged_name, '%original' => $this->name)));
  2233. }
  2234. /**
  2235. * White listed extensions are ignored by file_munge_filename().
  2236. */
  2237. function testMungeIgnoreWhitelisted() {
  2238. // Declare our extension as whitelisted.
  2239. $munged_name = file_munge_filename($this->name, $this->bad_extension);
  2240. $this->assertIdentical($munged_name, $this->name, t('The new filename (%munged) matches the original (%original) once the extension has been whitelisted.', array('%munged' => $munged_name, '%original' => $this->name)));
  2241. }
  2242. /**
  2243. * Ensure that unmunge gets your name back.
  2244. */
  2245. function testUnMunge() {
  2246. $munged_name = file_munge_filename($this->name, '', FALSE);
  2247. $unmunged_name = file_unmunge_filename($munged_name);
  2248. $this->assertIdentical($unmunged_name, $this->name, t('The unmunged (%unmunged) filename matches the original (%original)', array('%unmunged' => $unmunged_name, '%original' => $this->name)));
  2249. }
  2250. }
  2251. /**
  2252. * Tests for file_get_mimetype().
  2253. */
  2254. class FileMimeTypeTest extends DrupalWebTestCase {
  2255. function setUp() {
  2256. parent::setUp('file_test');
  2257. }
  2258. public static function getInfo() {
  2259. return array(
  2260. 'name' => 'File mimetypes',
  2261. 'description' => 'Test filename mimetype detection.',
  2262. 'group' => 'File API',
  2263. );
  2264. }
  2265. /**
  2266. * Test mapping of mimetypes from filenames.
  2267. */
  2268. public function testFileMimeTypeDetection() {
  2269. $prefix = 'public://';
  2270. $test_case = array(
  2271. 'test.jar' => 'application/java-archive',
  2272. 'test.jpeg' => 'image/jpeg',
  2273. 'test.JPEG' => 'image/jpeg',
  2274. 'test.jpg' => 'image/jpeg',
  2275. 'test.jar.jpg' => 'image/jpeg',
  2276. 'test.jpg.jar' => 'application/java-archive',
  2277. 'test.pcf.Z' => 'application/x-font',
  2278. 'pcf.z' => 'application/octet-stream',
  2279. 'jar' => 'application/octet-stream',
  2280. 'some.junk' => 'application/octet-stream',
  2281. 'foo.file_test_1' => 'madeup/file_test_1',
  2282. 'foo.file_test_2' => 'madeup/file_test_2',
  2283. 'foo.doc' => 'madeup/doc',
  2284. 'test.ogg' => 'audio/ogg',
  2285. );
  2286. // Test using default mappings.
  2287. foreach ($test_case as $input => $expected) {
  2288. // Test stream [URI].
  2289. $output = file_get_mimetype($prefix . $input);
  2290. $this->assertIdentical($output, $expected, t('Mimetype for %input is %output (expected: %expected).', array('%input' => $input, '%output' => $output, '%expected' => $expected)));
  2291. // Test normal path equivalent
  2292. $output = file_get_mimetype($input);
  2293. $this->assertIdentical($output, $expected, t('Mimetype (using default mappings) for %input is %output (expected: %expected).', array('%input' => $input, '%output' => $output, '%expected' => $expected)));
  2294. }
  2295. // Now test passing in the map.
  2296. $mapping = array(
  2297. 'mimetypes' => array(
  2298. 0 => 'application/java-archive',
  2299. 1 => 'image/jpeg',
  2300. ),
  2301. 'extensions' => array(
  2302. 'jar' => 0,
  2303. 'jpg' => 1,
  2304. )
  2305. );
  2306. $test_case = array(
  2307. 'test.jar' => 'application/java-archive',
  2308. 'test.jpeg' => 'application/octet-stream',
  2309. 'test.jpg' => 'image/jpeg',
  2310. 'test.jar.jpg' => 'image/jpeg',
  2311. 'test.jpg.jar' => 'application/java-archive',
  2312. 'test.pcf.z' => 'application/octet-stream',
  2313. 'pcf.z' => 'application/octet-stream',
  2314. 'jar' => 'application/octet-stream',
  2315. 'some.junk' => 'application/octet-stream',
  2316. 'foo.file_test_1' => 'application/octet-stream',
  2317. 'foo.file_test_2' => 'application/octet-stream',
  2318. 'foo.doc' => 'application/octet-stream',
  2319. 'test.ogg' => 'application/octet-stream',
  2320. );
  2321. foreach ($test_case as $input => $expected) {
  2322. $output = file_get_mimetype($input, $mapping);
  2323. $this->assertIdentical($output, $expected, t('Mimetype (using passed-in mappings) for %input is %output (expected: %expected).', array('%input' => $input, '%output' => $output, '%expected' => $expected)));
  2324. }
  2325. }
  2326. }
  2327. /**
  2328. * Tests stream wrapper functions.
  2329. */
  2330. class StreamWrapperTest extends DrupalWebTestCase {
  2331. protected $scheme = 'dummy';
  2332. protected $classname = 'DrupalDummyStreamWrapper';
  2333. public static function getInfo() {
  2334. return array(
  2335. 'name' => 'Stream wrappers',
  2336. 'description' => 'Tests stream wrapper functions.',
  2337. 'group' => 'File API',
  2338. );
  2339. }
  2340. function setUp() {
  2341. parent::setUp('file_test');
  2342. drupal_static_reset('file_get_stream_wrappers');
  2343. }
  2344. function tearDown() {
  2345. parent::tearDown();
  2346. stream_wrapper_unregister($this->scheme);
  2347. }
  2348. /**
  2349. * Test the getClassName() function.
  2350. */
  2351. function testGetClassName() {
  2352. // Check the dummy scheme.
  2353. $this->assertEqual($this->classname, file_stream_wrapper_get_class($this->scheme), t('Got correct class name for dummy scheme.'));
  2354. // Check core's scheme.
  2355. $this->assertEqual('DrupalPublicStreamWrapper', file_stream_wrapper_get_class('public'), t('Got correct class name for public scheme.'));
  2356. }
  2357. /**
  2358. * Test the file_stream_wrapper_get_instance_by_scheme() function.
  2359. */
  2360. function testGetInstanceByScheme() {
  2361. $instance = file_stream_wrapper_get_instance_by_scheme($this->scheme);
  2362. $this->assertEqual($this->classname, get_class($instance), t('Got correct class type for dummy scheme.'));
  2363. $instance = file_stream_wrapper_get_instance_by_scheme('public');
  2364. $this->assertEqual('DrupalPublicStreamWrapper', get_class($instance), t('Got correct class type for public scheme.'));
  2365. }
  2366. /**
  2367. * Test the URI and target functions.
  2368. */
  2369. function testUriFunctions() {
  2370. $instance = file_stream_wrapper_get_instance_by_uri($this->scheme . '://foo');
  2371. $this->assertEqual($this->classname, get_class($instance), t('Got correct class type for dummy URI.'));
  2372. $instance = file_stream_wrapper_get_instance_by_uri('public://foo');
  2373. $this->assertEqual('DrupalPublicStreamWrapper', get_class($instance), t('Got correct class type for public URI.'));
  2374. // Test file_uri_target().
  2375. $this->assertEqual(file_uri_target('public://foo/bar.txt'), 'foo/bar.txt', t('Got a valid stream target from public://foo/bar.txt.'));
  2376. $this->assertFalse(file_uri_target('foo/bar.txt'), t('foo/bar.txt is not a valid stream.'));
  2377. // Test file_build_uri() and DrupalLocalStreamWrapper::getDirectoryPath().
  2378. $this->assertEqual(file_build_uri('foo/bar.txt'), 'public://foo/bar.txt', t('Expected scheme was added.'));
  2379. $this->assertEqual(file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath(), variable_get('file_public_path'), t('Expected default directory path was returned.'));
  2380. $this->assertEqual(file_stream_wrapper_get_instance_by_scheme('temporary')->getDirectoryPath(), variable_get('file_temporary_path'), t('Expected temporary directory path was returned.'));
  2381. variable_set('file_default_scheme', 'private');
  2382. $this->assertEqual(file_build_uri('foo/bar.txt'), 'private://foo/bar.txt', t('Got a valid URI from foo/bar.txt.'));
  2383. }
  2384. /**
  2385. * Test the scheme functions.
  2386. */
  2387. function testGetValidStreamScheme() {
  2388. $this->assertEqual('foo', file_uri_scheme('foo://pork//chops'), t('Got the correct scheme from foo://asdf'));
  2389. $this->assertTrue(file_stream_wrapper_valid_scheme(file_uri_scheme('public://asdf')), t('Got a valid stream scheme from public://asdf'));
  2390. $this->assertFalse(file_stream_wrapper_valid_scheme(file_uri_scheme('foo://asdf')), t('Did not get a valid stream scheme from foo://asdf'));
  2391. }
  2392. }