How to pull a dependency with different features under Cargo.toml "dependencies" and "dev-dependencies"?
Asked Answered
D

1

20

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.

Dulcinea answered 20/10, 2020 at 3:41 Comment(4)
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 necessaryPinprick
Yes I tried it and as said, the compiler seems to have disregarded the definition under dev-dependencies.Dulcinea
As a workaround, what I did once is to set the dependency as optional and run the tests with cargo test --all-features.Villain
As an update on this, it looks like issue 7916 has been merged. IIUC, you can also use version 2 of the dependency resolver, which no longer merges dev- and normal dependencies, unless the target in question actually needs them.Alta
P
5

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.

Pewee answered 2/1, 2022 at 21:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.