Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 42 additions & 2 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,13 @@ jobs:
else
version="${prefix}.${GITHUB_RUN_NUMBER}-preview"
fi
for p in SimpleBehav SimpleBehav.NUnit SimpleBehav.SpecGen; do
dotnet pack "src/$p" --configuration Release -p:ContinuousIntegrationBuild=true -p:Version="$version" --output nupkgs
for p in \
DSL/dotnet/SimpleBehav \
Playwright/dotnet/SimpleBehav.Playwright \
Playwright/dotnet/SimpleBehav.NUnit \
LivingDoc/dotnet/SimpleBehav.SpecGen
do
dotnet pack "$p" --configuration Release -p:ContinuousIntegrationBuild=true -p:Version="$version" --output nupkgs
done
echo "version=$version" >> "$GITHUB_OUTPUT"

Expand All @@ -62,6 +67,41 @@ jobs:
name: nupkg
path: nupkgs

kotlin:
name: Kotlin
runs-on: ubuntu-latest
defaults:
run:
working-directory: kotlin
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: 17
- name: Test
run: ./gradlew test --no-daemon
- name: Browser test
run: ./gradlew :simplebehav-playwright:browserTest --no-daemon

typescript:
name: TypeScript
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
- name: Test DSL
working-directory: DSL/typescript
run: npm install && npm test && npm run build
- name: Typecheck Playwright
working-directory: Playwright/typescript
run: npm install && npx tsc --noEmit
- name: Browser test
working-directory: Playwright/typescript
run: npx playwright install chromium && npm run test:browser

deploy:
needs: build
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
Expand Down
9 changes: 9 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@
[Bb]in/
[Oo]bj/

# Gradle
.gradle/
.kotlin/
build/

# Node
node_modules/
dist/

# Test artifacts
artifacts/

Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System.Runtime.CompilerServices;
using Microsoft.Playwright;
using SimpleBehav.Reporter;

namespace SimpleBehav;
Expand Down Expand Up @@ -46,6 +45,24 @@ public interface ISystemUnderTestBuilder
Task DisposeAsync();
}

/// <summary>
/// Optional adapter capability. Playwright starts a trace around the scenario and
/// copies the trace viewer next to the artifacts. Adapters without a browser ignore it.
/// </summary>
public interface IScenarioTrace
{
Task StartTraceAsync();
Task StopTraceAsync(string tracePath);
void EnsureViewer(string artifactsRoot);
}

/// <summary>A Then-step. The adapter's context is passed through; the assertion knows how to read it.</summary>
public interface IAssertion
{
string Label { get; }
Task RunAsync(ISetupContext context);
}

// ─── Pre-built setup ──────────────────────────────────────────────────────────

public static class Setup
Expand Down Expand Up @@ -99,9 +116,8 @@ internal async Task ExecuteAsync(IReadOnlyList<(string Label, IAssertion Asserti
string? failureMessage = null;
var ctx = _adapter.CreateContext();

// Start trace before any interaction
if (_adapter is PlaywrightBuilder pw)
await pw.StartTraceAsync();
if (_adapter is IScenarioTrace trace)
await trace.StartTraceAsync();

try
{
Expand All @@ -125,12 +141,11 @@ internal async Task ExecuteAsync(IReadOnlyList<(string Label, IAssertion Asserti
var bundle = emitter.Build(status);
var dir = await emitter.EmitAsync(bundle, _outDir, _suitePath);

// Stop trace and write the zip next to the scenario's bundle
var tracePath = Path.Combine(dir, "trace.zip");
if (_adapter is PlaywrightBuilder pwStop)
if (_adapter is IScenarioTrace traceStop)
{
await pwStop.StopTraceAsync(tracePath);
PlaywrightBuilder.EnsureTraceViewer(_outDir);
await traceStop.StopTraceAsync(tracePath);
traceStop.EnsureViewer(_outDir);
}

// The viewer lives at the artifacts root, the suite page one level per path segment below it
Expand Down Expand Up @@ -171,11 +186,10 @@ private async Task RunWhenAsync(ISetupContext ctx, ArtifactEmitter emitter)

private async Task RunThenAsync(ISetupContext ctx, IReadOnlyList<(string Label, IAssertion Assertion)> assertions, ArtifactEmitter emitter)
{
var page = TryGetPage(ctx);
foreach (var (label, assertion) in assertions)
{
var t = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
await assertion.RunAsync(page!);
await assertion.RunAsync(ctx);
emitter.AddStep(new ArtifactStep
{
Type = StepType.Assert,
Expand All @@ -185,10 +199,6 @@ private async Task RunThenAsync(ISetupContext ctx, IReadOnlyList<(string Label,
}
}

private IPage? TryGetPage(ISetupContext ctx)
{
try { return _adapter.Construct<IPage>(ctx); } catch { return null; }
}
}

// ─── Token chain ──────────────────────────────────────────────────────────────
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<PackageId>SimpleBehav</PackageId>
<Description>Playwright acceptance test DSL for .NET — fluent Given / When / Then scenarios. Ships Agent Skills for writing those scenarios.</Description>
<Description>Polyglot behavior DSL for SimpleBehav — fluent Given / When / Then scenarios and the shared artifact format. Ships Agent Skills for writing those scenarios.</Description>
<PackageTags>$(PackageTags);agent-skills;skills</PackageTags>
<IsPackable>true</IsPackable>
</PropertyGroup>

<ItemGroup>
<Content Include="..\..\.agents\skills\**\*" Link="contentFiles\any\any\skills\%(RecursiveDir)%(Filename)%(Extension)">
<Content Include="..\..\..\.agents\skills\**\*" Link="contentFiles\any\any\skills\%(RecursiveDir)%(Filename)%(Extension)">
<Pack>true</Pack>
<PackagePath>contentFiles\any\any\skills\%(RecursiveDir)%(Filename)%(Extension)</PackagePath>
<BuildAction>None</BuildAction>
Expand All @@ -24,14 +24,4 @@
<None Include="build\skill.gitignore" Pack="true" PackagePath="buildTransitive\skill.gitignore" />
</ItemGroup>

<ItemGroup>
<!-- Peer dependencies. PrivateAssets keeps them out of the nuspec so a consumer pin cannot downgrade against SimpleBehav (NU1605). The test project references them directly. -->
<PackageReference Include="Microsoft.Playwright" Version="1.63.0">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.0">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>

</Project>
10 changes: 10 additions & 0 deletions DSL/kotlin/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
plugins {
kotlin("jvm")
kotlin("plugin.serialization")
}

dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.8.0")
api("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.1")
testImplementation(kotlin("test"))
}
140 changes: 140 additions & 0 deletions DSL/kotlin/src/main/kotlin/simplebehav/Artifact.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
package simplebehav

import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.add
import kotlinx.serialization.json.addJsonObject
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import java.nio.file.Files
import java.nio.file.Path
import java.security.MessageDigest
import java.time.Instant
import java.util.UUID
import kotlin.reflect.KClass

@Serializable
enum class StepType { Setup, Act, Assert }

@Serializable
data class ArtifactStep(
val type: StepType,
val label: String,
val durationMs: Long,
val error: String? = null,
)

@Serializable
data class ArtifactBundle(
val id: String,
val title: String,
val status: String,
val startedAt: String,
val durationMs: Long,
val steps: List<ArtifactStep>,
)

private val artifactJson = Json {
prettyPrint = true
explicitNulls = false
}

private val pretty = Json { prettyPrint = true }

internal object ArtifactPaths {
fun slug(value: String): String {
val cleaned = value.lowercase().replace(' ', '-').replace(Regex("[^a-z0-9-]"), "")
if (cleaned.length <= 80) return cleaned
val hash = MessageDigest.getInstance("SHA-256")
.digest(value.toByteArray(Charsets.UTF_8))
.joinToString("") { "%02x".format(it) }
.take(8)
return cleaned.take(71) + "-" + hash
}

fun suitePath(projectName: String, testClass: KClass<*>?): List<String> {
val project = segment(projectName)
if (testClass == null) return listOf(project)
val packages = testClass.java.packageName.split('.').filter { it.isNotEmpty() }.map(::segment)
val file = segment(testClass.simpleName ?: "suite")
return listOf(project) + packages + file
}

private fun segment(value: String): String {
val cleaned = value.replace(Regex("[^A-Za-z0-9._-]"), "-")
return cleaned.ifEmpty { "suite" }
}
}

internal class ArtifactEmitter(private val title: String) {
private val id = UUID.randomUUID().toString()
private val startedAt = System.currentTimeMillis()
private val steps = mutableListOf<ArtifactStep>()

fun add(step: ArtifactStep) {
steps += step
}

fun build(status: String) = ArtifactBundle(
id = id,
title = title,
status = status,
startedAt = Instant.ofEpochMilli(startedAt).toString(),
durationMs = System.currentTimeMillis() - startedAt,
steps = steps.toList(),
)

/** Writes bundle.json and cucumber.json. The runner then refreshes the suite index.html. */
fun emit(bundle: ArtifactBundle, outDir: String, suitePath: List<String>): Path {
val slug = ArtifactPaths.slug(bundle.title)
val dir = suitePath.fold(Path.of(outDir)) { path, segment -> path.resolve(segment) }.resolve(slug)
Files.createDirectories(dir)
Files.writeString(dir.resolve("bundle.json"), artifactJson.encodeToString(bundle))
Files.writeString(dir.resolve("cucumber.json"), cucumber(bundle, suitePath, slug))
return dir
}

private fun cucumber(bundle: ArtifactBundle, suitePath: List<String>, slug: String): String {
val document = buildJsonArray {
addJsonObject {
put("uri", suitePath.joinToString("/") + "/$slug")
put("id", bundle.id)
put("keyword", "Feature")
put("name", suitePath.last())
put("line", 1)
put("description", "Generated by SimpleBehav")
put("elements", buildJsonArray {
addJsonObject {
put("id", "${bundle.id};$slug")
put("keyword", "Scenario")
put("name", bundle.title)
put("line", 1)
put("type", "scenario")
put("steps", buildJsonArray {
bundle.steps.forEachIndexed { index, step ->
addJsonObject {
put("keyword", when (step.type) {
StepType.Setup -> "Given "
StepType.Act -> "When "
StepType.Assert -> "Then "
})
put("name", step.label)
put("line", index + 1)
put("result", buildJsonObject {
put("duration", JsonPrimitive(step.durationMs * 1_000_000))
put("status", if (step.error == null) "passed" else "failed")
if (step.error != null) put("error_message", step.error)
})
}
}
})
}
})
}
}
return pretty.encodeToString(kotlinx.serialization.json.JsonElement.serializer(), document)
}
}
45 changes: 45 additions & 0 deletions DSL/kotlin/src/main/kotlin/simplebehav/Model.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package simplebehav

import kotlin.reflect.KClass

/** An opaque precondition. The adapter decides what it means for the system under test. */
interface Setup {
val label: String
}

/** Adapter-owned context for one scenario. The DSL passes it through and does not inspect it. */
interface SetupContext

/**
* Pluggable builder for the system under test. One implementation per system type
* (Playwright, Ktor, a DI host). The DSL drives the lifecycle.
*/
interface SystemUnderTestBuilder {
suspend fun initialize()
fun createContext(): SetupContext
suspend fun apply(context: SetupContext, setup: Setup)
fun <T : Any> construct(context: SetupContext, type: KClass<T>): T
suspend fun dispose()
}

/** Optional. A browser adapter records a trace around the scenario. */
interface ScenarioTrace {
suspend fun startTrace()
suspend fun stopTrace(tracePath: java.nio.file.Path)
fun ensureViewer(artifactsRoot: java.nio.file.Path)
}

/** A Then-step. The assertion knows how to read the adapter context. */
interface Assertion {
val label: String
suspend fun run(context: SetupContext)
}

fun setup(label: String, action: suspend (SetupContext) -> Unit): Setup = ActionSetup(label, action)

private class ActionSetup(
override val label: String,
private val action: suspend (SetupContext) -> Unit,
) : Setup {
suspend fun apply(context: SetupContext) = action(context)
}
Loading
Loading