-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlib.rs
99 lines (82 loc) · 2.21 KB
/
lib.rs
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
#[cfg(test)]
mod tests {
// Brings all of the non-test paths into scope. Neat!
use super::*;
// Indicates that this ia test function, and the test runner should treat this function as a test.
//
// We can also have non-test functions to perform common operations, so this annotation is needed.
#[test]
fn it_works() {
let result = 2 + 2;
// Macro that asserts two values are equal, according to PartialEq.
assert_eq!(result, 4);
}
#[test]
#[should_panic]
fn does_not_work() {
panic!("Make this test fail");
}
#[test]
fn larger_can_hold_smaller() {
let larger = Rectangle::new(8, 7);
let smaller = Rectangle::new(5, 1);
assert!(larger.can_hold(&smaller));
}
#[test]
fn smaller_cannot_hold_larger() {
let larger = Rectangle::new(8, 7);
let smaller = Rectangle::new(5, 1);
assert!(!smaller.can_hold(&larger));
}
#[test]
fn it_adds_two() {
let result = add_two(2);
assert_eq!(4, result, "Number did not add 2, value was {result}");
}
#[test]
#[should_panic(expected = "between 1 and 100, got 200")]
fn greater_than_100() {
Guess::new(200);
}
#[test]
fn using_result_in_tests() -> Result<(), String> {
if 2 + 2 == 4 {
Ok(())
} else {
Err(String::from("2 + 2 != 4"))
}
}
}
// Code is considered dead_code if it's only used within tests, which is fucking awesome.
// (Another option would be making this struct public)
#[allow(dead_code)]
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
#[allow(dead_code)]
impl Rectangle {
fn new(width: u32, height: u32) -> Rectangle {
Rectangle { width, height }
}
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
pub fn add_two(a: i32) -> i32 {
a + 2
}
#[allow(dead_code)]
struct Guess {
value: i32,
}
#[allow(dead_code)]
impl Guess {
fn new(value: i32) -> Guess {
if value < 1 || value > 100 {
panic!("Guess value must be between 1 and 100, got {}.", value);
}
Guess { value }
}
}