• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang mock.AnythingOfType函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/stretchr/testify/mock.AnythingOfType函数的典型用法代码示例。如果您正苦于以下问题:Golang AnythingOfType函数的具体用法?Golang AnythingOfType怎么用?Golang AnythingOfType使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了AnythingOfType函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: TestCommandCommit_NoContainer

func TestCommandCommit_NoContainer(t *testing.T) {
	b, c := makeBuild(t, "", Config{})
	cmd := &CommandCommit{}

	resultImage := &docker.Image{ID: "789"}
	b.state.ImageID = "123"
	b.state.Commit("a").Commit("b")

	c.On("CreateContainer", mock.AnythingOfType("State")).Return("456", nil).Run(func(args mock.Arguments) {
		arg := args.Get(0).(State)
		assert.Equal(t, []string{"/bin/sh", "-c", "#(nop) a; b"}, arg.Config.Cmd)
	}).Once()

	c.On("CommitContainer", mock.AnythingOfType("State")).Return(resultImage, nil).Once()
	c.On("RemoveContainer", "456").Return(nil).Once()

	state, err := cmd.Execute(b)
	if err != nil {
		t.Fatal(err)
	}

	c.AssertExpectations(t)
	assert.Equal(t, "a; b", b.state.GetCommits())
	assert.Equal(t, "", state.GetCommits())
	assert.Equal(t, "789", state.ImageID)
	assert.Equal(t, "", state.NoCache.ContainerID)
}
开发者ID:andrewrothstein,项目名称:rocker,代码行数:27,代码来源:commands_test.go


示例2: TestCommandCopy_Simple

func TestCommandCopy_Simple(t *testing.T) {
	// TODO: do we need to check the dest is always a directory?
	b, c := makeBuild(t, "", Config{})
	cmd := NewCommand(ConfigCommand{
		name: "copy",
		args: []string{"testdata/Rockerfile", "/Rockerfile"},
	})

	c.On("CreateContainer", mock.AnythingOfType("State")).Return("456", nil).Run(func(args mock.Arguments) {
		arg := args.Get(0).(State)
		// TODO: a better check
		assert.True(t, len(arg.Config.Cmd) > 0)
	}).Once()

	c.On("UploadToContainer", "456", mock.AnythingOfType("*io.PipeReader"), "/").Return(nil).Once()

	state, err := cmd.Execute(b)
	if err != nil {
		t.Fatal(err)
	}

	t.Logf("state: %# v", pretty.Formatter(state))

	c.AssertExpectations(t)
	assert.Equal(t, "456", state.NoCache.ContainerID)
}
开发者ID:andrewrothstein,项目名称:rocker,代码行数:26,代码来源:commands_test.go


示例3: TestTeardownCallsShaper

// TestTeardownBeforeSetUp tests that a `TearDown` call does call
// `shaper.Reset`
func TestTeardownCallsShaper(t *testing.T) {
	fexec := &exec.FakeExec{
		CommandScript: []exec.FakeCommandAction{},
		LookPathFunc: func(file string) (string, error) {
			return fmt.Sprintf("/fake-bin/%s", file), nil
		},
	}
	fhost := nettest.NewFakeHost(nil)
	fshaper := &bandwidth.FakeShaper{}
	mockcni := &mock_cni.MockCNI{}
	kubenet := newFakeKubenetPlugin(map[kubecontainer.ContainerID]string{}, fexec, fhost)
	kubenet.cniConfig = mockcni
	kubenet.iptables = ipttest.NewFake()
	kubenet.bandwidthShaper = fshaper
	kubenet.hostportHandler = hostporttest.NewFakeHostportHandler()

	mockcni.On("DelNetwork", mock.AnythingOfType("*libcni.NetworkConfig"), mock.AnythingOfType("*libcni.RuntimeConf")).Return(nil)

	details := make(map[string]interface{})
	details[network.NET_PLUGIN_EVENT_POD_CIDR_CHANGE_DETAIL_CIDR] = "10.0.0.1/24"
	kubenet.Event(network.NET_PLUGIN_EVENT_POD_CIDR_CHANGE, details)

	existingContainerID := kubecontainer.BuildContainerID("docker", "123")
	kubenet.podIPs[existingContainerID] = "10.0.0.1"

	if err := kubenet.TearDownPod("namespace", "name", existingContainerID); err != nil {
		t.Fatalf("Unexpected error in TearDownPod: %v", err)
	}
	assert.Equal(t, []string{"10.0.0.1/32"}, fshaper.ResetCIDRs, "shaper.Reset should have been called")

	mockcni.AssertExpectations(t)
}
开发者ID:Xmagicer,项目名称:origin,代码行数:34,代码来源:kubenet_linux_test.go


示例4: TestTearDownWithoutRuntime

// TestInvocationWithoutRuntime invokes the plugin without a runtime.
// This is how kubenet is invoked from the cri.
func TestTearDownWithoutRuntime(t *testing.T) {
	fhost := nettest.NewFakeHost(nil)
	fhost.Legacy = false
	fhost.Runtime = nil
	mockcni := &mock_cni.MockCNI{}

	fexec := &exec.FakeExec{
		CommandScript: []exec.FakeCommandAction{},
		LookPathFunc: func(file string) (string, error) {
			return fmt.Sprintf("/fake-bin/%s", file), nil
		},
	}

	kubenet := newFakeKubenetPlugin(map[kubecontainer.ContainerID]string{}, fexec, fhost)
	kubenet.cniConfig = mockcni
	kubenet.iptables = ipttest.NewFake()

	details := make(map[string]interface{})
	details[network.NET_PLUGIN_EVENT_POD_CIDR_CHANGE_DETAIL_CIDR] = "10.0.0.1/24"
	kubenet.Event(network.NET_PLUGIN_EVENT_POD_CIDR_CHANGE, details)

	existingContainerID := kubecontainer.BuildContainerID("docker", "123")
	kubenet.podIPs[existingContainerID] = "10.0.0.1"

	mockcni.On("DelNetwork", mock.AnythingOfType("*libcni.NetworkConfig"), mock.AnythingOfType("*libcni.RuntimeConf")).Return(nil)

	if err := kubenet.TearDownPod("namespace", "name", existingContainerID); err != nil {
		t.Fatalf("Unexpected error in TearDownPod: %v", err)
	}
	// Assert that the CNI DelNetwork made it through and we didn't crash
	// without a runtime.
	mockcni.AssertExpectations(t)
}
开发者ID:Q-Lee,项目名称:kubernetes,代码行数:35,代码来源:kubenet_linux_test.go


示例5: TestKMS

func TestKMS(t *testing.T) {
	mockKMS := &mocks.KMSAPI{}
	defer mockKMS.AssertExpectations(t)
	kmsSvc = mockKMS
	isMocked = true
	encryptOutput := &kms.EncryptOutput{}
	decryptOutput := &kms.DecryptOutput{}
	mockKMS.On("Encrypt", mock.AnythingOfType("*kms.EncryptInput")).Return(encryptOutput, nil).Run(func(args mock.Arguments) {
		encryptOutput.CiphertextBlob = args.Get(0).(*kms.EncryptInput).Plaintext
	})
	mockKMS.On("Decrypt", mock.AnythingOfType("*kms.DecryptInput")).Return(decryptOutput, nil).Run(func(args mock.Arguments) {
		decryptOutput.Plaintext = args.Get(0).(*kms.DecryptInput).CiphertextBlob
	})
	k := MasterKey{Arn: "arn:aws:kms:us-east-1:927034868273:key/e9fc75db-05e9-44c1-9c35-633922bac347", Role: "", EncryptedKey: ""}
	f := func(x []byte) bool {
		err := k.Encrypt(x)
		if err != nil {
			fmt.Println(err)
		}
		v, err := k.Decrypt()
		if err != nil {
			fmt.Println(err)
		}
		return bytes.Equal(v, x)
	}
	config := quick.Config{}
	if testing.Short() {
		config.MaxCount = 10
	}
	if err := quick.Check(f, &config); err != nil {
		t.Error(err)
	}
}
开发者ID:twolfson,项目名称:sops,代码行数:33,代码来源:keysource_test.go


示例6: TestBuild_ReplaceEnvVars

func TestBuild_ReplaceEnvVars(t *testing.T) {
	rockerfile := "FROM ubuntu\nENV PATH=$PATH:/cassandra/bin"
	b, c := makeBuild(t, rockerfile, Config{})
	plan := makePlan(t, rockerfile)

	img := &docker.Image{
		ID: "123",
		Config: &docker.Config{
			Env: []string{"PATH=/usr/bin"},
		},
	}

	resultImage := &docker.Image{ID: "789"}

	c.On("InspectImage", "ubuntu").Return(img, nil).Once()

	c.On("CreateContainer", mock.AnythingOfType("State")).Return("456", nil).Run(func(args mock.Arguments) {
		arg := args.Get(0).(State)
		assert.Equal(t, []string{"PATH=/usr/bin:/cassandra/bin"}, arg.Config.Env)
	}).Once()

	c.On("CommitContainer", mock.AnythingOfType("State"), "ENV PATH=/usr/bin:/cassandra/bin").Return(resultImage, nil).Once()

	c.On("RemoveContainer", "456").Return(nil).Once()

	if err := b.Run(plan); err != nil {
		t.Fatal(err)
	}
}
开发者ID:romank87,项目名称:rocker,代码行数:29,代码来源:build_test.go


示例7: TestServeRequestDispatch

func TestServeRequestDispatch(t *testing.T) {
	testCases := []struct {
		t MessageType
		a mock.AnythingOfTypeArgument
	}{
		{MessageTypeDHCPDiscover, mock.AnythingOfType("DHCPDiscover")},
		{MessageTypeDHCPRequest, mock.AnythingOfType("DHCPRequest")},
		{MessageTypeDHCPDecline, mock.AnythingOfType("DHCPDecline")},
		{MessageTypeDHCPRelease, mock.AnythingOfType("DHCPRelease")},
		{MessageTypeDHCPInform, mock.AnythingOfType("DHCPInform")},
	}

	for _, testCase := range testCases {
		var buf []byte
		var err error

		p := NewPacket(BootRequest)
		p.SetMessageType(testCase.t)

		if buf, err = PacketToBytes(p, nil); err != nil {
			panic(err)
		}

		pc := &testPacketConn{}
		pc.ReadSuccess(buf)
		pc.ReadError(io.EOF)

		h := &testHandler{}
		h.On("ServeDHCP", mock.Anything).Return()

		Serve(pc, h)

		h.AssertCalled(t, "ServeDHCP", testCase.a)
	}
}
开发者ID:vmware,项目名称:godhcpv4,代码行数:35,代码来源:handler_test.go


示例8: Test_ItOverwritesValuesFromHigherPrioritySources

func Test_ItOverwritesValuesFromHigherPrioritySources(t *testing.T) {
	config := New()
	s1, s2 := &MockSource{}, &MockSource{}
	s1Values := map[string]interface{}{
		"t1": 1,
		"t3": 4,
	}
	s2Values := map[string]interface{}{
		"t2": 2,
		"t3": 3,
	}
	expectedValues := map[string]interface{}{
		"t1": 1,
		"t2": 2,
		"t3": 4,
	}

	s1.On("Unmarshal", mock.AnythingOfType("[]string"), mock.AnythingOfType("KeySplitter")).Return(s1Values, nil)
	s2.On("Unmarshal", mock.AnythingOfType("[]string"), mock.AnythingOfType("KeySplitter")).Return(s2Values, nil)

	config.AddSource(s1)
	config.AddSource(s2)
	config.Parse()

	assert.Equal(t, expectedValues, config.cache)
}
开发者ID:adrianduke,项目名称:configr,代码行数:26,代码来源:configr_test.go


示例9: TestEngineCpusMemory

func TestEngineCpusMemory(t *testing.T) {
	engine := NewEngine("test", 0, engOpts)
	engine.setState(stateUnhealthy)
	assert.False(t, engine.isConnected())

	client := mockclient.NewMockClient()
	apiClient := engineapimock.NewMockClient()
	apiClient.On("Info", mock.Anything).Return(mockInfo, nil)
	apiClient.On("ServerVersion", mock.Anything).Return(mockVersion, nil)
	apiClient.On("NetworkList", mock.Anything,
		mock.AnythingOfType("NetworkListOptions"),
	).Return([]types.NetworkResource{}, nil)
	apiClient.On("VolumeList", mock.Anything,
		mock.AnythingOfType("Args"),
	).Return(types.VolumesListResponse{}, nil)
	apiClient.On("ImageList", mock.Anything, mock.AnythingOfType("ImageListOptions")).Return([]types.Image{}, nil)
	apiClient.On("ContainerList", mock.Anything, types.ContainerListOptions{All: true, Size: false}).Return([]types.Container{}, nil)
	apiClient.On("Events", mock.Anything, mock.AnythingOfType("EventsOptions")).Return(&nopCloser{infiniteRead{}}, nil)

	assert.NoError(t, engine.ConnectWithClient(client, apiClient))
	assert.True(t, engine.isConnected())
	assert.True(t, engine.IsHealthy())

	assert.Equal(t, engine.UsedCpus(), int64(0))
	assert.Equal(t, engine.UsedMemory(), int64(0))

	client.Mock.AssertExpectations(t)
	apiClient.Mock.AssertExpectations(t)
}
开发者ID:cbbs,项目名称:swarm,代码行数:29,代码来源:engine_test.go


示例10: TestPollOnceWithGetMessagesReturnError

// TestPollOnceWithGetMessagesReturnError tests the pollOnce function with errors from GetMessages function
func TestPollOnceWithGetMessagesReturnError(t *testing.T) {
	// prepare test case fields
	proc, tc := prepareTestPollOnce()

	// mock GetMessagesOutput to return one message
	getMessageOutput := ssmmds.GetMessagesOutput{
		Destination:       &testDestination,
		Messages:          make([]*ssmmds.Message, 1),
		MessagesRequestId: &testMessageId,
	}

	// mock GetMessages function to return an error
	tc.MdsMock.On("GetMessages", mock.AnythingOfType("*log.Mock"), mock.AnythingOfType("string")).Return(&getMessageOutput, fmt.Errorf("Test"))
	isMessageProcessed := false
	processMessage = func(proc *Processor, msg *ssmmds.Message) {
		isMessageProcessed = true
	}

	// execute pollOnce
	proc.pollOnce()

	// check expectations
	tc.MdsMock.AssertExpectations(t)
	assert.False(t, isMessageProcessed)
}
开发者ID:aws,项目名称:amazon-ssm-agent,代码行数:26,代码来源:processor_test.go


示例11: TestPollOnceMultipleTimes

// TestPollOnceMultipleTimes tests the pollOnce function with five messages
func TestPollOnceMultipleTimes(t *testing.T) {
	// prepare test case fields
	proc, tc := prepareTestPollOnce()

	// mock GetMessagesOutput to return five message
	getMessageOutput := ssmmds.GetMessagesOutput{
		Destination:       &testDestination,
		Messages:          make([]*ssmmds.Message, 5),
		MessagesRequestId: &testMessageId,
	}

	// mock GetMessages function to return mocked GetMessagesOutput and no error
	tc.MdsMock.On("GetMessages", mock.AnythingOfType("*log.Mock"), mock.AnythingOfType("string")).Return(&getMessageOutput, nil)
	countMessageProcessed := 0
	processMessage = func(proc *Processor, msg *ssmmds.Message) {
		countMessageProcessed++
	}

	// execute pollOnce
	proc.pollOnce()

	// check expectations
	tc.MdsMock.AssertExpectations(t)
	assert.Equal(t, countMessageProcessed, 5)
}
开发者ID:aws,项目名称:amazon-ssm-agent,代码行数:26,代码来源:processor_test.go


示例12: TestEngineSpecs

func TestEngineSpecs(t *testing.T) {
	engine := NewEngine("test", 0, engOpts)
	engine.setState(stateUnhealthy)
	assert.False(t, engine.isConnected())

	client := mockclient.NewMockClient()
	apiClient := engineapimock.NewMockClient()
	apiClient.On("Info", mock.Anything).Return(mockInfo, nil)
	apiClient.On("ServerVersion", mock.Anything).Return(mockVersion, nil)
	apiClient.On("NetworkList", mock.Anything,
		mock.AnythingOfType("NetworkListOptions"),
	).Return([]types.NetworkResource{}, nil)
	apiClient.On("VolumeList", mock.Anything,
		mock.AnythingOfType("Args"),
	).Return(types.VolumesListResponse{}, nil)
	apiClient.On("ImageList", mock.Anything, mock.AnythingOfType("ImageListOptions")).Return([]types.Image{}, nil)
	apiClient.On("ContainerList", mock.Anything, types.ContainerListOptions{All: true, Size: false}).Return([]types.Container{}, nil)
	apiClient.On("Events", mock.Anything, mock.AnythingOfType("EventsOptions")).Return(&nopCloser{infiniteRead{}}, nil)

	assert.NoError(t, engine.ConnectWithClient(client, apiClient))
	assert.True(t, engine.isConnected())
	assert.True(t, engine.IsHealthy())

	assert.Equal(t, engine.Cpus, int64(mockInfo.NCPU))
	assert.Equal(t, engine.Memory, mockInfo.MemTotal)
	assert.Equal(t, engine.Labels["storagedriver"], mockInfo.Driver)
	assert.Equal(t, engine.Labels["executiondriver"], mockInfo.ExecutionDriver)
	assert.Equal(t, engine.Labels["kernelversion"], mockInfo.KernelVersion)
	assert.Equal(t, engine.Labels["operatingsystem"], mockInfo.OperatingSystem)
	assert.Equal(t, engine.Labels["foo"], "bar")

	client.Mock.AssertExpectations(t)
	apiClient.Mock.AssertExpectations(t)
}
开发者ID:cbbs,项目名称:swarm,代码行数:34,代码来源:engine_test.go


示例13: TestCreateVolumeFromSnapshot

func TestCreateVolumeFromSnapshot(t *testing.T) {
	cfg := newConfig()
	cfg.snapshotName = strPtr("my-name")
	fakeAsgEbs := NewFakeAsgEbs(cfg)

	fakeAsgEbs.
		On("findSnapshot", mock.AnythingOfType("string"), mock.AnythingOfType("string")).
		Return(defaultSnapshotId, nil)
	fakeAsgEbs.
		On("createVolume", mock.AnythingOfType("int64"), mock.AnythingOfType("string"), mock.AnythingOfType("string"), mock.AnythingOfType("map[string]string"), mock.AnythingOfType("*string")).
		Return(defaultVolumeId, nil)
	fakeAsgEbs.
		On("waitUntilVolumeAvailable", mock.AnythingOfType("string")).
		Return(nil)
	fakeAsgEbs.
		On("attachVolume", defaultVolumeId, mock.AnythingOfType("string"), mock.AnythingOfType("bool")).
		Return(nil)
	fakeAsgEbs.
		On("mountVolume", mock.AnythingOfType("string"), mock.AnythingOfType("string")).
		Return(nil)

	runAsgEbs(fakeAsgEbs, *cfg)

	fakeAsgEbs.AssertCalled(t, "findSnapshot", "Name", *cfg.snapshotName)
	fakeAsgEbs.AssertNotCalled(t, "findVolume", *cfg.tagKey, *cfg.tagValue)
	fakeAsgEbs.AssertCalled(t, "createVolume", *cfg.createSize, *cfg.createName, *cfg.createVolumeType, *cfg.createTags, strPtr(defaultSnapshotId))
	fakeAsgEbs.AssertCalled(t, "waitUntilVolumeAvailable", defaultVolumeId)
	fakeAsgEbs.AssertCalled(t, "attachVolume", defaultVolumeId, *cfg.attachAs, *cfg.deleteOnTermination)
	fakeAsgEbs.AssertNotCalled(t, "makeFileSystem", filepath.Join("/dev", *cfg.attachAs), *cfg.mkfsInodeRatio, defaultVolumeId)
	fakeAsgEbs.AssertCalled(t, "mountVolume", filepath.Join("/dev", *cfg.attachAs), *cfg.mountPoint)
}
开发者ID:Jimdo,项目名称:asg-ebs,代码行数:31,代码来源:main_test.go


示例14: TestRetryIfVolumeCouldNotBeAttached

func TestRetryIfVolumeCouldNotBeAttached(t *testing.T) {
	// This is testing for a race condition when somebody stole our volume.
	cfg := newConfig()
	fakeAsgEbs := NewFakeAsgEbs(cfg)

	anotherVolumeId := "vol-123457"

	fakeAsgEbs.
		On("findVolume", mock.AnythingOfType("string"), mock.AnythingOfType("string")).
		Return(defaultVolumeId, nil).Once()
	fakeAsgEbs.
		On("findVolume", mock.AnythingOfType("string"), mock.AnythingOfType("string")).
		Return(anotherVolumeId, nil)
	fakeAsgEbs.
		On("attachVolume", defaultVolumeId, mock.AnythingOfType("string"), mock.AnythingOfType("bool")).
		Return(errors.New("Already attached")).Once()
	fakeAsgEbs.
		On("attachVolume", anotherVolumeId, mock.AnythingOfType("string"), mock.AnythingOfType("bool")).
		Return(nil)
	fakeAsgEbs.
		On("mountVolume", mock.AnythingOfType("string"), mock.AnythingOfType("string")).
		Return(nil)

	runAsgEbs(fakeAsgEbs, *cfg)

	fakeAsgEbs.AssertNumberOfCalls(t, "findVolume", 2)
	fakeAsgEbs.AssertNumberOfCalls(t, "attachVolume", 2)
	fakeAsgEbs.AssertNotCalled(t, "makeFileSystem", filepath.Join("/dev", *cfg.attachAs), *cfg.mkfsInodeRatio, defaultVolumeId)
	fakeAsgEbs.AssertCalled(t, "mountVolume", filepath.Join("/dev", *cfg.attachAs), *cfg.mountPoint)
}
开发者ID:Jimdo,项目名称:asg-ebs,代码行数:30,代码来源:main_test.go


示例15: TestGetMetrics

func TestGetMetrics(t *testing.T) {
	Convey("Given docker id and running containers info", t, func() {
		longDockerId := "1234567890ab9207edb4e6188cf5be3294c23c936ca449c3d48acd2992e357a8"
		containersInfo := []ContainerInfo{ContainerInfo{Id: longDockerId}}
		mountPoint := "cgroup/mount/point/path"
		stats := cgroups.NewStats()

		Convey("and docker plugin initialized", func() {
			mockClient := new(ClientMock)
			mockStats := new(StatsMock)
			mockTools := new(ToolsMock)
			mockWrapper := map[string]Stats{"cpu": mockStats}

			mockTools.On(
				"Map2Namespace",
				mock.Anything,
				mock.AnythingOfType("string"),
				mock.AnythingOfType("*[]string"),
			).Return().Run(
				func(args mock.Arguments) {
					id := args.String(1)
					ns := args.Get(2).(*[]string)
					*ns = append(*ns, filepath.Join(id, "cpu_stats/cpu_usage/total_usage"))
				})

			mockClient.On("FindCgroupMountpoint", "cpu").Return(mountPoint, nil)
			mockStats.On("GetStats", mock.AnythingOfType("string"), mock.AnythingOfType("*cgroups.Stats")).Return(nil)

			d := &docker{
				stats:          stats,
				client:         mockClient,
				tools:          mockTools,
				groupWrap:      mockWrapper,
				containersInfo: containersInfo,
				hostname:       "",
			}

			Convey("When GetMetrics is called", func() {
				mts, err := d.GetMetricTypes(plugin.PluginConfigType{})

				Convey("Then no error should be reported", func() {
					So(err, ShouldBeNil)
				})

				Convey("Then one explicit metric should be returned and wildcard docker id metric", func() {
					So(len(mts), ShouldEqual, 2)
				})

				Convey("Then metric namespace should be correctly set", func() {
					ns := filepath.Join(mts[0].Namespace()...)
					expected := filepath.Join(
						NS_VENDOR, NS_CLASS, NS_PLUGIN, longDockerId[:12], "cpu_stats", "cpu_usage", "total_usage")
					So(ns, ShouldEqual, expected)
				})
			})
		})

	})
}
开发者ID:sandlbn,项目名称:snap-plugin-collector-docker,代码行数:59,代码来源:docker_test.go


示例16: TestPruneExpired

func (s *MutexSuite) TestPruneExpired() {
	underTest := NewMutex(VALID_MUTEX_NAME, VALID_MUTEX_TTL, s.mock)

	s.mock.On("Get", mock.AnythingOfType("string")).Return(&models.Item{Name: VALID_MUTEX_NAME, Created: VALID_MUTEX_CREATED}, nil)
	s.mock.On("Delete", mock.AnythingOfType("string")).Return(nil)

	underTest.PruneExpired()
}
开发者ID:rgarcia,项目名称:ddbsync,代码行数:8,代码来源:mutex_test.go


示例17: TestCollectMetricsWildcard

func TestCollectMetricsWildcard(t *testing.T) {

	Convey("Given * wildcard in requested metric type", t, func() {

		mountPoint := "cgroup/mount/point/path"
		longDockerId1 := "1234567890ab9207edb4e6188cf5be3294c23c936ca449c3d48acd2992e357a8"
		longDockerId2 := "0987654321yz9207edb4e6188cf5be3294c23c936ca449c3d48acd2992e357a8"

		ns := []string{NS_VENDOR, NS_CLASS, NS_PLUGIN, "*", "cpu_stats", "cpu_usage", "total_usage"}
		metricTypes := []plugin.PluginMetricType{plugin.PluginMetricType{Namespace_: ns}}

		Convey("and docker plugin intitialized", func() {

			stats := cgroups.NewStats()

			mockClient := new(ClientMock)
			mockStats := new(StatsMock)
			mockTools := new(ToolsMock)
			mockWrapper := map[string]Stats{"cpu": mockStats}

			mockClient.On("FindCgroupMountpoint", "cpu").Return(mountPoint, nil)

			mockStats.On("GetStats", mock.AnythingOfType("string"), stats).Return(nil)

			mockTools.On("GetValueByNamespace", mock.AnythingOfType("*cgroups.Stats"), mock.Anything).Return(43)

			d := &docker{
				stats:  stats,
				client: mockClient,
				tools:  mockTools,
				containersInfo: []ContainerInfo{
					ContainerInfo{Id: longDockerId1},
					ContainerInfo{Id: longDockerId2}},
				groupWrap: mockWrapper,
				hostname:  "",
			}

			Convey("When CollectMetric is called", func() {
				mts, err := d.CollectMetrics(metricTypes)

				Convey("Then error should not be reported", func() {
					So(err, ShouldBeNil)
				})

				Convey("Two metrics should be returned", func() {
					So(len(mts), ShouldEqual, 2)
				})

				Convey("Metric value should be correctly set", func() {
					So(mts[0].Data(), ShouldEqual, 43)
					So(mts[1].Data(), ShouldEqual, 43)
				})
			})

		})
	})
}
开发者ID:sandlbn,项目名称:snap-plugin-collector-docker,代码行数:57,代码来源:docker_test.go


示例18: TestMockedCookieJar

func TestMockedCookieJar(t *testing.T) {
	jar := &CookieJarMock{}
	cookie := http.Cookie{Name: "hello", Value: "World"}
	jar.On("Cookies", mock.AnythingOfType("*url.URL")).Return([]*http.Cookie{&cookie}).Once()
	c := http.Client{Jar: jar}
	c.Get("http://localhost")

	jar.On("Cookies", mock.AnythingOfType("*url.URL")).Return(nil).Once()
	c.Get("http://localhost")
}
开发者ID:ernesto-jimenez,项目名称:gogen,代码行数:10,代码来源:generator_test.go


示例19: TestAPNS

func TestAPNS(t *testing.T) {

	msg := new(CommandMsg)
	json.Unmarshal([]byte(`{
		"command": {
			"command": "push",
			"push_type": "ios",
			"build": "store",
			"device_token": "123456"
		},
		"message": {
			"event": "foobaz",
			"data": {
				"message_text": "foobar"
			},
			"time": 1234
		}
	}`), &msg)

	configVars := make(map[string]string)
	configVars["ios_push_sound"] = "bingbong.wav"

	mockAPNS := &apns.MockClient{}

	mockAPNS.On("Send", mock.AnythingOfType("*apns.PushNotification")).Return(&apns.PushNotificationResponse{
		Success:       true,
		AppleResponse: "Hello from California!",
		Error:         nil,
	})

	server := &Server{
		Stats: &DiscardStats{},
		Config: &Configuration{
			vars: configVars,
		},
		apnsProvider: func(build string) apns.APNSClient { return mockAPNS },
	}

	msg.FromRedis(server)

	mockAPNS.AssertCalled(t, "Send", mock.AnythingOfType("*apns.PushNotification"))

	pushNotification := mockAPNS.Calls[0].Arguments[0].(*apns.PushNotification)

	if pushNotification.DeviceToken != "123456" {
		t.Fatalf("Expected device token to be 123456, instead %s in %+v", pushNotification.DeviceToken, pushNotification)
	}

	apsPayload := pushNotification.Get("aps").(*apns.Payload)

	if apsPayload.Alert != "foobar" {
		t.Fatalf("Expected push alert to be \"foobar\", instead %s in %+v", apsPayload.Alert, pushNotification)
	}

}
开发者ID:se77en,项目名称:incus,代码行数:55,代码来源:message_test.go


示例20: TestPassword

func TestPassword(t *testing.T) {
	account := &doorbot.Account{
		ID:        444,
		Name:      "ACME",
		IsEnabled: true,
	}

	person := &doorbot.Person{
		ID:    1,
		Name:  "Cookie Monster",
		Email: "[email protected]",
	}

	passwordAuthentication := &doorbot.Authentication{
		AccountID: 444,
		PersonID:  1,
		Token:     "$2a$10$8XdprxFRIXCv1TC2cDjMNuQRiYkOX9PIivVpnSMM9b.1UjulLlrVm", // test
	}

	passwordRequest := PasswordRequest{
		Authentication: PasswordAuthentication{
			Email:    "[email protected]",
			Password: "test",
		},
	}

	var tokenNotFound *doorbot.Authentication

	render := new(tests.MockRender)
	personRepo := new(tests.MockPersonRepository)
	authRepo := new(tests.MockAuthenticationRepository)

	repositories := new(tests.MockRepositories)
	repositories.On("PersonRepository").Return(personRepo)
	repositories.On("AuthenticationRepository").Return(authRepo)

	db := new(tests.MockExecutor)
	repositories.On("DB").Return(db)

	personRepo.On("FindByEmail", db, "[email protected]").Return(person, nil)

	authRepo.On("FindByPersonIDAndProviderID", db, person.ID, auth.ProviderPassword).Return(passwordAuthentication, nil).Once()
	authRepo.On("FindByPersonIDAndProviderID", db, person.ID, auth.ProviderAPIToken).Return(tokenNotFound, nil).Once()
	authRepo.On("Create", db, mock.AnythingOfType("*doorbot.Authentication")).Return(nil).Once()

	render.On("JSON", http.StatusOK, mock.AnythingOfType("auth.APITokenResponse")).Return().Once()
	Password(render, account, repositories, passwordRequest)

	render.Mock.AssertExpectations(t)
	personRepo.Mock.AssertExpectations(t)
	repositories.Mock.AssertExpectations(t)
	authRepo.Mock.AssertExpectations(t)
}
开发者ID:masom,项目名称:doorbot,代码行数:53,代码来源:auth_test.go



注:本文中的github.com/stretchr/testify/mock.AnythingOfType函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang mock.AssertExpectationsForObjects函数代码示例发布时间:2022-05-28
下一篇:
Golang http.TestResponseWriter类代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap