Files
boursecu_server/tests/Unit/FilePublicUrlTest.php
T
2026-07-06 22:01:16 +03:30

116 lines
3.3 KiB
PHP

<?php
namespace Tests\Unit;
use App\Models\File;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Tests\TestCase;
class FilePublicUrlTest extends TestCase
{
private function bindRequest(string $host, string $path = '/server/admin/file'): Request
{
$request = Request::create('https://'.$host.$path, 'POST');
$this->app->instance('request', $request);
return $request;
}
private function expectedServerBase(string $host): string
{
return 'https://'.$host.'/server';
}
private function seedServerUrlSetting(string $host): void
{
Setting::query()->updateOrCreate(
['key' => 'server_url'],
['value' => $this->expectedServerBase($host), 'is_active' => 1, 'title_fa' => 'server']
);
}
private function seedAdminUrlSetting(string $host): void
{
Setting::query()->updateOrCreate(
['key' => 'admin_url'],
['value' => 'https://'.$host.'/admin/', 'is_active' => 1, 'title_fa' => 'admin']
);
}
public function test_public_url_uses_request_host_for_storage_path(): void
{
$host = 'tenant-a.test';
$this->bindRequest($host);
$url = File::publicUrl('storage/1405/02/27/sample.jpg');
$this->assertSame(
$this->expectedServerBase($host).'/storage/1405/02/27/sample.jpg',
$url
);
}
public function test_public_url_rewrites_legacy_wrong_absolute_url_using_request_host(): void
{
$host = 'tenant-a.test';
$this->bindRequest($host);
$url = File::publicUrl('https://'.$host.'/storage/1405/02/27/sample.jpg');
$this->assertSame(
$this->expectedServerBase($host).'/storage/1405/02/27/sample.jpg',
$url
);
}
public function test_resolve_base_from_admin_url_setting_when_no_http_request(): void
{
Config::set('app.domain', null);
Config::set('app.url', 'http://localhost');
$host = 'tenant-b.test';
$this->seedAdminUrlSetting($host);
$this->assertSame($this->expectedServerBase($host), File::resolvePublicBaseUrl());
}
public function test_public_url_falls_back_to_relative_path_when_base_unknown(): void
{
Config::set('app.domain', null);
Config::set('app.url', 'http://localhost');
$url = File::publicUrl('storage/1405/02/27/sample.jpg');
$this->assertSame('storage/1405/02/27/sample.jpg', $url);
}
public function test_resolve_base_from_current_request_host(): void
{
Config::set('app.domain', null);
Config::set('app.url', 'http://localhost');
$host = 'tenant-c.test';
$this->bindRequest($host);
$this->assertSame($this->expectedServerBase($host), File::resolvePublicBaseUrl());
}
public function test_request_host_wins_over_stale_settings_domain(): void
{
$staleHost = 'stale-tenant.test';
$requestHost = 'current-tenant.test';
$this->seedServerUrlSetting($staleHost);
$this->bindRequest($requestHost);
$url = File::publicUrl('storage/1405/04/15/sample.png');
$this->assertSame(
$this->expectedServerBase($requestHost).'/storage/1405/04/15/sample.png',
$url
);
}
}