github.com/ipfans/trojan-go@v0.11.0/config/config_test.go (about)

     1  package config
     2  
     3  import (
     4  	"context"
     5  	"testing"
     6  
     7  	"github.com/ipfans/trojan-go/common"
     8  )
     9  
    10  type Foo struct {
    11  	Field1 string `json,yaml:"field1"`
    12  	Field2 bool   `json:"field2" yaml:"field2"`
    13  }
    14  
    15  type TestStruct struct {
    16  	Field1 string `json,yaml:"field1"`
    17  	Field2 bool   `json,yaml:"field2"`
    18  	Field3 []Foo  `json,yaml:"field3"`
    19  }
    20  
    21  func creator() interface{} {
    22  	return &TestStruct{}
    23  }
    24  
    25  func TestJSONConfig(t *testing.T) {
    26  	RegisterConfigCreator("test", creator)
    27  	data := []byte(`
    28  	{
    29  		"field1": "test1",
    30  		"field2": true,
    31  		"field3": [
    32  			{
    33  				"field1": "aaaa",
    34  				"field2": true
    35  			}
    36  		]
    37  	}
    38  	`)
    39  	ctx, err := WithJSONConfig(context.Background(), data)
    40  	common.Must(err)
    41  	c := FromContext(ctx, "test").(*TestStruct)
    42  	if c.Field1 != "test1" || c.Field2 != true {
    43  		t.Fail()
    44  	}
    45  }
    46  
    47  func TestYAMLConfig(t *testing.T) {
    48  	RegisterConfigCreator("test", creator)
    49  	data := []byte(`
    50  field1: 012345678
    51  field2: true
    52  field3:
    53    - field1: test
    54      field2: true
    55  `)
    56  	ctx, err := WithYAMLConfig(context.Background(), data)
    57  	common.Must(err)
    58  	c := FromContext(ctx, "test").(*TestStruct)
    59  	if c.Field1 != "012345678" || c.Field2 != true || c.Field3[0].Field1 != "test" {
    60  		t.Fail()
    61  	}
    62  }