Update unit testing post for new panic handler

This commit is contained in:
Philipp Oppermann
2018-06-05 11:06:17 +02:00
parent ee07901388
commit c33811ae3d
2 changed files with 12 additions and 18 deletions

View File

@@ -24,23 +24,20 @@ Unfortunately it's a bit more complicated for `no_std` applications such as our
```
> cargo test
Compiling blog_os v0.2.0 (file:///home/philipp/Documents/blog_os)
error[E0152]: duplicate lang item found: `panic_fmt`.
--> src/main.rs:26:1
Compiling blog_os v0.2.0 (file:////blog_os)
error[E0152]: duplicate lang item found: `panic_impl`.
--> src/main.rs:35:1
|
26 | / pub extern "C" fn rust_begin_panic(
27 | | _msg: core::fmt::Arguments,
28 | | _file: &'static str,
29 | | _line: u32,
... |
32 | | loop {}
33 | | }
35 | / pub fn panic(info: &PanicInfo) -> ! {
36 | | println!("{}", info);
37 | | loop {}
38 | | }
| |_^
|
= note: first defined in crate `std`.
```
The problem is that unit tests are built for the host machine, with the `std` library included. This makes sense because they should be able to run as a normal application on the host operating system. Since the standard library has it's own implementation of the `panic_fmt` language item, we get the above error. To fix it, we use [conditional compilation] to include our implementation of the language item only in non-test environments:
The problem is that unit tests are built for the host machine, with the `std` library included. This makes sense because they should be able to run as a normal application on the host operating system. Since the standard library has it's own `panic_implementation` function, we get the above error. To fix it, we use [conditional compilation] to include our implementation of the panic handler only in non-test environments:
[conditional compilation]: https://doc.rust-lang.org/reference/attributes.html#conditional-compilation
@@ -49,14 +46,10 @@ The problem is that unit tests are built for the host machine, with the `std` li
// in src/main.rs
#[cfg(not(test))] // only compile when the test flag is not set
#[lang = "panic_fmt"]
#[panic_implementation]
#[no_mangle]
pub extern "C" fn rust_begin_panic(
_msg: core::fmt::Arguments,
_file: &'static str,
_line: u32,
_column: u32,
) -> ! {
pub fn panic(info: &PanicInfo) -> ! {
println!("{}", info);
loop {}
}
```

View File

@@ -29,6 +29,7 @@ pub extern "C" fn _start() -> ! {
}
/// This function is called on panic.
#[cfg(not(test))]
#[panic_implementation]
#[no_mangle]
pub fn panic(info: &PanicInfo) -> ! {