[Solved] Test panics at Box<Any> Comparing Strings

Hi,

I have a pretty simple test which compares two strings representing software versions, one for a client and one for a server. Let's consider the server to be always correct. I wrote three unit tests to cover the three possible cases:

  1. Current versions match
  2. Client is older than Server
  3. Client is (somehow) newer than Server

Two of the three cases pass, but one always fails. What I do not understand is why this fails at all given that the other two cases pass.

Fun fact: On my PC it always fails for test case '2', but on Rust Playground it fails for case '3'.

I was reading a little bit and some people pointed to using lazy_static!{} but I couldn't get it working. On my actual code base, SYSTEM_VERSION is defined in a non-root-crate module used by two different binaries.

src\
  |-- client.rs   <--- defines a `main()`
  |-- net.rs
  |__ server.rs   <--- defines a `main()`

Both import net.rs

Link to Rust Playgound

Code Snippet:


pub static SYSTEM_VERSION: &'static str = env!("CARGO_PKG_VERSION");

fn validate_version(version: String) -> bool {
    return version <= SYSTEM_VERSION.to_owned()
}

fn main () {

    assert!(validate_version( env!("CARGO_PKG_VERSION").to_owned()), true);
    
    assert!(validate_version(format!("{}.{}.{}", 0, 0, 1).to_owned()), true);
    
    assert!(validate_version(format!("{}.{}.{}", <i32>::max_value(), <i32>::max_value(), <i32>::max_value()).to_owned()), false);

    println!("All cases passed");
}

Any help would be appreciated. Thanks.

It's really not appropriate to be using lexicographical string comparisons for comparing version numbers. That will 100% not do what you seem to want. Look at the semver crate.

As for the inconsistent failures, I'd assume it's because CARGO_PK_VERSION is different. I'm not sure why you haven't tried printing the values out to see what's actually being compared, since that would probably tell you for certain.

Also, if you have multiple binaries, the convention is to put them in src/bin/*.rs, with src/lib.rs containing all the common code. Not required, mind you.

2 Likes

semver is exactly what I needed using semver::Version::parse(...), thanks for the speedy reply.

As a side note, it seems to help that I fixed the typo assert! with assert_eq!, d'oh!