المشكلة: الخدمتين شغالين لوحدهم ومكسورين مع بعض
فريق الـ billing غيّر اسم حقل في الـ response من planId لـ plan_id. كل الـ unit tests عندهم عدّت. الـ Angular والـ ingestion worker وقعوا في الإنتاج. الـ E2E tests كانت هتكتشف ده — لو كانت موجودة لكل التركيبات، وسريعة، ومستقرة. وده نادر. Contract testing بيملا الفجوة: كل consumer بيكتب «أنا بستخدم إيه بالظبط»، والـ provider بيتحقق إنه بيوفي بكل العقود دي قبل الـ deploy.
| النوع | بيكتشف | ما بيكتشفش |
|---|---|---|
| OpenAPI diff | تغييرات schema بتكسر (حقل اتشال، type اتغير) | هل الـ consumer فعلًا بيستخدم الحقل ده؟ وهل السلوك (status في حالة معينة) اتغير؟ |
| Contract test (Pact) | التوقعات الفعلية لكل consumer: request، response shape، status لحالات محددة | منطق البيزنس الكامل، الأداء |
| Integration test | الخدمة مع dependencies حقيقية (DB) | توافق مع خدمات تانية في نسخها الحالية |
| E2E | الـ flow الكامل | بطيء وهش ومكلف — قليل منه بس |
Consumer test بـ PactNet
الـ consumer هنا: ingestion worker (.NET) بيكلم Billing API عشان يعرف حدود الخطة قبل ما يعالج مستند. الاختبار بيشغّل mock server من Pact، الكود الحقيقي بتاع الـ client بيكلمه، والـ interactions بتتسجل في pact file.
public sealed class EntitlementsClientPactTests
{
private readonly IPactBuilderV4 _pact = Pact.V4("ingestion-worker", "billing-api", new PactConfig
{
PactDir = Path.Combine("..", "..", "..", "pacts") // pact JSON written here, then published to the broker
}).WithHttpInteractions();
[Fact]
public async Task Gets_document_limit_for_an_active_tenant()
{
var tenantId = "6f1c2a10-0000-4000-8000-000000000001";
_pact.UponReceiving("a request for tenant entitlements")
.Given("tenant 6f1c… is on the Pro plan") // provider state
.WithRequest(HttpMethod.Get, $"/api/tenants/{tenantId}/entitlements")
.WithHeader("Accept", "application/json")
.WillRespond()
.WithStatus(HttpStatusCode.OK)
.WithJsonBody(new
{
plan = Match.Type("pro"), // any string, not literally "pro"
limits = new { documents = Match.Integer(500), aiTokensPerMonth = Match.Integer(2_000_000) },
status = Match.Regex("active", "^(active|trialing|past_due)$")
});
await _pact.VerifyAsync(async ctx =>
{
var client = new EntitlementsClient(new HttpClient { BaseAddress = ctx.MockServerUri }); // the REAL client code
var e = await client.GetAsync(Guid.Parse(tenantId), default);
Assert.Equal(500, e.Limits.Documents);
});
}
[Fact]
public async Task Treats_404_as_unknown_tenant()
{
_pact.UponReceiving("a request for an unknown tenant")
.Given("tenant does not exist")
.WithRequest(HttpMethod.Get, "/api/tenants/00000000-0000-4000-8000-000000000000/entitlements")
.WillRespond().WithStatus(HttpStatusCode.NotFound);
await _pact.VerifyAsync(async ctx =>
{
var client = new EntitlementsClient(new HttpClient { BaseAddress = ctx.MockServerUri });
await Assert.ThrowsAsync<UnknownTenantException>(() => client.GetAsync(Guid.Empty, default));
});
}
}- Matchers (
Match.Type،Integer،Regex) بتخلي العقد عن الشكل مش القيم الحرفية — وإلا أي تغيير في بيانات الـ test عند الـ provider هيكسره. - اختبر اللي بتستخدمه بس: لو الـ worker ما بيقراش
createdAt، ما تحطوش في العقد. كده الـ provider حر يغيّر أي حاجة محدش بيستخدمها — دي قيمة «consumer-driven». - حالات الأخطاء جزء من العقد (404، 402) — غالبًا هي اللي بتتكسر.
Provider verification على ASP.NET Core
public sealed class BillingApiPactVerificationTests(ITestOutputHelper output) : IClassFixture<BillingApiFixture>
{
[Fact]
public void Honours_all_consumer_pacts()
{
using var fixture = new BillingApiFixture(); // starts the real API on a local port (Kestrel)
var config = new PactVerifierConfig { Outputters = [new XunitOutput(output)] };
using var verifier = new PactVerifier("billing-api", config);
verifier.WithHttpEndpoint(fixture.ServerUri)
.WithPactBrokerSource(new Uri(Environment.GetEnvironmentVariable("PACT_BROKER_URL")!), o => o
.TokenAuthentication(Environment.GetEnvironmentVariable("PACT_BROKER_TOKEN")!)
.ConsumerVersionSelectors(new ConsumerVersionSelector { MainBranch = true },
new ConsumerVersionSelector { DeployedOrReleased = true })
.PublishResults(Environment.GetEnvironmentVariable("GIT_SHA")!, r => r.ProviderBranch(Environment.GetEnvironmentVariable("GIT_BRANCH")!)))
.WithProviderStateUrl(new Uri(fixture.ServerUri, "/pact/provider-states"))
.Verify();
}
}
// Test-only endpoint in the fixture (never mapped in production builds)
app.MapPost("/pact/provider-states", async (ProviderState s, AppDb db) =>
{
switch (s.State)
{
case "tenant 6f1c… is on the Pro plan":
await TestData.SeedTenantAsync(db, Guid.Parse("6f1c2a10-0000-4000-8000-000000000001"), plan: "pro"); break;
case "tenant does not exist":
break; // nothing to seed
}
return Results.Ok();
});Provider states هي اللي بتخلي الـ verification مستقلة: كل interaction بتقول «لازم تكون الدنيا كده»، والـ provider بيجهز البيانات دي (DB test أو fakes لـ dependencies بتاعته) قبل ما الـ request يتبعت. ما تحاولش تتحقق ضد بيئة staging مشتركة — البيانات هناك مش تحت سيطرتك.
الـ Broker و can-i-deploy: العقد كـ gate
# consumer pipeline (ingestion-worker)
- run: dotnet test tests/Ingestion.PactTests # writes pacts/*.json
- run: pact-broker publish pacts --consumer-app-version $GITHUB_SHA --branch $GITHUB_REF_NAME
- name: can I deploy the worker to production?
run: pact-broker can-i-deploy --pacticipant ingestion-worker --version $GITHUB_SHA --to-environment production
- run: ./deploy.sh production
- run: pact-broker record-deployment --pacticipant ingestion-worker --version $GITHUB_SHA --environment production
# provider pipeline (billing-api)
- run: dotnet test tests/Billing.PactVerification # verifies pacts from main + deployed consumer versions
- run: pact-broker can-i-deploy --pacticipant billing-api --version $GITHUB_SHA --to-environment production- can-i-deploy بيسأل الـ broker: «النسخة دي اتعمل لها verification ناجح ضد النسخ اللي شغالة دلوقتي في production من كل الـ consumers/providers؟» — لو لأ، الـ deploy بيقف.
- Webhooks: لما consumer ينشر pact جديد، الـ broker يشغّل verification الـ provider تلقائيًا (فالفريقين بيعرفوا بسرعة).
- Pending pacts / WIP: توقعات جديدة من consumer ما بتكسرش build الـ provider لحد ما يتحقق منها أول مرة — بيمنع إن فريق يوقف فريق تاني.
BDD: Gherkin كلغة مشتركة
BDD مش أداة؛ هي ممارسة: المطور والـ QA والـ product بيتفقوا على أمثلة محددة للسلوك قبل البناء، ويكتبوها بلغة مفهومة للكل. الأمثلة دي بتبقى acceptance tests قابلة للتنفيذ.
Feature: Plan document limits
Tenants on a plan cannot exceed the plan's document quota,
but admins see a clear way to upgrade.
Background:
Given a tenant "Acme" on the "Starter" plan with a limit of 5 documents
And "Acme" already has 5 documents
Scenario: Upload beyond the quota is rejected with an upgrade hint
When a member of "Acme" uploads a document "policy.pdf"
Then the upload is rejected with status 402
And the response includes the meter "documents" and the limit 5
And no document is stored for "Acme"
Scenario: Upgrading raises the limit immediately
Given "Acme" upgrades to the "Pro" plan
When a member of "Acme" uploads a document "policy.pdf"
Then the upload is accepted
Scenario Outline: Quotas per plan
Given a tenant "T" on the "<plan>" plan with no documents
When a member of "T" uploads <count> documents
Then <accepted> uploads are accepted
Examples:
| plan | count | accepted |
| Starter | 6 | 5 |
| Pro | 6 | 6 |[Binding]
public sealed class PlanLimitsSteps(TestApp app, ScenarioContext ctx)
{
[Given("a tenant {string} on the {string} plan with a limit of {int} documents")]
public Task GivenTenantOnPlan(string tenant, string plan, int limit) => app.SeedTenantAsync(tenant, plan, limit);
[Given("{string} already has {int} documents")]
public Task GivenExistingDocs(string tenant, int n) => app.SeedDocumentsAsync(tenant, n);
[When("a member of {string} uploads a document {string}")]
public async Task WhenUpload(string tenant, string file) =>
ctx["response"] = await app.ClientFor(tenant, role: "member").PostAsync("/api/documents", TestFiles.Pdf(file));
[Then("the upload is rejected with status {int}")]
public void ThenRejected(int status) => Assert.Equal(status, (int)((HttpResponseMessage)ctx["response"]).StatusCode);
[Then("no document is stored for {string}")]
public async Task ThenNothingStored(string tenant) => Assert.Equal(5, await app.CountDocumentsAsync(tenant));
}Reqnroll هو المشروع المفتوح اللي كمّل بعد SpecFlow (اللي وقف تطويره)، ومتوافق معاه بشكل كبير مع migration guide. الـ steps بتستخدم نفس WebApplicationFactory و Testcontainers بتوع الـ integration tests — الـ Gherkin طبقة قراءة فوقهم مش test framework منفصل.
إمتى BDD بيستاهل؟
| بيستاهل | مش بيستاهل |
|---|---|
| قواعد بيزنس معقدة (billing، صلاحيات، تسعير) والـ product بيقرا ويراجع الـ scenarios | محدش غير المطورين بيقرا الـ feature files |
| Regulated domains محتاجة توثيق «السلوك المتفق عليه» | اختبارات تقنية (retry، caching) — xUnit أوضح |
| Discovery workshops (Three Amigos) بتطلّع حالات حدودية قبل الكود | Scenarios مكتوبة بعد الكود كترجمة للـ tests (ceremony) |
علامات Gherkin سيء: steps فيها تفاصيل UI («click button id=btn-submit»)، scenarios طويلة 20 خطوة، وصياغة imperative بدل declarative. الكويس: لغة البيزنس، scenario واحد = قاعدة واحدة، وأمثلة بأرقام حقيقية.
الـ pipeline الكامل: كل نوع اختبار فين
- الـ contract tests مكانها بين الـ integration والـ E2E: أسرع من E2E بكتير، وبتغطي اللي الـ unit مش شايفه.
- الـ OpenAPI diff والـ Pact مكملين لبعض: الأول بيحمي العملاء اللي مش بيكتبوا pacts (شركاء خارجيين)، والتاني بيحمي الـ consumers الداخليين بسلوكهم الفعلي.
- Angular كـ consumer:
@pact-foundation/pactمع Jest/Vitest بيعمل نفس الشيء من جهة الـ frontend.
Contracts للـ messages والـ events
الـ breaking changes في الـ events أخطر من الـ HTTP: الـ consumer مش موجود في نفس اللحظة، والرسايل القديمة لسه في الـ queue. Pact بيدعم message pacts: الـ consumer بيوصف شكل الـ message اللي بيتوقعها (مثلًا DocumentUploaded)، والـ provider بيثبت إن الـ producer code بيطلع message مطابقة.
_pact.ExpectsToReceive("a DocumentUploaded event")
.Given("a PDF was uploaded")
.WithJsonContent(new
{
type = "document.uploaded", version = Match.Integer(1),
documentId = Match.Regex("00000000-0000-4000-8000-000000000001", "^[0-9a-f-]{36}$"),
tenantId = Match.Type("6f1c2a10-0000-4000-8000-000000000001"),
blobRef = Match.Type("t/6f1c…/raw/abc.pdf"), contentType = Match.Regex("application/pdf", "^[a-z]+/[a-z0-9.+-]+$")
})
.Verify<DocumentUploaded>(msg => handler.Validate(msg)); // the real handler's parsing/validationمع قواعد versioning للـ events (حقول إضافية بس في نفس الـ version، و version جديد للتغيير الكاسر مع دعم القديم لفترة) — زي Messaging.
الـ frontend كـ consumer
const provider = new PactV4({ consumer: 'knowledge-web', provider: 'knowledge-api', dir: './pacts' });
it('lists documents for the dashboard', () =>
provider.addInteraction()
.given('tenant has 2 ready documents')
.uponReceiving('a request for the first page of documents')
.withRequest('GET', '/api/documents', b => b.query({ page: '1' }).headers({ Accept: 'application/json' }))
.willRespondWith(200, b => b.jsonBody({
items: eachLike({ id: uuid(), title: like('Leave policy'), status: regex('ready|processing|failed', 'ready') }),
total: integer(2),
}))
.executeTest(async server => {
const api = new DocumentsApi(createHttpClient(server.url)); // the real Angular service
const page = await firstValueFrom(api.list(1));
expect(page.items[0].status).toBe('ready');
}));كده لو فريق الـ API غيّر status من string لـ enum رقمي، الـ verification بتاعتهم هتفشل قبل الـ merge، مش الـ dashboard في الإنتاج.
أخطاء شائعة
- Pacts بقيم حرفية بدل matchers ← بتتكسر مع أي تغيير بيانات.
- الـ provider بيكتب الـ pacts بنفسه (provider-driven) — بيفقد فكرة «اللي بيستخدمه الـ consumer فعلًا».
- Verification ضد staging مشتركة بدل provider states.
- Pact لاختبار منطق البيزنس الكامل (هو للعقد مش للسلوك الداخلي).
- Gherkin مكتوب بلغة UI أو بعد الكود من غير ما الـ product يقراه.
- مفيش can-i-deploy، فالـ pacts بتعدّي بس محدش بيمنع الـ deploy.
اختبر فهمك
الـ provider عايز يشيل حقل createdAt من الـ response. إزاي يعرف إنه آمن؟
Provider state في Pact معناه؟
تمرين محلول
صمّم استراتيجية contracts للـ Capstone: Angular ← API، worker ← billing API، API ← LLM provider
الحل: Angular ← API: Pact (JS) على الـ endpoints اللي الـ UI بتستخدمها + OpenAPI diff + types متولدة. worker ← billing: Pact (.NET) زي المثال، can-i-deploy على الاتنين. API ← LLM provider: مش ممكن تعمل pact مع طرف تالت مش بيتحقق؛ بدلها: adapter معزول، contract tests ضد mock-llm بنفس شكل الـ API الحقيقي، smoke test يومي ضد الـ provider الحقيقي بمفتاح test، وتثبيت API version. ده بيغطي التلات حدود من غير E2E ضخم.
أسئلة إنترفيو
(Mid) إيه الفرق بين contract test و integration test؟
(Senior) فريقين بيعطلوا بعض بالـ breaking changes. تعمل إيه؟
المراجع والقراءة الإضافية
الدرس بيشرح الفكرة نفسها؛ الروابط دي للتحقق والتعمق والرجوع لتفاصيل الـ API. (محتاجة إنترنت.)
مصادر تعليمية ومتقدمة — Third-party & advanced reading
خلصت الدرس وحليت الأسئلة؟ علّم عليه عشان يتحسب في تقدّمك.