Giter Site home page Giter Site logo

pactify's Introduction

Pactify

Pactify is very simple contract testing tool for .NET Core. It was inspired by PACT.io.

master develop
AppVeyor Build status Build status
CodeCov codecov codecov

Installation

Package manager

Install-Package Pactify -Version 1.1.0

.NET CLI

dotnet add package Pactify --version 1.1.0

Getting started

Start with creating a simple unit test on consumer side:

[Fact]  
public async Task Consumer_Should_Create_A_Pact()  
{  
    var options = new PactDefinitionOptions  
    {  
        IgnoreContractValues = true,  
        IgnoreCasing = true  
    };  
    
    await PactMaker  
        .Create(options)  
        .Between("orders", "parcels")  
        .WithHttpInteraction(cb => cb  
            .Given("There is a parcel with some id")  
            .UponReceiving("A GET Request to retrieve the parcel")  
            .With( request => request  
                .WithMethod(HttpMethod.Get)  
                .WithPath("api/parcels/1"))  
            .WillRespondWith(response => response  
                .WithHeader("Content-Type", "application/json")  
                .WithStatusCode(HttpStatusCode.OK)  
                .WithBody<ParcelReadModel>()))  
        .PublishedAsFile("../../../../../pacts")  
        .MakeAsync();   
}

In the above example the result JSON file will be saved in the specified directory. Alternatively you can publish the JSON via HTTP as follows:

.PublishViaHttp("http://myapi.com/pacts", HttpMethod.Post, apiKey = "myApiKey");

The above unit test will create a PACT JSON between orders and parcels services:

{  
  "consumer": {  
    "name": "orders"  
  },  
  "provider": {  
    "name": "parcels"  
  },  
  "interactions": [  
    {  
      "provider_state": "There is a parcel with some id",  
      "description": "A GET Request to retrieve the parcel",  
      "request": {  
        "method": "GET",  
        "path": "api/parcels/1"  
  },  
      "response": {  
        "headers": {  
          "content-Type": "application/json"  
  },  
        "status": 200,  
        "body": {  
          "id": "00000000-0000-0000-0000-000000000000",  
          "name": null,  
          "price": 0.0  
  }  
      }  
    }  
  ],  
  "options": {  
    "ignoreCasing": true,  
    "ignoreContractValues": true  
  }  
}

Because the whole idea assumes that consumer is always right this part of the testing should always pass!

Having that, you can move to the verifying the pact on the provider's side:

[Fact]  
public async Task Provider_Should_Meet_Consumers_Expectations()  
{  
    await PactVerifier  
        .CreateFor<Startup>()  
        .Between("orders", "parcels")  
        .RetrieveFromFile("../../../../../pacts")  
        .VerifyAsync();  
}

Notice that PactVerifier was created using Startup class. Thanks to that your provider's API will be ran in memory using Microsoft.AspNetCore.TestHost package with proxy HttpClient object. If for some reason this is not a right solution, you can simply pass your custom HttpClient instance instead:

PactVerifier.Create(myHttpClient)
...

If the pacts verification passes the above test should pass. Otherwise proper error messages are going to be displayed to you.

Integration with PACT broker

Pactify integrates easily with PACT Broker which allows you to manage and read (via UI) your pacts on external HTTP server running inside Docker container. First, clone the broker's repository:

git clone https://github.com/DiUS/pact_broker-docker.git

Navigate to the repository and run the docker-compose.yml file using the following command:

docker-compose up -d

This will run all the broker's necessary infrastructure in the detached mode. The UI should be available at localhost:9292:

UI

Change your code to publish and receive the pact from the broker:

[Fact]  
public async Task Consumer_Should_Create_APact()  
{  
    var options = new PactDefinitionOptions  
  {  
        IgnoreContractValues = true,  
        IgnoreCasing = true  
  };  
  
    await PactMaker  
		.Create(options)  
        .Between("orders", "parcels")  
        .WithHttpInteraction(cb => cb  
            .Given("There is a parcel with some id")  
            .UponReceiving("A GET Request to retrieve the parcel")  
            .With( request => request  
                .WithMethod(HttpMethod.Get)  
                .WithPath("api/parcels/1"))  
            .WillRespondWith(response => response  
                .WithHeader("Content-Type", "application/json")  
                .WithStatusCode(HttpStatusCode.OK)  
                .WithBody<ParcelReadModel>()))  
        .PublishedViaHttp("http://localhost:9292/pacts/provider/parcels/consumer/orders/version/1.2.104", HttpMethod.Put) 
        .MakeAsync();  
}  
  
[Fact]  
public async Task Provider_Should_Meet_Consumers_Expectations()  
{  
    await PactVerifier  
        .CreateFor<Startup>()  
        .Between("orders", "parcels")  
        .RetrievedViaHttp("http://localhost:9292/pacts/provider/parcels/consumer/orders/latest")  
        .VerifyAsync();  
}

Both tests should be green. After refreshing the broker's UI, you should see the pact:

ui-pact

Once you click on it, you should be able to inspect your pact file:

ui-pact-details

Contributing

Want to help developing Pactify? Awesome! Here you can find contributor guide ;)

Icon

Icon made by Freepik from www.flaticon.com is licensed by Creative Commons BY 3.0

pactify's People

Contributors

goorion avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.