当前位置: 首页>>代码示例>>Golang>>正文


Golang mock.AnythingOfType函数代码示例

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


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


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