Ejemplo n.º 1
1
func makeRequestWithManifest(manifest string, c *gocheck.C) (*httptest.ResponseRecorder, *http.Request) {
	b := bytes.NewBufferString(manifest)
	request, err := http.NewRequest("POST", "/services", b)
	c.Assert(err, gocheck.IsNil)
	recorder := httptest.NewRecorder()
	return recorder, request
}
Ejemplo n.º 2
1
func (s *uniterSuite) TestOpenPort(c *gc.C) {
	openedPorts := s.wordpressUnit.OpenedPorts()
	c.Assert(openedPorts, gc.HasLen, 0)

	args := params.EntitiesPorts{Entities: []params.EntityPort{
		{Tag: "unit-mysql-0", Protocol: "tcp", Port: 1234},
		{Tag: "unit-wordpress-0", Protocol: "udp", Port: 4321},
		{Tag: "unit-foo-42", Protocol: "tcp", Port: 42},
	}}
	result, err := s.uniter.OpenPort(args)
	c.Assert(err, gc.IsNil)
	c.Assert(result, gc.DeepEquals, params.ErrorResults{
		Results: []params.ErrorResult{
			{apiservertesting.ErrUnauthorized},
			{nil},
			{apiservertesting.ErrUnauthorized},
		},
	})

	// Verify the wordpressUnit's port is opened.
	err = s.wordpressUnit.Refresh()
	c.Assert(err, gc.IsNil)
	openedPorts = s.wordpressUnit.OpenedPorts()
	c.Assert(openedPorts, gc.DeepEquals, []instance.Port{
		{Protocol: "udp", Number: 4321},
	})
}
Ejemplo n.º 3
1
func (s *uniterSuite) addRelation(c *gc.C, first, second string) *state.Relation {
	eps, err := s.State.InferEndpoints([]string{first, second})
	c.Assert(err, gc.IsNil)
	rel, err := s.State.AddRelation(eps...)
	c.Assert(err, gc.IsNil)
	return rel
}
Ejemplo n.º 4
1
// MakeConfig creates a functional environConfig for a test.
func MakeConfig(c *gc.C, attrs testing.Attrs) *environConfig {
	cfg, err := config.New(config.NoDefaults, attrs)
	c.Assert(err, gc.IsNil)
	env, err := environs.Prepare(cfg, testing.Context(c), configstore.NewMem())
	c.Assert(err, gc.IsNil)
	return env.(*joyentEnviron).Ecfg()
}
Ejemplo n.º 5
1
func (s *S) TestExportEnvironmentsBackward(c *gocheck.C) {
	envNames := []string{
		"TSURU_S3_ACCESS_KEY_ID", "TSURU_S3_SECRET_KEY",
		"TSURU_APPNAME", "TSURU_HOST", "TSURU_S3_ENDPOINT",
		"TSURU_S3_LOCATIONCONSTRAINT", "TSURU_S3_BUCKET",
		"TSURU_APP_TOKEN",
	}
	app := App{Name: "moon", Platform: "opeth", Env: make(map[string]bind.EnvVar)}
	for _, name := range envNames {
		envVar := bind.EnvVar{Name: name, Value: name, Public: false}
		if strings.HasPrefix(name, "TSURU_S3_") {
			envVar.InstanceName = s3InstanceName
		}
		app.Env[name] = envVar
	}
	token, err := auth.CreateApplicationToken(app.Name)
	c.Assert(err, gocheck.IsNil)
	app.Env["TSURU_APP_TOKEN"] = bind.EnvVar{Name: "TSURU_APP_NAME", Value: token.Token}
	err = s.conn.Apps().Insert(app)
	c.Assert(err, gocheck.IsNil)
	defer s.conn.Apps().Remove(bson.M{"name": app.Name})
	ctx := action.BWContext{Params: []interface{}{&app}}
	exportEnvironmentsAction.Backward(ctx)
	copy, err := GetByName(app.Name)
	c.Assert(err, gocheck.IsNil)
	for _, name := range envNames {
		if _, ok := copy.Env[name]; ok {
			c.Errorf("Variable %q should be unexported, but it's still exported.", name)
		}
	}
	_, err = auth.GetToken("bearer " + token.Token)
	c.Assert(err, gocheck.Equals, auth.ErrInvalidToken)
}
Ejemplo n.º 6
1
func (s *MetaSuite) TestMetaHooks(c *gc.C) {
	meta, err := charm.ReadMeta(repoMeta("wordpress"))
	c.Assert(err, gc.IsNil)
	hooks := meta.Hooks()
	expectedHooks := map[string]bool{
		"install":                           true,
		"start":                             true,
		"config-changed":                    true,
		"upgrade-charm":                     true,
		"stop":                              true,
		"cache-relation-joined":             true,
		"cache-relation-changed":            true,
		"cache-relation-departed":           true,
		"cache-relation-broken":             true,
		"db-relation-joined":                true,
		"db-relation-changed":               true,
		"db-relation-departed":              true,
		"db-relation-broken":                true,
		"logging-dir-relation-joined":       true,
		"logging-dir-relation-changed":      true,
		"logging-dir-relation-departed":     true,
		"logging-dir-relation-broken":       true,
		"monitoring-port-relation-joined":   true,
		"monitoring-port-relation-changed":  true,
		"monitoring-port-relation-departed": true,
		"monitoring-port-relation-broken":   true,
		"url-relation-joined":               true,
		"url-relation-changed":              true,
		"url-relation-departed":             true,
		"url-relation-broken":               true,
	}
	c.Assert(hooks, gc.DeepEquals, expectedHooks)
}
Ejemplo n.º 7
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)
}
Ejemplo n.º 8
1
func (t *localServerSuite) TestPrecheckInstanceAvailZonesUnsupported(c *gc.C) {
	t.srv.Service.Nova.SetAvailabilityZones() // no availability zone support
	env := t.Prepare(c)
	placement := "zone=test-unknown"
	err := env.PrecheckInstance("precise", constraints.Value{}, placement)
	c.Assert(err, jc.Satisfies, jujuerrors.IsNotImplemented)
}
Ejemplo n.º 9
0
func (s *localServer) start(c *gc.C, cred *identity.Credentials) {
	// Set up the HTTP server.
	if s.UseTLS {
		s.Server = httptest.NewTLSServer(nil)
	} else {
		s.Server = httptest.NewServer(nil)
	}
	c.Assert(s.Server, gc.NotNil)
	s.oldHandler = s.Server.Config.Handler
	s.Mux = http.NewServeMux()
	s.Server.Config.Handler = s.Mux
	cred.URL = s.Server.URL
	c.Logf("Started service at: %v", s.Server.URL)
	s.Service = openstackservice.New(cred, identity.AuthUserPass)
	s.Service.SetupHTTP(s.Mux)
	s.restoreTimeouts = envtesting.PatchAttemptStrategies(openstack.ShortAttempt, openstack.StorageAttempt)
	s.Service.Nova.SetAvailabilityZones(
		nova.AvailabilityZone{Name: "test-unavailable"},
		nova.AvailabilityZone{
			Name: "test-available",
			State: nova.AvailabilityZoneState{
				Available: true,
			},
		},
	)
}
Ejemplo n.º 10
0
func (s *localServerSuite) TestPrecheckInstanceValidInstanceType(c *gc.C) {
	env := s.Open(c)
	cons := constraints.MustParse("instance-type=m1.small")
	placement := ""
	err := env.PrecheckInstance("precise", cons, placement)
	c.Assert(err, gc.IsNil)
}
Ejemplo n.º 11
0
func (s *localServerSuite) TestPrecheckInstanceInvalidInstanceType(c *gc.C) {
	env := s.Open(c)
	cons := constraints.MustParse("instance-type=m1.large")
	placement := ""
	err := env.PrecheckInstance("precise", cons, placement)
	c.Assert(err, gc.ErrorMatches, `invalid Openstack flavour "m1.large" specified`)
}
Ejemplo n.º 12
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"`)
}
Ejemplo n.º 13
0
func (s *localServerSuite) TestResolveNetworkUUID(c *gc.C) {
	env := s.Prepare(c)
	var sampleUUID = "f81d4fae-7dec-11d0-a765-00a0c91e6bf6"
	networkId, err := openstack.ResolveNetwork(env, sampleUUID)
	c.Assert(err, gc.IsNil)
	c.Assert(networkId, gc.Equals, sampleUUID)
}
Ejemplo n.º 14
0
func (s *ProvisionSuite) makeRequestToServicesHandler(c *gocheck.C) (*httptest.ResponseRecorder, *http.Request) {
	request, err := http.NewRequest("GET", "/services", nil)
	c.Assert(err, gocheck.IsNil)
	request.Header.Set("Content-Type", "application/json")
	recorder := httptest.NewRecorder()
	return recorder, request
}
Ejemplo n.º 15
0
// startReading starts a goroutine receiving the lines out of the reader
// in the background and passing them to a created string channel. This
// will used in the assertions.
func startReading(c *gc.C, tailer *tailer.Tailer, reader *io.PipeReader, writer *io.PipeWriter) chan string {
	linec := make(chan string)
	// Start goroutine for reading.
	go func() {
		defer close(linec)
		reader := bufio.NewReader(reader)
		for {
			line, err := reader.ReadString('\n')
			switch err {
			case nil:
				linec <- line
			case io.EOF:
				return
			default:
				c.Fail()
			}
		}
	}()
	// Close writer when tailer is stopped or has an error. Tailer using
	// components can do it the same way.
	go func() {
		tailer.Wait()
		writer.Close()
	}()
	return linec
}
Ejemplo n.º 16
0
func (s *S) TestCollectStatusIDChangeFromPending(c *gocheck.C) {
	server, url := badGatewayServer()
	defer server.Close()
	tmpdir, err := commandmocker.Add("juju", generateOutput(url))
	c.Assert(err, gocheck.IsNil)
	defer commandmocker.Remove(tmpdir)
	p := JujuProvisioner{}
	collection := p.unitsCollection()
	defer collection.Close()
	err = collection.Insert(instance{UnitName: "as_i_rise/0", InstanceID: "pending"})
	c.Assert(err, gocheck.IsNil)
	defer collection.Remove(bson.M{"_id": bson.M{"$in": []string{"as_i_rise/0", "the_infanta/0"}}})
	_, err = p.CollectStatus()
	c.Assert(err, gocheck.IsNil)
	done := make(chan int8)
	go func() {
		for {
			q := bson.M{"_id": "as_i_rise/0", "instanceid": "i-00000439"}
			ct, err := collection.Find(q).Count()
			c.Assert(err, gocheck.IsNil)
			if ct == 1 {
				done <- 1
				return
			}
			runtime.Gosched()
		}
	}()
	select {
	case <-done:
	case <-time.After(5e9):
		c.Fatal("Did not update the unit after 5 seconds.")
	}
}
Ejemplo n.º 17
0
func (s *MetaSuite) TestRelationsConstraints(c *gc.C) {
	check := func(s, e string) {
		meta, err := charm.ReadMeta(strings.NewReader(s))
		if e != "" {
			c.Assert(err, gc.ErrorMatches, e)
			c.Assert(meta, gc.IsNil)
		} else {
			c.Assert(err, gc.IsNil)
			c.Assert(meta, gc.NotNil)
		}
	}
	prefix := "name: a\nsummary: b\ndescription: c\n"
	for i, t := range relationsConstraintsTests {
		c.Logf("test %d", i)
		check(prefix+t.rels, t.err)
		check(prefix+"subordinate: true\n"+t.rels, t.err)
	}
	// The juju-* namespace is accessible to container-scoped require
	// relations on subordinate charms.
	check(prefix+`
subordinate: true
requires:
  juju-info:
    interface: juju-info
    scope: container`, "")
	// The juju-* interfaces are allowed on any require relation.
	check(prefix+`
requires:
  innocuous: juju-info`, "")
}
Ejemplo n.º 18
0
func (s *S) TestUnitStatus(c *gocheck.C) {
	var tests = []struct {
		instance     string
		agent        string
		machineAgent string
		expected     provision.Status
	}{
		{"something", "nothing", "wut", provision.StatusBuilding},
		{"", "", "", provision.StatusBuilding},
		{"", "", "pending", provision.StatusBuilding},
		{"", "", "not-started", provision.StatusBuilding},
		{"pending", "", "", provision.StatusBuilding},
		{"", "not-started", "running", provision.StatusBuilding},
		{"error", "install-error", "start-error", provision.StatusDown},
		{"started", "start-error", "running", provision.StatusDown},
		{"started", "charm-upgrade-error", "running", provision.StatusDown},
		{"running", "pending", "running", provision.StatusBuilding},
		{"running", "started", "running", provision.StatusStarted},
		{"running", "down", "running", provision.StatusDown},
	}
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	}))
	defer server.Close()
	url := strings.Replace(server.URL, "http://", "", -1)
	for _, t := range tests {
		m := machine{AgentState: t.machineAgent, InstanceState: t.instance}
		u := unit{AgentState: t.agent}
		unit := provision.Unit{Ip: url}
		got := unitStatus(m, u, unit)
		c.Assert(got, gocheck.Equals, t.expected)
	}
}
Ejemplo n.º 19
0
func (s *MetaSuite) TestSubordinateWithoutContainerRelation(c *gc.C) {
	r := repoMeta("dummy")
	hackYaml := ReadYaml(r)
	hackYaml["subordinate"] = true
	_, err := charm.ReadMeta(hackYaml.Reader())
	c.Assert(err, gc.ErrorMatches, "subordinate charm \"dummy\" lacks \"requires\" relation with container scope")
}
Ejemplo n.º 20
0
func (s *S) TestIsUnreachableOnBadGateway(c *gocheck.C) {
	server, url := badGatewayServer()
	defer server.Close()
	unit := provision.Unit{Ip: url}
	reachable, _ := IsReachable(unit)
	c.Assert(reachable, gocheck.Equals, false)
}
Ejemplo n.º 21
0
func (s *ELBSuite) TestGetCollection(c *gocheck.C) {
	manager := ELBManager{}
	conn, coll := manager.collection()
	defer conn.Close()
	other := s.conn.Collection(s.cName)
	c.Assert(coll.FullName, gocheck.Equals, other.FullName)
}
Ejemplo n.º 22
0
func (tw *TestWatcher) TriggerChange(c *gc.C) {
	select {
	case tw.changes <- struct{}{}:
	case <-time.After(coretesting.LongWait):
		c.Errorf("Timeout changes triggering change after %s", coretesting.LongWait)
	}
}
Ejemplo n.º 23
0
func (s *S) TestCreateBucketBackward(c *gocheck.C) {
	patchRandomReader()
	defer unpatchRandomReader()
	auth := aws.Auth{AccessKey: "access", SecretKey: "s3cr3t"}
	region := aws.Region{
		Name:                 "myregion",
		S3Endpoint:           s.t.S3Server.URL(),
		S3LocationConstraint: true,
		S3LowercaseBucket:    true,
	}
	s3Client := s3.New(auth, region)
	app := App{Name: "leper"}
	err := s3Client.Bucket(app.Name).PutBucket(s3.BucketOwnerFull)
	c.Assert(err, gocheck.IsNil)
	env := s3Env{
		Auth:               aws.Auth{AccessKey: "access", SecretKey: "s3cr3t"},
		bucket:             app.Name,
		endpoint:           s.t.S3Server.URL(),
		locationConstraint: true,
	}
	ctx := action.BWContext{Params: []interface{}{&app}, FWResult: &env}
	createBucketAction.Backward(ctx)
	_, err = s3Client.Bucket(app.Name).List("", "/", "", 100)
	c.Assert(err, gocheck.NotNil)
}
Ejemplo n.º 24
0
func (s *notifyWorkerSuite) TestStop(c *gc.C) {
	err := s.worker.Stop()
	c.Assert(err, gc.IsNil)
	// After stop, Wait should return right away
	err = WaitShort(c, s.worker)
	c.Assert(err, gc.IsNil)
}
Ejemplo n.º 25
0
func (s *WriterSuite) SetUpSuite(c *gocheck.C) {
	var err error
	config.Set("database:url", "127.0.0.1:27017")
	config.Set("database:name", "tsuru_api_writer_test")
	s.conn, err = db.Conn()
	c.Assert(err, gocheck.IsNil)
}
Ejemplo n.º 26
0
func (s *deployerSuite) TestAPIAddresses(c *gc.C) {
	apiInfo := s.APIInfo(c)

	addresses, err := s.st.APIAddresses()
	c.Assert(err, gc.IsNil)
	c.Assert(addresses, gc.DeepEquals, apiInfo.Addrs)
}
Ejemplo n.º 27
0
func (s *uniterSuite) TestWatchConfigSettings(c *gc.C) {
	err := s.wordpressUnit.SetCharmURL(s.wpCharm.URL())
	c.Assert(err, gc.IsNil)

	c.Assert(s.resources.Count(), gc.Equals, 0)

	args := params.Entities{Entities: []params.Entity{
		{Tag: "unit-mysql-0"},
		{Tag: "unit-wordpress-0"},
		{Tag: "unit-foo-42"},
	}}
	result, err := s.uniter.WatchConfigSettings(args)
	c.Assert(err, gc.IsNil)
	c.Assert(result, gc.DeepEquals, params.NotifyWatchResults{
		Results: []params.NotifyWatchResult{
			{Error: apiservertesting.ErrUnauthorized},
			{NotifyWatcherId: "1"},
			{Error: apiservertesting.ErrUnauthorized},
		},
	})

	// Verify the resource was registered and stop when done
	c.Assert(s.resources.Count(), gc.Equals, 1)
	resource := s.resources.Get("1")
	defer statetesting.AssertStop(c, resource)

	// Check that the Watch has consumed the initial event ("returned" in
	// the Watch call)
	wc := statetesting.NewNotifyWatcherC(c, s.State, resource.(state.NotifyWatcher))
	wc.AssertNoChange()
}
Ejemplo n.º 28
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)
}
Ejemplo n.º 29
0
func (*AddressSuite) TestSortAddresses(c *gc.C) {
	addrs := network.NewAddresses(
		"127.0.0.1",
		"localhost",
		"example.com",
		"::1",
		"fc00::1",
		"fe80::2",
		"172.16.0.1",
		"8.8.8.8",
	)
	network.SortAddresses(addrs, false)
	c.Assert(addrs, jc.DeepEquals, network.NewAddresses(
		"example.com",
		"localhost",
		"127.0.0.1",
		"172.16.0.1",
		"8.8.8.8",
		"::1",
		"fe80::2",
		"fc00::1",
	))

	network.SortAddresses(addrs, true)
	c.Assert(addrs, jc.DeepEquals, network.NewAddresses(
		"example.com",
		"localhost",
		"fe80::2",
		"::1",
		"fc00::1",
		"127.0.0.1",
		"172.16.0.1",
		"8.8.8.8",
	))
}
Ejemplo n.º 30
0
func (s *ClientTests) createInstanceAndLB(c *gocheck.C) (*elb.CreateLoadBalancer, string) {
	options := ec2.RunInstancesOptions{
		ImageId:      "ami-ccf405a5",
		InstanceType: "t1.micro",
		AvailZone:    "us-east-1c",
	}
	resp1, err := s.ec2.RunInstances(&options)
	c.Assert(err, gocheck.IsNil)
	instId := resp1.Instances[0].InstanceId
	createLBReq := elb.CreateLoadBalancer{
		Name:       "testlb",
		AvailZones: []string{"us-east-1c"},
		Listeners: []elb.Listener{
			{
				InstancePort:     80,
				InstanceProtocol: "http",
				LoadBalancerPort: 80,
				Protocol:         "http",
			},
		},
	}
	_, err = s.elb.CreateLoadBalancer(&createLBReq)
	c.Assert(err, gocheck.IsNil)
	return &createLBReq, instId
}