Best Gauge code snippet using execution.Test
test.go
Source:test.go
...26 APIExecutionReport = "execution/%s/report/%s"27 APIExecutionArtifactList = "execution/%s/artifact"28 APIExecutionArtifact = "execution/%s/artifact/%s"29 //Default values30 defaultResultPath="build/Test"31 defaultSourcePath="src/tosca"32 defaultToscaAdminUsername="admin"33 defaultTimeout=time.Duration(30)34 //Execution Status35 executionPending ExecutionStatus = "Pending"36 executionPreparing ExecutionStatus = "Preparing"37 executionExecuting ExecutionStatus = "Executing"38 executionImportingResults ExecutionStatus = "ImportingResults"39 executionWaitingToImportResults ExecutionStatus = "WaitingToImportResults"40 executionGeneratingReports ExecutionStatus = "GeneratingReports"41 executionCompleted ExecutionStatus = "Completed"42 executionFailed ExecutionStatus = "Failed"43 executionCanceled ExecutionStatus = "Canceled"44)45var AlreadyRunningExecution = errors.New("already Running Execution on the node")46var TestsFailed = errors.New("some tests has been failed")47type ExecutionStatus string48type KeyValue struct {49 Key string50 Value string51}52type TestExecutorConfiguration struct {53 WorkspaceSessionID string `json:"sessionID"`54 Selectors []KeyValue `json:"selectors,omitempty"`55 Parameters []KeyValue `json:"parameters,omitempty"`56 Reports []string `json:"reports,omitempty"`57 VideoRecord bool `json:"videoRecord,omitempty"`58 buildDirectory string `json:"-"`59 xUnitPath string `json:"-"`60 artifactsPath string `json:"-"`61 reportsPath string `json:"-"`62 workspace *Workspace `json:"-"`63 hostname string `json:"-"`64 executionID string `json:"-"`65 executionLists []ExecutionList66}67type ExecutionFiles struct {68 Id string69 Path string70 Size int6471}72type ExecutionList struct {73 Name string74 Entries []string75}76type TestExecutionResponse struct {77 Error string78 ExecutionID string79 ExecutionLists []ExecutionList80 Status ExecutionStatus81 Files []ExecutionFiles82}83func (c *TestExecutorConfiguration) load(config TestSuiteConfiguration) {84 for k,v := range config.TestSuite.Selectors {85 c.Selectors = append(c.Selectors,KeyValue{86 Key: k,87 Value: v,88 })89 }90 for k,v := range config.TestSuite.Parameters{91 c.Parameters = append(c.Parameters,KeyValue{92 Key: k,93 Value: v,94 })95 }96 for _,report := range config.TestSuite.Reports {97 c.Reports = append(c.Reports,report)98 }99 c.VideoRecord = config.TestSuite.VideoRecord100}101// LoadTestSuiteConfiguration expect a testSuiteName file with format tosca-{testSuiteName}.json on workingDir102// parses the file and return TestSuiteConfiguration or TestCaseError103func LoadTestSuiteConfiguration(testSuitePath string,name string) (testSuite *TestSuiteConfiguration,err error) {104 testSuite = &TestSuiteConfiguration{105 Name: name,106 ResultFolder: defaultResultPath,107 Project: ProjectDefinition{108 SourcePath: defaultSourcePath,109 WorkspaceUsername: defaultToscaAdminUsername,110 },111 Agent: TestAgentConfiguration{},112 TestSuite: TestExecutionConfiguration{113 Parameters: entity.KeyValue{},114 Selectors: entity.KeyValue{},115 Timeout: defaultTimeout,116 VideoRecord: true,117 },118 }119 executionTypeFile, err := os.Open(testSuitePath)120 if err != nil {121 return nil,fmt.Errorf("error when opening TestExecutionConfiguration file: %s",err)122 }123 defer executionTypeFile.Close()124 executionTypeBytes, err := ioutil.ReadAll(executionTypeFile)125 if err!=nil{126 return nil,fmt.Errorf("error when reading execution type file: %s",err)127 }128 if err=json.Unmarshal(executionTypeBytes,&testSuite);err!=nil{129 return nil,fmt.Errorf("error when unmarshalling json from execution type file: %s",err)130 }131 return testSuite,nil132}133var logTestSuite *log.Entry134var logTestSuiteExecution *log.Entry135func (t *Provider) RunTestSuite(suiteConfig TestSuiteConfiguration,ctx context.Context) ( err error) {136 logTestSuite=log.WithField("testSuite",suiteConfig.Name)137 logTestSuite.Info("Preparing to execute Test Suite")138 logTestSuite.Debugf("Test Suite Configuration: %+v",suiteConfig)139 timeoutContext,_:=context.WithTimeout(ctx,suiteConfig.TestSuite.Timeout*time.Minute)140 buildDirPath :=path.Join(t.config.WorkingDir, suiteConfig.ResultFolder,suiteConfig.Name)141 _, err = os.Stat(buildDirPath)142 if !os.IsNotExist(err) {143 logTestSuite.Warnf("Build directory %s is not empty, deleting...",buildDirPath)144 if err:=os.RemoveAll(buildDirPath);err!=nil{145 return err146 }147 }148 executorSuiteConfig:= &TestExecutorConfiguration{149 buildDirectory: buildDirPath,150 xUnitPath: path.Join(buildDirPath,"junit"),151 artifactsPath: path.Join(buildDirPath,"Artifacts"),152 reportsPath: path.Join(buildDirPath,"Reports"),153 }154 if suiteConfig.Agent.Selectors!=nil && suiteConfig.Agent.Selectors.Length()>0 {155 agentController,err:=t.deployAgentNode(suiteConfig.Agent.Selectors,timeoutContext)156 if err!=nil {157 return err158 }159 //TODO set hostname160 executorSuiteConfig.hostname=agentController.hostname161 defer func(){162 if err2:=t.destroyAgentNode(agentController);err2!=nil{163 err=fmt.Errorf("error when destroying tosca agent: please remove it by hand, %v",err2)164 }165 }()166 //TODO get hostname and VM Controller167 }else{168 executorSuiteConfig.hostname=suiteConfig.Agent.Hostname169 }170 logTestSuite.Infof("Selected Node %s",suiteConfig.Agent.Hostname)171 logTestSuite.Infof("Preparing Workspace...")172 executorSuiteConfig.load(suiteConfig)173 executorSuiteConfig.workspace,err=t.prepareWorkspace(suiteConfig,timeoutContext)174 if err!=nil {175 return err176 }177 executorSuiteConfig.WorkspaceSessionID=executorSuiteConfig.workspace.SessionID178 logTestSuite.Debugf("Executor Suite Config: %+v",executorSuiteConfig)179 defer func(){180 logTestSuite.Infof("Deleting Workspace")181 if err2:=t.DeleteWorkspace(executorSuiteConfig,context.Background());err2!=nil{182 err=fmt.Errorf("error when deleting workspace: please remove it by hand, %v",err2)183 }184 }()185 logTestSuite.Infof("Workspace %s ready", executorSuiteConfig.workspace.SessionID)186 logTestSuite.Infof("Requesting Test %s on workspace %s",suiteConfig.Name,executorSuiteConfig.workspace.SessionID)187 if err := t.requestTestExecution(executorSuiteConfig, timeoutContext);err!=nil{188 return err189 }190 logTestSuite.Debugf("Execution Summary")191 for _,executionList := range executorSuiteConfig.executionLists {192 for _,entry := range executionList.Entries {193 logTestSuite.WithFields(log.Fields{194 "executionList":executionList.Name,195 "entry":entry}).196 Debugf("Execution Entry %s",entry)197 }198 }199 logTestSuiteExecution = logTestSuite.WithField("executionID",executorSuiteConfig.executionID)200 logTestSuiteExecution.Info("Test placed")201 if err := t.waitUntilCompletion(timeoutContext, executorSuiteConfig); err != nil {202 return err203 }204 logTestSuiteExecution.Infof("Test %s completed",suiteConfig.Name)205 logTestSuiteExecution.Infof("Downloading xunit results")206 testReports,errTestReport := t.getTestReports(executorSuiteConfig,timeoutContext)207 logTestSuiteExecution.Infof("Downloading artifacts")208 _,errArtifacts := t.getArtifacts(executorSuiteConfig,timeoutContext)209 logTestSuiteExecution.Infof("Downloading Reports")210 _,errReports := t.getReports(executorSuiteConfig,timeoutContext)211 if errTestReport != nil {212 return errTestReport213 }214 if errArtifacts != nil {215 return errArtifacts216 }217 if errReports != nil {218 return errReports219 }220 failedTests := testReports.GetNumberFailedTests()221 testsWithErrors := testReports.GetNumberErrorsTests()222 totalTests :=testReports.GetNumberTests()223 logTestSuiteExecution.Infof("%d test failed",failedTests)224 logTestSuiteExecution.Infof("%d tests with errors",testsWithErrors)225 logTestSuiteExecution.Infof("%d tests executed",totalTests)226 logTestSuiteExecution.Infof("results saved on %s",executorSuiteConfig.buildDirectory)227 if testReports.GetNumberFailedTests() > 0 {228 return TestsFailed229 }230 return nil231}232func (t *Provider) requestTestExecution(executorSuiteConfig *TestExecutorConfiguration, timeoutContext context.Context) error {233 err := retry.Do(func() error {234 return t.triggerExecution(executorSuiteConfig, timeoutContext)235 }, retry.RetryIf(func(err error) bool {236 if errors.Is(err,AlreadyRunningExecution) {237 logTestSuite.Warn("other execution still running, waiting for agent being free")238 return true239 }240 return false241 }), retry.Attempts(10000),retry.DelayType(retry.FixedDelay),retry.Delay(15*time.Second),retry.Context(timeoutContext))242 if err != nil {243 return err244 }245 return err246}247func (t *Provider) waitUntilCompletion(ctx context.Context, executorSuiteConfig *TestExecutorConfiguration) error {248 for {249 select {250 case <-ctx.Done():251 logTestSuiteExecution.Warnf("Canceling Test execution %s",executorSuiteConfig.executionID)252 if err:=t.cancelTestExecution(executorSuiteConfig);err!=nil{253 return err254 }255 return ctx.Err()256 case <-time.After(15 * time.Second):257 status, err := t.checkStatus(executorSuiteConfig, ctx)258 logTestSuiteExecution.Infof("%s state", status)259 switch status {260 case executionCompleted:261 return nil262 case executionFailed:263 return err264 }265 }266 }267 return nil268}269func (t *Provider) triggerExecution(testExecutorConfig *TestExecutorConfiguration,ctx context.Context) error {270 b,err:=json.Marshal(testExecutorConfig)271 if err!=nil{272 return err273 }274 executionURL,err:=t.getAgentURL(testExecutorConfig, APICreateExecution)275 if err!=nil{276 return err277 }278 logTestSuite.Debugf("Request Execution Payload: %+v",testExecutorConfig)279 req, err := http.NewRequestWithContext(ctx,"POST",executionURL , bytes.NewBuffer(b))280 if err!=nil{281 return err282 }283 if t.config.Username!="" && t.config.Password !=""{284 req.SetBasicAuth(t.config.Username,t.config.Password)285 }286 req.Header.Add("Content-Type", "application/json")287 client := &http.Client{}288 response,err:=client.Do(req)289 if err!=nil{290 return err291 }292 defer response.Body.Close()293 byteResponse,err :=ioutil.ReadAll(response.Body)294 if err!=nil {295 return err296 }297 if response.StatusCode == http.StatusConflict {298 return AlreadyRunningExecution299 }else if response.StatusCode != http.StatusAccepted {300 return fmt.Errorf("error %s statusCode %d",string(byteResponse),response.StatusCode)301 }302 executionResponse:= &TestExecutionResponse{}303 if err:=json.Unmarshal(byteResponse,executionResponse);err!=nil {304 return err305 }306 if executionResponse.Error !=""{307 return fmt.Errorf(executionResponse.Error)308 }309 testExecutorConfig.executionID = executionResponse.ExecutionID310 testExecutorConfig.executionLists = executionResponse.ExecutionLists311 return nil312}313func (t *Provider) getArtifacts(testExecutorConfig *TestExecutorConfiguration,ctx context.Context) ([]string,error) {314 return t.getToscaFiles(testExecutorConfig,APIExecutionArtifactList,APIExecutionArtifact,testExecutorConfig.artifactsPath,ctx)315}316func (t *Provider) getReports(testExecutorConfig *TestExecutorConfiguration,ctx context.Context) ([]string,error) {317 return t.getToscaFiles(testExecutorConfig,APIExecutionReportList,APIExecutionReport,testExecutorConfig.reportsPath,ctx)318}319func (t *Provider) getTestReports(testExecutorConfig *TestExecutorConfiguration,ctx context.Context) (test.TestResults,error) {320 testResults := test.TestResults{}321 testResultFiles,err:=t.getToscaFiles(testExecutorConfig,APIExecutionXUnitList,APIExecutionXUnit,testExecutorConfig.xUnitPath,ctx)322 if err!=nil {323 return nil,err324 }325 var now = time.Now()326 var now_s = now.Format(time.RFC3339)327 for _, testResultFile := range testResultFiles{328 testResult, err := test.ReadTestResults(testResultFile)329 if err!=nil {330 return nil,err331 }332 // Fix missing timestamp (prior to Tosca 15.0)333 err = test.PatchMissingTimestamp(now_s, testResult, testResultFile)334 if err != nil {335 return nil,err336 }337 testResults = append(testResults,testResult)338 }339 return testResults,nil340}341func (t *Provider) getToscaFiles(testExecutorConfig *TestExecutorConfiguration,urlBase string,urldownload string,outputPath string,ctx context.Context) ([]string,error) {342 var toscaFiles []string343 reportListURL,err:=t.getAgentURL(testExecutorConfig,fmt.Sprintf(urlBase,testExecutorConfig.executionID))344 log.Debugf("Get Tosca Files Request %s",reportListURL)345 if err!=nil{346 return nil,err347 }348 req, err := http.NewRequestWithContext(ctx,"GET",reportListURL,nil)349 if err!=nil{350 return nil,err351 }352 req.Header.Add("Content-Type", "application/json")353 client := &http.Client{}354 resp,err:=client.Do(req)355 if err!=nil{356 return nil,err357 }358 defer resp.Body.Close()359 if resp.StatusCode!=http.StatusOK {360 return nil,fmt.Errorf("error when recovering Reports %s",resp.Status)361 }362 byteResponse,err:=ioutil.ReadAll(resp.Body)363 if err!=nil{364 return nil,err365 }366 executionResponse:= &TestExecutionResponse{}367 log.Debugf("Get Tosca Files Response %s",string(byteResponse))368 if err:=json.Unmarshal(byteResponse,executionResponse);err!=nil {369 return nil,err370 }371 if executionResponse.Error !=""{372 return nil,fmt.Errorf(executionResponse.Error)373 }374 logTestSuite.Infof("%d files found",len(executionResponse.Files))375 for _,file := range executionResponse.Files {376 logTestSuite.WithField("file",file.Path).Info("Downloading...")377 downloadURL,err:=t.getAgentURL(testExecutorConfig,fmt.Sprintf(urldownload,testExecutorConfig.executionID,file.Id))378 if err!=nil{379 return nil,err380 }381 filePath := path.Join(outputPath,file.Path)382 err=helper.DownloadFile(downloadURL,filePath,ctx)383 toscaFiles = append(toscaFiles,filePath)384 }385 return toscaFiles,nil386}387type agentController struct {388 hostname string389}390func (t *Provider) deployAgentNode(selector entity.KeyValue,ctx context.Context) (agentController,error) {391 //Tod@392 return agentController{},nil393}394func (t *Provider) prepareWorkspace(testSuiteConfig TestSuiteConfiguration,ctx context.Context) (*Workspace,error) {395 templateType:= CreatefromDefinition396 if testSuiteConfig.Project.SourceConnectionStringDB!=""{397 templateType = CreateFromDatabase398 }399 rand.Seed(time.Now().UnixNano())400 rndNumber := rand.Intn(1000 - 1) + 1401 workspace,err :=t.createProject(ProjectCreateRequest{402 SourcePath: testSuiteConfig.Project.SourcePath,403 Name: fmt.Sprintf("%s%d",testSuiteConfig.Name,rndNumber),404 TemplateType: templateType,405 TemplateConnectionString: testSuiteConfig.Project.SourceConnectionStringDB,406 TemplateConnectionUsername: testSuiteConfig.Project.WorkspaceUsername,407 TemplateConnectionPassword: testSuiteConfig.Project.WorkspacePassword,408 DBType: LocalDB,409 },testSuiteConfig.Agent.Hostname,ctx)410 if err!=nil {411 return nil,err412 }413 return workspace,nil414}415func (t *Provider) checkStatus(config *TestExecutorConfiguration,ctx context.Context) (ExecutionStatus,error) {416 executionStatusURL,err:=t.getAgentURL(config,fmt.Sprintf(APIExecution,config.executionID))417 if err!=nil{418 return executionFailed,err419 }420 logTestSuite.Debugf("Request Execution Status: %s",executionStatusURL)421 req, err := http.NewRequestWithContext(ctx,"GET", executionStatusURL,nil)422 if err!=nil{423 return executionFailed,err424 }425 req.Header.Add("Content-Type", "application/json")426 client := &http.Client{}427 response,err:=client.Do(req)428 if err!=nil{429 return executionFailed,err430 }431 defer response.Body.Close()432 byteResponse,err :=ioutil.ReadAll(response.Body)433 if err!=nil {434 return executionFailed,err435 }436 logTestSuite.Debugf("Response Execution Status: %s",string(byteResponse))437 if response.StatusCode == http.StatusNotFound {438 return executionFailed,fmt.Errorf("execution not found, agent probably dead")439 }else if response.StatusCode!=http.StatusOK {440 return "",fmt.Errorf(string(byteResponse))441 }442 executionResponse:= &TestExecutionResponse{}443 if err:=json.Unmarshal(byteResponse,executionResponse);err!=nil {444 return "",err445 }446 if executionResponse.Error !=""{447 return executionFailed,fmt.Errorf(executionResponse.Error)448 }449 return executionResponse.Status,nil450}451func (t *Provider) destroyAgentNode(controller agentController) error {452 //TODO453 return nil454}455func (t *Provider) cancelTestExecution(config *TestExecutorConfiguration) error {456 cancelExecutionURL, err := t.getAgentURL(config, fmt.Sprintf(APIExecution, config.executionID))457 if err != nil {458 return err459 }460 logTestSuite.Debugf("Request Cancel Execution: %s",cancelExecutionURL)461 req, err := http.NewRequest("DELETE", cancelExecutionURL, nil)462 if err != nil {463 return err464 }465 client := &http.Client{}466 response, err := client.Do(req)467 if err != nil {468 return err469 }470 defer response.Body.Close()471 if response.StatusCode != http.StatusOK {472 return fmt.Errorf("error: %d (%s) when canceling execution %s",response.StatusCode,response.Status,config.executionID)473 }474 return nil...
operationModeValidator_test.go
Source:operationModeValidator_test.go
...33 validateOperationWorkflowModeStateSuite struct {34 suite.Suite35 }36)37func TestValidateOperationWorkflowModeStateSuite(t *testing.T) {38 s := new(validateOperationWorkflowModeStateSuite)39 suite.Run(t, s)40}41func (s *validateOperationWorkflowModeStateSuite) SetupSuite() {42}43func (s *validateOperationWorkflowModeStateSuite) TearDownSuite() {44}45func (s *validateOperationWorkflowModeStateSuite) SetupTest() {46}47func (s *validateOperationWorkflowModeStateSuite) TearDownTest() {48}49func (s *validateOperationWorkflowModeStateSuite) TestCreateMode_UpdateCurrent() {50 stateToError := map[enumsspb.WorkflowExecutionState]bool{51 enumsspb.WORKFLOW_EXECUTION_STATE_CREATED: false,52 enumsspb.WORKFLOW_EXECUTION_STATE_RUNNING: false,53 enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED: false,54 enumsspb.WORKFLOW_EXECUTION_STATE_ZOMBIE: true,55 }56 creatModes := []CreateWorkflowMode{57 CreateWorkflowModeBrandNew,58 CreateWorkflowModeUpdateCurrent,59 }60 for state, expectError := range stateToError {61 testSnapshot := s.newTestWorkflowSnapshot(state)62 for _, createMode := range creatModes {63 err := ValidateCreateWorkflowModeState(createMode, testSnapshot)64 if !expectError {65 s.NoError(err, err)66 } else {67 s.Error(err, err)68 }69 }70 }71}72func (s *validateOperationWorkflowModeStateSuite) TestCreateMode_BypassCurrent() {73 stateToError := map[enumsspb.WorkflowExecutionState]bool{74 enumsspb.WORKFLOW_EXECUTION_STATE_CREATED: true,75 enumsspb.WORKFLOW_EXECUTION_STATE_RUNNING: true,76 enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED: false,77 enumsspb.WORKFLOW_EXECUTION_STATE_ZOMBIE: false,78 }79 for state, expectError := range stateToError {80 testSnapshot := s.newTestWorkflowSnapshot(state)81 err := ValidateCreateWorkflowModeState(CreateWorkflowModeBypassCurrent, testSnapshot)82 if !expectError {83 s.NoError(err, err)84 } else {85 s.Error(err, err)86 }87 }88}89func (s *validateOperationWorkflowModeStateSuite) TestUpdateMode_UpdateCurrent() {90 // only current workflow91 stateToError := map[enumsspb.WorkflowExecutionState]bool{92 enumsspb.WORKFLOW_EXECUTION_STATE_CREATED: false,93 enumsspb.WORKFLOW_EXECUTION_STATE_RUNNING: false,94 enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED: false,95 enumsspb.WORKFLOW_EXECUTION_STATE_ZOMBIE: true,96 }97 for state, expectError := range stateToError {98 testCurrentMutation := s.newTestWorkflowMutation(state)99 err := ValidateUpdateWorkflowModeState(100 UpdateWorkflowModeUpdateCurrent,101 testCurrentMutation,102 nil,103 )104 if !expectError {105 s.NoError(err, err)106 } else {107 s.Error(err, err)108 }109 }110 // current workflow & new workflow111 currentStateToError := map[enumsspb.WorkflowExecutionState]bool{112 enumsspb.WORKFLOW_EXECUTION_STATE_CREATED: true,113 enumsspb.WORKFLOW_EXECUTION_STATE_RUNNING: true,114 enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED: false,115 enumsspb.WORKFLOW_EXECUTION_STATE_ZOMBIE: false,116 }117 newStateToError := map[enumsspb.WorkflowExecutionState]bool{118 enumsspb.WORKFLOW_EXECUTION_STATE_CREATED: false,119 enumsspb.WORKFLOW_EXECUTION_STATE_RUNNING: false,120 enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED: true,121 enumsspb.WORKFLOW_EXECUTION_STATE_ZOMBIE: true,122 }123 for currentState, currentExpectError := range currentStateToError {124 for newState, newExpectError := range newStateToError {125 testCurrentMutation := s.newTestWorkflowMutation(currentState)126 testNewSnapshot := s.newTestWorkflowSnapshot(newState)127 err := ValidateUpdateWorkflowModeState(128 UpdateWorkflowModeUpdateCurrent,129 testCurrentMutation,130 &testNewSnapshot,131 )132 if currentExpectError || newExpectError {133 s.Error(err, err)134 } else {135 s.NoError(err, err)136 }137 }138 }139}140func (s *validateOperationWorkflowModeStateSuite) TestUpdateMode_BypassCurrent() {141 // only current workflow142 stateToError := map[enumsspb.WorkflowExecutionState]bool{143 enumsspb.WORKFLOW_EXECUTION_STATE_CREATED: true,144 enumsspb.WORKFLOW_EXECUTION_STATE_RUNNING: true,145 enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED: false,146 enumsspb.WORKFLOW_EXECUTION_STATE_ZOMBIE: false,147 }148 for state, expectError := range stateToError {149 testMutation := s.newTestWorkflowMutation(state)150 err := ValidateUpdateWorkflowModeState(151 UpdateWorkflowModeBypassCurrent,152 testMutation,153 nil,154 )155 if !expectError {156 s.NoError(err, err)157 } else {158 s.Error(err, err)159 }160 }161 // current workflow & new workflow162 currentStateToError := map[enumsspb.WorkflowExecutionState]bool{163 enumsspb.WORKFLOW_EXECUTION_STATE_CREATED: true,164 enumsspb.WORKFLOW_EXECUTION_STATE_RUNNING: true,165 enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED: false,166 enumsspb.WORKFLOW_EXECUTION_STATE_ZOMBIE: false,167 }168 newStateToError := map[enumsspb.WorkflowExecutionState]bool{169 enumsspb.WORKFLOW_EXECUTION_STATE_CREATED: true,170 enumsspb.WORKFLOW_EXECUTION_STATE_RUNNING: true,171 enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED: true,172 enumsspb.WORKFLOW_EXECUTION_STATE_ZOMBIE: false,173 }174 for currentState, currentExpectError := range currentStateToError {175 for newState, newExpectError := range newStateToError {176 testCurrentMutation := s.newTestWorkflowMutation(currentState)177 testNewSnapshot := s.newTestWorkflowSnapshot(newState)178 err := ValidateUpdateWorkflowModeState(179 UpdateWorkflowModeBypassCurrent,180 testCurrentMutation,181 &testNewSnapshot,182 )183 if currentExpectError || newExpectError {184 s.Error(err, err)185 } else {186 s.NoError(err, err)187 }188 }189 }190}191func (s *validateOperationWorkflowModeStateSuite) TestConflictResolveMode_UpdateCurrent() {192 // only reset workflow193 stateToError := map[enumsspb.WorkflowExecutionState]bool{194 enumsspb.WORKFLOW_EXECUTION_STATE_CREATED: false,195 enumsspb.WORKFLOW_EXECUTION_STATE_RUNNING: false,196 enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED: false,197 enumsspb.WORKFLOW_EXECUTION_STATE_ZOMBIE: true,198 }199 for state, expectError := range stateToError {200 testSnapshot := s.newTestWorkflowSnapshot(state)201 err := ValidateConflictResolveWorkflowModeState(202 ConflictResolveWorkflowModeUpdateCurrent,203 testSnapshot,204 nil,205 nil,206 )207 if !expectError {208 s.NoError(err, err)209 } else {210 s.Error(err, err)211 }212 }213 // reset workflow & new workflow214 resetStateToError := map[enumsspb.WorkflowExecutionState]bool{215 enumsspb.WORKFLOW_EXECUTION_STATE_CREATED: true,216 enumsspb.WORKFLOW_EXECUTION_STATE_RUNNING: true,217 enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED: false,218 enumsspb.WORKFLOW_EXECUTION_STATE_ZOMBIE: true,219 }220 newStateToError := map[enumsspb.WorkflowExecutionState]bool{221 enumsspb.WORKFLOW_EXECUTION_STATE_CREATED: false,222 enumsspb.WORKFLOW_EXECUTION_STATE_RUNNING: false,223 enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED: true,224 enumsspb.WORKFLOW_EXECUTION_STATE_ZOMBIE: true,225 }226 for resetState, resetExpectError := range resetStateToError {227 for newState, newExpectError := range newStateToError {228 testResetSnapshot := s.newTestWorkflowSnapshot(resetState)229 testNewSnapshot := s.newTestWorkflowSnapshot(newState)230 err := ValidateConflictResolveWorkflowModeState(231 ConflictResolveWorkflowModeUpdateCurrent,232 testResetSnapshot,233 &testNewSnapshot,234 nil,235 )236 if resetExpectError || newExpectError {237 s.Error(err, err)238 } else {239 s.NoError(err, err)240 }241 }242 }243 // reset workflow & current workflow244 resetStateToError = map[enumsspb.WorkflowExecutionState]bool{245 enumsspb.WORKFLOW_EXECUTION_STATE_CREATED: false,246 enumsspb.WORKFLOW_EXECUTION_STATE_RUNNING: false,247 enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED: false,248 enumsspb.WORKFLOW_EXECUTION_STATE_ZOMBIE: true,249 }250 currentStateToError := map[enumsspb.WorkflowExecutionState]bool{251 enumsspb.WORKFLOW_EXECUTION_STATE_CREATED: true,252 enumsspb.WORKFLOW_EXECUTION_STATE_RUNNING: true,253 enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED: false,254 enumsspb.WORKFLOW_EXECUTION_STATE_ZOMBIE: false,255 }256 for resetState, resetExpectError := range resetStateToError {257 for currentState, currentExpectError := range currentStateToError {258 testResetSnapshot := s.newTestWorkflowSnapshot(resetState)259 testCurrentSnapshot := s.newTestWorkflowMutation(currentState)260 err := ValidateConflictResolveWorkflowModeState(261 ConflictResolveWorkflowModeUpdateCurrent,262 testResetSnapshot,263 nil,264 &testCurrentSnapshot,265 )266 if resetExpectError || currentExpectError {267 s.Error(err, err)268 } else {269 s.NoError(err, err)270 }271 }272 }273 // reset workflow & new workflow & current workflow274 resetStateToError = map[enumsspb.WorkflowExecutionState]bool{275 enumsspb.WORKFLOW_EXECUTION_STATE_CREATED: true,276 enumsspb.WORKFLOW_EXECUTION_STATE_RUNNING: true,277 enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED: false,278 enumsspb.WORKFLOW_EXECUTION_STATE_ZOMBIE: true,279 }280 newStateToError = map[enumsspb.WorkflowExecutionState]bool{281 enumsspb.WORKFLOW_EXECUTION_STATE_CREATED: false,282 enumsspb.WORKFLOW_EXECUTION_STATE_RUNNING: false,283 enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED: true,284 enumsspb.WORKFLOW_EXECUTION_STATE_ZOMBIE: true,285 }286 currentStateToError = map[enumsspb.WorkflowExecutionState]bool{287 enumsspb.WORKFLOW_EXECUTION_STATE_CREATED: true,288 enumsspb.WORKFLOW_EXECUTION_STATE_RUNNING: true,289 enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED: false,290 enumsspb.WORKFLOW_EXECUTION_STATE_ZOMBIE: false,291 }292 for resetState, resetExpectError := range resetStateToError {293 for newState, newExpectError := range newStateToError {294 for currentState, currentExpectError := range currentStateToError {295 testResetSnapshot := s.newTestWorkflowSnapshot(resetState)296 testNewSnapshot := s.newTestWorkflowSnapshot(newState)297 testCurrentSnapshot := s.newTestWorkflowMutation(currentState)298 err := ValidateConflictResolveWorkflowModeState(299 ConflictResolveWorkflowModeUpdateCurrent,300 testResetSnapshot,301 &testNewSnapshot,302 &testCurrentSnapshot,303 )304 if resetExpectError || newExpectError || currentExpectError {305 s.Error(err, err)306 } else {307 s.NoError(err, err)308 }309 }310 }311 }312}313func (s *validateOperationWorkflowModeStateSuite) TestConflictResolveMode_BypassCurrent() {314 // only reset workflow315 stateToError := map[enumsspb.WorkflowExecutionState]bool{316 enumsspb.WORKFLOW_EXECUTION_STATE_CREATED: true,317 enumsspb.WORKFLOW_EXECUTION_STATE_RUNNING: true,318 enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED: false,319 enumsspb.WORKFLOW_EXECUTION_STATE_ZOMBIE: false,320 }321 for state, expectError := range stateToError {322 testSnapshot := s.newTestWorkflowSnapshot(state)323 err := ValidateConflictResolveWorkflowModeState(324 ConflictResolveWorkflowModeBypassCurrent,325 testSnapshot,326 nil,327 nil,328 )329 if !expectError {330 s.NoError(err, err)331 } else {332 s.Error(err, err)333 }334 }335 // reset workflow & new workflow336 resetStateToError := map[enumsspb.WorkflowExecutionState]bool{337 enumsspb.WORKFLOW_EXECUTION_STATE_CREATED: true,338 enumsspb.WORKFLOW_EXECUTION_STATE_RUNNING: true,339 enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED: false,340 enumsspb.WORKFLOW_EXECUTION_STATE_ZOMBIE: true,341 }342 newStateToError := map[enumsspb.WorkflowExecutionState]bool{343 enumsspb.WORKFLOW_EXECUTION_STATE_CREATED: true,344 enumsspb.WORKFLOW_EXECUTION_STATE_RUNNING: true,345 enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED: true,346 enumsspb.WORKFLOW_EXECUTION_STATE_ZOMBIE: false,347 }348 for resetState, resetExpectError := range resetStateToError {349 for newState, newExpectError := range newStateToError {350 testResetSnapshot := s.newTestWorkflowSnapshot(resetState)351 testNewSnapshot := s.newTestWorkflowSnapshot(newState)352 err := ValidateConflictResolveWorkflowModeState(353 ConflictResolveWorkflowModeBypassCurrent,354 testResetSnapshot,355 &testNewSnapshot,356 nil,357 )358 if resetExpectError || newExpectError {359 if err == nil {360 fmt.Print("##")361 }362 s.Error(err, err)363 } else {364 s.NoError(err, err)365 }366 }367 }368}369func (s *validateOperationWorkflowModeStateSuite) newTestWorkflowSnapshot(370 state enumsspb.WorkflowExecutionState,371) WorkflowSnapshot {372 return WorkflowSnapshot{373 ExecutionInfo: &persistencespb.WorkflowExecutionInfo{},374 ExecutionState: &persistencespb.WorkflowExecutionState{State: state},375 }376}377func (s *validateOperationWorkflowModeStateSuite) newTestWorkflowMutation(378 state enumsspb.WorkflowExecutionState,379) WorkflowMutation {380 return WorkflowMutation{381 ExecutionInfo: &persistencespb.WorkflowExecutionInfo{},382 ExecutionState: &persistencespb.WorkflowExecutionState{State: state},383 }384}...
execution_cache_store_test.go
Source:execution_cache_store_test.go
...28 StartedAtInSec: 1,29 EndedAtInSec: 1,30 }31}32func TestCreateExecutionCache(t *testing.T) {33 db := NewFakeDbOrFatal()34 defer db.Close()35 executionCacheStore := NewExecutionCacheStore(db, util.NewFakeTimeForEpoch())36 executionCacheExpected := model.ExecutionCache{37 ID: 1,38 ExecutionCacheKey: "test",39 ExecutionTemplate: "testTemplate",40 ExecutionOutput: "testOutput",41 MaxCacheStaleness: -1,42 StartedAtInSec: 1,43 EndedAtInSec: 1,44 }45 executionCache := &model.ExecutionCache{46 ExecutionCacheKey: "test",47 ExecutionTemplate: "testTemplate",48 ExecutionOutput: "testOutput",49 MaxCacheStaleness: -1,50 }51 executionCache, err := executionCacheStore.CreateExecutionCache(executionCache)52 assert.Nil(t, err)53 require.Equal(t, executionCacheExpected, *executionCache)54}55func TestCreateExecutionCacheWithDuplicateRecord(t *testing.T) {56 executionCache := &model.ExecutionCache{57 ID: 1,58 ExecutionCacheKey: "test",59 ExecutionTemplate: "testTemplate",60 ExecutionOutput: "testOutput",61 MaxCacheStaleness: -1,62 StartedAtInSec: 1,63 EndedAtInSec: 1,64 }65 db := NewFakeDbOrFatal()66 defer db.Close()67 executionCacheStore := NewExecutionCacheStore(db, util.NewFakeTimeForEpoch())68 executionCacheStore.CreateExecutionCache(executionCache)69 cache, err := executionCacheStore.CreateExecutionCache(executionCache)70 assert.Nil(t, cache)71 assert.Contains(t, err.Error(), "Failed to create a new execution cache")72}73func TestGetExecutionCache(t *testing.T) {74 db := NewFakeDbOrFatal()75 defer db.Close()76 executionCacheStore := NewExecutionCacheStore(db, util.NewFakeTimeForEpoch())77 executionCacheStore.CreateExecutionCache(createExecutionCache("testKey", "testOutput"))78 executionCacheExpected := model.ExecutionCache{79 ID: 1,80 ExecutionCacheKey: "testKey",81 ExecutionTemplate: "testTemplate",82 ExecutionOutput: "testOutput",83 MaxCacheStaleness: -1,84 StartedAtInSec: 1,85 EndedAtInSec: 1,86 }87 var executionCache *model.ExecutionCache88 executionCache, err := executionCacheStore.GetExecutionCache("testKey", -1)89 require.Nil(t, err)90 require.Equal(t, &executionCacheExpected, executionCache)91}92func TestGetExecutionCacheWithEmptyCacheEntry(t *testing.T) {93 db := NewFakeDbOrFatal()94 defer db.Close()95 executionCacheStore := NewExecutionCacheStore(db, util.NewFakeTimeForEpoch())96 executionCacheStore.CreateExecutionCache(createExecutionCache("testKey", "testOutput"))97 var executionCache *model.ExecutionCache98 executionCache, err := executionCacheStore.GetExecutionCache("wrongKey", -1)99 require.Nil(t, executionCache)100 require.Contains(t, err.Error(), `Execution cache not found with cache key: "wrongKey"`)101}102func TestGetExecutionCacheWithLatestCacheEntry(t *testing.T) {103 db := NewFakeDbOrFatal()104 defer db.Close()105 executionCacheStore := NewExecutionCacheStore(db, util.NewFakeTimeForEpoch())106 executionCacheStore.CreateExecutionCache(createExecutionCache("testKey", "testOutput"))107 executionCacheStore.CreateExecutionCache(createExecutionCache("testKey", "testOutput2"))108 executionCacheExpected := model.ExecutionCache{109 ID: 2,110 ExecutionCacheKey: "testKey",111 ExecutionTemplate: "testTemplate",112 ExecutionOutput: "testOutput2",113 MaxCacheStaleness: -1,114 StartedAtInSec: 2,115 EndedAtInSec: 2,116 }117 var executionCache *model.ExecutionCache118 executionCache, err := executionCacheStore.GetExecutionCache("testKey", -1)119 require.Nil(t, err)120 require.Equal(t, &executionCacheExpected, executionCache)121}122func TestGetExecutionCacheWithExpiredMaxCacheStaleness(t *testing.T) {123 db := NewFakeDbOrFatal()124 defer db.Close()125 executionCacheStore := NewExecutionCacheStore(db, util.NewFakeTimeForEpoch())126 executionCacheToPersist := &model.ExecutionCache{127 ExecutionCacheKey: "testKey",128 ExecutionTemplate: "testTemplate",129 ExecutionOutput: "testOutput",130 MaxCacheStaleness: 0,131 }132 executionCacheStore.CreateExecutionCache(executionCacheToPersist)133 var executionCache *model.ExecutionCache134 executionCache, err := executionCacheStore.GetExecutionCache("testKey", -1)135 require.Contains(t, err.Error(), "Execution cache not found")136 require.Nil(t, executionCache)137}138func TestDeleteExecutionCache(t *testing.T) {139 db := NewFakeDbOrFatal()140 defer db.Close()141 executionCacheStore := NewExecutionCacheStore(db, util.NewFakeTimeForEpoch())142 executionCacheStore.CreateExecutionCache(createExecutionCache("testKey", "testOutput"))143 executionCache, err := executionCacheStore.GetExecutionCache("testKey", -1)144 assert.Nil(t, err)145 assert.NotNil(t, executionCache)146 err = executionCacheStore.DeleteExecutionCache("1")147 assert.Nil(t, err)148 _, err = executionCacheStore.GetExecutionCache("testKey", -1)149 assert.NotNil(t, err)150 assert.Contains(t, err.Error(), "not found")151}...
Test
Using AI Code Generation
1import (2type execution struct {3}4func (e execution) Test() {5 fmt.Println("Name is:", e.name)6 fmt.Println("Age is:", e.age)7}8func main() {9 e := execution{"John", 20}10 e.Test()11}12import (13type execution struct {14}15func (e execution) Test(name string, age int) {16 fmt.Println("Name is:", name)17 fmt.Println("Age is:", age)18}19func main() {20 e := execution{"John", 20}21 e.Test("John", 20)22}23import (24type execution struct {25}26func (e execution) Test(name string, age int) (string, int) {27}28func main() {29 e := execution{"John", 20}30 name, age := e.Test("John", 20)31 fmt.Println("Name is:", name)32 fmt.Println("Age is:", age)33}34import (
Test
Using AI Code Generation
1import (2func Test(t *testing.T) {3 fmt.Println("Hello World")4}5func main() {6 fmt.Println("Hello World")7}8import (9func TestMain(m *testing.M) {10 fmt.Println("Hello World")11}12func main() {13 fmt.Println("Hello World")14}15import (16func Test(t *testing.T) {17 fmt.Println("Hello World")18}19func main() {20 fmt.Println("Hello World")21}22import (23func TestMain(m *testing.M) {24 fmt.Println("Hello World")25}26func main() {27 fmt.Println("Hello World")28}29import (30func Test(t *testing.T) {31 fmt.Println("Hello World")32}33func main() {34 fmt.Println("Hello World")35}36import (37func TestMain(m *testing.M) {38 fmt.Println("Hello World")39}40func main() {41 fmt.Println("Hello World")42}43import (44func Test(t *testing.T) {45 fmt.Println("Hello World")46}47func main() {48 fmt.Println("Hello World")49}
Test
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, playground")4 fmt.Println(execution.Test())5}6import "fmt"7func Test() string {8 return fmt.Sprint("Test")9}10import (11func main() {12 fmt.Println("Hello, playground")13 fmt.Println(execution.Test())14}15import (16func main() {17 fmt.Println("Hello, playground")18 fmt.Println(execution.Test())19}
Test
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, playground")4 e := execution{}5 e.Test()6}7import (8type execution struct {9}10func (e execution) Test() {11 fmt.Println("test method of execution class")12}13func main() {14 fmt.Println("Hello, playground")15 e := execution{}16 e.Test()17}18import (19type execution struct {20}21func (e execution) Test() {22 fmt.Println("test method of execution class")23}24func main() {25 fmt.Println("Hello, playground")26 e := execution{}27 e.Test()28 e.Test()29}30import (31type execution struct {32}33func (e execution) Test() {34 fmt.Println("test method of execution class")35}36func main() {37 fmt.Println("Hello, playground")38 e := execution{}39 e.Test()40 e.Test()41 e.Test()42}
Test
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, playground")4}5func Test(t *testing.T) {6 fmt.Println("Test method called")7}8import (9func main() {10 fmt.Println("Hello, playground")11}12func Test(t *testing.T) {13 fmt.Println("Test method called")14}15import (16func main() {17 fmt.Println("Hello, playground")18}19func Test(t *testing.T) {20 fmt.Println("Test method called")21}
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!