How to use Baz method of source Package

Best Mock code snippet using source.Baz

event_test.go

Source:event_test.go Github

copy

Full Screen

1/*2Copyright 2014 The Kubernetes Authors.3Licensed under the Apache License, Version 2.0 (the "License");4you may not use this file except in compliance with the License.5You may obtain a copy of the License at6 http://www.apache.org/licenses/LICENSE-2.07Unless required by applicable law or agreed to in writing, software8distributed under the License is distributed on an "AS IS" BASIS,9WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.10See the License for the specific language governing permissions and11limitations under the License.12*/13package record14import (15 "encoding/json"16 "fmt"17 "net/http"18 "strconv"19 "testing"20 "time"21 v1 "k8s.io/api/core/v1"22 "k8s.io/apimachinery/pkg/api/errors"23 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"24 k8sruntime "k8s.io/apimachinery/pkg/runtime"25 "k8s.io/apimachinery/pkg/util/clock"26 "k8s.io/apimachinery/pkg/util/strategicpatch"27 "k8s.io/client-go/kubernetes/scheme"28 restclient "k8s.io/client-go/rest"29 ref "k8s.io/client-go/tools/reference"30)31type testEventSink struct {32 OnCreate func(e *v1.Event) (*v1.Event, error)33 OnUpdate func(e *v1.Event) (*v1.Event, error)34 OnPatch func(e *v1.Event, p []byte) (*v1.Event, error)35}36// CreateEvent records the event for testing.37func (t *testEventSink) Create(e *v1.Event) (*v1.Event, error) {38 if t.OnCreate != nil {39 return t.OnCreate(e)40 }41 return e, nil42}43// UpdateEvent records the event for testing.44func (t *testEventSink) Update(e *v1.Event) (*v1.Event, error) {45 if t.OnUpdate != nil {46 return t.OnUpdate(e)47 }48 return e, nil49}50// PatchEvent records the event for testing.51func (t *testEventSink) Patch(e *v1.Event, p []byte) (*v1.Event, error) {52 if t.OnPatch != nil {53 return t.OnPatch(e, p)54 }55 return e, nil56}57type OnCreateFunc func(*v1.Event) (*v1.Event, error)58func OnCreateFactory(testCache map[string]*v1.Event, createEvent chan<- *v1.Event) OnCreateFunc {59 return func(event *v1.Event) (*v1.Event, error) {60 testCache[getEventKey(event)] = event61 createEvent <- event62 return event, nil63 }64}65type OnPatchFunc func(*v1.Event, []byte) (*v1.Event, error)66func OnPatchFactory(testCache map[string]*v1.Event, patchEvent chan<- *v1.Event) OnPatchFunc {67 return func(event *v1.Event, patch []byte) (*v1.Event, error) {68 cachedEvent, found := testCache[getEventKey(event)]69 if !found {70 return nil, fmt.Errorf("unexpected error: couldn't find Event in testCache.")71 }72 originalData, err := json.Marshal(cachedEvent)73 if err != nil {74 return nil, fmt.Errorf("unexpected error: %v", err)75 }76 patched, err := strategicpatch.StrategicMergePatch(originalData, patch, event)77 if err != nil {78 return nil, fmt.Errorf("unexpected error: %v", err)79 }80 patchedObj := &v1.Event{}81 err = json.Unmarshal(patched, patchedObj)82 if err != nil {83 return nil, fmt.Errorf("unexpected error: %v", err)84 }85 patchEvent <- patchedObj86 return patchedObj, nil87 }88}89func TestEventf(t *testing.T) {90 testPod := &v1.Pod{91 ObjectMeta: metav1.ObjectMeta{92 SelfLink: "/api/v1/namespaces/baz/pods/foo",93 Name: "foo",94 Namespace: "baz",95 UID: "bar",96 },97 }98 testPod2 := &v1.Pod{99 ObjectMeta: metav1.ObjectMeta{100 SelfLink: "/api/v1/namespaces/baz/pods/foo",101 Name: "foo",102 Namespace: "baz",103 UID: "differentUid",104 },105 }106 testRef, err := ref.GetPartialReference(scheme.Scheme, testPod, "spec.containers[2]")107 if err != nil {108 t.Fatal(err)109 }110 testRef2, err := ref.GetPartialReference(scheme.Scheme, testPod2, "spec.containers[3]")111 if err != nil {112 t.Fatal(err)113 }114 table := []struct {115 obj k8sruntime.Object116 eventtype string117 reason string118 messageFmt string119 elements []interface{}120 expect *v1.Event121 expectLog string122 expectUpdate bool123 }{124 {125 obj: testRef,126 eventtype: v1.EventTypeNormal,127 reason: "Started",128 messageFmt: "some verbose message: %v",129 elements: []interface{}{1},130 expect: &v1.Event{131 ObjectMeta: metav1.ObjectMeta{132 Name: "foo",133 Namespace: "baz",134 },135 InvolvedObject: v1.ObjectReference{136 Kind: "Pod",137 Name: "foo",138 Namespace: "baz",139 UID: "bar",140 APIVersion: "v1",141 FieldPath: "spec.containers[2]",142 },143 Reason: "Started",144 Message: "some verbose message: 1",145 Source: v1.EventSource{Component: "eventTest"},146 Count: 1,147 Type: v1.EventTypeNormal,148 },149 expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"v1", ResourceVersion:"", FieldPath:"spec.containers[2]"}): type: 'Normal' reason: 'Started' some verbose message: 1`,150 expectUpdate: false,151 },152 {153 obj: testPod,154 eventtype: v1.EventTypeNormal,155 reason: "Killed",156 messageFmt: "some other verbose message: %v",157 elements: []interface{}{1},158 expect: &v1.Event{159 ObjectMeta: metav1.ObjectMeta{160 Name: "foo",161 Namespace: "baz",162 },163 InvolvedObject: v1.ObjectReference{164 Kind: "Pod",165 Name: "foo",166 Namespace: "baz",167 UID: "bar",168 APIVersion: "v1",169 },170 Reason: "Killed",171 Message: "some other verbose message: 1",172 Source: v1.EventSource{Component: "eventTest"},173 Count: 1,174 Type: v1.EventTypeNormal,175 },176 expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"v1", ResourceVersion:"", FieldPath:""}): type: 'Normal' reason: 'Killed' some other verbose message: 1`,177 expectUpdate: false,178 },179 {180 obj: testRef,181 eventtype: v1.EventTypeNormal,182 reason: "Started",183 messageFmt: "some verbose message: %v",184 elements: []interface{}{1},185 expect: &v1.Event{186 ObjectMeta: metav1.ObjectMeta{187 Name: "foo",188 Namespace: "baz",189 },190 InvolvedObject: v1.ObjectReference{191 Kind: "Pod",192 Name: "foo",193 Namespace: "baz",194 UID: "bar",195 APIVersion: "v1",196 FieldPath: "spec.containers[2]",197 },198 Reason: "Started",199 Message: "some verbose message: 1",200 Source: v1.EventSource{Component: "eventTest"},201 Count: 2,202 Type: v1.EventTypeNormal,203 },204 expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"v1", ResourceVersion:"", FieldPath:"spec.containers[2]"}): type: 'Normal' reason: 'Started' some verbose message: 1`,205 expectUpdate: true,206 },207 {208 obj: testRef2,209 eventtype: v1.EventTypeNormal,210 reason: "Started",211 messageFmt: "some verbose message: %v",212 elements: []interface{}{1},213 expect: &v1.Event{214 ObjectMeta: metav1.ObjectMeta{215 Name: "foo",216 Namespace: "baz",217 },218 InvolvedObject: v1.ObjectReference{219 Kind: "Pod",220 Name: "foo",221 Namespace: "baz",222 UID: "differentUid",223 APIVersion: "v1",224 FieldPath: "spec.containers[3]",225 },226 Reason: "Started",227 Message: "some verbose message: 1",228 Source: v1.EventSource{Component: "eventTest"},229 Count: 1,230 Type: v1.EventTypeNormal,231 },232 expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"differentUid", APIVersion:"v1", ResourceVersion:"", FieldPath:"spec.containers[3]"}): type: 'Normal' reason: 'Started' some verbose message: 1`,233 expectUpdate: false,234 },235 {236 obj: testRef,237 eventtype: v1.EventTypeNormal,238 reason: "Started",239 messageFmt: "some verbose message: %v",240 elements: []interface{}{1},241 expect: &v1.Event{242 ObjectMeta: metav1.ObjectMeta{243 Name: "foo",244 Namespace: "baz",245 },246 InvolvedObject: v1.ObjectReference{247 Kind: "Pod",248 Name: "foo",249 Namespace: "baz",250 UID: "bar",251 APIVersion: "v1",252 FieldPath: "spec.containers[2]",253 },254 Reason: "Started",255 Message: "some verbose message: 1",256 Source: v1.EventSource{Component: "eventTest"},257 Count: 3,258 Type: v1.EventTypeNormal,259 },260 expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"v1", ResourceVersion:"", FieldPath:"spec.containers[2]"}): type: 'Normal' reason: 'Started' some verbose message: 1`,261 expectUpdate: true,262 },263 {264 obj: testRef2,265 eventtype: v1.EventTypeNormal,266 reason: "Stopped",267 messageFmt: "some verbose message: %v",268 elements: []interface{}{1},269 expect: &v1.Event{270 ObjectMeta: metav1.ObjectMeta{271 Name: "foo",272 Namespace: "baz",273 },274 InvolvedObject: v1.ObjectReference{275 Kind: "Pod",276 Name: "foo",277 Namespace: "baz",278 UID: "differentUid",279 APIVersion: "v1",280 FieldPath: "spec.containers[3]",281 },282 Reason: "Stopped",283 Message: "some verbose message: 1",284 Source: v1.EventSource{Component: "eventTest"},285 Count: 1,286 Type: v1.EventTypeNormal,287 },288 expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"differentUid", APIVersion:"v1", ResourceVersion:"", FieldPath:"spec.containers[3]"}): type: 'Normal' reason: 'Stopped' some verbose message: 1`,289 expectUpdate: false,290 },291 {292 obj: testRef2,293 eventtype: v1.EventTypeNormal,294 reason: "Stopped",295 messageFmt: "some verbose message: %v",296 elements: []interface{}{1},297 expect: &v1.Event{298 ObjectMeta: metav1.ObjectMeta{299 Name: "foo",300 Namespace: "baz",301 },302 InvolvedObject: v1.ObjectReference{303 Kind: "Pod",304 Name: "foo",305 Namespace: "baz",306 UID: "differentUid",307 APIVersion: "v1",308 FieldPath: "spec.containers[3]",309 },310 Reason: "Stopped",311 Message: "some verbose message: 1",312 Source: v1.EventSource{Component: "eventTest"},313 Count: 2,314 Type: v1.EventTypeNormal,315 },316 expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"differentUid", APIVersion:"v1", ResourceVersion:"", FieldPath:"spec.containers[3]"}): type: 'Normal' reason: 'Stopped' some verbose message: 1`,317 expectUpdate: true,318 },319 }320 testCache := map[string]*v1.Event{}321 logCalled := make(chan struct{})322 createEvent := make(chan *v1.Event)323 updateEvent := make(chan *v1.Event)324 patchEvent := make(chan *v1.Event)325 testEvents := testEventSink{326 OnCreate: OnCreateFactory(testCache, createEvent),327 OnUpdate: func(event *v1.Event) (*v1.Event, error) {328 updateEvent <- event329 return event, nil330 },331 OnPatch: OnPatchFactory(testCache, patchEvent),332 }333 eventBroadcaster := NewBroadcasterForTests(0)334 sinkWatcher := eventBroadcaster.StartRecordingToSink(&testEvents)335 clock := clock.NewFakeClock(time.Now())336 recorder := recorderWithFakeClock(v1.EventSource{Component: "eventTest"}, eventBroadcaster, clock)337 for index, item := range table {338 clock.Step(1 * time.Second)339 logWatcher := eventBroadcaster.StartLogging(func(formatter string, args ...interface{}) {340 if e, a := item.expectLog, fmt.Sprintf(formatter, args...); e != a {341 t.Errorf("Expected '%v', got '%v'", e, a)342 }343 logCalled <- struct{}{}344 })345 recorder.Eventf(item.obj, item.eventtype, item.reason, item.messageFmt, item.elements...)346 <-logCalled347 // validate event348 if item.expectUpdate {349 actualEvent := <-patchEvent350 validateEvent(strconv.Itoa(index), actualEvent, item.expect, t)351 } else {352 actualEvent := <-createEvent353 validateEvent(strconv.Itoa(index), actualEvent, item.expect, t)354 }355 logWatcher.Stop()356 }357 sinkWatcher.Stop()358}359func recorderWithFakeClock(eventSource v1.EventSource, eventBroadcaster EventBroadcaster, clock clock.Clock) EventRecorder {360 return &recorderImpl{scheme.Scheme, eventSource, eventBroadcaster.(*eventBroadcasterImpl).Broadcaster, clock}361}362func TestWriteEventError(t *testing.T) {363 type entry struct {364 timesToSendError int365 attemptsWanted int366 err error367 }368 table := map[string]*entry{369 "giveUp1": {370 timesToSendError: 1000,371 attemptsWanted: 1,372 err: &restclient.RequestConstructionError{},373 },374 "giveUp2": {375 timesToSendError: 1000,376 attemptsWanted: 1,377 err: &errors.StatusError{},378 },379 "retry1": {380 timesToSendError: 1000,381 attemptsWanted: 12,382 err: &errors.UnexpectedObjectError{},383 },384 "retry2": {385 timesToSendError: 1000,386 attemptsWanted: 12,387 err: fmt.Errorf("A weird error"),388 },389 "succeedEventually": {390 timesToSendError: 2,391 attemptsWanted: 2,392 err: fmt.Errorf("A weird error"),393 },394 }395 clock := clock.IntervalClock{Time: time.Now(), Duration: time.Second}396 eventCorrelator := NewEventCorrelator(&clock)397 for caseName, ent := range table {398 attempts := 0399 sink := &testEventSink{400 OnCreate: func(event *v1.Event) (*v1.Event, error) {401 attempts++402 if attempts < ent.timesToSendError {403 return nil, ent.err404 }405 return event, nil406 },407 }408 ev := &v1.Event{}409 recordToSink(sink, ev, eventCorrelator, 0)410 if attempts != ent.attemptsWanted {411 t.Errorf("case %v: wanted %d, got %d attempts", caseName, ent.attemptsWanted, attempts)412 }413 }414}415func TestUpdateExpiredEvent(t *testing.T) {416 clock := clock.IntervalClock{Time: time.Now(), Duration: time.Second}417 eventCorrelator := NewEventCorrelator(&clock)418 var createdEvent *v1.Event419 sink := &testEventSink{420 OnPatch: func(*v1.Event, []byte) (*v1.Event, error) {421 return nil, &errors.StatusError{422 ErrStatus: metav1.Status{423 Code: http.StatusNotFound,424 Reason: metav1.StatusReasonNotFound,425 }}426 },427 OnCreate: func(event *v1.Event) (*v1.Event, error) {428 createdEvent = event429 return event, nil430 },431 }432 ev := &v1.Event{}433 ev.ResourceVersion = "updated-resource-version"434 ev.Count = 2435 recordToSink(sink, ev, eventCorrelator, 0)436 if createdEvent == nil {437 t.Error("Event did not get created after patch failed")438 return439 }440 if createdEvent.ResourceVersion != "" {441 t.Errorf("Event did not have its resource version cleared, was %s", createdEvent.ResourceVersion)442 }443}444func TestLotsOfEvents(t *testing.T) {445 recorderCalled := make(chan struct{})446 loggerCalled := make(chan struct{})447 // Fail each event a few times to ensure there's some load on the tested code.448 var counts [1000]int449 testEvents := testEventSink{450 OnCreate: func(event *v1.Event) (*v1.Event, error) {451 num, err := strconv.Atoi(event.Message)452 if err != nil {453 t.Error(err)454 return event, nil455 }456 counts[num]++457 if counts[num] < 5 {458 return nil, fmt.Errorf("fake error")459 }460 recorderCalled <- struct{}{}461 return event, nil462 },463 }464 eventBroadcaster := NewBroadcasterForTests(0)465 sinkWatcher := eventBroadcaster.StartRecordingToSink(&testEvents)466 logWatcher := eventBroadcaster.StartLogging(func(formatter string, args ...interface{}) {467 loggerCalled <- struct{}{}468 })469 recorder := eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: "eventTest"})470 for i := 0; i < maxQueuedEvents; i++ {471 // we want a unique object to stop spam filtering472 ref := &v1.ObjectReference{473 Kind: "Pod",474 Name: fmt.Sprintf("foo-%v", i),475 Namespace: "baz",476 UID: "bar",477 APIVersion: "version",478 }479 // we need to vary the reason to prevent aggregation480 go recorder.Eventf(ref, v1.EventTypeNormal, "Reason-"+strconv.Itoa(i), strconv.Itoa(i))481 }482 // Make sure no events were dropped by either of the listeners.483 for i := 0; i < maxQueuedEvents; i++ {484 <-recorderCalled485 <-loggerCalled486 }487 // Make sure that every event was attempted 5 times488 for i := 0; i < maxQueuedEvents; i++ {489 if counts[i] < 5 {490 t.Errorf("Only attempted to record event '%d' %d times.", i, counts[i])491 }492 }493 sinkWatcher.Stop()494 logWatcher.Stop()495}496func TestEventfNoNamespace(t *testing.T) {497 testPod := &v1.Pod{498 ObjectMeta: metav1.ObjectMeta{499 SelfLink: "/api/v1/namespaces/default/pods/foo",500 Name: "foo",501 UID: "bar",502 },503 }504 testRef, err := ref.GetPartialReference(scheme.Scheme, testPod, "spec.containers[2]")505 if err != nil {506 t.Fatal(err)507 }508 table := []struct {509 obj k8sruntime.Object510 eventtype string511 reason string512 messageFmt string513 elements []interface{}514 expect *v1.Event515 expectLog string516 expectUpdate bool517 }{518 {519 obj: testRef,520 eventtype: v1.EventTypeNormal,521 reason: "Started",522 messageFmt: "some verbose message: %v",523 elements: []interface{}{1},524 expect: &v1.Event{525 ObjectMeta: metav1.ObjectMeta{526 Name: "foo",527 Namespace: "default",528 },529 InvolvedObject: v1.ObjectReference{530 Kind: "Pod",531 Name: "foo",532 Namespace: "",533 UID: "bar",534 APIVersion: "v1",535 FieldPath: "spec.containers[2]",536 },537 Reason: "Started",538 Message: "some verbose message: 1",539 Source: v1.EventSource{Component: "eventTest"},540 Count: 1,541 Type: v1.EventTypeNormal,542 },543 expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"", Name:"foo", UID:"bar", APIVersion:"v1", ResourceVersion:"", FieldPath:"spec.containers[2]"}): type: 'Normal' reason: 'Started' some verbose message: 1`,544 expectUpdate: false,545 },546 }547 testCache := map[string]*v1.Event{}548 logCalled := make(chan struct{})549 createEvent := make(chan *v1.Event)550 updateEvent := make(chan *v1.Event)551 patchEvent := make(chan *v1.Event)552 testEvents := testEventSink{553 OnCreate: OnCreateFactory(testCache, createEvent),554 OnUpdate: func(event *v1.Event) (*v1.Event, error) {555 updateEvent <- event556 return event, nil557 },558 OnPatch: OnPatchFactory(testCache, patchEvent),559 }560 eventBroadcaster := NewBroadcasterForTests(0)561 sinkWatcher := eventBroadcaster.StartRecordingToSink(&testEvents)562 clock := clock.NewFakeClock(time.Now())563 recorder := recorderWithFakeClock(v1.EventSource{Component: "eventTest"}, eventBroadcaster, clock)564 for index, item := range table {565 clock.Step(1 * time.Second)566 logWatcher := eventBroadcaster.StartLogging(func(formatter string, args ...interface{}) {567 if e, a := item.expectLog, fmt.Sprintf(formatter, args...); e != a {568 t.Errorf("Expected '%v', got '%v'", e, a)569 }570 logCalled <- struct{}{}571 })572 recorder.Eventf(item.obj, item.eventtype, item.reason, item.messageFmt, item.elements...)573 <-logCalled574 // validate event575 if item.expectUpdate {576 actualEvent := <-patchEvent577 validateEvent(strconv.Itoa(index), actualEvent, item.expect, t)578 } else {579 actualEvent := <-createEvent580 validateEvent(strconv.Itoa(index), actualEvent, item.expect, t)581 }582 logWatcher.Stop()583 }584 sinkWatcher.Stop()585}586func TestMultiSinkCache(t *testing.T) {587 testPod := &v1.Pod{588 ObjectMeta: metav1.ObjectMeta{589 SelfLink: "/api/v1/namespaces/baz/pods/foo",590 Name: "foo",591 Namespace: "baz",592 UID: "bar",593 },594 }595 testPod2 := &v1.Pod{596 ObjectMeta: metav1.ObjectMeta{597 SelfLink: "/api/v1/namespaces/baz/pods/foo",598 Name: "foo",599 Namespace: "baz",600 UID: "differentUid",601 },602 }603 testRef, err := ref.GetPartialReference(scheme.Scheme, testPod, "spec.containers[2]")604 if err != nil {605 t.Fatal(err)606 }607 testRef2, err := ref.GetPartialReference(scheme.Scheme, testPod2, "spec.containers[3]")608 if err != nil {609 t.Fatal(err)610 }611 table := []struct {612 obj k8sruntime.Object613 eventtype string614 reason string615 messageFmt string616 elements []interface{}617 expect *v1.Event618 expectLog string619 expectUpdate bool620 }{621 {622 obj: testRef,623 eventtype: v1.EventTypeNormal,624 reason: "Started",625 messageFmt: "some verbose message: %v",626 elements: []interface{}{1},627 expect: &v1.Event{628 ObjectMeta: metav1.ObjectMeta{629 Name: "foo",630 Namespace: "baz",631 },632 InvolvedObject: v1.ObjectReference{633 Kind: "Pod",634 Name: "foo",635 Namespace: "baz",636 UID: "bar",637 APIVersion: "v1",638 FieldPath: "spec.containers[2]",639 },640 Reason: "Started",641 Message: "some verbose message: 1",642 Source: v1.EventSource{Component: "eventTest"},643 Count: 1,644 Type: v1.EventTypeNormal,645 },646 expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"v1", ResourceVersion:"", FieldPath:"spec.containers[2]"}): type: 'Normal' reason: 'Started' some verbose message: 1`,647 expectUpdate: false,648 },649 {650 obj: testPod,651 eventtype: v1.EventTypeNormal,652 reason: "Killed",653 messageFmt: "some other verbose message: %v",654 elements: []interface{}{1},655 expect: &v1.Event{656 ObjectMeta: metav1.ObjectMeta{657 Name: "foo",658 Namespace: "baz",659 },660 InvolvedObject: v1.ObjectReference{661 Kind: "Pod",662 Name: "foo",663 Namespace: "baz",664 UID: "bar",665 APIVersion: "v1",666 },667 Reason: "Killed",668 Message: "some other verbose message: 1",669 Source: v1.EventSource{Component: "eventTest"},670 Count: 1,671 Type: v1.EventTypeNormal,672 },673 expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"v1", ResourceVersion:"", FieldPath:""}): type: 'Normal' reason: 'Killed' some other verbose message: 1`,674 expectUpdate: false,675 },676 {677 obj: testRef,678 eventtype: v1.EventTypeNormal,679 reason: "Started",680 messageFmt: "some verbose message: %v",681 elements: []interface{}{1},682 expect: &v1.Event{683 ObjectMeta: metav1.ObjectMeta{684 Name: "foo",685 Namespace: "baz",686 },687 InvolvedObject: v1.ObjectReference{688 Kind: "Pod",689 Name: "foo",690 Namespace: "baz",691 UID: "bar",692 APIVersion: "v1",693 FieldPath: "spec.containers[2]",694 },695 Reason: "Started",696 Message: "some verbose message: 1",697 Source: v1.EventSource{Component: "eventTest"},698 Count: 2,699 Type: v1.EventTypeNormal,700 },701 expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"v1", ResourceVersion:"", FieldPath:"spec.containers[2]"}): type: 'Normal' reason: 'Started' some verbose message: 1`,702 expectUpdate: true,703 },704 {705 obj: testRef2,706 eventtype: v1.EventTypeNormal,707 reason: "Started",708 messageFmt: "some verbose message: %v",709 elements: []interface{}{1},710 expect: &v1.Event{711 ObjectMeta: metav1.ObjectMeta{712 Name: "foo",713 Namespace: "baz",714 },715 InvolvedObject: v1.ObjectReference{716 Kind: "Pod",717 Name: "foo",718 Namespace: "baz",719 UID: "differentUid",720 APIVersion: "v1",721 FieldPath: "spec.containers[3]",722 },723 Reason: "Started",724 Message: "some verbose message: 1",725 Source: v1.EventSource{Component: "eventTest"},726 Count: 1,727 Type: v1.EventTypeNormal,728 },729 expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"differentUid", APIVersion:"v1", ResourceVersion:"", FieldPath:"spec.containers[3]"}): type: 'Normal' reason: 'Started' some verbose message: 1`,730 expectUpdate: false,731 },732 {733 obj: testRef,734 eventtype: v1.EventTypeNormal,735 reason: "Started",736 messageFmt: "some verbose message: %v",737 elements: []interface{}{1},738 expect: &v1.Event{739 ObjectMeta: metav1.ObjectMeta{740 Name: "foo",741 Namespace: "baz",742 },743 InvolvedObject: v1.ObjectReference{744 Kind: "Pod",745 Name: "foo",746 Namespace: "baz",747 UID: "bar",748 APIVersion: "v1",749 FieldPath: "spec.containers[2]",750 },751 Reason: "Started",752 Message: "some verbose message: 1",753 Source: v1.EventSource{Component: "eventTest"},754 Count: 3,755 Type: v1.EventTypeNormal,756 },757 expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"v1", ResourceVersion:"", FieldPath:"spec.containers[2]"}): type: 'Normal' reason: 'Started' some verbose message: 1`,758 expectUpdate: true,759 },760 {761 obj: testRef2,762 eventtype: v1.EventTypeNormal,763 reason: "Stopped",764 messageFmt: "some verbose message: %v",765 elements: []interface{}{1},766 expect: &v1.Event{767 ObjectMeta: metav1.ObjectMeta{768 Name: "foo",769 Namespace: "baz",770 },771 InvolvedObject: v1.ObjectReference{772 Kind: "Pod",773 Name: "foo",774 Namespace: "baz",775 UID: "differentUid",776 APIVersion: "v1",777 FieldPath: "spec.containers[3]",778 },779 Reason: "Stopped",780 Message: "some verbose message: 1",781 Source: v1.EventSource{Component: "eventTest"},782 Count: 1,783 Type: v1.EventTypeNormal,784 },785 expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"differentUid", APIVersion:"v1", ResourceVersion:"", FieldPath:"spec.containers[3]"}): type: 'Normal' reason: 'Stopped' some verbose message: 1`,786 expectUpdate: false,787 },788 {789 obj: testRef2,790 eventtype: v1.EventTypeNormal,791 reason: "Stopped",792 messageFmt: "some verbose message: %v",793 elements: []interface{}{1},794 expect: &v1.Event{795 ObjectMeta: metav1.ObjectMeta{796 Name: "foo",797 Namespace: "baz",798 },799 InvolvedObject: v1.ObjectReference{800 Kind: "Pod",801 Name: "foo",802 Namespace: "baz",803 UID: "differentUid",804 APIVersion: "v1",805 FieldPath: "spec.containers[3]",806 },807 Reason: "Stopped",808 Message: "some verbose message: 1",809 Source: v1.EventSource{Component: "eventTest"},810 Count: 2,811 Type: v1.EventTypeNormal,812 },813 expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"differentUid", APIVersion:"v1", ResourceVersion:"", FieldPath:"spec.containers[3]"}): type: 'Normal' reason: 'Stopped' some verbose message: 1`,814 expectUpdate: true,815 },816 }817 testCache := map[string]*v1.Event{}818 createEvent := make(chan *v1.Event)819 updateEvent := make(chan *v1.Event)820 patchEvent := make(chan *v1.Event)821 testEvents := testEventSink{822 OnCreate: OnCreateFactory(testCache, createEvent),823 OnUpdate: func(event *v1.Event) (*v1.Event, error) {824 updateEvent <- event825 return event, nil826 },827 OnPatch: OnPatchFactory(testCache, patchEvent),828 }829 testCache2 := map[string]*v1.Event{}830 createEvent2 := make(chan *v1.Event)831 updateEvent2 := make(chan *v1.Event)832 patchEvent2 := make(chan *v1.Event)833 testEvents2 := testEventSink{834 OnCreate: OnCreateFactory(testCache2, createEvent2),835 OnUpdate: func(event *v1.Event) (*v1.Event, error) {836 updateEvent2 <- event837 return event, nil838 },839 OnPatch: OnPatchFactory(testCache2, patchEvent2),840 }841 eventBroadcaster := NewBroadcasterForTests(0)842 clock := clock.NewFakeClock(time.Now())843 recorder := recorderWithFakeClock(v1.EventSource{Component: "eventTest"}, eventBroadcaster, clock)844 sinkWatcher := eventBroadcaster.StartRecordingToSink(&testEvents)845 for index, item := range table {846 clock.Step(1 * time.Second)847 recorder.Eventf(item.obj, item.eventtype, item.reason, item.messageFmt, item.elements...)848 // validate event849 if item.expectUpdate {850 actualEvent := <-patchEvent851 validateEvent(strconv.Itoa(index), actualEvent, item.expect, t)852 } else {853 actualEvent := <-createEvent854 validateEvent(strconv.Itoa(index), actualEvent, item.expect, t)855 }856 }857 // Another StartRecordingToSink call should start to record events with new clean cache.858 sinkWatcher2 := eventBroadcaster.StartRecordingToSink(&testEvents2)859 for index, item := range table {860 clock.Step(1 * time.Second)861 recorder.Eventf(item.obj, item.eventtype, item.reason, item.messageFmt, item.elements...)862 // validate event863 if item.expectUpdate {864 actualEvent := <-patchEvent2865 validateEvent(strconv.Itoa(index), actualEvent, item.expect, t)866 } else {867 actualEvent := <-createEvent2868 validateEvent(strconv.Itoa(index), actualEvent, item.expect, t)869 }870 }871 sinkWatcher.Stop()872 sinkWatcher2.Stop()873}...

Full Screen

Full Screen

transformer_test.go

Source:transformer_test.go Github

copy

Full Screen

...22)23func TestTransformer_Basics(t *testing.T) {24 g := NewGomegaWithT(t)25 inputs := collection.NewSchemasBuilder().MustAdd(data.Foo).MustAdd(data.Bar).Build()26 outputs := collection.NewSchemasBuilder().MustAdd(data.Boo).MustAdd(data.Baz).Build()27 var started, stopped bool28 xform := event.NewFnTransform(29 inputs,30 outputs,31 func() { started = true },32 func() { stopped = true },33 func(e event.Event, h event.Handler) {},34 )35 g.Expect(xform.Inputs()).To(Equal(inputs))36 g.Expect(xform.Outputs()).To(Equal(outputs))37 g.Expect(started).To(BeFalse())38 g.Expect(stopped).To(BeFalse())39 xform.Start()40 g.Expect(started).To(BeTrue())41 g.Expect(stopped).To(BeFalse())42 xform.Stop()43 g.Expect(stopped).To(BeTrue())44}45func TestTransformer_Selection(t *testing.T) {46 g := NewGomegaWithT(t)47 inputs := collection.NewSchemasBuilder().MustAdd(data.Foo).MustAdd(data.Bar).Build()48 outputs := collection.NewSchemasBuilder().MustAdd(data.Boo).MustAdd(data.Baz).Build()49 xform := event.NewFnTransform(50 inputs,51 outputs,52 nil,53 nil,54 func(e event.Event, h event.Handler) {55 // Simply translate events56 if e.IsSource(data.Foo.Name()) {57 h.Handle(e.WithSource(data.Boo))58 }59 if e.IsSource(data.Bar.Name()) {60 h.Handle(e.WithSource(data.Baz))61 }62 },63 )64 accBoo := &fixtures.Accumulator{}65 accBaz := &fixtures.Accumulator{}66 xform.DispatchFor(data.Boo, accBoo)67 xform.DispatchFor(data.Baz, accBaz)68 xform.Start()69 xform.Handle(data.Event1Col1AddItem1.WithSource(data.Foo))70 xform.Handle(data.Event1Col1AddItem1.WithSource(data.Bar))71 g.Expect(accBoo.Events()).To(ConsistOf(72 data.Event1Col1AddItem1.WithSource(data.Boo),73 ))74 g.Expect(accBaz.Events()).To(ConsistOf(75 data.Event1Col1AddItem1.WithSource(data.Baz),76 ))77}78func TestTransformer_InvalidEvent(t *testing.T) {79 g := NewGomegaWithT(t)80 inputs := collection.NewSchemasBuilder().MustAdd(data.Foo).Build()81 outputs := collection.NewSchemasBuilder().MustAdd(data.Bar).Build()82 xform := event.NewFnTransform(83 inputs,84 outputs,85 nil,86 nil,87 func(e event.Event, h event.Handler) {88 // Simply translate events89 if e.IsSource(data.Foo.Name()) {90 h.Handle(e.WithSource(data.Bar))91 }92 },93 )94 acc := &fixtures.Accumulator{}95 xform.DispatchFor(data.Bar, acc)96 xform.Start()97 xform.Handle(data.Event1Col1AddItem1.WithSource(data.Bar))98 g.Expect(acc.Events()).To(BeEmpty())99}100func TestTransformer_Reset(t *testing.T) {101 g := NewGomegaWithT(t)102 inputs := collection.NewSchemasBuilder().MustAdd(data.Foo).Build()103 outputs := collection.NewSchemasBuilder().MustAdd(data.Bar).MustAdd(data.Baz).Build()104 xform := event.NewFnTransform(105 inputs,106 outputs,107 nil,108 nil,109 func(e event.Event, h event.Handler) {110 // Simply translate events111 if e.IsSource(data.Foo.Name()) {112 h.Handle(e.WithSource(data.Bar))113 }114 },115 )116 accBar := &fixtures.Accumulator{} // it is a trap!117 xform.DispatchFor(data.Bar, accBar)118 accBaz := &fixtures.Accumulator{}119 xform.DispatchFor(data.Baz, accBaz)120 xform.Start()121 xform.Handle(event.Event{Kind: event.Reset})122 g.Expect(accBar.Events()).To(ConsistOf(123 event.Event{Kind: event.Reset},124 ))125 g.Expect(accBar.Events()).To(ConsistOf(126 event.Event{Kind: event.Reset},127 ))128}129func TestTransformer_FullSync(t *testing.T) {130 g := NewGomegaWithT(t)131 inputs := collection.NewSchemasBuilder().MustAdd(data.Foo).MustAdd(data.Bar).Build()132 outputs := collection.NewSchemasBuilder().MustAdd(data.Boo).MustAdd(data.Baz).Build()133 xform := event.NewFnTransform(134 inputs,135 outputs,136 nil,137 nil,138 func(e event.Event, h event.Handler) {139 // Simply translate events140 if e.IsSource(data.Foo.Name()) {141 h.Handle(e.WithSource(data.Boo))142 }143 if e.IsSource(data.Bar.Name()) {144 h.Handle(e.WithSource(data.Baz))145 }146 },147 )148 accBoo := &fixtures.Accumulator{}149 accBaz := &fixtures.Accumulator{}150 xform.DispatchFor(data.Boo, accBoo)151 xform.DispatchFor(data.Baz, accBaz)152 xform.Start()153 xform.Handle(event.FullSyncFor(data.Foo))154 g.Expect(accBoo.Events()).To(BeEmpty())155 g.Expect(accBaz.Events()).To(BeEmpty())156 xform.Handle(event.FullSyncFor(data.Bar))157 g.Expect(accBoo.Events()).To(ConsistOf(event.FullSyncFor(data.Boo)))158 g.Expect(accBaz.Events()).To(ConsistOf(event.FullSyncFor(data.Baz)))159 // redo160 accBoo.Clear()161 accBaz.Clear()162 xform.Stop()163 xform.Start()164 xform.Handle(event.FullSyncFor(data.Bar))165 g.Expect(accBoo.Events()).To(BeEmpty())166 g.Expect(accBaz.Events()).To(BeEmpty())167 xform.Handle(event.FullSyncFor(data.Foo))168 g.Expect(accBoo.Events()).To(ConsistOf(event.FullSyncFor(data.Boo)))169 g.Expect(accBaz.Events()).To(ConsistOf(event.FullSyncFor(data.Baz)))170}...

Full Screen

Full Screen

imports_test.go

Source:imports_test.go Github

copy

Full Screen

...80 "fu/baz.proto": `81 syntax = "proto3";82 package fu;83 import "bar.proto";84 message Baz {85 repeated foo.Bar foobar = 1;86 }87 `,88 }),89 ImportPaths: []string{"foo"},90 }91 fds, err := p.ParseFilesButDoNotLink("foo/bar.proto", "fu/baz.proto")92 testutil.Ok(t, err)93 // Since we didn't link, fu.Baz.foobar field in second file has no type94 // (it can't know whether it's a message or enum until linking is done).95 // So go ahead and fill in the correct type:96 fds[1].MessageType[0].Field[0].Type = descriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum()97 // sanity check: make sure linking fails without an import resolver98 _, err = desc.CreateFileDescriptors(fds)99 testutil.Require(t, err != nil)100 testutil.Eq(t, `no such file: "bar.proto"`, err.Error())101 // now try again with resolver102 var r desc.ImportResolver103 r.RegisterImportPath("foo/bar.proto", "bar.proto")104 linkedFiles, err := r.CreateFileDescriptors(fds)105 // success!106 testutil.Ok(t, err)107 // quick check of the resulting files108 fd := linkedFiles["foo/bar.proto"]109 testutil.Require(t, fd != nil)110 md := fd.FindMessage("foo.Bar")111 testutil.Require(t, md != nil)112 fd2 := linkedFiles["fu/baz.proto"]113 testutil.Require(t, fd2 != nil)114 md2 := fd2.FindMessage("fu.Baz")115 testutil.Require(t, md2 != nil)116 fld := md2.FindFieldByNumber(1)117 testutil.Require(t, fld != nil)118 testutil.Eq(t, md, fld.GetMessageType())119 testutil.Eq(t, fd, fd2.GetDependencies()[0])120}121func expectPanic(t *testing.T, fn func()) {122 defer func() {123 p := recover()124 testutil.Require(t, p != nil, "expecting panic")125 }()126 fn()127}...

Full Screen

Full Screen

Baz

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(stringutil.Baz())4}5import (6func main() {7 fmt.Println(stringutil.Bar())8}9func ReverseRunes(s string) string {10 r := []rune(s)11 for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {12 }13 return string(r)14}

Full Screen

Full Screen

Baz

Using AI Code Generation

copy

Full Screen

1import "github.com/yourname/yourproject/source"2func main() {3 source.Baz()4}5import "github.com/yourname/yourproject/source"6func main() {7 source.Bar()8}9import "github.com/yourname/yourproject/source"10func main() {11 source.Foo()12}13import "github.com/yourname/yourproject/source"14func main() {15 source.Foo()16}17import "github.com/yourname/yourproject/source"18func main() {19 source.Foo()20}21import "github.com/yourname/yourproject/source"22func main() {23 source.Foo()24}25import "github.com/yourname/yourproject/source"26func main() {27 source.Foo()28}29import "github.com/yourname/yourproject/source"30func main() {31 source.Foo()32}33import "github.com/yourname/yourproject/source"34func main() {35 source.Foo()36}37import "github.com/yourname/yourproject/source"38func main() {39 source.Foo()40}41import "github.com/yourname/yourproject/source"42func main() {43 source.Foo()44}45import "github.com/yourname/yourproject/source"46func main() {47 source.Foo()48}

Full Screen

Full Screen

Baz

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 first.Baz()4}5import (6func main() {7 first.Bar()8}9import (10func main() {11 first.Foo()12}13import (14func main() {15 first.Foo()16}17import (18func main() {19 first.Foo()20}21import (22func main() {23 first.Foo()24}25import (26func main() {27 first.Foo()28}29import (30func main() {31 first.Foo()32}33import (34func main() {35 first.Foo()36}37import (38func main() {39 first.Foo()40}41import (42func main() {43 first.Foo()44}

Full Screen

Full Screen

Baz

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(b.Method())4}5import (6func main() {7 fmt.Println(b.Method())8}9type Baz interface {10 Method() string11}12import (13func main() {14 fmt.Println(b.Method())15}16type Baz interface {17 Method(string) string18}19import (20func main() {21 fmt.Println(b.Method("hello"))22}23type Baz interface {24 Method(string) string25}26import (27func main() {28 fmt.Println(b.Method("hello"))29}30type Baz struct {31}

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.

Run Mock automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful