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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
use crate::jormungandr::{JormungandrRest, MemPoolCheck, RestError};
use chain_impl_mockchain::{fragment::FragmentId, key::Hash};
use jormungandr_lib::interfaces::{
    FragmentRejectionReason, FragmentStatus, FragmentsProcessingSummary,
};

pub struct FragmentLogVerifier {
    rest: JormungandrRest,
}

impl FragmentLogVerifier {
    pub fn new(rest: JormungandrRest) -> Self {
        Self { rest }
    }

    pub fn assert_size(self, size: usize) -> Self {
        assert_eq!(
            self.rest.fragment_logs().unwrap().len(),
            size,
            "only {size} transactions should be in fragment log"
        );
        self
    }

    pub fn assert_contains_only(self, hash: &Hash) -> Self {
        assert_eq!(
            self.rest
                .fragment_logs()
                .unwrap()
                .values()
                .next()
                .unwrap()
                .fragment_id()
                .into_hash(),
            *hash,
            "transaction not found in fragment log"
        );
        self
    }

    pub fn assert_empty(self) -> Self {
        assert_eq!(
            self.rest.fragment_logs().unwrap().len(),
            0,
            "none transactions should be in fragment log"
        );
        self
    }

    pub fn assert_all_valid(self, mem_pool_checks: &[MemPoolCheck]) -> Self {
        let ids: Vec<String> = mem_pool_checks
            .iter()
            .map(|x| x.fragment_id().to_string())
            .collect();
        let statuses = self.rest.fragments_statuses(ids.clone()).unwrap();

        assert_eq!(ids.len(), statuses.len());

        ids.iter().for_each(|id| match statuses.get(id) {
            Some(status) => self.assert_in_block(status),
            None => panic!("{} not found", id),
        });
        self
    }

    pub fn assert_valid(self, mem_pool_check: &MemPoolCheck) -> Self {
        let ids = vec![mem_pool_check.fragment_id().to_string()];

        let statuses = self.rest.fragments_statuses(ids.clone()).unwrap();

        assert_eq!(ids.len(), statuses.len());

        ids.iter().for_each(|id| match statuses.get(id) {
            Some(status) => self.assert_in_block(status),
            None => panic!("{} not found", id),
        });
        self
    }

    pub fn assert_not_exist(self, mem_pool_check: &MemPoolCheck) -> Self {
        let ids = vec![mem_pool_check.fragment_id().to_string()];

        let statuses = self.rest.fragments_statuses(ids).unwrap();

        assert_eq!(statuses.len(), 0);
        self
    }

    pub fn assert_invalid(self, mem_pool_check: &MemPoolCheck) -> Self {
        let ids = vec![mem_pool_check.fragment_id().to_string()];
        let statuses = self.rest.fragments_statuses(ids.clone()).unwrap();
        assert_eq!(ids.len(), statuses.len());

        ids.iter().for_each(|id| match statuses.get(id) {
            Some(status) => self.assert_not_in_block(status),
            None => panic!("{} not found", id),
        });
        self
    }

    pub fn assert_no_fragments(self) -> Self {
        let fragment_logs = self.rest.fragment_logs().unwrap();
        assert!(fragment_logs.is_empty());
        self
    }

    pub fn assert_in_block(&self, fragment_status: &FragmentStatus) {
        match fragment_status {
            FragmentStatus::InABlock { .. } => (),
            _ => panic!("should be in block '{:?}'", fragment_status),
        };
    }

    pub fn assert_not_in_block(&self, fragment_status: &FragmentStatus) {
        let in_block = matches!(fragment_status, FragmentStatus::InABlock { .. });
        assert!(!in_block, "should NOT be in block '{:?}'", fragment_status);
    }

    pub fn assert_invalid_id(self, id: String, prefix: &str) -> Self {
        let statuses = self.rest.fragments_statuses(vec![id.clone()]).unwrap();
        assert_eq!(1, statuses.len());

        let invalid_id = statuses.get(&id);

        match invalid_id {
            Some(status) => self.assert_not_in_block(status),
            None => panic!("Assert Error: {}", prefix),
        };

        self
    }

    pub fn assert_single_id(self, id: String, prefix: &str) -> Self {
        let statuses = self.rest.fragments_statuses(vec![id.clone()]).unwrap();

        assert_eq!(1, statuses.len());

        let alice_tx_status = statuses.get(&id);

        match alice_tx_status {
            Some(status) => self.assert_in_block(status),
            None => panic!("Assert Error: {}", prefix),
        };
        self
    }

    pub fn assert_multiple_ids(self, ids: Vec<String>, prefix: &str) -> Self {
        let statuses = self.rest.fragments_statuses(ids.clone()).unwrap();

        assert_eq!(ids.len(), statuses.len());

        ids.iter().for_each(|id| match statuses.get(id) {
            Some(status) => self.assert_in_block(status),
            None => panic!("{}", prefix),
        });
        self
    }

    pub fn assert_empty_ids(self, ids: Vec<String>, prefix: &str) -> Self {
        assert!(
            self.rest.fragments_statuses(ids).is_err(),
            "{} - expected failure",
            prefix
        );
        self
    }
}

pub fn assert_accepted_rejected(
    accepted: Vec<FragmentId>,
    rejected: Vec<(FragmentId, FragmentRejectionReason)>,
    result: Result<FragmentsProcessingSummary, RestError>,
) -> Vec<MemPoolCheck> {
    match result.err().unwrap() {
        RestError::NonSuccessErrorCode {
            checks,
            status,
            response,
        } => {
            let summary: FragmentsProcessingSummary = serde_json::from_str(&response).unwrap();
            if !rejected.is_empty() {
                assert_eq!(status, reqwest::StatusCode::BAD_REQUEST);
            }
            assert_eq!(summary.accepted, accepted);
            assert_eq!(
                summary
                    .rejected
                    .iter()
                    .map(|x| (x.id, x.reason.clone()))
                    .collect::<Vec<(FragmentId, FragmentRejectionReason)>>(),
                rejected
            );

            checks
        }
        _ => panic!("wrong error code"),
    }
}

pub fn assert_bad_request(
    result: Result<FragmentsProcessingSummary, RestError>,
) -> Vec<MemPoolCheck> {
    match result.err().unwrap() {
        RestError::NonSuccessErrorCode { status, checks, .. } => {
            assert_eq!(status, reqwest::StatusCode::BAD_REQUEST);
            checks
        }
        _ => panic!("unexcepted error"),
    }
}