Giter VIP home page Giter VIP logo

axum-test's People

Contributors

akesling avatar autopp avatar cbeck88 avatar connorskees avatar iustin avatar josephlenton avatar lasantosr avatar pitbuster avatar ricerca1-itg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

axum-test's Issues

Address already in use

Running more than a single test with axum-test results in address already in use:

running 5 tests
test resources::utils::tests::it_handles_unauthorized ... ok
test resources::utils::tests::it_handles_unknown ... ok
test utils::jwt::tests::it_encodes_data ... ok
test resources::public::handlers::register::tests::it_can_validate_payloads ... FAILED
test resources::public::handlers::register::tests::it_can_create_a_user ... ok

failures:

---- resources::public::handlers::register::tests::it_can_validate_payloads stdout ----
thread 'resources::public::handlers::register::tests::it_can_validate_payloads' panicked at src/resources/public/mod.rs:17:10:
called `Result::unwrap()` on an `Err` value: Os { code: 48, kind: AddrInUse, message: "Address already in use" }

I can see in the examples dir that everything seems to work for you. What am I missing?

#[cfg(test)]
mod tests {
    use crate::{resources::public, state};
    use axum_test::TestServer;
    use serde_json::json;

    #[tokio::test]
    async fn it_can_validate_payloads() {
        let state = state::read().await;
        let resource = public::spawn(state).await;
        let server = TestServer::new(resource.app).unwrap();

        let email = "matilda";
        let payload = json!({ "email": email });
        let response = server.post("/auth/register").json(&payload).await;

        response.assert_status_forbidden();
        response.assert_json(&json!({ "message": "It appears as though the email address is invalid, please take a look and try again." }));
    }

    #[tokio::test]
    async fn it_can_create_a_user() {
        let state = state::read().await;
        let resource = public::spawn(state).await;
        let server = TestServer::new(resource.app).unwrap();

        let email = "[email protected]";
        let payload = json!({ "email": email });
        let response = server.post("/auth/register").json(&payload).await;

        response.assert_status_ok();
        response.assert_json(&json!({ "user": { "email": email } }));
    }
}

Default behavior to panic on status code != 200

I use axum-test to test a REST API. To me, it feels awkward to write
let response = server.post("/sessions").expect_failure().json(&request).await;
because I don't expect a failure - I expect a status code of 201 (Created), which signifies success in the context of a REST API. Perhaps it would be better to limit failure status codes to the 5xx range?

Support for axum 0.7.1

After upgrading to axum 0.7.1 I get the following error:

the trait bound `Router: IntoTransportLayer` is not satisfied
the following other types implement trait `IntoTransportLayer`:
  axum::extract::connect_info::IntoMakeServiceWithConnectInfo<axum::routing::Router, C>
  axum::routing::Router
  axum::routing::into_make_service::IntoMakeService<axum::routing::Router>

Cookies are not removed

When the server responds a request with a cookie removal (expiration date way in the past), the cookie is not removed and is sent to consecutive requests.

Unable to run tests on Windows machine

Hi,
I can't run the test on a Windows 10 machine. I have to switch to an Ubuntu WSL to run it.
Here is the message on the native terminal.

Compiling backend v0.1.0 (C:\Users\quanh\workspace-c\GoViral\backend)
    Finished test [unoptimized + debuginfo] target(s) in 3.10s
     Running unittests src\main.rs (target\debug\deps\backend-da715d141979108d.exe)

running 1 test
test test_get_home::it_should_return_message ... FAILED

failures:

---- test_get_home::it_should_return_message stdout ----
thread 'test_get_home::it_should_return_message' panicked at 'Sending request failed: Expect Hyper Response to succeed on request to /

Caused by:
    0: error trying to connect: tcp connect error: The requested address is not valid in its context. (os error 10049)
    1: tcp connect error: The requested address is not valid in its context. (os error 10049)
    2: The requested address is not valid in its context. (os error 10049)', C:\Users\quanh\.cargo\registry\src\github.com-1ecc6299db9ec823\axum-test-7.2.0\src\test_request.rs:216:27
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace


failures:
    test_get_home::it_should_return_message

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s

error: test failed, to rerun pass `--bin backend`

Support of multipart

Unless I'm missing something, it's not yet possible to use multipart while testing.
As I use axum = { version = "0.7.2", features = ["multipart"] } and async fn red_pixels(mut multipart: Multipart) -> (StatusCode, String) {} in my code, I wanted to test that part.
I tried to use this crate like I would have with the reqwest crate (where I need to set my cargo.toml to
reqwest = { version = "0.11.23", features = ["multipart"] } ) but it doesn't seem to be possible here, and I didn't find something about that on the docs :

#[tokio::test]
async fn task2() {
    let app = get_day_11_router();

    // Run the application for testing.
    let server = TestServer::new(app).unwrap();

    // Send the request.
    let form = Form::new().part(
        "image",
        Part::bytes(include_bytes!("../../assets/decoration.png").as_slice())
            .file_name("decoration.png")
            .mime_str("image/png")
            .unwrap(),
    );
    let response = server.post("/red_pixels").multipart(form).await;

    response.assert_status(StatusCode::OK);
}

do you plan to do something about it?
Thank you!

No way to pass parameters that uses serde_qs

Hi, first of all, i really appreciate the amount of effort you have put into improve the testing experience. GREAT JOB!

I am running into an issue, i believe i am missing something.
In my my app i am using serde_qs to parse the query string in format ?filters[amount][op]=EQ&filters[amount][value]=[0], but i found no way in axum_test to pass query in such a format.

Any suggestions?

Stack Overflow Error

I love this crate but I've hit a problem when I try to run tests using it. I'm hitting a stack overflow issue (specifically fatal runtime error: stack overflow). I have tried increasing the stack using RUST_MIN_STACK and can get farther through the test suite before hitting the error but I cannot get through them all. This error occurs both under macOS and on a AWS RHEL server I am also using. I can get these tests to run just fine if I only run a few of them. The issue seems to occur when I run the whole suite

I do not have this SO problem if the tests which use axum-server are marked to be ignored.

Below is a sample of one of the tests that uses the test server. I unfortunately cannot share much code beyond this due to our policies.

I know I haven't given a good bug report here. But, I'm hoping it is enough to get some ideas towards a resolution path.

Thank you for your help and assistance.

    fn setup_test_server(app_state: AppState) -> TestServer {
        TestServer::new(
            Router::new()
                .route("/test/:foo_id", get(foo_api_get))
                .route(
                    "/test/:foo_id/bar",
                    patch(foo_api_bar),
                )
                .route(
                    "/test/:foo_id/baz",
                    patch(foo_api_baz),
                )
                .with_state(app_state),
        )
        .unwrap()
    }

   ...

    #[tokio::test]
    async fn patch_foo_api_bar() {
        let mut foo_state = AppState::default();
        foo_state.db = rbatis_sqlite_in_memory_db_setup().await;
        let db = &mut foo_state.db;
        let (_customer_id, foo_id, _trace_id) = setup_test_env(db).await;
        let server = setup_test_server(foo_state);

        assert_eq!(
            server
                .get(format!("/test/{}", foo_id).as_str())
                .await
                .json::<FooResponse>()
                .foo
                .state,
            Some("zing".to_string())
        );

        assert_eq!(
            server
                .patch(format!("/test/{}/bar", foo_id).as_str())
                .await
                .json::<FooResponse>()
                .foo
                .state,
            Some("bar".to_string())
        );
    }

How to send custom headers?

I may be missing something, but how can I add custom headers when sending a request? Seems like currently the headers vector is a private field and I can't find any method to set it.

Make `TestResponse` assertion methods take self by reference

Currently the helper methods on TestResponse take in self by value and return Self, e.g.

pub fn assert_status_bad_request(self) -> Self;

The usage of these functions then has to look like this,

let res = server.post("/foo");

res.assert_status(StatusCode::CREATED).assert_text("0")

This API feels a bit clunky as taking res by value moves the struct. This makes it harder to assert a value based on a condition:

let res = server.post("/foo");

// res gets moved here
res.assert_status(StatusCode::CREATED);

// not possible without re-assigning `res` in the line above
if foo.bar {
  res.assert_text("0");
} else {
  res.assert_text("1");
}

It would be nice if these methods had their signatures changed to be

pub fn assert_status_bad_request(&self);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.