Example #1
1
func (s *decodeSuite) TestDecodeCheckInvalidSignature(c *gc.C) {
	r := bytes.NewReader([]byte(invalidClearsignInput + signSuffix))
	_, err := simplestreams.DecodeCheckSignature(r, testSigningKey)
	c.Assert(err, gc.Not(gc.IsNil))
	_, ok := err.(*simplestreams.NotPGPSignedError)
	c.Assert(ok, jc.IsFalse)
}
Example #2
0
func (s *UserSuite) TestPasswordValidUpdatesSalt(c *gc.C) {
	user := s.Factory.MakeUser(c, nil)

	compatHash := utils.UserPasswordHash("foo", utils.CompatSalt)
	err := user.SetPasswordHash(compatHash, "")
	c.Assert(err, jc.ErrorIsNil)
	beforeSalt, beforeHash := state.GetUserPasswordSaltAndHash(user)
	c.Assert(beforeSalt, gc.Equals, "")
	c.Assert(beforeHash, gc.Equals, compatHash)
	c.Assert(user.PasswordValid("bar"), jc.IsFalse)
	// A bad password doesn't trigger a rewrite
	afterBadSalt, afterBadHash := state.GetUserPasswordSaltAndHash(user)
	c.Assert(afterBadSalt, gc.Equals, "")
	c.Assert(afterBadHash, gc.Equals, compatHash)
	// When we get a valid check, we then add a salt and rewrite the hash
	c.Assert(user.PasswordValid("foo"), jc.IsTrue)
	afterSalt, afterHash := state.GetUserPasswordSaltAndHash(user)
	c.Assert(afterSalt, gc.Not(gc.Equals), "")
	c.Assert(afterHash, gc.Not(gc.Equals), compatHash)
	c.Assert(afterHash, gc.Equals, utils.UserPasswordHash("foo", afterSalt))
	// running PasswordValid again doesn't trigger another rewrite
	c.Assert(user.PasswordValid("foo"), jc.IsTrue)
	lastSalt, lastHash := state.GetUserPasswordSaltAndHash(user)
	c.Assert(lastSalt, gc.Equals, afterSalt)
	c.Assert(lastHash, gc.Equals, afterHash)
}
Example #3
0
func (*DebugHooksClientSuite) TestClientScript(c *gc.C) {
	ctx := debug.NewHooksContext("foo/8")

	// Test the variable substitutions.
	result := debug.ClientScript(ctx, nil)
	// No variables left behind.
	c.Assert(result, gc.Not(gc.Matches), "(.|\n)*{unit_name}(.|\n)*")
	c.Assert(result, gc.Not(gc.Matches), "(.|\n)*{tmux_conf}(.|\n)*")
	c.Assert(result, gc.Not(gc.Matches), "(.|\n)*{entry_flock}(.|\n)*")
	c.Assert(result, gc.Not(gc.Matches), "(.|\n)*{exit_flock}(.|\n)*")
	// tmux new-session -d -s {unit_name}
	c.Assert(result, gc.Matches, fmt.Sprintf("(.|\n)*tmux attach-session -t %s(.|\n)*", regexp.QuoteMeta(ctx.Unit)))
	//) 9>{exit_flock}
	c.Assert(result, gc.Matches, fmt.Sprintf("(.|\n)*\\) 9>%s(.|\n)*", regexp.QuoteMeta(ctx.ClientExitFileLock())))
	//) 8>{entry_flock}
	c.Assert(result, gc.Matches, fmt.Sprintf("(.|\n)*\\) 8>%s(.|\n)*", regexp.QuoteMeta(ctx.ClientFileLock())))

	// nil is the same as empty slice is the same as "*".
	// Also, if "*" is present as well as a named hook,
	// it is equivalent to "*".
	c.Assert(debug.ClientScript(ctx, nil), gc.Equals, debug.ClientScript(ctx, []string{}))
	c.Assert(debug.ClientScript(ctx, []string{"*"}), gc.Equals, debug.ClientScript(ctx, nil))
	c.Assert(debug.ClientScript(ctx, []string{"*", "something"}), gc.Equals, debug.ClientScript(ctx, []string{"*"}))

	// debug.ClientScript does not validate hook names, as it doesn't have
	// a full state API connection to determine valid relation hooks.
	expected := fmt.Sprintf(
		`(.|\n)*echo "aG9va3M6Ci0gc29tZXRoaW5nIHNvbWV0aGluZ2Vsc2UK" | base64 -d > %s(.|\n)*`,
		regexp.QuoteMeta(ctx.ClientFileLock()),
	)
	c.Assert(debug.ClientScript(ctx, []string{"something somethingelse"}), gc.Matches, expected)
}
Example #4
0
func (s *ConstraintsSuite) TestIsEmpty(c *gc.C) {
	con := constraints.Value{}
	c.Check(&con, jc.Satisfies, constraints.IsEmpty)
	con = constraints.MustParse("arch=amd64")
	c.Check(&con, gc.Not(jc.Satisfies), constraints.IsEmpty)
	con = constraints.MustParse("")
	c.Check(&con, jc.Satisfies, constraints.IsEmpty)
	con = constraints.MustParse("tags=")
	c.Check(&con, gc.Not(jc.Satisfies), constraints.IsEmpty)
	con = constraints.MustParse("spaces=")
	c.Check(&con, gc.Not(jc.Satisfies), constraints.IsEmpty)
	con = constraints.MustParse("mem=")
	c.Check(&con, gc.Not(jc.Satisfies), constraints.IsEmpty)
	con = constraints.MustParse("arch=")
	c.Check(&con, gc.Not(jc.Satisfies), constraints.IsEmpty)
	con = constraints.MustParse("root-disk=")
	c.Check(&con, gc.Not(jc.Satisfies), constraints.IsEmpty)
	con = constraints.MustParse("cpu-power=")
	c.Check(&con, gc.Not(jc.Satisfies), constraints.IsEmpty)
	con = constraints.MustParse("cores=")
	c.Check(&con, gc.Not(jc.Satisfies), constraints.IsEmpty)
	con = constraints.MustParse("container=")
	c.Check(&con, gc.Not(jc.Satisfies), constraints.IsEmpty)
	con = constraints.MustParse("instance-type=")
	c.Check(&con, gc.Not(jc.Satisfies), constraints.IsEmpty)
}
Example #5
0
func (s *ConstraintsSuite) TestParseNoTagsNoNetworks(c *gc.C) {
	con := constraints.MustParse("arch=amd64 mem=4G cpu-cores=1 root-disk=8G tags= networks=")
	c.Assert(con.Tags, gc.Not(gc.IsNil))
	c.Assert(con.Networks, gc.Not(gc.IsNil))
	c.Check(*con.Tags, gc.HasLen, 0)
	c.Check(*con.Networks, gc.HasLen, 0)
}
Example #6
0
func (s *OpenSuite) TestUpdateEnvInfo(c *gc.C) {
	store := jujuclienttesting.NewMemStore()
	ctx := envtesting.BootstrapContext(c)
	uuid := utils.MustNewUUID().String()
	cfg, err := config.New(config.UseDefaults, map[string]interface{}{
		"type": "dummy",
		"name": "admin-model",
		"uuid": uuid,
	})
	c.Assert(err, jc.ErrorIsNil)
	controllerCfg := testing.FakeControllerConfig()
	_, err = bootstrap.Prepare(ctx, store, bootstrap.PrepareParams{
		ControllerConfig: controllerCfg,
		ControllerName:   "controller-name",
		ModelConfig:      cfg.AllAttrs(),
		Cloud:            dummy.SampleCloudSpec(),
		AdminSecret:      "admin-secret",
	})
	c.Assert(err, jc.ErrorIsNil)

	foundController, err := store.ControllerByName("controller-name")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(foundController.ControllerUUID, gc.Not(gc.Equals), "")
	c.Assert(foundController.CACert, gc.Not(gc.Equals), "")
	foundModel, err := store.ModelByName("controller-name", "admin/admin-model")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(foundModel, jc.DeepEquals, &jujuclient.ModelDetails{
		ModelUUID: cfg.UUID(),
	})
}
Example #7
0
func (s *configFunctionalSuite) TestUsingTCPRemote(c *gc.C) {
	if s.client == nil {
		c.Skip("LXD not running locally")
	}
	// We can't just pass the testingCert as part of the Local connection,
	// because Validate() doesn't like Local remotes that have
	// Certificates.
	lxdclient.PatchGenerateCertificate(&s.CleanupSuite, testingCert, testingKey)

	cfg := lxdclient.Config{
		Namespace: "my-ns",
		Remote:    lxdclient.Local,
	}
	nonlocal, err := cfg.UsingTCPRemote()
	c.Assert(err, jc.ErrorIsNil)

	checkValidRemote(c, &nonlocal.Remote)
	c.Check(nonlocal, jc.DeepEquals, lxdclient.Config{
		Namespace: "my-ns",
		Remote: lxdclient.Remote{
			Name:          lxdclient.Local.Name,
			Host:          nonlocal.Remote.Host,
			Cert:          nonlocal.Remote.Cert,
			Protocol:      lxdclient.LXDProtocol,
			ServerPEMCert: nonlocal.Remote.ServerPEMCert,
		},
	})
	c.Check(nonlocal.Remote.Host, gc.Not(gc.Equals), "")
	c.Check(nonlocal.Remote.Cert.CertPEM, gc.Not(gc.Equals), "")
	c.Check(nonlocal.Remote.Cert.KeyPEM, gc.Not(gc.Equals), "")
	c.Check(nonlocal.Remote.ServerPEMCert, gc.Not(gc.Equals), "")
	// TODO(ericsnow) Check that the server has the certs.
}
Example #8
0
func (s *gonzoSuite) TestInsertQueryMatch(c *gc.C) {
	for _, testCase := range queryMatchTestCases {
		err := s.session.DB("db1").C("c1").Insert(testCase)
		c.Assert(err, gc.IsNil)
	}

	var err error
	var result []bson.M
	err = s.session.DB("db1").C("c1").Find(bson.M{"artist": "ed hall"}).All(&result)
	c.Assert(err, gc.IsNil)
	c.Assert(result, gc.HasLen, 1)

	err = s.session.DB("db1").C("c1").Find(bson.M{"label": "trance syndicate"}).All(&result)
	c.Assert(err, gc.IsNil)
	c.Assert(result, gc.HasLen, 2)
	for i, m := range result {
		c.Assert(m["label"], gc.Equals, "trance syndicate")
		if i > 0 {
			c.Assert(m["artist"], gc.Not(gc.DeepEquals), result[i-1]["artist"])
			c.Assert(m["venue"], gc.Not(gc.DeepEquals), result[i-1]["venue"])
			c.Assert(m["_id"], gc.Not(gc.DeepEquals), result[i-1]["_id"])
		}
	}

	err = s.session.DB("db1").C("c1").Find(nil).All(&result)
	c.Assert(err, gc.IsNil)
	c.Assert(result, gc.HasLen, 3)
}
Example #9
0
func (t *Tests) TestBootstrap(c *gc.C) {
	e := t.Prepare(c)
	err := bootstrap.Bootstrap(envtesting.BootstrapContext(c), e, bootstrap.BootstrapParams{})
	c.Assert(err, jc.ErrorIsNil)

	controllerInstances, err := e.ControllerInstances()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(controllerInstances, gc.Not(gc.HasLen), 0)

	e2 := t.Open(c, e.Config())
	controllerInstances2, err := e2.ControllerInstances()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(controllerInstances2, gc.Not(gc.HasLen), 0)
	c.Assert(controllerInstances2, jc.SameContents, controllerInstances)

	err = environs.Destroy(e2.Config().Name(), e2, t.ControllerStore)
	c.Assert(err, jc.ErrorIsNil)

	// Prepare again because Destroy invalidates old environments.
	e3 := t.Prepare(c)

	err = bootstrap.Bootstrap(envtesting.BootstrapContext(c), e3, bootstrap.BootstrapParams{})
	c.Assert(err, jc.ErrorIsNil)

	err = environs.Destroy(e3.Config().Name(), e3, t.ControllerStore)
	c.Assert(err, jc.ErrorIsNil)
}
Example #10
0
func (*metadataHelperSuite) TestResolveMetadata(c *gc.C) {
	var versionStrings = []string{"1.2.3-precise-amd64"}
	dir := c.MkDir()
	toolstesting.MakeTools(c, dir, "released", versionStrings)
	toolsList := coretools.List{{
		Version: version.MustParseBinary(versionStrings[0]),
		Size:    123,
		SHA256:  "abc",
	}}

	stor, err := filestorage.NewFileStorageReader(dir)
	c.Assert(err, jc.ErrorIsNil)
	err = tools.ResolveMetadata(stor, "released", nil)
	c.Assert(err, jc.ErrorIsNil)

	// We already have size/sha256, so ensure that storage isn't consulted.
	countingStorage := &countingStorage{StorageReader: stor}
	metadata := tools.MetadataFromTools(toolsList, "released")
	err = tools.ResolveMetadata(countingStorage, "released", metadata)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(countingStorage.counter, gc.Equals, 0)

	// Now clear size/sha256, and check that it is called, and
	// the size/sha256 sum are updated.
	metadata[0].Size = 0
	metadata[0].SHA256 = ""
	err = tools.ResolveMetadata(countingStorage, "released", metadata)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(countingStorage.counter, gc.Equals, 1)
	c.Assert(metadata[0].Size, gc.Not(gc.Equals), 0)
	c.Assert(metadata[0].SHA256, gc.Not(gc.Equals), "")
}
Example #11
0
func (s *serviceSuite) TestServiceStatus(c *gc.C) {
	message := "a test message"
	stat, err := s.wordpressService.Status()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(stat.Status, gc.Not(gc.Equals), status.Active)
	c.Assert(stat.Message, gc.Not(gc.Equals), message)

	now := time.Now()
	sInfo := status.StatusInfo{
		Status:  status.Active,
		Message: message,
		Data:    map[string]interface{}{},
		Since:   &now,
	}
	err = s.wordpressService.SetStatus(sInfo)
	c.Check(err, jc.ErrorIsNil)

	stat, err = s.wordpressService.Status()
	c.Check(err, jc.ErrorIsNil)
	c.Check(stat.Status, gc.Equals, status.Active)
	c.Check(stat.Message, gc.Equals, message)

	result, err := s.apiService.Status(s.wordpressUnit.Name())
	c.Check(err, gc.ErrorMatches, `"wordpress/0" is not leader of "wordpress"`)

	s.claimLeadership(c, s.wordpressUnit, s.wordpressService)
	result, err = s.apiService.Status(s.wordpressUnit.Name())
	c.Check(err, jc.ErrorIsNil)
	c.Check(result.Application.Status, gc.Equals, status.Active.String())
}
Example #12
0
func (s *statePoolSuite) TestClose(c *gc.C) {
	p := state.NewStatePool(s.State)
	defer p.Close()

	// Get some State instances.
	st1, err := p.Get(s.ModelUUID1)
	c.Assert(err, jc.ErrorIsNil)

	st2, err := p.Get(s.ModelUUID1)
	c.Assert(err, jc.ErrorIsNil)

	// Now close them.
	err = p.Close()
	c.Assert(err, jc.ErrorIsNil)

	// Confirm that controller State isn't closed.
	_, err = s.State.Model()
	c.Assert(err, jc.ErrorIsNil)

	// Ensure that new ones are returned if further States are
	// requested.
	st1_, err := p.Get(s.ModelUUID1)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(st1_, gc.Not(gc.Equals), st1)

	st2_, err := p.Get(s.ModelUUID2)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(st2_, gc.Not(gc.Equals), st2)
}
Example #13
0
func (s *environSuite) TestBase(c *gc.C) {
	baseConfig := newConfig(c, validAttrs().Merge(testing.Attrs{"name": "testname"}))
	env, err := environs.New(environs.OpenParams{
		Cloud:  fakeCloudSpec(),
		Config: baseConfig,
	})
	c.Assert(err, gc.IsNil)

	cfg := env.Config()
	c.Assert(cfg, gc.NotNil)
	c.Check(cfg.Name(), gc.Equals, "testname")

	c.Check(env.PrecheckInstance("", constraints.Value{}, ""), gc.IsNil)

	hasRegion, ok := env.(simplestreams.HasRegion)
	c.Check(ok, gc.Equals, true)
	c.Assert(hasRegion, gc.NotNil)

	cloudSpec, err := hasRegion.Region()
	c.Assert(err, gc.IsNil)
	c.Check(cloudSpec.Region, gc.Not(gc.Equals), "")
	c.Check(cloudSpec.Endpoint, gc.Not(gc.Equals), "")

	c.Check(env.OpenPorts(nil), gc.IsNil)
	c.Check(env.ClosePorts(nil), gc.IsNil)
	ports, err := env.Ports()
	c.Assert(err, gc.IsNil)
	c.Check(ports, gc.IsNil)
}
Example #14
0
func (s *UserSuite) TestAddUserSetsSalt(c *gc.C) {
	user := s.Factory.MakeUser(c, &factory.UserParams{Password: "******"})
	salt, hash := state.GetUserPasswordSaltAndHash(user)
	c.Assert(hash, gc.Not(gc.Equals), "")
	c.Assert(salt, gc.Not(gc.Equals), "")
	c.Assert(utils.UserPasswordHash("a-password", salt), gc.Equals, hash)
	c.Assert(user.PasswordValid("a-password"), jc.IsTrue)
}
Example #15
0
func (s *ConstraintsSuite) TestParseNoTagsNoSpaces(c *gc.C) {
	con := constraints.MustParse(
		"arch=amd64 mem=4G cores=1 root-disk=8G tags= spaces=",
	)
	c.Assert(con.Tags, gc.Not(gc.IsNil))
	c.Assert(con.Spaces, gc.Not(gc.IsNil))
	c.Check(*con.Tags, gc.HasLen, 0)
	c.Check(*con.Spaces, gc.HasLen, 0)
}
Example #16
0
File: tests.go Project: bac/juju
func (t *Tests) TestBootstrap(c *gc.C) {
	credential := t.Credential
	if credential.AuthType() == "" {
		credential = cloud.NewEmptyCredential()
	}

	var regions []cloud.Region
	if t.CloudRegion != "" {
		regions = []cloud.Region{{
			Name:     t.CloudRegion,
			Endpoint: t.CloudEndpoint,
		}}
	}

	args := bootstrap.BootstrapParams{
		ControllerConfig: coretesting.FakeControllerConfig(),
		CloudName:        t.TestConfig["type"].(string),
		Cloud: cloud.Cloud{
			Type:      t.TestConfig["type"].(string),
			AuthTypes: []cloud.AuthType{credential.AuthType()},
			Regions:   regions,
			Endpoint:  t.CloudEndpoint,
		},
		CloudRegion:         t.CloudRegion,
		CloudCredential:     &credential,
		CloudCredentialName: "credential",
		AdminSecret:         AdminSecret,
		CAPrivateKey:        coretesting.CAKey,
	}

	e := t.Prepare(c)
	err := bootstrap.Bootstrap(envtesting.BootstrapContext(c), e, args)
	c.Assert(err, jc.ErrorIsNil)

	controllerInstances, err := e.ControllerInstances(t.ControllerUUID)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(controllerInstances, gc.Not(gc.HasLen), 0)

	e2 := t.Open(c, e.Config())
	controllerInstances2, err := e2.ControllerInstances(t.ControllerUUID)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(controllerInstances2, gc.Not(gc.HasLen), 0)
	c.Assert(controllerInstances2, jc.SameContents, controllerInstances)

	err = environs.Destroy(e2.Config().Name(), e2, t.ControllerStore)
	c.Assert(err, jc.ErrorIsNil)

	// Prepare again because Destroy invalidates old environments.
	e3 := t.Prepare(c)

	err = bootstrap.Bootstrap(envtesting.BootstrapContext(c), e3, args)
	c.Assert(err, jc.ErrorIsNil)

	err = environs.Destroy(e3.Config().Name(), e3, t.ControllerStore)
	c.Assert(err, jc.ErrorIsNil)
}
Example #17
0
func (s *filesSuite) TestDirectoriesCleaned(c *gc.C) {
	recreatableFolder := filepath.Join(s.root, "recreate_me")
	os.MkdirAll(recreatableFolder, os.FileMode(0755))
	recreatableFolderInfo, err := os.Stat(recreatableFolder)
	c.Assert(err, jc.ErrorIsNil)

	recreatableFolder1 := filepath.Join(recreatableFolder, "recreate_me_too")
	os.MkdirAll(recreatableFolder1, os.FileMode(0755))
	recreatableFolder1Info, err := os.Stat(recreatableFolder1)
	c.Assert(err, jc.ErrorIsNil)

	deletableFolder := filepath.Join(recreatableFolder, "dont_recreate_me")
	os.MkdirAll(deletableFolder, os.FileMode(0755))

	deletableFile := filepath.Join(recreatableFolder, "delete_me")
	fh, err := os.Create(deletableFile)
	c.Assert(err, jc.ErrorIsNil)
	defer fh.Close()

	deletableFile1 := filepath.Join(recreatableFolder1, "delete_me.too")
	fhr, err := os.Create(deletableFile1)
	c.Assert(err, jc.ErrorIsNil)
	defer fhr.Close()

	s.PatchValue(backups.ReplaceableFolders, func() (map[string]os.FileMode, error) {
		replaceables := map[string]os.FileMode{}
		for _, replaceable := range []string{
			recreatableFolder,
			recreatableFolder1,
		} {
			dirStat, err := os.Stat(replaceable)
			if err != nil {
				return map[string]os.FileMode{}, errors.Annotatef(err, "cannot stat %q", replaceable)
			}
			replaceables[replaceable] = dirStat.Mode()
		}
		return replaceables, nil
	})

	err = backups.PrepareMachineForRestore()
	c.Assert(err, jc.ErrorIsNil)

	_, err = os.Stat(deletableFolder)
	c.Assert(err, gc.Not(gc.IsNil))
	c.Assert(os.IsNotExist(err), gc.Equals, true)

	recreatedFolderInfo, err := os.Stat(recreatableFolder)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(recreatableFolderInfo.Mode(), gc.Equals, recreatedFolderInfo.Mode())
	c.Assert(recreatableFolderInfo.Sys().(*syscall.Stat_t).Ino, gc.Not(gc.Equals), recreatedFolderInfo.Sys().(*syscall.Stat_t).Ino)

	recreatedFolder1Info, err := os.Stat(recreatableFolder1)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(recreatableFolder1Info.Mode(), gc.Equals, recreatedFolder1Info.Mode())
	c.Assert(recreatableFolder1Info.Sys().(*syscall.Stat_t).Ino, gc.Not(gc.Equals), recreatedFolder1Info.Sys().(*syscall.Stat_t).Ino)
}
Example #18
0
func (s *RelopSuite) TestLessThan(c *gc.C) {
	c.Assert(42, jc.LessThan, 45)
	c.Assert(1.0, jc.LessThan, 2.25)
	c.Assert(42, gc.Not(jc.LessThan), 42)
	c.Assert(42, gc.Not(jc.LessThan), 10)

	result, msg := jc.LessThan.Check([]interface{}{"Hello", "World"}, nil)
	c.Assert(result, jc.IsFalse)
	c.Assert(msg, gc.Equals, `obtained value string:"Hello" not supported`)
}
Example #19
0
func (s *RelopSuite) TestGreaterThan(c *gc.C) {
	c.Assert(45, jc.GreaterThan, 42)
	c.Assert(2.25, jc.GreaterThan, 1.0)
	c.Assert(42, gc.Not(jc.GreaterThan), 42)
	c.Assert(10, gc.Not(jc.GreaterThan), 42)

	result, msg := jc.GreaterThan.Check([]interface{}{"Hello", "World"}, nil)
	c.Assert(result, jc.IsFalse)
	c.Assert(msg, gc.Equals, `obtained value string:"Hello" not supported`)
}
Example #20
0
func (s *managedStorageSuite) TestPutSamePathDifferentDataMulti(c *gc.C) {
	resPath := s.assertPut(c, "/path/to/blob", []byte("another resource"))
	secondResPath := s.assertPut(c, "/anotherpath/to/blob", []byte("some resource"))
	c.Assert(resPath, gc.Not(gc.Equals), secondResPath)
	s.assertResourceCatalogCount(c, 2)

	thirdResPath := s.assertPut(c, "/path/to/blob", []byte("some resource"))
	c.Assert(resPath, gc.Not(gc.Equals), secondResPath)
	c.Assert(secondResPath, gc.Equals, thirdResPath)
	s.assertResourceCatalogCount(c, 1)
}
Example #21
0
func (s *UserSuite) TestSetPasswordChangesSalt(c *gc.C) {
	user := s.Factory.MakeUser(c, nil)
	origSalt, origHash := state.GetUserPasswordSaltAndHash(user)
	c.Assert(origSalt, gc.Not(gc.Equals), "")
	user.SetPassword("a-password")
	newSalt, newHash := state.GetUserPasswordSaltAndHash(user)
	c.Assert(newSalt, gc.Not(gc.Equals), "")
	c.Assert(newSalt, gc.Not(gc.Equals), origSalt)
	c.Assert(newHash, gc.Not(gc.Equals), origHash)
	c.Assert(user.PasswordValid("a-password"), jc.IsTrue)
}
Example #22
0
func (s *EnvSuite) TestEnvSetsPath(c *gc.C) {
	paths := context.OSDependentEnvVars(MockEnvPaths{})
	c.Assert(paths, gc.Not(gc.HasLen), 0)
	vars, err := keyvalues.Parse(paths, true)
	c.Assert(err, jc.ErrorIsNil)
	key := "PATH"
	if runtime.GOOS == "windows" {
		key = "Path"
	}
	c.Assert(vars[key], gc.Not(gc.Equals), "")
}
Example #23
0
func (*testingSuite) TestPatchAttemptStrategiesPatchesEnvironsStrategies(c *gc.C) {
	c.Assert(common.LongAttempt, gc.Not(gc.DeepEquals), impatientAttempt)
	c.Assert(common.ShortAttempt, gc.Not(gc.DeepEquals), impatientAttempt)
	c.Assert(environs.AddressesRefreshAttempt, gc.Not(gc.DeepEquals), impatientAttempt)

	cleanup := PatchAttemptStrategies()
	defer cleanup()

	c.Check(common.LongAttempt, gc.DeepEquals, impatientAttempt)
	c.Check(common.ShortAttempt, gc.DeepEquals, impatientAttempt)
	c.Check(environs.AddressesRefreshAttempt, gc.DeepEquals, impatientAttempt)
}
Example #24
0
func (*ConfigSuite) TestDefaultConfig(c *gc.C) {
	cfg, err := bootstrap.NewConfig(nil)
	c.Assert(err, jc.ErrorIsNil)

	// These three things are generated.
	c.Assert(cfg.AdminSecret, gc.Not(gc.HasLen), 0)
	c.Assert(cfg.CACert, gc.Not(gc.HasLen), 0)
	c.Assert(cfg.CAPrivateKey, gc.Not(gc.HasLen), 0)

	c.Assert(cfg.BootstrapTimeout, gc.Equals, time.Second*1200)
	c.Assert(cfg.BootstrapRetryDelay, gc.Equals, time.Second*5)
	c.Assert(cfg.BootstrapAddressesDelay, gc.Equals, time.Second*10)
}
Example #25
0
func (s *NewAPIClientSuite) TestWithConfigAndNoInfo(c *gc.C) {
	c.Skip("not really possible now that there is no defined admin user")
	s.PatchValue(&version.Current, coretesting.FakeVersionNumber)
	coretesting.MakeSampleJujuHome(c)

	store := newConfigStore(coretesting.SampleModelName, &environInfo{
		bootstrapConfig: map[string]interface{}{
			"type":                      "dummy",
			"name":                      "myenv",
			"state-server":              true,
			"authorized-keys":           "i-am-a-key",
			"default-series":            config.LatestLtsSeries(),
			"firewall-mode":             config.FwInstance,
			"development":               false,
			"ssl-hostname-verification": true,
			"admin-secret":              "adminpass",
		},
	})
	s.bootstrapEnv(c, coretesting.SampleModelName, store)

	info, err := store.ReadInfo("myenv")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(info, gc.NotNil)
	c.Logf("%#v", info.APICredentials())

	called := 0
	expectState := mockedAPIState(0)
	apiOpen := func(apiInfo *api.Info, opts api.DialOpts) (api.Connection, error) {
		c.Check(apiInfo.Tag, gc.Equals, dummy.AdminUserTag())
		c.Check(string(apiInfo.CACert), gc.Not(gc.Equals), "")
		c.Check(apiInfo.Password, gc.Equals, "adminpass")
		// ModelTag wasn't in regular Config
		c.Check(apiInfo.ModelTag.Id(), gc.Equals, "")
		c.Check(opts, gc.DeepEquals, api.DefaultDialOpts())
		called++
		return expectState, nil
	}
	st, err := juju.NewAPIFromStore("myenv", store, apiOpen)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(st, gc.Equals, expectState)
	c.Assert(called, gc.Equals, 1)

	// Make sure the cache is updated.
	info, err = store.ReadInfo("myenv")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(info, gc.NotNil)
	ep := info.APIEndpoint()
	c.Assert(ep.Addresses, gc.HasLen, 1)
	c.Check(ep.Addresses[0], gc.Matches, `localhost:\d+`)
	c.Check(ep.CACert, gc.Not(gc.Equals), "")
}
Example #26
0
func (s *stateSuite) TestLoginTracksFacadeVersions(c *gc.C) {
	apistate, tag, password := s.OpenAPIWithoutLogin(c)
	defer apistate.Close()
	// We haven't called Login yet, so the Facade Versions should be empty
	c.Check(apistate.AllFacadeVersions(), gc.HasLen, 0)
	err := apistate.Login(tag, password, "", nil)
	c.Assert(err, jc.ErrorIsNil)
	// Now that we've logged in, AllFacadeVersions should be updated.
	allVersions := apistate.AllFacadeVersions()
	c.Check(allVersions, gc.Not(gc.HasLen), 0)
	// For sanity checking, ensure that we have a v2 of the Client facade
	c.Assert(allVersions["Client"], gc.Not(gc.HasLen), 0)
	c.Check(allVersions["Client"][0], gc.Equals, 1)
}
Example #27
0
func (ts *TestTradeSuite) TestTradeApi(c *check.C) {
	t, err := ts.c.NewTrade(oanda.Buy, 2, "eur_usd", oanda.StopLoss(0.5), oanda.TakeProfit(3.0))
	c.Assert(err, check.IsNil)
	c.Log(t)
	c.Assert(t.TradeId, check.Not(check.Equals), 0)
	c.Assert(t.Price, check.Not(check.Equals), 0.0)
	c.Assert(t.Instrument, check.Equals, "EUR_USD")
	c.Assert(t.Side, check.Equals, string(oanda.Buy))
	c.Assert(t.Units, check.Equals, 2)
	c.Assert(t.StopLoss, check.Equals, 0.5)
	c.Assert(t.TakeProfit, check.Equals, 3.0)
	c.Assert(t.TrailingStop, check.Equals, 0.0)

	dup, err := ts.c.Trade(t.TradeId)
	c.Assert(err, check.IsNil)
	c.Assert(dup.TradeId, check.Equals, t.TradeId)
	c.Assert(dup.Price, check.Equals, t.Price)
	c.Assert(dup.Instrument, check.Equals, t.Instrument)
	c.Assert(dup.Side, check.Equals, t.Side)
	c.Assert(dup.Units, check.Equals, t.Units)
	c.Assert(dup.StopLoss, check.Equals, t.StopLoss)
	c.Assert(dup.TakeProfit, check.Equals, t.TakeProfit)
	c.Assert(dup.TrailingStop, check.Equals, t.TrailingStop)
	c.Assert(dup.Time.Equal(t.Time), check.Equals, true)

	t, err = ts.c.ModifyTrade(t.TradeId, oanda.StopLoss(0.75))
	c.Assert(err, check.IsNil)
	c.Assert(t.StopLoss, check.Equals, 0.75)

	trades, err := ts.c.Trades()
	c.Assert(err, check.IsNil)
	c.Assert(trades, check.HasLen, 1)
	c.Assert(trades[0].TradeId, check.Equals, t.TradeId)
	c.Assert(trades[0].Price, check.Equals, t.Price)
	c.Assert(trades[0].Instrument, check.Equals, t.Instrument)
	c.Assert(trades[0].Side, check.Equals, t.Side)
	c.Assert(trades[0].Units, check.Equals, t.Units)
	c.Assert(trades[0].StopLoss, check.Equals, t.StopLoss)
	c.Assert(trades[0].TakeProfit, check.Equals, t.TakeProfit)
	c.Assert(trades[0].TrailingStop, check.Equals, t.TrailingStop)
	c.Assert(trades[0].Time.Equal(t.Time), check.Equals, true)

	rsp, err := ts.c.CloseTrade(t.TradeId)
	c.Assert(err, check.IsNil)
	c.Log(rsp)

	trades, err = ts.c.Trades()
	c.Assert(err, check.IsNil)
	c.Assert(trades, check.HasLen, 0)
}
Example #28
0
func (s *OpenSuite) TestUpdateEnvInfo(c *gc.C) {
	store := configstore.NewMem()
	ctx := envtesting.BootstrapContext(c)
	_, err := environs.PrepareFromName("erewhemos", ctx, store)
	c.Assert(err, jc.ErrorIsNil)

	info, err := store.ReadInfo("erewhemos")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(info, gc.NotNil)
	c.Assert(info.APIEndpoint().CACert, gc.Not(gc.Equals), "")
	c.Assert(info.APIEndpoint().EnvironUUID, gc.Not(gc.Equals), "")
	c.Assert(info.APICredentials().Password, gc.Not(gc.Equals), "")
	c.Assert(info.APICredentials().User, gc.Equals, "admin")
}
func (s *StorageBlobSuite) TestCreateBlockBlobFromReaderWithShortData(c *chk.C) {
	cli := getBlobClient(c)
	cnt := randContainer()
	c.Assert(cli.CreateContainer(cnt, ContainerAccessTypePrivate), chk.IsNil)
	defer cli.deleteContainer(cnt)

	name := randString(20)
	data := randBytes(8888)
	err := cli.CreateBlockBlobFromReader(cnt, name, 9999, bytes.NewReader(data), nil)
	c.Assert(err, chk.Not(chk.IsNil))

	_, err = cli.GetBlob(cnt, name)
	// Upload was incomplete: blob should not have been created.
	c.Assert(err, chk.Not(chk.IsNil))
}
Example #30
0
func (s *RootKeyStorageSuite) TestRootKey(c *gc.C) {
	now := epoch
	s.PatchValue(mgostorage.TimeNow, func() time.Time {
		return now
	})

	store := mgostorage.NewRootKeys(10).NewStorage(s.coll(), mgostorage.Policy{
		GenerateInterval: 2 * time.Minute,
		ExpiryDuration:   5 * time.Minute,
	})
	key, id, err := store.RootKey()
	c.Assert(err, gc.IsNil)
	c.Assert(key, gc.HasLen, 24)
	c.Assert(id, gc.Matches, "[0-9a-f]{32}")

	// If we get a key within the generate interval, we should
	// get the same one.
	now = epoch.Add(time.Minute)
	key1, id1, err := store.RootKey()
	c.Assert(err, gc.IsNil)
	c.Assert(key1, gc.DeepEquals, key)
	c.Assert(id1, gc.Equals, id)

	// A different storage instance should get the same root key.
	store1 := mgostorage.NewRootKeys(10).NewStorage(s.coll(), mgostorage.Policy{
		GenerateInterval: 2 * time.Minute,
		ExpiryDuration:   5 * time.Minute,
	})
	key1, id1, err = store1.RootKey()
	c.Assert(err, gc.IsNil)
	c.Assert(key1, gc.DeepEquals, key)
	c.Assert(id1, gc.Equals, id)

	// After the generation interval has passed, we should generate a new key.
	now = epoch.Add(2*time.Minute + time.Second)
	key1, id1, err = store.RootKey()
	c.Assert(err, gc.IsNil)
	c.Assert(key, gc.HasLen, 24)
	c.Assert(id, gc.Matches, "[0-9a-f]{32}")
	c.Assert(key1, gc.Not(gc.DeepEquals), key)
	c.Assert(id1, gc.Not(gc.Equals), id)

	// The other store should pick it up too.
	key2, id2, err := store1.RootKey()
	c.Assert(err, gc.IsNil)
	c.Assert(key2, gc.DeepEquals, key1)
	c.Assert(id2, gc.Equals, id1)
}