func (s *instanceTypeSuite) TestFindInstanceSpec(c *gc.C) { env := s.setupEnvWithDummyMetadata(c) for i, t := range findInstanceSpecTests { c.Logf("test %d", i) cons := constraints.MustParse(t.cons) constraints := &instances.InstanceConstraint{ Region: "West US", Series: t.series, Arches: []string{"amd64"}, Constraints: cons, } // Find a matching instance type and image. spec, err := findInstanceSpec(env, constraints) c.Assert(err, gc.IsNil) // We got the instance type we described in our constraints, and // the image returned by (the fake) simplestreams. if cons.HasInstanceType() { c.Check(spec.InstanceType.Name, gc.Equals, *cons.InstanceType) } else { c.Check(spec.InstanceType.Name, gc.Equals, t.itype) } c.Check(spec.Image.Id, gc.Equals, "image-id") } }
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) } }
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`, "") }
func (t *LxcSuite) TestPreferFastLXC(c *gc.C) { for i, test := range []struct { message string releaseVersion string expected bool }{{ message: "missing release file", }, { message: "precise release", releaseVersion: "12.04", }, { message: "trusty release", releaseVersion: "14.04", expected: true, }, { message: "unstable unicorn", releaseVersion: "14.10", expected: true, }, { message: "lucid", releaseVersion: "10.04", }} { c.Logf("%v: %v", i, test.message) value := lxc.PreferFastLXC(test.releaseVersion) c.Assert(value, gc.Equals, test.expected) } }
func (s *StateFileSuite) TestStates(c *gc.C) { for i, t := range stateTests { c.Logf("test %d", i) path := filepath.Join(c.MkDir(), "uniter") file := uniter.NewStateFile(path) _, err := file.Read() c.Assert(err, gc.Equals, uniter.ErrNoStateFile) write := func() { err := file.Write(t.st.Started, t.st.Op, t.st.OpStep, t.st.Hook, t.st.CharmURL) c.Assert(err, gc.IsNil) } if t.err != "" { c.Assert(write, gc.PanicMatches, "invalid uniter state: "+t.err) err := utils.WriteYaml(path, &t.st) c.Assert(err, gc.IsNil) _, err = file.Read() c.Assert(err, gc.ErrorMatches, "cannot read charm state at .*: invalid uniter state: "+t.err) continue } write() st, err := file.Read() c.Assert(err, gc.IsNil) c.Assert(*st, gc.DeepEquals, t.st) } }
func (s *syncSuite) TestSyncing(c *gc.C) { for i, test := range tests { // Perform all tests in a "clean" environment. func() { s.setUpTest(c) defer s.tearDownTest(c) c.Logf("test %d: %s", i, test.description) if test.source { test.ctx.Source = s.localStorage } if test.version != version.Zero { version.Current.Number = test.version } if test.major > 0 { test.ctx.MajorVersion = test.major test.ctx.MinorVersion = test.minor } stor := s.targetEnv.Storage() test.ctx.TargetToolsFinder = sync.StorageToolsFinder{stor} test.ctx.TargetToolsUploader = sync.StorageToolsUploader{stor, true, false} err := sync.SyncTools(test.ctx) c.Assert(err, gc.IsNil) targetTools, err := envtools.FindTools( s.targetEnv, test.ctx.MajorVersion, test.ctx.MinorVersion, coretools.Filter{}, envtools.DoNotAllowRetry) c.Assert(err, gc.IsNil) assertToolsList(c, targetTools, test.tools) assertNoUnexpectedTools(c, s.targetEnv.Storage()) assertMirrors(c, s.targetEnv.Storage(), test.expectMirrors) }() } }
func (*scriptSuite) TestDumpFileOnErrorScript(c *gc.C) { tempdir := c.MkDir() filename := filepath.Join(tempdir, "log.txt") err := ioutil.WriteFile(filename, []byte("abc"), 0644) c.Assert(err, gc.IsNil) dumpScript := shell.DumpFileOnErrorScript(filename) c.Logf("%s", dumpScript) run := func(command string) (stdout, stderr string) { var stdoutBuf, stderrBuf bytes.Buffer cmd := exec.Command("/bin/bash", "-s") cmd.Stdin = strings.NewReader(dumpScript + command) cmd.Stdout = &stdoutBuf cmd.Stderr = &stderrBuf cmd.Run() return stdoutBuf.String(), stderrBuf.String() } stdout, stderr := run("exit 0") c.Assert(stdout, gc.Equals, "") c.Assert(stderr, gc.Equals, "") stdout, stderr = run("exit 1") c.Assert(stdout, gc.Equals, "") c.Assert(stderr, gc.Equals, "abc") err = os.Remove(filename) c.Assert(err, gc.IsNil) stdout, stderr = run("exit 1") c.Assert(stdout, gc.Equals, "") c.Assert(stderr, gc.Equals, "") }
func (s *machineSuite) TestMachineIdFormats(c *gc.C) { for i, test := range machineIdTests { c.Logf("test %d: %q", i, test.pattern) c.Assert(names.IsMachine(test.pattern), gc.Equals, test.valid) c.Assert(names.IsContainerMachine(test.pattern), gc.Equals, test.container) } }
func (s *SimpleStreamsToolsSuite) TestFindTools(c *gc.C) { for i, test := range findToolsTests { c.Logf("\ntest %d: %s", i, test.info) s.reset(c, nil) custom := s.uploadCustom(c, test.custom...) public := s.uploadPublic(c, test.public...) actual, err := envtools.FindTools(s.env, test.major, test.minor, coretools.Filter{}, envtools.DoNotAllowRetry) if test.err != nil { if len(actual) > 0 { c.Logf(actual.String()) } c.Check(err, jc.Satisfies, errors.IsNotFound) continue } expect := map[version.Binary]string{} for _, expected := range test.expect { // If the tools exist in custom, that's preferred. var ok bool if expect[expected], ok = custom[expected]; !ok { expect[expected] = public[expected] } } c.Check(actual.URLs(), gc.DeepEquals, expect) } }
func (s *MachineSuite) waitProvisioned(c *gc.C, unit *state.Unit) (*state.Machine, instance.Id) { c.Logf("waiting for unit %q to be provisioned", unit) machineId, err := unit.AssignedMachineId() c.Assert(err, gc.IsNil) m, err := s.State.Machine(machineId) c.Assert(err, gc.IsNil) w := m.Watch() defer w.Stop() timeout := time.After(coretesting.LongWait) for { select { case <-timeout: c.Fatalf("timed out waiting for provisioning") case _, ok := <-w.Changes(): c.Assert(ok, jc.IsTrue) err := m.Refresh() c.Assert(err, gc.IsNil) if instId, err := m.InstanceId(); err == nil { c.Logf("unit provisioned with instance %s", instId) return m, instId } else { c.Check(err, jc.Satisfies, state.IsNotProvisionedError) } } } panic("watcher died") }
func (s *storeManagerStateSuite) TestChanged(c *gc.C) { collections := map[string]*mgo.Collection{ "machines": s.State.machines, "units": s.State.units, "services": s.State.services, "relations": s.State.relations, "annotations": s.State.annotations, "statuses": s.State.statuses, "constraints": s.State.constraints, "settings": s.State.settings, } for i, test := range allWatcherChangedTests { c.Logf("test %d. %s", i, test.about) b := newAllWatcherStateBacking(s.State) all := multiwatcher.NewStore() for _, info := range test.add { all.Update(info) } test.setUp(c, s.State) c.Logf("done set up") ch := test.change ch.C = collections[ch.C].Name err := b.Changed(all, test.change) c.Assert(err, gc.IsNil) assertEntitiesEqual(c, all.All(), test.expectContents) s.Reset(c) } }
func (*suite) TestInvalidConfig(c *gc.C) { for i, t := range invalidConfigTests { c.Logf("running test %v", i) _, err := environs.ReadEnvironsBytes([]byte(t.env)) c.Check(err, gc.ErrorMatches, t.err) } }
func (*suite) TestParseBinary(c *gc.C) { parseBinaryTests := []struct { v string err string expect version.Binary }{{ v: "1.2.3-a-b", expect: binaryVersion(1, 2, 3, 0, "", "a", "b"), }, { v: "1.2.3.4-a-b", expect: binaryVersion(1, 2, 3, 4, "", "a", "b"), }, { v: "1.2-alpha3-a-b", expect: binaryVersion(1, 2, 3, 0, "alpha", "a", "b"), }, { v: "1.2-alpha3.4-a-b", expect: binaryVersion(1, 2, 3, 4, "alpha", "a", "b"), }, { v: "1.2.3", err: "invalid binary version.*", }, { v: "1.2-beta1", err: "invalid binary version.*", }, { v: "1.2.3--b", err: "invalid binary version.*", }, { v: "1.2.3-a-", err: "invalid binary version.*", }} for i, test := range parseBinaryTests { c.Logf("test 1: %d", i) got, err := version.ParseBinary(test.v) if test.err != "" { c.Assert(err, gc.ErrorMatches, test.err) } else { c.Assert(err, gc.IsNil) c.Assert(got, gc.Equals, test.expect) } } for i, test := range parseTests { c.Logf("test 2: %d", i) v := test.v + "-a-b" got, err := version.ParseBinary(v) expect := version.Binary{ Number: test.expect, Series: "a", Arch: "b", } if test.err != "" { c.Assert(err, gc.ErrorMatches, strings.Replace(test.err, "version", "binary version", 1)) } else { c.Assert(err, gc.IsNil) c.Assert(got, gc.Equals, expect) c.Check(got.IsDev(), gc.Equals, test.dev) } } }
func (s *DeploySuite) TestInitErrors(c *gc.C) { for i, t := range initErrorTests { c.Logf("test %d", i) err := coretesting.InitCommand(envcmd.Wrap(&DeployCommand{}), t.args) c.Assert(err, gc.ErrorMatches, t.err) } }
func (s *clientSuite) TestShareEnvironmentExistingUser(c *gc.C) { client := s.APIState.Client() user := s.Factory.MakeEnvUser(c, nil) cleanup := api.PatchClientFacadeCall(client, func(request string, paramsIn interface{}, response interface{}) error { if users, ok := paramsIn.(params.ModifyEnvironUsers); ok { c.Assert(users.Changes, gc.HasLen, 1) c.Logf(string(users.Changes[0].Action), gc.Equals, string(params.AddEnvUser)) c.Logf(users.Changes[0].UserTag, gc.Equals, user.UserTag().String()) } else { c.Fatalf("wrong input structure") } if result, ok := response.(*params.ErrorResults); ok { err := ¶ms.Error{Message: "failed to create environment user: env user already exists"} *result = params.ErrorResults{Results: []params.ErrorResult{{Error: err}}} } else { c.Fatalf("wrong input structure") } return nil }, ) defer cleanup() result, err := client.ShareEnvironment([]names.UserTag{user.UserTag()}) c.Assert(err, gc.IsNil) c.Assert(result.OneError().Error(), gc.Matches, "failed to create environment user: env user already exists") c.Assert(result.Results, gc.HasLen, 1) c.Assert(result.Results[0].Error, gc.ErrorMatches, `failed to create environment user: env user already exists`) }
func (s *ConstraintsSuite) TestHasContainer(c *gc.C) { for i, t := range hasContainerTests { c.Logf("test %d", i) cons := constraints.MustParse(t.constraints) c.Check(cons.HasContainer(), gc.Equals, t.hasContainer) } }
func (*PortSuite) TestCollapsePorts(c *gc.C) { testCases := []struct { about string ports []network.Port expected []network.PortRange }{{ "single port", []network.Port{{"tcp", 80}}, []network.PortRange{{80, 80, "tcp"}}, }, { "continuous port range", []network.Port{{"tcp", 80}, {"tcp", 81}, {"tcp", 82}, {"tcp", 83}}, []network.PortRange{{80, 83, "tcp"}}, }, { "non-continuous port range", []network.Port{{"tcp", 80}, {"tcp", 81}, {"tcp", 82}, {"tcp", 84}, {"tcp", 85}}, []network.PortRange{{80, 82, "tcp"}, {84, 85, "tcp"}}, }, { "non-continuous port range (udp vs tcp)", []network.Port{{"tcp", 80}, {"tcp", 81}, {"tcp", 82}, {"udp", 84}, {"tcp", 83}}, []network.PortRange{{80, 83, "tcp"}, {84, 84, "udp"}}, }, } for i, t := range testCases { c.Logf("test %d: %s", i, t.about) c.Assert(network.CollapsePorts(t.ports), gc.DeepEquals, t.expected) } }
func (*suite) TestParseMajorMinor(c *gc.C) { parseMajorMinorTests := []struct { v string err string expectMajor int expectMinor int }{{ v: "1.2", expectMajor: 1, expectMinor: 2, }, { v: "1", expectMajor: 1, expectMinor: -1, }, { v: "1.2.3", err: "invalid major.minor version number 1.2.3", }, { v: "blah", err: `invalid major version number blah: strconv.ParseInt: parsing "blah": invalid syntax`, }} for i, test := range parseMajorMinorTests { c.Logf("test %d", i) major, minor, err := version.ParseMajorMinor(test.v) if test.err != "" { c.Check(err, gc.ErrorMatches, test.err) } else { c.Check(err, gc.IsNil) c.Check(major, gc.Equals, test.expectMajor) c.Check(minor, gc.Equals, test.expectMinor) } } }
func (s *upgradeSuite) TestPerformUpgrade(c *gc.C) { s.PatchValue(upgrades.UpgradeOperations, upgradeOperations) for i, test := range upgradeTests { c.Logf("%d: %s", i, test.about) var messages []string ctx := &mockContext{ messages: messages, } fromVersion := version.Zero if test.fromVersion != "" { fromVersion = version.MustParse(test.fromVersion) } toVersion := version.MustParse("1.18.0") if test.toVersion != "" { toVersion = version.MustParse(test.toVersion) } vers := version.Current vers.Number = toVersion s.PatchValue(&version.Current, vers) err := upgrades.PerformUpgrade(fromVersion, test.target, ctx) if test.err == "" { c.Check(err, gc.IsNil) } else { c.Check(err, gc.ErrorMatches, test.err) } c.Check(ctx.messages, jc.DeepEquals, test.expectedSteps) } }
func (s *simplestreamsSuite) TestGetMirrorMetadata(c *gc.C) { for i, t := range getMirrorTests { c.Logf("test %d", i) if t.region == "" { t.region = "us-east-2" } if t.endpoint == "" { t.endpoint = "https://ec2.us-east-2.amazonaws.com" } cloud := simplestreams.CloudSpec{t.region, t.endpoint} params := simplestreams.ValueParams{ DataType: "content-download", MirrorContentId: "com.ubuntu.juju:released:tools", } indexRef, err := simplestreams.GetIndexWithFormat( s.Source, s.IndexPath(), sstesting.Index_v1, s.RequireSigned, cloud, params) if !c.Check(err, gc.IsNil) { continue } if t.err != "" { c.Check(err, gc.ErrorMatches, t.err) continue } if !c.Check(err, gc.IsNil) { continue } mirrorURL, err := indexRef.Source.URL("") if !c.Check(err, gc.IsNil) { continue } c.Check(mirrorURL, gc.Equals, t.mirrorURL) c.Check(indexRef.MirroredProductsPath, gc.Equals, t.path) } }
func (s *LxcSuite) TestContainerDirFilesystem(c *gc.C) { for i, test := range []struct { message string output string expected string errorMatch string }{{ message: "btrfs", output: "Type\nbtrfs\n", expected: lxc.Btrfs, }, { message: "ext4", output: "Type\next4\n", expected: "ext4", }, { message: "not enough output", output: "foo", errorMatch: "could not determine filesystem type", }} { c.Logf("%v: %s", i, test.message) s.HookCommandOutput(&lxc.FsCommandOutput, []byte(test.output), nil) value, err := lxc.ContainerDirFilesystem() if test.errorMatch == "" { c.Check(err, gc.IsNil) c.Check(value, gc.Equals, test.expected) } else { c.Check(err, gc.ErrorMatches, test.errorMatch) } } }
func (s *S) TestWeightedTimeSeeded(c *check.C) { c.Log("Note: This test is stochastic and is expected to fail with probability ≈ 0.05.") rand.Seed(time.Now().Unix()) f := make([]float64, len(sel)) ts := make(Selector, len(sel)) for i := 0; i < 1e6; i++ { copy(ts, sel) ts.Init() item, err := ts.Select() if err != nil { c.Fatal(err) } f[item-1]++ } fsum, exsum := 0., 0. for i := range f { fsum += f[i] exsum += exp[i] } fac := fsum / exsum for i := range f { exp[i] *= fac } // Check that our obtained values are within statistical expectations for p = 0.05. // This will not be true approximately 1 in 20 tests. X := chi2(f, exp) c.Logf("H₀: d(Sample) = d(Expect), H₁: d(S) ≠ d(Expect). df = %d, p = 0.05, X² threshold = %.2f, X² = %f", len(f)-1, sigChi2, X) c.Check(X < sigChi2, check.Equals, true) }
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) } }
func (*suite) TestDumpRequest(c *gc.C) { for i, test := range dumpRequestTests { c.Logf("test %d; %#v", i, test.hdr) data := jsoncodec.DumpRequest(&test.hdr, test.body) c.Check(string(data), gc.Equals, test.expect) } }
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) } }
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 (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, }, }, ) }
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) } }
func (s *StorageSuite) TestReadList(c *gc.C) { store := s.env.Storage() v001 := version.MustParseBinary("0.0.1-precise-amd64") t001 := envtesting.UploadFakeToolsVersion(c, store, v001) v100 := version.MustParseBinary("1.0.0-precise-amd64") t100 := envtesting.UploadFakeToolsVersion(c, store, v100) v101 := version.MustParseBinary("1.0.1-precise-amd64") t101 := envtesting.UploadFakeToolsVersion(c, store, v101) for i, t := range []struct { majorVersion int list tools.List }{{ 0, tools.List{t001}, }, { 1, tools.List{t100, t101}, }, { 2, nil, }} { c.Logf("test %d", i) list, err := tools.ReadList(store, t.majorVersion) if t.list != nil { c.Assert(err, gc.IsNil) c.Assert(list, gc.DeepEquals, t.list) } else { c.Assert(err, gc.Equals, tools.ErrNoMatches) } } }
func (s *ConfigSuite) TestFirewallMode(c *gc.C) { for i, test := range firewallModeTests { c.Logf("test %d: %s", i, test.configFirewallMode) attrs := dummy.SampleConfig() if test.configFirewallMode != "" { attrs = attrs.Merge(testing.Attrs{ "firewall-mode": test.configFirewallMode, }) } cfg, err := config.New(config.NoDefaults, attrs) if err != nil { c.Assert(err, gc.ErrorMatches, test.errorMsg) continue } ctx := testing.Context(c) env, err := environs.Prepare(cfg, ctx, configstore.NewMem()) if test.errorMsg != "" { c.Assert(err, gc.ErrorMatches, test.errorMsg) continue } c.Assert(err, gc.IsNil) defer env.Destroy() firewallMode := env.Config().FirewallMode() c.Assert(firewallMode, gc.Equals, test.firewallMode) s.TearDownTest(c) } }