nealrichardson / httptest2

Utilities for testing R 📦s that use httr2
https://enpiar.com/httptest2/
Other
26 stars 6 forks source link

Should the default mock path be absolute? #29

Open maelle opened 11 months ago

maelle commented 11 months ago

Sorry in advance for not writing a proper reprex! I might come to this later. :innocent:

I think my current problem is similar to https://github.com/r-lib/testthat/pull/1476 in testthat.

When changing the current directory in a test, then using say httptest2::with_mock_dir(), nothing gets recorded in the actual package. I think it's because httptest2:::default_mock_path() is relative to the current directory.

nealrichardson commented 11 months ago

I'd be interested to see what you do to trigger that--I can imagine how it might be possible, but I can't picture the exact workflow that would get you there.

maelle commented 11 months ago

I created a reprex! :innocent:

If I run the test in https://github.com/maelle/mockmock/blob/main/tests/testthat/test-blop.R no mock file is created.

maelle commented 11 months ago

(but if I comment out withr::local_dir(temp_dir), a mock file is created)

nealrichardson commented 11 months ago

I think a mock file is created, it's just in the temp_dir you created.

with_mock_dir() just checks if dir exists; whether dir is relative or absolute is up to you. In your example, if you want dir not to be relative to temp_dir, you could normalizePath before you change local_dir(temp_dir). I'm not sure what else would make sense for the function to do. Is there a realistic scenario where this is a problem?

maelle commented 11 months ago

I discovered this behavior, that I agree is not that surprising, when writing tests for fledge, a package helping with package development, in which tests we often change the current directory to the directory of a toy package.

In fledge tests, using snapshot tests without further customization works since the PR https://github.com/r-lib/testthat/pull/1476 so I wonder whether that could be tweaked in httptest2 too.

I don't know exactly how that could happen. The initial current directory could be "recorded" by code stored in the setup/helper file that loads httptest2, and then used throughout the httptest2 calls in the tests.

But I agree I can also tweak my tests.

maelle commented 11 months ago

For the record, in the fledge branch I was working on, tests/testthat/helper-httptest2.r now is

library("httptest2")

test_path <- normalizePath(testthat::test_path())
Sys.setenv("fledge.test.path" = test_path)
with_mock_dir <- function(name, ...) {
  dir <- file.path(dirname(Sys.getenv("fledge.test.path")), "fixtures", name)
  httptest2::with_mock_dir(dir, ...)
}