|
| 1 | +package utils |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "github.com/dl1998/go-logging/internal/testutils" |
| 6 | + "net/http" |
| 7 | + "testing" |
| 8 | +) |
| 9 | + |
| 10 | +var ( |
| 11 | + testStruct = struct { |
| 12 | + private string |
| 13 | + Int int |
| 14 | + Int8 int8 |
| 15 | + Int16 int16 |
| 16 | + Int32 int32 |
| 17 | + Int64 int64 |
| 18 | + Uint uint |
| 19 | + Uint8 uint8 |
| 20 | + Uint16 uint16 |
| 21 | + Uint32 uint32 |
| 22 | + Uint64 uint64 |
| 23 | + Float32 float32 |
| 24 | + Float64 float64 |
| 25 | + Bool bool |
| 26 | + String string |
| 27 | + Header http.Header |
| 28 | + CustomStruct CustomStruct |
| 29 | + }{ |
| 30 | + private: "private", |
| 31 | + Int: -1, |
| 32 | + Int8: -8, |
| 33 | + Int16: -16, |
| 34 | + Int32: -32, |
| 35 | + Int64: -64, |
| 36 | + Uint: 1, |
| 37 | + Uint8: 8, |
| 38 | + Uint16: 16, |
| 39 | + Uint32: 32, |
| 40 | + Uint64: 64, |
| 41 | + Float32: 32.00, |
| 42 | + Float64: 64.00, |
| 43 | + Bool: true, |
| 44 | + String: "string", |
| 45 | + Header: http.Header{"key": []string{"value"}}, |
| 46 | + CustomStruct: CustomStruct{Field: "custom field"}, |
| 47 | + } |
| 48 | +) |
| 49 | + |
| 50 | +type CustomStruct struct { |
| 51 | + Field string |
| 52 | +} |
| 53 | + |
| 54 | +func (customStruct *CustomStruct) String() string { |
| 55 | + return customStruct.Field |
| 56 | +} |
| 57 | + |
| 58 | +// TestStructToMap tests that StructToMap converts a struct to a map. |
| 59 | +func TestStructToMap(t *testing.T) { |
| 60 | + expected := map[string]interface{}{ |
| 61 | + "Int": testStruct.Int, |
| 62 | + "Int8": testStruct.Int8, |
| 63 | + "Int16": testStruct.Int16, |
| 64 | + "Int32": testStruct.Int32, |
| 65 | + "Int64": testStruct.Int64, |
| 66 | + "Uint": testStruct.Uint, |
| 67 | + "Uint8": testStruct.Uint8, |
| 68 | + "Uint16": testStruct.Uint16, |
| 69 | + "Uint32": testStruct.Uint32, |
| 70 | + "Uint64": testStruct.Uint64, |
| 71 | + "Float32": testStruct.Float32, |
| 72 | + "Float64": testStruct.Float64, |
| 73 | + "Bool": testStruct.Bool, |
| 74 | + "String": testStruct.String, |
| 75 | + "Header.key": []string{"value"}, |
| 76 | + "CustomStruct": fmt.Sprintf("{%s}", testStruct.CustomStruct.Field), |
| 77 | + } |
| 78 | + |
| 79 | + actual := StructToMap(testStruct) |
| 80 | + |
| 81 | + testutils.AssertNotNil(t, actual) |
| 82 | + testutils.AssertEquals(t, expected, actual) |
| 83 | +} |
| 84 | + |
| 85 | +// BenchmarkStructToMap benchmarks the StructToMap function. |
| 86 | +func BenchmarkStructToMap(b *testing.B) { |
| 87 | + for index := 0; index < b.N; index++ { |
| 88 | + _ = StructToMap(testStruct) |
| 89 | + } |
| 90 | +} |
0 commit comments