AgentUploadTest.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. <?php
  2. namespace Tests\Integration;
  3. use App\Http\Controllers\agent\UploadController;
  4. use Illuminate\Filesystem\FilesystemManager;
  5. use Illuminate\Http\Request;
  6. use Illuminate\Http\UploadedFile;
  7. use PHPUnit\Framework\TestCase;
  8. use Tests\Support\AgentTestEnvironment;
  9. /** 代理后台上传图片 POST /agent/upload/image。 */
  10. class AgentUploadTest extends TestCase
  11. {
  12. use AgentTestEnvironment;
  13. public function test_agent_uploads_image_and_rejects_other_files(): void
  14. {
  15. $root = sys_get_temp_dir() . '/agent-upload-' . bin2hex(random_bytes(4));
  16. config(['app.url' => 'https://api.example.test', 'filesystems.default' => 'public',
  17. 'filesystems.disks.public' => ['driver' => 'local', 'root' => $root, 'url' => 'https://api.example.test/storage', 'visibility' => 'public']]);
  18. $this->app->instance('filesystem', new FilesystemManager($this->app));
  19. $png = tempnam(sys_get_temp_dir(), 'img');
  20. file_put_contents($png, base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII='));
  21. try {
  22. $call = function (UploadedFile $file) {
  23. $request = Request::create('/agent/upload/image', 'POST', [], [], ['image' => $file]);
  24. $request->attributes->set('agent', $this->agent());
  25. $this->app->instance('request', $request);
  26. return (new UploadController())->image($request)->getData(true);
  27. };
  28. $ok = $call(new UploadedFile($png, 'proof.exe', 'image/png', null, true));
  29. $this->assertSame(0, $ok['code'], (string) $ok['msg']);
  30. $this->assertMatchesRegularExpression('#^https://api\.example\.test/storage/images/[0-9a-f]{32}\.png$#', $ok['data']['path'], 'extension follows file content');
  31. $this->assertFileExists($root . '/images/' . basename($ok['data']['path']));
  32. $txt = tempnam(sys_get_temp_dir(), 'txt'); file_put_contents($txt, 'not an image');
  33. $this->assertNotSame(0, $call(new UploadedFile($txt, 'a.png', 'image/png', null, true))['code']);
  34. } finally {
  35. @unlink($png);
  36. if (is_dir($root)) { array_map('unlink', glob($root . '/images/*') ?: []); @rmdir($root . '/images'); @rmdir($root); }
  37. }
  38. }
  39. }