Module users::mock [−][src]
Mockable users and groups.
When you’re testing your code, you don’t want to actually rely on the system actually having various users and groups present - it’s much better to have a custom set of users that are guaranteed to be there, so you can test against them.
This module allows you to create these custom users and groups
definitions, then access them using the same Users
trait as in the main
library, with few changes to your code.
Creating Mock Users
The only thing a mock users table needs to know in advance is the UID of
the current user. Aside from that, you can add users and groups with
add_user
and add_group
to the table:
use std::sync::Arc; use users::mock::{MockUsers, User, Group}; use users::os::unix::{UserExt, GroupExt}; let mut users = MockUsers::with_current_uid(1000); let bobbins = User::new(1000, "Bobbins", 1000).with_home_dir("/home/bobbins"); users.add_user(bobbins); users.add_group(Group::new(100, "funkyppl"));
The exports get re-exported into the mock module, for simpler use
lines.
Using Mock Users
To set your program up to use either type of Users
table, make your
functions and structs accept a generic parameter that implements the Users
trait. Then, you can pass in a value of either Cache or Mock type.
Here’s a complete example:
use std::sync::Arc; use users::{Users, UsersCache, User}; use users::os::unix::UserExt; use users::mock::MockUsers; fn print_current_username<U: Users>(users: &mut U) { println!("Current user: {:?}", users.get_current_username()); } let mut users = MockUsers::with_current_uid(1001); users.add_user(User::new(1001, "fred", 101)); print_current_username(&mut users); let mut actual_users = UsersCache::new(); print_current_username(&mut actual_users);
Structs
Group | Information about a particular group. |
MockUsers | A mocking users table that you can add your own users and groups to. |
User | Information about a particular user. |
Traits
Groups | Trait for producers of groups. |
Users | Trait for producers of users. |
Type Definitions
gid_t | |
uid_t |