tests.rs 18.2 KB
Newer Older
1
// Copyright 2018-2021 Parity Technologies (UK) Ltd.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use super::Vec as StorageVec;
use crate::{
17
18
19
20
    collections::vec::IndexOutOfBounds,
    traits::{
        KeyPtr,
        SpreadLayout,
21
    },
22
    Lazy,
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
};
use ink_primitives::Key;

#[test]
fn new_vec_works() {
    // `StorageVec::new`
    let vec = <StorageVec<i32>>::new();
    assert!(vec.is_empty());
    assert_eq!(vec.len(), 0);
    assert_eq!(vec.get(0), None);
    assert!(vec.iter().next().is_none());
    // `StorageVec::default`
    let default = <StorageVec<i32> as Default>::default();
    assert!(default.is_empty());
    assert_eq!(default.len(), 0);
    assert_eq!(vec.get(0), None);
    assert!(default.iter().next().is_none());
    // `StorageVec::new` and `StorageVec::default` should be equal.
    assert_eq!(vec, default);
}

#[test]
fn from_iterator_works() {
    let some_primes = [1, 2, 3, 5, 7, 11, 13];
    assert_eq!(some_primes.iter().copied().collect::<StorageVec<_>>(), {
        let mut vec = StorageVec::new();
        for prime in &some_primes {
            vec.push(*prime)
        }
        vec
    });
}

#[test]
fn from_empty_iterator_works() {
    assert_eq!(
        [].iter().copied().collect::<StorageVec<i32>>(),
        StorageVec::new(),
    );
}

#[test]
fn first_last_of_empty() {
    let mut vec = <StorageVec<u8>>::new();
    assert_eq!(vec.first(), None);
    assert_eq!(vec.first_mut(), None);
    assert_eq!(vec.last(), None);
    assert_eq!(vec.last_mut(), None);
}

#[test]
fn push_pop_first_last_works() {
    /// Asserts conditions are met for the given storage vector.
    fn assert_vec<F, L>(vec: &StorageVec<u8>, len: u32, first: F, last: L)
    where
        F: Into<Option<u8>>,
        L: Into<Option<u8>>,
    {
        assert_eq!(vec.is_empty(), len == 0);
        assert_eq!(vec.len(), len);
        assert_eq!(vec.first().copied(), first.into());
        assert_eq!(vec.last().copied(), last.into());
    }

    let mut vec = StorageVec::new();
    assert_vec(&vec, 0, None, None);

    // Sequence of `push`
    vec.push(b'a');
    assert_vec(&vec, 1, b'a', b'a');
    vec.push(b'b');
    assert_vec(&vec, 2, b'a', b'b');
    vec.push(b'c');
    assert_vec(&vec, 3, b'a', b'c');
    vec.push(b'd');
    assert_vec(&vec, 4, b'a', b'd');

    // Sequence of `pop`
    assert_eq!(vec.pop(), Some(b'd'));
    assert_vec(&vec, 3, b'a', b'c');
    assert_eq!(vec.pop(), Some(b'c'));
    assert_vec(&vec, 2, b'a', b'b');
    assert_eq!(vec.pop(), Some(b'b'));
    assert_vec(&vec, 1, b'a', b'a');
    assert_eq!(vec.pop(), Some(b'a'));
    assert_vec(&vec, 0, None, None);

    // Pop from empty vector.
    assert_eq!(vec.pop(), None);
    assert_vec(&vec, 0, None, None);
}

#[test]
fn pop_drop_works() {
    let elems = [b'a', b'b', b'c', b'd'];
    let mut vec = vec_from_slice(&elems);
    assert_eq!(vec.pop_drop(), Some(()));
    assert_eq_slice(&vec, &elems[0..3]);
    assert_eq!(vec.pop_drop(), Some(()));
    assert_eq_slice(&vec, &elems[0..2]);
    assert_eq!(vec.pop_drop(), Some(()));
    assert_eq_slice(&vec, &elems[0..1]);
    assert_eq!(vec.pop_drop(), Some(()));
    assert_eq_slice(&vec, &[]);
    assert_eq!(vec.pop_drop(), None);
    assert_eq_slice(&vec, &[]);
}

#[test]
fn get_works() {
    let elems = [b'a', b'b', b'c', b'd'];
    let mut vec = vec_from_slice(&elems);
    for (n, mut expected) in elems.iter().copied().enumerate() {
        let n = n as u32;
        assert_eq!(vec.get(n), Some(&expected));
        assert_eq!(vec.get_mut(n), Some(&mut expected));
        assert_eq!(&vec[n], &expected);
        assert_eq!(&mut vec[n], &mut expected);
    }
    let len = vec.len();
    assert_eq!(vec.get(len), None);
    assert_eq!(vec.get_mut(len), None);
}

#[test]
#[should_panic(expected = "index out of bounds: the len is 3 but the index is 3")]
fn index_out_of_bounds_works() {
    let test_values = [b'a', b'b', b'c'];
    let vec = vec_from_slice(&test_values);
    let _ = &vec[test_values.len() as u32];
}

#[test]
#[should_panic(expected = "index out of bounds: the len is 3 but the index is 3")]
fn index_mut_out_of_bounds_works() {
    let test_values = [b'a', b'b', b'c'];
    let mut vec = vec_from_slice(&test_values);
    let _ = &mut vec[test_values.len() as u32];
}

#[test]
fn iter_next_works() {
    let elems = [b'a', b'b', b'c', b'd'];
    let vec = vec_from_slice(&elems);
    // Test iterator over `&T`:
    let mut iter = vec.iter();
    assert_eq!(iter.count(), 4);
    assert_eq!(iter.size_hint(), (4, Some(4)));
    assert_eq!(iter.next(), Some(&b'a'));
    assert_eq!(iter.size_hint(), (3, Some(3)));
    assert_eq!(iter.next(), Some(&b'b'));
    assert_eq!(iter.size_hint(), (2, Some(2)));
    assert_eq!(iter.count(), 2);
    assert_eq!(iter.next(), Some(&b'c'));
    assert_eq!(iter.size_hint(), (1, Some(1)));
    assert_eq!(iter.next(), Some(&b'd'));
    assert_eq!(iter.size_hint(), (0, Some(0)));
    assert_eq!(iter.count(), 0);
    assert_eq!(iter.next(), None);
    // Test iterator over `&mut T`:
    let mut vec = vec;
    let mut iter = vec.iter_mut();
    assert_eq!(iter.size_hint(), (4, Some(4)));
    assert_eq!(iter.next(), Some(&mut b'a'));
    assert_eq!(iter.size_hint(), (3, Some(3)));
    assert_eq!(iter.next(), Some(&mut b'b'));
    assert_eq!(iter.size_hint(), (2, Some(2)));
    assert_eq!(iter.next(), Some(&mut b'c'));
    assert_eq!(iter.size_hint(), (1, Some(1)));
    assert_eq!(iter.next(), Some(&mut b'd'));
    assert_eq!(iter.size_hint(), (0, Some(0)));
    assert_eq!(iter.next(), None);
    assert_eq!(iter.count(), 0);
}

#[test]
fn iter_nth_works() {
    let elems = [b'a', b'b', b'c', b'd'];
    let vec = vec_from_slice(&elems);
    // Test iterator over `&T`:
    let mut iter = vec.iter();
    assert_eq!(iter.count(), 4);
    assert_eq!(iter.size_hint(), (4, Some(4)));
    assert_eq!(iter.nth(1), Some(&b'b'));
    assert_eq!(iter.count(), 2);
    assert_eq!(iter.size_hint(), (2, Some(2)));
    assert_eq!(iter.nth(1), Some(&b'd'));
    assert_eq!(iter.size_hint(), (0, Some(0)));
    assert_eq!(iter.count(), 0);
    assert_eq!(iter.nth(1), None);
    // Test iterator over `&mut T`:
    let mut vec = vec;
    let mut iter = vec.iter_mut();
    assert_eq!(iter.size_hint(), (4, Some(4)));
    assert_eq!(iter.nth(1), Some(&mut b'b'));
    assert_eq!(iter.size_hint(), (2, Some(2)));
    assert_eq!(iter.nth(1), Some(&mut b'd'));
    assert_eq!(iter.size_hint(), (0, Some(0)));
    assert_eq!(iter.nth(1), None);
    assert_eq!(iter.count(), 0);
}

#[test]
fn iter_next_back_works() {
    let elems = [b'a', b'b', b'c', b'd'];
    let vec = vec_from_slice(&elems);
    // Test iterator over `&T`:
    let mut iter = vec.iter().rev();
    assert_eq!(iter.clone().count(), 4);
    assert_eq!(iter.next(), Some(&b'd'));
    assert_eq!(iter.next(), Some(&b'c'));
    assert_eq!(iter.clone().count(), 2);
    assert_eq!(iter.next(), Some(&b'b'));
    assert_eq!(iter.next(), Some(&b'a'));
    assert_eq!(iter.clone().count(), 0);
    assert_eq!(iter.next(), None);
    // Test iterator over `&mut T`:
    let mut vec = vec;
    let mut iter = vec.iter_mut().rev();
    assert_eq!(iter.next(), Some(&mut b'd'));
    assert_eq!(iter.next(), Some(&mut b'c'));
    assert_eq!(iter.next(), Some(&mut b'b'));
    assert_eq!(iter.next(), Some(&mut b'a'));
    assert_eq!(iter.next(), None);
    assert_eq!(iter.count(), 0);
}

#[test]
fn iter_nth_back_works() {
    let elems = [b'a', b'b', b'c', b'd'];
    let vec = vec_from_slice(&elems);
    // Test iterator over `&T`:
    let mut iter = vec.iter().rev();
    assert_eq!(iter.clone().count(), 4);
    assert_eq!(iter.nth(1), Some(&b'c'));
    assert_eq!(iter.clone().count(), 2);
    assert_eq!(iter.nth(1), Some(&b'a'));
    assert_eq!(iter.clone().count(), 0);
    assert_eq!(iter.nth(1), None);
    // Test iterator over `&mut T`:
    let mut vec = vec;
    let mut iter = vec.iter_mut().rev();
    assert_eq!(iter.nth(1), Some(&mut b'c'));
    assert_eq!(iter.nth(1), Some(&mut b'a'));
    assert_eq!(iter.nth(1), None);
    assert_eq!(iter.count(), 0);
}

/// Asserts that the the given ordered storage vector elements are equal to the
/// ordered elements of the given slice.
fn assert_eq_slice(vec: &StorageVec<u8>, slice: &[u8]) {
    assert_eq!(vec.len() as usize, slice.len());
    assert!(vec.iter().zip(slice.iter()).all(|(lhs, rhs)| *lhs == *rhs))
}

/// Creates a storage vector from the given slice.
fn vec_from_slice(slice: &[u8]) -> StorageVec<u8> {
    slice.iter().copied().collect::<StorageVec<u8>>()
}

#[test]
fn swap_works() {
    let elems = [b'a', b'b', b'c', b'd'];
    let mut vec = vec_from_slice(&elems);

    // Swap at same position is a no-op.
    for index in 0..elems.len() as u32 {
        vec.swap(index, index);
        assert_eq_slice(&vec, &elems);
    }

    // Swap first and second
    vec.swap(0, 1);
    assert_eq_slice(&vec, &[b'b', b'a', b'c', b'd']);
    // Swap third and last
    vec.swap(2, 3);
    assert_eq_slice(&vec, &[b'b', b'a', b'd', b'c']);
    // Swap first and last
    vec.swap(0, 3);
    assert_eq_slice(&vec, &[b'c', b'a', b'd', b'b']);
}

#[test]
#[should_panic]
fn swap_one_invalid_index() {
    let mut vec = vec_from_slice(&[b'a', b'b', b'c', b'd']);
    vec.swap(0, vec.len());
}

#[test]
#[should_panic]
fn swap_both_invalid_indices() {
    let mut vec = vec_from_slice(&[b'a', b'b', b'c', b'd']);
    vec.swap(vec.len(), vec.len());
}

#[test]
fn swap_remove_works() {
    let mut vec = vec_from_slice(&[b'a', b'b', b'c', b'd']);

    // Swap remove first element.
    assert_eq!(vec.swap_remove(0), Some(b'a'));
    assert_eq_slice(&vec, &[b'd', b'b', b'c']);
    // Swap remove middle element.
    assert_eq!(vec.swap_remove(1), Some(b'b'));
    assert_eq_slice(&vec, &[b'd', b'c']);
    // Swap remove last element.
    assert_eq!(vec.swap_remove(1), Some(b'c'));
    assert_eq_slice(&vec, &[b'd']);
    // Swap remove only element.
    assert_eq!(vec.swap_remove(0), Some(b'd'));
    assert_eq_slice(&vec, &[]);
    // Swap remove from empty vector.
    assert_eq!(vec.swap_remove(0), None);
    assert_eq_slice(&vec, &[]);
}

#[test]
fn swap_remove_drop_works() {
    let mut vec = vec_from_slice(&[b'a', b'b', b'c', b'd']);

    // Swap remove first element.
    assert_eq!(vec.swap_remove_drop(0), Some(()));
    assert_eq_slice(&vec, &[b'd', b'b', b'c']);
    // Swap remove middle element.
    assert_eq!(vec.swap_remove_drop(1), Some(()));
    assert_eq_slice(&vec, &[b'd', b'c']);
    // Swap remove last element.
    assert_eq!(vec.swap_remove_drop(1), Some(()));
    assert_eq_slice(&vec, &[b'd']);
    // Swap remove only element.
    assert_eq!(vec.swap_remove_drop(0), Some(()));
    assert_eq_slice(&vec, &[]);
    // Swap remove from empty vector.
    assert_eq!(vec.swap_remove_drop(0), None);
    assert_eq_slice(&vec, &[]);
}

#[test]
362
fn spread_layout_push_pull_works() -> ink_env::Result<()> {
363
    ink_env::test::run_test::<ink_env::DefaultEnvironment, _>(|_| {
364
        let vec1 = vec_from_slice(&[b'a', b'b', b'c', b'd']);
365
        let root_key = Key::from([0x42; 32]);
366
367
368
369
370
371
372
373
374
375
376
377
378
        SpreadLayout::push_spread(&vec1, &mut KeyPtr::from(root_key));
        // Load the pushed storage vector into another instance and check that
        // both instances are equal:
        let vec2 =
            <StorageVec<u8> as SpreadLayout>::pull_spread(&mut KeyPtr::from(root_key));
        assert_eq!(vec1, vec2);
        Ok(())
    })
}

#[test]
#[should_panic(expected = "encountered empty storage cell")]
fn spread_layout_clear_works() {
379
    ink_env::test::run_test::<ink_env::DefaultEnvironment, _>(|_| {
380
        let vec1 = vec_from_slice(&[b'a', b'b', b'c', b'd']);
381
        let root_key = Key::from([0x42; 32]);
382
383
384
385
386
387
388
389
390
391
392
393
394
395
        SpreadLayout::push_spread(&vec1, &mut KeyPtr::from(root_key));
        // It has already been asserted that a valid instance can be pulled
        // from contract storage after a push to the same storage region.
        //
        // Now clear the associated storage from `vec1` and check whether
        // loading another instance from this storage will panic since the
        // vector's length property cannot read a value:
        SpreadLayout::clear_spread(&vec1, &mut KeyPtr::from(root_key));
        let _ =
            <StorageVec<u8> as SpreadLayout>::pull_spread(&mut KeyPtr::from(root_key));
        Ok(())
    })
    .unwrap()
}
396
397
398

#[test]
fn set_works() {
399
    ink_env::test::run_test::<ink_env::DefaultEnvironment, _>(|_| {
400
401
402
403
404
405
406
        let mut vec = vec_from_slice(&[b'a', b'b', b'c', b'd']);
        let _ = vec.set(0, b'x').unwrap();
        let expected = vec_from_slice(&[b'x', b'b', b'c', b'd']);
        assert_eq!(vec, expected);
        Ok(())
    })
    .unwrap()
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
}

#[test]
fn set_fails_when_index_oob() {
    let mut vec = vec_from_slice(&[b'a']);
    let res = vec.set(1, b'x');
    assert_eq!(res, Err(IndexOutOfBounds));
}

#[test]
fn clear_works_on_filled_vec() {
    let mut vec = vec_from_slice(&[b'a', b'b', b'c', b'd']);
    vec.clear();
    assert!(vec.is_empty());
}

#[test]
fn clear_works_on_empty_vec() {
    let mut vec = vec_from_slice(&[]);
    vec.clear();
    assert!(vec.is_empty());
}
429
430
431

#[test]
#[should_panic(expected = "encountered empty storage cell")]
432
#[cfg(not(feature = "ink-experimental-engine"))]
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
fn storage_is_cleared_completely_after_pull_lazy() {
    ink_env::test::run_test::<ink_env::DefaultEnvironment, _>(|_| {
        // given
        let root_key = Key::from([0x42; 32]);
        let mut lazy_vec: Lazy<StorageVec<u32>> = Lazy::new(StorageVec::new());
        lazy_vec.push(13u32);
        lazy_vec.push(13u32);
        SpreadLayout::push_spread(&lazy_vec, &mut KeyPtr::from(root_key));
        let pulled_vec = <Lazy<StorageVec<u32>> as SpreadLayout>::pull_spread(
            &mut KeyPtr::from(root_key),
        );

        // when
        SpreadLayout::clear_spread(&pulled_vec, &mut KeyPtr::from(root_key));

        // then
        let contract_id = ink_env::test::get_current_contract_account_id::<
            ink_env::DefaultEnvironment,
        >()
        .expect("Cannot get contract id");
        let used_cells = ink_env::test::count_used_storage_cells::<
            ink_env::DefaultEnvironment,
        >(&contract_id)
        .expect("used cells must be returned");
        assert_eq!(used_cells, 0);
        let _ =
            *<Lazy<Lazy<u32>> as SpreadLayout>::pull_spread(&mut KeyPtr::from(root_key));

        Ok(())
    })
    .unwrap()
}

#[test]
#[should_panic(expected = "encountered empty storage cell")]
468
#[cfg(not(feature = "ink-experimental-engine"))]
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
fn drop_works() {
    ink_env::test::run_test::<ink_env::DefaultEnvironment, _>(|_| {
        let root_key = Key::from([0x42; 32]);

        // if the setup panics it should not cause the test to pass
        let setup_result = std::panic::catch_unwind(|| {
            let vec = vec_from_slice(&[b'a', b'b', b'c', b'd']);
            SpreadLayout::push_spread(&vec, &mut KeyPtr::from(root_key));
            let _ = <StorageVec<u8> as SpreadLayout>::pull_spread(&mut KeyPtr::from(
                root_key,
            ));
            // vec is dropped which should clear the cells
        });
        assert!(setup_result.is_ok(), "setup should not panic");

        let contract_id = ink_env::test::get_current_contract_account_id::<
            ink_env::DefaultEnvironment,
        >()
487
        .expect("Cannot get contract id");
488
489
490
491
492
493
494
495
496
497
498
499
        let used_cells = ink_env::test::count_used_storage_cells::<
            ink_env::DefaultEnvironment,
        >(&contract_id)
        .expect("used cells must be returned");
        assert_eq!(used_cells, 0);

        let _ =
            <StorageVec<u8> as SpreadLayout>::pull_spread(&mut KeyPtr::from(root_key));
        Ok(())
    })
    .unwrap()
}
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564

#[test]
#[should_panic(expected = "encountered empty storage cell")]
#[cfg(feature = "ink-experimental-engine")]
fn storage_is_cleared_completely_after_pull_lazy() {
    ink_env::test::run_test::<ink_env::DefaultEnvironment, _>(|_| {
        // given
        let root_key = Key::from([0x42; 32]);
        let mut lazy_vec: Lazy<StorageVec<u32>> = Lazy::new(StorageVec::new());
        lazy_vec.push(13u32);
        lazy_vec.push(13u32);
        SpreadLayout::push_spread(&lazy_vec, &mut KeyPtr::from(root_key));
        let pulled_vec = <Lazy<StorageVec<u32>> as SpreadLayout>::pull_spread(
            &mut KeyPtr::from(root_key),
        );

        // when
        SpreadLayout::clear_spread(&pulled_vec, &mut KeyPtr::from(root_key));

        // then
        let contract_id = ink_env::test::callee::<ink_env::DefaultEnvironment>();
        let used_cells = ink_env::test::count_used_storage_cells::<
            ink_env::DefaultEnvironment,
        >(&contract_id)
        .expect("used cells must be returned");
        assert_eq!(used_cells, 0);
        let _ =
            *<Lazy<Lazy<u32>> as SpreadLayout>::pull_spread(&mut KeyPtr::from(root_key));

        Ok(())
    })
    .unwrap()
}

#[test]
#[should_panic(expected = "encountered empty storage cell")]
#[cfg(feature = "ink-experimental-engine")]
fn drop_works() {
    ink_env::test::run_test::<ink_env::DefaultEnvironment, _>(|_| {
        let root_key = Key::from([0x42; 32]);

        // if the setup panics it should not cause the test to pass
        let setup_result = std::panic::catch_unwind(|| {
            let vec = vec_from_slice(&[b'a', b'b', b'c', b'd']);
            SpreadLayout::push_spread(&vec, &mut KeyPtr::from(root_key));
            let _ = <StorageVec<u8> as SpreadLayout>::pull_spread(&mut KeyPtr::from(
                root_key,
            ));
            // vec is dropped which should clear the cells
        });
        assert!(setup_result.is_ok(), "setup should not panic");

        let contract_id = ink_env::test::callee::<ink_env::DefaultEnvironment>();
        let used_cells = ink_env::test::count_used_storage_cells::<
            ink_env::DefaultEnvironment,
        >(&contract_id)
        .expect("used cells must be returned");
        assert_eq!(used_cells, 0);

        let _ =
            <StorageVec<u8> as SpreadLayout>::pull_spread(&mut KeyPtr::from(root_key));
        Ok(())
    })
    .unwrap()
}