goose 0.18.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
use httpmock::{Method::GET, Method::POST, Mock, MockServer};
use reqwest::header;

mod common;

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

// In this test the SessionData is a simple String.
struct SessionData(String);

// The actual session data that is set and later validated.
const SESSION_DATA: &str = "This is my session data.";

// Paths used in load tests performed during these tests.
const SESSION_PATH: &str = "/session";
const COOKIE_PATH: &str = "/cookie";

// Indexes for valid requests of above paths, used to validate tests.
const POST_SESSION_KEY: usize = 0;
const GET_SESSION_KEY: usize = 1;
const POST_COOKIE_KEY_0: usize = 2;
const GET_COOKIE_KEY_0: usize = 6;
const POST_COOKIE_KEY_1: usize = 7;
const GET_COOKIE_KEY_1: usize = 11;
const POST_COOKIE_KEY_2: usize = 12;
const GET_COOKIE_KEY_2: usize = 16;
const POST_COOKIE_KEY_3: usize = 17;
const GET_COOKIE_KEY_3: usize = 21;

// How many users to simulate, each with their own session.
const SESSION_USERS: &str = "10";

// How many users to simulate, each with their own cookie.
const COOKIE_USERS: &str = "4";

// There are multiple test variations in this file.
#[derive(Clone)]
enum TestType {
    // Test sessions.
    Session,
    // Test cookies.
    Cookie,
}

// Create a unqiue session per-user.
pub async fn set_session_data(user: &mut GooseUser) -> TransactionResult {
    // Confirm that we start with empty session data.
    let session_data = user.get_session_data::<SessionData>();
    assert!(session_data.is_none());

    // We don't really have to make a request here, but we can...
    let _goose = user.post(SESSION_PATH, SESSION_DATA).await?;

    // Store data in the session, unique per user.
    user.set_session_data(SessionData(format!(
        "{}.{}",
        SESSION_DATA, user.weighted_users_index
    )));

    // Confirm that we now have session data.
    let session_data = user.get_session_data::<SessionData>();
    assert!(session_data.is_some());

    Ok(())
}

// Verify that the per-user session data is correct.
pub async fn validate_session_data(user: &mut GooseUser) -> TransactionResult {
    // We don't really have to make a request here, but we can...
    let _goose = user.get(SESSION_PATH).await?;

    // Confirm that we now have session data.
    let session_data = user.get_session_data::<SessionData>();
    assert!(session_data.is_some());

    // Confirm tht the session data is valid.
    if let Some(data) = session_data {
        // Validate that session data is unique-per-user.
        assert!(data.0 == format!("{}.{}", SESSION_DATA, user.weighted_users_index));
    } else {
        panic!("no session data !?");
    }

    Ok(())
}

// Set a cookie that is unique per-user.
pub async fn set_cookie(user: &mut GooseUser) -> TransactionResult {
    // Per-user cookie name.
    let cookie_name = format!("TestCookie{}", user.weighted_users_index);

    // Per-user cookie path.
    let cookie_path = format!("{}{}", COOKIE_PATH, user.weighted_users_index);

    // Set the Cookie.
    let request_builder = user
        .get_request_builder(&GooseMethod::Post, &cookie_path)?
        .header("Cookie", format!("{cookie_name}=foo"));
    let goose_request = GooseRequest::builder()
        .set_request_builder(request_builder)
        .build();
    let goose = user.request(goose_request).await?;
    let response = goose.response.expect("there must be a response");
    let cookie: reqwest::cookie::Cookie = response.cookies().next().expect("cookie must be set");
    assert!(cookie.name() == cookie_name);

    Ok(())
}

// Verify that the per-user cookie is correct.
pub async fn validate_cookie(user: &mut GooseUser) -> TransactionResult {
    // Per-user cookie path.
    let cookie_path = format!("{}{}", COOKIE_PATH, user.weighted_users_index);

    // Load COOKIE_PATH, the mock endpoint will validate that the proper Cookie is set.
    // Each GooseUser launched has a unique user.weighted_users_index (from 0 to 3),
    // and each user has a unique Cookie name which is TestCookie# where # is the index.
    // Reqwest doesn't expose the cookie data it tracks, so we set up a per-user path
    // and validate the cookie on the mock server side. A 200 will be returned if the
    // correct cookie is passed in by the client. A 404 will be returned if not.
    let _goose = user.get(&cookie_path).await?;

    Ok(())
}

// All tests in this file run against common endpoints.
fn setup_mock_server_endpoints(server: &MockServer) -> Vec<Mock<'_>> {
    let cookie_path_0 = format!("{COOKIE_PATH}0");
    let cookie_path_1 = format!("{COOKIE_PATH}1");
    let cookie_path_2 = format!("{COOKIE_PATH}2");
    let cookie_path_3 = format!("{COOKIE_PATH}3");
    vec![
        // Set up SESSION_PATH, store in vector at POST_SESSION_KEY.
        server.mock(|when, then| {
            when.method(POST).path(SESSION_PATH);
            then.status(200);
        }),
        // Set up SESSION_PATH, store in vector at GET_SESSION_KEY.
        server.mock(|when, then| {
            when.method(GET).path(SESSION_PATH);
            then.status(200);
        }),
        // CookiePath0: TestCookie0=foo
        server.mock(|when, then| {
            when.method(POST).path(&cookie_path_0);
            then.status(200)
                .header(header::SET_COOKIE.as_str(), "TestCookie0=foo");
        }),
        // Be sure TestCookie1 doesn't exist for user0.
        server.mock(|when, then| {
            when.method(GET)
                .path(&cookie_path_0)
                .cookie_exists("TestCookie1");
            then.status(500);
        }),
        // Be sure TestCookie2 doesn't exist for user0.
        server.mock(|when, then| {
            when.method(GET)
                .path(&cookie_path_0)
                .cookie_exists("TestCookie2");
            then.status(500);
        }),
        // Be sure TestCookie3 doesn't exist for user0.
        server.mock(|when, then| {
            when.method(GET)
                .path(&cookie_path_0)
                .cookie_exists("TestCookie3");
            then.status(500);
        }),
        // TestCookie0 should only exist for user0.
        server.mock(|when, then| {
            when.method(GET)
                .path(cookie_path_0)
                .cookie_exists("TestCookie0");
            then.status(200);
        }),
        // CookiePath1: TestCookie1=foo
        server.mock(|when, then| {
            when.method(POST).path(&cookie_path_1);
            then.status(200)
                .header(header::SET_COOKIE.as_str(), "TestCookie1=foo");
        }),
        // Be sure TestCookie0 doesn't exist for user1.
        server.mock(|when, then| {
            when.method(GET)
                .path(&cookie_path_1)
                .cookie_exists("TestCookie0");
            then.status(500);
        }),
        // Be sure TestCookie2 doesn't exist for user1.
        server.mock(|when, then| {
            when.method(GET)
                .path(&cookie_path_1)
                .cookie_exists("TestCookie2");
            then.status(500);
        }),
        // Be sure TestCookie3 doesn't exist for user1.
        server.mock(|when, then| {
            when.method(GET)
                .path(&cookie_path_1)
                .cookie_exists("TestCookie3");
            then.status(500);
        }),
        // TestCookie1 should only exist for user1.
        server.mock(|when, then| {
            when.method(GET)
                .path(cookie_path_1)
                .cookie_exists("TestCookie1");
            then.status(200);
        }),
        // CookiePath2: TestCookie2=foo
        server.mock(|when, then| {
            when.method(POST).path(&cookie_path_2);
            then.status(200)
                .header(header::SET_COOKIE.as_str(), "TestCookie2=foo");
        }),
        // Be sure TestCookie0 doesn't exist for user2.
        server.mock(|when, then| {
            when.method(GET)
                .path(&cookie_path_2)
                .cookie_exists("TestCookie0");
            then.status(500);
        }),
        // Be sure TestCookie1 doesn't exist for user2.
        server.mock(|when, then| {
            when.method(GET)
                .path(&cookie_path_2)
                .cookie_exists("TestCookie1");
            then.status(500);
        }),
        // Be sure TestCookie3 doesn't exist for user2.
        server.mock(|when, then| {
            when.method(GET)
                .path(&cookie_path_2)
                .cookie_exists("TestCookie3");
            then.status(500);
        }),
        // TestCookie2 should only exist for user0.
        server.mock(|when, then| {
            when.method(GET)
                .path(cookie_path_2)
                .cookie_exists("TestCookie2");
            then.status(200);
        }),
        // CookiePath3: TestCookie3=foo
        server.mock(|when, then| {
            when.method(POST).path(&cookie_path_3);
            then.status(200)
                .header(header::SET_COOKIE.as_str(), "TestCookie3=foo");
        }),
        // Be sure TestCookie0 doesn't exist for user3.
        server.mock(|when, then| {
            when.method(GET)
                .path(&cookie_path_3)
                .cookie_exists("TestCookie0");
            then.status(500);
        }),
        // Be sure TestCookie1 doesn't exist for user3.
        server.mock(|when, then| {
            when.method(GET)
                .path(&cookie_path_3)
                .cookie_exists("TestCookie1");
            then.status(500);
        }),
        // Be sure TestCookie2 doesn't exist for user3.
        server.mock(|when, then| {
            when.method(GET)
                .path(&cookie_path_3)
                .cookie_exists("TestCookie2");
            then.status(500);
        }),
        // TestCookie3 should only exist for user3.
        server.mock(|when, then| {
            when.method(GET)
                .path(cookie_path_3)
                .cookie_exists("TestCookie3");
            then.status(200);
        }),
    ]
}

// Build appropriate configuration for these tests.
fn common_build_configuration(
    test_type: &TestType,
    server: &MockServer,
    custom: &mut Vec<&str>,
) -> GooseConfiguration {
    // Common elements in all our tests.
    let mut configuration = match test_type {
        TestType::Session => vec![
            "--users",
            SESSION_USERS,
            "--hatch-rate",
            SESSION_USERS,
            "--run-time",
            "2",
        ],
        TestType::Cookie => vec![
            "--users",
            COOKIE_USERS,
            "--hatch-rate",
            COOKIE_USERS,
            "--run-time",
            "2",
        ],
    };

    // Custom elements in some tests.
    configuration.append(custom);

    // Return the resulting configuration.
    common::build_configuration(server, configuration)
}

// Helper to confirm all variations generate appropriate results.
fn validate_requests(test_type: TestType, goose_metrics: &GooseMetrics, mock_endpoints: &[Mock]) {
    // Convert USERS to a usize.
    let users = match test_type {
        TestType::Session => SESSION_USERS
            .parse::<usize>()
            .expect("must be a valid usize"),
        TestType::Cookie => COOKIE_USERS
            .parse::<usize>()
            .expect("must be a valid usize"),
    };

    match test_type {
        TestType::Session => {
            // Confirm that each user set a session one and only one time.
            assert!(mock_endpoints[POST_SESSION_KEY].hits() == users);
            // Confirm that each user validated their session multiple times.
            assert!(mock_endpoints[GET_SESSION_KEY].hits() > users);
        }
        TestType::Cookie => {
            // Confirm that each user set a cookie one and only one time.
            assert!(mock_endpoints[POST_COOKIE_KEY_0].hits() == 1);
            assert!(mock_endpoints[POST_COOKIE_KEY_1].hits() == 1);
            assert!(mock_endpoints[POST_COOKIE_KEY_2].hits() == 1);
            assert!(mock_endpoints[POST_COOKIE_KEY_3].hits() == 1);
            // Confirm that each user validated their cookie multiple times.
            assert!(mock_endpoints[GET_COOKIE_KEY_0].hits() > 1);
            assert!(mock_endpoints[GET_COOKIE_KEY_1].hits() > 1);
            assert!(mock_endpoints[GET_COOKIE_KEY_2].hits() > 1);
            assert!(mock_endpoints[GET_COOKIE_KEY_3].hits() > 1);
        }
    }

    // Extract the POST requests out of goose metrics.
    let post_metrics = match test_type {
        TestType::Session => goose_metrics.requests.get("POST create session").unwrap(),
        TestType::Cookie => goose_metrics.requests.get("POST create cookie").unwrap(),
    };

    // Extract the GET requests out of goose metrics.
    let get_metrics = match test_type {
        TestType::Session => goose_metrics.requests.get("GET read session").unwrap(),
        TestType::Cookie => goose_metrics.requests.get("GET read cookie").unwrap(),
    };

    // We made POST requests.
    assert!(post_metrics.method == GooseMethod::Post);
    // We made GET requests.
    assert!(get_metrics.method == GooseMethod::Get);
    // We made only 1 POST request per user.
    assert!(post_metrics.success_count == users);
    // We made more than 1 GET request per user.
    assert!(get_metrics.success_count > users);
    // There were no POST errors.
    assert!(post_metrics.fail_count == 0);
    // There were no GET errors.
    assert!(get_metrics.fail_count == 0);
}

// Returns the appropriate scenario needed to build these tests.
fn get_scenarios(test_type: &TestType) -> Scenario {
    match test_type {
        TestType::Session => {
            scenario!("Sessions")
                // Set up the sesssion only one time
                .register_transaction(
                    transaction!(set_session_data)
                        .set_on_start()
                        .set_name("create session"),
                )
                // Validate the session repeateldy.
                .register_transaction(transaction!(validate_session_data).set_name("read session"))
        }
        TestType::Cookie => {
            scenario!("Cookie")
                // Create the cookie only one time
                .register_transaction(
                    transaction!(set_cookie)
                        .set_on_start()
                        .set_name("create cookie"),
                )
                // Validate the cookie repeateldy.
                .register_transaction(transaction!(validate_cookie).set_name("read cookie"))
        }
    }
}

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

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

    let mut configuration_flags = vec!["--no-reset-metrics"];

    // Build common configuration elements.
    let configuration = common_build_configuration(&test_type, &server, &mut configuration_flags);

    // Run the Goose Attack.
    let goose_metrics = common::run_load_test(
        common::build_load_test(
            configuration.clone(),
            vec![get_scenarios(&test_type)],
            None,
            None,
        ),
        None,
    )
    .await;

    // Confirm that the load test ran correctly.
    validate_requests(test_type, &goose_metrics, &mock_endpoints);
}

#[tokio::test]
// Test to confirm sessions are unique per GooseUser and last their lifetime.
async fn test_session() {
    run_standalone_test(TestType::Session).await;
}

#[tokio::test]
// Test to confirm cookies are unique per GooseUser and last their lifetime.
async fn test_cookie() {
    run_standalone_test(TestType::Cookie).await;
}