|
| 1 | +package io.reflectoring; |
| 2 | + |
| 3 | +import java.lang.reflect.Method; |
| 4 | +import java.util.List; |
| 5 | +import java.util.Map; |
| 6 | +import java.util.Set; |
| 7 | +import java.util.stream.Collectors; |
| 8 | + |
| 9 | +import au.com.dius.pact.model.Interaction; |
| 10 | +import au.com.dius.pact.model.v3.messaging.Message; |
| 11 | +import au.com.dius.pact.provider.ConsumerInfo; |
| 12 | +import au.com.dius.pact.provider.PactVerifyProvider; |
| 13 | +import au.com.dius.pact.provider.ProviderInfo; |
| 14 | +import au.com.dius.pact.provider.ProviderVerifier; |
| 15 | +import org.reflections.Reflections; |
| 16 | +import org.reflections.scanners.MethodAnnotationsScanner; |
| 17 | +import org.reflections.util.ConfigurationBuilder; |
| 18 | + |
| 19 | +public class CustomProviderVerifier extends ProviderVerifier { |
| 20 | + |
| 21 | + private List<String> packagesToScan; |
| 22 | + |
| 23 | + public CustomProviderVerifier(List<String> packagesToScan) { |
| 24 | + this.packagesToScan = packagesToScan; |
| 25 | + } |
| 26 | + |
| 27 | + @Override |
| 28 | + public boolean verifyResponseByInvokingProviderMethods(ProviderInfo providerInfo, ConsumerInfo consumer, |
| 29 | + Object interaction, String interactionMessage, Map failures) { |
| 30 | + try { |
| 31 | + |
| 32 | + ConfigurationBuilder configurationBuilder = new ConfigurationBuilder() |
| 33 | + .setScanners(new MethodAnnotationsScanner()) |
| 34 | + .forPackages(packagesToScan.toArray(new String[]{})); |
| 35 | + |
| 36 | + Reflections reflections = new Reflections(configurationBuilder); |
| 37 | + Set<Method> methodsAnnotatedWith = reflections.getMethodsAnnotatedWith(PactVerifyProvider.class); |
| 38 | + Set<Method> providerMethods = methodsAnnotatedWith.stream() |
| 39 | + .filter(m -> { |
| 40 | + PactVerifyProvider annotation = m.getAnnotation(PactVerifyProvider.class); |
| 41 | + return annotation.value().equals(((Interaction)interaction).getDescription()); |
| 42 | + }) |
| 43 | + .collect(Collectors.toSet()); |
| 44 | + |
| 45 | + if (providerMethods.isEmpty()) { |
| 46 | + throw new RuntimeException("No annotated methods were found for interaction " + |
| 47 | + "'${interaction.description}'. You need to provide a method annotated with " + |
| 48 | + "@PactVerifyProvider(\"${interaction.description}\") that returns the message contents."); |
| 49 | + } else { |
| 50 | + if (interaction instanceof Message) { |
| 51 | + verifyMessagePact(providerMethods, (Message) interaction, interactionMessage, failures); |
| 52 | + } else { |
| 53 | + throw new RuntimeException("only supports Message interactions!"); |
| 54 | + } |
| 55 | + } |
| 56 | + } catch (Exception e) { |
| 57 | + throw new RuntimeException("verification failed", e); |
| 58 | + } |
| 59 | + return true; |
| 60 | + } |
| 61 | + |
| 62 | +} |
0 commit comments