├── provider
├── spec
│ ├── pacts
│ │ └── .gitkeep
│ ├── spec_helper.rb
│ └── pact_helper.rb
├── .ruby-gemset
├── .ruby-version
├── .gitignore
├── .rspec
├── config.ru
├── Gemfile
├── Rakefile
├── lib
│ └── provider.rb
└── Gemfile.lock
├── consumer
├── app
│ ├── .gitignore
│ ├── src
│ │ ├── main
│ │ │ ├── java
│ │ │ │ └── au
│ │ │ │ │ └── com
│ │ │ │ │ └── dius
│ │ │ │ │ └── pactconsumer
│ │ │ │ │ ├── app
│ │ │ │ │ ├── PactView.java
│ │ │ │ │ ├── PactPresenter.java
│ │ │ │ │ ├── di
│ │ │ │ │ │ ├── ApplicationComponent.java
│ │ │ │ │ │ ├── ApplicationModule.java
│ │ │ │ │ │ └── NetworkModule.java
│ │ │ │ │ ├── PactApplication.java
│ │ │ │ │ └── PactActivity.java
│ │ │ │ │ ├── data
│ │ │ │ │ ├── exceptions
│ │ │ │ │ │ ├── ServiceException.java
│ │ │ │ │ │ └── BadRequestException.java
│ │ │ │ │ ├── Repository.java
│ │ │ │ │ ├── FakeService.java
│ │ │ │ │ ├── model
│ │ │ │ │ │ ├── Animal.java
│ │ │ │ │ │ └── ServiceResponse.java
│ │ │ │ │ └── Service.java
│ │ │ │ │ ├── domain
│ │ │ │ │ ├── Contract.java
│ │ │ │ │ ├── Presenter.java
│ │ │ │ │ └── ViewState.java
│ │ │ │ │ ├── util
│ │ │ │ │ ├── Logger.java
│ │ │ │ │ ├── DateHelper.java
│ │ │ │ │ └── RxBinder.java
│ │ │ │ │ └── presentation
│ │ │ │ │ ├── AnimalsAdapter.java
│ │ │ │ │ └── HomeActivity.java
│ │ │ ├── res
│ │ │ │ ├── mipmap-hdpi
│ │ │ │ │ └── ic_launcher.png
│ │ │ │ ├── mipmap-mdpi
│ │ │ │ │ └── ic_launcher.png
│ │ │ │ ├── mipmap-xhdpi
│ │ │ │ │ └── ic_launcher.png
│ │ │ │ ├── mipmap-xxhdpi
│ │ │ │ │ └── ic_launcher.png
│ │ │ │ ├── mipmap-xxxhdpi
│ │ │ │ │ └── ic_launcher.png
│ │ │ │ ├── values
│ │ │ │ │ ├── dimens.xml
│ │ │ │ │ ├── colors.xml
│ │ │ │ │ ├── strings.xml
│ │ │ │ │ └── styles.xml
│ │ │ │ ├── menu
│ │ │ │ │ └── menu_animals.xml
│ │ │ │ ├── layout
│ │ │ │ │ ├── activity_animals.xml
│ │ │ │ │ ├── layout_animal.xml
│ │ │ │ │ └── content_animals.xml
│ │ │ │ └── drawable
│ │ │ │ │ ├── bird.xml
│ │ │ │ │ ├── dog.xml
│ │ │ │ │ └── cat.xml
│ │ │ └── AndroidManifest.xml
│ │ └── test
│ │ │ └── java
│ │ │ └── au
│ │ │ └── com
│ │ │ └── dius
│ │ │ └── pactconsumer
│ │ │ ├── data
│ │ │ ├── FakeServiceTest.java
│ │ │ ├── ServiceTest.java
│ │ │ ├── ServiceMissingQueryPactTest.java
│ │ │ ├── ServiceNoContentPactTest.java
│ │ │ └── ServicePactTest.java
│ │ │ ├── util
│ │ │ └── TestRxBinder.java
│ │ │ └── domain
│ │ │ └── PresenterTest.java
│ ├── proguard-rules.pro
│ └── build.gradle
├── settings.gradle
├── .idea
│ ├── copyright
│ │ └── profiles_settings.xml
│ ├── vcs.xml
│ ├── modules.xml
│ ├── runConfigurations.xml
│ ├── gradle.xml
│ ├── compiler.xml
│ └── misc.xml
├── gradle
│ └── wrapper
│ │ ├── gradle-wrapper.jar
│ │ └── gradle-wrapper.properties
├── .gitignore
├── build.gradle
├── gradle.properties
├── gradlew.bat
└── gradlew
├── LICENSE
└── README.md
/provider/spec/pacts/.gitkeep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/consumer/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/provider/.ruby-gemset:
--------------------------------------------------------------------------------
1 | example_pact
2 |
--------------------------------------------------------------------------------
/provider/.ruby-version:
--------------------------------------------------------------------------------
1 | ruby-2.3.0
2 |
--------------------------------------------------------------------------------
/consumer/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------
/provider/spec/spec_helper.rb:
--------------------------------------------------------------------------------
1 | require 'ap'
2 |
--------------------------------------------------------------------------------
/provider/.gitignore:
--------------------------------------------------------------------------------
1 | log/
2 | reports/
3 | spec/pacts/*
4 |
--------------------------------------------------------------------------------
/provider/.rspec:
--------------------------------------------------------------------------------
1 | --color
2 | --format documentation
3 |
--------------------------------------------------------------------------------
/provider/config.ru:
--------------------------------------------------------------------------------
1 | #\ -w -p 4567
2 | require './lib/provider'
3 | run Provider
4 |
--------------------------------------------------------------------------------
/consumer/.idea/copyright/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/consumer/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DiUS/pact-workshop-android/HEAD/consumer/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/consumer/app/src/main/java/au/com/dius/pactconsumer/app/PactView.java:
--------------------------------------------------------------------------------
1 | package au.com.dius.pactconsumer.app;
2 |
3 | public interface PactView {
4 | }
5 |
--------------------------------------------------------------------------------
/consumer/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DiUS/pact-workshop-android/HEAD/consumer/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/consumer/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DiUS/pact-workshop-android/HEAD/consumer/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/consumer/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DiUS/pact-workshop-android/HEAD/consumer/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/consumer/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DiUS/pact-workshop-android/HEAD/consumer/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/consumer/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DiUS/pact-workshop-android/HEAD/consumer/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/consumer/app/src/main/java/au/com/dius/pactconsumer/app/PactPresenter.java:
--------------------------------------------------------------------------------
1 | package au.com.dius.pactconsumer.app;
2 |
3 |
4 | public interface PactPresenter {
5 | void onStart();
6 | void onStop();
7 | }
8 |
--------------------------------------------------------------------------------
/consumer/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/consumer/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 | .externalNativeBuild
10 | app/target/pacts/*
11 | app/okhttp_cache/
12 |
--------------------------------------------------------------------------------
/provider/Gemfile:
--------------------------------------------------------------------------------
1 | source 'https://rubygems.org'
2 |
3 | gem 'rake'
4 | gem 'activesupport'
5 | gem 'rack'
6 | gem 'sinatra'
7 |
8 | group :development, :test do
9 | gem 'pry'
10 | gem 'rspec'
11 | gem 'awesome_print'
12 | gem 'pact'
13 | end
14 |
--------------------------------------------------------------------------------
/consumer/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 | 180dp
3 | 8dp
4 | 8dp
5 | 100dp
6 |
7 |
--------------------------------------------------------------------------------
/consumer/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/consumer/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Dec 28 10:00:20 PST 2015
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
7 |
--------------------------------------------------------------------------------
/consumer/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | PactConsumer
3 | Settings
4 | Oops, something went wrong
5 | No animals found
6 |
7 |
--------------------------------------------------------------------------------
/consumer/app/src/main/java/au/com/dius/pactconsumer/data/exceptions/ServiceException.java:
--------------------------------------------------------------------------------
1 | package au.com.dius.pactconsumer.data.exceptions;
2 |
3 | public class ServiceException extends RuntimeException {
4 |
5 | public ServiceException() { }
6 |
7 | public ServiceException(String message, Throwable cause) {
8 | super(message, cause);
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/consumer/app/src/main/java/au/com/dius/pactconsumer/data/exceptions/BadRequestException.java:
--------------------------------------------------------------------------------
1 | package au.com.dius.pactconsumer.data.exceptions;
2 |
3 | public class BadRequestException extends ServiceException {
4 |
5 | public BadRequestException() { }
6 |
7 | public BadRequestException(String message, Throwable cause) {
8 | super(message, cause);
9 | }
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/consumer/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/consumer/app/src/main/java/au/com/dius/pactconsumer/data/Repository.java:
--------------------------------------------------------------------------------
1 | package au.com.dius.pactconsumer.data;
2 |
3 | import android.support.annotation.NonNull;
4 |
5 | import org.joda.time.DateTime;
6 |
7 | import au.com.dius.pactconsumer.data.model.ServiceResponse;
8 | import io.reactivex.Single;
9 |
10 | public interface Repository {
11 |
12 | @NonNull
13 | Single fetchResponse(@NonNull DateTime dateTime);
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/consumer/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 |
3 | repositories {
4 | jcenter()
5 | }
6 |
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:2.2.3'
9 | classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
10 | classpath 'me.tatarka:gradle-retrolambda:3.3.0'
11 | }
12 |
13 | }
14 |
15 | allprojects {
16 | repositories {
17 | jcenter()
18 | }
19 | }
20 |
21 | task clean(type: Delete) {
22 | delete rootProject.buildDir
23 | }
24 |
--------------------------------------------------------------------------------
/consumer/app/src/main/java/au/com/dius/pactconsumer/domain/Contract.java:
--------------------------------------------------------------------------------
1 | package au.com.dius.pactconsumer.domain;
2 |
3 | import android.support.annotation.NonNull;
4 |
5 | import au.com.dius.pactconsumer.app.PactPresenter;
6 | import au.com.dius.pactconsumer.app.PactView;
7 |
8 | public interface Contract {
9 |
10 | interface View extends PactView {
11 | void setViewState(@NonNull ViewState viewState);
12 | }
13 |
14 | interface Presenter extends PactPresenter {
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/provider/Rakefile:
--------------------------------------------------------------------------------
1 | # encoding: utf-8
2 |
3 | require 'rubygems'
4 | require 'bundler'
5 |
6 | begin
7 | Bundler.setup(:default, :development)
8 | rescue Bundler::BundlerError => e
9 | $stderr.puts e.message
10 | $stderr.puts "Run `bundle install` to install missing gems"
11 | exit e.status_code
12 | end
13 |
14 | require 'rake'
15 | require 'rspec/core/rake_task'
16 | RSpec::Core::RakeTask.new(:spec)
17 |
18 | require 'pact/tasks'
19 |
20 | task :default => [:spec]
21 |
22 | $:.unshift 'lib'
23 |
--------------------------------------------------------------------------------
/consumer/app/src/main/res/menu/menu_animals.xml:
--------------------------------------------------------------------------------
1 |
11 |
--------------------------------------------------------------------------------
/consumer/app/src/main/java/au/com/dius/pactconsumer/util/Logger.java:
--------------------------------------------------------------------------------
1 | package au.com.dius.pactconsumer.util;
2 |
3 | import android.support.annotation.NonNull;
4 | import android.util.Log;
5 |
6 | import javax.inject.Inject;
7 | import javax.inject.Singleton;
8 |
9 | @Singleton
10 | public class Logger {
11 |
12 | @Inject
13 | public Logger() {
14 | }
15 |
16 | public void d(@NonNull String tag, @NonNull String msg) {
17 | Log.d(tag, msg);
18 | }
19 |
20 | public void e(@NonNull String tag, @NonNull String msg, @NonNull Throwable tr) {
21 | Log.e(tag, msg, tr);
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/provider/spec/pact_helper.rb:
--------------------------------------------------------------------------------
1 | require 'pact/provider/rspec'
2 |
3 | Pact.service_provider "our_provider" do
4 |
5 | honours_pact_with 'our_consumer' do
6 | pact_uri URI.encode('https://test.pact.dius.com.au/pact/provider/our_provider/consumer/our_consumer/latest')
7 | end
8 |
9 | end
10 |
11 | Pact.provider_states_for "our_consumer" do
12 |
13 | provider_state "data count is > 0" do
14 | set_up do
15 | ProviderData.animals = ANIMALS_LIST
16 | end
17 | end
18 |
19 | provider_state "data count is == 0" do
20 | set_up do
21 | ProviderData.animals = []
22 | end
23 | end
24 |
25 | end
26 |
--------------------------------------------------------------------------------
/consumer/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
12 |
--------------------------------------------------------------------------------
/consumer/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/consumer/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /home/theeban/Android/Sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/consumer/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/ApplicationComponent.java:
--------------------------------------------------------------------------------
1 | package au.com.dius.pactconsumer.app.di;
2 |
3 | import android.content.Context;
4 | import android.support.annotation.NonNull;
5 |
6 | import javax.inject.Singleton;
7 |
8 | import au.com.dius.pactconsumer.data.Repository;
9 | import au.com.dius.pactconsumer.presentation.HomeActivity;
10 | import au.com.dius.pactconsumer.util.Logger;
11 | import dagger.Component;
12 |
13 | @Singleton
14 | @Component(modules = {ApplicationModule.class, NetworkModule.class})
15 | public interface ApplicationComponent {
16 |
17 | @NonNull
18 | Context getContext();
19 |
20 | @NonNull
21 | Logger getLogger();
22 |
23 | @NonNull
24 | Repository getRepository();
25 |
26 | void inject(HomeActivity homeActivity);
27 | }
28 |
--------------------------------------------------------------------------------
/consumer/app/src/test/java/au/com/dius/pactconsumer/data/FakeServiceTest.java:
--------------------------------------------------------------------------------
1 | package au.com.dius.pactconsumer.data;
2 |
3 | import org.joda.time.DateTime;
4 | import org.junit.Before;
5 | import org.junit.Test;
6 |
7 | import au.com.dius.pactconsumer.data.model.ServiceResponse;
8 | import io.reactivex.observers.TestObserver;
9 |
10 | public class FakeServiceTest {
11 |
12 | FakeService service;
13 |
14 | @Before
15 | public void setUp() {
16 | service = new FakeService();
17 | }
18 |
19 | @Test
20 | public void should_return_list_of_animals() {
21 | // when
22 | TestObserver observer = service.fetchResponse(DateTime.now()).test();
23 |
24 | // then
25 | observer.assertNoErrors();
26 | observer.assertValue(FakeService.RESPONSE);
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/consumer/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/consumer/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/consumer/app/src/main/java/au/com/dius/pactconsumer/util/DateHelper.java:
--------------------------------------------------------------------------------
1 | package au.com.dius.pactconsumer.util;
2 |
3 | import android.support.annotation.NonNull;
4 | import android.support.annotation.Nullable;
5 |
6 | import org.joda.time.DateTime;
7 |
8 | import java.io.UnsupportedEncodingException;
9 | import java.net.URLEncoder;
10 |
11 | public final class DateHelper {
12 |
13 | private DateHelper() {
14 | }
15 |
16 | public static String encodeDate(@Nullable DateTime dateTime) throws UnsupportedEncodingException {
17 | if (dateTime == null) {
18 | return null;
19 | }
20 | return URLEncoder.encode(toString(dateTime), "UTF-8");
21 | }
22 |
23 | public static DateTime parse(@NonNull String value) {
24 | return DateTime.parse(value);
25 | }
26 |
27 | public static String toString(@NonNull DateTime value) {
28 | return value.toString();
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/provider/lib/provider.rb:
--------------------------------------------------------------------------------
1 | require 'sinatra/base'
2 | require 'json'
3 |
4 | ANIMALS_LIST = [
5 | {
6 | name: "Buddy",
7 | image: "dog"
8 | },
9 | {
10 | name: "Cathy",
11 | image: "cat"
12 | },
13 | {
14 | name: "Birdy",
15 | image: "bird"
16 | }
17 | ]
18 |
19 | class ProviderData
20 | @animals = ANIMALS_LIST
21 | class << self
22 | attr_accessor :animals
23 | end
24 | end
25 |
26 | class Provider < Sinatra::Base
27 |
28 | get '/provider.json', :provides => 'json' do
29 | if params[:valid_date].nil?
30 | [400, '"valid_date is required"']
31 | elsif ProviderData.animals.size == 0
32 | 404
33 | else
34 | valid_time = Time.parse(params[:valid_date])
35 | JSON.pretty_generate({
36 | :test => 'NO',
37 | :valid_date => DateTime.now,
38 | :animals => ProviderData.animals
39 | })
40 | end
41 | end
42 |
43 | end
44 |
--------------------------------------------------------------------------------
/consumer/app/src/main/res/layout/activity_animals.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/consumer/app/src/main/java/au/com/dius/pactconsumer/app/PactApplication.java:
--------------------------------------------------------------------------------
1 | package au.com.dius.pactconsumer.app;
2 |
3 | import android.app.Application;
4 | import android.support.annotation.NonNull;
5 |
6 | import au.com.dius.pactconsumer.app.di.ApplicationComponent;
7 | import au.com.dius.pactconsumer.app.di.ApplicationModule;
8 | import au.com.dius.pactconsumer.app.di.DaggerApplicationComponent;
9 |
10 | public class PactApplication extends Application {
11 |
12 | private ApplicationComponent applicationComponent;
13 |
14 | @Override
15 | public void onCreate() {
16 | super.onCreate();
17 | initialise();
18 | }
19 |
20 | private void initialise() {
21 | applicationComponent = DaggerApplicationComponent.builder()
22 | .applicationModule(new ApplicationModule(this))
23 | .build();
24 | }
25 |
26 | @NonNull
27 | public ApplicationComponent getApplicationComponent() {
28 | return applicationComponent;
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/ApplicationModule.java:
--------------------------------------------------------------------------------
1 | package au.com.dius.pactconsumer.app.di;
2 |
3 | import android.content.Context;
4 | import android.support.annotation.NonNull;
5 |
6 | import javax.inject.Singleton;
7 |
8 | import au.com.dius.pactconsumer.data.Repository;
9 | import au.com.dius.pactconsumer.data.Service;
10 | import dagger.Module;
11 | import dagger.Provides;
12 | import retrofit2.Retrofit;
13 |
14 | @Module
15 | public class ApplicationModule {
16 |
17 | private final Context context;
18 |
19 | public ApplicationModule(@NonNull Context context) {
20 | this.context = context;
21 | }
22 |
23 | @Singleton
24 | @Provides
25 | @NonNull
26 | public Context getContext() {
27 | return context;
28 | }
29 |
30 | @Singleton
31 | @Provides
32 | @NonNull
33 | public Repository getRepository(@NonNull Retrofit retrofit) {
34 | return new Service(retrofit.create(Service.Api.class));
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/consumer/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
15 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/consumer/app/src/main/java/au/com/dius/pactconsumer/app/PactActivity.java:
--------------------------------------------------------------------------------
1 | package au.com.dius.pactconsumer.app;
2 |
3 | import android.app.Application;
4 | import android.os.Bundle;
5 | import android.support.annotation.NonNull;
6 | import android.support.annotation.Nullable;
7 | import android.support.v7.app.AppCompatActivity;
8 |
9 | import au.com.dius.pactconsumer.app.di.ApplicationComponent;
10 |
11 | public abstract class PactActivity extends AppCompatActivity {
12 |
13 | @Override
14 | protected void onCreate(@Nullable Bundle savedInstanceState) {
15 | super.onCreate(savedInstanceState);
16 | inject(getPactApplication().getApplicationComponent());
17 | }
18 |
19 | public abstract void inject(@NonNull ApplicationComponent component);
20 |
21 | public PactApplication getPactApplication() {
22 | Application application = getApplication();
23 | if (application instanceof PactApplication) {
24 | return (PactApplication) application;
25 | }
26 | throw new IllegalStateException("Activity " + this.getClass() + " must have a pact application");
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/consumer/app/src/main/java/au/com/dius/pactconsumer/data/FakeService.java:
--------------------------------------------------------------------------------
1 | package au.com.dius.pactconsumer.data;
2 |
3 | import android.support.annotation.NonNull;
4 |
5 | import org.joda.time.DateTime;
6 |
7 | import java.util.Arrays;
8 |
9 | import javax.inject.Inject;
10 | import javax.inject.Singleton;
11 |
12 | import au.com.dius.pactconsumer.data.model.Animal;
13 | import au.com.dius.pactconsumer.data.model.ServiceResponse;
14 | import io.reactivex.Single;
15 |
16 | @Singleton
17 | public class FakeService implements Repository {
18 |
19 | public static final ServiceResponse RESPONSE;
20 |
21 | static {
22 | RESPONSE = new ServiceResponse(
23 | DateTime.now(),
24 | Arrays.asList(
25 | Animal.create("Doggy", "dog"),
26 | Animal.create("Cathy", "cat"),
27 | Animal.create("Birdy", "bird")
28 | )
29 | );
30 | }
31 |
32 | @Inject
33 | public FakeService() {
34 | }
35 |
36 | @NonNull
37 | @Override
38 | public Single fetchResponse(@NonNull DateTime dateTime) {
39 | return Single.just(RESPONSE);
40 | }
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/consumer/app/src/test/java/au/com/dius/pactconsumer/data/ServiceTest.java:
--------------------------------------------------------------------------------
1 | package au.com.dius.pactconsumer.data;
2 |
3 | import org.joda.time.DateTime;
4 | import org.junit.Before;
5 | import org.junit.Test;
6 |
7 | import java.util.Collections;
8 |
9 | import au.com.dius.pactconsumer.data.model.Animal;
10 | import au.com.dius.pactconsumer.data.model.ServiceResponse;
11 | import io.reactivex.Single;
12 | import io.reactivex.observers.TestObserver;
13 |
14 | import static org.mockito.ArgumentMatchers.any;
15 | import static org.mockito.Mockito.mock;
16 | import static org.mockito.Mockito.when;
17 |
18 | public class ServiceTest {
19 |
20 | Service.Api api;
21 | Service service;
22 |
23 | @Before
24 | public void setup() {
25 | api = mock(Service.Api.class);
26 | service = new Service(api);
27 | }
28 |
29 | @Test
30 | public void should_process_json_payload_from_provider() {
31 | // given
32 | ServiceResponse response = ServiceResponse.create(DateTime.now(), Collections.singletonList(Animal.create("Doggy", "dog")));
33 | when(api.loadProviderJson(any())).thenReturn(Single.just(response));
34 |
35 | // when
36 | TestObserver observer = service.fetchResponse(DateTime.now()).test();
37 |
38 | // then
39 | observer.assertNoErrors();
40 | observer.assertValue(response);
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/consumer/app/src/main/res/layout/layout_animal.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
15 |
23 |
32 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/Animal.java:
--------------------------------------------------------------------------------
1 | package au.com.dius.pactconsumer.data.model;
2 |
3 |
4 | import android.support.annotation.NonNull;
5 |
6 | import com.squareup.moshi.Json;
7 |
8 | public class Animal {
9 |
10 | @Json(name = "name")
11 | private final String name;
12 |
13 | @Json(name = "image")
14 | private final String image;
15 |
16 | public Animal(@NonNull String name, @NonNull String image) {
17 | this.name = name;
18 | this.image = image;
19 | }
20 |
21 | @NonNull
22 | public String getName() {
23 | return name;
24 | }
25 |
26 | @NonNull
27 | public String getType() {
28 | return image;
29 | }
30 |
31 | @Override
32 | public boolean equals(Object o) {
33 | if (this == o) return true;
34 | if (o == null || getClass() != o.getClass()) return false;
35 |
36 | Animal animal = (Animal) o;
37 |
38 | if (name != null ? !name.equals(animal.name) : animal.name != null) return false;
39 | return image != null ? image.equals(animal.image) : animal.image == null;
40 |
41 | }
42 |
43 | @Override
44 | public int hashCode() {
45 | int result = name != null ? name.hashCode() : 0;
46 | result = 31 * result + (image != null ? image.hashCode() : 0);
47 | return result;
48 | }
49 |
50 | @Override
51 | public String toString() {
52 | return "Animal{" +
53 | "name='" + name + '\'' +
54 | ", image='" + image + '\'' +
55 | '}';
56 | }
57 |
58 | public static Animal create(@NonNull String name, @NonNull String image) {
59 | return new Animal(name, image);
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/consumer/app/src/test/java/au/com/dius/pactconsumer/util/TestRxBinder.java:
--------------------------------------------------------------------------------
1 | package au.com.dius.pactconsumer.util;
2 |
3 | import io.reactivex.Observable;
4 | import io.reactivex.exceptions.Exceptions;
5 | import io.reactivex.functions.Action;
6 | import io.reactivex.functions.Consumer;
7 | import io.reactivex.observers.DisposableObserver;
8 |
9 | public class TestRxBinder extends RxBinder {
10 |
11 | @Override
12 | public void bind(Observable observable,
13 | Consumer onNext,
14 | Consumer onError,
15 | Action onComplete) {
16 | observable
17 | .subscribeWith(new DisposableObserver() {
18 |
19 | @Override
20 | public void onNext(T o) {
21 | try {
22 | onNext.accept(o);
23 | } catch (Exception e) {
24 | e.printStackTrace();
25 | }
26 | }
27 |
28 | @Override
29 | public void onError(Throwable thr) {
30 | if (!(thr instanceof Exception)) {
31 | Exceptions.throwIfFatal(thr);
32 | return;
33 | }
34 |
35 | try {
36 | onError.accept((Exception) thr);
37 | } catch (Exception e) {
38 | e.printStackTrace();
39 | }
40 | }
41 |
42 | @Override
43 | public void onComplete() {
44 | try {
45 | onComplete.run();
46 | } catch (Exception e) {
47 | e.printStackTrace();
48 | }
49 | }
50 | });
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/consumer/app/src/main/res/layout/content_animals.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
18 |
19 |
26 |
27 |
36 |
37 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/consumer/app/src/main/java/au/com/dius/pactconsumer/presentation/AnimalsAdapter.java:
--------------------------------------------------------------------------------
1 | package au.com.dius.pactconsumer.presentation;
2 |
3 | import android.content.Context;
4 | import android.support.annotation.NonNull;
5 | import android.support.v7.widget.RecyclerView;
6 | import android.view.LayoutInflater;
7 | import android.view.View;
8 | import android.view.ViewGroup;
9 | import android.widget.ImageView;
10 | import android.widget.TextView;
11 |
12 | import java.util.List;
13 |
14 | import au.com.dius.pactconsumer.R;
15 | import au.com.dius.pactconsumer.data.model.Animal;
16 |
17 | public class AnimalsAdapter extends RecyclerView.Adapter {
18 |
19 | private final List animals;
20 |
21 | public AnimalsAdapter(@NonNull List animals) {
22 | this.animals = animals;
23 | }
24 |
25 | @Override
26 | public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
27 | return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_animal, parent, false));
28 | }
29 |
30 | @Override
31 | public void onBindViewHolder(ViewHolder holder, int position) {
32 | Animal animal = animals.get(position);
33 | holder.titleView.setText(animal.getName());
34 | Context context = holder.itemView.getContext();
35 | int id = holder.itemView.getContext().getResources().getIdentifier(animal.getType(), "drawable", context.getPackageName());
36 | holder.imageView.setImageDrawable(context.getResources().getDrawable(id, null));
37 | }
38 |
39 | @Override
40 | public int getItemCount() {
41 | return animals.size();
42 | }
43 |
44 | public static class ViewHolder extends RecyclerView.ViewHolder {
45 |
46 | public ImageView imageView;
47 | public TextView titleView;
48 |
49 | public ViewHolder(View itemView) {
50 | super(itemView);
51 | imageView = (ImageView) itemView.findViewById(R.id.img_animal);
52 | titleView = (TextView) itemView.findViewById(R.id.txt_title);
53 | }
54 |
55 | }
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java:
--------------------------------------------------------------------------------
1 | package au.com.dius.pactconsumer.data.model;
2 |
3 | import android.support.annotation.NonNull;
4 | import android.support.annotation.Nullable;
5 |
6 | import com.squareup.moshi.Json;
7 |
8 | import org.joda.time.DateTime;
9 |
10 | import java.util.List;
11 |
12 | public class ServiceResponse {
13 |
14 | @Json(name = "valid_date")
15 | private final DateTime validDate;
16 |
17 | @Json(name = "animals")
18 | private final List animals;
19 |
20 | public ServiceResponse(@Nullable DateTime validDate,
21 | @NonNull List animals) {
22 | this.validDate = validDate;
23 | this.animals = animals;
24 | }
25 |
26 | @Nullable
27 | public DateTime getValidDate() {
28 | return validDate;
29 | }
30 |
31 | @NonNull
32 | public List getAnimals() {
33 | return animals;
34 | }
35 |
36 | @Override
37 | public boolean equals(Object o) {
38 | if (this == o) return true;
39 | if (o == null || getClass() != o.getClass()) return false;
40 |
41 | ServiceResponse that = (ServiceResponse) o;
42 |
43 | long millis = validDate != null ? validDate.getMillis() : -1;
44 | long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1;
45 | if (millis != thatMillis)
46 | return false;
47 |
48 | return animals != null ? animals.equals(that.animals) : that.animals == null;
49 | }
50 |
51 | @Override
52 | public int hashCode() {
53 | int result = validDate != null ? validDate.hashCode() : 0;
54 | result = 31 * result + (animals != null ? animals.hashCode() : 0);
55 | return result;
56 | }
57 |
58 | @Override
59 | public String toString() {
60 | return "ServiceResponse{" +
61 | "validDate=" + validDate +
62 | ", animals=" + animals +
63 | '}';
64 | }
65 |
66 | public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List animals) {
67 | return new ServiceResponse(validDate, animals);
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/consumer/app/src/test/java/au/com/dius/pactconsumer/data/ServiceMissingQueryPactTest.java:
--------------------------------------------------------------------------------
1 | package au.com.dius.pactconsumer.data;
2 |
3 |
4 | import android.content.Context;
5 |
6 | import org.junit.Before;
7 | import org.junit.Rule;
8 | import org.junit.Test;
9 |
10 | import java.io.UnsupportedEncodingException;
11 |
12 | import au.com.dius.pact.consumer.Pact;
13 | import au.com.dius.pact.consumer.PactProviderRule;
14 | import au.com.dius.pact.consumer.PactVerification;
15 | import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
16 | import au.com.dius.pact.model.PactFragment;
17 | import au.com.dius.pactconsumer.app.di.NetworkModule;
18 | import au.com.dius.pactconsumer.data.exceptions.BadRequestException;
19 | import au.com.dius.pactconsumer.data.model.ServiceResponse;
20 | import io.reactivex.observers.TestObserver;
21 |
22 | import static org.mockito.Mockito.mock;
23 |
24 | public class ServiceMissingQueryPactTest {
25 |
26 | Service service;
27 |
28 | @Before
29 | public void setUp() {
30 | NetworkModule networkModule = new NetworkModule();
31 | service = new Service(networkModule.getRetrofit(mock(Context.class), "http://localhost:9292").create(Service.Api.class));
32 | }
33 |
34 | @Rule
35 | public PactProviderRule mockProvider = new PactProviderRule("our_provider", "localhost", 9292, this);
36 |
37 | @Pact(provider = "our_provider", consumer = "our_consumer")
38 | public PactFragment createFragment(PactDslWithProvider builder) throws UnsupportedEncodingException {
39 | return builder
40 | .given("data count is > 0")
41 | .uponReceiving("a request with an missing date parameter")
42 | .path("/provider.json")
43 | .method("GET")
44 | .willRespondWith()
45 | .status(400)
46 | .body("valid_date is required")
47 | .toFragment();
48 | }
49 |
50 | @Test
51 | @PactVerification("our_provider")
52 | public void should_process_the_json_payload_from_provider() {
53 | TestObserver observer = service.fetchResponse(null).test();
54 | observer.assertError(BadRequestException.class);
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/consumer/app/src/main/java/au/com/dius/pactconsumer/data/Service.java:
--------------------------------------------------------------------------------
1 | package au.com.dius.pactconsumer.data;
2 |
3 | import android.support.annotation.NonNull;
4 |
5 | import com.jakewharton.retrofit2.adapter.rxjava2.HttpException;
6 |
7 | import org.joda.time.DateTime;
8 |
9 | import java.io.UnsupportedEncodingException;
10 | import java.util.Collections;
11 |
12 | import javax.inject.Inject;
13 | import javax.inject.Singleton;
14 |
15 | import au.com.dius.pactconsumer.data.exceptions.BadRequestException;
16 | import au.com.dius.pactconsumer.data.model.ServiceResponse;
17 | import au.com.dius.pactconsumer.util.DateHelper;
18 | import io.reactivex.Single;
19 | import retrofit2.http.GET;
20 | import retrofit2.http.Query;
21 |
22 | @Singleton
23 | public class Service implements Repository {
24 |
25 | private static final int BAD_REQUEST = 400;
26 | private static final int NOT_FOUND = 404;
27 |
28 | public interface Api {
29 | @GET("provider.json")
30 | Single loadProviderJson(@Query("valid_date") String validDate);
31 | }
32 |
33 | private final Api api;
34 |
35 | @Inject
36 | public Service(@NonNull Api api) {
37 | this.api = api;
38 | }
39 |
40 | @NonNull
41 | @Override
42 | public Single fetchResponse(@NonNull DateTime dateTime) {
43 | try {
44 | return api.loadProviderJson(DateHelper.encodeDate(dateTime))
45 | .onErrorResumeNext(this::mapError);
46 | } catch (UnsupportedEncodingException e) {
47 | return Single.error(e);
48 | }
49 | }
50 |
51 | private Single mapError(Throwable throwable) {
52 | if (!(throwable instanceof HttpException)) {
53 | return Single.error(throwable);
54 | }
55 |
56 | HttpException exception = (HttpException) throwable;
57 | if (exception.code() == NOT_FOUND) {
58 | return Single.just(new ServiceResponse(null, Collections.emptyList()));
59 | } else if (exception.code() == BAD_REQUEST) {
60 | return Single.error(new BadRequestException(exception.message(), exception));
61 | }
62 | return Single.error(throwable);
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/consumer/app/src/test/java/au/com/dius/pactconsumer/data/ServiceNoContentPactTest.java:
--------------------------------------------------------------------------------
1 | package au.com.dius.pactconsumer.data;
2 |
3 |
4 | import android.content.Context;
5 |
6 | import org.joda.time.DateTime;
7 | import org.junit.Before;
8 | import org.junit.Rule;
9 | import org.junit.Test;
10 |
11 | import java.io.UnsupportedEncodingException;
12 | import java.util.Collections;
13 |
14 | import au.com.dius.pact.consumer.Pact;
15 | import au.com.dius.pact.consumer.PactProviderRule;
16 | import au.com.dius.pact.consumer.PactVerification;
17 | import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
18 | import au.com.dius.pact.model.PactFragment;
19 | import au.com.dius.pactconsumer.app.di.NetworkModule;
20 | import au.com.dius.pactconsumer.data.model.ServiceResponse;
21 | import au.com.dius.pactconsumer.util.DateHelper;
22 | import io.reactivex.observers.TestObserver;
23 |
24 | import static org.mockito.Mockito.mock;
25 |
26 | public class ServiceNoContentPactTest {
27 |
28 | static final DateTime DATE_TIME;
29 |
30 | static {
31 | DATE_TIME = DateTime.now();
32 | }
33 |
34 | Service service;
35 |
36 | @Before
37 | public void setUp() {
38 | NetworkModule networkModule = new NetworkModule();
39 | service = new Service(networkModule.getRetrofit(mock(Context.class), "http://localhost:9292").create(Service.Api.class));
40 | }
41 |
42 | @Rule
43 | public PactProviderRule mockProvider = new PactProviderRule("our_provider", "localhost", 9292, this);
44 |
45 | @Pact(provider = "our_provider", consumer = "our_consumer")
46 | public PactFragment createFragment(PactDslWithProvider builder) throws UnsupportedEncodingException {
47 | return builder
48 | .given("data count is == 0")
49 | .uponReceiving("a request for json data")
50 | .path("/provider.json")
51 | .method("GET")
52 | .query("valid_date=" + DateHelper.encodeDate(DATE_TIME))
53 | .willRespondWith()
54 | .status(404)
55 | .toFragment();
56 | }
57 |
58 | @Test
59 | @PactVerification("our_provider")
60 | public void should_process_the_json_payload_from_provider() {
61 | TestObserver observer = service.fetchResponse(DATE_TIME).test();
62 | observer.assertNoErrors();
63 | observer.assertValue(new ServiceResponse(null, Collections.emptyList()));
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/consumer/app/src/main/java/au/com/dius/pactconsumer/util/RxBinder.java:
--------------------------------------------------------------------------------
1 | package au.com.dius.pactconsumer.util;
2 |
3 |
4 | import android.util.Log;
5 |
6 | import io.reactivex.Observable;
7 | import io.reactivex.android.schedulers.AndroidSchedulers;
8 | import io.reactivex.disposables.CompositeDisposable;
9 | import io.reactivex.exceptions.Exceptions;
10 | import io.reactivex.functions.Action;
11 | import io.reactivex.functions.Consumer;
12 | import io.reactivex.observers.DisposableObserver;
13 | import io.reactivex.schedulers.Schedulers;
14 |
15 | public class RxBinder {
16 |
17 | private CompositeDisposable compositeDisposable = new CompositeDisposable();
18 |
19 | public void bind(Observable observable,
20 | Consumer onNext,
21 | Consumer onError,
22 | Action onComplete) {
23 | compositeDisposable.add(
24 | observable.subscribeOn(Schedulers.io())
25 | .observeOn(AndroidSchedulers.mainThread())
26 | .subscribeWith(new DisposableObserver() {
27 |
28 | @Override
29 | public void onNext(T o) {
30 | try {
31 | onNext.accept(o);
32 | } catch (Exception e) {
33 | Log.e(RxBinder.class.getSimpleName(), "Error calling onNext", e);
34 | }
35 | }
36 |
37 | @Override
38 | public void onError(Throwable thr) {
39 | if (!(thr instanceof Exception)) {
40 | Exceptions.throwIfFatal(thr);
41 | return;
42 | }
43 |
44 | try {
45 | onError.accept((Exception) thr);
46 | } catch (Exception e) {
47 | Log.e(RxBinder.class.getSimpleName(), "Error calling onError", thr);
48 | }
49 | }
50 |
51 | @Override
52 | public void onComplete() {
53 | try {
54 | onComplete.run();
55 | } catch (Exception e) {
56 | Log.e(RxBinder.class.getSimpleName(), "Error calling onComplete", e);
57 | }
58 | }
59 | })
60 | );
61 | }
62 |
63 | public void clear() {
64 | compositeDisposable.clear();
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/consumer/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/NetworkModule.java:
--------------------------------------------------------------------------------
1 | package au.com.dius.pactconsumer.app.di;
2 |
3 | import android.content.Context;
4 | import android.support.annotation.NonNull;
5 | import android.support.annotation.VisibleForTesting;
6 |
7 | import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
8 | import com.squareup.moshi.FromJson;
9 | import com.squareup.moshi.Moshi;
10 | import com.squareup.moshi.ToJson;
11 |
12 | import org.joda.time.DateTime;
13 |
14 | import java.io.File;
15 |
16 | import javax.inject.Singleton;
17 |
18 | import au.com.dius.pactconsumer.BuildConfig;
19 | import au.com.dius.pactconsumer.util.DateHelper;
20 | import dagger.Module;
21 | import dagger.Provides;
22 | import okhttp3.Cache;
23 | import okhttp3.OkHttpClient;
24 | import okhttp3.logging.HttpLoggingInterceptor;
25 | import retrofit2.Retrofit;
26 | import retrofit2.converter.moshi.MoshiConverterFactory;
27 |
28 |
29 | @Module
30 | public class NetworkModule {
31 |
32 | @Singleton
33 | @Provides
34 | @NonNull
35 | public Retrofit getRetrofit(@NonNull Context context) {
36 | return getRetrofit(context, BuildConfig.BASE_URL);
37 | }
38 |
39 | @VisibleForTesting
40 | public Retrofit getRetrofit(@NonNull Context context,
41 | @NonNull String baseUrl) {
42 | return new Retrofit.Builder()
43 | .baseUrl(baseUrl)
44 | .client(getOkHttpClient(context))
45 | .addConverterFactory(MoshiConverterFactory.create(getMoshi()))
46 | .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
47 | .build();
48 | }
49 |
50 | private OkHttpClient getOkHttpClient(@NonNull Context context) {
51 | OkHttpClient.Builder builder = new OkHttpClient.Builder();
52 | if (BuildConfig.DEBUG) {
53 | HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
54 | interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
55 | builder.addNetworkInterceptor(interceptor);
56 | }
57 | builder.cache(new Cache(new File(context.getCacheDir(), "okhttp_cache"), 10 * 1024 * 1024));
58 | return builder.build();
59 | }
60 |
61 | private Moshi getMoshi() {
62 | return new Moshi.Builder().add(new DateTimeAdapter()).build();
63 | }
64 |
65 | public static class DateTimeAdapter {
66 |
67 | @ToJson
68 | public String toJson(DateTime dateTime) {
69 | return DateHelper.toString(dateTime);
70 | }
71 |
72 | @FromJson
73 | public DateTime fromJson(String json) {
74 | return DateHelper.parse(json);
75 | }
76 | }
77 |
78 | }
79 |
--------------------------------------------------------------------------------
/provider/Gemfile.lock:
--------------------------------------------------------------------------------
1 | GEM
2 | remote: https://rubygems.org/
3 | specs:
4 | activesupport (4.2.5.1)
5 | i18n (~> 0.7)
6 | json (~> 1.7, >= 1.7.7)
7 | minitest (~> 5.1)
8 | thread_safe (~> 0.3, >= 0.3.4)
9 | tzinfo (~> 1.1)
10 | awesome_print (1.6.1)
11 | coderay (1.1.1)
12 | diff-lcs (1.2.5)
13 | find_a_port (1.0.1)
14 | i18n (0.7.0)
15 | json (1.8.3)
16 | method_source (0.8.2)
17 | minitest (5.8.4)
18 | pact (1.9.0)
19 | awesome_print (~> 1.1)
20 | find_a_port (~> 1.0.1)
21 | json
22 | pact-mock_service (~> 0.7)
23 | pact-support (~> 0.5)
24 | rack-test (~> 0.6.2)
25 | randexp (~> 0.1.7)
26 | rspec (>= 2.14)
27 | term-ansicolor (~> 1.0)
28 | thor
29 | webrick
30 | pact-mock_service (0.8.1)
31 | find_a_port (~> 1.0.1)
32 | json
33 | pact-support (~> 0.5.3)
34 | rack
35 | rack-test (~> 0.6.2)
36 | rspec (>= 2.14)
37 | term-ansicolor (~> 1.0)
38 | thor
39 | webrick
40 | pact-support (0.5.4)
41 | awesome_print (~> 1.1)
42 | find_a_port (~> 1.0.1)
43 | json
44 | rack-test (~> 0.6.2)
45 | randexp (~> 0.1.7)
46 | rspec (>= 2.14)
47 | term-ansicolor (~> 1.0)
48 | thor
49 | pry (0.10.3)
50 | coderay (~> 1.1.0)
51 | method_source (~> 0.8.1)
52 | slop (~> 3.4)
53 | rack (1.6.4)
54 | rack-protection (1.5.3)
55 | rack
56 | rack-test (0.6.3)
57 | rack (>= 1.0)
58 | rake (10.5.0)
59 | randexp (0.1.7)
60 | rspec (3.4.0)
61 | rspec-core (~> 3.4.0)
62 | rspec-expectations (~> 3.4.0)
63 | rspec-mocks (~> 3.4.0)
64 | rspec-core (3.4.3)
65 | rspec-support (~> 3.4.0)
66 | rspec-expectations (3.4.0)
67 | diff-lcs (>= 1.2.0, < 2.0)
68 | rspec-support (~> 3.4.0)
69 | rspec-mocks (3.4.1)
70 | diff-lcs (>= 1.2.0, < 2.0)
71 | rspec-support (~> 3.4.0)
72 | rspec-support (3.4.1)
73 | sinatra (1.4.7)
74 | rack (~> 1.5)
75 | rack-protection (~> 1.4)
76 | tilt (>= 1.3, < 3)
77 | slop (3.6.0)
78 | term-ansicolor (1.3.2)
79 | tins (~> 1.0)
80 | thor (0.19.1)
81 | thread_safe (0.3.5)
82 | tilt (2.0.2)
83 | tins (1.9.0)
84 | tzinfo (1.2.2)
85 | thread_safe (~> 0.1)
86 | webrick (1.3.1)
87 |
88 | PLATFORMS
89 | ruby
90 |
91 | DEPENDENCIES
92 | activesupport
93 | awesome_print
94 | pact
95 | pry
96 | rack
97 | rake
98 | rspec
99 | sinatra
100 |
101 | BUNDLED WITH
102 | 1.11.2
103 |
--------------------------------------------------------------------------------
/consumer/app/src/main/java/au/com/dius/pactconsumer/domain/Presenter.java:
--------------------------------------------------------------------------------
1 | package au.com.dius.pactconsumer.domain;
2 |
3 | import android.support.annotation.NonNull;
4 | import android.support.annotation.Nullable;
5 |
6 | import org.joda.time.DateTime;
7 |
8 | import java.lang.ref.WeakReference;
9 | import java.util.List;
10 |
11 | import au.com.dius.pactconsumer.R;
12 | import au.com.dius.pactconsumer.data.Repository;
13 | import au.com.dius.pactconsumer.data.model.Animal;
14 | import au.com.dius.pactconsumer.data.model.ServiceResponse;
15 | import au.com.dius.pactconsumer.util.Logger;
16 | import au.com.dius.pactconsumer.util.RxBinder;
17 | import io.reactivex.Observable;
18 |
19 | public class Presenter implements Contract.Presenter {
20 |
21 | private final Repository repository;
22 |
23 | private final WeakReference viewRef;
24 |
25 | private final RxBinder binder;
26 |
27 | private final Logger logger;
28 |
29 | public Presenter(@NonNull Repository repository,
30 | @NonNull Contract.View view,
31 | @NonNull RxBinder binder,
32 | @NonNull Logger logger) {
33 | this.repository = repository;
34 | this.viewRef = new WeakReference<>(view);
35 | this.binder = binder;
36 | this.logger = logger;
37 | }
38 |
39 | @Override
40 | public void onStart() {
41 | setLoading();
42 | binder.bind(getAnimals(), this::setAnimals, this::setError, this::setComplete);
43 | }
44 |
45 | @Override
46 | public void onStop() {
47 | binder.clear();
48 | }
49 |
50 | private Observable> getAnimals() {
51 | return repository.fetchResponse(DateTime.now())
52 | .toObservable()
53 | .map(ServiceResponse::getAnimals);
54 | }
55 |
56 | private void setLoading() {
57 | Contract.View view = getView();
58 | if (view == null) return;
59 |
60 | view.setViewState(ViewState.Loading.create());
61 | }
62 |
63 | private void setAnimals(@NonNull List animals) {
64 | Contract.View view = getView();
65 | if (view == null) return;
66 |
67 | if (animals.isEmpty()) {
68 | view.setViewState(ViewState.Empty.create(R.string.empty_message));
69 | return;
70 | }
71 |
72 | view.setViewState(ViewState.Loaded.create(animals));
73 | }
74 |
75 | private void setError(@NonNull Exception exception) {
76 | Contract.View view = getView();
77 | if (view == null) return;
78 |
79 | logger.e(Presenter.class.getSimpleName(), "Error loading service response", exception);
80 | view.setViewState(ViewState.Error.create(R.string.error_message));
81 | }
82 |
83 | private void setComplete() {
84 | }
85 |
86 | @Nullable
87 | private Contract.View getView() {
88 | return viewRef.get();
89 | }
90 |
91 | }
92 |
--------------------------------------------------------------------------------
/consumer/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/consumer/app/src/test/java/au/com/dius/pactconsumer/domain/PresenterTest.java:
--------------------------------------------------------------------------------
1 | package au.com.dius.pactconsumer.domain;
2 |
3 | import org.junit.Before;
4 | import org.junit.Test;
5 | import org.mockito.InOrder;
6 | import org.mockito.Mockito;
7 |
8 | import java.util.Collections;
9 |
10 | import au.com.dius.pactconsumer.R;
11 | import au.com.dius.pactconsumer.data.FakeService;
12 | import au.com.dius.pactconsumer.data.Repository;
13 | import au.com.dius.pactconsumer.data.exceptions.ServiceException;
14 | import au.com.dius.pactconsumer.data.model.ServiceResponse;
15 | import au.com.dius.pactconsumer.util.Logger;
16 | import au.com.dius.pactconsumer.util.TestRxBinder;
17 | import io.reactivex.Single;
18 |
19 | import static org.mockito.ArgumentMatchers.any;
20 | import static org.mockito.Mockito.mock;
21 | import static org.mockito.Mockito.verify;
22 | import static org.mockito.Mockito.when;
23 |
24 | public class PresenterTest {
25 |
26 | Repository repository;
27 | Contract.View view;
28 | Presenter presenter;
29 |
30 | @Before
31 | public void setUp() {
32 | repository = mock(Repository.class);
33 | view = mock(Contract.View.class);
34 | presenter = new Presenter(repository, view, new TestRxBinder(), mock(Logger.class));
35 | }
36 |
37 | @Test
38 | public void should_show_loaded_when_fetch_succeeds() {
39 | // given
40 | when(repository.fetchResponse(any())).thenReturn(Single.just(FakeService.RESPONSE));
41 |
42 | // when
43 | presenter.onStart();
44 |
45 | // then
46 | verify(view).setViewState(ViewState.Loaded.create(FakeService.RESPONSE.getAnimals()));
47 | }
48 |
49 | @Test
50 | public void should_show_error_when_fetch_fails() {
51 | // given
52 | ServiceException exception = new ServiceException();
53 | when(repository.fetchResponse(any())).thenReturn(Single.error(exception));
54 |
55 | // when
56 | presenter.onStart();
57 |
58 | // then
59 | verify(view).setViewState(ViewState.Error.create(R.string.error_message));
60 | }
61 |
62 | @Test
63 | public void should_show_empty_when_fetch_returns_nothing() {
64 | // given
65 | when(repository.fetchResponse(any())).thenReturn(Single.just(new ServiceResponse(null, Collections.emptyList())));
66 |
67 | // when
68 | presenter.onStart();
69 |
70 | // then
71 | verify(view).setViewState(ViewState.Empty.create(R.string.empty_message));
72 | }
73 |
74 | @Test
75 | public void should_show_loading_when_fetching() {
76 | // given
77 | when(repository.fetchResponse(any())).thenReturn(Single.just(FakeService.RESPONSE));
78 |
79 | // when
80 | presenter.onStart();
81 |
82 | // then
83 | InOrder inOrder = Mockito.inOrder(view);
84 | inOrder.verify(view).setViewState(ViewState.Loading.create());
85 | inOrder.verify(view).setViewState(ViewState.Loaded.create(FakeService.RESPONSE.getAnimals()));
86 | }
87 |
88 | }
89 |
--------------------------------------------------------------------------------
/consumer/app/src/test/java/au/com/dius/pactconsumer/data/ServicePactTest.java:
--------------------------------------------------------------------------------
1 | package au.com.dius.pactconsumer.data;
2 |
3 |
4 | import android.content.Context;
5 |
6 | import org.joda.time.DateTime;
7 | import org.junit.Before;
8 | import org.junit.Rule;
9 | import org.junit.Test;
10 |
11 | import java.io.UnsupportedEncodingException;
12 | import java.util.Arrays;
13 | import java.util.HashMap;
14 | import java.util.Map;
15 |
16 | import au.com.dius.pact.consumer.Pact;
17 | import au.com.dius.pact.consumer.PactProviderRule;
18 | import au.com.dius.pact.consumer.PactVerification;
19 | import au.com.dius.pact.consumer.dsl.PactDslJsonBody;
20 | import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
21 | import au.com.dius.pact.model.PactFragment;
22 | import au.com.dius.pactconsumer.app.di.NetworkModule;
23 | import au.com.dius.pactconsumer.data.model.Animal;
24 | import au.com.dius.pactconsumer.data.model.ServiceResponse;
25 | import au.com.dius.pactconsumer.util.DateHelper;
26 | import io.reactivex.observers.TestObserver;
27 |
28 | import static org.mockito.Mockito.mock;
29 |
30 | public class ServicePactTest {
31 |
32 | static final DateTime DATE_TIME;
33 | static final Map HEADERS;
34 |
35 | static {
36 | DATE_TIME = DateTime.now();
37 |
38 | HEADERS = new HashMap<>();
39 | HEADERS.put("Content-Type", "application/json");
40 | }
41 |
42 | Service service;
43 |
44 | @Before
45 | public void setUp() {
46 | NetworkModule networkModule = new NetworkModule();
47 | service = new Service(networkModule.getRetrofit(mock(Context.class), "http://localhost:9292").create(Service.Api.class));
48 | }
49 |
50 | @Rule
51 | public PactProviderRule mockProvider = new PactProviderRule("our_provider", "localhost", 9292, this);
52 |
53 | @Pact(provider = "our_provider", consumer = "our_consumer")
54 | public PactFragment createFragment(PactDslWithProvider builder) throws UnsupportedEncodingException {
55 | PactDslJsonBody body = new PactDslJsonBody()
56 | .stringType("test")
57 | .stringType("valid_date", DateHelper.toString(DATE_TIME))
58 | .eachLike("animals", 3)
59 | .stringType("name", "Doggy")
60 | .stringType("image", "dog")
61 | .closeObject()
62 | .closeArray()
63 | .asBody();
64 |
65 | return builder
66 | .given("data count is > 0")
67 | .uponReceiving("a request for json data")
68 | .path("/provider.json")
69 | .method("GET")
70 | .query("valid_date=" + DateHelper.encodeDate(DATE_TIME))
71 | .willRespondWith()
72 | .status(200)
73 | .headers(HEADERS)
74 | .body(body)
75 | .toFragment();
76 | }
77 |
78 | @Test
79 | @PactVerification("our_provider")
80 | public void should_process_the_json_payload_from_provider() {
81 | TestObserver observer = service.fetchResponse(DATE_TIME).test();
82 | observer.assertNoErrors();
83 | observer.assertValue(ServiceResponse.create(DATE_TIME, Arrays.asList(
84 | Animal.create("Doggy", "dog"),
85 | Animal.create("Doggy", "dog"),
86 | Animal.create("Doggy", "dog")
87 | )));
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/consumer/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'com.neenbedankt.android-apt'
3 | apply plugin: 'me.tatarka.retrolambda'
4 | apply plugin: 'au.com.dius.pact'
5 |
6 | buildscript {
7 | repositories {
8 | mavenCentral()
9 | }
10 | dependencies {
11 | classpath 'au.com.dius:pact-jvm-provider-gradle_2.11:3.2.4'
12 | }
13 | }
14 |
15 | android {
16 | compileSdkVersion 25
17 | buildToolsVersion "25.0.2"
18 |
19 | defaultConfig {
20 | applicationId "au.com.dius.pactconsumer"
21 | minSdkVersion 21
22 | targetSdkVersion 25
23 | versionCode 1
24 | versionName "1.0"
25 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
26 |
27 | buildConfigField "String", "BASE_URL", "\"http://10.0.2.2:4567\""
28 | }
29 |
30 | buildTypes {
31 | release {
32 | minifyEnabled false
33 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
34 | }
35 | }
36 |
37 | compileOptions {
38 | sourceCompatibility JavaVersion.VERSION_1_8
39 | targetCompatibility JavaVersion.VERSION_1_8
40 | }
41 |
42 | lintOptions {
43 | abortOnError false
44 | warning 'InvalidPackage' // Note: issue with okio: https://github.com/square/okio/issues/58
45 | }
46 |
47 | testOptions.unitTests.all {
48 | testLogging {
49 | events 'passed', 'skipped', 'failed'
50 | }
51 | }
52 |
53 | }
54 |
55 | dependencies {
56 | compile fileTree(dir: 'libs', include: ['*.jar'])
57 |
58 | def androidSupportVersion = '25.1.1'
59 | compile "com.android.support:appcompat-v7:$androidSupportVersion"
60 | compile "com.android.support:design:$androidSupportVersion"
61 | compile "com.android.support:support-annotations:$androidSupportVersion"
62 | compile "com.android.support:cardview-v7:$androidSupportVersion"
63 |
64 | def daggerVersion = '2.5'
65 | apt "com.google.dagger:dagger-compiler:$daggerVersion"
66 | compile "com.google.dagger:dagger:$daggerVersion"
67 | provided 'javax.annotation:jsr250-api:1.0'
68 |
69 | compile "io.reactivex.rxjava2:rxjava:2.0.3"
70 | compile "io.reactivex.rxjava2:rxandroid:2.0.1"
71 |
72 | compile "com.squareup.retrofit2:retrofit:2.1.0"
73 | compile "com.squareup.retrofit2:converter-moshi:2.1.0"
74 | compile "com.squareup.retrofit2:converter-scalars:2.1.0"
75 | compile "com.squareup.moshi:moshi:1.3.1"
76 | compile "com.squareup.okhttp3:logging-interceptor:3.3.1"
77 | compile "com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0"
78 |
79 | compile "joda-time:joda-time:2.9.4"
80 |
81 | /* Test dependencies */
82 |
83 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
84 | exclude group: 'com.android.support', module: 'support-annotations'
85 | })
86 |
87 | testCompile "junit:junit:4.12"
88 | testCompile "org.mockito:mockito-core:2.1.0-RC.2"
89 | testCompile "org.hamcrest:hamcrest-junit:2.0.0.0"
90 | testCompile "joda-time:joda-time:2.9.4"
91 |
92 | testCompile "au.com.dius:pact-jvm-consumer-junit_2.11:3.3.6"
93 |
94 | }
95 |
96 | pact {
97 | publish {
98 | pactDirectory = 'app/target/pacts' // defaults to $buildDir/pacts
99 | pactBrokerUrl = 'https://dXfltyFMgNOFZAxr8io9wJ37iUpY42M:O5AIZWxelWbLvqMd8PkAVycBJh2Psyg1@test.pact.dius.com.au/'
100 | version = '1.0.0'
101 | }
102 | }
103 |
--------------------------------------------------------------------------------
/consumer/app/src/main/java/au/com/dius/pactconsumer/domain/ViewState.java:
--------------------------------------------------------------------------------
1 | package au.com.dius.pactconsumer.domain;
2 |
3 | import android.support.annotation.NonNull;
4 | import android.support.annotation.StringRes;
5 |
6 | import java.util.List;
7 |
8 | import au.com.dius.pactconsumer.data.model.Animal;
9 |
10 | public class ViewState {
11 |
12 | public static class Loaded extends ViewState {
13 |
14 | @NonNull
15 | private final List animals;
16 |
17 | private Loaded(@NonNull List animals) {
18 | this.animals = animals;
19 | }
20 |
21 | @NonNull
22 | public List getAnimals() {
23 | return animals;
24 | }
25 |
26 | @Override
27 | public boolean equals(Object o) {
28 | if (this == o) return true;
29 | if (o == null || getClass() != o.getClass()) return false;
30 |
31 | Loaded loaded = (Loaded) o;
32 |
33 | return animals.equals(loaded.animals);
34 |
35 | }
36 |
37 | @Override
38 | public int hashCode() {
39 | return animals.hashCode();
40 | }
41 |
42 | @Override
43 | public String toString() {
44 | return "Loaded{" +
45 | "animals=" + animals +
46 | '}';
47 | }
48 |
49 | public static Loaded create(@NonNull List animals) {
50 | return new Loaded(animals);
51 | }
52 |
53 | }
54 |
55 | public static class Loading extends ViewState {
56 |
57 | private static final Loading instance = new Loading();
58 |
59 | @Override
60 | public String toString() {
61 | return "Loading{}";
62 | }
63 |
64 | public static Loading create() {
65 | return instance;
66 | }
67 |
68 | }
69 |
70 | public static class Empty extends ViewState {
71 |
72 | private final @StringRes int messageRes;
73 |
74 | private Empty(@StringRes int messageRes) {
75 | this.messageRes = messageRes;
76 | }
77 |
78 | @StringRes
79 | public int getMessage() {
80 | return messageRes;
81 | }
82 |
83 | @Override
84 | public boolean equals(Object o) {
85 | if (this == o) return true;
86 | if (o == null || getClass() != o.getClass()) return false;
87 |
88 | Empty empty = (Empty) o;
89 |
90 | return messageRes == empty.messageRes;
91 |
92 | }
93 |
94 | @Override
95 | public int hashCode() {
96 | return messageRes;
97 | }
98 |
99 | @Override
100 | public String toString() {
101 | return "Empty{" +
102 | "messageRes=" + messageRes +
103 | '}';
104 | }
105 |
106 | public static Empty create(@StringRes int messageRes) {
107 | return new Empty(messageRes);
108 | }
109 | }
110 |
111 | public static class Error extends ViewState {
112 |
113 | private final @StringRes int messageRes;
114 |
115 | private Error(@StringRes int messageRes) {
116 | this.messageRes = messageRes;
117 | }
118 |
119 | @StringRes
120 | public int getMessage() {
121 | return messageRes;
122 | }
123 |
124 | @Override
125 | public boolean equals(Object o) {
126 | if (this == o) return true;
127 | if (o == null || getClass() != o.getClass()) return false;
128 |
129 | Error error = (Error) o;
130 |
131 | return messageRes == error.messageRes;
132 |
133 | }
134 |
135 | @Override
136 | public int hashCode() {
137 | return messageRes;
138 | }
139 |
140 | @Override
141 | public String toString() {
142 | return "Error{" +
143 | "messageRes=" + messageRes +
144 | '}';
145 | }
146 |
147 | public static Error create(@StringRes int messageRes) {
148 | return new Error(messageRes);
149 | }
150 | }
151 |
152 | }
153 |
--------------------------------------------------------------------------------
/consumer/app/src/main/java/au/com/dius/pactconsumer/presentation/HomeActivity.java:
--------------------------------------------------------------------------------
1 | package au.com.dius.pactconsumer.presentation;
2 |
3 | import android.os.Bundle;
4 | import android.support.annotation.NonNull;
5 | import android.support.annotation.Nullable;
6 | import android.support.v7.widget.LinearLayoutManager;
7 | import android.support.v7.widget.RecyclerView;
8 | import android.support.v7.widget.Toolbar;
9 | import android.view.View;
10 | import android.widget.TextView;
11 |
12 | import javax.inject.Inject;
13 |
14 | import au.com.dius.pactconsumer.R;
15 | import au.com.dius.pactconsumer.app.PactActivity;
16 | import au.com.dius.pactconsumer.app.di.ApplicationComponent;
17 | import au.com.dius.pactconsumer.data.Repository;
18 | import au.com.dius.pactconsumer.domain.Contract;
19 | import au.com.dius.pactconsumer.domain.Presenter;
20 | import au.com.dius.pactconsumer.domain.ViewState;
21 | import au.com.dius.pactconsumer.util.Logger;
22 | import au.com.dius.pactconsumer.util.RxBinder;
23 |
24 | public class HomeActivity extends PactActivity implements Contract.View {
25 |
26 | @Inject
27 | Repository repository;
28 |
29 | @Inject
30 | Logger logger;
31 |
32 | private Presenter presenter;
33 |
34 | private View loadingView;
35 | private TextView emptyView;
36 | private TextView errorView;
37 | private RecyclerView recyclerView;
38 |
39 | @Override
40 | protected void onCreate(@Nullable Bundle savedInstanceState) {
41 | super.onCreate(savedInstanceState);
42 | setContentView(R.layout.activity_animals);
43 | Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
44 | setSupportActionBar(toolbar);
45 |
46 | initialiseView();
47 | initialisePresenter(savedInstanceState);
48 | }
49 |
50 | private void initialiseView() {
51 | loadingView = findViewById(R.id.view_loading);
52 | emptyView = (TextView) findViewById(R.id.txt_empty);
53 | errorView = (TextView) findViewById(R.id.txt_error);
54 | recyclerView = (RecyclerView) findViewById(R.id.view_recycler);
55 | recyclerView.setLayoutManager(new LinearLayoutManager(this));
56 | }
57 |
58 | private void initialisePresenter(@Nullable Bundle savedInstanceState) {
59 | presenter = new Presenter(repository, this, new RxBinder(), logger);
60 | }
61 |
62 | @Override
63 | public void inject(@NonNull ApplicationComponent component) {
64 | component.inject(this);
65 | }
66 |
67 | @Override
68 | protected void onResume() {
69 | super.onResume();
70 | presenter.onStart();
71 | }
72 |
73 | @Override
74 | protected void onPause() {
75 | super.onPause();
76 | presenter.onStop();
77 | }
78 |
79 | @Override
80 | public void setViewState(@NonNull ViewState viewState) {
81 | if (viewState instanceof ViewState.Loading) {
82 | setLoading((ViewState.Loading) viewState);
83 | } else if (viewState instanceof ViewState.Loaded) {
84 | setLoaded((ViewState.Loaded) viewState);
85 | } else if (viewState instanceof ViewState.Empty) {
86 | setEmpty((ViewState.Empty) viewState);
87 | } else if (viewState instanceof ViewState.Error) {
88 | setError((ViewState.Error) viewState);
89 | }
90 | }
91 |
92 | private void setLoading(@NonNull ViewState.Loading viewState) {
93 | hideViews();
94 | loadingView.setVisibility(View.VISIBLE);
95 | }
96 |
97 | private void setLoaded(@NonNull ViewState.Loaded viewState) {
98 | hideViews();
99 | recyclerView.setVisibility(View.VISIBLE);
100 | recyclerView.setAdapter(new AnimalsAdapter(viewState.getAnimals()));
101 | }
102 |
103 | private void setEmpty(@NonNull ViewState.Empty viewState) {
104 | hideViews();
105 | emptyView.setText(getResources().getString(viewState.getMessage()));
106 | emptyView.setVisibility(View.VISIBLE);
107 | }
108 |
109 | private void setError(@NonNull ViewState.Error viewState) {
110 | hideViews();
111 | errorView.setText(getResources().getString(viewState.getMessage()));
112 | errorView.setVisibility(View.VISIBLE);
113 | }
114 |
115 | private void hideViews() {
116 | loadingView.setVisibility(View.GONE);
117 | emptyView.setVisibility(View.GONE);
118 | errorView.setVisibility(View.GONE);
119 | recyclerView.setVisibility(View.GONE);
120 | }
121 |
122 | }
123 |
--------------------------------------------------------------------------------
/consumer/app/src/main/res/drawable/bird.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
41 |
70 |
78 |
85 |
92 |
--------------------------------------------------------------------------------
/consumer/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -image d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/consumer/app/src/main/res/drawable/dog.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
15 |
22 |
35 |
44 |
57 |
66 |
74 |
82 |
90 |
103 |
111 |
119 |
125 |
132 |
140 |
148 |
156 |
162 |
169 |
177 |
185 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/consumer/app/src/main/res/drawable/cat.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
29 |
48 |
54 |
68 |
73 |
78 |
85 |
92 |
99 |
106 |
113 |
120 |
129 |
136 |
143 |
151 |
159 |
169 |
177 |
182 |
187 |
192 |
197 |
202 |
207 |
212 |
217 |
222 |
227 |
232 |
245 |
259 |
274 |
296 |
310 |
318 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Example Android Project for Pact Workshop
2 | ======================================
3 |
4 | When writing a lot of small services, testing the interactions between these becomes a major headache. That's the problem Pact is trying to solve.
5 |
6 | Integration tests typically are slow and brittle, requiring each component to have it's own environment to run the tests in. With a micro-service architecture, this becomes even more of a problem. They also have to be 'all-knowing' and this makes them difficult to keep from being fragile.
7 |
8 | After J. B. Rainsberger's talk "Integrated Tests Are A Scam" people have been thinking how to get the confidence we need to deploy our software to production without having a tiresome integration test suite that does not give us all the coverage we think it does.
9 |
10 | Pact is a testing framework that allows you to define a pact between service consumers and providers. It provides a DSL for service consumers to define the request they will make to a service producer and the response they expect back. This expectation is used in the consumers specs to provide a mock producer, and is also played back in the producer specs to ensure the producer actually does provide the response the consumer expects.
11 |
12 | This allows you to test both sides of an integration point using fast unit tests.
13 |
14 | ## Prerequisites
15 |
16 | You will need to have the following items installed for you to run through the workshop.
17 |
18 | - Java 1.8
19 | - AndroidStudio (2.2.3)
20 | - Android SDK 25, Emulator Image and Latest build Tools
21 | - Ruby 2.3.0
22 |
23 | ## Step 1 - Simple customer calling Provider
24 |
25 | Given we have a android app that needs to make a HTTP GET request to a sinatra webapp, and requires a response in JSON format. The client would look something like:
26 |
27 | Service.java:
28 |
29 | ```java
30 | public class Service implements Repository {
31 |
32 | public interface Api {
33 | @GET("provider.json")
34 | Single loadProviderJson(@Query("valid_date") String validDate);
35 | }
36 |
37 | private final Api api;
38 |
39 | @Inject
40 | public Service(@NonNull Api api) {
41 | this.api = api;
42 | }
43 |
44 | @NonNull
45 | @Override
46 | public Single fetchResponse(@NonNull DateTime dateTime) {
47 | try {
48 | return api.loadProviderJson(DateHelper.encodeDate(dateTime));
49 | } catch (UnsupportedEncodingException e) {
50 | return Single.error(e);
51 | }
52 | }
53 |
54 | }
55 | ```
56 |
57 | and the reponse ServiceResponse.java:
58 |
59 | ```java
60 | public class ServiceResponse {
61 |
62 | @Json(name = "date")
63 | private final DateTime validDate;
64 |
65 | @Json(name = "data")
66 | private final List animals;
67 |
68 | public ServiceResponse(@Nullable DateTime validDate,
69 | @NonNull List animals) {
70 | this.validDate = validDate;
71 | this.animals = animals;
72 | }
73 |
74 | @Nullable
75 | public DateTime getValidDate() {
76 | return validDate;
77 | }
78 |
79 | @NonNull
80 | public List getAnimals() {
81 | return animals;
82 | }
83 | ...
84 | ```
85 |
86 | and the provider provider.rb:
87 |
88 | ```ruby
89 | class Provider < Sinatra::Base
90 |
91 | get '/provider.json', :provides => 'json' do
92 | valid_time = Time.parse(params[:valid_date])
93 | JSON.pretty_generate({
94 | :test => 'NO',
95 | :valid_date => DateTime.now,
96 | :animals => ProviderData.animals
97 | })
98 | end
99 |
100 | end
101 | ```
102 |
103 | ## Step 2 - Client Tested but integration fails
104 |
105 | Now lets test the client on the app:
106 |
107 | ServiceTest.java:
108 |
109 | ```java
110 | public class ServiceTest {
111 |
112 | Service.Api api;
113 | Service service;
114 |
115 | @Before
116 | public void setup() {
117 | api = mock(Service.Api.class);
118 | service = new Service(api);
119 | }
120 |
121 | @Test
122 | public void should_process_json_payload_from_provider() {
123 | // given
124 | ServiceResponse response = ServiceResponse.create(DateTime.now(), Collections.singletonList(Animal.create("Doggy", "dog")));
125 | when(api.loadProviderJson(any())).thenReturn(Single.just(response));
126 |
127 | // when
128 | TestObserver observer = service.fetchResponse(DateTime.now()).test();
129 |
130 | // then
131 | observer.assertNoErrors();
132 | observer.assertValue(response);
133 | }
134 |
135 | }
136 | ```
137 |
138 | Let's run this test and see it all pass:
139 |
140 | ```console
141 | $ ./gradlew clean testDebugUnitTest
142 |
143 | ...
144 | :app:testDebugUnitTest
145 |
146 | au.com.dius.pactconsumer.domain.PresenterTest > should_show_empty_when_fetch_returns_nothing PASSED
147 |
148 | au.com.dius.pactconsumer.domain.PresenterTest > should_show_error_when_fetch_fails PASSED
149 |
150 | au.com.dius.pactconsumer.domain.PresenterTest > should_show_loaded_when_fetch_succeeds PASSED
151 |
152 | au.com.dius.pactconsumer.domain.PresenterTest > should_show_loading_when_fetching PASSED
153 |
154 | au.com.dius.pactconsumer.data.ServiceTest > should_process_json_payload_from_provider PASSED
155 |
156 | au.com.dius.pactconsumer.data.FakeServiceTest > should_return_list_of_animals PASSED
157 |
158 | BUILD SUCCESSFUL
159 |
160 | Total time: 16.089 secs
161 | ```
162 |
163 | However, there is a problem with this integration point. The provider returns a different field names, which will blow up when run for real even with the tests all passing. Here is where Pact comes in.
164 |
165 | ## Step 3 - Pact to the rescue
166 |
167 | Lets setup Pact in the consumer. Pact lets the consumers define the expectations for the integration point.
168 |
169 | Lets add a pact for the consumer.
170 |
171 | ServicePactTest.java:
172 |
173 | ```java
174 | public class ServicePactTest {
175 |
176 | static final DateTime DATE_TIME;
177 | static final Map HEADERS;
178 | static final String JSON;
179 |
180 | static {
181 | DATE_TIME = DateTime.now();
182 |
183 | HEADERS = new HashMap<>();
184 | HEADERS.put("Content-Type", "application/json");
185 |
186 | JSON = "{\n" +
187 | " \"test\": \"NO\",\n" +
188 | " \"date\": \"" + DateHelper.toString(DATE_TIME) + "\",\n" +
189 | " \"data\": [\n" +
190 | " {\n" +
191 | " \"name\": \"Doggy\",\n" +
192 | " \"image\": \"dog\"\n" +
193 | " }\n" +
194 | " ]\n" +
195 | "}";
196 | }
197 |
198 | Service service;
199 |
200 | @Before
201 | public void setUp() {
202 | NetworkModule networkModule = new NetworkModule();
203 | service = new Service(networkModule.getRetrofit(mock(Context.class), "http://localhost:9292").create(Service.Api.class));
204 | }
205 |
206 | @Rule
207 | public PactProviderRule mockProvider = new PactProviderRule("our_provider", "localhost", 9292, this);
208 |
209 | @Pact(provider = "our_provider", consumer = "our_consumer")
210 | public PactFragment createFragment(PactDslWithProvider builder) throws UnsupportedEncodingException {
211 | return builder
212 | .given("data count is > 0")
213 | .uponReceiving("a request for json data")
214 | .path("/provider.json")
215 | .method("GET")
216 | .query("valid_date=" + DateHelper.encodeDate(DATE_TIME))
217 | .willRespondWith()
218 | .status(200)
219 | .headers(HEADERS)
220 | .body(JSON)
221 | .toFragment();
222 | }
223 |
224 | @Test
225 | @PactVerification("our_provider")
226 | public void should_process_the_json_payload_from_provider() {
227 | TestObserver observer = service.fetchResponse(DATE_TIME).test();
228 | observer.assertNoErrors();
229 | observer.assertValue(ServiceResponse.create(DATE_TIME, Collections.singletonList(Animal.create("Doggy", "dog"))));
230 | }
231 | }
232 | ```
233 |
234 | Running this test still passes, but it creates a pact file which we can use to validate our assumptions on the provider side.
235 |
236 | ```console
237 | ./gradlew clean testDebugUnitTest
238 | ...
239 |
240 | au.com.dius.pactconsumer.domain.PresenterTest > should_show_empty_when_fetch_returns_nothing PASSED
241 |
242 | au.com.dius.pactconsumer.domain.PresenterTest > should_show_error_when_fetch_fails PASSED
243 |
244 | au.com.dius.pactconsumer.domain.PresenterTest > should_show_loaded_when_fetch_succeeds PASSED
245 |
246 | au.com.dius.pactconsumer.domain.PresenterTest > should_show_loading_when_fetching PASSED
247 |
248 | au.com.dius.pactconsumer.data.ServiceTest > should_process_json_payload_from_provider PASSED
249 |
250 | au.com.dius.pactconsumer.data.FakeServiceTest > should_return_list_of_animals PASSED
251 |
252 | au.com.dius.pactconsumer.data.ServicePactTest > should_process_the_json_payload_from_provider PASSED
253 |
254 | BUILD SUCCESSFUL
255 |
256 | Total time: 18.835 secs
257 | ```
258 |
259 | Generated pact file (consumer/app/target/pacts/our_consumer-our_provider.json):
260 |
261 | ```json
262 | {
263 | "provider": {
264 | "name": "our_provider"
265 | },
266 | "consumer": {
267 | "name": "our_consumer"
268 | },
269 | "interactions": [
270 | {
271 | "description": "a request for json data",
272 | "request": {
273 | "method": "GET",
274 | "path": "/provider.json",
275 | "query": "valid_date=2017-02-01T19%253A53%253A27.038%252B11%253A00"
276 | },
277 | "response": {
278 | "status": 200,
279 | "headers": {
280 | "Content-Type": "application/json"
281 | },
282 | "body": {
283 | "data": [
284 | {
285 | "image": "dog",
286 | "name": "Doggy"
287 | }
288 | ],
289 | "date": "2017-02-01T19:53:27.038+11:00",
290 | "test": "NO"
291 | }
292 | },
293 | "providerState": "data count is > 0"
294 | }
295 | ],
296 | "metadata": {
297 | "pact-specification": {
298 | "version": "2.0.0"
299 | },
300 | "pact-jvm": {
301 | "version": "3.3.6"
302 | }
303 | }
304 | }
305 | ```
306 | ## Step 4 - Verify pact against provider
307 |
308 | Pact has a rake task to verify the producer against the generated pact file. It can get the pact file from any URL (like the last successful CI build), but we just going to use the local one. Here is the addition to the Rakefile.
309 |
310 | Rakefile:
311 |
312 | ```ruby
313 | require 'pact/tasks'
314 | ```
315 |
316 | spec/pact_helper.rb:
317 |
318 | ```ruby
319 | require 'pact/provider/rspec'
320 |
321 | Pact.service_provider "our_provider" do
322 |
323 | honours_pact_with 'our_consumer' do
324 | pact_uri 'spec/pacts/our_consumer-our_provider.json'
325 | end
326 |
327 | end
328 | ```
329 |
330 | Now if we copy the pact file from the consumer project and run our pact verification task, it should fail.
331 |
332 | ```console
333 | $ rake pact:verify
334 |
335 | SPEC_OPTS='' /home/theeban/.rvm/rubies/ruby-2.3.0/bin/ruby -S pact verify --pact-helper /home/theeban/Projects/pact-workshop-android/provider/spec/pact_helper.rb
336 | Reading pact at spec/pacts/our_consumer-our_provider.json
337 |
338 | Verifying a pact between our_consumer and our_provider
339 | Given data count is > 0
340 | a request for json data
341 | with GET /provider.json?valid_date=2017-02-01T19%253A53%253A27.038%252B11%253A00
342 | returns a response which
343 | has status code 200 (FAILED - 1)
344 | has a matching body (FAILED - 2)
345 | includes headers
346 | "Content-Type" with value "application/json" (FAILED - 3)
347 |
348 | Failures:
349 |
350 | 1) Verifying a pact between our_consumer and our_provider Given data count is > 0 a request for json data with GET /provider.json?valid_date=2017-02-01T19%253A53%253A27.038%252B11%253A00 returns a response which has status code 200
351 | Got 0 failures and 2 other errors:
352 |
353 | 1.1) Failure/Error: set_up_provider_state interaction.provider_state, options[:consumer]
354 |
355 | RuntimeError:
356 | Could not find provider state "data count is > 0" for consumer our_consumer
357 | # /home/theeban/.rvm/gems/ruby-2.3.0@example_pact/gems/pact-1.9.0/bin/pact:4:in `'
358 | # /home/theeban/.rvm/gems/ruby-2.3.0@example_pact/bin/pact:22:in `load'
359 | # /home/theeban/.rvm/gems/ruby-2.3.0@example_pact/bin/pact:22:in `'
360 |
361 | 1.2) Failure/Error: tear_down_provider_state interaction.provider_state, options[:consumer]
362 |
363 | RuntimeError:
364 | Could not find provider state "data count is > 0" for consumer our_consumer
365 | # /home/theeban/.rvm/gems/ruby-2.3.0@example_pact/gems/pact-1.9.0/bin/pact:4:in `'
366 | # /home/theeban/.rvm/gems/ruby-2.3.0@example_pact/bin/pact:22:in `load'
367 | # /home/theeban/.rvm/gems/ruby-2.3.0@example_pact/bin/pact:22:in `'
368 |
369 | 2) Verifying a pact between our_consumer and our_provider Given data count is > 0 a request for json data with GET /provider.json?valid_date=2017-02-01T19%253A53%253A27.038%252B11%253A00 returns a response which has a matching body
370 | Got 0 failures and 2 other errors:
371 |
372 | 2.1) Failure/Error: set_up_provider_state interaction.provider_state, options[:consumer]
373 |
374 | RuntimeError:
375 | Could not find provider state "data count is > 0" for consumer our_consumer
376 | # /home/theeban/.rvm/gems/ruby-2.3.0@example_pact/gems/pact-1.9.0/bin/pact:4:in `'
377 | # /home/theeban/.rvm/gems/ruby-2.3.0@example_pact/bin/pact:22:in `load'
378 | # /home/theeban/.rvm/gems/ruby-2.3.0@example_pact/bin/pact:22:in `'
379 |
380 | 2.2) Failure/Error: tear_down_provider_state interaction.provider_state, options[:consumer]
381 |
382 | RuntimeError:
383 | Could not find provider state "data count is > 0" for consumer our_consumer
384 | # /home/theeban/.rvm/gems/ruby-2.3.0@example_pact/gems/pact-1.9.0/bin/pact:4:in `'
385 | # /home/theeban/.rvm/gems/ruby-2.3.0@example_pact/bin/pact:22:in `load'
386 | # /home/theeban/.rvm/gems/ruby-2.3.0@example_pact/bin/pact:22:in `'
387 |
388 | 3) Verifying a pact between our_consumer and our_provider Given data count is > 0 a request for json data with GET /provider.json?valid_date=2017-02-01T19%253A53%253A27.038%252B11%253A00 returns a response which includes headers "Content-Type" with value "application/json"
389 | Got 0 failures and 2 other errors:
390 |
391 | 3.1) Failure/Error: set_up_provider_state interaction.provider_state, options[:consumer]
392 |
393 | RuntimeError:
394 | Could not find provider state "data count is > 0" for consumer our_consumer
395 | # /home/theeban/.rvm/gems/ruby-2.3.0@example_pact/gems/pact-1.9.0/bin/pact:4:in `'
396 | # /home/theeban/.rvm/gems/ruby-2.3.0@example_pact/bin/pact:22:in `load'
397 | # /home/theeban/.rvm/gems/ruby-2.3.0@example_pact/bin/pact:22:in `'
398 |
399 | 3.2) Failure/Error: tear_down_provider_state interaction.provider_state, options[:consumer]
400 |
401 | RuntimeError:
402 | Could not find provider state "data count is > 0" for consumer our_consumer
403 | # /home/theeban/.rvm/gems/ruby-2.3.0@example_pact/gems/pact-1.9.0/bin/pact:4:in `'
404 | # /home/theeban/.rvm/gems/ruby-2.3.0@example_pact/bin/pact:22:in `load'
405 | # /home/theeban/.rvm/gems/ruby-2.3.0@example_pact/bin/pact:22:in `'
406 |
407 | 1 interaction, 1 failure
408 |
409 | Failed interactions:
410 |
411 | bundle exec rake pact:verify:at[spec/pacts/our_consumer-our_provider.json] PACT_DESCRIPTION="a request for json data" PACT_PROVIDER_STATE="data count is > 0" # A request for json data given data count is > 0
412 |
413 | For assistance debugging failures, run `bundle exec rake pact:verify:help`
414 |
415 | Could not find one or more provider states.
416 | Have you required the provider states file for this consumer in your pact_helper.rb?
417 | If you have not yet defined these states, here is a template:
418 |
419 | Pact.provider_states_for "our_consumer" do
420 |
421 | provider_state "data count is > 0" do
422 | set_up do
423 | # Your set up code goes here
424 | end
425 | end
426 |
427 | end
428 | ```
429 |
430 | This has failed due to the provider state we defined. Luckily pact has been quite helpful and given us a snippet
431 | of what we need to do to fix it.
432 |
433 | ## Step 5 - Correct provider states
434 |
435 | Add the snippet from the verification failure to the pact helper.
436 |
437 | spec/pact_helper.rb:
438 |
439 | ```ruby
440 | Pact.provider_states_for "our_consumer" do
441 |
442 | provider_state "data count is > 0" do
443 | set_up do
444 | # Your set up code goes here
445 | end
446 | end
447 |
448 | end
449 | ```
450 |
451 | and then re-run the provider verification.
452 |
453 | ```console
454 | $ rake pact:verify
455 |
456 | SPEC_OPTS='' /home/theeban/.rvm/rubies/ruby-2.3.0/bin/ruby -S pact verify --pact-helper /home/theeban/Projects/pact-workshop-android/provider/spec/pact_helper.rb
457 | Reading pact at spec/pacts/our_consumer-our_provider.json
458 |
459 | Verifying a pact between our_consumer and our_provider
460 | Given data count is > 0
461 | a request for json data
462 | with GET /provider.json?valid_date=2017-02-01T19%253A53%253A27.038%252B11%253A00
463 | returns a response which
464 | has status code 200
465 | has a matching body (FAILED - 1)
466 | includes headers
467 | "Content-Type" with value "application/json"
468 |
469 | Failures:
470 |
471 | 1) Verifying a pact between our_consumer and our_provider Given data count is > 0 a request for json data with GET /provider.json?valid_date=2017-02-01T19%253A53%253A27.038%252B11%253A00 returns a response which has a matching body
472 | Failure/Error: expect(response_body).to match_term expected_response_body, diff_options
473 |
474 | Actual: {"test":"NO","valid_date":"2017-02-01T20:14:51+11:00","animals":[{"name":"Buddy","image":"dog"},{"name":"Cathy","image":"cat"},{"name":"Birdy","image":"bird"}]}
475 |
476 | @@ -1,10 +1,3 @@
477 | {
478 | - "data": [
479 | - {
480 | - "image": "dog",
481 | - "name": "Doggy"
482 | - },
483 | - ],
484 | - "date": "2017-02-01T19:53:27.038+11:00"
485 | }
486 |
487 | Key: - means "expected, but was not found".
488 | + means "actual, should not be found".
489 | Values where the expected matches the actual are not shown.
490 | # /home/theeban/.rvm/gems/ruby-2.3.0@example_pact/gems/pact-1.9.0/bin/pact:4:in `'
491 | # /home/theeban/.rvm/gems/ruby-2.3.0@example_pact/bin/pact:22:in `load'
492 | # /home/theeban/.rvm/gems/ruby-2.3.0@example_pact/bin/pact:22:in `'
493 |
494 | 1 interaction, 1 failure
495 |
496 | Failed interactions:
497 |
498 | bundle exec rake pact:verify:at[spec/pacts/our_consumer-our_provider.json] PACT_DESCRIPTION="a request for json data" PACT_PROVIDER_STATE="data count is > 0" # A request for json data given data count is > 0
499 |
500 | For assistance debugging failures, run `bundle exec rake pact:verify:help`
501 |
502 | ```
503 |
504 | The test has failed for 2 reasons. Firstly, the animals field has a different value to what was expected by the consumer. Secondly, and more importantly, the consumer was expecting a date field.
505 |
506 | ## Step 6 - Back to the client we go
507 |
508 | Let's correct the consumer tests to handle any list of animals and use the correct field for the date.
509 |
510 | Then we need to add a type matcher for `animals` and change the field for the date to be `valid_date`. We can also
511 | add a regular expression to make sure the `valid_date` field is a valid date. This is important because we are
512 | parsing it.
513 |
514 | The updated consumer test is now:
515 |
516 | ```java
517 | public class ServicePactTest {
518 |
519 | static final DateTime DATE_TIME;
520 | static final Map HEADERS;
521 |
522 | static {
523 | DATE_TIME = DateTime.now();
524 |
525 | HEADERS = new HashMap<>();
526 | HEADERS.put("Content-Type", "application/json");
527 | }
528 |
529 | Service service;
530 |
531 | @Before
532 | public void setUp() {
533 | NetworkModule networkModule = new NetworkModule();
534 | service = new Service(networkModule.getRetrofit(mock(Context.class), "http://localhost:9292").create(Service.Api.class));
535 | }
536 |
537 | @Rule
538 | public PactProviderRule mockProvider = new PactProviderRule("our_provider", "localhost", 9292, this);
539 |
540 | @Pact(provider = "our_provider", consumer = "our_consumer")
541 | public PactFragment createFragment(PactDslWithProvider builder) throws UnsupportedEncodingException {
542 | PactDslJsonBody body = new PactDslJsonBody()
543 | .stringType("test")
544 | .stringType("valid_date", DateHelper.toString(DATE_TIME))
545 | .eachLike("animals", 3)
546 | .stringType("name", "Doggy")
547 | .stringType("image", "dog")
548 | .closeObject()
549 | .closeArray()
550 | .asBody();
551 |
552 | return builder
553 | .given("data count is > 0")
554 | .uponReceiving("a request for json data")
555 | .path("/provider.json")
556 | .method("GET")
557 | .query("valid_date=" + DateHelper.encodeDate(DATE_TIME))
558 | .willRespondWith()
559 | .status(200)
560 | .headers(HEADERS)
561 | .body(body)
562 | .toFragment();
563 | }
564 |
565 | @Test
566 | @PactVerification("our_provider")
567 | public void should_process_the_json_payload_from_provider() {
568 | TestObserver observer = service.fetchResponse(DATE_TIME).test();
569 | observer.assertNoErrors();
570 | observer.assertValue(ServiceResponse.create(DATE_TIME, Arrays.asList(
571 | Animal.create("Doggy", "dog"),
572 | Animal.create("Doggy", "dog"),
573 | Animal.create("Doggy", "dog")
574 | )));
575 | }
576 | }
577 | ```
578 |
579 | Re-run the tests will now generate an updated pact file.
580 |
581 | ```console
582 | ./gradlew clean testDebugUnitTest
583 | ...
584 |
585 | au.com.dius.pactconsumer.domain.PresenterTest > should_show_empty_when_fetch_returns_nothing PASSED
586 |
587 | au.com.dius.pactconsumer.domain.PresenterTest > should_show_error_when_fetch_fails PASSED
588 |
589 | au.com.dius.pactconsumer.domain.PresenterTest > should_show_loaded_when_fetch_succeeds PASSED
590 |
591 | au.com.dius.pactconsumer.domain.PresenterTest > should_show_loading_when_fetching PASSED
592 |
593 | au.com.dius.pactconsumer.data.ServiceTest > should_process_json_payload_from_provider PASSED
594 |
595 | au.com.dius.pactconsumer.data.FakeServiceTest > should_return_list_of_animals PASSED
596 |
597 | au.com.dius.pactconsumer.data.ServicePactTest > should_process_the_json_payload_from_provider PASSED
598 |
599 | BUILD SUCCESSFUL
600 |
601 | Total time: 17.235 secs
602 | ```
603 |
604 | ## Step 7 - Verify the provider again
605 |
606 | Copy over the new pact file.
607 |
608 | Running the verification against the provider now passes. Yay!
609 |
610 | ```console
611 | $ rake pact:verify
612 | SPEC_OPTS='' /home/theeban/.rvm/rubies/ruby-2.3.0/bin/ruby -S pact verify --pact-helper /home/theeban/Projects/pact-workshop-android/provider/spec/pact_helper.rb
613 | Reading pact at spec/pacts/our_consumer-our_provider.json
614 | WARN: Ignoring unsupported matching rules {"min"=>0} for path $['body']['animals']
615 |
616 | Verifying a pact between our_consumer and our_provider
617 | Given data count is > 0
618 | a request for json data
619 | with GET /provider.json?valid_date=2017-02-01T20%253A30%253A58.233%252B11%253A00
620 | returns a response which
621 | has status code 200
622 | has a matching body
623 | includes headers
624 | "Content-Type" with value "application/json"
625 |
626 | 1 interaction, 0 failures
627 | ```
628 |
629 | # Step 8 - Test for the missing query parameter
630 |
631 | In this step we are going to add a test for the case where the query parameter is missing. We do
632 | this by adding additional expectations.
633 |
634 | ServiceMissingQueryPactTest.java:
635 |
636 | ```java
637 | public class ServiceMissingQueryPactTest {
638 |
639 | Service service;
640 |
641 | @Before
642 | public void setUp() {
643 | NetworkModule networkModule = new NetworkModule();
644 | service = new Service(networkModule.getRetrofit(mock(Context.class), "http://localhost:9292").create(Service.Api.class));
645 | }
646 |
647 | @Rule
648 | public PactProviderRule mockProvider = new PactProviderRule("our_provider", "localhost", 9292, this);
649 |
650 | @Pact(provider = "our_provider", consumer = "our_consumer")
651 | public PactFragment createFragment(PactDslWithProvider builder) throws UnsupportedEncodingException {
652 | return builder
653 | .given("data count is > 0")
654 | .uponReceiving("a request with an missing date parameter")
655 | .path("/provider.json")
656 | .method("GET")
657 | .willRespondWith()
658 | .status(400)
659 | .body("valid_date is required")
660 | .toFragment();
661 | }
662 |
663 | @Test
664 | @PactVerification("our_provider")
665 | public void should_process_the_json_payload_from_provider() {
666 | TestObserver observer = service.fetchResponse(null).test();
667 | observer.assertError(BadRequestException.class);
668 | }
669 | }
670 | ```
671 |
672 | After running our tests, the pact file will have a new interaction.
673 |
674 | spec/pacts/our_consumer-our_provider.json:
675 |
676 | ```json
677 | {
678 | "description": "a request with an missing date parameter",
679 | "request": {
680 | "method": "GET",
681 | "path": "/provider.json"
682 | },
683 | "response": {
684 | "status": 400,
685 | "body": "valid_date is required"
686 | },
687 | "providerState": "data count is > 0"
688 | }
689 | ```
690 |
691 | Let us run this updated pact file with our provider.
692 |
693 | We get a lot of errors because our provider fails with a 500 status and an HTML error page.
694 | Time to update the provider to handle these cases.
695 |
696 | ## Step 9 - Updated the provider to handle the missing query parameter
697 |
698 | lib/provider.rb:
699 |
700 | ```ruby
701 | class Provider < Sinatra::Base
702 |
703 | get '/provider.json', :provides => 'json' do
704 | if params[:valid_date].nil?
705 | [400, '"valid_date is required"']
706 | else
707 | valid_time = Time.parse(params[:valid_date])
708 | JSON.pretty_generate({
709 | :test => 'NO',
710 | :valid_date => DateTime.now,
711 | :animals => ProviderData.animals
712 | })
713 | end
714 | end
715 |
716 | end
717 | ```
718 |
719 | Now the pact verification all passes.
720 |
721 | ## Step 10 - Provider states
722 |
723 | We have one final thing to test for. We need to handle when there is no animals. This is an important bit of information to add to our contract. Let us start with a
724 | consumer test for this.
725 |
726 | ServiceNoContentPactTest.java:
727 |
728 | ```java
729 | public class ServiceNoContentPactTest {
730 |
731 | static final DateTime DATE_TIME;
732 |
733 | static {
734 | DATE_TIME = DateTime.now();
735 | }
736 |
737 | Service service;
738 |
739 | @Before
740 | public void setUp() {
741 | NetworkModule networkModule = new NetworkModule();
742 | service = new Service(networkModule.getRetrofit(mock(Context.class), "http://localhost:9292").create(Service.Api.class));
743 | }
744 |
745 | @Rule
746 | public PactProviderRule mockProvider = new PactProviderRule("our_provider", "localhost", 9292, this);
747 |
748 | @Pact(provider = "our_provider", consumer = "our_consumer")
749 | public PactFragment createFragment(PactDslWithProvider builder) throws UnsupportedEncodingException {
750 | return builder
751 | .given("data count is == 0")
752 | .uponReceiving("a request for json data")
753 | .path("/provider.json")
754 | .method("GET")
755 | .query("valid_date=" + DateHelper.encodeDate(DATE_TIME))
756 | .willRespondWith()
757 | .status(404)
758 | .toFragment();
759 | }
760 |
761 | @Test
762 | @PactVerification("our_provider")
763 | public void should_process_the_json_payload_from_provider() {
764 | TestObserver observer = service.fetchResponse(DATE_TIME).test();
765 | observer.assertNoErrors();
766 | observer.assertValue(new ServiceResponse(null, Collections.emptyList()));
767 | }
768 | }
769 | ```
770 |
771 | ```json
772 | {
773 | "description": "a request for json data",
774 | "request": {
775 | "method": "GET",
776 | "path": "/provider.json",
777 | "query": "valid_date=2017-02-01T20%253A50%253A45.397%252B11%253A00"
778 | },
779 | "response": {
780 | "status": 404
781 | },
782 | "providerState": "data count is == 0"
783 | },
784 | ```
785 |
786 | To be able to verify our provider, we create a data class that the provider can use, and then set the data in
787 | the state change setup callback.
788 |
789 | lib/provider.rb:
790 |
791 | ```ruby
792 | class Provider < Sinatra::Base
793 |
794 | get '/provider.json', :provides => 'json' do
795 | if params[:valid_date].nil?
796 | [400, '"valid_date is required"']
797 | elsif ProviderData.animals.size == 0
798 | 404
799 | else
800 | valid_time = Time.parse(params[:valid_date])
801 | JSON.pretty_generate({
802 | :test => 'NO',
803 | :valid_date => DateTime.now,
804 | :animals => ProviderData.animals
805 | })
806 | end
807 | end
808 |
809 | end
810 | ```
811 |
812 | Now we can set the data count appropriately.
813 |
814 | spec/pact_helper.rb:
815 |
816 | ```ruby
817 | Pact.provider_states_for "our_consumer" do
818 |
819 | provider_state "data count is > 0" do
820 | set_up do
821 | ProviderData.animals = ANIMALS_LIST
822 | end
823 | end
824 |
825 | provider_state "data count is == 0" do
826 | set_up do
827 | ProviderData.animals = []
828 | end
829 | end
830 |
831 | end
832 | ```
833 |
834 | Running the provider verification passes. Awesome, we are all done.
835 |
836 | ## Step 11 - Sharing pacts with the Pact Broker
837 |
838 | OK, so now we have our Consumer generating pacts and our Provider verifying
839 | them - awesome! But what if other teams are providing APIs for you to consumer?
840 | It's a bit cumbersome sharing files around like this.
841 |
842 | How can we effectively collaborate on these contracts?
843 |
844 | This is where the [Pact Broker](https://github.com/bethesque/pact_broker) comes in, The Pact Broker
845 | enables you to share your pacts between projects. It has a bunch of features, but for
846 | now we are most interested in the fact that it lets us query and manage them via an HTTP API.
847 |
848 | In our consumer gradle build, we've added a new task to do this.
849 |
850 | app/build.gradle:
851 |
852 | ```groovy
853 | pact {
854 | publish {
855 | pactDirectory = 'app/target/pacts'
856 | pactBrokerUrl = 'https://dXfltyFMgNOFZAxr8io9wJ37iUpY42M:O5AIZWxelWbLvqMd8PkAVycBJh2Psyg1@test.pact.dius.com.au/'
857 | version = '1.0.0'
858 | }
859 | }
860 | ```
861 |
862 | Run `./gradlew pactPublish` to grab all pacts from `app/target/pacts` and publish them to our broker, assiging them
863 | the version `1.0.0`.
864 |
865 | Head over to https://test.pact.dius.com.au/ui/relationships to see a visualisation of this.
866 |
867 | Now that we've published the contracts, in your provider build, we update the `pact_helper.rb` to pull pacts from the broker instead of a local file:
868 |
869 | spec/pact_helper.rb:
870 |
871 | ```ruby
872 | Pact.service_provider "our_provider" do
873 |
874 | honours_pact_with 'our_consumer' do
875 | pact_uri URI.encode('https://test.pact.dius.com.au/pact/provider/our_provider/consumer/our_consumer/latest')
876 | end
877 |
878 | end
879 | ```
880 |
--------------------------------------------------------------------------------