Esempio n. 1
1
func TestInsertRead(t *testing.T) {
	tmp := "/tmp/tiedot_test_col"
	os.Remove(tmp)
	defer os.Remove(tmp)
	col, err := OpenCollection(tmp)
	if err != nil {
		t.Fatalf("Failed to open: %v", err)
		return
	}
	defer col.Close()
	docs := [][]byte{
		[]byte("abc"),
		[]byte("1234")}
	ids := [2]int{}
	if ids[0], err = col.Insert(docs[0]); ids[0] != 0 || err != nil {
		t.Fatalf("Failed to insert: %d %v", ids[0], err)
	}
	if ids[1], err = col.Insert(docs[1]); err != nil {
		t.Fatalf("Failed to insert: %v", err)
	}
	if doc0 := col.Read(ids[0]); doc0 == nil || strings.TrimSpace(string(doc0)) != string(docs[0]) {
		t.Fatal("Failed to read", doc0)
	}
	if doc1 := col.Read(ids[1]); doc1 == nil || strings.TrimSpace(string(doc1)) != string(docs[1]) {
		t.Fatalf("Failed to read")
	}
	// it shall not panic
	col.Read(col.Size)
}
func TestGraphNodeConfigModuleExpandFlatten(t *testing.T) {
	mod := testModule(t, "graph-node-module-flatten")

	node := &GraphNodeConfigModule{
		Path:   []string{RootModuleName, "child"},
		Module: &config.Module{},
		Tree:   nil,
	}

	g, err := node.Expand(&BasicGraphBuilder{
		Steps: []GraphTransformer{
			&ConfigTransformer{Module: mod},
		},
	})
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	fg := g.(GraphNodeFlatGraph)

	actual := strings.TrimSpace(fg.FlattenGraph().String())
	expected := strings.TrimSpace(testGraphNodeModuleExpandFlattenStr)
	if actual != expected {
		t.Fatalf("bad:\n\n%s", actual)
	}
}
func (s *DockerSuite) TestContainerApiDeleteRemoveLinks(c *check.C) {
	testRequires(c, DaemonIsLinux)
	out, _ := dockerCmd(c, "run", "-d", "--name", "tlink1", "busybox", "top")

	id := strings.TrimSpace(out)
	c.Assert(waitRun(id), check.IsNil)

	out, _ = dockerCmd(c, "run", "--link", "tlink1:tlink1", "--name", "tlink2", "-d", "busybox", "top")

	id2 := strings.TrimSpace(out)
	c.Assert(waitRun(id2), check.IsNil)

	links, err := inspectFieldJSON(id2, "HostConfig.Links")
	c.Assert(err, check.IsNil)

	if links != "[\"/tlink1:/tlink2/tlink1\"]" {
		c.Fatal("expected to have links between containers")
	}

	status, _, err := sockRequest("DELETE", "/containers/tlink2/tlink1?link=1", nil)
	c.Assert(err, check.IsNil)
	c.Assert(status, check.Equals, http.StatusNoContent)

	linksPostRm, err := inspectFieldJSON(id2, "HostConfig.Links")
	c.Assert(err, check.IsNil)

	if linksPostRm != "null" {
		c.Fatal("call to api deleteContainer links should have removed the specified links")
	}
}
func testStringMatch(t *testing.T, s fmt.Stringer, expected string) {
	actual := strings.TrimSpace(s.String())
	expected = strings.TrimSpace(expected)
	if actual != expected {
		t.Fatalf("Actual\n\n%s\n\nExpected:\n\n%s", actual, expected)
	}
}
// #18453
func (s *DockerSuite) TestEventsContainerFilterBeforeCreate(c *check.C) {
	testRequires(c, DaemonIsLinux)
	var (
		out string
		ch  chan struct{}
	)
	ch = make(chan struct{})

	// calculate the time it takes to create and start a container and sleep 2 seconds
	// this is to make sure the docker event will recevie the event of container
	since := daemonTime(c).Unix()
	id, _ := dockerCmd(c, "run", "-d", "busybox", "top")
	cID := strings.TrimSpace(id)
	waitRun(cID)
	time.Sleep(2 * time.Second)
	duration := daemonTime(c).Unix() - since

	go func() {
		out, _ = dockerCmd(c, "events", "-f", "container=foo", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix()+2*duration))
		close(ch)
	}()
	// Sleep 2 second to wait docker event to start
	time.Sleep(2 * time.Second)
	id, _ = dockerCmd(c, "run", "--name=foo", "-d", "busybox", "top")
	cID = strings.TrimSpace(id)
	waitRun(cID)
	<-ch
	c.Assert(out, checker.Contains, cID, check.Commentf("Missing event of container (foo)"))
}
Esempio n. 6
0
func (blp *BinlogPlayer) dmlTableMatch(sqlSlice []string) bool {
	if blp.tables == nil {
		return true
	}
	if len(blp.tables) == 0 {
		return true
	}
	var firstKw string
	for _, sql := range sqlSlice {
		firstKw = strings.TrimSpace(strings.Split(sql, BLPL_SPACE)[0])
		if firstKw != "insert" && firstKw != "update" && firstKw != "delete" {
			continue
		}
		streamCommentIndex := strings.Index(sql, BLPL_STREAM_COMMENT_START)
		if streamCommentIndex == -1 {
			//log.Warningf("sql doesn't have stream comment '%v'", sql)
			//If sql doesn't have stream comment, don't match
			return false
		}
		tableName := strings.TrimSpace(strings.Split(sql[(streamCommentIndex+len(BLPL_STREAM_COMMENT_START)):], BLPL_SPACE)[0])
		for _, table := range blp.tables {
			if tableName == table {
				return true
			}
		}
	}

	return false
}
Esempio n. 7
0
//资料修改
func (this *AccountController) Profile() {
	user := models.User{Id: this.userid}
	if err := user.Read(); err != nil {
		this.showmsg(err.Error())
	}
	if this.isPost() {
		errmsg := make(map[string]string)
		password := strings.TrimSpace(this.GetString("password"))
		newpassword := strings.TrimSpace(this.GetString("newpassword"))
		newpassword2 := strings.TrimSpace(this.GetString("newpassword2"))
		updated := false
		if newpassword != "" {
			if password == "" || util.Md5([]byte(password)) != user.Password {
				errmsg["password"] = "******"
			} else if len(newpassword) < 6 {
				errmsg["newpassword"] = "******"
			} else if newpassword != newpassword2 {
				errmsg["newpassword2"] = "两次输入的密码不一致"
			}
			if len(errmsg) == 0 {
				user.Password = util.Md5([]byte(newpassword))
				user.Update("password")
				updated = true
			}
		}
		this.Data["updated"] = updated
		this.Data["errmsg"] = errmsg
	}
	this.Data["user"] = user
	this.display()
}
Esempio n. 8
0
func ParseHashtags(text string) (string, string) {
	words := strings.Fields(text)

	hashtagString := ""
	plainString := ""
	for _, word := range words {
		// trim off surrounding punctuation
		word = puncStart.ReplaceAllString(word, "")
		word = puncEnd.ReplaceAllString(word, "")

		// and remove extra pound #s
		word = hashtagStart.ReplaceAllString(word, "#")

		if validHashtag.MatchString(word) {
			hashtagString += " " + word
		} else {
			plainString += " " + word
		}
	}

	if len(hashtagString) > 1000 {
		hashtagString = hashtagString[:999]
		lastSpace := strings.LastIndex(hashtagString, " ")
		if lastSpace > -1 {
			hashtagString = hashtagString[:lastSpace]
		} else {
			hashtagString = ""
		}
	}

	return strings.TrimSpace(hashtagString), strings.TrimSpace(plainString)
}
Esempio n. 9
0
File: url.go Progetto: qgweb/new
func (this *Domain) domainData(out chan interface{}, in chan int8) {
	var (
		tname = "zhejiang_urltrack_" + time.Now().Format("200601")
		btime = timestamp.GetHourTimestamp(-1)
		etime = timestamp.GetHourTimestamp(0)
	)

	sc := hbase.NewScan([]byte(tname), 10000, this.hb)
	sc.StartRow = []byte(btime)
	sc.StopRow = []byte(etime)

	for {
		row := sc.Next()
		if row == nil {
			break
		}

		ad := strings.TrimSpace(string(row.Columns["base:ad"].Value))
		ua := strings.TrimSpace(string(row.Columns["base:ua"].Value))
		cids := make([]string, 0, len(row.Columns)-2)

		for _, v := range row.Columns {
			if string(v.Family) == "cids" {
				cids = append(cids, string(v.Qual))
			}
		}

		out <- fmt.Sprintf("%s\t%s\t%s", ad, ua, strings.Join(cids, ","))
	}
	in <- 1
	sc.Close()
}
Esempio n. 10
0
func (s *DockerSuite) TestLinksHostsFilesInject(c *check.C) {
	testRequires(c, SameHostDaemon, ExecSupport)

	out, _ := dockerCmd(c, "run", "-itd", "--name", "one", "busybox", "top")
	idOne := strings.TrimSpace(out)

	out, _ = dockerCmd(c, "run", "-itd", "--name", "two", "--link", "one:onetwo", "busybox", "top")
	idTwo := strings.TrimSpace(out)

	time.Sleep(1 * time.Second)

	contentOne, err := readContainerFileWithExec(idOne, "/etc/hosts")
	if err != nil {
		c.Fatal(err, string(contentOne))
	}

	contentTwo, err := readContainerFileWithExec(idTwo, "/etc/hosts")
	if err != nil {
		c.Fatal(err, string(contentTwo))
	}

	if !strings.Contains(string(contentTwo), "onetwo") {
		c.Fatal("Host is not present in updated hosts file", string(contentTwo))
	}

}
func (s *DockerSuite) TestRestartContainerwithRestartPolicy(c *check.C) {
	out1, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "false")
	out2, _ := dockerCmd(c, "run", "-d", "--restart=always", "busybox", "false")

	id1 := strings.TrimSpace(string(out1))
	id2 := strings.TrimSpace(string(out2))
	err := waitInspect(id1, "{{ .State.Restarting }} {{ .State.Running }}", "false false", 30*time.Second)
	c.Assert(err, checker.IsNil)

	// TODO: fix racey problem during restart:
	// https://jenkins.dockerproject.org/job/Docker-PRs-Win2Lin/24665/console
	// Error response from daemon: Cannot restart container 6655f620d90b390527db23c0a15b3e46d86a58ecec20a5697ab228d860174251: remove /var/run/docker/libcontainerd/6655f620d90b390527db23c0a15b3e46d86a58ecec20a5697ab228d860174251/rootfs: device or resource busy
	if _, _, err := dockerCmdWithError("restart", id1); err != nil {
		// if restart met racey problem, try again
		time.Sleep(500 * time.Millisecond)
		dockerCmd(c, "restart", id1)
	}
	if _, _, err := dockerCmdWithError("restart", id2); err != nil {
		// if restart met racey problem, try again
		time.Sleep(500 * time.Millisecond)
		dockerCmd(c, "restart", id2)
	}

	dockerCmd(c, "stop", id1)
	dockerCmd(c, "stop", id2)
	dockerCmd(c, "start", id1)
	dockerCmd(c, "start", id2)
}
Esempio n. 12
0
func (s *systemtestSuite) TestVolpluginRestartMultiMount(c *C) {
	_, err := s.mon0cmd("sudo truncate -s0 /tmp/volplugin.log")
	c.Assert(err, IsNil)

	volName := fqVolume("policy1", genRandomVolume())

	c.Assert(s.createVolume("mon0", volName, map[string]string{"unlocked": "true"}), IsNil)
	out, err := s.dockerRun("mon0", false, true, volName, "sleep 10m")
	c.Assert(err, IsNil, Commentf(out))
	// test if any containers can start after this -- they should be able to.
	// This just starts and stops a container quickly.
	outErr, err := s.dockerRun("mon0", false, false, volName, "echo")
	c.Assert(err, IsNil, Commentf(outErr))
	out2, err := s.dockerRun("mon0", false, true, volName, "sleep 10m")
	c.Assert(err, IsNil, Commentf(out2))
	c.Assert(stopVolplugin(s.vagrant.GetNode("mon0")), IsNil)
	c.Assert(startVolplugin(s.vagrant.GetNode("mon0")), IsNil)
	c.Assert(waitForVolplugin(s.vagrant.GetNode("mon0")), IsNil)
	time.Sleep(15 * time.Second)

	out = strings.TrimSpace(out)
	out2 = strings.TrimSpace(out2)

	errout, err := s.mon0cmd(fmt.Sprintf("docker kill -s KILL '%s' && sleep 1 && docker rm '%s'", out, out))
	c.Assert(err, IsNil, Commentf(errout))
	errout, err = s.mon0cmd(fmt.Sprintf("docker kill -s KILL '%s' && sleep 1 && docker rm '%s'", out2, out2))
	c.Assert(err, IsNil, Commentf(errout))

	errout, err = s.mon0cmd("grep 500 /tmp/volplugin.log")
	c.Assert(err, NotNil, Commentf(errout))
}
Esempio n. 13
0
func readJson(r io.Reader) ([]byte, error) {

	s, err := ioutil.ReadAll(r)
	if err != nil {
		return s, err
	}

	lines := make([]string, 0)
	for _, line := range strings.Split(strings.Replace(string(s), "\r\n", "\n", -1), "\n") {
		line = strings.TrimSpace(line)
		if line == "" || strings.HasPrefix(line, "//") {
			continue
		}
		lines = append(lines, line)
	}

	var b bytes.Buffer
	for i, line := range lines {
		if i < len(lines)-1 {
			nextLine := strings.TrimSpace(lines[i+1])
			if nextLine == "]" ||
				nextLine == "]," ||
				nextLine == "}" ||
				nextLine == "}," {
				if strings.HasSuffix(line, ",") {
					line = strings.TrimSuffix(line, ",")
				}
			}
		}
		b.WriteString(line)
	}

	return b.Bytes(), nil
}
Esempio n. 14
0
func (g *Goop) currentRev(vcsCmd string, path string) (string, error) {
	switch vcsCmd {
	case "git":
		cmd := exec.Command("git", "rev-parse", "--verify", "HEAD")
		cmd.Dir = path
		cmd.Stderr = g.stderr
		rev, err := cmd.Output()
		if err != nil {
			return "", err
		} else {
			return strings.TrimSpace(string(rev)), err
		}
	case "hg":
		cmd := exec.Command("hg", "log", "-r", ".", "--template", "{node}")
		cmd.Dir = path
		cmd.Stderr = g.stderr
		rev, err := cmd.Output()
		if err != nil {
			return "", err
		} else {
			return strings.TrimSpace(string(rev)), err
		}
	}
	return "", &UnsupportedVCSError{VCS: vcsCmd}
}
Esempio n. 15
0
func wrapText(s string, l int, prefix string) string {
	// Basic text wrapping of s at spaces to fit in l
	var ret string

	s = strings.TrimSpace(s)

	for len(s) > l {
		// Try to split on space
		suffix := ""

		pos := strings.LastIndex(s[:l], " ")

		if pos < 0 {
			pos = l - 1
			suffix = "-\n"
		}

		if len(ret) != 0 {
			ret += "\n" + prefix
		}

		ret += strings.TrimSpace(s[:pos]) + suffix
		s = strings.TrimSpace(s[pos:])
	}

	if len(s) > 0 {
		if len(ret) != 0 {
			ret += "\n" + prefix
		}

		return ret + s
	}

	return ret
}
Esempio n. 16
0
func (s *DockerSuite) TestEventsFilterLabels(c *check.C) {
	since := daemonUnixTime(c)
	label := "io.docker.testing=foo"

	out, _ := dockerCmd(c, "run", "-d", "-l", label, "busybox:latest", "true")
	container1 := strings.TrimSpace(out)

	out, _ = dockerCmd(c, "run", "-d", "busybox", "true")
	container2 := strings.TrimSpace(out)

	out, _ = dockerCmd(
		c,
		"events",
		"--since", since,
		"--until", daemonUnixTime(c),
		"--filter", fmt.Sprintf("label=%s", label))

	events := strings.Split(strings.TrimSpace(out), "\n")
	c.Assert(len(events), checker.Equals, 3)

	for _, e := range events {
		c.Assert(e, checker.Contains, container1)
		c.Assert(e, checker.Not(checker.Contains), container2)
	}
}
Esempio n. 17
0
func (s *DockerSuite) TestEventsAttach(c *check.C) {
	// TODO Windows CI: Figure out why this test fails intermittently (TP5).
	testRequires(c, DaemonIsLinux)

	out, _ := dockerCmd(c, "run", "-di", "busybox", "cat")
	cID := strings.TrimSpace(out)
	c.Assert(waitRun(cID), checker.IsNil)

	cmd := exec.Command(dockerBinary, "attach", cID)
	stdin, err := cmd.StdinPipe()
	c.Assert(err, checker.IsNil)
	defer stdin.Close()
	stdout, err := cmd.StdoutPipe()
	c.Assert(err, checker.IsNil)
	defer stdout.Close()
	c.Assert(cmd.Start(), checker.IsNil)
	defer cmd.Process.Kill()

	// Make sure we're done attaching by writing/reading some stuff
	_, err = stdin.Write([]byte("hello\n"))
	c.Assert(err, checker.IsNil)
	out, err = bufio.NewReader(stdout).ReadString('\n')
	c.Assert(err, checker.IsNil)
	c.Assert(strings.TrimSpace(out), checker.Equals, "hello", check.Commentf("expected 'hello'"))

	c.Assert(stdin.Close(), checker.IsNil)

	dockerCmd(c, "kill", cID)
	c.Assert(waitExited(cID, 5*time.Second), checker.IsNil)

	until := daemonUnixTime(c)
	out, _ = dockerCmd(c, "events", "-f", "container="+cID, "--until="+until)
	c.Assert(out, checker.Contains, "attach", check.Commentf("Missing 'attach' log event"))
}
Esempio n. 18
0
File: util.go Progetto: ARodri/hume
// parseSizeInBytes converts strings like 1GB or 12 mb into an unsigned integer number of bytes
func parseSizeInBytes(sizeStr string) uint {
	sizeStr = strings.TrimSpace(sizeStr)
	lastChar := len(sizeStr) - 1
	multiplier := uint(1)

	if lastChar > 0 {
		if sizeStr[lastChar] == 'b' || sizeStr[lastChar] == 'B' {
			if lastChar > 1 {
				switch unicode.ToLower(rune(sizeStr[lastChar-1])) {
				case 'k':
					multiplier = 1 << 10
					sizeStr = strings.TrimSpace(sizeStr[:lastChar-1])
				case 'm':
					multiplier = 1 << 20
					sizeStr = strings.TrimSpace(sizeStr[:lastChar-1])
				case 'g':
					multiplier = 1 << 30
					sizeStr = strings.TrimSpace(sizeStr[:lastChar-1])
				default:
					multiplier = 1
					sizeStr = strings.TrimSpace(sizeStr[:lastChar])
				}
			}
		}
	}

	size := cast.ToInt(sizeStr)
	if size < 0 {
		size = 0
	}

	return safeMul(uint(size), multiplier)
}
Esempio n. 19
0
//登录
func (this *AccountController) Login() {

	if this.userid > 0 {
		this.Redirect("/admin", 302)
	}

	if this.GetString("dosubmit") == "yes" {
		account := strings.TrimSpace(this.GetString("account"))
		password := strings.TrimSpace(this.GetString("password"))
		remember := this.GetString("remember")
		if account != "" && password != "" {
			var user models.User
			user.Name = account
			if user.Read("name") != nil || user.Password != util.Md5([]byte(password)) {
				this.Data["errmsg"] = "帐号或密码错误"
			} else if user.Active == 0 {
				this.Data["errmsg"] = "该帐号未激活"
			} else {
				user.LoginCount += 1
				user.LastIp = this.getClientIp()
				user.LastLogin = this.getTime()
				user.Update()
				authkey := util.Md5([]byte(this.getClientIp() + "|" + user.Password))
				if remember == "yes" {
					this.Ctx.SetCookie("auth", strconv.FormatInt(user.Id, 10)+"|"+authkey, 7*86400)
				} else {
					this.Ctx.SetCookie("auth", strconv.FormatInt(user.Id, 10)+"|"+authkey)
				}

				this.Redirect("/admin", 302)
			}
		}
	}
	this.TplNames = this.moduleName + "/account/login.html"
}
Esempio n. 20
0
// Test case for #23498
func (s *DockerSuite) TestCreateUnsetEntrypoint(c *check.C) {
	name := "test-entrypoint"
	dockerfile := `FROM busybox
ADD entrypoint.sh /entrypoint.sh
RUN chmod 755 /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
CMD echo foobar`

	ctx, err := fakeContext(dockerfile, map[string]string{
		"entrypoint.sh": `#!/bin/sh
echo "I am an entrypoint"
exec "$@"`,
	})
	c.Assert(err, check.IsNil)
	defer ctx.Close()

	_, err = buildImageFromContext(name, ctx, true)
	c.Assert(err, check.IsNil)

	out, _ := dockerCmd(c, "create", "--entrypoint=", name, "echo", "foo")
	id := strings.TrimSpace(out)
	c.Assert(id, check.Not(check.Equals), "")
	out, _ = dockerCmd(c, "start", "-a", id)
	c.Assert(strings.TrimSpace(out), check.Equals, "foo")
}
Esempio n. 21
0
func getCreationStartTime(t *testing.T, ctx *testutils.RktRunCtx, imageID string) (creation time.Time, start time.Time) {
	// Run rkt list --full
	rktCmd := fmt.Sprintf("%s list --full", ctx.Cmd())
	child := spawnOrFail(t, rktCmd)
	child.Wait()

	// Get creation time
	match := fmt.Sprintf(".*%s\t.*\t(.*)\t(.*)\t", imageID)
	result, out, err := expectRegexWithOutput(child, match)
	if err != nil {
		t.Fatalf("%q regex not found, Error: %v\nOutput: %v", match, err, out)
	}
	tmStr := strings.TrimSpace(result[1])
	creation, err = time.Parse(defaultTimeLayout, tmStr)
	if err != nil {
		t.Fatalf("Error parsing creation time: %q", err)
	}

	tmStr = strings.TrimSpace(result[2])
	start, err = time.Parse(defaultTimeLayout, tmStr)
	if err != nil {
		t.Fatalf("Error parsing start time: %q", err)
	}

	return creation, start
}
Esempio n. 22
0
func TestLoadDir_override(t *testing.T) {
	c, err := LoadDir(filepath.Join(fixtureDir, "dir-override"))
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	if c == nil {
		t.Fatal("config should not be nil")
	}

	actual := variablesStr(c.Variables)
	if actual != strings.TrimSpace(dirOverrideVariablesStr) {
		t.Fatalf("bad:\n%s", actual)
	}

	actual = providerConfigsStr(c.ProviderConfigs)
	if actual != strings.TrimSpace(dirOverrideProvidersStr) {
		t.Fatalf("bad:\n%s", actual)
	}

	actual = resourcesStr(c.Resources)
	if actual != strings.TrimSpace(dirOverrideResourcesStr) {
		t.Fatalf("bad:\n%s", actual)
	}

	actual = outputsStr(c.Outputs)
	if actual != strings.TrimSpace(dirOverrideOutputsStr) {
		t.Fatalf("bad:\n%s", actual)
	}
}
Esempio n. 23
0
func doRow0(top *Top, line string) {

	rexp := regexp.MustCompile(`top[\s\-0-9:]+up([:0-9A-z,\s]+?)([0-9] user.*)`)
	matches := rexp.FindStringSubmatch(line)
	if len(matches) != 3 {
		return
	}

	top.Uptime = strings.Trim(matches[1], " ,")

	ls := strings.Split(matches[2], ",")
	if len(ls) != 4 {
		return
	}
	// users
	ls[0] = strings.TrimSpace(ls[0])
	top.Users, _ = strconv.Atoi(strings.Split(ls[0], " ")[0])
	// load avgs
	// 5
	if i := strings.Index(ls[1], "load average:"); i > -1 {
		ls[1] = strings.TrimSpace(ls[1][i+13:])
		top.LoadAvg5, _ = strconv.ParseFloat(ls[1], 64)
	}
	// 10
	top.LoadAvg10, _ = strconv.ParseFloat(strings.TrimSpace(ls[2]), 64)
	// 15
	top.LoadAvg15, _ = strconv.ParseFloat(strings.TrimSpace(ls[3]), 64)
}
Esempio n. 24
0
func TestLoadBasic(t *testing.T) {
	c, err := Load(filepath.Join(fixtureDir, "basic.tf"))
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	if c == nil {
		t.Fatal("config should not be nil")
	}

	if c.Dir != "" {
		t.Fatalf("bad: %#v", c.Dir)
	}

	actual := variablesStr(c.Variables)
	if actual != strings.TrimSpace(basicVariablesStr) {
		t.Fatalf("bad:\n%s", actual)
	}

	actual = providerConfigsStr(c.ProviderConfigs)
	if actual != strings.TrimSpace(basicProvidersStr) {
		t.Fatalf("bad:\n%s", actual)
	}

	actual = resourcesStr(c.Resources)
	if actual != strings.TrimSpace(basicResourcesStr) {
		t.Fatalf("bad:\n%s", actual)
	}

	actual = outputsStr(c.Outputs)
	if actual != strings.TrimSpace(basicOutputsStr) {
		t.Fatalf("bad:\n%s", actual)
	}
}
Esempio n. 25
0
// Search and sort a data from the storage
func (storage *Record) Search(query string) (answer string, ok bool) {
	ok = false
	answer = "not found\n"
	if len(strings.TrimSpace(query)) == 0 {
		log.Println("Empty query")
	} else {
		mapp, err := storage.LoadMapper(strings.TrimSpace(query))
		if err != nil {
			log.Println("Query:", query, err.Error())
		} else {
			if mapp == nil || mapp.Count() == 0 {
				return answer, ok
			}
			ok = true

			// get keys of a map and sort their
			keys := make([]string, 0, mapp.Count())
			for key := range mapp.Fields {
				keys = append(keys, key)
			}
			sort.Strings(keys)
			answer = prepareAnswer(mapp, keys)
		}
	}

	return answer, ok
}
Esempio n. 26
0
func TestLoadBasic_import(t *testing.T) {
	// Skip because we disabled importing
	t.Skip()

	c, err := Load(filepath.Join(fixtureDir, "import.tf"))
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	if c == nil {
		t.Fatal("config should not be nil")
	}

	actual := variablesStr(c.Variables)
	if actual != strings.TrimSpace(importVariablesStr) {
		t.Fatalf("bad:\n%s", actual)
	}

	actual = providerConfigsStr(c.ProviderConfigs)
	if actual != strings.TrimSpace(importProvidersStr) {
		t.Fatalf("bad:\n%s", actual)
	}

	actual = resourcesStr(c.Resources)
	if actual != strings.TrimSpace(importResourcesStr) {
		t.Fatalf("bad:\n%s", actual)
	}
}
Esempio n. 27
0
/*
	Command line
*/
func parseArgs(args []string) (cmd string, key string, val string) {
	pos := [2]string{}
	copy(pos[:], args[1:])
	cmd = strings.ToUpper(args[0])
	key, val = strings.TrimSpace(pos[0]), strings.TrimSpace(pos[1])
	return cmd, key, val
}
Esempio n. 28
0
func getEngine() (*xorm.Engine, error) {
	LoadConfig()

	cnnstr := ""
	switch DbCfg.Type {
	case "mysql":
		cnnstr = fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8",
			DbCfg.User, DbCfg.Pwd, DbCfg.Host, DbCfg.Name)
	case "postgres":
		var host, port = "127.0.0.1", "5432"
		fields := strings.Split(DbCfg.Host, ":")
		if len(fields) > 0 && len(strings.TrimSpace(fields[0])) > 0 {
			host = fields[0]
		}
		if len(fields) > 1 && len(strings.TrimSpace(fields[1])) > 0 {
			port = fields[1]
		}
		cnnstr = fmt.Sprintf("user=%s password=%s host=%s port=%s dbname=%s sslmode=%s",
			DbCfg.User, DbCfg.Pwd, host, port, DbCfg.Name, DbCfg.SslMode)
	case "sqlite3":
		if !filepath.IsAbs(DbCfg.Path) {
			DbCfg.Path = filepath.Join(setting.DataPath, DbCfg.Path)
		}
		os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm)
		cnnstr = "file:" + DbCfg.Path + "?cache=shared&mode=rwc&_loc=Local"
	default:
		return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
	}

	log.Info("Database: %v", DbCfg.Type)

	return xorm.NewEngine(DbCfg.Type, cnnstr)
}
Esempio n. 29
0
func (s *DockerSuite) TestEventsFilterImageName(c *check.C) {
	since := daemonUnixTime(c)

	out, _ := dockerCmd(c, "run", "--name", "container_1", "-d", "busybox:latest", "true")
	container1 := strings.TrimSpace(out)

	out, _ = dockerCmd(c, "run", "--name", "container_2", "-d", "busybox", "true")
	container2 := strings.TrimSpace(out)

	name := "busybox"
	out, _ = dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", fmt.Sprintf("image=%s", name))
	events := strings.Split(out, "\n")
	events = events[:len(events)-1]
	c.Assert(events, checker.Not(checker.HasLen), 0) //Expected events but found none for the image busybox:latest
	count1 := 0
	count2 := 0

	for _, e := range events {
		if strings.Contains(e, container1) {
			count1++
		} else if strings.Contains(e, container2) {
			count2++
		}
	}
	c.Assert(count1, checker.Not(checker.Equals), 0, check.Commentf("Expected event from container but got %d from %s", count1, container1))
	c.Assert(count2, checker.Not(checker.Equals), 0, check.Commentf("Expected event from container but got %d from %s", count2, container2))

}
Esempio n. 30
0
// reads a bulk reply (i.e $5\r\nhello)
func readBulk(reader *bufio.Reader, head string) ([]byte, error) {
	var err error
	var data []byte

	if head == "" {
		head, err = reader.ReadString('\n')
		if err != nil {
			return nil, err
		}
	}
	switch head[0] {
	case ':':
		data = []byte(strings.TrimSpace(head[1:]))

	case '$':
		size, err := strconv.Atoi(strings.TrimSpace(head[1:]))
		if err != nil {
			return nil, err
		}
		if size == -1 {
			return nil, doesNotExist
		}
		lr := io.LimitReader(reader, int64(size))
		data, err = ioutil.ReadAll(lr)
		if err == nil {
			// read end of line
			_, err = reader.ReadString('\n')
		}
	default:
		return nil, RedisError("Expecting Prefix '$' or ':'")
	}

	return data, err
}