Environments and resources

A script calls resources by name. bbrun.yaml says what each name is, once for each environment. Addresses, credentials and mocks live here and nowhere else.

The configuration file

bbrun.yaml
defaultEnvironment: local

environments:
  local:
    resources:
      paymentsApi:
        type: mock

  dev:
    resources:
      paymentsApi:
        baseUrl: "https://payments.dev.example.com/v1"
        auth:
          type: bearer
          token: "${DEV_PAYMENTS_TOKEN}"

domain: models/domain.json     # the DRef models; default: domain.json next to this file
logging:
  dir: logs                    # one log file for each script run
  • Every environment declares the same names. What differs is what stands behind them. That is what lets a script run anywhere.
  • ${NAME} is replaced by the environment variable NAME of your shell when the file is read, and ${NAME:-value} by value when the variable is not set. Keep secrets in variables, not in the file.
  • Paths in the file start at the folder of the file.
  • Without -c, the command reads bbrun.yaml (or .yml, .json) in the current folder, else next to the first script, else in a folder above it.

--env chooses the environment; without it, defaultEnvironment is used. bbrun envs shows what the file declares:

terminal
$ bbrun envs
BBRun Configured Environments (2):

  • dev
      - paymentsApi (http) -> https://payments.dev.example.com/v1
        auth: bearer

  • local [DEFAULT]
      - paymentsApi (mock)

Kinds of resources

KindDeclared withOperations
HTTP APIbaseUrl: "https://…"get post put patch delete, and websocket
Mocktype: mockthose of what it stands for, answered from routes
Databasetype: sql, with engine: (a server) or data: (embedded)query execute
Queuetype: queuesend receive peek
Emailtype: email, from:send outbox
Filestype: file, dir:get put list delete
Service of the hostthe program that runs the scripts, when it is not the commandwhatever it answers

The kind of a resource with a baseUrl is read from the URL, so type: http may be left out. All kinds except the mock and the services of a host are opened by iconn.

HTTP resources

yaml
shopApi:
  baseUrl: "https://shop.example.com/v1"
  headers:
    X-Tenant: acme               # sent with every call
  auth:
    type: apikey
    headerName: X-API-Key
    headerValue: "${SHOP_KEY}"
  timeout: 30s                   # optional: how long a call waits for its answer
  mapping: "Catalog product"     # optional: see Models and mappings

The base URL is the root of the API. A script gives the rest of the path, and the full address is the one followed by the other: with the resource above, shopApi.get("/products/${id}") sends GET https://shop.example.com/v1/products/…. A script may also give a whole address, one an answer handed back; the resource's headers and auth go with it only on the base URL's own scheme, host and port (see Calling a resource).

timeout is how long a call waits for its answer: 30s, 500ms, 2m, or a number of milliseconds. Without it, 15 seconds. A resource that answers slowly on purpose, such as a long poll, says so here, and one call can wait longer still with timeout(ms).

A path is a resource of the API and the operation is what you do to it, so one path serves a whole life:

ScriptRequest
productsApi.post("/products", product)POST /v1/products
productsApi.get("/products")GET /v1/products
productsApi.get("/products/${id}")GET /v1/products/{id}
productsApi.put("/products/${id}", { "price": 24.99 })PUT /v1/products/{id}
productsApi.delete("/products/${id}")DELETE /v1/products/{id}

Credentials

auth.typeFieldsSends
nonenothing; the default
bearertokenAuthorization: Bearer …
basicusername, passwordAuthorization: Basic …
apikeyheaderName, headerValuethat header
oauth2tokenUrl, clientId, clientSecret, scope (optional)a bearer token it gets itself

oauth2 is the client credentials grant. On the first call, bbrun exchanges the client's id and secret for a token at tokenUrl, keeps it, and gets a new one shortly before it expires. The script sees none of it.

yaml
paymentsApi:
  baseUrl: "https://org-staging.apigee.net/v1"
  auth:
    type: oauth2
    tokenUrl: "https://org-staging.apigee.net/oauth/token"
    clientId: "${APIGEE_CLIENT_ID}"
    clientSecret: "${APIGEE_CLIENT_SECRET}"
    scope: "payments.read payments.write"

A script that signs in as a user sets the credentials itself, with authenticate.

Mocks

A mock stands for a resource that is not there: a service that is not built yet, one that costs money to call, or one whose failures you want to decide. In the script it is called like the real one.

bbrun.yaml
customersApi:
  type: mock

Its routes are in mocks/<name>.yaml, next to the configuration file. A route is an operation and a path, and one source for the answer:

mocks/customersApi.yaml
routes:
  - method: get
    path: /customers
    file: fixtures/customers.json        # a JSON file

  - method: post
    path: /customers
    status: 201
    expr: >-                             # an expression over the request
      {
        "id": "cus_" + randomString(6),
        "email": body.email
      }

  - method: get
    path: /customers/{id}/limits
    data: { "daily": 500, "currency": "EUR" }     # the answer itself

  - methods: [get, delete]
    path: /customers/{id}
    script: customer-detail.bbrun        # a script decides
SourceThe answer is
datathe value written in the route
filea JSON file; its path starts at the folder of the routes file
expra bbrun expression that can read body, params, query, headers (names in any case: headers["x-request-id"]), verb and path
scriptwhat a bbrun script returns, with the same names to read
  • {id} in a path takes one segment and gives it as params.id. The query string is in query: /probe?a=1 gives query.a == "1".
  • status is 200 unless the route says otherwise.
  • when is a condition, written as an expression: the route answers only when it is true. Two routes on the same path can so answer different requests.

A script as a route

The script of a route is the other side of the wire. return answers with status 200; respond(status, body) answers with another status, and takes headers as a third argument.

mocks/customer-detail.bbrun
let known = {
    "cus_1": { "id": "cus_1", "email": "sarah@example.com" },
    "cus_2": { "id": "cus_2", "email": "ana@example.com" }
}

let customer = known[params.id]
if customer == null {
    respond(404, { "error": "customer not found", "id": params.id })
} else {
    return customer
}

A mock plays someone else's service, so its scripts do not know your models: typed declarations and validate fail there.

A request no route answers

An HTTP mock without a route for a request behaves as a small store: post keeps the body under its path and answers 201, and get on that path answers the list of what is kept there. A path with the id of one object after it reads that object with get, replaces it with put, changes the fields given with patch and removes it with delete; the list follows. A mock with no routes file at all is this store, which is enough for a first create-and-read scenario.

Routes somewhere else

  • mocks: custom.yaml on the resource reads the routes from that file.
  • routes: on the resource, in bbrun.yaml, holds them in place. It cannot be used together with mocks:.

A mock of something that is not HTTP

mock: says what the mock stands for: sql, queue, email or file. Its routes are found by op, the operation the script calls, in place of a method and a path.

bbrun.yaml
orderQueue:
  type: mock
  mock: queue
mocks/orderQueue.yaml
routes:
  - op: send
    expr: '{ "queued": body.job, "status": "scheduled" }'

  - op: receive
    data: { "job": "invoice_1550", "amount": 1550 }

Such a mock answers only what its routes say: an operation without a route fails. Its sources read op, args (the arguments of the call), headers and body (the last argument).

Databases

A database is a name, like any resource. The environment says which database it is: a server with its engine, or, in a local environment, an embedded database that needs nothing installed. The script is the same for both.

bbrun.yaml
environments:
  local:                          # nothing to install: an embedded database
    resources:
      ordersDb:
        type: sql
        data:
          orders:
            - { id: "ord_1", status: "pending", total: 1550 }

  staging:                        # the real one
    resources:
      ordersDb:
        type: sql
        engine: postgresql
        host: db.staging.internal
        port: 5432
        database: orders
        username: orders_app
        password: "${ORDERS_DB_PASSWORD}"
        ssl: true

A database server

A type: sql resource with an engine is a real database. Its fields are those of a database in iconn and in kfig:

FieldMeaning
enginewhich database it is: see below
host, portwhere it listens; without port, the engine's own
databasethe database on that server
username, passwordthe account; read the password from a variable of the shell or the pipeline, never write it in the file
ssltrue: the connection is encrypted and the server's certificate checked; false: not encrypted; without it, the driver decides
poolSizeat most this many connections open at once (10); a call that finds them all busy waits for one, ten seconds at most
enginePortdatabase isDriver
postgresql5432the database namecomes with bbrun
sqlserver1433the database namecomes with bbrun
h29092the database as an H2 server names itcomes with bbrun
mysql, mariadb3306the database nameadd it: com.mysql:mysql-connector-j or org.mariadb.jdbc:mariadb-java-client
oracle1521the service name, such as FREEPDB1add it: com.oracle.database.jdbc:ojdbc11

bbrun carries the drivers whose licences let anyone pass them on. The others are added by the project, under their own licence. A real database is never seeded: data and engine together are refused, and bbrun envs shows which database each environment names.

The embedded database

A type: sql resource without an engine is a database inside the run: H2, in memory, made from data (the rows each table starts with, each table made from its first row's fields). It is gone when the run ends. It speaks H2's SQL, which is close to the standard; a statement that only one engine knows runs on that engine only.

Reading and writing

bbrun
let pending = ordersDb.query("select * from orders where status = ?", ["pending"])
assert pending.length == 1
assert pending[0].id == "ord_1"

let placed = ordersDb.execute("insert into orders (id, status, total) values (?, ?, ?)",
    [orderId, "pending", 700])
assert placed.affectedRows == 1
  • query answers the rows, a list of objects by column name. A column is also there in lower case, as databases differ in case. Dates and times come as ISO text.
  • execute answers { "affectedRows": n }.
  • A statement that changes rows is refused by query unless it answers rows too (insert … returning), and a select is refused by execute, before either runs.
  • Values go in through ? marks and a list after the SQL. Never build SQL with + or ${…} from a value a caller sent: a ? is never read as SQL.

Transactions

When the bbrun command runs a scenario, each statement is committed as it runs: the services a scenario tests must see what it wrote.

When a service runs a script as a function, the run is one unit of work. It has one transaction for each database it uses: what it wrote is committed when the script ends well, and rolled back when it fails (a false assert, a failed validate, an abort, an error). The script reads what it wrote; nobody else does before the commit.

The databases are committed one after another, in the order the script first used them. That is not one atomic step: if a commit fails, the databases after it are rolled back, those before it stay committed, and the failure names both. Calls to HTTP APIs, queues and mail are never rolled back.

Libraries

A service bbrun does not reach by itself is reached through a library the project adds: the driver of a database whose licence does not let bbrun carry it, or a connector for a kind of service, such as a queue on a broker. libraries in bbrun.yaml lists them, for every environment:

bbrun.yaml
libraries:
  - com.mysql:mysql-connector-j:9.4.0     # from Maven Central, with what it needs
  - drivers/ojdbc11.jar                    # a jar of the project
  - connectors/                            # every jar of a folder

environments:
  staging:
    resources:
      shopDb:
        type: sql
        engine: mysql
        host: db.staging.internal
        database: shop
        username: shop_app
        password: "${SHOP_DB_PASSWORD}"
  • Coordinates are fetched from Maven Central once, with the libraries they need to run, each checked against the checksum Central publishes, and kept in ~/.bbrun/libraries. BBRUN_MAVEN_REPOSITORY names a mirror instead.
  • A path starts at the folder of bbrun.yaml.
  • A project that adds libraries runs on Java, 21 or later: the bbrun command runs the same command on the Java of JAVA_HOME or of the PATH, with bbrun's own files installed beside it, and says so if there is none. Without libraries, nothing but the command is needed.
  • bbrun libraries lists what each entry adds, and fetches what is missing: run it once in a pipeline before the scripts.
  • A database whose driver is missing says which library to add.

The other fields of a queue or a mail server with an engine go to its connector as they are written, as a database's go to its driver: the connector says which it reads.

Local resources

A queue, a mailbox and a folder that live inside the run, like the embedded database. They need nothing installed, which makes them good stand-ins in a local environment, and they keep what happened so that a scenario can check it.

Queue

yaml
jobsQueue:
  type: queue
bbrun
jobsQueue.send({ "job": "invoice_1550", "amount": 1550 })
jobsQueue.send({ "job": "invoice_3250", "amount": 3250 })
assert jobsQueue.receive().job == "invoice_1550"     // first in, first out
assert jobsQueue.peek().amount == 3250               // looks without taking

One queue for each resource name, for the length of a run. receive on an empty queue answers status 204.

Email

yaml
mailSender:
  type: email
  from: notifications@example.com
bbrun
let sent = mailSender.send({ to: "ops@example.com", subject: "Daily report ready", body: "See attachments" })
assert sent.accepted == true
assert mailSender.outbox()[0].subject == "Daily report ready"

Nothing leaves the process: send keeps the message, and outbox() gives what was sent.

Files

yaml
fileStore:
  type: file
  dir: fs
bbrun
fileStore.put("reports/daily.json", { "day": "2026-09-10", "orders": 4 })
let report = fileStore.get("reports/daily.json")
assert report.exists == true
assert report.content contains "2026-09-10"
assert fileStore.list("reports").length == 1
fileStore.delete("reports/daily.json")

dir is the folder the paths start at. put writes JSON for an object or a list and the text itself for a string; list answers the path, type and size of each entry.