Files

93 lines
2.8 KiB
PHP

<?php
namespace Tests\Feature;
use App\Models\Category;
use App\Models\Post;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class ApiTest 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' => 'API 测试文章',
'slug' => 'api-post',
'content' => '**加粗** 内容',
'content_format' => 'markdown',
'status' => 'published',
'published_at' => now(),
]);
}
public function test_site_endpoint(): void
{
$this->getJson('/api/site')->assertOk()->assertJsonPath('api_version', '1.0');
}
public function test_posts_list_and_detail(): void
{
$this->getJson('/api/posts')->assertOk()->assertJsonCount(1, 'data');
$this->getJson('/api/posts/api-post')
->assertOk()
->assertJsonPath('title', 'API 测试文章')
->assertJsonPath('category.name', '技术');
}
public function test_posts_search_and_filters(): void
{
$this->getJson('/api/posts?q=API')->assertOk()->assertJsonCount(1, 'data');
$this->getJson('/api/posts?category=tech')->assertOk()->assertJsonCount(1, 'data');
$this->getJson('/api/posts?q=不存在的词')->assertOk()->assertJsonCount(0, 'data');
}
public function test_categories_and_tags(): void
{
$this->getJson('/api/categories')->assertOk()->assertJsonCount(1, 'data');
$this->getJson('/api/tags')->assertOk();
}
public function test_store_comment(): void
{
$post = Post::where('slug', 'api-post')->first();
$this->postJson('/api/comments', [
'post_id' => $post->id,
'author_name' => 'API 访客',
'content' => '来自 API 的评论',
'website' => '',
])->assertCreated()->assertJsonPath('data.status', 'published');
$this->assertDatabaseHas('comments', ['author_name' => 'API 访客']);
}
public function test_comment_honeypot_rejected(): void
{
$post = Post::where('slug', 'api-post')->first();
$this->postJson('/api/comments', [
'post_id' => $post->id,
'author_name' => '机器人',
'content' => 'spam',
'website' => 'http://spam.example.com',
])->assertStatus(422);
}
public function test_me_requires_token(): void
{
$this->getJson('/api/me')->assertUnauthorized();
}
}