How do I build code in a documentation test but not run it? - rust

I have code in my documentation that can only be run if the user has some software on their machine. To emulate this, I add panic! to the sample code:
//!```rust
//!fn main() {
//! panic!("Not run me");
//!}
//!```
#[cfg(test)]
mod tests {
#[test]
fn it_works() {}
}
I want to check that the code in the comments can be compiled, but I do not want it to be run during cargo test. Right now, I get:
running 1 test
test src/lib.rs - (line 1) ... FAILED
failures:
---- src/lib.rs - (line 1) stdout ----
thread 'rustc' panicked at 'test executable failed:
thread 'main' panicked at 'Not run me', <anon>:2
note: Run with `RUST_BACKTRACE=1` for a backtrace.
I read about doctest = false, but that disables not only the running of code in comments, but also syntax checking the code in comments.
How can I only disable running of code in comments, but still enable compilation of code in comments during cargo test?

There are several annotations you can use to change how the Rust code is processed. See the test documentation.
In your case it sounds like no_run is the one you'd want
//!```rust,no_run
//!fn main() {
//! panic!("Not run me");
//!}
//!```
Alternatively you could use should_panic so Rust will run the code, but expect the panic. If it's code that won't actually compile, you can use ignore.

Related

cargo rust build script - print output of command

I am new to rust and cargo, and I am trying to do something very simple!
I have something like this (in build.rs):
use std::process::Command;
fn main() {
Command::new("echo 123");
}
And I want to see the output of the command echo 123. I want 123 to get printed to the build output (this is mostly to debug what I am doing) and wont be part of the final project.
I have tried cargo build --verbose - this does not work.
I can't extrapolate an answer from there posts (and some others like it):
https://github.com/rust-lang/cargo/issues/985
https://github.com/rust-lang/cargo/issues/1106
I feel this must be simple to do - but I have been stuck for hours looking on the web and not finding the answer.
Just building a Command with Command::new does not execute it yet. It just starts a builder pattern. To actually execute it, you have to use the methods spawn, output or status. Example:
Command::new("echo")
.arg("123")
.spawn()
.expect("failed to spawn process");
It's very unfortunate that this doesn't produce a warning. Someone recently tried to add the #[must_use] attribute to Command, which would make your code procude a warning. The PR closed for now but it seems like it will be added eventually.
We can use a macro and it worked form me, but there is a warning, since it uses cargo to display. but that is fine for me.
I found below code from git hub discussion:
Cargo doesn’t display output from a command in build.rs #985
macro_rules! p {
($($tokens: tt)*) => {
println!("cargo:warning={}", format!($($tokens)*))
}
}
fn main() {
p!("BUILD.rs -> Starting ...");
}

Where do I need to put file to be read by Rust?

When I was reading through the tutorial for Rust here (https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html). I found this block of code:
use std::fs::File;
fn main() {
let f = File::open("hello.txt");
let f = match f {
Ok(file) => file,
Err(error) => panic!("Problem opening the file: {:?}", error),
};
}
It always displays an error: { code: 2, kind: NotFound, message: "The system cannot find the file specified." } even when I make a hello.txt at the root folder of the src, it fails to read it.
In another example here, I use cargo run to no success. The program still fails to read hello.txt file. I'm aware that the example uses rustc open.rs && ./open. Since I don't understand why is it suddenly use different compile method and what's it even mean... I just kinda skip it and try to use cargo run instead
Where do I need to put my file here so cargo run can read it ?
Also if I run the production code and need the program to read an external file, where do I need to put it ?
Here's my folder structure. Pretty simple since I just start to learn RUST.
Thank you in advance.
A file without a directory component in the name needs to be in the current working directory, i.e. the directory from which you start your executable or cargo run.
If you start cargo from an IDE, it might not be immediately apparent what directory it will use as the current directory. In that case, you can always find the current working directory by printing it explicitly:
fn main() {
println!("{}", std::env::current_dir().unwrap().display())
}

How to enable unstable Rust feature str_split_once?

I'm having a hard time figuring out where do I need to write something to enable this feature.
I tried adding #![feature(str_split_once)] to the file where I'm using it but nothing happens. By Googling I found How do you enable a Rust "crate feature"? but after adding
[features]
default = ["str_split_once"]
to Cargo it doesn't build with
Caused by: feature default includes str_split_once which is
neither a dependency nor another feature
I tried adding #![feature(str_split_once)] to the file where I'm using it but nothing happens.
I guess there's not really "nothing happens", but there was a warning similar to this one:
warning: crate-level attribute should be in the root module
--> src/lib.rs:2:5
|
2 | #![feature(str_split_once)]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
Playground
Just add this line at the beginning of lib.rs and/or main.rs, build with nightly, and it should work:
#![feature(str_split_once)]
fn main() {
// prints Some(("test1", "test2 test3"))
println!("{:?}", "test1 test2 test3".split_once(" "));
}
Playground

Why does `cargo build` not show all errors in my code?

This code doesn't compile:
extern crate iron;
#[marco_use] //misspelled here
extern crate mime;
use iron::prelude::*;
use iron::status;
fn main() {
let mut response = Response::new();
response.set_mut(mime!(Text/Html; Charset=Utf8));
}
it shows:
error: cannot find macro `mime!` in this scope
--> src/main.rs:10:22
|
10 | response.set_mut(mime!(Text/Html; Charset=Utf8));
| ^^^^
If I add extern crate hyper; use hyper::mime::*;, then it shows:
error: The attribute `marco_use` is currently unknown to the compiler and
may have meaning added to it in the future (see issue #29642)
--> src\main.rs:2:1
|
2 | #[marco_use] extern crate mime;
| ^^^^^^^^^^^^
If I could've seen this earlier, it would've helped me to fix the mistake...
I guess Cargo only shows one error? I could not find anything about this behaviour online. How can I see all errors?
The compilation process is divided into several stages and if during one of them an error breaks the build, the following stages are not processed further. This is not specific to Cargo, but rustc as well (example: When are numeric literals assigned to default types?).
I haven't seen it officially documented, but the high-level process has been described by japaric:

Unable to build Hyper - invalid character `-` in crate name

I am trying to run the hyper example listed on the Github readme.
extern crate hyper;
use std::io::Write;
use hyper::Server;
use hyper::server::Request;
use hyper::server::Response;
use hyper::net::Fresh;
fn hello(_: Request, res: Response<Fresh>) {
let mut res = res.start().unwrap();
res.write_all(b"Hello World!").unwrap();
res.end().unwrap();
}
fn main() {
Server::http(hello).listen("127.0.0.1:3000").unwrap();
}
And the Cargo.toml looks like this:
[package]
name = <crate_name>
version = <version>
authors = <authors>
[dependencies]
hyper = "0.3"
However, when I attempt to build it using Cargo run I get the following error:
error: invalid character `-` in crate name: `build-script-build`
error: invalid character `-` in crate name: `pkg-config`
error: invalid character `-` in crate name: `rustc-serialize`
I looked through these different crates trying to see if maybe I could just change a "rustc-serialize" to "rustc_serialize" because I think that crate names can no longer have hyphens. However, I couldn't find anything of the sort. I would really like to be able to solve this problem because I have a feeling that I am going to run into this error a few more times while Rust is still being polished.
Edit: The versions are as follows:
Rust: 1.0.0-beta.2
Hyper: 0.3.14
Cargo: 0.0.1-pre-nightly (built 2015-03-09)
Your version of Hyper seems to require a newer version of Rust, which automatically converts hyphens to underscores in crate names.
See RFC 940 and Issue #23533.

Resources