I'm trying to write tests for a binary that contacts an online host I control.
For the tests, I would like that host to be localhost, and not the public, production one.
To that end, I defined the host to be used for production with the annotation #[cfg(not(test))] (see here) and the host to be used for tests with the annotation #[cfg(test)] (see here).
In the tests, I call the binary with Command::new("target/debug/asfald"), but it uses the production host, not the local host. Can I make the tests build the binary with the test profile?
You could move your logic to library instead of binary and test it directly.
You could check presence of some environment variable to overwrite default server location and set it for tests.
side note: I don't think you should ever hardcode such values. Use config files, env variables, or CLI arguments to pass this information instead. This will be more testable, maintainable - when your domain changes you don't have to recompile - and depending on your threat model, more secure.
You can conditionally compile your code with features. And then you can make tests depend on those features. For example:
Thanks @akrauze for your feedback. Here is some more context about my problem and why I think just working with an env var is not possible (but correct me if I'm wrong!).
Regarding 1., I wanted to test the binary so I can test it as a user would use it, with a combination of flags passed to the binary. I can test functions from the lib, but then I don't have the same view as the user, and I could make mistakes in the translation between the flags passed to the binay and the library's function call.
Regarding 2., I totally agree with your suggestion based on what I asked, but the situation is a bit more complex. For example, I want production code to only issue requests with https, but I accept test code to issue http requests. This means that in tests I define an additional variant in an enum, but that variant should not be available in production code. I'll be happy to learn an alternative approach if there is!
It worked with your suggestion (3.). If anyone is interested, here are the small changes I had to apply: test-only code is marked with #[cfg(any(test, feature = "testing"))], and production-only code is marked with #[cfg(not(any(test, feature = "testing")))]