file.test 110 KB

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