github.com/ShaleApps/viper@v1.15.1-concurrent/internal/encoding/dotenv/codec_test.go (about)

     1  package dotenv
     2  
     3  import (
     4  	"reflect"
     5  	"testing"
     6  )
     7  
     8  // original form of the data
     9  const original = `# key-value pair
    10  KEY=value
    11  `
    12  
    13  // encoded form of the data
    14  const encoded = `KEY=value
    15  `
    16  
    17  // Viper's internal representation
    18  var data = map[string]interface{}{
    19  	"KEY": "value",
    20  }
    21  
    22  func TestCodec_Encode(t *testing.T) {
    23  	codec := Codec{}
    24  
    25  	b, err := codec.Encode(data)
    26  	if err != nil {
    27  		t.Fatal(err)
    28  	}
    29  
    30  	if encoded != string(b) {
    31  		t.Fatalf("decoded value does not match the expected one\nactual:   %#v\nexpected: %#v", string(b), encoded)
    32  	}
    33  }
    34  
    35  func TestCodec_Decode(t *testing.T) {
    36  	t.Run("OK", func(t *testing.T) {
    37  		codec := Codec{}
    38  
    39  		v := map[string]interface{}{}
    40  
    41  		err := codec.Decode([]byte(original), v)
    42  		if err != nil {
    43  			t.Fatal(err)
    44  		}
    45  
    46  		if !reflect.DeepEqual(data, v) {
    47  			t.Fatalf("decoded value does not match the expected one\nactual:   %#v\nexpected: %#v", v, data)
    48  		}
    49  	})
    50  
    51  	t.Run("InvalidData", func(t *testing.T) {
    52  		codec := Codec{}
    53  
    54  		v := map[string]interface{}{}
    55  
    56  		err := codec.Decode([]byte(`invalid data`), v)
    57  		if err == nil {
    58  			t.Fatal("expected decoding to fail")
    59  		}
    60  
    61  		t.Logf("decoding failed as expected: %s", err)
    62  	})
    63  }