about summary refs log blame commit diff
path: root/tvix/nix-compat/src/wire/ser/mock.rs
blob: 7104a94238ffa2d0822226a69cbff8148ef848b5 (plain) (tree)
1
2
3
4
5
6
7
8
9
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493








                                       
                                 


































































































































































































































































































































































































































































































                                                                                                    




                                                          













































































































































































                                                                                  
use std::collections::VecDeque;
use std::fmt;
use std::io;
use std::thread;

#[cfg(test)]
use ::proptest::prelude::TestCaseError;
use thiserror::Error;

use crate::wire::ProtocolVersion;

use super::NixWrite;

#[derive(Debug, Error, PartialEq, Eq, Clone)]
pub enum Error {
    #[error("custom error '{0}'")]
    Custom(String),
    #[error("unsupported data error '{0}'")]
    UnsupportedData(String),
    #[error("Invalid enum: {0}")]
    InvalidEnum(String),
    #[error("IO error {0} '{1}'")]
    IO(io::ErrorKind, String),
    #[error("wrong write: expected {0} got {1}")]
    WrongWrite(OperationType, OperationType),
    #[error("unexpected write: got an extra {0}")]
    ExtraWrite(OperationType),
    #[error("got an unexpected number {0} in write_number")]
    UnexpectedNumber(u64),
    #[error("got an unexpected slice '{0:?}' in write_slice")]
    UnexpectedSlice(Vec<u8>),
    #[error("got an unexpected display '{0:?}' in write_slice")]
    UnexpectedDisplay(String),
}

impl Error {
    pub fn unexpected_write_number(expected: OperationType) -> Error {
        Error::WrongWrite(expected, OperationType::WriteNumber)
    }

    pub fn extra_write_number() -> Error {
        Error::ExtraWrite(OperationType::WriteNumber)
    }

    pub fn unexpected_write_slice(expected: OperationType) -> Error {
        Error::WrongWrite(expected, OperationType::WriteSlice)
    }

    pub fn unexpected_write_display(expected: OperationType) -> Error {
        Error::WrongWrite(expected, OperationType::WriteDisplay)
    }
}

impl super::Error for Error {
    fn custom<T: fmt::Display>(msg: T) -> Self {
        Self::Custom(msg.to_string())
    }

    fn io_error(err: std::io::Error) -> Self {
        Self::IO(err.kind(), err.to_string())
    }

    fn unsupported_data<T: fmt::Display>(msg: T) -> Self {
        Self::UnsupportedData(msg.to_string())
    }

    fn invalid_enum<T: fmt::Display>(msg: T) -> Self {
        Self::InvalidEnum(msg.to_string())
    }
}

#[allow(clippy::enum_variant_names)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum OperationType {
    WriteNumber,
    WriteSlice,
    WriteDisplay,
}

impl fmt::Display for OperationType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::WriteNumber => write!(f, "write_number"),
            Self::WriteSlice => write!(f, "write_slice"),
            Self::WriteDisplay => write!(f, "write_display"),
        }
    }
}

#[allow(clippy::enum_variant_names)]
#[derive(Debug, Clone, PartialEq, Eq)]
enum Operation {
    WriteNumber(u64, Result<(), Error>),
    WriteSlice(Vec<u8>, Result<(), Error>),
    WriteDisplay(String, Result<(), Error>),
}

impl From<Operation> for OperationType {
    fn from(value: Operation) -> Self {
        match value {
            Operation::WriteNumber(_, _) => OperationType::WriteNumber,
            Operation::WriteSlice(_, _) => OperationType::WriteSlice,
            Operation::WriteDisplay(_, _) => OperationType::WriteDisplay,
        }
    }
}

pub struct Builder {
    version: ProtocolVersion,
    ops: VecDeque<Operation>,
}

impl Builder {
    pub fn new() -> Builder {
        Builder {
            version: Default::default(),
            ops: VecDeque::new(),
        }
    }

    pub fn version<V: Into<ProtocolVersion>>(&mut self, version: V) -> &mut Self {
        self.version = version.into();
        self
    }

    pub fn write_number(&mut self, value: u64) -> &mut Self {
        self.ops.push_back(Operation::WriteNumber(value, Ok(())));
        self
    }

    pub fn write_number_error(&mut self, value: u64, err: Error) -> &mut Self {
        self.ops.push_back(Operation::WriteNumber(value, Err(err)));
        self
    }

    pub fn write_slice(&mut self, value: &[u8]) -> &mut Self {
        self.ops
            .push_back(Operation::WriteSlice(value.to_vec(), Ok(())));
        self
    }

    pub fn write_slice_error(&mut self, value: &[u8], err: Error) -> &mut Self {
        self.ops
            .push_back(Operation::WriteSlice(value.to_vec(), Err(err)));
        self
    }

    pub fn write_display<D>(&mut self, value: D) -> &mut Self
    where
        D: fmt::Display,
    {
        let msg = value.to_string();
        self.ops.push_back(Operation::WriteDisplay(msg, Ok(())));
        self
    }

    pub fn write_display_error<D>(&mut self, value: D, err: Error) -> &mut Self
    where
        D: fmt::Display,
    {
        let msg = value.to_string();
        self.ops.push_back(Operation::WriteDisplay(msg, Err(err)));
        self
    }

    #[cfg(test)]
    fn write_operation_type(&mut self, op: OperationType) -> &mut Self {
        match op {
            OperationType::WriteNumber => self.write_number(10),
            OperationType::WriteSlice => self.write_slice(b"testing"),
            OperationType::WriteDisplay => self.write_display("testing"),
        }
    }

    #[cfg(test)]
    fn write_operation(&mut self, op: &Operation) -> &mut Self {
        match op {
            Operation::WriteNumber(value, Ok(_)) => self.write_number(*value),
            Operation::WriteNumber(value, Err(Error::UnexpectedNumber(_))) => {
                self.write_number(*value)
            }
            Operation::WriteNumber(_, Err(Error::ExtraWrite(OperationType::WriteNumber))) => self,
            Operation::WriteNumber(_, Err(Error::WrongWrite(op, OperationType::WriteNumber))) => {
                self.write_operation_type(*op)
            }
            Operation::WriteNumber(value, Err(Error::Custom(msg))) => {
                self.write_number_error(*value, Error::Custom(msg.clone()))
            }
            Operation::WriteNumber(value, Err(Error::IO(kind, msg))) => {
                self.write_number_error(*value, Error::IO(*kind, msg.clone()))
            }
            Operation::WriteSlice(value, Ok(_)) => self.write_slice(value),
            Operation::WriteSlice(value, Err(Error::UnexpectedSlice(_))) => self.write_slice(value),
            Operation::WriteSlice(_, Err(Error::ExtraWrite(OperationType::WriteSlice))) => self,
            Operation::WriteSlice(_, Err(Error::WrongWrite(op, OperationType::WriteSlice))) => {
                self.write_operation_type(*op)
            }
            Operation::WriteSlice(value, Err(Error::Custom(msg))) => {
                self.write_slice_error(value, Error::Custom(msg.clone()))
            }
            Operation::WriteSlice(value, Err(Error::IO(kind, msg))) => {
                self.write_slice_error(value, Error::IO(*kind, msg.clone()))
            }
            Operation::WriteDisplay(value, Ok(_)) => self.write_display(value),
            Operation::WriteDisplay(value, Err(Error::Custom(msg))) => {
                self.write_display_error(value, Error::Custom(msg.clone()))
            }
            Operation::WriteDisplay(value, Err(Error::IO(kind, msg))) => {
                self.write_display_error(value, Error::IO(*kind, msg.clone()))
            }
            Operation::WriteDisplay(value, Err(Error::UnexpectedDisplay(_))) => {
                self.write_display(value)
            }
            Operation::WriteDisplay(_, Err(Error::ExtraWrite(OperationType::WriteDisplay))) => self,
            Operation::WriteDisplay(_, Err(Error::WrongWrite(op, OperationType::WriteDisplay))) => {
                self.write_operation_type(*op)
            }
            s => panic!("Invalid operation {:?}", s),
        }
    }

    pub fn build(&mut self) -> Mock {
        Mock {
            version: self.version,
            ops: self.ops.clone(),
        }
    }
}

impl Default for Builder {
    fn default() -> Self {
        Self::new()
    }
}

pub struct Mock {
    version: ProtocolVersion,
    ops: VecDeque<Operation>,
}

impl Mock {
    #[cfg(test)]
    #[allow(dead_code)]
    async fn assert_operation(&mut self, op: Operation) {
        match op {
            Operation::WriteNumber(_, Err(Error::UnexpectedNumber(value))) => {
                assert_eq!(
                    self.write_number(value).await,
                    Err(Error::UnexpectedNumber(value))
                );
            }
            Operation::WriteNumber(value, res) => {
                assert_eq!(self.write_number(value).await, res);
            }
            Operation::WriteSlice(_, ref res @ Err(Error::UnexpectedSlice(ref value))) => {
                assert_eq!(self.write_slice(value).await, res.clone());
            }
            Operation::WriteSlice(value, res) => {
                assert_eq!(self.write_slice(&value).await, res);
            }
            Operation::WriteDisplay(_, ref res @ Err(Error::UnexpectedDisplay(ref value))) => {
                assert_eq!(self.write_display(value).await, res.clone());
            }
            Operation::WriteDisplay(value, res) => {
                assert_eq!(self.write_display(value).await, res);
            }
        }
    }

    #[cfg(test)]
    async fn prop_assert_operation(&mut self, op: Operation) -> Result<(), TestCaseError> {
        use ::proptest::prop_assert_eq;

        match op {
            Operation::WriteNumber(_, Err(Error::UnexpectedNumber(value))) => {
                prop_assert_eq!(
                    self.write_number(value).await,
                    Err(Error::UnexpectedNumber(value))
                );
            }
            Operation::WriteNumber(value, res) => {
                prop_assert_eq!(self.write_number(value).await, res);
            }
            Operation::WriteSlice(_, ref res @ Err(Error::UnexpectedSlice(ref value))) => {
                prop_assert_eq!(self.write_slice(value).await, res.clone());
            }
            Operation::WriteSlice(value, res) => {
                prop_assert_eq!(self.write_slice(&value).await, res);
            }
            Operation::WriteDisplay(_, ref res @ Err(Error::UnexpectedDisplay(ref value))) => {
                prop_assert_eq!(self.write_display(&value).await, res.clone());
            }
            Operation::WriteDisplay(value, res) => {
                prop_assert_eq!(self.write_display(&value).await, res);
            }
        }
        Ok(())
    }
}

impl NixWrite for Mock {
    type Error = Error;

    fn version(&self) -> ProtocolVersion {
        self.version
    }

    async fn write_number(&mut self, value: u64) -> Result<(), Self::Error> {
        match self.ops.pop_front() {
            Some(Operation::WriteNumber(expected, ret)) => {
                if value != expected {
                    return Err(Error::UnexpectedNumber(value));
                }
                ret
            }
            Some(op) => Err(Error::unexpected_write_number(op.into())),
            _ => Err(Error::ExtraWrite(OperationType::WriteNumber)),
        }
    }

    async fn write_slice(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
        match self.ops.pop_front() {
            Some(Operation::WriteSlice(expected, ret)) => {
                if buf != expected {
                    return Err(Error::UnexpectedSlice(buf.to_vec()));
                }
                ret
            }
            Some(op) => Err(Error::unexpected_write_slice(op.into())),
            _ => Err(Error::ExtraWrite(OperationType::WriteSlice)),
        }
    }

    async fn write_display<D>(&mut self, msg: D) -> Result<(), Self::Error>
    where
        D: fmt::Display + Send,
        Self: Sized,
    {
        let value = msg.to_string();
        match self.ops.pop_front() {
            Some(Operation::WriteDisplay(expected, ret)) => {
                if value != expected {
                    return Err(Error::UnexpectedDisplay(value));
                }
                ret
            }
            Some(op) => Err(Error::unexpected_write_display(op.into())),
            _ => Err(Error::ExtraWrite(OperationType::WriteDisplay)),
        }
    }
}

impl Drop for Mock {
    fn drop(&mut self) {
        // No need to panic again
        if thread::panicking() {
            return;
        }
        if let Some(op) = self.ops.front() {
            panic!("reader dropped with {op:?} operation still unread")
        }
    }
}

#[cfg(test)]
mod proptest {
    use std::io;

    use proptest::{
        prelude::{any, Arbitrary, BoxedStrategy, Just, Strategy},
        prop_oneof,
    };

    use super::{Error, Operation, OperationType};

    pub fn arb_write_number_operation() -> impl Strategy<Value = Operation> {
        (
            any::<u64>(),
            prop_oneof![
                Just(Ok(())),
                any::<u64>().prop_map(|v| Err(Error::UnexpectedNumber(v))),
                Just(Err(Error::WrongWrite(
                    OperationType::WriteSlice,
                    OperationType::WriteNumber
                ))),
                Just(Err(Error::WrongWrite(
                    OperationType::WriteDisplay,
                    OperationType::WriteNumber
                ))),
                any::<String>().prop_map(|s| Err(Error::Custom(s))),
                (any::<io::ErrorKind>(), any::<String>())
                    .prop_map(|(kind, msg)| Err(Error::IO(kind, msg))),
            ],
        )
            .prop_filter("same number", |(v, res)| match res {
                Err(Error::UnexpectedNumber(exp_v)) => v != exp_v,
                _ => true,
            })
            .prop_map(|(v, res)| Operation::WriteNumber(v, res))
    }

    pub fn arb_write_slice_operation() -> impl Strategy<Value = Operation> {
        (
            any::<Vec<u8>>(),
            prop_oneof![
                Just(Ok(())),
                any::<Vec<u8>>().prop_map(|v| Err(Error::UnexpectedSlice(v))),
                Just(Err(Error::WrongWrite(
                    OperationType::WriteNumber,
                    OperationType::WriteSlice
                ))),
                Just(Err(Error::WrongWrite(
                    OperationType::WriteDisplay,
                    OperationType::WriteSlice
                ))),
                any::<String>().prop_map(|s| Err(Error::Custom(s))),
                (any::<io::ErrorKind>(), any::<String>())
                    .prop_map(|(kind, msg)| Err(Error::IO(kind, msg))),
            ],
        )
            .prop_filter("same slice", |(v, res)| match res {
                Err(Error::UnexpectedSlice(exp_v)) => v != exp_v,
                _ => true,
            })
            .prop_map(|(v, res)| Operation::WriteSlice(v, res))
    }

    #[allow(dead_code)]
    pub fn arb_extra_write() -> impl Strategy<Value = Operation> {
        prop_oneof![
            any::<u64>().prop_map(|msg| {
                Operation::WriteNumber(msg, Err(Error::ExtraWrite(OperationType::WriteNumber)))
            }),
            any::<Vec<u8>>().prop_map(|msg| {
                Operation::WriteSlice(msg, Err(Error::ExtraWrite(OperationType::WriteSlice)))
            }),
            any::<String>().prop_map(|msg| {
                Operation::WriteDisplay(msg, Err(Error::ExtraWrite(OperationType::WriteDisplay)))
            }),
        ]
    }

    pub fn arb_write_display_operation() -> impl Strategy<Value = Operation> {
        (
            any::<String>(),
            prop_oneof![
                Just(Ok(())),
                any::<String>().prop_map(|v| Err(Error::UnexpectedDisplay(v))),
                Just(Err(Error::WrongWrite(
                    OperationType::WriteNumber,
                    OperationType::WriteDisplay
                ))),
                Just(Err(Error::WrongWrite(
                    OperationType::WriteSlice,
                    OperationType::WriteDisplay
                ))),
                any::<String>().prop_map(|s| Err(Error::Custom(s))),
                (any::<io::ErrorKind>(), any::<String>())
                    .prop_map(|(kind, msg)| Err(Error::IO(kind, msg))),
            ],
        )
            .prop_filter("same string", |(v, res)| match res {
                Err(Error::UnexpectedDisplay(exp_v)) => v != exp_v,
                _ => true,
            })
            .prop_map(|(v, res)| Operation::WriteDisplay(v, res))
    }

    pub fn arb_operation() -> impl Strategy<Value = Operation> {
        prop_oneof![
            arb_write_number_operation(),
            arb_write_slice_operation(),
            arb_write_display_operation(),
        ]
    }

    impl Arbitrary for Operation {
        type Parameters = ();
        type Strategy = BoxedStrategy<Operation>;

        fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
            arb_operation().boxed()
        }
    }
}

#[cfg(test)]
mod test {
    use hex_literal::hex;
    use proptest::prelude::any;
    use proptest::prelude::TestCaseError;
    use proptest::proptest;

    use crate::wire::ser::mock::proptest::arb_extra_write;
    use crate::wire::ser::mock::Operation;
    use crate::wire::ser::mock::OperationType;
    use crate::wire::ser::Error as _;
    use crate::wire::ser::NixWrite;

    use super::{Builder, Error};

    #[tokio::test]
    async fn write_number() {
        let mut mock = Builder::new().write_number(10).build();
        mock.write_number(10).await.unwrap();
    }

    #[tokio::test]
    async fn write_number_error() {
        let mut mock = Builder::new()
            .write_number_error(10, Error::custom("bad number"))
            .build();
        assert_eq!(
            Err(Error::custom("bad number")),
            mock.write_number(10).await
        );
    }

    #[tokio::test]
    async fn write_number_unexpected() {
        let mut mock = Builder::new().write_slice(b"").build();
        assert_eq!(
            Err(Error::unexpected_write_number(OperationType::WriteSlice)),
            mock.write_number(11).await
        );
    }

    #[tokio::test]
    async fn write_number_unexpected_number() {
        let mut mock = Builder::new().write_number(10).build();
        assert_eq!(
            Err(Error::UnexpectedNumber(11)),
            mock.write_number(11).await
        );
    }

    #[tokio::test]
    async fn extra_write_number() {
        let mut mock = Builder::new().build();
        assert_eq!(
            Err(Error::ExtraWrite(OperationType::WriteNumber)),
            mock.write_number(11).await
        );
    }

    #[tokio::test]
    async fn write_slice() {
        let mut mock = Builder::new()
            .write_slice(&[])
            .write_slice(&hex!("0000 1234 5678 9ABC DEFF"))
            .build();
        mock.write_slice(&[]).await.expect("write_slice empty");
        mock.write_slice(&hex!("0000 1234 5678 9ABC DEFF"))
            .await
            .expect("write_slice");
    }

    #[tokio::test]
    async fn write_slice_error() {
        let mut mock = Builder::new()
            .write_slice_error(&[], Error::custom("bad slice"))
            .build();
        assert_eq!(Err(Error::custom("bad slice")), mock.write_slice(&[]).await);
    }

    #[tokio::test]
    async fn write_slice_unexpected() {
        let mut mock = Builder::new().write_number(10).build();
        assert_eq!(
            Err(Error::unexpected_write_slice(OperationType::WriteNumber)),
            mock.write_slice(b"").await
        );
    }

    #[tokio::test]
    async fn write_slice_unexpected_slice() {
        let mut mock = Builder::new().write_slice(b"").build();
        assert_eq!(
            Err(Error::UnexpectedSlice(b"bad slice".to_vec())),
            mock.write_slice(b"bad slice").await
        );
    }

    #[tokio::test]
    async fn extra_write_slice() {
        let mut mock = Builder::new().build();
        assert_eq!(
            Err(Error::ExtraWrite(OperationType::WriteSlice)),
            mock.write_slice(b"extra slice").await
        );
    }

    #[tokio::test]
    async fn write_display() {
        let mut mock = Builder::new().write_display("testing").build();
        mock.write_display("testing").await.unwrap();
    }

    #[tokio::test]
    async fn write_display_error() {
        let mut mock = Builder::new()
            .write_display_error("testing", Error::custom("bad number"))
            .build();
        assert_eq!(
            Err(Error::custom("bad number")),
            mock.write_display("testing").await
        );
    }

    #[tokio::test]
    async fn write_display_unexpected() {
        let mut mock = Builder::new().write_number(10).build();
        assert_eq!(
            Err(Error::unexpected_write_display(OperationType::WriteNumber)),
            mock.write_display("").await
        );
    }

    #[tokio::test]
    async fn write_display_unexpected_display() {
        let mut mock = Builder::new().write_display("").build();
        assert_eq!(
            Err(Error::UnexpectedDisplay("bad display".to_string())),
            mock.write_display("bad display").await
        );
    }

    #[tokio::test]
    async fn extra_write_display() {
        let mut mock = Builder::new().build();
        assert_eq!(
            Err(Error::ExtraWrite(OperationType::WriteDisplay)),
            mock.write_display("extra slice").await
        );
    }

    #[test]
    #[should_panic]
    fn operations_left() {
        let _ = Builder::new().write_number(10).build();
    }

    #[test]
    fn proptest_mock() {
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap();
        proptest!(|(
            operations in any::<Vec<Operation>>(),
            extra_operations in proptest::collection::vec(arb_extra_write(), 0..3)
            )| {
            rt.block_on(async {
                let mut builder = Builder::new();
                for op in operations.iter() {
                    builder.write_operation(op);
                }
                for op in extra_operations.iter() {
                    builder.write_operation(op);
                }
                let mut mock = builder.build();
                for op in operations {
                    mock.prop_assert_operation(op).await?;
                }
                for op in extra_operations {
                    mock.prop_assert_operation(op).await?;
                }
                Ok(()) as Result<(), TestCaseError>
            })?;
        });
    }
}