Exemplo n.º 1
0
func (suite *TestSuiteTemplate) TestGet(c *C) {
	// Write something
	url := "zk://" + strings.Join(Hosts(), ",")
	zk, err := namespace.Dial(context.Background(), url)
	c.Assert(err, IsNil)
	c.Log(zk)
	defer zk.Close()

	k := fmt.Sprintf("/unit-test/registry/template/%d/test", time.Now().Unix())
	p := namespace.NewPath(k)
	v := []byte("test")
	_, err = zk.Put(p, v, false)
	c.Assert(err, IsNil)

	suite.template = "The value is {{get \"zk://" + k + "\"}}!"

	// Generate the auth token required by the server.
	token := auth.NewToken(1*time.Hour).Add("secure", 1)
	header := http.Header{}
	token.SetHeader(header, testutil.PrivateKeyFunc)

	ctx := resource.ContextPutHttpHeader(context.Background(), header)
	applied, err := template.Execute(ctx, fmt.Sprintf("http://localhost:%d/secure", suite.port))
	c.Assert(err, IsNil)
	c.Log(string(applied))
	c.Assert(string(applied), Equals, "The value is test!")
}
Exemplo n.º 2
0
func (suite *TestSuiteTemplate) TestTemplateExecuteWithVarBlock(c *C) {
	// Generate the auth token required by the server.
	token := auth.NewToken(1*time.Hour).Add("secure", 1)
	header := http.Header{}
	token.SetHeader(header, testutil.PrivateKeyFunc)

	// This is the content to be served by the test server.
	// Using the Execute will add additional functions that can be included in the var blocks.
	suite.template = `
{{define "comments"}}
# The variable define blocks allow the definition of variables that are reused throughout the
# main body of the template.  The variables are referenced as '<blockname>.<fieldname>'.
{{end}}

{{define "app"}} # blockname is 'app'
version: 1.2
image: repo
build: 1234
dir: {{sh "pwd"}} # Invoke shell and use that as the value.
user: "******"USER"}}"  # Getting the environment variable and use that as value.
{{end}}

{{define "host"}}
label: appserver
name: myhost
port: {{.port}}  # Here we allow the application to pass in a context that's refereceable.
{{end}}

{
   "image" : "repo/myapp:` + "{{my `app.version`}}-{{my `app.build`}}" + `",
   "host" : "` + "{{my `host.name`}}" + `",{{/* use this for comment in JSON :) */}}
   "dir" : "` + "{{my `app.dir`}}" + `",
   "user" : "` + "{{my `app.user`}}" + `",
   "port" : "` + "{{my `host.port`}}" + `"
}`

	// The url is a template too.
	url := "http://localhost:{{.port}}/secure"

	data := map[string]interface{}{
		"Name": "test",
		"Age":  20,
		"port": suite.port,
	}
	ctx := ContextPutTemplateData(resource.ContextPutHttpHeader(context.Background(), header), data)

	text, err := Execute(ctx, url)
	c.Assert(err, IsNil)
	c.Log(string(text))
	obj := make(map[string]string)
	err = json.Unmarshal(text, &obj)
	c.Assert(err, IsNil)
	c.Assert(obj["image"], Equals, "repo/myapp:1.2-1234")
	c.Assert(obj["user"], Equals, os.Getenv("USER"))
	c.Assert(obj["host"], Equals, "myhost")
	c.Assert(obj["port"], Equals, fmt.Sprintf("%d", suite.port))
	c.Assert(obj["dir"], Equals, os.Getenv("PWD"))
}
Exemplo n.º 3
0
// Tests overlaying one config on top of another via multiple flags
func (suite *TestSuiteConf) TestConfOverlay(c *C) {

	suite.template1 = `
string: this is a literal string
int: 25
addr:
  addr1: 1234 post
  addr2: sf, ca 94019
`
	suite.template2 = `
string: this is a override literal string
int: 50
template: '{{ format "hello/{{.Domain}}/{{.Service}}" }}'  # { is special char in yaml, must quote the string with '
bar: 27
`

	test := new(testCommand)

	test.OnDoneExecuteLayer = func(cf *Conf, url string, result []byte, err error) {
		c.Log("Processed:", url, ".... result=", string(result))
	}

	test.OnDoneUnmarshalLayer = func(cf *Conf, url string, err error) {
		c.Log("Processed:", url, ".... model=", cf.Model())
	}

	test.OnDoneUnmarshal = func(cf *Conf, obj interface{}) {
		c.Log("Got unmarshaled object = ", cf.model, "===object=>", obj)
	}

	fs := flag.GetFlagSet("test", test)
	err := fs.Parse(args("-conf.url=http://localhost:7997/template1 -conf.url=http://localhost:7997/template2"))

	header := http.Header{}
	token := auth.NewToken(1*time.Hour).Add("secure", 1)
	token.SetHeader(header, testutil.PrivateKeyFunc)

	ctx := resource.ContextPutHttpHeader(context.Background(), header)
	ctx = ContextPutConfigDataType(ctx, encoding.ContentTypeYAML)

	fm := NewFuncMap().Bind("format").To(escapeFunc("format")).Build()
	c.Assert(fm["format"], Not(IsNil))

	err = Configure(ctx, test.Conf, test, fm)
	c.Assert(err, IsNil)

	c.Log("test=", test)

	c.Assert(test.Urls, DeepEquals, []string{"http://localhost:7997/template1", "http://localhost:7997/template2"})
	c.Assert(test.String, Equals, "this is a override literal string")
	c.Assert(test.Int, Equals, 50)
	c.Assert(test.Addr.Addr1, Equals, "1234 post")
	c.Assert(test.Addr.Addr2, Equals, "sf, ca 94019")
	c.Assert(test.Template, Equals, "{{format \"hello/{{.Domain}}/{{.Service}}\"}}")
}
Exemplo n.º 4
0
func (suite *TestSuiteTemplate) TestList(c *C) {
	// Write something
	url := "zk://" + strings.Join(Hosts(), ",")
	zk, err := namespace.Dial(context.Background(), url)
	c.Assert(err, IsNil)
	c.Log(zk)
	defer zk.Close()

	k := "/unit-test/registry/template/test"
	p := namespace.NewPath(k)

	err = zk.Delete(p)

	// Write new data
	v := []byte("test")
	_, err = zk.Put(p, v, false)
	c.Assert(err, IsNil)

	// write children
	for i := 0; i < 5; i++ {
		cp := p.Sub(fmt.Sprintf("child-%d", i))
		cv := []byte(fmt.Sprintf("value-%d", i))
		_, err = zk.Put(cp, cv, false)
		c.Assert(err, IsNil)
	}

	suite.template = "{{range list \"zk://" + k + "\"}}\n{{.}}{{end}}"

	// Generate the auth token required by the server.
	token := auth.NewToken(1*time.Hour).Add("secure", 1)
	header := http.Header{}
	token.SetHeader(header, testutil.PrivateKeyFunc)

	ctx := resource.ContextPutHttpHeader(context.Background(), header)
	applied, err := template.Execute(ctx, fmt.Sprintf("http://localhost:%d/secure", suite.port))
	c.Assert(err, IsNil)
	c.Log(string(applied))

	l := strings.Split(string(applied), "\n")[1:]
	c.Assert(l, DeepEquals, []string{
		url + "/unit-test/registry/template/test/child-4",
		url + "/unit-test/registry/template/test/child-3",
		url + "/unit-test/registry/template/test/child-2",
		url + "/unit-test/registry/template/test/child-1",
		url + "/unit-test/registry/template/test/child-0",
	})
}
Exemplo n.º 5
0
func (suite *TestSuiteFuncs) TestContentInline(c *C) {
	token := auth.NewToken(1*time.Hour).Add("secure", 1)
	header := http.Header{}
	token.SetHeader(header, testutil.PrivateKeyFunc)
	ctx := resource.ContextPutHttpHeader(context.Background(), header)

	// set up the content
	suite.content = "this is a test"

	f := ContentInline(ctx)
	inline, ok := f.(func(string) (string, error))
	c.Assert(ok, Equals, true)

	out, err := inline(fmt.Sprintf("http://localhost:%d/secure", suite.port))
	c.Assert(err, IsNil)
	c.Log("out=", out)
	c.Assert(out, Equals, suite.content)
}
Exemplo n.º 6
0
// This test here shows how to implement two stages of configuring an object.
// First a field in the struct gets the source of the config url from the command line flags.
// Second, the config is fetched and unmarshalled to the object.
// Finally, we parse again so that additional flag values are overlaid onto the struct.
func (suite *TestSuiteCommand) TestCommandReparseFlag(c *C) {
	Register("person", func() (Module, ErrorHandling) {
		return new(person), PanicOnError
	})

	// Generate the auth token required by the server.
	token := auth.NewToken(1*time.Hour).Add("secure", 1)
	header := http.Header{}
	token.SetHeader(header, testutil.PrivateKeyFunc)
	ctx := resource.ContextPutHttpHeader(context.Background(), header)

	suite.template = `
name: joe
age: 21
employee: false
not-a-field: hello
`

	p := &person{
		Age:      18,
		Employee: true,
	}

	RunModule("person", p, strings.Split("--config_url=http://localhost:7986/secure --age=35", " "), nil)

	c.Assert(p.ConfigUrl, Equals, "http://localhost:7986/secure")
	c.Assert(p.Employee, Equals, true)

	data, err := resource.Fetch(ctx, p.ConfigUrl)
	c.Assert(err, IsNil)
	c.Log(string(data))
	err = encoding.Unmarshal(encoding.ContentTypeYAML, bytes.NewBuffer(data), p)
	c.Assert(err, IsNil)
	c.Assert(p.Age, Equals, 21)
	c.Assert(p.Name, Equals, "joe")
	c.Assert(p.Employee, Equals, true) // we don't expect the yaml to change the field.

	ReparseFlags(p)
	c.Assert(p.Age, Equals, 35) // This is overwritten by the flag value
	c.Assert(p.Name, Equals, "joe")
	c.Assert(p.Employee, Equals, true)
}
Exemplo n.º 7
0
func (suite *TestSuiteFuncs) TestContentToFileWithAuthToken(c *C) {
	token := auth.NewToken(1*time.Hour).Add("secure", 1)
	header := http.Header{}
	token.SetHeader(header, testutil.PrivateKeyFunc)
	ctx := resource.ContextPutHttpHeader(context.Background(), header)

	// set up the content
	suite.content = "this is a test"

	f := ContentToFile(ctx)
	tofile, ok := f.(func(string, ...interface{}) (string, error))
	c.Assert(ok, Equals, true)

	path, err := tofile(fmt.Sprintf("http://localhost:%d/secure", suite.port))
	c.Assert(err, IsNil)
	c.Log("path=", path)

	bytes, err := ioutil.ReadFile(path)
	c.Assert(err, IsNil)
	c.Assert(string(bytes), Equals, suite.content)
}
Exemplo n.º 8
0
func (suite *TestSuiteTemplate) TestTemplateExecute(c *C) {
	// Generate the auth token required by the server.
	token := auth.NewToken(1*time.Hour).Add("secure", 1)
	header := http.Header{}
	token.SetHeader(header, testutil.PrivateKeyFunc)

	// This is the content to be served by the test server.
	suite.template = "My name is {{.Name}} and I am {{.Age}} years old."

	// The url is a template too.
	url := "http://localhost:{{.port}}/secure"

	data := map[string]interface{}{
		"Name": "test",
		"Age":  20,
		"port": suite.port,
	}
	ctx := ContextPutTemplateData(resource.ContextPutHttpHeader(context.Background(), header), data)

	text, err := Execute(ctx, url)
	c.Assert(err, IsNil)
	c.Log(string(text))
	c.Assert(string(text), Equals, "My name is test and I am 20 years old.")
}
Exemplo n.º 9
0
func (suite *TestSuiteTemplate) TestTemplateExecuteWithVarBlock(c *C) {
	// Write something
	url := "zk://" + strings.Join(Hosts(), ",")
	zk, err := namespace.Dial(context.Background(), url)
	c.Assert(err, IsNil)
	c.Log(zk)

	k := "/unit-test/registry/template/test-template-execute-vars/PG_PASS"
	p := namespace.NewPath(k)

	err = zk.Delete(p)

	// Write new data
	v := []byte("password")
	_, err = zk.Put(p, v, false)
	c.Assert(err, IsNil)

	zk.Close()

	// Now use the value in zk in the template

	// Generate the auth token required by the server.
	token := auth.NewToken(1*time.Hour).Add("secure", 1)
	header := http.Header{}
	token.SetHeader(header, testutil.PrivateKeyFunc)

	// This is the content to be served by the test server.
	// Using the Execute will add additional functions that can be included in the var blocks.
	suite.template = `
{{define "comments"}}
# The variable define blocks allow the definition of variables that are reused throughout the
# main body of the template.  The variables are referenced as '<blockname>.<fieldname>'.
{{end}}

{{define "app"}} # blockname is 'app'
version: 1.2
image: repo
build: 1234
user: "******"USER"}}"  # Getting the environment variable and use that as value.
password: "******"zk:///unit-test/registry/template/test-template-execute-vars/PG_PASS" }}"
{{end}}

{{define "host"}}
label: appserver
name: myhost
port: {{.port}}  # Here we allow the application to pass in a context that's refereceable.
{{end}}

{
   "image" : "repo/myapp:` + "{{my `app.version`}}-{{my `app.build`}}" + `",
   "host" : "` + "{{my `host.name`}}" + `",{{/* use this for comment in JSON :) */}}
   "user" : "` + "{{my `app.user`}}" + `",
   "password" : "` + "{{my `app.password`}}" + `",
   "port" : "` + "{{my `host.port`}}" + `"
}`

	// The url is a template too.
	url = "http://localhost:{{.port}}/secure"

	data := map[string]interface{}{
		"Name": "test",
		"Age":  20,
		"port": suite.port,
	}
	ctx := template.ContextPutTemplateData(resource.ContextPutHttpHeader(context.Background(), header), data)

	text, err := template.Execute(ctx, url)
	c.Assert(err, IsNil)
	c.Log(string(text))
	obj := make(map[string]string)
	err = json.Unmarshal(text, &obj)
	c.Assert(err, IsNil)
	c.Assert(obj["image"], Equals, "repo/myapp:1.2-1234")
	c.Assert(obj["user"], Equals, os.Getenv("USER"))
	c.Assert(obj["host"], Equals, "myhost")
	c.Assert(obj["port"], Equals, fmt.Sprintf("%d", suite.port))
	c.Assert(obj["password"], Equals, string(v))
}