The language

A script is a list of statements, run from top to bottom. It calls resources, looks at their answers and decides what to do next. The language is small on purpose: what it cannot say belongs in a service.

bbrun
// comments use // or /* ... */

let id = "cus_" + randomString(6)
customersApi.post("/customers", { "id": id, "email": "ana@example.com" })
assert response.status == 201
print "created customer " + id

Semicolons are optional and line breaks mean nothing: a statement ends where the next one starts.

Values

ValueWritten
Number42, -1, 3.14
String"double quoted" or 'single quoted', with the escapes \n \t \r \" \' \\; ${…} inside puts a value there (see Strings)
Booleantrue, false
Nullnull
Object{ "id": "pi_1", "amount": 100 }
List["a", "b", "c"]
Responsewhat a resource call answers: see The response
Bytesa file exactly as it is on disk: bytes("logo.png"), see Files as bytes
WebSocketan open socket: eventsApi.websocket("/orders"), see WebSockets

Objects and lists are written as in JSON. The keys of an object are quoted strings, its values are expressions, and a comma after the last entry is allowed. A whole number is kept as a whole number, any other as a decimal: 5 / 2 is 2.5 and 5 == 5.0 is true.

Strings

Every string puts the value of each ${…} where it stands, wherever the string is written: a path, a let, a value in an object, a print, the message of an assert.

bbrun
let path = "/orders/${order.id}/items"
print "${items.length} items, ${total * 1.2} with tax"
let note = { "text": "order ${order.id} is ${order.status}" }

Between the braces goes any expression. A string goes in as it is, a number or a boolean as written, an object or a list as JSON, and null as nothing. In a "…" string, write the strings of the expression with single quotes, "${find(items, 'sku', 'a1').qty}", since a " would end the string. \${ keeps a ${ as it is: "\${id}" is the text ${id}.

Variables

let declares a variable. name = value sets it again, and so does a let of a name that exists, which is how a loop keeps what it found.

bbrun
let name = "Sarah"
let meta = { "tags": ["a", "b"], "nested": { "x": 1 } }

let found = null
for user in users {
    if user.email == "ana@example.com" {
        let found = user
        break
    }
}

A variable is visible from its declaration to the end of the script, also when it was declared inside a block, a step or a loop. Only a function keeps variables of its own.

Setting a field or an element

= also sets a key of an object or an element of a list, at any depth:

bbrun
let order = { "status": "new", "items": [{ "sku": "a1", "qty": 1 }] }
order.status = "paid"
order.items[0].qty = 3
order.items[1] = { "sku": "b2", "qty": 1 }   // the index after the last adds an element
order["gift note"] = "Happy birthday"

The variable must exist, and so must each object on the way: order.address.city = "Berlin" fails while order.address is null. An index further than the one after the last fails too. Objects are shared, not copied: after let copy = order, setting copy.status changes order; order + {} is a copy. The body of a response is an object like any other; the response itself cannot be changed.

Expressions

Operators, from the one that binds first to the one that binds last:

OperatorMeaning
f(…), x.name(…)a function call, a resource operation or a method
x.name, x[i]a key of an object, an element of a list
* /multiply, divide
+ -add numbers, join strings, lists or objects; subtract
== != < > <= >=compare
matchesvalue matches Model: true when the value is a valid Model (see Models and mappings)
contains, not containsan element in a list, a key in an object, a part of a string
notthe opposite
andboth
oreither
  • == compares values: 1 == 1.0 is true, lists are compared element by element and objects key by key, so an answer compares with a literal: assert response.body.ids == [1, 2].
  • + joins when either side is a string, and joins two lists into a new one: let seen = seen + [id] grows a list in a loop. Two objects make a new one with the keys of the left, then those of the right over them: base + { "amount": 1250 }; neither side changes. Anything else, such as [1] + 2, fails the script and says what it was given.
  • < and the like also compare strings, in alphabetical order.
  • Where a condition is expected, false, null, 0, an empty string and an empty list or object count as false. Everything else is true.
  • and and or stop at the first answer: the right side is evaluated only when the left side does not decide. So if order != null and order.total > 0 is safe when order is null. Both give true or false.

Members and methods

bbrun
print employee.name                // a key of an object
print employees.length             // the size of a list
print employees[0]                 // an element of a list
print "HELLO".toLowerCase()        // "hello"
print "  x  ".trim()               // "x"

A list has length (or size), and the methods contains(x) and indexOf(x) (-1 when absent), which compare as == does. A string has length too, and the methods toLowerCase(), toUpperCase(), trim(), length(), startsWith(s), endsWith(s), contains(s), indexOf(s), replace(a, b), split(separator) and substring(from, to). Any other method is an error.

Calling a resource

A resource is one of the names the environment declares. A script calls an operation on it.

bbrun
customersApi.post("/customers", customer)
paymentsApi.get("/services/partners/${partnerId}/balances/${currency}")
assert response.status == 200

On an HTTP resource and on its mock, the operations are get, post, put, patch and delete. The first argument is the path, exactly as it goes on the wire, after the base URL of the environment, with its ${…} filled in (see Strings). Other kinds of resources have their own operations, such as query on a database or send on a queue: see Environments and resources.

A path may also be a whole address, https://…, one an answer handed back: a download address, a Location, the next page. The call goes there. The credentials of the resource (its auth and headers, and what authenticate set) go with it only when the address is on the resource's own origin: the same scheme, host and port as its base URL.

bbrun
assets.post("/files", { "name": "logo.png" })
assets.get(response.body.downloadUrl)       // another host: sent without the credentials

After the path come the body and the options of the call, in any order:

bbrun
assets.post("/upload?key=logo.svg", file("fixtures/logo.svg"))
assets.put("/files/logo.png", bytes("fixtures/logo.png"))
assets.get("/files/logo.svg", headers({ "Accept-Language": "de", "If-None-Match": etag }))
metrics.get("/points?waitSeconds=30", timeout(40000))
signIn.post("/login", form({ "email": "ana@example.com", "password": env("PASSWORD") }))
  • A body is sent as JSON, unless it was made by form({…}) (a URL-encoded form), file(path) (a text file as it is) or bytes(path) (any file, byte for byte), each with the content type of the file's extension.
  • headers({…}) adds headers to that call only. They win over the headers of the resource, and go wherever the call goes.
  • timeout(ms) is how long that call waits for its answer: timeout(40000) or timeout("40s"). Without it, a call waits as long as its resource says (timeout: in the configuration), 15 seconds when it says nothing, and then fails the script with what it waited for.
  • A redirect is answered to the script, not followed: the script reads response.headers.location.

The same calls can be written verb first, which some scenarios read better with:

bbrun
post bulk to customersApi."/customers/bulk"
get customersApi."/customers/${id}"
delete ordersApi."/orders/o_y"

Credentials set by the script

The environment gives each resource its credentials. A script that signs in can replace them with what it got: authenticate(resource, auth) sends auth with every later call to that resource, until the next authenticate.

bbrun
signIn.post("/login", form({ "email": "ana@example.com", "password": env("PASSWORD") }))
assert response.status == 302
api.post("/token", { "code": urlParam(response.headers.location, "code") })
authenticate(api, { "type": "bearer", "token": response.body.accessToken })
api.get("/me")

auth is written as in the configuration: {"type": "bearer", "token": t}, {"type": "apikey", "headerName": "X-API-Key", "headerValue": k}, {"type": "basic", "username": u, "password": p}, {"type": "headers", "headers": {…}} for any headers, or {"type": "none"} to stop sending what an earlier call set.

Files as bytes

file(path) reads a file as text. An image, a PDF or an archive goes with bytes(path), exactly as it is on disk, and an answer keeps the bytes it came with, whatever they are:

bbrun
let logo = bytes("fixtures/logo.png")            // image/png, from the extension
assets.put("/files/logo.png", logo)
assets.get("/files/logo.png", headers({ "Accept": "image/png" }))
assert response.headers["content-type"] == "image/png"
assert response.size == logo.size                // the bytes received
assert response.sha256 == logo.sha256            // the same bytes
assets.put("/files/copy.png", base64Bytes(response.bytes, "image/png"))

Bytes have size, sha256 (in hex), base64 and contentType. A binary answer is compared by its response.size and response.sha256; its response.body is the text of it, not meant to be read. A mock reads bytes as their base64 text.

WebSockets

resource.websocket(path) opens a WebSocket on an HTTP resource, at its base URL with wss:// for https:// (ws:// for http://), or at a whole address. It carries the credentials of the resource and the call's headers({…}), as any call does. Its answer is 101, and its value the open socket. A server that refuses answers as HTTP does: response.status and response.body are that answer (401, 403…), so check the status before using the socket.

bbrun
let ws = queues.websocket("/queues/orders/subscribe?max=5")
assert response.status == 101
let m = ws.receive(5000)                         // the next message, or null after 5 s
assert m.type == "message"
ws.send({ "type": "ack", "id": m.id })           // an object goes as JSON, a string as it is
assert ws.receive(1000) == null : "nothing more came"
ws.close()
assert ws.open == false
Of a socketGives
ws.receive(ms)the next message, waiting at most ms (or "5s"; 5 seconds when left out): JSON as an object, other text as it is, a binary message in base64; null when none came in time or the socket is closed
ws.send(value)sends a text message: a string as it is, anything else as JSON
ws.close()closes it (1000)
ws.opentrue until either side closed it
ws.closeCode, ws.closeReasonhow it was closed, such as 1008 and "No queue orders/x"; null while it is open

Subprotocols are offered with headers({ "Sec-WebSocket-Protocol": "v1" }). Messages wait, in order, until receive takes them, so the script can make other calls meanwhile; pings are answered by themselves. A socket the script leaves open is closed when it ends. Only the opening counts as a request; each receive, send and close is a line of the log.

The response

Every resource call puts its answer in the variable response, and the call itself has that value, so let customer = customersApi.get(…) keeps it.

FieldMeaning
response.statusthe HTTP status, or its like for other resources
response.bodythe answer, decoded: an object, a list, a string, a number or null
response.headersthe headers, each with its first value; names are read in any case: response.headers.location, response.headers["content-type"]
response.headerValuesevery value of each header, as a list: response.headerValues["set-cookie"]
response.timehow long the call took, in milliseconds
response.sizethe size of the body, in bytes
response.sha256the SHA-256 of the body's bytes, in hex: compare it with a file's, bytes(path).sha256
response.bytesthe body exactly as it came, in base64

The answer of a resource that is not HTTP, or of a mock, has the bytes of its body as text (or JSON).

response is always the last call. Keep a body in a variable before making another call. A script makes one call at a time, so response is never ambiguous; every run of a script has its own, the users of a load test included.

Checking

bbrun
assert response.status == 201
assert response.body.amount > 0 : "amount must be positive"
warn response.body.amount < 10000
validate response.body as PaymentIntent
  • assert fails the script when its expression is false. After : comes the message to show, any expression, worked out only when the assertion fails: assert left == 0 : left + " messages left". The failure names the step, the line, the expression as written, the value found and the last response.
  • warn reports the same, with a message written the same way, and lets the script continue.
  • validate value as Model fails the script when the value is not a valid Model, and lists the fields that are wrong. Models are described in a DRef document: see Models and mappings.
  • abort ends the script as failed, where it stands, with an optional reason: abort "payment not found".

Conditions and loops

bbrun
if response.status == 200 {
    print "ok: " + response.body.id
} else if response.status == 201 {
    print "created"
} else {
    warn false : "unexpected status"
}

for i in 1..10 {                    // 1 to 10, both included
    print "attempt " + i
}

for payment in payments {           // each element of a list
    if payment.status == "canceled" {
        break
    }
}

for x in list also walks the values of an object. break leaves the innermost loop. There is no while and no continue: to wait for something, loop over a range, sleep, and break when it happened.

bbrun
for attempt in 1..20 {
    jobsApi.get("/jobs/${jobId}")
    if response.body.status == "done" {
        break
    }
    sleep(500)
}
assert response.body.status == "done" : "the job did not finish in ten seconds"

Functions

bbrun
function orderFor(customer, lines) {
    let total = 0
    for line in lines {
        total = total + line.price * line.qty
    }
    shopApi.post("/orders", { "customer": customer, "lines": lines, "total": total })
    assert response.status == 201 : "the order for ${customer} answered ${response.status}"
    return response.body
}

let order = orderFor("cus_1", [{ "sku": "a1", "price": 5, "qty": 2 }])
assert order.total == 10
  • function name(a, b) { … } declares a function, and return value ends it with that value; without a return, its value is null. A script's functions can be called from its first line on, and those of a file it includes from the include on: shared steps are a file of functions.
  • Its parameters and the variables it declares are its own: they leave the script's variables of the same name alone, and are gone when it returns. It reads the script's variables. An object it is given is the caller's: setting a key of it changes it for the caller too.
  • Calls inside it set response for the whole script, as calls anywhere do; step, cleanup and assert work in it as outside.
  • It takes as many arguments as it has parameters, or the script fails. It may call itself, up to 200 calls deep. A function of the script wins over a built-in function of the same name.
  • A resource is a value like any other: held in a variable or given to a function, its calls still go to that resource.
bbrun
function isUp(api) {
    api.get("/health")
    return response.status == 200
}

assert isUp(shopApi) and isUp(billingApi)

Scenarios

Four statements give a script the shape of a scenario: goal, step, cleanup and include. They are described in Scenarios.

A script as a function

A script is not only a test. A service can run one as the logic of an operation: it hands the script what it received, and sends back what the script returns. Such a script reads two values and ends with return:

operations/get-order.bbrun
ordersApi.get("/records/${request.path.id}")
if response.status == 404 {
    status(404)
    return { "code": "ORDER_NOT_FOUND" }
}
Order order = response.body
if order.customerId != context.customerId {
    status(404)
    return { "code": "ORDER_NOT_FOUND" }
}
return order
NameHolds
requestwhat the caller sent, as the service passes it: for example request.body and request.path.id
contextwhat the service knows and the caller cannot write: who is signed in, a correlation id
return valueends the script; the value is the result, as it is
status(code)the status the service should answer with, when the logic decides it
header(name, value)a header for that answer

A script that ends without return has no result. One that fails, by a false assert, a failed validate or an abort, has a failure in place of a result. How a service runs scripts is in the repository on GitHub.

A run is one unit of work. What it writes to each database is committed when the script ends well and rolled back when it fails, so an operation that writes to two databases and then aborts leaves both as they were:

operations/place-order.bbrun
ordersDb.execute("insert into orders (id, customer, total) values (?, ?, ?)",
    [request.body.id, context.customerId, request.body.total])
stockDb.execute("update stock set reserved = reserved + ? where sku = ?", [request.body.qty, request.body.sku])

paymentsApi.post("/charges", { "orderId": request.body.id, "amount": request.body.total })
if response.status != 201 {
    abort "payment declined"        // neither database keeps the order
}
status(201)
return { "id": request.body.id }

The commits are not one atomic step, and an HTTP call is never undone: see Transactions.

In the script of a mock route, return is the answer of the mock: see Mocks.

Built-in functions

FunctionGives
uuid()a random UUID
now()the time, in milliseconds since 1970
random(), random(max)a random decimal from 0 to 1; a random whole number below max
randomString(length)random letters and digits (8 without a length)
env(name), env(name, default)an environment variable of the process
sleep(ms)waits
authenticate(resource, auth)sets the credentials of a resource for the calls that follow
headers({…})headers for one call, given as an argument of the call
form({…})a URL-encoded form body
file(path), file(path, contentType)a text file as a body
bytes(path), bytes(path, contentType)any file as a body, byte for byte: see Files as bytes
base64Bytes(text), base64Bytes(text, contentType)the bytes a base64 text holds, as a body: response.bytes sent on again
timeout(ms)how long one call waits for its answer, given as an argument of the call: timeout(40000), timeout("40s")
readText(path), readJson(path), readCsv(path)the text of a file, its JSON, or its CSV rows as lists of strings
parseJson(text), toJson(value)JSON text to a value, and back
keys(object)the keys of an object
pluck(list, field)that field of each object of a list
find(list, field, value)the first object of a list whose field has that value, or null
urlParam(url, name)a query parameter of a URL, decoded
urlEncode(text)the text, encoded for a URL
base64Encode(text), base64Decode(text)Base64, there and back
jwtClaims(token)the claims of a JWT, read without checking its signature
sha256Hex(text), sha256Hex(bytes)the SHA-256 of the text, or of bytes, in hex
es256KeyPair()a new P-256 key pair: privateKey and publicKey in PEM, and the public point as x, y and point (base64url)
es256Sign(privateKey, text)the text signed with ECDSA P-256 and SHA-256, as JWS's ES256 does (base64url): a request a device or a webhook signs
status(code), header(name, value)the status and a header of the answer, in a script run as a function
respond(status, body), respond(status, body, headers)the answer of a mock, in the script of a mock route only

A path given to file, bytes, readText, readJson, readCsv or include starts at the folder of the script that names it. Calling a function that does not exist is an error.

Reserved words

let map using validate as assert warn print if else for in break return abort true false null matches contains not and or get post put patch delete to goal step cleanup include function. None of them names a variable, a loop variable, a parameter or a function: for get in list fails with 'get' is a reserved word.

A reserved word is still a good name after a dot: jobsQueue.delete(…), email.to and { to: "ops@example.com" } are all valid. The names of operations, such as query, send or receive, are not reserved. status and header are names too (for status in [200, 201]), except for a function.

Grammar

The grammar is an ANTLR 4 file in the source, bbrun-core/src/main/antlr/BBRun.g4. In short:

script          : statement* EOF ;

statement       : functionDecl | typedDeclaration | variableDecl | assignStatement
                | verbRequestStatement | mapStatement
                | validateStatement | assertStatement | warnStatement
                | printStatement | ifStatement | forStatement | returnStatement
                | breakStatement | abortStatement
                | goalStatement | stepStatement | cleanupStatement | includeStatement
                | expressionStatement | ';' ;

goalStatement   : 'goal' expression ;
stepStatement   : 'step' expression block ;
cleanupStatement: 'cleanup' block ;
includeStatement: 'include' STRING ;

variable        : IDENTIFIER | 'status' | 'header' ;
typedDeclaration: IDENTIFIER variable '=' expression
                | IDENTIFIER '[' ']' variable '=' expression ;
variableDecl    : 'let' variable '=' expression ;
assignStatement : variable ('.' name | '[' expression ']')* '=' expression ;
functionDecl    : 'function' IDENTIFIER '(' (variable (',' variable)*)? ')' block ;
assertStatement : 'assert' expression (':' expression)? ;
warnStatement   : 'warn' expression (':' expression)? ;
mapStatement    : 'map' expression 'using' STRING ('as' IDENTIFIER)? ;
validateStatement: 'validate' expression 'as' IDENTIFIER (':' STRING)? ;
ifStatement     : 'if' expression block ('else' 'if' expression block)* ('else' block)? ;
forStatement    : 'for' variable 'in' expression '..' expression block
                | 'for' variable 'in' expression block ;
breakStatement  : 'break' ;
returnStatement : 'return' expression ;
abortStatement  : 'abort' expression? ;
block           : '{' statement* '}' ;

expression      : primary
                | expression '.' name '(' argumentList? ')'
                | expression '.' name
                | expression '[' expression ']'
                | IDENTIFIER '(' argumentList? ')'
                | expression ('*'|'/') expression
                | expression ('+'|'-') expression
                | expression ('=='|'!='|'<'|'>'|'<='|'>=') expression
                | expression 'matches' IDENTIFIER
                | expression 'not'? 'contains' expression
                | 'not' expression
                | expression 'and' expression
                | expression 'or' expression ;