ZipTestCase.php 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. namespace PhpZip;
  3. /**
  4. * PHPUnit test case and helper methods.
  5. */
  6. class ZipTestCase extends \PHPUnit_Framework_TestCase
  7. {
  8. /**
  9. * Assert correct zip archive.
  10. *
  11. * @param string $filename
  12. * @param string|null $password
  13. */
  14. public static function assertCorrectZipArchive($filename, $password = null)
  15. {
  16. if (DIRECTORY_SEPARATOR !== '\\' && `which unzip`) {
  17. $command = "unzip";
  18. if ($password !== null) {
  19. $command .= " -P " . escapeshellarg($password);
  20. }
  21. $command .= " -t " . escapeshellarg($filename);
  22. exec($command, $output, $returnCode);
  23. $output = implode(PHP_EOL, $output);
  24. if ($password !== null && $returnCode === 81) {
  25. if(`which 7z`){
  26. // WinZip 99-character limit
  27. // @see https://sourceforge.net/p/p7zip/discussion/383044/thread/c859a2f0/
  28. $password = substr($password, 0, 99);
  29. $command = "7z t -p" . escapeshellarg($password). " " . escapeshellarg($filename);
  30. exec($command, $output, $returnCode);
  31. $output = implode(PHP_EOL, $output);
  32. self::assertEquals($returnCode, 0);
  33. self::assertNotContains(' Errors', $output);
  34. self::assertContains(' Ok', $output);
  35. }
  36. else{
  37. fwrite(STDERR, 'Program unzip cannot support this function.'.PHP_EOL);
  38. fwrite(STDERR, 'Please install 7z. For Ubuntu-like: sudo apt-get install p7zip-full'.PHP_EOL);
  39. }
  40. }
  41. else {
  42. self::assertEquals($returnCode, 0);
  43. self::assertNotContains('incorrect password', $output);
  44. self::assertContains(' OK', $output);
  45. self::assertContains('No errors', $output);
  46. }
  47. }
  48. }
  49. /**
  50. * Assert correct empty zip archive.
  51. *
  52. * @param $filename
  53. */
  54. public static function assertCorrectEmptyZip($filename)
  55. {
  56. if (DIRECTORY_SEPARATOR !== '\\' && `which zipinfo`) {
  57. exec("zipinfo " . escapeshellarg($filename), $output, $returnCode);
  58. $output = implode(PHP_EOL, $output);
  59. self::assertContains('Empty zipfile', $output);
  60. }
  61. $actualEmptyZipData = pack('VVVVVv', ZipConstants::END_OF_CENTRAL_DIRECTORY_RECORD_SIG, 0, 0, 0, 0, 0);
  62. self::assertEquals(file_get_contents($filename), $actualEmptyZipData);
  63. }
  64. /**
  65. * @param string $filename
  66. * @return bool|null If null - can not install zipalign
  67. */
  68. public static function doZipAlignVerify($filename)
  69. {
  70. if (DIRECTORY_SEPARATOR !== '\\' && `which zipalign`) {
  71. exec("zipalign -c -v 4 " . escapeshellarg($filename), $output, $returnCode);
  72. return $returnCode === 0;
  73. } else {
  74. fwrite(STDERR, 'Can not find program "zipalign" for test');
  75. return null;
  76. }
  77. }
  78. }