github.com/diptanu/nomad@v0.5.7-0.20170516172507-d72e86cbe3d9/command/data_format_test.go (about)

     1  package command
     2  
     3  import (
     4  	"strings"
     5  	"testing"
     6  )
     7  
     8  type testData struct {
     9  	Region string
    10  	ID     string
    11  	Name   string
    12  }
    13  
    14  const expectJSON = `{
    15      "ID": "1",
    16      "Name": "example",
    17      "Region": "global"
    18  }`
    19  
    20  var (
    21  	tData        = testData{"global", "1", "example"}
    22  	testFormat   = map[string]string{"json": "", "template": "{{.Region}}"}
    23  	expectOutput = map[string]string{"json": expectJSON, "template": "global"}
    24  )
    25  
    26  func TestDataFormat(t *testing.T) {
    27  	for k, v := range testFormat {
    28  		fm, err := DataFormat(k, v)
    29  		if err != nil {
    30  			t.Fatalf("err: %v", err)
    31  		}
    32  
    33  		result, err := fm.TransformData(tData)
    34  		if err != nil {
    35  			t.Fatalf("err: %v", err)
    36  		}
    37  
    38  		if result != expectOutput[k] {
    39  			t.Fatalf("expected output:\n%s\nactual:\n%s", expectOutput[k], result)
    40  		}
    41  	}
    42  }
    43  
    44  func TestInvalidJSONTemplate(t *testing.T) {
    45  	// Invalid template {{.foo}}
    46  	fm, err := DataFormat("template", "{{.foo}}")
    47  	if err != nil {
    48  		t.Fatalf("err: %v", err)
    49  	}
    50  	_, err = fm.TransformData(tData)
    51  	if !strings.Contains(err.Error(), "can't evaluate field foo") {
    52  		t.Fatalf("expected invalid template error, got: %s", err.Error())
    53  	}
    54  
    55  	// No template is specified
    56  	fm, err = DataFormat("template", "")
    57  	if err != nil {
    58  		t.Fatalf("err: %v", err)
    59  	}
    60  	_, err = fm.TransformData(tData)
    61  	if !strings.Contains(err.Error(), "template needs to be specified the golang templates.") {
    62  		t.Fatalf("expected not specified template error, got: %s", err.Error())
    63  	}
    64  }