Beispiel #1
1
func (*GrubTester) TestParseGfxmode(c *C.C) {
	sw, sh := getPrimaryScreenBestResolution()
	data := []struct {
		v    string
		w, h uint16
	}{
		{"auto", sw, sh},
		{"auto,800x600", sw, sh},
		{"1024x768", 1024, 768},
		{"1024x768x24", 1024, 768},
		{"1024x768,800x600,auto", 1024, 768},
		{"1024x768;800x600;auto", 1024, 768},
		{"1024x768x24,800x600,auto", 1024, 768},
	}
	for _, d := range data {
		w, h, _ := doParseGfxmode(d.v)
		c.Check(w, C.Equals, d.w)
		c.Check(h, C.Equals, d.h)
	}

	// test wrong format
	_, _, err := doParseGfxmode("")
	c.Check(err, C.NotNil)
	_, _, err = doParseGfxmode("1024")
	c.Check(err, C.NotNil)
	_, _, err = doParseGfxmode("1024x")
	c.Check(err, C.NotNil)
	_, _, err = doParseGfxmode("autox24")
	c.Check(err, C.NotNil)
}
Beispiel #2
0
func (*facadeRegistrySuite) TestWrapNewFacadeCallsFunc(c *gc.C) {
	wrapped, _, err := common.WrapNewFacade(validFactory)
	c.Assert(err, gc.IsNil)
	val, err := wrapped(nil, nil, nil, "")
	c.Assert(err, gc.IsNil)
	c.Check(*(val.(*int)), gc.Equals, 100)
}
Beispiel #3
0
func (s *V4SignerSuite) TestCases(c *gocheck.C) {
	signer := aws.NewV4Signer(s.auth, "host", s.region)

	for _, testCase := range s.cases {

		req, err := http.NewRequest(testCase.request.method, "http://"+testCase.request.host+testCase.request.url, strings.NewReader(testCase.request.body))
		c.Assert(err, gocheck.IsNil, gocheck.Commentf("Testcase: %s", testCase.label))
		for _, v := range testCase.request.headers {
			h := strings.SplitN(v, ":", 2)
			req.Header.Add(h[0], h[1])
		}
		req.Header.Set("host", req.Host)

		t := signer.RequestTime(req)

		canonicalRequest := signer.CanonicalRequest(req)
		c.Check(canonicalRequest, gocheck.Equals, testCase.canonicalRequest, gocheck.Commentf("Testcase: %s", testCase.label))

		stringToSign := signer.StringToSign(t, canonicalRequest)
		c.Check(stringToSign, gocheck.Equals, testCase.stringToSign, gocheck.Commentf("Testcase: %s", testCase.label))

		signature := signer.Signature(t, stringToSign)
		c.Check(signature, gocheck.Equals, testCase.signature, gocheck.Commentf("Testcase: %s", testCase.label))

		authorization := signer.Authorization(req.Header, t, signature)
		c.Check(authorization, gocheck.Equals, testCase.authorization, gocheck.Commentf("Testcase: %s", testCase.label))

		signer.Sign(req)
		c.Check(req.Header.Get("Authorization"), gocheck.Equals, testCase.authorization, gocheck.Commentf("Testcase: %s", testCase.label))
	}
}
Beispiel #4
0
func checkToolsContent(c *gc.C, data []byte, uploaded string) {
	zr, err := gzip.NewReader(bytes.NewReader(data))
	c.Check(err, gc.IsNil)
	defer zr.Close()
	tr := tar.NewReader(zr)
	found := false
	for {
		hdr, err := tr.Next()
		if err == io.EOF {
			break
		}
		c.Check(err, gc.IsNil)
		if strings.ContainsAny(hdr.Name, "/\\") {
			c.Fail()
		}
		if hdr.Typeflag != tar.TypeReg {
			c.Fail()
		}
		content, err := ioutil.ReadAll(tr)
		c.Check(err, gc.IsNil)
		c.Check(string(content), gc.Equals, uploaded)
		found = true
	}
	c.Check(found, jc.IsTrue)
}
Beispiel #5
0
func (s *localServerSuite) TestResolveNetworkNotPresent(c *gc.C) {
	env := s.Prepare(c)
	var notPresentNetwork = "no-network-with-this-label"
	networkId, err := openstack.ResolveNetwork(env, notPresentNetwork)
	c.Check(networkId, gc.Equals, "")
	c.Assert(err, gc.ErrorMatches, `No networks exist with label "no-network-with-this-label"`)
}
Beispiel #6
0
func (s *ClientTests) TestConfigureHealthCheck(c *gocheck.C) {
	createLBReq := elb.CreateLoadBalancer{
		Name:       "testlb",
		AvailZones: []string{"us-east-1a"},
		Listeners: []elb.Listener{
			{
				InstancePort:     80,
				InstanceProtocol: "http",
				LoadBalancerPort: 80,
				Protocol:         "http",
			},
		},
	}
	_, err := s.elb.CreateLoadBalancer(&createLBReq)
	c.Assert(err, gocheck.IsNil)
	defer func() {
		_, err := s.elb.DeleteLoadBalancer(createLBReq.Name)
		c.Check(err, gocheck.IsNil)
	}()
	hc := elb.HealthCheck{
		HealthyThreshold:   10,
		Interval:           30,
		Target:             "HTTP:80/",
		Timeout:            5,
		UnhealthyThreshold: 2,
	}
	resp, err := s.elb.ConfigureHealthCheck(createLBReq.Name, &hc)
	c.Assert(err, gocheck.IsNil)
	c.Assert(resp.HealthCheck.HealthyThreshold, gocheck.Equals, 10)
	c.Assert(resp.HealthCheck.Interval, gocheck.Equals, 30)
	c.Assert(resp.HealthCheck.Target, gocheck.Equals, "HTTP:80/")
	c.Assert(resp.HealthCheck.Timeout, gocheck.Equals, 5)
	c.Assert(resp.HealthCheck.UnhealthyThreshold, gocheck.Equals, 2)
}
Beispiel #7
0
func (s *preallocSuite) TestFsAvailSpaceErrors(c *gc.C) {
	tests := []struct {
		desc   string
		output string
		err    string
	}{{
		desc: "result is non-numeric",
		output: `Filesystem     1K-blocks    Used Available Use% Mounted on
    /dev/vda1        8124856 1365292       abc  18% /`,
		err: `strconv.ParseInt: parsing "abc": invalid syntax`,
	}, {
		desc:   "not enough lines",
		output: "abc",
		err:    `could not determine available space on ""`,
	}, {
		desc:   "not enough fields on second line",
		output: "abc\ndef",
		err:    `could not determine available space on ""`,
	}}
	for i, test := range tests {
		c.Logf("test %d: %s", i, test.desc)
		testing.PatchExecutable(c, s, "df", "#!/bin/sh\ncat<<EOF\n"+test.output+"\nEOF")
		_, err := mongo.FsAvailSpace("")
		c.Check(err, gc.ErrorMatches, test.err)
	}
}
Beispiel #8
0
func (*testWrapper) TestUserInfoValid(c *C.C) {
	var infos = []struct {
		name  UserInfo
		valid bool
	}{
		{
			UserInfo{Name: "root"},
			false,
		},
		{
			UserInfo{Name: "test1", Shell: "/bin/bash"},
			true,
		},
		{
			UserInfo{Name: "test1", Shell: "/bin/false"},
			false,
		},
		{
			UserInfo{Name: "test1", Shell: "/bin/nologin"},
			false,
		},
		{
			UserInfo{Name: "test3", Shell: "/bin/bash"},
			false,
		},
		{
			UserInfo{Name: "test4", Shell: "/bin/bash"},
			false,
		},
	}

	for _, v := range infos {
		c.Check(v.name.isHumanUser("testdata/shadow"), C.Equals, v.valid)
	}
}
Beispiel #9
0
func (s *loginSuite) TestUsersAreNotRateLimited(c *gc.C) {
	info, cleanup := s.setupServer(c)
	info.Tag = s.AdminUserTag(c)
	info.Password = "******"
	defer cleanup()
	delayChan, cleanup := apiserver.DelayLogins()
	defer cleanup()
	// We can login more than LoginRateLimit users
	nLogins := apiserver.LoginRateLimit * 2
	errResults, wg := startNLogins(c, nLogins, info)
	select {
	case err := <-errResults:
		c.Fatalf("we should not have gotten any logins yet: %v", err)
	case <-time.After(coretesting.ShortWait):
	}
	c.Logf("letting %d logins complete", nLogins)
	for i := 0; i < nLogins; i++ {
		delayChan <- struct{}{}
	}
	c.Logf("waiting for original requests to finish")
	wg.Wait()
	close(errResults)
	for err := range errResults {
		c.Check(err, gc.IsNil)
	}
}
func (*InstanceTypeSuite) TestSelectMachineTypeChecksArch(c *gc.C) {
	unsupportedArch := "amd32k"
	constraint := constraints.Value{Arch: &unsupportedArch}
	_, err := selectMachineType(nil, constraint)
	c.Assert(err, gc.NotNil)
	c.Check(err, gc.ErrorMatches, `requested unsupported architecture "amd32k"`)
}
Beispiel #11
0
func (s *S) TestRemoveOld(c *gocheck.C) {
	config.Set("auth:max-simultaneous-sessions", 6)
	defer config.Unset("auth:max-simultaneous-sessions")
	user := "******"
	defer s.conn.Tokens().RemoveAll(bson.M{"useremail": user})
	initial := time.Now().Add(-48 * time.Hour)
	for i := 0; i < 30; i++ {
		token := Token{
			Token:     fmt.Sprintf("blastoise-%d", i),
			Expires:   100 * 24 * time.Hour,
			Creation:  initial.Add(time.Duration(i) * time.Hour),
			UserEmail: user,
		}
		err := s.conn.Tokens().Insert(token)
		c.Check(err, gocheck.IsNil)
	}
	err := removeOldTokens(user)
	c.Assert(err, gocheck.IsNil)
	var tokens []Token
	err = s.conn.Tokens().Find(bson.M{"useremail": user}).All(&tokens)
	c.Assert(err, gocheck.IsNil)
	c.Assert(tokens, gocheck.HasLen, 6)
	names := make([]string, len(tokens))
	for i := range tokens {
		names[i] = tokens[i].Token
	}
	expected := []string{
		"blastoise-24", "blastoise-25", "blastoise-26",
		"blastoise-27", "blastoise-28", "blastoise-29",
	}
	c.Assert(names, gocheck.DeepEquals, expected)
}
Beispiel #12
0
func (s *gomaxprocsSuite) TestUseMultipleCPUsWhenEnabled(c *gc.C) {
	utils.UseMultipleCPUs()
	c.Check(s.setMaxProcs, gc.Equals, 2)
	s.numCPUResponse = 4
	utils.UseMultipleCPUs()
	c.Check(s.setMaxProcs, gc.Equals, 4)
}
Beispiel #13
0
func (s *unitUpgraderSuite) TestSetTools(c *gc.C) {
	cur := version.Current
	_, err := s.rawUnit.AgentTools()
	c.Assert(err, jc.Satisfies, errors.IsNotFound)
	args := params.EntitiesVersion{
		AgentTools: []params.EntityVersion{{
			Tag: s.rawUnit.Tag(),
			Tools: &params.Version{
				Version: cur,
			}},
		},
	}
	results, err := s.upgrader.SetTools(args)
	c.Assert(err, gc.IsNil)
	c.Assert(results.Results, gc.HasLen, 1)
	c.Assert(results.Results[0].Error, gc.IsNil)
	// Check that the new value actually got set, we must Refresh because
	// it was set on a different Machine object
	err = s.rawUnit.Refresh()
	c.Assert(err, gc.IsNil)
	realTools, err := s.rawUnit.AgentTools()
	c.Assert(err, gc.IsNil)
	c.Check(realTools.Version.Arch, gc.Equals, cur.Arch)
	c.Check(realTools.Version.Series, gc.Equals, cur.Series)
	c.Check(realTools.Version.Major, gc.Equals, cur.Major)
	c.Check(realTools.Version.Minor, gc.Equals, cur.Minor)
	c.Check(realTools.Version.Patch, gc.Equals, cur.Patch)
	c.Check(realTools.Version.Build, gc.Equals, cur.Build)
	c.Check(realTools.URL, gc.Equals, "")
}
Beispiel #14
0
func (*facadeRegistrySuite) TestGetType(c *gc.C) {
	r := &common.FacadeRegistry{}
	c.Assert(r.Register("name", 0, validIdFactory, intPtrType), gc.IsNil)
	typ, err := r.GetType("name", 0)
	c.Assert(err, gc.IsNil)
	c.Check(typ, gc.Equals, intPtrType)
}
Beispiel #15
0
func (*facadeRegistrySuite) TestRegisterAndList(c *gc.C) {
	r := &common.FacadeRegistry{}
	c.Assert(r.Register("name", 0, validIdFactory, intPtrType), gc.IsNil)
	c.Check(r.List(), gc.DeepEquals, []common.FacadeDescription{
		{Name: "name", Versions: []int{0}},
	})
}
Beispiel #16
0
func (*testWrapper) TestAdminUser(c *C.C) {
	var datas = []struct {
		name  string
		admin bool
	}{
		{
			name:  "wen",
			admin: true,
		},
		{
			name:  "test1",
			admin: true,
		},
		{
			name:  "test2",
			admin: false,
		},
	}

	list, err := getAdminUserList("testdata/group")
	c.Check(err, C.Equals, nil)

	for _, data := range datas {
		c.Check(isStrInArray(data.name, list), C.Equals, data.admin)
	}
}
Beispiel #17
0
func (*testWrapper) TestStrInArray(c *C.C) {
	var array = []string{"abc", "123", "xyz"}

	var datas = []struct {
		value string
		ret   bool
	}{
		{
			value: "abc",
			ret:   true,
		},
		{
			value: "xyz",
			ret:   true,
		},
		{
			value: "abcd",
			ret:   false,
		},
	}

	for _, data := range datas {
		c.Check(isStrInArray(data.value, array), C.Equals, data.ret)
	}
}
func (s *ValidateImageMetadataSuite) TestInitErrors(c *gc.C) {
	for i, t := range validateInitImageErrorTests {
		c.Logf("test %d", i)
		err := coretesting.InitCommand(envcmd.Wrap(&ValidateImageMetadataCommand{}), t.args)
		c.Check(err, gc.ErrorMatches, t.err)
	}
}
Beispiel #19
0
func (s *preallocSuite) TestPreallocFileSizes(c *gc.C) {
	const MB = 1024 * 1024

	tests := []struct {
		desc   string
		size   int
		result []int
	}{{
		desc:   "zero size, zero files",
		size:   0,
		result: nil,
	}, {
		desc:   "exactly divides the max chunk size",
		size:   1024 * MB,
		result: []int{512 * MB, 512 * MB},
	}, {
		desc:   "remainder comes at the beginning",
		size:   1025 * MB,
		result: []int{1 * MB, 512 * MB, 512 * MB},
	}, {
		desc:   "remaining one byte must be padded out to 4096 bytes",
		size:   1024*MB + 1,
		result: []int{4096, 512 * MB, 512 * MB},
	}}

	for i, test := range tests {
		c.Logf("test %d: %s", i, test.desc)
		sizes := mongo.PreallocFileSizes(test.size)
		c.Check(sizes, gc.DeepEquals, test.result)
	}
}
Beispiel #20
0
func assertToolsList(c *gc.C, list coretools.List, expected []version.Binary) {
	urls := list.URLs()
	c.Check(urls, gc.HasLen, len(expected))
	for _, vers := range expected {
		c.Assert(urls[vers], gc.Not(gc.Equals), "")
	}
}
Beispiel #21
0
func (s *S) TestSchedulerScheduleTeamOwner(c *gocheck.C) {
	a1 := app.App{
		Name:      "impius",
		Teams:     []string{"nodockerforme"},
		TeamOwner: "tsuruteam",
	}
	cont1 := container{ID: "1", Name: "impius1", AppName: a1.Name}
	err := s.storage.Apps().Insert(a1)
	c.Assert(err, gocheck.IsNil)
	defer s.storage.Apps().RemoveAll(bson.M{"name": a1.Name})
	coll := s.storage.Collection(schedulerCollection)
	p := Pool{Name: "pool1", Nodes: []string{"http://url0:1234"}, Teams: []string{"tsuruteam"}}
	err = coll.Insert(p)
	c.Assert(err, gocheck.IsNil)
	defer coll.RemoveAll(bson.M{"_id": p.Name})
	contColl := collection()
	err = contColl.Insert(cont1)
	c.Assert(err, gocheck.IsNil)
	defer contColl.RemoveAll(bson.M{"name": cont1.Name})
	var scheduler segregatedScheduler
	opts := docker.CreateContainerOptions{Name: cont1.Name}
	node, err := scheduler.Schedule(opts, a1.Name)
	c.Assert(err, gocheck.IsNil)
	c.Check(node.ID, gocheck.Equals, "http://url0:1234")
}
Beispiel #22
0
func (s *withoutStateServerSuite) TestDistributionGroupMachineAgentAuth(c *gc.C) {
	anAuthorizer := s.authorizer
	anAuthorizer.Tag = "machine-1"
	anAuthorizer.EnvironManager = false
	anAuthorizer.MachineAgent = true
	provisioner, err := provisioner.NewProvisionerAPI(s.State, s.resources, anAuthorizer)
	c.Check(err, gc.IsNil)
	args := params.Entities{Entities: []params.Entity{
		{Tag: "machine-0"},
		{Tag: "machine-1"},
		{Tag: "machine-42"},
		{Tag: "machine-0-lxc-99"},
		{Tag: "machine-1-lxc-99"},
		{Tag: "machine-1-lxc-99-lxc-100"},
	}}
	result, err := provisioner.DistributionGroup(args)
	c.Assert(err, gc.IsNil)
	c.Assert(result, gc.DeepEquals, params.DistributionGroupResults{
		Results: []params.DistributionGroupResult{
			{Error: apiservertesting.ErrUnauthorized},
			{Result: []instance.Id{}},
			{Error: apiservertesting.ErrUnauthorized},
			// only a machine agent for the container or its
			// parent may access it.
			{Error: apiservertesting.ErrUnauthorized},
			{Error: apiservertesting.NotFoundError("machine 1/lxc/99")},
			{Error: apiservertesting.ErrUnauthorized},
		},
	})
}
Beispiel #23
0
func (s *ClientTests) TestConfigureHealthCheckBadRequest(c *gocheck.C) {
	createLBReq := elb.CreateLoadBalancer{
		Name:       "testlb",
		AvailZones: []string{"us-east-1a"},
		Listeners: []elb.Listener{
			{
				InstancePort:     80,
				InstanceProtocol: "http",
				LoadBalancerPort: 80,
				Protocol:         "http",
			},
		},
	}
	_, err := s.elb.CreateLoadBalancer(&createLBReq)
	c.Assert(err, gocheck.IsNil)
	defer func() {
		_, err := s.elb.DeleteLoadBalancer(createLBReq.Name)
		c.Check(err, gocheck.IsNil)
	}()
	hc := elb.HealthCheck{
		HealthyThreshold:   10,
		Interval:           30,
		Target:             "HTTP:80",
		Timeout:            5,
		UnhealthyThreshold: 2,
	}
	resp, err := s.elb.ConfigureHealthCheck(createLBReq.Name, &hc)
	c.Assert(resp, gocheck.IsNil)
	c.Assert(err, gocheck.NotNil)
	expected := "HealthCheck HTTP Target must specify a port followed by a path that begins with a slash. e.g. HTTP:80/ping/this/path (ValidationError)"
	c.Assert(err.Error(), gocheck.Equals, expected)
}
Beispiel #24
0
// Communicate with all EC2 endpoints to see if they are alive.
func (s *ClientTests) TestRegions(c *gocheck.C) {
	name := sessionName("goamz-region-test")
	perms := []ec2.IPPerm{{
		Protocol:  "tcp",
		FromPort:  80,
		ToPort:    80,
		SourceIPs: []string{"127.0.0.1/32"},
	}}
	errs := make(chan error, len(allRegions))
	for _, region := range allRegions {
		go func(r aws.Region) {
			e := ec2.New(s.ec2.Auth, r)
			_, err := e.AuthorizeSecurityGroup(ec2.SecurityGroup{Name: name}, perms)
			errs <- err
		}(region)
	}
	for _ = range allRegions {
		err := <-errs
		if err != nil {
			ec2_err, ok := err.(*ec2.Error)
			if ok {
				c.Check(ec2_err.Code, gocheck.Matches, "InvalidGroup.NotFound")
			} else {
				c.Errorf("Non-EC2 error: %s", err)
			}
		} else {
			c.Errorf("Test should have errored but it seems to have succeeded")
		}
	}
}
Beispiel #25
0
// TODO (wallyworld) - this test was copied from the ec2 provider.
// It should be moved to environs.jujutests.Tests.
func (s *localServerSuite) TestBootstrapInstanceUserDataAndState(c *gc.C) {
	env := s.Prepare(c)
	err := bootstrap.Bootstrap(coretesting.Context(c), env, environs.BootstrapParams{})
	c.Assert(err, gc.IsNil)

	// check that the state holds the id of the bootstrap machine.
	stateData, err := bootstrap.LoadState(env.Storage())
	c.Assert(err, gc.IsNil)
	c.Assert(stateData.StateInstances, gc.HasLen, 1)

	insts, err := env.AllInstances()
	c.Assert(err, gc.IsNil)
	c.Assert(insts, gc.HasLen, 1)
	c.Check(insts[0].Id(), gc.Equals, stateData.StateInstances[0])

	addresses, err := insts[0].Addresses()
	c.Assert(err, gc.IsNil)
	c.Assert(addresses, gc.Not(gc.HasLen), 0)

	// TODO(wallyworld) - 2013-03-01 bug=1137005
	// The nova test double needs to be updated to support retrieving instance userData.
	// Until then, we can't check the cloud init script was generated correctly.
	// When we can, we should also check cloudinit for a non-manager node (as in the
	// ec2 tests).
}
func (s *S) TestRetire(c *gocheck.C) {
	defer func() {
		if r := recover(); !c.Failed() && r == nil {
			c.Errorf("Should panic in ping, but did not!")
		}
	}()
	Open("127.0.0.1:27017", "tsuru_storage_test")
	sess := conn["127.0.0.1:27017"]
	sess.used = sess.used.Add(-1 * 2 * period)
	conn["127.0.0.1:27017"] = sess
	var ticker time.Ticker
	ch := make(chan time.Time, 1)
	ticker.C = ch
	ch <- time.Now()
	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		retire(&ticker)
		wg.Done()
	}()
	close(ch)
	wg.Wait()
	_, ok := conn["127.0.0.1:27017"]
	c.Check(ok, gocheck.Equals, false)
	sess.s.Ping()
}
Beispiel #27
0
func (s *deployerSuite) TearDownTest(c *gc.C) {
	if s.stateAPI != nil {
		err := s.stateAPI.Close()
		c.Check(err, gc.IsNil)
	}
	s.JujuConnSuite.TearDownTest(c)
}
Beispiel #28
0
func (s *macOSXVersionSuite) TestOSVersion(c *gc.C) {
	knownSeries := set.Strings{}
	for _, series := range macOSXSeries {
		knownSeries.Add(series)
	}
	c.Check(osVersion(), jc.Satisfies, knownSeries.Contains)
}
Beispiel #29
0
func (s *LxcSuite) TestContainerManagerLXCClone(c *gc.C) {
	type test struct {
		releaseVersion string
		useClone       string
		expectClone    bool
	}
	tests := []test{{
		releaseVersion: "12.04",
		useClone:       "true",
		expectClone:    true,
	}, {
		releaseVersion: "14.04",
		expectClone:    true,
	}, {
		releaseVersion: "12.04",
		useClone:       "false",
	}, {
		releaseVersion: "14.04",
		useClone:       "false",
	}}

	for i, test := range tests {
		c.Logf("test %d: %v", i, test)
		s.PatchValue(lxc.ReleaseVersion, func() string { return test.releaseVersion })

		mgr, err := lxc.NewContainerManager(container.ManagerConfig{
			container.ConfigName: "juju",
			"use-clone":          test.useClone,
		})
		c.Assert(err, gc.IsNil)
		c.Check(lxc.GetCreateWithCloneValue(mgr), gc.Equals, test.expectClone)
	}
}
Beispiel #30
0
func (*facadeRegistrySuite) TestWrapNewFacadeHandlesId(c *gc.C) {
	wrapped, _, err := common.WrapNewFacade(validFactory)
	c.Assert(err, gc.IsNil)
	val, err := wrapped(nil, nil, nil, "badId")
	c.Check(err, gc.ErrorMatches, "id not found")
	c.Check(val, gc.Equals, nil)
}