Exemple #1
0
func (s *commonMachineSuite) SetUpTest(c *gc.C) {
	s.agentSuite.SetUpTest(c)
	s.TestSuite.SetUpTest(c)

	os.Remove(jujuRun) // ignore error; may not exist
	// Fake $HOME, and ssh user to avoid touching ~ubuntu/.ssh/authorized_keys.
	fakeHome := coretesting.MakeEmptyFakeHomeWithoutJuju(c)
	s.AddCleanup(func(*gc.C) { fakeHome.Restore() })
	s.PatchValue(&authenticationworker.SSHUser, "")

	testpath := c.MkDir()
	s.PatchEnvPathPrepend(testpath)
	// mock out the start method so we can fake install services without sudo
	fakeCmd(filepath.Join(testpath, "start"))
	fakeCmd(filepath.Join(testpath, "stop"))

	s.PatchValue(&upstart.InitDir, c.MkDir())

	s.singularRecord = &singularRunnerRecord{}
	testing.PatchValue(&newSingularRunner, s.singularRecord.newSingularRunner)
	testing.PatchValue(&peergrouperNew, func(st *state.State) (worker.Worker, error) {
		return newDummyWorker(), nil
	})

	s.fakeEnsureMongo = fakeEnsure{}
	s.PatchValue(&ensureMongoServer, s.fakeEnsureMongo.fakeEnsureMongo)
	s.PatchValue(&maybeInitiateMongoServer, s.fakeEnsureMongo.fakeInitiateMongo)
}
Exemple #2
0
func PatchHostAndCertPool(host string, certPool *x509.CertPool) func() {
	restoreHost := testing.PatchValue(&metricsHost, host)
	restoreCertsPool := testing.PatchValue(&metricsCertsPool, certPool)
	return func() {
		restoreHost()
		restoreCertsPool()
	}
}
Exemple #3
0
func (s *agreeSuite) SetUpTest(c *gc.C) {
	s.client = &mockClient{}

	jujutesting.PatchValue(agree.ClientNew, func(...terms.ClientOption) (terms.Client, error) {
		return s.client, nil
	})
}
Exemple #4
0
func (s *DeploySuite) TestDeployCharmsEndpointNotImplemented(c *gc.C) {
	setter := &testMetricCredentialsSetter{
		assert: func(serviceName string, data []byte) {},
		err: &params.Error{
			Message: "IsMetered",
			Code:    params.CodeNotImplemented,
		},
	}
	cleanup := jujutesting.PatchValue(&getMetricCredentialsAPI, func(_ api.Connection) (metricCredentialsAPI, error) {
		return setter, nil
	})
	defer cleanup()

	stub := &jujutesting.Stub{}
	handler := &testMetricsRegistrationHandler{Stub: stub}
	server := httptest.NewServer(handler)
	defer server.Close()

	testcharms.Repo.ClonedDirPath(s.SeriesPath, "metered")
	deploy := &DeployCommand{Steps: []DeployStep{&RegisterMeteredCharm{RegisterURL: server.URL, QueryURL: server.URL}}}
	_, err := coretesting.RunCommand(c, envcmd.Wrap(deploy), "local:quantal/metered-1", "--plan", "someplan")

	c.Assert(err, jc.ErrorIsNil)
	c.Check(c.GetTestLog(), jc.Contains, "current state server version does not support charm metering")
}
Exemple #5
0
func (s *DeploySuite) TestAddMetricCredentialsHttp(c *gc.C) {
	handler := &testMetricsRegistrationHandler{}
	server := httptest.NewServer(handler)
	defer server.Close()

	var called bool
	setter := &testMetricCredentialsSetter{
		assert: func(serviceName string, data []byte) {
			called = true
			c.Assert(serviceName, gc.DeepEquals, "metered")
			var b []byte
			err := json.Unmarshal(data, &b)
			c.Assert(err, gc.IsNil)
			c.Assert(string(b), gc.Equals, "hello registration")
		},
	}

	cleanup := jujutesting.PatchValue(&getMetricCredentialsAPI, func(_ api.Connection) (metricCredentialsAPI, error) {
		return setter, nil
	})
	defer cleanup()

	testcharms.Repo.ClonedDirPath(s.SeriesPath, "metered")
	_, err := coretesting.RunCommand(c, envcmd.Wrap(&deployCommand{RegisterURL: server.URL}), "local:quantal/metered-1")
	c.Assert(err, jc.ErrorIsNil)
	curl := charm.MustParseURL("local:quantal/metered-1")
	s.AssertService(c, "metered", curl, 1, 0)
	c.Assert(called, jc.IsTrue)

	c.Assert(handler.registrationCalls, gc.HasLen, 1)
	c.Assert(handler.registrationCalls[0].CharmURL, gc.DeepEquals, "local:quantal/metered-1")
	c.Assert(handler.registrationCalls[0].ServiceName, gc.DeepEquals, "metered")
}
Exemple #6
0
func (*PatchValueSuite) TestSetInt(c *gc.C) {
	i := 99
	restore := testing.PatchValue(&i, 88)
	c.Assert(i, gc.Equals, 88)
	restore()
	c.Assert(i, gc.Equals, 99)
}
Exemple #7
0
func (s *storageSuite) SetUpSuite(c *gc.C) {
	s.LoggingSuite.SetUpSuite(c)

	var err error
	flockBin, err = exec.LookPath("flock")
	c.Assert(err, gc.IsNil)

	s.bin = c.MkDir()
	s.PatchEnvPathPrepend(s.bin)

	// Create a "sudo" command which shifts away the "-n", sets
	// SUDO_UID/SUDO_GID, and executes the remaining args.
	err = ioutil.WriteFile(filepath.Join(s.bin, "sudo"), []byte(
		"#!/bin/sh\nshift; export SUDO_UID=`id -u` SUDO_GID=`id -g`; exec \"$@\"",
	), 0755)
	c.Assert(err, gc.IsNil)
	restoreSshCommand := testing.PatchValue(&sshCommand, func(host string, command ...string) *ssh.Cmd {
		return s.sshCommand(c, host, command...)
	})
	s.AddSuiteCleanup(func(*gc.C) { restoreSshCommand() })

	// Create a new "flock" which calls the original, but in non-blocking mode.
	data := []byte(fmt.Sprintf("#!/bin/sh\nexec %s --nonblock \"$@\"", flockBin))
	err = ioutil.WriteFile(filepath.Join(s.bin, "flock"), data, 0755)
	c.Assert(err, gc.IsNil)
}
Exemple #8
0
func checkArgs(c *gc.C, args *CheckArgs, facade string, version int, id, method string, inArgs, outResults interface{}) {
	if args == nil {
		c.Logf("checkArgs: args is nil!")
		return
	} else {
		if args.Facade != "" {
			c.Check(facade, gc.Equals, args.Facade)
		}
		if args.Version != 0 {
			c.Check(version, gc.Equals, args.Version)
		} else if args.VersionIsZero {
			c.Check(version, gc.Equals, 0)
		}
		if args.Id != "" {
			c.Check(id, gc.Equals, args.Id)
		} else if args.IdIsEmpty {
			c.Check(id, gc.Equals, "")
		}
		if args.Method != "" {
			c.Check(method, gc.Equals, args.Method)
		}
		if args.Args != nil {
			c.Check(inArgs, jc.DeepEquals, args.Args)
		}
		if args.Results != nil {
			c.Check(outResults, gc.NotNil)
			testing.PatchValue(outResults, args.Results)
		}
	}
}
Exemple #9
0
func (s *BaseActionSuite) patchAPIClient(client *fakeAPIClient) func() {
	return jujutesting.PatchValue(action.NewActionAPIClient,
		func(c *action.ActionCommandBase) (action.APIClient, error) {
			return client, nil
		},
	)
}
Exemple #10
0
func (s *senderSuite) SetUpTest(c *gc.C) {
	s.spoolDir = c.MkDir()
	s.socketDir = c.MkDir()

	s.metricfactory = &stubMetricFactory{
		&testing.Stub{},
		s.spoolDir,
	}

	declaredMetrics := map[string]corecharm.Metric{
		"pings": corecharm.Metric{Description: "test pings", Type: corecharm.MetricTypeAbsolute},
	}
	recorder, err := s.metricfactory.Recorder(declaredMetrics, "local:trusty/testcharm", "testcharm/0")
	c.Assert(err, jc.ErrorIsNil)

	err = recorder.AddMetric("pings", "50", time.Now())
	c.Assert(err, jc.ErrorIsNil)

	err = recorder.Close()
	c.Assert(err, jc.ErrorIsNil)

	reader, err := s.metricfactory.Reader()
	c.Assert(err, jc.ErrorIsNil)
	batches, err := reader.Read()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(batches, gc.HasLen, 1)

	testing.PatchValue(sender.SocketName, func(_, _ string) string {
		return sockPath(c)
	})
}
Exemple #11
0
func mockAPICaller(c *gc.C, callNumber *int32, apiCalls ...apiCall) apitesting.APICallerFunc {
	apiCaller := apitesting.APICallerFunc(func(objType string, version int, id, request string, arg, result interface{}) error {
		switch objType {
		case "NotifyWatcher":
			return nil
		case "Uniter":
			index := int(atomic.AddInt32(callNumber, 1)) - 1
			c.Check(index < len(apiCalls), jc.IsTrue)
			call := apiCalls[index]
			c.Logf("request %d, %s", index, request)
			c.Check(version, gc.Equals, 4)
			c.Check(id, gc.Equals, "")
			c.Check(request, gc.Equals, call.request)
			c.Check(arg, jc.DeepEquals, call.args)
			if call.err != nil {
				return common.ServerError(call.err)
			}
			testing.PatchValue(result, call.result)
		default:
			c.Fail()
		}
		return nil
	})
	return apiCaller
}
Exemple #12
0
// DisableFinishBootstrap disables common.FinishBootstrap so that tests
// do not attempt to SSH to non-existent machines. The result is a function
// that restores finishBootstrap.
func DisableFinishBootstrap() func() {
	f := func(environs.BootstrapContext, ssh.Client, instance.Instance, *cloudinit.MachineConfig) error {
		logger.Warningf("provider/common.FinishBootstrap is disabled")
		return nil
	}
	return testing.PatchValue(&common.FinishBootstrap, f)
}
func (s *listAgreementsSuite) SetUpTest(c *gc.C) {
	s.FakeJujuXDGDataHomeSuite.SetUpTest(c)
	s.client = &mockClient{}

	jujutesting.PatchValue(listagreements.NewClient, func(_ *httpbakery.Client) (listagreements.TermsServiceClient, error) {
		return s.client, nil
	})
}
Exemple #14
0
func (*PatchValueSuite) TestSetErrorToNil(c *gc.C) {
	oldErr := errors.New("foo")
	err := oldErr
	restore := testing.PatchValue(&err, nil)
	c.Assert(err, gc.Equals, nil)
	restore()
	c.Assert(err, gc.Equals, oldErr)
}
Exemple #15
0
func (*PatchValueSuite) TestSetMapToNil(c *gc.C) {
	oldMap := map[string]int{"foo": 1234}
	m := oldMap
	restore := testing.PatchValue(&m, nil)
	c.Assert(m, gc.IsNil)
	restore()
	c.Assert(m, gc.DeepEquals, oldMap)
}
Exemple #16
0
func (s *agreeSuite) SetUpTest(c *gc.C) {
	s.FakeJujuXDGDataHomeSuite.SetUpTest(c)
	s.client = &mockClient{}

	jujutesting.PatchValue(agree.ClientNew, func(...api.ClientOption) (api.Client, error) {
		return s.client, nil
	})
}
Exemple #17
0
func lifeTest(c *gc.C, stub *testing.Stub, life apiagent.Life, test func() (api.Connection, error)) (api.Connection, error) {
	newFacade := func(apiCaller base.APICaller) (apiagent.ConnFacade, error) {
		c.Check(apiCaller, gc.FitsTypeOf, (*mockConn)(nil))
		return newMockConnFacade(stub, life), nil
	}
	unpatch := testing.PatchValue(apicaller.NewConnFacade, newFacade)
	defer unpatch()
	return test()
}
func (s *RsyslogSuite) SetUpSuite(c *gc.C) {
	s.JujuConnSuite.SetUpSuite(c)
	// TODO(waigani) 2014-03-19 bug 1294462
	// Add patch for suite functions
	restore := testing.PatchValue(rsyslog.LookupUser, func(username string) (uid, gid int, err error) {
		// worker will not attempt to chown files if uid/gid is 0
		return 0, 0, nil
	})
	s.AddSuiteCleanup(func(*gc.C) { restore() })
}
Exemple #19
0
func (s *WindowsHookSuite) TestHookCommandNotPowerShellScripts(c *gc.C) {
	restorer := envtesting.PatchValue(&version.Current.OS, version.Windows)
	defer restorer()

	cmdhook := "somehook.cmd"
	c.Assert(runner.HookCommand(cmdhook), gc.DeepEquals, []string{cmdhook})

	bathook := "somehook.bat"
	c.Assert(runner.HookCommand(bathook), gc.DeepEquals, []string{bathook})
}
Exemple #20
0
func (s *unitSuite) TestWatchActionsNoResults(c *gc.C) {
	restore := testing.PatchValue(uniter.Call, func(st *uniter.State, method string, params, results interface{}) error {
		return nil
	})

	defer restore()

	_, err := s.apiUnit.WatchActions()
	c.Assert(err.Error(), gc.Equals, "expected 1 result, got 0")
}
Exemple #21
0
func (s *unitSuite) TestWatchActionsError(c *gc.C) {
	restore := testing.PatchValue(uniter.Call, func(st *uniter.State, method string, params, results interface{}) error {
		return fmt.Errorf("Test error")
	})

	defer restore()

	_, err := s.apiUnit.WatchActions()
	c.Assert(err.Error(), gc.Equals, "Test error")
}
Exemple #22
0
func lifeTest(c *gc.C, stub *testing.Stub, life apiagent.Life, test func() (api.Connection, error)) (api.Connection, error) {
	expectConn := &mockConn{stub: stub}
	newFacade := func(apiCaller base.APICaller) (apiagent.ConnFacade, error) {
		c.Check(apiCaller, jc.DeepEquals, expectConn)
		return newMockConnFacade(stub, life), nil
	}
	unpatch := testing.PatchValue(apicaller.NewConnFacade, newFacade)
	defer unpatch()
	return test()
}
Exemple #23
0
func (s *WindowsHookSuite) TestHookCommandNotPowerShellScripts(c *gc.C) {
	restorer := envtesting.PatchValue(&os.HostOS, func() os.OSType { return os.Windows })
	defer restorer()

	cmdhook := "somehook.cmd"
	c.Assert(runner.HookCommand(cmdhook), gc.DeepEquals, []string{cmdhook})

	bathook := "somehook.bat"
	c.Assert(runner.HookCommand(bathook), gc.DeepEquals, []string{bathook})
}
Exemple #24
0
func (s *WindowsHookSuite) TestSearchHookWindowsError(c *gc.C) {
	charmDir, _ := makeCharm(c, hookSpec{
		name: "something-happened.linux",
		perm: 0755,
	})

	restorer := envtesting.PatchValue(&version.Current.OS, version.Windows)
	defer restorer()
	obtained, err := uniter.SearchHook(charmDir, filepath.Join("hooks", "something-happened"))
	c.Assert(err, gc.ErrorMatches, "hooks/something-happened does not exist")
	c.Assert(obtained, gc.Equals, "")
}
Exemple #25
0
// AddBackupMetadataID adds the metadata to storage, using the given
// backup ID.
func AddBackupMetadataID(st *state.State, meta *Metadata, id string) error {
	restore := testing.PatchValue(&newStorageID, func(*storageMetaDoc) string {
		return id
	})
	defer restore()

	db := getBackupDBWrapper(st)
	defer db.Close()
	doc := newStorageMetaDoc(meta)
	_, err := addStorageMetadata(db, &doc)
	return errors.Trace(err)
}
Exemple #26
0
func (s prepareGitUniter) step(c *gc.C, ctx *context) {
	c.Assert(ctx.uniter, gc.IsNil, gc.Commentf("please don't try to patch stuff while the uniter's running"))
	newDeployer := func(charmPath, dataPath string, bundles charm.BundleReader) (charm.Deployer, error) {
		return charm.NewGitDeployer(charmPath, dataPath, bundles), nil
	}
	restoreNewDeployer := gt.PatchValue(&charm.NewDeployer, newDeployer)
	defer restoreNewDeployer()

	fixDeployer := func(deployer *charm.Deployer) error {
		return nil
	}
	restoreFixDeployer := gt.PatchValue(&charm.FixDeployer, fixDeployer)
	defer restoreFixDeployer()

	for _, prepStep := range s.prepSteps {
		step(c, ctx, prepStep)
	}
	if ctx.uniter != nil {
		step(c, ctx, stopUniter{})
	}
}
Exemple #27
0
func (s *WindowsHookSuite) TestSearchHookWindows(c *gc.C) {
	charmDir, _ := makeCharm(c, hookSpec{
		name: "something-happened.ps1",
		perm: 0755,
	})

	restorer := envtesting.PatchValue(&version.Current.OS, version.Windows)

	defer restorer()
	obtained, err := uniter.SearchHook(charmDir, filepath.Join("hooks", "something-happened"))
	c.Assert(err, gc.IsNil)
	c.Assert(obtained, gc.Equals, filepath.Join(charmDir, "hooks", "something-happened.ps1"))
}
Exemple #28
0
func (s *unitSuite) TestWatchActionsMoreResults(c *gc.C) {
	restore := testing.PatchValue(uniter.Call, func(st *uniter.State, method string, args, results interface{}) error {
		if results, ok := results.(*params.StringsWatchResults); ok {
			results.Results = make([]params.StringsWatchResult, 2)
		}
		return nil
	})

	defer restore()

	_, err := s.apiUnit.WatchActions()
	c.Assert(err.Error(), gc.Equals, "expected 1 result, got 2")
}
Exemple #29
0
func strategyTest(stub *testing.Stub, strategy utils.AttemptStrategy, test func(api.OpenFunc) (api.Connection, error)) (api.Connection, error) {
	unpatch := testing.PatchValue(apicaller.Strategy, strategy)
	defer unpatch()
	return test(func(info *api.Info, opts api.DialOpts) (api.Connection, error) {
		// copy because I don't trust what might happen to info
		stub.AddCall("apiOpen", *info, opts)
		err := stub.NextErr()
		if err != nil {
			return nil, err
		}
		return &mockConn{stub: stub}, nil
	})
}
Exemple #30
0
func (s *agreeSuite) TestAgreementNothingToSign(c *gc.C) {
	jujutesting.PatchValue(agree.UserAnswer, func() (string, error) {
		return "y", nil
	})

	s.client.user = "******"
	s.client.setUnsignedTerms([]terms.GetTermsResponse{})

	ctx, err := cmdtesting.RunCommand(c, agree.NewAgreeCommand(), "test-term/1")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(cmdtesting.Stdout(ctx), gc.Equals, `Already agreed
`)
}