diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e7aca4e..512ea4b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -30,8 +30,11 @@ jobs: GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }} run: echo "GPG key loaded" - - name: Build and publish - run: ./gradlew build :preflight-core:preflight-gradle-plugin:publishPlugins :preflight-core:preflight-runtime:publishMavenPublicationToOrbitalRepository :preflight-core:preflight-spec:publishMavenPublicationToOrbitalRepository + - name: Publish preflight-spec + run: cd preflight-spec && ./gradlew build publishMavenPublicationToOrbitalRepository + + - name: Build and publish preflight-core + run: ./gradlew build :preflight-core:preflight-gradle-plugin:publishPlugins :preflight-core:preflight-runtime:publishMavenPublicationToOrbitalRepository env: GRADLE_PUBLISH_KEY: ${{ secrets.GRADLE_PUBLISH_KEY }} GRADLE_PUBLISH_SECRET: ${{ secrets.GRADLE_PUBLISH_SECRET }} diff --git a/BUILDING.md b/BUILDING.md index 231c656..740fd05 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -1,19 +1,25 @@ # Building and Releasing -## Building locally +## Project Structure -```bash -cd preflight-core -./gradlew build -``` +The repository uses two separate Gradle builds connected via composite builds: + +- **`preflight-spec/`** — Standalone build for the markdown test spec parser/writer. Has no Orbital dependencies (only commonmark + jackson), so Orbital itself can depend on it without circular dependencies. +- **`preflight-core/`** — Main build containing `preflight-runtime` and `preflight-gradle-plugin`. Depends on Orbital libraries. Consumes `preflight-spec` via composite build (`includeBuild`). -This builds all modules (`preflight-spec`, `preflight-runtime`, `preflight-gradle-plugin`) and runs their tests. +The root `settings.gradle.kts` wires both builds together along with the example projects. -To also run the example project tests: +## Building locally ```bash -# From the repo root +# Full build from repo root (builds everything including examples) ./gradlew build + +# Build preflight-spec standalone +cd preflight-spec && ./gradlew build + +# Build preflight-core (resolves preflight-spec via composite build) +cd preflight-core && ./gradlew build ``` ## Installing to local Maven repo @@ -51,16 +57,12 @@ The plugin itself injects the Orbital Maven repositories automatically, so no ot ## Bumping the version -The version is set in one place: `preflight-core/build.gradle.kts` +The version is set in **two places** (kept in sync manually): -```kotlin -allprojects { - group = "com.orbitalhq.preflight" - version = "0.1.0" // <-- change this -} -``` +1. `preflight-core/build.gradle.kts` — `val PROJECT_VERSION = "0.1.0-SNAPSHOT"` +2. `preflight-spec/build.gradle.kts` — `version = "0.1.0-SNAPSHOT"` -All submodules inherit this version. The Gradle plugin also embeds it at build time via a generated `Versions.kt` constant. +All preflight-core submodules inherit their version from `preflight-core/build.gradle.kts`. The Gradle plugin also embeds it at build time via a generated `Versions.kt` constant. ## Releasing @@ -71,7 +73,7 @@ Releases are triggered by pushing a git tag. GitHub Actions handles building, si git checkout main git pull -# 2. Bump the version in preflight-core/build.gradle.kts, commit +# 2. Bump the version in both build.gradle.kts files, commit # 3. Tag the release git tag v0.1.0 @@ -84,9 +86,10 @@ git push origin v0.1.0 The `release.yml` workflow then: 1. Builds the project with JDK 21 2. Signs artifacts with GPG -3. Publishes the Gradle plugin to the **Gradle Plugin Portal** -4. Publishes `preflight-runtime` and `preflight-spec` to the **Orbital Maven repository** (`s3://repo.orbitalhq.com/release`) -5. Creates a GitHub Release with JARs and auto-generated notes +3. Publishes `preflight-spec` to the **Orbital Maven repository** +4. Publishes the Gradle plugin to the **Gradle Plugin Portal** +5. Publishes `preflight-runtime` to the **Orbital Maven repository** +6. Creates a GitHub Release with JARs and auto-generated notes ## Where artifacts are published diff --git a/CLAUDE.md b/CLAUDE.md index 83339bd..b884fba 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,11 +8,17 @@ Preflight is a Kotlin-based testing framework for Taxi/Orbital projects. It prov ### Core Components +- **preflight-spec**: Standalone markdown test spec parser/writer (`preflight-spec/`) + - Has zero Orbital dependencies (only commonmark + jackson) + - Lives in its own top-level Gradle build so Orbital can depend on it without circular dependencies + - `TestSpecReader` / `TestSpecWriter`: Parse and generate markdown test specifications + - **preflight-runtime**: Core testing DSL and execution engine (`preflight-core/preflight-runtime/`) - `OrbitalSpec`: Base test class extending Kotest's DescribeSpec with Taxi/Orbital-specific functionality - `PreflightExtension`: Kotest extension that handles Taxi compilation and Orbital service initialization - `StubHelper`: Utilities for stubbing external data sources in tests - Environment variable support and configuration management + - Depends on `preflight-spec` via Maven coordinates (resolved by composite build locally) - **preflight-gradle-plugin**: Gradle plugin for project integration (`preflight-core/preflight-gradle-plugin/`) - `PreflightPlugin`: Main plugin class that configures Kotlin JVM, dependencies, and test execution @@ -20,8 +26,10 @@ Preflight is a Kotlin-based testing framework for Taxi/Orbital projects. It prov ### Project Structure -The repository uses a composite build structure: -- Root project includes core modules and example projects as composite builds +The repository uses a two-build composite structure: +- `preflight-spec/` — standalone Gradle build (no Orbital dependencies) +- `preflight-core/` — main Gradle build containing runtime and plugin (depends on Orbital) +- Root `settings.gradle.kts` wires both builds together with example projects via `includeBuild` - Example projects demonstrate usage patterns and serve as integration tests - Documentation site built with Next.js in `docs/` directory @@ -119,4 +127,8 @@ preflight { ## Version Management -Project version is managed centrally in `preflight-core/build.gradle.kts` (currently 0.0.4). The Gradle plugin uses code generation to embed version constants at build time via the `generateVersionConstants` task. \ No newline at end of file +Project version is set in two places (kept in sync manually): +- `preflight-core/build.gradle.kts` — `val PROJECT_VERSION = "0.1.0-SNAPSHOT"` (inherited by runtime and plugin) +- `preflight-spec/build.gradle.kts` — `version = "0.1.0-SNAPSHOT"` + +The Gradle plugin uses code generation to embed version constants at build time via the `generateVersionConstants` task. \ No newline at end of file diff --git a/example-projects/warehouse-orders/build.gradle.kts b/example-projects/warehouse-orders/build.gradle.kts index 2e5e3d5..dd1d35c 100644 --- a/example-projects/warehouse-orders/build.gradle.kts +++ b/example-projects/warehouse-orders/build.gradle.kts @@ -7,24 +7,24 @@ plugins { // OR specify a custom Orbital version preflight { - orbitalVersion = "0.38.0-SNAPSHOT" + orbitalVersion = "0.38.0-M4" } repositories { mavenLocal() mavenCentral() - maven { - name = "orbital" - url = URI("https://repo.orbitalhq.com/release") - mavenContent { - releasesOnly() - } - } - maven { - name = "orbital-snapshot" - url = URI("https://repo.orbitalhq.com/snapshot") - mavenContent { - snapshotsOnly() - } - } +// maven { +// name = "orbital" +// url = URI("https://repo.orbitalhq.com/release") +// mavenContent { +// releasesOnly() +// } +// } +// maven { +// name = "orbital-snapshot" +// url = URI("https://repo.orbitalhq.com/snapshot") +// mavenContent { +// snapshotsOnly() +// } +// } } diff --git a/example-projects/warehouse-orders/test-resources/specs/enrich-warehouse-order.spec.md b/example-projects/warehouse-orders/test-resources/specs/enrich-warehouse-order.spec.md index 8b410a4..a3e9166 100644 --- a/example-projects/warehouse-orders/test-resources/specs/enrich-warehouse-order.spec.md +++ b/example-projects/warehouse-orders/test-resources/specs/enrich-warehouse-order.spec.md @@ -4,7 +4,7 @@ spec-version: 0.1 # Enrich warehouse order -This test covers streaming a warehouse order event and eniching it with a product name from an API +This test covers streaming a warehouse order event and enriching it with a product name from an API ## Query @@ -24,31 +24,75 @@ stream { SurePostDeliveryEvent } as { Message: ```json { - "productId" : "PROD-1001", - "qtyDelivered" : 45, - "orderId" : "520c80f8-661e-48c7-8b4e-c9c36bd93785", + "productId" : "PROD-1013", + "qtyDelivered" : 72, + "orderId" : "a29788b5-6b7a-4c30-8e9c-775c1341fef8", "supplierId" : "SUREPOST", - "timestamp" : "2026-02-26T05:54:25.719167197" + "timestamp" : "2026-02-27T08:21:37.136364734" } ``` +Message: +```json +{ + "productId" : "PROD-1003", + "qtyDelivered" : 20, + "orderId" : "e69e51a4-85e6-4fe6-90a8-4faec726e316", + "supplierId" : "SUREPOST", + "timestamp" : "2026-02-27T08:21:39.136643659" +} +``` + +Message: +```json +{ + "productId" : "PROD-1003", + "qtyDelivered" : 26, + "orderId" : "5e3ea02a-9eaf-45c9-ab66-9150d5aeb981", + "supplierId" : "SUREPOST", + "timestamp" : "2026-02-27T08:21:41.136906122" +} +``` + +### getProduct + + +Request: +```json +{ + "productId" : "PROD-1013" +} +``` + +Response: +```json +{"productId":"PROD-1013","sku":"SKU-WEB013","productName":"HD Webcam with Microphone","category":"Electronics","storageLocation":"WAREHOUSE-A-02"} +``` + ### getProduct +Request: +```json +{ + "productId" : "PROD-1003" +} +``` + Response: ```json -{"productId":"PROD-1001","sku":"SKU-LAP001","productName":"Gaming Laptop Pro 15\"","category":"Electronics","storageLocation":"WAREHOUSE-A-02"} +{"productId":"PROD-1003","sku":"SKU-KEY003","productName":"Mechanical Keyboard RGB","category":"Accessories","storageLocation":"WAREHOUSE-B-01"} ``` ## Expected Result ```json { - "productName" : "Gaming Laptop Pro 15\"", - "productId" : "PROD-1001", - "qtyDelivered" : 45, - "orderId" : "520c80f8-661e-48c7-8b4e-c9c36bd93785", + "productName" : "HD Webcam with Microphone", + "productId" : "PROD-1013", + "qtyDelivered" : 72, + "orderId" : "a29788b5-6b7a-4c30-8e9c-775c1341fef8", "supplierId" : "SUREPOST", - "timestamp" : "26-Feb-2026 05:54:25" + "timestamp" : "27-Feb-2026 08:21:37" } -``` +``` \ No newline at end of file diff --git a/preflight-core/build.gradle.kts b/preflight-core/build.gradle.kts index 81fd26f..d9a9610 100644 --- a/preflight-core/build.gradle.kts +++ b/preflight-core/build.gradle.kts @@ -9,6 +9,7 @@ plugins { `maven-publish` } +val PROJECT_VERSION = "0.1.0-SNAPSHOT" tasks.register("publishAll") { @@ -26,7 +27,7 @@ tasks.register("publishAllMavenLocal") { allprojects { group = "com.orbitalhq.preflight" - version = "0.1.0-M2" + version = PROJECT_VERSION repositories { mavenCentral() diff --git a/preflight-core/preflight-gradle-plugin/build.gradle.kts b/preflight-core/preflight-gradle-plugin/build.gradle.kts index f810748..9043627 100644 --- a/preflight-core/preflight-gradle-plugin/build.gradle.kts +++ b/preflight-core/preflight-gradle-plugin/build.gradle.kts @@ -52,6 +52,7 @@ tasks.shadowJar { archiveClassifier.set("") // Make this the main JAR dependencies { include(project(":preflight-runtime")) + include(dependency("com.orbitalhq.preflight:preflight-spec")) include(dependency("org.taxilang:.*")) include(dependency("com.orbitalhq:.*")) } diff --git a/preflight-core/preflight-runtime/build.gradle.kts b/preflight-core/preflight-runtime/build.gradle.kts index d76289c..c161530 100644 --- a/preflight-core/preflight-runtime/build.gradle.kts +++ b/preflight-core/preflight-runtime/build.gradle.kts @@ -4,10 +4,10 @@ plugins { } val taxiVersion = "1.71.0-SNAPSHOT" -val orbitalVersion = "0.38.0-SNAPSHOT" // Default version, can be overridden in consumer projects +val orbitalVersion = "0.38.0-M4" // Default version, can be overridden in consumer projects dependencies { - implementation(project(":preflight-spec")) + implementation("com.orbitalhq.preflight:preflight-spec") testImplementation(platform("org.junit:junit-bom:5.10.0")) testImplementation("org.junit.jupiter:junit-jupiter") implementation(platform("org.testcontainers:testcontainers-bom:1.19.3")) diff --git a/preflight-core/preflight-runtime/src/main/kotlin/com/orbitalhq/preflight/dsl/MarkdownSpec.kt b/preflight-core/preflight-runtime/src/main/kotlin/com/orbitalhq/preflight/dsl/MarkdownSpec.kt index b9e47fe..b04a62f 100644 --- a/preflight-core/preflight-runtime/src/main/kotlin/com/orbitalhq/preflight/dsl/MarkdownSpec.kt +++ b/preflight-core/preflight-runtime/src/main/kotlin/com/orbitalhq/preflight/dsl/MarkdownSpec.kt @@ -1,18 +1,19 @@ package com.orbitalhq.preflight.dsl +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper -import com.orbitalhq.models.Provided -import com.orbitalhq.models.TypedInstance -import com.orbitalhq.models.json.right +import com.fasterxml.jackson.module.kotlin.readValue +import com.orbitalhq.models.json.Jackson +import com.orbitalhq.preflight.spec.Stub import com.orbitalhq.preflight.spec.StubMode import com.orbitalhq.preflight.spec.TestSpec import com.orbitalhq.preflight.spec.TestSpecReader -import com.orbitalhq.schemas.fqn +import com.orbitalhq.query.RemoteCallExchangeMetadata import com.orbitalhq.stubbing.StubService import io.kotest.matchers.shouldBe import kotlinx.coroutines.flow.flowOf import java.nio.file.Files -import java.nio.file.Path import java.nio.file.Paths import kotlin.io.path.extension import kotlin.io.path.isRegularFile @@ -41,24 +42,65 @@ abstract class MarkdownSpec( private fun OrbitalSpec.registerSpec( spec: TestSpec, - objectMapper: com.fasterxml.jackson.databind.ObjectMapper + objectMapper: ObjectMapper ) { val stubCustomizer: (StubService) -> Unit = { stubService -> - for (stub in spec.dataSources) { - when (stub.mode) { - StubMode.REQUEST_RESPONSE -> { - val response = stub.response - if (response != null) { - stubService.addResponse(stub.operationName, response) + + val stubsByOperationName = spec.dataSources.groupBy { it.operationName } + stubsByOperationName + .forEach { (operationName, stubbedCalls) -> + if (stubbedCalls.isNotEmpty()) { + val modes = stubbedCalls.map { it.mode }.distinct() + if (modes.size > 1) { + // There's no reason we can't support this in theory, but I don't think it's a real use-case, + // and complicates the execution, as we need to further split these + error("Operation $operationName has a mix of stub modes (${modes.joinToString()}) which is not currently supported") } - } - StubMode.STREAM -> { - stubService.addResponseFlow(stub.operationName) { _,_ -> - val messages = messagesAsTypedInstanceResponses(stub, stubService.schema!!) - flowOf(*messages.toTypedArray()) + val singleStubMode = modes.single() + when (singleStubMode) { + StubMode.STREAM -> { + stubbedCalls.forEach { stub -> + stubService.addResponseFlow(stub.operationName) { _,_ -> + val messages = stubResponseAsTypedInstanceResponses(stub, stubService.schema!!) + flowOf(*messages.toTypedArray()) + } + } + } + + StubMode.REQUEST_RESPONSE -> { + val stubbedCallsByParameters: List, Stub>> = stubbedCalls.map { stubbedCall -> + val parametersAsMap = if (stubbedCall.parameters != null) { + Jackson.defaultObjectMapper.readValue>(stubbedCall.parameters!!) + } else emptyMap() + parametersAsMap to stubbedCall + } + stubService.addResponse(operationName) { _,parameters -> + // We need to match the request with the incoming parameters + if (parameters.isEmpty()) { + // If there's no parameters provided, we just match the first call + if (stubbedCalls.size != 1) { + error("The test spec is ambiguous. There are ${stubbedCalls.size} calls configured for ${operationName}, but no parameters are declared on the operation, so cannot determine which to pick") + } else { + val stubbedCall = stubbedCalls.single() + stubResponseAsTypedInstanceResponses(stubbedCall, stubService.schema!!) + } + } else { + // Otherwise, we need to map on parameters + val receivedParametersAsMap = RemoteCallExchangeMetadata.convertParametersToMap(parameters) + val matchingCalls = stubbedCallsByParameters.filter { it.first == receivedParametersAsMap } + when (matchingCalls.size) { + 0 -> error("No stubbed operation calls for operation ${operationName} matched on the provided parameters, although ${stubbedCalls.size} stubs are configured for this operation. Provided parameters: ${receivedParametersAsMap}") + 1 -> stubResponseAsTypedInstanceResponses(matchingCalls.single().second, stubService.schema!!) + else -> error("The test spec is ambiguous. There are ${matchingCalls.size} calls configured for ${operationName}, which match the parameters provided: ${receivedParametersAsMap}") + } + + } + } + } } } - } + + } } @@ -69,11 +111,11 @@ private fun OrbitalSpec.registerSpec( if (isArray) { val actual = spec.query.queryForCollectionOfMaps(stubCustomizer) - val actualJson = objectMapper.valueToTree(actual) + val actualJson = objectMapper.valueToTree(actual) actualJson shouldBe expectedJson } else { val actual = spec.query.queryForMap(stubCustomizer) - val actualJson = objectMapper.valueToTree(actual) + val actualJson = objectMapper.valueToTree(actual) actualJson shouldBe expectedJson } } diff --git a/preflight-core/preflight-runtime/src/main/kotlin/com/orbitalhq/preflight/dsl/PreflightExtension.kt b/preflight-core/preflight-runtime/src/main/kotlin/com/orbitalhq/preflight/dsl/PreflightExtension.kt index dd028cd..88d908b 100644 --- a/preflight-core/preflight-runtime/src/main/kotlin/com/orbitalhq/preflight/dsl/PreflightExtension.kt +++ b/preflight-core/preflight-runtime/src/main/kotlin/com/orbitalhq/preflight/dsl/PreflightExtension.kt @@ -327,39 +327,40 @@ class PreflightExtension( val context = PreflightTestCaseContext(testCase) return withContext(context) { val testResult = execute(testCase) - val capturedScenario = capturedScenarios[testCase] - if (testResult.isFailure && capturedScenario != null) { - val failure = testResult as TestResult.Failure - val cause = failure.cause - if (cause is AssertionFailedError) { - val originalError = failure.cause as AssertionFailedError - val (_, playgroundLink) = PlaygroundScenarioFactory.buildPlaygroundScenario( - capturedScenario, - sourcePackage, - schema, - originalError, - testCase - ) - val errorMessageWithPlaygroundLink = """${originalError.message} - | - |This error is explorable in Taxi Playground at the following link: $playgroundLink - """.trimMargin() - val failureWithPlaygroundLink = failure.copy( - cause = AssertionFailedError( - message = errorMessageWithPlaygroundLink, - cause = originalError.cause, - expectedValue = originalError.expectedValue, - actualValue = originalError.actualValue, - ) - ) - failureWithPlaygroundLink - } else { - testResult - } - - } else { - testResult - } + testResult +// val capturedScenario = capturedScenarios[testCase] +// if (testResult.isFailure && capturedScenario != null) { +// val failure = testResult as TestResult.Failure +// val cause = failure.cause +// if (cause is AssertionFailedError) { +// val originalError = failure.cause as AssertionFailedError +//// val (_, playgroundLink) = PlaygroundScenarioFactory.buildPlaygroundScenario( +//// capturedScenario, +//// sourcePackage, +//// schema, +//// originalError, +//// testCase +//// ) +//// val errorMessageWithPlaygroundLink = """${originalError.message} +//// | +//// |This error is explorable in Taxi Playground at the following link: $playgroundLink +//// """.trimMargin() +// val failureWithPlaygroundLink = failure.copy( +// cause = AssertionFailedError( +// message = originalError.message, +// cause = originalError.cause, +// expectedValue = originalError.expectedValue, +// actualValue = originalError.actualValue, +// ) +// ) +// failureWithPlaygroundLink +// } else { +// testResult +// } +// +// } else { +// testResult +// } } } diff --git a/preflight-core/preflight-runtime/src/main/kotlin/com/orbitalhq/preflight/dsl/StubHelper.kt b/preflight-core/preflight-runtime/src/main/kotlin/com/orbitalhq/preflight/dsl/StubHelper.kt index ed2edb5..c9d11c3 100644 --- a/preflight-core/preflight-runtime/src/main/kotlin/com/orbitalhq/preflight/dsl/StubHelper.kt +++ b/preflight-core/preflight-runtime/src/main/kotlin/com/orbitalhq/preflight/dsl/StubHelper.kt @@ -3,11 +3,13 @@ package com.orbitalhq.preflight.dsl import arrow.core.Either import com.orbitalhq.models.Provided import com.orbitalhq.models.TypedInstance +import com.orbitalhq.models.TypedNull import com.orbitalhq.models.json.right import com.orbitalhq.preflight.spec.Stub import com.orbitalhq.query.StreamErrorMessage import com.orbitalhq.schemas.Schema import com.orbitalhq.schemas.fqn +import lang.taxi.types.PrimitiveType import kotlin.collections.map import kotlin.collections.orEmpty @@ -33,12 +35,34 @@ data class StubResponseBuilder(val operationName: String) { data class StubScenario(val operationName: String, val response: String) -fun messagesAsTypedInstanceResponses(stub: Stub, schema: Schema): List> { - val (_,operation) = schema.remoteOperation(stub.operationName.fqn()) - val streamType = operation.returnType.typeParameters[0] - val messagesAsTypedInstances = stub.messages.orEmpty().map { json -> - TypedInstance.from(streamType, json, source = Provided, schema = schema) - .right() +/** + * Converts the stub response (either a request response, or a stream) into + * the format expected by the stub service + */ +fun stubResponseAsTypedInstanceResponses(stub: Stub, schema: Schema): List> { + val (_, operation) = schema.remoteOperation(stub.operationName.fqn()) + // Unwrap Array or Stream types + val stubResponseAsTypedInstance = when { + stub.messages != null -> { + // Should be a stream + val responseType = operation.returnType.typeParameters[0] + stub.messages.orEmpty().map { json -> + TypedInstance.from(responseType, json, source = Provided, schema = schema) + .right() + } + } + stub.response != null -> { + val responseType = operation.returnType + listOf(TypedInstance.from(responseType, stub.response, source = Provided, schema = schema).right()) + } + else -> { + // No response provided -- could be a void method - so return null + // Not actually sure what to return here, since void methods don't typically exist, + // but doesn't feel like a reasonable reason to bail + listOf(TypedNull.create(schema.type(PrimitiveType.ANY)).right()) + } } - return messagesAsTypedInstances + return stubResponseAsTypedInstance + + return stubResponseAsTypedInstance } \ No newline at end of file diff --git a/preflight-core/settings.gradle.kts b/preflight-core/settings.gradle.kts index b8e3711..470aefe 100644 --- a/preflight-core/settings.gradle.kts +++ b/preflight-core/settings.gradle.kts @@ -1,5 +1,6 @@ rootProject.name = "preflight-core" include("preflight-runtime") -include("preflight-spec") include("preflight-gradle-plugin") + +includeBuild("../preflight-spec") diff --git a/preflight-core/preflight-spec/README.md b/preflight-spec/README.md similarity index 100% rename from preflight-core/preflight-spec/README.md rename to preflight-spec/README.md diff --git a/preflight-core/preflight-spec/build.gradle.kts b/preflight-spec/build.gradle.kts similarity index 69% rename from preflight-core/preflight-spec/build.gradle.kts rename to preflight-spec/build.gradle.kts index f4feac4..b89b9e5 100644 --- a/preflight-core/preflight-spec/build.gradle.kts +++ b/preflight-spec/build.gradle.kts @@ -1,9 +1,22 @@ plugins { - kotlin("jvm") + kotlin("jvm") version "2.1.10" `maven-publish` } +group = "com.orbitalhq.preflight" +version = "0.1.0-SNAPSHOT" + +repositories { + mavenCentral() + mavenLocal() +} + +kotlin { + jvmToolchain(21) +} + dependencies { + implementation(kotlin("stdlib")) implementation("org.commonmark:commonmark:0.24.0") implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.17.2") @@ -21,6 +34,14 @@ publishing { publications { create("maven") { from(components["java"]) + pom { + licenses { + license { + name.set("The Apache License, Version 2.0") + url.set("https://www.apache.org/licenses/LICENSE-2.0.txt") + } + } + } } } repositories { diff --git a/preflight-spec/gradle/wrapper/gradle-wrapper.jar b/preflight-spec/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..9bbc975 Binary files /dev/null and b/preflight-spec/gradle/wrapper/gradle-wrapper.jar differ diff --git a/preflight-spec/gradle/wrapper/gradle-wrapper.properties b/preflight-spec/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..37f78a6 --- /dev/null +++ b/preflight-spec/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/preflight-spec/gradlew b/preflight-spec/gradlew new file mode 100755 index 0000000..faf9300 --- /dev/null +++ b/preflight-spec/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/preflight-spec/gradlew.bat b/preflight-spec/gradlew.bat new file mode 100644 index 0000000..9d21a21 --- /dev/null +++ b/preflight-spec/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/preflight-spec/settings.gradle.kts b/preflight-spec/settings.gradle.kts new file mode 100644 index 0000000..5a40745 --- /dev/null +++ b/preflight-spec/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "preflight-spec" diff --git a/preflight-core/preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/SpecParseException.kt b/preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/SpecParseException.kt similarity index 100% rename from preflight-core/preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/SpecParseException.kt rename to preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/SpecParseException.kt diff --git a/preflight-core/preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/TestSpec.kt b/preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/TestSpec.kt similarity index 95% rename from preflight-core/preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/TestSpec.kt rename to preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/TestSpec.kt index 3e4f1f0..8a06303 100644 --- a/preflight-core/preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/TestSpec.kt +++ b/preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/TestSpec.kt @@ -20,6 +20,7 @@ data class Stub( val label: String, val operationName: String, val mode: StubMode, + val parameters: String?, val response: String?, val messages: List? ) diff --git a/preflight-core/preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/TestSpecReader.kt b/preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/TestSpecReader.kt similarity index 97% rename from preflight-core/preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/TestSpecReader.kt rename to preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/TestSpecReader.kt index 1740b88..bcddba5 100644 --- a/preflight-core/preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/TestSpecReader.kt +++ b/preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/TestSpecReader.kt @@ -44,6 +44,7 @@ object TestSpecReader { // Stub parsing state var currentStubLabel: String? = null var currentStubDirectives = mutableListOf() + var currentStubParameters: String? = null var currentStubResponse: String? = null var currentStubMessages = mutableListOf() var lastParagraphLabel: String? = null @@ -88,12 +89,14 @@ object TestSpecReader { operationName = operationName, mode = mode, response = if (mode == StubMode.REQUEST_RESPONSE) currentStubResponse else null, - messages = if (mode == StubMode.STREAM) currentStubMessages.toList() else null + messages = if (mode == StubMode.STREAM) currentStubMessages.toList() else null, + parameters = currentStubParameters ) ) currentStubLabel = null currentStubDirectives = mutableListOf() + currentStubParameters = null currentStubResponse = null currentStubMessages = mutableListOf() lastParagraphLabel = null @@ -157,6 +160,7 @@ object TestSpecReader { if (currentStubLabel != null) { val content = node.literal.trimEnd() when (lastParagraphLabel) { + "Request" -> currentStubParameters = content "Response" -> currentStubResponse = content "Message" -> currentStubMessages.add(content) } diff --git a/preflight-core/preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/TestSpecWriter.kt b/preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/TestSpecWriter.kt similarity index 92% rename from preflight-core/preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/TestSpecWriter.kt rename to preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/TestSpecWriter.kt index 3eca62f..dce9c2b 100644 --- a/preflight-core/preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/TestSpecWriter.kt +++ b/preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/TestSpecWriter.kt @@ -44,6 +44,14 @@ object TestSpecWriter { } appendLine() + if (stub.parameters != null) { + appendLine("Request:") + appendLine("```json") + appendLine(stub.parameters) + appendLine("```") + appendLine() + } + when (stub.mode) { StubMode.REQUEST_RESPONSE -> { if (stub.response != null) { diff --git a/preflight-core/preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/internal/DirectiveParser.kt b/preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/internal/DirectiveParser.kt similarity index 100% rename from preflight-core/preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/internal/DirectiveParser.kt rename to preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/internal/DirectiveParser.kt diff --git a/preflight-core/preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/internal/FrontMatterParser.kt b/preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/internal/FrontMatterParser.kt similarity index 100% rename from preflight-core/preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/internal/FrontMatterParser.kt rename to preflight-spec/src/main/kotlin/com/orbitalhq/preflight/spec/internal/FrontMatterParser.kt diff --git a/preflight-core/preflight-spec/src/test/kotlin/com/orbitalhq/preflight/spec/DirectiveParserTest.kt b/preflight-spec/src/test/kotlin/com/orbitalhq/preflight/spec/DirectiveParserTest.kt similarity index 100% rename from preflight-core/preflight-spec/src/test/kotlin/com/orbitalhq/preflight/spec/DirectiveParserTest.kt rename to preflight-spec/src/test/kotlin/com/orbitalhq/preflight/spec/DirectiveParserTest.kt diff --git a/preflight-core/preflight-spec/src/test/kotlin/com/orbitalhq/preflight/spec/RoundTripTest.kt b/preflight-spec/src/test/kotlin/com/orbitalhq/preflight/spec/RoundTripTest.kt similarity index 73% rename from preflight-core/preflight-spec/src/test/kotlin/com/orbitalhq/preflight/spec/RoundTripTest.kt rename to preflight-spec/src/test/kotlin/com/orbitalhq/preflight/spec/RoundTripTest.kt index f57bdc5..63acc77 100644 --- a/preflight-core/preflight-spec/src/test/kotlin/com/orbitalhq/preflight/spec/RoundTripTest.kt +++ b/preflight-spec/src/test/kotlin/com/orbitalhq/preflight/spec/RoundTripTest.kt @@ -14,7 +14,7 @@ class RoundTripTest : DescribeSpec({ description = null, query = "find { Customer }", dataSources = listOf( - Stub("Get Customer", "getCustomer", StubMode.REQUEST_RESPONSE, """{ "id": "1" }""", null) + Stub("Get Customer", "getCustomer", StubMode.REQUEST_RESPONSE, parameters = null, response = """{ "id": "1" }""", messages = null) ), expectedResult = """{ "id": "1" }""", flow = null @@ -30,8 +30,8 @@ class RoundTripTest : DescribeSpec({ description = "Tests with multiple data sources.", query = "find { Customer } with { orders: Order[] }", dataSources = listOf( - Stub("Fetch Customer", "getCustomer", StubMode.REQUEST_RESPONSE, """{ "id": "12345", "name": "Alice" }""", null), - Stub("Fetch Orders", "getOrders", StubMode.REQUEST_RESPONSE, """[{ "orderId": "ORD-1" }]""", null) + Stub("Fetch Customer", "getCustomer", StubMode.REQUEST_RESPONSE, parameters = null, response = """{ "id": "12345", "name": "Alice" }""", messages = null), + Stub("Fetch Orders", "getOrders", StubMode.REQUEST_RESPONSE, parameters = null, response = """[{ "orderId": "ORD-1" }]""", messages = null) ), expectedResult = """{ "customer": "Alice", "orders": [{ "orderId": "ORD-1" }] }""", flow = null @@ -48,8 +48,8 @@ class RoundTripTest : DescribeSpec({ query = "stream { Prices }", dataSources = listOf( Stub( - "Price Updates", "priceStream", StubMode.STREAM, null, - listOf("""{ "price": 100 }""", """{ "price": 200 }""", """{ "price": 300 }""") + "Price Updates", "priceStream", StubMode.STREAM, parameters = null, response = null, + messages = listOf("""{ "price": 100 }""", """{ "price": 200 }""", """{ "price": 300 }""") ) ), expectedResult = """[{ "price": 100 }, { "price": 200 }, { "price": 300 }]""", @@ -66,7 +66,7 @@ class RoundTripTest : DescribeSpec({ description = "A comprehensive test case.", query = "find { Customer }", dataSources = listOf( - Stub("Get Customer", "getCustomer", StubMode.REQUEST_RESPONSE, """{ "id": "1" }""", null) + Stub("Get Customer", "getCustomer", StubMode.REQUEST_RESPONSE, parameters = null, response = """{ "id": "1" }""", messages = null) ), expectedResult = """{ "id": "1" }""", flow = "sequenceDiagram\n Q->>S: getCustomer\n S-->>Q: Customer" @@ -82,7 +82,7 @@ class RoundTripTest : DescribeSpec({ description = null, query = "find { Customer }", dataSources = listOf( - Stub("Get Customer", "getCustomer", StubMode.REQUEST_RESPONSE, """{ "id": "1" }""", null) + Stub("Get Customer", "getCustomer", StubMode.REQUEST_RESPONSE, parameters = null, response = """{ "id": "1" }""", messages = null) ), expectedResult = """{ "type": "Customer", "value": { "id": "1" } }""", resultFormat = ResultFormat.TYPED_INSTANCE, @@ -99,7 +99,7 @@ class RoundTripTest : DescribeSpec({ description = null, query = "find { Customer }", dataSources = listOf( - Stub("Get Customer", "getCustomer", StubMode.REQUEST_RESPONSE, """{ "id": "1" }""", null) + Stub("Get Customer", "getCustomer", StubMode.REQUEST_RESPONSE, parameters = null, response = """{ "id": "1" }""", messages = null) ), expectedResult = """{ "id": "1" }""", resultFormat = ResultFormat.JSON, @@ -116,9 +116,9 @@ class RoundTripTest : DescribeSpec({ description = null, query = "find { Dashboard }", dataSources = listOf( - Stub("Static Data", "getConfig", StubMode.REQUEST_RESPONSE, """{ "theme": "dark" }""", null), - Stub("Live Prices", "priceStream", StubMode.STREAM, null, listOf("""{ "price": 42 }""")), - Stub("User Profile", "getUser", StubMode.REQUEST_RESPONSE, """{ "name": "Bob" }""", null) + Stub("Static Data", "getConfig", StubMode.REQUEST_RESPONSE, parameters = null, response = """{ "theme": "dark" }""", messages = null), + Stub("Live Prices", "priceStream", StubMode.STREAM, parameters = null, response = null, messages = listOf("""{ "price": 42 }""")), + Stub("User Profile", "getUser", StubMode.REQUEST_RESPONSE, parameters = null, response = """{ "name": "Bob" }""", messages = null) ), expectedResult = """{ "theme": "dark", "price": 42, "name": "Bob" }""", flow = null @@ -126,5 +126,24 @@ class RoundTripTest : DescribeSpec({ val roundTripped = TestSpecReader.read(TestSpecWriter.write(original)) roundTripped shouldBe original } + + it("round-trips a spec with stub parameters") { + val original = TestSpec( + specVersion = "0.1", + name = "Parameterised Test", + description = null, + query = "find { Product }", + dataSources = listOf( + Stub("Get Product", "getProduct", StubMode.REQUEST_RESPONSE, + parameters = """{ "productId": "PROD-1001" }""", + response = """{ "productId": "PROD-1001", "name": "Laptop" }""", + messages = null) + ), + expectedResult = """{ "productId": "PROD-1001", "name": "Laptop" }""", + flow = null + ) + val roundTripped = TestSpecReader.read(TestSpecWriter.write(original)) + roundTripped shouldBe original + } } }) diff --git a/preflight-core/preflight-spec/src/test/kotlin/com/orbitalhq/preflight/spec/TestSpecReaderTest.kt b/preflight-spec/src/test/kotlin/com/orbitalhq/preflight/spec/TestSpecReaderTest.kt similarity index 91% rename from preflight-core/preflight-spec/src/test/kotlin/com/orbitalhq/preflight/spec/TestSpecReaderTest.kt rename to preflight-spec/src/test/kotlin/com/orbitalhq/preflight/spec/TestSpecReaderTest.kt index f1612e3..127cb78 100644 --- a/preflight-core/preflight-spec/src/test/kotlin/com/orbitalhq/preflight/spec/TestSpecReaderTest.kt +++ b/preflight-spec/src/test/kotlin/com/orbitalhq/preflight/spec/TestSpecReaderTest.kt @@ -394,6 +394,82 @@ class TestSpecReaderTest : DescribeSpec({ spec.query shouldBe "find { Foo }" } + it("parses Request block as parameters") { + val markdown = """ + |--- + |spec-version: 0.1 + |--- + | + |# Test + | + |## Query + | + |```taxiql + |find { Foo } + |``` + | + |## Data Sources + | + |### Get Product + | + | + |Request: + |```json + |{ "productId": "PROD-1001" } + |``` + | + |Response: + |```json + |{ "productId": "PROD-1001", "name": "Laptop" } + |``` + | + |## Expected Result + | + |```json + |{ "productId": "PROD-1001", "name": "Laptop" } + |``` + """.trimMargin() + + val spec = TestSpecReader.read(markdown) + spec.dataSources[0].parameters shouldBe """{ "productId": "PROD-1001" }""" + spec.dataSources[0].response shouldBe """{ "productId": "PROD-1001", "name": "Laptop" }""" + } + + it("parses stub without Request block as null parameters") { + val markdown = """ + |--- + |spec-version: 0.1 + |--- + | + |# Test + | + |## Query + | + |```taxiql + |find { Foo } + |``` + | + |## Data Sources + | + |### Stub + | + | + |Response: + |```json + |{} + |``` + | + |## Expected Result + | + |```json + |{} + |``` + """.trimMargin() + + val spec = TestSpecReader.read(markdown) + spec.dataSources[0].parameters.shouldBeNull() + } + it("parses Expected Results with no qualifier as JSON format") { val markdown = """ |--- diff --git a/preflight-core/preflight-spec/src/test/kotlin/com/orbitalhq/preflight/spec/TestSpecWriterTest.kt b/preflight-spec/src/test/kotlin/com/orbitalhq/preflight/spec/TestSpecWriterTest.kt similarity index 78% rename from preflight-core/preflight-spec/src/test/kotlin/com/orbitalhq/preflight/spec/TestSpecWriterTest.kt rename to preflight-spec/src/test/kotlin/com/orbitalhq/preflight/spec/TestSpecWriterTest.kt index dafe786..0642998 100644 --- a/preflight-core/preflight-spec/src/test/kotlin/com/orbitalhq/preflight/spec/TestSpecWriterTest.kt +++ b/preflight-spec/src/test/kotlin/com/orbitalhq/preflight/spec/TestSpecWriterTest.kt @@ -28,8 +28,8 @@ class TestSpecWriterTest : DescribeSpec({ it("writes spec with multiple stubs") { val spec = minimalSpec().copy( dataSources = listOf( - Stub("Get Customer", "getCustomer", StubMode.REQUEST_RESPONSE, """{ "id": "1" }""", null), - Stub("Get Orders", "getOrders", StubMode.REQUEST_RESPONSE, """[{ "orderId": "A" }]""", null) + Stub("Get Customer", "getCustomer", StubMode.REQUEST_RESPONSE, parameters = null, response = """{ "id": "1" }""", messages = null), + Stub("Get Orders", "getOrders", StubMode.REQUEST_RESPONSE, parameters = null, response = """[{ "orderId": "A" }]""", messages = null) ) ) val output = TestSpecWriter.write(spec) @@ -42,7 +42,7 @@ class TestSpecWriterTest : DescribeSpec({ it("writes stream-mode stub with mode directive present") { val spec = minimalSpec().copy( dataSources = listOf( - Stub("Price Stream", "priceStream", StubMode.STREAM, null, listOf("""{ "price": 100 }""")) + Stub("Price Stream", "priceStream", StubMode.STREAM, parameters = null, response = null, messages = listOf("""{ "price": 100 }""")) ) ) val output = TestSpecWriter.write(spec) @@ -106,12 +106,35 @@ class TestSpecWriterTest : DescribeSpec({ output shouldContain "```json typedInstance" } + it("writes Request block before Response when parameters are present") { + val spec = minimalSpec().copy( + dataSources = listOf( + Stub("Get Product", "getProduct", StubMode.REQUEST_RESPONSE, + parameters = """{ "productId": "PROD-1001" }""", + response = """{ "productId": "PROD-1001", "name": "Laptop" }""", + messages = null) + ) + ) + val output = TestSpecWriter.write(spec) + output shouldContain "Request:" + output shouldContain "Response:" + val requestIdx = output.indexOf("Request:") + val responseIdx = output.indexOf("Response:") + assert(requestIdx < responseIdx) { "Request should appear before Response" } + } + + it("omits Request block when parameters are null") { + val spec = minimalSpec() + val output = TestSpecWriter.write(spec) + output shouldNotContain "Request:" + } + it("writes stream stub with multiple messages in order") { val spec = minimalSpec().copy( dataSources = listOf( Stub( - "Prices", "priceStream", StubMode.STREAM, null, - listOf("""{ "price": 100 }""", """{ "price": 200 }""", """{ "price": 300 }""") + "Prices", "priceStream", StubMode.STREAM, parameters = null, response = null, + messages = listOf("""{ "price": 100 }""", """{ "price": 200 }""", """{ "price": 300 }""") ) ) ) @@ -130,7 +153,7 @@ class TestSpecWriterTest : DescribeSpec({ it("writes stream stub with single message") { val spec = minimalSpec().copy( dataSources = listOf( - Stub("Stream", "myStream", StubMode.STREAM, null, listOf("""{ "value": 1 }""")) + Stub("Stream", "myStream", StubMode.STREAM, parameters = null, response = null, messages = listOf("""{ "value": 1 }""")) ) ) val output = TestSpecWriter.write(spec) @@ -146,7 +169,7 @@ private fun minimalSpec() = TestSpec( description = null, query = "find { Customer }", dataSources = listOf( - Stub("Get Customer", "getCustomer", StubMode.REQUEST_RESPONSE, """{ "id": "1" }""", null) + Stub("Get Customer", "getCustomer", StubMode.REQUEST_RESPONSE, parameters = null, response = """{ "id": "1" }""", messages = null) ), expectedResult = """{ "id": "1" }""", flow = null diff --git a/settings.gradle.kts b/settings.gradle.kts index caa12ba..4fe330a 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,6 +1,7 @@ rootProject.name = "preflight" -// Include the plugin build as a composite +// Include preflight-spec first so it's available when preflight-core resolves +includeBuild("preflight-spec") includeBuild("preflight-core") // Include example projects as composites too