-
Notifications
You must be signed in to change notification settings - Fork 212
/
TokenMapSpec.hs
1169 lines (1020 loc) · 39.9 KB
/
TokenMapSpec.hs
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
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
494
495
496
497
498
499
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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{- HLINT ignore "Use camelCase" -}
{- HLINT ignore "Functor law" -}
module Cardano.Wallet.Primitive.Types.TokenMapSpec
( spec
) where
import Prelude
import Algebra.PartialOrd
( PartialOrd (..) )
import Cardano.Numeric.Util
( inAscendingPartialOrder )
import Cardano.Wallet.Primitive.Types.Hash
( Hash (..) )
import Cardano.Wallet.Primitive.Types.TokenMap
( AssetId (..)
, Flat (..)
, Lexicographic (..)
, Nested (..)
, TokenMap
, difference
)
import Cardano.Wallet.Primitive.Types.TokenMap.Gen
( AssetIdF (..)
, genAssetId
, genAssetIdLargeRange
, genTokenMap
, genTokenMapPartition
, genTokenMapSmallRange
, shrinkAssetId
, shrinkTokenMap
)
import Cardano.Wallet.Primitive.Types.TokenPolicy
( TokenName, TokenPolicyId, mkTokenName )
import Cardano.Wallet.Primitive.Types.TokenPolicy.Gen
( genTokenName, genTokenPolicyId, shrinkTokenName, shrinkTokenPolicyId )
import Cardano.Wallet.Primitive.Types.TokenQuantity
( TokenQuantity (..) )
import Cardano.Wallet.Primitive.Types.TokenQuantity.Gen
( genTokenQuantity
, genTokenQuantityPositive
, shrinkTokenQuantity
, shrinkTokenQuantityPositive
)
import Control.Monad
( replicateM )
import Data.Aeson
( FromJSON (..), ToJSON (..) )
import Data.Aeson.QQ
( aesonQQ )
import Data.Bifunctor
( bimap, first, second )
import Data.ByteString
( ByteString )
import Data.Either
( fromRight )
import Data.Function
( (&) )
import Data.List.NonEmpty
( NonEmpty (..) )
import Data.Maybe
( mapMaybe )
import Data.Proxy
( Proxy (..) )
import Data.Ratio
( (%) )
import Data.String.QQ
( s )
import Data.Text
( Text )
import Data.Text.Class
( fromText, toText )
import Data.Typeable
( Typeable )
import Fmt
( pretty )
import Numeric.Natural
( Natural )
import System.FilePath
( (</>) )
import Test.Hspec
( Expectation, Spec, describe, it, shouldBe )
import Test.Hspec.Core.QuickCheck
( modifyMaxSuccess )
import Test.Hspec.Extra
( parallel )
import Test.QuickCheck
( Arbitrary (..)
, Blind (..)
, CoArbitrary (..)
, Fun
, Function (..)
, Property
, Testable
, applyFun
, checkCoverage
, choose
, conjoin
, counterexample
, cover
, forAll
, forAllBlind
, frequency
, property
, scale
, (.||.)
, (===)
, (==>)
)
import Test.QuickCheck.Classes
( eqLaws, monoidLaws, ordLaws, semigroupLaws, semigroupMonoidLaws )
import Test.QuickCheck.Instances.ByteString
()
import Test.Utils.Laws
( testLawsMany )
import Test.Utils.Laws.PartialOrd
( partialOrdLaws )
import Test.Utils.Paths
( getTestData )
import qualified Cardano.Wallet.Primitive.Types.TokenMap as TokenMap
import qualified Cardano.Wallet.Primitive.Types.TokenQuantity as TokenQuantity
import qualified Data.Aeson.Types as Aeson
import qualified Data.Foldable as F
import qualified Data.List.NonEmpty as NE
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified Test.QuickCheck as QC
import qualified Test.Utils.Roundtrip as Roundtrip
spec :: Spec
spec =
describe "Token map properties" $
modifyMaxSuccess (const 1000) $ do
parallel $ describe "Class instances obey laws" $ do
testLawsMany @TokenMap
[ eqLaws
, monoidLaws
, partialOrdLaws
, semigroupLaws
, semigroupMonoidLaws
]
testLawsMany @(Lexicographic TokenMap)
[ eqLaws
, ordLaws
]
parallel $ describe
"All operations preserve the invariant: \
\all token quantities held within a map are non-zero" $ do
it "prop_arbitrary_invariant" $
property prop_arbitrary_invariant
it "prop_shrink_invariant" $
property prop_shrink_invariant
it "prop_empty_invariant" $
property prop_empty_invariant
it "prop_singleton_invariant" $
property prop_singleton_invariant
it "prop_fromFlatList_invariant" $
property prop_fromFlatList_invariant
it "prop_fromNestedList_invariant" $
property prop_fromNestedList_invariant
it "prop_add_invariant" $
property prop_add_invariant
it "prop_subtract_invariant" $
property prop_subtract_invariant
it "prop_difference_invariant" $
property prop_difference_invariant
it "prop_intersection_invariant" $
property prop_intersection_invariant
it "prop_setQuantity_invariant" $
property prop_setQuantity_invariant
it "prop_adjustQuantity_invariant" $
property prop_adjustQuantity_invariant
parallel $ describe "Construction and deconstruction" $ do
it "prop_fromFlatList" $
property prop_fromFlatList
it "prop_fromNestedList" $
property prop_fromNestedList
it "prop_empty_toFlatList" $
property prop_empty_toFlatList
it "prop_singleton_toFlatList" $
property prop_singleton_toFlatList
it "prop_toFlatList_fromFlatList" $
property prop_toFlatList_fromFlatList
it "prop_toNestedList_fromNestedList" $
property prop_toNestedList_fromNestedList
parallel $ describe "Filtering" $ do
it "prop_filter_conjoin" $
property prop_filter_conjoin
it "prop_filter_partition" $
property prop_filter_partition
it "prop_filter_twice" $
property prop_filter_twice
parallel $ describe "Arithmetic" $ do
it "prop_add_commutative" $
property prop_add_commutative
it "prop_add_associative" $
property prop_add_associative
it "prop_add_subtract_associative" $
property prop_add_subtract_associative
it "prop_subtract_null" $
property prop_subtract_null
it "prop_difference_zero (x - 0 = x)" $
property prop_difference_zero
it "prop_difference_zero2 (0 - x = 0)" $
property prop_difference_zero2
it "prop_difference_zero3 (x - x = 0)" $
property prop_difference_zero3
it "prop_difference_leq (x - y ⊆ x)" $
property prop_difference_leq
it "prop_difference_add ((x - y) + y ⊇ x)" $
property prop_difference_add
it "prop_difference_subtract" $
property prop_difference_subtract
it "prop_difference_equality" $
property prop_difference_equality
it "prop_intersection_associativity" $
property prop_intersection_associativity
it "prop_intersection_commutativity" $
property prop_intersection_commutativity
it "prop_intersection_empty" $
property prop_intersection_empty
it "prop_intersection_equality" $
property prop_intersection_equality
it "prop_intersection_identity" $
property prop_intersection_identity
it "prop_intersection_subset" $
property prop_intersection_subset
parallel $ describe "Quantities" $ do
it "prop_removeQuantity_isEmpty" $
property prop_removeQuantity_isEmpty
it "prop_setQuantity_getQuantity" $
property prop_setQuantity_getQuantity
it "prop_setQuantity_hasQuantity" $
property prop_setQuantity_hasQuantity
it "prop_adjustQuantity_getQuantity" $
property prop_adjustQuantity_getQuantity
it "prop_adjustQuantity_hasQuantity" $
property prop_adjustQuantity_hasQuantity
it "prop_maximumQuantity_all" $
property prop_maximumQuantity_all
parallel $ describe "Queries" $ do
it "prop_size_isEmpty" $ do
property prop_size_isEmpty
it "prop_size_toFlatList" $ do
property prop_size_toFlatList
parallel $ describe "Transformations" $ do
it "prop_mapAssetIds_identity" $ do
prop_mapAssetIds_identity & property
it "prop_mapAssetIds_composition" $ do
prop_mapAssetIds_composition & property
parallel $ describe "Partitioning assets" $ do
it "prop_equipartitionAssets_coverage" $
property prop_equipartitionAssets_coverage
it "prop_equipartitionAssets_length" $
property prop_equipartitionAssets_length
it "prop_equipartitionAssets_sizes" $
property prop_equipartitionAssets_sizes
it "prop_equipartitionAssets_sum" $
property prop_equipartitionAssets_sum
parallel $ describe "Partitioning quantities" $ do
it "prop_equipartitionQuantities_fair" $
property prop_equipartitionQuantities_fair
it "prop_equipartitionQuantities_length" $
property prop_equipartitionQuantities_length
it "prop_equipartitionQuantities_order" $
property prop_equipartitionQuantities_order
it "prop_equipartitionQuantities_sum" $
property prop_equipartitionQuantities_sum
parallel $ describe "Partitioning quantities with an upper bound" $ do
it "prop_equipartitionQuantitiesWithUpperBound_coverage" $
property prop_equipartitionQuantitiesWithUpperBound_coverage
it "prop_equipartitionQuantitiesWithUpperBound_length" $
property prop_equipartitionQuantitiesWithUpperBound_length
it "prop_equipartitionQuantitiesWithUpperBound_max" $
property prop_equipartitionQuantitiesWithUpperBound_max
it "prop_equipartitionQuantitiesWithUpperBound_order" $
property prop_equipartitionQuantitiesWithUpperBound_order
it "prop_equipartitionQuantitiesWithUpperBound_sum" $
property prop_equipartitionQuantitiesWithUpperBound_sum
parallel $ describe "Generating partitions" $ do
it "prop_genTokenMapPartition_fold" $
prop_genTokenMapPartition_fold & property
it "prop_genTokenMapPartition_length" $
prop_genTokenMapPartition_length & property
it "prop_genTokenMapPartition_nonPositive" $
prop_genTokenMapPartition_nonPositive & property
parallel $ describe "JSON serialization" $ do
describe "Roundtrip tests" $ do
testJson $ Proxy @(Flat TokenMap)
testJson $ Proxy @(Nested TokenMap)
describe "Negative tests" $ do
it "Zero-valued token quantity (from flat representation)"
testZeroValuedTokenQuantityFlat
it "Zero-valued token quantity (from nested representation)"
testZeroValuedTokenQuantityNested
it "Empty token list"
testEmptyTokenList
parallel $ describe "Textual serialization" $ do
it "Flat style" $
property testPrettyFlat
it "Nested style" $
property testPrettyNested
--------------------------------------------------------------------------------
-- Invariant properties
--------------------------------------------------------------------------------
-- Tests that all quantities within the given map are non-zero.
--
invariantHolds :: TokenMap -> Bool
invariantHolds b =
all TokenQuantity.isNonZero $ getQuantity <$> TokenMap.toFlatList b
where
getQuantity (_, q) = q
prop_arbitrary_invariant :: TokenMap -> Property
prop_arbitrary_invariant = property . invariantHolds
prop_shrink_invariant :: TokenMap -> Property
prop_shrink_invariant b = property $ all invariantHolds $ shrink b
prop_empty_invariant :: Property
prop_empty_invariant = property $ invariantHolds TokenMap.empty
prop_singleton_invariant :: (AssetId, TokenQuantity) -> Property
prop_singleton_invariant (asset, quantity) = property $
invariantHolds $ TokenMap.singleton asset quantity
prop_fromFlatList_invariant :: [(AssetId, TokenQuantity)] -> Property
prop_fromFlatList_invariant entries =
property $ invariantHolds $ TokenMap.fromFlatList entries
prop_fromNestedList_invariant
:: [(TokenPolicyId, NonEmpty (TokenName, TokenQuantity))] -> Property
prop_fromNestedList_invariant entries =
property $ invariantHolds $ TokenMap.fromNestedList entries
prop_add_invariant :: TokenMap -> TokenMap -> Property
prop_add_invariant b1 b2 = property $ invariantHolds $ TokenMap.add b1 b2
prop_subtract_invariant :: TokenMap -> TokenMap -> Property
prop_subtract_invariant m1 m2 = property $
m2 `leq` m1 ==> invariantHolds result
where
result =
case TokenMap.subtract m1 m2 of
Nothing -> error "prop_subtract_invariant"
Just r -> r
prop_difference_invariant :: TokenMap -> TokenMap -> Property
prop_difference_invariant m1 m2 =
property $ invariantHolds $ TokenMap.difference m1 m2
prop_intersection_invariant :: TokenMap -> TokenMap -> Property
prop_intersection_invariant m1 m2 =
property $ invariantHolds $ TokenMap.intersection m1 m2
prop_setQuantity_invariant
:: TokenMap -> AssetId -> TokenQuantity -> Property
prop_setQuantity_invariant b asset quantity = property $
invariantHolds $ TokenMap.setQuantity b asset quantity
prop_adjustQuantity_invariant :: TokenMap -> AssetId -> Property
prop_adjustQuantity_invariant b asset = property $
invariantHolds $ TokenMap.adjustQuantity b asset TokenQuantity.predZero
--------------------------------------------------------------------------------
-- Construction and deconstruction properties
--------------------------------------------------------------------------------
prop_fromFlatList :: [(AssetId, TokenQuantity)] -> Property
prop_fromFlatList assetQuantities = checkCoverage $ property $
cover 2 (length assetQuantities == length combinedAssetQuantities)
"Every asset has exactly one quantity" $
cover 20 (length assetQuantities > length combinedAssetQuantities)
"Some assets have more than one quantity" $
-- Check that multiple quantities for the same asset are combined
-- additively:
F.all (\(a, q) -> TokenMap.getQuantity tokenMap a == q)
combinedAssetQuantities
where
tokenMap = TokenMap.fromFlatList assetQuantities
combinedAssetQuantities =
Map.toList $ Map.fromListWith TokenQuantity.add assetQuantities
prop_fromNestedList
:: [(TokenPolicyId, NonEmpty (TokenName, TokenQuantity))]
-> Property
prop_fromNestedList assetQuantities = checkCoverage $ property $
cover 2 (length flattenedAssetQuantities == length combinedAssetQuantities)
"Every asset has exactly one quantity" $
cover 20 (length flattenedAssetQuantities > length combinedAssetQuantities)
"Some assets have more than one quantity" $
-- Check that multiple quantities for the same asset are combined
-- additively:
F.all (\(a, q) -> TokenMap.getQuantity tokenMap a == q)
combinedAssetQuantities
where
tokenMap = TokenMap.fromNestedList assetQuantities
combinedAssetQuantities = Map.toList $
Map.fromListWith TokenQuantity.add flattenedAssetQuantities
flattenedAssetQuantities =
[ (AssetId p t, q)
| (p, tq) <- fmap (fmap NE.toList) assetQuantities
, (t, q) <- tq
]
prop_empty_toFlatList :: Property
prop_empty_toFlatList =
TokenMap.toFlatList TokenMap.empty === []
prop_singleton_toFlatList
:: (AssetId, TokenQuantity) -> Property
prop_singleton_toFlatList entry@(asset, quantity) = property $
case TokenMap.toFlatList $ TokenMap.singleton asset quantity of
[] -> quantity === TokenQuantity.zero
[entryRetrieved] -> entryRetrieved === entry
_ -> error "prop_singleton_toFlatList"
prop_toFlatList_fromFlatList :: TokenMap -> Property
prop_toFlatList_fromFlatList b =
TokenMap.fromFlatList (TokenMap.toFlatList b) === b
prop_toNestedList_fromNestedList :: TokenMap -> Property
prop_toNestedList_fromNestedList b =
TokenMap.fromNestedList (TokenMap.toNestedList b) === b
--------------------------------------------------------------------------------
-- Filtering properties
--------------------------------------------------------------------------------
-- | Verify that all assets in the resulting filtered map satisfy the predicate.
prop_filter_conjoin :: Fun AssetIdF Bool -> TokenMap -> Property
prop_filter_conjoin f b =
let
as = TokenMap.getAssets $ TokenMap.filter (applyFun f . AssetIdF) b
in
Set.foldr ((&&) . applyFun f . AssetIdF) True as === True
-- | Verify that we can partition the token map using the predicate, and recover
-- the original map by computing the union of both partitions.
prop_filter_partition :: Fun AssetIdF Bool -> TokenMap -> Property
prop_filter_partition f b =
let
l = TokenMap.filter (applyFun f . AssetIdF) b
r = TokenMap.filter (not . applyFun f . AssetIdF) b
in
(l <> r) === b
-- | Verify that filtering twice has the same effect as filtering once.
prop_filter_twice :: Fun AssetIdF Bool -> TokenMap -> Property
prop_filter_twice f b =
let
once = TokenMap.filter (applyFun f . AssetIdF) b
twice = TokenMap.filter (applyFun f . AssetIdF) once
in
once === twice
--------------------------------------------------------------------------------
-- Arithmetic properties
--------------------------------------------------------------------------------
prop_add_commutative :: TokenMap -> TokenMap -> Property
prop_add_commutative b1 b2 =
b1 `TokenMap.add` b2 === b2 `TokenMap.add` b1
prop_add_associative :: TokenMap -> TokenMap -> TokenMap -> Property
prop_add_associative b1 b2 b3 = (===)
((b1 `TokenMap.add` b2) `TokenMap.add` b3)
(b1 `TokenMap.add` (b2 `TokenMap.add` b3))
prop_add_subtract_associative
:: TokenMap -> TokenMap -> TokenMap -> Property
prop_add_subtract_associative m1 m2 m3 =
m3 `leq` m2 ==> (===)
((m1 `TokenMap.add` m2) `TokenMap.subtract` m3)
(fmap (m1 `TokenMap.add`) (m2 `TokenMap.subtract` m3))
prop_subtract_null :: TokenMap -> Property
prop_subtract_null m =
m `TokenMap.subtract` m === Just TokenMap.empty
prop_difference_zero :: TokenMap -> Property
prop_difference_zero x =
x `difference` mempty === x
prop_difference_zero2 :: TokenMap-> Property
prop_difference_zero2 x =
mempty `difference` x === mempty
prop_difference_zero3 :: TokenMap -> Property
prop_difference_zero3 x =
x `difference` x === mempty
prop_difference_leq :: TokenMap -> TokenMap -> Property
prop_difference_leq x y = property $
x `difference` y `leq` x
-- (x - y) + y ⊇ x
prop_difference_add :: TokenMap -> TokenMap -> Property
prop_difference_add x y =
let
delta = x `difference` y
yAndDelta = delta `TokenMap.add` y
in
counterexample ("x - y = " <> show delta) $
counterexample ("(x - y) + y = " <> show yAndDelta) $
property $ x `leq` yAndDelta
prop_difference_subtract :: TokenMap -> TokenMap -> Property
prop_difference_subtract x y =
y `leq` x ==> (===)
(x `TokenMap.subtract` y)
(Just $ x `TokenMap.difference` y)
prop_difference_equality :: TokenMap -> TokenMap -> Property
prop_difference_equality x y = checkCoverage $
cover 5 (TokenMap.isNotEmpty xReduced)
"reduced maps are not empty" $
xReduced === yReduced
where
xReduced = x `TokenMap.unsafeSubtract` xExcess
yReduced = y `TokenMap.unsafeSubtract` yExcess
xExcess = x `TokenMap.difference` y
yExcess = y `TokenMap.difference` x
prop_intersection_associativity :: Property
prop_intersection_associativity =
forAllBlind gen $ \x ->
forAllBlind gen $ \y ->
forAllBlind gen $ \z ->
prop_inner x y z
where
gen = scale (* 4) genTokenMap
prop_inner x y z =
checkCoverage $
cover 50 (x /= y && y /= z)
"maps are different" $
cover 50 (TokenMap.isNotEmpty r1 && TokenMap.isNotEmpty r2)
"intersection is not empty" $
counterexample (pretty (Flat <$> [x, y, z, r1, r2])) $
r1 == r2
where
r1 = (x `TokenMap.intersection` y) `TokenMap.intersection` z
r2 = x `TokenMap.intersection` (y `TokenMap.intersection` z)
prop_intersection_commutativity :: Property
prop_intersection_commutativity =
forAllBlind gen $ \x ->
forAllBlind gen $ \y ->
prop_inner x y
where
gen = scale (* 2) genTokenMap
prop_inner x y =
checkCoverage $
cover 50 (x /= y)
"maps are different" $
cover 50 (TokenMap.isNotEmpty r1 && TokenMap.isNotEmpty r2)
"intersection is not empty" $
counterexample (pretty (Flat <$> [x, y, r1, r2])) $
r1 == r2
where
r1 = x `TokenMap.intersection` y
r2 = y `TokenMap.intersection` x
prop_intersection_empty :: TokenMap -> Property
prop_intersection_empty x =
checkCoverage $
cover 50 (TokenMap.isNotEmpty x)
"map is not empty" $
x `TokenMap.intersection` TokenMap.empty === TokenMap.empty
prop_intersection_equality :: Property
prop_intersection_equality =
forAllBlind gen $ \x ->
forAllBlind gen $ \y ->
prop_inner x y
where
gen = scale (* 2) genTokenMap
prop_inner x y =
checkCoverage $
cover 50 (x /= y)
"maps are different" $
cover 50 (TokenMap.isNotEmpty x && TokenMap.isNotEmpty y)
"maps are not empty" $
counterexample (pretty (Flat <$> [x, y, total])) $
conjoin
[ total `TokenMap.intersection` x === x
, total `TokenMap.intersection` y === y
]
where
total = x <> y
prop_intersection_identity :: TokenMap -> Property
prop_intersection_identity x =
checkCoverage $
cover 50 (TokenMap.isNotEmpty x)
"map is not empty" $
x `TokenMap.intersection` x === x
prop_intersection_subset :: Property
prop_intersection_subset =
forAllBlind gen $ \x ->
forAllBlind gen $ \y ->
prop_inner x y
where
gen = scale (* 2) genTokenMap
prop_inner x y =
checkCoverage $
cover 50 (x /= y)
"maps are different" $
cover 50 (TokenMap.isNotEmpty x && TokenMap.isNotEmpty y)
"maps are not empty" $
counterexample (pretty (Flat <$> [x, y, intersection])) $
conjoin
[ intersection `leq` x
, intersection `leq` y
]
where
intersection = x `TokenMap.intersection` y
--------------------------------------------------------------------------------
-- Quantity properties
--------------------------------------------------------------------------------
prop_removeQuantity_isEmpty :: TokenMap -> Property
prop_removeQuantity_isEmpty b =
F.foldl' TokenMap.removeQuantity b assets === TokenMap.empty
where
assets = fst <$> TokenMap.toFlatList b
prop_setQuantity_getQuantity
:: TokenMap -> AssetId -> TokenQuantity -> Property
prop_setQuantity_getQuantity b asset quantity =
TokenMap.getQuantity (TokenMap.setQuantity b asset quantity) asset
=== quantity
prop_setQuantity_hasQuantity
:: TokenMap -> AssetId -> TokenQuantity -> Property
prop_setQuantity_hasQuantity b asset quantity =
TokenMap.hasQuantity (TokenMap.setQuantity b asset quantity) asset
=== TokenQuantity.isNonZero quantity
prop_adjustQuantity_getQuantity
:: TokenMap -> AssetId -> Property
prop_adjustQuantity_getQuantity b asset =
TokenMap.getQuantity (TokenMap.adjustQuantity b asset adjust) asset
=== adjust quantityOriginal
where
quantityOriginal = TokenMap.getQuantity b asset
adjust = TokenQuantity.predZero
prop_adjustQuantity_hasQuantity
:: TokenMap -> AssetId -> Property
prop_adjustQuantity_hasQuantity b asset =
TokenMap.hasQuantity (TokenMap.adjustQuantity b asset adjust) asset
=== TokenQuantity.isNonZero (adjust quantityOriginal)
where
quantityOriginal = TokenMap.getQuantity b asset
adjust = TokenQuantity.predZero
prop_maximumQuantity_all
:: TokenMap -> Property
prop_maximumQuantity_all b =
property $ all (<= maxQ) (snd <$> TokenMap.toFlatList b)
where
maxQ = TokenMap.maximumQuantity b
--------------------------------------------------------------------------------
-- Queries
--------------------------------------------------------------------------------
prop_size_isEmpty :: TokenMap -> Property
prop_size_isEmpty m =
checkCoverage_size m $
if TokenMap.isEmpty m
then TokenMap.size m == 0
else TokenMap.size m > 0
prop_size_toFlatList :: TokenMap -> Property
prop_size_toFlatList m =
checkCoverage_size m $
TokenMap.size m === length (TokenMap.toFlatList m)
checkCoverage_size :: Testable prop => TokenMap -> (prop -> Property)
checkCoverage_size m
= checkCoverage
. cover 2 (TokenMap.size m == 0) "size == 0"
. cover 2 (TokenMap.size m == 1) "size == 1"
. cover 2 (TokenMap.size m == 2) "size == 2"
. cover 2 (TokenMap.size m >= 3) "size >= 3"
--------------------------------------------------------------------------------
-- Transformations
--------------------------------------------------------------------------------
prop_mapAssetIds_identity :: TokenMap -> Property
prop_mapAssetIds_identity m =
TokenMap.mapAssetIds id m === m
prop_mapAssetIds_composition
:: TokenMap -> Fun AssetId AssetId -> Fun AssetId AssetId -> Property
prop_mapAssetIds_composition m (applyFun -> f) (applyFun -> g) =
TokenMap.mapAssetIds f (TokenMap.mapAssetIds g m) ===
TokenMap.mapAssetIds (f . g) m
--------------------------------------------------------------------------------
-- Partitioning assets
--------------------------------------------------------------------------------
prop_equipartitionAssets_coverage
:: Blind (Large TokenMap) -> Property
prop_equipartitionAssets_coverage m = checkCoverage $
cover 4 (assetCount == 0)
"asset count = 0" $
cover 4 (assetCount == 1)
"asset count = 1" $
cover 20 (2 <= assetCount && assetCount <= 31)
"2 <= asset count <= 31" $
cover 20 (32 <= assetCount && assetCount <= 63)
"32 <= asset count <= 63"
True
where
assetCount = TokenMap.size $ getLarge $ getBlind m
prop_equipartitionAssets_length
:: Blind (Large TokenMap) -> NonEmpty () -> Property
prop_equipartitionAssets_length (Blind (Large m)) count =
NE.length (TokenMap.equipartitionAssets m count) === NE.length count
prop_equipartitionAssets_sizes
:: Blind (Large TokenMap) -> NonEmpty () -> Property
prop_equipartitionAssets_sizes (Blind (Large m)) count = (.||.)
(assetCountDifference == 0)
(assetCountDifference == 1)
where
assetCounts = TokenMap.size <$> results
assetCountMin = F.minimum assetCounts
assetCountMax = F.maximum assetCounts
assetCountDifference = assetCountMax - assetCountMin
results = TokenMap.equipartitionAssets m count
prop_equipartitionAssets_sum
:: Blind (Large TokenMap) -> NonEmpty () -> Property
prop_equipartitionAssets_sum (Blind (Large m)) count =
F.fold (TokenMap.equipartitionAssets m count) === m
--------------------------------------------------------------------------------
-- Partitioning quantities
--------------------------------------------------------------------------------
-- Test that token map quantities are equipartitioned fairly:
--
-- Each token quantity portion must be within unity of the ideal portion.
--
prop_equipartitionQuantities_fair :: TokenMap -> NonEmpty () -> Property
prop_equipartitionQuantities_fair m count = property $
isZeroOrOne maximumDifference
where
-- Here we take advantage of the fact that the resultant maps are sorted
-- into ascending order when compared with the 'leq' function.
--
-- Consequently:
--
-- - the head map will be the smallest;
-- - the last map will be the greatest.
--
-- Therefore, subtracting the head map from the last map will produce a map
-- where each token quantity is equal to the difference between:
--
-- - the smallest quantity of that token in the resulting maps;
-- - the greatest quantity of that token in the resulting maps.
--
differences :: TokenMap
differences = NE.last results `TokenMap.unsafeSubtract` NE.head results
isZeroOrOne :: TokenQuantity -> Bool
isZeroOrOne (TokenQuantity q) = q == 0 || q == 1
maximumDifference :: TokenQuantity
maximumDifference = TokenMap.maximumQuantity differences
results = TokenMap.equipartitionQuantities m count
prop_equipartitionQuantities_length :: TokenMap -> NonEmpty () -> Property
prop_equipartitionQuantities_length m count =
NE.length (TokenMap.equipartitionQuantities m count) === NE.length count
prop_equipartitionQuantities_order :: TokenMap -> NonEmpty () -> Property
prop_equipartitionQuantities_order m count = property $
inAscendingPartialOrder (TokenMap.equipartitionQuantities m count)
prop_equipartitionQuantities_sum :: TokenMap -> NonEmpty () -> Property
prop_equipartitionQuantities_sum m count =
F.fold (TokenMap.equipartitionQuantities m count) === m
--------------------------------------------------------------------------------
-- Partitioning quantities according to an upper bound
--------------------------------------------------------------------------------
-- | Computes the number of parts that 'equipartitionQuantitiesWithUpperBound'
-- should return.
--
equipartitionQuantitiesWithUpperBound_expectedLength
:: TokenMap -> TokenQuantity -> Int
equipartitionQuantitiesWithUpperBound_expectedLength
m (TokenQuantity maxQuantity) =
max 1 $ ceiling $ currentMaxQuantity % maxQuantity
where
TokenQuantity currentMaxQuantity = TokenMap.maximumQuantity m
prop_equipartitionQuantitiesWithUpperBound_coverage
:: TokenMap -> Positive TokenQuantity -> Property
prop_equipartitionQuantitiesWithUpperBound_coverage m (Positive maxQuantity) =
checkCoverage $
cover 4 (maxQuantity == TokenQuantity 1)
"Maximum allowable quantity == 1" $
cover 4 (maxQuantity == TokenQuantity 2)
"Maximum allowable quantity == 2" $
cover 8 (maxQuantity >= TokenQuantity 3)
"Maximum allowable quantity >= 3" $
cover 8 (expectedLength == 1)
"Expected number of parts == 1" $
cover 8 (expectedLength == 2)
"Expected number of parts == 2" $
cover 8 (expectedLength >= 3)
"Expected number of parts >= 3" $
property $ expectedLength > 0
where
expectedLength = equipartitionQuantitiesWithUpperBound_expectedLength
m maxQuantity
prop_equipartitionQuantitiesWithUpperBound_length
:: TokenMap -> Positive TokenQuantity -> Property
prop_equipartitionQuantitiesWithUpperBound_length m (Positive maxQuantity) =
length (TokenMap.equipartitionQuantitiesWithUpperBound m maxQuantity)
=== equipartitionQuantitiesWithUpperBound_expectedLength m maxQuantity
prop_equipartitionQuantitiesWithUpperBound_max
:: TokenMap -> Positive TokenQuantity -> Property
prop_equipartitionQuantitiesWithUpperBound_max m (Positive maxQuantity) =
checkCoverage $
cover 10 (maxResultQuantity == maxQuantity)
"At least one resultant token map has a maximal quantity" $
property $ maxResultQuantity <= maxQuantity
where
results = TokenMap.equipartitionQuantitiesWithUpperBound m maxQuantity
maxResultQuantity = F.maximum (TokenMap.maximumQuantity <$> results)
prop_equipartitionQuantitiesWithUpperBound_order
:: TokenMap -> Positive TokenQuantity -> Property
prop_equipartitionQuantitiesWithUpperBound_order m (Positive maxQuantity) =
property $ inAscendingPartialOrder
(TokenMap.equipartitionQuantitiesWithUpperBound m maxQuantity)
prop_equipartitionQuantitiesWithUpperBound_sum
:: TokenMap -> Positive TokenQuantity -> Property
prop_equipartitionQuantitiesWithUpperBound_sum m (Positive maxQuantity) =
F.fold (TokenMap.equipartitionQuantitiesWithUpperBound m maxQuantity) === m
--------------------------------------------------------------------------------
-- Generating partitions
--------------------------------------------------------------------------------
prop_genTokenMapPartition_fold
:: TokenMap -> QC.Positive (QC.Small Int) -> Property
prop_genTokenMapPartition_fold m (QC.Positive (QC.Small i)) =
forAll (genTokenMapPartition m i) $ (=== m) . F.fold
prop_genTokenMapPartition_length
:: TokenMap -> QC.Positive (QC.Small Int) -> Property
prop_genTokenMapPartition_length m (QC.Positive (QC.Small i)) =
forAll (genTokenMapPartition m i) $ (=== i) . F.length
prop_genTokenMapPartition_nonPositive
:: TokenMap -> QC.NonPositive (QC.Small Int) -> Property
prop_genTokenMapPartition_nonPositive m (QC.NonPositive (QC.Small i)) =
forAll (genTokenMapPartition m i) (=== pure m)
--------------------------------------------------------------------------------
-- JSON serialization tests
--------------------------------------------------------------------------------
failurePreamble :: String
failurePreamble = unwords
[ "Error in $:"
, "Error while deserializing token map from JSON:"
]
testZeroValuedTokenQuantityFlat :: Expectation
testZeroValuedTokenQuantityFlat =
Aeson.parseEither (parseJSON @(Flat TokenMap)) json `shouldBe`
Left message
where
policy = dummyTokenPolicyId 'A'
token = dummyTokenName "DUMMY-TOKEN"
json =
[aesonQQ|
[ { "policy_id": #{policy}
, "asset_name": #{token}
, "quantity": 0
}
]
|]
message = unwords
[ failurePreamble
, "Encountered zero-valued quantity for token"
, show (toText token)
, "within policy"
, show (toText policy) <> "."
]
testZeroValuedTokenQuantityNested :: Expectation
testZeroValuedTokenQuantityNested =
Aeson.parseEither (parseJSON @(Nested TokenMap)) json `shouldBe`
Left message
where
policy = dummyTokenPolicyId 'A'
token = dummyTokenName "DUMMY-TOKEN"
json =
[aesonQQ|
[ { "policy_id": #{policy}
, "tokens": [{"asset_name": #{token}, "quantity": 0}]
}
]
|]
message = unwords
[ failurePreamble
, "Encountered zero-valued quantity for token"
, show (toText token)
, "within policy"
, show (toText policy) <> "."
]
testEmptyTokenList :: Expectation
testEmptyTokenList =
Aeson.parseEither (parseJSON @(Nested TokenMap)) json `shouldBe`
Left message
where
policy = dummyTokenPolicyId 'A'
json = [aesonQQ|[{"policy_id": #{policy}, "tokens": []}]|]
message = unwords
[ failurePreamble
, "Encountered empty token list for policy"
, show (toText policy) <> "."
]
testJson
:: (Arbitrary a, ToJSON a, FromJSON a, Typeable a) => Proxy a -> Spec
testJson = Roundtrip.jsonRoundtripAndGolden testJsonDataDirectory
testJsonDataDirectory :: FilePath
testJsonDataDirectory =
($(getTestData)
</> "Cardano"
</> "Wallet"
</> "Primitive"
</> "Types"