nealrichardson / httptest

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

capture_requests doesn't capture responses #17

Closed justynafurman closed 6 years ago

justynafurman commented 6 years ago

Following your example I want to capture requests responses and use them later for tests. So, I tried

capture_requests({
    GET("http://httpbin.org/get")
    GET("http://httpbin.org/response-headers",
        query=list(`Content-Type`="application/json"))
})

and I got in RStudio terminal

> capture_requests({
+     GET("http://httpbin.org/get")
+     GET("http://httpbin.org/response-headers",
+         query=list(`Content-Type`="application/json"))
+ })
Response [http://httpbin.org/response-headers?Content-Type=application%2Fjson]
  Date: 2018-08-21 12:22
  Status: 200
  Content-Type: application/json
  Size: 104 B
{
  "Content-Length": "104", 
  "Content-Type": [
    "application/json", 
    "application/json"
  ]
}

but no files have been saved. Changing path argument didn't help, setting options(httptest.verbose=TRUE) also did nothing. I got the same result with start_capturing()...stop_capturing() approach. What is wrong, why this function doesn't work as supposed to?

nealrichardson commented 6 years ago

Thanks. The issue was a fine detail in how base::trace() works. httptest was designed for package developers, and the GET et al. requesting functions were set to record responses in the way that they were accessed via the namespace. It turned out that the tracing you need to get that behavior when you call library(httr) and invoke GET directly is a little different. So in your example, it did not record when you called GET(...), but if you had changed it to httr::GET(...), it would have. Subtle and not ideal.

The commit referenced above adds support for calling the function directly from an interactive session, as you had (reasonably) tried. The following now works as expected and writes out a file:

> library(httr)
> library(httptest)
Loading required package: testthat
> file.exists("httpbin.org/get.json")
[1] FALSE
> capture_requests({
+     x <- GET("http://httpbin.org/get")
+ })
Response [http://httpbin.org/get]
  Date: 2018-08-23 04:17
  Status: 200
  Content-Type: application/json
  Size: 326 B
{
  "args": {}, 
  "headers": {
    "Accept": "application/json, text/xml, application/xml, */*", 
    "Accept-Encoding": "gzip, deflate", 
    "Connection": "close", 
    "Host": "httpbin.org", 
    "User-Agent": "libcurl/7.54.0 r-curl/3.2 httr/1.3.1"
  }, 
  "origin": "52.119.118.235", 
...
> file.exists("httpbin.org/get.json")
[1] TRUE