示例#1
0
func (s *ConsulCatalogSuite) SetUpSuite(c *check.C) {
	dockerHost := os.Getenv("DOCKER_HOST")
	if dockerHost == "" {
		// FIXME Handle windows -- see if dockerClient already handle that or not
		dockerHost = fmt.Sprintf("unix://%s", opts.DefaultUnixSocket)
	}
	// Make sure we can speak to docker
	dockerClient, err := docker.NewClient(dockerHost)
	c.Assert(err, checker.IsNil, check.Commentf("Error connecting to docker daemon"))
	s.dockerClient = dockerClient

	s.createComposeProject(c, "consul_catalog")
	err = s.composeProject.Up()
	c.Assert(err, checker.IsNil, check.Commentf("Error starting project"))

	consul, err := s.GetContainer("integration-test-consul_catalog_consul_1")
	c.Assert(err, checker.IsNil, check.Commentf("Error finding consul container"))

	s.consulIP = consul.NetworkSettings.IPAddress
	config := api.DefaultConfig()
	config.Address = s.consulIP + ":8500"
	consulClient, err := api.NewClient(config)
	if err != nil {
		c.Fatalf("Error creating consul client")
	}
	s.consulClient = consulClient

	// Wait for consul to elect itself leader
	time.Sleep(2000 * time.Millisecond)
}
示例#2
0
func (s *bakerySuite) TestPrimaryKey(c *gc.C) {
	// Put some records in, with some duplicates. Exercises rollbacks.
	c.Assert(s.storage.Put("foo", "bar"), gc.IsNil)
	c.Assert(s.storage.Put("foo", "bar"), gc.NotNil)
	c.Assert(s.storage.Put("foo", "bar"), gc.NotNil)
	_, err := s.storage.Get("nope")
	c.Assert(err, gc.NotNil)
	c.Assert(s.storage.Put("baz", "quux"), gc.IsNil)
	c.Assert(s.storage.Put("baz", "quux"), gc.NotNil)
	c.Assert(s.storage.Put("a", "b"), gc.IsNil)
	c.Assert(s.storage.Put("empty", ""), gc.IsNil)
	for i, testCase := range []struct {
		location, item string
	}{{"foo", "bar"}, {"baz", "quux"}, {"a", "b"}, {"empty", ""}} {
		comment := gc.Commentf("test#%d expect contents %#v", i, testCase)
		item, err := s.storage.Get(testCase.location)
		c.Assert(err, gc.IsNil, comment)
		c.Assert(item, gc.Equals, testCase.item, comment)
	}
	for i, loc := range []string{"foo", "baz", "a", "empty"} {
		comment := gc.Commentf("test#%d expect unique %s", i, loc)
		var count int
		row := s.db.QueryRow("SELECT COUNT(1) FROM bakery WHERE location = $1", loc)
		c.Assert(row.Scan(&count), gc.IsNil, comment)
		c.Assert(count, gc.Equals, 1, comment)
	}
}
示例#3
0
func (s *DockerSuite) SetUpSuite(c *check.C) {
	dockerHost := os.Getenv("DOCKER_HOST")
	if dockerHost == "" {
		// FIXME Handle windows -- see if dockerClient already handle that or not
		dockerHost = fmt.Sprintf("unix://%s", opts.DefaultUnixSocket)
	}
	// Make sure we can speak to docker
	dockerClient, err := docker.NewClient(dockerHost)
	c.Assert(err, checker.IsNil, check.Commentf("Error connecting to docker daemon"))

	s.client = dockerClient
	c.Assert(s.client.Ping(), checker.IsNil)

	// Pull required images
	for repository, tag := range RequiredImages {
		image := fmt.Sprintf("%s:%s", repository, tag)
		_, err := s.client.InspectImage(image)
		if err != nil {
			if err != docker.ErrNoSuchImage {
				c.Fatalf("Error while inspect image %s", image)
			}
			err = s.client.PullImage(docker.PullImageOptions{
				Repository: repository,
				Tag:        tag,
			}, docker.AuthConfiguration{})
			c.Assert(err, checker.IsNil, check.Commentf("Error while pulling image %s", image))
		}
	}
}
示例#4
0
func (s *objectSuite) TestPrimaryKey(c *gc.C) {
	// Put some records in, with some duplicates. Exercises rollbacks.
	c.Assert(s.storage.Put("foo", []byte("bar"), "bar-ish"), gc.IsNil)
	c.Assert(s.storage.Put("foo", []byte("bar"), "bar-ish"), gc.NotNil)
	c.Assert(s.storage.Put("foo", []byte("bar"), "bar-ish"), gc.NotNil)
	_, _, err := s.storage.Get("nope")
	c.Assert(err, gc.NotNil)
	c.Assert(s.storage.Put("baz", []byte("quux"), "quux-ish"), gc.IsNil)
	c.Assert(s.storage.Put("baz", []byte("quux"), "quux-ish"), gc.NotNil)
	c.Assert(s.storage.Put("a", []byte("b"), ""), gc.IsNil)
	c.Assert(s.storage.Put("empty", []byte(""), "nothing-ness"), gc.IsNil)
	for i, testCase := range []struct {
		id, contents, contentType string
	}{{"foo", "bar", "bar-ish"}, {"baz", "quux", "quux-ish"}, {"a", "b", ""}, {"empty", "", "nothing-ness"}} {
		comment := gc.Commentf("test#%d expect contents %#v", i, testCase)
		content, contentType, err := s.storage.Get(testCase.id)
		c.Assert(err, gc.IsNil, comment)
		c.Assert(content, gc.DeepEquals, []byte(testCase.contents), comment)
		c.Assert(contentType, gc.Equals, testCase.contentType, comment)
	}
	for i, id := range []string{"foo", "baz", "a", "empty"} {
		comment := gc.Commentf("test#%d expect unique %s", i, id)
		var count int
		row := s.db.QueryRow("SELECT COUNT(1) FROM object WHERE id = $1", id)
		c.Assert(row.Scan(&count), gc.IsNil, comment)
		c.Assert(count, gc.Equals, 1, comment)
	}
}
示例#5
0
func (s *ConsulCatalogSuite) TestSingleService(c *check.C) {
	cmd := exec.Command(traefikBinary, "--consulCatalog", "--consulCatalog.endpoint="+s.consulIP+":8500", "--consulCatalog.domain=consul.localhost", "--configFile=fixtures/consul_catalog/simple.toml")
	err := cmd.Start()
	c.Assert(err, checker.IsNil)
	defer cmd.Process.Kill()

	nginx, err := s.GetContainer("integration-test-consul_catalog_nginx_1")
	c.Assert(err, checker.IsNil, check.Commentf("Error finding nginx container"))

	err = s.registerService("test", nginx.NetworkSettings.IPAddress, 80)
	c.Assert(err, checker.IsNil, check.Commentf("Error registering service"))
	defer s.deregisterService("test", nginx.NetworkSettings.IPAddress)

	time.Sleep(5000 * time.Millisecond)
	client := &http.Client{}
	req, err := http.NewRequest("GET", "http://127.0.0.1:8000/", nil)
	c.Assert(err, checker.IsNil)
	req.Host = "test.consul.localhost"
	resp, err := client.Do(req)

	c.Assert(err, checker.IsNil)
	c.Assert(resp.StatusCode, checker.Equals, 200)

	_, err = ioutil.ReadAll(resp.Body)
	c.Assert(err, checker.IsNil)
}
示例#6
0
func (s *APIv2Suite) TestRequestMustAppendParamsToURL(c *check.C) {
	mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		c.Check(r.URL.Query()["test-param1"], check.DeepEquals, []string{"test-value1"},
			check.Commentf("Wrong param value"))
		c.Check(r.URL.Query()["test-param2"], check.DeepEquals, []string{"test-value2"},
			check.Commentf("Wrong param value"))

		io.WriteString(w, "{}")
	}))
	c.Assert(mockServer, check.NotNil, check.Commentf("Error creating mock server"))
	defer mockServer.Close()

	mockServerURL, err := url.Parse(mockServer.URL)
	c.Assert(err, check.IsNil, check.Commentf("Error parsing URL: %s", err))

	client := NewClient("test-id")
	client.URL = *mockServerURL

	var r interface{}
	params := url.Values{
		"test-param1": {"test-value1"},
		"test-param2": {"test-value2"},
	}
	err = client.Request("dummy-method", "test-path", params, &r)

	c.Assert(err, check.IsNil, check.Commentf("Error on request: %s", err))
}
示例#7
0
func (s *APIv2Suite) TestRequestMustReturnJSON(c *check.C) {
	testJSON := map[string]interface{}{
		"test-param1": "test-value1",
		"test-param2": "test-value2",
	}

	mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		b, err := json.Marshal(testJSON)
		c.Assert(err, check.IsNil, check.Commentf("Error encoding the JSON: %s", err))
		w.Header().Set("Content-Type", "application/json")
		w.Write(b)
	}))
	c.Assert(mockServer, check.NotNil, check.Commentf("Error creating mock server"))
	defer mockServer.Close()

	mockServerURL, err := url.Parse(mockServer.URL)
	c.Assert(err, check.IsNil, check.Commentf("Error parsing URL: %s", err))

	client := NewClient("test-id")
	client.URL = *mockServerURL

	var r interface{}
	params := url.Values{
		"test-param1": {"test-value1"},
		"test-param2": {"test-value2"},
	}
	err = client.Request("dummy-method", "test-path", params, &r)
	c.Assert(err, check.IsNil, check.Commentf("Error on request: %s", err))

	c.Assert(r, check.DeepEquals, testJSON)
}
示例#8
0
文件: machine_test.go 项目: bac/juju
func (s *MachineSuite) TestMachineAgentSymlinkJujuRunExists(c *gc.C) {
	if runtime.GOOS == "windows" {
		// Cannot make symlink to nonexistent file on windows or
		// create a file point a symlink to it then remove it
		c.Skip("Cannot test this on windows")
	}

	stm, _, _ := s.primeAgent(c, state.JobManageModel)
	a := s.newAgent(c, stm)
	defer a.Stop()

	// Pre-create the symlinks, but pointing to the incorrect location.
	links := []string{jujuRun, jujuDumpLogs}
	a.rootDir = c.MkDir()
	for _, link := range links {
		fullLink := utils.EnsureBaseDir(a.rootDir, link)
		c.Assert(os.MkdirAll(filepath.Dir(fullLink), os.FileMode(0755)), jc.ErrorIsNil)
		c.Assert(symlink.New("/nowhere/special", fullLink), jc.ErrorIsNil, gc.Commentf(link))
	}

	// Start the agent and wait for it be running.
	_, done := s.waitForOpenState(c, a)

	// juju-run symlink should have been recreated.
	for _, link := range links {
		fullLink := utils.EnsureBaseDir(a.rootDir, link)
		linkTarget, err := symlink.Read(fullLink)
		c.Assert(err, jc.ErrorIsNil)
		c.Assert(linkTarget, gc.Not(gc.Equals), "/nowhere/special", gc.Commentf(link))
	}

	s.waitStopped(c, state.JobManageModel, a, done)
}
示例#9
0
func (s *SubunitSuite) TestWithoutFlagsPacketMustNotSetAnyPresentFlag(c *check.C) {
	s.stream.Status(subunit.Event{})
	s.output.Next(1) // skip the signature
	flags := s.output.Next(2)
	flagsHighByte := flags[0] & 0xf // Remove the version, 4 first bits.
	flagsLowByte := flags[1]
	c.Check(flagsHighByte, check.Equals, uint8(0x0), check.Commentf("Wrong flags high byte"))
	c.Check(flagsLowByte, check.Equals, uint8(0x0), check.Commentf("Wrong flags low byte"))
}
示例#10
0
func (s *ParserReportSuite) TestParserReporterReturnsTheNumberOfBytesWritten(c *check.C) {
	actual, err := s.subject.Write([]byte(fmt.Sprintf("****** Running %s\n", s.testID)))
	c.Assert(err, check.IsNil, check.Commentf("Error while writing to output %s", err))

	expected := len([]byte(fmt.Sprintf("test: %s\n", s.testID)))

	c.Assert(actual, check.Equals, expected,
		check.Commentf("Expected length output %d not found, actual %d",
			expected, actual))
}
示例#11
0
func (s *CommonSuite) TestOS(c *checker.C) {
	expwin := (os.PathSeparator == '\\' && os.PathListSeparator == ';')
	res := IsWindows()

	if !expwin {
		c.Assert(res, checker.Equals, expwin, checker.Commentf("IsWindows is", res, "but path is", os.PathSeparator))
	} else {
		c.Assert(res, checker.Not(checker.Equals), expwin, checker.Commentf("IsWindows is", res, "but path is", os.PathSeparator))
	}
}
示例#12
0
文件: pgtest.go 项目: cmars/pgtest
func (s *PGSuite) SetUpSuite(c *gc.C) {
	s.initdbDir = c.MkDir()
	out, err := exec.Command("pg_config", "--bindir").Output()
	c.Assert(err, gc.IsNil, gc.Commentf("pg_config"))

	bindir := string(bytes.TrimSpace(out))
	s.postgres = filepath.Join(bindir, "postgres")
	initdb := filepath.Join(bindir, "initdb")
	err = exec.Command(initdb, "-D", s.initdbDir).Run()
	c.Assert(err, gc.IsNil, gc.Commentf("initdb"))
}
示例#13
0
func (s *FileReportSuite) TestFileReporterReturnsTheNumberOfBytesWritten(c *check.C) {
	testData := "Test data"
	actual, err := s.subject.Write([]byte(testData))
	c.Assert(err, check.IsNil, check.Commentf("Error while writing to output %s", err))

	expected := len([]byte(testData))

	c.Assert(actual, check.Equals, expected,
		check.Commentf("Expected length output %d not found, actual %d",
			expected, actual))
}
示例#14
0
func clientID(c *check.C) string {
	confFile, err := os.Open("conf.json")
	c.Assert(err, check.IsNil, check.Commentf("Error opening conf file: %s", err))
	defer confFile.Close()
	var config conf
	confFileContents, err := ioutil.ReadAll(confFile)
	c.Assert(err, check.IsNil, check.Commentf("Error reading the conf file: %s", err))
	err = json.Unmarshal(confFileContents, &config)
	c.Assert(err, check.IsNil, check.Commentf("Error unmarshaling JSON config: %s", err))
	return config.ClientID
}
示例#15
0
func (s *SubunitSuite) TestPacketMIME(c *check.C) {
	testMIME := "text/plain;charset=utf8"
	s.stream.Status(subunit.Event{MIME: testMIME})
	// skip the signature (1 byte) and the flags (2 bytes)
	s.output.Next(3)
	// skip the packet length (variable size)
	s.readNumber()
	idLen := s.readNumber()
	c.Check(idLen, check.Equals, len(testMIME), check.Commentf("Wrong length"))
	mime := string(s.output.Next(idLen))
	c.Check(mime, check.Equals, testMIME, check.Commentf("Wrong ID"))
}
示例#16
0
func (s *FileReportSuite) TestFileReporterWritesGivenData(c *check.C) {
	s.subject.Write([]byte("Test"))

	content, err := ioutil.ReadFile(s.path)

	c.Assert(err, check.IsNil,
		check.Commentf("Error reading file %s, %s", s.path, err))

	c.Assert(string(content), check.Equals, "Test",
		check.Commentf("Expected content '%s' not found, actual '%s'",
			"Test", string(content)))
}
示例#17
0
func (s *FileReportSuite) TestFileReporterDoNotRecreateOutputFile(c *check.C) {
	s.subject.Write([]byte("Start"))
	s.subject.Write([]byte("-End"))

	content, err := ioutil.ReadFile(s.path)
	c.Assert(err, check.IsNil,
		check.Commentf("Obtained error while reading file %s, %s", s.path, err))

	c.Assert(string(content), check.Equals, "Start-End",
		check.Commentf("Not found appended data in output file! content %s, not found %s",
			string(content), "Start-End"))
}
示例#18
0
// TestStartStop is similar to Tests.TestStartStop except
// that it does not assume a pristine environment.
func (t *LiveTests) TestStartStop(c *gc.C) {
	t.BootstrapOnce(c)

	inst, _ := jujutesting.AssertStartInstance(c, t.Env, "0")
	c.Assert(inst, gc.NotNil)
	id0 := inst.Id()

	insts, err := t.Env.Instances([]instance.Id{id0, id0})
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(insts, gc.HasLen, 2)
	c.Assert(insts[0].Id(), gc.Equals, id0)
	c.Assert(insts[1].Id(), gc.Equals, id0)

	// Asserting on the return of AllInstances makes the test fragile,
	// as even comparing the before and after start values can be thrown
	// off if other instances have been created or destroyed in the same
	// time frame. Instead, just check the instance we created exists.
	insts, err = t.Env.AllInstances()
	c.Assert(err, jc.ErrorIsNil)
	found := false
	for _, inst := range insts {
		if inst.Id() == id0 {
			c.Assert(found, gc.Equals, false, gc.Commentf("%v", insts))
			found = true
		}
	}
	c.Assert(found, gc.Equals, true, gc.Commentf("expected %v in %v", inst, insts))

	addresses, err := jujutesting.WaitInstanceAddresses(t.Env, inst.Id())
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(addresses, gc.Not(gc.HasLen), 0)

	insts, err = t.Env.Instances([]instance.Id{id0, ""})
	c.Assert(err, gc.Equals, environs.ErrPartialInstances)
	c.Assert(insts, gc.HasLen, 2)
	c.Check(insts[0].Id(), gc.Equals, id0)
	c.Check(insts[1], gc.IsNil)

	err = t.Env.StopInstances(inst.Id())
	c.Assert(err, jc.ErrorIsNil)

	// The machine may not be marked as shutting down
	// immediately. Repeat a few times to ensure we get the error.
	for a := t.Attempt.Start(); a.Next(); {
		insts, err = t.Env.Instances([]instance.Id{id0})
		if err != nil {
			break
		}
	}
	c.Assert(err, gc.Equals, environs.ErrNoInstances)
	c.Assert(insts, gc.HasLen, 0)
}
示例#19
0
func (s *serviceSuite) TestAddCharmConcurrently(c *gc.C) {
	var putBarrier sync.WaitGroup
	var blobs blobs
	s.PatchValue(service.NewStateStorage, func(uuid string, session *mgo.Session) statestorage.Storage {
		storage := statestorage.NewStorage(uuid, session)
		return &recordingStorage{Storage: storage, blobs: &blobs, putBarrier: &putBarrier}
	})

	client := s.APIState.Client()
	curl, _ := s.UploadCharm(c, "trusty/wordpress-3", "wordpress")

	// Try adding the same charm concurrently from multiple goroutines
	// to test no "duplicate key errors" are reported (see lp bug
	// #1067979) and also at the end only one charm document is
	// created.

	var wg sync.WaitGroup
	// We don't add them 1-by-1 because that would allow each goroutine to
	// finish separately without actually synchronizing between them
	putBarrier.Add(10)
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func(index int) {
			defer wg.Done()

			c.Assert(client.AddCharm(curl), gc.IsNil, gc.Commentf("goroutine %d", index))
			sch, err := s.State.Charm(curl)
			c.Assert(err, gc.IsNil, gc.Commentf("goroutine %d", index))
			c.Assert(sch.URL(), jc.DeepEquals, curl, gc.Commentf("goroutine %d", index))
		}(i)
	}
	wg.Wait()

	blobs.Lock()

	c.Assert(blobs.m, gc.HasLen, 10)

	// Verify there is only a single uploaded charm remains and it
	// contains the correct data.
	sch, err := s.State.Charm(curl)
	c.Assert(err, jc.ErrorIsNil)
	storagePath := sch.StoragePath()
	c.Assert(blobs.m[storagePath], jc.IsTrue)
	for path, exists := range blobs.m {
		if path != storagePath {
			c.Assert(exists, jc.IsFalse)
		}
	}

	storage := statestorage.NewStorage(s.State.EnvironUUID(), s.State.MongoSession())
	s.assertUploaded(c, storage, sch.StoragePath(), sch.BundleSha256())
}
示例#20
0
文件: prompt.go 项目: bac/juju
// CheckDone asserts that all the expected prompts
// have been printed and all the replies read, and
// reports whether the check succeeded.
func (p *SeqPrompter) CheckDone() bool {
	if p.failed {
		// No point in doing the details checks if
		// a prompt failed earlier - it just makes
		// the resulting test failure noisy.
		p.c.Errorf("prompter has failed")
		return false
	}
	r := p.c.Check(p.ios, gc.HasLen, 0, gc.Commentf("unused prompts"))
	r = p.c.Check(p.HasUnread(), gc.Equals, false, gc.Commentf("some input was not read")) && r
	r = p.c.Check(p.Tail(), gc.Matches, p.finalText, gc.Commentf("final text mismatch")) && r
	return r
}
示例#21
0
func (s *backupsCommonSuite) assertErrorResponse(c *gc.C, resp *http.Response, statusCode int, msg string) *params.Error {
	body, err := ioutil.ReadAll(resp.Body)
	c.Assert(err, jc.ErrorIsNil)

	c.Assert(resp.StatusCode, gc.Equals, statusCode, gc.Commentf("body: %s", body))
	c.Assert(resp.Header.Get("Content-Type"), gc.Equals, params.ContentTypeJSON)

	var failure params.Error
	err = json.Unmarshal(body, &failure)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(&failure, gc.ErrorMatches, msg, gc.Commentf("body: %s", body))
	return &failure
}
示例#22
0
func assertScriptMatch(c *gc.C, got []string, expect string, exact bool) {

	// Convert string slice into line struct slice
	assembleLines := func(lines []string, lineProcessor func(string) string) []line {
		var assembledLines []line
		for lineIdx, currLine := range lines {
			if nil != lineProcessor {
				currLine = lineProcessor(currLine)
			}
			assembledLines = append(assembledLines, line{
				index: lineIdx,
				line:  currLine,
			})
		}
		return assembledLines
	}

	pats := assembleLines(strings.Split(strings.Trim(expect, "\n"), "\n"), nil)
	scripts := assembleLines(got, func(line string) string {
		return strings.Replace(line, "\n", "\\n", -1) // make .* work
	})

	// Pop patterns and scripts off the head as we find pairs
	for {
		switch {
		case len(pats) == 0 && len(scripts) == 0:
			return
		case len(pats) == 0:
			if exact {
				c.Fatalf("too many scripts found (got %q at line %d)", scripts[0].line, scripts[0].index)
			}
			return
		case len(scripts) == 0:
			if exact {
				c.Fatalf("too few scripts found (expected %q at line %d)", pats[0].line, pats[0].index)
			}
			c.Fatalf("could not find match for %q\ngot:\n%s", pats[0].line, strings.Join(got, "\n"))
		default:
			ok, err := regexp.MatchString(pats[0].line, scripts[0].line)
			c.Assert(err, jc.ErrorIsNil, gc.Commentf("invalid regexp: %q", pats[0].line))
			if ok {
				pats = pats[1:]
				scripts = scripts[1:]
			} else if exact {
				c.Assert(scripts[0].line, gc.Matches, pats[0].line, gc.Commentf("line %d; expected %q; got %q; paths: %#v", scripts[0].index, pats[0].line, scripts[0].line, pats))
			} else {
				scripts = scripts[1:]
			}
		}
	}
}
示例#23
0
func (s *S) TestResolve(c *gc.C) {
	res, err := http.Get(s.srv.URL + "/pks/lookup?op=get&search=0x44a2d1db")
	c.Assert(err, gc.IsNil)
	res.Body.Close()
	c.Assert(err, gc.IsNil)
	c.Assert(res.StatusCode, gc.Equals, http.StatusNotFound)

	s.addKey(c, "uat.asc")

	keyDocs := s.queryAllKeys(c)
	c.Assert(keyDocs, gc.HasLen, 1)
	c.Assert(keyDocs[0].assertParse(c).ShortKeyID, gc.Equals, "44a2d1db")

	// Should match
	for _, search := range []string{
		// short, long and full fingerprint key IDs match
		"0x44a2d1db", "0xf79362da44a2d1db", "0x81279eee7ec89fb781702adaf79362da44a2d1db",

		// subkeys
		"0xdb769d16cdb9ad53", "0xe9ebaf4195c1826c", "0x6cdc23d76cba8ca9",

		// contiguous words and email addresses match
		"casey", "marshall", "marshal", "casey+marshall", "cAseY+MArSHaLL",
		"*****@*****.**", "*****@*****.**"} {
		comment := gc.Commentf("search=%s", search)
		res, err = http.Get(s.srv.URL + "/pks/lookup?op=get&search=" + search)
		c.Assert(err, gc.IsNil, comment)
		armor, err := ioutil.ReadAll(res.Body)
		res.Body.Close()
		c.Assert(err, gc.IsNil, comment)
		c.Assert(res.StatusCode, gc.Equals, http.StatusOK, comment)

		keys := openpgp.MustReadArmorKeys(bytes.NewBuffer(armor)).MustParse()
		c.Assert(keys, gc.HasLen, 1)
		c.Assert(keys[0].ShortID(), gc.Equals, "44a2d1db")
		c.Assert(keys[0].UserIDs, gc.HasLen, 2)
		c.Assert(keys[0].UserAttributes, gc.HasLen, 1)
		c.Assert(keys[0].UserIDs[0].Keywords, gc.Equals, "Casey Marshall <*****@*****.**>")
	}

	// Shouldn't match any of these
	for _, search := range []string{
		"0xdeadbeef", "0xce353cf4", "0xd1db", "44a2d1db", "0xadaf79362da44a2d1db",
		"*****@*****.**", "*****@*****.**", "com"} {
		comment := gc.Commentf("search=%s", search)
		res, err = http.Get(s.srv.URL + "/pks/lookup?op=get&search=" + search)
		c.Assert(err, gc.IsNil, comment)
		res.Body.Close()
		c.Assert(res.StatusCode, gc.Equals, http.StatusNotFound, comment)
	}
}
示例#24
0
func (*desiredPeerGroupSuite) TestDesiredPeerGroup(c *gc.C) {
	DoTestForIPv4AndIPv6(func(ipVersion TestIPVersion) {
		for i, test := range desiredPeerGroupTests(ipVersion) {
			c.Logf("\ntest %d: %s", i, test.about)
			machineMap := make(map[string]*machine)
			for _, m := range test.machines {
				c.Assert(machineMap[m.id], gc.IsNil)
				machineMap[m.id] = m
			}
			info := &peerGroupInfo{
				machines: machineMap,
				statuses: test.statuses,
				members:  test.members,
			}
			members, voting, err := desiredPeerGroup(info)
			if test.expectErr != "" {
				c.Assert(err, gc.ErrorMatches, test.expectErr)
				c.Assert(members, gc.IsNil)
				continue
			}
			sort.Sort(membersById(members))
			c.Assert(members, jc.DeepEquals, test.expectMembers)
			if len(members) == 0 {
				continue
			}
			for i, m := range test.machines {
				vote, votePresent := voting[m]
				c.Check(votePresent, jc.IsTrue)
				c.Check(vote, gc.Equals, test.expectVoting[i], gc.Commentf("machine %s", m.id))
			}
			// Assure ourselves that the total number of desired votes is odd in
			// all circumstances.
			c.Assert(countVotes(members)%2, gc.Equals, 1)

			// Make sure that when the members are set as
			// required, that there's no further change
			// if desiredPeerGroup is called again.
			info.members = members
			members, voting, err = desiredPeerGroup(info)
			c.Assert(members, gc.IsNil)
			for i, m := range test.machines {
				vote, votePresent := voting[m]
				c.Check(votePresent, jc.IsTrue)
				c.Check(vote, gc.Equals, test.expectVoting[i], gc.Commentf("machine %s", m.id))
			}
			c.Assert(err, jc.ErrorIsNil)
		}
	})
}
示例#25
0
文件: user_test.go 项目: juju/names
func (s *userSuite) TestIsValidUserNameOrDomain(c *gc.C) {
	for i, t := range []struct {
		string string
		expect bool
	}{
		{"", false},
		{"bob", true},
		{"Bob", true},
		{"bOB", true},
		{"b^b", false},
		{"bob1", true},
		{"bob-1", true},
		{"bob+1", true},
		{"bob+", false},
		{"+bob", false},
		{"bob.1", true},
		{"1bob", true},
		{"1-bob", true},
		{"1+bob", true},
		{"1.bob", true},
		{"jim.bob+99-1.", false},
		{"a", false},
		{"0foo", true},
		{"foo bar", false},
		{"bar{}", false},
		{"bar+foo", true},
		{"bar_foo", false},
		{"bar!", false},
		{"bar^", false},
		{"bar*", false},
		{"foo=bar", false},
		{"foo?", false},
		{"[bar]", false},
		{"'foo'", false},
		{"%bar", false},
		{"&bar", false},
		{"#1foo", false},
		{"[email protected]", false},
		{"bar@local", false},
		{"bar@ubuntuone", false},
		{"bar@", false},
		{"@local", false},
		{"not/valid", false},
	} {
		c.Logf("test %d: %s", i, t.string)
		c.Assert(names.IsValidUserName(t.string), gc.Equals, t.expect, gc.Commentf("%s", t.string))
		c.Assert(names.IsValidUserDomain(t.string), gc.Equals, t.expect, gc.Commentf("%s", t.string))
	}
}
示例#26
0
func (s *SubunitSuite) TestPacketTestID(c *check.C) {
	for _, t := range idtests {
		s.output.Reset()
		testID := t.testIDPrefix + strings.Repeat("_", t.testIDLen-len(t.testIDPrefix))
		s.stream.Status(subunit.Event{TestID: testID, Status: ""})
		// skip the signature (1 byte) and the flags (2 bytes)
		s.output.Next(3)
		// skip the packet length (variable size)
		s.readNumber()
		idLen := s.readNumber()
		c.Check(idLen, check.Equals, len(testID), check.Commentf("Wrong length"))
		id := string(s.output.Next(idLen))
		c.Check(id, check.Equals, testID, check.Commentf("Wrong ID"))
	}
}
示例#27
0
文件: gui_test.go 项目: bac/juju
func (s *guiArchiveSuite) TestGUIArchivePostCurrent(c *gc.C) {
	// Add an existing GUI archive and set it as the current one.
	storage, err := s.State.GUIStorage()
	c.Assert(err, jc.ErrorIsNil)
	defer storage.Close()
	vers := version.MustParse("2.0.47")
	setupGUIArchive(c, storage, vers.String(), nil)
	err = s.State.GUISetVersion(vers)
	c.Assert(err, jc.ErrorIsNil)

	// Create a GUI archive to be uploaded.
	r, hash, _ := makeGUIArchive(c, vers.String(), map[string]string{"filename": "content"})

	// Prepare and send the request to upload a new GUI archive.
	v := url.Values{}
	v.Set("version", vers.String())
	v.Set("hash", hash)
	resp := s.authRequest(c, httpRequestParams{
		method:      "POST",
		url:         s.guiURL(c) + "?" + v.Encode(),
		contentType: apiserver.BZMimeType,
		body:        r,
	})

	// Check that the response reflects a successful upload.
	body := assertResponse(c, resp, http.StatusOK, params.ContentTypeJSON)
	var jsonResponse params.GUIArchiveVersion
	err = json.Unmarshal(body, &jsonResponse)
	c.Assert(err, jc.ErrorIsNil, gc.Commentf("body: %s", body))
	c.Assert(jsonResponse, jc.DeepEquals, params.GUIArchiveVersion{
		Version: vers,
		SHA256:  hash,
		Current: true,
	})
}
示例#28
0
文件: gui_test.go 项目: bac/juju
func (s *guiArchiveSuite) TestGUIArchivePostErrors(c *gc.C) {
	type exoticReader struct {
		io.Reader
	}
	for i, test := range guiArchivePostErrorsTests {
		c.Logf("\n%d: %s", i, test.about)

		// Prepare the request.
		var r io.Reader = strings.NewReader("archive contents")
		if test.noContentLength {
			// net/http will automatically add a Content-Length header if it
			// sees *strings.Reader, but not if it's a type it doesn't know.
			r = exoticReader{r}
		}

		// Send the request and retrieve the error response.
		resp := s.authRequest(c, httpRequestParams{
			method:      "POST",
			url:         s.guiURL(c) + test.query,
			contentType: test.contentType,
			body:        r,
		})
		body := assertResponse(c, resp, test.expectedStatus, params.ContentTypeJSON)
		var jsonResp params.ErrorResult
		err := json.Unmarshal(body, &jsonResp)
		c.Assert(err, jc.ErrorIsNil, gc.Commentf("body: %s", body))
		c.Assert(jsonResp.Error.Message, gc.Matches, test.expectedError)
	}
}
示例#29
0
文件: tools_test.go 项目: bac/juju
func (s *toolsCommonSuite) assertResponse(c *gc.C, resp *http.Response, expStatus int) params.ToolsResult {
	body := assertResponse(c, resp, expStatus, params.ContentTypeJSON)
	var toolsResponse params.ToolsResult
	err := json.Unmarshal(body, &toolsResponse)
	c.Assert(err, jc.ErrorIsNil, gc.Commentf("body: %s", body))
	return toolsResponse
}
示例#30
0
func (s *SubunitSuite) TestPacketMustContainVersion2Flag(c *check.C) {
	s.stream.Status(subunit.Event{TestID: "dummytest", Status: "dummystatus"})
	s.output.Next(1) // skip the signature.
	flags := s.output.Next(2)
	version := flags[0] >> 4 // 4 first bits of the first byte.
	c.Assert(version, check.Equals, uint8(0x2), check.Commentf("Wrong version"))
}