LocalAdapterTest.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. declare(strict_types=1);
  3. use Tinywan\Storage\Adapter\LocalAdapter;
  4. use Webman\Http\UploadFile;
  5. /*
  6. * 本地适配器测试专用子类:
  7. * _is_file_upload = false 时构造函数不会从 request() 读取文件,
  8. * 这里提供注入口直接塞入待上传文件。
  9. */
  10. function makeLocalAdapter(string $root)
  11. {
  12. return new class([
  13. 'adapter' => LocalAdapter::class,
  14. 'root' => $root,
  15. 'dirname' => 'unit-test',
  16. 'domain' => 'http://127.0.0.1:8787',
  17. 'uri' => '/storage',
  18. 'algo' => 'sha1',
  19. '_is_file_upload' => false,
  20. ]) extends LocalAdapter {
  21. /**
  22. * @param UploadFile[] $files
  23. */
  24. public function withFiles(array $files): self
  25. {
  26. $this->files = $files;
  27. return $this;
  28. }
  29. };
  30. }
  31. function makeTempFile(string $content): string
  32. {
  33. $path = (string) tempnam(sys_get_temp_dir(), 'storage_test_');
  34. file_put_contents($path, $content);
  35. return $path;
  36. }
  37. test('本地上传文件返回标准信息且文件落盘', function () {
  38. $root = sys_get_temp_dir() . '/storage_test_' . uniqid();
  39. $tmpFile = makeTempFile('hello webman storage');
  40. // 上传过程会移动源文件,需在上传前计算哈希
  41. $expectedHash = sha1_file($tmpFile);
  42. $uploadFile = new UploadFile($tmpFile, 'demo.txt', 'text/plain', UPLOAD_ERR_OK);
  43. $result = makeLocalAdapter($root)->withFiles([$uploadFile])->uploadFile();
  44. expect($result)->toHaveCount(1);
  45. $file = $result[0];
  46. expect($file)->toHaveKeys([
  47. 'key',
  48. 'origin_name',
  49. 'save_name',
  50. 'save_path',
  51. 'url',
  52. 'unique_id',
  53. 'size',
  54. 'mime_type',
  55. 'extension',
  56. ]);
  57. expect($file['origin_name'])->toBe('demo.txt');
  58. expect($file['extension'])->toBe('txt');
  59. expect($file['size'])->toBe(strlen('hello webman storage'));
  60. expect($file['unique_id'])->toBe($expectedHash);
  61. // url = domain + uri + 分隔符 + dirname(uri 尾部分隔符自动规整)
  62. expect($file['url'])->toBe('http://127.0.0.1:8787/storage/unit-test/' . $file['save_name']);
  63. // root 无尾部分隔符时,dirname 也必须独立成目录(storage/日期 而非 storage日期)
  64. expect($file['save_path'])->toStartWith($root . DIRECTORY_SEPARATOR . 'unit-test' . DIRECTORY_SEPARATOR);
  65. expect($file['save_path'])->toBeFile();
  66. });
  67. test('未实现的能力返回失败并记录错误信息', function () {
  68. $root = sys_get_temp_dir() . '/storage_test_' . uniqid();
  69. $adapter = makeLocalAdapter($root);
  70. expect($adapter->uploadBase64('data:image/png;base64,xxx'))
  71. ->toBeFalse()
  72. ->and($adapter->getMessage())
  73. ->toBe('暂不支持')
  74. ->and($adapter->uploadServerFile(__FILE__))
  75. ->toBeFalse();
  76. });