Documentation
¶
Overview ¶
Package jotaro is a library for load-testing HTTP servers with scenarios: a flow such as login → list → order, written as plain Go code.
This package is the entry point. It handles scenarios (Scenario / User / Step) and how load is applied (Plan / Run). Load is applied either with a fixed number of users (Plan.Users), with a number of users that changes over time (Plan.UserStages), or by arrival rate (Plan.Arrival with Rate / Ramp / Stages). Plan.Scenarios runs a weighted mix of scenarios instead of a single one. The result is returned as a report.Report. Writing it to the console, JSON or HTML, and checking it against thresholds, is done by the report package; raw per-request records are handled by the record package.
sc := jotaro.NewScenario("checkout", func(ctx context.Context, u *jotaro.User) error {
return u.Step("login", func(s *jotaro.Step) error {
return s.Post("/login").JSON(creds).Do().ExpectStatus(200)
})
})
rep, err := jotaro.Run(ctx, jotaro.Plan{Scenario: sc, BaseURL: url, Users: 20, Duration: time.Minute})
rep.Write(os.Stdout, report.FormatText)
Example ¶
A scenario is plain Go code. Run it with a Plan, here against a local test server.
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"time"
"github.com/RIRUa/jotaro"
)
func main() {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/login":
fmt.Fprint(w, `{"token":"secret"}`)
default:
w.WriteHeader(http.StatusCreated)
}
}))
defer srv.Close()
checkout := jotaro.NewScenario("checkout", func(ctx context.Context, u *jotaro.User) error {
var login struct {
Token string `json:"token"`
}
if err := u.Step("login", func(s *jotaro.Step) error {
return s.Post("/login").JSON(map[string]string{"user": "alice"}).Do().Decode(&login)
}); err != nil {
return err // return err to stop; ignore it to continue
}
u.Think(10 * time.Millisecond) // waiting time; not counted in latency
return u.Step("order", func(s *jotaro.Step) error {
return s.Post("/orders").Bearer(login.Token).
JSON(map[string]int{"item": 1}).
Do().ExpectStatus(http.StatusCreated)
})
})
rep, err := jotaro.Run(context.Background(), jotaro.Plan{
Scenario: checkout,
BaseURL: srv.URL,
Duration: 200 * time.Millisecond,
Users: 2,
})
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println("ran:", rep.Requests.Count > 0)
fmt.Println("errors:", len(rep.Requests.Errors))
}
Output: ran: true errors: 0
Index ¶
- Variables
- func LoadCSV(r io.Reader) ([]map[string]string, error)
- func Run(ctx context.Context, p Plan) (*report.Report, error)
- type AbortRule
- type Arrival
- type ExpectError
- type FeedMode
- type Feeder
- type Plan
- type Request
- func (r *Request) Basic(user, pass string) *Request
- func (r *Request) Bearer(token string) *Request
- func (r *Request) Body(v any) *Request
- func (r *Request) Do() *Response
- func (r *Request) Form(v url.Values) *Request
- func (r *Request) Header(key, value string) *Request
- func (r *Request) Headers(h map[string]string) *Request
- func (r *Request) JSON(v any) *Request
- func (r *Request) Queries(v url.Values) *Request
- func (r *Request) Query(key, value string) *Request
- type RequestSpec
- type Response
- func (r *Response) Decode(v any) error
- func (r *Response) Err() error
- func (r *Response) ExpectBodyContains(substr string) error
- func (r *Response) ExpectHeader(key, want string) error
- func (r *Response) ExpectJSON(path string, want any) error
- func (r *Response) ExpectStatus(code int) error
- func (r *Response) ExpectStatusIn(codes ...int) error
- func (r *Response) JSON(path string) (any, error)
- type Scenario
- type Stage
- type Step
- type User
- type UserStage
- type Weighted
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrAborted = errors.New("jotaro: run aborted")
ErrAborted is wrapped by the error Run returns when Plan.AbortOn stopped the run early. The report returned together with it covers the run up to the abort. Test for it with errors.Is.
Functions ¶
func LoadCSV ¶
LoadCSV reads a CSV whose first line is the header into rows keyed by column name.
Example ¶
LoadCSV reads rows keyed by the column names of the header line.
package main
import (
"fmt"
"strings"
"github.com/RIRUa/jotaro"
)
func main() {
rows, err := jotaro.LoadCSV(strings.NewReader("user,password\nalice,a1\nbob,b2\n"))
if err != nil {
fmt.Println(err)
return
}
feeder := jotaro.NewFeeder(rows, jotaro.Once)
row, _ := feeder.Next()
fmt.Println(feeder.Len(), row["user"], row["password"])
}
Output: 2 alice a1
func Run ¶
Run applies load according to the Plan, then aggregates and returns the result.
Flow of a run:
- validate the Plan, and clone the default Transport so connections are not shared with other code
- start the health sampler, then run the closed (Users or UserStages) or open (Arrival) loop until Duration ends
- wait up to Grace for running iterations, then cancel them
- build the report. Records are folded into histograms as they arrive (percentiles within 1% relative error, memory independent of the run length). With Plan.Raw each record is also written to it at once, and the stream is finished (health and final run info) when the run ends
When ctx is done, everything stops at once, including running iterations, and the results so far are returned. Report.Elapsed is the real time until all users have stopped.
Types ¶
type AbortRule ¶ added in v0.1.3
type AbortRule struct {
// When is the condition, such as "error_rate>50%".
When string
// For is how long When must hold without a break before the run is aborted. 0 aborts at the first
// evaluation where it holds. A value of a few seconds keeps one early failure from stopping a run
// whose statistics have not settled yet.
For time.Duration
}
AbortRule is one condition of Plan.AbortOn: stop the run as soon as When holds.
When uses the threshold syntax of report.ParseThreshold, but it describes the state to stop at rather than the state to accept. So "http_5xx_rate>50%" aborts once more than half of the requests got a 5xx response:
AbortOn: []jotaro.AbortRule{
{When: "http_5xx_rate>50%", For: 5 * time.Second},
{When: "error_rate>50%", For: 5 * time.Second},
{When: "p95>2s", For: 10 * time.Second},
},
Mind which metric sees the failure: error_rate is the share of requests that ended in a transport-level error (timeout, connection refused, DNS failure and so on). A failed Expect* check is not a request error: it fails the step with expect_mismatch and reaches iteration_fail_rate when the scenario returns that error. An HTTP error status is counted by http_4xx_rate / http_5xx_rate.
The condition is evaluated every second against the whole run so far (not a sliding window), the same way Report.Check reads a finished report. Percentiles are therefore the approximate ones of a run without Plan.Raw. Nothing counts as holding while there is no data yet (for example before the first request has finished, or before a step named in a {step=...} filter has run).
type Arrival ¶
type Arrival interface {
// contains filtered or unexported methods
}
Arrival is how scenarios arrive in the open model. Arrival times are decided independently of how long a scenario takes.
func Ramp ¶
Ramp changes the arrival rate linearly from from to to over over. The rate is a count per per; after over has passed it stays at to (if to is 0, arrivals stop there). For example, Ramp(0, 50, time.Second, 30*time.Second) raises the rate from 0 to 50 per second over 30 seconds.
The length of the whole run is set by Plan.Duration. If over is longer than Duration, to is never reached.
func Rate ¶
Rate starts scenarios at a rate of n per per. For example, Rate(10, time.Second) is 10 per second.
func Stages ¶
Stages runs several stages in order. The Arrival of each stage runs with the start of that stage as 0 (a Ramp's slope also starts there). For example, ramp up to 50/s over 30 seconds, hold for 60 seconds, then ramp down to 0 over 10 seconds:
Stages(
Stage{Ramp(0, 50, time.Second, 30*time.Second), 30 * time.Second},
Stage{Rate(50, time.Second), 60 * time.Second},
Stage{Ramp(50, 0, time.Second, 10*time.Second), 10 * time.Second},
)
Arrivals stop when all stages are over. The length of the whole run is set by Plan.Duration, so make it match the sum of the For of every stage.
type ExpectError ¶
type ExpectError struct {
// Want is the status code that was expected. It is 0 for non-status checks.
Want int
// Got is the status code that came back.
Got int
// Detail describes a non-status mismatch (header, body or JSON value).
// It is empty for ExpectStatus.
Detail string
}
ExpectError reports that a response did not match what an Expect* check expected. It is classified as record.ErrExpect (expect_mismatch).
func (*ExpectError) Error ¶
func (e *ExpectError) Error() string
Error implements the error interface.
type FeedMode ¶
type FeedMode int
FeedMode is the order in which a Feeder hands out rows.
const ( // Circular hands out rows from the first one and wraps around after the last. Circular FeedMode = iota // Random picks a row at random each time. The same row can be picked twice in a row. Random // Once hands out rows from the first one and returns false once they are used up. // It is meant for data such as accounts that can be used only once. Once )
type Feeder ¶
type Feeder[T any] struct { // contains filtered or unexported fields }
Feeder hands out different data (accounts, input values, ...) to each user. Next may be called from all users at the same time.
Example ¶
A Feeder hands out different data to each user.
package main
import (
"fmt"
"github.com/RIRUa/jotaro"
)
func main() {
accounts := jotaro.NewFeeder([]map[string]string{
{"user": "alice"}, {"user": "bob"},
}, jotaro.Circular)
for range 3 {
row, _ := accounts.Next()
fmt.Println(row["user"])
}
}
Output: alice bob alice
Example (Once) ¶
With Once, rows are handed out once and then Next returns false.
package main
import (
"fmt"
"github.com/RIRUa/jotaro"
)
func main() {
tokens := jotaro.NewFeeder([]string{"t1", "t2"}, jotaro.Once)
for {
tok, ok := tokens.Next()
if !ok {
break
}
fmt.Println(tok)
}
}
Output: t1 t2
type Plan ¶
type Plan struct {
// Scenario is the flow every virtual user runs. Exactly one of Scenario and Scenarios must be set.
Scenario *Scenario
// Scenarios is a weighted mix of flows, for example 70% browse and 30% checkout. It cannot be set together
// with Scenario. Every iteration (closed model) or arrival (open model) picks one scenario at random with
// probability Weight divided by the sum of the weights. The report and thresholds already separate the
// results by scenario name, so the scenarios of a mix need distinct names.
Scenarios []Weighted
// BaseURL is prepended to the relative paths of requests (for example "http://localhost:8080").
BaseURL string
// Users is the number of virtual users running at the same time.
Users int
// UserStages changes the number of users over time in the closed model. It cannot be set together with Users or Arrival.
//
// Every user keeps its ID (User.ID counts from 0) and its iteration count for the whole run, so a user
// that is stopped by a smaller target and started again by a larger one carries on where it left off.
// When the target goes down, the users with the highest IDs stop: each one finishes the iteration it is
// running (it is not interrupted) and then waits. So the active-user count of the report (Series.Concurrency)
// can be above the target for a while. After the last stage the number of users stays at its Target until Duration.
UserStages []UserStage
// StartUsers is how many users are already running when the first stage of UserStages begins, so that
// the load does not have to ramp up from 0. 0 means none. It can only be set together with UserStages.
StartUsers int
// Arrival is how scenarios arrive (e.g. Rate(10, time.Second)). It cannot be set together with Users or UserStages.
Arrival Arrival
// MaxUsers is the cap on concurrency with Arrival. 0 means 1000.
// Arrivals that come in while the cap is reached are not run and are counted as dropped.
MaxUsers int
// After Duration has passed, no new iterations are started.
Duration time.Duration
// Timeout is the limit for a single request. 0 means 30 seconds.
Timeout time.Duration
// Grace is how long to wait for running iterations to finish after Duration.
// Those that exceed it are aborted and recorded as record.ErrCanceled. 0 means 30 seconds.
Grace time.Duration
// If Raw is not nil, the raw data is written to it as JSON Lines while the run is in progress, one line per
// record as it arrives (record.RawWriter), so memory stays constant however many requests there are.
// Even if writing fails, the aggregated Report is returned (together with an error).
//
// The Report that Run returns is aggregated incrementally, as without Raw, so its percentiles are within
// 1% relative error. For exact percentiles, read the raw data back (record.ReadRaw, report.FromRaw,
// or `jotaro report -raw`).
Raw io.Writer
// If Progress is not nil, one line is written to it every second while the run is in progress,
// for example "12s/60s rps=480 p95=38ms err=0.2%" (elapsed/Duration, throughput of the last second,
// and p95 and error rate over the run so far). Pass os.Stderr to watch a long run.
// The p95 is an approximation within 1% relative error. Nothing is written after Run returns,
// and write errors are ignored. It works together with Raw.
Progress io.Writer
// If MetricsAddr is not empty, Run serves the state of the run so far at http://<MetricsAddr>/metrics in the
// Prometheus text format (for example ":9090"), so Grafana and similar tools can chart it while the run is in
// progress. It has the request, response class and error counts, the throughput and the latency quantiles of the
// whole run so far (within 1% relative error). The server stops when Run returns. If the address cannot be
// listened on, Run fails before sending any request.
MetricsAddr string
// AbortOn stops the run early when any of its conditions holds, for example
// {When: "error_rate>50%", For: 5 * time.Second}. A broken server is then not hit for the whole Duration.
// See AbortRule for the syntax and how the conditions are evaluated.
//
// On abort no new iterations are started and the running ones get Grace, counted from the moment of the abort,
// to finish (the rest is cancelled and recorded as record.ErrCanceled), exactly as at the end of Duration.
// Run then returns the report of the run up to that point (and writes Plan.Raw) together with an error
// that wraps ErrAborted. If Progress is set, a line saying why is written to it.
AbortOn []AbortRule
}
Plan describes how load is applied.
Specify exactly one of Users, UserStages (closed model) and Arrival (open model).
- Users: a fixed number of users repeat the scenario until Duration has passed.
- UserStages: like Users, but the number of users changes over time (ramp up, hold, ramp down).
- Arrival: scenarios start at a fixed rate, regardless of how long a scenario takes.
Example (AbortOn) ¶
AbortOn stops a run early when a condition holds, so a broken server is not hit for the whole Duration. Run then returns the report up to that point together with an error that wraps ErrAborted.
package main
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"time"
"github.com/RIRUa/jotaro"
)
func main() {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusServiceUnavailable) // a broken server
}))
defer srv.Close()
ping := jotaro.NewScenario("ping", func(ctx context.Context, u *jotaro.User) error {
return u.Step("ping", func(s *jotaro.Step) error {
return s.Get("/").Do().ExpectStatus(http.StatusOK)
})
})
rep, err := jotaro.Run(context.Background(), jotaro.Plan{
Scenario: ping,
BaseURL: srv.URL,
Duration: time.Minute,
Users: 2,
AbortOn: []jotaro.AbortRule{{When: "http_5xx_rate>50%"}}, // For: 0 aborts at the first evaluation that holds
})
fmt.Println("aborted:", errors.Is(err, jotaro.ErrAborted))
fmt.Println("report returned:", rep != nil && rep.Requests.Count > 0)
}
Output: aborted: true report returned: true
Example (Open) ¶
In the open model, scenarios start at a fixed rate whatever the server does. Stages switches the arrival stage by stage: ramp up, hold, ramp down.
package main
import (
"time"
"github.com/RIRUa/jotaro"
)
func main() {
var scenario *jotaro.Scenario // see the Example above
plan := jotaro.Plan{
Scenario: scenario,
BaseURL: "http://localhost:8080",
Duration: 100 * time.Second,
Arrival: jotaro.Stages(
jotaro.Stage{Arrival: jotaro.Ramp(0, 50, time.Second, 30*time.Second), For: 30 * time.Second},
jotaro.Stage{Arrival: jotaro.Rate(50, time.Second), For: 60 * time.Second},
jotaro.Stage{Arrival: jotaro.Ramp(50, 0, time.Second, 10*time.Second), For: 10 * time.Second},
),
MaxUsers: 500, // arrivals beyond this are counted as dropped
}
_ = plan // jotaro.Run(ctx, plan)
}
Output:
Example (Scenarios) ¶
Scenarios runs a weighted mix of flows in one plan. Every iteration picks one scenario in proportion to its weight, and the report keeps the results apart by scenario name, so the names must differ.
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"sort"
"time"
"github.com/RIRUa/jotaro"
)
func main() {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
defer srv.Close()
visit := func(name, path string) *jotaro.Scenario {
return jotaro.NewScenario(name, func(ctx context.Context, u *jotaro.User) error {
return u.Step("visit", func(s *jotaro.Step) error {
return s.Get(path).Do().ExpectStatus(http.StatusOK)
})
})
}
rep, err := jotaro.Run(context.Background(), jotaro.Plan{
Scenarios: []jotaro.Weighted{
{Scenario: visit("browse", "/products"), Weight: 1}, // 1 : 1 is 50% each; 70 : 30 would be 70% and 30%
{Scenario: visit("buy", "/orders"), Weight: 1},
},
BaseURL: srv.URL,
Duration: 200 * time.Millisecond,
Users: 2,
})
if err != nil {
fmt.Println("error:", err)
return
}
var names []string
for _, sc := range rep.Scenarios {
if sc.Iterations.Count > 0 {
names = append(names, sc.Name)
}
}
sort.Strings(names)
fmt.Println("scenarios that ran:", names)
}
Output: scenarios that ran: [browse buy]
Example (UserStages) ¶
UserStages changes the number of users over time in the closed model, here from 2 users up to 4 and down to 0. StartUsers is how many users are already running when the first stage begins.
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"time"
"github.com/RIRUa/jotaro"
)
func main() {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
defer srv.Close()
ping := jotaro.NewScenario("ping", func(ctx context.Context, u *jotaro.User) error {
return u.Step("ping", func(s *jotaro.Step) error {
return s.Get("/").Do().ExpectStatus(http.StatusOK)
})
})
rep, err := jotaro.Run(context.Background(), jotaro.Plan{
Scenario: ping,
BaseURL: srv.URL,
StartUsers: 2,
UserStages: []jotaro.UserStage{
{Target: 4, For: 100 * time.Millisecond},
{Target: 4, For: 100 * time.Millisecond},
{Target: 0, For: 100 * time.Millisecond},
},
Duration: 300 * time.Millisecond,
})
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println("ran:", rep.Requests.Count > 0)
fmt.Println("open model:", rep.Open)
}
Output: ran: true open model: false
type Request ¶
type Request struct {
// Spec is the data form of the request. It can be edited directly before Do.
Spec RequestSpec
// contains filtered or unexported fields
}
Request is a request builder. Send it with Do.
Builder methods return the Request so calls can be chained. A failure while building (for example JSON that cannot be encoded) is stored and returned later by the Response, which keeps the chain free of error checks.
func (*Request) Body ¶
Body sets the body according to its type.
[]byte / string sent as is. Content-Type is not set; add it with Header if you need it io.Reader read to the end and sent as is. Content-Type is not set url.Values same as Form anything else same as JSON (structs, maps, slices, ...)
nil sets nothing. Use JSON when you want to make it explicit that the body is JSON (also when you want to send a string as a JSON string).
func (*Request) Do ¶
Do sends the request. A network error is kept in the response and returned by Decode or ExpectStatus.
type RequestSpec ¶
type RequestSpec struct {
Method string
Path string
Query url.Values // added to the query of Path
Header http.Header
Body []byte
}
RequestSpec describes a request. It is kept as data separate from execution so that it can later be built from YAML and the like.
type Response ¶
type Response struct {
// Code is the HTTP status code. It is 0 when no response was received.
Code int
// Header holds the response headers. It is nil when no response was received.
Header http.Header
// Body is the whole body, already read.
Body []byte
// contains filtered or unexported fields
}
Response is the result of a single request. HTTP 4xx/5xx are not network errors, so Err stays nil and the status goes into Code.
func (*Response) Err ¶
Err returns the network error, if any. It does not look at the HTTP status code.
func (*Response) ExpectBodyContains ¶ added in v0.1.3
ExpectBodyContains checks that the body contains substr.
func (*Response) ExpectHeader ¶ added in v0.1.3
ExpectHeader checks that the response header key equals want.
func (*Response) ExpectJSON ¶ added in v0.1.3
ExpectJSON checks that the value at path in the JSON body equals want. Both sides are compared in their JSON form, so ExpectJSON("n", 3) matches {"n": 3}.
Example ¶
ExpectJSON checks the value at a path. A mismatch is an *ExpectError (expect_mismatch), which fails the step.
package main
import (
"fmt"
"github.com/RIRUa/jotaro"
)
func main() {
resp := &jotaro.Response{Code: 200, Body: []byte(`{"status":"accepted","count":2}`)}
fmt.Println(resp.ExpectJSON("status", "accepted"))
fmt.Println(resp.ExpectJSON("count", 3))
}
Output: <nil> jotaro: unexpected JSON at "count" (want 3, got 2)
func (*Response) ExpectStatus ¶
ExpectStatus checks that the status code equals code.
func (*Response) ExpectStatusIn ¶ added in v0.1.3
ExpectStatusIn checks that the status code is one of codes.
func (*Response) JSON ¶ added in v0.1.3
JSON extracts the value at path from the JSON body. path is dot-separated; object keys are looked up by name and array elements by index, e.g. "data.items.0.id". An empty path returns the whole body. Numbers come back as float64, as with encoding/json.
Example ¶
JSON reads one value from a JSON body by a dot path, without declaring a struct. Object keys are looked up by name and array elements by index. Numbers come back as float64.
package main
import (
"fmt"
"github.com/RIRUa/jotaro"
)
func main() {
resp := &jotaro.Response{Code: 200, Body: []byte(`{"data":{"items":[{"id":7,"name":"tea"}]}}`)}
id, _ := resp.JSON("data.items.0.id")
name, _ := resp.JSON("data.items.0.name")
_, err := resp.JSON("data.items.1.id")
fmt.Println(id, name)
fmt.Println(err)
}
Output: 7 tea jotaro: JSON path "data.items.1.id": bad index "1" (len 1)
type Scenario ¶
type Scenario struct {
// Name labels the scenario in every record and in the report.
Name string
// Fn is the flow itself. Returning an error marks the iteration as failed.
Fn func(ctx context.Context, u *User) error
}
Scenario is the flow that a virtual user runs once.
type Stage ¶
type Stage struct {
// Arrival decides when scenarios start within this stage, counted from the stage's own start.
Arrival Arrival
// For is how long the stage lasts. Arrivals that would fall at or after For are dropped.
For time.Duration
}
Stage is one stage of Stages. It keeps Arrival going for For.
type Step ¶
type Step struct {
// contains filtered or unexported fields
}
Step is the entry point for building requests inside u.Step. Every request built from it is recorded under this step's name.
type User ¶
type User struct {
// ID identifies the virtual user. In the open model every arrival gets its own ID.
ID int
// Iteration counts how many times this user has run the scenario (0-based).
Iteration int
// Client sends the requests. Use it directly for anything the Step builders do not cover,
// but note that such requests are not recorded.
Client *http.Client
// contains filtered or unexported fields
}
User is a virtual user that runs the scenario once. ID is the number of the virtual user and does not change across iterations. Client has its own cookie jar per iteration, so every iteration starts a fresh session.
type UserStage ¶ added in v0.1.3
type UserStage struct {
// Target is the number of active users at the end of the stage.
Target int
// For is how long the stage lasts.
For time.Duration
}
UserStage is one stage of Plan.UserStages. During the stage, the number of active users moves linearly from the Target of the previous stage (Plan.StartUsers, 0 by default, for the first stage) to Target over For. Set Target to the previous Target to hold the number of users.
For example, ramp up to 100 users over 30 seconds, hold for 60 seconds, then ramp down to 0 over 10 seconds:
UserStages: []jotaro.UserStage{
{Target: 100, For: 30 * time.Second},
{Target: 100, For: 60 * time.Second},
{Target: 0, For: 10 * time.Second},
},
func RepeatUserStages ¶ added in v0.1.3
RepeatUserStages returns stages repeated n times in a row, for a load shape that goes up and down several times. Every repetition starts from the Target the previous one ended at, so end the sequence at the Target it begins from (or accept that the first stage of the next round moves from there). Join the result with other stages using append.
For example, three waves of ramp up, hold and ramp down, after a first warm-up stage:
UserStages: append(
[]jotaro.UserStage{{Target: 10, For: 10 * time.Second}},
jotaro.RepeatUserStages(3,
jotaro.UserStage{Target: 100, For: 20 * time.Second},
jotaro.UserStage{Target: 100, For: 30 * time.Second},
jotaro.UserStage{Target: 10, For: 10 * time.Second},
)...,
),
It returns nil when n is not positive or no stage is given. The result is a new slice, so changing it does not change stages. Plan.UserStages rejects an empty result.
Example ¶
RepeatUserStages repeats a sequence of stages, for a load shape that goes up and down several times. Join it with other stages using append.
package main
import (
"fmt"
"time"
"github.com/RIRUa/jotaro"
)
func main() {
stages := append(
[]jotaro.UserStage{{Target: 10, For: 10 * time.Second}}, // warm up
jotaro.RepeatUserStages(2,
jotaro.UserStage{Target: 100, For: 20 * time.Second},
jotaro.UserStage{Target: 100, For: 30 * time.Second},
jotaro.UserStage{Target: 10, For: 10 * time.Second},
)...,
)
for _, st := range stages {
fmt.Println(st.Target, st.For)
}
}
Output: 10 10s 100 20s 100 30s 10 10s 100 20s 100 30s 10 10s
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
jotaro
command
Command jotaro is a CLI that works with result files saved by the jotaro library.
|
Command jotaro is a CLI that works with result files saved by the jotaro library. |
|
examples
|
|
|
checkout
command
Command checkout is a sample that shows how to use jotaro.
|
Command checkout is a sample that shows how to use jotaro. |
|
marketplace
command
Command marketplace is a deeper sample than examples/checkout.
|
Command marketplace is a deeper sample than examples/checkout. |
|
mix
command
Command mix is a sample of the plan-level features of jotaro: a weighted mix of scenarios, waves of users, aborting when the server is broken, live progress and metrics, and thresholds per scenario.
|
Command mix is a sample of the plan-level features of jotaro: a weighted mix of scenarios, waves of users, aborting when the server is broken, live progress and metrics, and thresholds per scenario. |
|
internal
|
|
|
histogram
Package histogram is the log histogram (DDSketch style) that Latency holds for merging.
|
Package histogram is the log histogram (DDSketch style) that Latency holds for merging. |
|
mcpserver
Package mcpserver is the MCP server behind "jotaro mcp".
|
Package mcpserver is the MCP server behind "jotaro mcp". |
|
Package record holds the raw data of a load test (records of requests, steps and iterations), and its input and output.
|
Package record holds the raw data of a load test (records of requests, steps and iterations), and its input and output. |
|
Package report aggregates and outputs the results (Report) of a load test.
|
Package report aggregates and outputs the results (Report) of a load test. |