file.test 109 KB

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