How do you insert header elements for testing in actix?

I am writing tests that involve sending data with an authentication value through the header element. I did some searching and found this line of code:

 let header = test::TestRequest::default().insert_header(
            actix_web::http::header::AUTHORIZATION,
            HeaderValue::from(.....) // This line 
        ).to_http_request();
```, and it used content-length instead of authentication. I don't how to send the basic authentication through the headervalue element when it is not one of the types it takes in. 

Here is my code:  
```...
        let data = <initializing data>;
        let app = test::init_service(
            App::new()
                .app_data(data)
                .service(<app_service>))
                .await;
        let basicAuth = BasicAuth::from(Basic::new("<username>", Some("<password>")));
        let header = test::TestRequest::default().insert_header(
            actix_web::http::header::AUTHORIZATION,
            HeaderValue::from(.....) // This line 
        ).to_http_request();
        let req = test::TestRequest::put().uri("<route>").app_data(http_req).to_request();
        let resp: MyResponse = test::call_and_read_body_json(&app, req).await;
...

Please help

Try this, please:

        let auth = Basic::new("<username>", Some("<password>"));
        let header = test::TestRequest::default().insert_header((
            actix_web::http::header::AUTHORIZATION,
            auth,
        )).to_http_request();

Basic implements TryIntoHeaderValue. TestRequest::insert_header takes something that implements TryIntoHeaderPair as argument. A tuple (HeaderName, V) where V: TryIntoHeaderValue implements TryIntoHeaderPair, so I believe the snippet above should satisfy the required trait bounds.

2 Likes

awesome, thank you so much. I ran into another problem, could I ask about here or should I do another post?

If it's not related to inserting headers into an actix-web test request I'd create a new topic

ok. How do you add the header element to the request and how should I initialize the header element? I realized passing in the http request through the .app_data function was not working.

Ah, yes. Try using the header request as your test request directly, instead of trying to add it as app_data to req, please:

        let auth = Basic::new("<username>", Some("<password>"));
        let req = test::TestRequest::put()
            .uri("<route>")
            .insert_header((
                actix_web::http::header::AUTHORIZATION,
                auth,
            ))
            .to_request();
        let resp: MyResponse = test::call_and_read_body_json(&app, req).await;
1 Like

thank you so much. it worked

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.