Korxona ilovalarini testlash
Dasturchi QQS ni yaxlitlash qatorini “chiroyliroq” qilib qayta yozdi. Hammasi ishlayapti. Uch oydan keyin hisob-fakturalardagi QQS soliq hisobotidan 1 so‘mga farq qila boshladi. Buni kim, qachon sezishi kerak edi?
Xato kodda emas, jarayonda. Qaysi bosqich uni ushlab qolishi mumkin edi?
Bu ma’ruza oxirida siz quyidagilarni bajara olasiz...
Testlash strategiyasi va Pest asoslari
Test turlari va ularning narxi
| Tur | Nima tekshiradi | Tezlik / soni | OmborPro misoli |
|---|---|---|---|
| Unit | Sof biznes-qoida, bazasiz | ms / yuzlab | OrderStatus o‘tishlari, QQS |
| Integratsion | Servis + PostgreSQL + tranzaksiya | 10–100 ms / o‘nlab | StockService::reserve() |
| API (feature) | HTTP → middleware → JSON | 50–300 ms / o‘nlab | POST /api/v1/orders → 201/422/403 |
| E2E (brauzer) | Foydalanuvchi ssenariysi | soniyalar / bir nechta | Login → buyurtma → hisob-faktura |
Birinchi unit test: AAA tuzilmasi
// tests/Unit/VatTest.php use App\Domain\Vat; test('QQS 12 % bilan, so‘mgacha yaxlitlanadi', function () { // Arrange $subtotal = 1_000_005; // Act $vat = Vat::of($subtotal); // Assert expect($vat)->toBe(120_001); }); it('nol summadan QQS nolga teng', function () { expect(Vat::of(0))->toBe(0); });
$ php artisan test --filter=Vat PASS Tests\Unit\VatTest ✓ QQS 12 % bilan, so‘mgacha yaxlitlanadi 0.01s ✓ it nol summadan QQS nolga teng 0.01s Tests: 2 passed (2 assertions)
it nomga “it” qo‘shadi===) taqqoslashYomon va yaxshi test
✗ Noto‘g‘ri
test('test1')— nomidan nima tekshirilishi noma’lum- Bitta testda 5 ta turli xatti-harakat
now()va real cbu.uz ga bog‘liq — ertaga qizil- Kutilgan qiymat production formulasidan ko‘chirilgan
- Oldingi test yaratgan yozuvga tayanadi
✓ To‘g‘ri
it('qoldiq yetmasa rezerv qilinmaydi')- Bitta xatti-harakat, aniq Arrange / Act / Assert
freezeTime(),Http::fake()— deterministik- Kutilgan qiymat qo‘lda hisoblangan:
120_001 - Har test o‘z ma’lumotini fabrika bilan yaratadi
1-bo‘lim yakuni: Testlash strategiyasi va Pest asoslari
1-topshiriq: Test natijalari xulosasi
Test yurgizuvchi (runner) natijalari ro‘yxati berilgan: har biri ['name' => string, 'status' => string, 'ms' => int], status — passed, failed yoki skipped. Xulosa tuzing: har bir holat soni, jami vaqt, eng sekin test nomi (bir xil bo‘lsa — ro‘yxatda birinchisi; ro‘yxat bo‘sh bo‘lsa null) va ok — yiqilgan test yo‘q va kamida bitta o‘tgan test bor. Noma’lum status — InvalidArgumentException.
Imzo: function test_hisoboti(array $natijalar): array
Qaytaradi: ['passed' => int, 'failed' => int, 'skipped' => int, 'duration_ms' => int, 'slowest' => ?string, 'ok' => bool] — kalitlar shu tartibda.
test_hisoboti([['name' => 'qqs', 'status' => 'passed', 'ms' => 12], ['name' => 'rezerv', 'status' => 'failed', 'ms' => 80], ['name' => 'api', 'status' => 'passed', 'ms' => 150]])
{"passed":2,"failed":1,"skipped":0,"duration_ms":242,"slowest":"api","ok":false}Unit testlar: biznes-qoidalar
Holat mashinasini jadval bilan testlash
use App\Enums\OrderStatus as S; it('ruxsat etilgan o‘tishlar', function (S $from, S $to) { expect($from->canTransitionTo($to))->toBeTrue(); })->with([ [S::Draft, S::Confirmed], [S::Confirmed, S::Reserved], [S::Reserved, S::Invoiced], [S::Invoiced, S::Shipped], [S::Reserved, S::Cancelled], ]); it('taqiqlangan o‘tishlar', function (S $from, S $to) { expect($from->canTransitionTo($to))->toBeFalse(); })->with([ [S::Shipped, S::Cancelled], [S::Invoiced, S::Cancelled], [S::Draft, S::Shipped], ]);
✓ it ruxsat etilgan o‘tishlar with (OrderStatus::Draft, OrderStatus::Confirmed) ✓ it ruxsat etilgan o‘tishlar with (OrderStatus::Confirmed, OrderStatus::Reserved) ... ✓ it taqiqlangan o‘tishlar with (OrderStatus::Draft, OrderStatus::Shipped) Tests: 8 passed (8 assertions)
OrderStatus enumidagi o‘tish qoidasi metodiKo‘p ishlatiladigan tekshiruvlar
| Tekshiruv | Ma’nosi | Misol |
|---|---|---|
toBe($x) | Qat’iy tenglik === | expect($vat)->toBe(120_000) |
toEqual($x) | ==, massivlarni chuqur | expect($dto->toArray())->toEqual([...]) |
toMatchArray([...]) | Massivda shu kalit-qiymatlar bor | ->toMatchArray(['status' => 'draft']) |
toHaveCount(n) | Elementlar soni | expect($items)->toHaveCount(3) |
toThrow(E::class) | Closure istisno tashlaydi | expect(fn () => ...)->toThrow(...) |
not->... | Inkor | expect($rate)->not->toBeNull() |
->prop->toBe() | Obyekt xossasi bo‘yicha | expect($stock)->reserved->toBe(4) |
toBe('1120000.00'), toBe(1120000) emas.Dataset aslida nima qiladi
$allowed = ['draft>confirmed', 'draft>cancelled', 'confirmed>reserved', 'confirmed>cancelled', 'reserved>invoiced', 'reserved>cancelled', 'invoiced>shipped']; $dataset = [ ['draft', 'confirmed', true], ['reserved', 'cancelled', true], ['invoiced', 'cancelled', false], ['shipped', 'draft', false], ['draft', 'shipped', true], // ataylab xato kutilma ]; $passed = $failed = 0; foreach ($dataset as [$from, $to, $expected]) { $ok = in_array("$from>$to", $allowed, true) === $expected; $ok ? $passed++ : $failed++; echo ($ok ? 'PASS' : 'FAIL') . " $from -> $to" . PHP_EOL; } echo "Tests: $passed passed, $failed failed";
PASS draft -> confirmed PASS reserved -> cancelled PASS invoiced -> cancelled PASS shipped -> draft FAIL draft -> shipped Tests: 4 passed, 1 failed
2-bo‘lim yakuni: Unit testlar: biznes-qoidalar
toBe va toEqual farqi nimada?2-topshiriq: Mini expect(): tekshiruvlar
Pest ning expect() tekshiruvlarini soddalashtirilgan ko‘rinishda yozing. $matcher: toBe (===), toEqual (==), toBeTrue (=== true), toBeNull, toHaveCount (massiv bo‘lsa count === $expected, aks holda false), toContain (massiv — qat’iy in_array, satr — str_contains, boshqa tur — false), toBeGreaterThan (>). not-> prefiksi natijani inkor qiladi: not->toBe. Noma’lum matcher — InvalidArgumentException.
Imzo: function ifoda_tekshir(mixed $actual, string $matcher, mixed $expected = null): bool
Qaytaradi: true — tekshiruv o‘tdi, false — yiqildi.
ifoda_tekshir(120000, 'toBe', 120000)
true
Integratsion testlar: baza, fabrikalar, fake lar
ProductFactory: definition va state
class ProductFactory extends Factory { public function definition(): array { return [ 'sku' => fake()->unique()->bothify('UN-###'), 'name' => fake()->words(3, true), 'category_id' => Category::factory(), 'unit' => fake()->randomElement(['dona', 'kg', 'quti']), 'price' => fake()->numberBetween(1_000, 500_000) . '.00', 'min_stock' => 10, 'is_active' => true, ]; } public function inactive(): static { return $this->state(fn () => ['is_active' => false]); } }
Product::factory()->count(3)->create(); // 3 ta faol
Product::factory()->inactive()->make(); // bazaga yozmaydi
Product::factory()->sequence(['unit' => 'kg'], ['unit' => 'dona'])
->count(4)->create(); // kg, dona, kg, donasku unique — takrorlanmas qiymatQoldiq yetmasa — rezerv yo‘q, holat o‘zgarmaydi
it('qoldiq yetmasa rezerv qilinmaydi', function () { $stock = Stock::factory() ->create(['quantity' => 5, 'reserved' => 3]); $service = app(StockService::class); expect(fn () => $service->reserve( $stock->warehouse_id, $stock->product_id, 3, ))->toThrow(InsufficientStockException::class); expect($stock->fresh()) ->quantity->toBe(5) ->reserved->toBe(3); $this->assertDatabaseMissing('stock_movements', [ 'product_id' => $stock->product_id, 'type' => 'reserve', ]); });
PASS Tests\Feature\StockServiceTest ✓ it qoldiq yetmasa rezerv qilinmaydi 0.08s
InsufficientStockExceptionCbuRateService: tarmoqsiz test
it('CBU dan faqat kerakli valyutalarni saqlaydi', function () { Http::preventStrayRequests(); Http::fake(['cbu.uz/*' => Http::response([ ['Ccy' => 'USD', 'Rate' => '12850.45', 'Nominal' => '1', 'Date' => '27.10.2026'], ['Ccy' => 'GBP', 'Rate' => '16500.00', 'Nominal' => '1', 'Date' => '27.10.2026'], ])]); expect(app(CbuRateService::class)->fetch())->toBe(1); $this->assertDatabaseHas('exchange_rates', [ 'date' => '2026-10-27', 'currency' => 'USD', ]); Http::assertSentCount(1); });
✓ it CBU dan faqat kerakli valyutalarni saqlaydi 0.05s (haqiqiy cbu.uz ga so‘rov ketmadi)
Yon ta’sirlarni almashtirish
| Vosita | Tekshiruv | OmborPro misoli |
|---|---|---|
Queue::fake() | assertPushedOn('reports', ...) | Hisobot jobi navbatga tushdi |
Notification::fake() | assertSentTo($user, ...) | Omborchiga LowStockNotification |
Http::fake([...]) | assertSent(fn ($r) => ...) | cbu.uz, SMS provayderi |
Event::fake([...]) | assertDispatched(OrderConfirmed::class) | Buyurtma tasdiqlandi hodisasi |
Storage::fake('local') | Storage::disk('local')->assertExists() | Hisobot fayli yaratildi |
$this->freezeTime() | now() o‘zgarmaydi | Kunlik kesh kaliti, scheduler |
3-bo‘lim yakuni: Integratsion testlar: baza, fabrikalar, fake lar
RefreshDatabase testlarni bir-biridan qanday ajratadi?Http::preventStrayRequests() nima uchun kerak?API (feature) testlar
Mahsulotlar ro‘yxati: sahifalash va tuzilma
beforeEach(function () { $this->seed(RoleSeeder::class); $this->user = User::factory()->create()->assignRole('menejer'); }); it('mahsulotlarni sahifalab qaytaradi', function () { Product::factory()->count(25)->create(); $this->actingAs($this->user, 'api') ->getJson('/api/v1/products?per_page=10') ->assertOk() ->assertJsonCount(10, 'data') ->assertJsonPath('meta.total', 25) ->assertJsonStructure(['data' => [['sku', 'name', 'price']]]); });
PASS Tests\Feature\Api\ProductApiTest ✓ it mahsulotlarni sahifalab qaytaradi 0.21s
403 va 422 ni tekshirish
it('bo‘sh items bilan 422 qaytaradi', function () { $this->actingAs($this->user, 'api') ->postJson('/api/v1/orders', validOrderPayload(['items' => []])) ->assertUnprocessable() ->assertJsonValidationErrors(['items']); }); it('rol bo‘yicha huquq', function (string $role, int $code) { $user = User::factory()->create()->assignRole($role); $this->actingAs($user, 'api') ->postJson('/api/v1/orders', validOrderPayload()) ->assertStatus($code); })->with([ ['admin', 201], ['menejer', 201], ['omborchi', 403], ['buxgalter', 403], ]);
✓ it bo‘sh items bilan 422 qaytaradi
✓ it rol bo‘yicha huquq with ('admin', 201)
✓ it rol bo‘yicha huquq with ('menejer', 201)
✓ it rol bo‘yicha huquq with ('omborchi', 403)
✓ it rol bo‘yicha huquq with ('buxgalter', 403)tests/Pest.php dagi yordamchi: yaroqli so‘rov + o‘zgartirishHisobot so‘rovi: 202 va navbatdagi job
it('hisobot so‘rovi jobni navbatga qo‘yadi', function () { Queue::fake(); $accountant = User::factory()->create()->assignRole('buxgalter'); $this->actingAs($accountant) ->postJson('/reports/sales', [ 'from' => '2026-10-01', 'to' => '2026-10-31', ]) ->assertStatus(202); Queue::assertPushedOn('reports', GenerateSalesReport::class, fn ($job) => $job->from === '2026-10-01' && $job->user->is($accountant)); });
✓ it hisobot so‘rovi jobni navbatga qo‘yadi 0.09s
HTTP javob tasdiqlari
| Usul | Kod / ma’no | Qachon |
|---|---|---|
assertOk() | 200 | Ro‘yxat, ko‘rish |
assertCreated() | 201 | Yangi resurs yaratildi |
assertStatus(202) | 202 | Asinxron qabul qilindi |
assertUnauthorized() | 401 | Token yo‘q yoki yaroqsiz |
assertForbidden() | 403 | Rol yoki Policy ruxsat bermaydi |
assertUnprocessable() | 422 | Validatsiya xatosi |
assertJsonPath(p, v) | Yo‘l bo‘yicha qiymat | Maydon qiymati muhim bo‘lsa |
assertJsonStructure([...]) | Maydonlar mavjud | Shartnoma himoyasi |
4-bo‘lim yakuni: API (feature) testlar
post() emas, postJson() ishlatiladi?assertCreated() bilan cheklanish nima uchun yetarli emas?Qamrov (coverage) va statik tahlil
php artisan test --coverage --min=80
# Docker obrazida PCOV (dev bosqichi): # RUN pecl install pcov && docker-php-ext-enable pcov docker compose exec app php artisan test --coverage --min=80 # HTML hisobot: qaysi qatorlar qoplanmagan docker compose exec app ./vendor/bin/pest --coverage-html coverage
Services/CbuRateService ............................ 100.0 % Services/OrderService .................. 41..58 / 86.4 % Services/StockService .............................. 95.2 % Http/Controllers/ReportController ...... 22..31 / 62.5 % Total: 81.7 %
Qamrov foizi qanday hisoblanadi
$files = [ 'Services/OrderService.php' => [120, 104], // [jami, qoplangan] 'Services/StockService.php' => [84, 80], 'Http/Controllers/ReportController.php' => [40, 25], 'Models/Product.php' => [0, 0], // bajariladigan qator yo‘q ]; $all = $hit = 0; foreach ($files as $file => [$lines, $covered]) { if ($lines === 0) { continue; } $all += $lines; $hit += $covered; printf("%-38s %5.1f %%\n", $file, $covered / $lines * 100); } printf("Total: %.1f %%\n", $hit / $all * 100); echo $hit / $all >= 0.8 ? 'OK (min 80 %)' : 'FAIL (min 80 %)';
Services/OrderService.php 86.7 % Services/StockService.php 95.2 % Http/Controllers/ReportController.php 62.5 % Total: 85.7 % OK (min 80 %)
phpstan.neon va natija
# phpstan.neon includes: - vendor/larastan/larastan/extension.neon parameters: paths: - app/ level: 6 # ishga tushirish: # ./vendor/bin/phpstan analyse --memory-limit=1G # eski loyihada boshlash: # ./vendor/bin/phpstan analyse --generate-baseline
------ --------------------------------------------------------
Line app/Services/InvoiceService.php
------ --------------------------------------------------------
42 Method App\Services\InvoiceService::vat() should return
string but returns float.
[ERROR] Found 1 errorArxitektura qoidalari — test ko‘rinishida
// tests/Feature/ArchTest.php arch('controllerlar DB fasadini to‘g‘ridan-to‘g‘ri ishlatmaydi') ->expect('App\Http\Controllers') ->not->toUse('Illuminate\Support\Facades\DB'); arch('debug funksiyalari qolib ketmagan') ->expect(['dd', 'dump', 'ray']) ->not->toBeUsed(); arch('modellar Eloquent Model dan meros oladi') ->expect('App\Models') ->toExtend('Illuminate\Database\Eloquent\Model');
✓ arch controllerlar DB fasadini to‘g‘ridan-to‘g‘ri ishlatmaydi
✗ arch debug funksiyalari qolib ketmagan
Expecting 'dd' not to be used in 'App\Services\ReportService' (line 57).dd() production ga chiqmasin5-bo‘lim yakuni: Qamrov (coverage) va statik tahlil
pint va pint --test farqi nimada va qaysi biri CI da ishlatiladi?3-topshiriq: Qamrov hisoboti
Har bir fayl uchun [jami_bajariladigan_qatorlar, qoplangan_qatorlar] berilgan. Bajariladigan qatori 0 bo‘lgan fayllar hisobga olinmaydi. Har bir fayl foizi va jami foiz (qatorlar yig‘indisi bo‘yicha, fayl foizlarining o‘rtachasi emas) round(..., 1) bilan. files — foiz bo‘yicha o‘sish tartibida, teng bo‘lsa yo‘l bo‘yicha. below — foizi $min dan past fayllar (shu tartibda). pass — jami ≥ $min. below va pass yaxlitlangan foizlar bilan solishtiriladi. Qoplangan > jami yoki manfiy qiymat — InvalidArgumentException; hisobga olinadigan fayl yo‘q — DomainException.
Imzo: function qamrov_hisoboti(array $fayllar, float $min): array
Qaytaradi: ['total' => float, 'files' => [yo‘l => float, ...], 'below' => list<string>, 'pass' => bool].
qamrov_hisoboti(['Services/OrderService.php' => [120, 104], 'Services/StockService.php' => [84, 80], 'Http/ReportController.php' => [40, 25], 'Models/Product.php' => [0, 0]], 80)
{"total":85.7,"files":{"Http/ReportController.php":62.5,"Services/OrderService.php":86.7,"Services/StockService.php":95.2},"below":["Http/ReportController.php"],"pass":true}Kod tahlili (code review) va pre-commit hooklar
O‘zgarish main ga qanday yetib boradi
Tarmoq
git switch -c feature/low-stock-alert — issue raqami bilanKichik commitlar
PR ochish
Avtomatik tekshiruvlar
Kod tahlili
Squash merge
.githooks/pre-commit
#!/bin/sh # o‘rnatish: git config core.hooksPath .githooks FILES=$(git diff --cached --name-only --diff-filter=ACMR -- '*.php') [ -z "$FILES" ] && exit 0 echo "Pint..." ./vendor/bin/pint --test $FILES || { echo "Uslub xatosi: ./vendor/bin/pint ni ishga tushiring" exit 1 } echo "Larastan..." ./vendor/bin/phpstan analyse --no-progress $FILES || exit 1 echo "Unit testlar..." ./vendor/bin/pest --testsuite=Unit --stop-on-failure || exit 1
$ git commit -m "Kam qoldiq xabari" Pint... ⨯ app/Jobs/SendLowStockAlert.php no_unused_imports Uslub xatosi: ./vendor/bin/pint ni ishga tushiring (commit bekor qilindi)
Ko‘rib chiquvchi nimaga qaraydi
1Biznes-qoidalar
2Tranzaksiya
DB::transaction; qoldiq — lockForUpdate; job — afterCommit.3Xavfsizlik
$fillable, xom SQL da bog‘langan parametrlar, kalitlar .env da.4Unumdorlik
5Testlar
6Migratsiya
down() bormi, katta jadvalda xavfsizmi, default qiymatlar?6-bo‘lim yakuni: Kod tahlili (code review) va pre-commit hooklar
nit: va blocking: izohlarining farqi nimada?Asosiy xulosalar
1Test — bajariladigan spetsifikatsiya
2Unit — sof biznes-qoidalar
expect, dataset, toThrow (closure bilan), chegaraviy qiymatlar.3Integratsion — haqiqiy baza
RefreshDatabase, PostgreSQL test bazasi, fabrikalar, invariantlar va fake lar.4API test — shartnoma himoyasi
5Qamrov va linterlar
--coverage --min, Pint --test, Larastan darajalari, arch testlar.6Code review + hook
Yakunlashdan oldin sakkizta savol
RefreshDatabase nima qiladi?12-amaliy mashg‘ulot: 5 ta PHP topshiriq va loyiha bosqichi
Factory sequence modeli
assertJsonPath modeli
Pre-commit: tekshiriladigan PHP fayllar
Pull Request merge ga tayyormi?
Ombor daftari: testlanadigan biznes-qoidalar
Darsni tark etishdan oldin
Javoblaringizni yozing (✎ Javob yozish) yoki qog‘ozga yozib topshiring.
blocking: izoh qanday bo‘lardi?