lucasdotvin / laravel-database-queries-counter
此包提供了一个简单的特性来检查测试套件执行了多少查询。
0.5.0
2022-05-18 22:22 UTC
Requires
- php: ^7.4|^8.0|^8.1
- illuminate/contracts: ^8.0|^9.0
Requires (Dev)
- nunomaduro/collision: ^5.10|^6.0
- nunomaduro/larastan: ^1.0|^2.0.1
- orchestra/testbench: ^6.22|^7.0
- pestphp/pest: ^1.21
- pestphp/pest-plugin-laravel: ^1.1
- phpstan/extension-installer: ^1.1
- phpstan/phpstan-deprecation-rules: ^1.0
- phpstan/phpstan-phpunit: ^1.0
- phpunit/phpunit: ^9.5
- spatie/laravel-ray: ^1.26
This package is auto-updated.
Last update: 2024-09-09 18:23:39 UTC
README
此包提供了一种简单的方法来检查测试套件执行了多少查询。
需要注意的是,仅仅控制你在数据库上执行了多少查询并不足以确保你的应用程序有良好的性能。此包的目的不是这样做,而是旨在帮助你防止常见的错误(如N+1查询)。
安装
您可以通过composer安装此包
composer require lucasdotvin/laravel-database-queries-counter --dev
如果您想扩展它们,可以发布特性
php artisan vendor:publish --tag="laravel-database-queries-counter-traits"
使用
将CountsQueries
特性添加到您的测试套件类中,以便访问包方法,如startCountingQueries
、stopCountingQueries
和assertDatabaseQueriesCount
,如下所示,其中我们断言索引路由不会执行N+1查询来加载博客中的帖子
<?php namespace Tests\Feature; use App\Models\Post; use App\Models\User; use LucasDotVin\DBQueriesCounter\Traits\CountsQueries; use Tests\TestCase; class PostTest extends TestCase { use CountsQueries; public function testIndexPageDoesNotPerfomNPlusOneQueries() { Post::factory()->times(10)->create(); $user = User::factory()->create(); $this->actingAs($user); $this->startCountingQueries(); $response = $this->get(route('posts.index')); $this->stopCountingQueries(); $response->assertSuccessful(); $this->assertDatabaseQueriesCount(1); } }
您还可以使用whileCountingQueries
方法来避免控制何时开始和停止计数查询,如下所示,我们对上面的示例进行重构
public function testIndexPageDoesNotPerfomNPlusOneQueries() { Post::factory()->times(10)->create(); $user = User::factory()->create(); $this->actingAs($user); $response = $this->whileCountingQueries(fn () => $this->get(route('posts.index'))); $response->assertSuccessful(); $this->assertDatabaseQueriesCount(1); }
测试
composer test
变更日志
请参阅变更日志获取有关最近更改的更多信息。
贡献
请参阅贡献指南获取详细信息。
安全漏洞
请审查我们的安全策略了解如何报告安全漏洞。
致谢
许可
MIT许可(MIT)。请参阅许可文件获取更多信息。