Assert_fs - assert and &'static str

As a word of warning, I am Rust n00b (r00b?) so this question may very well be a case of me failing to grok the docs, or Rust, or both.

I am writing an integration test for a small cli app that captures a path from the user and stores it in a file. The test must validate the contents of the file and, as I am using TempDir, I base the input path on the created tempdir. This means that the contents of the output file are dynamic. This causes an issue when I try to assert the contents of the output file.

Test:

let temp = assert_fs::TempDir::new().unwrap();

.... some code that writes to the file, removed for brevity....

let config_file = temp.child(".wtcconfig.yml");                                                                     
let expected_contents = format!("---\neditor: gedit\n{}/foo", temp.path().to_str().unwrap());                       
let expected_as_slice = &expected_contents[..];                                                                     
config_file.assert(expected_as_slice);

The compiler returns the below:

30 |     let expected_as_slice = &expected_contents[..];
   |                              ^^^^^^^^^^^^^^^^^ borrowed value does not live long enough

Looking at the docs for assert() leads me to this which leads to this.

All of which I interpret to mean that assert() can be passed a string literal as it is a slice with a static lifetime. What I have read via the interwebs suggests that if you find yourself in a position where the answer is to convert String to &'static str then you have probably gone wrong somewhere.

I am going to rewrite this test so as to not rely on assert(), but I am curious to know if I am misunderstanding the problem entirely (i.e. there is a way to use assert() that does not require creating a &'static str).

It looks like they want one of the predicates from the predicates crate.

config_file.assert(predicates::ord::eq(expected_as_slice));

This looks a bit sloppy in the design of assert_fs to me. If &'static str is accepted, it should accept &str too.

cc @epage

1 Like

I've just posted a change that loosens the restrictions on what can be used for a "shortcut" predicate.

I am going to rewrite this test so as to not rely on assert(),

Was this the only reason or have there been other concerns?

Wow, thanks @epage! It was pretty much the only reason - I assumed that I was using it wrong (I have found that starting with this assumption makes for way less tears in the end) and so I was going to rewrite it to just use fs::read_to_string and assert_eq!.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.