コード例 #1
1
ファイル: recover_test.go プロジェクト: voiid/authboss
func TestRecover_startHandlerFunc_GET(t *testing.T) {
	t.Parallel()

	rec, _, _ := testSetup()
	ctx, w, r, _ := testRequest(rec.Authboss, "GET")

	if err := rec.startHandlerFunc(ctx, w, r); err != nil {
		t.Error("Unexpected error:", err)
	}

	if w.Code != http.StatusOK {
		t.Error("Unexpected status:", w.Code)
	}

	body := w.Body.String()
	if !strings.Contains(body, `<form action="recover"`) {
		t.Error("Should have rendered a form")
	}
	if !strings.Contains(body, `name="`+rec.PrimaryID) {
		t.Error("Form should contain the primary ID field")
	}
	if !strings.Contains(body, `name="confirm_`+rec.PrimaryID) {
		t.Error("Form should contain the confirm primary ID field")
	}
}
コード例 #2
0
ファイル: docker_cli_push_test.go プロジェクト: ranid/docker
func (s *DockerTrustSuite) TestTrustedPushWithIncorrectPassphraseForNonRoot(c *check.C) {
	repoName := fmt.Sprintf("%v/dockercliincorretpwd/trusted:latest", privateRegistryURL)
	// tag the image and upload it to the private registry
	dockerCmd(c, "tag", "busybox", repoName)

	// Push with default passphrases
	pushCmd := exec.Command(dockerBinary, "push", repoName)
	s.trustedCmd(pushCmd)
	out, _, err := runCommandWithOutput(pushCmd)
	if err != nil {
		c.Fatalf("trusted push failed: %s\n%s", err, out)
	}

	if !strings.Contains(string(out), "Signing and pushing trust metadata") {
		c.Fatalf("Missing expected output on trusted push:\n%s", out)
	}

	// Push with wrong passphrases
	pushCmd = exec.Command(dockerBinary, "push", repoName)
	s.trustedCmdWithPassphrases(pushCmd, "12345678", "87654321")
	out, _, err = runCommandWithOutput(pushCmd)
	if err == nil {
		c.Fatalf("Error missing from trusted push with short targets passphrase: \n%s", out)
	}

	if !strings.Contains(string(out), "password invalid, operation has failed") {
		c.Fatalf("Missing expected output on trusted push with short targets/snapsnot passphrase:\n%s", out)
	}
}
コード例 #3
0
ファイル: dialer.go プロジェクト: sunjiahz/goproxy
func (d *Dialer) DialTLS(network, address string) (net.Conn, error) {
	switch network {
	case "tcp", "tcp4", "tcp6":
		if host, port, err := net.SplitHostPort(address); err == nil {
			if alias0, ok := d.hosts.Lookup(host); ok {
				alias := alias0.(string)
				if hosts, err := d.iplist.Lookup(alias); err == nil {
					config := &tls.Config{
						InsecureSkipVerify: true,
						ServerName:         address,
					}
					if strings.Contains(address, ".appspot.com") ||
						strings.Contains(address, ".google") ||
						strings.Contains(address, ".gstatic.com") ||
						strings.Contains(address, ".ggpht.com") {
						config.ServerName = "www.bing.com"
						config.CipherSuites = []uint16{tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA}
					}

					addrs := make([]string, len(hosts))
					for i, host := range hosts {
						addrs[i] = net.JoinHostPort(host, port)
					}
					return d.dialMultiTLS(network, addrs, config)
				}
			}
		}
	default:
		break
	}
	return tls.DialWithDialer(&d.Dialer, network, address, d.TLSConfig)
}
コード例 #4
0
ファイル: describe_test.go プロジェクト: ngbinh/kubernetes
func TestDefaultDescribers(t *testing.T) {
	out, err := DefaultObjectDescriber.DescribeObject(&api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}})
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if !strings.Contains(out, "foo") {
		t.Errorf("unexpected output: %s", out)
	}

	out, err = DefaultObjectDescriber.DescribeObject(&api.Service{ObjectMeta: api.ObjectMeta{Name: "foo"}})
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if !strings.Contains(out, "foo") {
		t.Errorf("unexpected output: %s", out)
	}

	out, err = DefaultObjectDescriber.DescribeObject(&api.ReplicationController{ObjectMeta: api.ObjectMeta{Name: "foo"}})
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if !strings.Contains(out, "foo") {
		t.Errorf("unexpected output: %s", out)
	}

	out, err = DefaultObjectDescriber.DescribeObject(&api.Node{ObjectMeta: api.ObjectMeta{Name: "foo"}})
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if !strings.Contains(out, "foo") {
		t.Errorf("unexpected output: %s", out)
	}
}
コード例 #5
0
func TestBuildWithVolumeOwnership(t *testing.T) {
	name := "testbuildimg"
	defer deleteImages(name)

	_, err := buildImage(name,
		`FROM busybox:latest
        RUN mkdir /test && chown daemon:daemon /test && chmod 0600 /test
        VOLUME /test`,
		true)

	if err != nil {
		t.Fatal(err)
	}

	cmd := exec.Command(dockerBinary, "run", "--rm", "testbuildimg", "ls", "-la", "/test")
	out, _, err := runCommandWithOutput(cmd)
	if err != nil {
		t.Fatal(err)
	}

	if expected := "drw-------"; !strings.Contains(out, expected) {
		t.Fatalf("expected %s received %s", expected, out)
	}

	if expected := "daemon   daemon"; !strings.Contains(out, expected) {
		t.Fatalf("expected %s received %s", expected, out)
	}

	logDone("build - volume ownership")
}
コード例 #6
0
ファイル: morph.go プロジェクト: kdar/morphgen
// options:
//  url - url to generate codes from
//  notmog - turn off grabbing transmogged items from armory
func (g *Generator) Generate(options map[string]interface{}, w io.Writer) error {
	url := to.String(options["url"])
	var tmorphItems TMorphItems
	var err error
	switch {
	case strings.Contains(url, "wowhead.com"):
		tmorphItems, err = wowhead(options)
	case strings.Contains(url, "battle.net/wow"):
		tmorphItems, err = wowarmory(options)
	case strings.Contains(url, "http"):
		tmorphItems, err = generic(options)
	default:
		return errors.New("Do not recognize the URL.")
	}

	if err != nil {
		return err
	}

	g.lastTmorphItems = tmorphItems
	bonus := int(to.Int64(options["bonus"]))
	g.Bonus(bonus)
	g.Output(w)

	return nil
}
コード例 #7
0
ファイル: api_test.go プロジェクト: asvins/warehouse
func TestWithdrawalBuildQuery(t *testing.T) {
	fmt.Println("[INFO] -- TestWithdrawalBuildQuery start --")
	querystring := map[string][]string{"gte": {"quantity|200", "approved_at|123456789"}, "eq": {"product_id|45", "order_id|100", "name|h2oh", "2"}}
	w := Withdrawal{Query: querystring}

	query := w.BuildQuery()
	fmt.Println("[INFO] query = ", query)

	if !strings.Contains(query, "quantity>=200") {
		t.Error("[ERROR] Withdrawal BuildQuery() 'gte'  is broken")
	}

	if !strings.Contains(query, "approved_at>=123456789") {
		t.Error("[ERROR] Withdrawal BuildQuery() 'gte' is broken")
	}

	if !strings.Contains(query, "product_id=45") {
		t.Error("[ERROR] Withdrawal BuildQuery() 'eq' is broken")
	}

	if !strings.Contains(query, "order_id=100") {
		t.Error("[ERROR] Withdrawal BuildQuery() 'eq' is broken")
	}

	if !strings.Contains(query, "name='h2oh'") {
		t.Error("[ERROR] Withdrawal BuildQuery() 'eq' is broken")
	}

	fmt.Println("[INFO] -- TestWithdrawalBuildQuery end --\n")
}
コード例 #8
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))

}
コード例 #9
0
ファイル: scan.go プロジェクト: XiliangSong/gscan
func (options *ScanOptions) SSLMatchHosts(conn *tls.Conn) []string {
	hosts := make([]string, 0)
	options.hostsMutex.Lock()
	for _, host := range options.inputHosts {
		testhost := host.Host
		if strings.Contains(testhost, ".appspot.com") {
			testhost = "appengine.google.com"
		} else if strings.Contains(testhost, "ggpht.com") {
			testhost = "googleusercontent.com"
		} else if strings.Contains(testhost, ".books.google.com") {
			testhost = "books.google.com"
		} else if strings.Contains(testhost, ".googleusercontent.com") {
			testhost = "googleusercontent.com"
		}
		if conn.VerifyHostname(testhost) == nil {
			hosts = append(hosts, host.Host)
		}
	}
	options.hostsMutex.Unlock()
	dest := make([]string, len(hosts))
	perm := rand.Perm(len(hosts))
	for i, v := range perm {
		dest[v] = hosts[i]
	}
	hosts = dest
	return hosts
}
コード例 #10
0
ファイル: cobra_test.go プロジェクト: QuentinPerez/delve
func TestRootHelp(t *testing.T) {
	x := fullSetupTest("--help")

	checkResultContains(t, x, "Available Commands:")
	checkResultContains(t, x, "for more information about a command")

	if strings.Contains(x.Output, "unknown flag: --help") {
		t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output)
	}

	if strings.Contains(x.Output, cmdEcho.Use) {
		t.Errorf("--help shouldn't display subcommand's usage, Got: \n %s", x.Output)
	}

	x = fullSetupTest("echo --help")

	if strings.Contains(x.Output, cmdTimes.Use) {
		t.Errorf("--help shouldn't display subsubcommand's usage, Got: \n %s", x.Output)
	}

	checkResultContains(t, x, "Available Commands:")
	checkResultContains(t, x, "for more information about a command")

	if strings.Contains(x.Output, "unknown flag: --help") {
		t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output)
	}

}
コード例 #11
0
ファイル: default_app.go プロジェクト: felixonmars/dde-daemon
func IsTerminalEmulator(fileName string) bool {
	keyFile := glib.NewKeyFile()
	defer keyFile.Free()
	_, err := keyFile.LoadFromFile(fileName, glib.KeyFileFlagsNone)
	if err != nil {
		logger.Debug("KeyFile Load File Failed:", err)
		return false
	}

	categories, err := keyFile.GetString(_DESKTOP_ENTRY, _CATEGORY)
	if err != nil {
		return false
	}

	if strings.Contains(categories, _TERMINAL_EMULATOR) {
		execName, err := keyFile.GetString(_DESKTOP_ENTRY, _EXEC)
		if err != nil {
			return false
		}

		if strings.Contains(execName, _X_TERMINAL_EMULATOR) {
			return false
		}

		for _, v := range _TerminalBlacklist {
			if strings.Contains(execName, v) {
				return false
			}
		}

		return true
	}

	return false
}
コード例 #12
0
ファイル: hidden_digits.go プロジェクト: oorja/ce-challenges
func main() {
	data, err := os.Open(os.Args[1])
	if err != nil {
		log.Fatal(err)
	}
	defer data.Close()
	scanner := bufio.NewScanner(data)
	for scanner.Scan() {
		maph := func(r rune) rune {
			if strings.Contains("0123456789", string(r)) {
				return r
			} else if strings.Contains("abcdefghij", string(r)) {
				return r - 'a' + '0'
			}
			return -1
		}
		t := strings.Map(maph, scanner.Text())

		if len(t) == 0 {
			fmt.Println("NONE")
		} else {
			fmt.Println(t)
		}
	}
}
コード例 #13
0
ファイル: error_test.go プロジェクト: rawlingsj/gofabric8
func TestErrorString(t *testing.T) {
	e := &Error{Location: "<L>", Message: "<M>", Reason: "<R>"}
	got := e.Error()
	if !strings.Contains(got, "<L>") || !strings.Contains(got, "<M>") || !strings.Contains(got, "<R>") {
		t.Errorf(`got %q, expected to see "<L>", "<M>" and "<R>"`, got)
	}
}
コード例 #14
0
ファイル: docker_cli_push_test.go プロジェクト: ranid/docker
func (s *DockerTrustSuite) TestTrustedPushWithExpiredTimestamp(c *check.C) {
	c.Skip("Currently changes system time, causing instability")
	repoName := fmt.Sprintf("%v/dockercliexpiredtimestamppush/trusted:latest", privateRegistryURL)
	// tag the image and upload it to the private registry
	dockerCmd(c, "tag", "busybox", repoName)

	// Push with default passphrases
	pushCmd := exec.Command(dockerBinary, "push", repoName)
	s.trustedCmd(pushCmd)
	out, _, err := runCommandWithOutput(pushCmd)
	if err != nil {
		c.Fatalf("trusted push failed: %s\n%s", err, out)
	}

	if !strings.Contains(string(out), "Signing and pushing trust metadata") {
		c.Fatalf("Missing expected output on trusted push:\n%s", out)
	}

	// The timestamps expire in two weeks. Lets check three
	threeWeeksLater := time.Now().Add(time.Hour * 24 * 21)

	// Should succeed because the server transparently re-signs one
	runAtDifferentDate(threeWeeksLater, func() {
		pushCmd := exec.Command(dockerBinary, "push", repoName)
		s.trustedCmd(pushCmd)
		out, _, err := runCommandWithOutput(pushCmd)
		if err != nil {
			c.Fatalf("Error running trusted push: %s\n%s", err, out)
		}
		if !strings.Contains(string(out), "Signing and pushing trust metadata") {
			c.Fatalf("Missing expected output on trusted push with expired timestamp:\n%s", out)
		}
	})
}
コード例 #15
0
ファイル: docker_cli_push_test.go プロジェクト: ranid/docker
func (s *DockerTrustSuite) TestTrustedPushWithExpiredSnapshot(c *check.C) {
	c.Skip("Currently changes system time, causing instability")
	repoName := fmt.Sprintf("%v/dockercliexpiredsnapshot/trusted:latest", privateRegistryURL)
	// tag the image and upload it to the private registry
	dockerCmd(c, "tag", "busybox", repoName)

	// Push with default passphrases
	pushCmd := exec.Command(dockerBinary, "push", repoName)
	s.trustedCmd(pushCmd)
	out, _, err := runCommandWithOutput(pushCmd)
	if err != nil {
		c.Fatalf("trusted push failed: %s\n%s", err, out)
	}

	if !strings.Contains(string(out), "Signing and pushing trust metadata") {
		c.Fatalf("Missing expected output on trusted push:\n%s", out)
	}

	// Snapshots last for three years. This should be expired
	fourYearsLater := time.Now().Add(time.Hour * 24 * 365 * 4)

	runAtDifferentDate(fourYearsLater, func() {
		// Push with wrong passphrases
		pushCmd = exec.Command(dockerBinary, "push", repoName)
		s.trustedCmd(pushCmd)
		out, _, err = runCommandWithOutput(pushCmd)
		if err == nil {
			c.Fatalf("Error missing from trusted push with expired snapshot: \n%s", out)
		}

		if !strings.Contains(string(out), "repository out-of-date") {
			c.Fatalf("Missing expected output on trusted push with expired snapshot:\n%s", out)
		}
	})
}
コード例 #16
0
ファイル: recover_test.go プロジェクト: voiid/authboss
func TestRecover_sendRecoverEmail(t *testing.T) {
	t.Parallel()

	r, _, _ := testSetup()

	mailer := mocks.NewMockMailer()
	r.EmailSubjectPrefix = "foo "
	r.RootURL = "bar"
	r.Mailer = mailer

	r.sendRecoverEmail("[email protected]", "abc=")
	if len(mailer.Last.To) != 1 {
		t.Error("Expected 1 to email")
	}
	if mailer.Last.To[0] != "[email protected]" {
		t.Error("Unexpected to email:", mailer.Last.To[0])
	}
	if mailer.Last.Subject != "foo Password Reset" {
		t.Error("Unexpected subject:", mailer.Last.Subject)
	}

	url := fmt.Sprintf("%s/recover/complete?token=abc%%3D", r.RootURL)
	if !strings.Contains(mailer.Last.HTMLBody, url) {
		t.Error("Expected HTMLBody to contain url:", url)
	}
	if !strings.Contains(mailer.Last.TextBody, url) {
		t.Error("Expected TextBody to contain url:", url)
	}
}
コード例 #17
0
ファイル: recover_test.go プロジェクト: voiid/authboss
func TestRecover_completeHandlerFunc_GET(t *testing.T) {
	t.Parallel()

	rec, storer, _ := testSetup()

	storer.Users["john"] = authboss.Attributes{StoreRecoverToken: testStdBase64Token, StoreRecoverTokenExpiry: time.Now().Add(1 * time.Hour)}

	ctx, w, r, _ := testRequest(rec.Authboss, "GET", "token", testURLBase64Token)

	if err := rec.completeHandlerFunc(ctx, w, r); err != nil {
		t.Error("Unexpected error:", err)
	}

	if w.Code != http.StatusOK {
		t.Error("Unexpected status:", w.Code)
	}

	body := w.Body.String()
	if !strings.Contains(body, `<form action="recover/complete"`) {
		t.Error("Should have rendered a form")
	}
	if !strings.Contains(body, `name="password"`) {
		t.Error("Form should contain the password field")
	}
	if !strings.Contains(body, `name="confirm_password"`) {
		t.Error("Form should contain the confirm password field")
	}
	if !strings.Contains(body, `name="token"`) {
		t.Error("Form should contain the token field")
	}
}
コード例 #18
0
ファイル: extractor_test.go プロジェクト: dunglas/calavera
func TestMarkdown_Extract(t *testing.T) {
	creativeWork := schema.NewCreativeWork()

	extractor := Markdown{}
	err := extractor.Extract(creativeWork, "../fixtures/foo.md")

	if err != nil {
		t.Error(err)
	}

	if creativeWork.Name != "Foo" {
		t.Errorf("Title should be \"Foo\", but is \"%s\"." + creativeWork.Name)
	}

	if strings.Contains(creativeWork.Text, ".md") {
		t.Error("References to Markdown file must be changed to references to JSON-LD files.")
	}

	if strings.Contains(creativeWork.Text, "rel=\"nofollow\"") {
		t.Error("Links must be followed by spiders.")
	}

	if !strings.Contains(creativeWork.Text, "class=\"language-php\"") {
		t.Error("Classes must be preserved.")
	}
}
コード例 #19
0
ファイル: vcs.go プロジェクト: klobucar/go
// repoRootForImportPath analyzes importPath to determine the
// version control system, and code repository to use.
func repoRootForImportPath(importPath string, security securityMode) (*repoRoot, error) {
	rr, err := repoRootForImportPathStatic(importPath, "", security)
	if err == errUnknownSite {
		// If there are wildcards, look up the thing before the wildcard,
		// hoping it applies to the wildcarded parts too.
		// This makes 'go get rsc.io/pdf/...' work in a fresh GOPATH.
		lookup := strings.TrimSuffix(importPath, "/...")
		if i := strings.Index(lookup, "/.../"); i >= 0 {
			lookup = lookup[:i]
		}
		rr, err = repoRootForImportDynamic(lookup, security)

		// repoRootForImportDynamic returns error detail
		// that is irrelevant if the user didn't intend to use a
		// dynamic import in the first place.
		// Squelch it.
		if err != nil {
			if buildV {
				log.Printf("import %q: %v", importPath, err)
			}
			err = fmt.Errorf("unrecognized import path %q", importPath)
		}
	}

	if err == nil && strings.Contains(importPath, "...") && strings.Contains(rr.root, "...") {
		// Do not allow wildcards in the repo root.
		rr = nil
		err = fmt.Errorf("cannot expand ... in %q", importPath)
	}
	return rr, err
}
コード例 #20
0
ファイル: select.go プロジェクト: cshapeshifter/wingo
func (slct *Select) FilterItems(search string) {
	bs := slct.theme.BorderSize
	pad := slct.theme.Padding
	inpHeight := slct.input.Geom.Height()
	needle := strings.ToLower(search)

	slct.items = make([]*SelectItem, 0)

	x, y := bs+pad, (2*bs)+pad+inpHeight
	for _, group := range slct.groups {
		shown := false // true when at least 1 item is showing

		if group.hasGroup() {
			group.show(x, y)
			y += group.win.Geom.Height()
		}
		for _, item := range group.items {
			haystack := strings.ToLower(item.text)
			switch slct.tabComplete {
			case TabCompleteAny:
				if !strings.Contains(haystack, needle) {
					item.hide()
					continue
				}
			case TabCompleteMultiple:
				words := strings.Fields(needle)
				match := true
				for _, word := range words {
					if !strings.Contains(haystack, word) {
						match = false
						break
					}
				}
				if !match {
					item.hide()
					continue
				}
			default:
				if !strings.HasPrefix(haystack, needle) {
					item.hide()
					continue
				}
			}

			y += itemTopSpace
			item.show(x, y)
			y += item.regular.Geom.Height() + itemBotSpace
			slct.items = append(slct.items, item)
			shown = true
		}
		if group.hasGroup() {
			if shown {
				y += slct.theme.GroupSpacing
			} else {
				group.hide()
				y -= group.win.Geom.Height()
			}
		}
	}
}
コード例 #21
0
ファイル: environprovider.go プロジェクト: Pankov404/juju
// getHostAndPort expects argument in the form host:port and
// returns host and port as distinctive strings.
func getHostAndPort(original string) (host, port string) {
	// Host and post specification is host:port
	hostAndPortRegexp := regexp.MustCompile(`(?P<host>\[?[::]*[^:]+)(?P<port>$|:[^:]+$)`)

	matched := hostAndPortRegexp.FindStringSubmatch(original)
	if len(matched) == 0 {
		// Passed in parameter is not in the form host:port.
		// Let's not mess with it.
		return original, ""
	}

	// For the string in the form host:port, FindStringSubmatch above
	// will return {host:port, host, :port}
	host = matched[1]
	port = matched[2]

	// For hosts like [::1], remove brackets
	if strings.Contains(host, "[") {
		host = host[1 : len(host)-1]
	}

	// For hosts like ::1, substring :1 is not a port!
	if strings.Contains(host, port) {
		port = ""
	}
	return
}
コード例 #22
0
func (s *DockerSuite) TestCreateByImageID(c *check.C) {
	imageName := "testcreatebyimageid"
	imageID, err := buildImage(imageName,
		`FROM busybox
		MAINTAINER dockerio`,
		true)
	if err != nil {
		c.Fatal(err)
	}
	truncatedImageID := stringid.TruncateID(imageID)

	dockerCmd(c, "create", imageID)
	dockerCmd(c, "create", truncatedImageID)
	dockerCmd(c, "create", fmt.Sprintf("%s:%s", imageName, truncatedImageID))

	// Ensure this fails
	out, exit, _ := dockerCmdWithError("create", fmt.Sprintf("%s:%s", imageName, imageID))
	if exit == 0 {
		c.Fatalf("expected non-zero exit code; received %d", exit)
	}

	if expected := "Error parsing reference"; !strings.Contains(out, expected) {
		c.Fatalf(`Expected %q in output; got: %s`, expected, out)
	}

	out, exit, _ = dockerCmdWithError("create", fmt.Sprintf("%s:%s", "wrongimage", truncatedImageID))
	if exit == 0 {
		c.Fatalf("expected non-zero exit code; received %d", exit)
	}

	if expected := "Unable to find image"; !strings.Contains(out, expected) {
		c.Fatalf(`Expected %q in output; got: %s`, expected, out)
	}
}
コード例 #23
0
ファイル: server_test.go プロジェクト: chenzhen411/kubernetes
func TestServeLogs(t *testing.T) {
	fw := newServerTest()

	content := string(`<pre><a href="kubelet.log">kubelet.log</a><a href="google.log">google.log</a></pre>`)

	fw.fakeKubelet.logFunc = func(w http.ResponseWriter, req *http.Request) {
		w.WriteHeader(http.StatusOK)
		w.Header().Add("Content-Type", "text/html")
		w.Write([]byte(content))
	}

	resp, err := http.Get(fw.testHTTPServer.URL + "/logs/")
	if err != nil {
		t.Fatalf("Got error GETing: %v", err)
	}
	defer resp.Body.Close()

	body, err := httputil.DumpResponse(resp, true)
	if err != nil {
		// copying the response body did not work
		t.Errorf("Cannot copy resp: %#v", err)
	}
	result := string(body)
	if !strings.Contains(result, "kubelet.log") || !strings.Contains(result, "google.log") {
		t.Errorf("Received wrong data: %s", result)
	}
}
コード例 #24
0
ファイル: router_test.go プロジェクト: huyan/beego
// Execution point: FinishRouter
// expectation: only FinishRouter function is executed, match as router handles
func TestFilterFinishRouter(t *testing.T) {
	testName := "TestFilterFinishRouter"
	url := "/finishRouter"

	mux := NewControllerRegister()
	mux.InsertFilter(url, BeforeRouter, beegoFilterNoOutput)
	mux.InsertFilter(url, BeforeExec, beegoFilterNoOutput)
	mux.InsertFilter(url, AfterExec, beegoFilterNoOutput)
	mux.InsertFilter(url, FinishRouter, beegoFinishRouter1)

	mux.Get(url, beegoFilterFunc)

	rw, r := testRequest("GET", url)
	mux.ServeHTTP(rw, r)

	if strings.Contains(rw.Body.String(), "FinishRouter1") == true {
		t.Errorf(testName + " FinishRouter did not run")
	}
	if strings.Contains(rw.Body.String(), "hello") == false {
		t.Errorf(testName + " handler did not run properly")
	}
	if strings.Contains(rw.Body.String(), "AfterExec1") == true {
		t.Errorf(testName + " AfterExec ran in error")
	}
	if strings.Contains(rw.Body.String(), "BeforeRouter") == true {
		t.Errorf(testName + " BeforeRouter ran in error")
	}
	if strings.Contains(rw.Body.String(), "BeforeExec") == true {
		t.Errorf(testName + " BeforeExec ran in error")
	}
}
コード例 #25
0
// #6445 ensure ONBUILD triggers aren't committed to grandchildren
func TestBuildOnBuildLimitedInheritence(t *testing.T) {
	name1 := "testonbuildtrigger1"
	dockerfile1 := `
		FROM busybox
		RUN echo "GRANDPARENT"
		ONBUILD RUN echo "ONBUILD PARENT"
	`
	ctx1, err := fakeContext(dockerfile1, nil)
	if err != nil {
		t.Fatal(err)
	}

	buildCmd := exec.Command(dockerBinary, "build", "-t", name1, ".")
	buildCmd.Dir = ctx1.Dir
	out1, _, err := runCommandWithOutput(buildCmd)
	errorOut(err, t, fmt.Sprintf("build failed to complete: %v %v", out1, err))
	defer deleteImages(name1)

	name2 := "testonbuildtrigger2"
	dockerfile2 := `
		FROM testonbuildtrigger1
	`
	ctx2, err := fakeContext(dockerfile2, nil)
	if err != nil {
		t.Fatal(err)
	}

	buildCmd = exec.Command(dockerBinary, "build", "-t", name2, ".")
	buildCmd.Dir = ctx2.Dir
	out2, _, err := runCommandWithOutput(buildCmd)
	errorOut(err, t, fmt.Sprintf("build failed to complete: %v %v", out2, err))
	defer deleteImages(name2)

	name3 := "testonbuildtrigger3"
	dockerfile3 := `
		FROM testonbuildtrigger2
	`
	ctx3, err := fakeContext(dockerfile3, nil)
	if err != nil {
		t.Fatal(err)
	}

	buildCmd = exec.Command(dockerBinary, "build", "-t", name3, ".")
	buildCmd.Dir = ctx3.Dir
	out3, _, err := runCommandWithOutput(buildCmd)
	errorOut(err, t, fmt.Sprintf("build failed to complete: %v %v", out3, err))
	defer deleteImages(name3)

	// ONBUILD should be run in second build.
	if !strings.Contains(out2, "ONBUILD PARENT") {
		t.Fatalf("ONBUILD instruction did not run in child of ONBUILD parent")
	}

	// ONBUILD should *not* be run in third build.
	if strings.Contains(out3, "ONBUILD PARENT") {
		t.Fatalf("ONBUILD instruction ran in grandchild of ONBUILD parent")
	}

	logDone("build - onbuild")
}
コード例 #26
0
ファイル: registry.go プロジェクト: nbogojevic/origin
func (d *ClusterRegistry) checkRegistryLogs(pod *kapi.Pod, r types.DiagnosticResult) {
	// pull out logs from the pod
	readCloser, err := d.KubeClient.RESTClient.Get().
		Namespace("default").Name(pod.ObjectMeta.Name).
		Resource("pods").SubResource("log").
		Param("follow", "false").
		Param("container", pod.Spec.Containers[0].Name).
		Stream()
	if err != nil {
		r.Warn("DClu1010", nil, fmt.Sprintf(clRegPodLog, pod.ObjectMeta.Name, registryName, fmt.Sprintf("(%T) %[1]v", err)))
		return
	}
	defer readCloser.Close()

	clientError := ""
	registryError := ""
	scanner := bufio.NewScanner(readCloser)
	for scanner.Scan() {
		logLine := scanner.Text()
		// TODO: once the logging API gets "since" and "tail" and "limit", limit to more recent log entries
		// https://github.com/kubernetes/kubernetes/issues/12447
		if strings.Contains(logLine, `level=error msg="client error:`) {
			clientError = logLine // end up showing only the most recent client error
		} else if strings.Contains(logLine, "level=error msg=") {
			registryError += "\n" + logLine // gather generic errors
		}
	}
	if clientError != "" {
		r.Error("DClu1011", nil, fmt.Sprintf(clRegPodConn, pod.ObjectMeta.Name, registryName, clientError))
	}
	if registryError != "" {
		r.Warn("DClu1012", nil, fmt.Sprintf(clRegPodErr, pod.ObjectMeta.Name, registryName, registryError))
	}

}
コード例 #27
0
ファイル: settings.go プロジェクト: microscaling/microscaling
func initLogging() {
	// The MSS_LOG_DEBUG environment variable controls what logging is output
	// By default the log level is INFO for all components
	// Adding a component name to MSS_LOG_DEBUG makes its logging level DEBUG
	// In addition, if "detail" is included in the environment variable details of the process ID and file name / line number are included in the logs
	// MSS_LOG_DEBUG="all" - turn on DEBUG for all components
	// MSS_LOG_DEBUG="mssapi,detail" - turn on DEBUG for the api package, and use the detailed logging format
	basicLogFormat := logging.MustStringFormatter(`%{color}%{level:.4s} %{time:15:04:05.000}: %{color:reset} %{message}`)
	detailLogFormat := logging.MustStringFormatter(`%{color}%{level:.4s} %{time:15:04:05.000} %{pid} %{shortfile}: %{color:reset} %{message}`)

	logComponents := getEnvOrDefault("MSS_LOG_DEBUG", "none")
	if strings.Contains(logComponents, "detail") {
		logging.SetFormatter(detailLogFormat)
	} else {
		logging.SetFormatter(basicLogFormat)
	}

	logBackend := logging.NewLogBackend(os.Stdout, "", 0)
	logging.SetBackend(logBackend)

	var components = []string{"mssagent", "mssapi", "mssconfig", "mssdemand", "mssengine", "mssmetric", "mssscheduler", "msstarget", "mssutils"}

	for _, component := range components {
		if strings.Contains(logComponents, component) || strings.Contains(logComponents, "all") {
			logging.SetLevel(logging.DEBUG, component)
		} else {
			logging.SetLevel(logging.INFO, component)
		}
	}
}
コード例 #28
0
ファイル: replica.go プロジェクト: maniktaneja/luxstor
func IsOwner(req *gomemcached.MCRequest) bool {

	key := req.Key
	nodeList := getVbucketNode(int(findShard(string(key))))
	nodes := strings.Split(nodeList, ";")

	//log.Printf(" Nodes list %v key %s", nodes, string(key))
	if strings.Contains(nodes[0], "localhost") || strings.Contains(nodes[0], "127.0.0.1") || nodes[0] == "" {
		return true
	}

	if len(nodes) < 1 {
		log.Fatal("Nodelist is empty. Cannot proceed")
	}

	for _, node := range nodes {
		hostname := strings.Split(node, ":")
		for _, ip := range ipList {
			if ip == hostname[0] {
				return true
			}
		}
	}

	return false
}
コード例 #29
0
func TestNewAndSet(t *testing.T) {
	dir, teardown, err := setup(t)
	// dir, _, err := setup(t)
	if err != nil {
		t.Fatal(err)
	}
	defer teardown()

	a := account.New()
	a.WltIDs[bitcoin.Type] = "bitcoin_sd110"
	a.WltIDs[skycoin.Type] = "skycoin_sd110"
	account.Set(a)

	// get account
	d, err := ioutil.ReadFile(filepath.Join(dir, account.FileName()))
	if err != nil {
		t.Fatal(err)
	}
	if !strings.Contains(string(d), a.Pubkey) {
		t.Fatal("new account failed")
	}

	if !strings.Contains(string(d), a.Seckey) {
		t.Fatal("new account failed")
	}

	if !strings.Contains(string(d), "bitcoin_sd110") {
		t.Fatal("new account failed")
	}

	if !strings.Contains(string(d), "skycoin_sd110") {
		t.Fatal("new account failed")
	}
}
コード例 #30
0
ファイル: engine.go プロジェクト: rolfedh/swarm
// CheckConnectionErr checks error from client response and adjusts engine healthy indicators
func (e *Engine) CheckConnectionErr(err error) {
	if err == nil {
		e.setErrMsg("")
		// If current state is unhealthy, change it to healthy
		if e.state == stateUnhealthy {
			log.WithFields(log.Fields{"name": e.Name, "id": e.ID}).Infof("Engine came back to life after %d retries. Hooray!", e.failureCount)
			e.emitEvent("engine_reconnect")
			e.setState(stateHealthy)
		}
		e.resetFailureCount()
		return
	}

	// dockerclient defines ErrConnectionRefused error. but if http client is from swarm, it's not using
	// dockerclient. We need string matching for these cases. Remove the first character to deal with
	// case sensitive issue
	if err == dockerclient.ErrConnectionRefused ||
		strings.Contains(err.Error(), "onnection refused") ||
		strings.Contains(err.Error(), "annot connect to the docker engine endpoint") {
		// each connection refused instance may increase failure count so
		// engine can fail fast. Short engine freeze or network failure may result
		// in engine marked as unhealthy. If this causes unnecessary failure, engine
		// can track last error time. Only increase failure count if last error is
		// not too recent, e.g., last error is at least 1 seconds ago.
		e.incFailureCount()
		// update engine error message
		e.setErrMsg(err.Error())
		return
	}
	// other errors may be ambiguous.
}