summaryrefslogtreecommitdiffstats
path: root/vendor/derive_builder/tests/try_setter.rs
blob: 28f6a01c0289fb5b2e4cfd2ceedd7640100c6071 (plain)
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
#[macro_use]
extern crate derive_builder;

use std::convert::TryFrom;
use std::net::{AddrParseError, IpAddr};
use std::str::FromStr;
use std::string::ToString;

#[derive(Debug, Clone, PartialEq)]
pub struct MyAddr(IpAddr);

impl From<IpAddr> for MyAddr {
    fn from(v: IpAddr) -> Self {
        MyAddr(v)
    }
}

impl<'a> TryFrom<&'a str> for MyAddr {
    type Error = AddrParseError;

    fn try_from(v: &str) -> Result<Self, Self::Error> {
        Ok(MyAddr(v.parse()?))
    }
}

#[derive(Debug, PartialEq, Builder)]
#[builder(try_setter, setter(into))]
struct Lorem {
    pub source: MyAddr,
    pub dest: MyAddr,
}

#[derive(Debug, PartialEq, Builder)]
#[builder(try_setter, setter(into, prefix = "set"))]
struct Ipsum {
    pub source: MyAddr,
}

fn exact_helper() -> Result<Lorem, LoremBuilderError> {
    LoremBuilder::default()
        .source(IpAddr::from_str("1.2.3.4").unwrap())
        .dest(IpAddr::from_str("0.0.0.0").unwrap())
        .build()
}

fn try_helper() -> Result<Lorem, LoremBuilderError> {
    LoremBuilder::default()
        .try_source("1.2.3.4")
        .map_err(|e| e.to_string())?
        .try_dest("0.0.0.0")
        .map_err(|e| e.to_string())?
        .build()
}

#[test]
fn infallible_set() {
    let _ = LoremBuilder::default()
        .source(IpAddr::from_str("1.2.3.4").unwrap())
        .dest(IpAddr::from_str("0.0.0.0").unwrap())
        .build();
}

#[test]
fn fallible_set() {
    let mut builder = LoremBuilder::default();
    let try_result = builder.try_source("1.2.3.4");
    let built = try_result
        .expect("Passed well-formed address")
        .dest(IpAddr::from_str("0.0.0.0").unwrap())
        .build()
        .unwrap();
    assert_eq!(built, exact_helper().unwrap());
}

#[test]
fn with_helper() {
    assert_eq!(exact_helper().unwrap(), try_helper().unwrap());
}

#[test]
fn renamed() {
    IpsumBuilder::default()
        .try_set_source("0.0.0.0")
        .unwrap()
        .build()
        .expect("All fields were provided");
}