Fluent Load Testing API
Use load(path) for a single GET step. For headers, payloads, checks, and multiple steps, start with loadScenario(name). step(name) returns LoadStep; and() returns its parent LoadScenario.
POST request
The following fragment belongs inside a BaseLoadTest test method, with java.util.Map imported:
loadScenario("Create order").users(10)
.step("Create").post("/orders")
.header("Content-Type", "application/json")
.body(Map.of("sku", "PROD-998", "quantity", 1))
.check(status().is(201)).and()
.run().assertErrorRateBelow(0.01);
Multi-step journey
import io.testfly.loadtest.BaseLoadTest;
import io.testfly.loadtest.LoadTestFeeder;
import org.testng.annotations.Test;
import java.time.Duration;
import java.util.Map;
public class CheckoutLoadTest extends BaseLoadTest {
@Test
public void checkout() {
loadScenario("Checkout")
.engine("jdk").users(15).hold(Duration.ofSeconds(10))
.feed(LoadTestFeeder.csv("testdata/users.csv"))
.step("Login").post("/login")
.body(Map.of("username", "${username}", "password", "${password}"))
.check(status().is(200)).extract("token", "$.accessToken").and()
.step("Payment").post("/payment")
.header("Authorization", "Bearer ${token}")
.body(Map.of("amount", 10)).check(status().is(200)).and()
.run().assertStepP95Below("Login", 300)
.assertStepP95Below("Payment", 800)
.assertStepErrorRateBelow("Payment", 0.01);
}
}
Workload models (Gatling only)
users, rampUp and hold describe one fixed shape: users start evenly over rampUp and each one loops for hold (see Configuration). For any other shape, give the scenario a workload with workload(Workload.open(...)) or workload(Workload.closed(...)). The steps run in order, and each virtual user runs the scenario steps once; there is no hold loop.
- Closed model: you set how many users run at the same time. A user that finishes is replaced by a new one.
- Open model: you set how users arrive, whatever the number already running. Concurrency is an outcome: on a slow endpoint, users pile up.
import io.testfly.loadtest.BaseLoadTest;
import io.testfly.loadtest.ClosedStep;
import io.testfly.loadtest.OpenStep;
import io.testfly.loadtest.Workload;
import org.testng.annotations.Test;
import java.time.Duration;
public class CartWorkloadLoadTest extends BaseLoadTest {
@Test
public void cartUnderConstantConcurrency() {
loadScenario("Cart")
.engine("gatling")
.workload(Workload.closed(
ClosedStep.rampConcurrent(0, 50, Duration.ofSeconds(30)),
ClosedStep.constantConcurrent(50, Duration.ofMinutes(2)),
ClosedStep.rampConcurrent(50, 0, Duration.ofSeconds(30)))) // ramp-down
.step("Cart").get("/cart").and()
.run()
.assertP95Below(300)
.assertErrorRateBelow(0.01);
}
@Test
public void searchArrivalRate() {
loadScenario("Search")
.engine("gatling")
.workload(Workload.open(
OpenStep.atOnce(10),
OpenStep.rampRate(1, 20, Duration.ofSeconds(30)),
OpenStep.constantRate(20, Duration.ofMinutes(2)),
OpenStep.nothingFor(Duration.ofSeconds(10)),
OpenStep.stressPeak(100, Duration.ofSeconds(20))))
.step("Search").get("/search?q=shoes").and()
.run()
.assertErrorRateBelow(0.01);
}
}
| Step | Model | Meaning |
|---|---|---|
OpenStep.atOnce(users) | open | Starts users users at once (lasts 0). |
OpenStep.ramp(users, over) | open | Starts users users spread evenly over over. |
OpenStep.constantRate(usersPerSec, during) | open | Starts usersPerSec new users per second during during. |
OpenStep.rampRate(fromPerSec, toPerSec, during) | open | Changes the arrival rate linearly from fromPerSec to toPerSec. |
OpenStep.stressPeak(users, over) | open | Starts users users following a smooth (Heaviside) spike over over. |
OpenStep.nothingFor(duration) | open | Starts no user for duration. |
ClosedStep.constantConcurrent(users, during) | closed | Keeps users users running at the same time during during. |
ClosedStep.rampConcurrent(fromUsers, toUsers, during) | closed | Changes the concurrent users linearly from fromUsers to toUsers. |
Rules, all checked before any request is sent:
- Gatling only. On the JDK engine, or with
autowhen Gatling is not on the classpath,run()fails withIllegalArgumentException("workload(...) requires the Gatling engine"). - No mixing. Open and closed steps are different types, so they cannot be mixed in one workload. A workload cannot be combined with
users,rampUp,holdorcooldownon the same scenario (IllegalArgumentException). Values for those keys from@LoadTestortestfly.ymlare ignored, and an INFO line says so. - Arguments. The factories throw
IllegalArgumentExceptionat once for a user count below 1 (rampConcurrentaccepts 0), a negative or non-finite rate, or a duration that is not positive. A workload that starts nobody (only pauses, only zero rates, or a closed peak of 0) is rejected. loadtest.maxUsers. For a closed workload it caps the peak concurrency, ramp end points included. For an open workload it caps the peak arrival rate (users/s ofconstantRateandrampRate) and the user count of eachatOnce,rampandstressPeakstep. It does not cap the concurrency that results from an open workload.- Ramp-down. Write it as
rampConcurrent(n, 0, duration).cooldownis still not applied to theusers/rampUp/holdshape. - Reported users.
metrics().users()is the planned number of users: for a closed workload the peak concurrency; for an open workload the users of theatOnce,rampandstressPeaksteps plus the rate steps'rate × duration, rounded up.
New step types may be added in minor releases, so a switch over OpenStep or ClosedStep needs a default branch. To run several workloads together, see Simulations and SLAs.
Flow control
Since 1.1.0 a scenario can hold blocks besides steps: loops, conditions, weighted random branches, named groups, retries and pacing. Both engines run every block the same way and report the same metrics (see Engines).
| Method | What it runs |
|---|---|
repeat(times, body) | body times times in every iteration. |
repeat(times, counter, body) | The same, with the 0-based iteration number in the variable counter (${counter}) inside body. The variable is removed after the loop. A null counter means no counter, as with the two-argument form. |
doIf(condition, then) | then when the condition holds. |
doIfOrElse(condition, then, orElse) | then when the condition holds, orElse otherwise. |
randomSwitch(branch, more...) | At most one branch, drawn by its percentage. |
group(name, body) | body; its steps are reported as "name / step" (see Groups). |
tryMax(times, body) | body up to times tries in total (see Retries). |
pace(interval), pace(min, max) | Waits until interval (or a random interval between min and max) has passed since this user last reached this point (see Pacing). |
Each method returns the builder it was called on, so the chain goes on after the block:
import io.testfly.loadtest.BaseLoadTest;
import io.testfly.loadtest.LoadBranch;
import io.testfly.loadtest.LoadCondition;
import io.testfly.loadtest.LoadTestFeeder;
import org.testng.annotations.Test;
import java.time.Duration;
import java.util.Map;
public class ShopFlowLoadTest extends BaseLoadTest {
@Test
public void shop() {
loadScenario("Shop")
.engine("jdk").users(10).hold(Duration.ofMinutes(1))
.feed(LoadTestFeeder.sequence("customerId", 1, 1))
.step("Home").get("/").and()
.repeat(3, "page", b -> b
.step("List").get("/items").queryParam("page", "${page}"))
.step("Profile").get("/customers/${customerId}")
.extract("tier", "$.tier").and()
.doIfOrElse(LoadCondition.equalTo("tier", "gold"),
b -> b.step("Gold offers").get("/offers/gold"),
b -> b.step("Offers").get("/offers"))
.randomSwitch(
LoadBranch.percent(70, b -> b.step("Browse").get("/products")),
LoadBranch.percent(20, b -> b.step("Search").get("/search?q=shoes")))
.group("Checkout", b -> b
.step("Cart").get("/cart").and()
.tryMax(3, t -> t
.step("Pay").post("/pay")
.body(Map.of("amount", 10))
.check(status().is(201))))
.run()
.assertStepP95Below("Checkout / Pay", 800)
.assertErrorRateBelow(0.05);
}
}
In this scenario each iteration requests three pages of /items (page = 0, 1, 2), shows the gold offers only to customers whose tier is gold, browses in 70 % and searches in 20 % of the iterations (and does neither in the other 10 %), and tries the payment up to three times.
Block builders
A block body is a Consumer<LoadScenario>. It receives a block builder: a LoadScenario for the inside of the block.
- Add steps to the block builder:
step(..), the shortcutsget,post,put,patch,delete,head,options, and nested blocks. Inside a block,step(..)...and()returns the block builder. - Scenario settings on a block builder throw
IllegalStateException("users(..) is a scenario setting and cannot be used inside repeat(..)"). These areusers,rampUp,hold,cooldown,workload,engine,baseUrl,feed,addFeeder,feedCsv,feedJson,thinkTime,sla,runand theassert*shortcuts.LoadStep.run()on a step inside a block throws too. Set them on the scenario, before or after the block. - While a body runs, the enclosing builder is locked. Adding a step or block to the outer scenario from inside the lambda (
s.step(..)instead ofb.step(..)) throwsIllegalStateException("add steps to the block builder, not the enclosing scenario"). Scenario settings,run()and theassert*shortcuts on the outer scenario throw too ("cannot be used inside a block body; set it on the scenario after the block returns"). - When the body returns, its block builder is sealed. Adding to a block builder (or through a step's
and()) after that throwsIllegalStateException. ALoadStepkept from a body is not sealed: its headers, body or checks can still be changed after the block is built. Do not rely on this; configure every step inside its body. - Each body lambda runs once, when the block method is called, not in every iteration. A value computed in the lambda is fixed for the whole run; use a feeder,
extract(..)or arepeatcounter for values that change. - A
nullbody, anullbranch inrandomSwitch(..)and anorElsebody without a step throwIllegalArgumentExceptionat once. The other rules are checked before any request is sent (see Validation limits).
Conditions
doIf and doIfOrElse take a LoadCondition on a session variable. The variable comes from the feeder, from extract(..) or from a repeat counter. A variable that is not set, or whose value is null, is missing.
| Condition | true when |
|---|---|
LoadCondition.exists(var) | var is set and not null. |
LoadCondition.missing(var) | var is not set or is null. |
LoadCondition.equalTo(var, value) | var is set and String.valueOf(var) equals String.valueOf(value). false when var is missing. |
LoadCondition.notEqualTo(var, value) | The negation of equalTo: also true when var is missing. |
- The comparison is on text, so
equalTo("count", 5)matches the value5and the string"5", but not5.0. A missing variable is not equal to anything, not evenequalTo(var, "null"). - A JSONPath
extract(..)storesnullfor a JSONnullvalue, somissing(var)istruefor it. AjmesPath(..)extraction treats JSONnullas not found (see Correlation). A failedextract(..)without a default sets nothing. - The variable name must be non-blank and must not contain
#{or${: writeequalTo("tier", "gold"), notequalTo("${tier}", "gold"). - A condition never throws; both engines evaluate it the same way.
Random branches
randomSwitch(LoadBranch.percent(p, body), ...) runs at most one branch per pass:
- Each percentage is finite and in
(0, 100], and together they add up to at most 100 (a sum within 1e-9 of 100 is accepted, so33.3,33.3,33.4is valid). - Branches are tried in argument order: a number in
[0, 100)is drawn, and the first branch whose running total of percentages is above it runs. - The remainder up to 100 runs no branch: with
percent(70, ..)andpercent(20, ..), 10 % of the passes go straight to the next node. - Every pass draws again. A branch that was never drawn still has its steps in the metrics, with 0 requests.
Groups
group(name, body) names a part of the scenario. A group only changes names: the key of a step inside it is "Group / Step", and for nested groups "Outer / Inner / Step".
- Use the key everywhere a step name is expected:
metrics().step("Checkout / Pay"),assertStepP95Below("Checkout / Pay", 800)andsla().step("Checkout / Pay"). The bare name"Pay"is not a key. - A group has no entry of its own in the metrics.
- In a simulation with more than one scenario, the global metrics use
"<scenario> :: Group / Step"(for example"Shop :: Checkout / Pay"); each scenario's own metrics use"Group / Step". - On Gatling the group also appears in Gatling's own report. On the JDK engine it only changes the names.
- A group name must be non-blank and must not contain
#{,${," :: "or" / ".a/bandv1::x(without the spaces) are allowed.
Unique names. Steps at the top level may share a name; they share one entry in the metrics, as before 1.1.0. A step inside any block needs a name that is unique in the scenario, compared with its group path: the run fails before any request with an IllegalArgumentException that names both places. The same step name in two different groups is fine. Shortcut steps are named after their path, so two get("/items") steps inside blocks collide.
Retries (tryMax)
tryMax(times, body) tries body up to times times in total, the first try included.
- A failed request ends the try at once: a failed check (the default status rule included), no response, or a failed
extract(..). The rest of that try, including the think time after the failed step, is skipped, and the skipped steps are not counted. - A try in which every request passes ends the block.
- When the tries run out, the block ends and the next node runs. The virtual user goes on.
- Each
tryMaxblock starts with a clean status: a failed request before the block, including one from an earliertryMaxwhose tries ran out, does not make its first try count as failed. - A request that cannot be built (for example a
${var}with no value) differs by engine. On Gatling it counts as one KO attempt and skips the rest of that try, like any failed request. On the JDK engine an unbuildable request URI aborts the whole run withIllegalStateException, inside atryMaxor not. - Every try sends real requests and counts them: a request that fails twice and then passes counts 3 requests, 1 OK and 2 KO, and the failed tries raise the error rate.
- A step after a failing step inside the try may never run; it is reported with 0 requests.
- A
tryMaxcannot be nested in anothertryMax, at any depth.
loadScenario("Reserve")
.engine("jdk").users(5).hold(Duration.ofSeconds(30))
.tryMax(3, t -> t
.step("Reserve").post("/reservations").check(status().is(201)).and()
.step("Confirm").post("/reservations/confirm").check(status().is(200)))
.step("Receipt").get("/receipt").and()
.run();
Pacing
pace(interval) keeps a virtual user from passing the same point more often than once per interval; pace(min, max) draws a new interval uniformly from min..max on every pass. Both engines follow Gatling's semantics:
- The state is the next start time, kept per virtual user and per
pacecall. It persists across the user's iterations. - On the first pass, or when the next start time has already passed, it does not wait and sets the next start time to now + interval. A user that arrives late re-anchors on now; it never catches up with shorter waits.
- Otherwise it waits until the next start time, then sets the next start time to the wake-up time + interval.
- At the top level a
pacepaces whole iterations of theusers/rampUp/holdloop. The run can then last up to one paced iteration longer thanhold. - Inside a
repeatit spaces the repetitions. - It is independent of
thinkTime, which still applies after every step. - With a workload, each user runs the scenario once, so a
pacemust be inside arepeat(at any depth); otherwise the run is rejected before any request.
// Each user polls at most every 10 s
loadScenario("Status")
.engine("jdk").users(5).hold(Duration.ofMinutes(2))
.pace(Duration.ofSeconds(10))
.step("Status").get("/status").and()
.run();
// With a workload: 12 polls per user, 4 to 6 s apart
loadScenario("Status")
.engine("gatling")
.workload(Workload.open(OpenStep.atOnce(5)))
.repeat(12, b -> b
.pace(Duration.ofSeconds(4), Duration.ofSeconds(6))
.step("Status").get("/status"))
.run();
steps() and flow()
steps()returns every step in declaration order, including the steps inside blocks (athenbody before itsorElse, branches in argument order). It describes the steps, not the run: it does not show repetitions, branches or the order in which requests are sent. For a scenario without blocks nothing changes.flow()returns the execution tree: an unmodifiable list ofLoadFlownodes, one per step or block, in declaration order. The node types are the recordsLoadFlow.Step,Repeat,DoIf(orElseis empty for a plaindoIf),RandomSwitch(withLoadFlow.Branch),Group,TryMaxandPace. A scenario without blocks is allStepnodes, in the order ofsteps().
New node types may be added in minor releases, so a switch over LoadFlow needs a default branch:
for (LoadFlow node : scenario.flow()) {
switch (node) {
case LoadFlow.Step s -> System.out.println("step " + s.step().name());
case LoadFlow.Repeat r -> System.out.println("repeat x" + r.times());
default -> System.out.println(node);
}
}
Validation limits
Before any request is sent, the scenario is checked for the resolved engine; a violation throws IllegalArgumentException.
| Rule | Limit |
|---|---|
repeat count | 1 to 100 000 |
tryMax count | 1 to 100; no tryMax inside another tryMax |
| Nesting | at most 8 levels of blocks (pace is not a block) |
| Requests per iteration | at most 100 000 in the worst case: repeat and tryMax multiply their body, doIf/doIfOrElse and randomSwitch count their largest branch; pace sends no request and is not counted, so repeat(100_000, b -> b.pace(Duration.ofSeconds(1)).get("/x")) is valid |
| Bodies | every block body, orElse body and branch has at least one step |
randomSwitch | at least one branch; each percentage finite and in (0, 100]; the sum at most 100 |
pace | max from 1 ms to 2 147 483 647 ms (Integer.MAX_VALUE, about 24.8 days); min is 0 or at least 1 ms; min ≤ max; inside a repeat when the scenario has a workload |
| Group name | non-blank; no #{, ${, " :: " or " / " |
repeat counter | null for no counter; otherwise non-blank, no #{ or ${, no testfly. prefix, and not the counter name of an enclosing repeat (sibling repeat blocks may reuse a name) |
| Variable names | the testfly. prefix is reserved: for repeat counters, extract(..) target names and the variables of built-in feeders (CSV/JSON columns and generated variables); this applies to every scenario, with or without blocks |
| Condition variable | non-blank; no #{ or ${ |
| Step names | a step inside a block has a key that is unique in the scenario (see Groups) |
Both engines pace in whole milliseconds, which is why a bound below 1 ms (other than a min of 0) is rejected instead of running as 0 ms.
Method reference
| Receiver | Methods |
|---|---|
BaseLoadTest | load(String path), loadScenario(String name), loadSimulation(String name), sla(), lastLoadMetrics(), status(), jsonPath(String) |
LoadScenario | users, rampUp, hold, cooldown, workload, sla, engine, baseUrl, feed, addFeeder (several feeders), feedCsv, feedJson, thinkTime, step, run; single-step shortcuts get, post, put, patch, delete, head, options (each takes a path); flow control repeat, doIf, doIfOrElse, randomSwitch, group, tryMax, pace; steps(), flow(), feeders() |
LoadCondition, LoadBranch | exists, missing, equalTo, notEqualTo; LoadBranch.percent(p, body) |
LoadStep | get(path), post(path), put(path), patch(path), delete(path), head(path), options(path), header, queryParam, formParam, body, check, extract(var, jsonPath), extract(var, source) and extract(var, source, default) (correlation), and, run; extractions(), extractors() |
LoadStep (static) | status(), jsonPath(p), headerPresent(name); since 1.1.0 responseHeader(name), regex(pattern), xpath(expression), xpath(expression, namespaces), jmesPath(expression) (see Response checks per source) |
LoadSimulation | scenario, baseUrl, engine, sla, run (see Simulations and SLAs) |
rampUp(Duration) and hold(Duration) are applied in whole seconds; a fraction rounds up, so hold(Duration.ofMillis(800)) holds for 1 s (see Configuration). thinkTime(Duration) sets a fixed pause; thinkTime(minMs, maxMs) sets a random pause between requests. extract makes a response value available to subsequent steps of the same virtual user. There is no load(LoadScenario) overload or targetRps() throttling API; for an arrival rate, use an open workload with constantRate. Place load settings on the scenario and request settings on its steps.
Checks and request options
Checks behave the same on the JDK and Gatling engines:
| Check | Meaning |
|---|---|
status().is(code), status().in(codes...) | The HTTP status equals code or is one of codes. |
| (no status check) | Default rule: the status must be 2xx (200–299) or 304. |
jsonPath(p).exists() | A value exists at the JSONPath p. |
jsonPath(p).is(n), jsonPath(p).in(n...) | The JSON value at p equals n or is one of the values (compared as strings, so JSON number 5 matches 5). |
status().matches(regex), jsonPath(p).matches(regex) | The regex is found anywhere in the whole response body (Matcher.find(), no implicit DOTALL). The JSONPath is not used. |
LoadStep.headerPresent(name) | The response has the header name (name matched in any case). Works on every HTTP method, including HEAD. |
responseHeader(name), regex(p), xpath(e), jmesPath(e) (since 1.1.0) | The response header, a body regex, an XPath or a JMESPath; see Response checks per source for every combination. |
- A terminal that does not apply to its source throws
IllegalStateExceptionwhen the check is built, for examplestatus().exists(),status().is("200"),regex(p).matches(..)orresponseHeader(name).in(..). The table in Response checks per source lists them. headerPresent(name)is a static method ofLoadStep(since 1.1.0). Inside aBaseLoadTest(or anyLoadTestSupportclass) the shortcutheaderPresent("ETag")works likestatus()andjsonPath(..); elsewhere writeLoadStep.headerPresent("ETag").responseHeader,regex,xpathandjmesPathhave noBaseLoadTestshortcut: writeLoadStep.regex(..), or addimport static io.testfly.loadtest.LoadStep.regex;.extract(var, path)marks the request as failed whenpathis not found.extract(var, source[, default])reads the other sources; see Correlation.formParam(name, value)sends anapplication/x-www-form-urlencodedbody on both engines, unless you set aContent-Typeheader. A step cannot combinebody(...)andformParam(...).queryParamvalues are URL-encoded (UTF-8, spaces as%20) after${var}substitution.- A step with a
body(...)and noContent-Typeheader gets an inferredContent-Type; see Request Content-Type.
Unsupported input fails with IllegalArgumentException before any request is sent. Examples are a step with both a body and form parameters, a blank JSONPath, or an invalid regex. A path without a leading $ is read as $. plus the path on both engines (token means $.token). The JDK engine supports only the JSONPath forms $.a.b, $.a[0].b and $[0]. On both engines a JSON null value counts as present: exists() passes and extract(...) stores null. Wildcards, deep scan (..), filters, slices and bracket keys such as ['x'] fail fast on the JDK engine and need engine("gatling").
Correlation
Since 1.1.0 a step can read a value from its response and pass it to the following steps: a token from a response header, an id from a JSON body, a value from an XML body or from plain text. extract(variable, source) stores the value as ${variable} for the next steps of the same virtual user. The sources are the check sources of Response checks per source, except status():
| Source | Reads | Value stored |
|---|---|---|
jsonPath(p) | The JSON body | The value at p; a JSON null is found, but nothing usable is stored (see JSON null with jsonPath) |
responseHeader(name) | A response header (name matched in any case) | The header's first value |
regex(pattern) | The body as text | Group 1 of the first match, or the whole match when the pattern has no group |
xpath(expression), xpath(expression, namespaces) | An XML body (XPath 1.0) | The string value of the first selected node; for an attribute, its value |
jmesPath(expression) | The JSON body | The value found; JSON null counts as not found |
import io.testfly.loadtest.BaseLoadTest;
import org.testng.annotations.Test;
import java.time.Duration;
import java.util.Map;
import static io.testfly.loadtest.LoadStep.jmesPath;
import static io.testfly.loadtest.LoadStep.regex;
import static io.testfly.loadtest.LoadStep.responseHeader;
import static io.testfly.loadtest.LoadStep.xpath;
public class OrderCorrelationLoadTest extends BaseLoadTest {
private static final Map<String, String> INV = Map.of("inv", "urn:example:invoice");
@Test
public void order() {
loadScenario("Order")
.engine("jdk").users(5).hold(Duration.ofSeconds(30))
// the response carries the header X-Auth-Token: t-123
.step("Login").post("/login")
.body(Map.of("username", "demo"))
.check(status().is(200))
.extract("token", responseHeader("X-Auth-Token")).and()
// the response body is {"order":{"id":42,"lines":[{"sku":"PROD-998"}]}}
.step("Create").post("/orders")
.header("X-Auth-Token", "${token}")
.body(Map.of("sku", "PROD-998"))
.extract("orderId", jmesPath("order.id"))
.extract("coupon", jmesPath("order.coupon"), "none").and()
// the response body is the text "ref=CNF-1234;"
.step("Confirm").get("/orders/${orderId}/confirmation")
.extract("ref", regex("ref=(\\w+-\\d+)")).and()
// the response body is <inv:invoice xmlns:inv="urn:example:invoice"><inv:total currency="EUR">10.00</inv:total></inv:invoice>
.step("Invoice").get("/invoices/${ref}")
.extract("total", xpath("//inv:total", INV))
.extract("currency", xpath("//inv:total/@currency", INV)).and()
.step("Pay").post("/payments")
.body(Map.of("order", "${orderId}", "amount", "${total}", "currency", "${currency}",
"coupon", "${coupon}"))
.check(status().is(201)).and()
.run()
.assertErrorRateBelow(0.01);
}
}
The Login step stores t-123 as token and the Create step sends it back. orderId is 42, ref is CNF-1234 (group 1), total is 10.00 and currency is EUR. The Create response has no order.coupon, so coupon gets the default none. status() comes from BaseLoadTest; the four other sources are static methods of LoadStep, imported here. The same calls run on both engines in CorrelationIntegrationTest; this listing itself is not compiled by the build.
Rules for each source
Both engines apply the same rules:
- First match. Every source takes the first value it finds: the header's first value, the first regex match, the first node in document order.
responseHeader(name). The name is matched in any case.matches(regex)searches the first value withfind().regex(pattern). The body is the decoded response text. The pattern is searched withfind(), without an implicit DOTALL (add(?s)for.to cross lines). The value is group 1 when the pattern has at least one group, otherwise the whole match. A group 1 that did not take part in the match, as inid=(\d+)?, counts as not found.xpath(expression[, namespaces]). XPath 1.0 on a namespace-aware DOM. The value is the string value of the first selected node (the text of an element and its descendants, the value of an attribute). A body that is not well-formed XML gives not found; the parse error is never printed. A prefix in the expression resolves only through thenamespacesmap (prefix to URI, kept in declaration order). There is no default element namespace: to select an element in a default namespace (<r xmlns="urn:a">), map a prefix to that URI and use it,xpath("/a:r", Map.of("a", "urn:a")).- XXE protection. The XML parser runs with secure processing and rejects document type declarations, so a body that contains a
<!DOCTYPE ...>gives not found: the check fails, or the extraction is KO or takes its default. External entities are never loaded. - JSON bodies. For
jsonPath(..)andjmesPath(..)a body that is not JSON counts as not found. Without a default the request is KO; with a default the default applies (one exception on Gatling, see Missing values and defaults). jmesPath(expression). A JSONnullresult or a missing value counts as not found. Numbers are stored as Jackson writes them, the same on both engines:{"p":1.10}gives1.1. This differs fromjsonPath(..), where a JSONnullvalue exists:jsonPath("$.a").exists()passes on{"a":null}andjmesPath("a").exists()fails. See JMESPath on each engine.- Literal text. Expressions, header names and default values are used as written; a
${var}inside them is not replaced.
Missing values and defaults
extract(variable, source): when the source finds nothing, the request is KO and the variable is not set. UsedoIf(LoadCondition.exists(variable), ..)to skip the steps that need it.extract(variable, source, defaultValue): when the source finds nothing,defaultValueis stored and the request stays OK. A default that applies counts as a normal OK request in the metrics.- A body that is not JSON is "nothing found" for
jsonPath(..)andjmesPath(..), so with a default the default applies, on both engines. One exception: on Gatling, ajsonPath(..)expression outside the JDK subset (a wildcard, a filter,..) with a default uses Gatling's ownwithDefault, and a body that is not JSON makes the request KO there. Without a default, a body that is not JSON is KO on both engines.
JSON null with jsonPath
With jsonPath(..), a JSON null value counts as found, with or without a default: the request is OK and the default is not applied. Nothing usable is stored, so a later ${variable} stays unresolved, and the engines then differ: the JDK engine sends the text ${variable} as written (in a path or query parameter, where it makes the URI invalid, the run aborts; see Retries), while Gatling cannot build the request and counts it as KO with status -1. When a null needs a fallback:
-
guard the next steps with
doIf(LoadCondition.exists(variable), ..):existsisfalsefor anullvalue; or -
extract with
jmesPath(..), where a JSONnullis not found, so the default applies:extract("coupon", jmesPath("order.coupon"), "none"). -
defaultValuemust not benull(IllegalArgumentException); omit it to make a missing value KO.extract(variable, status())throwsIllegalArgumentExceptiontoo. -
Extracting a variable again in the same step replaces the earlier extraction: the last one wins, whatever the source.
extract("id", "$.id").extract("id", regex("id=(\\d+)"))keeps only the regex. -
Several variables can be extracted from one response.
extractions() and extractors()
extractions()is the 1.0 map of variable to JSONPath. It holds onlyextract(var, path)andextract(var, jsonPath(p))without a default, and it is still mutable, as in 1.0.extractors()(since 1.1.0) returns every extraction as an unmodifiable list ofLoadExtraction(variable(),source(),expression(),namespaces(),hasDefault(),defaultValue()): first the entries ofextractions(), asJSON_PATH, then the other extractions in declaration order. Both engines evaluate them in that order.- New constants may be appended to
LoadExtraction.Source(JSON_PATH,HEADER,REGEX,XPATH,JMES_PATH), so aswitchover it needs adefaultbranch.
JMESPath on each engine
- JDK engine: a subset, written by TestFly on Jackson: names joined by
., with array indexes. A name is[A-Za-z_][A-Za-z0-9_]*or a quoted key such as"key with space", decoded as a JSON string (\",\\,\t,\u00e9); an index is[n]withn≥ 0 in ASCII digits, after a name, after another index or at the start. Accepted examples:a,a.b,a[0].b,a[12][3],[0].id,"key with space".x,a."b-c". Filters, projections (a[*].b,a.*,a[]), negative indexes, slices, pipes, functions, multiselects and@are rejected before any request, with a message that names the Gatling engine. - Gatling engine: full JMESPath, for example
items[?id > `3`].n | [0]orlength(items). Before the run TestFly compiles the expression with the JMESPath library that Gatling brings (io.burt:jmespath-jackson), so an invalid expression fails before any request. If that library is not on the test classpath, the expression is not checked, one WARN is logged, and an invalid expression makes every request of the step KO. A check, or an extraction without a default, runs Gatling's ownjmesPathcheck. An extraction with a default is evaluated by TestFly with the same library, so that a body that is not JSON takes the default, as on the JDK engine. - On both engines scalars are compared and stored as text.
Validation
Before any request is sent, both engines reject the following with IllegalArgumentException; the message names the scenario and the step:
| Input | Rule |
|---|---|
responseHeader(name) | name is an RFC 7230 token: ASCII letters, digits and !#$%&'*+-.^_`|~, nothing else. The same rule now applies to headerPresent(name). is(value) needs a value; matches(regex) needs a regex that compiles. |
regex(pattern) | Not blank, and Pattern.compile accepts it; the message carries the regex error. |
xpath(expression[, namespaces]) | Not blank; compiles as XPath 1.0 with only the declared prefixes, so an undeclared prefix fails; selects nodes: count(..), string(..), boolean(..) or 1 + 1 fail with "xpath(..) must select nodes". The rule is the same on Gatling. |
namespaces | Each prefix is an ASCII NCName ([A-Za-z_][A-Za-z0-9_.-]*) other than xml and xmlns; each URI is not blank. |
jmesPath(expression) | Not blank. JDK engine: inside the subset above. Gatling engine: compiles as JMESPath (when the library is on the classpath). |
| Extraction variable | Not blank, and not starting with the reserved testfly. prefix. |
| HEAD step | Only status(), headerPresent(..) and responseHeader(..) checks, and only responseHeader(..) extractions (see HEAD and OPTIONS steps). |
Request Content-Type
When a step has a body(...) and no Content-Type header, both engines send a Content-Type inferred from the body:
| Declared body | Content-Type sent |
|---|---|
Any non-String object (a Map, a record, a number, …), serialized to JSON | application/json |
A String whose first non-whitespace character is { or [ | application/json |
A String whose first non-whitespace character is < | application/xml |
A String that starts with a template, ${ or #{ (after leading whitespace) | application/json: the resolved value is unknown, so the earlier default is kept |
An empty or blank String | application/json (the earlier default) |
Any other literal text: a JSON scalar such as "42" or "true", $5, # heading, or text with a template after other characters such as id=${id} | text/plain; charset=UTF-8 |
- The rule looks at the body as declared, before any
${var}or#{var}is resolved.body("${payload}")is sent asapplication/jsonwhateverpayloadholds; if it holds XML or plain text, set the header yourself. - A
Content-Typeheader that you set always wins; the header name is matched in any case (content-typecounts). formParam(...)steps are unchanged:application/x-www-form-urlencodedunless you set the header.- A step with no body and no form parameters sends no
Content-Type.
Before 1.1.0, every body without a Content-Type header was sent as application/json. XML bodies (starting with <) and literal text bodies, including JSON scalars such as "42" and text such as id=${id}, now get application/xml or text/plain; charset=UTF-8. If the server expects JSON for such a body, add .header("Content-Type", "application/json") to the step.
HEAD and OPTIONS steps
LoadStep.head(path) and LoadStep.options(path) send a HEAD or OPTIONS request on both engines. LoadScenario.head(path) and LoadScenario.options(path) are shortcuts that add a single step named after the path, like get(path).
loadScenario("Health")
.engine("jdk").users(5).hold(Duration.ofSeconds(10))
.step("Probe").head("/health")
.check(status().is(200))
.check(LoadStep.headerPresent("Content-Length")).and()
.step("Preflight").options("/orders")
.header("Origin", "https://shop.example.com")
.header("Access-Control-Request-Method", "POST")
.check(status().in(200, 204)).and()
.run().assertErrorRateBelow(0.01);
- A HEAD request and its response have no body, so a HEAD step may only have status checks (
status().is(..),status().in(..)),headerPresent(..)checks and, since 1.1.0,responseHeader(..)checks (exists(),is(..),matches(..)) andresponseHeader(..)extractions, with or without a default. The following fail withIllegalArgumentExceptionbefore any request is sent, on both engines: ajsonPath(..),regex(..),xpath(..)orjmesPath(..)check, a bodymatches(..)check (status().matches(..)andjsonPath(..).matches(..)search the body), any otherextract(..)(a JSONPath one included), abody(..)and form parameters. The message names the source, for example "a HEAD step cannot have a regex(..) check". - OPTIONS steps accept every check, because an OPTIONS response may carry a body.