alexliesenfeld / httpmock

HTTP mocking library for Rust
https://httpmock.rs
MIT License
488 stars 45 forks source link

Make timestamp in file name optional #115

Open ddimaria opened 2 months ago

ddimaria commented 2 months ago

In recording fixtures within a repo to be replayed independently of recording, it's helpful to be able to just load the file by scenario. Since the file name has a prepended timestamp, I have to rename the file once created to have a consistent name. If I could load by directory and scenario name, it would save a bit of code.

Current behavior:

 let playback_server = MockServer::start();
playback_server.playback(PathBuf::from("./fixtures/my-scenario_1726530273.yaml"));
// make the request

Desired behavior:

 let playback_server = MockServer::start();
playback_server.playback_scenario(PathBuf::from("./fixtures"), "my-scenario");
// make the request

Here is my current workaround:

async fn test_query(record: bool, max_bytes: Option<u64>) -> (Bytes, bool) {
    let connection = get_connection();
    let url = "https://some-url";

    let server = MockServer::start();
    server.forward_to(&url, |rule| {
        rule.filter(|when| {
            when.any_request();
        });
    });

    // setuup the recording server, this is not used during playback but required for recording
    let recording = server.record(|rule| {
        rule.filter(|when| {
            when.any_request();
        });
    });

    let client = get_client();

    let scenario = "my-scenario";
    let fixtures_dir = "./fixtures";
    let fixtures_path = PathBuf::from(fixtures_dir);
    let path = PathBuf::from(format!("{fixtures_dir}/{scenario}.yml"));

    if !record {
        let playback_server = MockServer::start();
        playback_server.playback(path.clone());
    }

    // make the request

    if record {
        let saved_path = recording
            .save_to_async(fixtures_path, scenario)
            .await
            .expect("cannot store scenario on disk");

        std::fs::rename(saved_path, path).unwrap();
    }

    result
}

Let me know if you're interested in having this kind of feature and I'll submit a PR. Thanks!

alexliesenfeld commented 1 month ago

Makes sense, thank you. I assume playback_server.playback_scenario(PathBuf::from("./fixtures"), "my-scenario"); should load the scenario file with the most recent timestamp, right?