Testing Messaging Systems
“When testing code that dispatches jobs, you may wish to instruct Laravel to not actually execute the job itself, since the job's code can be tested directly and separately of the code that dispatches it.” — Laravel 13 documentation, Queues: Testing
خلاصه: کد ناهمگام با حذف تدریجی نامعینی تست میشود: fake برای منطق، contract برای شکل پیام، broker واقعی برای سیمکشی و تزریق خطا برای مسیر شکست. تمرکز: هرم تست در سیستمهای ناهمگام، port و fake، fakeهای Laravel، contract test، Testcontainers، idempotency، chaos، جداسازی، تست ناپایدار و هزینهٔ CI. هدف یادگیری: برای هر رفتار پیامرسانی ارزانترین تستِ قادر به اثبات آن را انتخاب کنید، در Go و Laravel 13 بنویسید و مجموعه را قطعی، جدا از هم و سریع نگه دارید.
این فصل دربارهٔ نحوهٔ تست کدی است که پیام میفرستد و میگیرد. چرایی تکرار و جابهجایی پیام در تضمینهای تحویل آمده است؛ طراحی dedup که اینجا تست میشود در مصرفکنندهٔ idempotent است؛ مسیر شکست در DLQ؛ زمانبندی تلاشها در Retry و backoff؛ قواعد سازگاری در طراحی پیام و تکامل schema؛ و الگوی Test Message برای بررسیهای نزدیک به production در الگوهای مدیریت سیستم.
نقشهٔ صفحه
| دنبال چه هستید؟ | بخش مربوط |
|---|---|
| کدام نوع تست چه رفتاری را ثابت میکند | هرم تست |
| interface، fake، stub و mock در Go | Port و تستدابل |
| تست retry و backoff بدون انتظار | ساعت جعلی |
Queue::fake()، Bus::fake()، Event::fake()، Notification::fake() | fakeهای Laravel |
| تست تحویل تکراری، خارج از ترتیب و پیام مسموم | Idempotency، ترتیب، مسموم |
| بررسیهای Pact، AsyncAPI و schema registry | قراردادها |
| RabbitMQ، Kafka یا Redis واقعی در container | یکپارچگی، تفاوت brokerها |
| نام یکتا، پاکسازی و تست موازی | جداسازی |
| قطع broker، crash پیش از ack، rebalance | Chaos |
| مجموعهٔ کند، ناپایدار یا گران | تست ناپایدار، هزینهٔ CI |
| دستورهای آزمایش | آزمایشگاه |
همهچیز در یک دقیقه
| لایه | چه چیزی را ثابت میکند | سرعت | نیاز |
|---|---|---|---|
| تست واحد با fake | منطق handler، تصمیمهای retry، مسیریابی DLQ | میلیثانیه | فقط runtime زبان |
| Contract test | تولیدکننده و مصرفکننده روی شکل پیام توافق دارند | میلیثانیه | فایل pact، schema یا golden |
| تست یکپارچگی | تنظیم client، ack، offset و topology روی broker واقعی کار میکند | ثانیه | runtime کانتینر مثل Docker |
| پیام آزمایشی سرتاسری | مسیر مستقر از تولیدکننده تا مصرفکننده سالم است | دقیقه | محیط staging |
| Chaos یا تزریق خطا | بازیابی پس از crash، قطعی یا rebalance | ثانیه تا دقیقه | راهی برای خرابکردن عمدی یک وابستگی |
| تست property-based یا golden | invariantها برای ورودیهای فراوان برقرارند؛ قالب سیمی تغییر نکرده | میلیثانیه | مولد ورودی یا فایل ذخیرهشده |
| پرسش | پاسخ عملی | پیامد نادیدهگرفتن |
|---|---|---|
| برای تست handler به broker نیاز دارم؟ | نه: به یک interface کوچک وابسته شوید و fake بدهید | مجموعهای کند که کسی محلی اجرا نمیکند |
| fake میتواند درستی تنظیم broker را ثابت کند؟ | نه: فقط broker واقعی | تست سبز و سیمکشی خراب در production |
| backoff دهدقیقهای را چگونه تست کنم؟ | ساعت تزریق کنید و sleepهای درخواستشده را بسنجید | تستی که میخوابد یا کد retry که هیچوقت تست نمیشود |
آیا Queue::fake() job را تست میکند؟ | نه: فقط push شدن را؛ handle() را جدا صدا بزنید | jobهایی که push میشوند اما اجرا نمیشوند |
| چرا تست تنها میگذرد و در مجموعه میافتد؟ | queue، group، stream یا state سراسری مشترک | شکستهای ناپایدار که خطای واقعی را پنهان میکنند |
| چه کسی از فیلد تغییرنامیافته محافظت میکند؟ | contract test، نه تست یکپارچگی | رخداد در اولین deploy |
از کجا آمده
مقالهٔ مارتین فاولر با عنوان The Practical Test Pyramid قاعدهای را میگوید که این فصل به پیامرسانی تعمیم میدهد: «Write lots of small and fast unit tests.» بعد «some more coarse-grained tests and very few high-level tests that test your application from end to end» میآید. مدخل bliki دربارهٔ Test Double واژگان را میدهد: «Test Double is a generic term for any case where you replace a production object for testing purposes» و dummy، fake، stub و mock انواع آناند. دربارهٔ fake میگوید: «Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production»؛ نمونهٔ فاولر پایگاه دادهٔ تست درونحافظهای است.
قرارداد مصرفکنندهمحور (Consumer-driven contract) هم در همان مقاله آمده است: «Consumer-Driven Contract tests (CDC tests) let the consumers drive the implementation of a contract.» Pact این ایده را برای HTTP و پیام به کار میبرد؛ برای پیام، هر interaction «The minimal expected message - describing the parts of the message that the consumer wants to use» است (Pact: how Pact works). صفحهٔ specification میگوید نسخهٔ ۳ «Introduces pact format for message queues» را آورد (Pact specification).
Laravel خودش تستدابل برای queue، bus، event و notification دارد. صفحهٔ events در Laravel 13 هشدار میدهد: «After calling Event::fake(), no event listeners will be executed.» Testcontainers خانوادهای از کتابخانههاست که از داخل کد تست containerهای موقت بالا میآورد؛ مستندات Go ماژولهایی برای RabbitMQ، Kafka، Redpanda، Redis و Toxiproxy فهرست میکند.
چرا وجود دارد
سیستم ناهمگام راههای بیشتری برای اشتباه دارد: پیام ممکن است تکراری، جابهجا، دیرهنگام یا گم شود و نتیجه بعداً جای دیگری دیده شود. تست برای این است که این رفتارها ارزان تحریک و بررسی شوند.
| رویکرد وسوسهبرانگیز | رویکرد بهتر |
|---|---|
| برای هر تست یک broker واقعی بالا بیاورید | fake برای منطق؛ broker واقعی فقط برای سیمکشی |
sleep(5) و امید به پایان consumer | ساعت جعلی یا poll با مهلت برای یک شرط |
یک topic مشترک به نام test | topic، queue یا stream یکتا برای هر تست |
| بررسی اینکه پیام publish شد | بررسی اینکه پیام با contract میخواند |
| تست فقط مسیر خوش | تزریق تکرار، ورودی مسموم و broker خاموش |
| همهٔ تستها روی هر commit | لایهٔ سریع همیشه؛ container روی PR؛ chaos شبانه |
سه بدفهمی را از ابتدا کنار بگذارید: fake همان mock نیست (رفتار واقعی دارد، نه انتظار از پیش نوشته)؛ مجموعهٔ سبزِ مبتنی بر fake دربارهٔ تنظیم broker هیچ نمیگوید؛ و تست یکپارچگی contract test نیست، چون فقط همان یک تولیدکننده و مصرفکنندهای را میسنجد که بالا آورده است.
واقعاً دربارهٔ چیست
تست کد ناهمگام یعنی حذف یکییکی منابع نامعینی تا هر تست فقط یک دلیل برای شکست داشته باشد. برنامه به portهای (Ports) کوچک وابسته است (publisher، ساعت، ذخیرهٔ dedup) و تستها پیادهسازی درونحافظهای میدهند. آنچه fake پوشش نمیدهد با لایهٔ نازکی از تست روی broker واقعی پوشش داده میشود.
| منبع نامعینی | تست چگونه آن را حذف میکند |
|---|---|
| ساعت دیواری (backoff، TTL، تأخیر) | ساعت تزریق کنید؛ sleepهای درخواستشده را بسنجید یا زمان را جلو ببرید |
| ترتیب تحویل و redelivery در broker | bus درونحافظهای که گامبهگام میرانید و Crash() دارد |
| همزمانی و زمانبندی goroutineها | هر بار یک پیام؛ -race؛ poll با مهلت |
| state مشترک broker | نام یکتا برای هر تست و پاکسازی در t.Cleanup |
| شناسه و زمان تصادفی | ID و زمان را تزریق کنید؛ golden file با مقادیر ثابت |
| خطای شبکه و وابستگی | fake شکستخور یا proxy تزریق خطا |
تصویری از زندگی روزمره
به آژیر آتش یک ساختمان فکر کنید. هر دتکتور دود را با دکمهٔ تست خودش میآزمایید (تست واحد با fake). بررسی میکنید تابلوی آژیر و دتکتورها یک سیگنال را میفهمند (contract). در ساختمان بسته یک آژیر واقعی راه میاندازید تا سیمکشی، آژیرها و درها را ببینید (یکپارچگی). گاهی تمرین سرزده با یک خروجی مسدود برگزار میکنید (chaos). برای تست دتکتور ساختمان را نمیسوزانید، و دتکتورِ سالم ثابت نمیکند آژیرها درست وصلاند.
فهرست مفاهیم
هرم تست در سیستمهای ناهمگام (Test pyramid) حیاتی
به زبان ساده: تستهای سریع فراوان در پایین، تستهای کند و واقعگرایانهٔ اندک در بالا، و هر رفتار در ارزانترین لایهای تست میشود که میتواند آن را ثابت کند.
بدفهمی رایج: «پیامرسانی یعنی یکپارچگی، پس با broker واقعی تست کنید.» بیشتر باگهای پیامرسانی در منطق handler هستند: دستهبندی، dedup و تصمیم retry. اینها broker نمیخواهند.
تعریف: هرم تست (ایدهٔ مایک کوهن که فاولر در مقالهاش بحث میکند) مجموعهها را بر اساس دانهبندی مرتب میکند: واحد، سرویس یا یکپارچگی، سپس سرتاسری. در پیامرسانی، تست واحد از fake استفاده میکند؛ contract test خود پیام را میسنجد؛ تست یکپارچگی broker را بالا میآورد؛ تست سرتاسری یک پیام واقعی را از staging رد میکند.
1 Handler logic changed -> unit test with fakes (ms, every save)
2 Event field renamed -> contract test (ms, every commit)
3 Prefetch / ack mode changed -> integration test, container (s, every PR)
4 New route added in staging -> end-to-end test message (min, per deploy)
5 Broker node restarted -> chaos experiment (min, nightly)سناریوهای واقعی: بودجهٔ retry در consumer صورتحساب (واحد)؛ payload رخداد OrderPlaced که currency را حذف میکند (contract)؛ queue که در کد durable است ولی در policy موقت (یکپارچگی)؛ غلط تایپی در routing key فقط در یک محیط (سرتاسری)؛ consumer که با restart شدن RabbitMQ پیام گم میکند (chaos).
| رفتار | ارزانترین لایهٔ اثبات |
|---|---|
| زمانبندی retry، مسیریابی DLQ، dedup | واحد با fake |
| شکل پیام و سازگاری | Contract، golden file، بررسی registry |
حالت ack، prefetch، offset، MKSTREAM | یکپارچگی با broker واقعی |
| سیمکشی محیط، credential، مسیریابی | پیام آزمایشی سرتاسری |
| بازیابی پس از crash یا جابهجایی partition | Chaos یا تزریق خطا |
روش استفاده: برای هر باگی که رفع میکنید بپرسید کدام لایه میتوانست آن را بگیرد و تست را همانجا بیفزایید. اگر لایهای پر از تست کندی شد که فقط منطق را میسنجند، آنها را پایین بیاورید.
Port، fake، stub و mock (Test double) حیاتی
به زبان ساده: client broker را پشت یک interface کوچک پنهان کنید. در تست، جانشینی بگذارید که آنچه رخ داد را ثبت میکند.
بدفهمی رایج: «همهچیز را mock کنید.» تست پر از mock نحوهٔ صدا زدن client را میسنجد، نه نتیجه را، و با هر refactor میشکند. برای چیزهایی مثل publisher یا inbox، fake با رفتار واقعی را ترجیح دهید.
تعریف: Port interfaceای است که خود برنامه مالک آن است (Publisher، Clock). Dummy فقط پارامتر پر میکند. Stub پاسخ آماده میدهد. Fake با یک میانبر کار میکند: in-memory publisher که به یک slice اضافه میکند. Mock فراخوانیهای مورد انتظار را راستیآزمایی میکند. Spy فراخوانیها را برای بررسی بعدی ثبت میکند. Go از interfaceهای کوچکِ سمت مصرفکننده استفاده میکند؛ Laravel از facadeهای دارای fake داخلی و Mockery برای بقیه.
1 test -> newConsumer(t): wires MemoryPublisher, FakeClock, fresh Projection
2 test -> consumer.Process(ctx, msg)
3 SUT -> Clock.Sleep(1s) -> FakeClock records [1s], advances virtual time
4 SUT -> DLQ.Publish(...) -> MemoryPublisher stores the failure envelope
5 test -> asserts outcome, sleeps [1s 2s 4s], one DLQ record with reasonسناریوهای واقعی: consumer صورتحساب با publisher شکستخور تست میشود تا ثابت شود وقتی parking شکست میخورد ack نمیزند؛ inbox که در تست یک map و در production یک جدول SQL است؛ سرویس Laravel که Bus::chain() را با Bus::fake() تست میکنند؛ client درگاه پرداخت که stub است و ردِ آماده برمیگرداند.
| Double | رفتار | کاربرد | ریسک |
|---|---|---|---|
| Dummy | هیچ | پرکردن آرگومان الزامی | هیچ |
| Stub | پاسخ آماده | وادارکردن مسیر خطا | فاصلهگرفتن از client واقعی |
| Fake | میانبر کارا | publisher، bus، inbox، ساعت | رفتار fake با broker فرق کند |
| Mock | راستیآزمایی فراخوانی | یک مرزی که نمیشود fake کرد | شکننده، پیادهسازی را میسنجد |
| Spy | ثبت فراخوانی | بررسی پس از عمل | ضعیفتر از بررسی state |
روش استفاده: interface را همانجا که استفاده میشود تعریف کنید، به یک یا دو متد محدود کنید و fake را کنار آن بنویسید. fake را یک بار در یک تست یکپارچگی با broker واقعی بسنجید تا میانبرش صادق بماند.
ساعت جعلی و کنترل زمان (Fake clock) حیاتی
به زبان ساده: منتظر زمان نمانید. زمان را وابستگی کنید و بگذارید تست آن را جابهجا کند.
بدفهمی رایج: «backoff را در تست ۱۰ میلیثانیه کنید.» این تنظیمِ دیگری را میسنجد و sleep واقعی تحت بار تست را کند و ناپایدار میکند.
تعریف: ساعت جعلی همان interface ساعت واقعی را دارد اما sleepهای درخواستی را ثبت میکند و زمان مجازی را فوراً جلو میبرد. در Go 1.25 و بعد، testing/synctest تابعی را در یک bubble اجرا میکند که به تعبیر مستندات «the time package uses a fake clock»؛ Laravel روی feature testها travel()، travelTo() و travelBack() دارد.
1 Handler attempt 1 fails -> Clock.Sleep(1s) virtual now = +1s
2 Handler attempt 2 fails -> Clock.Sleep(2s) virtual now = +3s
3 Handler attempt 3 succeeds -> Applied
4 Test asserts Sleeps == [1s 2s], elapsed virtual time == 3s, wall time ~ 0سناریوهای واقعی: backoff نمایی با سقف؛ بررسی انقضای پیام (TTL)؛ jobهای زمانبندیشدهٔ تطبیق؛ job تأخیری که با release(30) برمیگردد؛ circuit breaker که پس از خنکشدن دوباره باز میشود.
| ابزار | کجا | نکته |
|---|---|---|
interface تزریقشدهٔ Clock | Go، هر نسخه | با goroutineهایی که کنترل میکنید کار میکند؛ در این فصل استفاده شده |
testing/synctest | Go 1.25 و بعد | زمان جعلی در bubble؛ به directive نسخهٔ 1.25 یا بالاتر نیاز دارد |
$this->travel()، travelTo()، travelBack() | تستهای feature در Laravel | now() و Carbon را عوض میکند |
$job->assertReleased(delay: 30) | Laravel، withFakeQueueInteractions() | تأخیر درخواستی را بدون انتظار میسنجد |
روش استفاده: jitter را از مسیر تستشونده بیرون بگذارید یا منبع تصادفی را تزریق کنید؛ برنامهٔ زمانی را بسنجید، نه زمان سپریشدهٔ دیواری. طراحی کامل سیاست retry در Retry و backoff است.
fakeهای Laravel: Queue، Bus، Event، Notification حیاتی
به زبان ساده: Laravel میتواند queue، bus، dispatcher رخداد و کانال notification را با ثبتکننده عوض کند. کد تحت تست اجرا میشود، چیزی واقعاً ارسال نمیشود و از ثبتکننده میپرسید چه شد.
بدفهمی رایج: «Event::fake() فقط رخدادها را ثبت میکند.» listenerها را هم اجرا نمیکند؛ پس factoryهای مدلی که به رخداد تکیه دارند (مثلاً UUID که در listener رخداد creating ساخته میشود) باید پیش از fake اجرا شوند.
تعریف: Queue::fake()، Bus::fake()، Event::fake() و Notification::fake() سرویس زیرین را با fake ثبتکننده عوض میکنند. fake کردن زیرمجموعه (Queue::fake([ShipOrder::class])) یا همه بهجز زیرمجموعه (->except([...])) اجازه میدهد بقیهٔ jobها یا رخدادها عادی رفتار کنند.
1 test -> Queue::fake(); Bus::fake()
2 SUT -> Bus::chain([A, B, C])->onQueue('orders')->dispatch()
3 fake -> records A with chain [B, C] on queue orders; runs nothing
4 test -> Queue::assertPushedOn('orders', A::class)
5 test -> Bus::assertChained([A::class, B::class, C::class])سناریوهای واقعی: سرویس سفارش زنجیرهٔ پرداخت را dispatch میکند؛ import یک batch از ردیفهای CSV میفرستد؛ وقتی اعتبارسنجی رد شد کنترلر نباید چیزی dispatch کند؛ یک listener باید به رخداد متصل باشد.
| Fake | Assertionها (Laravel 13) | نکته |
|---|---|---|
Queue::fake() | assertPushed، assertPushedOn، assertPushedOnce، assertPushedTimes، assertNotPushed، assertNothingPushed، assertCount، assertClosurePushed | jobها ثبت میشوند، اجرا نمیشوند |
Queue::fake() | assertPushedWithChain، assertPushedWithoutChain | در کلاس QueueFake خود framework؛ job اول و زنجیرهاش را میسنجد |
Bus::fake() | assertDispatched، assertNotDispatched، assertDispatchedSync، assertDispatchedAfterResponse، assertNothingDispatched | کلاس، closure یا آرایهٔ property میپذیرند |
Bus::fake() | assertChained، assertBatched، assertBatchCount، assertNothingBatched | Bus::chainedBatch() یک batch را درون زنجیره میگذارد |
Event::fake() | assertDispatched، assertDispatchedOnce، assertNotDispatched، assertNothingDispatched، assertListening | ->except([...]) و Event::fakeFor(fn) دامنهٔ fake را محدود میکنند |
Notification::fake() | assertSentTo، assertSentToOnce، assertNothingSent، assertCount | برحسب گیرنده و کلاس |
$job->withFakeBatch() | $batch->cancelled()، $batch->added | تعامل job با batch را بدون پایگاه داده تست کنید |
$job->withFakeQueueInteractions() | assertReleased، assertDeleted، assertFailed، assertFailedWith، assertNotFailed | تصمیمهای release، delete و fail را تست کنید |
روش استفاده: handle() یک job را در تست واحد خودش صدا بزنید؛ از fakeها فقط برای بررسی اینکه کار درست صف شد استفاده کنید. بخش Laravel پایینتر تستهای آمادهٔ اجرا دارد. درونساخت driverهای صف در درون Laravel Queue است.
تست idempotency و تحویل تکراری حیاتی
به زبان ساده: عمداً یک پیام را دو بار تحویل بدهید و ببینید اثر کسبوکار یک بار رخ داد.
بدفهمی رایج: «at-least-once مشکل broker است.» تکرار بهطور طراحیشده به handler شما میرسد؛ فقط تستهای شما ثابت میکنند handler از آن جان به در میبرد.
تعریف: تست idempotency (Idempotency test) یک پیام (با همان ID) را پس از موفقیت، پس از crash پیش از ack و پس از شکست جزئی دوباره پخش میکند و یک اثر واحد را میسنجد. تحویل تکراری (Duplicate delivery) کاری است که broker با گمشدن ack انجام میدهد. طراحی تحت تست در مصرفکنندهٔ idempotent و inbox است.
1 Bus.Publish(m1)
2 Consumer.Poll -> Process(m1) -> Applied, effects = 1
3 Bus.Crash() -> worker died before Ack; m1 returns, Redelivered = true
4 Consumer.Poll -> Process(m1) -> Duplicate, effects = 1
5 Delivery.Ack -> depth 0 ready / 0 in flightسناریوهای واقعی: پرداخت دو بار ثبت میشود؛ دو ایمیل برای یک سفارش؛ موجودی پس از rebalance دو بار کم میشود؛ webhook که فرستنده دوباره میفرستد.
| چه چیزی بازپخش شود | نتیجهٔ مورد انتظار |
|---|---|
| همان پیام، همان ID، پس از موفقیت | Duplicate، شمار اثر تغییر نمیکند |
| همان پیام پس از crash پیش از ack | یک بار redeliver و یک اثر |
| همان رخداد کسبوکاری با ID انتقالی تازه | کلید کسبوکار لازم است، نه شناسهٔ تحویل |
| دو نسخهٔ همزمان در حال پردازش | قید یکتا یا قفل میگذارد یکی برنده شود |
روش استفاده: در inbox مبتنی بر پایگاه داده با SQL بررسی کنید دقیقاً یک ردیف هست:
-- After replaying message m-1 twice, the inbox must hold exactly one row.
CREATE TABLE inbox (
message_id text PRIMARY KEY,
consumer text NOT NULL,
processed_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO inbox (message_id, consumer) VALUES ('m-1', 'billing') ON CONFLICT DO NOTHING;
INSERT INTO inbox (message_id, consumer) VALUES ('m-1', 'billing') ON CONFLICT DO NOTHING;
SELECT count(*) FROM inbox WHERE message_id = 'm-1'; -- expect 1ترتیب، تحویل خارج از ترتیب و تست property-based مهم
به زبان ساده: رخدادها را به consumer با ترتیب بد بدهید و ببینید state نهایی هنوز درست است.
بدفهمی رایج: «ترتیب تضمین broker است، پس تست نمیخواهد.» brokerها درون یک queue یا partition ترتیب میدهند؛ retry، چند consumer و replay باز هم رسیدن خارج از ترتیب (Out-of-order) به handler را میسازند. ترتیب و partitioning را ببینید.
تعریف: تست out-of-order توالی ۲ را پیش از ۱ تحویل میدهد. تست property-based برنامههای تصادفی فراوان (تکرار، جایگشت) تولید میکند و یک invariant را میسنجد، مثل «projection همیشه به بالاترین توالی همگرا میشود.» testing/quick در کتابخانهٔ استاندارد Go این کار را میکند، هرچند مستندات پکیج میگوید «is frozen and is not accepting new features»؛ pgregory.net/rapid shrinking و تست state machine اضافه میکند.
1 arrive seq 2 ("shipped") -> Applied
2 arrive seq 1 ("paid") -> Stale, state stays "shipped"
3 arrive seq 2 again -> Duplicate
4 property: for any schedule of seq in 1..5, final state == status of max(seq)سناریوهای واقعی: OrderShipped پیش از OrderPaid؛ backlog بازپخششده که با ترافیک زنده در هم میآید؛ retry که بعد از رخداد جدیدتر میرسد؛ rebalance در Kafka که partition را وسط batch جابهجا میکند.
| تکنیک | چه چیزی را پیدا میکند | هزینه |
|---|---|---|
| تست جایگشت دستی | همان جابهجایی که به ذهنتان رسید | کم |
property با testing/quick | برنامههای فراوان، بدون shrinking | کم |
property با rapid و shrinking | کوچکترین برنامهٔ شکستخور | یک وابستگی اضافه |
| تست مبتنی بر مدل (state machine) | توالی عملیاتی که invariant را میشکند | بیشتر |
روش استفاده: invariant را صریح و ارزان کنید: last-writer-wins بر اساس توالی، یا نسخهٔ یکنوا. برنامههای تولیدی را آنقدر کوچک نگه دارید که اشکالزدایی شوند.
پیام مسموم و تست DLQ (Poison message) حیاتی
به زبان ساده: عمداً آشغال بفرستید و ببینید همراه شواهد پارک میشود و اگر پارک شکست خورد مبدأ تأیید نمیشود.
بدفهمی رایج: «تست DLQ یعنی بررسی وجود DLQ.» بخش پرخطر انتقال است: ack پیش از park پیام را گم میکند.
تعریف: پیام مسموم (Poison message) تحت consumer فعلی هر بار شکست میخورد. تست DLQ دستهبندی، پوشش شکست (علت، تعداد تلاش، ID اصلی) و ترتیب settlement را میسنجد. طراحی در Dead-letter queue است.
1 Publish invalid JSON {nope
2 Process -> undecodable -> park(reason=undecodable)
3 DLQ.Publish fails (broker down) -> Process returns error, NO ack
4 Retry -> DLQ.Publish succeeds -> exactly one parked recordسناریوهای واقعی: نسخهٔ schema پشتیبانینشده پس از deploy بد؛ فیلد الزامی گمشده؛ کد ارزی که سرویس صورتحساب نمیشناسد؛ بودجهٔ تلاش که وابستگی ناپایدار آن را تمام کرده.
| ورودی | مسیر مورد انتظار |
|---|---|
| بایتهای غیرقابلرمزگشایی | فوراً با علت undecodable پارک شود |
version پشتیبانینشده | با نسخه در علت پارک شود |
| خطای کسبوکاری دائمی | پس از یک تلاش پارک شود |
| خطای گذرا و تمامشدن بودجه | با attempts-exhausted و شمار تلاش پارک شود |
| خطای گذرا که برطرف میشود | Applied، چیزی پارک نشود |
روش استفاده: موردها را جدولی (Table-driven) کنید، یک ردیف برای هر دستهٔ ورودی، تا افزودن حالت شکست یک خط باشد.
Contract test: Pact، AsyncAPI، schema registry مهم
به زبان ساده: بنویسید مصرفکننده از پیام چه میخواهد و build تولیدکننده را وقتی آن را نمیدهد شکست دهید.
بدفهمی رایج: «اگر هر دو سرویس تست دارند، contract تست شده است.» هر طرف میتواند با فرضهای خودش سبز باشد و با دیگری ناسازگار.
تعریف: قرارداد مصرفکنندهمحور (Consumer-driven contract) حداقل پیام مورد انتظار را ثبت میکند. Message pact (نسخهٔ ۳ مشخصهٔ Pact قالب پیام را آورد) در سمت مصرفکننده با دادن نمونه به handler واقعی و در سمت تولیدکننده با اجرای کد واقعی تولید و مقایسه راستیآزمایی میشود. AsyncAPI کانالها، عملیات و payload پیامها را در یک سند توصیف میکند. Schema registry هنگام ثبت، حالتهای schema registry compatibility را اعمال میکند: در Confluent Schema Registry «BACKWARD compatibility means that consumers using the new schema can read data produced with the last schema» و پیشفرض BACKWARD است. قواعد و مسیر مهاجرت در طراحی پیام و تکامل schema است.
1 Consumer test -> handler reads example {id, data.order_id, data.currency}
2 Pact written -> minimal expected message (only fields the consumer uses)
3 Provider build -> real producer code builds the message; verify against the pact
4 Producer drops "currency" -> verification fails; deploy gate stays redسناریوهای واقعی: تولیدکننده total را به total_minor تغییر نام میدهد؛ فیلد اختیاری تازه ظاهر میشود (نباید consumer را بشکند)؛ enum مقدار جدید میگیرد؛ تیمی میخواهد پیش از merge با subject در registry بسنجد.
| ابزار | چه چیزی را میسنجد | کجا اجرا میشود |
|---|---|---|
| Pact message pact | انتظار حداقلی مصرفکننده در برابر خروجی تولیدکننده | تست واحد مصرفکننده و تولیدکننده |
| سند AsyncAPI | توصیف کانال، عملیات و payload | lint در CI؛ تولید کد |
| سازگاری schema registry | schema جدید در برابر نسخههای ثبتشده | POST /compatibility/subjects/(subject)/versions/(version) یا افزونهٔ build |
| Golden file | بایتهای دقیق سریالشده | تست واحد تولیدکننده |
| تست Tolerant reader | فیلد ناشناخته نادیده، فیلد الزامی اجباری | تست واحد مصرفکننده |
روش استفاده: وقتی هر دو تیم را کنترل میکنید و انتظار مختص مصرفکننده میخواهید Pact بزنید؛ وقتی چند consumer یک topic مشترک دارند از registry استفاده کنید. Pact پیادهسازی Go و PHP دارد (جدول پشتیبانی در صفحهٔ مشخصهٔ Pact)؛ پیش از کپیکردن نمونه ببینید هر کدام کدام نسخهٔ مشخصه را پشتیبانی میکند.
Golden file برای envelope مهم
به زبان ساده: یک پیام سریالشدهٔ درست و شناختهشده را در repo نگه دارید و هر build را با آن مقایسه کنید.
بدفهمی رایج: «snapshot test تنبلی است.» golden file قراردادی قابلبازبینی است: هر تغییر در نام یا ترتیب فیلد بهصورت diff دیده میشود.
تعریف: Golden file خروجی مورد انتظار ذخیرهشده است. تست ورودی ثابتی را سریال میکند و بایتها را مقایسه میکند؛ پرچم -update وقتی قالب را عمداً عوض میکنید فایل را بازنویسی میکند. نیمهٔ مصرفکننده همان فایل را رمزگشایی میکند.
1 test serializes fixed envelope -> compares to testdata/order_placed.v1.golden.json
2 field renamed in code -> byte comparison fails, diff visible in review
3 go test ./msg -update -> file rewritten deliberately, committed with the change
4 decoder test reads the same file -> consumers still read v1سناریوهای واقعی: envelope یک header میگیرد؛ ارتقای کتابخانهٔ JSON ترتیب کلیدها یا قالب اعداد اعشاری را عوض میکند؛ شمارهٔ فیلد Protobuf تغییر میکند.
| روش | چرا |
|---|---|
| ID و زمان ثابت در ورودی | بایتهای قطعی |
| برای هر نوع و نسخهٔ پیام یک golden | نسخههای قدیمی خواندنی میمانند |
| بهروزرسانی فقط با پرچم آگاهانه | از رانش بیصدا جلوگیری میکند |
| golden را در تست مصرفکننده رمزگشایی کنید | خوانایی روبهعقب را ثابت میکند |
روش استفاده: golden file را با تست tolerant-reader جفت کنید تا افزودن فیلد اختیاری بگذرد و حذف فیلد الزامی بشکند.
تست یکپارچگی با Testcontainers حیاتی
به زبان ساده: از داخل تست یک broker واقعی را در container موقت بالا بیاورید، استفاده کنید و دور بیندازید.
بدفهمی رایج: «تست یکپارچگی جای تست واحد را میگیرد.» کندتر است، اشکالزداییاش سختتر است و مسیرهای کمی را میپوشاند. برای سیمکشی استفاده کنید: تنظیم اتصال، حالت ack، offset، topology و صداقت fakeهایتان.
تعریف: Testcontainers از کد تست containerها را بالا میآورد و در پایان حذف میکند. testcontainers-go ماژولهایی برای RabbitMQ، Kafka، Redpanda و Redis دارد، هر کدام با تابع Run(ctx, image, options...) و کمکیهایی مانند AmqpURL، Brokers، KafkaSeedBroker و ConnectionString. برای PHP کتابخانهٔ testcontainers جامعهمحور هست؛ بسیاری از تیمهای Laravel بهجای آن compose یا service container در CI را میپسندند.
1 TestMain or test -> rabbitmq.Run(ctx, "rabbitmq:3.12.11-management-alpine")
2 test -> AmqpURL(ctx) -> amqp.Dial; declare a unique exclusive queue
3 test -> publish, then poll the management API for messages_ready == 1
4 cleanup -> testcontainers.CleanupContainer(t, ctr) removes the containerسناریوهای واقعی: راستیآزمایی تنظیم prefetch؛ اثبات اینکه commit دستی با group واقعی کار میکند؛ بررسی اسکریپت Lua روی Redis واقعی؛ تأیید اینکه policy از نوع DLX پیام ردشده را مسیریابی میکند.
| دغدغه | broker واقعی ثابت میکند | fake نمیتواند |
|---|---|---|
| معنای ack، nack، requeue | بله | فقط تقریب میزند |
| offset گروه consumer و rebalance | بله | خیر |
| اسکریپت Lua و فرمانهای stream | بله | miniredis بسیاری را میپوشاند، نه همه را |
| Policy، افزونه، TTL و DLX | بله | خیر |
| احراز هویت، TLS، ACL | بله | خیر |
روش استفاده: تستهای container را پشت build tag یا متغیر محیطی بگذارید، برای هر پکیج یک container بالا بیاورید و به هر تست نام یکتا بدهید. همهٔ نمونههای container در این فصل «خروجی موردانتظار؛ اجرا نشده» هستند: این محیط Docker ندارد.
جداسازی تست و پاکسازی (Test isolation) حیاتی
به زبان ساده: هر تست queue، topic یا stream خودش و consumer group خودش را دارد. جز container چیزی مشترک نیست.
بدفهمی رایج: «بین تستها broker را restart کنید.» کند است. نام یکتا برای هر تست همان جداسازی را در چند میکروثانیه میدهد.
تعریف: جداسازی تست یعنی هیچ تستی پیام، offset یا state consumer تست دیگر را نبیند. از unique topic، یک consumer group per test، XGROUP CREATE ... MKSTREAM در Redis و queueهای exclusive با نام ساختهٔ سرور در RabbitMQ استفاده کنید. پاکسازی (Cleanup) در t.Cleanup (Go) یا tearDown (PHPUnit) اجرا میشود تا تست شکستخورده هم پاک کند.
1 test A: name = unique(t) -> topic.a1f3, group.a1f3
2 test B: name = unique(t) -> topic.9c2e, group.9c2e (parallel with A)
3 both publish and consume -> neither sees the other's records
4 t.Cleanup -> delete topic, group or stream; exclusive queue dies with its connectionسناریوهای واقعی: دو تست orders را به اشتراک میگذارند و هر کدام پیام دیگری را میبیند؛ تست شکستخورده پیام unacked به جا میگذارد و اجرای بعدی را مسموم میکند؛ consumer group ثابت offsetی commit میکند که اجرای دوباره را از رکوردها رد میکند.
| Broker | ابزار جداسازی |
|---|---|
| RabbitMQ | queue exclusive و auto-delete با نام ساختهٔ سرور، یا نام queue یکتا و vhost یکتا |
| Kafka | topic یکتا که با admin ساخته شود، group.id یکتا، offset شروع صریح |
| Redis Streams | کلید stream یکتا، group یکتا که با MKSTREAM ساخته شود |
| Laravel | RefreshDatabase، نام queue با پیشوند، Queue::fake() برای تست واحد |
روش استفاده: یک helper (unique(t, kind)) هر نام را از نام تست بهعلاوهٔ بایت تصادفی میسازد؛ هیچوقت نام topic ثابت در تست ننویسید.
Chaos و تزریق خطا (Failure injection) مهم
به زبان ساده: در تست عمداً چیزها را خراب کنید و ببینید سیستم بدون گمکردن یا تکرار کار بازیابی میشود.
بدفهمی رایج: «chaos فقط برای production است.» بخش ارزان و ارزشمند، تزریق خطا به fakeها و containerها در CI است.
تعریف: تزریق خطا (Failure injection) یک وابستگی را به شکل کنترلشده خراب میکند: publisher که خطا برمیگرداند، bus که پیش از ack میمیرد، proxy که اتصال را میاندازد. آزمایشهای Chaos چنین خطاهایی را روی سیستم در حال اجرا میزنند. Toxiproxy (یک ماژول Testcontainers) میتواند اتصال TCP بین client و broker را قطع یا کند کند.
1 FailNext(ErrBrokerDown) -> DLQ.Publish fails once
2 Process(poison) -> returns error; caller must not Ack
3 Bus.Crash() -> in-flight messages return, Redelivered = true
4 re-run -> message parked once; no double effectسناریوهای واقعی: broker هنگام publish خاموش است؛ worker بعد از پردازش و پیش از ack کشته میشود؛ rebalance در Kafka هنگام پردازش batch یک partition را جابهجا میکند؛ failover در Redis آخرین نوشتن را گم میکند؛ وابستگی کند بودجهٔ retry را تمام میکند.
| خطا | چگونه تزریق میشود | رفتار مورد انتظار |
|---|---|---|
| broker هنگام publish در دسترس نیست | FailNext(err) روی fake | خطا برمیگردد؛ مبدأ ack نمیشود |
| crash پیش از ack | Bus.Crash() | redelivery؛ تکرار را inbox جذب میکند |
| قطع اتصال وسط batch | Toxiproxy در تست یکپارچگی | client دوباره وصل میشود؛ بدون اتلاف |
| rebalance هنگام پردازش | consumer دوم به همان group میپیوندد | تکرار تحمل میشود؛ commit گم نمیشود |
| وابستگی کند | stub که از طریق ساعت جعلی میخوابد | backoff و سپس DLQ |
روش استفاده: برای هر وعدهٔ بازیابی که در سند طراحی میدهید یک تست تزریق خطا بنویسید.
تست سرتاسری و پیام آزمایشی (Test message) تکمیلی
به زبان ساده: یک پیام کاملاً مشخصشده را از مسیر واقعی مستقر رد کنید و ببینید از آن سو بیرون میآید.
بدفهمی رایج: «تست سرتاسری باید همهچیز را بپوشاند.» کند و ناپایدار است؛ برای هر مسیر چند smoke test نگه دارید.
تعریف: پیام آزمایشی (الگوی Test Message در Enterprise Integration Patterns، که نقش اصلی injectorش «to tag messages in order to differentiate 'real' application messages from test messages» است؛ Test Message) پیامی مصنوعی است که برای راستیآزمایی سرتاسری به سیستم زنده تزریق میشود؛ header نشانهگذار به consumerها اجازه میدهد اثر جانبی را رد کنند یا به probe مسیر بدهند. الگوهای مدیریت سیستم را ببینید.
1 Probe publishes {type: test, id: probe-123} to the real topic
2 Consumer sees header x-test=true -> exercises the path, skips billing effect
3 Probe reads the output channel -> asserts probe-123 arrived within the SLOسناریوهای واقعی: smoke test پس از deploy؛ ضربان مصنوعی برای هر مسیر؛ consumer قناری (canary) روی نسخهٔ جدید.
| روش | چرا |
|---|---|
| پیام آزمایشی را با header علامت بزنید | consumerهای واقعی میتوانند اثر جانبی را نادیده بگیرند |
| tenant یا کلید اختصاصی | probe را از aggregateهای واقعی دور نگه میدارد |
| برای نرسیدن probe هشدار بدهید | pipeline گیرکرده را آشکار میکند |
روش استفاده: برای هر مسیر حیاتی یک probe نگه دارید و پس از هر deploy اجرا کنید.
تست ناپایدار و کنترل زمان (Flaky test) حیاتی
به زبان ساده: تست ناپایدار روی یک کد گاهی میگذرد و گاهی میافتد. در تستهای ناهمگام معمولاً علت منتظر ماندن برای چیز اشتباه است.
بدفهمی رایج: «retry یا sleep بلندتر اضافه کنید.» این race را پنهان میکند و هر اجرا را کند.
تعریف: Flaky test نتیجهٔ نامعین دارد. علتها: sleep ثابت، state مشترک بین تستها، وابستگی به ساعت دیواری، فرض ترتیب و محدودیت منابع در CI.
1 Bad: publish; sleep(2s); assert received (slow, still races)
2 Good: publish; poll every 50ms up to 5s until received; fail with the last state
3 Best: drive the fake bus one step at a time; no waiting at allسناریوهای واقعی: تست consumer که ۲ ثانیه میخوابد و روی runner شلوغ CI میافتد؛ دو تست با یک queue؛ تستی که به ترتیب پیمایش map وابسته است.
| علت | راهحل |
|---|---|
sleep ثابت | poll برای یک شرط با مهلت، یا fake |
| نامهای مشترک | نام یکتا برای هر تست |
| زمان واقعی در منطق | ساعت تزریق کنید |
| race در goroutineها | go test -race؛ هر بار یک پیام |
| state باقیمانده در container | یک container برای هر پکیج، نام یکتا، cleanup |
روش استفاده: تستهای مشکوک را با -count=50 و -race اجرا کنید؛ قرنطینه کنید، بعد رفع کنید، هرگز نادیده نگیرید.
کنترل هزینهٔ CI تکمیلی
به زبان ساده: تستهای ارزان را همیشه، containerها را گاهی و chaos را بهندرت اجرا کنید.
بدفهمی رایج: «همهچیز را روی هر commit اجرا کنید.» راهاندازی container بر هزینه و زمان غالب است.
تعریف: کنترل هزینهٔ CI یعنی انتخاب اینکه کدام لایه کِی اجرا شود: واحد و contract روی هر push؛ یکپارچگی با container روی pull request و main؛ chaos و سرتاسری شبانه یا پس از deploy.
1 push -> go test -race ./... and php artisan test --parallel
2 pull request -> + go test -tags integration ./... (needs Docker)
3 main / nightly -> + chaos experiments, soak, schema compatibility against the registry
4 after deploy -> test-message smoke probeسناریوهای واقعی: مجموعهٔ ۱۰ دقیقهای که هر push را مسدود میکند؛ container Kafka که در ۸۰ تست بالا میآید؛ imageای که در هر اجرا دوباره pull میشود.
| اهرم | اثر |
|---|---|
| محافظ build tag یا متغیر محیطی | بدون Docker تستهای container رد میشوند |
| یک container برای هر پکیج | هزینهٔ راهاندازی یک بار |
| tag ثابت image و cache | سریعتر و بازتولیدپذیر |
| Fail fast: واحد پیش از یکپارچگی | با واحد قرمز container بالا نیاید |
| تست موازی با نام یکتا | زمان دیواری کوتاهتر |
روش استفاده: snippet فایل ci/github-actions.yml شکل کار را نشان میدهد؛ آن را «خروجی موردانتظار؛ اجرا نشده» بدانید.
سازوکار و کنترلهای دقیق
کنترلهای تست در Go مهم
| کنترل | معنا |
|---|---|
t.Parallel() | تست را همزمان با تستهای موازی دیگر اجرا میکند؛ state جدا میخواهد |
t.Cleanup(fn) | fn را پس از تست و زیرتستها حتی هنگام شکست اجرا میکند |
t.Setenv(k, v) | متغیر محیطی را برای یک تست میگذارد؛ با t.Parallel() سازگار نیست |
t.TempDir() | پوشهای که خودکار حذف میشود |
go test -race | race دادهٔ مشترک را تشخیص میدهد |
go test -count=1 | cache نتیجه را خاموش میکند؛ برای تست یکپارچگی |
go test -run Name | تستها را با regexp انتخاب میکند |
-tags integration | فایلهای محافظتشده با //go:build integration را شامل میکند |
TestMain(m) | یک container مشترک برای کل پکیج بالا میآورد |
پرچم -update (سفارشی) | golden fileها را عمداً بازنویسی میکند |
هر fake در Laravel چه میکند و چه نمیکند مهم
| Fake | listener یا job اجرا میشود؟ | دامنهٔ ثبت |
|---|---|---|
Queue::fake() | jobها اجرا نمیشوند | pushهای عبوری از facade صف |
Bus::fake() | jobها اجرا نمیشوند | dispatchها، زنجیرهها و batchها |
Event::fake() | listenerها اجرا نمیشوند (بهجز رخدادهای نامبرده) | رخدادهای عبوری از dispatcher |
Notification::fake() | چیزی ارسال نمیشود | notificationها برحسب گیرنده و کلاس |
Queue::fake([A::class]) | فقط A fake میشود؛ jobهای دیگر عادی push میشوند | زیرمجموعه |
Event::fakeFor(fn) | فقط درون closure fake است | با دامنهٔ محدود |
شکستهای رایج تست و معنای آنها مهم
| نشانه | علت | راهحل |
|---|---|---|
BUSYGROUP در Redis هنگام ساخت group | group برای این stream از قبل هست | نام group یکتا، یا BUSYGROUP را تحمل کنید |
NOGROUP در Redis هنگام خواندن | group یا stream نیست | اول XGROUP CREATE ... MKSTREAM |
RESOURCE_LOCKED در RabbitMQ | queue exclusive از اتصال دیگری استفاده شده | روی همان اتصال declare و consume کنید |
| consumer جدید Kafka برای group تازه برای همیشه منتظر میماند | پیشفرض auto.offset.reset در Java برابر latest است | offset شروع را صریح بگذارید |
| تست تنها میگذرد، در مجموعه میافتد | queue، topic یا state سراسری مشترک | نام یکتا؛ fakeها را برای هر تست ریست کنید |
| assertion با management API مسابقه میدهد | آمار broker عقب میماند | poll با مهلت |
Event::fake() factoryهای مدل را میشکند | listenerها خاموشاند | مدلها را پیش از fake بسازید |
راهحل مشکلات کلاسیک
مجموعهٔ کند چون broker میخواهد
| راهحل | چگونه | مزیت | هزینه |
|---|---|---|---|
| Port و fake | interface برای publisher، ساعت، inbox | میلیثانیه، بدون Docker | fake باید صادق نگه داشته شود |
| miniredis برای منطق Redis | سرور Redis جعلی درونفرایندی | بدون Docker؛ stream و XGROUP CREATE را پشتیبانی میکند | همهٔ فرمانها و لبهها نه |
| یک container برای هر پکیج | TestMain یک بار بالا میآورد | هزینهٔ راهاندازی یک بار | Docker در CI لازم است |
| Tag و محافظ env | //go:build integration | اجرای محلی سریع میماند | فراموشی در CI آسان است |
ابتدا تستهای منطق را از broker جدا کنید. بعد مجموعهٔ کوچک و tagدار یکپارچگی بیفزایید که همان کد worker را روی container واقعی اجرا میکند.
consumer که فقط مسیر خوش تست شده
| خلأ | تستی که باید اضافه شود |
|---|---|
| تکرار | همان ID را دو بار پردازش کنید؛ یک اثر را بسنجید |
| جابهجایی ترتیب | توالی ۲ و بعد ۱ را بدهید؛ جدیدترین باید برنده شود |
| ورودی مسموم | بدنهٔ غیرقابلرمزگشایی؛ پارک شدن و ack نشدن مبدأ هنگام شکست park |
| خطای وابستگی | stub شکستخور؛ برنامهٔ backoff و DLQ پس از بودجه |
| crash پیش از ack | Bus.Crash()؛ جذب redelivery |
رانش contract بین تیمها
| راهحل | چگونه | مزیت | هزینه |
|---|---|---|---|
| Golden file | تست واحد تولیدکننده در برابر envelope ذخیرهشده | بدون زیرساخت | فقط سمت تولیدکننده |
| Pact message pact | مصرفکننده pact مینویسد؛ تولیدکننده راستیآزمایی میکند | مختص مصرفکننده، فیلد به فیلد | pact broker یا اشتراک فایل لازم است |
| بررسی سازگاری registry | CI نقطهٔ بررسی سازگاری را صدا میزند | مرکزی و مستقل از زبان | registry لازم و انتخاب حالت سازگاری |
| lint سند AsyncAPI | اعتبارسنجی سند در CI | مستندات درست میمانند | توصیف میکند، رفتار را نمیسنجد |
انتخاب لایهٔ تست
| وضعیت | توصیه | تکنیک تکمیلی | دلیل |
|---|---|---|---|
| منطق جدید retry یا DLQ | تست واحد با fake | ساعت جعلی، جدولی | سریع و قطعی |
| فیلد جدید روی رخداد | Contract بهعلاوهٔ golden file | تست tolerant-reader | از consumerها محافظت میکند |
| تغییر prefetch، حالت ack یا offset | تست یکپارچگی با container | نام یکتا | فقط broker واقعی ثابتش میکند |
| اسکریپت Lua یا فرمان stream | اول miniredis، بعد Redis واقعی | MKSTREAM برای هر تست | ارزان اول، واقعی دوم |
| مسیر یا محیط جدید | smoke test با پیام آزمایشی | header نشانهگذار | سیمکشی مستقر را میسنجد |
| ادعای بازیابی در سند طراحی | تست تزریق خطا | Toxiproxy یا خطای fake | وعده را ثابت میکند |
| رخدادهای فراوان، invariant ترتیب | تست property-based | testing/quick یا rapid | برنامههایی را پیدا میکند که تصورشان نکرده بودید |
| job در Laravel کار صف میکند | Queue::fake() یا Bus::fake() | تست جدا برای handle() | dispatch را از اجرا جدا میکند |
Go
Before
worker که client Redis خودش را میسازد، واقعاً میخوابد و حتی وقتی نوشتن DLQ شکست خورده Ack میزند. هر تست Redis زنده و ۳۰ ثانیه برای هر شکست میخواهد. عمداً تستناپذیر است، نه خراب.
// Package before shows a consumer that cannot be unit-tested: it builds its
// own Redis client, sleeps with time.Sleep and writes the DLQ itself. Every
// test needs a live Redis, and the 30-second backoff makes the suite crawl.
// It compiles; it is bad design, not broken code.
package before
import (
"context"
"time"
"github.com/redis/go-redis/v9"
)
type Worker struct{}
func (Worker) Run(ctx context.Context, addr string) error {
rdb := redis.NewClient(&redis.Options{Addr: addr}) // concrete dependency, hidden inside
for ctx.Err() == nil {
res, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
Group: "billing", Consumer: "w1", Streams: []string{"orders", ">"}, Count: 10, Block: 5 * time.Second,
}).Result()
if err != nil && err != redis.Nil {
return err
}
for _, s := range res {
for _, m := range s.Messages {
if err := process(m.Values); err != nil {
time.Sleep(30 * time.Second) // real wall-clock sleep inside the logic
rdb.XAdd(ctx, &redis.XAddArgs{Stream: "orders.dlq", Values: m.Values})
}
rdb.XAck(ctx, "orders", "billing", m.ID) // ack even if the DLQ write failed
}
}
}
return ctx.Err()
}
func process(map[string]any) error { return nil }After
برنامه به portها وابسته است: نوع پیام، publisher، ساعت. fakeها کوچکاند و کنار portها زندگی میکنند.
// Package msg holds the ports (small interfaces) that application code
// depends on, plus the message envelope. Production adapters (amqp091-go,
// kgo, go-redis) implement these; tests use the in-memory fakes in fakes.go.
package msg
import (
"context"
"encoding/json"
"time"
)
// Message is the transport-neutral envelope the application sees.
type Message struct {
ID string `json:"id"`
Key string `json:"key"`
Type string `json:"type"`
Version int `json:"version"`
Body json.RawMessage `json:"data"`
Headers map[string]string `json:"headers,omitempty"`
// Redelivered is set by the broker (or the fake) on a repeat delivery.
Redelivered bool `json:"-"`
}
// Publisher is the outbound port. Application code never imports a broker client.
type Publisher interface {
Publish(ctx context.Context, topic string, m Message) error
}
// Clock is the time port. Retry and backoff code sleeps through it, so a test
// can run a ten-minute backoff schedule in microseconds.
type Clock interface {
Now() time.Time
Sleep(ctx context.Context, d time.Duration) error
}
// RealClock is the production Clock.
type RealClock struct{}
func (RealClock) Now() time.Time { return time.Now() }
func (RealClock) Sleep(ctx context.Context, d time.Duration) error {
t := time.NewTimer(d)
defer t.Stop()
select {
case <-t.C:
return nil
case <-ctx.Done():
return ctx.Err()
}
}package msg
import (
"context"
"errors"
"sync"
"time"
)
// MemoryPublisher is a fake: a working in-memory implementation with a
// shortcut that makes it unsuitable for production. It records every publish.
type MemoryPublisher struct {
mu sync.Mutex
byTopic map[string][]Message
failures []error // consumed one per Publish call, nil entries mean success
}
func NewMemoryPublisher() *MemoryPublisher {
return &MemoryPublisher{byTopic: map[string][]Message{}}
}
// FailNext queues errors returned by the next len(errs) Publish calls.
// This is failure injection: a broker that is down, a confirm that never came.
func (p *MemoryPublisher) FailNext(errs ...error) {
p.mu.Lock()
defer p.mu.Unlock()
p.failures = append(p.failures, errs...)
}
func (p *MemoryPublisher) Publish(_ context.Context, topic string, m Message) error {
p.mu.Lock()
defer p.mu.Unlock()
if len(p.failures) > 0 {
err := p.failures[0]
p.failures = p.failures[1:]
if err != nil {
return err
}
}
p.byTopic[topic] = append(p.byTopic[topic], m)
return nil
}
// Published returns a copy of the messages recorded for a topic.
func (p *MemoryPublisher) Published(topic string) []Message {
p.mu.Lock()
defer p.mu.Unlock()
return append([]Message(nil), p.byTopic[topic]...)
}
// ErrBrokerDown is the canned error used by failure-injection tests.
var ErrBrokerDown = errors.New("broker unavailable")
// FakeClock never really sleeps: Sleep records the requested duration and
// advances virtual time, so tests are fast and deterministic.
type FakeClock struct {
mu sync.Mutex
now time.Time
sleeps []time.Duration
}
func NewFakeClock(start time.Time) *FakeClock { return &FakeClock{now: start} }
func (c *FakeClock) Now() time.Time {
c.mu.Lock()
defer c.mu.Unlock()
return c.now
}
func (c *FakeClock) Sleep(ctx context.Context, d time.Duration) error {
if err := ctx.Err(); err != nil {
return err
}
c.mu.Lock()
defer c.mu.Unlock()
c.sleeps = append(c.sleeps, d)
c.now = c.now.Add(d)
return nil
}
// Sleeps returns every duration requested so far, in order.
func (c *FakeClock) Sleeps() []time.Duration {
c.mu.Lock()
defer c.mu.Unlock()
return append([]time.Duration(nil), c.sleeps...)
}bus جعلی برای تستها semantics مدل at-least-once میدهد: پیامهای Ackنشده پس از Crash() با Redelivered برمیگردند.
package msg
import (
"context"
"sync"
)
// Bus is an in-memory, single-queue-per-topic broker with at-least-once
// semantics: a delivery that is not acked is redelivered after Crash().
// It exists to test consumer logic, not to model any real broker.
type Bus struct {
mu sync.Mutex
ready map[string][]Message
inflight map[string][]Message
}
func NewBus() *Bus {
return &Bus{ready: map[string][]Message{}, inflight: map[string][]Message{}}
}
func (b *Bus) Publish(_ context.Context, topic string, m Message) error {
b.mu.Lock()
defer b.mu.Unlock()
b.ready[topic] = append(b.ready[topic], m)
return nil
}
// Delivery is one unacknowledged hand-off to a consumer.
type Delivery struct {
Msg Message
bus *Bus
topic string
}
// Poll hands out the next ready message, or false when the topic is empty.
func (b *Bus) Poll(topic string) (Delivery, bool) {
b.mu.Lock()
defer b.mu.Unlock()
q := b.ready[topic]
if len(q) == 0 {
return Delivery{}, false
}
m := q[0]
b.ready[topic] = q[1:]
b.inflight[topic] = append(b.inflight[topic], m)
return Delivery{Msg: m, bus: b, topic: topic}, true
}
// Ack settles the delivery; the message will not come back.
func (d Delivery) Ack() {
d.bus.mu.Lock()
defer d.bus.mu.Unlock()
in := d.bus.inflight[d.topic]
for i, m := range in {
if m.ID == d.Msg.ID {
d.bus.inflight[d.topic] = append(in[:i:i], in[i+1:]...)
return
}
}
}
// Crash simulates the consumer dying before it acked: every in-flight message
// returns to the front of the queue, flagged Redelivered.
func (b *Bus) Crash() {
b.mu.Lock()
defer b.mu.Unlock()
for topic, in := range b.inflight {
back := make([]Message, 0, len(in)+len(b.ready[topic]))
for _, m := range in {
m.Redelivered = true
back = append(back, m)
}
b.ready[topic] = append(back, b.ready[topic]...)
b.inflight[topic] = nil
}
}
// Depth reports ready and in-flight counts, the numbers a management API shows.
func (b *Bus) Depth(topic string) (ready, inflight int) {
b.mu.Lock()
defer b.mu.Unlock()
return len(b.ready[topic]), len(b.inflight[topic])
}consumer تحت تست inbox برای dedup، state نسخهدار، retry محدود از طریق ساعت و DLQ دارد که اگر parking شکست خورد هرگز اجازهٔ ack نمیدهد.
// Package orders is the system under test: a consumer with a dedup inbox,
// bounded retry with backoff, version-checked state updates and a DLQ.
// It depends only on the ports in package msg.
package orders
import (
"context"
"encoding/json"
"errors"
"fmt"
"sync"
"time"
"academy/testing-messaging/msg"
)
// Permanent marks an error that no retry can fix (a poison message).
type Permanent struct{ Err error }
func (p Permanent) Error() string { return "permanent: " + p.Err.Error() }
func (p Permanent) Unwrap() error { return p.Err }
// Outcome says what the consumer did, so tests can assert on it directly.
type Outcome string
const (
Applied Outcome = "applied"
Duplicate Outcome = "duplicate"
Stale Outcome = "stale"
Parked Outcome = "parked"
)
const DLQTopic = "orders.billing.dlq"
type orderEvent struct {
OrderID string `json:"order_id"`
Status string `json:"status"`
}
// Projection is the read model the consumer maintains: latest status per order.
type Projection struct {
mu sync.Mutex
status map[string]string
version map[string]int
seen map[string]bool
effects int
}
func NewProjection() *Projection {
return &Projection{status: map[string]string{}, version: map[string]int{}, seen: map[string]bool{}}
}
func (p *Projection) Status(order string) string {
p.mu.Lock()
defer p.mu.Unlock()
return p.status[order]
}
func (p *Projection) Effects() int { p.mu.Lock(); defer p.mu.Unlock(); return p.effects }
// Consumer processes one message at a time. Ack is the caller's job and must
// happen only after Process returns a nil error.
type Consumer struct {
Proj *Projection
DLQ msg.Publisher
Clock msg.Clock
MaxAttempts int
BaseBackoff time.Duration
// Handle is the business effect; tests replace it to inject failures.
Handle func(ctx context.Context, ev orderEvent) error
}
func (c *Consumer) Process(ctx context.Context, m msg.Message) (Outcome, error) {
var ev orderEvent
if err := json.Unmarshal(m.Body, &ev); err != nil || ev.OrderID == "" {
return c.park(ctx, m, "undecodable", 0)
}
if m.Version != 1 {
return c.park(ctx, m, fmt.Sprintf("unsupported-version-%d", m.Version), 0)
}
if c.seen(m.ID) {
return Duplicate, nil
}
var last error
for attempt := 1; attempt <= c.MaxAttempts; attempt++ {
last = c.Handle(ctx, ev)
if last == nil {
return c.commit(m, ev), nil
}
var perm Permanent
if errors.As(last, &perm) {
return c.park(ctx, m, "permanent", attempt)
}
if attempt < c.MaxAttempts {
backoff := c.BaseBackoff << (attempt - 1)
if err := c.Clock.Sleep(ctx, backoff); err != nil {
return "", err
}
}
}
return c.park(ctx, m, "attempts-exhausted", c.MaxAttempts)
}
func (c *Consumer) seen(id string) bool {
c.Proj.mu.Lock()
defer c.Proj.mu.Unlock()
return c.Proj.seen[id]
}
// commit marks the message as seen and applies it only if it is newer than
// what the projection already holds (last-writer-wins by message sequence).
func (c *Consumer) commit(m msg.Message, ev orderEvent) Outcome {
p := c.Proj
p.mu.Lock()
defer p.mu.Unlock()
p.seen[m.ID] = true
seq := sequence(m)
if seq <= p.version[ev.OrderID] {
return Stale
}
p.version[ev.OrderID] = seq
p.status[ev.OrderID] = ev.Status
p.effects++
return Applied
}
func sequence(m msg.Message) int {
var n int
fmt.Sscanf(m.Headers["sequence"], "%d", &n)
return n
}
// park writes the failure envelope to the DLQ. If that write fails the error
// is returned and the caller must NOT ack: the source stays recoverable.
func (c *Consumer) park(ctx context.Context, m msg.Message, reason string, attempts int) (Outcome, error) {
dead := m
dead.Headers = map[string]string{
"x-reason": reason,
"x-attempts": fmt.Sprint(attempts),
"x-original-id": m.ID,
"x-consumer": "billing",
}
if err := c.DLQ.Publish(ctx, DLQTopic, dead); err != nil {
return "", fmt.Errorf("park %s: %w", m.ID, err)
}
return Parked, nil
}تستهای جدولی هر دستهٔ شکست را یک بار میپوشانند؛ تستهای جدا backoff روی ساعت جعلی، تکرار، تحویل خارج از ترتیب، park شکستخورده و crash پیش از ack را پوشش میدهند.
package orders
import (
"context"
"encoding/json"
"fmt"
"testing"
"time"
"academy/testing-messaging/msg"
)
var t0 = time.Date(2026, 1, 15, 9, 0, 0, 0, time.UTC)
// newConsumer builds a consumer wired to fakes. Every test gets its own
// projection, publisher and clock, so tests share no state and can run in parallel.
func newConsumer(t *testing.T) (*Consumer, *msg.MemoryPublisher, *msg.FakeClock) {
t.Helper()
pub := msg.NewMemoryPublisher()
clk := msg.NewFakeClock(t0)
c := &Consumer{
Proj: NewProjection(),
DLQ: pub,
Clock: clk,
MaxAttempts: 4,
BaseBackoff: time.Second,
Handle: func(context.Context, orderEvent) error { return nil },
}
return c, pub, clk
}
func order(id string, seq int, status string) msg.Message {
body, _ := json.Marshal(orderEvent{OrderID: "o-1", Status: status})
return msg.Message{
ID: id, Key: "o-1", Type: "order.status_changed", Version: 1,
Body: body, Headers: map[string]string{"sequence": fmt.Sprint(seq)},
}
}package orders
import (
"context"
"errors"
"reflect"
"testing"
"time"
"academy/testing-messaging/msg"
)
// Table-driven: one row per failure class, one assertion shape.
func TestProcessClassifiesFailures(t *testing.T) {
transient := errors.New("db timeout")
cases := []struct {
name string
msg msg.Message
handle func(context.Context, orderEvent) error
wantOut Outcome
wantReason string
wantSleeps []time.Duration
}{
{"success", order("m1", 1, "paid"), nil, Applied, "", nil},
{"undecodable body", msg.Message{ID: "m2", Version: 1, Body: []byte("{nope")}, nil, Parked, "undecodable", nil},
{"unsupported version", func() msg.Message { m := order("m3", 1, "paid"); m.Version = 9; return m }(), nil, Parked, "unsupported-version-9", nil},
{"permanent business error", order("m4", 1, "paid"),
func(context.Context, orderEvent) error { return Permanent{errors.New("unknown currency")} },
Parked, "permanent", nil},
{"transient forever exhausts budget", order("m5", 1, "paid"),
func(context.Context, orderEvent) error { return transient },
Parked, "attempts-exhausted", []time.Duration{time.Second, 2 * time.Second, 4 * time.Second}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
c, dlq, clk := newConsumer(t)
if tc.handle != nil {
c.Handle = tc.handle
}
out, err := c.Process(context.Background(), tc.msg)
if err != nil {
t.Fatalf("Process: %v", err)
}
if out != tc.wantOut {
t.Fatalf("outcome = %s, want %s", out, tc.wantOut)
}
parked := dlq.Published(DLQTopic)
if tc.wantReason == "" && len(parked) != 0 {
t.Fatalf("unexpected DLQ traffic: %v", parked)
}
if tc.wantReason != "" {
if len(parked) != 1 || parked[0].Headers["x-reason"] != tc.wantReason {
t.Fatalf("DLQ = %+v, want one record with reason %q", parked, tc.wantReason)
}
if parked[0].Headers["x-original-id"] != tc.msg.ID {
t.Fatalf("parked record lost its source identity")
}
}
if got := clk.Sleeps(); !reflect.DeepEqual(got, tc.wantSleeps) && !(len(got) == 0 && len(tc.wantSleeps) == 0) {
t.Fatalf("backoff schedule = %v, want %v", got, tc.wantSleeps)
}
})
}
}
// A fake clock turns "waits 1s, 2s, then succeeds" into an instant assertion.
func TestTransientFailureRecoversAfterBackoff(t *testing.T) {
c, dlq, clk := newConsumer(t)
calls := 0
c.Handle = func(context.Context, orderEvent) error {
calls++
if calls < 3 {
return errors.New("503 from payment gateway")
}
return nil
}
out, err := c.Process(context.Background(), order("m1", 1, "paid"))
if err != nil || out != Applied {
t.Fatalf("out=%s err=%v", out, err)
}
if want := []time.Duration{time.Second, 2 * time.Second}; !reflect.DeepEqual(clk.Sleeps(), want) {
t.Fatalf("sleeps = %v, want %v", clk.Sleeps(), want)
}
if got := clk.Now().Sub(t0); got != 3*time.Second {
t.Fatalf("virtual elapsed = %v, want 3s", got)
}
if len(dlq.Published(DLQTopic)) != 0 {
t.Fatal("a recovered message must not be parked")
}
}
// Duplicate delivery: the same message ID twice yields one business effect.
func TestDuplicateDeliveryHasOneEffect(t *testing.T) {
c, _, _ := newConsumer(t)
m := order("m1", 1, "paid")
first, _ := c.Process(context.Background(), m)
second, _ := c.Process(context.Background(), m)
if first != Applied || second != Duplicate {
t.Fatalf("outcomes = %s, %s", first, second)
}
if c.Proj.Effects() != 1 {
t.Fatalf("effects = %d, want 1", c.Proj.Effects())
}
}
// Out-of-order delivery: sequence 2 arrives before sequence 1.
func TestOutOfOrderDeliveryKeepsNewestState(t *testing.T) {
c, _, _ := newConsumer(t)
ctx := context.Background()
c.Process(ctx, order("m2", 2, "shipped"))
out, _ := c.Process(ctx, order("m1", 1, "paid"))
if out != Stale {
t.Fatalf("late older event outcome = %s, want stale", out)
}
if got := c.Proj.Status("o-1"); got != "shipped" {
t.Fatalf("status = %q, want shipped", got)
}
}
// Chaos: the DLQ publish fails. Process must return an error so the caller
// does not ack; the message stays recoverable and the retry succeeds.
func TestParkFailureIsReturnedAndNotAcked(t *testing.T) {
c, dlq, _ := newConsumer(t)
bad := msg.Message{ID: "poison", Version: 1, Body: []byte("{nope")}
dlq.FailNext(msg.ErrBrokerDown)
if _, err := c.Process(context.Background(), bad); !errors.Is(err, msg.ErrBrokerDown) {
t.Fatalf("err = %v, want broker down", err)
}
if out, err := c.Process(context.Background(), bad); err != nil || out != Parked {
t.Fatalf("second attempt out=%s err=%v", out, err)
}
if n := len(dlq.Published(DLQTopic)); n != 1 {
t.Fatalf("DLQ records = %d, want exactly 1", n)
}
}
// Chaos: crash after processing but before the ack. The broker redelivers;
// the inbox absorbs the duplicate.
func TestCrashBeforeAckRedeliversWithoutDoubleEffect(t *testing.T) {
c, _, _ := newConsumer(t)
bus := msg.NewBus()
ctx := context.Background()
bus.Publish(ctx, "orders", order("m1", 1, "paid"))
d, _ := bus.Poll("orders")
if out, _ := c.Process(ctx, d.Msg); out != Applied {
t.Fatalf("first outcome = %s", out)
}
bus.Crash() // the worker dies before d.Ack()
d, ok := bus.Poll("orders")
if !ok || !d.Msg.Redelivered {
t.Fatalf("expected a redelivered message, got ok=%v redelivered=%v", ok, d.Msg.Redelivered)
}
if out, _ := c.Process(ctx, d.Msg); out != Duplicate {
t.Fatalf("redelivery outcome = %s, want duplicate", out)
}
d.Ack()
if ready, inflight := bus.Depth("orders"); ready != 0 || inflight != 0 {
t.Fatalf("depth = %d/%d, want 0/0", ready, inflight)
}
if c.Proj.Effects() != 1 {
t.Fatalf("effects = %d, want 1", c.Proj.Effects())
}
}تست property برنامههای دلخواه را بازپخش میکند و همگرایی را میسنجد.
package orders
import (
"context"
"fmt"
"testing"
"testing/quick"
)
// Property: for ANY arrival schedule made of sequences 1..5, with any
// duplicates and any order, the projection ends at the highest sequence seen
// and every distinct message ID is applied or ignored at most once.
func TestProjectionConvergesUnderAnySchedule(t *testing.T) {
statuses := []string{"", "created", "paid", "packed", "shipped", "delivered"}
prop := func(schedule []uint8) bool {
c, _, _ := newConsumer(t)
highest := 0
for _, raw := range schedule {
seq := int(raw%5) + 1
if seq > highest {
highest = seq
}
// The message ID is derived from the sequence, so a repeated
// sequence is a duplicate delivery of the same message.
m := order(fmt.Sprintf("m%d", seq), seq, statuses[seq])
if _, err := c.Process(context.Background(), m); err != nil {
return false
}
}
if highest == 0 {
return c.Proj.Status("o-1") == ""
}
return c.Proj.Status("o-1") == statuses[highest] && c.Proj.Effects() <= 5
}
if err := quick.Check(prop, &quick.Config{MaxCount: 500}); err != nil {
t.Fatal(err)
}
}تست golden-file بایتهای envelope را ثابت میکند؛ تست رمزگشا همان فایل را میخواند.
package msg
import (
"bytes"
"encoding/json"
"flag"
"os"
"path/filepath"
"testing"
)
var update = flag.Bool("update", false, "rewrite golden files")
// Golden-file test: the serialized envelope is a public contract. Any change
// to field names, order or defaults shows up as a reviewable diff of
// testdata/*.golden.json instead of a silent break in a consumer.
func TestEnvelopeGolden(t *testing.T) {
m := Message{
ID: "0194f2c0-7d2e-7b3a-9a41-2f6f0c1d8e55",
Key: "order-1042",
Type: "order.placed",
Version: 1,
Body: json.RawMessage(`{"order_id":"order-1042","total_minor":4599,"currency":"USD"}`),
Headers: map[string]string{"correlation-id": "req-7f3a", "sequence": "1"},
}
got, err := json.MarshalIndent(m, "", " ")
if err != nil {
t.Fatal(err)
}
got = append(got, '\n')
path := filepath.Join("testdata", "order_placed.v1.golden.json")
if *update {
if err := os.WriteFile(path, got, 0o644); err != nil {
t.Fatal(err)
}
}
want, err := os.ReadFile(path)
if err != nil {
t.Fatalf("missing golden file (run: go test ./msg -update): %v", err)
}
if !bytes.Equal(got, want) {
t.Fatalf("envelope changed.\n--- got ---\n%s--- want ---\n%s", got, want)
}
}
// A decoder written for v1 must keep reading the golden bytes: the consumer
// half of the same contract.
func TestGoldenStillDecodes(t *testing.T) {
raw, err := os.ReadFile(filepath.Join("testdata", "order_placed.v1.golden.json"))
if err != nil {
t.Fatal(err)
}
var m Message
if err := json.Unmarshal(raw, &m); err != nil {
t.Fatal(err)
}
if m.Type != "order.placed" || m.Version != 1 || m.Key != "order-1042" {
t.Fatalf("decoded %+v", m)
}
}{
"id": "0194f2c0-7d2e-7b3a-9a41-2f6f0c1d8e55",
"key": "order-1042",
"type": "order.placed",
"version": 1,
"data": {
"order_id": "order-1042",
"total_minor": 4599,
"currency": "USD"
},
"headers": {
"correlation-id": "req-7f3a",
"sequence": "1"
}
}نگاه Go
سبک Go یک interface کوچک است که مصرفکننده تعریف میکند، بهعلاوهٔ تستها در همان پکیج. go test -race -count=1 ./... را اجرا کنید؛ هیچکدام از این تستها شبکه نمیخواهند. t.Parallel() را فقط جایی بزنید که تستها state مشترک ندارند: اینجا هر تست consumer، publisher و ساعت خودش را میسازد. پکیج testing/synctest در Go 1.25 میتواند برای کدی که مستقیم از time استفاده میکند جای ساعت تزریقی را بگیرد؛ این module روی go 1.24 و Clock صریح مانده تا تستها روی هر دو اجرا شوند.
Laravel
Before
کد Laravel که dispatch، رخداد و notification را درهم میآمیزد وقتی تستپذیر است که هر فراخوانی از facadeای عبور کند که fake دارد. سرویس زیر یک رخداد، زنجیرهٔ چهارجobی و یک notification را dispatch میکند؛ وقتی fakeها فعالاند broker در کار نیست.
<?php
namespace App\Services;
use App\Events\OrderPlaced;
use App\Jobs\ProcessPayment;
use App\Jobs\RecordShipment;
use App\Jobs\ShipOrder;
use App\Jobs\UpdateInventory;
use App\Models\Order;
use App\Notifications\OrderReceived;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Notification;
// System under test for the fakes: one event, one chain, one notification.
class PlaceOrder
{
public function __invoke(Order $order): void
{
event(new OrderPlaced($order));
Bus::chain([
new ProcessPayment($order->id),
new ShipOrder($order->id),
new RecordShipment($order->id),
new UpdateInventory($order->id),
])->onQueue('orders')->dispatch();
Notification::send($order->customer, new OrderReceived($order));
}
}After
تستهای feature صف، bus، رخداد یا notification را fake میکنند، سرویس را اجرا میکنند و آنچه ثبت شد را میسنجند. مدلها را پیش از Event::fake() بسازید.
<?php
namespace Tests\Feature;
use App\Events\OrderPlaced;
use App\Jobs\ProcessPayment;
use App\Jobs\RecordShipment;
use App\Jobs\ShipOrder;
use App\Jobs\UpdateInventory;
use App\Listeners\SendOrderReceipt;
use App\Models\Order;
use App\Notifications\OrderReceived;
use App\Services\PlaceOrder;
use Illuminate\Events\CallQueuedListener;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Queue;
use Tests\TestCase;
class PlaceOrderTest extends TestCase
{
use RefreshDatabase;
public function test_queue_fake_records_the_first_job_and_its_chain(): void
{
// Create models BEFORE faking events: Event::fake() stops model listeners.
$order = Order::factory()->create();
Queue::fake();
app(PlaceOrder::class)($order);
Queue::assertPushedOn('orders', ProcessPayment::class);
Queue::assertPushedOnce(ProcessPayment::class);
Queue::assertPushedWithChain(ProcessPayment::class, [
ShipOrder::class,
RecordShipment::class,
UpdateInventory::class,
]);
// Chained successors are not pushed until the first job succeeds.
Queue::assertNotPushed(ShipOrder::class);
Queue::assertCount(1);
}
public function test_bus_fake_asserts_the_whole_chain_shape(): void
{
$order = Order::factory()->create();
Bus::fake();
app(PlaceOrder::class)($order);
Bus::assertChained([
ProcessPayment::class,
ShipOrder::class,
RecordShipment::class,
UpdateInventory::class,
]);
Bus::assertDispatched(ProcessPayment::class, ['orderId' => $order->id]);
Bus::assertNothingBatched();
}
public function test_event_fake_records_dispatch_and_skips_listeners(): void
{
$order = Order::factory()->create();
Event::fake([OrderPlaced::class]); // other events (model events) still run
Bus::fake();
app(PlaceOrder::class)($order);
Event::assertDispatched(OrderPlaced::class, fn (OrderPlaced $e) => $e->order->is($order));
Event::assertDispatchedOnce(OrderPlaced::class);
}
public function test_event_fake_except_lets_one_event_reach_its_listeners(): void
{
$order = Order::factory()->create();
Event::fake()->except([OrderPlaced::class]); // fake every event except OrderPlaced
Queue::fake();
app(PlaceOrder::class)($order);
// OrderPlaced ran for real, so its queued listener became a queued job.
Queue::assertPushed(
CallQueuedListener::class,
fn (CallQueuedListener $job) => $job->class === SendOrderReceipt::class,
);
}
public function test_notification_fake_checks_recipient_and_class(): void
{
$order = Order::factory()->create();
Notification::fake();
Bus::fake();
app(PlaceOrder::class)($order);
Notification::assertSentTo($order->customer, OrderReceived::class);
Notification::assertCount(1);
}
public function test_nothing_is_pushed_when_the_order_is_invalid(): void
{
Queue::fake();
Bus::fake();
$this->postJson('/orders', [])->assertUnprocessable();
Queue::assertNothingPushed();
Bus::assertNothingDispatched();
}
}batchها از Bus::assertBatched، assertBatchCount و withFakeBatch استفاده میکنند.
<?php
namespace App\Jobs;
use Illuminate\Bus\Batchable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
class ProcessCsvRow implements ShouldQueue
{
use Batchable, Queueable;
public function __construct(public int $row, public bool $corrupt = false) {}
public function handle(): void
{
if ($this->batch()?->cancelled()) {
return; // a sibling already cancelled the batch
}
if ($this->corrupt) {
$this->batch()?->cancel();
}
}
}<?php
namespace Tests\Feature;
use App\Jobs\ProcessCsvRow;
use Illuminate\Bus\PendingBatch;
use Illuminate\Support\Facades\Bus;
use Illuminate\Http\UploadedFile;
use Tests\TestCase;
class BatchTest extends TestCase
{
public function test_import_dispatches_one_named_batch_of_three_rows(): void
{
Bus::fake();
$this->post('/imports', ['file' => UploadedFile::fake()->createWithContent('rows.csv', "a\nb\nc\n")])
->assertAccepted();
Bus::assertBatched(function (PendingBatch $batch) {
return $batch->name === 'Import CSV' && $batch->jobs->count() === 3;
});
Bus::assertBatched(fn (PendingBatch $batch) => $batch->hasJobs([
fn (ProcessCsvRow $job) => $job->row === 1,
fn (ProcessCsvRow $job) => $job->row === 2,
fn (ProcessCsvRow $job) => $job->row === 3,
]));
Bus::assertBatchCount(1);
}
public function test_job_cancels_its_batch_on_a_corrupt_row(): void
{
// withFakeBatch gives the job a fake batch it can cancel, no database needed.
[$job, $batch] = (new ProcessCsvRow(row: 99, corrupt: true))->withFakeBatch();
$job->handle();
$this->assertTrue($batch->cancelled());
}
}یک job و middlewareاش مستقیم تست میشوند؛ withFakeQueueInteractions() تصمیمهای release، delete و fail را میسنجد؛ failed() دستی صدا زده میشود.
<?php
namespace App\Jobs;
use App\Exceptions\CardDeclined;
use App\Jobs\Middleware\SkipIfAlreadyProcessed;
use App\Services\PaymentGateway;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Support\Facades\Log;
use Throwable;
#[Tries(3)]
class ProcessPayment implements ShouldQueue
{
use Queueable;
public function __construct(public int $orderId) {}
/** @return array<int, object> */
public function middleware(): array
{
return [new SkipIfAlreadyProcessed("payment:{$this->orderId}")];
}
public function handle(PaymentGateway $gateway): void
{
try {
$gateway->charge($this->orderId, idempotencyKey: "order-{$this->orderId}");
} catch (CardDeclined $e) {
$this->fail($e); // retrying cannot help
}
}
public function failed(?Throwable $exception): void
{
Log::warning('payment parked', ['order_id' => $this->orderId, 'exception' => $exception ? $exception::class : null]);
}
}<?php
namespace App\Jobs\Middleware;
use Closure;
use Illuminate\Support\Facades\Cache;
// Job middleware: wraps handle(). Pure PHP, so a test can call it with a closure.
class SkipIfAlreadyProcessed
{
public function __construct(private string $key) {}
public function handle(object $job, Closure $next): void
{
if (Cache::has("done:{$this->key}")) {
$job->delete(); // duplicate delivery: acknowledge and do nothing
return;
}
$next($job);
Cache::put("done:{$this->key}", true, now()->addDay());
}
}<?php
namespace Tests\Unit;
use App\Exceptions\CardDeclined;
use App\Jobs\Middleware\SkipIfAlreadyProcessed;
use App\Jobs\ProcessPayment;
use App\Services\PaymentGateway;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Mockery;
use Tests\TestCase;
class ProcessPaymentTest extends TestCase
{
public function test_handle_charges_with_a_stable_idempotency_key(): void
{
$gateway = Mockery::mock(PaymentGateway::class);
$gateway->shouldReceive('charge')->once()->with(42, idempotencyKey: 'order-42');
(new ProcessPayment(42))->handle($gateway);
}
public function test_declined_card_fails_the_job_without_retrying(): void
{
$gateway = Mockery::mock(PaymentGateway::class);
$gateway->shouldReceive('charge')->andThrow(new CardDeclined());
$job = (new ProcessPayment(42))->withFakeQueueInteractions();
$job->handle($gateway);
$job->assertFailedWith(CardDeclined::class);
$job->assertNotReleased();
}
public function test_failed_hook_logs_the_class_not_the_payload(): void
{
Log::spy();
(new ProcessPayment(42))->failed(new CardDeclined());
Log::shouldHaveReceived('warning')->once();
}
public function test_middleware_skips_a_duplicate_delivery(): void
{
Cache::put('done:payment:42', true);
$job = (new ProcessPayment(42))->withFakeQueueInteractions();
$ran = false;
(new SkipIfAlreadyProcessed('payment:42'))->handle($job, function () use (&$ran) {
$ran = true;
});
$this->assertFalse($ran);
$job->assertDeleted();
}
public function test_middleware_marks_success_so_the_next_delivery_is_skipped(): void
{
Cache::forget('done:payment:7');
$job = (new ProcessPayment(7))->withFakeQueueInteractions();
(new SkipIfAlreadyProcessed('payment:7'))->handle($job, fn () => null);
$this->assertTrue(Cache::has('done:payment:7'));
}
}contract test برای envelope یکپارچهسازی: خروجی تولیدکننده با golden file میخواند و tolerant reader فیلدهای تازه را میپذیرد اما نبود فیلد الزامی را رد میکند.
<?php
namespace App\Messaging;
use DateTimeImmutable;
use DateTimeInterface;
use JsonException;
// The integration envelope other services consume. Its JSON shape is a public contract.
final class OrderPlacedEnvelope
{
public const TYPE = 'order.placed';
public const VERSION = 1;
public function __construct(
public readonly string $id,
public readonly string $orderId,
public readonly int $totalMinor,
public readonly string $currency,
public readonly DateTimeImmutable $occurredAt,
) {}
/** @return array<string, mixed> */
public function toArray(): array
{
return [
'id' => $this->id,
'type' => self::TYPE,
'version' => self::VERSION,
'occurred_at' => $this->occurredAt->format(DateTimeInterface::ATOM),
'data' => [
'order_id' => $this->orderId,
'total_minor' => $this->totalMinor,
'currency' => $this->currency,
],
];
}
public function toJson(): string
{
return json_encode($this->toArray(), JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
}
/** Tolerant reader: ignores unknown fields, rejects missing required ones. */
public static function fromJson(string $json): self
{
try {
$d = json_decode($json, true, flags: JSON_THROW_ON_ERROR);
return new self(
$d['id'],
$d['data']['order_id'],
(int) $d['data']['total_minor'],
$d['data']['currency'],
new DateTimeImmutable($d['occurred_at']),
);
} catch (JsonException|\Throwable $e) {
throw new \InvalidArgumentException('undecodable order.placed envelope', 0, $e);
}
}
}<?php
namespace Tests\Unit;
use App\Messaging\OrderPlacedEnvelope;
use DateTimeImmutable;
use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
// Plain PHPUnit: a contract test needs no framework boot and no broker.
class OrderPlacedContractTest extends TestCase
{
private function envelope(): OrderPlacedEnvelope
{
return new OrderPlacedEnvelope(
'0194f2c0-7d2e-7b3a-9a41-2f6f0c1d8e55',
'order-1042',
4599,
'USD',
new DateTimeImmutable('2026-01-15T09:00:00+00:00'),
);
}
public function test_producer_output_matches_the_golden_file(): void
{
$golden = file_get_contents(__DIR__.'/golden/order_placed.v1.json');
$this->assertSame(trim($golden), $this->envelope()->toJson());
}
public function test_consumer_reads_the_golden_file_and_ignores_unknown_fields(): void
{
$withExtra = json_decode(file_get_contents(__DIR__.'/golden/order_placed.v1.json'), true);
$withExtra['data']['coupon'] = 'SPRING'; // a newer producer added a field
$read = OrderPlacedEnvelope::fromJson(json_encode($withExtra));
$this->assertSame('order-1042', $read->orderId);
$this->assertSame(4599, $read->totalMinor);
}
public function test_consumer_rejects_a_message_missing_a_required_field(): void
{
$this->expectException(InvalidArgumentException::class);
OrderPlacedEnvelope::fromJson('{"id":"x","type":"order.placed","version":1}');
}
public function test_required_fields_are_exactly_the_published_contract(): void
{
$keys = array_keys($this->envelope()->toArray());
sort($keys);
// Removing or renaming any of these breaks every consumer.
$this->assertSame(['data', 'id', 'occurred_at', 'type', 'version'], $keys);
}
}{
"id": "0194f2c0-7d2e-7b3a-9a41-2f6f0c1d8e55",
"type": "order.placed",
"version": 1,
"occurred_at": "2026-01-15T09:00:00+00:00",
"data": {
"order_id": "order-1042",
"total_minor": 4599,
"currency": "USD"
}
}همان assertionها به سبک Pest:
<?php
use App\Jobs\ShipOrder;
use App\Models\Order;
use App\Services\PlaceOrder;
use Illuminate\Support\Facades\Queue;
// The same assertions in Pest style: a closure per test, the fake set up first.
test('only ShipOrder is faked; other jobs are pushed normally', function () {
$order = Order::factory()->create();
Queue::fake([ShipOrder::class]);
app(PlaceOrder::class)($order);
Queue::assertPushedTimes(ShipOrder::class, 1);
});
test('fake everything except ShipOrder', function () {
$order = Order::factory()->create();
Queue::fake()->except([ShipOrder::class]);
app(PlaceOrder::class)($order);
Queue::assertNotPushed(ShipOrder::class);
});نگاه Laravel
Laravel 13 «database, Amazon SQS, Redis, and Beanstalkd drivers» را مستند میکند؛ RabbitMQ و Kafka به package نیاز دارند، پس تستهایی که از آن packageها استفاده میکنند container یا fake میخواهند. وقتی فقط اهمیت دارد که job push شد از Queue::fake() استفاده کنید و وقتی کار job مهم است خودتان handle() را صدا بزنید. خانوادهٔ Queue::fake() closure یا آرایهٔ مقادیر property مورد انتظار هم میپذیرد؛ مقدارها با تساوی سخت و مدلهای Eloquent با is مقایسه میشوند. Bus::fake() تنها fakeای است که زنجیره و batch را میبیند (assertChained، assertBatched). Queue::assertPushedWithChain و assertPushedWithoutChain در کلاس QueueFake خود framework هستند؛ چون صفحهٔ مستندات Laravel آنها را فهرست نکرده، پیش از اتکا با نسخهٔ نصبشدهتان تطبیق دهید.
برای زمان، travel()، travelTo() و travelBack() مقدار now() را عوض میکنند. برای تست یکپارچگی یا service container در CI اجرا کنید یا یک کتابخانهٔ Testcontainers جامعهمحور PHP به کار ببرید؛ بلوغ و API آن را پیش از پذیرش بررسی کنید. QUEUE_CONNECTION را در phpunit.xml صریح بگذارید تا تست تصادفاً به صف واقعی نرسد. Mockery برای مرزی که نمیشود fake کرد، مثل درگاه پرداخت، ابزار درست است.
| نیاز | ابزار |
|---|---|
| job push شد؟ کجا؟ چند بار؟ | Queue::assertPushed، assertPushedOn، assertPushedTimes |
| زنجیره یا batch dispatch شد؟ | Bus::assertChained، assertBatched، assertBatchCount |
| کد رخداد dispatch کرد؟ | Event::assertDispatched |
| listener صف شد؟ | Queue::assertPushed(CallQueuedListener::class, fn ...) |
| notification ارسال شد؟ | Notification::assertSentTo |
| job چه میکند؟ | نمونه بسازید و handle() را صدا بزنید |
| job release یا fail کرد؟ | assertionهای withFakeQueueInteractions() |
| hook شکست امن لاگ میکند؟ | failed() را با Log::spy() صدا بزنید |
تفاوتهای اجرا در brokerها
RabbitMQ
RabbitMQ ویژگیهای queue دارد که جداسازی را آسان میکند: queue exclusive و auto-delete با نام ساختهٔ سرور همراه اتصالش ناپدید میشود و تست شکستخورده چیزی جا نمیگذارد. مستندات RabbitMQ میگوید استفاده از queue exclusive از اتصال دیگر «will result in a channel-level exception RESOURCE_LOCKED»؛ پس روی یک اتصال declare و consume کنید. management HTTP API مسیر GET /api/queues/{vhost}/{name} را با messages_ready دارد؛ برای سنجش state سمت broker از آن استفاده کنید و poll کنید چون اعداد ممکن است عقب بمانند. ماژول RabbitMQ در Testcontainers Run، AmqpURL() و HttpURL() میدهد. نمونه «خروجی موردانتظار؛ اجرا نشده» است (به Docker نیاز دارد).
//go:build integration
package integration
import (
"context"
"encoding/json"
"fmt"
"net/http"
"testing"
"time"
amqp "github.com/rabbitmq/amqp091-go"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/modules/rabbitmq"
)
// expected, not run: needs a Docker daemon.
func TestRabbitMQExclusiveQueueAndManagementAPI(t *testing.T) {
ctx := context.Background()
ctr, err := rabbitmq.Run(ctx, "rabbitmq:3.12.11-management-alpine",
rabbitmq.WithAdminUsername("admin"), rabbitmq.WithAdminPassword("password"))
testcontainers.CleanupContainer(t, ctr) // terminates the container when the test ends
if err != nil {
t.Fatal(err)
}
url, err := ctr.AmqpURL(ctx)
if err != nil {
t.Fatal(err)
}
conn, err := amqp.Dial(url)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = conn.Close() })
ch, err := conn.Channel()
if err != nil {
t.Fatal(err)
}
// Exclusive + auto-delete: the broker removes the queue when this
// connection closes, so a failed test cannot leave a queue behind.
q, err := ch.QueueDeclare(unique(t, "q"), false, true, true, false, nil)
if err != nil {
t.Fatal(err)
}
if err := ch.PublishWithContext(ctx, "", q.Name, false, false,
amqp.Publishing{MessageId: "m-1", Body: []byte(`{"order_id":"o-1"}`)}); err != nil {
t.Fatal(err)
}
// Assert broker-side state through the management HTTP API. Its numbers
// can lag behind the broker, so poll instead of asserting once.
base, err := ctr.HttpURL(ctx)
if err != nil {
t.Fatal(err)
}
deadline := time.Now().Add(15 * time.Second)
for {
ready, err := messagesReady(ctx, base, "admin", "password", q.Name)
if err == nil && ready == 1 {
break
}
if time.Now().After(deadline) {
t.Fatalf("queue %s: messages_ready=%d err=%v, want 1", q.Name, ready, err)
}
time.Sleep(500 * time.Millisecond)
}
d, ok, err := ch.Get(q.Name, true)
if err != nil || !ok || d.MessageId != "m-1" {
t.Fatalf("Get: ok=%v id=%q err=%v", ok, d.MessageId, err)
}
}
func messagesReady(ctx context.Context, base, user, pass, queue string) (int, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("%s/api/queues/%%2F/%s", base, queue), nil)
if err != nil {
return 0, err
}
req.SetBasicAuth(user, pass)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return 0, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return 0, fmt.Errorf("management API status %d", resp.StatusCode)
}
var body struct {
MessagesReady int `json:"messages_ready"`
}
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
return 0, err
}
return body.MessagesReady, nil
}در Laravel، تستهایی که از vladimir-yuldashev/laravel-queue-rabbitmq استفاده میکنند برای تست واحد صف را fake میکنند و فقط برای چند تستی که به driver واقعی نیاز دارند از service container RabbitMQ بهره میبرند. snippet مربوط به CI service containerها را نشان میدهد.
# Expected, not run. Unit tests need no services; the integration job gets
# real brokers as service containers. Only the integration job pays for them.
name: tests
on: [push, pull_request]
jobs:
unit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with: { go-version: '1.24' }
- run: go test -race -count=1 ./...
working-directory: go
integration:
runs-on: ubuntu-latest
needs: unit # do not start containers if the fast layer is red
if: github.event_name == 'pull_request' || github.ref == 'refs/heads/main'
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with: { go-version: '1.26' }
# Testcontainers starts and removes the containers itself; the runner only needs Docker.
- run: go test -tags integration -count=1 -timeout 10m ./...
working-directory: go/integration
laravel:
runs-on: ubuntu-latest
services:
redis:
image: redis:7
ports: ['6379:6379']
options: >-
--health-cmd "redis-cli ping" --health-interval 5s --health-retries 10
steps:
- uses: actions/checkout@v4
- uses: shivammathur/setup-php@v2
with: { php-version: '8.3' }
- run: composer install --no-interaction --prefer-dist
- run: php artisan test --parallel
env:
QUEUE_CONNECTION: redis
REDIS_HOST: 127.0.0.1Kafka
تستهای Kafka سه انتخاب صریح میخواهند: topic را خودتان بسازید (admin API، نه ساخت خودکار)، به هر تست group.id جدا بدهید و بگویید group تازه از کجا شروع کند. مستندات consumer در Kafka برای auto.offset.reset پیشفرض latest را فهرست میکند، پس group تازه رکوردهای پیش از پیوستنش را رد میکند؛ franz-go مستند میکند که AtStart پیشفرضش است اما تست نباید به آن تکیه کند. ماژول Kafka در Testcontainers (KRaft، confluentinc/confluent-local) تابع Brokers(ctx) و ماژول Redpanda تابع KafkaSeedBroker(ctx) را میدهد. Redpanda سریعتر بالا میآید و پروتکل Kafka را میفهمد؛ رفتارهایی که به آن تکیه دارید، مثل transactionها، را روی brokerی که در production دارید تأیید کنید. تست rebalance یک client دوم را در همان group بالا میآورد در حالی که اولی batch پردازش میکند و بررسی میکند commit گم نشده و تکرار تحمل میشود. نمونه «خروجی موردانتظار؛ اجرا نشده».
//go:build integration
package integration
import (
"context"
"testing"
"time"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/modules/kafka"
"github.com/testcontainers/testcontainers-go/modules/redpanda"
"github.com/twmb/franz-go/pkg/kadm"
"github.com/twmb/franz-go/pkg/kgo"
)
// expected, not run: needs a Docker daemon.
func TestKafkaUniqueTopicAndGroup(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
ctr, err := kafka.Run(ctx, "confluentinc/confluent-local:7.5.0", kafka.WithClusterID("test-cluster"))
testcontainers.CleanupContainer(t, ctr)
if err != nil {
t.Fatal(err)
}
brokers, err := ctr.Brokers(ctx)
if err != nil {
t.Fatal(err)
}
roundTrip(ctx, t, brokers)
}
// Redpanda starts faster than a JVM broker and speaks the Kafka protocol; it
// is a common CI substitute, but confirm behaviours you depend on (for
// example transactions or exact error codes) against the broker you run.
func TestRedpandaUniqueTopicAndGroup(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
ctr, err := redpanda.Run(ctx, "docker.redpanda.com/redpandadata/redpanda:v23.3.3")
testcontainers.CleanupContainer(t, ctr)
if err != nil {
t.Fatal(err)
}
seed, err := ctr.KafkaSeedBroker(ctx)
if err != nil {
t.Fatal(err)
}
roundTrip(ctx, t, []string{seed})
}
func roundTrip(ctx context.Context, t *testing.T, brokers []string) {
t.Helper()
topic, group := unique(t, "topic"), unique(t, "group")
// Create the topic explicitly: no reliance on broker auto-creation, and
// one partition keeps the ordering assertion trivial.
admin, err := kgo.NewClient(kgo.SeedBrokers(brokers...))
if err != nil {
t.Fatal(err)
}
t.Cleanup(admin.Close)
if _, err := kadm.NewClient(admin).CreateTopic(ctx, 1, 1, nil, topic); err != nil {
t.Fatal(err)
}
for _, v := range []string{"a", "b", "c"} {
res := admin.ProduceSync(ctx, &kgo.Record{Topic: topic, Key: []byte("k"), Value: []byte(v)})
if err := res.FirstErr(); err != nil {
t.Fatal(err)
}
}
// A fresh group has no committed offset. State the start position
// explicitly: the Java client defaults to auto.offset.reset=latest and
// would wait forever for records produced before it joined; franz-go
// documents AtStart as its default, but a test should not rely on that.
cl, err := kgo.NewClient(
kgo.SeedBrokers(brokers...),
kgo.ConsumerGroup(group),
kgo.ConsumeTopics(topic),
kgo.ConsumeStartOffset(kgo.NewOffset().AtStart()),
kgo.DisableAutoCommit(),
)
if err != nil {
t.Fatal(err)
}
t.Cleanup(cl.Close)
var got []string
for len(got) < 3 {
fetches := cl.PollFetches(ctx)
if err := fetches.Err0(); err != nil {
t.Fatal(err)
}
fetches.EachRecord(func(r *kgo.Record) { got = append(got, string(r.Value)) })
}
if want := "abc"; got[0]+got[1]+got[2] != want {
t.Fatalf("records = %v, want %q in order", got, want)
}
if err := cl.CommitUncommittedOffsets(ctx); err != nil {
t.Fatal(err)
}
}در Laravel با mateusjunges/laravel-kafka، تست واحد مرز producer یا consumer را fake میکند و مقدار و headerهای پیام را میسنجد؛ تست broker واقعی جایش در CI با container است.
Redis Streams
Redis Streams ارزانترین برای تست است: miniredis سرور Go درونفرایندی است که XADD، XGROUP CREATE، XREADGROUP، XACK، XPENDING، XCLAIM و XAUTOCLAIM را پشتیبانی میکند (README آنها را فهرست میکند؛ XINFO جزئی است)، پس منطق stream در go test ساده و بدون Docker اجرا میشود. group را با XGROUP CREATE key group $ MKSTREAM بسازید؛ MKSTREAM اگر stream نباشد آن را میسازد و BUSYGROUP یعنی group از قبل هست. برای هر تست stream و group یکتا بگذارید. همان کد worker را در یک تست tagدار روی Redis واقعی اجرا کنید تا آنچه fake مدل نمیکند، مثل اسکریپت Lua و replication، گرفته شود. driver صف Redis در Laravel از list و sorted set استفاده میکند، نه stream؛ پس تست stream در Laravel مستقیم با facade Redis نوشته میشود.
// Package streams is a minimal Redis Streams consumer used to show per-test
// isolation: every test creates its own stream and consumer group.
package streams
import (
"context"
"errors"
"strings"
"github.com/redis/go-redis/v9"
)
// EnsureGroup creates the group and the stream if either is missing.
// MKSTREAM makes XGROUP CREATE succeed on a stream that does not exist yet;
// BUSYGROUP means a previous run already created it, which is fine.
func EnsureGroup(ctx context.Context, rdb redis.Cmdable, stream, group string) error {
err := rdb.XGroupCreateMkStream(ctx, stream, group, "$").Err()
if err != nil && !strings.HasPrefix(err.Error(), "BUSYGROUP") {
return err
}
return nil
}
// Handler processes one entry; a nil error means "safe to XACK".
type Handler func(ctx context.Context, id string, fields map[string]any) error
// ReadOnce reads up to count NEW entries (">") for this consumer, handles
// each, and acknowledges only the ones whose handler returned nil. A failed
// entry stays in the group's pending entries list (PEL) for later recovery.
func ReadOnce(ctx context.Context, rdb redis.Cmdable, stream, group, consumer string, count int64, h Handler) (handled int, err error) {
return read(ctx, rdb, stream, group, consumer, ">", count, h)
}
// RecoverOwn re-reads this consumer's own pending entries (id "0"),
// the normal first step after a restart that kept the same consumer name.
func RecoverOwn(ctx context.Context, rdb redis.Cmdable, stream, group, consumer string, count int64, h Handler) (handled int, err error) {
return read(ctx, rdb, stream, group, consumer, "0", count, h)
}
func read(ctx context.Context, rdb redis.Cmdable, stream, group, consumer, start string, count int64, h Handler) (int, error) {
res, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
Group: group, Consumer: consumer, Streams: []string{stream, start},
Count: count, Block: -1, // negative: do not send BLOCK, return immediately
}).Result()
if errors.Is(err, redis.Nil) {
return 0, nil
}
if err != nil {
return 0, err
}
handled := 0
for _, s := range res {
for _, m := range s.Messages {
if herr := h(ctx, m.ID, m.Values); herr != nil {
continue // leave it pending; an operator or reaper decides
}
if err := rdb.XAck(ctx, stream, group, m.ID).Err(); err != nil {
return handled, err
}
handled++
}
}
return handled, nil
}
// PendingCount is the number of delivered-but-unacknowledged entries.
func PendingCount(ctx context.Context, rdb redis.Cmdable, stream, group string) (int64, error) {
p, err := rdb.XPending(ctx, stream, group).Result()
if err != nil {
return 0, err
}
return p.Count, nil
}package streams
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"strings"
"testing"
"github.com/alicebob/miniredis/v2"
"github.com/redis/go-redis/v9"
)
// uniqueName gives every test its own stream/group so tests never see each
// other's entries, even when they share one real Redis in CI.
func uniqueName(t *testing.T, kind string) string {
t.Helper()
b := make([]byte, 4)
if _, err := rand.Read(b); err != nil {
t.Fatal(err)
}
return kind + "-" + strings.ReplaceAll(strings.ToLower(t.Name()), "/", "_") + "-" + hex.EncodeToString(b)
}
// newRedis starts an in-process fake Redis; no Docker, no network port clash.
func newRedis(t *testing.T) *redis.Client {
t.Helper()
mr := miniredis.RunT(t) // closed automatically via t.Cleanup
rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
t.Cleanup(func() { _ = rdb.Close() })
return rdb
}
func TestAckRemovesFromPendingAndFailureStaysPending(t *testing.T) {
ctx := context.Background()
rdb := newRedis(t)
stream, group := uniqueName(t, "s"), uniqueName(t, "g")
if err := EnsureGroup(ctx, rdb, stream, group); err != nil {
t.Fatal(err)
}
if err := EnsureGroup(ctx, rdb, stream, group); err != nil {
t.Fatalf("second EnsureGroup must tolerate BUSYGROUP: %v", err)
}
for _, v := range []string{"ok", "bad"} {
if err := rdb.XAdd(ctx, &redis.XAddArgs{Stream: stream, Values: map[string]any{"v": v}}).Err(); err != nil {
t.Fatal(err)
}
}
handler := func(_ context.Context, _ string, f map[string]any) error {
if f["v"] == "bad" {
return errors.New("cannot process")
}
return nil
}
handled, err := ReadOnce(ctx, rdb, stream, group, "worker-1", 10, handler)
if err != nil || handled != 1 {
t.Fatalf("handled=%d err=%v, want 1", handled, err)
}
if n, _ := PendingCount(ctx, rdb, stream, group); n != 1 {
t.Fatalf("pending = %d, want 1 (the failed entry)", n)
}
// Fix the "bug", restart with the same consumer name, recover the pending entry.
handled, err = RecoverOwn(ctx, rdb, stream, group, "worker-1", 10, func(context.Context, string, map[string]any) error { return nil })
if err != nil || handled != 1 {
t.Fatalf("recovered=%d err=%v, want 1", handled, err)
}
if n, _ := PendingCount(ctx, rdb, stream, group); n != 0 {
t.Fatalf("pending after recovery = %d, want 0", n)
}
}
func TestTwoTestsNeverShareAGroup(t *testing.T) {
ctx := context.Background()
rdb := newRedis(t)
a, b := uniqueName(t, "s"), uniqueName(t, "s")
if a == b {
t.Fatal("unique names collided")
}
if err := EnsureGroup(ctx, rdb, a, "g"); err != nil {
t.Fatal(err)
}
if n, _ := rdb.Exists(ctx, b).Result(); n != 0 {
t.Fatal("stream b must not exist")
}
}//go:build integration
package integration
import (
"context"
"testing"
"github.com/redis/go-redis/v9"
"github.com/testcontainers/testcontainers-go"
tcredis "github.com/testcontainers/testcontainers-go/modules/redis"
"academy/testing-messaging/streams"
)
// expected, not run: needs a Docker daemon. The same worker code that the
// miniredis unit test exercises runs here against a real Redis server.
func TestRedisStreamsAgainstRealServer(t *testing.T) {
ctx := context.Background()
ctr, err := tcredis.Run(ctx, "redis:7")
testcontainers.CleanupContainer(t, ctr)
if err != nil {
t.Fatal(err)
}
uri, err := ctr.ConnectionString(ctx)
if err != nil {
t.Fatal(err)
}
opt, err := redis.ParseURL(uri)
if err != nil {
t.Fatal(err)
}
rdb := redis.NewClient(opt)
t.Cleanup(func() { _ = rdb.Close() })
stream, group := unique(t, "stream"), unique(t, "group")
// XGROUP CREATE ... MKSTREAM: the group and the stream appear together.
if err := streams.EnsureGroup(ctx, rdb, stream, group); err != nil {
t.Fatal(err)
}
if err := rdb.XAdd(ctx, &redis.XAddArgs{Stream: stream, Values: map[string]any{"v": "x"}}).Err(); err != nil {
t.Fatal(err)
}
n, err := streams.ReadOnce(ctx, rdb, stream, group, "c1", 10,
func(context.Context, string, map[string]any) error { return nil })
if err != nil || n != 1 {
t.Fatalf("handled=%d err=%v", n, err)
}
t.Cleanup(func() { rdb.Del(context.Background(), stream) }) // best-effort cleanup on shared Redis
}//go:build integration
package integration
import (
"crypto/rand"
"encoding/hex"
"strings"
"testing"
)
// unique returns a name no other test, and no earlier run of this test, can
// reuse: topic, queue, stream and consumer-group names all come from here.
func unique(t *testing.T, kind string) string {
t.Helper()
b := make([]byte, 4)
if _, err := rand.Read(b); err != nil {
t.Fatal(err)
}
name := strings.NewReplacer("/", "_", " ", "_").Replace(strings.ToLower(t.Name()))
return kind + "." + name + "." + hex.EncodeToString(b)
}brokerهای بیرون از دامنهٔ این فصل مثل NATS، Pulsar و SQS هم گزینهٔ container یا emulator دارند (Testcontainers ماژول NATS و Pulsar فهرست میکند)؛ لایههای تست همان است.
در سیستمهای واقعی
- مستندات Laravel میگوید
Event::fake()listenerها را خاموش میکند؛ تیمهایی که اول fake میکنند و بعد مدل میسازند دادهٔ ساختهشده با factory را بدون UUID یا slug میبینند. در تستهای شکستخورده ترتیب را بررسی کنید. - مستندات Testcontainers برای Go ماژولهای جدا برای RabbitMQ، Kafka، Redpanda و Redis با
Runو کمکیهای اتصال دارد؛ یک container برای هر پکیج با نامهای یکتا الگوی مناسب هزینه است. - پیشفرض مستند Confluent Schema Registry برابر BACKWARD است که transitive نیست؛ تاریخچهٔ سهنسخهای برای محافظت از consumerهای قدیمیترین schema به
BACKWARD_TRANSITIVEنیاز دارد. - message pactها در نسخهٔ ۳ مشخصهٔ Pact آمدند؛ پیادهسازیها بسته به زبان فرق دارند، پس تأیید کنید کتابخانهتان قالب پیام را پشتیبانی میکند.
در معماری: از یک فرایند تا سیستم توزیعشده
یکپارچه (Monolith): یک فرایند و یک پایگاه داده
یک برنامهٔ Laravel jobها را به صف پایگاه داده یا Redis میفرستد. تستهای واحد از Queue::fake() استفاده میکنند و handle() را صدا میزنند؛ یک تست feature با driver همگام اجرا میشود تا ثابت کند کل job روی پایگاه دادهٔ تست کار میکند. سرویس کوچک Go consumer خود را با bus درونحافظهای و ساعت جعلی تست میکند. container لازم نیست.
یکپارچهٔ ماژولار (Modular monolith): مالک مشخص
صورتحساب و ارسال در یک deployment هستند اما queueهای جدا دارند. contract testها در مرز ماژول مینشینند: golden file ماژول تولیدکننده ورودی تست ماژول مصرفکننده است. fake در هر port ماژولها را جدا تستپذیر نگه میدارد و پیشوند queue یکتا برای هر ماژول مانع درهمآمیختن زیرساخت مشترک تست میشود.
میکروسرویسها (Microservices): contractها جای محیط تست مشترک را میگیرند
Orders رخداد OrderPlaced را منتشر میکند؛ Billing، Shipping و Email مصرف میکنند. staging مشترک برای هر تغییر کند و ناپایدار است. بهجای آن هر consumer یک pact منتشر میکند، Orders همه را در build خودش راستیآزمایی میکند و دروازهٔ deploy مثل ابزار can-i-deploy در Pact که روی «Matrix» نسخههای آزمودهشدهٔ consumer و provider بنا شده، انتشار شکننده را میبندد. بررسی سازگاری registry از topic محافظت میکند. probeهای سرتاسری میمانند اما اندکند. تست outbox بررسی میکند ردیف رخداد در همان تراکنش نوشته شده؛ تست saga بررسی میکند پس از شکست یک گام جبران انجام میشود.
دادهٔ توزیعشده (Distributed data): replica، shard و region
handlerی که از replica عقبمانده میخواند ممکن است سفارش را نیابد و پیام را اشتباهی پارک کند. با repository جعلی که بار اول «پیدا نشد» و بار دوم «پیدا شد» برمیگرداند تست کنید و retry را بهجای parking بسنجید. رفتار میانregion را با تزریق خطا تست کنید: publish که محلی موفق و از راه دور timeout میشود و redelivery پس از failover که با همان ID کسبوکاری میرسد. تستهای container را تکregion نگه دارید؛ خطای region را با proxy شبیهسازی کنید.
مسیر مقیاس (Scaling path)
| بار | طراحی تست | مثال |
|---|---|---|
| 1x | fake، تست جدولی، golden file | یک سرویس، یک queue، مجموعه زیر ۱۰ ثانیه |
| 10x | contract و چند تست container برای هر broker | چند consumer؛ CI روی pull request containerها را اجرا میکند |
| 100x | دروازهٔ contract در deploy، chaos شبانه، probe مصنوعی | تیمهای فراوان؛ بررسی schema روی registry مشترک، پیام آزمایشی قناری |
مجموعه منحنی هزینه هم دارد: هر لایهای که اضافه میکنید باید با رخدادهای پیشگیریشده خودش را توجیه کند.
آزمایشگاه
آزمایشهای واحد و contract در Go روی همین دستگاه اجرا شدهاند؛ آزمایشهای container و Laravel زیر «خروجی موردانتظار؛ اجرا نشده» هستند. برای آزمایش ۱ و ۲ Docker، Compose یا cluster لازم نیست.
1. مجموعهٔ سریع Go را اجرا کنید
cd docs/snippets/messaging/testing-messaging/go
go test -count=1 -race ./...
# run output: ok academy/testing-messaging/msg, .../orders, .../streams (about 1 s with -race)TestTransientFailureRecoversAfterBackoff را بخوانید: handler ثانیههای مجازی منتظر میماند و تست در میکروثانیه تمام میشود.
2. کد را خراب کنید و شکست تستها را ببینید
در orders/consumer.go عبارت if c.seen(m.ID) { را به if false && c.seen(m.ID) { تغییر دهید.
go test -count=1 ./orders
# run output: FAIL TestDuplicateDeliveryHasOneEffect and TestCrashBeforeAckRedeliversWithoutDoubleEffectتغییر را برگردانید. تستی که نتواند شکست بخورد چیزی ثابت نمیکند.
3. RabbitMQ واقعی با container
cd docs/snippets/messaging/testing-messaging/go/integration
go test -tags integration -count=1 -run RabbitMQ ./...
# expected, not run: PASS after ~10-20 s (image pull dominates the first run); the exclusive queue is gone afterwards4. offset شروع Kafka و group یکتا
go test -tags integration -count=1 -run 'TestKafka|TestRedpanda' ./...
# expected, not run: records a, b, c are read in order; removing ConsumeStartOffset on a Java-style default hangs until the context times out5. fakeهای Laravel
php artisan test --filter=PlaceOrderTest
# expected, not run: 5 tests pass; the invalid-order test asserts Queue::assertNothingPushed()بدفهمیهای رایج
| باور | واقعیت |
|---|---|
| کد پیامرسانی باید با broker واقعی تست شود | بیشتر منطق با fake تست میشود؛ broker برای سیمکشی |
| fake و mock یکیاند | fake رفتار واقعی دارد؛ mock فراخوانیهای از پیش نوشته را راستیآزمایی میکند |
Queue::fake() job من را اجرا میکند | pushها را ثبت میکند؛ برای تست job handle() را صدا بزنید |
Event::fake() فقط ثبت میکند | listenerها را هم از اجرا میاندازد |
| تست یکپارچگی contract test را بینیاز میکند | یک جفت را میسنجد؛ contract از همهٔ consumerها محافظت میکند |
| sleep بلندتر تست ناپایدار را درست میکند | race را پنهان میکند؛ شرط را poll کنید یا fake بگذارید |
| restart کردن broker تستها را جدا میکند | نام یکتا برای هر تست سریعتر جدا میکند |
| broker ترتیب را تضمین میکند، پس تست ترتیب لازم نیست | retry، replay و چند consumer ترتیب رسیدن را بههم میزنند |
| schema registry تست consumer را بینیاز میکند | قواعد schema را میسنجد، نه آنچه هر consumer واقعاً میخواند |
| chaos به production نیاز دارد | تزریق خطا در fake و container بیشتر باگهای بازیابی را میگیرد |
| CI سبز یعنی DLQ کار میکند | فقط تستی که park را شکست میدهد ثابت میکند مبدأ ack نمیشود |
چکیدهٔ سریع
| موضوع | نکتهٔ ماندگار |
|---|---|
| هرم | تست fake سریع فراوان، container کم، سرتاسری کمتر |
| Port | interface کوچک به مالکیت consumer؛ fake کنار آن |
| Fake در برابر mock | fake رفتار دارد؛ mock فراخوانی را راستیآزمایی میکند |
| ساعت جعلی | sleepها را ثبت کنید؛ برنامه را بسنجید، نه زمان سپریشده |
| صف Laravel | Queue::fake() سپس assertPushed، assertPushedOn، assertNothingPushed |
| bus Laravel | Bus::fake() سپس assertChained، assertBatched، assertBatchCount |
| رخداد Laravel | Event::fake() listenerها را میبندد؛ اول مدل بسازید؛ except برای نگهداشتن بعضی |
| تست job | handle() را صدا بزنید؛ withFakeQueueInteractions()؛ failed() را صدا بزنید |
| Idempotency | یک ID دو بار، crash پیش از ack، یک اثر |
| ترتیب | توالی ۲ و بعد ۱؛ تست property بیفزایید |
| DLQ | شکست park نباید مبدأ را ack کند |
| Contract | Pact برای مصرفکنندهمحور، registry برای topic مشترک، golden برای بایتها |
| Container | تست tagدار، یکی برای هر پکیج، نام یکتا، cleanup |
| Kafka | topic بسازید، group یکتا، offset شروع صریح |
| Redis | miniredis برای منطق، MKSTREAM برای هر تست، Redis واقعی برای اسکریپت |
| CI | واحد همیشه، container روی PR، chaos شبانه |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — چرا برای publisher fake بهتر از mock است؟ حیاتی
پاسخ
پاسخ: fake رفتار واقعی دارد، پس تست نتیجه (چه چیزی publish شد) را میسنجد نه نحوهٔ صدا زدن client را و در برابر refactor میماند.
۲ — Queue::fake() چه کاری نمیکند؟ حیاتی
پاسخ
پاسخ: jobها را اجرا نمیکند. pushها را ثبت میکند؛ job را با ساختن نمونه و صدا زدن handle() تست کنید.
۳ — چرا مدلها را پیش از Event::fake() بسازیم؟ مهم
پاسخ
پاسخ: Event::fake listenerها را میبندد، پس دادهای که factory با رخداد مدل میسازد (UUID، slug) گم میشود.
۴ — backoff دهدقیقهای را چطور سریع تست کنیم؟ حیاتی
پاسخ
پاسخ: ساعتی تزریق کنید که Sleep آن مدت را ثبت و زمان مجازی را جلو ببرد، سپس برنامهٔ ثبتشده را بسنجید.
۵ — چه چیزی ثابت میکند consumer از crash پیش از ack جان به در میبرد؟ مهم
پاسخ
پاسخ: تستی که پیام را پردازش میکند، crash را شبیهسازی میکند تا broker دوباره تحویل دهد، دوباره پردازش میکند و یک اثر کسبوکاری را میسنجد.
۶ — چرا تست DLQ باید شکست نوشتن parking را بپوشاند؟ مهم
پاسخ
پاسخ: اگر consumer پس از park شکستخورده ack بزند تنها نسخه گم میشود. تست بررسی میکند خطا برمیگردد و مبدأ ack نمیشود.
۷ — تست یکپارچگی با contract test چه فرقی دارد؟ حیاتی
پاسخ
پاسخ: تست یکپارچگی یک تولیدکننده و مصرفکننده را روی broker واقعی با هم میسنجد؛ contract test بدون broker بررسی میکند پیام حداقل انتظار مصرفکننده را برآورده میکند.
۸ — چرا group تازهٔ Kafka در تست میتواند برای همیشه منتظر بماند؟ مهم
پاسخ
پاسخ: client جاوا پیشفرض auto.offset.reset=latest دارد، پس group تازه بعد از رکوردهای پیشین شروع میکند. offset شروع را صریح بگذارید.
۹ — تستهایی که یک container broker را به اشتراک میگذارند چگونه جدا شوند؟ مهم
پاسخ
پاسخ: به هر تست queue، topic یا stream یکتا و consumer group خودش بدهید و در t.Cleanup یا tearDown پاک کنید.
۱۰ — وقتی miniredis هست کی به container Redis نیاز داریم؟ مهم
پاسخ
پاسخ: برای رفتاری که fake مدل نمیکند: اسکریپت Lua، replication و failover، ACL و معنای دقیق خطا.
۱۱ — دو علت تست ناپایدار ناهمگام و راهحل هر کدام را نام ببرید. حیاتی
پاسخ
پاسخ: sleep ثابت (poll برای شرط یا fake) و state مشترک (نام یکتا و cleanup).
واژهنامه
| اصطلاح | معنا |
|---|---|
| هرم تست (Test pyramid) | شکل مجموعه: تست واحد فراوان، یکپارچگی کمتر، سرتاسری بسیار کم |
| Port | interfaceای که برنامه مالک آن است و adapter یا fake پیادهاش میکند |
| تستدابل (Test double) | هر جانشین شیء production در تست |
| Dummy | double که فقط پارامتر را پر میکند |
| Stub | double با پاسخ آماده |
| Fake | double با پیادهسازی کارای میانبر |
| Mock | double که فراخوانیهای مورد انتظار را راستیآزمایی میکند |
| Spy | double که فراخوانیها را برای بررسی بعدی ثبت میکند |
| In-memory publisher | publisher جعلی که پیام را در حافظه نگه میدارد |
| ساعت جعلی (Fake clock) | ساعتی که sleepهایش ثبت و آنی است |
| تست جدولی (Table-driven test) | یک بدنهٔ تست که روی جدولی از موردها اجرا میشود |
Queue::fake() | ثبتکنندهٔ Laravel برای jobهای صفشده |
Bus::fake() | ثبتکنندهٔ Laravel برای jobها، زنجیرهها و batchهای dispatchشده |
Event::fake() | ثبتکنندهٔ Laravel که listenerها را هم میبندد |
Notification::fake() | ثبتکنندهٔ Laravel برای notificationها |
| Testcontainers | خانوادهٔ کتابخانههایی که از تست containerهای موقت بالا میآورند |
| miniredis | پیادهسازی درونفرایندی Go از سرور Redis برای تست |
| Redpanda | broker سازگار با پروتکل Kafka که اغلب container تست است |
| Consumer-driven contract | قراردادی که از نیاز مصرفکننده نوشته میشود |
| Pact / message pact | قالب و ابزار قرارداد؛ message pact صفها را میپوشاند |
| AsyncAPI | مشخصهای برای توصیف کانالها، عملیات و payload پیام |
| Schema registry compatibility | قواعدی که هنگام ثبت نسخهٔ جدید schema بررسی میشوند |
| Golden file | خروجی مورد انتظار ذخیرهشده که بایت به بایت مقایسه میشود |
| Property-based test | تست یک invariant روی ورودیهای تولیدشده |
| Failure injection | خرابکردن عمدی یک وابستگی در تست |
| Flaky test | تستی با نتیجهٔ نامعین روی همان کد |
| Test isolation | هیچ تستی state تست دیگر را نبیند |
| Poison message | پیامی که تحت consumer فعلی هر بار شکست میخورد |
| Test message | پیام مصنوعی علامتدار که از مسیر واقعی رد میشود |
منابع
- Fowler: The Practical Test Pyramid، Test Double.
- Laravel 13: Queues، Events، Mocking، Notifications.
- fakeهای framework در Laravel: QueueFake، BusFake، EventFake، InteractsWithQueue، CallQueuedListener.
- Testcontainers برای Go: Quickstart، RabbitMQ، Kafka، Redpanda، Redis؛ PHP: testcontainers-php.
- Enterprise Integration Patterns: Test Message.
- Pact: How Pact works، can-i-deploy، Specification versions، pact-go.
- AsyncAPI: Document structure. Confluent: Schema evolution and compatibility، Schema Registry API.
- Go: testing، testing/quick، testing/synctest، rapid، miniredis، miniredis package.
- RabbitMQ: Queues، Management plugin، HTTP API reference.
- Kafka: Consumer configs؛ franz-go: kgo، kadm.
- Redis: XGROUP CREATE، XREADGROUP.