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) }
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) }
// 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) }
// 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) }
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) } }
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) } }
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) } }
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) }
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) }
// 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) }
// 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) }
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) }
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) }
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) }
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) }) }) }) }) }
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() }
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) }) }) }) }) }
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") }
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) } }
func TestPassword(t *testing.T) { account := &doorbot.Account{ ID: 444, Name: "ACME", IsEnabled: true, } person := &doorbot.Person{ ID: 1, Name: "Cookie Monster", Email: "*****@*****.**", } passwordAuthentication := &doorbot.Authentication{ AccountID: 444, PersonID: 1, Token: "$2a$10$8XdprxFRIXCv1TC2cDjMNuQRiYkOX9PIivVpnSMM9b.1UjulLlrVm", // test } passwordRequest := PasswordRequest{ Authentication: PasswordAuthentication{ Email: "*****@*****.**", Password: "******", }, } 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, "*****@*****.**").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) }
func TestImportImage(t *testing.T) { // create cluster c := &Cluster{ engines: make(map[string]*cluster.Engine), } // create engione id := "test-engine" engine := cluster.NewEngine(id, 0, engOpts) engine.Name = id engine.ID = id // create mock client 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.Anything).Return(types.VolumesListResponse{}, nil) apiClient.On("Events", mock.Anything, mock.AnythingOfType("EventsOptions")).Return(&nopCloser{bytes.NewBufferString("")}, 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).Once() // connect client engine.ConnectWithClient(client, apiClient) // add engine to cluster c.engines[engine.ID] = engine // import success readCloser := nopCloser{bytes.NewBufferString("ok")} apiClient.On("ImageImport", mock.Anything, mock.AnythingOfType("types.ImageImportSource"), mock.Anything, mock.AnythingOfType("types.ImageImportOptions")).Return(readCloser, nil).Once() callback := func(what, status string, err error) { // import success assert.Nil(t, err) } c.Import("-", "testImageOK", "latest", bytes.NewReader(nil), callback) // import error readCloser = nopCloser{bytes.NewBufferString("error")} err := fmt.Errorf("Import error") apiClient.On("ImageImport", mock.Anything, mock.AnythingOfType("types.ImageImportSource"), mock.Anything, mock.AnythingOfType("types.ImageImportOptions")).Return(readCloser, err).Once() callback = func(what, status string, err error) { // import error assert.NotNil(t, err) } c.Import("-", "testImageError", "latest", bytes.NewReader(nil), callback) }
func newFakeClient(applicationsError bool, applications *marathon.Applications, tasksError bool, tasks *marathon.Tasks) *fakeClient { // create an instance of our test object fakeClient := new(fakeClient) if applicationsError { fakeClient.On("Applications", mock.AnythingOfType("url.Values")).Return(nil, errors.New("error")) } fakeClient.On("Applications", mock.AnythingOfType("url.Values")).Return(applications, nil) if tasksError { fakeClient.On("AllTasks", mock.AnythingOfType("*marathon.AllTasksOpts")).Return(nil, errors.New("error")) } fakeClient.On("AllTasks", mock.AnythingOfType("*marathon.AllTasksOpts")).Return(tasks, nil) return fakeClient }
func TestEngineState(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("Events", mock.Anything, mock.AnythingOfType("EventsOptions")).Return(&nopCloser{infiniteRead{}}, nil) // The client will return one container at first, then a second one will appear. apiClient.On("ImageList", mock.Anything, mock.AnythingOfType("ImageListOptions")).Return([]types.Image{}, nil).Once() apiClient.On("ContainerList", mock.Anything, types.ContainerListOptions{All: true, Size: false}).Return([]types.Container{{ID: "one"}}, nil).Once() apiClient.On("ContainerInspect", mock.Anything, "one").Return(types.ContainerJSON{ContainerJSONBase: &types.ContainerJSONBase{HostConfig: &containertypes.HostConfig{Resources: containertypes.Resources{CPUShares: 100}}}, Config: &containertypes.Config{}, NetworkSettings: &types.NetworkSettings{Networks: nil}}, nil).Once() filterArgs := filters.NewArgs() filterArgs.Add("id", "two") apiClient.On("ContainerList", mock.Anything, types.ContainerListOptions{All: true, Size: false, Filter: filterArgs}).Return([]types.Container{{ID: "two"}}, nil).Once() apiClient.On("ContainerInspect", mock.Anything, "two").Return(types.ContainerJSON{ContainerJSONBase: &types.ContainerJSONBase{HostConfig: &containertypes.HostConfig{Resources: containertypes.Resources{CPUShares: 100}}}, Config: &containertypes.Config{}, NetworkSettings: &types.NetworkSettings{Networks: nil}}, nil).Once() assert.NoError(t, engine.ConnectWithClient(client, apiClient)) assert.True(t, engine.isConnected()) // The engine should only have a single container at this point. containers := engine.Containers() assert.Len(t, containers, 1) if containers[0].ID != "one" { t.Fatalf("Missing container: one") } // Fake an event which will trigger a refresh. The second container will appear. engine.handler(events.Message{ID: "two", Status: "created"}) containers = engine.Containers() assert.Len(t, containers, 2) if containers[0].ID != "one" && containers[1].ID != "one" { t.Fatalf("Missing container: one") } if containers[0].ID != "two" && containers[1].ID != "two" { t.Fatalf("Missing container: two") } client.Mock.AssertExpectations(t) apiClient.Mock.AssertExpectations(t) }
func Test_ItRespectsNestedValuesFromMultipleSources(t *testing.T) { config := New() s1, s2 := &MockSource{}, &MockSource{} s1Values := map[string]interface{}{ "t1": false, "t2": map[string]interface{}{ "t22": 5, }, "t3": map[string]interface{}{ "t31": map[string]interface{}{ "t312": 6, }, }, } s2Values := map[string]interface{}{ "t1": true, "t2": map[string]interface{}{ "t21": 1, "t22": 2, }, "t3": map[string]interface{}{ "t31": map[string]interface{}{ "t311": 3, "t312": 4, }, }, } expectedValues := map[string]interface{}{ "t1": false, "t2": map[string]interface{}{ "t21": 1, "t22": 5, }, "t3": map[string]interface{}{ "t31": map[string]interface{}{ "t311": 3, "t312": 6, }, }, } 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) }
func (suite *APITestSuite) TestCreateJobSuccess() { payload := "{\"name\":\"foo\"}\n" suite.jm.On("Create", mock.AnythingOfType("*job.Job")).Return(nil) suite.jm.On("Execute", mock.AnythingOfType("*job.Job")).Return(nil) res, _ := http.Post(suite.url("jobs"), "application/json", bytes.NewBufferString(payload)) body, _ := ioutil.ReadAll(res.Body) time.Sleep(time.Millisecond) suite.Equal(http.StatusCreated, res.StatusCode) suite.Equal(payload, string(body)) suite.jm.Mock.AssertExpectations(suite.T()) }
func TestLoadImage(t *testing.T) { // create cluster c := &Cluster{ engines: make(map[string]*cluster.Engine), } // create engione id := "test-engine" engine := cluster.NewEngine(id, 0, engOpts) engine.Name = id engine.ID = id // create mock client 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.Anything).Return(types.VolumesListResponse{}, nil) apiClient.On("Events", mock.Anything, mock.AnythingOfType("EventsOptions")).Return(&nopCloser{bytes.NewBufferString("")}, 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).Once() // connect client engine.ConnectWithClient(client, apiClient) // add engine to cluster c.engines[engine.ID] = engine // load success readCloser := nopCloser{bytes.NewBufferString("")} apiClient.On("ImageLoad", mock.Anything, mock.AnythingOfType("*io.PipeReader"), false).Return(types.ImageLoadResponse{Body: readCloser}, nil).Once() callback := func(what, status string, err error) { //if load OK, err will be nil assert.Nil(t, err) } c.Load(bytes.NewReader(nil), callback) // load error err := fmt.Errorf("Load error") apiClient.On("ImageLoad", mock.Anything, mock.AnythingOfType("*io.PipeReader"), false).Return(types.ImageLoadResponse{}, err).Once() callback = func(what, status string, err error) { // load error, err is not nil assert.NotNil(t, err) } c.Load(bytes.NewReader(nil), callback) }
func TestImportImage(t *testing.T) { // create cluster c := &Cluster{ engines: make(map[string]*cluster.Engine), } // create engione id := "test-engine" engine := cluster.NewEngine(id, 0) engine.Name = id engine.ID = id // create mock client client := mockclient.NewMockClient() client.On("Info").Return(mockInfo, nil) client.On("Version").Return(mockVersion, nil) client.On("StartMonitorEvents", mock.Anything, mock.Anything, mock.Anything).Return() client.On("ListContainers", true, false, "").Return([]dockerclient.Container{}, nil).Once() client.On("ListImages", mock.Anything).Return([]*dockerclient.Image{}, nil) client.On("ListVolumes", mock.Anything).Return([]*dockerclient.Volume{}, nil) client.On("ListNetworks", mock.Anything).Return([]*dockerclient.NetworkResource{}, nil) // connect client engine.ConnectWithClient(client) // add engine to cluster c.engines[engine.ID] = engine // import success readCloser := nopCloser{bytes.NewBufferString("ok")} client.On("ImportImage", mock.Anything, mock.Anything, mock.Anything, mock.AnythingOfType("*io.PipeReader")).Return(readCloser, nil).Once() callback := func(what, status string, err error) { // import success assert.Nil(t, err) } c.Import("-", "testImageOK", "latest", bytes.NewReader(nil), callback) // import error readCloser = nopCloser{bytes.NewBufferString("error")} err := fmt.Errorf("Import error") client.On("ImportImage", mock.Anything, mock.Anything, mock.Anything, mock.AnythingOfType("*io.PipeReader")).Return(readCloser, err).Once() callback = func(what, status string, err error) { // import error assert.NotNil(t, err) } c.Import("-", "testImageError", "latest", bytes.NewReader(nil), callback) }
func TestEngineState(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) client.On("StartMonitorEvents", mock.Anything, mock.Anything, mock.Anything).Return() // The client will return one container at first, then a second one will appear. client.On("ListContainers", true, false, "").Return([]dockerclient.Container{{Id: "one"}}, nil).Once() apiClient.On("ImageList", mock.Anything, mock.AnythingOfType("ImageListOptions")).Return([]types.Image{}, nil).Once() client.On("InspectContainer", "one").Return(&dockerclient.ContainerInfo{Config: &dockerclient.ContainerConfig{CpuShares: 100}}, nil).Once() client.On("ListContainers", true, false, fmt.Sprintf("{%q:[%q]}", "id", "two")).Return([]dockerclient.Container{{Id: "two"}}, nil).Once() client.On("InspectContainer", "two").Return(&dockerclient.ContainerInfo{Config: &dockerclient.ContainerConfig{CpuShares: 100}}, nil).Once() assert.NoError(t, engine.ConnectWithClient(client, apiClient)) assert.True(t, engine.isConnected()) // The engine should only have a single container at this point. containers := engine.Containers() assert.Len(t, containers, 1) if containers[0].Id != "one" { t.Fatalf("Missing container: one") } // Fake an event which will trigger a refresh. The second container will appear. engine.handler(&dockerclient.Event{ID: "two", Status: "created"}, nil) containers = engine.Containers() assert.Len(t, containers, 2) if containers[0].Id != "one" && containers[1].Id != "one" { t.Fatalf("Missing container: one") } if containers[0].Id != "two" && containers[1].Id != "two" { t.Fatalf("Missing container: two") } client.Mock.AssertExpectations(t) apiClient.Mock.AssertExpectations(t) }
func TestDFSAlmostEmptyGraph(t *testing.T) { g := ggv.NewGraph() g.SetName("G") g.AddNode("G", "N1", nil) g.SetDir(true) nodeToOutEdges := map[string][]*ggv.Edge{} buffer := new(bytes.Buffer) mockPathStringer := new(mockPathStringer) anythingType := mock.AnythingOfType("map[string]*gographviz.Node") mockPathStringer.On("pathAsString", []ggv.Edge{}, anythingType).Return("").Once() searcherWithTestStringer := &defaultSearcher{ pathStringer: mockPathStringer, } searcherWithTestStringer.dfs(searchArgs{ root: "N1", path: []ggv.Edge{}, nodeToOutEdges: nodeToOutEdges, nameToNodes: g.Nodes.Lookup, buffer: buffer, statusMap: make(map[string]discoveryStatus), }) correctOutput := "" actualOutput := buffer.String() assert.Equal(t, correctOutput, actualOutput) mockPathStringer.AssertExpectations(t) }
func TestUpload(t *testing.T) { mockS3 := new(S3API) mockUploader := new(mockS3uploader) mockS3.On("ListObjects", &s3.ListObjectsInput{ Bucket: aws.String("droot-containers"), }).Return(&s3.ListObjectsOutput{}, nil) in := bytes.NewReader([]byte{}) mockUploader.On("Upload", &s3manager.UploadInput{ Bucket: aws.String("droot-containers"), Key: aws.String("app.tar.gz"), Body: in, }, mock.AnythingOfType("func(*s3manager.Uploader)"), ).Return(&s3manager.UploadOutput{ Location: "https://droot-containers.s3-ap-northeast-1.amazonaws.com/app.tar.gz", }, nil) c := &S3Client{svc: mockS3, uploader: mockUploader} location, err := c.Upload("droot-containers", "app.tar.gz", in) assert.NoError(t, err) assert.Equal(t, "https://droot-containers.s3-ap-northeast-1.amazonaws.com/app.tar.gz", location) }