How to use Len method of gomock Package

Best Mock code snippet using gomock.Len

pubsub_test.go

Source:pubsub_test.go Github

copy

Full Screen

...69 sub := newSubscription(testTopic, expected)70 require.Equal(t, cap(sub.msgChan), expected)71 })72 t.Run("buffered channel", func(t *testing.T) {73 bufLen := 274 sub := newSubscription(testTopic, bufLen)75 require.Equal(t, cap(sub.msgChan), bufLen)76 })77}78func getSubMngr(ctx context.Context, ctrl *gomock.Controller) *subscriptionManager {79 mockConn := mock_net.NewMockConn(ctrl)80 mockConn.EXPECT().SetReadDeadline(gomock.Any())81 opts := &PoolOptions{82 Dial: func(ctx context.Context) (net.Conn, error) {83 return mockConn, nil84 },85 }86 c, _ := NewClient(ctx, opts)87 subMngr := c.(*client).subMngr88 subMngr.getConn(ctx)89 subMngr.msgChan = make(chan *Message, 2)...

Full Screen

Full Screen

controller_test.go

Source:controller_test.go Github

copy

Full Screen

1/*2 * Copyright 2020 Kaiserpfalz EDV-Service, Roland T. Lichti.3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16package installedfeaturegroup_test17import (18 "errors"19 "github.com/golang/mock/gomock"20 . "github.com/klenkes74/k8s-installed-features-catalogue/api/v1alpha1"21 . "github.com/klenkes74/k8s-installed-features-catalogue/controllers/installedfeaturegroup"22 . "github.com/onsi/ginkgo"23 . "github.com/onsi/gomega"24 "github.com/pborman/uuid"25 errors2 "k8s.io/apimachinery/pkg/api/errors"26 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"27 "k8s.io/apimachinery/pkg/runtime/schema"28 "k8s.io/apimachinery/pkg/types"29 k8sclient "sigs.k8s.io/controller-runtime/pkg/client"30 "sigs.k8s.io/controller-runtime/pkg/reconcile"31 "time"32 // +kubebuilder:scaffold:imports33)34var _ = Describe("InstalledFeature controller", func() {35 const (36 name = "basic-feature-group"37 namespace = "default"38 provider = "Kaiserpfalz EDV-Service"39 description = "a basic demonstration feature"40 uri = "https://www.kaiserpfalz-edv.de/k8s/"41 )42 var (43 iftLookupKey = types.NamespacedName{Name: name, Namespace: namespace}44 iftReconcileRequest = reconcile.Request{45 NamespacedName: iftLookupKey,46 }47 )48 Context("When installing a InstalledFeature CR", func() {49 It("should be created when there are no conflicting features installed and all dependencies met", func() {50 By("By creating a new InstalledFeature")51 ift := createIFTG(name, namespace, provider, description, uri, true, false)52 client.EXPECT().LoadInstalledFeatureGroup(gomock.Any(), iftLookupKey).Return(ift, nil)53 client.EXPECT().GetInstalledFeatureGroupPatchBase(gomock.Any()).Return(k8sclient.MergeFrom(ift))54 client.EXPECT().PatchInstalledFeatureGroupStatus(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil)55 result, err := sut.Reconcile(iftReconcileRequest)56 Expect(result).Should(Equal(reconcile.Result{Requeue: false}))57 Expect(err).ShouldNot(HaveOccurred())58 })59 It("should add the finalizer when the finalizer is not set", func() {60 By("By creating a new InstalledFeature without finalizer")61 ift := createIFTG(name, namespace, provider, description, uri, false, false)62 client.EXPECT().LoadInstalledFeatureGroup(gomock.Any(), iftLookupKey).Return(ift, nil)63 expected := copyIFTG(ift)64 expected.Finalizers = make([]string, 1)65 expected.Finalizers[0] = FinalizerName66 client.EXPECT().SaveInstalledFeatureGroup(gomock.Any(), expected).Return(nil)67 client.EXPECT().GetInstalledFeatureGroupPatchBase(gomock.Any()).Return(k8sclient.MergeFrom(ift))68 client.EXPECT().PatchInstalledFeatureGroupStatus(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil)69 result, err := sut.Reconcile(iftReconcileRequest)70 Expect(result).Should(Equal(reconcile.Result{Requeue: false}))71 Expect(err).ShouldNot(HaveOccurred())72 })73 It("should remove the finalizer when the instance is deleted", func() {74 By("By creating a new InstalledFeature without finalizer")75 ift := createIFTG(name, namespace, provider, description, uri, true, true)76 client.EXPECT().LoadInstalledFeatureGroup(gomock.Any(), iftLookupKey).Return(ift, nil)77 expected := copyIFTG(ift)78 expected.Finalizers = make([]string, 0)79 client.EXPECT().SaveInstalledFeatureGroup(gomock.Any(), expected).Return(nil)80 client.EXPECT().GetInstalledFeatureGroupPatchBase(gomock.Any()).Return(k8sclient.MergeFrom(ift))81 client.EXPECT().PatchInstalledFeatureGroupStatus(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil)82 result, err := sut.Reconcile(iftReconcileRequest)83 Expect(result).Should(Equal(reconcile.Result{Requeue: false}))84 Expect(err).ShouldNot(HaveOccurred())85 })86 })87 Context("Delete an existing InstalledFeature", func() {88 It("should be deleted when there are no dependencies on the removed feature", func() {89 // TODO 2020-09-26 klenkes74 Implement this test90 })91 It("should not be deleted when there are dependencies on the removed feature", func() {92 // TODO 2020-09-26 klenkes74 Implement this test93 })94 })95 Context("Technical handling", func() {96 It("should drop the request when the ift can't be loaded due to NotFoundError", func() {97 By("By having a problem loading the ift")98 client.EXPECT().LoadInstalledFeatureGroup(gomock.Any(), iftLookupKey).Return(nil, errors.New("some error"))99 result, err := sut.Reconcile(iftReconcileRequest)100 Expect(result).Should(Equal(reconcile.Result{RequeueAfter: 60}))101 Expect(err).To(HaveOccurred())102 })103 It("should requeue request when the ift can't be loaded due to another error but NotFoundError", func() {104 client.EXPECT().LoadInstalledFeatureGroup(gomock.Any(), iftLookupKey).Return(nil, errors2.NewNotFound(schema.GroupResource{105 Group: "features.kaiserpfalz-edv.de",106 Resource: "installedfeatures",107 }, iftLookupKey.Name))108 result, err := sut.Reconcile(iftReconcileRequest)109 Expect(result).Should(Equal(reconcile.Result{Requeue: false}))110 Expect(err).To(HaveOccurred())111 })112 It("should requeue request when writing the reconciled object fails", func() {113 By("By getting a failure while saving the data back into the k8s cluster")114 ift := createIFTG(name, namespace, provider, description, uri, false, false)115 client.EXPECT().LoadInstalledFeatureGroup(gomock.Any(), iftLookupKey).Return(ift, nil)116 expected := copyIFTG(ift)117 expected.Finalizers = make([]string, 1)118 expected.Finalizers[0] = FinalizerName119 client.EXPECT().SaveInstalledFeatureGroup(gomock.Any(), expected).Return(errors.New("some error"))120 result, err := sut.Reconcile(iftReconcileRequest)121 Expect(result).Should(Equal(reconcile.Result{RequeueAfter: 60}))122 Expect(err).To(HaveOccurred())123 })124 It("should requeue request when writing the reconciled object fails", func() {125 By("By getting a failure while saving the data back into the k8s cluster")126 ift := createIFTG(name, namespace, provider, description, uri, false, false)127 client.EXPECT().LoadInstalledFeatureGroup(gomock.Any(), iftLookupKey).Return(ift, nil)128 expected := copyIFTG(ift)129 expected.Finalizers = make([]string, 1)130 expected.Finalizers[0] = FinalizerName131 client.EXPECT().SaveInstalledFeatureGroup(gomock.Any(), expected).Return(errors.New("some error"))132 result, err := sut.Reconcile(iftReconcileRequest)133 Expect(result).Should(Equal(reconcile.Result{RequeueAfter: 60}))134 Expect(err).To(HaveOccurred())135 })136 It("should requeue the request when updating the status fails", func() {137 By("By getting an error when updating the status")138 ift := createIFTG(name, namespace, provider, description, uri, true, false)139 client.EXPECT().LoadInstalledFeatureGroup(gomock.Any(), iftLookupKey).Return(ift, nil)140 client.EXPECT().GetInstalledFeatureGroupPatchBase(gomock.Any()).Return(k8sclient.MergeFrom(ift))141 client.EXPECT().142 PatchInstalledFeatureGroupStatus(gomock.Any(), gomock.Any(), gomock.Any()).143 Return(errors.New("patching failed"))144 result, err := sut.Reconcile(iftReconcileRequest)145 Expect(result).Should(Equal(reconcile.Result{RequeueAfter: 60}))146 Expect(err).To(HaveOccurred())147 })148 })149})150func createIFTG(name string, namespace string, provider string, description string, uri string, finalizer bool, deleted bool) *InstalledFeatureGroup {151 result := &InstalledFeatureGroup{152 TypeMeta: metav1.TypeMeta{153 Kind: "InstalledFeature",154 APIVersion: GroupVersion.Group + "/" + GroupVersion.Version,155 },156 ObjectMeta: metav1.ObjectMeta{157 Name: name,158 Namespace: namespace,159 CreationTimestamp: metav1.Time{Time: time.Now().Add(24 * time.Hour)},160 ResourceVersion: "1",161 Generation: 0,162 UID: types.UID(uuid.New()),163 },164 Spec: InstalledFeatureGroupSpec{165 Provider: provider,166 Description: description,167 Uri: uri,168 },169 }170 if finalizer {171 result.Finalizers = make([]string, 1)172 result.Finalizers[0] = FinalizerName173 }174 if deleted {175 deletionGracePeriod := int64(60)176 result.DeletionGracePeriodSeconds = &deletionGracePeriod177 result.DeletionTimestamp = &metav1.Time{Time: time.Now().Add(2 * time.Minute)}178 }179 return result180}181func copyIFTG(orig *InstalledFeatureGroup) *InstalledFeatureGroup {182 //goland:noinspection GoDeprecation183 result := &InstalledFeatureGroup{184 TypeMeta: metav1.TypeMeta{185 Kind: orig.TypeMeta.Kind,186 APIVersion: orig.TypeMeta.APIVersion,187 },188 ObjectMeta: metav1.ObjectMeta{189 Name: orig.ObjectMeta.Name,190 GenerateName: orig.ObjectMeta.GenerateName,191 Namespace: orig.ObjectMeta.Namespace,192 SelfLink: orig.ObjectMeta.SelfLink,193 UID: orig.ObjectMeta.UID,194 ResourceVersion: orig.ObjectMeta.ResourceVersion,195 Generation: orig.ObjectMeta.Generation,196 CreationTimestamp: orig.ObjectMeta.CreationTimestamp,197 DeletionTimestamp: orig.ObjectMeta.DeletionTimestamp,198 DeletionGracePeriodSeconds: orig.ObjectMeta.DeletionGracePeriodSeconds,199 ClusterName: orig.ObjectMeta.ClusterName,200 },201 Spec: InstalledFeatureGroupSpec{202 Provider: orig.Spec.Provider,203 Description: orig.Spec.Description,204 Uri: orig.Spec.Uri,205 },206 Status: InstalledFeatureGroupStatus{207 Phase: orig.Status.Phase,208 Message: orig.Status.Message,209 },210 }211 if len(orig.ObjectMeta.Labels) > 0 {212 result.ObjectMeta.Labels = make(map[string]string)213 for key, value := range orig.ObjectMeta.Labels {214 result.ObjectMeta.Labels[key] = value215 }216 }217 if len(orig.ObjectMeta.Annotations) > 0 {218 result.ObjectMeta.Annotations = make(map[string]string)219 for key, value := range orig.ObjectMeta.Annotations {220 result.ObjectMeta.Annotations[key] = value221 }222 }223 if len(orig.ObjectMeta.Finalizers) > 0 {224 result.ObjectMeta.Finalizers = make([]string, len(orig.ObjectMeta.Finalizers))225 for i, value := range orig.ObjectMeta.Finalizers {226 result.ObjectMeta.Finalizers[i] = value227 }228 }229 if len(orig.ObjectMeta.OwnerReferences) > 0 {230 result.ObjectMeta.OwnerReferences = make([]metav1.OwnerReference, len(orig.ObjectMeta.OwnerReferences))231 for i, r := range orig.ObjectMeta.OwnerReferences {232 result.ObjectMeta.OwnerReferences[i] = metav1.OwnerReference{233 APIVersion: r.APIVersion,234 Kind: r.Kind,235 Name: r.Name,236 UID: r.UID,237 Controller: r.Controller,238 BlockOwnerDeletion: r.BlockOwnerDeletion,239 }240 }241 }242 if len(orig.ObjectMeta.ManagedFields) > 0 {243 result.ObjectMeta.ManagedFields = make([]metav1.ManagedFieldsEntry, len(orig.ObjectMeta.ManagedFields))244 for i, r := range orig.ObjectMeta.ManagedFields {245 result.ObjectMeta.ManagedFields[i] = metav1.ManagedFieldsEntry{246 Manager: r.Manager,247 Operation: r.Operation,248 APIVersion: r.APIVersion,249 Time: r.Time,250 FieldsType: r.FieldsType,251 FieldsV1: &metav1.FieldsV1{252 Raw: r.FieldsV1.Raw,253 },254 }255 }256 }257 if len(orig.Status.Features) > 0 {258 result.Status.Features = make([]InstalledFeatureGroupListedFeature, len(orig.Status.Features))259 for i, feature := range orig.Status.Features {260 result.Status.Features[i] = InstalledFeatureGroupListedFeature{261 Namespace: feature.Namespace,262 Name: feature.Name,263 }264 }265 }266 return result267}...

Full Screen

Full Screen

saver_test.go

Source:saver_test.go Github

copy

Full Screen

1package saver_test2import (3 "context"4 "errors"5 "github.com/golang/mock/gomock"6 . "github.com/onsi/ginkgo"7 . "github.com/onsi/gomega"8 "github.com/ozoncp/ocp-feedback-api/internal/mocks"9 "github.com/ozoncp/ocp-feedback-api/internal/models"10 "github.com/ozoncp/ocp-feedback-api/internal/saver"11)12var _ = Describe("Saver", func() {13 Describe("Constructor call", func() {14 var (15 controller *gomock.Controller16 flusher *flusherStub17 alarmer *alarmerStub18 )19 BeforeEach(func() {20 controller = gomock.NewController(GinkgoT())21 flusher = &flusherStub{}22 alarmer = &alarmerStub{make(chan struct{})}23 })24 AfterEach(func() {25 controller.Finish()26 })27 When("arguments are invalid", func() {28 It("should return an error", func() {29 By("receiving invalid capacity")30 got, err := saver.New(0, saver.DropAll, alarmer, flusher)31 Ω(err).Should(HaveOccurred())32 Ω(got).Should(BeNil())33 By("receiving a nil alarmer")34 got, err = saver.New(1, saver.DropAll, nil, flusher)35 Ω(err).Should(HaveOccurred())36 Ω(got).Should(BeNil())37 By("receiving a nil flusher")38 got, err = saver.New(1, saver.DropAll, alarmer, nil)39 Ω(err).Should(HaveOccurred())40 Ω(got).Should(BeNil())41 })42 })43 When("arguments are valid", func() {44 It("should return valid object", func() {45 got, err := saver.New(1, saver.DropAll, alarmer, flusher)46 Ω(err).ShouldNot(HaveOccurred())47 Ω(got).ShouldNot(BeNil())48 })49 })50 })51 Describe("Init call", func() {52 var (53 controller *gomock.Controller54 mockFlusher *mocks.MockFlusher55 alarmer *alarmerStub56 )57 BeforeEach(func() {58 controller = gomock.NewController(GinkgoT())59 mockFlusher = mocks.NewMockFlusher(controller)60 alarmer = &alarmerStub{make(chan struct{})}61 })62 AfterEach(func() {63 controller.Finish()64 })65 Context("Flushing", func() {66 When("Cap is not reached", func() {67 When("Save is not called before closing ", func() {68 It("should flush everything on alarm and close shouldn't flush anything", func() {69 entities := []models.Entity{70 &entityStub{id: 1},71 &entityStub{id: 2},72 &entityStub{id: 3},73 &entityStub{id: 4},74 }75 saver, _ := saver.New(len(entities)+1, saver.DropAll, alarmer, mockFlusher)76 ctx, cancel := context.WithCancel(context.Background())77 defer saver.WaitClosed()78 defer cancel()79 gomock.InOrder(80 mockFlusher.EXPECT().Flush(ctx, gomock.Eq(entities)),81 mockFlusher.EXPECT().Flush(ctx, gomock.Eq(entities[:0])),82 )83 saver.Init(ctx)84 for i := 0; i < len(entities); i++ {85 saver.Save(entities[i])86 }87 alarmer.alarm()88 })89 })90 When("Save is called before closing ", func() {91 It("should flush something on alarm and the rest after close has been called", func() {92 entities := []models.Entity{93 &entityStub{id: 1},94 &entityStub{id: 2},95 &entityStub{id: 3},96 &entityStub{id: 4},97 }98 saver, _ := saver.New(len(entities)+1, saver.DropAll, alarmer, mockFlusher)99 ctx, cancel := context.WithCancel(context.Background())100 defer saver.WaitClosed()101 defer cancel()102 gomock.InOrder(103 mockFlusher.EXPECT().Flush(ctx, gomock.Eq(entities[:2])),104 mockFlusher.EXPECT().Flush(ctx, gomock.Eq(entities[2:])),105 )106 saver.Init(ctx)107 for i := 0; i < 2; i++ {108 saver.Save(entities[i])109 }110 alarmer.alarm()111 for i := 2; i < len(entities); i++ {112 saver.Save(entities[i])113 }114 })115 })116 })117 When("Cap is reached", func() {118 When("Policy is DropAll", func() {119 It("should drop everything", func() {120 entities := []models.Entity{121 &entityStub{id: 1},122 &entityStub{id: 2},123 &entityStub{id: 3},124 &entityStub{id: 4},125 }126 newEntities := []models.Entity{127 &entityStub{id: 10},128 &entityStub{id: 20},129 }130 saver, _ := saver.New(len(entities), saver.DropAll, alarmer, mockFlusher)131 ctx, cancel := context.WithCancel(context.Background())132 defer saver.WaitClosed()133 defer cancel()134 gomock.InOrder(135 mockFlusher.EXPECT().Flush(ctx, gomock.Eq(newEntities)),136 mockFlusher.EXPECT().Flush(ctx, gomock.Eq(newEntities[:0])),137 )138 saver.Init(ctx)139 for i := 0; i < len(entities); i++ {140 saver.Save(entities[i])141 }142 for i := 0; i < len(newEntities); i++ {143 saver.Save(newEntities[i])144 }145 alarmer.alarm()146 })147 })148 })149 When("Policy is DropOne", func() {150 It("should drop the oldest one", func() {151 entities := []models.Entity{152 &entityStub{id: 1},153 &entityStub{id: 2},154 &entityStub{id: 3},155 &entityStub{id: 4},156 }157 shifted := []models.Entity{158 &entityStub{id: 3},159 &entityStub{id: 4},160 &entityStub{id: 5},161 &entityStub{id: 6},162 }163 saver, _ := saver.New(len(entities), saver.DropOne, alarmer, mockFlusher)164 ctx, cancel := context.WithCancel(context.Background())165 defer saver.WaitClosed()166 defer cancel()167 gomock.InOrder(168 mockFlusher.EXPECT().Flush(ctx, gomock.Eq(shifted)),169 mockFlusher.EXPECT().Flush(ctx, gomock.Eq(shifted[:0])),170 )171 saver.Init(ctx)172 for i := 0; i < len(entities); i++ {173 saver.Save(entities[i])174 }175 saver.Save(&entityStub{id: 5})176 saver.Save(&entityStub{id: 6})177 alarmer.alarm()178 })179 })180 })181 When("Close is called", func() {182 It("should flush everything at once", func() {183 entities := []models.Entity{184 &entityStub{id: 1},185 &entityStub{id: 2},186 &entityStub{id: 3},187 &entityStub{id: 4},188 }189 saver, _ := saver.New(len(entities)+1, saver.DropAll, alarmer, mockFlusher)190 ctx, cancel := context.WithCancel(context.Background())191 defer saver.WaitClosed()192 defer cancel()193 mockFlusher.EXPECT().Flush(ctx, gomock.Eq(entities))194 saver.Init(ctx)195 for i := 0; i < len(entities); i++ {196 saver.Save(entities[i])197 }198 cancel()199 })200 })201 When("Flush has failed", func() {202 It("should re-flush remaining", func() {203 entities := []models.Entity{204 &entityStub{id: 1},205 &entityStub{id: 2},206 &entityStub{id: 3},207 &entityStub{id: 4},208 }209 saver, _ := saver.New(len(entities), saver.DropAll, alarmer, mockFlusher)210 ctx, cancel := context.WithCancel(context.Background())211 defer saver.WaitClosed()212 defer cancel()213 gomock.InOrder(214 mockFlusher.EXPECT().Flush(ctx, gomock.Eq(entities)).215 Return([]models.Entity{&entityStub{id: 3}, &entityStub{id: 4}},216 errors.New("flushing failed")),217 mockFlusher.EXPECT().Flush(ctx, gomock.Eq(entities[2:])),218 )219 saver.Init(ctx)220 for i := 0; i < len(entities); i++ {221 saver.Save(entities[i])222 }223 alarmer.alarm()224 })225 })226 When("Flush has failed on close", func() {227 It("should handle an error", func() {228 entities := []models.Entity{229 &entityStub{id: 1},230 &entityStub{id: 2},231 &entityStub{id: 3},232 &entityStub{id: 4},233 }234 saver, _ := saver.New(len(entities), saver.DropAll, alarmer, mockFlusher)235 ctx, cancel := context.WithCancel(context.Background())236 defer saver.WaitClosed()237 defer cancel()238 mockFlusher.EXPECT().Flush(ctx, gomock.Eq(entities)).239 Return(entities, errors.New("flushing failed"))240 saver.Init(ctx)241 for i := 0; i < len(entities); i++ {242 saver.Save(entities[i])243 }244 })245 })246 })247})248type alarmerStub struct {249 alarms chan struct{}250}251func (a *alarmerStub) Alarm() <-chan struct{} {252 return a.alarms253}254func (a *alarmerStub) alarm() {255 a.alarms <- struct{}{}256}257type flusherStub struct {258}259func (f *flusherStub) Flush(ctx context.Context, entities []models.Entity) ([]models.Entity, error) {260 return nil, nil261}262type entityStub struct {263 id uint64264}265func (d *entityStub) ObjectId() uint64 {266 return d.id267}...

Full Screen

Full Screen

install_test.go

Source:install_test.go Github

copy

Full Screen

1package install2import (3 "errors"4 "fmt"5 "io"6 "testing"7 "github.com/golang/mock/gomock"8 fsys "github.com/spoke-d/clui/autocomplete/fsys"9)10func TestNew(t *testing.T) {11 t.Parallel()12 t.Run("binary path", func(t *testing.T) {13 ctrl := gomock.NewController(t)14 defer ctrl.Finish()15 exec := NewMockExecutable(ctrl)16 exec.EXPECT().BinaryPath().Return("", errors.New("fail"))17 _, err := New(OptionExecutable(exec))18 if expected, actual := "fail", err.Error(); expected != actual {19 t.Errorf("expected: %v, actual: %v, err: %v", expected, actual, err)20 }21 })22}23func TestInstall(t *testing.T) {24 t.Parallel()25 t.Run("install", func(t *testing.T) {26 ctrl := gomock.NewController(t)27 defer ctrl.Finish()28 exec := NewMockExecutable(ctrl)29 exec.EXPECT().BinaryPath().Return("/home", nil)30 existingLine := "complete -C /home yyy"31 newLine := "complete -C /home xxx"32 file := NewMockFile(ctrl)33 fs := NewMockFileSystem(ctrl)34 // FileContains35 gomock.InOrder(36 fs.EXPECT().Open(".profile").Return(file, nil),37 file.EXPECT().Read(gomock.Any()).Return(len(existingLine), io.EOF).Do(func(b []byte) {38 for i := 0; i < len(existingLine); i++ {39 b[i] = existingLine[i]40 }41 }),42 file.EXPECT().Close(),43 )44 // AppendToFile45 gomock.InOrder(46 fs.EXPECT().OpenFile(".profile", gomock.Any(), gomock.Any()).Return(file, nil),47 file.EXPECT().Write([]byte(fmt.Sprintf("\n%s\n", newLine))).Return(0, nil),48 file.EXPECT().Close(),49 )50 in, err := New(OptionExecutable(exec), OptionShell(StubShell(fs)))51 if err != nil {52 t.Fail()53 }54 err = in.Install("xxx")55 if expected, actual := true, err == nil; expected != actual {56 t.Errorf("expected: %v, actual: %v, err: %v", expected, actual, err)57 }58 })59 t.Run("install fails already exists", func(t *testing.T) {60 ctrl := gomock.NewController(t)61 defer ctrl.Finish()62 exec := NewMockExecutable(ctrl)63 exec.EXPECT().BinaryPath().Return("/home", nil)64 existingLine := "complete -C /home xxx"65 file := NewMockFile(ctrl)66 fs := NewMockFileSystem(ctrl)67 // FileContains68 gomock.InOrder(69 fs.EXPECT().Open(".profile").Return(file, nil),70 file.EXPECT().Read(gomock.Any()).Return(len(existingLine), io.EOF).Do(func(b []byte) {71 for i := 0; i < len(existingLine); i++ {72 b[i] = existingLine[i]73 }74 }),75 file.EXPECT().Close(),76 )77 in, err := New(OptionExecutable(exec), OptionShell(StubShell(fs)))78 if err != nil {79 t.Fail()80 }81 err = in.Install("xxx")82 if expected, actual := `file already contains line: "complete -C /home xxx"`, err.Error(); expected != actual {83 t.Errorf("expected: %v, actual: %v, err: %v", expected, actual, err)84 }85 })86 t.Run("install fails appending file", func(t *testing.T) {87 ctrl := gomock.NewController(t)88 defer ctrl.Finish()89 exec := NewMockExecutable(ctrl)90 exec.EXPECT().BinaryPath().Return("/home", nil)91 existingLine := "complete -C /home yyy"92 file := NewMockFile(ctrl)93 fs := NewMockFileSystem(ctrl)94 // FileContains95 gomock.InOrder(96 fs.EXPECT().Open(".profile").Return(file, nil),97 file.EXPECT().Read(gomock.Any()).Return(len(existingLine), io.EOF).Do(func(b []byte) {98 for i := 0; i < len(existingLine); i++ {99 b[i] = existingLine[i]100 }101 }),102 file.EXPECT().Close(),103 )104 // AppendToFile105 gomock.InOrder(106 fs.EXPECT().OpenFile(".profile", gomock.Any(), gomock.Any()).Return(file, errors.New("fail")),107 )108 in, err := New(OptionExecutable(exec), OptionShell(StubShell(fs)))109 if err != nil {110 t.Fail()111 }112 err = in.Install("xxx")113 if expected, actual := "fail", err.Error(); expected != actual {114 t.Errorf("expected: %v, actual: %v, err: %v", expected, actual, err)115 }116 })117}118func TestUninstall(t *testing.T) {119 t.Parallel()120 t.Run("uninstall", func(t *testing.T) {121 ctrl := gomock.NewController(t)122 defer ctrl.Finish()123 exec := NewMockExecutable(ctrl)124 exec.EXPECT().BinaryPath().Return("/home", nil)125 existingLine := "complete -C /home xxx"126 file := NewMockFile(ctrl)127 backupFile := NewMockFile(ctrl)128 tmpFile := NewMockFile(ctrl)129 fs := NewMockFileSystem(ctrl)130 // FileContains131 gomock.InOrder(132 fs.EXPECT().Open(".profile").Return(file, nil),133 file.EXPECT().Read(gomock.Any()).Return(len(existingLine), io.EOF).Do(func(b []byte) {134 for i := 0; i < len(existingLine); i++ {135 b[i] = existingLine[i]136 }137 }),138 file.EXPECT().Close(),139 )140 // CopyFile141 gomock.InOrder(142 fs.EXPECT().Open(".profile").Return(file, nil),143 fs.EXPECT().Create(".profile.bck").Return(backupFile, nil),144 file.EXPECT().Read(gomock.Any()).Return(len(existingLine), io.EOF).Do(func(b []byte) {145 for i := 0; i < len(existingLine); i++ {146 b[i] = existingLine[i]147 }148 }),149 backupFile.EXPECT().Write([]byte(fmt.Sprintf("%s", existingLine))).Return(len(existingLine), nil),150 backupFile.EXPECT().Close(),151 file.EXPECT().Close(),152 )153 // RemoveContentFromTmpFile154 gomock.InOrder(155 fs.EXPECT().Open(".profile").Return(file, nil),156 file.EXPECT().Read(gomock.Any()).Return(len(existingLine), io.EOF).Do(func(b []byte) {157 for i := 0; i < len(existingLine); i++ {158 b[i] = existingLine[i]159 }160 }),161 file.EXPECT().Close().Return(nil),162 )163 // CopyFile164 gomock.InOrder(165 fs.EXPECT().Open(gomock.Any()).Return(tmpFile, nil),166 fs.EXPECT().Create(".profile").Return(file, nil),167 tmpFile.EXPECT().Read(gomock.Any()).Return(len(existingLine), io.EOF).Do(func(b []byte) {168 for i := 0; i < len(existingLine); i++ {169 b[i] = existingLine[i]170 }171 }),172 file.EXPECT().Write([]byte(fmt.Sprintf("%s", existingLine))).Return(len(existingLine), nil),173 file.EXPECT().Close(),174 tmpFile.EXPECT().Close(),175 )176 // Remove177 gomock.InOrder(178 fs.EXPECT().Remove(".profile.bck").Return(nil),179 )180 in, err := New(OptionExecutable(exec), OptionShell(StubShell(fs)))181 if err != nil {182 t.Fail()183 }184 err = in.Uninstall("xxx")185 if expected, actual := true, err == nil; expected != actual {186 t.Errorf("expected: %v, actual: %v, err: %v", expected, actual, err)187 }188 })189}190func StubShell(fsys fsys.FileSystem) *Shell {191 return &Shell{192 fsys: fsys,193 files: []string{".profile"},194 cmdFn: func(cmd, bin string) string {195 return fmt.Sprintf("complete -C %s %s", bin, cmd)196 },197 }198}...

Full Screen

Full Screen

Len

Using AI Code Generation

copy

Full Screen

1import (2func TestLen(t *testing.T) {3 ctrl := gomock.NewController(t)4 defer ctrl.Finish()5 mock := NewMockMyInterface(ctrl)6 mock.EXPECT().Len().Return(42)7 fmt.Println(mock.Len())8}9import (10func TestLen(t *testing.T) {11 ctrl := gomock.NewController(t)12 defer ctrl.Finish()13 mock := NewMockMyInterface(ctrl)14 mock.EXPECT().Len().Return(42)15 fmt.Println(mock.Len())16}17import (18func TestLen(t *testing.T) {19 ctrl := gomock.NewController(t)20 defer ctrl.Finish()21 mock := NewMockMyInterface(ctrl)22 mock.EXPECT().Len().Return(42)23 fmt.Println(mock.Len())24}25import (26func TestLen(t *testing.T) {27 ctrl := gomock.NewController(t)28 defer ctrl.Finish()29 mock := NewMockMyInterface(ctrl)30 mock.EXPECT().Len().Return(42)31 fmt.Println(mock.Len())32}33import (34func TestLen(t *testing.T) {35 ctrl := gomock.NewController(t)36 defer ctrl.Finish()37 mock := NewMockMyInterface(ctrl)38 mock.EXPECT().Len().Return(42)39 fmt.Println(mock.Len())40}41import (

Full Screen

Full Screen

Len

Using AI Code Generation

copy

Full Screen

1func TestLen(t *testing.T) {2 mockCtrl := gomock.NewController(t)3 defer mockCtrl.Finish()4 mock := NewMockLen(mockCtrl)5 mock.EXPECT().Len().Return(10)6 if mock.Len() != 10 {7 t.Errorf("Len() = %d; want 10", mock.Len())8 }9}10--- PASS: TestLen (0.00s)11func TestLenAndAdd(t *testing.T) {12 mockCtrl := gomock.NewController(t)13 defer mockCtrl.Finish()14 mock := NewMockLen(mockCtrl)15 mock.EXPECT().Len().Return(10)16 mock.EXPECT().Add(1)17 if mock.Len() != 10 {18 t.Errorf("Len() = %d; want 10", mock.Len())19 }20 mock.Add(1)21}22--- PASS: TestLenAndAdd (0.00s)

Full Screen

Full Screen

Len

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctrl := gomock.NewController(nil)4 defer ctrl.Finish()5 mock := mocks.NewMockLen(ctrl)6 mock.EXPECT().Len().Return(10)7 fmt.Println(mock.Len())8}9import (10func main() {11 ctrl := gomock.NewController(nil)12 defer ctrl.Finish()13 mock := mocks.NewMockLen(ctrl)14 mock.EXPECT().Len().Return(10)15 fmt.Println(mock.Len())16}

Full Screen

Full Screen

Len

Using AI Code Generation

copy

Full Screen

1func TestLen(t *testing.T) {2 mock := gomock.NewController(t)3 defer mock.Finish()4 mock1 := mockgomock.NewMockGomock(mock)5 mock1.EXPECT().Len().Return(5)6 ret := len(mock1)7 if ret != 5 {8 t.Errorf("Expected 5, got %d", ret)9 }10}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful