83 lines
2.2 KiB
PHP
83 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace Tests\Feature;
|
|
|
|
use App\Blog\Support\PageCacheMiddleware;
|
|
use App\Models\Category;
|
|
use App\Models\Post;
|
|
use App\Models\User;
|
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
|
use Illuminate\Support\Facades\Cache;
|
|
use Tests\TestCase;
|
|
|
|
class PageCacheTest extends TestCase
|
|
{
|
|
use RefreshDatabase;
|
|
|
|
protected function setUp(): void
|
|
{
|
|
parent::setUp();
|
|
|
|
$this->seed();
|
|
|
|
$user = User::create(['name' => '作者', 'email' => 'w@t.com', 'password' => bcrypt('x')]);
|
|
$cat = Category::create(['name' => '技术', 'slug' => 'tech']);
|
|
Post::create([
|
|
'user_id' => $user->id,
|
|
'category_id' => $cat->id,
|
|
'title' => '缓存测试',
|
|
'slug' => 'cache-test',
|
|
'content' => '内容',
|
|
'content_format' => 'markdown',
|
|
'status' => 'published',
|
|
'published_at' => now(),
|
|
]);
|
|
}
|
|
|
|
public function test_anonymous_page_is_cached(): void
|
|
{
|
|
PageCacheMiddleware::flush();
|
|
|
|
$this->get('/')->assertOk();
|
|
$this->assertSame(1, PageCacheMiddleware::count());
|
|
|
|
// 第二次命中缓存
|
|
$this->get('/')->assertOk();
|
|
$this->assertSame(1, PageCacheMiddleware::count());
|
|
}
|
|
|
|
public function test_authenticated_user_not_cached(): void
|
|
{
|
|
PageCacheMiddleware::flush();
|
|
|
|
$user = User::where('email', 'admin@laralog.test')->first();
|
|
$this->actingAs($user)->get('/')->assertOk();
|
|
|
|
$this->assertSame(0, PageCacheMiddleware::count());
|
|
}
|
|
|
|
public function test_track_view_increments_without_caching(): void
|
|
{
|
|
PageCacheMiddleware::flush();
|
|
|
|
$post = Post::where('slug', 'cache-test')->first();
|
|
$views = $post->views;
|
|
|
|
$this->get('/posts/cache-test.shtml')->assertOk();
|
|
$this->get('/track-view/'.$post->id)->assertStatus(204);
|
|
|
|
$post->refresh();
|
|
$this->assertSame($views + 1, $post->views);
|
|
}
|
|
|
|
public function test_flush_clears_pages(): void
|
|
{
|
|
$this->get('/')->assertOk();
|
|
$this->assertSame(1, PageCacheMiddleware::count());
|
|
|
|
PageCacheMiddleware::flush();
|
|
|
|
$this->assertSame(0, PageCacheMiddleware::count());
|
|
}
|
|
}
|