Skip to content

Creating a JMeter script compatible with PerfShop

This guide explains how to create a JMeter scenario from the JMeter GUI on your workstation, then upload it into PerfShop with Prometheus monitoring properly configured.

It incorporates the lessons learned during the development of PerfShop's bundled scenarios (JMeter 5.5 + XStream compatibility, XML pitfalls, plugin-free JSON extraction, Grafana label routing).


Prerequisites

  • JMeter 5.5 installed locally (download)
  • Prometheus Listener plugin installed in your local JMeter (optional for editing, required for PerfShop runs)
  • Access to the PerfShop JMeter UI (http://localhost:3005 or public URL)

Step 1 — Test plan structure

For metrics to surface by transaction name in the Grafana dashboard, each business step must be wrapped in a TransactionController with parent=true:

Test Plan
└── Thread Group
    ├── HTTP Request Defaults
    ├── CSV Data Set Config          ← user accounts
    ├── Cookie Manager               ← handles JSESSIONID automatically
    ├── Header Manager               ← global Content-Type / Accept
    │
    ├── TransactionController [T01_Homepage]  ← parent=true
    │   ├── GET /api/products
    │   └── GET /api/products/categories
    │
    ├── Flow Control Action [Think time]  ← one pause, between two transactions
    │   └── GaussianRandomTimer      ← child of the action: it fires only once (see §7.5)
    │
    ├── TransactionController [T02_SearchProduct]
    │   └── GET /api/products/search?q=...
    │       └── JSR223PostProcessor  ← JSON extraction (see step 3)
    │
    ├── ... (other transactions)
    │
    └── Prometheus Listener          ← with its 3 collectors (see step 4)

TransactionController parent=true — key to Grafana label routing

With parent=true, the TransactionController generates a single aggregated sample whose label is the transaction name (e.g. T01_Homepage). This label is what the Prometheus plugin uses to break down metrics in Grafana. Without parent=true, every inner HTTP sampler surfaces individually — the dashboard becomes unreadable with many requests.

1.2 Naming transactions for Grafana

The TransactionController name becomes the Prometheus label. Adopt a convention:

T01_Homepage
T02_SearchProduct
T03_AddToCart
T04_Login
T05_PlaceOrder
...

The Grafana dashboard automatically filters out technical samplers via:

label!~"null|Pr[ée]parer.*|BeanShell.*|JSR223.*|Setup.*|Teardown.*|DEBUG.*|__.*"

Avoid these prefixes for your business transactions.

1.3 Configure target variables

Never hardcode the host and port. Use the JMeter properties injected by PerfShop:

In HTTP Request Defaults:

Field Value to enter
Server Name or IP ${__P(target_host,perfshop-app)}
Port Number ${__P(target_port,8080)}
Protocol ${__P(target_protocol,http)}

Step 2 — JMeter 5.5 + XStream compatibility (XML pitfalls)

Three loading pitfalls (pitfalls 1 to 3)

These rules stem from XStream errors encountered in production: the plan does not load (NumberFormatException, NullPointerException, CannotResolveClassException). Pitfalls 1 and 2 are below, pitfall 3 is in step 3. Pitfalls 4 and 5 (a plan that loads but measures wrongly) are in steps 7.5 and 4; pitfalls 6 to 10 are in step 8.

2.1 Pitfall 1 — ThreadGroup.duration must be a stringProp

Problem: JMeter 5.5 uses XStream to deserialise JMX files. If ThreadGroup.duration is declared as a <longProp>, XStream tries to parse the value as a long before evaluating JMeter functions — causing:

Caused by: java.lang.NumberFormatException: For input string: "${__P(duration,300)}"

Rule: Always declare ThreadGroup.duration as <stringProp>, never <longProp>:

<!-- ✅ Correct -->
<stringProp name="ThreadGroup.duration">${__P(duration,300)}</stringProp>

<!-- ❌ Causes NumberFormatException with ${__P(...)} variables -->
<longProp name="ThreadGroup.duration">${__P(duration,300)}</longProp>

2.2 Pitfall 2 — stringProp elements inside collectionProp must have a name attribute

Problem: In ResponseAssertion, HTTP codes are stored in a collectionProp. Every <stringProp> child must have a name attribute equal to the Java hashCode of its value, otherwise XStream throws:

Caused by: java.lang.NullPointerException
    at ConversionHelp.getUpgradePropertyName(ConversionHelp.java:253)

Rule: Use the Java hashCode of the value as the name attribute:

<!-- ✅ Correct -->
<collectionProp name="Asserion.test_strings">
    <stringProp name="49586">200</stringProp>
</collectionProp>

<!-- ❌ Causes NullPointerException -->
<collectionProp name="Asserion.test_strings">
    <stringProp>200</stringProp>
</collectionProp>

Java String.hashCode() values for common HTTP codes:

HTTP code name to use
200 49586
201 49587
400 51508
401 51509
403 51511
404 51512
409 51517
500 52469
503 52472

Step 3 — Plugin-free JSON extraction (JSR223PostProcessor)

Pitfall 3 — JSONPathExtractor not available in the PerfShop image

JSONPathExtractor is provided by the bzm-json plugin (JMeter Plugins Manager). This plugin is not installed in the justb4/jmeter:5.5 image used by PerfShop: the only plugin present is the Prometheus Listener, and any element from another plugin makes the plan fail to load. Using it causes:

Caused by: com.thoughtworks.xstream.mapper.CannotResolveClassException: JSONPathExtractor

Not to be confused with the JSON elements of JMeter core

JSONPostProcessor ("JSON Extractor") and JSONPathAssertion ("JSON Assertion") are part of JMeter 5.5 itself, with no plugin: the plans shipped with PerfShop use them (see §3.4 and §7.8).

Solution: Use a JSR223PostProcessor with native Groovy (below) or the JSONPostProcessor of JMeter core (§3.4). Groovy and JsonSlurper are bundled in JMeter 5.5 with no plugin required.

3.1 JSON extraction pattern

<JSR223PostProcessor guiclass="TestBeanGUI" testclass="JSR223PostProcessor"
    testname="Extract securityToken" enabled="true">
  <stringProp name="scriptLanguage">groovy</stringProp>
  <stringProp name="parameters"></stringProp>
  <stringProp name="filename"></stringProp>
  <stringProp name="cacheKey">true</stringProp>
  <stringProp name="script">
try {
    def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
    def val = json.securityToken
    vars.put("securityToken", val != null ? val.toString() : "NO_TOKEN")
} catch(Exception e) {
    vars.put("securityToken", "NO_TOKEN")
}
  </stringProp>
</JSR223PostProcessor>
<hashTree/>

3.2 Common JSON path equivalents

JSONPath equivalent Groovy access
$.securityToken json.securityToken
$.content[0].id json.content[0].id
$.orderNumber json.orderNumber
$.totalPages json.totalPages
$.id json.id

3.3 In the JMeter GUI

To create this post-processor graphically: right-click on the sampler → Add → Post Processors → JSR223 Post Processor

3.4 Script-free variant: the JSONPostProcessor of JMeter core

For a simple extraction, JMeter's "JSON Extractor" is enough. This is the form used by the shipped plans Fonctionnel/checkout-stress-f1f2.jmx and Master/full-chaos-master.jmx:

<JSONPostProcessor guiclass="JSONPostProcessorGui" testclass="JSONPostProcessor"
    testname="Extract securityToken" enabled="true">
  <stringProp name="JSONPostProcessor.referenceNames">securityToken</stringProp>
  <stringProp name="JSONPostProcessor.jsonPathExprs">$.securityToken</stringProp>
  <stringProp name="JSONPostProcessor.match_numbers">1</stringProp>
  <stringProp name="JSONPostProcessor.defaultValues">NO_TOKEN</stringProp>
</JSONPostProcessor>
<hashTree/>

The default value (NO_TOKEN) acts as a witness: if the extraction fails, the next request shows it.


Step 4 — Add the Prometheus Listener

4.1 Position in the tree

A listener receives the samples of its scope:

Thread Group
└── Prometheus Listener  ← the requests of THIS group only
Test Plan
├── Thread Group A
├── Thread Group B
└── Prometheus Listener  ← the requests of ALL groups

With a single group, both positions work (the shipped single-group plans place it under the group). With several groups, place it under the Test Plan: this is where the shipped plan Master/full-chaos-master.jmx has it, and each of its three profiles is reported under its own label.

Pitfall 5 — a listener without collectors only exposes jmeter_threads

Live monitoring reads three metrics: jmeter_transactions_total, jmeter_response_time and jmeter_success_ratio. They only exist if the listener carries their three definitions (prometheus.collector_definitions, §4.2). Without them the run proceeds and the HTML report is complete, but Prometheus only receives jmeter_threads: JMeter UI shows 0 transactions, and the Grafana panels for transactions, latency and error rate have no series to read.

4.2 Configuration in the JMX

<com.github.johrstrom.listener.PrometheusListener
    guiclass="com.github.johrstrom.listener.gui.PrometheusListenerGui"
    testclass="com.github.johrstrom.listener.PrometheusListener"
    testname="Prometheus Metrics Exporter" enabled="true">
  <stringProp name="prometheus.port">${__P(prometheus.port,9270)}</stringProp>
  <stringProp name="prometheus.save.threads">true</stringProp>
  <stringProp name="prometheus.save.jvm">false</stringProp>
  <collectionProp name="prometheus.collector_definitions">
    <!-- jmeter_transactions_total (COUNTER) -->
    <elementProp name="" elementType="com.github.johrstrom.listener.ListenerCollectorConfig">
      <stringProp name="collector.metric_name">jmeter_transactions_total</stringProp>
      <stringProp name="collector.type">COUNTER</stringProp>
      <collectionProp name="collector.labels">
        <stringProp name="102727412">label</stringProp>
        <stringProp name="3059181">code</stringProp>
      </collectionProp>
      <stringProp name="listener.collector.listen_to">samples</stringProp>
      <stringProp name="listener.collector.measuring">CountTotal</stringProp>
    </elementProp>
    <!-- jmeter_response_time (SUMMARY P50/P95/P99) -->
    <elementProp name="" elementType="com.github.johrstrom.listener.ListenerCollectorConfig">
      <stringProp name="collector.metric_name">jmeter_response_time</stringProp>
      <stringProp name="collector.type">SUMMARY</stringProp>
      <collectionProp name="collector.labels">
        <stringProp name="102727412">label</stringProp>
      </collectionProp>
      <stringProp name="collector.quantiles_or_buckets">0.5,0.05|0.95,0.01|0.99,0.001</stringProp>
      <stringProp name="listener.collector.listen_to">samples</stringProp>
      <stringProp name="listener.collector.measuring">ResponseTime</stringProp>
    </elementProp>
    <!-- jmeter_success_ratio -->
    <elementProp name="" elementType="com.github.johrstrom.listener.ListenerCollectorConfig">
      <stringProp name="collector.metric_name">jmeter_success_ratio</stringProp>
      <stringProp name="collector.type">SUCCESS_RATIO</stringProp>
      <collectionProp name="collector.labels">
        <stringProp name="102727412">label</stringProp>
      </collectionProp>
      <stringProp name="listener.collector.listen_to">samples</stringProp>
      <stringProp name="listener.collector.measuring">SuccessRatio</stringProp>
    </elementProp>
  </collectionProp>
</com.github.johrstrom.listener.PrometheusListener>
<hashTree/>

Step 5 — CSV Data Set and variables

For multi-user scenarios, use a CSVDataSet with shareMode.all (global cursor: each thread receives a different account per iteration — see the warning below; shareMode.thread would cause account collisions):

<CSVDataSet guiclass="TestBeanGUI" testclass="CSVDataSet"
    testname="User accounts" enabled="true">
  <stringProp name="filename">/scripts/users.csv</stringProp>
  <stringProp name="fileEncoding">UTF-8</stringProp>
  <stringProp name="variableNames">userEmail,userPassword,userName</stringProp>
  <stringProp name="delimiter">,</stringProp>
  <boolProp name="ignoreFirstLine">true</boolProp>
  <boolProp name="recycle">true</boolProp>
  <boolProp name="stopThread">false</boolProp>
  <stringProp name="shareMode">shareMode.all</stringProp>
</CSVDataSet>
<hashTree/>

The users.csv file is mounted inside the container at /scripts/users.csv.


Step 6 — Upload and run in PerfShop

  1. Save the .jmx: File → Save Test Plan As
  2. Open PerfShop JMeter UI → 🗂️ Manage
  3. Choose the target folder → 📤 → select the .jmx
  4. Launch with ▶ Start run

Metrics appear in the perfshop-jmeter-live Grafana dashboard after ~10 seconds, broken down by TransactionController name.

6.1 What JMeter UI tells you and keeps for you

  • Shipped plans are read-only. The 8 plans delivered with PerfShop are labelled "shipped" in the manager: they cannot be deleted, moved, replaced by an upload of the same name, or saved from the editor (403 refusal). Give your plan another name: your own scenarios remain fully editable.
  • Your plans and your reports are yours. On the class platform, each account keeps what it made: only you (and the instructor) delete the report of your run, and move, replace, edit or delete a plan you uploaded. A classmate's plan shows its author and opens read-only; its name is taken: give yours another name (with your initials, for instance). The Reports list tells, for each run, the plan and the starter.
  • A plan that does not load. The status becomes "Error" and the cause found in the JMeter log is shown under the badge (for instance the element of a missing plugin, or the badly closed XML tag and its line). No report is produced: nothing was sent.
  • A run without a single sample (every thread stopped at start) is an "Error" too, with the first error of the log.
  • A stopped run is marked "Stopped", with the time actually run; its HTML report is built from the results already written and joins the Reports list.
  • Reports open through a read link valid for two hours: reopen them from the Reports list once it has expired, or after a restart of the service.
  • The P50, P95 and P99 cards, and the response-time chart, show during the run the percentile of the worst transaction: the highest value across the labels of the plan. It is not the percentile of the whole run, and the three figures may come from three different transactions. The per-transaction detail is in the Statistics table of the HTML report and in the Grafana dashboard perfshop-jmeter-live.
  • A plan writes only to /results. In the JMeter container, /scenarios, /scripts and /plugins are read-only: a script that writes a file there fails with "Read-only file system", and a listener whose file points there writes nothing, with no error in the log. A listener whose file is given as a relative path writes to the working directory of JMeter, inside the container — a file you will not find again. Give an absolute path under /results.

Summary — Pre-upload checklist

Check point ✅ Expected
target_host ${__P(target_host,perfshop-app)}
target_port ${__P(target_port,8080)} — never 9080
ThreadGroup.duration <stringProp> — never <longProp> with ${__P(...)}
stringProp in collectionProp name attribute with Java hashCode of the value
JSON extraction JSR223PostProcessor Groovy or JSONPostProcessor (JMeter core) — never JSONPathExtractor (plugin not installed)
TransactionController parent=true on each business step
PrometheusListener Under the Thread Group (one group) or under the Test Plan (several groups), with its 3 collectors
Prometheus port ${__P(prometheus.port,9270)}
Think time One GaussianRandomTimer per pause, child of a Flow Control Action placed between two transactions — never directly under the Thread Group
No hardcoded URL Neither localhost, nor a fixed IP, nor a public hostname

Step 7 — Step-by-step guide using JMeter GUI

This guide shows how to build a complete business journey scenario from the JMeter graphical interface, without editing XML by hand.

7.1 Create the test plan

  1. Launch JMeter: jmeter.bat (Windows) or jmeter (Linux/Mac)
  2. File → New for a blank plan
  3. Click Test Plan → rename: PerfShop — My scenario
  4. In the bottom panel, uncheck Functional Test Mode

7.2 Add a Thread Group

Right-click Test Plan → Add → Threads (Users) → Thread Group

Parameter Recommended value
Number of Threads ${__P(users,5)}
Ramp-up period ${__P(ramp_time,30)}
Duration ${__P(duration,300)}
Loop Count -1 (infinite with scheduler)
Scheduler ✅ Checked
On Sample Error Continue

Never hardcode users/duration

Always use ${__P(users,5)} — this allows the PerfShop JMeter UI to control the number of vUsers and duration without modifying the JMX file.

7.3 Add configuration elements

Right-click Thread Group → Add:

HTTP Request Defaults (Config Element → HTTP Request Defaults)

Field Value
Server Name ${__P(target_host,perfshop-app)}
Port ${__P(target_port,8080)}
Protocol ${__P(target_protocol,http)}
Encoding UTF-8

HTTP Header Manager (Config Element → HTTP Header Manager)

Add two headers:

Name Value
Content-Type application/json
Accept application/json

HTTP Cookie Manager (Config Element → HTTP Cookie Manager)

  • Clear cookies each iteration: ✅

CSV Data Set Config (Config Element → CSV Data Set Config)

Field Value
Filename /scripts/users.csv
Variable Names userEmail,userPassword,userName
Delimiter ,
Ignore first line ✅
Recycle on EOF ✅
Share Mode shareMode.all

shareMode.all — prevents account collisions

With shareMode.thread, each thread advances independently and multiple threads may land on the same account simultaneously. With shareMode.all, all threads share a global cursor that advances sequentially — each thread receives a different account per iteration. This is essential to avoid the "Duplicate order detected" error from the PerfShop backend (3-second anti-duplicate cooldown per user+cart).

7.4 Add a transaction

For each business step (T01, T02...):

  1. Right-click Thread Group → Add → Logic Controller → Transaction Controller
  2. Name it: T01_Homepage
  3. Check Generate parent sample: ✅ (this is the parent=true required for Grafana)
  4. Right-click the transaction → Add → Sampler → HTTP Request
  5. Configure the request: method, path, body

7.5 Add think time (Flow Control Action + GaussianRandomTimer)

A timer is not a step: it applies before every request in its scope.

Pitfall 4 — a timer placed directly under the Thread Group applies to ALL its requests

Ten timers placed "between" the transactions, at Thread Group level, do not make ten spread-out pauses: their delays add up before every request. Measured on parcours-metier-nominal.jmx before it was fixed: a 17.5 s wait before each of its requests, 11 samples in 100 s with 2 users. The plan runs, without errors, but generates almost no load.

For a pause between two transactions, played only once per iteration:

  1. Right-click Thread Group → Add → Sampler → Flow Control Action; action Pause, duration 0; place it between the two TransactionController elements.
  2. Right-click that Flow Control Action → Add → Timer → Gaussian Random Timer:
Field Value
Constant Delay 2000 (ms)
Deviation 600 (ms)

The timer now has a single request in its scope, the Flow Control Action, which produces no sample: the pause appears neither in the report nor in the metrics. In the JMX:

<TestAction guiclass="TestActionGui" testclass="TestAction" testname="Think time — browsing" enabled="true">
  <intProp name="ActionProcessor.action">1</intProp>
  <intProp name="ActionProcessor.target">0</intProp>
  <stringProp name="ActionProcessor.duration">0</stringProp>
</TestAction>
<hashTree>
  <GaussianRandomTimer guiclass="GaussianRandomTimerGui" testclass="GaussianRandomTimer"
      testname="Browsing pause 2s ±600ms" enabled="true">
    <stringProp name="ConstantTimer.delay">2000</stringProp>
    <stringProp name="RandomTimer.range">600</stringProp>
  </GaussianRandomTimer>
  <hashTree/>
</hashTree>

This is the form used by the shipped plans parcours-metier-nominal.jmx and E2E/parcours-complet-e2e.jmx: one iteration lasts the sum of its pauses, plus the response times.

A single timer for a single request

When a Thread Group contains only one request (plans baseline-nominal, simple-api-products, Fonctionnel/*), a timer placed under the group applies to that request only: this is correct.

7.6 Add JSON extraction (JSR223PostProcessor)

Right-click the HTTP sampler → Add → Post Processors → JSR223 Post Processor

  • Script Language: groovy
  • Cache compiled script if possible: ✅
  • Script:
try {
    def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
    def val = json.securityToken
    vars.put("securityToken", val != null ? val.toString() : "NO_TOKEN")
} catch(Exception e) {
    vars.put("securityToken", "NO_TOKEN")
}

7.7 Add a response assertion

Right-click the HTTP sampler → Add → Assertions → Response Assertion

  • Field to Test: Response Code
  • Pattern Matching Rules: Equals
  • Patterns to test: 200

To check 200 or 201 (OR): - Add 200 and 201 as patterns - Pattern Matching Rules: OR (check "OR")

An assertion does not \"rescue\" an HTTP error code

For JMeter, an HTTP request whose code is 4xx or 5xx has already failed, before any assertion. A "200 or 500" assertion therefore does not make a 500 pass (you would have to tick Ignore Status), and the failure then carries no message. Write the assertion for the expected result ("200") and fill in its failure message (Custom failure message): that is what the failed samples carry.

7.8 Add a Groovy assertion (JSR223Assertion)

For complex checks (e.g. canCheckout = true):

Right-click the sampler → Add → Assertions → JSR223 Assertion

try {
    def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
    if (json.canCheckout != true) {
        AssertionResult.setFailure(true)
        AssertionResult.setFailureMessage("canCheckout = false")
    }
} catch(Exception e) {
    AssertionResult.setFailure(true)
    AssertionResult.setFailureMessage("Invalid JSON: " + e.getMessage())
}

JSONPathAssertion is part of JMeter 5.5

The JSON assertion of JMeter core ("JSON Assertion", class JSONPathAssertion) needs no plugin: three shipped plans use it (E2E/parcours-complet-e2e.jmx, Fonctionnel/browse-product-f4.jmx, Master/full-chaos-master.jmx). What the PerfShop image lacks is the bzm-json plugin (JSONPathExtractor, pitfall 3).

To check a single field, it avoids a script. Example from the browse-product-f4.jmx plan — the response fails if stock equals 0:

<JSONPathAssertion guiclass="JSONPathAssertionGui" testclass="JSONPathAssertion"
    testname="[F4] Stock ne doit pas être 0" enabled="true">
  <stringProp name="JSON_PATH">$.stock</stringProp>
  <stringProp name="EXPECTED_VALUE">0</stringProp>
  <boolProp name="JSONVALIDATION">true</boolProp>
  <boolProp name="EXPECT_NULL">false</boolProp>
  <boolProp name="INVERT">true</boolProp>
  <boolProp name="ISREGEX">false</boolProp>
</JSONPathAssertion>
<hashTree/>

7.9 Add a JSR223PreProcessor (before a sampler)

To prepare dynamic variables before a sampler executes:

Right-click the sampler → Add → Pre Processors → JSR223 Pre Processor

Example — randomly select a shipping method without __chooseRandom:

def methods = ["standard", "standard", "express", "premium"]
def r = new Random()
vars.put("shippingMethodToUse", methods[r.nextInt(methods.size())])

PreProcessor as child of a sampler: runs BEFORE the sampler

A JSR223PreProcessor positioned as a child of an HTTPSamplerProxy executes before that sampler. Variables it defines are available in the sampler's request body.

7.10 Add the Prometheus Listener

Right-click Thread Group → Add → Listener → jp@gc - Prometheus Listener

  • Port: ${__P(prometheus.port,9270)}
  • Save threads: ✅
  • Save JVM: ☐

Add three metrics (click +):

Metric Name Type Labels Measuring
jmeter_transactions_total COUNTER label, code CountTotal
jmeter_response_time SUMMARY label ResponseTime
jmeter_success_ratio SUCCESS_RATIO label SuccessRatio

For jmeter_response_time, add quantiles: 0.5,0.05|0.95,0.01|0.99,0.001

7.11 Save and test locally

  1. File → Save Test Plan As → name it my-scenario.jmx
  2. Run locally: Run → Start (or Ctrl+R)
  3. Verify in View Results Tree that all assertions pass
  4. Upload to PerfShop JMeter UI → 🗂️ Manage → 📤

Step 8 — Additional pitfalls discovered on PerfShop

These pitfalls come from debugging the parcours-metier-nominal.jmx scenario.

❌ Pitfall 6 — Groovy scripts on a single line with literal \n

Symptom:

startup failed:
Script166.groovy: 1: Unexpected character: '\' @ line 1, column 6.
   try {\n    def json = new groovy.json.JsonSlurper()...

Cause: When a JMX is edited manually and the Groovy script is placed on a single line with literal \n sequences (backslash + n), JMeter 5.5 / Groovy 3.0 does not interpret them as line breaks. The Groovy is syntactically invalid.

<!-- ❌ BAD — literal \n, single line -->
<stringProp name="script">try {\n    def json = ...\n} catch(Exception e) {\n}</stringProp>

<!-- ✅ CORRECT — real line breaks in XML -->
<stringProp name="script">
try {
    def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
    vars.put("myVar", json.myField?.toString() ?: "default")
} catch(Exception e) {
    vars.put("myVar", "default")
}
</stringProp>

Rule: Groovy scripts in stringProp elements must always contain real XML line breaks.

❌ Pitfall 7 — __chooseRandom with trailing comma generates empty values

Symptom: Requests with 400/422, JSON body with empty fields ("street":"").

Cause: __chooseRandom(val1,val2,val3,) — the trailing comma is interpreted as an extra empty item. When JMeter picks the last item, the variable equals "" and the backend rejects the JSON.

# ❌ BAD — trailing comma
${__chooseRandom(standard,express,premium,)}

# ✅ CORRECT — no trailing comma (but still not recommended, see below)
${__chooseRandom(standard,express,premium)}

# ✅ BEST — JSR223PreProcessor with Groovy array
def methods = ["standard", "express", "premium"]
vars.put("method", methods[new Random().nextInt(methods.size())])

Rule: Never use __chooseRandom in PerfShop — always use a JSR223PreProcessor with a Groovy array.

❌ Pitfall 8 — && in inline JMeter functions causes XmlPullParserException

Symptom:

Caused by: org.xmlpull.v1.XmlPullParserException: entity reference names can not start with character '&'

Cause: The & character in an XML attribute must be escaped as &amp;. Inside a stringProp, && (Groovy logical AND) is invalid XML. The XStream parser (XmlPullParser) rejects it.

<!-- ❌ BAD — && invalid in XML stringProp -->
<stringProp name="Argument.value">{"id":${__groovy(vars.get('a') != null && !vars.get('a').equals('0') ? vars.get('a') : '1',)}}</stringProp>

<!-- ✅ CORRECT — separate JSR223PreProcessor BEFORE the sampler -->
// In a JSR223PreProcessor child of the sampler:
def a = vars.get("a")
vars.put("idToUse", (a != null && !a.equals("0")) ? a : "1")

Rule: All conditional logic must go in a separate JSR223PreProcessor. Never put &&, ||, or <> in a stringProp without XML escaping.

❌ Pitfall 9 — Backend anti-duplicate protection (HTTP 409)

Symptom: under load, some POST /api/orders come back as 409 with {"error":"Duplicate order detected — please wait"} (on a French deployment: "Commande en double détectée — veuillez patienter").

Cause: this is not a fault. The PerfShop backend refuses a second order from the same account with the same cart less than 3 seconds after the first one: it is its double-click protection, active at levels 0 and 1 of the business chaos (anomaly A5 removes it from level 2). A plan whose threads share one account and order the same cart triggers it every time.

A 409 is an expected business refusal, like the "insufficient stock" 409: it is counted apart from server errors (5xx) and must not be masked.

Fix — distinct accounts or distinct carts:

  • a different account at each iteration: shareMode.all in the CSV Data Set (step 5);
  • or a different cart for each order: the shipped plans Fonctionnel/checkout-stress-f1f2.jmx and Master/full-chaos-master.jmx order with a single account and vary the quantity with a counter.

Do not "accept" this code in an assertion: for JMeter a 409 remains a failure (see §7.7), and the error rate of the run would then mix business refusals and faults.

❌ Pitfall 10 — Empty orderId in URL causes URISyntaxException

Symptom:

Non HTTP response code: java.net.URISyntaxException

Cause: If T08 (order creation) fails, ${orderId} remains empty. The URL /api/orders//details is syntactically invalid for java.net.URI.

Fix: Add a JSR223PreProcessor before the detail request (path /api/orders/${orderIdToFetch}/details) that sets a fallback of "0" if orderId is missing:

def oid = vars.get("orderId")
if (oid == null || oid.equals("") || oid.equals("0")) {
    vars.put("orderIdToFetch", "0")
} else {
    vars.put("orderIdToFetch", oid)
}

Use ${orderIdToFetch} in the path instead of ${orderId} — in the path only: the request name stays fixed (GET /api/orders/{id}/details), otherwise the report counts one label per order.


Step 9 — Extract a response header and send it back

An API may return a value in a response header (a token, a correlation identifier) and expect it to be sent back in the following requests. The technique does not depend on the API; the example below reads the Content-Type header and sends it back in an X-Exemple header.

9.1 Extract: Regular Expression Extractor on the headers

Right-click the request that receives the header → Add → Post Processors → Regular Expression Extractor, field Field to check: Response Headers. In the JMX:

<RegexExtractor guiclass="RegexExtractorGui" testclass="RegexExtractor" testname="Extraire Content-Type" enabled="true">
  <stringProp name="RegexExtractor.useHeaders">true</stringProp>
  <stringProp name="RegexExtractor.refname">exempleValeur</stringProp>
  <stringProp name="RegexExtractor.regex">(?i)Content-Type: ([^\r\n;]+)</stringProp>
  <stringProp name="RegexExtractor.template">$1$</stringProp>
  <stringProp name="RegexExtractor.default">ABSENT</stringProp>
  <stringProp name="RegexExtractor.match_no">1</stringProp>
</RegexExtractor>
<hashTree/>
  • RegexExtractor.useHeaders set to true: the expression applies to the response headers, one Name: value line per header;
  • (?i): an HTTP header name is case-insensitive;
  • the default value (ABSENT) acts as a witness: if the header is missing, the next request shows it.

9.2 Send back: HTTP Header Manager

Right-click the request that must carry the header → Add → Config Element → HTTP Header Manager:

<HeaderManager guiclass="HeaderPanel" testclass="HeaderManager" testname="Renvoyer X-Exemple" enabled="true">
  <collectionProp name="HeaderManager.headers">
    <elementProp name="" elementType="Header">
      <stringProp name="Header.name">X-Exemple</stringProp>
      <stringProp name="Header.value">${exempleValeur}</stringProp>
    </elementProp>
  </collectionProp>
</HeaderManager>
<hashTree/>

As a child of a request, it applies to that request only; as a child of a controller or of the Thread Group, to every request in its scope.

9.3 One value per virtual user: vars, not props

Scope Write Read
Variable one thread (one virtual user) extractor, vars.put("name", value) ${name}, vars.get("name")
Property the whole run, all threads props.put("name", value), option -Jname=value ${__P(name)}, props.get("name")

A value returned to one user (token, session identifier) belongs in a variable: each thread keeps its own. Stored in a property, it would be overwritten by the last thread that writes, and all threads would send the same one. The HTTP Cookie Manager follows the same rule: one set of cookies per thread.

Measured on a 3-thread proof plan (PerfShop's JMeter 5.5): each thread's variable kept its value on every request, whereas the shared property no longer held the thread's own value in 60 requests out of 91.

The shipped plans that share a session

Fonctionnel/checkout-stress-f1f2.jmx and Master/full-chaos-master.jmx log a single account in within their setUp group and deliberately share its session through properties: this is a stress-plan shortcut, valid as long as the server accepts the same session for all threads.

9.4 Script variant (JSR223PostProcessor)

def ligne = prev.getResponseHeaders().readLines().find { it.toLowerCase().startsWith('content-type:') }
vars.put('exempleValeurScript', ligne != null ? ligne.substring(ligne.indexOf(':') + 1).trim() : 'ABSENT')

The PerfShop JMeter container runs Groovy 3 on Java 8: a script only has the Java 8 APIs available.


Complete summary — Definitive JMX rules for PerfShop

Rule Description
✅ shareMode.all CSV Data Set — sequential account distribution across threads
✅ Multi-line Groovy scripts Real line breaks in stringProp script elements
✅ JSR223PreProcessor for logic Never use &&, ||, __groovy() inline in stringProp
✅ JSON extraction: JSR223PostProcessor or JSONPostProcessor Never use JSONPathExtractor (plugin not installed)
✅ JSON assertion: JSONPathAssertion (one field) or JSR223Assertion (logic) Both are in JMeter 5.5, no plugin needed
✅ A failure message on every assertion An assertion does not make a 4xx or 5xx code pass
✅ JSR223PreProcessor for random data Never use __chooseRandom with trailing comma
✅ Fallback on critical variables Check orderId, foundProductId, foundProductPrice before use in URLs
✅ TransactionController parent=true Required for Grafana metric ventilation
✅ ${__P(...)} for all configurable params Never hardcode users, duration, target_host
✅ <stringProp> for ThreadGroup.duration Never <longProp> with ${__P(...)}
✅ HashCode name attribute on stringProp in collectionProp Avoids XStream NPE
✅ PrometheusListener with its 3 collectors Under the Thread Group, or under the Test Plan when there are several groups
✅ One Flow Control Action per pause Never a timer directly under a Thread Group that has several requests
✅ Fixed request name Never a variable in the name (${id}): one label per value in the report and in the metrics
✅ vars for what belongs to one virtual user props is shared by all threads (step 9)