Skip to content

Commit 81088ab

Browse files
committed
Refactor skip_if_not_root into macro
This macro can be used in tests to skip the test if it requires root to sucssfully run.
1 parent 57603c6 commit 81088ab

File tree

2 files changed

+18
-13
lines changed

2 files changed

+18
-13
lines changed

test/test.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,21 @@ extern crate libc;
99
extern crate rand;
1010
extern crate tempfile;
1111

12+
macro_rules! skip_if_not_root {
13+
($name:expr) => {
14+
use nix::unistd::Uid;
15+
use std;
16+
use std::io::Write;
17+
18+
if !Uid::current().is_root() {
19+
let stderr = std::io::stderr();
20+
let mut handle = stderr.lock();
21+
writeln!(handle, "{} requires root privileges. Skipping test.", $name).unwrap();
22+
return;
23+
}
24+
};
25+
}
26+
1227
mod sys;
1328
mod test_dir;
1429
mod test_fcntl;

test/test_unistd.rs

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use nix::unistd::ForkResult::*;
44
use nix::sys::signal::{SaFlags, SigAction, SigHandler, SigSet, Signal, sigaction};
55
use nix::sys::wait::*;
66
use nix::sys::stat::{self, Mode, SFlag};
7-
use std::{self, env, iter};
7+
use std::{env, iter};
88
use std::ffi::CString;
99
use std::fs::File;
1010
use std::io::Write;
@@ -127,12 +127,7 @@ mod linux_android {
127127
#[cfg(not(any(target_os = "ios", target_os = "macos")))]
128128
fn test_setgroups() {
129129
// Skip this test when not run as root as `setgroups()` requires root.
130-
if !Uid::current().is_root() {
131-
let stderr = std::io::stderr();
132-
let mut handle = stderr.lock();
133-
writeln!(handle, "test_setgroups requires root privileges. Skipping test.").unwrap();
134-
return;
135-
}
130+
skip_if_not_root!("test_setgroups");
136131

137132
let _m = ::GROUPS_MTX.lock().expect("Mutex got poisoned by another test");
138133

@@ -156,12 +151,7 @@ fn test_setgroups() {
156151
fn test_initgroups() {
157152
// Skip this test when not run as root as `initgroups()` and `setgroups()`
158153
// require root.
159-
if !Uid::current().is_root() {
160-
let stderr = std::io::stderr();
161-
let mut handle = stderr.lock();
162-
writeln!(handle, "test_initgroups requires root privileges. Skipping test.").unwrap();
163-
return;
164-
}
154+
skip_if_not_root!("test_initgroups");
165155

166156
let _m = ::GROUPS_MTX.lock().expect("Mutex got poisoned by another test");
167157

0 commit comments

Comments
 (0)