nealrichardson / httptest

A Test Environment for HTTP Requests in R
https://enpiar.com/r/httptest/
Other
79 stars 10 forks source link

Testing response headers #12

Closed byapparov closed 6 years ago

byapparov commented 6 years ago

Some APIs rely on values in the response headers. Is there a graceful way to test headers?

Thanks Bulat

nealrichardson commented 6 years ago

httptest has expect_header(), but that's for request headers, not response headers. If I were going to assert things about response headers, I'd just get the response and do regular testthat assertions, something like

resp <- GET("https://httpbin.org/get")
expect_equal(resp$headers[["content-type"]], "application/json")

That's pretty straightforward, IMO, but if you have an idea for a more graceful way, I'd be happy to entertain it.

byapparov commented 6 years ago

I have an API which uses headers to authentication (keys etc).

maybe that is something that I should just mock with lets say mockery?

nealrichardson commented 6 years ago

Maybe I misunderstand the problem. If you're talking about auth headers that you send in your request, you can use expect_header() (reference). So if you wanted to test that your auth header in e.g. this function, you could

without_internet({
    expect_header(
        expect_POST(executeSchedule("")),
        "Cookie: whatever-you-think-it-should-be"
    )
})

You don't need to make network requests to use expect_header().

Alternatively, if you're testing response headers, and you want to record a real API response to load in with_mock_api(), use capture_requests() (vignette) with the simplify = FALSE option to record full response objects. Be advised that by default, for your safety, any cookies in the response will be redacted (vignette), but you can control that behavior. You can also edit the .R mock file that is recorded to have whatever (safe) header or cookie value you want to assert in your tests.

Do either of these get at what you're trying to do? If not, if you want to give me a more concrete example, I can try to help better.

byapparov commented 6 years ago

Great, your second suggestion worked. Request saved as structure is a bit wordy.

note: I could not save request with capture_requests() but found function inside it that worked.