go.mondoo.com/cnquery@v0.0.0-20231005093811-59568235f6ea/explorer/impact_test.go (about) 1 // Copyright (c) Mondoo, Inc. 2 // SPDX-License-Identifier: BUSL-1.1 3 4 package explorer 5 6 import ( 7 "encoding/json" 8 "testing" 9 10 "github.com/stretchr/testify/assert" 11 "github.com/stretchr/testify/require" 12 ) 13 14 func TestParsing(t *testing.T) { 15 tests := []struct { 16 title string 17 data string 18 res *Impact 19 }{ 20 { 21 "simple number", 22 "30", 23 &Impact{ 24 Value: &ImpactValue{Value: 30}, 25 }, 26 }, 27 { 28 "complex definition", 29 `{"weight": 20, "value": 40}`, 30 &Impact{ 31 Weight: 20, 32 Value: &ImpactValue{Value: 40}, 33 }, 34 }, 35 } 36 37 for i := range tests { 38 cur := tests[i] 39 t.Run(cur.title, func(t *testing.T) { 40 var res *Impact 41 err := json.Unmarshal([]byte(cur.data), &res) 42 require.NoError(t, err) 43 assert.Equal(t, cur.res, res) 44 }) 45 } 46 47 errTests := []struct { 48 title string 49 data string 50 err string 51 }{ 52 { 53 "invalid low impact", 54 "-1", 55 "impact must be between 0 and 100", 56 }, 57 { 58 "invalid high impact", 59 "101", 60 "impact must be between 0 and 100", 61 }, 62 { 63 "invalid low impact in complex struct", 64 `{"value": -1}`, 65 "impact must be between 0 and 100", 66 }, 67 { 68 "invalid high impact in complex struct", 69 `{"value": 101, "weight": 90}`, 70 "impact must be between 0 and 100", 71 }, 72 } 73 74 for i := range errTests { 75 cur := errTests[i] 76 t.Run(cur.title, func(t *testing.T) { 77 var res *Impact 78 err := json.Unmarshal([]byte(cur.data), &res) 79 assert.EqualError(t, err, cur.err) 80 }) 81 } 82 } 83 84 func TestMerging(t *testing.T) { 85 tests := []struct { 86 title string 87 base *Impact 88 main *Impact 89 res *Impact 90 }{ 91 { 92 "nil base", 93 nil, 94 &Impact{Value: &ImpactValue{Value: 20}}, 95 &Impact{Value: &ImpactValue{Value: 20}}, 96 }, 97 { 98 "empty base", 99 &Impact{}, 100 &Impact{Value: &ImpactValue{Value: 20}}, 101 &Impact{Value: &ImpactValue{Value: 20}}, 102 }, 103 { 104 "empty main", 105 &Impact{Value: &ImpactValue{Value: 20}}, 106 &Impact{}, 107 &Impact{Value: &ImpactValue{Value: 20}}, 108 }, 109 { 110 "inherit value", 111 &Impact{Value: &ImpactValue{Value: 20}}, 112 &Impact{Weight: 10, Scoring: ScoringSystem_AVERAGE}, 113 &Impact{ 114 Value: &ImpactValue{Value: 20}, 115 Weight: 10, Scoring: ScoringSystem_AVERAGE, 116 }, 117 }, 118 { 119 "inherit scoring (explicit)", 120 &Impact{Scoring: ScoringSystem_IGNORE_SCORE}, 121 &Impact{Scoring: ScoringSystem_SCORING_UNSPECIFIED, Value: &ImpactValue{Value: 78}}, 122 &Impact{Scoring: ScoringSystem_IGNORE_SCORE, Value: &ImpactValue{Value: 78}}, 123 }, 124 } 125 126 for i := range tests { 127 cur := tests[i] 128 t.Run(cur.title, func(t *testing.T) { 129 cur.main.AddBase(cur.base) 130 assert.Equal(t, cur.res, cur.main) 131 }) 132 } 133 }