プラガブルアーキテクチャの使用
契約が YAML、RAML、PACT などの他の形式で定義されている場合があります。そのような場合でも、テストとスタブの自動生成のメリットを活用する必要があります。テストとスタブの両方を生成するための独自の実装を追加できます。また、テストの生成方法 (たとえば、他の言語のテストを生成できます) やスタブの生成方法 (たとえば、他の HTTP サーバー実装用のスタブを生成できます) をカスタマイズできます。
カスタム契約コンバーター
ContractConverter
インターフェースを使用すると、契約構造コンバーターの独自の実装を登録できます。次のコードリストは、ContractConverter
インターフェースを示しています。
import java.io.File;
import java.util.Collection;
/**
* Converter to be used to convert FROM {@link File} TO {@link Contract} and from
* {@link Contract} to {@code T}.
*
* @param <T> - type to which we want to convert the contract
* @author Marcin Grzejszczak
* @since 1.1.0
*/
public interface ContractConverter<T> extends ContractStorer<T>, ContractReader<T> {
/**
* Should this file be accepted by the converter. Can use the file extension to check
* if the conversion is possible.
* @param file - file to be considered for conversion
* @return - {@code true} if the given implementation can convert the file
*/
boolean isAccepted(File file);
/**
* Converts the given {@link File} to its {@link Contract} representation.
* @param file - file to convert
* @return - {@link Contract} representation of the file
*/
Collection<Contract> convertFrom(File file);
/**
* Converts the given {@link Contract} to a {@link T} representation.
* @param contract - the parsed contract
* @return - {@link T} the type to which we do the conversion
*/
T convertTo(Collection<Contract> contract);
}
実装では、変換を開始する条件を定義する必要があります。また、その変換を両方向で実行する方法を定義する必要があります。
実装を作成したら、実装の完全修飾名を指定する /META-INF/spring.factories ファイルを作成する必要があります。 |
次の例は、典型的な spring.factories
ファイルを示しています。
org.springframework.cloud.contract.spec.ContractConverter=\
org.springframework.cloud.contract.verifier.converter.YamlContractConverter
カスタムテストジェネレーターの使用
Java 以外の言語のテストを生成したい場合、または検証ツールによる Java テストの構築方法に満足できない場合は、独自の実装を登録できます。
SingleTestGenerator
インターフェースを使用すると、独自の実装を登録できます。次のコードリストは、SingleTestGenerator
インターフェースを示しています。
import java.nio.file.Path;
import java.util.Collection;
import org.springframework.cloud.contract.verifier.config.ContractVerifierConfigProperties;
import org.springframework.cloud.contract.verifier.file.ContractMetadata;
/**
* Builds a single test.
*
* @since 1.1.0
*/
public interface SingleTestGenerator {
/**
* Creates contents of a single test class in which all test scenarios from the
* contract metadata should be placed.
* @param properties - properties passed to the plugin
* @param listOfFiles - list of parsed contracts with additional metadata
* @param generatedClassData - information about the generated class
* @param includedDirectoryRelativePath - relative path to the included directory
* @return contents of a single test class
*/
String buildClass(ContractVerifierConfigProperties properties, Collection<ContractMetadata> listOfFiles,
String includedDirectoryRelativePath, GeneratedClassData generatedClassData);
class GeneratedClassData {
public final String className;
public final String classPackage;
public final Path testClassPath;
public GeneratedClassData(String className, String classPackage, Path testClassPath) {
this.className = className;
this.classPackage = classPackage;
this.testClassPath = testClassPath;
}
}
}
ここでも、次の例に示すような spring.factories
ファイルを指定する必要があります。
org.springframework.cloud.contract.verifier.builder.SingleTestGenerator=/
com.example.MyGenerator
カスタムスタブジェネレーターの使用
WireMock 以外のスタブサーバーのスタブを生成する場合は、StubGenerator
インターフェースの独自の実装をプラグインできます。次のコードリストは、StubGenerator
インターフェースを示しています。
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.cloud.contract.spec.Contract;
import org.springframework.cloud.contract.verifier.file.ContractMetadata;
/**
* Converts contracts into their stub representation.
*
* @param <T> - type of stub mapping
* @since 1.1.0
*/
public interface StubGenerator<T> {
/**
* @param mapping - potential stub mapping mapping
* @return {@code true} if this converter could have generated this mapping stub.
*/
default boolean canReadStubMapping(File mapping) {
return mapping.getName().endsWith(fileExtension());
}
/**
* @param rootName - root name of the contract
* @param content - metadata of the contract
* @return the collection of converted contracts into stubs. One contract can result
* in multiple stubs.
*/
Map<Contract, String> convertContents(String rootName, ContractMetadata content);
/**
* Post process a generated stub mapping.
* @param stubMapping - mapping of a stub
* @param contract - contract for which stub was generated
* @return the converted stub mapping
*/
default T postProcessStubMapping(T stubMapping, Contract contract) {
List<StubPostProcessor> processors = StubPostProcessor.PROCESSORS.stream()
.filter(p -> p.isApplicable(contract))
.collect(Collectors.toList());
if (processors.isEmpty()) {
return defaultStubMappingPostProcessing(stubMapping, contract);
}
T stub = stubMapping;
for (StubPostProcessor processor : processors) {
stub = (T) processor.postProcess(stub, contract);
}
return stub;
}
/**
* Stub mapping to chose when no post processors where found on the classpath.
* @param stubMapping - mapping of a stub
* @param contract - contract for which stub was generated
* @return the converted stub mapping
*/
default T defaultStubMappingPostProcessing(T stubMapping, Contract contract) {
return stubMapping;
}
/**
* @param inputFileName - name of the input file
* @return the name of the converted stub file. If you have multiple contracts in a
* single file then a prefix will be added to the generated file. If you provide the
* {@link Contract#getName} field then that field will override the generated file
* name.
*
* Example: name of file with 2 contracts is {@code foo.groovy}, it will be converted
* by the implementation to {@code foo.json}. The recursive file converter will create
* two files {@code 0_foo.json} and {@code 1_foo.json}
*/
String generateOutputFileNameForInput(String inputFileName);
/**
* Describes the file extension of the generated mapping that this stub generator can
* handle.
* @return string describing the file extension
*/
default String fileExtension() {
return ".json";
}
}
ここでも、次の例に示すような spring.factories
ファイルを指定する必要があります。
# Stub converters
org.springframework.cloud.contract.verifier.converter.StubGenerator=\
org.springframework.cloud.contract.verifier.wiremock.DslToWireMockClientConverter
デフォルトの実装は、WireMock スタブの生成です。
複数のスタブジェネレーター実装を提供できます。例: 単一の DSL から、WireMock スタブと Pact ファイルの両方を生成できます。 |
カスタムスタブランナーの使用
カスタムスタブ生成を使用する場合は、別のスタブプロバイダーでスタブを実行するカスタム方法も必要です。
モコ [GitHub] (英語) を使用してスタブを構築し、スタブジェネレーターを作成してスタブを JAR ファイルに配置したと仮定します。
スタブランナーがスタブの実行方法を認識できるようにするには、次の例のようなカスタム HTTP スタブサーバー実装を定義する必要があります。
import com.github.dreamhead.moco.bootstrap.arg.HttpArgs
import com.github.dreamhead.moco.runner.JsonRunner
import com.github.dreamhead.moco.runner.RunnerSetting
import groovy.transform.CompileStatic
import groovy.util.logging.Commons
import org.springframework.cloud.contract.stubrunner.HttpServerStub
import org.springframework.cloud.contract.stubrunner.HttpServerStubConfiguration
@Commons
@CompileStatic
class MocoHttpServerStub implements HttpServerStub {
private boolean started
private JsonRunner runner
private int port
@Override
int port() {
if (!isRunning()) {
return -1
}
return port
}
@Override
boolean isRunning() {
return started
}
@Override
HttpServerStub start(HttpServerStubConfiguration configuration) {
this.port = configuration.port
return this
}
@Override
HttpServerStub stop() {
if (!isRunning()) {
return this
}
this.runner.stop()
return this
}
@Override
HttpServerStub registerMappings(Collection<File> stubFiles) {
List<RunnerSetting> settings = stubFiles.findAll { it.name.endsWith("json") }
.collect {
log.info("Trying to parse [${it.name}]")
try {
return RunnerSetting.aRunnerSetting().addStream(it.newInputStream()).
build()
}
catch (Exception e) {
log.warn("Exception occurred while trying to parse file [${it.name}]", e)
return null
}
}.findAll { it }
this.runner = JsonRunner.newJsonRunnerWithSetting(settings,
HttpArgs.httpArgs().withPort(this.port).build())
this.runner.run()
this.started = true
return this
}
@Override
String registeredMappings() {
return ""
}
@Override
boolean isAccepted(File file) {
return file.name.endsWith(".json")
}
}
次に、次の例に示すように、それを spring.factories
ファイルに登録できます。
org.springframework.cloud.contract.stubrunner.HttpServerStub=\
org.springframework.cloud.contract.stubrunner.provider.moco.MocoHttpServerStub
これで、Moco でスタブを実行できるようになりました。
実装を指定しない場合は、デフォルト (WireMock) 実装が使用されます。複数指定した場合は、リストの最初のものが使用されます。 |
カスタムスタブダウンローダーの使用
次の例に示すように、StubDownloaderBuilder
インターフェースの実装を作成することで、スタブのダウンロード方法をカスタマイズできます。
class CustomStubDownloaderBuilder implements StubDownloaderBuilder {
@Override
public StubDownloader build(final StubRunnerOptions stubRunnerOptions) {
return new StubDownloader() {
@Override
public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(
StubConfiguration config) {
File unpackedStubs = retrieveStubs();
return new AbstractMap.SimpleEntry<>(
new StubConfiguration(config.getGroupId(), config.getArtifactId(), version,
config.getClassifier()), unpackedStubs);
}
File retrieveStubs() {
// here goes your custom logic to provide a folder where all the stubs reside
}
}
}
}
次に、次の例に示すように、それを spring.factories
ファイルに登録できます。
# Example of a custom Stub Downloader Provider
org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder=\
com.example.CustomStubDownloaderBuilder
これで、スタブのソースが含まれるフォルダーを選択できるようになりました。
実装を指定しない場合は、デフォルト (クラスパスのスキャン) が使用されます。stubsMode = StubRunnerProperties.StubsMode.LOCAL または stubsMode = StubRunnerProperties.StubsMode.REMOTE を指定した場合は、Aether 実装が使用されます。複数を指定した場合は、リストの最初の実装が使用されます。 |
SCM スタブダウンローダーの使用
repositoryRoot
が SCM プロトコル (現在は git://
のみをサポートしています) で開始されるたびに、スタブダウンローダーはリポジトリを複製し、それを契約のソースとして使用してテストまたはスタブを生成しようとします。
環境変数、システムプロパティ、またはプラグインまたは契約 リポジトリ設定内に設定されたプロパティを通じて、ダウンローダーの動作を微調整できます。次の表に、使用可能なプロパティを示します。
プロパティの型 | プロパティの名前 | 説明 |
* * * | マスター | どのブランチをチェックアウトするか |
* * * | Git クローンのユーザー名 | |
* * * | Git クローンのパスワード | |
* * * | 10 |
|
* * * | 1000 |
|