How to use updateStatus method of run Package

Best Keploy code snippet using run.updateStatus

run.go

Source:run.go Github

copy

Full Screen

...105func (r *Run) Discard() error {106 if !r.Discardable() {107 return ErrRunDiscardNotAllowed108 }109 r.updateStatus(RunDiscarded)110 return nil111}112// Cancel run.113func (r *Run) Cancel() error {114 if !r.Cancelable() {115 return ErrRunCancelNotAllowed116 }117 r.updateStatus(RunCanceled)118 return nil119}120func (r *Run) ForceCancelAvailableAt() time.Time {121 if r.status != RunCanceled {122 return time.Time{}123 }124 canceledAt, err := r.StatusTimestamp(r.status)125 if err != nil {126 panic("no corresponding timestamp found for canceled status")127 }128 // Run can be forcefully cancelled after a cool-off period of ten seconds129 return canceledAt.Add(10 * time.Second)130}131// ForceCancel updates the state of a run to reflect it having been forcefully132// cancelled.133func (r *Run) ForceCancel() error {134 if !r.ForceCancelable() {135 return ErrRunForceCancelNotAllowed136 }137 return r.updateStatus(RunForceCanceled)138}139// Cancelable determines whether run can be cancelled.140func (r *Run) Cancelable() bool {141 switch r.Status() {142 case RunPending, RunPlanQueued, RunPlanning, RunApplyQueued, RunApplying:143 return true144 default:145 return false146 }147}148// Confirmable determines whether run can be confirmed.149func (r *Run) Confirmable() bool {150 switch r.Status() {151 case RunPlanned:152 return true153 default:154 return false155 }156}157// Discardable determines whether run can be discarded.158func (r *Run) Discardable() bool {159 switch r.Status() {160 case RunPending, RunPlanned:161 return true162 default:163 return false164 }165}166// ForceCancelable determines whether a run can be forcibly cancelled.167func (r *Run) ForceCancelable() bool {168 availAt := r.ForceCancelAvailableAt()169 if availAt.IsZero() {170 return false171 }172 return CurrentTimestamp().After(availAt)173}174// Active determines whether run is currently the active run on a workspace,175// i.e. it is neither finished nor pending176func (r *Run) Active() bool {177 if r.Done() || r.Status() == RunPending {178 return false179 }180 return true181}182// Done determines whether run has reached an end state, e.g. applied,183// discarded, etc.184func (r *Run) Done() bool {185 switch r.Status() {186 case RunApplied, RunPlannedAndFinished, RunDiscarded, RunCanceled, RunErrored:187 return true188 default:189 return false190 }191}192func (r *Run) Speculative() bool {193 return r.speculative194}195func (r *Run) ApplyRun() error {196 return r.updateStatus(RunApplyQueued)197}198func (r *Run) EnqueuePlan() error {199 return r.updateStatus(RunPlanQueued)200}201func (r *Run) StatusTimestamp(status RunStatus) (time.Time, error) {202 for _, rst := range r.statusTimestamps {203 if rst.Status == status {204 return rst.Timestamp, nil205 }206 }207 return time.Time{}, ErrStatusTimestampNotFound208}209// CanLock determines whether requestor can replace run lock210func (r *Run) CanLock(requestor Identity) error {211 if _, ok := requestor.(*Run); ok {212 // run can replace lock held by different run213 return nil214 }215 return ErrWorkspaceAlreadyLocked216}217// CanUnlock determines whether requestor can unlock run lock218func (r *Run) CanUnlock(requestor Identity, force bool) error {219 if force {220 // TODO: only grant admin user force unlock always granted221 return nil222 }223 if _, ok := requestor.(*Run); ok {224 // runs can unlock other run locks225 return nil226 }227 return ErrWorkspaceLockedByDifferentUser228}229// Start a run job230func (r *Run) Start() error {231 switch r.status {232 case RunPlanQueued:233 r.updateStatus(RunPlanning)234 case RunApplyQueued:235 r.updateStatus(RunApplying)236 case RunPlanning, RunApplying:237 return ErrJobAlreadyClaimed238 default:239 return fmt.Errorf("run cannot be started: invalid status: %s", r.Status())240 }241 return nil242}243// Finish updates the run to reflect its plan having finished. An event is244// returned reflecting the run's new status.245func (r *Run) Finish(opts JobFinishOptions) (*Event, error) {246 if opts.Errored {247 if err := r.updateStatus(RunErrored); err != nil {248 return nil, err249 }250 return &Event{Payload: r, Type: EventRunErrored}, nil251 }252 switch r.status {253 case RunPlanning:254 r.updateStatus(RunPlanned)255 return r.plan.Finish()256 case RunApplying:257 r.updateStatus(RunApplied)258 return &Event{Payload: r, Type: EventRunApplied}, nil259 default:260 return nil, fmt.Errorf("run cannot be finished: invalid status: %s", r.status)261 }262}263// ToJSONAPI assembles a JSON-API DTO.264func (r *Run) ToJSONAPI(req *http.Request) any {265 dto := &jsonapi.Run{266 ID: r.ID(),267 Actions: &jsonapi.RunActions{268 IsCancelable: r.Cancelable(),269 IsConfirmable: r.Confirmable(),270 IsForceCancelable: r.ForceCancelable(),271 IsDiscardable: r.Discardable(),272 },273 CreatedAt: r.CreatedAt(),274 ForceCancelAvailableAt: r.ForceCancelAvailableAt(),275 HasChanges: r.plan.HasChanges(),276 IsDestroy: r.IsDestroy(),277 Message: r.Message(),278 Permissions: &jsonapi.RunPermissions{279 CanForceCancel: true,280 CanApply: true,281 CanCancel: true,282 CanDiscard: true,283 CanForceExecute: true,284 },285 PositionInQueue: 0,286 Refresh: r.Refresh(),287 RefreshOnly: r.RefreshOnly(),288 ReplaceAddrs: r.ReplaceAddrs(),289 Source: DefaultConfigurationSource,290 Status: string(r.Status()),291 StatusTimestamps: &jsonapi.RunStatusTimestamps{},292 TargetAddrs: r.TargetAddrs(),293 // Relations294 Apply: r.apply.ToJSONAPI(req).(*jsonapi.Apply),295 Plan: r.plan.ToJSONAPI(req).(*jsonapi.Plan),296 // Hardcoded anonymous user until authorization is introduced297 CreatedBy: &jsonapi.User{298 ID: DefaultUserID,299 Username: DefaultUsername,300 },301 ConfigurationVersion: &jsonapi.ConfigurationVersion{302 ID: r.configurationVersionID,303 },304 }305 if r.workspace != nil {306 dto.Workspace = r.workspace.ToJSONAPI(req).(*jsonapi.Workspace)307 } else {308 dto.Workspace = &jsonapi.Workspace{309 ID: r.workspaceID,310 }311 }312 for _, rst := range r.StatusTimestamps() {313 switch rst.Status {314 case RunPending:315 dto.StatusTimestamps.PlanQueueableAt = &rst.Timestamp316 case RunPlanQueued:317 dto.StatusTimestamps.PlanQueuedAt = &rst.Timestamp318 case RunPlanning:319 dto.StatusTimestamps.PlanningAt = &rst.Timestamp320 case RunPlanned:321 dto.StatusTimestamps.PlannedAt = &rst.Timestamp322 case RunPlannedAndFinished:323 dto.StatusTimestamps.PlannedAndFinishedAt = &rst.Timestamp324 case RunApplyQueued:325 dto.StatusTimestamps.ApplyQueuedAt = &rst.Timestamp326 case RunApplying:327 dto.StatusTimestamps.ApplyingAt = &rst.Timestamp328 case RunApplied:329 dto.StatusTimestamps.AppliedAt = &rst.Timestamp330 case RunErrored:331 dto.StatusTimestamps.ErroredAt = &rst.Timestamp332 case RunCanceled:333 dto.StatusTimestamps.CanceledAt = &rst.Timestamp334 case RunForceCanceled:335 dto.StatusTimestamps.ForceCanceledAt = &rst.Timestamp336 case RunDiscarded:337 dto.StatusTimestamps.DiscardedAt = &rst.Timestamp338 }339 }340 return dto341}342// updateStatus transitions the state - changes to a run are made only via this343// method.344func (r *Run) updateStatus(status RunStatus) error {345 switch status {346 case RunPending:347 r.plan.updateStatus(JobPending)348 r.apply.updateStatus(JobPending)349 case RunPlanQueued:350 r.plan.updateStatus(JobQueued)351 case RunPlanning:352 r.plan.updateStatus(JobRunning)353 case RunPlanned, RunPlannedAndFinished:354 r.plan.updateStatus(JobFinished)355 r.apply.updateStatus(JobUnreachable)356 case RunApplyQueued:357 r.apply.updateStatus(JobQueued)358 case RunApplying:359 r.apply.updateStatus(JobRunning)360 case RunApplied:361 r.apply.updateStatus(JobFinished)362 case RunErrored:363 switch r.Status() {364 case RunPlanning:365 r.plan.updateStatus(JobErrored)366 r.apply.updateStatus(JobUnreachable)367 case RunApplying:368 r.apply.updateStatus(JobErrored)369 }370 case RunCanceled:371 switch r.Status() {372 case RunPlanQueued, RunPlanning:373 r.plan.updateStatus(JobCanceled)374 r.apply.updateStatus(JobUnreachable)375 case RunApplyQueued, RunApplying:376 r.apply.updateStatus(JobCanceled)377 }378 }379 r.status = status380 r.statusTimestamps = append(r.statusTimestamps, RunStatusTimestamp{381 Status: status,382 Timestamp: CurrentTimestamp(),383 })384 // set job reflecting new status385 r.setJob()386 return nil387}388// setupEnv invokes the necessary steps before a plan or apply can proceed.389func (r *Run) setupEnv(env Environment) error {390 if err := env.RunFunc(r.downloadConfig); err != nil {...

Full Screen

Full Screen

service_test.go

Source:service_test.go Github

copy

Full Screen

1// Copyright 2020 Google LLC2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// https://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13package wire14import (15 "errors"16 "fmt"17 "testing"18 "time"19 "cloud.google.com/go/pubsublite/internal/test"20)21const receiveStatusTimeout = 5 * time.Second22type testStatusChangeReceiver struct {23 // Status change notifications are fired asynchronously, so a channel receives24 // the statuses.25 statusC chan serviceStatus26 lastStatus serviceStatus27 name string28}29func newTestStatusChangeReceiver(name string) *testStatusChangeReceiver {30 return &testStatusChangeReceiver{31 statusC: make(chan serviceStatus, 1),32 name: name,33 }34}35func (sr *testStatusChangeReceiver) Handle() interface{} { return sr }36func (sr *testStatusChangeReceiver) OnStatusChange(handle serviceHandle, status serviceStatus, err error) {37 sr.statusC <- status38}39func (sr *testStatusChangeReceiver) VerifyStatus(t *testing.T, want serviceStatus) {40 select {41 case status := <-sr.statusC:42 if status <= sr.lastStatus {43 t.Errorf("%s: Duplicate service status: %d, last status: %d", sr.name, status, sr.lastStatus)44 }45 if status != want {46 t.Errorf("%s: Got service status: %d, want: %d", sr.name, status, want)47 }48 sr.lastStatus = status49 case <-time.After(receiveStatusTimeout):50 t.Errorf("%s: Did not receive status within %v", sr.name, receiveStatusTimeout)51 }52}53func (sr *testStatusChangeReceiver) VerifyNoStatusChanges(t *testing.T) {54 select {55 case status := <-sr.statusC:56 t.Errorf("%s: Unexpected service status: %d", sr.name, status)57 default:58 }59}60type testService struct {61 receiver *testStatusChangeReceiver62 abstractService63}64func newTestService(name string) *testService {65 receiver := newTestStatusChangeReceiver(name)66 ts := &testService{receiver: receiver}67 ts.AddStatusChangeReceiver(receiver.Handle(), receiver.OnStatusChange)68 return ts69}70func (ts *testService) Start() { ts.UpdateStatus(serviceStarting, nil) }71func (ts *testService) Stop() { ts.UpdateStatus(serviceTerminating, nil) }72func (ts *testService) UpdateStatus(targetStatus serviceStatus, err error) {73 ts.mu.Lock()74 defer ts.mu.Unlock()75 ts.unsafeUpdateStatus(targetStatus, err)76}77func TestServiceUpdateStatusIsLinear(t *testing.T) {78 err1 := errors.New("error1")79 err2 := errors.New("error2")80 service := newTestService("service")81 service.UpdateStatus(serviceStarting, nil)82 service.receiver.VerifyStatus(t, serviceStarting)83 service.UpdateStatus(serviceActive, nil)84 service.UpdateStatus(serviceActive, nil)85 service.receiver.VerifyStatus(t, serviceActive)86 service.UpdateStatus(serviceTerminating, err1)87 service.UpdateStatus(serviceStarting, nil)88 service.UpdateStatus(serviceTerminating, nil)89 service.receiver.VerifyStatus(t, serviceTerminating)90 service.UpdateStatus(serviceTerminated, err2)91 service.UpdateStatus(serviceTerminated, nil)92 service.receiver.VerifyStatus(t, serviceTerminated)93 // Verify that the first error is not clobbered by the second.94 if got, want := service.Error(), err1; !test.ErrorEqual(got, want) {95 t.Errorf("service.Error(): got (%v), want (%v)", got, want)96 }97}98func TestServiceCheckServiceStatus(t *testing.T) {99 for _, tc := range []struct {100 status serviceStatus101 wantErr error102 }{103 {104 status: serviceUninitialized,105 wantErr: ErrServiceUninitialized,106 },107 {108 status: serviceStarting,109 wantErr: ErrServiceStarting,110 },111 {112 status: serviceActive,113 wantErr: nil,114 },115 {116 status: serviceTerminating,117 wantErr: ErrServiceStopped,118 },119 {120 status: serviceTerminated,121 wantErr: ErrServiceStopped,122 },123 } {124 t.Run(fmt.Sprintf("Status=%v", tc.status), func(t *testing.T) {125 s := newTestService("service")126 s.UpdateStatus(tc.status, nil)127 if gotErr := s.unsafeCheckServiceStatus(); !test.ErrorEqual(gotErr, tc.wantErr) {128 t.Errorf("service.unsafeCheckServiceStatus(): got (%v), want (%v)", gotErr, tc.wantErr)129 }130 })131 }132}133func TestServiceAddRemoveStatusChangeReceiver(t *testing.T) {134 receiver1 := newTestStatusChangeReceiver("receiver1")135 receiver2 := newTestStatusChangeReceiver("receiver2")136 receiver3 := newTestStatusChangeReceiver("receiver3")137 service := new(testService)138 service.AddStatusChangeReceiver(receiver1.Handle(), receiver1.OnStatusChange)139 service.AddStatusChangeReceiver(receiver2.Handle(), receiver2.OnStatusChange)140 service.AddStatusChangeReceiver(receiver3.Handle(), receiver3.OnStatusChange)141 t.Run("All receivers", func(t *testing.T) {142 service.UpdateStatus(serviceActive, nil)143 receiver1.VerifyStatus(t, serviceActive)144 receiver2.VerifyStatus(t, serviceActive)145 receiver3.VerifyStatus(t, serviceActive)146 })147 t.Run("receiver1 removed", func(t *testing.T) {148 service.RemoveStatusChangeReceiver(receiver1.Handle())149 service.UpdateStatus(serviceTerminating, nil)150 receiver1.VerifyNoStatusChanges(t)151 receiver2.VerifyStatus(t, serviceTerminating)152 receiver3.VerifyStatus(t, serviceTerminating)153 })154 t.Run("receiver2 removed", func(t *testing.T) {155 service.RemoveStatusChangeReceiver(receiver2.Handle())156 service.UpdateStatus(serviceTerminated, nil)157 receiver1.VerifyNoStatusChanges(t)158 receiver2.VerifyNoStatusChanges(t)159 receiver3.VerifyStatus(t, serviceTerminated)160 })161}162type testCompositeService struct {163 receiver *testStatusChangeReceiver164 compositeService165}166func newTestCompositeService(name string) *testCompositeService {167 receiver := newTestStatusChangeReceiver(name)168 ts := &testCompositeService{receiver: receiver}169 ts.AddStatusChangeReceiver(receiver.Handle(), receiver.OnStatusChange)170 ts.init()171 return ts172}173func (ts *testCompositeService) AddServices(services ...service) error {174 ts.mu.Lock()175 defer ts.mu.Unlock()176 return ts.unsafeAddServices(services...)177}178func (ts *testCompositeService) RemoveService(service service) {179 ts.mu.Lock()180 defer ts.mu.Unlock()181 ts.unsafeRemoveService(service)182}183func (ts *testCompositeService) DependenciesLen() int {184 ts.mu.Lock()185 defer ts.mu.Unlock()186 return len(ts.dependencies)187}188func (ts *testCompositeService) RemovedLen() int {189 ts.mu.Lock()190 defer ts.mu.Unlock()191 return len(ts.removed)192}193func TestCompositeServiceNormalStop(t *testing.T) {194 child1 := newTestService("child1")195 child2 := newTestService("child2")196 child3 := newTestService("child3")197 parent := newTestCompositeService("parent")198 if err := parent.AddServices(child1, child2); err != nil {199 t.Errorf("AddServices() got err: %v", err)200 }201 t.Run("Starting", func(t *testing.T) {202 wantState := serviceUninitialized203 if child1.Status() != wantState {204 t.Errorf("child1: current service status: got %d, want %d", child1.Status(), wantState)205 }206 if child2.Status() != wantState {207 t.Errorf("child2: current service status: got %d, want %d", child2.Status(), wantState)208 }209 parent.Start()210 child1.receiver.VerifyStatus(t, serviceStarting)211 child2.receiver.VerifyStatus(t, serviceStarting)212 parent.receiver.VerifyStatus(t, serviceStarting)213 // child3 is added after Start() and should be automatically started.214 if child3.Status() != wantState {215 t.Errorf("child3: current service status: got %d, want %d", child3.Status(), wantState)216 }217 if err := parent.AddServices(child3); err != nil {218 t.Errorf("AddServices() got err: %v", err)219 }220 child3.receiver.VerifyStatus(t, serviceStarting)221 })222 t.Run("Active", func(t *testing.T) {223 // parent service is active once all children are active.224 child1.UpdateStatus(serviceActive, nil)225 child2.UpdateStatus(serviceActive, nil)226 parent.receiver.VerifyNoStatusChanges(t)227 child3.UpdateStatus(serviceActive, nil)228 child1.receiver.VerifyStatus(t, serviceActive)229 child2.receiver.VerifyStatus(t, serviceActive)230 child3.receiver.VerifyStatus(t, serviceActive)231 parent.receiver.VerifyStatus(t, serviceActive)232 if err := parent.WaitStarted(); err != nil {233 t.Errorf("compositeService.WaitStarted() got err: %v", err)234 }235 })236 t.Run("Stopping", func(t *testing.T) {237 parent.Stop()238 child1.receiver.VerifyStatus(t, serviceTerminating)239 child2.receiver.VerifyStatus(t, serviceTerminating)240 child3.receiver.VerifyStatus(t, serviceTerminating)241 parent.receiver.VerifyStatus(t, serviceTerminating)242 // parent service is terminated once all children have terminated.243 child1.UpdateStatus(serviceTerminated, nil)244 child2.UpdateStatus(serviceTerminated, nil)245 parent.receiver.VerifyNoStatusChanges(t)246 child3.UpdateStatus(serviceTerminated, nil)247 child1.receiver.VerifyStatus(t, serviceTerminated)248 child2.receiver.VerifyStatus(t, serviceTerminated)249 child3.receiver.VerifyStatus(t, serviceTerminated)250 parent.receiver.VerifyStatus(t, serviceTerminated)251 if err := parent.WaitStopped(); err != nil {252 t.Errorf("compositeService.WaitStopped() got err: %v", err)253 }254 })255}256func TestCompositeServiceErrorDuringStartup(t *testing.T) {257 child1 := newTestService("child1")258 child2 := newTestService("child2")259 parent := newTestCompositeService("parent")260 if err := parent.AddServices(child1, child2); err != nil {261 t.Errorf("AddServices() got err: %v", err)262 }263 t.Run("Starting", func(t *testing.T) {264 parent.Start()265 parent.receiver.VerifyStatus(t, serviceStarting)266 child1.receiver.VerifyStatus(t, serviceStarting)267 child2.receiver.VerifyStatus(t, serviceStarting)268 })269 t.Run("Terminating", func(t *testing.T) {270 // child1 now errors.271 wantErr := errors.New("err during startup")272 child1.UpdateStatus(serviceTerminated, wantErr)273 child1.receiver.VerifyStatus(t, serviceTerminated)274 // This causes parent and child2 to start terminating.275 parent.receiver.VerifyStatus(t, serviceTerminating)276 child2.receiver.VerifyStatus(t, serviceTerminating)277 // parent has terminated once child2 has terminated.278 child2.UpdateStatus(serviceTerminated, nil)279 child2.receiver.VerifyStatus(t, serviceTerminated)280 parent.receiver.VerifyStatus(t, serviceTerminated)281 if gotErr := parent.WaitStarted(); !test.ErrorEqual(gotErr, wantErr) {282 t.Errorf("compositeService.WaitStarted() got err: (%v), want err: (%v)", gotErr, wantErr)283 }284 })285}286func TestCompositeServiceErrorWhileActive(t *testing.T) {287 child1 := newTestService("child1")288 child2 := newTestService("child2")289 parent := newTestCompositeService("parent")290 if err := parent.AddServices(child1, child2); err != nil {291 t.Errorf("AddServices() got err: %v", err)292 }293 t.Run("Starting", func(t *testing.T) {294 parent.Start()295 child1.receiver.VerifyStatus(t, serviceStarting)296 child2.receiver.VerifyStatus(t, serviceStarting)297 parent.receiver.VerifyStatus(t, serviceStarting)298 })299 t.Run("Active", func(t *testing.T) {300 child1.UpdateStatus(serviceActive, nil)301 child2.UpdateStatus(serviceActive, nil)302 child1.receiver.VerifyStatus(t, serviceActive)303 child2.receiver.VerifyStatus(t, serviceActive)304 parent.receiver.VerifyStatus(t, serviceActive)305 if err := parent.WaitStarted(); err != nil {306 t.Errorf("compositeService.WaitStarted() got err: %v", err)307 }308 })309 t.Run("Terminating", func(t *testing.T) {310 // child2 now errors.311 wantErr := errors.New("err while active")312 child2.UpdateStatus(serviceTerminating, wantErr)313 child2.receiver.VerifyStatus(t, serviceTerminating)314 // This causes parent and child1 to start terminating.315 child1.receiver.VerifyStatus(t, serviceTerminating)316 parent.receiver.VerifyStatus(t, serviceTerminating)317 // parent has terminated once both children have terminated.318 child1.UpdateStatus(serviceTerminated, nil)319 child2.UpdateStatus(serviceTerminated, nil)320 child1.receiver.VerifyStatus(t, serviceTerminated)321 child2.receiver.VerifyStatus(t, serviceTerminated)322 parent.receiver.VerifyStatus(t, serviceTerminated)323 if gotErr := parent.WaitStopped(); !test.ErrorEqual(gotErr, wantErr) {324 t.Errorf("compositeService.WaitStopped() got err: (%v), want err: (%v)", gotErr, wantErr)325 }326 })327}328func TestCompositeServiceRemoveService(t *testing.T) {329 child1 := newTestService("child1")330 child2 := newTestService("child2")331 parent := newTestCompositeService("parent")332 if err := parent.AddServices(child1, child2); err != nil {333 t.Errorf("AddServices() got err: %v", err)334 }335 t.Run("Starting", func(t *testing.T) {336 parent.Start()337 child1.receiver.VerifyStatus(t, serviceStarting)338 child2.receiver.VerifyStatus(t, serviceStarting)339 parent.receiver.VerifyStatus(t, serviceStarting)340 })341 t.Run("Active", func(t *testing.T) {342 child1.UpdateStatus(serviceActive, nil)343 child2.UpdateStatus(serviceActive, nil)344 child1.receiver.VerifyStatus(t, serviceActive)345 child2.receiver.VerifyStatus(t, serviceActive)346 parent.receiver.VerifyStatus(t, serviceActive)347 })348 t.Run("Remove service", func(t *testing.T) {349 if got, want := parent.DependenciesLen(), 2; got != want {350 t.Errorf("compositeService.dependencies: got len %d, want %d", got, want)351 }352 if got, want := parent.RemovedLen(), 0; got != want {353 t.Errorf("compositeService.removed: got len %d, want %d", got, want)354 }355 // Removing child1 should stop it, but leave everything else active.356 parent.RemoveService(child1)357 if got, want := parent.DependenciesLen(), 1; got != want {358 t.Errorf("compositeService.dependencies: got len %d, want %d", got, want)359 }360 if got, want := parent.RemovedLen(), 1; got != want {361 t.Errorf("compositeService.removed: got len %d, want %d", got, want)362 }363 child1.receiver.VerifyStatus(t, serviceTerminating)364 child2.receiver.VerifyNoStatusChanges(t)365 parent.receiver.VerifyNoStatusChanges(t)366 // After child1 has terminated, it should be removed.367 child1.UpdateStatus(serviceTerminated, nil)368 child1.receiver.VerifyStatus(t, serviceTerminated)369 child2.receiver.VerifyNoStatusChanges(t)370 parent.receiver.VerifyNoStatusChanges(t)371 if got, want := parent.Status(), serviceActive; got != want {372 t.Errorf("compositeService.Status() got %v, want %v", got, want)373 }374 })375 t.Run("Terminating", func(t *testing.T) {376 // Now stop the composite service.377 parent.Stop()378 child2.receiver.VerifyStatus(t, serviceTerminating)379 parent.receiver.VerifyStatus(t, serviceTerminating)380 child2.UpdateStatus(serviceTerminated, nil)381 child2.receiver.VerifyStatus(t, serviceTerminated)382 parent.receiver.VerifyStatus(t, serviceTerminated)383 if err := parent.WaitStopped(); err != nil {384 t.Errorf("compositeService.WaitStopped() got err: %v", err)385 }386 if got, want := parent.DependenciesLen(), 1; got != want {387 t.Errorf("compositeService.dependencies: got len %d, want %d", got, want)388 }389 if got, want := parent.RemovedLen(), 0; got != want {390 t.Errorf("compositeService.removed: got len %d, want %d", got, want)391 }392 })393}394func TestCompositeServiceTree(t *testing.T) {395 leaf1 := newTestService("leaf1")396 leaf2 := newTestService("leaf2")397 intermediate1 := newTestCompositeService("intermediate1")398 if err := intermediate1.AddServices(leaf1, leaf2); err != nil {399 t.Errorf("intermediate1.AddServices() got err: %v", err)400 }401 leaf3 := newTestService("leaf3")402 leaf4 := newTestService("leaf4")403 intermediate2 := newTestCompositeService("intermediate2")404 if err := intermediate2.AddServices(leaf3, leaf4); err != nil {405 t.Errorf("intermediate2.AddServices() got err: %v", err)406 }407 root := newTestCompositeService("root")408 if err := root.AddServices(intermediate1, intermediate2); err != nil {409 t.Errorf("root.AddServices() got err: %v", err)410 }411 wantErr := errors.New("fail")412 t.Run("Starting", func(t *testing.T) {413 // Start trickles down the tree.414 root.Start()415 leaf1.receiver.VerifyStatus(t, serviceStarting)416 leaf2.receiver.VerifyStatus(t, serviceStarting)417 leaf3.receiver.VerifyStatus(t, serviceStarting)418 leaf4.receiver.VerifyStatus(t, serviceStarting)419 intermediate1.receiver.VerifyStatus(t, serviceStarting)420 intermediate2.receiver.VerifyStatus(t, serviceStarting)421 root.receiver.VerifyStatus(t, serviceStarting)422 })423 t.Run("Active", func(t *testing.T) {424 // serviceActive notification trickles up the tree.425 leaf1.UpdateStatus(serviceActive, nil)426 leaf2.UpdateStatus(serviceActive, nil)427 leaf3.UpdateStatus(serviceActive, nil)428 leaf4.UpdateStatus(serviceActive, nil)429 leaf1.receiver.VerifyStatus(t, serviceActive)430 leaf2.receiver.VerifyStatus(t, serviceActive)431 leaf3.receiver.VerifyStatus(t, serviceActive)432 leaf4.receiver.VerifyStatus(t, serviceActive)433 intermediate1.receiver.VerifyStatus(t, serviceActive)434 intermediate2.receiver.VerifyStatus(t, serviceActive)435 root.receiver.VerifyStatus(t, serviceActive)436 if err := root.WaitStarted(); err != nil {437 t.Errorf("compositeService.WaitStarted() got err: %v", err)438 }439 })440 t.Run("Leaf fails", func(t *testing.T) {441 leaf1.UpdateStatus(serviceTerminated, wantErr)442 leaf1.receiver.VerifyStatus(t, serviceTerminated)443 // Leaf service failure should trickle up the tree and across to all other444 // leaves, causing them all to start terminating.445 leaf2.receiver.VerifyStatus(t, serviceTerminating)446 leaf3.receiver.VerifyStatus(t, serviceTerminating)447 leaf4.receiver.VerifyStatus(t, serviceTerminating)448 intermediate1.receiver.VerifyStatus(t, serviceTerminating)449 intermediate2.receiver.VerifyStatus(t, serviceTerminating)450 root.receiver.VerifyStatus(t, serviceTerminating)451 })452 t.Run("Terminated", func(t *testing.T) {453 // serviceTerminated notification trickles up the tree.454 leaf2.UpdateStatus(serviceTerminated, nil)455 leaf3.UpdateStatus(serviceTerminated, nil)456 leaf4.UpdateStatus(serviceTerminated, nil)457 leaf2.receiver.VerifyStatus(t, serviceTerminated)458 leaf3.receiver.VerifyStatus(t, serviceTerminated)459 leaf4.receiver.VerifyStatus(t, serviceTerminated)460 intermediate1.receiver.VerifyStatus(t, serviceTerminated)461 intermediate2.receiver.VerifyStatus(t, serviceTerminated)462 root.receiver.VerifyStatus(t, serviceTerminated)463 if gotErr := root.WaitStopped(); !test.ErrorEqual(gotErr, wantErr) {464 t.Errorf("compositeService.WaitStopped() got err: (%v), want err: (%v)", gotErr, wantErr)465 }466 })467}468func TestCompositeServiceAddServicesErrors(t *testing.T) {469 child1 := newTestService("child1")470 parent := newTestCompositeService("parent")471 if err := parent.AddServices(child1); err != nil {472 t.Errorf("AddServices(child1) got err: %v", err)473 }474 child2 := newTestService("child2")475 child2.Start()476 if gotErr, wantErr := parent.AddServices(child2), errChildServiceStarted; !test.ErrorEqual(gotErr, wantErr) {477 t.Errorf("AddServices(child2) got err: (%v), want err: (%v)", gotErr, wantErr)478 }479 parent.Stop()480 child3 := newTestService("child3")481 if gotErr, wantErr := parent.AddServices(child3), ErrServiceStopped; !test.ErrorEqual(gotErr, wantErr) {482 t.Errorf("AddServices(child3) got err: (%v), want err: (%v)", gotErr, wantErr)483 }484}...

Full Screen

Full Screen

response_test.go

Source:response_test.go Github

copy

Full Screen

1package monitoringplugin2import (3 "bytes"4 "github.com/stretchr/testify/assert"5 "os"6 "os/exec"7 "regexp"8 "strconv"9 "strings"10 "testing"11)12func TestOKResponse(t *testing.T) {13 defaultMessage := "OKTest"14 if os.Getenv("EXECUTE_PLUGIN") == "1" {15 r := NewResponse(defaultMessage)16 r.OutputAndExit()17 }18 cmd := exec.Command(os.Args[0], "-test.run=TestOKResponse")19 cmd.Env = append(os.Environ(), "EXECUTE_PLUGIN=1")20 var outputB bytes.Buffer21 cmd.Stdout = &outputB22 err := cmd.Run()23 if err != nil {24 if exitError, ok := err.(*exec.ExitError); ok {25 t.Error("OkResponse is expected to return exit status 0, but exited with exit code " + strconv.Itoa(exitError.ExitCode()))26 } else {27 t.Error("cmd.Run() Command resulted in an error that can not be converted to exec.ExitEror! error: " + err.Error())28 }29 return30 }31 output := outputB.String()32 match, err := regexp.MatchString("^OK: "+defaultMessage+"\n$", output)33 if err != nil {34 t.Error(err.Error())35 }36 if !match {37 t.Error("ok result output message did not match to the expected regex")38 }39 return40}41func TestWARNINGResponse(t *testing.T) {42 failureResponse(t, 1)43 return44}45func TestCRITICALResponse(t *testing.T) {46 failureResponse(t, 2)47 return48}49func TestUNKNOWNResponse(t *testing.T) {50 failureResponse(t, 3)51 return52}53func TestStatusHierarchy(t *testing.T) {54 r := NewResponse("")55 if r.statusCode != OK {56 t.Error("status code is supposed to be OK when a new Response is created")57 }58 r.UpdateStatus(WARNING, "")59 if r.statusCode != WARNING {60 t.Error("status code did not update from OK to WARNING after UpdateStatus(WARNING) is called!")61 }62 r.UpdateStatus(OK, "")63 if r.statusCode != WARNING {64 t.Error("status code did change from WARNING to " + strconv.Itoa(r.statusCode) + " after UpdateStatus(OK) was called! The function should not affect the status code, because WARNING is worse than OK")65 }66 r.UpdateStatus(CRITICAL, "")67 if r.statusCode != CRITICAL {68 t.Error("status code did not update from WARNING to CRITICAL after UpdateStatus(WARNING) is called!")69 }70 r.UpdateStatus(OK, "")71 if r.statusCode != CRITICAL {72 t.Error("status code did change from CRITICAL to " + strconv.Itoa(r.statusCode) + " after UpdateStatus(OK) was called! The function should not affect the status code, because CRITICAL is worse than OK")73 }74 r.UpdateStatus(WARNING, "")75 if r.statusCode != CRITICAL {76 t.Error("status code did change from CRITICAL to " + strconv.Itoa(r.statusCode) + " after UpdateStatus(WARNING) was called! The function should not affect the status code, because CRITICAL is worse than WARNING")77 }78 r.UpdateStatus(UNKNOWN, "")79 if r.statusCode != CRITICAL {80 t.Error("status code did change from CRITICAL to " + strconv.Itoa(r.statusCode) + " after UpdateStatus(UNKNOWN) was called! The function should not affect the status code, because CRITICAL is worse than UNKNOWN")81 }82 r = NewResponse("")83 r.UpdateStatus(UNKNOWN, "")84 if r.statusCode != UNKNOWN {85 t.Error("status code did not update from OK to UNKNOWN after UpdateStatus(UNKNOWN) is called!")86 }87 r.UpdateStatus(WARNING, "")88 if r.statusCode != UNKNOWN {89 t.Error("status code did change from UNKNOWN to " + strconv.Itoa(r.statusCode) + " after UpdateStatus(WARNING) was called! The function should not affect the status code, because UNKNOWN is worse than WARNING")90 }91 r.UpdateStatus(CRITICAL, "")92 if r.statusCode != CRITICAL {93 t.Error("status code is did not change from UNKNOWN to CRITICAL after UpdateStatus(CRITICAL) was called! The function should affect the status code, because CRITICAL is worse than UNKNOWN")94 }95}96func TestOutputMessages(t *testing.T) {97 defaultMessage := "default"98 if os.Getenv("EXECUTE_PLUGIN") == "1" {99 r := NewResponse(defaultMessage)100 r.UpdateStatus(0, "message1")101 r.UpdateStatus(0, "message2")102 r.UpdateStatus(0, "message3")103 r.UpdateStatus(0, "message4")104 r.OutputAndExit()105 return106 }107 if os.Getenv("EXECUTE_PLUGIN") == "2" {108 r := NewResponse(defaultMessage)109 r.UpdateStatus(1, "message1")110 r.UpdateStatus(0, "message2")111 r.UpdateStatus(0, "message3")112 r.UpdateStatus(0, "message4")113 r.SetOutputDelimiter(" / ")114 r.OutputAndExit()115 return116 }117 cmd := exec.Command(os.Args[0], "-test.run=TestOutputMessages")118 cmd.Env = append(os.Environ(), "EXECUTE_PLUGIN=1")119 var outputB bytes.Buffer120 cmd.Stdout = &outputB121 err := cmd.Run()122 if err != nil {123 t.Error("an error occurred during cmd.Run(), but the Response was expected to exit with exit code 0")124 return125 }126 output := outputB.String()127 match, err := regexp.MatchString("^OK: "+defaultMessage+"\nmessage1\nmessage2\nmessage3\nmessage4\n$", output)128 if err != nil {129 t.Error(err.Error())130 }131 if !match {132 t.Error("output did not match to the expected regex")133 }134 cmd = exec.Command(os.Args[0], "-test.run=TestOutputMessages")135 cmd.Env = append(os.Environ(), "EXECUTE_PLUGIN=2")136 var outputB2 bytes.Buffer137 cmd.Stdout = &outputB2138 err = cmd.Run()139 if err != nil {140 if exitError, ok := err.(*exec.ExitError); ok {141 if exitError.ExitCode() != 1 {142 t.Error("the command is expected to return exit status 1, but exited with exit code " + strconv.Itoa(exitError.ExitCode()))143 }144 } else {145 t.Errorf("cmd.Run() Command resulted in an error that can not be converted to exec.ExitEror! error: " + err.Error())146 }147 } else {148 t.Error("the command exited with exitcode 0 but is expected to exit with exitcode 1")149 }150 output = outputB2.String()151 match, err = regexp.MatchString("^WARNING: message1 / message2 / message3 / message4\n$", output)152 if err != nil {153 t.Error(err.Error())154 }155 if !match {156 t.Error("output did not match to the expected regex")157 }158}159func TestResponse_UpdateStatusIf(t *testing.T) {160 r := NewResponse("")161 r.UpdateStatusIf(false, 1, "")162 assert.True(t, r.statusCode == 0)163 r.UpdateStatusIf(true, 1, "")164 assert.True(t, r.statusCode == 1)165}166func TestResponse_UpdateStatusIfNot(t *testing.T) {167 r := NewResponse("")168 r.UpdateStatusIfNot(true, 1, "")169 assert.True(t, r.statusCode == 0)170 r.UpdateStatusIfNot(false, 1, "")171 assert.True(t, r.statusCode == 1)172}173func TestString2StatusCode(t *testing.T) {174 assert.True(t, String2StatusCode("ok") == 0)175 assert.True(t, String2StatusCode("OK") == 0)176 assert.True(t, String2StatusCode("Ok") == 0)177 assert.True(t, String2StatusCode("warning") == 1)178 assert.True(t, String2StatusCode("WARNING") == 1)179 assert.True(t, String2StatusCode("Warning") == 1)180 assert.True(t, String2StatusCode("critical") == 2)181 assert.True(t, String2StatusCode("CRITICAL") == 2)182 assert.True(t, String2StatusCode("Critical") == 2)183 assert.True(t, String2StatusCode("unknown") == 3)184 assert.True(t, String2StatusCode("UNKNOWN") == 3)185 assert.True(t, String2StatusCode("Unknown") == 3)186}187func TestOutputPerformanceData(t *testing.T) {188 p1 := NewPerformanceDataPoint("label1", 10).189 SetUnit("%").190 SetMin(0).191 SetMax(100).192 SetThresholds(193 NewThresholds(0, 80, 0, 90))194 p2 := NewPerformanceDataPoint("label2", 20).195 SetUnit("%").196 SetMin(0).197 SetMax(100).198 SetThresholds(199 NewThresholds(0, 80, 0, 90))200 p3 := NewPerformanceDataPoint("label3", 30).201 SetUnit("%").202 SetMin(0).203 SetMax(100).204 SetThresholds(205 NewThresholds(0, 80, 0, 90))206 defaultMessage := "OKTest"207 if os.Getenv("EXECUTE_PLUGIN") == "1" {208 r := NewResponse(defaultMessage)209 err := r.AddPerformanceDataPoint(p1)210 if err != nil {211 r.UpdateStatus(3, "error during add performance data point")212 }213 err = r.AddPerformanceDataPoint(p2)214 if err != nil {215 r.UpdateStatus(3, "error during add performance data point")216 }217 err = r.AddPerformanceDataPoint(p3)218 if err != nil {219 r.UpdateStatus(3, "error during add performance data point")220 }221 r.OutputAndExit()222 }223 cmd := exec.Command(os.Args[0], "-test.run=TestOutputPerformanceData")224 cmd.Env = append(os.Environ(), "EXECUTE_PLUGIN=1")225 var outputB bytes.Buffer226 cmd.Stdout = &outputB227 err := cmd.Run()228 if err != nil {229 t.Error("cmd.Run() returned an exitcode != 0, but exit code 0 was expected")230 }231 output := outputB.String()232 if !strings.HasPrefix(output, "OK: "+defaultMessage+" | ") {233 t.Error("output did not match the expected regex")234 }235}236func TestOutputPerformanceDataThresholdsExceeded(t *testing.T) {237 p1 := NewPerformanceDataPoint("label1", 10).238 SetUnit("%").239 SetMin(0).240 SetMax(100).241 SetThresholds(242 NewThresholds(0, 80, 0, 90))243 p2 := NewPerformanceDataPoint("label2", 20).244 SetUnit("%").245 SetMin(0).246 SetMax(100).247 SetThresholds(248 NewThresholds(0, 80, 0, 90))249 p3 := NewPerformanceDataPoint("label3", 85).250 SetUnit("%").251 SetMin(0).252 SetMax(100).253 SetThresholds(254 NewThresholds(0, 80, 0, 90))255 defaultMessage := "OKTest"256 if os.Getenv("EXECUTE_PLUGIN") == "1" {257 r := NewResponse(defaultMessage)258 err := r.AddPerformanceDataPoint(p1)259 if err != nil {260 r.UpdateStatus(3, "error during add performance data point")261 }262 err = r.AddPerformanceDataPoint(p2)263 if err != nil {264 r.UpdateStatus(3, "error during add performance data point")265 }266 err = r.AddPerformanceDataPoint(p3)267 if err != nil {268 r.UpdateStatus(3, "error during add performance data point")269 }270 r.OutputAndExit()271 }272 cmd := exec.Command(os.Args[0], "-test.run=TestOutputPerformanceDataThresholdsExceeded")273 cmd.Env = append(os.Environ(), "EXECUTE_PLUGIN=1")274 var outputB bytes.Buffer275 cmd.Stdout = &outputB276 err := cmd.Run()277 if err == nil {278 t.Error("cmd.Run() returned an exitcode = 0, but exit code 1 was expected")279 } else if err.Error() != "exit status 1" {280 t.Error("cmd.Run() returned an exitcode != 1, but exit code 1 was expected")281 }282 output := outputB.String()283 if !strings.HasPrefix(output, "WARNING: label3 is outside of WARNING threshold | ") {284 t.Error("output did not match the expected regex")285 }286}287func failureResponse(t *testing.T, exitCode int) {288 var status string289 switch exitCode {290 case 0:291 t.Error("exitcode in failureResponse function cannot be 0, because it is not meant to be used for a successful cmd")292 return293 case 1:294 status = "WARNING"295 case 2:296 status = "CRITICAL"297 default:298 status = "UNKNOWN"299 }300 message := status + "Test"301 if os.Getenv("EXECUTE_PLUGIN") == "1" {302 r := NewResponse("")303 r.UpdateStatus(exitCode, message)304 r.OutputAndExit()305 }306 cmd := exec.Command(os.Args[0], "-test.run=Test"+status+"Response")307 cmd.Env = append(os.Environ(), "EXECUTE_PLUGIN=1")308 var outputB bytes.Buffer309 cmd.Stdout = &outputB310 err := cmd.Run()311 if err != nil {312 if exitError, ok := err.(*exec.ExitError); ok {313 if exitError.ExitCode() != exitCode {314 t.Error(status + " Response is expected to return exit status " + strconv.Itoa(exitCode) + ", but exited with exit code " + strconv.Itoa(exitError.ExitCode()))315 }316 } else {317 t.Errorf("cmd.Run() Command resulted in an error that can not be converted to exec.ExitEror! error: " + err.Error())318 }319 } else {320 t.Error("the command exited with exitcode 0 but is expected to exit with exitcode " + strconv.Itoa(exitCode))321 }322 output := outputB.String()323 match, err := regexp.MatchString("^"+status+": "+message+"\n$", output)324 if err != nil {325 t.Error(err.Error())326 }327 if !match {328 t.Error(status + " result output message did not match to the expected regex")329 }330 return331}332func TestResponse_SortOutputMessagesByStatus(t *testing.T) {333 r := NewResponse("defaultMessage")334 r.UpdateStatus(OK, "message1")335 r.UpdateStatus(WARNING, "message2")336 r.UpdateStatus(UNKNOWN, "message3")337 r.UpdateStatus(CRITICAL, "message4")338 r.UpdateStatus(WARNING, "message5")339 r.UpdateStatus(CRITICAL, "message6")340 r.UpdateStatus(UNKNOWN, "message7")341 r.UpdateStatus(OK, "message8")342 r.validate()343 for x, message := range r.outputMessages {344 for _, m := range r.outputMessages[x:] {345 assert.True(t, message.Status >= m.Status || message.Status == CRITICAL, "sorting did not work")346 }347 }348}349func TestResponse_InvalidCharacter(t *testing.T) {350 r := NewResponse("checked")351 r.UpdateStatus(WARNING, "test|")352 r.validate()353 res := r.GetInfo()354 assert.True(t, res.RawOutput == "WARNING: test")355}356func TestResponse_InvalidCharacterReplace(t *testing.T) {357 r := NewResponse("checked")358 r.UpdateStatus(OK, "test|2")359 err := r.SetInvalidCharacterBehavior(InvalidCharacterReplace, "-")360 assert.NoError(t, err)361 r.validate()362 res := r.GetInfo()363 assert.True(t, res.RawOutput == "OK: checked\ntest-2")364}365func TestResponse_InvalidCharacterReplaceError(t *testing.T) {366 r := NewResponse("checked")367 r.UpdateStatus(OK, "test|")368 err := r.SetInvalidCharacterBehavior(InvalidCharacterReplace, "")369 assert.Error(t, err)370}371func TestResponse_InvalidCharacterRemoveMessage(t *testing.T) {372 r := NewResponse("checked")373 r.UpdateStatus(OK, "test|")374 err := r.SetInvalidCharacterBehavior(InvalidCharacterRemoveMessage, "")375 assert.NoError(t, err)376 r.validate()377 res := r.GetInfo()378 assert.True(t, res.RawOutput == "OK: checked")379}380func TestResponse_InvalidCharacterReplaceWithError(t *testing.T) {381 r := NewResponse("checked")382 r.UpdateStatus(WARNING, "test|")383 err := r.SetInvalidCharacterBehavior(InvalidCharacterReplaceWithError, "")384 assert.NoError(t, err)385 r.validate()386 res := r.GetInfo()387 assert.True(t, res.RawOutput == "WARNING: output message contains invalid character")388}389func TestResponse_InvalidCharacterReplaceWithErrorMultipleMessages(t *testing.T) {390 r := NewResponse("checked")391 r.UpdateStatus(WARNING, "test|")392 r.UpdateStatus(WARNING, "test|2")393 err := r.SetInvalidCharacterBehavior(InvalidCharacterReplaceWithError, "")394 assert.NoError(t, err)395 r.validate()396 res := r.GetInfo()397 assert.True(t, res.RawOutput == "WARNING: output message contains invalid character")398}399func TestResponse_InvalidCharacterReplaceWithErrorAndSetUnknown(t *testing.T) {400 r := NewResponse("checked")401 r.UpdateStatus(WARNING, "test|")402 err := r.SetInvalidCharacterBehavior(InvalidCharacterReplaceWithErrorAndSetUNKNOWN, "")403 assert.NoError(t, err)404 r.validate()405 res := r.GetInfo()406 assert.True(t, res.RawOutput == "UNKNOWN: output message contains invalid character")407}408func TestResponse_InvalidCharacterReplaceWithErrorAndSetUnknownMultipleMessages(t *testing.T) {409 r := NewResponse("checked")410 r.UpdateStatus(WARNING, "test|")411 r.UpdateStatus(WARNING, "test|2")412 err := r.SetInvalidCharacterBehavior(InvalidCharacterReplaceWithErrorAndSetUNKNOWN, "")413 assert.NoError(t, err)414 r.validate()415 res := r.GetInfo()416 assert.True(t, res.RawOutput == "UNKNOWN: output message contains invalid character")417}418func TestResponse_InvalidCharacterDefaultMessage(t *testing.T) {419 r := NewResponse("test|")420 r.validate()421 res := r.GetInfo()422 assert.True(t, res.RawOutput == "OK: test")423}...

Full Screen

Full Screen

updateStatus

Using AI Code Generation

copy

Full Screen

1func (r *RunReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {2 ctx := context.Background()3 log := r.Log.WithValues("run", req.NamespacedName)4 return ctrl.Result{}, nil5}6func (r *RunReconciler) SetupWithManager(mgr ctrl.Manager) error {7 Complete(r)8}9func (r *RunReconciler) updateStatus(ctx context.Context, run *examplev1alpha1.Run, status examplev1alpha1.RunStatus) error {10 if err := r.Status().Update(ctx, run); err != nil {11 }12}13type RunStatus struct {

Full Screen

Full Screen

updateStatus

Using AI Code Generation

copy

Full Screen

1import (2type run struct {3}4func (r *run) updateStatus(status string) {5}6func main() {7 r := run{status: "new"}8 fmt.Println(r.status)9 go func() {10 time.Sleep(3 * time.Second)11 r.updateStatus("updated")12 }()13 time.Sleep(5 * time.Second)14 fmt.Println(r.status)15}

Full Screen

Full Screen

updateStatus

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3 fmt.Println("Hello, World!")4}5import "fmt"6func main() {7 fmt.Println("Hello, World!")8}

Full Screen

Full Screen

updateStatus

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 run := Run{}4 run.updateStatus()5 fmt.Println(run.Status)6}7import (8func main() {9 run := Run{}10 run.updateStatus()11 fmt.Println(run.Status)12}13import (14func main() {15 run := Run{}16 run.updateStatus()17 fmt.Println(run.Status)18}19import (20func main() {21 run := Run{}22 run.updateStatus()23 fmt.Println(run.Status)24}25import (26func main() {27 run := Run{}28 run.updateStatus()29 fmt.Println(run.Status)30}31import (32func main() {33 run := Run{}34 run.updateStatus()35 fmt.Println(run.Status)36}37import (38func main() {39 run := Run{}40 run.updateStatus()41 fmt.Println(run.Status)42}43import (44func main() {45 run := Run{}46 run.updateStatus()47 fmt.Println(run.Status)48}49import (50func main() {51 run := Run{}52 run.updateStatus()53 fmt.Println(run.Status)54}55import (56func main() {57 run := Run{}58 run.updateStatus()59 fmt.Println(run.Status)60}61import (62func main() {63 run := Run{}64 run.updateStatus()65 fmt.Println(run.Status)66}

Full Screen

Full Screen

updateStatus

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 run := new(Run)4 run.updateStatus("Running")5 fmt.Println(run.status)6 time.Sleep(5 * time.Second)7 run.updateStatus("Completed")8 fmt.Println(run.status)9}10import (11func main() {12 run := new(Run)13 run.updateStatus("Running")14 fmt.Println(run.status)15 time.Sleep(5 * time.Second)16 run.updateStatus("Completed")17 fmt.Println(run.status)18}19import (20func main() {21 run := new(Run)22 run.updateStatus("Running")23 fmt.Println(run.status)24 time.Sleep(5 * time.Second)25 run.updateStatus("Completed")26 fmt.Println(run.status)27}28import (29func main() {30 run := new(Run)31 run.updateStatus("Running")32 fmt.Println(run.status)33 time.Sleep(5 * time.Second)34 run.updateStatus("Completed")35 fmt.Println(run.status)36}37import (38func main() {39 run := new(Run)40 run.updateStatus("Running")41 fmt.Println(run.status)42 time.Sleep(5 * time.Second)43 run.updateStatus("Completed")44 fmt.Println(run.status)45}46import (47func main() {48 run := new(Run)49 run.updateStatus("Running")50 fmt.Println(run.status)51 time.Sleep(5 * time.Second)52 run.updateStatus("Completed")53 fmt.Println(run.status)54}55import (56func main() {57 run := new(Run)58 run.updateStatus("Running")59 fmt.Println(run.status)60 time.Sleep(5 * time.Second)61 run.updateStatus("Completed")62 fmt.Println(run.status)63}

Full Screen

Full Screen

updateStatus

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 r := new(run)4 r.updateStatus("running")5 time.Sleep(5 * time.Second)6 r.updateStatus("done")7}8import (9func main() {10 r := new(run)11 r.updateStatus("running")12 time.Sleep(5 * time.Second)13 r.updateStatus("done")14}15import (16func main() {17 r := new(run)18 r.updateStatus("running")19 time.Sleep(5 * time.Second)20 r.updateStatus("done")21}22import (23func main() {24 r := new(run)25 r.updateStatus("running")26 time.Sleep(5 * time.Second)27 r.updateStatus("done")28}29import (30func main() {31 r := new(run)32 r.updateStatus("running")33 time.Sleep(5 * time.Second)34 r.updateStatus("done")35}36import (37func main() {38 r := new(run)39 r.updateStatus("running")40 time.Sleep(5 * time.Second)41 r.updateStatus("done")42}43import (44func main() {45 r := new(run)46 r.updateStatus("running")47 time.Sleep(5 * time.Second)48 r.updateStatus("done")49}50import (51func main() {52 r := new(run)53 r.updateStatus("running")54 time.Sleep(5 * time.Second)55 r.updateStatus("done")56}57import (58func main() {

Full Screen

Full Screen

updateStatus

Using AI Code Generation

copy

Full Screen

1func main() {2 r := Run{}3 r.updateStatus()4}5import "1.go"6func main() {7 r := Run{}8 r.updateStatus()9}10import "2.go"11func main() {12 r := Run{}13 r.updateStatus()14}15import "3.go"16func main() {17 r := Run{}18 r.updateStatus()19}20import "4.go"21func main() {22 r := Run{}23 r.updateStatus()24}25import "5.go"26func main() {27 r := Run{}28 r.updateStatus()29}30import "6.go"31func main() {32 r := Run{}33 r.updateStatus()34}35import "7.go"36func main() {37 r := Run{}38 r.updateStatus()39}40import "8.go"41func main() {42 r := Run{}43 r.updateStatus()44}45import "9.go"46func main() {47 r := Run{}48 r.updateStatus()49}50import "10.go"51func main() {52 r := Run{}53 r.updateStatus()54}55import "11.go"56func main() {57 r := Run{}58 r.updateStatus()59}60import "12.go"61func main() {62 r := Run{}63 r.updateStatus()64}65import "13.go"66func main() {67 r := Run{}68 r.updateStatus()69}70import "14.go"71func main() {72 r := Run{}73 r.updateStatus()74}75import "15.go"76func main() {77 r := Run{}78 r.updateStatus()79}80import "16.go"81func main() {82 r := Run{}83 r.updateStatus()84}

Full Screen

Full Screen

updateStatus

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 r := run{}4 r.updateStatus(2)5 fmt.Println(r.status)6}

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 Keploy 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