17

Suppose you have a dependency called "dep" which has two features called f1 and f2. I want to use "dep" with the f1 feature when I'm building my crate normally, but use it with f2 when building it for tests. I know dev-dependencies are those we need for tests and thought the following structure for Cargo.toml should work:

    [dev-dependencies]
    dep = { version = "1.0.0", features = ["f2"] }
    
    [dependencies]
    dep = { version = "1.0.0", features = ["f1"] }
    

However, it looks like once I have pulled in "dep" with "f1", the compiler would disregard the mention of the same dependency under the dev-dependencies section. On the other hand, making the dependency "optional" will not solve the issue because then "dep" will not be pulled in for the tests at all. Any ideas on how to resolve this issue or circumvent it nicely?

PS: I noticed the issue is being tracked here: https://github.com/rust-lang/cargo/issues/7916. So at the moment, I could only expect good workarounds from the respondents.

Alex Sed
  • 700
  • 5
  • 12
  • Have you tried this and encountered issues with it? It seems reasonable to me to assume that the compiler would merge the feature set as necessary – apetranzilla Oct 20 '20 at 03:58
  • Yes I tried it and as said, the compiler seems to have disregarded the definition under dev-dependencies. – Alex Sed Oct 20 '20 at 04:03
  • 1
    As a workaround, what I did once is to set the dependency as optional and run the tests with `cargo test --all-features`. – rodrigo Oct 20 '20 at 08:45
  • 1
    As an update on this, it looks like issue [7916](https://github.com/rust-lang/cargo/issues/7916) has been merged. IIUC, you can also use [version 2 of the dependency resolver](https://doc.rust-lang.org/nightly/cargo/reference/features.html#feature-resolver-version-2), which no longer merges dev- and normal dependencies, unless the target in question actually needs them. – bnaecker Jun 29 '21 at 20:51

1 Answers1

3

This is possible with rust 2021 using resolver version 2. as documented here. Specifically it says this:

Features enabled on dev-dependencies will not be unified when those same dependencies are used as a normal dependency, unless those dev-dependencies are currently being built

In order to do this you will need your root package to have edition = "2021", then you can use resolver = "2" in your crate manifest to enable the desired behaviour.

Alex jg
  • 915
  • 11
  • 23