goose 0.11.1

A load testing framework inspired by Locust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
use httpmock::{Method::GET, MockRef, MockServer};
use serial_test::serial;
use tokio::time::{sleep, Duration};

mod common;

use goose::prelude::*;
use goose::GooseConfiguration;

// Paths used in load tests performed during these tests.
const ONE_PATH: &str = "/one";
const TWO_PATH: &str = "/two";
const THREE_PATH: &str = "/three";
const START_ONE_PATH: &str = "/start/one";
const STOP_ONE_PATH: &str = "/stop/one";

// Indexes to the above paths.
const ONE_KEY: usize = 0;
const TWO_KEY: usize = 1;
const THREE_KEY: usize = 2;
const START_ONE_KEY: usize = 3;
const STOP_ONE_KEY: usize = 4;

// Load test configuration.
const EXPECT_WORKERS: usize = 4;
// Users needs to be an even number.
const USERS: usize = 18;
const RUN_TIME: usize = 3;

// There are two test variations in this file.
#[derive(Clone)]
enum TestType {
    // Schedule multiple task sets.
    TaskSets,
    // Schedule multiple tasks.
    Tasks,
}

// Test task.
pub async fn one_with_delay(user: &GooseUser) -> GooseTaskResult {
    let _goose = user.get(ONE_PATH).await?;

    // "Run out the clock" on the load test when this function runs. Sleep for
    // the total duration the test is to run plus 1 second to be sure no
    // additional tasks will run after this one.
    sleep(Duration::from_secs(RUN_TIME as u64 + 1)).await;

    Ok(())
}

// Test task.
pub async fn two_with_delay(user: &GooseUser) -> GooseTaskResult {
    let _goose = user.get(TWO_PATH).await?;

    // "Run out the clock" on the load test when this function runs. Sleep for
    // the total duration the test is to run plus 1 second to be sure no
    // additional tasks will run after this one.
    sleep(Duration::from_secs(RUN_TIME as u64 + 1)).await;

    Ok(())
}

// Test task.
pub async fn three(user: &GooseUser) -> GooseTaskResult {
    let _goose = user.get(THREE_PATH).await?;

    Ok(())
}

// Used as a test_start() function, which always runs one time.
pub async fn start_one(user: &GooseUser) -> GooseTaskResult {
    let _goose = user.get(START_ONE_PATH).await?;

    Ok(())
}

// Used as a test_stop() function, which always runs one time.
pub async fn stop_one(user: &GooseUser) -> GooseTaskResult {
    let _goose = user.get(STOP_ONE_PATH).await?;

    Ok(())
}

// All tests in this file run against common endpoints.
fn setup_mock_server_endpoints(server: &MockServer) -> Vec<MockRef> {
    vec![
        // First set up ONE_PATH, store in vector at ONE_KEY.
        server.mock(|when, then| {
            when.method(GET).path(ONE_PATH);
            then.status(200);
        }),
        // Next set up TWO_PATH, store in vector at TWO_KEY.
        server.mock(|when, then| {
            when.method(GET).path(TWO_PATH);
            then.status(200);
        }),
        // Next set up THREE_PATH, store in vector at THREE_KEY.
        server.mock(|when, then| {
            when.method(GET).path(THREE_PATH);
            then.status(200);
        }),
        // Next set up START_ONE_PATH, store in vector at START_ONE_KEY.
        server.mock(|when, then| {
            when.method(GET).path(START_ONE_PATH);
            then.status(200);
        }),
        // Next set up STOP_ONE_PATH, store in vector at STOP_ONE_KEY.
        server.mock(|when, then| {
            when.method(GET).path(STOP_ONE_PATH);
            then.status(200);
        }),
    ]
}

// Build appropriate configuration for these tests.
fn common_build_configuration(
    server: &MockServer,
    worker: Option<bool>,
    manager: Option<usize>,
) -> GooseConfiguration {
    if let Some(expect_workers) = manager {
        common::build_configuration(
            &server,
            vec![
                "--manager",
                "--expect-workers",
                &expect_workers.to_string(),
                "--users",
                &USERS.to_string(),
                "--hatch-rate",
                &USERS.to_string(),
                "--run-time",
                &RUN_TIME.to_string(),
                "--no-reset-metrics",
            ],
        )
    } else if worker.is_some() {
        common::build_configuration(&server, vec!["--worker"])
    } else {
        common::build_configuration(
            &server,
            vec![
                "--users",
                &USERS.to_string(),
                "--hatch-rate",
                &USERS.to_string(),
                "--run-time",
                &RUN_TIME.to_string(),
                "--no-reset-metrics",
            ],
        )
    }
}

// Helper to confirm all variations generate appropriate results.
fn validate_test(test_type: &TestType, scheduler: &GooseScheduler, mock_endpoints: &[MockRef]) {
    // START_ONE_PATH is loaded one and only one time on all variations.
    mock_endpoints[START_ONE_KEY].assert_hits(1);

    match test_type {
        TestType::TaskSets => {
            // Now validate scheduler-specific counters.
            match scheduler {
                GooseScheduler::RoundRobin => {
                    // We launch an equal number of each task set, so we call both endpoints
                    // an equal number of times.
                    mock_endpoints[TWO_KEY].assert_hits(mock_endpoints[ONE_KEY].hits());
                    mock_endpoints[ONE_KEY].assert_hits(USERS / 2);
                }
                GooseScheduler::Serial => {
                    // As we only launch as many users as the weight of the first task set, we only
                    // call the first endpoint, never the second endpoint.
                    mock_endpoints[ONE_KEY].assert_hits(USERS);
                    mock_endpoints[TWO_KEY].assert_hits(0);
                }
                GooseScheduler::Random => {
                    // When scheduling task sets randomly, we don't know how many of each will get
                    // launched, but we do now that added together they will equal the total number
                    // of users.
                    assert!(
                        mock_endpoints[ONE_KEY].hits() + mock_endpoints[TWO_KEY].hits() == USERS
                    );
                }
            }
        }
        TestType::Tasks => {
            // Now validate scheduler-specific counters.
            match scheduler {
                GooseScheduler::RoundRobin => {
                    // Tests are allocated round robin THREE, TWO, ONE. There's no delay
                    // in THREE, so the test runs THREE and TWO which then times things out
                    // and prevents ONE from running.
                    mock_endpoints[ONE_KEY].assert_hits(0);
                    mock_endpoints[TWO_KEY].assert_hits(USERS);
                    mock_endpoints[THREE_KEY].assert_hits(USERS);
                }
                GooseScheduler::Serial => {
                    // Tests are allocated sequentally THREE, TWO, ONE. There's no delay
                    // in THREE and it has a weight of 2, so the test runs THREE twice and
                    // TWO which then times things out and prevents ONE from running.
                    mock_endpoints[ONE_KEY].assert_hits(0);
                    mock_endpoints[TWO_KEY].assert_hits(USERS);
                    mock_endpoints[THREE_KEY].assert_hits(USERS * 2);
                }
                GooseScheduler::Random => {
                    // When scheduling task sets randomly, we don't know how many of each will get
                    // launched, but we do now that added together they will equal the total number
                    // of users (THREE_KEY isn't counted as there's no delay).
                    assert!(
                        mock_endpoints[ONE_KEY].hits() + mock_endpoints[TWO_KEY].hits() == USERS
                    );
                }
            }
        }
    }

    // STOP_ONE_PATH is loaded one and only one time on all variations.
    mock_endpoints[STOP_ONE_KEY].assert_hits(1);
}

// Returns the appropriate taskset, start_task and stop_task needed to build these tests.
fn get_tasksets() -> (GooseTaskSet, GooseTaskSet, GooseTask, GooseTask) {
    (
        taskset!("TaskSetOne")
            .register_task(task!(one_with_delay))
            .set_weight(USERS)
            .unwrap(),
        taskset!("TaskSetTwo")
            .register_task(task!(two_with_delay))
            // Add one to the weight to avoid this getting reduced by gcd.
            .set_weight(USERS + 1)
            .unwrap(),
        // Start runs before all other tasks, regardless of where defined.
        task!(start_one),
        // Stop runs after all other tasks, regardless of where defined.
        task!(stop_one),
    )
}

// Returns a single GooseTaskSet with two GooseTasks, a start_task, and a stop_task.
fn get_tasks() -> (GooseTaskSet, GooseTask, GooseTask) {
    (
        taskset!("TaskSet")
            .register_task(task!(three).set_weight(USERS * 2).unwrap())
            .register_task(task!(two_with_delay).set_weight(USERS).unwrap())
            .register_task(task!(one_with_delay).set_weight(USERS).unwrap()),
        // Start runs before all other tasks, regardless of where defined.
        task!(start_one),
        // Stop runs after all other tasks, regardless of where defined.
        task!(stop_one),
    )
}

// Helper to run all standalone tests.
fn run_standalone_test(test_type: &TestType, scheduler: &GooseScheduler) {
    // Start the mock server.
    let server = MockServer::start();

    // Setup the mock endpoints needed for this test.
    let mock_endpoints = setup_mock_server_endpoints(&server);

    // Build common configuration.
    let configuration = common_build_configuration(&server, None, None);

    let goose_attack;
    match test_type {
        TestType::TaskSets => {
            // Get the tasksets, start and stop tasks to build a load test.
            let (taskset1, taskset2, start_task, stop_task) = get_tasksets();
            // Set up the common base configuration.
            goose_attack = crate::GooseAttack::initialize_with_config(configuration)
                .unwrap()
                .register_taskset(taskset1)
                .register_taskset(taskset2)
                .test_start(start_task)
                .test_stop(stop_task)
                .set_scheduler(scheduler.clone());
        }
        TestType::Tasks => {
            // Get the taskset, start and stop tasks to build a load test.
            let (taskset1, start_task, stop_task) = get_tasks();
            // Set up the common base configuration.
            goose_attack = crate::GooseAttack::initialize_with_config(configuration)
                .unwrap()
                .register_taskset(taskset1)
                .test_start(start_task)
                .test_stop(stop_task)
                .set_scheduler(scheduler.clone());
        }
    }

    // Run the Goose Attack.
    common::run_load_test(goose_attack, None);

    // Confirm the load test ran correctly.
    validate_test(test_type, &scheduler, &mock_endpoints);
}

// Helper to run all gaggle tests.
fn run_gaggle_test(test_type: &TestType, scheduler: &GooseScheduler) {
    // Start the mock server.
    let server = MockServer::start();

    // Setup the mock endpoints needed for this test.
    let mock_endpoints = setup_mock_server_endpoints(&server);

    // Build common configuration.
    let worker_configuration = common_build_configuration(&server, Some(true), None);

    let goose_attack;
    match test_type {
        TestType::TaskSets => {
            // Get the tasksets, start and stop tasks to build a load test.
            let (taskset1, taskset2, start_task, stop_task) = get_tasksets();
            // Set up the common base configuration.
            goose_attack = crate::GooseAttack::initialize_with_config(worker_configuration)
                .unwrap()
                .register_taskset(taskset1)
                .register_taskset(taskset2)
                .test_start(start_task)
                .test_stop(stop_task)
                .set_scheduler(scheduler.clone());
        }
        TestType::Tasks => {
            // Get the taskset, start and stop tasks to build a load test.
            let (taskset1, start_task, stop_task) = get_tasks();
            // Set up the common base configuration.
            goose_attack = crate::GooseAttack::initialize_with_config(worker_configuration)
                .unwrap()
                .register_taskset(taskset1)
                .test_start(start_task)
                .test_stop(stop_task)
                .set_scheduler(scheduler.clone());
        }
    }

    // Workers launched in own threads, store thread handles.
    let worker_handles = common::launch_gaggle_workers(goose_attack, EXPECT_WORKERS);

    // Build Manager configuration.
    let manager_configuration = common_build_configuration(&server, None, Some(EXPECT_WORKERS));

    let manager_goose_attack;
    match test_type {
        TestType::TaskSets => {
            // Get the tasksets, start and stop tasks to build a load test.
            let (taskset1, taskset2, start_task, stop_task) = get_tasksets();
            // Build the load test for the Manager.
            manager_goose_attack =
                crate::GooseAttack::initialize_with_config(manager_configuration)
                    .unwrap()
                    .register_taskset(taskset1)
                    .register_taskset(taskset2)
                    .test_start(start_task)
                    .test_stop(stop_task)
                    .set_scheduler(scheduler.clone());
        }
        TestType::Tasks => {
            // Get the taskset, start and stop tasks to build a load test.
            let (taskset1, start_task, stop_task) = get_tasks();
            // Build the load test for the Manager.
            manager_goose_attack =
                crate::GooseAttack::initialize_with_config(manager_configuration)
                    .unwrap()
                    .register_taskset(taskset1)
                    .test_start(start_task)
                    .test_stop(stop_task)
                    .set_scheduler(scheduler.clone());
        }
    }

    // Run the Goose Attack.
    common::run_load_test(manager_goose_attack, Some(worker_handles));

    // Confirm the load test ran correctly.
    validate_test(test_type, &scheduler, &mock_endpoints);
}

#[test]
// Load test with multiple tasks allocating GooseTaskSets in round robin order.
fn test_round_robin_taskset() {
    run_standalone_test(&TestType::TaskSets, &GooseScheduler::RoundRobin);
}

#[test]
#[cfg_attr(not(feature = "gaggle"), ignore)]
#[serial]
// Load test with multiple tasks allocating GooseTaskSets in round robin order, in
// Gaggle mode.
fn test_round_robin_taskset_gaggle() {
    run_gaggle_test(&TestType::TaskSets, &GooseScheduler::RoundRobin);
}

#[test]
// Load test with multiple GooseTasks allocated in round robin order.
fn test_round_robin_task() {
    run_standalone_test(&TestType::Tasks, &GooseScheduler::RoundRobin);
}

#[test]
#[cfg_attr(not(feature = "gaggle"), ignore)]
#[serial]
// Load test with multiple GooseTasks allocated in round robin order, in
// Gaggle mode.
fn test_round_robin_task_gaggle() {
    run_gaggle_test(&TestType::Tasks, &GooseScheduler::RoundRobin);
}

#[test]
// Load test with multiple tasks allocating GooseTaskSets in serial order.
fn test_serial_taskset() {
    run_standalone_test(&TestType::TaskSets, &GooseScheduler::Serial);
}

#[test]
#[cfg_attr(not(feature = "gaggle"), ignore)]
#[serial]
// Load test with multiple tasks allocating GooseTaskSets in serial order, in
// Gaggle mode.
fn test_serial_taskset_gaggle() {
    run_gaggle_test(&TestType::TaskSets, &GooseScheduler::Serial);
}

#[test]
// Load test with multiple GooseTasks allocated in serial order.
fn test_serial_tasks() {
    run_standalone_test(&TestType::Tasks, &GooseScheduler::Serial);
}

#[test]
// Load test with multiple tasks allocating GooseTaskSets in random order.
fn test_random_taskset() {
    run_standalone_test(&TestType::TaskSets, &GooseScheduler::Random);
}

#[test]
#[cfg_attr(not(feature = "gaggle"), ignore)]
#[serial]
// Load test with multiple tasks allocating GooseTaskSets in random order, in
// Gaggle mode.
fn test_random_taskset_gaggle() {
    run_gaggle_test(&TestType::TaskSets, &GooseScheduler::Random);
}

#[test]
// Load test with multiple tasks allocating GooseTaskSets in random order.
fn test_random_tasks() {
    run_standalone_test(&TestType::Tasks, &GooseScheduler::Random);
}