-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlib.rs
More file actions
131 lines (111 loc) · 3.02 KB
/
lib.rs
File metadata and controls
131 lines (111 loc) · 3.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#[allow(dead_code)]
pub struct User {
username: String,
password: String,
}
pub trait OpenAuth {
fn validate(&self, user: &User) -> bool;
fn is_user_locked(&self, user: &User) -> bool;
}
pub trait Logger {
fn log(&self, message: &str);
}
pub fn login<A: OpenAuth, L: Logger>(auth: &A, logger: &L, user: &User) -> Result<String, String> {
if user.username.len() < 5 {
return Err("Username too short".to_string());
}
if auth.is_user_locked(user) {
return Err("Account is locked".to_string());
}
if auth.validate(user) {
logger.log(&format!("User {} logged in", user.username));
Ok(format!("Welcome, {}!", user.username))
} else {
Err("Invalid credentials".to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
struct MockAuth {
locked: bool,
valid: bool,
}
impl OpenAuth for MockAuth {
fn validate(&self, _: &User) -> bool {
self.valid
}
fn is_user_locked(&self, _: &User) -> bool {
self.locked
}
}
struct TestLogger {
pub messages: std::cell::RefCell<Vec<String>>,
}
impl Logger for TestLogger {
fn log(&self, message: &str) {
self.messages.borrow_mut().push(message.to_string());
}
}
#[test]
fn test_successful_login_with_logging() {
let auth = MockAuth {
locked: false,
valid: true,
};
let logger = TestLogger {
messages: std::cell::RefCell::new(vec![]),
};
let result = login(
&auth,
&logger,
&User {
username: "Billi Geyts".to_string(),
password: "1976".to_string(),
},
);
assert!(result.is_ok());
let logs = logger.messages.borrow();
assert_eq!(logs.len(), 1);
assert!(logs[0].contains("Billi Geyts"));
}
#[test]
fn test_login_fails_for_locked_account() {
let auth = MockAuth {
locked: true,
valid: true,
};
let logger = TestLogger {
messages: std::cell::RefCell::new(vec![]),
};
let result = login(
&auth,
&logger,
&User {
username: "Jan Claud".to_string(),
password: "1Dome".to_string(),
},
);
assert_eq!(result, Err("Account is locked".to_string()));
assert!(logger.messages.borrow().is_empty());
}
#[test]
fn test_short_username_rejected_before_auth() {
let auth = MockAuth {
locked: false,
valid: true,
};
let logger = TestLogger {
messages: std::cell::RefCell::new(vec![]),
};
let result = login(
&auth,
&logger,
&User {
username: "r".to_string(),
password: "secret".to_string(),
},
);
assert_eq!(result, Err("Username too short".to_string()));
}
}