项目作者: DiUS

项目描述 :
A Swift / ObjeciveC DSL for creating pacts.
高级语言: Swift
项目地址: git://github.com/DiUS/pact-consumer-swift.git
创建时间: 2015-01-14T05:41:05Z
项目社区:https://github.com/DiUS/pact-consumer-swift

开源协议:MIT License

下载


Pact Consumer Swift

Build
Codecov
Carthage compatible
Swift Package Manager
Swift
Badge w/ CocoaPod Version
Badge w/ Supported Platforms
License: MIT
Twitter


A new version featuring Pact Specification v3, a simplified installation and better management of the mock server processes is in active development and can be found at PactSwift. We are currently looking for people to try it out and provide feedback.

This library provides a Swift / Objective C DSL for creating Consumer Pacts. It provides support for Consumer Driven Contract Testing between dependent systems where the integration is based on HTTP (or message queues for some of the implementations).

But why? To test communication boundaries between your app and services.
You can view a presentation on how Pact can work in a mobile context here: Yow! Connected 2016 Andrew Spinks - Increasing The Confidence In Your Service Integrations.

Implements Pact Specification v2,
including flexible matching.

This DSL relies on the Ruby pact-ruby-standalone (brew tap) to provide the mock service for the tests.

Installation

Note: see Upgrading for notes on upgrading from 0.2 to 0.3

Install Pact Mock Service

Homebrew

  1. brew tap pact-foundation/pact-ruby-standalone
  2. brew install pact-ruby-standalone

This will install the following tools:

  1. pact
  2. pact-broker
  3. pact-message
  4. pact-mock-service
  5. pact-provider-verifier
  6. pact-publish
  7. pact-stub-service

Manually

Alternatively you can download and install the pact-ruby-standalone archives for your platform and install as per installation instructions written in Pact Ruby Standalone release notes.

Xcode Setup

In Xcode, edit your scheme and add pre- and post-actions to Test to start and stop pact-mock-service. Make sure you select your target in Provide build settings from the drop down menu.

  1. # Pre-actions
  2. PATH=/path/to/your/standalone/pact/bin:$PATH
  3. pact-mock-service start --pact-specification-version 2.0.0 --log "${SRCROOT}/tmp/pact.log" --pact-dir "${SRCROOT}/tmp/pacts" -p 1234
  4. # Post-actions
  5. PATH=/path/to/your/standalone/pact/bin:$PATH
  6. pact-mock-service stop

Note: your generated Pact files will be dropped into "${SRCROOT}/tmp/pacts" folder.

Xcode Scheme Test Pre-actions

Add the PactConsumerSwift library to your project

Using Carthage

  • See the PactSwiftExample Swift, Carthage Example - Build Status for an example project using pact-consumer-swift with Carthage for an iOS target.
  • See the PactMacOSExample Build for an example project using pact-consumer-swift through Carthage for a macOS target.

Using CocoaPods

  • See the PactObjectiveCExample Build Status for an example project using pact-consumer-swift with CocoaPods for an iOS target.

Using Swift Package Manager

  • See the PactSwiftPMExample Build for an example project using pact-consumer-swift library through Swift Package Manager for an executable that runs in terminal.

Writing Pact Tests

Testing with Swift

Write a Unit test similar to the following (NB: this example is using the Quick test framework)

  1. import PactConsumerSwift
  2. ...
  3. beforeEach {
  4. animalMockService = MockService(provider: "Animal Service", consumer: "Animal Consumer Swift")
  5. animalServiceClient = AnimalServiceClient(baseUrl: animalMockService!.baseUrl)
  6. }
  7. it("gets an alligator") {
  8. animalMockService!.given("an alligator exists")
  9. .uponReceiving("a request for an alligator")
  10. .withRequest(method:.GET, path: "/alligator")
  11. .willRespondWith(status:200,
  12. headers: ["Content-Type": "application/json"],
  13. body: ["name": "Mary"])
  14. //Run the tests
  15. animalMockService!.run { (testComplete) -> Void in
  16. animalServiceClient!.getAlligator { (alligator) in
  17. expect(alligator.name).to(equal("Mary"))
  18. testComplete()
  19. }
  20. }
  21. }

An optional timeout (seconds) parameter can be included on the run function. This defaults to 30 seconds.

  1. ...
  2. animalMockService!.run(timeout: 60) { (testComplete) -> Void in
  3. animalServiceClient!.getAlligator { (alligator) in
  4. expect(alligator.name).to(equal("Mary"))
  5. testComplete()
  6. }
  7. }

Testing with Objective-C

Write a Unit test similar to the following

  1. @import PactConsumerSwift;
  2. ...
  3. - (void)setUp {
  4. [super setUp];
  5. self.animalMockService = [[MockService alloc] initWithProvider:@"Animal Provider"
  6. consumer:@"Animal Service Client Objective-C"];
  7. self.animalServiceClient = [[OCAnimalServiceClient alloc] initWithBaseUrl:self.animalMockService.baseUrl];
  8. }
  9. - (void)testGetAlligator {
  10. typedef void (^CompleteBlock)();
  11. [[[[self.animalMockService given:@"an alligator exists"]
  12. uponReceiving:@"oc a request for an alligator"]
  13. withRequestHTTPMethod:PactHTTPMethodGET
  14. path:@"/alligator"
  15. query:nil headers:nil body:nil]
  16. willRespondWithHTTPStatus:200
  17. headers:@{@"Content-Type": @"application/json"}
  18. body: @"{ \"name\": \"Mary\"}" ];
  19. [self.animalMockService run:^(CompleteBlock testComplete) {
  20. Animal *animal = [self.animalServiceClient getAlligator];
  21. XCTAssertEqualObjects(animal.name, @"Mary");
  22. testComplete();
  23. }];
  24. }

An optional timeout (seconds) parameter can be included on the run function. This defaults to 30 seconds.

  1. ...
  2. [self.animalMockService run:^(CompleteBlock testComplete) {
  3. Animal *animal = [self.animalServiceClient getAlligator];
  4. XCTAssertEqualObjects(animal.name, @"Mary");
  5. testComplete();
  6. } timeout:60];
  7. }

Testing with XCTest

Write a Unit Test similar to the following:

  1. import PactConsumerSwift
  2. ...
  3. var animalMockService: MockService?
  4. var animalServiceClient: AnimalServiceClient?
  5. override func setUp() {
  6. super.setUp()
  7. animalMockService = MockService(provider: "Animal Provider", consumer: "Animal Service Client")
  8. animalServiceClient = AnimalServiceClient(baseUrl: animalMockService!.baseUrl)
  9. }
  10. func testItGetsAlligator() {
  11. // Prepare the expecated behaviour using pact's MockService
  12. animalMockService!
  13. .given("an alligator exists")
  14. .uponReceiving("a request for alligator")
  15. .withRequest(method: .GET, path: "/alligator")
  16. .willRespondWith(status: 200,
  17. headers: ["Content-Type": "application/json"],
  18. body: [ "name": "Mary" ])
  19. // Run the test
  20. animalMockService!.run(timeout: 60) { (testComplete) -> Void in
  21. self.animalServiceClient!.getAlligator { (response) -> in
  22. XCTAssertEqual(response.name, "Mary")
  23. testComplete()
  24. }
  25. }
  26. }
  27. ...

An optional timeout (seconds) parameter can be included on the run function. Defaults to 30 seconds.

  1. ...
  2. // Run the test
  3. animalMockService!.run(timeout: 60) { (testComplete) -> Void in
  4. self.animalServiceClient!.getAlligator { (response) -> in
  5. XCTAssertEqual(response.name, "Mary")
  6. testComplete()
  7. }
  8. }

For an example on how to test over https see PactSSLSpec.swift.

Matching

In addition to verbatim value matching, you have 3 useful matching functions
in the Matcher class that can increase expressiveness and reduce brittle test
cases.

  • Matcher.term(matcher, generate) - tells Pact that the value should match using
    a given regular expression, using generate in mock responses. generate must be
    a string.
  • Matcher.somethingLike(content) - tells Pact that the value itself is not important, as long
    as the element type (valid JSON number, string, object etc.) itself matches.
  • Matcher.eachLike(content, min) - tells Pact that the value should be an array type,
    consisting of elements like those passed in. min must be >= 1. content may
    be a valid JSON value: e.g. strings, numbers and objects.

NOTE: One caveat to note, is that you will need to use valid Ruby regular expressions and double escape backslashes.

See the PactSpecs.swift, PactObjectiveCTests.m for examples on how to expect error responses, how to use query params, and Matchers.

For more on request / response matching, see [Matching][getting_started/matching].

Using in your CI

Xcode’s pre-actions and post-actions do not honour non-zero script exits and therefore would not fail your build if publishing to a Pact Broker would fail. If you would like to upload your Pact files to a Pact Broker as part of your CI, we would suggest that you create a separate step in your CI workflow with that responsibility.

See pact-ruby-standalone page for installation instructions and how to use pact-broker client.

Verifying your client against the service you are integrating with

If your setup is correct and your tests run against the pack mock server, then you should see a log file here:
$YOUR_PROJECT/tmp/pact.log
And the generated pacts here:
$YOUR_PROJECT/tmp/pacts/...

Publish your generated pact file(s) to your Pact Broker or a Hosted Pact Broker so your API provider can always retrieve them from one location, even when pacts change. Or even just by simply sending the pact file to your API provider devs so they can used them in their tests of their API responses. See Verifying pacts for more information.
For an end-to-end example with a ruby back end service, have a look at the KatKit example.

Also, check out this article on @rajatvig/ios-docker-and-consumer-driven-contract-testing-with-pact-d99b6bf4b09e#.ozcbbktzk">using a dockerized Node.js service that uses provider states.

More reading

  • The Pact website Pact
  • The pact mock server that the Swift library uses under the hood Pact mock service
  • A pact broker for managing the generated pact files (so you don’t have to manually copy them around!) Pact broker

Contributing

Please read CONTRIBUTING.md