From c95c0ac8eb4ef9cdf3c85f3debcfc23499c72e6c Mon Sep 17 00:00:00 2001 From: zhongjie-cai Date: Fri, 15 Nov 2024 22:04:01 +0800 Subject: [PATCH] Upgrade dependency and adjust tests --- .devcontainer/devcontainer.json | 55 +- .devcontainer/docker-compose.yaml | 8 +- .github/workflows/ci.yaml | 63 ++ .gitignore | 2 + .travis.yml | 8 - 0_functionPointers.go | 162 --- 0_functionPointers_test.go | 1123 -------------------- application.go | 70 +- application_test.go | 817 ++++----------- customization.go | 13 +- customization_test.go | 235 +---- go.mod | 12 +- go.sum | 13 + handler.go | 25 +- handler_test.go | 379 ++----- jsonutil.go | 32 +- jsonutil_test.go | 426 +------- logLevel_test.go | 24 - logType.go | 11 +- logType_test.go | 118 --- logger.go | 32 +- logger_test.go | 501 ++++----- pointerutil.go | 2 +- pointerutil_test.go | 51 +- schedule.go | 24 +- scheduleMaker.go | 80 +- scheduleMaker_test.go | 1619 ++++++++--------------------- schedule_test.go | 803 +++++--------- session.go | 34 +- session_test.go | 407 ++------ timeutil.go | 12 +- timeutil_test.go | 67 -- webRequest.go | 109 +- webRequest_test.go | 1111 ++++---------------- 34 files changed, 1856 insertions(+), 6592 deletions(-) create mode 100644 .github/workflows/ci.yaml delete mode 100644 .travis.yml delete mode 100644 0_functionPointers.go delete mode 100644 0_functionPointers_test.go diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 8173c52..6e86eff 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -6,33 +6,40 @@ "service": "jobrunner_code", "shutdownAction": "stopCompose", - // Set *default* container specific settings.json values on container create. - "settings": { - "go.toolsManagement.checkForUpdates": "local", - "go.useLanguageServer": true, - "go.gopath": "/go", - "go.goroot": "/usr/local/go", - "go.toolsGopath": "/go/bin", - "go.buildOnSave": "package", - "go.testOnSave": true, - "go.coverOnTestPackage": true, - "go.coverageDecorator": { - "type": "gutter", - "coveredHighlightColor": "rgba(64,128,128,0.5)", - "uncoveredHighlightColor": "rgba(128,64,64,0.25)", - "coveredGutterStyle": "blockgreen", - "uncoveredGutterStyle": "blockred" - }, - "go.coverOnSingleTest": true, - "go.coverOnSave": true, - "go.testFlags": ["-short"] + "customizations": { + "vscode": { + // Set *default* container specific settings.json values on container create. + "settings": { + "go.toolsManagement.checkForUpdates": "local", + "go.useLanguageServer": true, + "go.gopath": "/go", + "go.goroot": "/usr/local/go", + "go.toolsGopath": "/go/bin", + "go.testOnSave": true, + "go.coverOnTestPackage": true, + "go.coverageDecorator": { + "type": "gutter", + "coveredHighlightColor": "rgba(64,128,128,0.5)", + "uncoveredHighlightColor": "rgba(128,64,64,0.25)", + "coveredGutterStyle": "blockgreen", + "uncoveredGutterStyle": "blockred" + }, + "go.coverOnSingleTest": true, + "go.coverOnSave": true, + "go.testFlags": ["-short", "-gcflags=all=-l"] + }, + + // Add the IDs of extensions you want installed when the container is created. + "extensions": [ + "golang.Go", + "eamodio.gitlens", + "yzhang.markdown-all-in-one" + ] + } }, // Mount to proper location - "workspaceFolder": "/go/src/github.com/zhongjie-cai/job-runner", - - // Add the IDs of extensions you want installed when the container is created. - "extensions": ["golang.Go", "eamodio.gitlens", "yzhang.markdown-all-in-one"] + "workspaceFolder": "/go/src/github.com/zhongjie-cai/job-runner" // Use 'forwardPorts' to make a list of ports inside the container available locally. // "forwardPorts": [], diff --git a/.devcontainer/docker-compose.yaml b/.devcontainer/docker-compose.yaml index 224145d..77a3beb 100644 --- a/.devcontainer/docker-compose.yaml +++ b/.devcontainer/docker-compose.yaml @@ -1,11 +1,9 @@ -version: '3.3' +version: "3.3" services: jobrunner_code: - build: - context: . - dockerfile: ./Dockerfile - container_name: 'jobrunner_code' + image: mcr.microsoft.com/vscode/devcontainers/go:1.23 + container_name: "jobrunner_code" volumes: # Mounts the project folder to '/workspace'. The target path inside the container # should match what your application expects. In this case, the compose file is diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml new file mode 100644 index 0000000..5788607 --- /dev/null +++ b/.github/workflows/ci.yaml @@ -0,0 +1,63 @@ +name: CI # The name of the workflow that will appear on Github + +on: + push: + branches: [master] + pull_request: + branches: [master] + # Allows you to run this workflow manually from the Actions tab + workflow_dispatch: + +jobs: + build: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest, windows-latest] + go: [1.23] + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + fetch-depth: 0 + + - name: Setup Go + uses: actions/setup-go@v4 + with: + go-version: ${{ matrix.go }} + + - name: Build + run: go install + + - name: Run Test + run: | + go test -gcflags=all=-l -v ./... -covermode=count -coverprofile='coverage.out' + go tool cover -func='coverage.out' -o='coverage.out' + + - name: Go Coverage Badge # Pass the `coverage.out` output to this action + uses: tj-actions/coverage-badge-go@v2 + if: ${{ runner.os == 'Linux' && matrix.go == '1.23' }} # Runs this on only one of the ci builds. + with: + green: 100 + filename: coverage.out + + - name: Verify Changed files + uses: tj-actions/verify-changed-files@v16 + id: verify-changed-files + with: + files: README.md + + - name: Commit changes + if: steps.verify-changed-files.outputs.files_changed == 'true' + run: | + git config --local user.email "action@github.com" + git config --local user.name "GitHub Action" + git add README.md + git commit -m "chore: Updated coverage badge." + + - name: Push changes + if: steps.verify-changed-files.outputs.files_changed == 'true' + uses: ad-m/github-push-action@master + with: + github_token: ${{ github.token }} + branch: ${{ github.head_ref }} diff --git a/.gitignore b/.gitignore index 84fed04..a83c4bb 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,7 @@ *.dll *.so *.dylib +.vscode/ # Test binary, built with `go test -c` *.test @@ -11,3 +12,4 @@ coverage/ # Output of the go coverage tool, specifically when used with LiteIDE *.out +vendor/ diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 6b802a5..0000000 --- a/.travis.yml +++ /dev/null @@ -1,8 +0,0 @@ -language: go - -matrix: - include: - - go: 1.15.x - - go: tip - allow_failures: - - go: tip diff --git a/0_functionPointers.go b/0_functionPointers.go deleted file mode 100644 index f82be15..0000000 --- a/0_functionPointers.go +++ /dev/null @@ -1,162 +0,0 @@ -package jobrunner - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "reflect" - "runtime" - "sort" - "strconv" - "strings" - "time" - - "github.com/google/uuid" -) - -// func pointers for injection / testing: application.go -var ( - isInterfaceValueNilFunc = isInterfaceValueNil - uuidNew = uuid.New - startApplicationFunc = startApplication - preBootstrapingFunc = preBootstraping - bootstrapFunc = bootstrap - postBootstrapingFunc = postBootstraping - endApplicationFunc = endApplication - beginApplicationFunc = beginApplication - logAppRootFunc = logAppRoot - handleSessionFunc = handleSession - waitForNextRunFunc = waitForNextRun - runInstancesFunc = runInstances - scheduleExecutionFunc = scheduleExecution - timeAfter = time.After - runApplicationFunc = runApplication - initializeHTTPClientsFunc = initializeHTTPClients -) - -// func pointers for injection / testing: customization.go -var ( - fmtPrintf = fmt.Printf - fmtSprintf = fmt.Sprintf - marshalIgnoreErrorFunc = marshalIgnoreError -) - -// func pointers for injection / testing: handler.go -var ( - stringsSplit = strings.Split - strconvAtoi = strconv.Atoi - initiateSessionFunc = initiateSession - getTimeNowUTCFunc = getTimeNowUTC - finalizeSessionFunc = finalizeSession - timeSince = time.Since - logProcessEnterFunc = logProcessEnter - logProcessRequestFunc = logProcessRequest - logProcessResponseFunc = logProcessResponse - logProcessExitFunc = logProcessExit - processSessionFunc = processSession -) - -// func pointers for injection / testing: jsonutil.go -var ( - jsonNewEncoder = json.NewEncoder - stringsTrimRight = strings.TrimRight - reflectTypeOf = reflect.TypeOf - strconvParseBool = strconv.ParseBool - stringsToLower = strings.ToLower - strconvParseInt = strconv.ParseInt - strconvParseFloat = strconv.ParseFloat - strconvParseUint = strconv.ParseUint - tryUnmarshalPrimitiveTypesFunc = tryUnmarshalPrimitiveTypes - jsonUnmarshal = json.Unmarshal - fmtErrorf = fmt.Errorf -) - -// func pointers for injection / testing: logger.go -var ( - prepareLoggingFunc = prepareLogging -) - -// func pointers for injection / testing: logType.go -var ( - sortStrings = sort.Strings - stringsJoin = strings.Join -) - -// func pointers for injection / testing: pointerutil.go -var ( - reflectValueOf = reflect.ValueOf -) - -// func pointers for injection / testing: schedule.go -var ( - timeDate = time.Date - moveValueIndexFunc = moveValueIndex - getDaysOfMonthFunc = getDaysOfMonth - constructTimeByScheduleFunc = constructTimeBySchedule - updateScheduleIndexFunc = updateScheduleIndex -) - -// func pointers for injection / testing: schedulemaker.go -var ( - generateFlagsDataFunc = generateFlagsData - constructValueSliceFunc = constructValueSlice - constructWeekdayMapFunc = constructWeekdayMap - constructYearSliceFunc = constructYearSlice - findValueMatchFunc = findValueMatch - isWeekdayMatchFunc = isWeekdayMatch - constructScheduleTemplateFunc = constructScheduleTemplate - determineScheduleIndexFunc = determineScheduleIndex - initialiseScheduleFunc = initialiseSchedule - sortInts = sort.Ints -) - -// func pointers for injection / testing: session.go -var ( - strconvItoa = strconv.Itoa - tryUnmarshalFunc = tryUnmarshal - jsonMarshal = json.Marshal - runtimeCaller = runtime.Caller - runtimeFuncForPC = runtime.FuncForPC - getMethodNameFunc = getMethodName - logMethodEnterFunc = logMethodEnter - logMethodParameterFunc = logMethodParameter - logMethodLogicFunc = logMethodLogic - logMethodReturnFunc = logMethodReturn - logMethodExitFunc = logMethodExit -) - -// func pointers for injection / testing: timeutil.go -var ( - timeNow = time.Now -) - -// func pointers for injection / testing: webRequest.go -var ( - clientDoFunc = clientDo - timeSleep = time.Sleep - getHTTPTransportFunc = getHTTPTransport - urlQueryEscape = url.QueryEscape - createQueryStringFunc = createQueryString - generateRequestURLFunc = generateRequestURL - stringsNewReader = strings.NewReader - httpNewRequest = http.NewRequest - logWebcallStartFunc = logWebcallStart - logWebcallRequestFunc = logWebcallRequest - logWebcallResponseFunc = logWebcallResponse - logWebcallFinishFunc = logWebcallFinish - createHTTPRequestFunc = createHTTPRequest - getClientForRequestFunc = getClientForRequest - clientDoWithRetryFunc = clientDoWithRetry - logErrorResponseFunc = logErrorResponse - logSuccessResponseFunc = logSuccessResponse - doRequestProcessingFunc = doRequestProcessing - ioutilReadAll = ioutil.ReadAll - ioutilNopCloser = ioutil.NopCloser - bytesNewBuffer = bytes.NewBuffer - httpStatusText = http.StatusText - getDataTemplateFunc = getDataTemplate - parseResponseFunc = parseResponse -) diff --git a/0_functionPointers_test.go b/0_functionPointers_test.go deleted file mode 100644 index ec7b549..0000000 --- a/0_functionPointers_test.go +++ /dev/null @@ -1,1123 +0,0 @@ -package jobrunner - -import ( - "bytes" - "crypto/tls" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "reflect" - "runtime" - "sort" - "strconv" - "strings" - "testing" - "time" - - "github.com/google/uuid" - "github.com/stretchr/testify/assert" -) - -var ( - isInterfaceValueNilFuncExpected int - isInterfaceValueNilFuncCalled int - uuidNewExpected int - uuidNewCalled int - startApplicationFuncExpected int - startApplicationFuncCalled int - preBootstrapingFuncExpected int - preBootstrapingFuncCalled int - bootstrapFuncExpected int - bootstrapFuncCalled int - postBootstrapingFuncExpected int - postBootstrapingFuncCalled int - endApplicationFuncExpected int - endApplicationFuncCalled int - beginApplicationFuncExpected int - beginApplicationFuncCalled int - logAppRootFuncExpected int - logAppRootFuncCalled int - handleSessionFuncExpected int - handleSessionFuncCalled int - waitForNextRunFuncExpected int - waitForNextRunFuncCalled int - runInstancesFuncExpected int - runInstancesFuncCalled int - scheduleExecutionFuncExpected int - scheduleExecutionFuncCalled int - timeAfterExpected int - timeAfterCalled int - runApplicationFuncExpected int - runApplicationFuncCalled int - initializeHTTPClientsFuncExpected int - initializeHTTPClientsFuncCalled int - fmtPrintfExpected int - fmtPrintfCalled int - fmtSprintfExpected int - fmtSprintfCalled int - marshalIgnoreErrorFuncExpected int - marshalIgnoreErrorFuncCalled int - stringsSplitExpected int - stringsSplitCalled int - strconvAtoiExpected int - strconvAtoiCalled int - initiateSessionFuncExpected int - initiateSessionFuncCalled int - getTimeNowUTCFuncExpected int - getTimeNowUTCFuncCalled int - finalizeSessionFuncExpected int - finalizeSessionFuncCalled int - timeSinceExpected int - timeSinceCalled int - jsonNewEncoderExpected int - jsonNewEncoderCalled int - stringsTrimRightExpected int - stringsTrimRightCalled int - jsonUnmarshalExpected int - jsonUnmarshalCalled int - fmtErrorfExpected int - fmtErrorfCalled int - reflectTypeOfExpected int - reflectTypeOfCalled int - stringsToLowerExpected int - stringsToLowerCalled int - strconvParseBoolExpected int - strconvParseBoolCalled int - strconvParseIntExpected int - strconvParseIntCalled int - strconvParseFloatExpected int - strconvParseFloatCalled int - strconvParseUintExpected int - strconvParseUintCalled int - tryUnmarshalPrimitiveTypesFuncExpected int - tryUnmarshalPrimitiveTypesFuncCalled int - prepareLoggingFuncExpected int - prepareLoggingFuncCalled int - sortStringsExpected int - sortStringsCalled int - stringsJoinExpected int - stringsJoinCalled int - reflectValueOfExpected int - reflectValueOfCalled int - timeDateExpected int - timeDateCalled int - moveValueIndexFuncExpected int - moveValueIndexFuncCalled int - getDaysOfMonthFuncExpected int - getDaysOfMonthFuncCalled int - constructTimeByScheduleFuncExpected int - constructTimeByScheduleFuncCalled int - updateScheduleIndexFuncExpected int - updateScheduleIndexFuncCalled int - generateFlagsDataFuncExpected int - generateFlagsDataFuncCalled int - constructValueSliceFuncExpected int - constructValueSliceFuncCalled int - constructWeekdayMapFuncExpected int - constructWeekdayMapFuncCalled int - constructYearSliceFuncExpected int - constructYearSliceFuncCalled int - findValueMatchFuncExpected int - findValueMatchFuncCalled int - isWeekdayMatchFuncExpected int - isWeekdayMatchFuncCalled int - constructScheduleTemplateFuncExpected int - constructScheduleTemplateFuncCalled int - determineScheduleIndexFuncExpected int - determineScheduleIndexFuncCalled int - initialiseScheduleFuncExpected int - initialiseScheduleFuncCalled int - sortIntsExpected int - sortIntsCalled int - ioutilReadAllExpected int - ioutilReadAllCalled int - ioutilNopCloserExpected int - ioutilNopCloserCalled int - bytesNewBufferExpected int - bytesNewBufferCalled int - logProcessEnterFuncExpected int - logProcessEnterFuncCalled int - logProcessExitFuncExpected int - logProcessExitFuncCalled int - logProcessResponseFuncExpected int - logProcessResponseFuncCalled int - logProcessRequestFuncExpected int - logProcessRequestFuncCalled int - processSessionFuncExpected int - processSessionFuncCalled int - httpStatusTextExpected int - httpStatusTextCalled int - strconvItoaExpected int - strconvItoaCalled int - tryUnmarshalFuncExpected int - tryUnmarshalFuncCalled int - jsonMarshalExpected int - jsonMarshalCalled int - runtimeCallerExpected int - runtimeCallerCalled int - runtimeFuncForPCExpected int - runtimeFuncForPCCalled int - getMethodNameFuncExpected int - getMethodNameFuncCalled int - logMethodEnterFuncExpected int - logMethodEnterFuncCalled int - logMethodParameterFuncExpected int - logMethodParameterFuncCalled int - logMethodLogicFuncExpected int - logMethodLogicFuncCalled int - logMethodReturnFuncExpected int - logMethodReturnFuncCalled int - logMethodExitFuncExpected int - logMethodExitFuncCalled int - timeNowExpected int - timeNowCalled int - clientDoFuncExpected int - clientDoFuncCalled int - timeSleepExpected int - timeSleepCalled int - getHTTPTransportFuncExpected int - getHTTPTransportFuncCalled int - urlQueryEscapeExpected int - urlQueryEscapeCalled int - createQueryStringFuncExpected int - createQueryStringFuncCalled int - generateRequestURLFuncExpected int - generateRequestURLFuncCalled int - stringsNewReaderExpected int - stringsNewReaderCalled int - httpNewRequestExpected int - httpNewRequestCalled int - logWebcallStartFuncExpected int - logWebcallStartFuncCalled int - logWebcallRequestFuncExpected int - logWebcallRequestFuncCalled int - logWebcallResponseFuncExpected int - logWebcallResponseFuncCalled int - logWebcallFinishFuncExpected int - logWebcallFinishFuncCalled int - createHTTPRequestFuncExpected int - createHTTPRequestFuncCalled int - getClientForRequestFuncExpected int - getClientForRequestFuncCalled int - clientDoWithRetryFuncExpected int - clientDoWithRetryFuncCalled int - logErrorResponseFuncExpected int - logErrorResponseFuncCalled int - logSuccessResponseFuncExpected int - logSuccessResponseFuncCalled int - doRequestProcessingFuncExpected int - doRequestProcessingFuncCalled int - getDataTemplateFuncExpected int - getDataTemplateFuncCalled int - parseResponseFuncExpected int - parseResponseFuncCalled int -) - -func createMock(t *testing.T) { - isInterfaceValueNilFuncExpected = 0 - isInterfaceValueNilFuncCalled = 0 - isInterfaceValueNilFunc = func(i interface{}) bool { - isInterfaceValueNilFuncCalled++ - return false - } - uuidNewExpected = 0 - uuidNewCalled = 0 - uuidNew = func() uuid.UUID { - uuidNewCalled++ - return uuid.Nil - } - startApplicationFuncExpected = 0 - startApplicationFuncCalled = 0 - startApplicationFunc = func(app *application) { - startApplicationFuncCalled++ - } - preBootstrapingFuncExpected = 0 - preBootstrapingFuncCalled = 0 - preBootstrapingFunc = func(app *application) bool { - preBootstrapingFuncCalled++ - return false - } - bootstrapFuncExpected = 0 - bootstrapFuncCalled = 0 - bootstrapFunc = func(app *application) { - bootstrapFuncCalled++ - } - postBootstrapingFuncExpected = 0 - postBootstrapingFuncCalled = 0 - postBootstrapingFunc = func(app *application) bool { - postBootstrapingFuncCalled++ - return false - } - endApplicationFuncExpected = 0 - endApplicationFuncCalled = 0 - endApplicationFunc = func(app *application) { - endApplicationFuncCalled++ - } - beginApplicationFuncExpected = 0 - beginApplicationFuncCalled = 0 - beginApplicationFunc = func(app *application) { - beginApplicationFuncCalled++ - } - logAppRootFuncExpected = 0 - logAppRootFuncCalled = 0 - logAppRootFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logAppRootFuncCalled++ - } - handleSessionFuncExpected = 0 - handleSessionFuncCalled = 0 - handleSessionFunc = func(app *application, index int, reruns int) error { - handleSessionFuncCalled++ - return nil - } - waitForNextRunFuncExpected = 0 - waitForNextRunFuncCalled = 0 - waitForNextRunFunc = func(app *application) { - waitForNextRunFuncCalled++ - } - runInstancesFuncExpected = 0 - runInstancesFuncCalled = 0 - runInstancesFunc = func(app *application) { - runInstancesFuncCalled++ - } - scheduleExecutionFuncExpected = 0 - scheduleExecutionFuncCalled = 0 - scheduleExecutionFunc = func(app *application) { - scheduleExecutionFuncCalled++ - } - timeAfterExpected = 0 - timeAfterCalled = 0 - timeAfter = func(d time.Duration) <-chan time.Time { - timeAfterCalled++ - return nil - } - runApplicationFuncExpected = 0 - runApplicationFuncCalled = 0 - runApplicationFunc = func(app *application) { - runApplicationFuncCalled++ - } - initializeHTTPClientsFuncExpected = 0 - initializeHTTPClientsFuncCalled = 0 - initializeHTTPClientsFunc = func(webcallTimeout time.Duration, skipServerCertVerification bool, clientCertificate *tls.Certificate, roundTripperWrapper func(originalTransport http.RoundTripper) http.RoundTripper) { - initializeHTTPClientsFuncCalled++ - } - fmtPrintfExpected = 0 - fmtPrintfCalled = 0 - fmtPrintf = func(format string, a ...interface{}) (n int, err error) { - fmtPrintfCalled++ - return 0, nil - } - fmtSprintfExpected = 0 - fmtSprintfCalled = 0 - fmtSprintf = func(format string, a ...interface{}) string { - fmtSprintfCalled++ - return "" - } - marshalIgnoreErrorFuncExpected = 0 - marshalIgnoreErrorFuncCalled = 0 - marshalIgnoreErrorFunc = func(v interface{}) string { - marshalIgnoreErrorFuncCalled++ - return "" - } - stringsSplitExpected = 0 - stringsSplitCalled = 0 - stringsSplit = func(s, sep string) []string { - stringsSplitCalled++ - return nil - } - strconvAtoiExpected = 0 - strconvAtoiCalled = 0 - strconvAtoi = func(s string) (int, error) { - strconvAtoiCalled++ - return 0, nil - } - initiateSessionFuncExpected = 0 - initiateSessionFuncCalled = 0 - initiateSessionFunc = func(app *application, index int, reruns int) *session { - initiateSessionFuncCalled++ - return nil - } - getTimeNowUTCFuncExpected = 0 - getTimeNowUTCFuncCalled = 0 - getTimeNowUTCFunc = func() time.Time { - getTimeNowUTCFuncCalled++ - return time.Time{} - } - finalizeSessionFuncExpected = 0 - finalizeSessionFuncCalled = 0 - finalizeSessionFunc = func(session *session, resultError error, recoverResult interface{}) error { - finalizeSessionFuncCalled++ - return nil - } - timeSinceExpected = 0 - timeSinceCalled = 0 - timeSince = func(t time.Time) time.Duration { - timeSinceCalled++ - return 0 - } - jsonNewEncoderExpected = 0 - jsonNewEncoderCalled = 0 - jsonNewEncoder = func(w io.Writer) *json.Encoder { - jsonNewEncoderCalled++ - return nil - } - stringsTrimRightExpected = 0 - stringsTrimRightCalled = 0 - stringsTrimRight = func(s string, cutset string) string { - stringsTrimRightCalled++ - return "" - } - jsonUnmarshalExpected = 0 - jsonUnmarshalCalled = 0 - jsonUnmarshal = func(data []byte, v interface{}) error { - jsonUnmarshalCalled++ - return nil - } - fmtErrorfExpected = 0 - fmtErrorfCalled = 0 - fmtErrorf = func(format string, a ...interface{}) error { - fmtErrorfCalled++ - return nil - } - reflectTypeOfExpected = 0 - reflectTypeOfCalled = 0 - reflectTypeOf = func(i interface{}) reflect.Type { - reflectTypeOfCalled++ - return nil - } - stringsToLowerExpected = 0 - stringsToLowerCalled = 0 - stringsToLower = func(s string) string { - stringsToLowerCalled++ - return "" - } - strconvParseBoolExpected = 0 - strconvParseBoolCalled = 0 - strconvParseBool = func(str string) (bool, error) { - strconvParseBoolCalled++ - return false, nil - } - strconvParseIntExpected = 0 - strconvParseIntCalled = 0 - strconvParseInt = func(s string, base int, bitSize int) (int64, error) { - strconvParseIntCalled++ - return 0, nil - } - strconvParseFloatExpected = 0 - strconvParseFloatCalled = 0 - strconvParseFloat = func(s string, bitSize int) (float64, error) { - strconvParseFloatCalled++ - return 0, nil - } - strconvParseUintExpected = 0 - strconvParseUintCalled = 0 - strconvParseUint = func(s string, base int, bitSize int) (uint64, error) { - strconvParseUintCalled++ - return 0, nil - } - tryUnmarshalPrimitiveTypesFuncExpected = 0 - tryUnmarshalPrimitiveTypesFuncCalled = 0 - tryUnmarshalPrimitiveTypesFunc = func(value string, dataTemplate interface{}) bool { - tryUnmarshalPrimitiveTypesFuncCalled++ - return false - } - prepareLoggingFuncExpected = 0 - prepareLoggingFuncCalled = 0 - prepareLoggingFunc = func(session *session, logType LogType, logLevel LogLevel, category string, subcategory string, messageFormat string, parameters ...interface{}) { - prepareLoggingFuncCalled++ - } - sortStringsExpected = 0 - sortStringsCalled = 0 - sortStrings = func(a []string) { - sortStringsCalled++ - } - stringsJoinExpected = 0 - stringsJoinCalled = 0 - stringsJoin = func(a []string, sep string) string { - stringsJoinCalled++ - return "" - } - reflectValueOfExpected = 0 - reflectValueOfCalled = 0 - reflectValueOf = func(i interface{}) reflect.Value { - reflectValueOfCalled++ - return reflect.Value{} - } - timeDateExpected = 0 - timeDateCalled = 0 - timeDate = func(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) time.Time { - timeDateCalled++ - return time.Time{} - } - moveValueIndexFuncExpected = 0 - moveValueIndexFuncCalled = 0 - moveValueIndexFunc = func(oldIndex int, values []int, maxValue int) (int, int, bool) { - moveValueIndexFuncCalled++ - return 0, 0, false - } - getDaysOfMonthFuncExpected = 0 - getDaysOfMonthFuncCalled = 0 - getDaysOfMonthFunc = func(year, month int) int { - getDaysOfMonthFuncCalled++ - return 0 - } - constructTimeByScheduleFuncExpected = 0 - constructTimeByScheduleFuncCalled = 0 - constructTimeByScheduleFunc = func(schedule *schedule) time.Time { - constructTimeByScheduleFuncCalled++ - return time.Time{} - } - updateScheduleIndexFuncExpected = 0 - updateScheduleIndexFuncCalled = 0 - updateScheduleIndexFunc = func(schedule *schedule) bool { - updateScheduleIndexFuncCalled++ - return false - } - generateFlagsDataFuncExpected = 0 - generateFlagsDataFuncCalled = 0 - generateFlagsDataFunc = func(data []bool, total int, values ...int) []bool { - generateFlagsDataFuncCalled++ - return nil - } - constructValueSliceFuncExpected = 0 - constructValueSliceFuncCalled = 0 - constructValueSliceFunc = func(values []bool, total int) []int { - constructValueSliceFuncCalled++ - return nil - } - constructWeekdayMapFuncExpected = 0 - constructWeekdayMapFuncCalled = 0 - constructWeekdayMapFunc = func(weekdays []bool) map[time.Weekday]bool { - constructWeekdayMapFuncCalled++ - return nil - } - constructYearSliceFuncExpected = 0 - constructYearSliceFuncCalled = 0 - constructYearSliceFunc = func(years map[int]bool) []int { - constructYearSliceFuncCalled++ - return nil - } - findValueMatchFuncExpected = 0 - findValueMatchFuncCalled = 0 - findValueMatchFunc = func(value int, values []int) (int, int, bool, bool) { - findValueMatchFuncCalled++ - return 0, 0, false, false - } - isWeekdayMatchFuncExpected = 0 - isWeekdayMatchFuncCalled = 0 - isWeekdayMatchFunc = func(year, month, day int, weekdays map[time.Weekday]bool) bool { - isWeekdayMatchFuncCalled++ - return false - } - constructScheduleTemplateFuncExpected = 0 - constructScheduleTemplateFuncCalled = 0 - constructScheduleTemplateFunc = func(scheduleMaker *scheduleMaker) *schedule { - constructScheduleTemplateFuncCalled++ - return nil - } - determineScheduleIndexFuncExpected = 0 - determineScheduleIndexFuncCalled = 0 - determineScheduleIndexFunc = func(start time.Time, schedule *schedule) (bool, time.Time, error) { - determineScheduleIndexFuncCalled++ - return false, time.Time{}, nil - } - initialiseScheduleFuncExpected = 0 - initialiseScheduleFuncCalled = 0 - initialiseScheduleFunc = func(start time.Time, schedule *schedule) error { - initialiseScheduleFuncCalled++ - return nil - } - sortIntsExpected = 0 - sortIntsCalled = 0 - sortInts = func(a []int) { - sortIntsCalled++ - } - ioutilReadAllExpected = 0 - ioutilReadAllCalled = 0 - ioutilReadAll = func(r io.Reader) ([]byte, error) { - ioutilReadAllCalled++ - return nil, nil - } - ioutilNopCloserExpected = 0 - ioutilNopCloserCalled = 0 - ioutilNopCloser = func(r io.Reader) io.ReadCloser { - ioutilNopCloserCalled++ - return nil - } - bytesNewBufferExpected = 0 - bytesNewBufferCalled = 0 - bytesNewBuffer = func(buf []byte) *bytes.Buffer { - bytesNewBufferCalled++ - return nil - } - logProcessEnterFuncExpected = 0 - logProcessEnterFuncCalled = 0 - logProcessEnterFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logProcessEnterFuncCalled++ - } - logProcessExitFuncExpected = 0 - logProcessExitFuncCalled = 0 - logProcessExitFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logProcessExitFuncCalled++ - } - logProcessResponseFuncExpected = 0 - logProcessResponseFuncCalled = 0 - logProcessResponseFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logProcessResponseFuncCalled++ - } - logProcessRequestFuncExpected = 0 - logProcessRequestFuncCalled = 0 - logProcessRequestFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logProcessRequestFuncCalled++ - } - processSessionFuncExpected = 0 - processSessionFuncCalled = 0 - processSessionFunc = func(session Session, customization Customization) error { - processSessionFuncCalled++ - return nil - } - httpStatusTextExpected = 0 - httpStatusTextCalled = 0 - httpStatusText = func(code int) string { - httpStatusTextCalled++ - return "" - } - strconvItoaExpected = 0 - strconvItoaCalled = 0 - strconvItoa = func(i int) string { - strconvItoaCalled++ - return "" - } - tryUnmarshalFuncExpected = 0 - tryUnmarshalFuncCalled = 0 - tryUnmarshalFunc = func(value string, dataTemplate interface{}) error { - tryUnmarshalFuncCalled++ - return nil - } - jsonMarshalExpected = 0 - jsonMarshalCalled = 0 - jsonMarshal = func(v interface{}) ([]byte, error) { - jsonMarshalCalled++ - return nil, nil - } - runtimeCallerExpected = 0 - runtimeCallerCalled = 0 - runtimeCaller = func(skip int) (pc uintptr, file string, line int, ok bool) { - runtimeCallerCalled++ - return 0, "", 0, false - } - runtimeFuncForPCExpected = 0 - runtimeFuncForPCCalled = 0 - runtimeFuncForPC = func(pc uintptr) *runtime.Func { - runtimeFuncForPCCalled++ - return nil - } - getMethodNameFuncExpected = 0 - getMethodNameFuncCalled = 0 - getMethodNameFunc = func() string { - getMethodNameFuncCalled++ - return "" - } - logMethodEnterFuncExpected = 0 - logMethodEnterFuncCalled = 0 - logMethodEnterFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logMethodEnterFuncCalled++ - } - logMethodParameterFuncExpected = 0 - logMethodParameterFuncCalled = 0 - logMethodParameterFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logMethodParameterFuncCalled++ - } - logMethodLogicFuncExpected = 0 - logMethodLogicFuncCalled = 0 - logMethodLogicFunc = func(session *session, logLevel LogLevel, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logMethodLogicFuncCalled++ - } - logMethodReturnFuncExpected = 0 - logMethodReturnFuncCalled = 0 - logMethodReturnFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logMethodReturnFuncCalled++ - } - logMethodExitFuncExpected = 0 - logMethodExitFuncCalled = 0 - logMethodExitFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logMethodExitFuncCalled++ - } - timeNowExpected = 0 - timeNowCalled = 0 - timeNow = func() time.Time { - timeNowCalled++ - return time.Time{} - } - clientDoFuncExpected = 0 - clientDoFuncCalled = 0 - clientDoFunc = func(httpClient *http.Client, httpRequest *http.Request) (*http.Response, error) { - clientDoFuncCalled++ - return nil, nil - } - timeSleepExpected = 0 - timeSleepCalled = 0 - timeSleep = func(time.Duration) { - timeSleepCalled++ - } - getHTTPTransportFuncExpected = 0 - getHTTPTransportFuncCalled = 0 - getHTTPTransportFunc = func(skipServerCertVerification bool, clientCertificate *tls.Certificate, roundTripperWrapper func(originalTransport http.RoundTripper) http.RoundTripper) http.RoundTripper { - getHTTPTransportFuncCalled++ - return nil - } - urlQueryEscapeExpected = 0 - urlQueryEscapeCalled = 0 - urlQueryEscape = func(s string) string { - urlQueryEscapeCalled++ - return "" - } - createQueryStringFuncExpected = 0 - createQueryStringFuncCalled = 0 - createQueryStringFunc = func(query map[string][]string) string { - createQueryStringFuncCalled++ - return "" - } - generateRequestURLFuncExpected = 0 - generateRequestURLFuncCalled = 0 - generateRequestURLFunc = func(baseURL string, query map[string][]string) string { - generateRequestURLFuncCalled++ - return "" - } - stringsNewReaderExpected = 0 - stringsNewReaderCalled = 0 - stringsNewReader = func(s string) *strings.Reader { - stringsNewReaderCalled++ - return nil - } - httpNewRequestExpected = 0 - httpNewRequestCalled = 0 - httpNewRequest = func(method, url string, body io.Reader) (*http.Request, error) { - httpNewRequestCalled++ - return nil, nil - } - logWebcallStartFuncExpected = 0 - logWebcallStartFuncCalled = 0 - logWebcallStartFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logWebcallStartFuncCalled++ - } - logWebcallRequestFuncExpected = 0 - logWebcallRequestFuncCalled = 0 - logWebcallRequestFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logWebcallRequestFuncCalled++ - } - logWebcallResponseFuncExpected = 0 - logWebcallResponseFuncCalled = 0 - logWebcallResponseFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logWebcallResponseFuncCalled++ - } - logWebcallFinishFuncExpected = 0 - logWebcallFinishFuncCalled = 0 - logWebcallFinishFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logWebcallFinishFuncCalled++ - } - createHTTPRequestFuncExpected = 0 - createHTTPRequestFuncCalled = 0 - createHTTPRequestFunc = func(webRequest *webRequest) (*http.Request, error) { - createHTTPRequestFuncCalled++ - return nil, nil - } - getClientForRequestFuncExpected = 0 - getClientForRequestFuncCalled = 0 - getClientForRequestFunc = func(sendClientCert bool) *http.Client { - getClientForRequestFuncCalled++ - return nil - } - clientDoWithRetryFuncExpected = 0 - clientDoWithRetryFuncCalled = 0 - clientDoWithRetryFunc = func(httpClient *http.Client, httpRequest *http.Request, connectivityRetryCount int, httpStatusRetryCount map[int]int, retryDelay time.Duration) (*http.Response, error) { - clientDoWithRetryFuncCalled++ - return nil, nil - } - logErrorResponseFuncExpected = 0 - logErrorResponseFuncCalled = 0 - logErrorResponseFunc = func(session *session, responseError error, startTime time.Time) { - logErrorResponseFuncCalled++ - } - logSuccessResponseFuncExpected = 0 - logSuccessResponseFuncCalled = 0 - logSuccessResponseFunc = func(session *session, response *http.Response, startTime time.Time) { - logSuccessResponseFuncCalled++ - } - doRequestProcessingFuncExpected = 0 - doRequestProcessingFuncCalled = 0 - doRequestProcessingFunc = func(webRequest *webRequest) (*http.Response, error) { - doRequestProcessingFuncCalled++ - return nil, nil - } - getDataTemplateFuncExpected = 0 - getDataTemplateFuncCalled = 0 - getDataTemplateFunc = func(session *session, statusCode int, dataReceivers []dataReceiver) interface{} { - getDataTemplateFuncCalled++ - return nil - } - parseResponseFuncExpected = 0 - parseResponseFuncCalled = 0 - parseResponseFunc = func(session *session, body io.ReadCloser, dataTemplate interface{}) error { - parseResponseFuncCalled++ - return nil - } -} - -func verifyAll(t *testing.T) { - isInterfaceValueNilFunc = isInterfaceValueNil - assert.Equal(t, isInterfaceValueNilFuncExpected, isInterfaceValueNilFuncCalled, "Unexpected number of calls to method isInterfaceValueNilFunc") - uuidNew = uuid.New - assert.Equal(t, uuidNewExpected, uuidNewCalled, "Unexpected number of calls to method uuidNew") - startApplicationFunc = startApplication - assert.Equal(t, startApplicationFuncExpected, startApplicationFuncCalled, "Unexpected number of calls to method startApplicationFunc") - preBootstrapingFunc = preBootstraping - assert.Equal(t, preBootstrapingFuncExpected, preBootstrapingFuncCalled, "Unexpected number of calls to method preBootstrapingFunc") - bootstrapFunc = bootstrap - assert.Equal(t, bootstrapFuncExpected, bootstrapFuncCalled, "Unexpected number of calls to method bootstrapFunc") - postBootstrapingFunc = postBootstraping - assert.Equal(t, postBootstrapingFuncExpected, postBootstrapingFuncCalled, "Unexpected number of calls to method postBootstrapingFunc") - endApplicationFunc = endApplication - assert.Equal(t, endApplicationFuncExpected, endApplicationFuncCalled, "Unexpected number of calls to method endApplicationFunc") - beginApplicationFunc = beginApplication - assert.Equal(t, beginApplicationFuncExpected, beginApplicationFuncCalled, "Unexpected number of calls to method beginApplicationFunc") - logAppRootFunc = logAppRoot - assert.Equal(t, logAppRootFuncExpected, logAppRootFuncCalled, "Unexpected number of calls to method logAppRootFunc") - handleSessionFunc = handleSession - assert.Equal(t, handleSessionFuncExpected, handleSessionFuncCalled, "Unexpected number of calls to method handleSessionFunc") - waitForNextRunFunc = waitForNextRun - assert.Equal(t, waitForNextRunFuncExpected, waitForNextRunFuncCalled, "Unexpected number of calls to method waitForNextRunFunc") - runInstancesFunc = runInstances - assert.Equal(t, runInstancesFuncExpected, runInstancesFuncCalled, "Unexpected number of calls to method runInstancesFunc") - scheduleExecutionFunc = scheduleExecution - assert.Equal(t, scheduleExecutionFuncExpected, scheduleExecutionFuncCalled, "Unexpected number of calls to method scheduleExecutionFunc") - timeAfter = time.After - assert.Equal(t, timeAfterExpected, timeAfterCalled, "Unexpected number of calls to method timeAfter") - runApplicationFunc = runApplication - assert.Equal(t, runApplicationFuncExpected, runApplicationFuncCalled, "Unexpected number of calls to method runApplicationFunc") - initializeHTTPClientsFunc = initializeHTTPClients - assert.Equal(t, initializeHTTPClientsFuncExpected, initializeHTTPClientsFuncCalled, "Unexpected number of calls to method initializeHTTPClientsFunc") - fmtPrintf = fmt.Printf - assert.Equal(t, fmtPrintfExpected, fmtPrintfCalled, "Unexpected number of calls to method fmtPrintf") - fmtSprintf = fmt.Sprintf - assert.Equal(t, fmtSprintfExpected, fmtSprintfCalled, "Unexpected number of calls to method fmtSprintf") - marshalIgnoreErrorFunc = marshalIgnoreError - assert.Equal(t, marshalIgnoreErrorFuncExpected, marshalIgnoreErrorFuncCalled, "Unexpected number of calls to method marshalIgnoreErrorFunc") - stringsSplit = strings.Split - assert.Equal(t, stringsSplitExpected, stringsSplitCalled, "Unexpected number of calls to method stringsSplit") - strconvAtoi = strconv.Atoi - assert.Equal(t, strconvAtoiExpected, strconvAtoiCalled, "Unexpected number of calls to method strconvAtoi") - initiateSessionFunc = initiateSession - assert.Equal(t, initiateSessionFuncExpected, initiateSessionFuncCalled, "Unexpected number of calls to method initiateSessionFunc") - getTimeNowUTCFunc = getTimeNowUTC - assert.Equal(t, getTimeNowUTCFuncExpected, getTimeNowUTCFuncCalled, "Unexpected number of calls to method getTimeNowUTCFunc") - finalizeSessionFunc = finalizeSession - assert.Equal(t, finalizeSessionFuncExpected, finalizeSessionFuncCalled, "Unexpected number of calls to method finalizeSessionFunc") - timeSince = time.Since - assert.Equal(t, timeSinceExpected, timeSinceCalled, "Unexpected number of calls to method timeSince") - jsonNewEncoder = json.NewEncoder - assert.Equal(t, jsonNewEncoderExpected, jsonNewEncoderCalled, "Unexpected number of calls to jsonNewEncoder") - stringsTrimRight = strings.TrimRight - assert.Equal(t, stringsTrimRightExpected, stringsTrimRightCalled, "Unexpected number of calls to stringsTrimRight") - jsonUnmarshal = json.Unmarshal - assert.Equal(t, jsonUnmarshalExpected, jsonUnmarshalCalled, "Unexpected number of calls to jsonUnmarshal") - fmtErrorf = fmt.Errorf - assert.Equal(t, fmtErrorfExpected, fmtErrorfCalled, "Unexpected number of calls to fmtErrorf") - reflectTypeOf = reflect.TypeOf - assert.Equal(t, reflectTypeOfExpected, reflectTypeOfCalled, "Unexpected number of calls to reflectTypeOf") - stringsToLower = strings.ToLower - assert.Equal(t, stringsToLowerExpected, stringsToLowerCalled, "Unexpected number of calls to stringsToLower") - strconvParseBool = strconv.ParseBool - assert.Equal(t, strconvParseBoolExpected, strconvParseBoolCalled, "Unexpected number of calls to strconvParseBool") - strconvParseInt = strconv.ParseInt - assert.Equal(t, strconvParseIntExpected, strconvParseIntCalled, "Unexpected number of calls to strconvParseInt") - strconvParseFloat = strconv.ParseFloat - assert.Equal(t, strconvParseFloatExpected, strconvParseFloatCalled, "Unexpected number of calls to strconvParseFloat") - strconvParseUint = strconv.ParseUint - assert.Equal(t, strconvParseUintExpected, strconvParseUintCalled, "Unexpected number of calls to strconvParseUint") - tryUnmarshalPrimitiveTypesFunc = tryUnmarshalPrimitiveTypes - assert.Equal(t, tryUnmarshalPrimitiveTypesFuncExpected, tryUnmarshalPrimitiveTypesFuncCalled, "Unexpected number of calls to tryUnmarshalPrimitiveTypesFunc") - prepareLoggingFunc = prepareLogging - assert.Equal(t, prepareLoggingFuncExpected, prepareLoggingFuncCalled, "Unexpected number of calls to prepareLoggingFunc") - sortStrings = sort.Strings - assert.Equal(t, sortStringsExpected, sortStringsCalled, "Unexpected number of calls to sortStrings") - stringsJoin = strings.Join - assert.Equal(t, stringsJoinExpected, stringsJoinCalled, "Unexpected number of calls to stringsJoin") - reflectValueOf = reflect.ValueOf - assert.Equal(t, reflectValueOfExpected, reflectValueOfCalled, "Unexpected number of calls to reflectValueOf") - timeDate = time.Date - assert.Equal(t, timeDateExpected, timeDateCalled, "Unexpected number of calls to timeDate") - moveValueIndexFunc = moveValueIndex - assert.Equal(t, moveValueIndexFuncExpected, moveValueIndexFuncCalled, "Unexpected number of calls to moveValueIndexFunc") - getDaysOfMonthFunc = getDaysOfMonth - assert.Equal(t, getDaysOfMonthFuncExpected, getDaysOfMonthFuncCalled, "Unexpected number of calls to getDaysOfMonthFunc") - constructTimeByScheduleFunc = constructTimeBySchedule - assert.Equal(t, constructTimeByScheduleFuncExpected, constructTimeByScheduleFuncCalled, "Unexpected number of calls to constructTimeByScheduleFunc") - updateScheduleIndexFunc = updateScheduleIndex - assert.Equal(t, updateScheduleIndexFuncExpected, updateScheduleIndexFuncCalled, "Unexpected number of calls to updateScheduleIndexFunc") - generateFlagsDataFunc = generateFlagsData - assert.Equal(t, generateFlagsDataFuncExpected, generateFlagsDataFuncCalled, "Unexpected number of calls to generateFlagsDataFunc") - constructValueSliceFunc = constructValueSlice - assert.Equal(t, constructValueSliceFuncExpected, constructValueSliceFuncCalled, "Unexpected number of calls to constructValueSliceFunc") - constructWeekdayMapFunc = constructWeekdayMap - assert.Equal(t, constructWeekdayMapFuncExpected, constructWeekdayMapFuncCalled, "Unexpected number of calls to constructWeekdayMapFunc") - constructYearSliceFunc = constructYearSlice - assert.Equal(t, constructYearSliceFuncExpected, constructYearSliceFuncCalled, "Unexpected number of calls to constructYearSliceFunc") - findValueMatchFunc = findValueMatch - assert.Equal(t, findValueMatchFuncExpected, findValueMatchFuncCalled, "Unexpected number of calls to findValueMatchFunc") - isWeekdayMatchFunc = isWeekdayMatch - assert.Equal(t, isWeekdayMatchFuncExpected, isWeekdayMatchFuncCalled, "Unexpected number of calls to isWeekdayMatchFunc") - constructScheduleTemplateFunc = constructScheduleTemplate - assert.Equal(t, constructScheduleTemplateFuncExpected, constructScheduleTemplateFuncCalled, "Unexpected number of calls to constructScheduleTemplateFunc") - determineScheduleIndexFunc = determineScheduleIndex - assert.Equal(t, determineScheduleIndexFuncExpected, determineScheduleIndexFuncCalled, "Unexpected number of calls to determineScheduleIndexFunc") - initialiseScheduleFunc = initialiseSchedule - assert.Equal(t, initialiseScheduleFuncExpected, initialiseScheduleFuncCalled, "Unexpected number of calls to initialiseScheduleFunc") - sortInts = sort.Ints - assert.Equal(t, sortIntsExpected, sortIntsCalled, "Unexpected number of calls to sortInts") - ioutilReadAll = ioutil.ReadAll - assert.Equal(t, ioutilReadAllExpected, ioutilReadAllCalled, "Unexpected number of calls to ioutilReadAll") - ioutilNopCloser = ioutil.NopCloser - assert.Equal(t, ioutilNopCloserExpected, ioutilNopCloserCalled, "Unexpected number of calls to ioutilNopCloser") - bytesNewBuffer = bytes.NewBuffer - assert.Equal(t, bytesNewBufferExpected, bytesNewBufferCalled, "Unexpected number of calls to bytesNewBuffer") - logProcessEnterFunc = logProcessEnter - assert.Equal(t, logProcessEnterFuncExpected, logProcessEnterFuncCalled, "Unexpected number of calls to method logProcessEnterFunc") - logProcessExitFunc = logProcessExit - assert.Equal(t, logProcessExitFuncExpected, logProcessExitFuncCalled, "Unexpected number of calls to method logProcessExitFunc") - logProcessResponseFunc = logProcessResponse - assert.Equal(t, logProcessResponseFuncExpected, logProcessResponseFuncCalled, "Unexpected number of calls to method logProcessResponseFunc") - logProcessRequestFunc = logProcessRequest - assert.Equal(t, logProcessRequestFuncExpected, logProcessRequestFuncCalled, "Unexpected number of calls to method logProcessRequestFunc") - processSessionFunc = processSession - assert.Equal(t, processSessionFuncExpected, processSessionFuncCalled, "Unexpected number of calls to method processSessionFunc") - httpStatusText = http.StatusText - assert.Equal(t, httpStatusTextExpected, httpStatusTextCalled, "Unexpected number of calls to method httpStatusText") - strconvItoa = strconv.Itoa - assert.Equal(t, strconvItoaExpected, strconvItoaCalled, "Unexpected number of calls to method strconvItoa") - tryUnmarshalFunc = tryUnmarshal - assert.Equal(t, tryUnmarshalFuncExpected, tryUnmarshalFuncCalled, "Unexpected number of calls to method tryUnmarshalFunc") - jsonMarshal = json.Marshal - assert.Equal(t, jsonMarshalExpected, jsonMarshalCalled, "Unexpected number of calls to method jsonMarshal") - runtimeCaller = runtime.Caller - assert.Equal(t, runtimeCallerExpected, runtimeCallerCalled, "Unexpected number of calls to method runtimeCaller") - runtimeFuncForPC = runtime.FuncForPC - assert.Equal(t, runtimeFuncForPCExpected, runtimeFuncForPCCalled, "Unexpected number of calls to method runtimeFuncForPC") - getMethodNameFunc = getMethodName - assert.Equal(t, getMethodNameFuncExpected, getMethodNameFuncCalled, "Unexpected number of calls to method getMethodNameFunc") - logMethodEnterFunc = logMethodEnter - assert.Equal(t, logMethodEnterFuncExpected, logMethodEnterFuncCalled, "Unexpected number of calls to method logMethodEnterFunc") - logMethodParameterFunc = logMethodParameter - assert.Equal(t, logMethodParameterFuncExpected, logMethodParameterFuncCalled, "Unexpected number of calls to method logMethodParameterFunc") - logMethodLogicFunc = logMethodLogic - assert.Equal(t, logMethodLogicFuncExpected, logMethodLogicFuncCalled, "Unexpected number of calls to method logMethodLogicFunc") - logMethodReturnFunc = logMethodReturn - assert.Equal(t, logMethodReturnFuncExpected, logMethodReturnFuncCalled, "Unexpected number of calls to method logMethodReturnFunc") - logMethodExitFunc = logMethodExit - assert.Equal(t, logMethodExitFuncExpected, logMethodExitFuncCalled, "Unexpected number of calls to method logMethodExitFunc") - timeNow = time.Now - assert.Equal(t, timeNowExpected, timeNowCalled, "Unexpected number of calls to timeNow") - clientDoFunc = clientDo - assert.Equal(t, clientDoFuncExpected, clientDoFuncCalled, "Unexpected number of calls to method clientDoFunc") - timeSleep = time.Sleep - assert.Equal(t, timeSleepExpected, timeSleepCalled, "Unexpected number of calls to method timeSleep") - getHTTPTransportFunc = getHTTPTransport - assert.Equal(t, getHTTPTransportFuncExpected, getHTTPTransportFuncCalled, "Unexpected number of calls to method getHTTPTransportFunc") - urlQueryEscape = url.QueryEscape - assert.Equal(t, urlQueryEscapeExpected, urlQueryEscapeCalled, "Unexpected number of calls to method urlQueryEscape") - createQueryStringFunc = createQueryString - assert.Equal(t, createQueryStringFuncExpected, createQueryStringFuncCalled, "Unexpected number of calls to method createQueryStringFunc") - generateRequestURLFunc = generateRequestURL - assert.Equal(t, generateRequestURLFuncExpected, generateRequestURLFuncCalled, "Unexpected number of calls to method generateRequestURLFunc") - stringsNewReader = strings.NewReader - assert.Equal(t, stringsNewReaderExpected, stringsNewReaderCalled, "Unexpected number of calls to method stringsNewReader") - httpNewRequest = http.NewRequest - assert.Equal(t, httpNewRequestExpected, httpNewRequestCalled, "Unexpected number of calls to method httpNewRequest") - logWebcallStartFunc = logWebcallStart - assert.Equal(t, logWebcallStartFuncExpected, logWebcallStartFuncCalled, "Unexpected number of calls to method logWebcallStartFunc") - logWebcallRequestFunc = logWebcallRequest - assert.Equal(t, logWebcallRequestFuncExpected, logWebcallRequestFuncCalled, "Unexpected number of calls to method logWebcallRequestFunc") - logWebcallResponseFunc = logWebcallResponse - assert.Equal(t, logWebcallResponseFuncExpected, logWebcallResponseFuncCalled, "Unexpected number of calls to method logWebcallResponseFunc") - logWebcallFinishFunc = logWebcallFinish - assert.Equal(t, logWebcallFinishFuncExpected, logWebcallFinishFuncCalled, "Unexpected number of calls to method logWebcallFinishFunc") - createHTTPRequestFunc = createHTTPRequest - assert.Equal(t, createHTTPRequestFuncExpected, createHTTPRequestFuncCalled, "Unexpected number of calls to method createHTTPRequestFunc") - getClientForRequestFunc = getClientForRequest - assert.Equal(t, getClientForRequestFuncExpected, getClientForRequestFuncCalled, "Unexpected number of calls to method getClientForRequestFunc") - clientDoWithRetryFunc = clientDoWithRetry - assert.Equal(t, clientDoWithRetryFuncExpected, clientDoWithRetryFuncCalled, "Unexpected number of calls to method clientDoWithRetryFunc") - logErrorResponseFunc = logErrorResponse - assert.Equal(t, logErrorResponseFuncExpected, logErrorResponseFuncCalled, "Unexpected number of calls to method logErrorResponseFunc") - logSuccessResponseFunc = logSuccessResponse - assert.Equal(t, logSuccessResponseFuncExpected, logSuccessResponseFuncCalled, "Unexpected number of calls to method logSuccessResponseFunc") - doRequestProcessingFunc = doRequestProcessing - assert.Equal(t, doRequestProcessingFuncExpected, doRequestProcessingFuncCalled, "Unexpected number of calls to method doRequestProcessingFunc") - getDataTemplateFunc = getDataTemplate - assert.Equal(t, getDataTemplateFuncExpected, getDataTemplateFuncCalled, "Unexpected number of calls to method getDataTemplateFunc") - parseResponseFunc = parseResponse - assert.Equal(t, parseResponseFuncExpected, parseResponseFuncCalled, "Unexpected number of calls to method parseResponseFunc") -} - -func functionPointerEquals(t *testing.T, expectFunc interface{}, actualFunc interface{}) { - var expectValue = fmt.Sprintf("%v", reflect.ValueOf(expectFunc)) - var actualValue = fmt.Sprintf("%v", reflect.ValueOf(actualFunc)) - assert.Equal(t, expectValue, actualValue) -} - -// mock structs -type dummyCustomization struct { - t *testing.T -} - -func (customization *dummyCustomization) PreBootstrap() error { - assert.Fail(customization.t, "Unexpected call to PreBootstrap") - return nil -} - -func (customization *dummyCustomization) PostBootstrap() error { - assert.Fail(customization.t, "Unexpected call to PostBootstrap") - return nil -} - -func (customization *dummyCustomization) AppClosing() error { - assert.Fail(customization.t, "Unexpected call to AppClosing") - return nil -} - -func (customization *dummyCustomization) Log(session Session, logType LogType, logLevel LogLevel, category, subcategory, description string) { - assert.Fail(customization.t, "Unexpected call to Log") -} - -func (customization *dummyCustomization) PreAction(session Session) error { - assert.Fail(customization.t, "Unexpected call to PreAction") - return nil -} - -func (customization *dummyCustomization) PostAction(session Session) error { - assert.Fail(customization.t, "Unexpected call to PostAction") - return nil -} - -func (customization *dummyCustomization) ActionFunc(session Session) error { - assert.Fail(customization.t, "Unexpected call to ActionFunc") - return nil -} - -func (customization *dummyCustomization) RecoverPanic(session Session, recoverResult interface{}) error { - assert.Fail(customization.t, "Unexpected call to RecoverPanic") - return nil -} - -func (customization *dummyCustomization) ClientCert() *tls.Certificate { - assert.Fail(customization.t, "Unexpected call to ClientCert") - return nil -} - -func (customization *dummyCustomization) DefaultTimeout() time.Duration { - assert.Fail(customization.t, "Unexpected call to DefaultTimeout") - return 0 -} - -func (customization *dummyCustomization) SkipServerCertVerification() bool { - assert.Fail(customization.t, "Unexpected call to SkipServerCertVerification") - return false -} - -func (customization *dummyCustomization) RoundTripper(originalTransport http.RoundTripper) http.RoundTripper { - assert.Fail(customization.t, "Unexpected call to RoundTripper") - return nil -} - -func (customization *dummyCustomization) WrapRequest(session Session, httpRequest *http.Request) *http.Request { - assert.Fail(customization.t, "Unexpected call to WrapRequest") - return nil -} - -type dummySession struct { - t *testing.T -} - -func (session *dummySession) GetID() uuid.UUID { - assert.Fail(session.t, "Unexpected call to GetID") - return uuid.Nil -} - -func (session *dummySession) GetIndex() int { - assert.Fail(session.t, "Unexpected call to GetIndex") - return 0 -} - -func (session *dummySession) GetReruns() int { - assert.Fail(session.t, "Unexpected call to GetReruns") - return 0 -} - -func (session *dummySession) Attach(name string, value interface{}) bool { - assert.Fail(session.t, "Unexpected call to Attach") - return false -} - -func (session *dummySession) Detach(name string) bool { - assert.Fail(session.t, "Unexpected call to Detach") - return false -} - -func (session *dummySession) GetRawAttachment(name string) (interface{}, bool) { - assert.Fail(session.t, "Unexpected call to GetRawAttachment") - return nil, false -} - -func (session *dummySession) GetAttachment(name string, dataTemplate interface{}) bool { - assert.Fail(session.t, "Unexpected call to GetAttachment") - return false -} - -func (session *dummySession) LogMethodEnter() { - assert.Fail(session.t, "Unexpected call to LogMethodEnter") -} - -func (session *dummySession) LogMethodParameter(parameters ...interface{}) { - assert.Fail(session.t, "Unexpected call to LogMethodParameter") -} - -func (session *dummySession) LogMethodLogic(logLevel LogLevel, category string, subcategory string, messageFormat string, parameters ...interface{}) { - assert.Fail(session.t, "Unexpected call to LogMethodLogic") -} - -func (session *dummySession) LogMethodReturn(returns ...interface{}) { - assert.Fail(session.t, "Unexpected call to LogMethodReturn") -} - -func (session *dummySession) LogMethodExit() { - assert.Fail(session.t, "Unexpected call to LogMethodExit") -} - -func (session *dummySession) CreateWebcallRequest(method string, url string, payload string, sendClientCert bool) WebRequest { - assert.Fail(session.t, "Unexpected call to CreateWebcallRequest") - return nil -} - -type dummyTransport struct { - t *testing.T -} - -func (transport *dummyTransport) RoundTrip(r *http.Request) (*http.Response, error) { - assert.Fail(transport.t, "Unexpected call to RoundTrip") - return nil, nil -} - -type dummySchedule struct { - t *testing.T - nextSchedule func() *time.Time -} - -func (dummySchedule *dummySchedule) NextSchedule() *time.Time { - if dummySchedule.nextSchedule != nil { - return dummySchedule.nextSchedule() - } - assert.Fail(dummySchedule.t, "Unexpected call to NextSchedule") - return nil -} diff --git a/application.go b/application.go index cc593b8..e66c8d5 100644 --- a/application.go +++ b/application.go @@ -3,6 +3,9 @@ package jobrunner import ( "sync" "sync/atomic" + "time" + + "github.com/google/uuid" ) // Application is the interface for job runner application @@ -33,9 +36,10 @@ type application struct { } // NewApplication creates a new application for job runner hosting -// instances marks how many action functions to be executed in parallel at once for a single scheduled execution -// schedule is a CRON schedule managing when the action functions should be executed until stop signal is given -// overlap marks a new execution should be executed or not when a previous execution has not yet completed +// +// instances marks how many action functions to be executed in parallel at once for a single scheduled execution +// schedule is a CRON schedule managing when the action functions should be executed until stop signal is given +// overlap marks a new execution should be executed or not when a previous execution has not yet completed func NewApplication( name string, version string, @@ -44,7 +48,7 @@ func NewApplication( overlap bool, customization Customization, ) Application { - if isInterfaceValueNilFunc(customization) { + if isInterfaceValueNil(customization) { customization = customizationDefault } var application = &application{ @@ -55,7 +59,7 @@ func NewApplication( schedule: schedule, overlap: overlap, session: &session{ - id: uuidNew(), + id: uuid.New(), index: 0, attachment: map[string]interface{}{}, customization: customization, @@ -70,7 +74,7 @@ func NewApplication( } func (app *application) Start() { - startApplicationFunc( + startApplication( app, ) } @@ -94,21 +98,21 @@ func startApplication(app *application) { if app.started { return } - if !preBootstrapingFunc(app) { + if !preBootstraping(app) { return } - bootstrapFunc(app) - if !postBootstrapingFunc(app) { + bootstrap(app) + if !postBootstraping(app) { return } - defer endApplicationFunc(app) - beginApplicationFunc(app) + defer endApplication(app) + beginApplication(app) } func preBootstraping(app *application) bool { var preBootstrapError = app.customization.PreBootstrap() if preBootstrapError != nil { - logAppRootFunc( + logAppRoot( app.session, "application", "preBootstraping", @@ -121,7 +125,7 @@ func preBootstraping(app *application) bool { ) return false } - logAppRootFunc( + logAppRoot( app.session, "application", "preBootstraping", @@ -131,13 +135,13 @@ func preBootstraping(app *application) bool { } func bootstrap(app *application) { - initializeHTTPClientsFunc( + initializeHTTPClients( app.customization.DefaultTimeout(), app.customization.SkipServerCertVerification(), app.customization.ClientCert(), app.customization.RoundTripper, ) - logAppRootFunc( + logAppRoot( app.session, "application", "bootstrap", @@ -148,7 +152,7 @@ func bootstrap(app *application) { func postBootstraping(app *application) bool { var postBootstrapError = app.customization.PostBootstrap() if postBootstrapError != nil { - logAppRootFunc( + logAppRoot( app.session, "application", "postBootstraping", @@ -161,7 +165,7 @@ func postBootstraping(app *application) bool { ) return false } - logAppRootFunc( + logAppRoot( app.session, "application", "postBootstraping", @@ -173,7 +177,7 @@ func postBootstraping(app *application) bool { func waitForNextRun(app *application) { var timeNext = app.schedule.NextSchedule() if timeNext == nil { - logAppRootFunc( + logAppRoot( app.session, "application", "waitForNextRun", @@ -183,9 +187,9 @@ func waitForNextRun(app *application) { return } var waitDuration = timeNext.Sub( - timeNow(), + time.Now(), ) - logAppRootFunc( + logAppRoot( app.session, "application", "waitForNextRun", @@ -193,7 +197,7 @@ func waitForNextRun(app *application) { *timeNext, waitDuration, ) - <-timeAfter( + <-time.After( waitDuration, ) } @@ -204,7 +208,7 @@ func runInstances(app *application) { waitGroup.Add(1) atomic.AddInt32(&app.reruns[id], 1) go func(index int, reruns int) { - var sessionError = handleSessionFunc( + var sessionError = handleSession( app, index, reruns, @@ -226,7 +230,7 @@ func runInstances(app *application) { func scheduleExecution(app *application) { for { - waitForNextRunFunc( + waitForNextRun( app, ) if !app.started { @@ -234,11 +238,11 @@ func scheduleExecution(app *application) { } if app.overlap { app.waits.Add(1) - go runInstancesFunc( + go runInstances( app, ) } else { - runInstancesFunc( + runInstances( app, ) } @@ -249,12 +253,12 @@ func scheduleExecution(app *application) { } func runApplication(app *application) { - if isInterfaceValueNilFunc(app.schedule) { - runInstancesFunc( + if isInterfaceValueNil(app.schedule) { + runInstances( app, ) } else { - scheduleExecutionFunc( + scheduleExecution( app, ) } @@ -262,7 +266,7 @@ func runApplication(app *application) { } func beginApplication(app *application) { - logAppRootFunc( + logAppRoot( app.session, "application", "beginApplication", @@ -271,10 +275,10 @@ func beginApplication(app *application) { app.version, ) app.started = true - go runApplicationFunc(app) + go runApplication(app) <-app.shutdown app.started = false - logAppRootFunc( + logAppRoot( app.session, "application", "beginApplication", @@ -285,7 +289,7 @@ func beginApplication(app *application) { func endApplication(app *application) { var appClosingError = app.customization.AppClosing() if appClosingError != nil { - logAppRootFunc( + logAppRoot( app.session, "application", "endApplication", @@ -297,7 +301,7 @@ func endApplication(app *application) { appClosingError, ) } else { - logAppRootFunc( + logAppRoot( app.session, "application", "endApplication", diff --git a/application_test.go b/application_test.go index 7625f4a..730c069 100644 --- a/application_test.go +++ b/application_test.go @@ -3,41 +3,44 @@ package jobrunner import ( "crypto/tls" "errors" - "math/rand" - "net/http" + "fmt" + "math/rand/v2" + "reflect" "sync" "testing" "time" "github.com/google/uuid" "github.com/stretchr/testify/assert" + "github.com/zhongjie-cai/gomocker/v2" ) +func functionPointerEquals(expectFunc interface{}, actualFunc interface{}) bool { + var expectValue = fmt.Sprintf("%v", reflect.ValueOf(expectFunc)) + var actualValue = fmt.Sprintf("%v", reflect.ValueOf(actualFunc)) + return expectValue == actualValue +} + +func assertFunctionEquals(t *testing.T, expectFunc interface{}, actualFunc interface{}) { + assert.True(t, functionPointerEquals(expectFunc, actualFunc)) +} + func TestNewApplication_NilCustomization(t *testing.T) { // arrange var dummyName = "some name" var dummyVersion = "some version" - var dummyInstances = rand.Intn(100) + var dummyInstances = rand.IntN(100) var dummySchedule Schedule - var dummyOverlap = rand.Intn(100) > 50 + var dummyOverlap = rand.IntN(100) > 50 var dummyCustomization Customization - var dummySessionID = uuid.New() + var dummySessionID = uuid.MustParse("00000000-0000-0000-0000-000000000001") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - isInterfaceValueNilFuncExpected = 1 - isInterfaceValueNilFunc = func(i interface{}) bool { - isInterfaceValueNilFuncCalled++ - assert.Equal(t, dummyCustomization, i) - return true - } - uuidNewExpected = 1 - uuidNew = func() uuid.UUID { - uuidNewCalled++ - return dummySessionID - } + m.Mock(isInterfaceValueNil).Expects(dummyCustomization).Returns(true).Once() + m.Mock(uuid.New).Expects().Returns(dummySessionID).Once() // SUT var result = NewApplication( @@ -66,36 +69,27 @@ func TestNewApplication_NilCustomization(t *testing.T) { assert.Empty(t, value.session.attachment) assert.Equal(t, customizationDefault, value.session.customization) assert.Equal(t, customizationDefault, value.customization) - - // verify - verifyAll(t) } func TestNewApplication_HasCustomization(t *testing.T) { // arrange var dummyName = "some name" var dummyVersion = "some version" - var dummyInstances = rand.Intn(100) + var dummyInstances = rand.IntN(100) var dummySchedule Schedule - var dummyOverlap = rand.Intn(100) > 50 - var dummyCustomization = &dummyCustomization{t: t} + var dummyOverlap = rand.IntN(100) > 50 + type customization struct { + Customization + } + var dummyCustomization = &customization{} var dummySessionID = uuid.New() // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - isInterfaceValueNilFuncExpected = 1 - isInterfaceValueNilFunc = func(i interface{}) bool { - isInterfaceValueNilFuncCalled++ - assert.Equal(t, dummyCustomization, i) - return false - } - uuidNewExpected = 1 - uuidNew = func() uuid.UUID { - uuidNewCalled++ - return dummySessionID - } + m.Mock(isInterfaceValueNil).Expects(dummyCustomization).Returns(false).Once() + m.Mock(uuid.New).Expects().Returns(dummySessionID).Once() // SUT var result = NewApplication( @@ -124,9 +118,6 @@ func TestNewApplication_HasCustomization(t *testing.T) { assert.Empty(t, value.session.attachment) assert.Equal(t, dummyCustomization, value.session.customization) assert.Equal(t, dummyCustomization, value.customization) - - // verify - verifyAll(t) } func TestApplication_Start(t *testing.T) { @@ -136,40 +127,27 @@ func TestApplication_Start(t *testing.T) { } // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - startApplicationFuncExpected = 1 - startApplicationFunc = func(app *application) { - startApplicationFuncCalled++ - assert.Equal(t, dummyApplication, app) - } + m.Mock(startApplication).Expects(dummyApplication).Returns().Once() // SUT + act dummyApplication.Start() - - // verify - verifyAll(t) } func TestApplication_IsRunning(t *testing.T) { // arrange var dummyApplication = &application{ name: "some name", - started: rand.Intn(100) > 50, + started: rand.IntN(100) > 50, } - // mock - createMock(t) - // SUT + act var result = dummyApplication.IsRunning() // assert assert.Equal(t, dummyApplication.started, result) - - // verify - verifyAll(t) } func TestApplication_LastErrors(t *testing.T) { @@ -184,17 +162,11 @@ func TestApplication_LastErrors(t *testing.T) { lastErrors: dummyLastErrors, } - // mock - createMock(t) - // SUT + act var result = dummyApplication.LastErrors() // assert assert.Equal(t, dummyApplication.lastErrors, result) - - // verify - verifyAll(t) } func TestApplication_Stop_NotStarted(t *testing.T) { @@ -204,14 +176,8 @@ func TestApplication_Stop_NotStarted(t *testing.T) { started: false, } - // mock - createMock(t) - // SUT + act dummyApplication.Stop() - - // verify - verifyAll(t) } func TestApplication_Stop_HasStarted(t *testing.T) { @@ -223,17 +189,11 @@ func TestApplication_Stop_HasStarted(t *testing.T) { started: true, } - // mock - createMock(t) - // SUT + act go dummyApplication.Stop() // assert assert.True(t, <-dummyShutdown) - - // verify - verifyAll(t) } func TestStartApplication_AlreadyStarted(t *testing.T) { @@ -243,14 +203,8 @@ func TestStartApplication_AlreadyStarted(t *testing.T) { started: true, } - // mock - createMock(t) - // SUT + act startApplication(dummyApplication) - - // verify - verifyAll(t) } func TestStartApplication_PreBootstrapingFailure(t *testing.T) { @@ -260,21 +214,13 @@ func TestStartApplication_PreBootstrapingFailure(t *testing.T) { } // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - preBootstrapingFuncExpected = 1 - preBootstrapingFunc = func(app *application) bool { - preBootstrapingFuncCalled++ - assert.Equal(t, dummyApplication, app) - return false - } + m.Mock(preBootstraping).Expects(dummyApplication).Returns(false).Once() // SUT + act startApplication(dummyApplication) - - // verify - verifyAll(t) } func TestStartApplication_PostBootstrapingFailure(t *testing.T) { @@ -284,32 +230,15 @@ func TestStartApplication_PostBootstrapingFailure(t *testing.T) { } // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - preBootstrapingFuncExpected = 1 - preBootstrapingFunc = func(app *application) bool { - preBootstrapingFuncCalled++ - assert.Equal(t, dummyApplication, app) - return true - } - bootstrapFuncExpected = 1 - bootstrapFunc = func(app *application) { - bootstrapFuncCalled++ - assert.Equal(t, dummyApplication, app) - } - postBootstrapingFuncExpected = 1 - postBootstrapingFunc = func(app *application) bool { - postBootstrapingFuncCalled++ - assert.Equal(t, dummyApplication, app) - return false - } + m.Mock(preBootstraping).Expects(dummyApplication).Returns(true).Once() + m.Mock(bootstrap).Expects(dummyApplication).Returns().Once() + m.Mock(postBootstraping).Expects(dummyApplication).Returns(false).Once() // SUT + act startApplication(dummyApplication) - - // verify - verifyAll(t) } func TestStartApplication_HappyPath(t *testing.T) { @@ -319,55 +248,17 @@ func TestStartApplication_HappyPath(t *testing.T) { } // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - preBootstrapingFuncExpected = 1 - preBootstrapingFunc = func(app *application) bool { - preBootstrapingFuncCalled++ - assert.Equal(t, dummyApplication, app) - return true - } - bootstrapFuncExpected = 1 - bootstrapFunc = func(app *application) { - bootstrapFuncCalled++ - assert.Equal(t, dummyApplication, app) - } - postBootstrapingFuncExpected = 1 - postBootstrapingFunc = func(app *application) bool { - postBootstrapingFuncCalled++ - assert.Equal(t, dummyApplication, app) - return true - } - beginApplicationFuncExpected = 1 - beginApplicationFunc = func(app *application) { - beginApplicationFuncCalled++ - assert.Equal(t, dummyApplication, app) - } - endApplicationFuncExpected = 1 - endApplicationFunc = func(app *application) { - endApplicationFuncCalled++ - assert.Equal(t, dummyApplication, app) - } + m.Mock(preBootstraping).Expects(dummyApplication).Returns(true).Once() + m.Mock(bootstrap).Expects(dummyApplication).Returns().Once() + m.Mock(postBootstraping).Expects(dummyApplication).Returns(true).Once() + m.Mock(beginApplication).Expects(dummyApplication).Returns().Once() + m.Mock(endApplication).Expects(dummyApplication).Returns().Once() // SUT + act startApplication(dummyApplication) - - // verify - verifyAll(t) -} - -type dummyCustomizationPreBootstrapping struct { - dummyCustomization - preBootstrap func() error -} - -func (customization *dummyCustomizationPreBootstrapping) PreBootstrap() error { - if customization.preBootstrap != nil { - return customization.preBootstrap() - } - assert.Fail(customization.t, "Unexpected call to PreBootstrap") - return nil } func TestPreBootstraping_Error(t *testing.T) { @@ -375,37 +266,24 @@ func TestPreBootstraping_Error(t *testing.T) { var dummySession = &session{ id: uuid.New(), } - var dummyCustomization = &dummyCustomizationPreBootstrapping{ - dummyCustomization: dummyCustomization{t: t}, + type customization struct { + Customization } + var dummyCustomization = &customization{} var dummyApplication = &application{ session: dummySession, customization: dummyCustomization, } - var customizationPreBootstrapExpected int - var customizationPreBootstrapCalled int var dummyError = errors.New("some error") var dummyMessageFormat = "Failed to execute customization.PreBootstrap. Error: %+v" // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - customizationPreBootstrapExpected = 1 - dummyCustomization.preBootstrap = func() error { - customizationPreBootstrapCalled++ - return dummyError - } - logAppRootFuncExpected = 1 - logAppRootFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logAppRootFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, "application", category) - assert.Equal(t, "preBootstraping", subcategory) - assert.Equal(t, dummyMessageFormat, messageFormat) - assert.Equal(t, 1, len(parameters)) - assert.Equal(t, dummyError, parameters[0]) - } + m.Mock((*customization).PreBootstrap).Expects(dummyCustomization).Returns(dummyError).Once() + m.Mock(logAppRoot).Expects(dummySession, "application", "preBootstraping", + dummyMessageFormat, dummyError).Returns().Once() // SUT + act var result = preBootstraping( @@ -414,12 +292,8 @@ func TestPreBootstraping_Error(t *testing.T) { // assert assert.False(t, result) - assert.Equal(t, 1, len(dummyApplication.lastErrors)) + assert.Len(t, dummyApplication.lastErrors, 1) assert.Equal(t, dummyError, dummyApplication.lastErrors[0]) - - // verify - verifyAll(t) - assert.Equal(t, customizationPreBootstrapExpected, customizationPreBootstrapCalled, "Unexpected number of calls to method customization.PreBootstrap") } func TestPreBootstraping_Success(t *testing.T) { @@ -427,35 +301,23 @@ func TestPreBootstraping_Success(t *testing.T) { var dummySession = &session{ id: uuid.New(), } - var dummyCustomization = &dummyCustomizationPreBootstrapping{ - dummyCustomization: dummyCustomization{t: t}, + type customization struct { + Customization } + var dummyCustomization = &customization{} var dummyApplication = &application{ session: dummySession, customization: dummyCustomization, } - var customizationPreBootstrapExpected int - var customizationPreBootstrapCalled int var dummyMessageFormat = "customization.PreBootstrap executed successfully" // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - customizationPreBootstrapExpected = 1 - dummyCustomization.preBootstrap = func() error { - customizationPreBootstrapCalled++ - return nil - } - logAppRootFuncExpected = 1 - logAppRootFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logAppRootFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, "application", category) - assert.Equal(t, "preBootstraping", subcategory) - assert.Equal(t, dummyMessageFormat, messageFormat) - assert.Empty(t, parameters) - } + m.Mock((*customization).PreBootstrap).Expects(dummyCustomization).Returns(nil).Once() + m.Mock(logAppRoot).Expects(dummySession, "application", + "preBootstraping", dummyMessageFormat).Returns().Once() // SUT + act var result = preBootstraping( @@ -465,50 +327,6 @@ func TestPreBootstraping_Success(t *testing.T) { // assert assert.True(t, result) assert.Empty(t, dummyApplication.lastErrors) - - // verify - verifyAll(t) - assert.Equal(t, customizationPreBootstrapExpected, customizationPreBootstrapCalled, "Unexpected number of calls to method customization.PreBootstrap") -} - -type dummyCustomizationBootstrap struct { - dummyCustomization - clientCert func() *tls.Certificate - defaultTimeout func() time.Duration - skipServerCertVerification func() bool - roundTripper func(http.RoundTripper) http.RoundTripper -} - -func (customization *dummyCustomizationBootstrap) ClientCert() *tls.Certificate { - if customization.clientCert != nil { - return customization.clientCert() - } - assert.Fail(customization.t, "Unexpected call to ClientCert") - return nil -} - -func (customization *dummyCustomizationBootstrap) DefaultTimeout() time.Duration { - if customization.defaultTimeout != nil { - return customization.defaultTimeout() - } - assert.Fail(customization.t, "Unexpected call to DefaultTimeout") - return 0 -} - -func (customization *dummyCustomizationBootstrap) SkipServerCertVerification() bool { - if customization.skipServerCertVerification != nil { - return customization.skipServerCertVerification() - } - assert.Fail(customization.t, "Unexpected call to SkipServerCertVerification") - return false -} - -func (customization *dummyCustomizationBootstrap) RoundTripper(originalTransport http.RoundTripper) http.RoundTripper { - if customization.roundTripper != nil { - return customization.roundTripper(originalTransport) - } - assert.Fail(customization.t, "Unexpected call to RoundTripper") - return nil } func TestBootstrap_HappyPath(t *testing.T) { @@ -516,94 +334,34 @@ func TestBootstrap_HappyPath(t *testing.T) { var dummySession = &session{ id: uuid.New(), } - var dummyCustomization = &dummyCustomizationBootstrap{ - dummyCustomization: dummyCustomization{t: t}, + type customization struct { + Customization } + var dummyCustomization = &customization{} var dummyApplication = &application{ session: dummySession, customization: dummyCustomization, } - var customizationDefaultTimeoutExpected int - var customizationDefaultTimeoutCalled int - var customizationSkipServerCertVerificationExpected int - var customizationSkipServerCertVerificationCalled int - var customizationClientCertExpected int - var customizationClientCertCalled int - var customizationRoundTripperExpected int - var customizationRoundTripperCalled int - var dummyWebcallTimeout = time.Duration(rand.Intn(100)) - var dummySkipCertVerification = rand.Intn(100) > 50 + var dummyWebcallTimeout = time.Duration(rand.IntN(100)) + var dummySkipCertVerification = rand.IntN(100) > 50 var dummyClientCertificate = &tls.Certificate{Certificate: [][]byte{{0}}} - var dummyOriginalTransport = &dummyTransport{t: t} var dummyMessageFormat = "Application bootstrapped successfully" // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - initializeHTTPClientsFuncExpected = 1 - initializeHTTPClientsFunc = func(webcallTimeout time.Duration, skipServerCertVerification bool, clientCertificate *tls.Certificate, roundTripperWrapper func(originalTransport http.RoundTripper) http.RoundTripper) { - initializeHTTPClientsFuncCalled++ - assert.Equal(t, dummyWebcallTimeout, webcallTimeout) - assert.Equal(t, dummySkipCertVerification, skipServerCertVerification) - assert.Equal(t, dummyClientCertificate, clientCertificate) - roundTripperWrapper(dummyOriginalTransport) - } - customizationDefaultTimeoutExpected = 1 - dummyCustomization.defaultTimeout = func() time.Duration { - customizationDefaultTimeoutCalled++ - return dummyWebcallTimeout - } - customizationSkipServerCertVerificationExpected = 1 - dummyCustomization.skipServerCertVerification = func() bool { - customizationSkipServerCertVerificationCalled++ - return dummySkipCertVerification - } - customizationClientCertExpected = 1 - dummyCustomization.clientCert = func() *tls.Certificate { - customizationClientCertCalled++ - return dummyClientCertificate - } - customizationRoundTripperExpected = 1 - dummyCustomization.roundTripper = func(originalTransport http.RoundTripper) http.RoundTripper { - customizationRoundTripperCalled++ - assert.Equal(t, dummyOriginalTransport, originalTransport) - return originalTransport - } - logAppRootFuncExpected = 1 - logAppRootFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logAppRootFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, "application", category) - assert.Equal(t, "bootstrap", subcategory) - assert.Equal(t, dummyMessageFormat, messageFormat) - assert.Empty(t, parameters) - } + m.Mock(initializeHTTPClients).Expects(dummyWebcallTimeout, dummySkipCertVerification, + dummyClientCertificate, gomocker.Anything()).Returns().Once() + m.Mock((*customization).DefaultTimeout).Expects(dummyCustomization).Returns(dummyWebcallTimeout).Once() + m.Mock((*customization).SkipServerCertVerification).Expects(dummyCustomization).Returns(dummySkipCertVerification).Once() + m.Mock((*customization).ClientCert).Expects(dummyCustomization).Returns(dummyClientCertificate).Once() + m.Mock(logAppRoot).Expects(dummySession, "application", "bootstrap", dummyMessageFormat).Returns().Once() // SUT + act bootstrap( dummyApplication, ) - - // verify - verifyAll(t) - assert.Equal(t, customizationDefaultTimeoutExpected, customizationDefaultTimeoutCalled, "Unexpected number of calls to method customization.DefaultTimeout") - assert.Equal(t, customizationSkipServerCertVerificationExpected, customizationSkipServerCertVerificationCalled, "Unexpected number of calls to method customization.SkipServerCertVerification") - assert.Equal(t, customizationClientCertExpected, customizationClientCertCalled, "Unexpected number of calls to method customization.ClientCert") - assert.Equal(t, customizationRoundTripperExpected, customizationRoundTripperCalled, "Unexpected number of calls to method customization.RoundTripper") -} - -type dummyCustomizationPostBootstrapping struct { - dummyCustomization - postBootstrap func() error -} - -func (customization *dummyCustomizationPostBootstrapping) PostBootstrap() error { - if customization.postBootstrap != nil { - return customization.postBootstrap() - } - assert.Fail(customization.t, "Unexpected call to PostBootstrap") - return nil } func TestPostBootstraping_Error(t *testing.T) { @@ -611,37 +369,24 @@ func TestPostBootstraping_Error(t *testing.T) { var dummySession = &session{ id: uuid.New(), } - var dummyCustomization = &dummyCustomizationPostBootstrapping{ - dummyCustomization: dummyCustomization{t: t}, + type customization struct { + Customization } + var dummyCustomization = &customization{} var dummyApplication = &application{ session: dummySession, customization: dummyCustomization, } - var customizationPostBootstrapExpected int - var customizationPostBootstrapCalled int var dummyError = errors.New("some error") var dummyMessageFormat = "Failed to execute customization.PostBootstrap. Error: %+v" // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - customizationPostBootstrapExpected = 1 - dummyCustomization.postBootstrap = func() error { - customizationPostBootstrapCalled++ - return dummyError - } - logAppRootFuncExpected = 1 - logAppRootFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logAppRootFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, "application", category) - assert.Equal(t, "postBootstraping", subcategory) - assert.Equal(t, dummyMessageFormat, messageFormat) - assert.Equal(t, 1, len(parameters)) - assert.Equal(t, dummyError, parameters[0]) - } + m.Mock((*customization).PostBootstrap).Expects(dummyCustomization).Returns(dummyError).Once() + m.Mock(logAppRoot).Expects(dummySession, "application", "postBootstraping", + dummyMessageFormat, dummyError).Returns().Once() // SUT + act var result = postBootstraping( @@ -650,12 +395,8 @@ func TestPostBootstraping_Error(t *testing.T) { // assert assert.False(t, result) - assert.Equal(t, 1, len(dummyApplication.lastErrors)) + assert.Len(t, dummyApplication.lastErrors, 1) assert.Equal(t, dummyError, dummyApplication.lastErrors[0]) - - // verify - verifyAll(t) - assert.Equal(t, customizationPostBootstrapExpected, customizationPostBootstrapCalled, "Unexpected number of calls to method customization.PostBootstrap") } func TestPostBootstraping_Success(t *testing.T) { @@ -663,35 +404,23 @@ func TestPostBootstraping_Success(t *testing.T) { var dummySession = &session{ id: uuid.New(), } - var dummyCustomization = &dummyCustomizationPostBootstrapping{ - dummyCustomization: dummyCustomization{t: t}, + type customization struct { + Customization } + var dummyCustomization = &customization{} var dummyApplication = &application{ session: dummySession, customization: dummyCustomization, } - var customizationPostBootstrapExpected int - var customizationPostBootstrapCalled int var dummyMessageFormat = "customization.PostBootstrap executed successfully" // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - customizationPostBootstrapExpected = 1 - dummyCustomization.postBootstrap = func() error { - customizationPostBootstrapCalled++ - return nil - } - logAppRootFuncExpected = 1 - logAppRootFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logAppRootFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, "application", category) - assert.Equal(t, "postBootstraping", subcategory) - assert.Equal(t, dummyMessageFormat, messageFormat) - assert.Empty(t, parameters) - } + m.Mock((*customization).PostBootstrap).Expects(dummyCustomization).Returns(nil).Once() + m.Mock(logAppRoot).Expects(dummySession, "application", + "postBootstraping", dummyMessageFormat).Returns().Once() // SUT + act var result = postBootstraping( @@ -701,15 +430,14 @@ func TestPostBootstraping_Success(t *testing.T) { // assert assert.True(t, result) assert.Empty(t, dummyApplication.lastErrors) - - // verify - verifyAll(t) - assert.Equal(t, customizationPostBootstrapExpected, customizationPostBootstrapCalled, "Unexpected number of calls to method customization.PostBootstrap") } func TestWaitForNextRun_NilNextSchedule(t *testing.T) { // arrange - var dummySchedule = &dummySchedule{t: t} + type schedule struct { + Schedule + } + var dummySchedule = &schedule{} var dummySession = &session{id: uuid.New()} var dummyApplication = &application{ name: "some name", @@ -719,27 +447,14 @@ func TestWaitForNextRun_NilNextSchedule(t *testing.T) { } var dummyTimeNext *time.Time var dummyMessageFormat = "No next schedule available, terminating execution" - var scheduleNextScheduleExpected int - var scheduleNextScheduleCalled int // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - scheduleNextScheduleExpected = 1 - dummySchedule.nextSchedule = func() *time.Time { - scheduleNextScheduleCalled++ - return dummyTimeNext - } - logAppRootFuncExpected = 1 - logAppRootFunc = func(session *session, category, subcategory, messageFormat string, parameters ...interface{}) { - logAppRootFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, "application", category) - assert.Equal(t, "waitForNextRun", subcategory) - assert.Equal(t, dummyMessageFormat, messageFormat) - assert.Empty(t, parameters) - } + m.Mock((*schedule).NextSchedule).Expects(dummySchedule).Returns(dummyTimeNext).Once() + m.Mock(logAppRoot).Expects(dummySession, "application", + "waitForNextRun", dummyMessageFormat).Returns().Once() // SUT + act waitForNextRun( @@ -748,15 +463,14 @@ func TestWaitForNextRun_NilNextSchedule(t *testing.T) { // assert assert.False(t, dummyApplication.started) - - // verify - verifyAll(t) - assert.Equal(t, scheduleNextScheduleExpected, scheduleNextScheduleCalled, "Unexpected number of calls to schedule.Wait") } func TestWaitForNextRun_ValidNextSchedule(t *testing.T) { // arrange - var dummySchedule = &dummySchedule{t: t} + type schedule struct { + Schedule + } + var dummySchedule = &schedule{} var dummySession = &session{id: uuid.New()} var dummyApplication = &application{ name: "some name", @@ -764,44 +478,20 @@ func TestWaitForNextRun_ValidNextSchedule(t *testing.T) { session: dummySession, } var dummyTimeNow = time.Now() - var dummyDuration = time.Duration(rand.Intn(1000)) + 10*time.Second + var dummyDuration = time.Duration(rand.IntN(1000)) + 10*time.Second var dummyTimeNext = dummyTimeNow.Add(dummyDuration) var dummyMessageFormat = "Next run at [%v]: waiting for [%v]" var dummyControlChannel = make(chan time.Time) - var scheduleNextScheduleExpected int - var scheduleNextScheduleCalled int // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - scheduleNextScheduleExpected = 1 - dummySchedule.nextSchedule = func() *time.Time { - scheduleNextScheduleCalled++ - return &dummyTimeNext - } - timeNowExpected = 1 - timeNow = func() time.Time { - timeNowCalled++ - return dummyTimeNow - } - logAppRootFuncExpected = 1 - logAppRootFunc = func(session *session, category, subcategory, messageFormat string, parameters ...interface{}) { - logAppRootFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, "application", category) - assert.Equal(t, "waitForNextRun", subcategory) - assert.Equal(t, dummyMessageFormat, messageFormat) - assert.Equal(t, 2, len(parameters)) - assert.Equal(t, dummyTimeNext, parameters[0]) - assert.Equal(t, dummyDuration, parameters[1]) - } - timeAfterExpected = 1 - timeAfter = func(d time.Duration) <-chan time.Time { - timeAfterCalled++ - assert.Equal(t, dummyDuration, d) - return dummyControlChannel - } + m.Mock((*schedule).NextSchedule).Expects(dummySchedule).Returns(&dummyTimeNext).Once() + m.Mock(time.Now).Expects().Returns(dummyTimeNow).Once() + m.Mock(logAppRoot).Expects(dummySession, "application", "waitForNextRun", + dummyMessageFormat, dummyTimeNext, dummyDuration).Returns().Once() + m.Mock(time.After).Expects(dummyDuration).Returns(dummyControlChannel).Once() // SUT + act go waitForNextRun( @@ -810,31 +500,21 @@ func TestWaitForNextRun_ValidNextSchedule(t *testing.T) { // push dummyControlChannel <- dummyTimeNext - - // verify - verifyAll(t) - assert.Equal(t, scheduleNextScheduleExpected, scheduleNextScheduleCalled, "Unexpected number of calls to schedule.Wait") } func TestRunInstances_ZeroInstance(t *testing.T) { // arrange var dummyApplication = &application{} - // mock - createMock(t) - // SUT + act runInstances( dummyApplication, ) - - // verify - verifyAll(t) } func TestRunInstances_SingleInstance(t *testing.T) { // arrange - var dummyReruns = rand.Int31n(65535) + var dummyReruns = rand.Int32N(65535) var dummyApplication = &application{ instances: 1, reruns: []int32{dummyReruns}, @@ -842,17 +522,10 @@ func TestRunInstances_SingleInstance(t *testing.T) { var dummyError = errors.New("some error") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - handleSessionFuncExpected = 1 - handleSessionFunc = func(app *application, index int, reruns int) error { - handleSessionFuncCalled++ - assert.Equal(t, dummyApplication, app) - assert.Equal(t, 0, index) - assert.Equal(t, int(dummyReruns)+1, reruns) - return dummyError - } + m.Mock(handleSession).Expects(dummyApplication, 0, int(dummyReruns)+1).Returns(dummyError).Once() // SUT + act runInstances( @@ -860,11 +533,8 @@ func TestRunInstances_SingleInstance(t *testing.T) { ) // assert - assert.Equal(t, 1, len(dummyApplication.lastErrors)) + assert.Len(t, dummyApplication.lastErrors, 1) assert.Equal(t, dummyError, dummyApplication.lastErrors[0]) - - // verify - verifyAll(t) } func TestRunInstances_MultipleInstances(t *testing.T) { @@ -875,25 +545,31 @@ func TestRunInstances_MultipleInstances(t *testing.T) { errors.New("some error 3"), } var dummyApplication = &application{ - instances: len(dummyErrors), - reruns: make([]int32, len(dummyErrors)), + instances: 3, + reruns: make([]int32, 3), + } + var calls = map[int]bool{} + var lock = sync.RWMutex{} + + // stub + var callChecker = func(value interface{}) bool { + lock.Lock() + defer lock.Unlock() + var called, found = calls[value.(int)] + if found || called { + return false + } + calls[value.(int)] = true + return true } - var expectedIndex = map[int]bool{} - var writeLock sync.Mutex // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - handleSessionFuncExpected = dummyApplication.instances - handleSessionFunc = func(app *application, index int, reruns int) error { - handleSessionFuncCalled++ - assert.Equal(t, dummyApplication, app) - writeLock.Lock() - expectedIndex[index] = true - writeLock.Unlock() - return dummyErrors[index] - } + m.Mock(handleSession).Expects(dummyApplication, gomocker.Matches(callChecker), 1).Returns(dummyErrors[0]).Once() + m.Mock(handleSession).Expects(dummyApplication, gomocker.Matches(callChecker), 1).Returns(dummyErrors[1]).Once() + m.Mock(handleSession).Expects(dummyApplication, gomocker.Matches(callChecker), 1).Returns(dummyErrors[2]).Once() // SUT + act runInstances( @@ -901,20 +577,13 @@ func TestRunInstances_MultipleInstances(t *testing.T) { ) // assert - assert.Equal(t, dummyApplication.instances, len(expectedIndex)) - assert.True(t, expectedIndex[0]) - assert.True(t, expectedIndex[1]) - assert.True(t, expectedIndex[2]) - assert.Equal(t, dummyApplication.instances, len(dummyApplication.lastErrors)) + assert.Len(t, dummyApplication.lastErrors, 3) assert.ElementsMatch(t, dummyErrors, dummyApplication.lastErrors) - - // verify - verifyAll(t) } func TestRunInstances_Overlap(t *testing.T) { // arrange - var dummyReruns = rand.Int31n(65535) + var dummyReruns = rand.Int32N(65535) var dummyApplication = &application{ instances: 1, reruns: []int32{dummyReruns}, @@ -926,17 +595,10 @@ func TestRunInstances_Overlap(t *testing.T) { dummyApplication.waits.Add(1) // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - handleSessionFuncExpected = 1 - handleSessionFunc = func(app *application, index int, reruns int) error { - handleSessionFuncCalled++ - assert.Equal(t, dummyApplication, app) - assert.Equal(t, 0, index) - assert.Equal(t, int(dummyReruns)+1, reruns) - return dummyError - } + m.Mock(handleSession).Expects(dummyApplication, 0, int(dummyReruns)+1).Returns(dummyError).Once() // SUT + act runInstances( @@ -944,11 +606,8 @@ func TestRunInstances_Overlap(t *testing.T) { ) // assert - assert.Equal(t, 1, len(dummyApplication.lastErrors)) + assert.Len(t, dummyApplication.lastErrors, 1) assert.Equal(t, dummyError, dummyApplication.lastErrors[0]) - - // verify - verifyAll(t) } func TestScheduleExecution_WithOverlap(t *testing.T) { @@ -958,36 +617,25 @@ func TestScheduleExecution_WithOverlap(t *testing.T) { started: true, overlap: true, } - var controlFlag = make(chan bool) // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - waitForNextRunFuncExpected = 2 - waitForNextRunFunc = func(app *application) { - waitForNextRunFuncCalled++ - assert.Equal(t, dummyApplication, app) - app.started = (waitForNextRunFuncCalled < waitForNextRunFuncExpected) - <-controlFlag - } - runInstancesFuncExpected = 1 - runInstancesFunc = func(app *application) { - runInstancesFuncCalled++ - assert.Equal(t, dummyApplication, app) - controlFlag <- true - } + m.Mock(waitForNextRun).Expects(dummyApplication).Returns().Once() + m.Mock(runInstances).Expects(dummyApplication).Returns().SideEffect( + func(index int, params ...interface{}) { + dummyApplication.waits.Done() + }).Once() + m.Mock(waitForNextRun).Expects(dummyApplication).Returns().SideEffect( + func(index int, params ...interface{}) { + dummyApplication.started = false + }).Once() // SUT + act - go scheduleExecution( + scheduleExecution( dummyApplication, ) - - // push - controlFlag <- true - - // verify - verifyAll(t) } func TestScheduleExecution_NoOverlap(t *testing.T) { @@ -999,34 +647,28 @@ func TestScheduleExecution_NoOverlap(t *testing.T) { } // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - waitForNextRunFuncExpected = 2 - waitForNextRunFunc = func(app *application) { - waitForNextRunFuncCalled++ - assert.Equal(t, dummyApplication, app) - app.started = (waitForNextRunFuncCalled < waitForNextRunFuncExpected) - } - runInstancesFuncExpected = 1 - runInstancesFunc = func(app *application) { - runInstancesFuncCalled++ - assert.Equal(t, dummyApplication, app) - } + m.Mock(waitForNextRun).Expects(dummyApplication).Returns().Once() + m.Mock(runInstances).Expects(dummyApplication).Returns().Once() + m.Mock(waitForNextRun).Expects(dummyApplication).Returns().SideEffect(func(index int, params ...interface{}) { + dummyApplication.started = false + }).Once() // SUT + act scheduleExecution( dummyApplication, ) - - // verify - verifyAll(t) } func TestRunApplication_NoSchedule(t *testing.T) { // arrange var dummyShutdown = make(chan bool) - var dummySchedule = &dummySchedule{t: t} + type schedule struct { + Schedule + } + var dummySchedule = &schedule{} var dummyApplication = &application{ name: "some name", shutdown: dummyShutdown, @@ -1034,20 +676,11 @@ func TestRunApplication_NoSchedule(t *testing.T) { } // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - isInterfaceValueNilFuncExpected = 1 - isInterfaceValueNilFunc = func(i interface{}) bool { - isInterfaceValueNilFuncCalled++ - assert.Equal(t, dummySchedule, i) - return true - } - runInstancesFuncExpected = 1 - runInstancesFunc = func(app *application) { - runInstancesFuncCalled++ - assert.Equal(t, dummyApplication, app) - } + m.Mock(isInterfaceValueNil).Expects(dummySchedule).Returns(true).Once() + m.Mock(runInstances).Expects(dummyApplication).Returns().Once() // SUT + act go runApplication( @@ -1056,15 +689,15 @@ func TestRunApplication_NoSchedule(t *testing.T) { // assert assert.True(t, <-dummyShutdown) - - // verify - verifyAll(t) } func TestRunApplication_WithSchedule(t *testing.T) { // arrange var dummyShutdown = make(chan bool) - var dummySchedule = &dummySchedule{t: t} + type schedule struct { + Schedule + } + var dummySchedule = &schedule{} var dummyApplication = &application{ name: "some name", shutdown: dummyShutdown, @@ -1072,20 +705,11 @@ func TestRunApplication_WithSchedule(t *testing.T) { } // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - isInterfaceValueNilFuncExpected = 1 - isInterfaceValueNilFunc = func(i interface{}) bool { - isInterfaceValueNilFuncCalled++ - assert.Equal(t, dummySchedule, i) - return false - } - scheduleExecutionFuncExpected = 1 - scheduleExecutionFunc = func(app *application) { - scheduleExecutionFuncCalled++ - assert.Equal(t, dummyApplication, app) - } + m.Mock(isInterfaceValueNil).Expects(dummySchedule).Returns(false).Once() + m.Mock(scheduleExecution).Expects(dummyApplication).Returns().Once() // SUT + act go runApplication( @@ -1094,9 +718,6 @@ func TestRunApplication_WithSchedule(t *testing.T) { // assert assert.True(t, <-dummyShutdown) - - // verify - verifyAll(t) } func TestBeginApplication_HappyPath(t *testing.T) { @@ -1113,32 +734,15 @@ func TestBeginApplication_HappyPath(t *testing.T) { } // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - runApplicationFuncExpected = 1 - runApplicationFunc = func(app *application) { - runApplicationFuncCalled++ - assert.True(t, dummyApplication.started) - assert.Equal(t, dummyApplication, app) + m.Mock(runApplication).Expects(dummyApplication).Returns().SideEffect(func(index int, params ...interface{}) { dummyShutdown <- true - } - logAppRootFuncExpected = 2 - logAppRootFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logAppRootFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, "application", category) - assert.Equal(t, "beginApplication", subcategory) - if logAppRootFuncCalled == 1 { - assert.Equal(t, "Trying to start runner [%v] (v-%v)", messageFormat) - assert.Equal(t, 2, len(parameters)) - assert.Equal(t, dummyName, parameters[0]) - assert.Equal(t, dummyVersion, parameters[1]) - } else if logAppRootFuncCalled == 2 { - assert.Equal(t, "Runner terminated", messageFormat) - assert.Empty(t, parameters) - } - } + }).Once() + m.Mock(logAppRoot).Expects(dummySession, "application", "beginApplication", + "Trying to start runner [%v] (v-%v)", dummyName, dummyVersion).Returns().Once() + m.Mock(logAppRoot).Expects(dummySession, "application", "beginApplication", "Runner terminated").Returns().Once() // SUT + act beginApplication( @@ -1147,22 +751,6 @@ func TestBeginApplication_HappyPath(t *testing.T) { // assert assert.False(t, dummyApplication.started) - - // verify - verifyAll(t) -} - -type dummyCustomizationEndApplication struct { - dummyCustomization - appClosing func() error -} - -func (customization *dummyCustomizationEndApplication) AppClosing() error { - if customization.appClosing != nil { - return customization.appClosing() - } - assert.Fail(customization.t, "Unexpected call to AppClosing") - return nil } func TestEndApplication_Error(t *testing.T) { @@ -1170,37 +758,24 @@ func TestEndApplication_Error(t *testing.T) { var dummySession = &session{ id: uuid.New(), } - var dummyCustomization = &dummyCustomizationEndApplication{ - dummyCustomization: dummyCustomization{t: t}, + type customization struct { + Customization } + var dummyCustomization = &customization{} var dummyApplication = &application{ session: dummySession, customization: dummyCustomization, } - var customizationAppClosingExpected int - var customizationAppClosingCalled int var dummyError = errors.New("some error") var dummyMessageFormat = "Failed to execute customization.AppClosing. Error: %+v" // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - customizationAppClosingExpected = 1 - dummyCustomization.appClosing = func() error { - customizationAppClosingCalled++ - return dummyError - } - logAppRootFuncExpected = 1 - logAppRootFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logAppRootFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, "application", category) - assert.Equal(t, "endApplication", subcategory) - assert.Equal(t, dummyMessageFormat, messageFormat) - assert.Equal(t, 1, len(parameters)) - assert.Equal(t, dummyError, parameters[0]) - } + m.Mock((*customization).AppClosing).Expects(dummyCustomization).Returns(dummyError).Once() + m.Mock(logAppRoot).Expects(dummySession, "application", "endApplication", + dummyMessageFormat, dummyError).Returns().Once() // SUT + act endApplication( @@ -1208,12 +783,8 @@ func TestEndApplication_Error(t *testing.T) { ) // assert - assert.Equal(t, 1, len(dummyApplication.lastErrors)) + assert.Len(t, dummyApplication.lastErrors, 1) assert.Equal(t, dummyError, dummyApplication.lastErrors[0]) - - // verify - verifyAll(t) - assert.Equal(t, customizationAppClosingExpected, customizationAppClosingCalled, "Unexpected number of calls to method customization.AppClosing") } func TestEndApplication_Success(t *testing.T) { @@ -1221,35 +792,23 @@ func TestEndApplication_Success(t *testing.T) { var dummySession = &session{ id: uuid.New(), } - var dummyCustomization = &dummyCustomizationEndApplication{ - dummyCustomization: dummyCustomization{t: t}, + type customization struct { + Customization } + var dummyCustomization = &customization{} var dummyApplication = &application{ session: dummySession, customization: dummyCustomization, } - var customizationAppClosingExpected int - var customizationAppClosingCalled int var dummyMessageFormat = "customization.AppClosing executed successfully" // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - customizationAppClosingExpected = 1 - dummyCustomization.appClosing = func() error { - customizationAppClosingCalled++ - return nil - } - logAppRootFuncExpected = 1 - logAppRootFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logAppRootFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, "application", category) - assert.Equal(t, "endApplication", subcategory) - assert.Equal(t, dummyMessageFormat, messageFormat) - assert.Empty(t, parameters) - } + m.Mock((*customization).AppClosing).Expects(dummyCustomization).Returns(nil).Once() + m.Mock(logAppRoot).Expects(dummySession, "application", + "endApplication", dummyMessageFormat).Returns().Once() // SUT + act endApplication( @@ -1258,8 +817,4 @@ func TestEndApplication_Success(t *testing.T) { // assert assert.Empty(t, dummyApplication.lastErrors) - - // verify - verifyAll(t) - assert.Equal(t, customizationAppClosingExpected, customizationAppClosingCalled, "Unexpected number of calls to method customization.AppClosing") } diff --git a/customization.go b/customization.go index 219bd57..c6e2559 100644 --- a/customization.go +++ b/customization.go @@ -2,6 +2,7 @@ package jobrunner import ( "crypto/tls" + "fmt" "net/http" "time" ) @@ -108,23 +109,21 @@ func (customization *DefaultCustomization) ActionFunc(session Session) error { // RecoverPanic is to customize the recovery of panic into a valid response and error in case it happens (for recoverable panic only) func (customization *DefaultCustomization) RecoverPanic(session Session, recoverResult interface{}) error { - if isInterfaceValueNilFunc(recoverResult) { + if isInterfaceValueNil(recoverResult) { return nil } var recoverError, ok = recoverResult.(error) if !ok { - recoverError = fmtErrorf("%v", recoverResult) + recoverError = fmt.Errorf("%v", recoverResult) } return recoverError } // Log is to customize the logging backend for the whole application func (customization *DefaultCustomization) Log(session Session, logType LogType, logLevel LogLevel, category, subcategory, description string) { - if isInterfaceValueNilFunc(session) { - return - } - fmtPrintf( - "<%v|%v> (%v|%v) [%v|%v] %v\n", + fmt.Printf( + "[%v] <%v|%v> (%v|%v) [%v|%v] %v\n", + formatDateTime(time.Now()), session.GetID(), session.GetIndex(), logType, diff --git a/customization_test.go b/customization_test.go index 9ced68d..ab40057 100644 --- a/customization_test.go +++ b/customization_test.go @@ -2,163 +2,74 @@ package jobrunner import ( "errors" - "math/rand" + "fmt" + "math/rand/v2" "net/http" "testing" "time" "github.com/google/uuid" "github.com/stretchr/testify/assert" + "github.com/zhongjie-cai/gomocker/v2" ) func TestDefaultCustomization_PreBootstrap(t *testing.T) { - // mock - createMock(t) - // SUT + act var err = customizationDefault.PreBootstrap() // assert assert.NoError(t, err) - - // verify - verifyAll(t) } func TestDefaultCustomization_PostBootstrap(t *testing.T) { - // mock - createMock(t) - // SUT + act var err = customizationDefault.PostBootstrap() // assert assert.NoError(t, err) - - // verify - verifyAll(t) } func TestDefaultCustomization_AppClosing(t *testing.T) { - // mock - createMock(t) - // SUT + act var err = customizationDefault.AppClosing() // assert assert.NoError(t, err) - - // verify - verifyAll(t) } -type dummySessionLog struct { - dummySession - getID func() uuid.UUID - getIndex func() int -} - -func (session *dummySessionLog) GetID() uuid.UUID { - if session.getID != nil { - return session.getID() - } - assert.Fail(session.t, "Unexpected call to GetID") - return uuid.Nil -} - -func (session *dummySessionLog) GetIndex() int { - if session.getIndex != nil { - return session.getIndex() - } - assert.Fail(session.t, "Unexpected call to GetIndex") - return 0 -} - -func TestDefaultCustomization_Log_NilSession(t *testing.T) { +func TestDefaultCustomization_Log_HappyPath(t *testing.T) { // arrange - var dummySession *session - var dummyLogType = LogType(rand.Intn(100)) - var dummyLogLevel = LogLevel(rand.Intn(100)) + var dummySession = &session{} + var dummyTimeNow = time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC) + var dummyTimeString = "some time string" + var dummyLogType = LogType(rand.IntN(100)) + var dummyLogLevel = LogLevel(rand.IntN(100)) var dummyCategory = "some category" var dummySubcategory = "some subcategory" var dummyDescription = "some description" + var dummySessionID = uuid.New() + var dummySessionIndex = rand.Int() + var dummyFormat = "[%v] <%v|%v> (%v|%v) [%v|%v] %v\n" // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - isInterfaceValueNilFuncExpected = 1 - isInterfaceValueNilFunc = func(i interface{}) bool { - isInterfaceValueNilFuncCalled++ - assert.Equal(t, dummySession, i) - return true - } - - // SUT + act - customizationDefault.Log( - dummySession, + m.Mock(time.Now).Expects().Returns(dummyTimeNow).Once() + m.Mock(formatDateTime).Expects(dummyTimeNow).Returns(dummyTimeString).Once() + m.Mock((*session).GetID).Expects(dummySession).Returns(dummySessionID).Once() + m.Mock((*session).GetIndex).Expects(dummySession).Returns(dummySessionIndex).Once() + m.Mock(fmt.Printf).Expects( + dummyFormat, + dummyTimeString, + dummySessionID, + dummySessionIndex, dummyLogType, dummyLogLevel, dummyCategory, dummySubcategory, dummyDescription, - ) - - // verify - verifyAll(t) -} - -func TestDefaultCustomization_Log_HappyPath(t *testing.T) { - // arrange - var dummySession = &dummySessionLog{dummySession: dummySession{t: t}} - var dummyLogType = LogType(rand.Intn(100)) - var dummyLogLevel = LogLevel(rand.Intn(100)) - var dummyCategory = "some category" - var dummySubcategory = "some subcategory" - var dummyDescription = "some description" - var sessionGetIDExpected int - var sessionGetIDCalled int - var sessionGetIndexExpected int - var sessionGetIndexCalled int - var dummySessionID = uuid.New() - var dummySessionIndex = rand.Int() - var dummyFormat = "<%v|%v> (%v|%v) [%v|%v] %v\n" - - // mock - createMock(t) - - // expect - isInterfaceValueNilFuncExpected = 1 - isInterfaceValueNilFunc = func(i interface{}) bool { - isInterfaceValueNilFuncCalled++ - assert.Equal(t, dummySession, i) - return false - } - sessionGetIDExpected = 1 - dummySession.getID = func() uuid.UUID { - sessionGetIDCalled++ - return dummySessionID - } - sessionGetIndexExpected = 1 - dummySession.getIndex = func() int { - sessionGetIndexCalled++ - return dummySessionIndex - } - fmtPrintfExpected = 1 - fmtPrintf = func(format string, a ...interface{}) (n int, err error) { - fmtPrintfCalled++ - assert.Equal(t, dummyFormat, format) - assert.Equal(t, 7, len(a)) - assert.Equal(t, dummySessionID, a[0]) - assert.Equal(t, dummySessionIndex, a[1]) - assert.Equal(t, dummyLogType, a[2]) - assert.Equal(t, dummyLogLevel, a[3]) - assert.Equal(t, dummyCategory, a[4]) - assert.Equal(t, dummySubcategory, a[5]) - assert.Equal(t, dummyDescription, a[6]) - return rand.Int(), errors.New("some error") - } + ).Returns(rand.Int(), errors.New("some error")).Once() // SUT + act customizationDefault.Log( @@ -169,62 +80,39 @@ func TestDefaultCustomization_Log_HappyPath(t *testing.T) { dummySubcategory, dummyDescription, ) - - // verify - verifyAll(t) - assert.Equal(t, sessionGetIDExpected, sessionGetIDCalled, "Unexpected number of calls to method sessionGetID") - assert.Equal(t, sessionGetIndexExpected, sessionGetIndexCalled, "Unexpected number of calls to method sessionGetIndex") } func TestDefaultCustomization_PreAction(t *testing.T) { // arrange var dummySession Session - // mock - createMock(t) - // SUT + act var err = customizationDefault.PreAction(dummySession) // assert assert.NoError(t, err) - - // verify - verifyAll(t) } func TestDefaultCustomization_PostAction(t *testing.T) { // arrange var dummySession Session - // mock - createMock(t) - // SUT + act var err = customizationDefault.PostAction(dummySession) // assert assert.NoError(t, err) - - // verify - verifyAll(t) } func TestDefaultCustomization_ActionFunc(t *testing.T) { // arrange var dummySession Session - // mock - createMock(t) - // SUT + act var err = customizationDefault.ActionFunc(dummySession) // assert assert.NoError(t, err) - - // verify - verifyAll(t) } func TestDefaultCustomization_RecoverPanic_NilRecoverResult(t *testing.T) { @@ -233,15 +121,10 @@ func TestDefaultCustomization_RecoverPanic_NilRecoverResult(t *testing.T) { var dummyRecoverResult *int // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - isInterfaceValueNilFuncExpected = 1 - isInterfaceValueNilFunc = func(i interface{}) bool { - isInterfaceValueNilFuncCalled++ - assert.Equal(t, dummyRecoverResult, i) - return true - } + m.Mock(isInterfaceValueNil).Expects(dummyRecoverResult).Returns(true).Once() // SUT + act var err = customizationDefault.RecoverPanic( @@ -251,9 +134,6 @@ func TestDefaultCustomization_RecoverPanic_NilRecoverResult(t *testing.T) { // assert assert.NoError(t, err) - - // verify - verifyAll(t) } func TestDefaultCustomization_RecoverPanic_RecoverResultAsError(t *testing.T) { @@ -262,15 +142,10 @@ func TestDefaultCustomization_RecoverPanic_RecoverResultAsError(t *testing.T) { var dummyRecoverResult = errors.New("some recover result") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - isInterfaceValueNilFuncExpected = 1 - isInterfaceValueNilFunc = func(i interface{}) bool { - isInterfaceValueNilFuncCalled++ - assert.Equal(t, dummyRecoverResult, i) - return false - } + m.Mock(isInterfaceValueNil).Expects(dummyRecoverResult).Returns(false).Once() // SUT + act var err = customizationDefault.RecoverPanic( @@ -280,9 +155,6 @@ func TestDefaultCustomization_RecoverPanic_RecoverResultAsError(t *testing.T) { // assert assert.Equal(t, dummyRecoverResult, err) - - // verify - verifyAll(t) } func TestDefaultCustomization_RecoverPanic_RecoverResultAsNonError(t *testing.T) { @@ -292,23 +164,11 @@ func TestDefaultCustomization_RecoverPanic_RecoverResultAsNonError(t *testing.T) var dummyError = errors.New("some error") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - isInterfaceValueNilFuncExpected = 1 - isInterfaceValueNilFunc = func(i interface{}) bool { - isInterfaceValueNilFuncCalled++ - assert.Equal(t, dummyRecoverResult, i) - return false - } - fmtErrorfExpected = 1 - fmtErrorf = func(format string, a ...interface{}) error { - fmtErrorfCalled++ - assert.Equal(t, "%v", format) - assert.Equal(t, 1, len(a)) - assert.Equal(t, dummyRecoverResult, a[0]) - return dummyError - } + m.Mock(isInterfaceValueNil).Expects(dummyRecoverResult).Returns(false).Once() + m.Mock(fmt.Errorf).Expects("%v", dummyRecoverResult).Returns(dummyError).Once() // SUT + act var err = customizationDefault.RecoverPanic( @@ -318,68 +178,41 @@ func TestDefaultCustomization_RecoverPanic_RecoverResultAsNonError(t *testing.T) // assert assert.Equal(t, dummyError, err) - - // verify - verifyAll(t) } func TestDefaultCustomization_ClientCert(t *testing.T) { - // mock - createMock(t) - // SUT + act var result = customizationDefault.ClientCert() // assert assert.Nil(t, result) - - // verify - verifyAll(t) } func TestDefaultCustomization_DefaultTimeout(t *testing.T) { - // mock - createMock(t) - // SUT + act var result = customizationDefault.DefaultTimeout() // assert assert.Equal(t, 3*time.Minute, result) - - // verify - verifyAll(t) } func TestDefaultCustomization_SkipServerCertVerification(t *testing.T) { - // mock - createMock(t) - // SUT + act var result = customizationDefault.SkipServerCertVerification() // assert assert.False(t, result) - - // verify - verifyAll(t) } func TestDefaultCustomization_RoundTripper(t *testing.T) { // arrange - var dummyTransport = &dummyTransport{t: t} - - // mock - createMock(t) + var dummyTransport = &http.Transport{} // SUT + act var result = customizationDefault.RoundTripper(dummyTransport) // assert assert.Equal(t, dummyTransport, result) - - // verify - verifyAll(t) } func TestDefaultCustomization_WrapRequest(t *testing.T) { @@ -387,15 +220,9 @@ func TestDefaultCustomization_WrapRequest(t *testing.T) { var dummySession Session var dummyRequest = &http.Request{Host: "some host"} - // mock - createMock(t) - // SUT + act var result = customizationDefault.WrapRequest(dummySession, dummyRequest) // assert assert.Equal(t, dummyRequest, result) - - // verify - verifyAll(t) } diff --git a/go.mod b/go.mod index 96d5134..ddd2223 100644 --- a/go.mod +++ b/go.mod @@ -1,8 +1,18 @@ module github.com/zhongjie-cai/job-runner -go 1.15 +go 1.23 + +toolchain go1.23.2 require ( github.com/google/uuid v1.3.0 github.com/stretchr/testify v1.8.0 + github.com/zhongjie-cai/gomocker/v2 v2.0.6 +) + +require ( + github.com/agiledragon/gomonkey/v2 v2.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index fa222d5..48548ca 100644 --- a/go.sum +++ b/go.sum @@ -1,15 +1,28 @@ +github.com/agiledragon/gomonkey/v2 v2.12.0 h1:ek0dYu9K1rSV+TgkW5LvNNPRWyDZVIxGMCFI6Pz9o38= +github.com/agiledragon/gomonkey/v2 v2.12.0/go.mod h1:ap1AmDzcVOAz1YpeJ3TCzIgstoaWLA6jbbgxfB4w2iY= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/zhongjie-cai/gomocker/v2 v2.0.6 h1:LpxePhbU/UDULWOtrmfmNm+Oqoqf0WQN9VYHAcilZE0= +github.com/zhongjie-cai/gomocker/v2 v2.0.6/go.mod h1:/rMIyPd/8+jT8iRqmThmBQrl9JvtMCypRAkc1S6NI5U= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/handler.go b/handler.go index d114450..54a8384 100644 --- a/handler.go +++ b/handler.go @@ -1,7 +1,10 @@ package jobrunner import ( + "fmt" "time" + + "github.com/google/uuid" ) func initiateSession( @@ -10,7 +13,7 @@ func initiateSession( reruns int, ) *session { return &session{ - id: uuidNew(), + id: uuid.New(), index: index, reruns: reruns, attachment: map[string]interface{}{}, @@ -30,7 +33,7 @@ func finalizeSession( if errorResult == nil { return recoverError } - return fmtErrorf( + return fmt.Errorf( "Original Error: %w\nRecover Error: %v", errorResult, recoverError, @@ -68,18 +71,18 @@ func handleSession( index int, reruns int, ) (err error) { - var session = initiateSessionFunc( + var session = initiateSession( app, index, reruns, ) - logProcessEnterFunc( + logProcessEnter( session, app.name, "", "", ) - logProcessRequestFunc( + logProcessRequest( session, app.name, "InstanceIndex", @@ -87,29 +90,29 @@ func handleSession( index, ) defer func(startTime time.Time) { - err = finalizeSessionFunc( + err = finalizeSession( session, err, recover(), ) - logProcessResponseFunc( + logProcessResponse( session, app.name, "", "%v", err, ) - logProcessExitFunc( + logProcessExit( session, app.name, "Duration", "%s", - timeSince(startTime), + time.Since(startTime), ) }( - getTimeNowUTCFunc(), + time.Now().UTC(), ) - return processSessionFunc( + return processSession( session, app.customization, ) diff --git a/handler_test.go b/handler_test.go index 5fbc923..439fcb0 100644 --- a/handler_test.go +++ b/handler_test.go @@ -2,33 +2,34 @@ package jobrunner import ( "errors" - "math/rand" + "fmt" + "math/rand/v2" "testing" "time" "github.com/google/uuid" "github.com/stretchr/testify/assert" + "github.com/zhongjie-cai/gomocker/v2" ) func TestInitiateSession(t *testing.T) { // arrange - var dummyCustomization = &dummyCustomization{t: t} + type customization struct { + Customization + } + var dummyCustomization = &customization{} var dummyApplication = &application{ customization: dummyCustomization, } - var dummyIndex = rand.Intn(65536) - var dummyReruns = rand.Intn(65536) - var dummySessionID = uuid.New() + var dummyIndex = rand.IntN(65536) + var dummyReruns = rand.IntN(65536) + var dummySessionID = uuid.MustParse("00000000-0000-0000-0000-000000000001") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - uuidNewExpected = 1 - uuidNew = func() uuid.UUID { - uuidNewCalled++ - return dummySessionID - } + m.Mock(uuid.New).Expects().Returns(dummySessionID).Once() // SUT + act var session = initiateSession( @@ -44,49 +45,26 @@ func TestInitiateSession(t *testing.T) { assert.Equal(t, dummyReruns, session.reruns) assert.Empty(t, session.attachment) assert.Equal(t, dummyCustomization, session.customization) - - // verify - verifyAll(t) -} - -type dummyCustomizationRecoverPanic struct { - dummyCustomization - recoverPanic func(session Session, recoverResult interface{}) error -} - -func (dummyCustomizationRecoverPanic *dummyCustomizationRecoverPanic) RecoverPanic(session Session, recoverResult interface{}) error { - if dummyCustomizationRecoverPanic.recoverPanic != nil { - return dummyCustomizationRecoverPanic.recoverPanic(session, recoverResult) - } - assert.Fail(dummyCustomizationRecoverPanic.t, "Unexpected call to RecoverPanic") - return nil } func TestFinalizeSession_NoErrorResult(t *testing.T) { // arrange - var dummyCustomizationRecoverPanic = &dummyCustomizationRecoverPanic{ - dummyCustomization: dummyCustomization{t: t}, + type customization struct { + Customization } + var dummyCustomization = &customization{} var dummySession = &session{ - customization: dummyCustomizationRecoverPanic, + customization: dummyCustomization, } var dummyErrorResult error var dummyRecoverResult = errors.New("some recover result") var dummyRecoverError = errors.New("some recover error") - var customizationRecoverPanicExpected int - var customizationRecoverPanicCalled int // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - customizationRecoverPanicExpected = 1 - dummyCustomizationRecoverPanic.recoverPanic = func(session Session, recoverResult interface{}) error { - customizationRecoverPanicCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, dummyRecoverResult, recoverResult) - return dummyRecoverError - } + m.Mock((*customization).RecoverPanic).Expects(dummyCustomization, dummySession, dummyRecoverResult).Returns(dummyRecoverError).Once() // SUT + act var err = finalizeSession( @@ -98,46 +76,28 @@ func TestFinalizeSession_NoErrorResult(t *testing.T) { // assert assert.Equal(t, dummyRecoverError, err) - // verify - verifyAll(t) - assert.Equal(t, customizationRecoverPanicExpected, customizationRecoverPanicCalled, "Unexpected number of calls to method customization.RecoverPanic") } func TestFinalizeSession_WithErrorResult(t *testing.T) { // arrange - var dummyCustomizationRecoverPanic = &dummyCustomizationRecoverPanic{ - dummyCustomization: dummyCustomization{t: t}, + type customization struct { + Customization } + var dummyCustomization = &customization{} var dummySession = &session{ - customization: dummyCustomizationRecoverPanic, + customization: dummyCustomization, } var dummyErrorResult = errors.New("some error result") var dummyRecoverResult = errors.New("some recover result") var dummyRecoverError = errors.New("some recover error") var dummyError = errors.New("some error") - var customizationRecoverPanicExpected int - var customizationRecoverPanicCalled int // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - customizationRecoverPanicExpected = 1 - dummyCustomizationRecoverPanic.recoverPanic = func(session Session, recoverResult interface{}) error { - customizationRecoverPanicCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, dummyRecoverResult, recoverResult) - return dummyRecoverError - } - fmtErrorfExpected = 1 - fmtErrorf = func(format string, a ...interface{}) error { - fmtErrorfCalled++ - assert.Equal(t, "Original Error: %w\nRecover Error: %v", format) - assert.Equal(t, 2, len(a)) - assert.Equal(t, dummyErrorResult, a[0]) - assert.Equal(t, dummyRecoverError, a[1]) - return dummyError - } + m.Mock((*customization).RecoverPanic).Expects(dummyCustomization, dummySession, dummyRecoverResult).Returns(dummyRecoverError).Once() + m.Mock(fmt.Errorf).Expects("Original Error: %w\nRecover Error: %v", dummyErrorResult, dummyRecoverError).Returns(dummyError).Once() // SUT + act var err = finalizeSession( @@ -149,239 +109,131 @@ func TestFinalizeSession_WithErrorResult(t *testing.T) { // assert assert.Equal(t, dummyError, err) - // verify - verifyAll(t) - assert.Equal(t, customizationRecoverPanicExpected, customizationRecoverPanicCalled, "Unexpected number of calls to method customization.RecoverPanic") -} - -type dummyCustomizationProcessSession struct { - dummyCustomization - preAction func(Session) error - actionFunc func(Session) error - postAction func(Session) error -} - -func (dummyCustomizationProcessSession *dummyCustomizationProcessSession) PreAction(session Session) error { - if dummyCustomizationProcessSession.preAction != nil { - return dummyCustomizationProcessSession.preAction(session) - } - assert.Fail(dummyCustomizationProcessSession.t, "Unexpected call to PreAction") - return nil -} - -func (dummyCustomizationProcessSession *dummyCustomizationProcessSession) ActionFunc(session Session) error { - if dummyCustomizationProcessSession.actionFunc != nil { - return dummyCustomizationProcessSession.actionFunc(session) - } - assert.Fail(dummyCustomizationProcessSession.t, "Unexpected call to ActionFunc") - return nil -} - -func (dummyCustomizationProcessSession *dummyCustomizationProcessSession) PostAction(session Session) error { - if dummyCustomizationProcessSession.postAction != nil { - return dummyCustomizationProcessSession.postAction(session) - } - assert.Fail(dummyCustomizationProcessSession.t, "Unexpected call to PostAction") - return nil } func TestProcessSession_PreActionError(t *testing.T) { // arrange - var dummySession = &dummySession{t: t} - var dummyCustomizationProcessSession = &dummyCustomizationProcessSession{ - dummyCustomization: dummyCustomization{t: t}, + type customization struct { + Customization + } + var dummyCustomization = &customization{} + var dummySession = &session{ + customization: dummyCustomization, } var dummyError = errors.New("some error") - var customizationPreActionExpected int - var customizationPreActionCalled int - var customizationActionFuncExpected int - var customizationActionFuncCalled int - var customizationPostActionExpected int - var customizationPostActionCalled int // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - customizationPreActionExpected = 1 - dummyCustomizationProcessSession.preAction = func(session Session) error { - customizationPreActionCalled++ - assert.Equal(t, dummySession, session) - return dummyError - } + m.Mock((*customization).PreAction).Expects(dummyCustomization, dummySession).Returns(dummyError).Once() // SUT + act var err = processSession( dummySession, - dummyCustomizationProcessSession, + dummyCustomization, ) // assert assert.Equal(t, dummyError, err) - // verify - verifyAll(t) - assert.Equal(t, customizationPreActionExpected, customizationPreActionCalled, "Unexpected number of calls to method customization.PreAction") - assert.Equal(t, customizationActionFuncExpected, customizationActionFuncCalled, "Unexpected number of calls to method customization.ActionFunc") - assert.Equal(t, customizationPostActionExpected, customizationPostActionCalled, "Unexpected number of calls to method customization.PostAction") } func TestProcessSession_ActionFuncError(t *testing.T) { // arrange - var dummySession = &dummySession{t: t} - var dummyCustomizationProcessSession = &dummyCustomizationProcessSession{ - dummyCustomization: dummyCustomization{t: t}, + type customization struct { + Customization + } + var dummyCustomization = &customization{} + var dummySession = &session{ + customization: dummyCustomization, } var dummyError = errors.New("some error") - var customizationPreActionExpected int - var customizationPreActionCalled int - var customizationActionFuncExpected int - var customizationActionFuncCalled int - var customizationPostActionExpected int - var customizationPostActionCalled int // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - customizationPreActionExpected = 1 - dummyCustomizationProcessSession.preAction = func(session Session) error { - customizationPreActionCalled++ - assert.Equal(t, dummySession, session) - return nil - } - customizationActionFuncExpected = 1 - dummyCustomizationProcessSession.actionFunc = func(session Session) error { - customizationActionFuncCalled++ - assert.Equal(t, dummySession, session) - return dummyError - } + m.Mock((*customization).PreAction).Expects(dummyCustomization, dummySession).Returns(nil).Once() + m.Mock((*customization).ActionFunc).Expects(dummyCustomization, dummySession).Returns(dummyError).Once() // SUT + act var err = processSession( dummySession, - dummyCustomizationProcessSession, + dummyCustomization, ) // assert assert.Equal(t, dummyError, err) - // verify - verifyAll(t) - assert.Equal(t, customizationPreActionExpected, customizationPreActionCalled, "Unexpected number of calls to method customization.PreAction") - assert.Equal(t, customizationActionFuncExpected, customizationActionFuncCalled, "Unexpected number of calls to method customization.ActionFunc") - assert.Equal(t, customizationPostActionExpected, customizationPostActionCalled, "Unexpected number of calls to method customization.PostAction") } func TestProcessSession_PostActionError(t *testing.T) { // arrange - var dummySession = &dummySession{t: t} - var dummyCustomizationProcessSession = &dummyCustomizationProcessSession{ - dummyCustomization: dummyCustomization{t: t}, + type customization struct { + Customization + } + var dummyCustomization = &customization{} + var dummySession = &session{ + customization: dummyCustomization, } var dummyError = errors.New("some error") - var customizationPreActionExpected int - var customizationPreActionCalled int - var customizationActionFuncExpected int - var customizationActionFuncCalled int - var customizationPostActionExpected int - var customizationPostActionCalled int // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - customizationPreActionExpected = 1 - dummyCustomizationProcessSession.preAction = func(session Session) error { - customizationPreActionCalled++ - assert.Equal(t, dummySession, session) - return nil - } - customizationActionFuncExpected = 1 - dummyCustomizationProcessSession.actionFunc = func(session Session) error { - customizationActionFuncCalled++ - assert.Equal(t, dummySession, session) - return nil - } - customizationPostActionExpected = 1 - dummyCustomizationProcessSession.postAction = func(session Session) error { - customizationPostActionCalled++ - assert.Equal(t, dummySession, session) - return dummyError - } + m.Mock((*customization).PreAction).Expects(dummyCustomization, dummySession).Returns(nil).Once() + m.Mock((*customization).ActionFunc).Expects(dummyCustomization, dummySession).Returns(nil).Once() + m.Mock((*customization).PostAction).Expects(dummyCustomization, dummySession).Returns(dummyError).Once() // SUT + act var err = processSession( dummySession, - dummyCustomizationProcessSession, + dummyCustomization, ) // assert assert.Equal(t, dummyError, err) - // verify - verifyAll(t) - assert.Equal(t, customizationPreActionExpected, customizationPreActionCalled, "Unexpected number of calls to method customization.PreAction") - assert.Equal(t, customizationActionFuncExpected, customizationActionFuncCalled, "Unexpected number of calls to method customization.ActionFunc") - assert.Equal(t, customizationPostActionExpected, customizationPostActionCalled, "Unexpected number of calls to method customization.PostAction") } func TestProcessSession_Success(t *testing.T) { // arrange - var dummySession = &dummySession{t: t} - var dummyCustomizationProcessSession = &dummyCustomizationProcessSession{ - dummyCustomization: dummyCustomization{t: t}, + type customization struct { + Customization + } + var dummyCustomization = &customization{} + var dummySession = &session{ + customization: dummyCustomization, } - var customizationPreActionExpected int - var customizationPreActionCalled int - var customizationActionFuncExpected int - var customizationActionFuncCalled int - var customizationPostActionExpected int - var customizationPostActionCalled int // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - customizationPreActionExpected = 1 - dummyCustomizationProcessSession.preAction = func(session Session) error { - customizationPreActionCalled++ - assert.Equal(t, dummySession, session) - return nil - } - customizationActionFuncExpected = 1 - dummyCustomizationProcessSession.actionFunc = func(session Session) error { - customizationActionFuncCalled++ - assert.Equal(t, dummySession, session) - return nil - } - customizationPostActionExpected = 1 - dummyCustomizationProcessSession.postAction = func(session Session) error { - customizationPostActionCalled++ - assert.Equal(t, dummySession, session) - return nil - } + m.Mock((*customization).PreAction).Expects(dummyCustomization, dummySession).Returns(nil).Once() + m.Mock((*customization).ActionFunc).Expects(dummyCustomization, dummySession).Returns(nil).Once() + m.Mock((*customization).PostAction).Expects(dummyCustomization, dummySession).Returns(nil).Once() // SUT + act var err = processSession( dummySession, - dummyCustomizationProcessSession, + dummyCustomization, ) // assert assert.NoError(t, err) - // verify - verifyAll(t) - assert.Equal(t, customizationPreActionExpected, customizationPreActionCalled, "Unexpected number of calls to method customization.PreAction") - assert.Equal(t, customizationActionFuncExpected, customizationActionFuncCalled, "Unexpected number of calls to method customization.ActionFunc") - assert.Equal(t, customizationPostActionExpected, customizationPostActionCalled, "Unexpected number of calls to method customization.PostAction") } func TestHandleSession_HappyPath(t *testing.T) { // arrange var dummyName = "some name" - var dummyCustomization = &dummyCustomization{t: t} + type customization struct { + Customization + } + var dummyCustomization = &customization{} var dummyApplication = &application{ name: dummyName, customization: dummyCustomization, @@ -389,88 +241,24 @@ func TestHandleSession_HappyPath(t *testing.T) { var dummyIndex = rand.Int() var dummyReruns = rand.Int() var dummySession = &session{id: uuid.New()} - var dummyTimeNow = time.Now() - var dummyDuration = time.Duration(rand.Intn(100)) + var dummyTimeNow = time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC) + var dummyDuration = time.Duration(rand.IntN(100)) var dummyProcessError = errors.New("some process error") var dummyFinalError = errors.New("some final error") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - initiateSessionFuncExpected = 1 - initiateSessionFunc = func(app *application, index int, reruns int) *session { - initiateSessionFuncCalled++ - assert.Equal(t, dummyApplication, app) - assert.Equal(t, dummyIndex, index) - assert.Equal(t, dummyReruns, reruns) - return dummySession - } - logProcessEnterFuncExpected = 1 - logProcessEnterFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logProcessEnterFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, dummyName, category) - assert.Equal(t, "", subcategory) - assert.Equal(t, "", messageFormat) - assert.Empty(t, parameters) - } - logProcessRequestFuncExpected = 1 - logProcessRequestFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logProcessRequestFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, dummyName, category) - assert.Equal(t, "InstanceIndex", subcategory) - assert.Equal(t, "%v", messageFormat) - assert.Equal(t, 1, len(parameters)) - assert.Equal(t, dummyIndex, parameters[0]) - } - getTimeNowUTCFuncExpected = 1 - getTimeNowUTCFunc = func() time.Time { - getTimeNowUTCFuncCalled++ - return dummyTimeNow - } - processSessionFuncExpected = 1 - processSessionFunc = func(session Session, customization Customization) error { - processSessionFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, dummyCustomization, customization) - return dummyProcessError - } - finalizeSessionFuncExpected = 1 - finalizeSessionFunc = func(session *session, resultError error, recoverResult interface{}) error { - finalizeSessionFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, dummyProcessError, resultError) - assert.Equal(t, recover(), recoverResult) - return dummyFinalError - } - timeSinceExpected = 1 - timeSince = func(tm time.Time) time.Duration { - timeSinceCalled++ - assert.Equal(t, dummyTimeNow, tm) - return dummyDuration - } - logProcessResponseFuncExpected = 1 - logProcessResponseFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logProcessResponseFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, dummyName, category) - assert.Equal(t, "", subcategory) - assert.Equal(t, "%v", messageFormat) - assert.Equal(t, 1, len(parameters)) - assert.Equal(t, dummyFinalError, parameters[0]) - } - logProcessExitFuncExpected = 1 - logProcessExitFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logProcessExitFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, dummyName, category) - assert.Equal(t, "Duration", subcategory) - assert.Equal(t, "%s", messageFormat) - assert.Equal(t, 1, len(parameters)) - assert.Equal(t, dummyDuration, parameters[0]) - } + m.Mock(initiateSession).Expects(dummyApplication, dummyIndex, dummyReruns).Returns(dummySession).Once() + m.Mock(logProcessEnter).Expects(dummySession, dummyName, "", "").Returns().Once() + m.Mock(logProcessRequest).Expects(dummySession, dummyName, "InstanceIndex", "%v", dummyIndex).Returns().Once() + m.Mock(time.Now).Expects().Returns(dummyTimeNow).Once() + m.Mock(processSession).Expects(dummySession, dummyCustomization).Returns(dummyProcessError).Once() + m.Mock(finalizeSession).Expects(dummySession, dummyProcessError, recover()).Returns(dummyFinalError).Once() + m.Mock(time.Since).Expects(dummyTimeNow).Returns(dummyDuration).Once() + m.Mock(logProcessResponse).Expects(dummySession, dummyName, "", "%v", dummyFinalError).Returns().Once() + m.Mock(logProcessExit).Expects(dummySession, dummyName, "Duration", "%s", dummyDuration).Returns().Once() // SUT + act var err = handleSession( @@ -481,7 +269,4 @@ func TestHandleSession_HappyPath(t *testing.T) { // assert assert.Equal(t, dummyFinalError, err) - - // verify - verifyAll(t) } diff --git a/jsonutil.go b/jsonutil.go index 04e9d70..563905b 100644 --- a/jsonutil.go +++ b/jsonutil.go @@ -2,7 +2,11 @@ package jobrunner import ( "bytes" + "encoding/json" + "fmt" "reflect" + "strconv" + "strings" ) var ( @@ -17,24 +21,24 @@ var ( // marshalIgnoreError returns the string representation of the given object; returns empty string in case of error func marshalIgnoreError(v interface{}) string { var buffer = &bytes.Buffer{} - var encoder = jsonNewEncoder(buffer) + var encoder = json.NewEncoder(buffer) encoder.SetEscapeHTML(false) encoder.Encode(v) var result = buffer.String() - return stringsTrimRight(result, "\n") + return strings.TrimRight(result, "\n") } func tryUnmarshalPrimitiveTypes(value string, dataTemplate interface{}) bool { if value == "" { return true } - switch reflectTypeOf(dataTemplate) { + switch reflect.TypeOf(dataTemplate) { case typeOfString: (*(dataTemplate).(*string)) = value return true case typeOfBool: - var parsedValue, parseError = strconvParseBool( - stringsToLower( + var parsedValue, parseError = strconv.ParseBool( + strings.ToLower( value, ), ) @@ -44,28 +48,28 @@ func tryUnmarshalPrimitiveTypes(value string, dataTemplate interface{}) bool { (*(dataTemplate).(*bool)) = parsedValue return true case typeOfInteger: - var parsedValue, parseError = strconvAtoi(value) + var parsedValue, parseError = strconv.Atoi(value) if parseError != nil { return false } (*(dataTemplate).(*int)) = parsedValue return true case typeOfInt64: - var parsedValue, parseError = strconvParseInt(value, 0, 64) + var parsedValue, parseError = strconv.ParseInt(value, 0, 64) if parseError != nil { return false } (*(dataTemplate).(*int64)) = parsedValue return true case typeOfFloat64: - var parsedValue, parseError = strconvParseFloat(value, 64) + var parsedValue, parseError = strconv.ParseFloat(value, 64) if parseError != nil { return false } (*(dataTemplate).(*float64)) = parsedValue return true case typeOfByte: - var parsedValue, parseError = strconvParseUint(value, 0, 8) + var parsedValue, parseError = strconv.ParseUint(value, 0, 8) if parseError != nil { return false } @@ -77,30 +81,30 @@ func tryUnmarshalPrimitiveTypes(value string, dataTemplate interface{}) bool { // tryUnmarshal tries to unmarshal given value to dataTemplate func tryUnmarshal(value string, dataTemplate interface{}) error { - if isInterfaceValueNilFunc(dataTemplate) { + if isInterfaceValueNil(dataTemplate) { return nil } - if tryUnmarshalPrimitiveTypesFunc( + if tryUnmarshalPrimitiveTypes( value, dataTemplate, ) { return nil } - var noQuoteJSONError = jsonUnmarshal( + var noQuoteJSONError = json.Unmarshal( []byte(value), dataTemplate, ) if noQuoteJSONError == nil { return nil } - var withQuoteJSONError = jsonUnmarshal( + var withQuoteJSONError = json.Unmarshal( []byte("\""+value+"\""), dataTemplate, ) if withQuoteJSONError == nil { return nil } - return fmtErrorf( + return fmt.Errorf( "Unable to unmarshal value [%v] into data template", value, ) diff --git a/jsonutil_test.go b/jsonutil_test.go index 43cbb84..423fb64 100644 --- a/jsonutil_test.go +++ b/jsonutil_test.go @@ -1,19 +1,16 @@ package jobrunner import ( - "encoding/json" "errors" "fmt" - "io" "math" - "math/rand" - "reflect" + "math/rand/v2" "strconv" - "strings" "testing" "github.com/google/uuid" "github.com/stretchr/testify/assert" + "github.com/zhongjie-cai/gomocker/v2" ) func TestMarshalIgnoreError_Empty(t *testing.T) { @@ -24,21 +21,6 @@ func TestMarshalIgnoreError_Empty(t *testing.T) { } var expectedResult = "null" - // mock - createMock(t) - - // expect - jsonNewEncoderExpected = 1 - jsonNewEncoder = func(w io.Writer) *json.Encoder { - jsonNewEncoderCalled++ - return json.NewEncoder(w) - } - stringsTrimRightExpected = 1 - stringsTrimRight = func(s string, cutset string) string { - stringsTrimRightCalled++ - return strings.TrimRight(s, cutset) - } - // SUT + act var result = marshalIgnoreError( dummyObject, @@ -46,9 +28,6 @@ func TestMarshalIgnoreError_Empty(t *testing.T) { // assert assert.Equal(t, expectedResult, result) - - // verify - verifyAll(t) } func TestMarshalIgnoreError_Success(t *testing.T) { @@ -62,21 +41,6 @@ func TestMarshalIgnoreError_Success(t *testing.T) { } var expectedResult = "{\"Foo\":\"\",\"Test\":123}" - // mock - createMock(t) - - // expect - jsonNewEncoderExpected = 1 - jsonNewEncoder = func(w io.Writer) *json.Encoder { - jsonNewEncoderCalled++ - return json.NewEncoder(w) - } - stringsTrimRightExpected = 1 - stringsTrimRight = func(s string, cutset string) string { - stringsTrimRightCalled++ - return strings.TrimRight(s, cutset) - } - // SUT + act var result = marshalIgnoreError( dummyObject, @@ -84,9 +48,6 @@ func TestMarshalIgnoreError_Success(t *testing.T) { // assert assert.Equal(t, expectedResult, result) - - // verify - verifyAll(t) } func TestTryUnmarshalPrimitiveTypes_Empty(t *testing.T) { @@ -94,9 +55,6 @@ func TestTryUnmarshalPrimitiveTypes_Empty(t *testing.T) { var dummyValue string var dummyDataTemplate string - // mock - createMock(t) - // SUT + act var result = tryUnmarshalPrimitiveTypes( dummyValue, @@ -106,9 +64,6 @@ func TestTryUnmarshalPrimitiveTypes_Empty(t *testing.T) { // assert assert.True(t, result) assert.Zero(t, dummyDataTemplate) - - // verify - verifyAll(t) } func TestTryUnmarshalPrimitiveTypes_String(t *testing.T) { @@ -116,16 +71,6 @@ func TestTryUnmarshalPrimitiveTypes_String(t *testing.T) { var dummyValue = "some value" var dummyDataTemplate string - // mock - createMock(t) - - // expect - reflectTypeOfExpected = 1 - reflectTypeOf = func(i interface{}) reflect.Type { - reflectTypeOfCalled++ - return reflect.TypeOf(i) - } - // SUT + act var result = tryUnmarshalPrimitiveTypes( dummyValue, @@ -135,9 +80,6 @@ func TestTryUnmarshalPrimitiveTypes_String(t *testing.T) { // assert assert.True(t, result) assert.Equal(t, dummyValue, dummyDataTemplate) - - // verify - verifyAll(t) } func TestTryUnmarshalPrimitiveTypes_Bool_Error(t *testing.T) { @@ -145,26 +87,6 @@ func TestTryUnmarshalPrimitiveTypes_Bool_Error(t *testing.T) { var dummyValue = "some invalid bool" var dummyDataTemplate bool - // mock - createMock(t) - - // expect - reflectTypeOfExpected = 1 - reflectTypeOf = func(i interface{}) reflect.Type { - reflectTypeOfCalled++ - return reflect.TypeOf(i) - } - stringsToLowerExpected = 1 - stringsToLower = func(s string) string { - stringsToLowerCalled++ - return strings.ToLower(s) - } - strconvParseBoolExpected = 1 - strconvParseBool = func(str string) (bool, error) { - strconvParseBoolCalled++ - return strconv.ParseBool(str) - } - // SUT + act var result = tryUnmarshalPrimitiveTypes( dummyValue, @@ -174,37 +96,14 @@ func TestTryUnmarshalPrimitiveTypes_Bool_Error(t *testing.T) { // assert assert.False(t, result) assert.Zero(t, dummyDataTemplate) - - // verify - verifyAll(t) } func TestTryUnmarshalPrimitiveTypes_Bool_NoError(t *testing.T) { // arrange - var dummyValue = rand.Intn(100) < 50 + var dummyValue = rand.IntN(100) < 50 var dummyValueString = fmt.Sprintf("%v", dummyValue) var dummyDataTemplate bool - // mock - createMock(t) - - // expect - reflectTypeOfExpected = 1 - reflectTypeOf = func(i interface{}) reflect.Type { - reflectTypeOfCalled++ - return reflect.TypeOf(i) - } - stringsToLowerExpected = 1 - stringsToLower = func(s string) string { - stringsToLowerCalled++ - return strings.ToLower(s) - } - strconvParseBoolExpected = 1 - strconvParseBool = func(str string) (bool, error) { - strconvParseBoolCalled++ - return strconv.ParseBool(str) - } - // SUT + act var result = tryUnmarshalPrimitiveTypes( dummyValueString, @@ -214,9 +113,6 @@ func TestTryUnmarshalPrimitiveTypes_Bool_NoError(t *testing.T) { // assert assert.True(t, result) assert.Equal(t, dummyValue, dummyDataTemplate) - - // verify - verifyAll(t) } func TestTryUnmarshalPrimitiveTypes_Integer_Error(t *testing.T) { @@ -224,21 +120,6 @@ func TestTryUnmarshalPrimitiveTypes_Integer_Error(t *testing.T) { var dummyValue = "some invalid integer" var dummyDataTemplate int - // mock - createMock(t) - - // expect - reflectTypeOfExpected = 1 - reflectTypeOf = func(i interface{}) reflect.Type { - reflectTypeOfCalled++ - return reflect.TypeOf(i) - } - strconvAtoiExpected = 1 - strconvAtoi = func(str string) (int, error) { - strconvAtoiCalled++ - return strconv.Atoi(str) - } - // SUT + act var result = tryUnmarshalPrimitiveTypes( dummyValue, @@ -248,32 +129,14 @@ func TestTryUnmarshalPrimitiveTypes_Integer_Error(t *testing.T) { // assert assert.False(t, result) assert.Zero(t, dummyDataTemplate) - - // verify - verifyAll(t) } func TestTryUnmarshalPrimitiveTypes_Integer_NoError(t *testing.T) { // arrange - var dummyValue = rand.Intn(math.MaxInt32) + var dummyValue = rand.IntN(math.MaxInt32) var dummyValueString = fmt.Sprintf("%v", dummyValue) var dummyDataTemplate int - // mock - createMock(t) - - // expect - reflectTypeOfExpected = 1 - reflectTypeOf = func(i interface{}) reflect.Type { - reflectTypeOfCalled++ - return reflect.TypeOf(i) - } - strconvAtoiExpected = 1 - strconvAtoi = func(str string) (int, error) { - strconvAtoiCalled++ - return strconv.Atoi(str) - } - // SUT + act var result = tryUnmarshalPrimitiveTypes( dummyValueString, @@ -283,9 +146,6 @@ func TestTryUnmarshalPrimitiveTypes_Integer_NoError(t *testing.T) { // assert assert.True(t, result) assert.Equal(t, dummyValue, dummyDataTemplate) - - // verify - verifyAll(t) } func TestTryUnmarshalPrimitiveTypes_Int64_Error(t *testing.T) { @@ -293,21 +153,6 @@ func TestTryUnmarshalPrimitiveTypes_Int64_Error(t *testing.T) { var dummyValue = "some invalid int64" var dummyDataTemplate int64 - // mock - createMock(t) - - // expect - reflectTypeOfExpected = 1 - reflectTypeOf = func(i interface{}) reflect.Type { - reflectTypeOfCalled++ - return reflect.TypeOf(i) - } - strconvParseIntExpected = 1 - strconvParseInt = func(s string, base int, bitSize int) (int64, error) { - strconvParseIntCalled++ - return strconv.ParseInt(s, base, bitSize) - } - // SUT + act var result = tryUnmarshalPrimitiveTypes( dummyValue, @@ -317,32 +162,14 @@ func TestTryUnmarshalPrimitiveTypes_Int64_Error(t *testing.T) { // assert assert.False(t, result) assert.Zero(t, dummyDataTemplate) - - // verify - verifyAll(t) } func TestTryUnmarshalPrimitiveTypes_Int64_NoError(t *testing.T) { // arrange - var dummyValue = rand.Int63() + var dummyValue = rand.Int64() var dummyValueString = fmt.Sprintf("%v", dummyValue) var dummyDataTemplate int64 - // mock - createMock(t) - - // expect - reflectTypeOfExpected = 1 - reflectTypeOf = func(i interface{}) reflect.Type { - reflectTypeOfCalled++ - return reflect.TypeOf(i) - } - strconvParseIntExpected = 1 - strconvParseInt = func(s string, base int, bitSize int) (int64, error) { - strconvParseIntCalled++ - return strconv.ParseInt(s, base, bitSize) - } - // SUT + act var result = tryUnmarshalPrimitiveTypes( dummyValueString, @@ -352,9 +179,6 @@ func TestTryUnmarshalPrimitiveTypes_Int64_NoError(t *testing.T) { // assert assert.True(t, result) assert.Equal(t, dummyValue, dummyDataTemplate) - - // verify - verifyAll(t) } func TestTryUnmarshalPrimitiveTypes_Float64_Error(t *testing.T) { @@ -362,21 +186,6 @@ func TestTryUnmarshalPrimitiveTypes_Float64_Error(t *testing.T) { var dummyValue = "some invalid float64" var dummyDataTemplate float64 - // mock - createMock(t) - - // expect - reflectTypeOfExpected = 1 - reflectTypeOf = func(i interface{}) reflect.Type { - reflectTypeOfCalled++ - return reflect.TypeOf(i) - } - strconvParseFloatExpected = 1 - strconvParseFloat = func(s string, bitSize int) (float64, error) { - strconvParseFloatCalled++ - return strconv.ParseFloat(s, bitSize) - } - // SUT + act var result = tryUnmarshalPrimitiveTypes( dummyValue, @@ -386,9 +195,6 @@ func TestTryUnmarshalPrimitiveTypes_Float64_Error(t *testing.T) { // assert assert.False(t, result) assert.Zero(t, dummyDataTemplate) - - // verify - verifyAll(t) } func TestTryUnmarshalPrimitiveTypes_Float64_NoError(t *testing.T) { @@ -397,21 +203,6 @@ func TestTryUnmarshalPrimitiveTypes_Float64_NoError(t *testing.T) { var dummyValueString = fmt.Sprintf("%v", dummyValue) var dummyDataTemplate float64 - // mock - createMock(t) - - // expect - reflectTypeOfExpected = 1 - reflectTypeOf = func(i interface{}) reflect.Type { - reflectTypeOfCalled++ - return reflect.TypeOf(i) - } - strconvParseFloatExpected = 1 - strconvParseFloat = func(s string, bitSize int) (float64, error) { - strconvParseFloatCalled++ - return strconv.ParseFloat(s, bitSize) - } - // SUT + act var result = tryUnmarshalPrimitiveTypes( dummyValueString, @@ -421,9 +212,6 @@ func TestTryUnmarshalPrimitiveTypes_Float64_NoError(t *testing.T) { // assert assert.True(t, result) assert.Equal(t, dummyValue, dummyDataTemplate) - - // verify - verifyAll(t) } func TestTryUnmarshalPrimitiveTypes_Byte_Error(t *testing.T) { @@ -431,21 +219,6 @@ func TestTryUnmarshalPrimitiveTypes_Byte_Error(t *testing.T) { var dummyValue = "some invalid byte" var dummyDataTemplate byte - // mock - createMock(t) - - // expect - reflectTypeOfExpected = 1 - reflectTypeOf = func(i interface{}) reflect.Type { - reflectTypeOfCalled++ - return reflect.TypeOf(i) - } - strconvParseUintExpected = 1 - strconvParseUint = func(s string, base int, bitSize int) (uint64, error) { - strconvParseUintCalled++ - return strconv.ParseUint(s, base, bitSize) - } - // SUT + act var result = tryUnmarshalPrimitiveTypes( dummyValue, @@ -455,32 +228,14 @@ func TestTryUnmarshalPrimitiveTypes_Byte_Error(t *testing.T) { // assert assert.False(t, result) assert.Zero(t, dummyDataTemplate) - - // verify - verifyAll(t) } func TestTryUnmarshalPrimitiveTypes_Byte_NoError(t *testing.T) { // arrange - var dummyValue = byte(rand.Intn(math.MaxUint8)) + var dummyValue = byte(rand.IntN(math.MaxUint8)) var dummyValueString = fmt.Sprintf("%v", dummyValue) var dummyDataTemplate byte - // mock - createMock(t) - - // expect - reflectTypeOfExpected = 1 - reflectTypeOf = func(i interface{}) reflect.Type { - reflectTypeOfCalled++ - return reflect.TypeOf(i) - } - strconvParseUintExpected = 1 - strconvParseUint = func(s string, base int, bitSize int) (uint64, error) { - strconvParseUintCalled++ - return strconv.ParseUint(s, base, bitSize) - } - // SUT + act var result = tryUnmarshalPrimitiveTypes( dummyValueString, @@ -490,9 +245,6 @@ func TestTryUnmarshalPrimitiveTypes_Byte_NoError(t *testing.T) { // assert assert.True(t, result) assert.Equal(t, dummyValue, dummyDataTemplate) - - // verify - verifyAll(t) } func TestTryUnmarshalPrimitiveTypes_OtherTypes(t *testing.T) { @@ -500,16 +252,6 @@ func TestTryUnmarshalPrimitiveTypes_OtherTypes(t *testing.T) { var dummyValue = "some value" var dummyDataTemplate error - // mock - createMock(t) - - // expect - reflectTypeOfExpected = 1 - reflectTypeOf = func(i interface{}) reflect.Type { - reflectTypeOfCalled++ - return reflect.TypeOf(i) - } - // SUT + act var result = tryUnmarshalPrimitiveTypes( dummyValue, @@ -519,9 +261,6 @@ func TestTryUnmarshalPrimitiveTypes_OtherTypes(t *testing.T) { // assert assert.False(t, result) assert.Zero(t, dummyDataTemplate) - - // verify - verifyAll(t) } func TestTryUnmarshal_NilDataTemplate(t *testing.T) { @@ -530,15 +269,10 @@ func TestTryUnmarshal_NilDataTemplate(t *testing.T) { var dummyDataTemplate interface{} // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - isInterfaceValueNilFuncExpected = 1 - isInterfaceValueNilFunc = func(i interface{}) bool { - isInterfaceValueNilFuncCalled++ - assert.Equal(t, &dummyDataTemplate, i) - return true - } + m.Mock(isInterfaceValueNil).Expects(&dummyDataTemplate).Returns(true).Once() // SUT + act var err = tryUnmarshal( @@ -549,9 +283,6 @@ func TestTryUnmarshal_NilDataTemplate(t *testing.T) { // assert assert.NoError(t, err) assert.Nil(t, dummyDataTemplate) - - // verify - verifyAll(t) } func TestTryUnmarshal_PrimitiveType(t *testing.T) { @@ -561,22 +292,15 @@ func TestTryUnmarshal_PrimitiveType(t *testing.T) { var dummyData = "some data" // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - isInterfaceValueNilFuncExpected = 1 - isInterfaceValueNilFunc = func(i interface{}) bool { - isInterfaceValueNilFuncCalled++ - assert.Equal(t, &dummyDataTemplate, i) - return false - } - tryUnmarshalPrimitiveTypesFuncExpected = 1 - tryUnmarshalPrimitiveTypesFunc = func(value string, dataTemplate interface{}) bool { - tryUnmarshalPrimitiveTypesFuncCalled++ - assert.Equal(t, dummyValue, value) - (*(dataTemplate).(*string)) = dummyData - return true - } + m.Mock(isInterfaceValueNil).Expects(&dummyDataTemplate).Returns(false).Once() + m.Mock(tryUnmarshalPrimitiveTypes).Expects(dummyValue, gomocker.Anything()). + Returns(true).SideEffect( + func(index int, params ...interface{}) { + (*(params[1]).(*string)) = dummyData + }).Once() // SUT + act var err = tryUnmarshal( @@ -587,9 +311,6 @@ func TestTryUnmarshal_PrimitiveType(t *testing.T) { // assert assert.NoError(t, err) assert.Equal(t, dummyData, dummyDataTemplate) - - // verify - verifyAll(t) } func TestTryUnmarshal_NoQuoteJSONSuccess_Primitive(t *testing.T) { @@ -599,27 +320,11 @@ func TestTryUnmarshal_NoQuoteJSONSuccess_Primitive(t *testing.T) { var dummyDataTemplate int // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - isInterfaceValueNilFuncExpected = 1 - isInterfaceValueNilFunc = func(i interface{}) bool { - isInterfaceValueNilFuncCalled++ - assert.Equal(t, &dummyDataTemplate, i) - return false - } - tryUnmarshalPrimitiveTypesFuncExpected = 1 - tryUnmarshalPrimitiveTypesFunc = func(value string, dataTemplate interface{}) bool { - tryUnmarshalPrimitiveTypesFuncCalled++ - assert.Equal(t, dummyValueString, value) - return false - } - jsonUnmarshalExpected = 1 - jsonUnmarshal = func(data []byte, v interface{}) error { - jsonUnmarshalCalled++ - assert.Equal(t, []byte(dummyValueString), data) - return json.Unmarshal(data, v) - } + m.Mock(isInterfaceValueNil).Expects(&dummyDataTemplate).Returns(false).Once() + m.Mock(tryUnmarshalPrimitiveTypes).Expects(dummyValueString, gomocker.Anything()).Returns(false).Once() // SUT + act var err = tryUnmarshal( @@ -630,9 +335,6 @@ func TestTryUnmarshal_NoQuoteJSONSuccess_Primitive(t *testing.T) { // assert assert.NoError(t, err) assert.Equal(t, dummyValue, dummyDataTemplate) - - // verify - verifyAll(t) } func TestTryUnmarshal_NoQuoteJSONSuccess_Struct(t *testing.T) { @@ -644,27 +346,11 @@ func TestTryUnmarshal_NoQuoteJSONSuccess_Struct(t *testing.T) { } // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - isInterfaceValueNilFuncExpected = 1 - isInterfaceValueNilFunc = func(i interface{}) bool { - isInterfaceValueNilFuncCalled++ - assert.Equal(t, &dummyDataTemplate, i) - return false - } - tryUnmarshalPrimitiveTypesFuncExpected = 1 - tryUnmarshalPrimitiveTypesFunc = func(value string, dataTemplate interface{}) bool { - tryUnmarshalPrimitiveTypesFuncCalled++ - assert.Equal(t, dummyValueString, value) - return false - } - jsonUnmarshalExpected = 1 - jsonUnmarshal = func(data []byte, v interface{}) error { - jsonUnmarshalCalled++ - assert.Equal(t, []byte(dummyValueString), data) - return json.Unmarshal(data, v) - } + m.Mock(isInterfaceValueNil).Expects(&dummyDataTemplate).Returns(false).Once() + m.Mock(tryUnmarshalPrimitiveTypes).Expects(dummyValueString, gomocker.Anything()).Returns(false).Once() // SUT + act var err = tryUnmarshal( @@ -676,9 +362,6 @@ func TestTryUnmarshal_NoQuoteJSONSuccess_Struct(t *testing.T) { assert.NoError(t, err) assert.Equal(t, "bar", dummyDataTemplate.Foo) assert.Equal(t, 123, dummyDataTemplate.Test) - - // verify - verifyAll(t) } func TestTryUnmarshal_WithQuoteJSONSuccess(t *testing.T) { @@ -687,31 +370,11 @@ func TestTryUnmarshal_WithQuoteJSONSuccess(t *testing.T) { var dummyDataTemplate string // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - isInterfaceValueNilFuncExpected = 1 - isInterfaceValueNilFunc = func(i interface{}) bool { - isInterfaceValueNilFuncCalled++ - assert.Equal(t, &dummyDataTemplate, i) - return false - } - tryUnmarshalPrimitiveTypesFuncExpected = 1 - tryUnmarshalPrimitiveTypesFunc = func(value string, dataTemplate interface{}) bool { - tryUnmarshalPrimitiveTypesFuncCalled++ - assert.Equal(t, dummyValue, value) - return false - } - jsonUnmarshalExpected = 2 - jsonUnmarshal = func(data []byte, v interface{}) error { - jsonUnmarshalCalled++ - if jsonUnmarshalCalled == 1 { - assert.Equal(t, []byte(dummyValue), data) - } else if jsonUnmarshalCalled == 2 { - assert.Equal(t, []byte("\""+dummyValue+"\""), data) - } - return json.Unmarshal(data, v) - } + m.Mock(isInterfaceValueNil).Expects(&dummyDataTemplate).Returns(false).Once() + m.Mock(tryUnmarshalPrimitiveTypes).Expects(dummyValue, gomocker.Anything()).Returns(false).Once() // SUT + act var err = tryUnmarshal( @@ -722,9 +385,6 @@ func TestTryUnmarshal_WithQuoteJSONSuccess(t *testing.T) { // assert assert.NoError(t, err) assert.Equal(t, dummyValue, dummyDataTemplate) - - // verify - verifyAll(t) } func TestTryUnmarshal_Failure(t *testing.T) { @@ -734,39 +394,12 @@ func TestTryUnmarshal_Failure(t *testing.T) { var dummyError = errors.New("some error") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - isInterfaceValueNilFuncExpected = 1 - isInterfaceValueNilFunc = func(i interface{}) bool { - isInterfaceValueNilFuncCalled++ - assert.Equal(t, &dummyDataTemplate, i) - return false - } - tryUnmarshalPrimitiveTypesFuncExpected = 1 - tryUnmarshalPrimitiveTypesFunc = func(value string, dataTemplate interface{}) bool { - tryUnmarshalPrimitiveTypesFuncCalled++ - assert.Equal(t, dummyValue, value) - return false - } - jsonUnmarshalExpected = 2 - jsonUnmarshal = func(data []byte, v interface{}) error { - jsonUnmarshalCalled++ - if jsonUnmarshalCalled == 1 { - assert.Equal(t, []byte(dummyValue), data) - } else if jsonUnmarshalCalled == 2 { - assert.Equal(t, []byte("\""+dummyValue+"\""), data) - } - return json.Unmarshal(data, v) - } - fmtErrorfExpected = 1 - fmtErrorf = func(format string, a ...interface{}) error { - fmtErrorfCalled++ - assert.Equal(t, "Unable to unmarshal value [%v] into data template", format) - assert.Equal(t, 1, len(a)) - assert.Equal(t, dummyValue, a[0]) - return dummyError - } + m.Mock(isInterfaceValueNil).Expects(&dummyDataTemplate).Returns(false).Once() + m.Mock(tryUnmarshalPrimitiveTypes).Expects(dummyValue, gomocker.Anything()).Returns(false).Once() + m.Mock(fmt.Errorf).Expects("Unable to unmarshal value [%v] into data template", dummyValue).Returns(dummyError).Once() // SUT + act var err = tryUnmarshal( @@ -777,7 +410,4 @@ func TestTryUnmarshal_Failure(t *testing.T) { // assert assert.Equal(t, dummyError, err) assert.Zero(t, dummyDataTemplate) - - // verify - verifyAll(t) } diff --git a/logLevel_test.go b/logLevel_test.go index 7309c50..44bee6a 100644 --- a/logLevel_test.go +++ b/logLevel_test.go @@ -10,9 +10,6 @@ func TestString_NonSupportedLogLevels(t *testing.T) { // arrange var unsupportedValue = maxLogLevel - // mock - createMock(t) - // SUT var sut = LogLevel(unsupportedValue) @@ -21,15 +18,9 @@ func TestString_NonSupportedLogLevels(t *testing.T) { // assert assert.Equal(t, debugLogLevelName, result) - - // verify - verifyAll(t) } func TestString_SupportedLogLevel(t *testing.T) { - // mock - createMock(t) - // SUT var sut = LogLevelError @@ -38,40 +29,25 @@ func TestString_SupportedLogLevel(t *testing.T) { // assert assert.Equal(t, errorLogLevelName, result) - - // verify - verifyAll(t) } func TestNewLogLevel_NoMatchFound(t *testing.T) { // arrange var dummyValue = "some value" - // mock - createMock(t) - // SUT + act var result = NewLogLevel(dummyValue) // assert assert.Equal(t, LogLevelDebug, result) - - // tear down - verifyAll(t) } func TestNewLogLevel_HappyPath(t *testing.T) { for key, value := range logLevelNameMapping { - // mock - createMock(t) - // SUT + act var result = NewLogLevel(key) // assert assert.Equal(t, value, result) - - // tear down - verifyAll(t) } } diff --git a/logType.go b/logType.go index f765258..412979c 100644 --- a/logType.go +++ b/logType.go @@ -1,5 +1,10 @@ package jobrunner +import ( + "sort" + "strings" +) + // LogType is the entry type of logging type LogType int @@ -127,8 +132,8 @@ func (logtype LogType) String() string { result = append(result, value) } } - sortStrings(result) - return stringsJoin(result, "|") + sort.Strings(result) + return strings.Join(result, "|") } // HasFlag checks whether this log category has the flag set or not @@ -144,7 +149,7 @@ func (logtype LogType) HasFlag(flag LogType) bool { // NewLogType converts a string representation of LogType flag to its strongly typed instance func NewLogType(value string) LogType { - var splitValues = stringsSplit( + var splitValues = strings.Split( value, "|", ) diff --git a/logType_test.go b/logType_test.go index cf5327a..ee730e4 100644 --- a/logType_test.go +++ b/logType_test.go @@ -1,7 +1,6 @@ package jobrunner import ( - "sort" "strings" "testing" @@ -12,9 +11,6 @@ func TestString_AppRoot(t *testing.T) { // arrange var appRootValue = 0 - // mock - createMock(t) - // SUT var sut = LogType(appRootValue) @@ -24,30 +20,12 @@ func TestString_AppRoot(t *testing.T) { // assert assert.Equal(t, LogTypeAppRoot, sut) assert.Equal(t, appRootLogTypeName, result) - - // verify - verifyAll(t) } func TestString_NonSupportedLogTypes(t *testing.T) { // arrange var unsupportedValue = 1 << 31 - // mock - createMock(t) - - // expect - sortStringsExpected = 1 - sortStrings = func(a []string) { - sortStringsCalled++ - sort.Strings(a) - } - stringsJoinExpected = 1 - stringsJoin = func(a []string, sep string) string { - stringsJoinCalled++ - return strings.Join(a, sep) - } - // SUT var sut = LogType(unsupportedValue) @@ -56,27 +34,9 @@ func TestString_NonSupportedLogTypes(t *testing.T) { // assert assert.Zero(t, result) - - // verify - verifyAll(t) } func TestString_SingleSupportedLogType(t *testing.T) { - // mock - createMock(t) - - // expect - sortStringsExpected = 1 - sortStrings = func(a []string) { - sortStringsCalled++ - sort.Strings(a) - } - stringsJoinExpected = 1 - stringsJoin = func(a []string, sep string) string { - stringsJoinCalled++ - return strings.Join(a, sep) - } - // SUT var sut = LogTypeMethodLogic @@ -85,30 +45,12 @@ func TestString_SingleSupportedLogType(t *testing.T) { // assert assert.Equal(t, methodLogicLogTypeName, result) - - // verify - verifyAll(t) } func TestString_MultipleSupportedLogTypes(t *testing.T) { // arrange var supportedValue = LogTypeProcessEnter | LogTypeProcessRequest | LogTypeMethodLogic | LogTypeProcessResponse | LogTypeProcessExit - // mock - createMock(t) - - // expect - sortStringsExpected = 1 - sortStrings = func(a []string) { - sortStringsCalled++ - sort.Strings(a) - } - stringsJoinExpected = 1 - stringsJoin = func(a []string, sep string) string { - stringsJoinCalled++ - return strings.Join(a, sep) - } - // SUT var sut = LogType(supportedValue) @@ -122,18 +64,12 @@ func TestString_MultipleSupportedLogTypes(t *testing.T) { assert.True(t, strings.Contains(result, methodLogicLogTypeName)) assert.True(t, strings.Contains(result, apiResponseLogTypeName)) assert.True(t, strings.Contains(result, apiExitLogTypeName)) - - // verify - verifyAll(t) } func TestHasFlag_FlagMatch_AppRoot(t *testing.T) { // arrange var flag = LogTypeAppRoot - // mock - createMock(t) - // SUT var sut = LogTypeAppRoot @@ -142,18 +78,12 @@ func TestHasFlag_FlagMatch_AppRoot(t *testing.T) { // assert assert.True(t, result) - - // verify - verifyAll(t) } func TestHasFlag_FlagNoMatch_AppRoot(t *testing.T) { // arrange var flag = LogTypeAppRoot - // mock - createMock(t) - // SUT var sut = LogTypeProcessEnter | LogTypeProcessExit @@ -162,18 +92,12 @@ func TestHasFlag_FlagNoMatch_AppRoot(t *testing.T) { // assert assert.True(t, result) - - // verify - verifyAll(t) } func TestHasFlag_FlagMatch_NotAppRoot(t *testing.T) { // arrange var flag = LogTypeMethodLogic - // mock - createMock(t) - // SUT var sut = LogTypeProcessEnter | LogTypeMethodLogic | LogTypeProcessExit @@ -182,18 +106,12 @@ func TestHasFlag_FlagMatch_NotAppRoot(t *testing.T) { // assert assert.True(t, result) - - // verify - verifyAll(t) } func TestHasFlag_FlagNoMatch_NotAppRoot(t *testing.T) { // arrange var flag = LogTypeMethodLogic - // mock - createMock(t) - // SUT var sut = LogTypeProcessEnter | LogTypeProcessExit @@ -202,72 +120,36 @@ func TestHasFlag_FlagNoMatch_NotAppRoot(t *testing.T) { // assert assert.False(t, result) - - // verify - verifyAll(t) } func TestNewLogType_NoMatchFound(t *testing.T) { // arrange var dummyValue = "some value" - // mock - createMock(t) - - // expect - stringsSplit = func(s, sep string) []string { - return strings.Split(s, sep) - } - // SUT + act var result = NewLogType(dummyValue) // assert assert.Equal(t, LogTypeAppRoot, result) - - // tear down - verifyAll(t) } func TestNewLogType_AppRoot(t *testing.T) { // arrange var dummyValue = appRootLogTypeName - // mock - createMock(t) - - // expect - stringsSplit = func(s, sep string) []string { - return strings.Split(s, sep) - } - // SUT + act var result = NewLogType(dummyValue) // assert assert.Equal(t, LogTypeAppRoot, result) - - // tear down - verifyAll(t) } func TestNewLogType_HappyPath(t *testing.T) { for key, value := range logTypeNameMapping { - // mock - createMock(t) - - // expect - stringsSplit = func(s, sep string) []string { - return strings.Split(s, sep) - } - // SUT + act var result = NewLogType(key) // assert assert.Equal(t, value, result) - - // tear down - verifyAll(t) } } diff --git a/logger.go b/logger.go index d18df2a..147605e 100644 --- a/logger.go +++ b/logger.go @@ -1,5 +1,7 @@ package jobrunner +import "fmt" + func prepareLogging( session *session, logType LogType, @@ -18,7 +20,7 @@ func prepareLogging( logLevel, category, subcategory, - fmtSprintf( + fmt.Sprintf( messageFormat, parameters..., ), @@ -27,7 +29,7 @@ func prepareLogging( // logAppRoot logs the given message as AppRoot category func logAppRoot(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - prepareLoggingFunc( + prepareLogging( session, LogTypeAppRoot, LogLevelInfo, @@ -40,7 +42,7 @@ func logAppRoot(session *session, category string, subcategory string, messageFo // logProcessEnter logs the given message as ProcessEnter category func logProcessEnter(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - prepareLoggingFunc( + prepareLogging( session, LogTypeProcessEnter, LogLevelInfo, @@ -53,7 +55,7 @@ func logProcessEnter(session *session, category string, subcategory string, mess // logProcessRequest logs the given message as ProcessRequest category func logProcessRequest(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - prepareLoggingFunc( + prepareLogging( session, LogTypeProcessRequest, LogLevelInfo, @@ -66,7 +68,7 @@ func logProcessRequest(session *session, category string, subcategory string, me // logMethodEnter logs the given message as MethodEnter category func logMethodEnter(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - prepareLoggingFunc( + prepareLogging( session, LogTypeMethodEnter, LogLevelInfo, @@ -79,7 +81,7 @@ func logMethodEnter(session *session, category string, subcategory string, messa // logMethodParameter logs the given message as MethodParameter category func logMethodParameter(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - prepareLoggingFunc( + prepareLogging( session, LogTypeMethodParameter, LogLevelInfo, @@ -92,7 +94,7 @@ func logMethodParameter(session *session, category string, subcategory string, m // logMethodLogic logs the given message as MethodLogic category func logMethodLogic(session *session, logLevel LogLevel, category string, subcategory string, messageFormat string, parameters ...interface{}) { - prepareLoggingFunc( + prepareLogging( session, LogTypeMethodLogic, logLevel, @@ -105,7 +107,7 @@ func logMethodLogic(session *session, logLevel LogLevel, category string, subcat // logWebcallStart logs the given message as WebcallStart category func logWebcallStart(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - prepareLoggingFunc( + prepareLogging( session, LogTypeWebcallStart, LogLevelInfo, @@ -118,7 +120,7 @@ func logWebcallStart(session *session, category string, subcategory string, mess // logWebcallRequest logs the given message as WebcallRequest category func logWebcallRequest(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - prepareLoggingFunc( + prepareLogging( session, LogTypeWebcallRequest, LogLevelInfo, @@ -131,7 +133,7 @@ func logWebcallRequest(session *session, category string, subcategory string, me // logWebcallResponse logs the given message as WebcallResponse category func logWebcallResponse(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - prepareLoggingFunc( + prepareLogging( session, LogTypeWebcallResponse, LogLevelInfo, @@ -144,7 +146,7 @@ func logWebcallResponse(session *session, category string, subcategory string, m // logWebcallFinish logs the given message as WebcallFinish category func logWebcallFinish(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - prepareLoggingFunc( + prepareLogging( session, LogTypeWebcallFinish, LogLevelInfo, @@ -157,7 +159,7 @@ func logWebcallFinish(session *session, category string, subcategory string, mes // logMethodReturn logs the given message as MethodReturn category func logMethodReturn(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - prepareLoggingFunc( + prepareLogging( session, LogTypeMethodReturn, LogLevelInfo, @@ -170,7 +172,7 @@ func logMethodReturn(session *session, category string, subcategory string, mess // logMethodExit logs the given message as MethodExit category func logMethodExit(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - prepareLoggingFunc( + prepareLogging( session, LogTypeMethodExit, LogLevelInfo, @@ -183,7 +185,7 @@ func logMethodExit(session *session, category string, subcategory string, messag // logProcessResponse logs the given message as ProcessResponse category func logProcessResponse(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - prepareLoggingFunc( + prepareLogging( session, LogTypeProcessResponse, LogLevelInfo, @@ -196,7 +198,7 @@ func logProcessResponse(session *session, category string, subcategory string, m // logProcessExit logs the given message as ProcessExit category func logProcessExit(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - prepareLoggingFunc( + prepareLogging( session, LogTypeProcessExit, LogLevelInfo, diff --git a/logger_test.go b/logger_test.go index f3ac322..01860d4 100644 --- a/logger_test.go +++ b/logger_test.go @@ -2,31 +2,19 @@ package jobrunner import ( "errors" - "math/rand" + "fmt" + "math/rand/v2" "testing" "github.com/google/uuid" - "github.com/stretchr/testify/assert" + "github.com/zhongjie-cai/gomocker/v2" ) -type dummyCustomizationLoger struct { - dummyCustomization - log func(session Session, logType LogType, logLevel LogLevel, category, subcategory, description string) -} - -func (customization *dummyCustomizationLoger) Log(session Session, logType LogType, logLevel LogLevel, category, subcategory, description string) { - if customization.log != nil { - customization.log(session, logType, logLevel, category, subcategory, description) - return - } - assert.Fail(customization.t, "Unexpected call to Log") -} - func TestPrepareLoggingFunc_NilSession(t *testing.T) { // arrange var dummySession *session - var dummyLogType = LogType(rand.Intn(100)) - var dummyLogLevel = LogLevel(rand.Intn(100)) + var dummyLogType = LogType(rand.IntN(100)) + var dummyLogLevel = LogLevel(rand.IntN(100)) var dummyCategory = "some category" var dummySubcategory = "some subcategory" var dummyMessageFormat = "some message format" @@ -34,9 +22,6 @@ func TestPrepareLoggingFunc_NilSession(t *testing.T) { var dummyParameter2 = rand.Int() var dummyParameter3 = errors.New("some parameter 3") - // mock - createMock(t) - // SUT + act prepareLogging( dummySession, @@ -49,55 +34,40 @@ func TestPrepareLoggingFunc_NilSession(t *testing.T) { dummyParameter2, dummyParameter3, ) - - // verify - verifyAll(t) } func TestPrepareLoggingFunc_HappyPath(t *testing.T) { // arrange - var dummyCustomizationLoger = &dummyCustomizationLoger{ - dummyCustomization: dummyCustomization{t: t}, + type customization struct { + Customization } + var dummyCustomization = &customization{} var dummySession = &session{ - customization: dummyCustomizationLoger, + customization: dummyCustomization, } - var dummyLogType = LogType(rand.Intn(100)) - var dummyLogLevel = LogLevel(rand.Intn(100)) + var dummyLogType = LogType(rand.IntN(100)) + var dummyLogLevel = LogLevel(rand.IntN(100)) var dummyCategory = "some category" var dummySubcategory = "some subcategory" - var dummyMessageFormat = "some message format" + var dummyMessageFormat = "some message format %v %v %v" var dummyParameter1 = "some parameter 1" var dummyParameter2 = rand.Int() var dummyParameter3 = errors.New("some parameter 3") - var dummyDescription = "some description" - var customizationLogExpected int - var customizationLogCalled int + var dummyDescription = fmt.Sprintf(dummyMessageFormat, dummyParameter1, dummyParameter2, dummyParameter3) // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - fmtSprintfExpected = 1 - fmtSprintf = func(format string, a ...interface{}) string { - fmtSprintfCalled++ - assert.Equal(t, dummyMessageFormat, format) - assert.Equal(t, 3, len(a)) - assert.Equal(t, dummyParameter1, a[0]) - assert.Equal(t, dummyParameter2, a[1]) - assert.Equal(t, dummyParameter3, a[2]) - return dummyDescription - } - customizationLogExpected = 1 - dummyCustomizationLoger.log = func(session Session, logType LogType, logLevel LogLevel, category, subcategory, description string) { - customizationLogCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, dummyLogType, logType) - assert.Equal(t, dummyLogLevel, logLevel) - assert.Equal(t, dummyCategory, category) - assert.Equal(t, dummySubcategory, subcategory) - assert.Equal(t, dummyDescription, description) - } + m.Mock((*customization).Log).Expects( + dummyCustomization, + dummySession, + dummyLogType, + dummyLogLevel, + dummyCategory, + dummySubcategory, + dummyDescription, + ).Returns().Once() // SUT + act prepareLogging( @@ -112,9 +82,6 @@ func TestPrepareLoggingFunc_HappyPath(t *testing.T) { dummyParameter3, ) - // verify - verifyAll(t) - assert.Equal(t, customizationLogExpected, customizationLogCalled, "Unexpected number of calls to method customization.Log") } func TestLogAppRoot(t *testing.T) { @@ -130,23 +97,20 @@ func TestLogAppRoot(t *testing.T) { var dummyParameter3 = errors.New("some parameter 3") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - prepareLoggingFuncExpected = 1 - prepareLoggingFunc = func(session *session, logType LogType, logLevel LogLevel, category string, subcategory string, messageFormat string, parameters ...interface{}) { - prepareLoggingFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, LogTypeAppRoot, logType) - assert.Equal(t, LogLevelInfo, logLevel) - assert.Equal(t, dummyCategory, category) - assert.Equal(t, dummySubcategory, subcategory) - assert.Equal(t, dummyMessageFormat, messageFormat) - assert.Equal(t, 3, len(parameters)) - assert.Equal(t, dummyParameter1, parameters[0]) - assert.Equal(t, dummyParameter2, parameters[1]) - assert.Equal(t, dummyParameter3, parameters[2]) - } + m.Mock(prepareLogging).Expects( + dummySession, + LogTypeAppRoot, + LogLevelInfo, + dummyCategory, + dummySubcategory, + dummyMessageFormat, + dummyParameter1, + dummyParameter2, + dummyParameter3, + ).Returns().Once() // SUT + act logAppRoot( @@ -158,9 +122,6 @@ func TestLogAppRoot(t *testing.T) { dummyParameter2, dummyParameter3, ) - - // verify - verifyAll(t) } func TestLogProcessEnter(t *testing.T) { @@ -176,23 +137,20 @@ func TestLogProcessEnter(t *testing.T) { var dummyParameter3 = errors.New("some parameter 3") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - prepareLoggingFuncExpected = 1 - prepareLoggingFunc = func(session *session, logType LogType, logLevel LogLevel, category string, subcategory string, messageFormat string, parameters ...interface{}) { - prepareLoggingFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, LogTypeProcessEnter, logType) - assert.Equal(t, LogLevelInfo, logLevel) - assert.Equal(t, dummyCategory, category) - assert.Equal(t, dummySubcategory, subcategory) - assert.Equal(t, dummyMessageFormat, messageFormat) - assert.Equal(t, 3, len(parameters)) - assert.Equal(t, dummyParameter1, parameters[0]) - assert.Equal(t, dummyParameter2, parameters[1]) - assert.Equal(t, dummyParameter3, parameters[2]) - } + m.Mock(prepareLogging).Expects( + dummySession, + LogTypeProcessEnter, + LogLevelInfo, + dummyCategory, + dummySubcategory, + dummyMessageFormat, + dummyParameter1, + dummyParameter2, + dummyParameter3, + ).Returns().Once() // SUT + act logProcessEnter( @@ -204,9 +162,6 @@ func TestLogProcessEnter(t *testing.T) { dummyParameter2, dummyParameter3, ) - - // verify - verifyAll(t) } func TestLogProcessRequest(t *testing.T) { @@ -222,23 +177,20 @@ func TestLogProcessRequest(t *testing.T) { var dummyParameter3 = errors.New("some parameter 3") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - prepareLoggingFuncExpected = 1 - prepareLoggingFunc = func(session *session, logType LogType, logLevel LogLevel, category string, subcategory string, messageFormat string, parameters ...interface{}) { - prepareLoggingFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, LogTypeProcessRequest, logType) - assert.Equal(t, LogLevelInfo, logLevel) - assert.Equal(t, dummyCategory, category) - assert.Equal(t, dummySubcategory, subcategory) - assert.Equal(t, dummyMessageFormat, messageFormat) - assert.Equal(t, 3, len(parameters)) - assert.Equal(t, dummyParameter1, parameters[0]) - assert.Equal(t, dummyParameter2, parameters[1]) - assert.Equal(t, dummyParameter3, parameters[2]) - } + m.Mock(prepareLogging).Expects( + dummySession, + LogTypeProcessRequest, + LogLevelInfo, + dummyCategory, + dummySubcategory, + dummyMessageFormat, + dummyParameter1, + dummyParameter2, + dummyParameter3, + ).Returns().Once() // SUT + act logProcessRequest( @@ -250,9 +202,6 @@ func TestLogProcessRequest(t *testing.T) { dummyParameter2, dummyParameter3, ) - - // verify - verifyAll(t) } func TestLogMethodEnter(t *testing.T) { @@ -268,23 +217,20 @@ func TestLogMethodEnter(t *testing.T) { var dummyParameter3 = errors.New("some parameter 3") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - prepareLoggingFuncExpected = 1 - prepareLoggingFunc = func(session *session, logType LogType, logLevel LogLevel, category string, subcategory string, messageFormat string, parameters ...interface{}) { - prepareLoggingFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, LogTypeMethodEnter, logType) - assert.Equal(t, LogLevelInfo, logLevel) - assert.Equal(t, dummyCategory, category) - assert.Equal(t, dummySubcategory, subcategory) - assert.Equal(t, dummyMessageFormat, messageFormat) - assert.Equal(t, 3, len(parameters)) - assert.Equal(t, dummyParameter1, parameters[0]) - assert.Equal(t, dummyParameter2, parameters[1]) - assert.Equal(t, dummyParameter3, parameters[2]) - } + m.Mock(prepareLogging).Expects( + dummySession, + LogTypeMethodEnter, + LogLevelInfo, + dummyCategory, + dummySubcategory, + dummyMessageFormat, + dummyParameter1, + dummyParameter2, + dummyParameter3, + ).Returns().Once() // SUT + act logMethodEnter( @@ -296,9 +242,6 @@ func TestLogMethodEnter(t *testing.T) { dummyParameter2, dummyParameter3, ) - - // verify - verifyAll(t) } func TestLogMethodParameter(t *testing.T) { @@ -314,23 +257,20 @@ func TestLogMethodParameter(t *testing.T) { var dummyParameter3 = errors.New("some parameter 3") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - prepareLoggingFuncExpected = 1 - prepareLoggingFunc = func(session *session, logType LogType, logLevel LogLevel, category string, subcategory string, messageFormat string, parameters ...interface{}) { - prepareLoggingFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, LogTypeMethodParameter, logType) - assert.Equal(t, LogLevelInfo, logLevel) - assert.Equal(t, dummyCategory, category) - assert.Equal(t, dummySubcategory, subcategory) - assert.Equal(t, dummyMessageFormat, messageFormat) - assert.Equal(t, 3, len(parameters)) - assert.Equal(t, dummyParameter1, parameters[0]) - assert.Equal(t, dummyParameter2, parameters[1]) - assert.Equal(t, dummyParameter3, parameters[2]) - } + m.Mock(prepareLogging).Expects( + dummySession, + LogTypeMethodParameter, + LogLevelInfo, + dummyCategory, + dummySubcategory, + dummyMessageFormat, + dummyParameter1, + dummyParameter2, + dummyParameter3, + ).Returns().Once() // SUT + act logMethodParameter( @@ -342,9 +282,6 @@ func TestLogMethodParameter(t *testing.T) { dummyParameter2, dummyParameter3, ) - - // verify - verifyAll(t) } func TestLogMethodLogic(t *testing.T) { @@ -352,7 +289,7 @@ func TestLogMethodLogic(t *testing.T) { var dummySession = &session{ id: uuid.New(), } - var dummyLogLevel = LogLevel(rand.Intn(100)) + var dummyLogLevel = LogLevel(rand.IntN(100)) var dummyCategory = "some category" var dummySubcategory = "some subcategory" var dummyMessageFormat = "some message format" @@ -361,23 +298,20 @@ func TestLogMethodLogic(t *testing.T) { var dummyParameter3 = errors.New("some parameter 3") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - prepareLoggingFuncExpected = 1 - prepareLoggingFunc = func(session *session, logType LogType, logLevel LogLevel, category string, subcategory string, messageFormat string, parameters ...interface{}) { - prepareLoggingFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, LogTypeMethodLogic, logType) - assert.Equal(t, dummyLogLevel, logLevel) - assert.Equal(t, dummyCategory, category) - assert.Equal(t, dummySubcategory, subcategory) - assert.Equal(t, dummyMessageFormat, messageFormat) - assert.Equal(t, 3, len(parameters)) - assert.Equal(t, dummyParameter1, parameters[0]) - assert.Equal(t, dummyParameter2, parameters[1]) - assert.Equal(t, dummyParameter3, parameters[2]) - } + m.Mock(prepareLogging).Expects( + dummySession, + LogTypeMethodLogic, + dummyLogLevel, + dummyCategory, + dummySubcategory, + dummyMessageFormat, + dummyParameter1, + dummyParameter2, + dummyParameter3, + ).Returns().Once() // SUT + act logMethodLogic( @@ -390,9 +324,6 @@ func TestLogMethodLogic(t *testing.T) { dummyParameter2, dummyParameter3, ) - - // verify - verifyAll(t) } func TestLogWebcallStart(t *testing.T) { @@ -408,23 +339,20 @@ func TestLogWebcallStart(t *testing.T) { var dummyParameter3 = errors.New("some parameter 3") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - prepareLoggingFuncExpected = 1 - prepareLoggingFunc = func(session *session, logType LogType, logLevel LogLevel, category string, subcategory string, messageFormat string, parameters ...interface{}) { - prepareLoggingFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, LogTypeWebcallStart, logType) - assert.Equal(t, LogLevelInfo, logLevel) - assert.Equal(t, dummyCategory, category) - assert.Equal(t, dummySubcategory, subcategory) - assert.Equal(t, dummyMessageFormat, messageFormat) - assert.Equal(t, 3, len(parameters)) - assert.Equal(t, dummyParameter1, parameters[0]) - assert.Equal(t, dummyParameter2, parameters[1]) - assert.Equal(t, dummyParameter3, parameters[2]) - } + m.Mock(prepareLogging).Expects( + dummySession, + LogTypeWebcallStart, + LogLevelInfo, + dummyCategory, + dummySubcategory, + dummyMessageFormat, + dummyParameter1, + dummyParameter2, + dummyParameter3, + ).Returns().Once() // SUT + act logWebcallStart( @@ -436,9 +364,6 @@ func TestLogWebcallStart(t *testing.T) { dummyParameter2, dummyParameter3, ) - - // verify - verifyAll(t) } func TestLogWebcallRequest(t *testing.T) { @@ -454,23 +379,20 @@ func TestLogWebcallRequest(t *testing.T) { var dummyParameter3 = errors.New("some parameter 3") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - prepareLoggingFuncExpected = 1 - prepareLoggingFunc = func(session *session, logType LogType, logLevel LogLevel, category string, subcategory string, messageFormat string, parameters ...interface{}) { - prepareLoggingFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, LogTypeWebcallRequest, logType) - assert.Equal(t, LogLevelInfo, logLevel) - assert.Equal(t, dummyCategory, category) - assert.Equal(t, dummySubcategory, subcategory) - assert.Equal(t, dummyMessageFormat, messageFormat) - assert.Equal(t, 3, len(parameters)) - assert.Equal(t, dummyParameter1, parameters[0]) - assert.Equal(t, dummyParameter2, parameters[1]) - assert.Equal(t, dummyParameter3, parameters[2]) - } + m.Mock(prepareLogging).Expects( + dummySession, + LogTypeWebcallRequest, + LogLevelInfo, + dummyCategory, + dummySubcategory, + dummyMessageFormat, + dummyParameter1, + dummyParameter2, + dummyParameter3, + ).Returns().Once() // SUT + act logWebcallRequest( @@ -482,9 +404,6 @@ func TestLogWebcallRequest(t *testing.T) { dummyParameter2, dummyParameter3, ) - - // verify - verifyAll(t) } func TestLogWebcallResponse(t *testing.T) { @@ -500,23 +419,20 @@ func TestLogWebcallResponse(t *testing.T) { var dummyParameter3 = errors.New("some parameter 3") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - prepareLoggingFuncExpected = 1 - prepareLoggingFunc = func(session *session, logType LogType, logLevel LogLevel, category string, subcategory string, messageFormat string, parameters ...interface{}) { - prepareLoggingFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, LogTypeWebcallResponse, logType) - assert.Equal(t, LogLevelInfo, logLevel) - assert.Equal(t, dummyCategory, category) - assert.Equal(t, dummySubcategory, subcategory) - assert.Equal(t, dummyMessageFormat, messageFormat) - assert.Equal(t, 3, len(parameters)) - assert.Equal(t, dummyParameter1, parameters[0]) - assert.Equal(t, dummyParameter2, parameters[1]) - assert.Equal(t, dummyParameter3, parameters[2]) - } + m.Mock(prepareLogging).Expects( + dummySession, + LogTypeWebcallResponse, + LogLevelInfo, + dummyCategory, + dummySubcategory, + dummyMessageFormat, + dummyParameter1, + dummyParameter2, + dummyParameter3, + ).Returns().Once() // SUT + act logWebcallResponse( @@ -528,9 +444,6 @@ func TestLogWebcallResponse(t *testing.T) { dummyParameter2, dummyParameter3, ) - - // verify - verifyAll(t) } func TestLogWebcallFinish(t *testing.T) { @@ -546,23 +459,20 @@ func TestLogWebcallFinish(t *testing.T) { var dummyParameter3 = errors.New("some parameter 3") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - prepareLoggingFuncExpected = 1 - prepareLoggingFunc = func(session *session, logType LogType, logLevel LogLevel, category string, subcategory string, messageFormat string, parameters ...interface{}) { - prepareLoggingFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, LogTypeWebcallFinish, logType) - assert.Equal(t, LogLevelInfo, logLevel) - assert.Equal(t, dummyCategory, category) - assert.Equal(t, dummySubcategory, subcategory) - assert.Equal(t, dummyMessageFormat, messageFormat) - assert.Equal(t, 3, len(parameters)) - assert.Equal(t, dummyParameter1, parameters[0]) - assert.Equal(t, dummyParameter2, parameters[1]) - assert.Equal(t, dummyParameter3, parameters[2]) - } + m.Mock(prepareLogging).Expects( + dummySession, + LogTypeWebcallFinish, + LogLevelInfo, + dummyCategory, + dummySubcategory, + dummyMessageFormat, + dummyParameter1, + dummyParameter2, + dummyParameter3, + ).Returns().Once() // SUT + act logWebcallFinish( @@ -574,9 +484,6 @@ func TestLogWebcallFinish(t *testing.T) { dummyParameter2, dummyParameter3, ) - - // verify - verifyAll(t) } func TestLogMethodReturn(t *testing.T) { @@ -592,23 +499,20 @@ func TestLogMethodReturn(t *testing.T) { var dummyParameter3 = errors.New("some parameter 3") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - prepareLoggingFuncExpected = 1 - prepareLoggingFunc = func(session *session, logType LogType, logLevel LogLevel, category string, subcategory string, messageFormat string, parameters ...interface{}) { - prepareLoggingFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, LogTypeMethodReturn, logType) - assert.Equal(t, LogLevelInfo, logLevel) - assert.Equal(t, dummyCategory, category) - assert.Equal(t, dummySubcategory, subcategory) - assert.Equal(t, dummyMessageFormat, messageFormat) - assert.Equal(t, 3, len(parameters)) - assert.Equal(t, dummyParameter1, parameters[0]) - assert.Equal(t, dummyParameter2, parameters[1]) - assert.Equal(t, dummyParameter3, parameters[2]) - } + m.Mock(prepareLogging).Expects( + dummySession, + LogTypeMethodReturn, + LogLevelInfo, + dummyCategory, + dummySubcategory, + dummyMessageFormat, + dummyParameter1, + dummyParameter2, + dummyParameter3, + ).Returns().Once() // SUT + act logMethodReturn( @@ -620,9 +524,6 @@ func TestLogMethodReturn(t *testing.T) { dummyParameter2, dummyParameter3, ) - - // verify - verifyAll(t) } func TestLogMethodExit(t *testing.T) { @@ -638,23 +539,20 @@ func TestLogMethodExit(t *testing.T) { var dummyParameter3 = errors.New("some parameter 3") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - prepareLoggingFuncExpected = 1 - prepareLoggingFunc = func(session *session, logType LogType, logLevel LogLevel, category string, subcategory string, messageFormat string, parameters ...interface{}) { - prepareLoggingFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, LogTypeMethodExit, logType) - assert.Equal(t, LogLevelInfo, logLevel) - assert.Equal(t, dummyCategory, category) - assert.Equal(t, dummySubcategory, subcategory) - assert.Equal(t, dummyMessageFormat, messageFormat) - assert.Equal(t, 3, len(parameters)) - assert.Equal(t, dummyParameter1, parameters[0]) - assert.Equal(t, dummyParameter2, parameters[1]) - assert.Equal(t, dummyParameter3, parameters[2]) - } + m.Mock(prepareLogging).Expects( + dummySession, + LogTypeMethodExit, + LogLevelInfo, + dummyCategory, + dummySubcategory, + dummyMessageFormat, + dummyParameter1, + dummyParameter2, + dummyParameter3, + ).Returns().Once() // SUT + act logMethodExit( @@ -666,9 +564,6 @@ func TestLogMethodExit(t *testing.T) { dummyParameter2, dummyParameter3, ) - - // verify - verifyAll(t) } func TestLogProcessResponse(t *testing.T) { @@ -684,23 +579,20 @@ func TestLogProcessResponse(t *testing.T) { var dummyParameter3 = errors.New("some parameter 3") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - prepareLoggingFuncExpected = 1 - prepareLoggingFunc = func(session *session, logType LogType, logLevel LogLevel, category string, subcategory string, messageFormat string, parameters ...interface{}) { - prepareLoggingFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, LogTypeProcessResponse, logType) - assert.Equal(t, LogLevelInfo, logLevel) - assert.Equal(t, dummyCategory, category) - assert.Equal(t, dummySubcategory, subcategory) - assert.Equal(t, dummyMessageFormat, messageFormat) - assert.Equal(t, 3, len(parameters)) - assert.Equal(t, dummyParameter1, parameters[0]) - assert.Equal(t, dummyParameter2, parameters[1]) - assert.Equal(t, dummyParameter3, parameters[2]) - } + m.Mock(prepareLogging).Expects( + dummySession, + LogTypeProcessResponse, + LogLevelInfo, + dummyCategory, + dummySubcategory, + dummyMessageFormat, + dummyParameter1, + dummyParameter2, + dummyParameter3, + ).Returns().Once() // SUT + act logProcessResponse( @@ -712,9 +604,6 @@ func TestLogProcessResponse(t *testing.T) { dummyParameter2, dummyParameter3, ) - - // verify - verifyAll(t) } func TestLogProcessExit(t *testing.T) { @@ -730,23 +619,20 @@ func TestLogProcessExit(t *testing.T) { var dummyParameter3 = errors.New("some parameter 3") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - prepareLoggingFuncExpected = 1 - prepareLoggingFunc = func(session *session, logType LogType, logLevel LogLevel, category string, subcategory string, messageFormat string, parameters ...interface{}) { - prepareLoggingFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, LogTypeProcessExit, logType) - assert.Equal(t, LogLevelInfo, logLevel) - assert.Equal(t, dummyCategory, category) - assert.Equal(t, dummySubcategory, subcategory) - assert.Equal(t, dummyMessageFormat, messageFormat) - assert.Equal(t, 3, len(parameters)) - assert.Equal(t, dummyParameter1, parameters[0]) - assert.Equal(t, dummyParameter2, parameters[1]) - assert.Equal(t, dummyParameter3, parameters[2]) - } + m.Mock(prepareLogging).Expects( + dummySession, + LogTypeProcessExit, + LogLevelInfo, + dummyCategory, + dummySubcategory, + dummyMessageFormat, + dummyParameter1, + dummyParameter2, + dummyParameter3, + ).Returns().Once() // SUT + act logProcessExit( @@ -758,7 +644,4 @@ func TestLogProcessExit(t *testing.T) { dummyParameter2, dummyParameter3, ) - - // verify - verifyAll(t) } diff --git a/pointerutil.go b/pointerutil.go index 32c0853..7083b06 100644 --- a/pointerutil.go +++ b/pointerutil.go @@ -6,7 +6,7 @@ func isInterfaceValueNil(i interface{}) bool { if i == nil { return true } - var v = reflectValueOf(i) + var v = reflect.ValueOf(i) if v.Kind() == reflect.Ptr { return v.IsNil() } diff --git a/pointerutil_test.go b/pointerutil_test.go index 247b3c0..a4100ac 100644 --- a/pointerutil_test.go +++ b/pointerutil_test.go @@ -6,17 +6,13 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/zhongjie-cai/gomocker/v2" ) func TestIsInterfaceValueNil_NilInterface(t *testing.T) { // arrange var dummyInterface http.ResponseWriter - // mock - createMock(t) - - // expect - // SUT + act var result = isInterfaceValueNil( dummyInterface, @@ -24,25 +20,11 @@ func TestIsInterfaceValueNil_NilInterface(t *testing.T) { // assert assert.True(t, result) - - // verify - verifyAll(t) } func TestIsInterfaceValueNil_NilValue(t *testing.T) { // arrange - var dummyInterface *dummyCustomization - - // mock - createMock(t) - - // expect - reflectValueOfExpected = 1 - reflectValueOf = func(i interface{}) reflect.Value { - reflectValueOfCalled++ - assert.Equal(t, dummyInterface, i) - return reflect.ValueOf(i) - } + var dummyInterface *DefaultCustomization // SUT + act var result = isInterfaceValueNil( @@ -51,9 +33,6 @@ func TestIsInterfaceValueNil_NilValue(t *testing.T) { // assert assert.True(t, result) - - // verify - verifyAll(t) } func TestIsInterfaceValueNil_EmptyValue(t *testing.T) { @@ -61,15 +40,10 @@ func TestIsInterfaceValueNil_EmptyValue(t *testing.T) { var dummyInterface = 0 // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - reflectValueOfExpected = 1 - reflectValueOf = func(i interface{}) reflect.Value { - reflectValueOfCalled++ - assert.Equal(t, dummyInterface, i) - return reflect.Value{} - } + m.Mock(reflect.Value.IsValid).Expects(gomocker.Anything()).Returns(false).Once() // SUT + act var result = isInterfaceValueNil( @@ -78,26 +52,12 @@ func TestIsInterfaceValueNil_EmptyValue(t *testing.T) { // assert assert.True(t, result) - - // verify - verifyAll(t) } func TestIsInterfaceValueNil_ValidValue(t *testing.T) { // arrange var dummyInterface = 0 - // mock - createMock(t) - - // expect - reflectValueOfExpected = 1 - reflectValueOf = func(i interface{}) reflect.Value { - reflectValueOfCalled++ - assert.Equal(t, dummyInterface, i) - return reflect.ValueOf(dummyInterface) - } - // SUT + act var result = isInterfaceValueNil( dummyInterface, @@ -105,7 +65,4 @@ func TestIsInterfaceValueNil_ValidValue(t *testing.T) { // assert assert.False(t, result) - - // verify - verifyAll(t) } diff --git a/schedule.go b/schedule.go index c7ba73f..11d01af 100644 --- a/schedule.go +++ b/schedule.go @@ -53,7 +53,7 @@ func getDaysOfMonth(year int, month int) int { // plays a trick that time.Date accepts values outside of normal ranges // so setting day to 0 would actually yield the last day of a previous month // that helps calculate the number of days within a given month - var lastDay = timeDate( + var lastDay = time.Date( year, // current year so no change time.Month(month+2), // slide to next month, yields back as current month by the trick 0, // the essential part of this trick - 0-day! @@ -63,7 +63,7 @@ func getDaysOfMonth(year int, month int) int { } func constructTimeBySchedule(schedule *schedule) time.Time { - return timeDate( + return time.Date( schedule.year, time.Month(schedule.month+1), schedule.day+1, @@ -80,45 +80,45 @@ func updateScheduleIndex( ) bool { var reset bool // get next second from schedule data - schedule.second, schedule.secondIndex, reset = moveValueIndexFunc( + schedule.second, schedule.secondIndex, reset = moveValueIndex( schedule.secondIndex, schedule.seconds, 60, ) if reset { // second reset, thus get next minute from schedule data - schedule.minute, schedule.minuteIndex, reset = moveValueIndexFunc( + schedule.minute, schedule.minuteIndex, reset = moveValueIndex( schedule.minuteIndex, schedule.minutes, 60, ) if reset { // minute reset, thus get next hour from schedule data - schedule.hour, schedule.hourIndex, reset = moveValueIndexFunc( + schedule.hour, schedule.hourIndex, reset = moveValueIndex( schedule.hourIndex, schedule.hours, 24, ) if reset { // hour reset, thus get next day from schedule data - schedule.day, schedule.dayIndex, reset = moveValueIndexFunc( + schedule.day, schedule.dayIndex, reset = moveValueIndex( schedule.dayIndex, schedule.days, - getDaysOfMonthFunc( + getDaysOfMonth( schedule.year, schedule.month, ), ) if reset { // day reset, thus get next month from schedule data - schedule.month, schedule.monthIndex, reset = moveValueIndexFunc( + schedule.month, schedule.monthIndex, reset = moveValueIndex( schedule.monthIndex, schedule.months, 12, ) if reset { // month reset, thus get next year from schedule data - schedule.year, schedule.yearIndex, reset = moveValueIndexFunc( + schedule.year, schedule.yearIndex, reset = moveValueIndex( schedule.yearIndex, schedule.years, 9999, // hopefully nobody is still using this library by year 9999? @@ -134,7 +134,7 @@ func updateScheduleIndex( } func (schedule *schedule) NextSchedule() *time.Time { - var currentLocalTime = timeNow() + var currentLocalTime = time.Now() if schedule.till != nil && schedule.till.Before(currentLocalTime) { // causes the schedule to terminate @@ -146,10 +146,10 @@ func (schedule *schedule) NextSchedule() *time.Time { return nil } // load next schedule time - var timeNext = constructTimeByScheduleFunc( + var timeNext = constructTimeBySchedule( schedule, ) - schedule.completed = updateScheduleIndexFunc( + schedule.completed = updateScheduleIndex( schedule, ) if currentLocalTime.Before(timeNext) { diff --git a/scheduleMaker.go b/scheduleMaker.go index ffe4225..aaa0523 100644 --- a/scheduleMaker.go +++ b/scheduleMaker.go @@ -1,6 +1,8 @@ package jobrunner import ( + "fmt" + "sort" "time" ) @@ -83,7 +85,7 @@ func generateFlagsData(data []bool, total int, values ...int) []bool { // OnSeconds sets up the scheduleMaker on second's level; if not called or called with no parameters, then every second is considered to be set up func (scheduleMaker *scheduleMaker) OnSeconds(seconds ...int) ScheduleMaker { - scheduleMaker.seconds = generateFlagsDataFunc( + scheduleMaker.seconds = generateFlagsData( scheduleMaker.seconds, 60, seconds..., @@ -93,7 +95,7 @@ func (scheduleMaker *scheduleMaker) OnSeconds(seconds ...int) ScheduleMaker { // OnMinutes sets up the scheduleMaker on minute's level; if not called or called with no parameters, then every minute is considered to be set up func (scheduleMaker *scheduleMaker) OnMinutes(minutes ...int) ScheduleMaker { - scheduleMaker.minutes = generateFlagsDataFunc( + scheduleMaker.minutes = generateFlagsData( scheduleMaker.minutes, 60, minutes..., @@ -103,7 +105,7 @@ func (scheduleMaker *scheduleMaker) OnMinutes(minutes ...int) ScheduleMaker { // AtHours sets up the scheduleMaker on hour's level; if not called or called with no parameters, then every hour is considered to be set up func (scheduleMaker *scheduleMaker) AtHours(hours ...int) ScheduleMaker { - scheduleMaker.hours = generateFlagsDataFunc( + scheduleMaker.hours = generateFlagsData( scheduleMaker.hours, 24, hours..., @@ -117,7 +119,7 @@ func (scheduleMaker *scheduleMaker) OnWeekdays(weekdays ...time.Weekday) Schedul for _, weekday := range weekdays { weekdaysInInt = append(weekdaysInInt, int(weekday)) } - scheduleMaker.weekdays = generateFlagsDataFunc( + scheduleMaker.weekdays = generateFlagsData( scheduleMaker.weekdays, 7, weekdaysInInt..., @@ -132,7 +134,7 @@ func (scheduleMaker *scheduleMaker) OnDays(days ...int) ScheduleMaker { // due to the fact that day value start from 1 instead of 0... daysInInt = append(daysInInt, day-1) } - scheduleMaker.days = generateFlagsDataFunc( + scheduleMaker.days = generateFlagsData( scheduleMaker.days, 31, daysInInt..., @@ -147,7 +149,7 @@ func (scheduleMaker *scheduleMaker) InMonths(months ...time.Month) ScheduleMaker // due to the fact that month value start from 1 instead of 0... monthsInInt = append(monthsInInt, int(month-1)) } - scheduleMaker.months = generateFlagsDataFunc( + scheduleMaker.months = generateFlagsData( scheduleMaker.months, 12, monthsInInt..., @@ -229,7 +231,7 @@ func constructYearSlice(years map[int]bool) []int { var data = []int{} if len(years) == 0 { // hard-code this to allow execution for 100 years if no year is specified - var currentTime = timeNow() + var currentTime = time.Now() var currentYear = currentTime.Year() for year := currentYear; year < currentYear+100; year++ { data = append(data, year) @@ -240,7 +242,7 @@ func constructYearSlice(years map[int]bool) []int { data = append(data, year) } } - sortInts(data) + sort.Ints(data) } return data } @@ -248,18 +250,18 @@ func constructYearSlice(years map[int]bool) []int { func constructScheduleTemplate(scheduleMaker *scheduleMaker) *schedule { var schedule = &schedule{ secondIndex: 0, - seconds: constructValueSliceFunc(scheduleMaker.seconds, 60), + seconds: constructValueSlice(scheduleMaker.seconds, 60), minuteIndex: 0, - minutes: constructValueSliceFunc(scheduleMaker.minutes, 60), + minutes: constructValueSlice(scheduleMaker.minutes, 60), hourIndex: 0, - hours: constructValueSliceFunc(scheduleMaker.hours, 24), + hours: constructValueSlice(scheduleMaker.hours, 24), dayIndex: 0, - days: constructValueSliceFunc(scheduleMaker.days, 31), + days: constructValueSlice(scheduleMaker.days, 31), monthIndex: 0, - months: constructValueSliceFunc(scheduleMaker.months, 12), + months: constructValueSlice(scheduleMaker.months, 12), yearIndex: 0, - years: constructYearSliceFunc(scheduleMaker.years), - weekdays: constructWeekdayMapFunc(scheduleMaker.weekdays), + years: constructYearSlice(scheduleMaker.years), + weekdays: constructWeekdayMap(scheduleMaker.weekdays), till: scheduleMaker.till, timezone: scheduleMaker.timezone, skipOverdue: scheduleMaker.skipOverdue, @@ -291,7 +293,7 @@ func isWeekdayMatch(year, month, day int, weekdays map[time.Weekday]bool) bool { if len(weekdays) == 0 { return true } - var date = timeDate( + var date = time.Date( year, time.Month(month+1), day+1, @@ -311,15 +313,15 @@ func determineScheduleIndex( ) (bool, time.Time, error) { var increment bool var overflow bool - schedule.year, schedule.yearIndex, increment, overflow = findValueMatchFunc( + schedule.year, schedule.yearIndex, increment, overflow = findValueMatch( start.Year(), schedule.years, ) if overflow { - return false, start, fmtErrorf("Invalid schedule configuration: no valid next execution time available") + return false, start, fmt.Errorf("Invalid schedule configuration: no valid next execution time available") } else if increment { return false, - timeDate( + time.Date( schedule.year, time.January, 1, @@ -331,13 +333,13 @@ func determineScheduleIndex( ), nil } - schedule.month, schedule.monthIndex, increment, overflow = findValueMatchFunc( + schedule.month, schedule.monthIndex, increment, overflow = findValueMatch( int(start.Month())-1, schedule.months, ) if overflow { return false, - timeDate( + time.Date( start.Year()+1, time.January, 1, @@ -350,7 +352,7 @@ func determineScheduleIndex( nil } else if increment { return false, - timeDate( + time.Date( schedule.year, time.Month(schedule.month+1), 1, @@ -362,13 +364,13 @@ func determineScheduleIndex( ), nil } - schedule.day, schedule.dayIndex, increment, overflow = findValueMatchFunc( + schedule.day, schedule.dayIndex, increment, overflow = findValueMatch( start.Day()-1, schedule.days, ) if overflow { return false, - timeDate( + time.Date( start.Year(), start.Month()+1, 1, @@ -381,7 +383,7 @@ func determineScheduleIndex( nil } else if increment { return false, - timeDate( + time.Date( schedule.year, time.Month(schedule.month+1), schedule.day+1, @@ -393,14 +395,14 @@ func determineScheduleIndex( ), nil } - if !isWeekdayMatchFunc( + if !isWeekdayMatch( schedule.year, schedule.month, schedule.day, schedule.weekdays, ) { return false, - timeDate( + time.Date( start.Year(), start.Month(), start.Day()+1, @@ -412,13 +414,13 @@ func determineScheduleIndex( ), nil } - schedule.hour, schedule.hourIndex, increment, overflow = findValueMatchFunc( + schedule.hour, schedule.hourIndex, increment, overflow = findValueMatch( start.Hour(), schedule.hours, ) if overflow { return false, - timeDate( + time.Date( start.Year(), start.Month(), start.Day()+1, @@ -431,7 +433,7 @@ func determineScheduleIndex( nil } else if increment { return false, - timeDate( + time.Date( schedule.year, time.Month(schedule.month+1), schedule.day+1, @@ -443,13 +445,13 @@ func determineScheduleIndex( ), nil } - schedule.minute, schedule.minuteIndex, increment, overflow = findValueMatchFunc( + schedule.minute, schedule.minuteIndex, increment, overflow = findValueMatch( start.Minute(), schedule.minutes, ) if overflow { return false, - timeDate( + time.Date( start.Year(), start.Month(), start.Day(), @@ -462,7 +464,7 @@ func determineScheduleIndex( nil } else if increment { return false, - timeDate( + time.Date( schedule.year, time.Month(schedule.month+1), schedule.day+1, @@ -474,13 +476,13 @@ func determineScheduleIndex( ), nil } - schedule.second, schedule.secondIndex, _, overflow = findValueMatchFunc( + schedule.second, schedule.secondIndex, _, overflow = findValueMatch( start.Second(), schedule.seconds, ) if overflow { return false, - timeDate( + time.Date( start.Year(), start.Month(), start.Day(), @@ -501,7 +503,7 @@ func initialiseSchedule( ) error { var calcError error for completed := false; !completed; { - completed, start, calcError = determineScheduleIndexFunc( + completed, start, calcError = determineScheduleIndex( start, schedule, ) @@ -514,15 +516,15 @@ func initialiseSchedule( // Schedule returns a compiled schedule based on all previously configured settings func (scheduleMaker *scheduleMaker) Schedule() (Schedule, error) { - var start = timeNow() + var start = time.Now() if scheduleMaker.from != nil && scheduleMaker.from.After(start) { start = *scheduleMaker.from } - var schedule = constructScheduleTemplateFunc( + var schedule = constructScheduleTemplate( scheduleMaker, ) - var calcError = initialiseScheduleFunc( + var calcError = initialiseSchedule( start, schedule, ) diff --git a/scheduleMaker_test.go b/scheduleMaker_test.go index f6c8aa5..eeb921b 100644 --- a/scheduleMaker_test.go +++ b/scheduleMaker_test.go @@ -2,18 +2,16 @@ package jobrunner import ( "errors" - "math/rand" - "sort" + "fmt" + "math/rand/v2" "testing" "time" "github.com/stretchr/testify/assert" + "github.com/zhongjie-cai/gomocker/v2" ) func TestNewScheduleMaker(t *testing.T) { - // mock - createMock(t) - // SUT var sut = NewScheduleMaker() @@ -32,22 +30,16 @@ func TestNewScheduleMaker(t *testing.T) { assert.Empty(t, result.years) assert.Nil(t, result.from) assert.Nil(t, result.till) - - // verify - verifyAll(t) } func TestGenerateFlagsData_EmptyValues(t *testing.T) { // arrange var dummyData = []bool{ - rand.Intn(100) > 50, - rand.Intn(100) > 50, - rand.Intn(100) > 50, + rand.IntN(100) > 50, + rand.IntN(100) > 50, + rand.IntN(100) > 50, } - var dummyTotal = rand.Intn(5) + 5 - - // mock - createMock(t) + var dummyTotal = rand.IntN(5) + 5 // SUT + act var result = generateFlagsData( @@ -60,17 +52,14 @@ func TestGenerateFlagsData_EmptyValues(t *testing.T) { for _, value := range result { assert.True(t, value) } - - // verify - verifyAll(t) } func TestGenerateFlagsData_ValidValues(t *testing.T) { // arrange var dummyData = []bool{ - rand.Intn(100) > 50, - rand.Intn(100) > 50, - rand.Intn(100) > 50, + rand.IntN(100) > 50, + rand.IntN(100) > 50, + rand.IntN(100) > 50, } var dummyTotal = 5 var dummyValue1 = 0 @@ -78,9 +67,6 @@ func TestGenerateFlagsData_ValidValues(t *testing.T) { var dummyValue3 = 4 var dummyValue4 = 6 - // mock - createMock(t) - // SUT + act var result = generateFlagsData( dummyData, @@ -92,43 +78,30 @@ func TestGenerateFlagsData_ValidValues(t *testing.T) { ) // assert - assert.Equal(t, 5, len(result)) + assert.Len(t, result, 5) assert.True(t, result[0]) assert.True(t, result[1]) assert.True(t, result[2]) assert.False(t, result[3]) assert.True(t, result[4]) - - // verify - verifyAll(t) } func TestScheduleMaker_OnSeconds(t *testing.T) { // arrange - var dummyOldSeconds = []bool{rand.Intn(100) > 50, rand.Intn(100) > 50, rand.Intn(100) > 50} + var dummyOldSeconds = []bool{rand.IntN(100) > 50, rand.IntN(100) > 50, rand.IntN(100) > 50} var dummyScheduleMaker = &scheduleMaker{ seconds: dummyOldSeconds, } - var dummySecond1 = rand.Intn(60) - var dummySecond2 = rand.Intn(60) - var dummySecond3 = rand.Intn(60) - var dummyNewSeconds = []bool{rand.Intn(100) > 50, rand.Intn(100) > 50, rand.Intn(100) > 50} + var dummySecond1 = rand.IntN(60) + var dummySecond2 = rand.IntN(60) + var dummySecond3 = rand.IntN(60) + var dummyNewSeconds = []bool{rand.IntN(100) > 50, rand.IntN(100) > 50, rand.IntN(100) > 50} // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - generateFlagsDataFuncExpected = 1 - generateFlagsDataFunc = func(data []bool, total int, values ...int) []bool { - generateFlagsDataFuncCalled++ - assert.Equal(t, dummyOldSeconds, data) - assert.Equal(t, 60, total) - assert.Equal(t, 3, len(values)) - assert.Equal(t, dummySecond1, values[0]) - assert.Equal(t, dummySecond2, values[1]) - assert.Equal(t, dummySecond3, values[2]) - return dummyNewSeconds - } + m.Mock(generateFlagsData).Expects(dummyOldSeconds, 60, dummySecond1, dummySecond2, dummySecond3).Returns(dummyNewSeconds).Once() // SUT var sut = dummyScheduleMaker @@ -143,37 +116,24 @@ func TestScheduleMaker_OnSeconds(t *testing.T) { // assert assert.Equal(t, dummyScheduleMaker, result) assert.Equal(t, dummyNewSeconds, dummyScheduleMaker.seconds) - - // verify - verifyAll(t) } func TestScheduleMaker_OnMinutes(t *testing.T) { // arrange - var dummyOldMinutes = []bool{rand.Intn(100) > 50, rand.Intn(100) > 50, rand.Intn(100) > 50} + var dummyOldMinutes = []bool{rand.IntN(100) > 50, rand.IntN(100) > 50, rand.IntN(100) > 50} var dummyScheduleMaker = &scheduleMaker{ minutes: dummyOldMinutes, } - var dummyMinute1 = rand.Intn(60) - var dummyMinute2 = rand.Intn(60) - var dummyMinute3 = rand.Intn(60) - var dummyNewMinutes = []bool{rand.Intn(100) > 50, rand.Intn(100) > 50, rand.Intn(100) > 50} + var dummyMinute1 = rand.IntN(60) + var dummyMinute2 = rand.IntN(60) + var dummyMinute3 = rand.IntN(60) + var dummyNewMinutes = []bool{rand.IntN(100) > 50, rand.IntN(100) > 50, rand.IntN(100) > 50} // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - generateFlagsDataFuncExpected = 1 - generateFlagsDataFunc = func(data []bool, total int, values ...int) []bool { - generateFlagsDataFuncCalled++ - assert.Equal(t, dummyOldMinutes, data) - assert.Equal(t, 60, total) - assert.Equal(t, 3, len(values)) - assert.Equal(t, dummyMinute1, values[0]) - assert.Equal(t, dummyMinute2, values[1]) - assert.Equal(t, dummyMinute3, values[2]) - return dummyNewMinutes - } + m.Mock(generateFlagsData).Expects(dummyOldMinutes, 60, dummyMinute1, dummyMinute2, dummyMinute3).Returns(dummyNewMinutes).Once() // SUT var sut = dummyScheduleMaker @@ -188,37 +148,24 @@ func TestScheduleMaker_OnMinutes(t *testing.T) { // assert assert.Equal(t, dummyScheduleMaker, result) assert.Equal(t, dummyNewMinutes, dummyScheduleMaker.minutes) - - // verify - verifyAll(t) } func TestScheduleMaker_AtHours(t *testing.T) { // arrange - var dummyOldHours = []bool{rand.Intn(100) > 50, rand.Intn(100) > 50, rand.Intn(100) > 50} + var dummyOldHours = []bool{rand.IntN(100) > 50, rand.IntN(100) > 50, rand.IntN(100) > 50} var dummyScheduleMaker = &scheduleMaker{ hours: dummyOldHours, } - var dummyHour1 = rand.Intn(24) - var dummyHour2 = rand.Intn(24) - var dummyHour3 = rand.Intn(24) - var dummyNewHours = []bool{rand.Intn(100) > 50, rand.Intn(100) > 50, rand.Intn(100) > 50} + var dummyHour1 = rand.IntN(24) + var dummyHour2 = rand.IntN(24) + var dummyHour3 = rand.IntN(24) + var dummyNewHours = []bool{rand.IntN(100) > 50, rand.IntN(100) > 50, rand.IntN(100) > 50} // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - generateFlagsDataFuncExpected = 1 - generateFlagsDataFunc = func(data []bool, total int, values ...int) []bool { - generateFlagsDataFuncCalled++ - assert.Equal(t, dummyOldHours, data) - assert.Equal(t, 24, total) - assert.Equal(t, 3, len(values)) - assert.Equal(t, dummyHour1, values[0]) - assert.Equal(t, dummyHour2, values[1]) - assert.Equal(t, dummyHour3, values[2]) - return dummyNewHours - } + m.Mock(generateFlagsData).Expects(dummyOldHours, 24, dummyHour1, dummyHour2, dummyHour3).Returns(dummyNewHours).Once() // SUT var sut = dummyScheduleMaker @@ -233,37 +180,24 @@ func TestScheduleMaker_AtHours(t *testing.T) { // assert assert.Equal(t, dummyScheduleMaker, result) assert.Equal(t, dummyNewHours, dummyScheduleMaker.hours) - - // verify - verifyAll(t) } func TestScheduleMaker_OnWeekdays(t *testing.T) { // arrange - var dummyOldWeekdays = []bool{rand.Intn(100) > 50, rand.Intn(100) > 50, rand.Intn(100) > 50} + var dummyOldWeekdays = []bool{rand.IntN(100) > 50, rand.IntN(100) > 50, rand.IntN(100) > 50} var dummyScheduleMaker = &scheduleMaker{ weekdays: dummyOldWeekdays, } - var dummyWeekday1 = time.Weekday(rand.Intn(7)) - var dummyWeekday2 = time.Weekday(rand.Intn(7)) - var dummyWeekday3 = time.Weekday(rand.Intn(7)) - var dummyNewWeekdays = []bool{rand.Intn(100) > 50, rand.Intn(100) > 50, rand.Intn(100) > 50} + var dummyWeekday1 = time.Weekday(rand.IntN(7)) + var dummyWeekday2 = time.Weekday(rand.IntN(7)) + var dummyWeekday3 = time.Weekday(rand.IntN(7)) + var dummyNewWeekdays = []bool{rand.IntN(100) > 50, rand.IntN(100) > 50, rand.IntN(100) > 50} // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - generateFlagsDataFuncExpected = 1 - generateFlagsDataFunc = func(data []bool, total int, values ...int) []bool { - generateFlagsDataFuncCalled++ - assert.Equal(t, dummyOldWeekdays, data) - assert.Equal(t, 7, total) - assert.Equal(t, 3, len(values)) - assert.Equal(t, int(dummyWeekday1), values[0]) - assert.Equal(t, int(dummyWeekday2), values[1]) - assert.Equal(t, int(dummyWeekday3), values[2]) - return dummyNewWeekdays - } + m.Mock(generateFlagsData).Expects(dummyOldWeekdays, 7, int(dummyWeekday1), int(dummyWeekday2), int(dummyWeekday3)).Returns(dummyNewWeekdays).Once() // SUT var sut = dummyScheduleMaker @@ -278,37 +212,24 @@ func TestScheduleMaker_OnWeekdays(t *testing.T) { // assert assert.Equal(t, dummyScheduleMaker, result) assert.Equal(t, dummyNewWeekdays, dummyScheduleMaker.weekdays) - - // verify - verifyAll(t) } func TestScheduleMaker_OnDays(t *testing.T) { // arrange - var dummyOldDays = []bool{rand.Intn(100) > 50, rand.Intn(100) > 50, rand.Intn(100) > 50} + var dummyOldDays = []bool{rand.IntN(100) > 50, rand.IntN(100) > 50, rand.IntN(100) > 50} var dummyScheduleMaker = &scheduleMaker{ days: dummyOldDays, } - var dummyDay1 = 1 + rand.Intn(31) - var dummyDay2 = 1 + rand.Intn(31) - var dummyDay3 = 1 + rand.Intn(31) - var dummyNewDays = []bool{rand.Intn(100) > 50, rand.Intn(100) > 50, rand.Intn(100) > 50} + var dummyDay1 = 1 + rand.IntN(31) + var dummyDay2 = 1 + rand.IntN(31) + var dummyDay3 = 1 + rand.IntN(31) + var dummyNewDays = []bool{rand.IntN(100) > 50, rand.IntN(100) > 50, rand.IntN(100) > 50} // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - generateFlagsDataFuncExpected = 1 - generateFlagsDataFunc = func(data []bool, total int, values ...int) []bool { - generateFlagsDataFuncCalled++ - assert.Equal(t, dummyOldDays, data) - assert.Equal(t, 31, total) - assert.Equal(t, 3, len(values)) - assert.Equal(t, dummyDay1-1, values[0]) - assert.Equal(t, dummyDay2-1, values[1]) - assert.Equal(t, dummyDay3-1, values[2]) - return dummyNewDays - } + m.Mock(generateFlagsData).Expects(dummyOldDays, 31, dummyDay1-1, dummyDay2-1, dummyDay3-1).Returns(dummyNewDays).Once() // SUT var sut = dummyScheduleMaker @@ -323,37 +244,24 @@ func TestScheduleMaker_OnDays(t *testing.T) { // assert assert.Equal(t, dummyScheduleMaker, result) assert.Equal(t, dummyNewDays, dummyScheduleMaker.days) - - // verify - verifyAll(t) } func TestScheduleMaker_InMonths(t *testing.T) { // arrange - var dummyOldMonths = []bool{rand.Intn(100) > 50, rand.Intn(100) > 50, rand.Intn(100) > 50} + var dummyOldMonths = []bool{rand.IntN(100) > 50, rand.IntN(100) > 50, rand.IntN(100) > 50} var dummyScheduleMaker = &scheduleMaker{ months: dummyOldMonths, } - var dummyMonth1 = time.Month(rand.Intn(12)) - var dummyMonth2 = time.Month(rand.Intn(12)) - var dummyMonth3 = time.Month(rand.Intn(12)) - var dummyNewMonths = []bool{rand.Intn(100) > 50, rand.Intn(100) > 50, rand.Intn(100) > 50} + var dummyMonth1 = time.Month(rand.IntN(12)) + var dummyMonth2 = time.Month(rand.IntN(12)) + var dummyMonth3 = time.Month(rand.IntN(12)) + var dummyNewMonths = []bool{rand.IntN(100) > 50, rand.IntN(100) > 50, rand.IntN(100) > 50} // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - generateFlagsDataFuncExpected = 1 - generateFlagsDataFunc = func(data []bool, total int, values ...int) []bool { - generateFlagsDataFuncCalled++ - assert.Equal(t, dummyOldMonths, data) - assert.Equal(t, 12, total) - assert.Equal(t, 3, len(values)) - assert.Equal(t, int(dummyMonth1)-1, values[0]) - assert.Equal(t, int(dummyMonth2)-1, values[1]) - assert.Equal(t, int(dummyMonth3)-1, values[2]) - return dummyNewMonths - } + m.Mock(generateFlagsData).Expects(dummyOldMonths, 12, int(dummyMonth1)-1, int(dummyMonth2)-1, int(dummyMonth3)-1).Returns(dummyNewMonths).Once() // SUT var sut = dummyScheduleMaker @@ -368,25 +276,19 @@ func TestScheduleMaker_InMonths(t *testing.T) { // assert assert.Equal(t, dummyScheduleMaker, result) assert.Equal(t, dummyNewMonths, dummyScheduleMaker.months) - - // verify - verifyAll(t) } func TestScheduleMaker_InYears_EmptyList(t *testing.T) { // arrange var dummyOldYears = map[int]bool{ - rand.Intn(100): rand.Intn(100) > 50, - rand.Intn(100): rand.Intn(100) > 50, - rand.Intn(100): rand.Intn(100) > 50, + rand.IntN(100): rand.IntN(100) > 50, + rand.IntN(100): rand.IntN(100) > 50, + rand.IntN(100): rand.IntN(100) > 50, } var dummyScheduleMaker = &scheduleMaker{ years: dummyOldYears, } - // mock - createMock(t) - // SUT var sut = dummyScheduleMaker @@ -396,30 +298,24 @@ func TestScheduleMaker_InYears_EmptyList(t *testing.T) { // assert assert.Equal(t, dummyScheduleMaker, result) assert.Equal(t, dummyOldYears, dummyScheduleMaker.years) - - // verify - verifyAll(t) } func TestScheduleMaker_InYears_ValidList(t *testing.T) { // arrange - var dummyYear1 = rand.Intn(100) - var dummyYear2 = rand.Intn(100) - var dummyYear3 = rand.Intn(100) + var dummyYear1 = rand.IntN(100) + var dummyYear2 = rand.IntN(100) + var dummyYear3 = rand.IntN(100) var dummyOldYears = map[int]bool{ - dummyYear1: rand.Intn(100) > 50, - dummyYear2: rand.Intn(100) > 50, - dummyYear3: rand.Intn(100) > 50, + dummyYear1: rand.IntN(100) > 50, + dummyYear2: rand.IntN(100) > 50, + dummyYear3: rand.IntN(100) > 50, } var dummyScheduleMaker = &scheduleMaker{ years: dummyOldYears, } - var dummyYear4 = 100 + rand.Intn(100) - var dummyYear5 = 100 + rand.Intn(100) - var dummyYear6 = 100 + rand.Intn(100) - - // mock - createMock(t) + var dummyYear4 = 100 + rand.IntN(100) + var dummyYear5 = 100 + rand.IntN(100) + var dummyYear6 = 100 + rand.IntN(100) // SUT var sut = dummyScheduleMaker @@ -439,9 +335,6 @@ func TestScheduleMaker_InYears_ValidList(t *testing.T) { assert.True(t, dummyScheduleMaker.years[dummyYear4]) assert.True(t, dummyScheduleMaker.years[dummyYear5]) assert.True(t, dummyScheduleMaker.years[dummyYear6]) - - // verify - verifyAll(t) } func TestScheduleMaker_From(t *testing.T) { @@ -449,9 +342,6 @@ func TestScheduleMaker_From(t *testing.T) { var dummyScheduleMaker = &scheduleMaker{} var dummyStart = time.Now() - // mock - createMock(t) - // SUT var sut = dummyScheduleMaker @@ -463,9 +353,6 @@ func TestScheduleMaker_From(t *testing.T) { // assert assert.Equal(t, dummyScheduleMaker, result) assert.Equal(t, dummyStart, *dummyScheduleMaker.from) - - // verify - verifyAll(t) } func TestScheduleMaker_Till(t *testing.T) { @@ -473,9 +360,6 @@ func TestScheduleMaker_Till(t *testing.T) { var dummyScheduleMaker = &scheduleMaker{} var dummyEnd = time.Now() - // mock - createMock(t) - // SUT var sut = dummyScheduleMaker @@ -487,18 +371,12 @@ func TestScheduleMaker_Till(t *testing.T) { // assert assert.Equal(t, dummyScheduleMaker, result) assert.Equal(t, dummyEnd, *dummyScheduleMaker.till) - - // verify - verifyAll(t) } func TestScheduleMaker_SkipOverdue(t *testing.T) { // arrange var dummyScheduleMaker = &scheduleMaker{} - // mock - createMock(t) - // SUT var sut = dummyScheduleMaker @@ -508,9 +386,6 @@ func TestScheduleMaker_SkipOverdue(t *testing.T) { // assert assert.Equal(t, dummyScheduleMaker, result) assert.True(t, dummyScheduleMaker.skipOverdue) - - // verify - verifyAll(t) } func TestScheduleMaker_Timezone_NilTimezone(t *testing.T) { @@ -518,9 +393,6 @@ func TestScheduleMaker_Timezone_NilTimezone(t *testing.T) { var dummyScheduleMaker = &scheduleMaker{} var dummyTimezone *time.Location - // mock - createMock(t) - // SUT var sut = dummyScheduleMaker @@ -532,9 +404,6 @@ func TestScheduleMaker_Timezone_NilTimezone(t *testing.T) { // assert assert.Equal(t, dummyScheduleMaker, result) assert.Equal(t, time.Local, dummyScheduleMaker.timezone) - - // verify - verifyAll(t) } func TestScheduleMaker_Timezone_ValidTimezone(t *testing.T) { @@ -542,9 +411,6 @@ func TestScheduleMaker_Timezone_ValidTimezone(t *testing.T) { var dummyScheduleMaker = &scheduleMaker{} var dummyTimezone, _ = time.LoadLocation("Asia/Shanghai") - // mock - createMock(t) - // SUT var sut = dummyScheduleMaker @@ -556,18 +422,12 @@ func TestScheduleMaker_Timezone_ValidTimezone(t *testing.T) { // assert assert.Equal(t, dummyScheduleMaker, result) assert.Equal(t, dummyTimezone, dummyScheduleMaker.timezone) - - // verify - verifyAll(t) } func TestConstructValueSlice_EmptyValues(t *testing.T) { // arrange var dummyValues = []bool{} - var dummyTotal = rand.Intn(10) + 5 - - // mock - createMock(t) + var dummyTotal = rand.IntN(10) + 5 // SUT + act var result = constructValueSlice( @@ -580,9 +440,6 @@ func TestConstructValueSlice_EmptyValues(t *testing.T) { for i := 0; i < len(result); i++ { assert.Equal(t, i, result[i]) } - - // verify - verifyAll(t) } func TestConstructValueSlice_ValidValues(t *testing.T) { @@ -597,9 +454,6 @@ func TestConstructValueSlice_ValidValues(t *testing.T) { } var dummyTotal = len(dummyValues) - // mock - createMock(t) - // SUT + act var result = constructValueSlice( dummyValues, @@ -607,29 +461,23 @@ func TestConstructValueSlice_ValidValues(t *testing.T) { ) // assert - assert.Equal(t, 3, len(result)) + assert.Len(t, result, 3) assert.Equal(t, 0, result[0]) assert.Equal(t, 2, result[1]) assert.Equal(t, 4, result[2]) - - // verify - verifyAll(t) } func TestConstructWeekdayMap_EmptyWeekdays(t *testing.T) { // arrange var dummyWeekdays = []bool{} - // mock - createMock(t) - // SUT + act var result = constructWeekdayMap( dummyWeekdays, ) // assert - assert.Equal(t, 7, len(result)) + assert.Len(t, result, 7) assert.True(t, result[time.Monday]) assert.True(t, result[time.Tuesday]) assert.True(t, result[time.Wednesday]) @@ -637,9 +485,6 @@ func TestConstructWeekdayMap_EmptyWeekdays(t *testing.T) { assert.True(t, result[time.Friday]) assert.True(t, result[time.Saturday]) assert.True(t, result[time.Sunday]) - - // verify - verifyAll(t) } func TestConstructWeekdayMap_ValidWeekdays(t *testing.T) { @@ -654,38 +499,28 @@ func TestConstructWeekdayMap_ValidWeekdays(t *testing.T) { false, } - // mock - createMock(t) - // SUT + act var result = constructWeekdayMap( dummyWeekdays, ) // assert - assert.Equal(t, 3, len(result)) + assert.Len(t, result, 3) assert.True(t, result[time.Monday]) assert.True(t, result[time.Wednesday]) assert.True(t, result[time.Friday]) - - // verify - verifyAll(t) } func TestConstructYearSlice_EmptyYears(t *testing.T) { // arrange var dummyYears = map[int]bool{} - var dummyTime = time.Now() + var dummyTime = time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC) // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - timeNowExpected = 1 - timeNow = func() time.Time { - timeNowCalled++ - return dummyTime - } + m.Mock(time.Now).Expects().Returns(dummyTime).Once() // SUT + act var result = constructYearSlice( @@ -693,13 +528,10 @@ func TestConstructYearSlice_EmptyYears(t *testing.T) { ) // assert - assert.Equal(t, 100, len(result)) + assert.Len(t, result, 100) for year := 0; year < 100; year++ { assert.Equal(t, dummyTime.Year()+year, result[year]) } - - // verify - verifyAll(t) } func TestConstructYearSlice_ValidYears(t *testing.T) { @@ -712,46 +544,33 @@ func TestConstructYearSlice_ValidYears(t *testing.T) { 2024: true, } - // mock - createMock(t) - - // expect - sortIntsExpected = 1 - sortInts = func(a []int) { - sortIntsCalled++ - sort.Ints(a) - } - // SUT + act var result = constructYearSlice( dummyYears, ) // assert - assert.Equal(t, 3, len(result)) + assert.Len(t, result, 3) assert.Equal(t, 2020, result[0]) assert.Equal(t, 2022, result[1]) assert.Equal(t, 2024, result[2]) - - // verify - verifyAll(t) } func TestConstructScheduleTemplate(t *testing.T) { // arrange - var dummyMakerSeconds = []bool{rand.Intn(100) > 50, rand.Intn(100) > 50, rand.Intn(100) > 50} - var dummyMakerMinutes = []bool{rand.Intn(100) > 50, rand.Intn(100) > 50, rand.Intn(100) > 50} - var dummyMakerHours = []bool{rand.Intn(100) > 50, rand.Intn(100) > 50, rand.Intn(100) > 50} - var dummyMakerWeekdays = []bool{rand.Intn(100) > 50, rand.Intn(100) > 50, rand.Intn(100) > 50} - var dummyMakerDays = []bool{rand.Intn(100) > 50, rand.Intn(100) > 50, rand.Intn(100) > 50} - var dummyMakerMonths = []bool{rand.Intn(100) > 50, rand.Intn(100) > 50, rand.Intn(100) > 50} + var dummyMakerSeconds = []bool{rand.IntN(100) > 50, rand.IntN(100) > 50, rand.IntN(100) > 50} + var dummyMakerMinutes = []bool{rand.IntN(100) > 50, rand.IntN(100) > 50, rand.IntN(100) > 50} + var dummyMakerHours = []bool{rand.IntN(100) > 50, rand.IntN(100) > 50, rand.IntN(100) > 50} + var dummyMakerWeekdays = []bool{rand.IntN(100) > 50, rand.IntN(100) > 50, rand.IntN(100) > 50} + var dummyMakerDays = []bool{rand.IntN(100) > 50, rand.IntN(100) > 50, rand.IntN(100) > 50} + var dummyMakerMonths = []bool{rand.IntN(100) > 50, rand.IntN(100) > 50, rand.IntN(100) > 50} var dummyMakerYears = map[int]bool{ - rand.Intn(100): rand.Intn(100) > 50, - rand.Intn(100): rand.Intn(100) > 50, - rand.Intn(100): rand.Intn(100) > 50, + rand.IntN(100): rand.IntN(100) > 50, + rand.IntN(100): rand.IntN(100) > 50, + rand.IntN(100): rand.IntN(100) > 50, } var dummyMakerTill = time.Now() - var dummySkipOverdue = rand.Intn(100) > 50 + var dummySkipOverdue = rand.IntN(100) > 50 var dummyScheduleMaker = &scheduleMaker{ seconds: dummyMakerSeconds, minutes: dummyMakerMinutes, @@ -763,60 +582,29 @@ func TestConstructScheduleTemplate(t *testing.T) { till: &dummyMakerTill, skipOverdue: dummySkipOverdue, } - var dummyScheduleSeconds = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyScheduleMinutes = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyScheduleHours = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyScheduleDays = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyScheduleMonths = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyScheduleYears = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} + var dummyScheduleSeconds = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyScheduleMinutes = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyScheduleHours = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyScheduleDays = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyScheduleMonths = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyScheduleYears = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} var dummyScheduleWeekdays = map[time.Weekday]bool{ - time.Weekday(rand.Intn(7)): rand.Intn(100) > 50, - time.Weekday(rand.Intn(7)): rand.Intn(100) > 50, - time.Weekday(rand.Intn(7)): rand.Intn(100) > 50, + time.Weekday(rand.IntN(7)): rand.IntN(100) > 50, + time.Weekday(rand.IntN(7)): rand.IntN(100) > 50, + time.Weekday(rand.IntN(7)): rand.IntN(100) > 50, } // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - constructValueSliceFuncExpected = 5 - constructValueSliceFunc = func(values []bool, total int) []int { - constructValueSliceFuncCalled++ - if constructValueSliceFuncCalled == 1 { - assert.Equal(t, dummyMakerSeconds, values) - assert.Equal(t, 60, total) - return dummyScheduleSeconds - } else if constructValueSliceFuncCalled == 2 { - assert.Equal(t, dummyMakerMinutes, values) - assert.Equal(t, 60, total) - return dummyScheduleMinutes - } else if constructValueSliceFuncCalled == 3 { - assert.Equal(t, dummyMakerHours, values) - assert.Equal(t, 24, total) - return dummyScheduleHours - } else if constructValueSliceFuncCalled == 4 { - assert.Equal(t, dummyMakerDays, values) - assert.Equal(t, 31, total) - return dummyScheduleDays - } else if constructValueSliceFuncCalled == 5 { - assert.Equal(t, dummyMakerMonths, values) - assert.Equal(t, 12, total) - return dummyScheduleMonths - } - return nil - } - constructYearSliceFuncExpected = 1 - constructYearSliceFunc = func(years map[int]bool) []int { - constructYearSliceFuncCalled++ - assert.Equal(t, dummyMakerYears, years) - return dummyScheduleYears - } - constructWeekdayMapFuncExpected = 1 - constructWeekdayMapFunc = func(weekdays []bool) map[time.Weekday]bool { - constructWeekdayMapFuncCalled++ - assert.Equal(t, dummyMakerWeekdays, weekdays) - return dummyScheduleWeekdays - } + m.Mock(constructValueSlice).Expects(dummyMakerSeconds, 60).Returns(dummyScheduleSeconds).Once() + m.Mock(constructValueSlice).Expects(dummyMakerMinutes, 60).Returns(dummyScheduleMinutes).Once() + m.Mock(constructValueSlice).Expects(dummyMakerHours, 24).Returns(dummyScheduleHours).Once() + m.Mock(constructValueSlice).Expects(dummyMakerDays, 31).Returns(dummyScheduleDays).Once() + m.Mock(constructValueSlice).Expects(dummyMakerMonths, 12).Returns(dummyScheduleMonths).Once() + m.Mock(constructYearSlice).Expects(dummyMakerYears).Returns(dummyScheduleYears).Once() + m.Mock(constructWeekdayMap).Expects(dummyMakerWeekdays).Returns(dummyScheduleWeekdays).Once() // SUT + act var result = constructScheduleTemplate( @@ -845,19 +633,13 @@ func TestConstructScheduleTemplate(t *testing.T) { assert.Equal(t, dummyScheduleWeekdays, result.weekdays) assert.Equal(t, &dummyMakerTill, result.till) assert.Equal(t, dummySkipOverdue, result.skipOverdue) - - // verify - verifyAll(t) } func TestFindValueMatch_EmptyValues(t *testing.T) { // arrange - var dummyValue = rand.Intn(10) + var dummyValue = rand.IntN(10) var dummyValues = []int{} - // mock - createMock(t) - // SUT + act var value, index, reset, overflow = findValueMatch( dummyValue, @@ -869,23 +651,17 @@ func TestFindValueMatch_EmptyValues(t *testing.T) { assert.Zero(t, index) assert.False(t, reset) assert.False(t, overflow) - - // verify - verifyAll(t) } func TestFindValueMatch_ValidValues_NoMatch(t *testing.T) { // arrange - var dummyValue = 30 + rand.Intn(10) + var dummyValue = 30 + rand.IntN(10) var dummyValues = []int{ - rand.Intn(10), - rand.Intn(10) + 10, - rand.Intn(10) + 20, + rand.IntN(10), + rand.IntN(10) + 10, + rand.IntN(10) + 20, } - // mock - createMock(t) - // SUT + act var value, index, reset, overflow = findValueMatch( dummyValue, @@ -897,26 +673,20 @@ func TestFindValueMatch_ValidValues_NoMatch(t *testing.T) { assert.Zero(t, index) assert.True(t, reset) assert.True(t, overflow) - - // verify - verifyAll(t) } func TestFindValueMatch_ValidValues_ExactMatch(t *testing.T) { // arrange - var dummyValue = 30 + rand.Intn(10) + var dummyValue = 30 + rand.IntN(10) var dummyValues = []int{ - rand.Intn(10), - rand.Intn(10) + 10, - rand.Intn(10) + 20, + rand.IntN(10), + rand.IntN(10) + 10, + rand.IntN(10) + 20, dummyValue, - rand.Intn(10) + 40, - rand.Intn(10) + 50, + rand.IntN(10) + 40, + rand.IntN(10) + 50, } - // mock - createMock(t) - // SUT + act var value, index, reset, overflow = findValueMatch( dummyValue, @@ -928,25 +698,19 @@ func TestFindValueMatch_ValidValues_ExactMatch(t *testing.T) { assert.Equal(t, 3, index) assert.False(t, reset) assert.False(t, overflow) - - // verify - verifyAll(t) } func TestFindValueMatch_ValidValues_SimMatch(t *testing.T) { // arrange - var dummyValue = 30 + rand.Intn(10) + var dummyValue = 30 + rand.IntN(10) var dummyValues = []int{ - rand.Intn(10), - rand.Intn(10) + 10, - rand.Intn(10) + 20, - rand.Intn(10) + 40, - rand.Intn(10) + 50, + rand.IntN(10), + rand.IntN(10) + 10, + rand.IntN(10) + 20, + rand.IntN(10) + 40, + rand.IntN(10) + 50, } - // mock - createMock(t) - // SUT + act var value, index, reset, overflow = findValueMatch( dummyValue, @@ -958,21 +722,15 @@ func TestFindValueMatch_ValidValues_SimMatch(t *testing.T) { assert.Equal(t, 3, index) assert.True(t, reset) assert.False(t, overflow) - - // verify - verifyAll(t) } func TestIsWeekdayMatch_EmptyWeekdays(t *testing.T) { // arrange - var dummyYear = rand.Intn(100) - var dummyMonth = rand.Intn(12) - var dummyDay = rand.Intn(31) + var dummyYear = rand.IntN(100) + var dummyMonth = rand.IntN(12) + var dummyDay = rand.IntN(31) var dummyWeekdays = map[time.Weekday]bool{} - // mock - createMock(t) - // SUT + act var result = isWeekdayMatch( dummyYear, @@ -983,16 +741,13 @@ func TestIsWeekdayMatch_EmptyWeekdays(t *testing.T) { // assert assert.True(t, result) - - // verify - verifyAll(t) } func TestIsWeekdayMatch_ValidWeekdays_NotFound(t *testing.T) { // arrange - var dummyYear = rand.Intn(100) - var dummyMonth = rand.Intn(12) - var dummyDay = rand.Intn(31) + var dummyYear = rand.IntN(100) + var dummyMonth = rand.IntN(12) + var dummyDay = rand.IntN(31) var dummyDate = time.Now() var dummyWeekday = dummyDate.Weekday() var dummyWeekdays = map[time.Weekday]bool{ @@ -1001,22 +756,11 @@ func TestIsWeekdayMatch_ValidWeekdays_NotFound(t *testing.T) { } // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - timeDateExpected = 1 - timeDate = func(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) time.Time { - timeDateCalled++ - assert.Equal(t, dummyYear, year) - assert.Equal(t, time.Month(dummyMonth+1), month) - assert.Equal(t, dummyDay+1, day) - assert.Zero(t, hour) - assert.Zero(t, min) - assert.Zero(t, sec) - assert.Zero(t, nsec) - assert.Equal(t, time.Local, loc) - return dummyDate - } + m.Mock(time.Date).Expects(dummyYear, time.Month(dummyMonth+1), dummyDay+1, + 0, 0, 0, 0, time.Local).Returns(dummyDate).Once() // SUT + act var result = isWeekdayMatch( @@ -1028,16 +772,13 @@ func TestIsWeekdayMatch_ValidWeekdays_NotFound(t *testing.T) { // assert assert.False(t, result) - - // verify - verifyAll(t) } func TestIsWeekdayMatch_ValidWeekdays_NotValid(t *testing.T) { // arrange - var dummyYear = rand.Intn(100) - var dummyMonth = rand.Intn(12) - var dummyDay = rand.Intn(31) + var dummyYear = rand.IntN(100) + var dummyMonth = rand.IntN(12) + var dummyDay = rand.IntN(31) var dummyDate = time.Now() var dummyWeekday = dummyDate.Weekday() var dummyWeekdays = map[time.Weekday]bool{ @@ -1047,22 +788,11 @@ func TestIsWeekdayMatch_ValidWeekdays_NotValid(t *testing.T) { } // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - timeDateExpected = 1 - timeDate = func(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) time.Time { - timeDateCalled++ - assert.Equal(t, dummyYear, year) - assert.Equal(t, time.Month(dummyMonth+1), month) - assert.Equal(t, dummyDay+1, day) - assert.Zero(t, hour) - assert.Zero(t, min) - assert.Zero(t, sec) - assert.Zero(t, nsec) - assert.Equal(t, time.Local, loc) - return dummyDate - } + m.Mock(time.Date).Expects(dummyYear, time.Month(dummyMonth+1), dummyDay+1, + 0, 0, 0, 0, time.Local).Returns(dummyDate).Once() // SUT + act var result = isWeekdayMatch( @@ -1074,16 +804,13 @@ func TestIsWeekdayMatch_ValidWeekdays_NotValid(t *testing.T) { // assert assert.False(t, result) - - // verify - verifyAll(t) } func TestIsWeekdayMatch_ValidWeekdays_FoundValid(t *testing.T) { // arrange - var dummyYear = rand.Intn(100) - var dummyMonth = rand.Intn(12) - var dummyDay = rand.Intn(31) + var dummyYear = rand.IntN(100) + var dummyMonth = rand.IntN(12) + var dummyDay = rand.IntN(31) var dummyDate = time.Now() var dummyWeekday = dummyDate.Weekday() var dummyWeekdays = map[time.Weekday]bool{ @@ -1093,22 +820,11 @@ func TestIsWeekdayMatch_ValidWeekdays_FoundValid(t *testing.T) { } // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - timeDateExpected = 1 - timeDate = func(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) time.Time { - timeDateCalled++ - assert.Equal(t, dummyYear, year) - assert.Equal(t, time.Month(dummyMonth+1), month) - assert.Equal(t, dummyDay+1, day) - assert.Zero(t, hour) - assert.Zero(t, min) - assert.Zero(t, sec) - assert.Zero(t, nsec) - assert.Equal(t, time.Local, loc) - return dummyDate - } + m.Mock(time.Date).Expects(dummyYear, time.Month(dummyMonth+1), dummyDay+1, + 0, 0, 0, 0, time.Local).Returns(dummyDate).Once() // SUT + act var result = isWeekdayMatch( @@ -1120,20 +836,17 @@ func TestIsWeekdayMatch_ValidWeekdays_FoundValid(t *testing.T) { // assert assert.True(t, result) - - // verify - verifyAll(t) } func TestDetermineScheduleIndex_YearOverflow(t *testing.T) { // arrange var dummyStart = time.Now() - var dummySeconds = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyMinutes = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyHours = []int{rand.Intn(24), rand.Intn(24), rand.Intn(24)} - var dummyDays = []int{rand.Intn(31), rand.Intn(31), rand.Intn(31)} - var dummyMonths = []int{rand.Intn(12), rand.Intn(12), rand.Intn(12)} - var dummyYears = []int{rand.Intn(100), rand.Intn(100), rand.Intn(100)} + var dummySeconds = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyMinutes = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyHours = []int{rand.IntN(24), rand.IntN(24), rand.IntN(24)} + var dummyDays = []int{rand.IntN(31), rand.IntN(31), rand.IntN(31)} + var dummyMonths = []int{rand.IntN(12), rand.IntN(12), rand.IntN(12)} + var dummyYears = []int{rand.IntN(100), rand.IntN(100), rand.IntN(100)} var dummySchedule = &schedule{ seconds: dummySeconds, minutes: dummyMinutes, @@ -1142,29 +855,17 @@ func TestDetermineScheduleIndex_YearOverflow(t *testing.T) { months: dummyMonths, years: dummyYears, } - var dummyYear = rand.Intn(100) - var dummyYearIndex = rand.Intn(100) + var dummyYear = rand.IntN(100) + var dummyYearIndex = rand.IntN(100) var dummyFormat = "Invalid schedule configuration: no valid next execution time available" var dummyError = errors.New("some error") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - findValueMatchFuncExpected = 1 - findValueMatchFunc = func(value int, values []int) (int, int, bool, bool) { - findValueMatchFuncCalled++ - assert.Equal(t, dummyStart.Year(), value) - assert.Equal(t, dummyYears, values) - return dummyYear, dummyYearIndex, false, true - } - fmtErrorfExpected = 1 - fmtErrorf = func(format string, a ...interface{}) error { - fmtErrorfCalled++ - assert.Equal(t, dummyFormat, format) - assert.Empty(t, a) - return dummyError - } + m.Mock(findValueMatch).Expects(dummyStart.Year(), dummyYears).Returns(dummyYear, dummyYearIndex, false, true).Once() + m.Mock(fmt.Errorf).Expects(dummyFormat).Returns(dummyError).Once() // SUT + act var completed, start, err = determineScheduleIndex( @@ -1176,20 +877,17 @@ func TestDetermineScheduleIndex_YearOverflow(t *testing.T) { assert.False(t, completed) assert.Equal(t, dummyStart, start) assert.Equal(t, dummyError, err) - - // verify - verifyAll(t) } func TestDetermineScheduleIndex_YearIncrement(t *testing.T) { // arrange var dummyStart = time.Now() - var dummySeconds = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyMinutes = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyHours = []int{rand.Intn(24), rand.Intn(24), rand.Intn(24)} - var dummyDays = []int{rand.Intn(31), rand.Intn(31), rand.Intn(31)} - var dummyMonths = []int{rand.Intn(12), rand.Intn(12), rand.Intn(12)} - var dummyYears = []int{rand.Intn(100), rand.Intn(100), rand.Intn(100)} + var dummySeconds = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyMinutes = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyHours = []int{rand.IntN(24), rand.IntN(24), rand.IntN(24)} + var dummyDays = []int{rand.IntN(31), rand.IntN(31), rand.IntN(31)} + var dummyMonths = []int{rand.IntN(12), rand.IntN(12), rand.IntN(12)} + var dummyYears = []int{rand.IntN(100), rand.IntN(100), rand.IntN(100)} var dummyLocation, _ = time.LoadLocation("Asia/Shanghai") var dummySchedule = &schedule{ seconds: dummySeconds, @@ -1200,34 +898,17 @@ func TestDetermineScheduleIndex_YearIncrement(t *testing.T) { years: dummyYears, timezone: dummyLocation, } - var dummyYear = rand.Intn(100) - var dummyYearIndex = rand.Intn(100) + var dummyYear = rand.IntN(100) + var dummyYearIndex = rand.IntN(100) var dummyTime = time.Now().Add(10 * time.Second) // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - findValueMatchFuncExpected = 1 - findValueMatchFunc = func(value int, values []int) (int, int, bool, bool) { - findValueMatchFuncCalled++ - assert.Equal(t, dummyStart.Year(), value) - assert.Equal(t, dummyYears, values) - return dummyYear, dummyYearIndex, true, false - } - timeDateExpected = 1 - timeDate = func(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) time.Time { - timeDateCalled++ - assert.Equal(t, dummyYear, year) - assert.Equal(t, time.January, month) - assert.Equal(t, 1, day) - assert.Zero(t, hour) - assert.Zero(t, min) - assert.Zero(t, sec) - assert.Zero(t, nsec) - assert.Equal(t, dummyLocation, loc) - return dummyTime - } + m.Mock(findValueMatch).Expects(dummyStart.Year(), dummyYears).Returns(dummyYear, dummyYearIndex, true, false).Once() + m.Mock(time.Date).Expects(dummyYear, time.January, 1, + 0, 0, 0, 0, dummyLocation).Returns(dummyTime).Once() // SUT + act var completed, start, err = determineScheduleIndex( @@ -1239,20 +920,17 @@ func TestDetermineScheduleIndex_YearIncrement(t *testing.T) { assert.False(t, completed) assert.Equal(t, dummyTime, start) assert.NoError(t, err) - - // verify - verifyAll(t) } func TestDetermineScheduleIndex_MonthOverflow(t *testing.T) { // arrange var dummyStart = time.Now() - var dummySeconds = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyMinutes = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyHours = []int{rand.Intn(24), rand.Intn(24), rand.Intn(24)} - var dummyDays = []int{rand.Intn(31), rand.Intn(31), rand.Intn(31)} - var dummyMonths = []int{rand.Intn(12), rand.Intn(12), rand.Intn(12)} - var dummyYears = []int{rand.Intn(100), rand.Intn(100), rand.Intn(100)} + var dummySeconds = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyMinutes = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyHours = []int{rand.IntN(24), rand.IntN(24), rand.IntN(24)} + var dummyDays = []int{rand.IntN(31), rand.IntN(31), rand.IntN(31)} + var dummyMonths = []int{rand.IntN(12), rand.IntN(12), rand.IntN(12)} + var dummyYears = []int{rand.IntN(100), rand.IntN(100), rand.IntN(100)} var dummyLocation, _ = time.LoadLocation("Asia/Shanghai") var dummySchedule = &schedule{ seconds: dummySeconds, @@ -1263,41 +941,20 @@ func TestDetermineScheduleIndex_MonthOverflow(t *testing.T) { years: dummyYears, timezone: dummyLocation, } - var dummyYear = rand.Intn(100) - var dummyYearIndex = rand.Intn(100) - var dummyMonth = rand.Intn(12) - var dummyMonthIndex = rand.Intn(12) + var dummyYear = rand.IntN(100) + var dummyYearIndex = rand.IntN(100) + var dummyMonth = rand.IntN(12) + var dummyMonthIndex = rand.IntN(12) var dummyTime = time.Now().Add(10 * time.Second) // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - findValueMatchFuncExpected = 2 - findValueMatchFunc = func(value int, values []int) (int, int, bool, bool) { - findValueMatchFuncCalled++ - if findValueMatchFuncCalled == 1 { - assert.Equal(t, dummyStart.Year(), value) - assert.Equal(t, dummyYears, values) - return dummyYear, dummyYearIndex, false, false - } - assert.Equal(t, int(dummyStart.Month())-1, value) - assert.Equal(t, dummyMonths, values) - return dummyMonth, dummyMonthIndex, false, true - } - timeDateExpected = 1 - timeDate = func(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) time.Time { - timeDateCalled++ - assert.Equal(t, dummyStart.Year()+1, year) - assert.Equal(t, time.January, month) - assert.Equal(t, 1, day) - assert.Zero(t, hour) - assert.Zero(t, min) - assert.Zero(t, sec) - assert.Zero(t, nsec) - assert.Equal(t, dummyLocation, loc) - return dummyTime - } + m.Mock(findValueMatch).Expects(dummyStart.Year(), dummyYears).Returns(dummyYear, dummyYearIndex, false, false).Once() + m.Mock(findValueMatch).Expects(int(dummyStart.Month())-1, dummyMonths).Returns(dummyMonth, dummyMonthIndex, false, true).Once() + m.Mock(time.Date).Expects(dummyStart.Year()+1, time.January, 1, + 0, 0, 0, 0, dummyLocation).Returns(dummyTime).Once() // SUT + act var completed, start, err = determineScheduleIndex( @@ -1309,20 +966,17 @@ func TestDetermineScheduleIndex_MonthOverflow(t *testing.T) { assert.False(t, completed) assert.Equal(t, dummyTime, start) assert.NoError(t, err) - - // verify - verifyAll(t) } func TestDetermineScheduleIndex_MonthIncrement(t *testing.T) { // arrange var dummyStart = time.Now() - var dummySeconds = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyMinutes = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyHours = []int{rand.Intn(24), rand.Intn(24), rand.Intn(24)} - var dummyDays = []int{rand.Intn(31), rand.Intn(31), rand.Intn(31)} - var dummyMonths = []int{rand.Intn(12), rand.Intn(12), rand.Intn(12)} - var dummyYears = []int{rand.Intn(100), rand.Intn(100), rand.Intn(100)} + var dummySeconds = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyMinutes = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyHours = []int{rand.IntN(24), rand.IntN(24), rand.IntN(24)} + var dummyDays = []int{rand.IntN(31), rand.IntN(31), rand.IntN(31)} + var dummyMonths = []int{rand.IntN(12), rand.IntN(12), rand.IntN(12)} + var dummyYears = []int{rand.IntN(100), rand.IntN(100), rand.IntN(100)} var dummyLocation, _ = time.LoadLocation("Asia/Shanghai") var dummySchedule = &schedule{ seconds: dummySeconds, @@ -1333,41 +987,20 @@ func TestDetermineScheduleIndex_MonthIncrement(t *testing.T) { years: dummyYears, timezone: dummyLocation, } - var dummyYear = rand.Intn(100) - var dummyYearIndex = rand.Intn(100) - var dummyMonth = rand.Intn(12) - var dummyMonthIndex = rand.Intn(12) + var dummyYear = rand.IntN(100) + var dummyYearIndex = rand.IntN(100) + var dummyMonth = rand.IntN(12) + var dummyMonthIndex = rand.IntN(12) var dummyTime = time.Now().Add(10 * time.Second) // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - findValueMatchFuncExpected = 2 - findValueMatchFunc = func(value int, values []int) (int, int, bool, bool) { - findValueMatchFuncCalled++ - if findValueMatchFuncCalled == 1 { - assert.Equal(t, dummyStart.Year(), value) - assert.Equal(t, dummyYears, values) - return dummyYear, dummyYearIndex, false, false - } - assert.Equal(t, int(dummyStart.Month())-1, value) - assert.Equal(t, dummyMonths, values) - return dummyMonth, dummyMonthIndex, true, false - } - timeDateExpected = 1 - timeDate = func(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) time.Time { - timeDateCalled++ - assert.Equal(t, dummyYear, year) - assert.Equal(t, time.Month(dummyMonth+1), month) - assert.Equal(t, 1, day) - assert.Zero(t, hour) - assert.Zero(t, min) - assert.Zero(t, sec) - assert.Zero(t, nsec) - assert.Equal(t, dummyLocation, loc) - return dummyTime - } + m.Mock(findValueMatch).Expects(dummyStart.Year(), dummyYears).Returns(dummyYear, dummyYearIndex, false, false).Once() + m.Mock(findValueMatch).Expects(int(dummyStart.Month())-1, dummyMonths).Returns(dummyMonth, dummyMonthIndex, true, false).Once() + m.Mock(time.Date).Expects(dummyYear, time.Month(dummyMonth+1), 1, + 0, 0, 0, 0, dummyLocation).Returns(dummyTime).Once() // SUT + act var completed, start, err = determineScheduleIndex( @@ -1379,20 +1012,17 @@ func TestDetermineScheduleIndex_MonthIncrement(t *testing.T) { assert.False(t, completed) assert.Equal(t, dummyTime, start) assert.NoError(t, err) - - // verify - verifyAll(t) } func TestDetermineScheduleIndex_DayOverflow(t *testing.T) { // arrange var dummyStart = time.Now() - var dummySeconds = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyMinutes = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyHours = []int{rand.Intn(24), rand.Intn(24), rand.Intn(24)} - var dummyDays = []int{rand.Intn(31), rand.Intn(31), rand.Intn(31)} - var dummyMonths = []int{rand.Intn(12), rand.Intn(12), rand.Intn(12)} - var dummyYears = []int{rand.Intn(100), rand.Intn(100), rand.Intn(100)} + var dummySeconds = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyMinutes = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyHours = []int{rand.IntN(24), rand.IntN(24), rand.IntN(24)} + var dummyDays = []int{rand.IntN(31), rand.IntN(31), rand.IntN(31)} + var dummyMonths = []int{rand.IntN(12), rand.IntN(12), rand.IntN(12)} + var dummyYears = []int{rand.IntN(100), rand.IntN(100), rand.IntN(100)} var dummyLocation, _ = time.LoadLocation("Asia/Shanghai") var dummySchedule = &schedule{ seconds: dummySeconds, @@ -1403,47 +1033,23 @@ func TestDetermineScheduleIndex_DayOverflow(t *testing.T) { years: dummyYears, timezone: dummyLocation, } - var dummyYear = rand.Intn(100) - var dummyYearIndex = rand.Intn(100) - var dummyMonth = rand.Intn(12) - var dummyMonthIndex = rand.Intn(12) - var dummyDay = rand.Intn(31) - var dummyDayIndex = rand.Intn(31) + var dummyYear = rand.IntN(100) + var dummyYearIndex = rand.IntN(100) + var dummyMonth = rand.IntN(12) + var dummyMonthIndex = rand.IntN(12) + var dummyDay = rand.IntN(31) + var dummyDayIndex = rand.IntN(31) var dummyTime = time.Now().Add(10 * time.Second) // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - findValueMatchFuncExpected = 3 - findValueMatchFunc = func(value int, values []int) (int, int, bool, bool) { - findValueMatchFuncCalled++ - if findValueMatchFuncCalled == 1 { - assert.Equal(t, dummyStart.Year(), value) - assert.Equal(t, dummyYears, values) - return dummyYear, dummyYearIndex, false, false - } else if findValueMatchFuncCalled == 2 { - assert.Equal(t, int(dummyStart.Month())-1, value) - assert.Equal(t, dummyMonths, values) - return dummyMonth, dummyMonthIndex, false, false - } - assert.Equal(t, dummyStart.Day()-1, value) - assert.Equal(t, dummyDays, values) - return dummyDay, dummyDayIndex, false, true - } - timeDateExpected = 1 - timeDate = func(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) time.Time { - timeDateCalled++ - assert.Equal(t, dummyStart.Year(), year) - assert.Equal(t, dummyStart.Month()+1, month) - assert.Equal(t, 1, day) - assert.Zero(t, hour) - assert.Zero(t, min) - assert.Zero(t, sec) - assert.Zero(t, nsec) - assert.Equal(t, dummyLocation, loc) - return dummyTime - } + m.Mock(findValueMatch).Expects(dummyStart.Year(), dummyYears).Returns(dummyYear, dummyYearIndex, false, false).Once() + m.Mock(findValueMatch).Expects(int(dummyStart.Month())-1, dummyMonths).Returns(dummyMonth, dummyMonthIndex, false, false).Once() + m.Mock(findValueMatch).Expects(dummyStart.Day()-1, dummyDays).Returns(dummyDay, dummyDayIndex, false, true).Once() + m.Mock(time.Date).Expects(dummyStart.Year(), dummyStart.Month()+1, 1, + 0, 0, 0, 0, dummyLocation).Returns(dummyTime).Once() // SUT + act var completed, start, err = determineScheduleIndex( @@ -1455,20 +1061,17 @@ func TestDetermineScheduleIndex_DayOverflow(t *testing.T) { assert.False(t, completed) assert.Equal(t, dummyTime, start) assert.NoError(t, err) - - // verify - verifyAll(t) } func TestDetermineScheduleIndex_DayIncrement(t *testing.T) { // arrange var dummyStart = time.Now() - var dummySeconds = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyMinutes = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyHours = []int{rand.Intn(24), rand.Intn(24), rand.Intn(24)} - var dummyDays = []int{rand.Intn(31), rand.Intn(31), rand.Intn(31)} - var dummyMonths = []int{rand.Intn(12), rand.Intn(12), rand.Intn(12)} - var dummyYears = []int{rand.Intn(100), rand.Intn(100), rand.Intn(100)} + var dummySeconds = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyMinutes = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyHours = []int{rand.IntN(24), rand.IntN(24), rand.IntN(24)} + var dummyDays = []int{rand.IntN(31), rand.IntN(31), rand.IntN(31)} + var dummyMonths = []int{rand.IntN(12), rand.IntN(12), rand.IntN(12)} + var dummyYears = []int{rand.IntN(100), rand.IntN(100), rand.IntN(100)} var dummyLocation, _ = time.LoadLocation("Asia/Shanghai") var dummySchedule = &schedule{ seconds: dummySeconds, @@ -1479,47 +1082,23 @@ func TestDetermineScheduleIndex_DayIncrement(t *testing.T) { years: dummyYears, timezone: dummyLocation, } - var dummyYear = rand.Intn(100) - var dummyYearIndex = rand.Intn(100) - var dummyMonth = rand.Intn(12) - var dummyMonthIndex = rand.Intn(12) - var dummyDay = rand.Intn(31) - var dummyDayIndex = rand.Intn(31) + var dummyYear = rand.IntN(100) + var dummyYearIndex = rand.IntN(100) + var dummyMonth = rand.IntN(12) + var dummyMonthIndex = rand.IntN(12) + var dummyDay = rand.IntN(31) + var dummyDayIndex = rand.IntN(31) var dummyTime = time.Now().Add(10 * time.Second) // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - findValueMatchFuncExpected = 3 - findValueMatchFunc = func(value int, values []int) (int, int, bool, bool) { - findValueMatchFuncCalled++ - if findValueMatchFuncCalled == 1 { - assert.Equal(t, dummyStart.Year(), value) - assert.Equal(t, dummyYears, values) - return dummyYear, dummyYearIndex, false, false - } else if findValueMatchFuncCalled == 2 { - assert.Equal(t, int(dummyStart.Month())-1, value) - assert.Equal(t, dummyMonths, values) - return dummyMonth, dummyMonthIndex, false, false - } - assert.Equal(t, dummyStart.Day()-1, value) - assert.Equal(t, dummyDays, values) - return dummyDay, dummyDayIndex, true, false - } - timeDateExpected = 1 - timeDate = func(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) time.Time { - timeDateCalled++ - assert.Equal(t, dummyYear, year) - assert.Equal(t, time.Month(dummyMonth+1), month) - assert.Equal(t, dummyDay+1, day) - assert.Zero(t, hour) - assert.Zero(t, min) - assert.Zero(t, sec) - assert.Zero(t, nsec) - assert.Equal(t, dummyLocation, loc) - return dummyTime - } + m.Mock(findValueMatch).Expects(dummyStart.Year(), dummyYears).Returns(dummyYear, dummyYearIndex, false, false).Once() + m.Mock(findValueMatch).Expects(int(dummyStart.Month())-1, dummyMonths).Returns(dummyMonth, dummyMonthIndex, false, false).Once() + m.Mock(findValueMatch).Expects(dummyStart.Day()-1, dummyDays).Returns(dummyDay, dummyDayIndex, true, false).Once() + m.Mock(time.Date).Expects(dummyYear, time.Month(dummyMonth+1), dummyDay+1, + 0, 0, 0, 0, dummyLocation).Returns(dummyTime).Once() // SUT + act var completed, start, err = determineScheduleIndex( @@ -1531,25 +1110,22 @@ func TestDetermineScheduleIndex_DayIncrement(t *testing.T) { assert.False(t, completed) assert.Equal(t, dummyTime, start) assert.NoError(t, err) - - // verify - verifyAll(t) } func TestDetermineScheduleIndex_WeekdayMismatch(t *testing.T) { // arrange var dummyStart = time.Now() - var dummySeconds = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyMinutes = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyHours = []int{rand.Intn(24), rand.Intn(24), rand.Intn(24)} - var dummyDays = []int{rand.Intn(31), rand.Intn(31), rand.Intn(31)} - var dummyMonths = []int{rand.Intn(12), rand.Intn(12), rand.Intn(12)} - var dummyYears = []int{rand.Intn(100), rand.Intn(100), rand.Intn(100)} + var dummySeconds = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyMinutes = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyHours = []int{rand.IntN(24), rand.IntN(24), rand.IntN(24)} + var dummyDays = []int{rand.IntN(31), rand.IntN(31), rand.IntN(31)} + var dummyMonths = []int{rand.IntN(12), rand.IntN(12), rand.IntN(12)} + var dummyYears = []int{rand.IntN(100), rand.IntN(100), rand.IntN(100)} var dummyLocation, _ = time.LoadLocation("Asia/Shanghai") var dummyWeekdays = map[time.Weekday]bool{ - time.Weekday(rand.Intn(7)): rand.Intn(100) > 50, - time.Weekday(rand.Intn(7)): rand.Intn(100) > 50, - time.Weekday(rand.Intn(7)): rand.Intn(100) > 50, + time.Weekday(rand.IntN(7)): rand.IntN(100) > 50, + time.Weekday(rand.IntN(7)): rand.IntN(100) > 50, + time.Weekday(rand.IntN(7)): rand.IntN(100) > 50, } var dummySchedule = &schedule{ seconds: dummySeconds, @@ -1561,56 +1137,24 @@ func TestDetermineScheduleIndex_WeekdayMismatch(t *testing.T) { timezone: dummyLocation, weekdays: dummyWeekdays, } - var dummyYear = rand.Intn(100) - var dummyYearIndex = rand.Intn(100) - var dummyMonth = rand.Intn(12) - var dummyMonthIndex = rand.Intn(12) - var dummyDay = rand.Intn(31) - var dummyDayIndex = rand.Intn(31) + var dummyYear = rand.IntN(100) + var dummyYearIndex = rand.IntN(100) + var dummyMonth = rand.IntN(12) + var dummyMonthIndex = rand.IntN(12) + var dummyDay = rand.IntN(31) + var dummyDayIndex = rand.IntN(31) var dummyTime = time.Now().Add(10 * time.Second) // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - findValueMatchFuncExpected = 3 - findValueMatchFunc = func(value int, values []int) (int, int, bool, bool) { - findValueMatchFuncCalled++ - if findValueMatchFuncCalled == 1 { - assert.Equal(t, dummyStart.Year(), value) - assert.Equal(t, dummyYears, values) - return dummyYear, dummyYearIndex, false, false - } else if findValueMatchFuncCalled == 2 { - assert.Equal(t, int(dummyStart.Month())-1, value) - assert.Equal(t, dummyMonths, values) - return dummyMonth, dummyMonthIndex, false, false - } - assert.Equal(t, dummyStart.Day()-1, value) - assert.Equal(t, dummyDays, values) - return dummyDay, dummyDayIndex, false, false - } - isWeekdayMatchFuncExpected = 1 - isWeekdayMatchFunc = func(year, month, day int, weekdays map[time.Weekday]bool) bool { - isWeekdayMatchFuncCalled++ - assert.Equal(t, dummyYear, year) - assert.Equal(t, dummyMonth, month) - assert.Equal(t, dummyDay, day) - assert.Equal(t, dummyWeekdays, weekdays) - return false - } - timeDateExpected = 1 - timeDate = func(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) time.Time { - timeDateCalled++ - assert.Equal(t, dummyStart.Year(), year) - assert.Equal(t, dummyStart.Month(), month) - assert.Equal(t, dummyStart.Day()+1, day) - assert.Zero(t, hour) - assert.Zero(t, min) - assert.Zero(t, sec) - assert.Zero(t, nsec) - assert.Equal(t, dummyLocation, loc) - return dummyTime - } + m.Mock(findValueMatch).Expects(dummyStart.Year(), dummyYears).Returns(dummyYear, dummyYearIndex, false, false).Once() + m.Mock(findValueMatch).Expects(int(dummyStart.Month())-1, dummyMonths).Returns(dummyMonth, dummyMonthIndex, false, false).Once() + m.Mock(findValueMatch).Expects(dummyStart.Day()-1, dummyDays).Returns(dummyDay, dummyDayIndex, false, false).Once() + m.Mock(isWeekdayMatch).Expects(dummyYear, dummyMonth, dummyDay, dummyWeekdays).Returns(false).Once() + m.Mock(time.Date).Expects(dummyStart.Year(), dummyStart.Month(), dummyStart.Day()+1, + 0, 0, 0, 0, dummyLocation).Returns(dummyTime).Once() // SUT + act var completed, start, err = determineScheduleIndex( @@ -1622,25 +1166,22 @@ func TestDetermineScheduleIndex_WeekdayMismatch(t *testing.T) { assert.False(t, completed) assert.Equal(t, dummyTime, start) assert.NoError(t, err) - - // verify - verifyAll(t) } func TestDetermineScheduleIndex_HourOverflow(t *testing.T) { // arrange var dummyStart = time.Now() - var dummySeconds = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyMinutes = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyHours = []int{rand.Intn(24), rand.Intn(24), rand.Intn(24)} - var dummyDays = []int{rand.Intn(31), rand.Intn(31), rand.Intn(31)} - var dummyMonths = []int{rand.Intn(12), rand.Intn(12), rand.Intn(12)} - var dummyYears = []int{rand.Intn(100), rand.Intn(100), rand.Intn(100)} + var dummySeconds = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyMinutes = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyHours = []int{rand.IntN(24), rand.IntN(24), rand.IntN(24)} + var dummyDays = []int{rand.IntN(31), rand.IntN(31), rand.IntN(31)} + var dummyMonths = []int{rand.IntN(12), rand.IntN(12), rand.IntN(12)} + var dummyYears = []int{rand.IntN(100), rand.IntN(100), rand.IntN(100)} var dummyLocation, _ = time.LoadLocation("Asia/Shanghai") var dummyWeekdays = map[time.Weekday]bool{ - time.Weekday(rand.Intn(7)): rand.Intn(100) > 50, - time.Weekday(rand.Intn(7)): rand.Intn(100) > 50, - time.Weekday(rand.Intn(7)): rand.Intn(100) > 50, + time.Weekday(rand.IntN(7)): rand.IntN(100) > 50, + time.Weekday(rand.IntN(7)): rand.IntN(100) > 50, + time.Weekday(rand.IntN(7)): rand.IntN(100) > 50, } var dummySchedule = &schedule{ seconds: dummySeconds, @@ -1652,62 +1193,27 @@ func TestDetermineScheduleIndex_HourOverflow(t *testing.T) { timezone: dummyLocation, weekdays: dummyWeekdays, } - var dummyYear = rand.Intn(100) - var dummyYearIndex = rand.Intn(100) - var dummyMonth = rand.Intn(12) - var dummyMonthIndex = rand.Intn(12) - var dummyDay = rand.Intn(31) - var dummyDayIndex = rand.Intn(31) - var dummyHour = rand.Intn(24) - var dummyHourIndex = rand.Intn(24) + var dummyYear = rand.IntN(100) + var dummyYearIndex = rand.IntN(100) + var dummyMonth = rand.IntN(12) + var dummyMonthIndex = rand.IntN(12) + var dummyDay = rand.IntN(31) + var dummyDayIndex = rand.IntN(31) + var dummyHour = rand.IntN(24) + var dummyHourIndex = rand.IntN(24) var dummyTime = time.Now().Add(10 * time.Second) // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - findValueMatchFuncExpected = 4 - findValueMatchFunc = func(value int, values []int) (int, int, bool, bool) { - findValueMatchFuncCalled++ - if findValueMatchFuncCalled == 1 { - assert.Equal(t, dummyStart.Year(), value) - assert.Equal(t, dummyYears, values) - return dummyYear, dummyYearIndex, false, false - } else if findValueMatchFuncCalled == 2 { - assert.Equal(t, int(dummyStart.Month())-1, value) - assert.Equal(t, dummyMonths, values) - return dummyMonth, dummyMonthIndex, false, false - } else if findValueMatchFuncCalled == 3 { - assert.Equal(t, dummyStart.Day()-1, value) - assert.Equal(t, dummyDays, values) - return dummyDay, dummyDayIndex, false, false - } - assert.Equal(t, dummyStart.Hour(), value) - assert.Equal(t, dummyHours, values) - return dummyHour, dummyHourIndex, false, true - } - isWeekdayMatchFuncExpected = 1 - isWeekdayMatchFunc = func(year, month, day int, weekdays map[time.Weekday]bool) bool { - isWeekdayMatchFuncCalled++ - assert.Equal(t, dummyYear, year) - assert.Equal(t, dummyMonth, month) - assert.Equal(t, dummyDay, day) - assert.Equal(t, dummyWeekdays, weekdays) - return true - } - timeDateExpected = 1 - timeDate = func(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) time.Time { - timeDateCalled++ - assert.Equal(t, dummyStart.Year(), year) - assert.Equal(t, dummyStart.Month(), month) - assert.Equal(t, dummyStart.Day()+1, day) - assert.Zero(t, hour) - assert.Zero(t, min) - assert.Zero(t, sec) - assert.Zero(t, nsec) - assert.Equal(t, dummyLocation, loc) - return dummyTime - } + m.Mock(findValueMatch).Expects(dummyStart.Year(), dummyYears).Returns(dummyYear, dummyYearIndex, false, false).Once() + m.Mock(findValueMatch).Expects(int(dummyStart.Month())-1, dummyMonths).Returns(dummyMonth, dummyMonthIndex, false, false).Once() + m.Mock(findValueMatch).Expects(dummyStart.Day()-1, dummyDays).Returns(dummyDay, dummyDayIndex, false, false).Once() + m.Mock(findValueMatch).Expects(dummyStart.Hour(), dummyHours).Returns(dummyHour, dummyHourIndex, false, true).Once() + m.Mock(isWeekdayMatch).Expects(dummyYear, dummyMonth, dummyDay, dummyWeekdays).Returns(true).Once() + m.Mock(time.Date).Expects(dummyStart.Year(), dummyStart.Month(), dummyStart.Day()+1, + 0, 0, 0, 0, dummyLocation).Returns(dummyTime).Once() // SUT + act var completed, start, err = determineScheduleIndex( @@ -1719,25 +1225,22 @@ func TestDetermineScheduleIndex_HourOverflow(t *testing.T) { assert.False(t, completed) assert.Equal(t, dummyTime, start) assert.NoError(t, err) - - // verify - verifyAll(t) } func TestDetermineScheduleIndex_HourIncrement(t *testing.T) { // arrange var dummyStart = time.Now() - var dummySeconds = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyMinutes = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyHours = []int{rand.Intn(24), rand.Intn(24), rand.Intn(24)} - var dummyDays = []int{rand.Intn(31), rand.Intn(31), rand.Intn(31)} - var dummyMonths = []int{rand.Intn(12), rand.Intn(12), rand.Intn(12)} - var dummyYears = []int{rand.Intn(100), rand.Intn(100), rand.Intn(100)} + var dummySeconds = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyMinutes = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyHours = []int{rand.IntN(24), rand.IntN(24), rand.IntN(24)} + var dummyDays = []int{rand.IntN(31), rand.IntN(31), rand.IntN(31)} + var dummyMonths = []int{rand.IntN(12), rand.IntN(12), rand.IntN(12)} + var dummyYears = []int{rand.IntN(100), rand.IntN(100), rand.IntN(100)} var dummyLocation, _ = time.LoadLocation("Asia/Shanghai") var dummyWeekdays = map[time.Weekday]bool{ - time.Weekday(rand.Intn(7)): rand.Intn(100) > 50, - time.Weekday(rand.Intn(7)): rand.Intn(100) > 50, - time.Weekday(rand.Intn(7)): rand.Intn(100) > 50, + time.Weekday(rand.IntN(7)): rand.IntN(100) > 50, + time.Weekday(rand.IntN(7)): rand.IntN(100) > 50, + time.Weekday(rand.IntN(7)): rand.IntN(100) > 50, } var dummySchedule = &schedule{ seconds: dummySeconds, @@ -1749,62 +1252,27 @@ func TestDetermineScheduleIndex_HourIncrement(t *testing.T) { timezone: dummyLocation, weekdays: dummyWeekdays, } - var dummyYear = rand.Intn(100) - var dummyYearIndex = rand.Intn(100) - var dummyMonth = rand.Intn(12) - var dummyMonthIndex = rand.Intn(12) - var dummyDay = rand.Intn(31) - var dummyDayIndex = rand.Intn(31) - var dummyHour = rand.Intn(24) - var dummyHourIndex = rand.Intn(24) + var dummyYear = rand.IntN(100) + var dummyYearIndex = rand.IntN(100) + var dummyMonth = rand.IntN(12) + var dummyMonthIndex = rand.IntN(12) + var dummyDay = rand.IntN(31) + var dummyDayIndex = rand.IntN(31) + var dummyHour = rand.IntN(24) + var dummyHourIndex = rand.IntN(24) var dummyTime = time.Now().Add(10 * time.Second) // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - findValueMatchFuncExpected = 4 - findValueMatchFunc = func(value int, values []int) (int, int, bool, bool) { - findValueMatchFuncCalled++ - if findValueMatchFuncCalled == 1 { - assert.Equal(t, dummyStart.Year(), value) - assert.Equal(t, dummyYears, values) - return dummyYear, dummyYearIndex, false, false - } else if findValueMatchFuncCalled == 2 { - assert.Equal(t, int(dummyStart.Month())-1, value) - assert.Equal(t, dummyMonths, values) - return dummyMonth, dummyMonthIndex, false, false - } else if findValueMatchFuncCalled == 3 { - assert.Equal(t, dummyStart.Day()-1, value) - assert.Equal(t, dummyDays, values) - return dummyDay, dummyDayIndex, false, false - } - assert.Equal(t, dummyStart.Hour(), value) - assert.Equal(t, dummyHours, values) - return dummyHour, dummyHourIndex, true, false - } - isWeekdayMatchFuncExpected = 1 - isWeekdayMatchFunc = func(year, month, day int, weekdays map[time.Weekday]bool) bool { - isWeekdayMatchFuncCalled++ - assert.Equal(t, dummyYear, year) - assert.Equal(t, dummyMonth, month) - assert.Equal(t, dummyDay, day) - assert.Equal(t, dummyWeekdays, weekdays) - return true - } - timeDateExpected = 1 - timeDate = func(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) time.Time { - timeDateCalled++ - assert.Equal(t, dummyYear, year) - assert.Equal(t, time.Month(dummyMonth+1), month) - assert.Equal(t, dummyDay+1, day) - assert.Equal(t, dummyHour, hour) - assert.Zero(t, min) - assert.Zero(t, sec) - assert.Zero(t, nsec) - assert.Equal(t, dummyLocation, loc) - return dummyTime - } + m.Mock(findValueMatch).Expects(dummyStart.Year(), dummyYears).Returns(dummyYear, dummyYearIndex, false, false).Once() + m.Mock(findValueMatch).Expects(int(dummyStart.Month())-1, dummyMonths).Returns(dummyMonth, dummyMonthIndex, false, false).Once() + m.Mock(findValueMatch).Expects(dummyStart.Day()-1, dummyDays).Returns(dummyDay, dummyDayIndex, false, false).Once() + m.Mock(findValueMatch).Expects(dummyStart.Hour(), dummyHours).Returns(dummyHour, dummyHourIndex, true, false).Once() + m.Mock(isWeekdayMatch).Expects(dummyYear, dummyMonth, dummyDay, dummyWeekdays).Returns(true).Once() + m.Mock(time.Date).Expects(dummyYear, time.Month(dummyMonth+1), dummyDay+1, + dummyHour, 0, 0, 0, dummyLocation).Returns(dummyTime).Once() // SUT + act var completed, start, err = determineScheduleIndex( @@ -1816,25 +1284,22 @@ func TestDetermineScheduleIndex_HourIncrement(t *testing.T) { assert.False(t, completed) assert.Equal(t, dummyTime, start) assert.NoError(t, err) - - // verify - verifyAll(t) } func TestDetermineScheduleIndex_MinuteOverflow(t *testing.T) { // arrange var dummyStart = time.Now() - var dummySeconds = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyMinutes = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyHours = []int{rand.Intn(24), rand.Intn(24), rand.Intn(24)} - var dummyDays = []int{rand.Intn(31), rand.Intn(31), rand.Intn(31)} - var dummyMonths = []int{rand.Intn(12), rand.Intn(12), rand.Intn(12)} - var dummyYears = []int{rand.Intn(100), rand.Intn(100), rand.Intn(100)} + var dummySeconds = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyMinutes = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyHours = []int{rand.IntN(24), rand.IntN(24), rand.IntN(24)} + var dummyDays = []int{rand.IntN(31), rand.IntN(31), rand.IntN(31)} + var dummyMonths = []int{rand.IntN(12), rand.IntN(12), rand.IntN(12)} + var dummyYears = []int{rand.IntN(100), rand.IntN(100), rand.IntN(100)} var dummyLocation, _ = time.LoadLocation("Asia/Shanghai") var dummyWeekdays = map[time.Weekday]bool{ - time.Weekday(rand.Intn(7)): rand.Intn(100) > 50, - time.Weekday(rand.Intn(7)): rand.Intn(100) > 50, - time.Weekday(rand.Intn(7)): rand.Intn(100) > 50, + time.Weekday(rand.IntN(7)): rand.IntN(100) > 50, + time.Weekday(rand.IntN(7)): rand.IntN(100) > 50, + time.Weekday(rand.IntN(7)): rand.IntN(100) > 50, } var dummySchedule = &schedule{ seconds: dummySeconds, @@ -1846,68 +1311,30 @@ func TestDetermineScheduleIndex_MinuteOverflow(t *testing.T) { timezone: dummyLocation, weekdays: dummyWeekdays, } - var dummyYear = rand.Intn(100) - var dummyYearIndex = rand.Intn(100) - var dummyMonth = rand.Intn(12) - var dummyMonthIndex = rand.Intn(12) - var dummyDay = rand.Intn(31) - var dummyDayIndex = rand.Intn(31) - var dummyHour = rand.Intn(24) - var dummyHourIndex = rand.Intn(24) - var dummyMinute = rand.Intn(60) - var dummyMinuteIndex = rand.Intn(60) + var dummyYear = rand.IntN(100) + var dummyYearIndex = rand.IntN(100) + var dummyMonth = rand.IntN(12) + var dummyMonthIndex = rand.IntN(12) + var dummyDay = rand.IntN(31) + var dummyDayIndex = rand.IntN(31) + var dummyHour = rand.IntN(24) + var dummyHourIndex = rand.IntN(24) + var dummyMinute = rand.IntN(60) + var dummyMinuteIndex = rand.IntN(60) var dummyTime = time.Now().Add(10 * time.Second) // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - findValueMatchFuncExpected = 5 - findValueMatchFunc = func(value int, values []int) (int, int, bool, bool) { - findValueMatchFuncCalled++ - if findValueMatchFuncCalled == 1 { - assert.Equal(t, dummyStart.Year(), value) - assert.Equal(t, dummyYears, values) - return dummyYear, dummyYearIndex, false, false - } else if findValueMatchFuncCalled == 2 { - assert.Equal(t, int(dummyStart.Month())-1, value) - assert.Equal(t, dummyMonths, values) - return dummyMonth, dummyMonthIndex, false, false - } else if findValueMatchFuncCalled == 3 { - assert.Equal(t, dummyStart.Day()-1, value) - assert.Equal(t, dummyDays, values) - return dummyDay, dummyDayIndex, false, false - } else if findValueMatchFuncCalled == 4 { - assert.Equal(t, dummyStart.Hour(), value) - assert.Equal(t, dummyHours, values) - return dummyHour, dummyHourIndex, false, false - } - assert.Equal(t, dummyStart.Minute(), value) - assert.Equal(t, dummyMinutes, values) - return dummyMinute, dummyMinuteIndex, false, true - } - isWeekdayMatchFuncExpected = 1 - isWeekdayMatchFunc = func(year, month, day int, weekdays map[time.Weekday]bool) bool { - isWeekdayMatchFuncCalled++ - assert.Equal(t, dummyYear, year) - assert.Equal(t, dummyMonth, month) - assert.Equal(t, dummyDay, day) - assert.Equal(t, dummyWeekdays, weekdays) - return true - } - timeDateExpected = 1 - timeDate = func(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) time.Time { - timeDateCalled++ - assert.Equal(t, dummyStart.Year(), year) - assert.Equal(t, dummyStart.Month(), month) - assert.Equal(t, dummyStart.Day(), day) - assert.Equal(t, dummyStart.Hour()+1, hour) - assert.Zero(t, min) - assert.Zero(t, sec) - assert.Zero(t, nsec) - assert.Equal(t, dummyLocation, loc) - return dummyTime - } + m.Mock(findValueMatch).Expects(dummyStart.Year(), dummyYears).Returns(dummyYear, dummyYearIndex, false, false).Once() + m.Mock(findValueMatch).Expects(int(dummyStart.Month())-1, dummyMonths).Returns(dummyMonth, dummyMonthIndex, false, false).Once() + m.Mock(findValueMatch).Expects(dummyStart.Day()-1, dummyDays).Returns(dummyDay, dummyDayIndex, false, false).Once() + m.Mock(findValueMatch).Expects(dummyStart.Hour(), dummyHours).Returns(dummyHour, dummyHourIndex, false, false).Once() + m.Mock(findValueMatch).Expects(dummyStart.Minute(), dummyMinutes).Returns(dummyMinute, dummyMinuteIndex, false, true).Once() + m.Mock(isWeekdayMatch).Expects(dummyYear, dummyMonth, dummyDay, dummyWeekdays).Returns(true).Once() + m.Mock(time.Date).Expects(dummyStart.Year(), dummyStart.Month(), dummyStart.Day(), + dummyStart.Hour()+1, 0, 0, 0, dummyLocation).Returns(dummyTime).Once() // SUT + act var completed, start, err = determineScheduleIndex( @@ -1919,25 +1346,22 @@ func TestDetermineScheduleIndex_MinuteOverflow(t *testing.T) { assert.False(t, completed) assert.Equal(t, dummyTime, start) assert.NoError(t, err) - - // verify - verifyAll(t) } func TestDetermineScheduleIndex_MinuteIncrement(t *testing.T) { // arrange var dummyStart = time.Now() - var dummySeconds = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyMinutes = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyHours = []int{rand.Intn(24), rand.Intn(24), rand.Intn(24)} - var dummyDays = []int{rand.Intn(31), rand.Intn(31), rand.Intn(31)} - var dummyMonths = []int{rand.Intn(12), rand.Intn(12), rand.Intn(12)} - var dummyYears = []int{rand.Intn(100), rand.Intn(100), rand.Intn(100)} + var dummySeconds = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyMinutes = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyHours = []int{rand.IntN(24), rand.IntN(24), rand.IntN(24)} + var dummyDays = []int{rand.IntN(31), rand.IntN(31), rand.IntN(31)} + var dummyMonths = []int{rand.IntN(12), rand.IntN(12), rand.IntN(12)} + var dummyYears = []int{rand.IntN(100), rand.IntN(100), rand.IntN(100)} var dummyLocation, _ = time.LoadLocation("Asia/Shanghai") var dummyWeekdays = map[time.Weekday]bool{ - time.Weekday(rand.Intn(7)): rand.Intn(100) > 50, - time.Weekday(rand.Intn(7)): rand.Intn(100) > 50, - time.Weekday(rand.Intn(7)): rand.Intn(100) > 50, + time.Weekday(rand.IntN(7)): rand.IntN(100) > 50, + time.Weekday(rand.IntN(7)): rand.IntN(100) > 50, + time.Weekday(rand.IntN(7)): rand.IntN(100) > 50, } var dummySchedule = &schedule{ seconds: dummySeconds, @@ -1949,68 +1373,30 @@ func TestDetermineScheduleIndex_MinuteIncrement(t *testing.T) { timezone: dummyLocation, weekdays: dummyWeekdays, } - var dummyYear = rand.Intn(100) - var dummyYearIndex = rand.Intn(100) - var dummyMonth = rand.Intn(12) - var dummyMonthIndex = rand.Intn(12) - var dummyDay = rand.Intn(31) - var dummyDayIndex = rand.Intn(31) - var dummyHour = rand.Intn(24) - var dummyHourIndex = rand.Intn(24) - var dummyMinute = rand.Intn(60) - var dummyMinuteIndex = rand.Intn(60) + var dummyYear = rand.IntN(100) + var dummyYearIndex = rand.IntN(100) + var dummyMonth = rand.IntN(12) + var dummyMonthIndex = rand.IntN(12) + var dummyDay = rand.IntN(31) + var dummyDayIndex = rand.IntN(31) + var dummyHour = rand.IntN(24) + var dummyHourIndex = rand.IntN(24) + var dummyMinute = rand.IntN(60) + var dummyMinuteIndex = rand.IntN(60) var dummyTime = time.Now().Add(10 * time.Second) // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - findValueMatchFuncExpected = 5 - findValueMatchFunc = func(value int, values []int) (int, int, bool, bool) { - findValueMatchFuncCalled++ - if findValueMatchFuncCalled == 1 { - assert.Equal(t, dummyStart.Year(), value) - assert.Equal(t, dummyYears, values) - return dummyYear, dummyYearIndex, false, false - } else if findValueMatchFuncCalled == 2 { - assert.Equal(t, int(dummyStart.Month())-1, value) - assert.Equal(t, dummyMonths, values) - return dummyMonth, dummyMonthIndex, false, false - } else if findValueMatchFuncCalled == 3 { - assert.Equal(t, dummyStart.Day()-1, value) - assert.Equal(t, dummyDays, values) - return dummyDay, dummyDayIndex, false, false - } else if findValueMatchFuncCalled == 4 { - assert.Equal(t, dummyStart.Hour(), value) - assert.Equal(t, dummyHours, values) - return dummyHour, dummyHourIndex, false, false - } - assert.Equal(t, dummyStart.Minute(), value) - assert.Equal(t, dummyMinutes, values) - return dummyMinute, dummyMinuteIndex, true, false - } - isWeekdayMatchFuncExpected = 1 - isWeekdayMatchFunc = func(year, month, day int, weekdays map[time.Weekday]bool) bool { - isWeekdayMatchFuncCalled++ - assert.Equal(t, dummyYear, year) - assert.Equal(t, dummyMonth, month) - assert.Equal(t, dummyDay, day) - assert.Equal(t, dummyWeekdays, weekdays) - return true - } - timeDateExpected = 1 - timeDate = func(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) time.Time { - timeDateCalled++ - assert.Equal(t, dummyYear, year) - assert.Equal(t, time.Month(dummyMonth+1), month) - assert.Equal(t, dummyDay+1, day) - assert.Equal(t, dummyHour, hour) - assert.Equal(t, dummyMinute, min) - assert.Zero(t, sec) - assert.Zero(t, nsec) - assert.Equal(t, dummyLocation, loc) - return dummyTime - } + m.Mock(findValueMatch).Expects(dummyStart.Year(), dummyYears).Returns(dummyYear, dummyYearIndex, false, false).Once() + m.Mock(findValueMatch).Expects(int(dummyStart.Month())-1, dummyMonths).Returns(dummyMonth, dummyMonthIndex, false, false).Once() + m.Mock(findValueMatch).Expects(dummyStart.Day()-1, dummyDays).Returns(dummyDay, dummyDayIndex, false, false).Once() + m.Mock(findValueMatch).Expects(dummyStart.Hour(), dummyHours).Returns(dummyHour, dummyHourIndex, false, false).Once() + m.Mock(findValueMatch).Expects(dummyStart.Minute(), dummyMinutes).Returns(dummyMinute, dummyMinuteIndex, true, false).Once() + m.Mock(isWeekdayMatch).Expects(dummyYear, dummyMonth, dummyDay, dummyWeekdays).Returns(true).Once() + m.Mock(time.Date).Expects(dummyYear, time.Month(dummyMonth+1), dummyDay+1, + dummyHour, dummyMinute, 0, 0, dummyLocation).Returns(dummyTime).Once() // SUT + act var completed, start, err = determineScheduleIndex( @@ -2022,25 +1408,22 @@ func TestDetermineScheduleIndex_MinuteIncrement(t *testing.T) { assert.False(t, completed) assert.Equal(t, dummyTime, start) assert.NoError(t, err) - - // verify - verifyAll(t) } func TestDetermineScheduleIndex_SecondOverflow(t *testing.T) { // arrange var dummyStart = time.Now() - var dummySeconds = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyMinutes = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyHours = []int{rand.Intn(24), rand.Intn(24), rand.Intn(24)} - var dummyDays = []int{rand.Intn(31), rand.Intn(31), rand.Intn(31)} - var dummyMonths = []int{rand.Intn(12), rand.Intn(12), rand.Intn(12)} - var dummyYears = []int{rand.Intn(100), rand.Intn(100), rand.Intn(100)} + var dummySeconds = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyMinutes = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyHours = []int{rand.IntN(24), rand.IntN(24), rand.IntN(24)} + var dummyDays = []int{rand.IntN(31), rand.IntN(31), rand.IntN(31)} + var dummyMonths = []int{rand.IntN(12), rand.IntN(12), rand.IntN(12)} + var dummyYears = []int{rand.IntN(100), rand.IntN(100), rand.IntN(100)} var dummyLocation, _ = time.LoadLocation("Asia/Shanghai") var dummyWeekdays = map[time.Weekday]bool{ - time.Weekday(rand.Intn(7)): rand.Intn(100) > 50, - time.Weekday(rand.Intn(7)): rand.Intn(100) > 50, - time.Weekday(rand.Intn(7)): rand.Intn(100) > 50, + time.Weekday(rand.IntN(7)): rand.IntN(100) > 50, + time.Weekday(rand.IntN(7)): rand.IntN(100) > 50, + time.Weekday(rand.IntN(7)): rand.IntN(100) > 50, } var dummySchedule = &schedule{ seconds: dummySeconds, @@ -2052,74 +1435,33 @@ func TestDetermineScheduleIndex_SecondOverflow(t *testing.T) { timezone: dummyLocation, weekdays: dummyWeekdays, } - var dummyYear = rand.Intn(100) - var dummyYearIndex = rand.Intn(100) - var dummyMonth = rand.Intn(12) - var dummyMonthIndex = rand.Intn(12) - var dummyDay = rand.Intn(31) - var dummyDayIndex = rand.Intn(31) - var dummyHour = rand.Intn(24) - var dummyHourIndex = rand.Intn(24) - var dummyMinute = rand.Intn(60) - var dummyMinuteIndex = rand.Intn(60) - var dummySecond = rand.Intn(60) - var dummySecondIndex = rand.Intn(60) + var dummyYear = rand.IntN(100) + var dummyYearIndex = rand.IntN(100) + var dummyMonth = rand.IntN(12) + var dummyMonthIndex = rand.IntN(12) + var dummyDay = rand.IntN(31) + var dummyDayIndex = rand.IntN(31) + var dummyHour = rand.IntN(24) + var dummyHourIndex = rand.IntN(24) + var dummyMinute = rand.IntN(60) + var dummyMinuteIndex = rand.IntN(60) + var dummySecond = rand.IntN(60) + var dummySecondIndex = rand.IntN(60) var dummyTime = time.Now().Add(10 * time.Second) // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - findValueMatchFuncExpected = 6 - findValueMatchFunc = func(value int, values []int) (int, int, bool, bool) { - findValueMatchFuncCalled++ - if findValueMatchFuncCalled == 1 { - assert.Equal(t, dummyStart.Year(), value) - assert.Equal(t, dummyYears, values) - return dummyYear, dummyYearIndex, false, false - } else if findValueMatchFuncCalled == 2 { - assert.Equal(t, int(dummyStart.Month())-1, value) - assert.Equal(t, dummyMonths, values) - return dummyMonth, dummyMonthIndex, false, false - } else if findValueMatchFuncCalled == 3 { - assert.Equal(t, dummyStart.Day()-1, value) - assert.Equal(t, dummyDays, values) - return dummyDay, dummyDayIndex, false, false - } else if findValueMatchFuncCalled == 4 { - assert.Equal(t, dummyStart.Hour(), value) - assert.Equal(t, dummyHours, values) - return dummyHour, dummyHourIndex, false, false - } else if findValueMatchFuncCalled == 5 { - assert.Equal(t, dummyStart.Minute(), value) - assert.Equal(t, dummyMinutes, values) - return dummyMinute, dummyMinuteIndex, false, false - } - assert.Equal(t, dummyStart.Second(), value) - assert.Equal(t, dummySeconds, values) - return dummySecond, dummySecondIndex, false, true - } - isWeekdayMatchFuncExpected = 1 - isWeekdayMatchFunc = func(year, month, day int, weekdays map[time.Weekday]bool) bool { - isWeekdayMatchFuncCalled++ - assert.Equal(t, dummyYear, year) - assert.Equal(t, dummyMonth, month) - assert.Equal(t, dummyDay, day) - assert.Equal(t, dummyWeekdays, weekdays) - return true - } - timeDateExpected = 1 - timeDate = func(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) time.Time { - timeDateCalled++ - assert.Equal(t, dummyStart.Year(), year) - assert.Equal(t, dummyStart.Month(), month) - assert.Equal(t, dummyStart.Day(), day) - assert.Equal(t, dummyStart.Hour(), hour) - assert.Equal(t, dummyStart.Minute()+1, min) - assert.Zero(t, sec) - assert.Zero(t, nsec) - assert.Equal(t, dummyLocation, loc) - return dummyTime - } + m.Mock(findValueMatch).Expects(dummyStart.Year(), dummyYears).Returns(dummyYear, dummyYearIndex, false, false).Once() + m.Mock(findValueMatch).Expects(int(dummyStart.Month())-1, dummyMonths).Returns(dummyMonth, dummyMonthIndex, false, false).Once() + m.Mock(findValueMatch).Expects(dummyStart.Day()-1, dummyDays).Returns(dummyDay, dummyDayIndex, false, false).Once() + m.Mock(findValueMatch).Expects(dummyStart.Hour(), dummyHours).Returns(dummyHour, dummyHourIndex, false, false).Once() + m.Mock(findValueMatch).Expects(dummyStart.Minute(), dummyMinutes).Returns(dummyMinute, dummyMinuteIndex, false, false).Once() + m.Mock(findValueMatch).Expects(dummyStart.Second(), dummySeconds).Returns(dummySecond, dummySecondIndex, false, true).Once() + m.Mock(isWeekdayMatch).Expects(dummyYear, dummyMonth, dummyDay, dummyWeekdays).Returns(true).Once() + m.Mock(time.Date).Expects(dummyStart.Year(), dummyStart.Month(), dummyStart.Day(), + dummyStart.Hour(), dummyStart.Minute()+1, 0, 0, dummyLocation).Returns(dummyTime).Once() // SUT + act var completed, start, err = determineScheduleIndex( @@ -2131,25 +1473,22 @@ func TestDetermineScheduleIndex_SecondOverflow(t *testing.T) { assert.False(t, completed) assert.Equal(t, dummyTime, start) assert.NoError(t, err) - - // verify - verifyAll(t) } func TestDetermineScheduleIndex_NoOverflow_NoIncrement(t *testing.T) { // arrange var dummyStart = time.Now() - var dummySeconds = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyMinutes = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyHours = []int{rand.Intn(24), rand.Intn(24), rand.Intn(24)} - var dummyDays = []int{rand.Intn(31), rand.Intn(31), rand.Intn(31)} - var dummyMonths = []int{rand.Intn(12), rand.Intn(12), rand.Intn(12)} - var dummyYears = []int{rand.Intn(100), rand.Intn(100), rand.Intn(100)} + var dummySeconds = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyMinutes = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyHours = []int{rand.IntN(24), rand.IntN(24), rand.IntN(24)} + var dummyDays = []int{rand.IntN(31), rand.IntN(31), rand.IntN(31)} + var dummyMonths = []int{rand.IntN(12), rand.IntN(12), rand.IntN(12)} + var dummyYears = []int{rand.IntN(100), rand.IntN(100), rand.IntN(100)} var dummyLocation, _ = time.LoadLocation("Asia/Shanghai") var dummyWeekdays = map[time.Weekday]bool{ - time.Weekday(rand.Intn(7)): rand.Intn(100) > 50, - time.Weekday(rand.Intn(7)): rand.Intn(100) > 50, - time.Weekday(rand.Intn(7)): rand.Intn(100) > 50, + time.Weekday(rand.IntN(7)): rand.IntN(100) > 50, + time.Weekday(rand.IntN(7)): rand.IntN(100) > 50, + time.Weekday(rand.IntN(7)): rand.IntN(100) > 50, } var dummySchedule = &schedule{ seconds: dummySeconds, @@ -2161,60 +1500,30 @@ func TestDetermineScheduleIndex_NoOverflow_NoIncrement(t *testing.T) { timezone: dummyLocation, weekdays: dummyWeekdays, } - var dummyYear = rand.Intn(100) - var dummyYearIndex = rand.Intn(100) - var dummyMonth = rand.Intn(12) - var dummyMonthIndex = rand.Intn(12) - var dummyDay = rand.Intn(31) - var dummyDayIndex = rand.Intn(31) - var dummyHour = rand.Intn(24) - var dummyHourIndex = rand.Intn(24) - var dummyMinute = rand.Intn(60) - var dummyMinuteIndex = rand.Intn(60) - var dummySecond = rand.Intn(60) - var dummySecondIndex = rand.Intn(60) + var dummyYear = rand.IntN(100) + var dummyYearIndex = rand.IntN(100) + var dummyMonth = rand.IntN(12) + var dummyMonthIndex = rand.IntN(12) + var dummyDay = rand.IntN(31) + var dummyDayIndex = rand.IntN(31) + var dummyHour = rand.IntN(24) + var dummyHourIndex = rand.IntN(24) + var dummyMinute = rand.IntN(60) + var dummyMinuteIndex = rand.IntN(60) + var dummySecond = rand.IntN(60) + var dummySecondIndex = rand.IntN(60) // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - findValueMatchFuncExpected = 6 - findValueMatchFunc = func(value int, values []int) (int, int, bool, bool) { - findValueMatchFuncCalled++ - if findValueMatchFuncCalled == 1 { - assert.Equal(t, dummyStart.Year(), value) - assert.Equal(t, dummyYears, values) - return dummyYear, dummyYearIndex, false, false - } else if findValueMatchFuncCalled == 2 { - assert.Equal(t, int(dummyStart.Month())-1, value) - assert.Equal(t, dummyMonths, values) - return dummyMonth, dummyMonthIndex, false, false - } else if findValueMatchFuncCalled == 3 { - assert.Equal(t, dummyStart.Day()-1, value) - assert.Equal(t, dummyDays, values) - return dummyDay, dummyDayIndex, false, false - } else if findValueMatchFuncCalled == 4 { - assert.Equal(t, dummyStart.Hour(), value) - assert.Equal(t, dummyHours, values) - return dummyHour, dummyHourIndex, false, false - } else if findValueMatchFuncCalled == 5 { - assert.Equal(t, dummyStart.Minute(), value) - assert.Equal(t, dummyMinutes, values) - return dummyMinute, dummyMinuteIndex, false, false - } - assert.Equal(t, dummyStart.Second(), value) - assert.Equal(t, dummySeconds, values) - return dummySecond, dummySecondIndex, false, false - } - isWeekdayMatchFuncExpected = 1 - isWeekdayMatchFunc = func(year, month, day int, weekdays map[time.Weekday]bool) bool { - isWeekdayMatchFuncCalled++ - assert.Equal(t, dummyYear, year) - assert.Equal(t, dummyMonth, month) - assert.Equal(t, dummyDay, day) - assert.Equal(t, dummyWeekdays, weekdays) - return true - } + m.Mock(findValueMatch).Expects(dummyStart.Year(), dummyYears).Returns(dummyYear, dummyYearIndex, false, false).Once() + m.Mock(findValueMatch).Expects(int(dummyStart.Month())-1, dummyMonths).Returns(dummyMonth, dummyMonthIndex, false, false).Once() + m.Mock(findValueMatch).Expects(dummyStart.Day()-1, dummyDays).Returns(dummyDay, dummyDayIndex, false, false).Once() + m.Mock(findValueMatch).Expects(dummyStart.Hour(), dummyHours).Returns(dummyHour, dummyHourIndex, false, false).Once() + m.Mock(findValueMatch).Expects(dummyStart.Minute(), dummyMinutes).Returns(dummyMinute, dummyMinuteIndex, false, false).Once() + m.Mock(findValueMatch).Expects(dummyStart.Second(), dummySeconds).Returns(dummySecond, dummySecondIndex, false, false).Once() + m.Mock(isWeekdayMatch).Expects(dummyYear, dummyMonth, dummyDay, dummyWeekdays).Returns(true).Once() // SUT + act var completed, start, err = determineScheduleIndex( @@ -2226,9 +1535,6 @@ func TestDetermineScheduleIndex_NoOverflow_NoIncrement(t *testing.T) { assert.True(t, completed) assert.Equal(t, dummyStart, start) assert.NoError(t, err) - - // verify - verifyAll(t) } func TestInitialiseSchedule_Error(t *testing.T) { @@ -2238,16 +1544,10 @@ func TestInitialiseSchedule_Error(t *testing.T) { var dummyError = errors.New("some error") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - determineScheduleIndexFuncExpected = 1 - determineScheduleIndexFunc = func(start time.Time, schedule *schedule) (bool, time.Time, error) { - determineScheduleIndexFuncCalled++ - assert.Equal(t, dummyStart, start) - assert.Equal(t, dummySchedule, schedule) - return false, dummyStart, dummyError - } + m.Mock(determineScheduleIndex).Expects(dummyStart, dummySchedule).Returns(false, dummyStart, dummyError).Once() // SUT + act var err = initialiseSchedule( @@ -2257,9 +1557,6 @@ func TestInitialiseSchedule_Error(t *testing.T) { // assert assert.Equal(t, dummyError, err) - - // verify - verifyAll(t) } func TestInitialiseSchedule_Success(t *testing.T) { @@ -2268,16 +1565,10 @@ func TestInitialiseSchedule_Success(t *testing.T) { var dummySchedule = &schedule{second: rand.Int()} // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - determineScheduleIndexFuncExpected = 2 - determineScheduleIndexFunc = func(start time.Time, schedule *schedule) (bool, time.Time, error) { - determineScheduleIndexFuncCalled++ - assert.Equal(t, dummyStart, start) - assert.Equal(t, dummySchedule, schedule) - return determineScheduleIndexFuncCalled == determineScheduleIndexFuncExpected, dummyStart, nil - } + m.Mock(determineScheduleIndex).Expects(dummyStart, dummySchedule).Returns(true, dummyStart, nil).Once() // SUT + act var err = initialiseSchedule( @@ -2287,42 +1578,24 @@ func TestInitialiseSchedule_Success(t *testing.T) { // assert assert.NoError(t, err) - - // verify - verifyAll(t) } func TestScheduleMaker_Schedule_WithoutFrom(t *testing.T) { // arrange var dummyScheduleMaker = &scheduleMaker{ - seconds: []bool{rand.Intn(100) > 50, rand.Intn(100) > 50, rand.Intn(100) > 50}, + seconds: []bool{rand.IntN(100) > 50, rand.IntN(100) > 50, rand.IntN(100) > 50}, } - var dummyTimeNow = time.Now() + var dummyTimeNow = time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC) var dummySchedule = &schedule{year: rand.Int()} var dummyError = errors.New("some error") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - timeNowExpected = 1 - timeNow = func() time.Time { - timeNowCalled++ - return dummyTimeNow - } - constructScheduleTemplateFuncExpected = 1 - constructScheduleTemplateFunc = func(scheduleMaker *scheduleMaker) *schedule { - constructScheduleTemplateFuncCalled++ - assert.Equal(t, dummyScheduleMaker, scheduleMaker) - return dummySchedule - } - initialiseScheduleFuncExpected = 1 - initialiseScheduleFunc = func(start time.Time, schedule *schedule) error { - initialiseScheduleFuncCalled++ - assert.Equal(t, dummyTimeNow, start) - assert.Equal(t, dummySchedule, schedule) - return dummyError - } + m.Mock(time.Now).Expects().Returns(dummyTimeNow).Once() + m.Mock(constructScheduleTemplate).Expects(dummyScheduleMaker).Returns(dummySchedule).Once() + m.Mock(initialiseSchedule).Expects(dummyTimeNow, dummySchedule).Returns(dummyError).Once() // SUT var sut, err = dummyScheduleMaker.Schedule() @@ -2334,44 +1607,26 @@ func TestScheduleMaker_Schedule_WithoutFrom(t *testing.T) { assert.True(t, ok) assert.Equal(t, dummySchedule, result) assert.Equal(t, dummyError, err) - - // verify - verifyAll(t) } func TestScheduleMaker_Schedule_WithFrom(t *testing.T) { // arrange var dummyFrom = time.Now().Add(100 * time.Second) var dummyScheduleMaker = &scheduleMaker{ - seconds: []bool{rand.Intn(100) > 50, rand.Intn(100) > 50, rand.Intn(100) > 50}, + seconds: []bool{rand.IntN(100) > 50, rand.IntN(100) > 50, rand.IntN(100) > 50}, from: &dummyFrom, } - var dummyTimeNow = time.Now() + var dummyTimeNow = time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC) var dummySchedule = &schedule{year: rand.Int()} var dummyError = errors.New("some error") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - timeNowExpected = 1 - timeNow = func() time.Time { - timeNowCalled++ - return dummyTimeNow - } - constructScheduleTemplateFuncExpected = 1 - constructScheduleTemplateFunc = func(scheduleMaker *scheduleMaker) *schedule { - constructScheduleTemplateFuncCalled++ - assert.Equal(t, dummyScheduleMaker, scheduleMaker) - return dummySchedule - } - initialiseScheduleFuncExpected = 1 - initialiseScheduleFunc = func(start time.Time, schedule *schedule) error { - initialiseScheduleFuncCalled++ - assert.Equal(t, dummyFrom, start) - assert.Equal(t, dummySchedule, schedule) - return dummyError - } + m.Mock(time.Now).Expects().Returns(dummyTimeNow).Once() + m.Mock(constructScheduleTemplate).Expects(dummyScheduleMaker).Returns(dummySchedule).Once() + m.Mock(initialiseSchedule).Expects(dummyFrom, dummySchedule).Returns(dummyError).Once() // SUT var sut, err = dummyScheduleMaker.Schedule() @@ -2383,9 +1638,6 @@ func TestScheduleMaker_Schedule_WithFrom(t *testing.T) { assert.True(t, ok) assert.Equal(t, dummySchedule, result) assert.Equal(t, dummyError, err) - - // verify - verifyAll(t) } func TestScheduleMaker_Integration(t *testing.T) { @@ -2404,15 +1656,16 @@ func TestScheduleMaker_Integration(t *testing.T) { "2001-10-15 23:55:30": "2002-01-01 00:00:00", } + // mock + var m = gomocker.NewMocker(t) + for given, expect := range testData { // arrange var timeStart, _ = time.Parse(layout, given) var timeExpect, _ = time.Parse(layout, expect) // stub - timeNow = func() time.Time { - return timeStart - } + m.Stub(time.Now).Returns(timeStart).Once() // SUT var scheduleMaker, _ = NewScheduleMaker().OnSeconds( diff --git a/schedule_test.go b/schedule_test.go index 805aef3..2abf76c 100644 --- a/schedule_test.go +++ b/schedule_test.go @@ -1,16 +1,17 @@ package jobrunner import ( - "math/rand" + "math/rand/v2" "testing" "time" "github.com/stretchr/testify/assert" + "github.com/zhongjie-cai/gomocker/v2" ) func TestMoveValueIndex_IndexOverflow(t *testing.T) { // arrange - var dummyOldIndex = rand.Intn(10) + 5 + var dummyOldIndex = rand.IntN(10) + 5 var dummyValues = []int{ rand.Int(), rand.Int(), @@ -19,9 +20,6 @@ func TestMoveValueIndex_IndexOverflow(t *testing.T) { } var dummyMaxValue = rand.Int() - // mock - createMock(t) - // SUT + act var value, index, reset = moveValueIndex( dummyOldIndex, @@ -33,25 +31,19 @@ func TestMoveValueIndex_IndexOverflow(t *testing.T) { assert.Equal(t, dummyValues[0], value) assert.Zero(t, index) assert.True(t, reset) - - // verify - verifyAll(t) } func TestMoveValueIndex_ValueOverflow(t *testing.T) { // arrange - var dummyOldIndex = rand.Intn(5) + var dummyOldIndex = rand.IntN(5) var dummyValues = []int{ - rand.Intn(100) + 10, - rand.Intn(100) + 10, - rand.Intn(100) + 10, - rand.Intn(100) + 10, - rand.Intn(100) + 10, + rand.IntN(100) + 10, + rand.IntN(100) + 10, + rand.IntN(100) + 10, + rand.IntN(100) + 10, + rand.IntN(100) + 10, } - var dummyMaxValue = rand.Intn(10) - - // mock - createMock(t) + var dummyMaxValue = rand.IntN(10) // SUT + act var value, index, reset = moveValueIndex( @@ -64,30 +56,24 @@ func TestMoveValueIndex_ValueOverflow(t *testing.T) { assert.Equal(t, dummyValues[0], value) assert.Zero(t, index) assert.True(t, reset) - - // verify - verifyAll(t) } func TestMoveValueIndex_NoOverflow(t *testing.T) { // arrange - var dummyOldIndex = rand.Intn(5) + var dummyOldIndex = rand.IntN(5) var dummyValues = []int{ - rand.Intn(100), - rand.Intn(100), - rand.Intn(100), - rand.Intn(100), - rand.Intn(100), - rand.Intn(100), - rand.Intn(100), - rand.Intn(100), - rand.Intn(100), - rand.Intn(100), - } - var dummyMaxValue = rand.Intn(100) + 100 - - // mock - createMock(t) + rand.IntN(100), + rand.IntN(100), + rand.IntN(100), + rand.IntN(100), + rand.IntN(100), + rand.IntN(100), + rand.IntN(100), + rand.IntN(100), + rand.IntN(100), + rand.IntN(100), + } + var dummyMaxValue = rand.IntN(100) + 100 // SUT + act var value, index, reset = moveValueIndex( @@ -100,34 +86,20 @@ func TestMoveValueIndex_NoOverflow(t *testing.T) { assert.Equal(t, dummyValues[dummyOldIndex+1], value) assert.Equal(t, dummyOldIndex+1, index) assert.False(t, reset) - - // verify - verifyAll(t) } func TestGetDaysOfMonth_Mocked(t *testing.T) { // arrange - var dummyYear = 2000 + rand.Intn(100) - var dummyMonth = rand.Intn(12) + var dummyYear = 2000 + rand.IntN(100) + var dummyMonth = rand.IntN(12) var dummyTime = time.Now() // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - timeDateExpected = 1 - timeDate = func(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) time.Time { - timeDateCalled++ - assert.Equal(t, dummyYear, year) - assert.Equal(t, time.Month(dummyMonth+2), month) - assert.Zero(t, day) - assert.Zero(t, hour) - assert.Zero(t, min) - assert.Zero(t, sec) - assert.Zero(t, nsec) - assert.Equal(t, time.Local, loc) - return dummyTime - } + m.Mock(time.Date).Expects(dummyYear, time.Month(dummyMonth+2), + 0, 0, 0, 0, 0, time.Local).Returns(dummyTime).Once() // SUT + act var result = getDaysOfMonth( @@ -137,9 +109,6 @@ func TestGetDaysOfMonth_Mocked(t *testing.T) { // assert assert.Equal(t, dummyTime.Day(), result) - - // verify - verifyAll(t) } func TestGetDaysOfMonth_Integration(t *testing.T) { @@ -147,24 +116,6 @@ func TestGetDaysOfMonth_Integration(t *testing.T) { var dummyYear = 2020 var dummyMonth = 1 - // mock - createMock(t) - - // expect - timeDateExpected = 1 - timeDate = func(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) time.Time { - timeDateCalled++ - assert.Equal(t, dummyYear, year) - assert.Equal(t, time.Month(dummyMonth+2), month) - assert.Zero(t, day) - assert.Zero(t, hour) - assert.Zero(t, min) - assert.Zero(t, sec) - assert.Zero(t, nsec) - assert.Equal(t, time.Local, loc) - return time.Date(year, month, day, hour, min, sec, nsec, loc) - } - // SUT + act var result = getDaysOfMonth( dummyYear, @@ -173,42 +124,29 @@ func TestGetDaysOfMonth_Integration(t *testing.T) { // assert assert.Equal(t, 29, result) - - // verify - verifyAll(t) } func TestConstructTimeBySchedule(t *testing.T) { // arrange var dummyLocation, _ = time.LoadLocation("China/Beijing") var dummySchedule = &schedule{ - year: rand.Intn(100) + 2000, - month: rand.Intn(12), - day: rand.Intn(31), - hour: rand.Intn(24), - minute: rand.Intn(60), - second: rand.Intn(60), + year: rand.IntN(100) + 2000, + month: rand.IntN(12), + day: rand.IntN(31), + hour: rand.IntN(24), + minute: rand.IntN(60), + second: rand.IntN(60), timezone: dummyLocation, } var dummyTime = time.Now() // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - timeDateExpected = 1 - timeDate = func(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) time.Time { - timeDateCalled++ - assert.Equal(t, dummySchedule.year, year) - assert.Equal(t, time.Month(dummySchedule.month+1), month) - assert.Equal(t, dummySchedule.day+1, day) - assert.Equal(t, dummySchedule.hour, hour) - assert.Equal(t, dummySchedule.minute, min) - assert.Equal(t, dummySchedule.second, sec) - assert.Zero(t, nsec) - assert.Equal(t, dummyLocation, loc) - return dummyTime - } + m.Mock(time.Date).Expects(dummySchedule.year, time.Month(dummySchedule.month+1), + dummySchedule.day+1, dummySchedule.hour, dummySchedule.minute, + dummySchedule.second, 0, dummyLocation).Returns(dummyTime).Once() // SUT + act var result = constructTimeBySchedule( @@ -217,31 +155,28 @@ func TestConstructTimeBySchedule(t *testing.T) { // assert assert.Equal(t, dummyTime, result) - - // verify - verifyAll(t) } func TestUpdateScheduleIndex_NoReset(t *testing.T) { // arrange - var dummyOldSecond = rand.Intn(60) - var dummyOldSecondIndex = rand.Intn(60) - var dummySeconds = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyOldMinute = rand.Intn(60) - var dummyOldMinuteIndex = rand.Intn(60) - var dummyMinutes = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyOldHour = rand.Intn(24) - var dummyOldHourIndex = rand.Intn(24) - var dummyHours = []int{rand.Intn(24), rand.Intn(24), rand.Intn(24)} - var dummyOldDay = rand.Intn(31) - var dummyOldDayIndex = rand.Intn(31) - var dummyDays = []int{rand.Intn(31), rand.Intn(31), rand.Intn(31)} - var dummyOldMonth = rand.Intn(12) - var dummyOldMonthIndex = rand.Intn(12) - var dummyMonths = []int{rand.Intn(12), rand.Intn(12), rand.Intn(12)} - var dummyOldYear = rand.Intn(100) - var dummyOldYearIndex = rand.Intn(100) - var dummyYears = []int{rand.Intn(100), rand.Intn(100), rand.Intn(100)} + var dummyOldSecond = rand.IntN(60) + var dummyOldSecondIndex = rand.IntN(60) + var dummySeconds = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyOldMinute = rand.IntN(60) + var dummyOldMinuteIndex = rand.IntN(60) + var dummyMinutes = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyOldHour = rand.IntN(24) + var dummyOldHourIndex = rand.IntN(24) + var dummyHours = []int{rand.IntN(24), rand.IntN(24), rand.IntN(24)} + var dummyOldDay = rand.IntN(31) + var dummyOldDayIndex = rand.IntN(31) + var dummyDays = []int{rand.IntN(31), rand.IntN(31), rand.IntN(31)} + var dummyOldMonth = rand.IntN(12) + var dummyOldMonthIndex = rand.IntN(12) + var dummyMonths = []int{rand.IntN(12), rand.IntN(12), rand.IntN(12)} + var dummyOldYear = rand.IntN(100) + var dummyOldYearIndex = rand.IntN(100) + var dummyYears = []int{rand.IntN(100), rand.IntN(100), rand.IntN(100)} var dummySchedule = &schedule{ second: dummyOldSecond, secondIndex: dummyOldSecondIndex, @@ -262,21 +197,15 @@ func TestUpdateScheduleIndex_NoReset(t *testing.T) { yearIndex: dummyOldYearIndex, years: dummyYears, } - var dummyNewSecond = rand.Intn(60) - var dummyNewSecondIndex = rand.Intn(60) + var dummyNewSecond = rand.IntN(60) + var dummyNewSecondIndex = rand.IntN(60) // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - moveValueIndexFuncExpected = 1 - moveValueIndexFunc = func(oldIndex int, values []int, maxValue int) (int, int, bool) { - moveValueIndexFuncCalled++ - assert.Equal(t, dummySchedule.secondIndex, oldIndex) - assert.Equal(t, dummySchedule.seconds, values) - assert.Equal(t, 60, maxValue) - return dummyNewSecond, dummyNewSecondIndex, false - } + m.Mock(moveValueIndex).Expects(dummySchedule.secondIndex, dummySchedule.seconds, 60). + Returns(dummyNewSecond, dummyNewSecondIndex, false).Once() // SUT + act updateScheduleIndex( @@ -296,31 +225,28 @@ func TestUpdateScheduleIndex_NoReset(t *testing.T) { assert.Equal(t, dummyOldMonthIndex, dummySchedule.monthIndex) assert.Equal(t, dummyOldYear, dummySchedule.year) assert.Equal(t, dummyOldYearIndex, dummySchedule.yearIndex) - - // verify - verifyAll(t) } func TestUpdateScheduleIndex_SecondReset(t *testing.T) { // arrange - var dummyOldSecond = rand.Intn(60) - var dummyOldSecondIndex = rand.Intn(60) - var dummySeconds = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyOldMinute = rand.Intn(60) - var dummyOldMinuteIndex = rand.Intn(60) - var dummyMinutes = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyOldHour = rand.Intn(24) - var dummyOldHourIndex = rand.Intn(24) - var dummyHours = []int{rand.Intn(24), rand.Intn(24), rand.Intn(24)} - var dummyOldDay = rand.Intn(31) - var dummyOldDayIndex = rand.Intn(31) - var dummyDays = []int{rand.Intn(31), rand.Intn(31), rand.Intn(31)} - var dummyOldMonth = rand.Intn(12) - var dummyOldMonthIndex = rand.Intn(12) - var dummyMonths = []int{rand.Intn(12), rand.Intn(12), rand.Intn(12)} - var dummyOldYear = rand.Intn(100) - var dummyOldYearIndex = rand.Intn(100) - var dummyYears = []int{rand.Intn(100), rand.Intn(100), rand.Intn(100)} + var dummyOldSecond = rand.IntN(60) + var dummyOldSecondIndex = rand.IntN(60) + var dummySeconds = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyOldMinute = rand.IntN(60) + var dummyOldMinuteIndex = rand.IntN(60) + var dummyMinutes = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyOldHour = rand.IntN(24) + var dummyOldHourIndex = rand.IntN(24) + var dummyHours = []int{rand.IntN(24), rand.IntN(24), rand.IntN(24)} + var dummyOldDay = rand.IntN(31) + var dummyOldDayIndex = rand.IntN(31) + var dummyDays = []int{rand.IntN(31), rand.IntN(31), rand.IntN(31)} + var dummyOldMonth = rand.IntN(12) + var dummyOldMonthIndex = rand.IntN(12) + var dummyMonths = []int{rand.IntN(12), rand.IntN(12), rand.IntN(12)} + var dummyOldYear = rand.IntN(100) + var dummyOldYearIndex = rand.IntN(100) + var dummyYears = []int{rand.IntN(100), rand.IntN(100), rand.IntN(100)} var dummySchedule = &schedule{ second: dummyOldSecond, secondIndex: dummyOldSecondIndex, @@ -341,29 +267,17 @@ func TestUpdateScheduleIndex_SecondReset(t *testing.T) { yearIndex: dummyOldYearIndex, years: dummyYears, } - var dummyNewSecond = rand.Intn(60) - var dummyNewSecondIndex = rand.Intn(60) - var dummyNewMinute = rand.Intn(60) - var dummyNewMinuteIndex = rand.Intn(60) + var dummyNewSecond = rand.IntN(60) + var dummyNewSecondIndex = rand.IntN(60) + var dummyNewMinute = rand.IntN(60) + var dummyNewMinuteIndex = rand.IntN(60) // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - moveValueIndexFuncExpected = 2 - moveValueIndexFunc = func(oldIndex int, values []int, maxValue int) (int, int, bool) { - moveValueIndexFuncCalled++ - if moveValueIndexFuncCalled == 1 { - assert.Equal(t, dummySchedule.secondIndex, oldIndex) - assert.Equal(t, dummySchedule.seconds, values) - assert.Equal(t, 60, maxValue) - return dummyNewSecond, dummyNewSecondIndex, true - } - assert.Equal(t, dummySchedule.minuteIndex, oldIndex) - assert.Equal(t, dummySchedule.minutes, values) - assert.Equal(t, 60, maxValue) - return dummyNewMinute, dummyNewMinuteIndex, false - } + m.Mock(moveValueIndex).Expects(dummySchedule.secondIndex, dummySchedule.seconds, 60).Returns(dummyNewSecond, dummyNewSecondIndex, true).Once() + m.Mock(moveValueIndex).Expects(dummySchedule.minuteIndex, dummySchedule.minutes, 60).Returns(dummyNewMinute, dummyNewMinuteIndex, false).Once() // SUT + act updateScheduleIndex( @@ -383,31 +297,28 @@ func TestUpdateScheduleIndex_SecondReset(t *testing.T) { assert.Equal(t, dummyOldMonthIndex, dummySchedule.monthIndex) assert.Equal(t, dummyOldYear, dummySchedule.year) assert.Equal(t, dummyOldYearIndex, dummySchedule.yearIndex) - - // verify - verifyAll(t) } func TestUpdateScheduleIndex_MinuteReset(t *testing.T) { // arrange - var dummyOldSecond = rand.Intn(60) - var dummyOldSecondIndex = rand.Intn(60) - var dummySeconds = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyOldMinute = rand.Intn(60) - var dummyOldMinuteIndex = rand.Intn(60) - var dummyMinutes = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyOldHour = rand.Intn(24) - var dummyOldHourIndex = rand.Intn(24) - var dummyHours = []int{rand.Intn(24), rand.Intn(24), rand.Intn(24)} - var dummyOldDay = rand.Intn(31) - var dummyOldDayIndex = rand.Intn(31) - var dummyDays = []int{rand.Intn(31), rand.Intn(31), rand.Intn(31)} - var dummyOldMonth = rand.Intn(12) - var dummyOldMonthIndex = rand.Intn(12) - var dummyMonths = []int{rand.Intn(12), rand.Intn(12), rand.Intn(12)} - var dummyOldYear = rand.Intn(100) - var dummyOldYearIndex = rand.Intn(100) - var dummyYears = []int{rand.Intn(100), rand.Intn(100), rand.Intn(100)} + var dummyOldSecond = rand.IntN(60) + var dummyOldSecondIndex = rand.IntN(60) + var dummySeconds = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyOldMinute = rand.IntN(60) + var dummyOldMinuteIndex = rand.IntN(60) + var dummyMinutes = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyOldHour = rand.IntN(24) + var dummyOldHourIndex = rand.IntN(24) + var dummyHours = []int{rand.IntN(24), rand.IntN(24), rand.IntN(24)} + var dummyOldDay = rand.IntN(31) + var dummyOldDayIndex = rand.IntN(31) + var dummyDays = []int{rand.IntN(31), rand.IntN(31), rand.IntN(31)} + var dummyOldMonth = rand.IntN(12) + var dummyOldMonthIndex = rand.IntN(12) + var dummyMonths = []int{rand.IntN(12), rand.IntN(12), rand.IntN(12)} + var dummyOldYear = rand.IntN(100) + var dummyOldYearIndex = rand.IntN(100) + var dummyYears = []int{rand.IntN(100), rand.IntN(100), rand.IntN(100)} var dummySchedule = &schedule{ second: dummyOldSecond, secondIndex: dummyOldSecondIndex, @@ -428,36 +339,20 @@ func TestUpdateScheduleIndex_MinuteReset(t *testing.T) { yearIndex: dummyOldYearIndex, years: dummyYears, } - var dummyNewSecond = rand.Intn(60) - var dummyNewSecondIndex = rand.Intn(60) - var dummyNewMinute = rand.Intn(60) - var dummyNewMinuteIndex = rand.Intn(60) - var dummyNewHour = rand.Intn(24) - var dummyNewHourIndex = rand.Intn(24) + var dummyNewSecond = rand.IntN(60) + var dummyNewSecondIndex = rand.IntN(60) + var dummyNewMinute = rand.IntN(60) + var dummyNewMinuteIndex = rand.IntN(60) + var dummyNewHour = rand.IntN(24) + var dummyNewHourIndex = rand.IntN(24) // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - moveValueIndexFuncExpected = 3 - moveValueIndexFunc = func(oldIndex int, values []int, maxValue int) (int, int, bool) { - moveValueIndexFuncCalled++ - if moveValueIndexFuncCalled == 1 { - assert.Equal(t, dummySchedule.secondIndex, oldIndex) - assert.Equal(t, dummySchedule.seconds, values) - assert.Equal(t, 60, maxValue) - return dummyNewSecond, dummyNewSecondIndex, true - } else if moveValueIndexFuncCalled == 2 { - assert.Equal(t, dummySchedule.minuteIndex, oldIndex) - assert.Equal(t, dummySchedule.minutes, values) - assert.Equal(t, 60, maxValue) - return dummyNewMinute, dummyNewMinuteIndex, true - } - assert.Equal(t, dummySchedule.hourIndex, oldIndex) - assert.Equal(t, dummySchedule.hours, values) - assert.Equal(t, 24, maxValue) - return dummyNewHour, dummyNewHourIndex, false - } + m.Mock(moveValueIndex).Expects(dummySchedule.secondIndex, dummySchedule.seconds, 60).Returns(dummyNewSecond, dummyNewSecondIndex, true).Once() + m.Mock(moveValueIndex).Expects(dummySchedule.minuteIndex, dummySchedule.minutes, 60).Returns(dummyNewMinute, dummyNewMinuteIndex, true).Once() + m.Mock(moveValueIndex).Expects(dummySchedule.hourIndex, dummySchedule.hours, 24).Returns(dummyNewHour, dummyNewHourIndex, false).Once() // SUT + act updateScheduleIndex( @@ -477,31 +372,28 @@ func TestUpdateScheduleIndex_MinuteReset(t *testing.T) { assert.Equal(t, dummyOldMonthIndex, dummySchedule.monthIndex) assert.Equal(t, dummyOldYear, dummySchedule.year) assert.Equal(t, dummyOldYearIndex, dummySchedule.yearIndex) - - // verify - verifyAll(t) } func TestUpdateScheduleIndex_HourReset(t *testing.T) { // arrange - var dummyOldSecond = rand.Intn(60) - var dummyOldSecondIndex = rand.Intn(60) - var dummySeconds = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyOldMinute = rand.Intn(60) - var dummyOldMinuteIndex = rand.Intn(60) - var dummyMinutes = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyOldHour = rand.Intn(24) - var dummyOldHourIndex = rand.Intn(24) - var dummyHours = []int{rand.Intn(24), rand.Intn(24), rand.Intn(24)} - var dummyOldDay = rand.Intn(31) - var dummyOldDayIndex = rand.Intn(31) - var dummyDays = []int{rand.Intn(31), rand.Intn(31), rand.Intn(31)} - var dummyOldMonth = rand.Intn(12) - var dummyOldMonthIndex = rand.Intn(12) - var dummyMonths = []int{rand.Intn(12), rand.Intn(12), rand.Intn(12)} - var dummyOldYear = rand.Intn(100) - var dummyOldYearIndex = rand.Intn(100) - var dummyYears = []int{rand.Intn(100), rand.Intn(100), rand.Intn(100)} + var dummyOldSecond = rand.IntN(60) + var dummyOldSecondIndex = rand.IntN(60) + var dummySeconds = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyOldMinute = rand.IntN(60) + var dummyOldMinuteIndex = rand.IntN(60) + var dummyMinutes = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyOldHour = rand.IntN(24) + var dummyOldHourIndex = rand.IntN(24) + var dummyHours = []int{rand.IntN(24), rand.IntN(24), rand.IntN(24)} + var dummyOldDay = rand.IntN(31) + var dummyOldDayIndex = rand.IntN(31) + var dummyDays = []int{rand.IntN(31), rand.IntN(31), rand.IntN(31)} + var dummyOldMonth = rand.IntN(12) + var dummyOldMonthIndex = rand.IntN(12) + var dummyMonths = []int{rand.IntN(12), rand.IntN(12), rand.IntN(12)} + var dummyOldYear = rand.IntN(100) + var dummyOldYearIndex = rand.IntN(100) + var dummyYears = []int{rand.IntN(100), rand.IntN(100), rand.IntN(100)} var dummySchedule = &schedule{ second: dummyOldSecond, secondIndex: dummyOldSecondIndex, @@ -522,51 +414,25 @@ func TestUpdateScheduleIndex_HourReset(t *testing.T) { yearIndex: dummyOldYearIndex, years: dummyYears, } - var dummyNewSecond = rand.Intn(60) - var dummyNewSecondIndex = rand.Intn(60) - var dummyNewMinute = rand.Intn(60) - var dummyNewMinuteIndex = rand.Intn(60) - var dummyNewHour = rand.Intn(24) - var dummyNewHourIndex = rand.Intn(24) - var dummyNewDay = rand.Intn(31) - var dummyNewDayIndex = rand.Intn(31) - var dummyDaysOfMonth = rand.Intn(31) + var dummyNewSecond = rand.IntN(60) + var dummyNewSecondIndex = rand.IntN(60) + var dummyNewMinute = rand.IntN(60) + var dummyNewMinuteIndex = rand.IntN(60) + var dummyNewHour = rand.IntN(24) + var dummyNewHourIndex = rand.IntN(24) + var dummyNewDay = rand.IntN(31) + var dummyNewDayIndex = rand.IntN(31) + var dummyDaysOfMonth = rand.IntN(31) // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - moveValueIndexFuncExpected = 4 - moveValueIndexFunc = func(oldIndex int, values []int, maxValue int) (int, int, bool) { - moveValueIndexFuncCalled++ - if moveValueIndexFuncCalled == 1 { - assert.Equal(t, dummySchedule.secondIndex, oldIndex) - assert.Equal(t, dummySchedule.seconds, values) - assert.Equal(t, 60, maxValue) - return dummyNewSecond, dummyNewSecondIndex, true - } else if moveValueIndexFuncCalled == 2 { - assert.Equal(t, dummySchedule.minuteIndex, oldIndex) - assert.Equal(t, dummySchedule.minutes, values) - assert.Equal(t, 60, maxValue) - return dummyNewMinute, dummyNewMinuteIndex, true - } else if moveValueIndexFuncCalled == 3 { - assert.Equal(t, dummySchedule.hourIndex, oldIndex) - assert.Equal(t, dummySchedule.hours, values) - assert.Equal(t, 24, maxValue) - return dummyNewHour, dummyNewHourIndex, true - } - assert.Equal(t, dummySchedule.dayIndex, oldIndex) - assert.Equal(t, dummySchedule.days, values) - assert.Equal(t, dummyDaysOfMonth, maxValue) - return dummyNewDay, dummyNewDayIndex, false - } - getDaysOfMonthFuncExpected = 1 - getDaysOfMonthFunc = func(year, month int) int { - getDaysOfMonthFuncCalled++ - assert.Equal(t, dummyOldYear, year) - assert.Equal(t, dummyOldMonth, month) - return dummyDaysOfMonth - } + m.Mock(moveValueIndex).Expects(dummySchedule.secondIndex, dummySchedule.seconds, 60).Returns(dummyNewSecond, dummyNewSecondIndex, true).Once() + m.Mock(moveValueIndex).Expects(dummySchedule.minuteIndex, dummySchedule.minutes, 60).Returns(dummyNewMinute, dummyNewMinuteIndex, true).Once() + m.Mock(moveValueIndex).Expects(dummySchedule.hourIndex, dummySchedule.hours, 24).Returns(dummyNewHour, dummyNewHourIndex, true).Once() + m.Mock(moveValueIndex).Expects(dummySchedule.dayIndex, dummySchedule.days, dummyDaysOfMonth).Returns(dummyNewDay, dummyNewDayIndex, false).Once() + m.Mock(getDaysOfMonth).Expects(dummyOldYear, dummyOldMonth).Returns(dummyDaysOfMonth).Once() // SUT + act updateScheduleIndex( @@ -586,31 +452,28 @@ func TestUpdateScheduleIndex_HourReset(t *testing.T) { assert.Equal(t, dummyOldMonthIndex, dummySchedule.monthIndex) assert.Equal(t, dummyOldYear, dummySchedule.year) assert.Equal(t, dummyOldYearIndex, dummySchedule.yearIndex) - - // verify - verifyAll(t) } func TestUpdateScheduleIndex_DayReset(t *testing.T) { // arrange - var dummyOldSecond = rand.Intn(60) - var dummyOldSecondIndex = rand.Intn(60) - var dummySeconds = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyOldMinute = rand.Intn(60) - var dummyOldMinuteIndex = rand.Intn(60) - var dummyMinutes = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyOldHour = rand.Intn(24) - var dummyOldHourIndex = rand.Intn(24) - var dummyHours = []int{rand.Intn(24), rand.Intn(24), rand.Intn(24)} - var dummyOldDay = rand.Intn(31) - var dummyOldDayIndex = rand.Intn(31) - var dummyDays = []int{rand.Intn(31), rand.Intn(31), rand.Intn(31)} - var dummyOldMonth = rand.Intn(12) - var dummyOldMonthIndex = rand.Intn(12) - var dummyMonths = []int{rand.Intn(12), rand.Intn(12), rand.Intn(12)} - var dummyOldYear = rand.Intn(100) - var dummyOldYearIndex = rand.Intn(100) - var dummyYears = []int{rand.Intn(100), rand.Intn(100), rand.Intn(100)} + var dummyOldSecond = rand.IntN(60) + var dummyOldSecondIndex = rand.IntN(60) + var dummySeconds = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyOldMinute = rand.IntN(60) + var dummyOldMinuteIndex = rand.IntN(60) + var dummyMinutes = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyOldHour = rand.IntN(24) + var dummyOldHourIndex = rand.IntN(24) + var dummyHours = []int{rand.IntN(24), rand.IntN(24), rand.IntN(24)} + var dummyOldDay = rand.IntN(31) + var dummyOldDayIndex = rand.IntN(31) + var dummyDays = []int{rand.IntN(31), rand.IntN(31), rand.IntN(31)} + var dummyOldMonth = rand.IntN(12) + var dummyOldMonthIndex = rand.IntN(12) + var dummyMonths = []int{rand.IntN(12), rand.IntN(12), rand.IntN(12)} + var dummyOldYear = rand.IntN(100) + var dummyOldYearIndex = rand.IntN(100) + var dummyYears = []int{rand.IntN(100), rand.IntN(100), rand.IntN(100)} var dummySchedule = &schedule{ second: dummyOldSecond, secondIndex: dummyOldSecondIndex, @@ -631,58 +494,28 @@ func TestUpdateScheduleIndex_DayReset(t *testing.T) { yearIndex: dummyOldYearIndex, years: dummyYears, } - var dummyNewSecond = rand.Intn(60) - var dummyNewSecondIndex = rand.Intn(60) - var dummyNewMinute = rand.Intn(60) - var dummyNewMinuteIndex = rand.Intn(60) - var dummyNewHour = rand.Intn(24) - var dummyNewHourIndex = rand.Intn(24) - var dummyNewDay = rand.Intn(31) - var dummyNewDayIndex = rand.Intn(31) - var dummyDaysOfMonth = rand.Intn(31) - var dummyNewMonth = rand.Intn(31) - var dummyNewMonthIndex = rand.Intn(31) + var dummyNewSecond = rand.IntN(60) + var dummyNewSecondIndex = rand.IntN(60) + var dummyNewMinute = rand.IntN(60) + var dummyNewMinuteIndex = rand.IntN(60) + var dummyNewHour = rand.IntN(24) + var dummyNewHourIndex = rand.IntN(24) + var dummyNewDay = rand.IntN(31) + var dummyNewDayIndex = rand.IntN(31) + var dummyDaysOfMonth = rand.IntN(31) + var dummyNewMonth = rand.IntN(31) + var dummyNewMonthIndex = rand.IntN(31) // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - moveValueIndexFuncExpected = 5 - moveValueIndexFunc = func(oldIndex int, values []int, maxValue int) (int, int, bool) { - moveValueIndexFuncCalled++ - if moveValueIndexFuncCalled == 1 { - assert.Equal(t, dummySchedule.secondIndex, oldIndex) - assert.Equal(t, dummySchedule.seconds, values) - assert.Equal(t, 60, maxValue) - return dummyNewSecond, dummyNewSecondIndex, true - } else if moveValueIndexFuncCalled == 2 { - assert.Equal(t, dummySchedule.minuteIndex, oldIndex) - assert.Equal(t, dummySchedule.minutes, values) - assert.Equal(t, 60, maxValue) - return dummyNewMinute, dummyNewMinuteIndex, true - } else if moveValueIndexFuncCalled == 3 { - assert.Equal(t, dummySchedule.hourIndex, oldIndex) - assert.Equal(t, dummySchedule.hours, values) - assert.Equal(t, 24, maxValue) - return dummyNewHour, dummyNewHourIndex, true - } else if moveValueIndexFuncCalled == 4 { - assert.Equal(t, dummySchedule.dayIndex, oldIndex) - assert.Equal(t, dummySchedule.days, values) - assert.Equal(t, dummyDaysOfMonth, maxValue) - return dummyNewDay, dummyNewDayIndex, true - } - assert.Equal(t, dummySchedule.monthIndex, oldIndex) - assert.Equal(t, dummySchedule.months, values) - assert.Equal(t, 12, maxValue) - return dummyNewMonth, dummyNewMonthIndex, false - } - getDaysOfMonthFuncExpected = 1 - getDaysOfMonthFunc = func(year, month int) int { - getDaysOfMonthFuncCalled++ - assert.Equal(t, dummyOldYear, year) - assert.Equal(t, dummyOldMonth, month) - return dummyDaysOfMonth - } + m.Mock(moveValueIndex).Expects(dummySchedule.secondIndex, dummySchedule.seconds, 60).Returns(dummyNewSecond, dummyNewSecondIndex, true).Once() + m.Mock(moveValueIndex).Expects(dummySchedule.minuteIndex, dummySchedule.minutes, 60).Returns(dummyNewMinute, dummyNewMinuteIndex, true).Once() + m.Mock(moveValueIndex).Expects(dummySchedule.hourIndex, dummySchedule.hours, 24).Returns(dummyNewHour, dummyNewHourIndex, true).Once() + m.Mock(moveValueIndex).Expects(dummySchedule.dayIndex, dummySchedule.days, dummyDaysOfMonth).Returns(dummyNewDay, dummyNewDayIndex, true).Once() + m.Mock(moveValueIndex).Expects(dummySchedule.monthIndex, dummySchedule.months, 12).Returns(dummyNewMonth, dummyNewMonthIndex, false).Once() + m.Mock(getDaysOfMonth).Expects(dummyOldYear, dummyOldMonth).Returns(dummyDaysOfMonth).Once() // SUT + act updateScheduleIndex( @@ -702,31 +535,28 @@ func TestUpdateScheduleIndex_DayReset(t *testing.T) { assert.Equal(t, dummyNewMonthIndex, dummySchedule.monthIndex) assert.Equal(t, dummyOldYear, dummySchedule.year) assert.Equal(t, dummyOldYearIndex, dummySchedule.yearIndex) - - // verify - verifyAll(t) } func TestUpdateScheduleIndex_MonthReset(t *testing.T) { // arrange - var dummyOldSecond = rand.Intn(60) - var dummyOldSecondIndex = rand.Intn(60) - var dummySeconds = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyOldMinute = rand.Intn(60) - var dummyOldMinuteIndex = rand.Intn(60) - var dummyMinutes = []int{rand.Intn(60), rand.Intn(60), rand.Intn(60)} - var dummyOldHour = rand.Intn(24) - var dummyOldHourIndex = rand.Intn(24) - var dummyHours = []int{rand.Intn(24), rand.Intn(24), rand.Intn(24)} - var dummyOldDay = rand.Intn(31) - var dummyOldDayIndex = rand.Intn(31) - var dummyDays = []int{rand.Intn(31), rand.Intn(31), rand.Intn(31)} - var dummyOldMonth = rand.Intn(12) - var dummyOldMonthIndex = rand.Intn(12) - var dummyMonths = []int{rand.Intn(12), rand.Intn(12), rand.Intn(12)} - var dummyOldYear = rand.Intn(100) - var dummyOldYearIndex = rand.Intn(100) - var dummyYears = []int{rand.Intn(100), rand.Intn(100), rand.Intn(100)} + var dummyOldSecond = rand.IntN(60) + var dummyOldSecondIndex = rand.IntN(60) + var dummySeconds = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyOldMinute = rand.IntN(60) + var dummyOldMinuteIndex = rand.IntN(60) + var dummyMinutes = []int{rand.IntN(60), rand.IntN(60), rand.IntN(60)} + var dummyOldHour = rand.IntN(24) + var dummyOldHourIndex = rand.IntN(24) + var dummyHours = []int{rand.IntN(24), rand.IntN(24), rand.IntN(24)} + var dummyOldDay = rand.IntN(31) + var dummyOldDayIndex = rand.IntN(31) + var dummyDays = []int{rand.IntN(31), rand.IntN(31), rand.IntN(31)} + var dummyOldMonth = rand.IntN(12) + var dummyOldMonthIndex = rand.IntN(12) + var dummyMonths = []int{rand.IntN(12), rand.IntN(12), rand.IntN(12)} + var dummyOldYear = rand.IntN(100) + var dummyOldYearIndex = rand.IntN(100) + var dummyYears = []int{rand.IntN(100), rand.IntN(100), rand.IntN(100)} var dummySchedule = &schedule{ second: dummyOldSecond, secondIndex: dummyOldSecondIndex, @@ -747,65 +577,31 @@ func TestUpdateScheduleIndex_MonthReset(t *testing.T) { yearIndex: dummyOldYearIndex, years: dummyYears, } - var dummyNewSecond = rand.Intn(60) - var dummyNewSecondIndex = rand.Intn(60) - var dummyNewMinute = rand.Intn(60) - var dummyNewMinuteIndex = rand.Intn(60) - var dummyNewHour = rand.Intn(24) - var dummyNewHourIndex = rand.Intn(24) - var dummyNewDay = rand.Intn(31) - var dummyNewDayIndex = rand.Intn(31) - var dummyDaysOfMonth = rand.Intn(31) - var dummyNewMonth = rand.Intn(31) - var dummyNewMonthIndex = rand.Intn(31) - var dummyNewYear = rand.Intn(100) - var dummyNewYearIndex = rand.Intn(100) + var dummyNewSecond = rand.IntN(60) + var dummyNewSecondIndex = rand.IntN(60) + var dummyNewMinute = rand.IntN(60) + var dummyNewMinuteIndex = rand.IntN(60) + var dummyNewHour = rand.IntN(24) + var dummyNewHourIndex = rand.IntN(24) + var dummyNewDay = rand.IntN(31) + var dummyNewDayIndex = rand.IntN(31) + var dummyDaysOfMonth = rand.IntN(31) + var dummyNewMonth = rand.IntN(31) + var dummyNewMonthIndex = rand.IntN(31) + var dummyNewYear = rand.IntN(100) + var dummyNewYearIndex = rand.IntN(100) // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - moveValueIndexFuncExpected = 6 - moveValueIndexFunc = func(oldIndex int, values []int, maxValue int) (int, int, bool) { - moveValueIndexFuncCalled++ - if moveValueIndexFuncCalled == 1 { - assert.Equal(t, dummySchedule.secondIndex, oldIndex) - assert.Equal(t, dummySchedule.seconds, values) - assert.Equal(t, 60, maxValue) - return dummyNewSecond, dummyNewSecondIndex, true - } else if moveValueIndexFuncCalled == 2 { - assert.Equal(t, dummySchedule.minuteIndex, oldIndex) - assert.Equal(t, dummySchedule.minutes, values) - assert.Equal(t, 60, maxValue) - return dummyNewMinute, dummyNewMinuteIndex, true - } else if moveValueIndexFuncCalled == 3 { - assert.Equal(t, dummySchedule.hourIndex, oldIndex) - assert.Equal(t, dummySchedule.hours, values) - assert.Equal(t, 24, maxValue) - return dummyNewHour, dummyNewHourIndex, true - } else if moveValueIndexFuncCalled == 4 { - assert.Equal(t, dummySchedule.dayIndex, oldIndex) - assert.Equal(t, dummySchedule.days, values) - assert.Equal(t, dummyDaysOfMonth, maxValue) - return dummyNewDay, dummyNewDayIndex, true - } else if moveValueIndexFuncCalled == 5 { - assert.Equal(t, dummySchedule.monthIndex, oldIndex) - assert.Equal(t, dummySchedule.months, values) - assert.Equal(t, 12, maxValue) - return dummyNewMonth, dummyNewMonthIndex, true - } - assert.Equal(t, dummySchedule.yearIndex, oldIndex) - assert.Equal(t, dummySchedule.years, values) - assert.Equal(t, 9999, maxValue) - return dummyNewYear, dummyNewYearIndex, rand.Intn(100) > 50 - } - getDaysOfMonthFuncExpected = 1 - getDaysOfMonthFunc = func(year, month int) int { - getDaysOfMonthFuncCalled++ - assert.Equal(t, dummyOldYear, year) - assert.Equal(t, dummyOldMonth, month) - return dummyDaysOfMonth - } + m.Mock(moveValueIndex).Expects(dummySchedule.secondIndex, dummySchedule.seconds, 60).Returns(dummyNewSecond, dummyNewSecondIndex, true).Once() + m.Mock(moveValueIndex).Expects(dummySchedule.minuteIndex, dummySchedule.minutes, 60).Returns(dummyNewMinute, dummyNewMinuteIndex, true).Once() + m.Mock(moveValueIndex).Expects(dummySchedule.hourIndex, dummySchedule.hours, 24).Returns(dummyNewHour, dummyNewHourIndex, true).Once() + m.Mock(moveValueIndex).Expects(dummySchedule.dayIndex, dummySchedule.days, dummyDaysOfMonth).Returns(dummyNewDay, dummyNewDayIndex, true).Once() + m.Mock(moveValueIndex).Expects(dummySchedule.monthIndex, dummySchedule.months, 12).Returns(dummyNewMonth, dummyNewMonthIndex, true).Once() + m.Mock(moveValueIndex).Expects(dummySchedule.yearIndex, dummySchedule.years, 9999).Returns(dummyNewYear, dummyNewYearIndex, rand.IntN(100) > 50).Once() + m.Mock(getDaysOfMonth).Expects(dummyOldYear, dummyOldMonth).Returns(dummyDaysOfMonth).Once() // SUT + act updateScheduleIndex( @@ -825,25 +621,11 @@ func TestUpdateScheduleIndex_MonthReset(t *testing.T) { assert.Equal(t, dummyNewMonthIndex, dummySchedule.monthIndex) assert.Equal(t, dummyNewYear, dummySchedule.year) assert.Equal(t, dummyNewYearIndex, dummySchedule.yearIndex) - - // verify - verifyAll(t) } func TestNextSchedule_ExceededTillTime(t *testing.T) { // arrange - var dummyCurrentLocalTime = time.Now() - var dummyTill = dummyCurrentLocalTime.Add(-1 * time.Second) - - // mock - createMock(t) - - // expect - timeNowExpected = 1 - timeNow = func() time.Time { - timeNowCalled++ - return dummyCurrentLocalTime - } + var dummyTill = time.Now().Add(-10 * time.Second) // SUT var sut = &schedule{ @@ -855,25 +637,9 @@ func TestNextSchedule_ExceededTillTime(t *testing.T) { // assert assert.Nil(t, result) - - // verify - verifyAll(t) } func TestNextSchedule_AlreadyCompleted(t *testing.T) { - // arrange - var dummyCurrentLocalTime = time.Now() - - // mock - createMock(t) - - // expect - timeNowExpected = 1 - timeNow = func() time.Time { - timeNowCalled++ - return dummyCurrentLocalTime - } - // SUT var sut = &schedule{ completed: true, @@ -884,39 +650,20 @@ func TestNextSchedule_AlreadyCompleted(t *testing.T) { // assert assert.Nil(t, result) - - // verify - verifyAll(t) } func TestNextSchedule_NextInFuture(t *testing.T) { // arrange - var dummyCurrentLocalTime = time.Now() var dummySchedule = &schedule{} - var dummyTimeNext = dummyCurrentLocalTime.Add(1 * time.Second) - var dummyCompleted = rand.Intn(100) > 50 + var dummyTimeNext = time.Now().Add(10 * time.Second) + var dummyCompleted = rand.IntN(100) > 50 // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - timeNowExpected = 1 - timeNow = func() time.Time { - timeNowCalled++ - return dummyCurrentLocalTime - } - constructTimeByScheduleFuncExpected = 1 - constructTimeByScheduleFunc = func(schedule *schedule) time.Time { - constructTimeByScheduleFuncCalled++ - assert.Equal(t, dummySchedule, schedule) - return dummyTimeNext - } - updateScheduleIndexFuncExpected = 1 - updateScheduleIndexFunc = func(schedule *schedule) bool { - updateScheduleIndexFuncCalled++ - assert.Equal(t, dummySchedule, schedule) - return dummyCompleted - } + m.Mock(constructTimeBySchedule).Expects(dummySchedule).Returns(dummyTimeNext).Once() + m.Mock(updateScheduleIndex).Expects(dummySchedule).Returns(dummyCompleted).Once() // SUT var sut = dummySchedule @@ -927,41 +674,22 @@ func TestNextSchedule_NextInFuture(t *testing.T) { // assert assert.Equal(t, dummyTimeNext, *result) assert.Equal(t, dummyCompleted, dummySchedule.completed) - - // verify - verifyAll(t) } func TestNextSchedule_NextInPast_NoSkipOverdue(t *testing.T) { // arrange - var dummyCurrentLocalTime = time.Now() var dummySchedule = &schedule{ skipOverdue: false, } - var dummyTimeNext = dummyCurrentLocalTime.Add(-1 * time.Second) - var dummyCompleted = rand.Intn(100) > 50 + var dummyTimeNext = time.Now().Add(-10 * time.Second) + var dummyCompleted = rand.IntN(100) > 50 // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - timeNowExpected = 1 - timeNow = func() time.Time { - timeNowCalled++ - return dummyCurrentLocalTime - } - constructTimeByScheduleFuncExpected = 1 - constructTimeByScheduleFunc = func(schedule *schedule) time.Time { - constructTimeByScheduleFuncCalled++ - assert.Equal(t, dummySchedule, schedule) - return dummyTimeNext - } - updateScheduleIndexFuncExpected = 1 - updateScheduleIndexFunc = func(schedule *schedule) bool { - updateScheduleIndexFuncCalled++ - assert.Equal(t, dummySchedule, schedule) - return dummyCompleted - } + m.Mock(constructTimeBySchedule).Expects(dummySchedule).Returns(dummyTimeNext).Once() + m.Mock(updateScheduleIndex).Expects(dummySchedule).Returns(dummyCompleted).Once() // SUT var sut = dummySchedule @@ -972,41 +700,22 @@ func TestNextSchedule_NextInPast_NoSkipOverdue(t *testing.T) { // assert assert.Equal(t, dummyTimeNext, *result) assert.Equal(t, dummyCompleted, dummySchedule.completed) - - // verify - verifyAll(t) } func TestNextSchedule_NextInPast_SkipOverdue_Completed(t *testing.T) { // arrange - var dummyCurrentLocalTime = time.Now() var dummySchedule = &schedule{ skipOverdue: true, } - var dummyTimeNext = dummyCurrentLocalTime.Add(-1 * time.Second) + var dummyTimeNext = time.Now().Add(-10 * time.Second) var dummyCompleted = true // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - timeNowExpected = 1 - timeNow = func() time.Time { - timeNowCalled++ - return dummyCurrentLocalTime - } - constructTimeByScheduleFuncExpected = 1 - constructTimeByScheduleFunc = func(schedule *schedule) time.Time { - constructTimeByScheduleFuncCalled++ - assert.Equal(t, dummySchedule, schedule) - return dummyTimeNext - } - updateScheduleIndexFuncExpected = 1 - updateScheduleIndexFunc = func(schedule *schedule) bool { - updateScheduleIndexFuncCalled++ - assert.Equal(t, dummySchedule, schedule) - return dummyCompleted - } + m.Mock(constructTimeBySchedule).Expects(dummySchedule).Returns(dummyTimeNext).Once() + m.Mock(updateScheduleIndex).Expects(dummySchedule).Returns(dummyCompleted).Once() // SUT var sut = dummySchedule @@ -1017,47 +726,24 @@ func TestNextSchedule_NextInPast_SkipOverdue_Completed(t *testing.T) { // assert assert.Nil(t, result) assert.True(t, dummySchedule.completed) - - // verify - verifyAll(t) } func TestNextSchedule_NextInPast_SkipOverdue_NotCompleted(t *testing.T) { // arrange - var dummyCurrentLocalTime = time.Now() var dummySchedule = &schedule{ skipOverdue: true, } - var dummyTimeNextInPast = dummyCurrentLocalTime.Add(-1 * time.Second) - var dummyTimeNextInFuture = dummyCurrentLocalTime.Add(1 * time.Second) + var dummyTimeNextInPast = time.Now().Add(-10 * time.Second) + var dummyTimeNextInFuture = time.Now().Add(10 * time.Second) var dummyCompleted = false // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - timeNowExpected = 1 - timeNow = func() time.Time { - timeNowCalled++ - return dummyCurrentLocalTime - } - constructTimeByScheduleFuncExpected = 2 - constructTimeByScheduleFunc = func(schedule *schedule) time.Time { - constructTimeByScheduleFuncCalled++ - assert.Equal(t, dummySchedule, schedule) - if constructTimeByScheduleFuncCalled == 1 { - return dummyTimeNextInPast - } else if constructTimeByScheduleFuncCalled == 2 { - return dummyTimeNextInFuture - } - return time.Time{} - } - updateScheduleIndexFuncExpected = 2 - updateScheduleIndexFunc = func(schedule *schedule) bool { - updateScheduleIndexFuncCalled++ - assert.Equal(t, dummySchedule, schedule) - return dummyCompleted - } + m.Mock(constructTimeBySchedule).Expects(dummySchedule).Returns(dummyTimeNextInPast).Once() + m.Mock(constructTimeBySchedule).Expects(dummySchedule).Returns(dummyTimeNextInFuture).Once() + m.Mock(updateScheduleIndex).Expects(dummySchedule).Returns(dummyCompleted).Twice() // SUT var sut = dummySchedule @@ -1068,7 +754,4 @@ func TestNextSchedule_NextInPast_SkipOverdue_NotCompleted(t *testing.T) { // assert assert.Equal(t, dummyTimeNextInFuture, *result) assert.False(t, dummySchedule.completed) - - // verify - verifyAll(t) } diff --git a/session.go b/session.go index d75f2a8..1b4c244 100644 --- a/session.go +++ b/session.go @@ -1,6 +1,10 @@ package jobrunner import ( + "encoding/json" + "runtime" + "strconv" + "github.com/google/uuid" ) @@ -139,11 +143,11 @@ func (session *session) GetAttachment(name string, dataTemplate interface{}) boo if !found { return false } - var bytes, marshalError = jsonMarshal(attachment) + var bytes, marshalError = json.Marshal(attachment) if marshalError != nil { return false } - var unmarshalError = jsonUnmarshal( + var unmarshalError = json.Unmarshal( bytes, dataTemplate, ) @@ -151,18 +155,18 @@ func (session *session) GetAttachment(name string, dataTemplate interface{}) boo } func getMethodName() string { - var pc, _, _, ok = runtimeCaller(3) + var pc, _, _, ok = runtime.Caller(3) if !ok { return "?" } - var fn = runtimeFuncForPC(pc) + var fn = runtime.FuncForPC(pc) return fn.Name() } // LogMethodEnter sends a logging entry of MethodEnter log type for the given session associated to the session ID func (session *session) LogMethodEnter() { - var methodName = getMethodNameFunc() - logMethodEnterFunc( + var methodName = getMethodName() + logMethodEnter( session, methodName, "", @@ -172,12 +176,12 @@ func (session *session) LogMethodEnter() { // LogMethodParameter sends a logging entry of MethodParameter log type for the given session associated to the session ID func (session *session) LogMethodParameter(parameters ...interface{}) { - var methodName = getMethodNameFunc() + var methodName = getMethodName() for index, parameter := range parameters { - logMethodParameterFunc( + logMethodParameter( session, methodName, - strconvItoa(index), + strconv.Itoa(index), "%v", parameter, ) @@ -186,7 +190,7 @@ func (session *session) LogMethodParameter(parameters ...interface{}) { // LogMethodLogic sends a logging entry of MethodLogic log type for the given session associated to the session ID func (session *session) LogMethodLogic(logLevel LogLevel, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logMethodLogicFunc( + logMethodLogic( session, logLevel, category, @@ -198,12 +202,12 @@ func (session *session) LogMethodLogic(logLevel LogLevel, category string, subca // LogMethodReturn sends a logging entry of MethodReturn log type for the given session associated to the session ID func (session *session) LogMethodReturn(returns ...interface{}) { - var methodName = getMethodNameFunc() + var methodName = getMethodName() for index, returnValue := range returns { - logMethodReturnFunc( + logMethodReturn( session, methodName, - strconvItoa(index), + strconv.Itoa(index), "%v", returnValue, ) @@ -212,8 +216,8 @@ func (session *session) LogMethodReturn(returns ...interface{}) { // LogMethodExit sends a logging entry of MethodExit log type for the given session associated to the session ID func (session *session) LogMethodExit() { - var methodName = getMethodNameFunc() - logMethodExitFunc( + var methodName = getMethodName() + logMethodExit( session, methodName, "", diff --git a/session_test.go b/session_test.go index 9fc9ec8..218a041 100644 --- a/session_test.go +++ b/session_test.go @@ -3,19 +3,16 @@ package jobrunner import ( "encoding/json" "errors" - "math/rand" + "math/rand/v2" "runtime" - "strconv" "testing" "github.com/google/uuid" "github.com/stretchr/testify/assert" + "github.com/zhongjie-cai/gomocker/v2" ) func TestSessionGetID_NilSessionObject(t *testing.T) { - // mock - createMock(t) - // SUT var dummySession *session @@ -24,18 +21,12 @@ func TestSessionGetID_NilSessionObject(t *testing.T) { // assert assert.Zero(t, result) - - // verify - verifyAll(t) } func TestSessionGetID_ValidSessionObject(t *testing.T) { // arrange var dummySessionID = uuid.New() - // mock - createMock(t) - // SUT var dummySession = &session{ id: dummySessionID, @@ -46,15 +37,9 @@ func TestSessionGetID_ValidSessionObject(t *testing.T) { // assert assert.Equal(t, dummySessionID, result) - - // verify - verifyAll(t) } func TestSessionGetIndex_NilSessionObject(t *testing.T) { - // mock - createMock(t) - // SUT var dummySession *session @@ -63,18 +48,12 @@ func TestSessionGetIndex_NilSessionObject(t *testing.T) { // assert assert.Zero(t, result) - - // verify - verifyAll(t) } func TestSessionGetIndex_ValidSessionObject(t *testing.T) { // arrange var dummyIndex = rand.Int() - // mock - createMock(t) - // SUT var dummySession = &session{ index: dummyIndex, @@ -85,29 +64,49 @@ func TestSessionGetIndex_ValidSessionObject(t *testing.T) { // assert assert.Equal(t, dummyIndex, result) +} + +func TestSessionGetReruns_NilSessionObject(t *testing.T) { + // SUT + var dummySession *session + + // act + var result = dummySession.GetReruns() - // verify - verifyAll(t) + // assert + assert.Zero(t, result) } -type dummyAttachment struct { - ID uuid.UUID - Foo string - Test int +func TestSessionGetReruns_ValidSessionObject(t *testing.T) { + // arrange + var dummyIndex = rand.Int() + + // SUT + var dummySession = &session{ + reruns: dummyIndex, + } + + // act + var result = dummySession.GetReruns() + + // assert + assert.Equal(t, dummyIndex, result) } func TestSessionAttach_NilSessionObject(t *testing.T) { // arrange + type dummyAttachment struct { + ID uuid.UUID + Foo string + Test int + } var dummyName = "some name" var dummyValue = dummyAttachment{ ID: uuid.New(), Foo: "bar", - Test: rand.Intn(100), + Test: rand.IntN(100), } - // mock - createMock(t) - // SUT var dummySession *session @@ -119,23 +118,22 @@ func TestSessionAttach_NilSessionObject(t *testing.T) { // assert assert.False(t, result) - - // verify - verifyAll(t) } func TestSessionAttach_NoAttachment(t *testing.T) { // arrange + type dummyAttachment struct { + ID uuid.UUID + Foo string + Test int + } var dummyName = "some name" var dummyValue = dummyAttachment{ ID: uuid.New(), Foo: "bar", - Test: rand.Intn(100), + Test: rand.IntN(100), } - // mock - createMock(t) - // SUT var dummySession = &session{ attachment: nil, @@ -150,23 +148,22 @@ func TestSessionAttach_NoAttachment(t *testing.T) { // assert assert.True(t, result) assert.Equal(t, dummyValue, dummySession.attachment[dummyName]) - - // verify - verifyAll(t) } func TestSessionAttach_WithAttachment(t *testing.T) { // arrange + type dummyAttachment struct { + ID uuid.UUID + Foo string + Test int + } var dummyName = "some name" var dummyValue = dummyAttachment{ ID: uuid.New(), Foo: "bar", - Test: rand.Intn(100), + Test: rand.IntN(100), } - // mock - createMock(t) - // SUT var dummySession = &session{ attachment: map[string]interface{}{ @@ -183,18 +180,12 @@ func TestSessionAttach_WithAttachment(t *testing.T) { // assert assert.True(t, result) assert.Equal(t, dummyValue, dummySession.attachment[dummyName]) - - // verify - verifyAll(t) } func TestSessionDetach_NilSessionObject(t *testing.T) { // arrange var dummyName = "some name" - // mock - createMock(t) - // SUT var dummySession *session @@ -205,18 +196,12 @@ func TestSessionDetach_NilSessionObject(t *testing.T) { // assert assert.False(t, result) - - // verify - verifyAll(t) } func TestSessionDetach_NoAttachment(t *testing.T) { // arrange var dummyName = "some name" - // mock - createMock(t) - // SUT var dummySession = &session{ attachment: nil, @@ -231,18 +216,12 @@ func TestSessionDetach_NoAttachment(t *testing.T) { assert.True(t, result) var _, found = dummySession.attachment[dummyName] assert.False(t, found) - - // verify - verifyAll(t) } func TestSessionDetach_WithAttachment(t *testing.T) { // arrange var dummyName = "some name" - // mock - createMock(t) - // SUT var dummySession = &session{ attachment: map[string]interface{}{ @@ -259,18 +238,12 @@ func TestSessionDetach_WithAttachment(t *testing.T) { assert.True(t, result) var _, found = dummySession.attachment[dummyName] assert.False(t, found) - - // verify - verifyAll(t) } func TestSessionGetRawAttachment_NoSession(t *testing.T) { // arrange var dummyName = "some name" - // mock - createMock(t) - // SUT var dummySession *session @@ -282,18 +255,12 @@ func TestSessionGetRawAttachment_NoSession(t *testing.T) { // assert assert.Nil(t, result) assert.False(t, found) - - // verify - verifyAll(t) } func TestSessionGetRawAttachment_NoAttachment(t *testing.T) { // arrange var dummyName = "some name" - // mock - createMock(t) - // SUT var dummySession = &session{} @@ -305,23 +272,22 @@ func TestSessionGetRawAttachment_NoAttachment(t *testing.T) { // assert assert.Nil(t, result) assert.False(t, found) - - // verify - verifyAll(t) } func TestSessionGetRawAttachment_Success(t *testing.T) { // arrange + type dummyAttachment struct { + ID uuid.UUID + Foo string + Test int + } var dummyName = "some name" var dummyValue = dummyAttachment{ - Foo: "bar", - Test: rand.Intn(100), ID: uuid.New(), + Foo: "bar", + Test: rand.IntN(100), } - // mock - createMock(t) - // SUT var dummySession = &session{ attachment: map[string]interface{}{ @@ -337,18 +303,12 @@ func TestSessionGetRawAttachment_Success(t *testing.T) { // assert assert.Equal(t, dummyValue, result) assert.True(t, found) - - // verify - verifyAll(t) } func TestSessionGetAttachment_NoSession(t *testing.T) { // arrange var dummyName = "some name" - var dummyDataTemplate dummyAttachment - - // mock - createMock(t) + var dummyDataTemplate map[string]interface{} // SUT var dummySession *session @@ -361,20 +321,19 @@ func TestSessionGetAttachment_NoSession(t *testing.T) { // assert assert.False(t, result) - assert.Zero(t, dummyDataTemplate) - - // verify - verifyAll(t) + assert.Zero(t, result) } func TestSessionGetAttachment_NoAttachment(t *testing.T) { // arrange + type dummyAttachment struct { + ID uuid.UUID + Foo string + Test int + } var dummyName = "some name" var dummyDataTemplate dummyAttachment - // mock - createMock(t) - // SUT var dummySession = &session{} @@ -386,32 +345,29 @@ func TestSessionGetAttachment_NoAttachment(t *testing.T) { // assert assert.False(t, result) - assert.Zero(t, dummyDataTemplate) - - // verify - verifyAll(t) + assert.Zero(t, result) } func TestSessionGetAttachment_MarshalError(t *testing.T) { // arrange + type dummyAttachment struct { + ID uuid.UUID + Foo string + Test int + } var dummyName = "some name" var dummyValue = dummyAttachment{ Foo: "bar", - Test: rand.Intn(100), + Test: rand.IntN(100), ID: uuid.New(), } var dummyDataTemplate dummyAttachment // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - jsonMarshalExpected = 1 - jsonMarshal = func(v interface{}) ([]byte, error) { - jsonMarshalCalled++ - assert.Equal(t, dummyValue, v) - return nil, errors.New("some marshal error") - } + m.Mock(json.Marshal).Expects(dummyValue).Returns(nil, errors.New("some marshal error")).Once() // SUT var dummySession = &session{ @@ -428,38 +384,24 @@ func TestSessionGetAttachment_MarshalError(t *testing.T) { // assert assert.False(t, result) - assert.Zero(t, dummyDataTemplate) - - // verify - verifyAll(t) + assert.Zero(t, result) } func TestSessionGetAttachment_UnmarshalError(t *testing.T) { // arrange + type dummyAttachment struct { + ID uuid.UUID + Foo string + Test int + } var dummyName = "some name" var dummyValue = dummyAttachment{ Foo: "bar", - Test: rand.Intn(100), + Test: rand.IntN(100), ID: uuid.New(), } var dummyDataTemplate int - // mock - createMock(t) - - // expect - jsonMarshalExpected = 1 - jsonMarshal = func(v interface{}) ([]byte, error) { - jsonMarshalCalled++ - assert.Equal(t, dummyValue, v) - return json.Marshal(v) - } - jsonUnmarshalExpected = 1 - jsonUnmarshal = func(data []byte, v interface{}) error { - jsonUnmarshalCalled++ - return json.Unmarshal(data, v) - } - // SUT var dummySession = &session{ attachment: map[string]interface{}{ @@ -475,38 +417,24 @@ func TestSessionGetAttachment_UnmarshalError(t *testing.T) { // assert assert.False(t, result) - assert.Zero(t, dummyDataTemplate) - - // verify - verifyAll(t) + assert.Zero(t, result) } func TestSessionGetAttachment_Success(t *testing.T) { // arrange + type dummyAttachment struct { + ID uuid.UUID + Foo string + Test int + } var dummyName = "some name" var dummyValue = dummyAttachment{ Foo: "bar", - Test: rand.Intn(100), + Test: rand.IntN(100), ID: uuid.New(), } var dummyDataTemplate dummyAttachment - // mock - createMock(t) - - // expect - jsonMarshalExpected = 1 - jsonMarshal = func(v interface{}) ([]byte, error) { - jsonMarshalCalled++ - assert.Equal(t, dummyValue, v) - return json.Marshal(v) - } - jsonUnmarshalExpected = 1 - jsonUnmarshal = func(data []byte, v interface{}) error { - jsonUnmarshalCalled++ - return json.Unmarshal(data, v) - } - // SUT var dummySession = &session{ attachment: map[string]interface{}{ @@ -523,9 +451,6 @@ func TestSessionGetAttachment_Success(t *testing.T) { // assert assert.True(t, result) assert.Equal(t, dummyValue, dummyDataTemplate) - - // verify - verifyAll(t) } func TestSessionGetMethodName_UnknownCaller(t *testing.T) { @@ -536,52 +461,24 @@ func TestSessionGetMethodName_UnknownCaller(t *testing.T) { var dummyOK = false // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - runtimeCallerExpected = 1 - runtimeCaller = func(skip int) (pc uintptr, file string, line int, ok bool) { - runtimeCallerCalled++ - assert.Equal(t, 3, skip) - return dummyPC, dummyFile, dummyLine, dummyOK - } + m.Mock(runtime.Caller).Expects(3).Returns(dummyPC, dummyFile, dummyLine, dummyOK).Once() // SUT + act var result = getMethodName() // assert assert.Equal(t, "?", result) - - // verify - verifyAll(t) } func TestSessionGetMethodName_HappyPath(t *testing.T) { - // mock - createMock(t) - - // expect - runtimeCallerExpected = 1 - runtimeCaller = func(skip int) (pc uintptr, file string, line int, ok bool) { - runtimeCallerCalled++ - assert.Equal(t, 3, skip) - return runtime.Caller(2) - } - runtimeFuncForPCExpected = 1 - runtimeFuncForPC = func(pc uintptr) *runtime.Func { - runtimeFuncForPCCalled++ - assert.NotZero(t, pc) - return runtime.FuncForPC(pc) - } - // SUT + act var result = getMethodName() // assert - assert.Contains(t, result, "TestSessionGetMethodName_HappyPath") - - // verify - verifyAll(t) + assert.Contains(t, result, "runtime.goexit") } func TestSessionLogMethodEnter(t *testing.T) { @@ -590,7 +487,7 @@ func TestSessionLogMethodEnter(t *testing.T) { var dummyMethodName = "some method name" // mock - createMock(t) + var m = gomocker.NewMocker(t) // SUT var dummySession = &session{ @@ -598,26 +495,11 @@ func TestSessionLogMethodEnter(t *testing.T) { } // expect - getMethodNameFuncExpected = 1 - getMethodNameFunc = func() string { - getMethodNameFuncCalled++ - return dummyMethodName - } - logMethodEnterFuncExpected = 1 - logMethodEnterFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logMethodEnterFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, dummyMethodName, category) - assert.Zero(t, subcategory) - assert.Zero(t, messageFormat) - assert.Empty(t, parameters) - } + m.Mock(getMethodName).Expects().Returns(dummyMethodName).Once() + m.Mock(logMethodEnter).Expects(dummySession, dummyMethodName, "", "").Returns().Once() // act dummySession.LogMethodEnter() - - // verify - verifyAll(t) } func TestSessionLogMethodParameter(t *testing.T) { @@ -634,7 +516,7 @@ func TestSessionLogMethodParameter(t *testing.T) { var dummyMethodName = "some method name" // mock - createMock(t) + var m = gomocker.NewMocker(t) // SUT var dummySession = &session{ @@ -642,26 +524,10 @@ func TestSessionLogMethodParameter(t *testing.T) { } // expect - getMethodNameFuncExpected = 1 - getMethodNameFunc = func() string { - getMethodNameFuncCalled++ - return dummyMethodName - } - strconvItoaExpected = 3 - strconvItoa = func(i int) string { - strconvItoaCalled++ - return strconv.Itoa(i) - } - logMethodParameterFuncExpected = 3 - logMethodParameterFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logMethodParameterFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, dummyMethodName, category) - assert.Equal(t, strconv.Itoa(logMethodParameterFuncCalled-1), subcategory) - assert.Equal(t, "%v", messageFormat) - assert.Equal(t, 1, len(parameters)) - assert.Equal(t, dummyParameters[logMethodParameterFuncCalled-1], parameters[0]) - } + m.Mock(getMethodName).Expects().Returns(dummyMethodName).Once() + m.Mock(logMethodParameter).Expects(dummySession, dummyMethodName, "0", "%v", dummyParameters[0]).Returns().Once() + m.Mock(logMethodParameter).Expects(dummySession, dummyMethodName, "1", "%v", dummyParameters[1]).Returns().Once() + m.Mock(logMethodParameter).Expects(dummySession, dummyMethodName, "2", "%v", dummyParameters[2]).Returns().Once() // act dummySession.LogMethodParameter( @@ -669,9 +535,6 @@ func TestSessionLogMethodParameter(t *testing.T) { dummyParameter2, dummyParameter3, ) - - // verify - verifyAll(t) } func TestSessionLogMethodLogic(t *testing.T) { @@ -686,7 +549,7 @@ func TestSessionLogMethodLogic(t *testing.T) { var dummyParameter3 = errors.New("test") // mock - createMock(t) + var m = gomocker.NewMocker(t) // SUT var dummySession = &session{ @@ -694,19 +557,16 @@ func TestSessionLogMethodLogic(t *testing.T) { } // expect - logMethodLogicFuncExpected = 1 - logMethodLogicFunc = func(session *session, logLevel LogLevel, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logMethodLogicFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, dummyLogLevel, logLevel) - assert.Equal(t, dummyCategory, category) - assert.Equal(t, dummySubcategory, subcategory) - assert.Equal(t, dummyMessageFormat, messageFormat) - assert.Equal(t, 3, len(parameters)) - assert.Equal(t, dummyParameter1, parameters[0]) - assert.Equal(t, dummyParameter2, parameters[1]) - assert.Equal(t, dummyParameter3, parameters[2]) - } + m.Mock(logMethodLogic).Expects( + dummySession, + dummyLogLevel, + dummyCategory, + dummySubcategory, + dummyMessageFormat, + dummyParameter1, + dummyParameter2, + dummyParameter3, + ).Returns().Once() // act dummySession.LogMethodLogic( @@ -718,9 +578,6 @@ func TestSessionLogMethodLogic(t *testing.T) { dummyParameter2, dummyParameter3, ) - - // verify - verifyAll(t) } func TestSessionLogMethodReturn(t *testing.T) { @@ -737,7 +594,7 @@ func TestSessionLogMethodReturn(t *testing.T) { var dummyMethodName = "some method name" // mock - createMock(t) + var m = gomocker.NewMocker(t) // SUT var dummySession = &session{ @@ -745,26 +602,10 @@ func TestSessionLogMethodReturn(t *testing.T) { } // expect - getMethodNameFuncExpected = 1 - getMethodNameFunc = func() string { - getMethodNameFuncCalled++ - return dummyMethodName - } - strconvItoaExpected = 3 - strconvItoa = func(i int) string { - strconvItoaCalled++ - return strconv.Itoa(i) - } - logMethodReturnFuncExpected = 3 - logMethodReturnFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logMethodReturnFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, dummyMethodName, category) - assert.Equal(t, strconv.Itoa(logMethodReturnFuncCalled-1), subcategory) - assert.Equal(t, "%v", messageFormat) - assert.Equal(t, 1, len(parameters)) - assert.Equal(t, dummyReturns[logMethodReturnFuncCalled-1], parameters[0]) - } + m.Mock(getMethodName).Expects().Returns(dummyMethodName).Once() + m.Mock(logMethodReturn).Expects(dummySession, dummyMethodName, "0", "%v", dummyReturns[0]).Returns().Once() + m.Mock(logMethodReturn).Expects(dummySession, dummyMethodName, "1", "%v", dummyReturns[1]).Returns().Once() + m.Mock(logMethodReturn).Expects(dummySession, dummyMethodName, "2", "%v", dummyReturns[2]).Returns().Once() // act dummySession.LogMethodReturn( @@ -772,9 +613,6 @@ func TestSessionLogMethodReturn(t *testing.T) { dummyReturn2, dummyReturn3, ) - - // verify - verifyAll(t) } func TestSessionLogMethodExit(t *testing.T) { @@ -783,7 +621,7 @@ func TestSessionLogMethodExit(t *testing.T) { var dummyMethodName = "some method name" // mock - createMock(t) + var m = gomocker.NewMocker(t) // SUT var dummySession = &session{ @@ -791,26 +629,11 @@ func TestSessionLogMethodExit(t *testing.T) { } // expect - getMethodNameFuncExpected = 1 - getMethodNameFunc = func() string { - getMethodNameFuncCalled++ - return dummyMethodName - } - logMethodExitFuncExpected = 1 - logMethodExitFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logMethodExitFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, dummyMethodName, category) - assert.Zero(t, subcategory) - assert.Zero(t, messageFormat) - assert.Empty(t, parameters) - } + m.Mock(getMethodName).Expects().Returns(dummyMethodName).Once() + m.Mock(logMethodExit).Expects(dummySession, dummyMethodName, "", "").Returns().Once() // act dummySession.LogMethodExit() - - // verify - verifyAll(t) } func TestSessionCreateWebcallRequest(t *testing.T) { @@ -819,10 +642,7 @@ func TestSessionCreateWebcallRequest(t *testing.T) { var dummyMethod = "some method" var dummyURL = "some URL" var dummyPayload = "some payload" - var dummySendClientCert = rand.Intn(100) < 50 - - // mock - createMock(t) + var dummySendClientCert = rand.IntN(100) < 50 // SUT var dummySession = &session{ @@ -853,7 +673,4 @@ func TestSessionCreateWebcallRequest(t *testing.T) { assert.Equal(t, dummySendClientCert, webrequest.sendClientCert) assert.Zero(t, webrequest.retryDelay) assert.Empty(t, webrequest.dataReceivers) - - // verify - verifyAll(t) } diff --git a/timeutil.go b/timeutil.go index 7bede3c..a075ede 100644 --- a/timeutil.go +++ b/timeutil.go @@ -4,20 +4,10 @@ import "time" const ( dateFormat string = "2006-01-02" - timeFormat string = "15:04:05" + timeFormat string = "15:04:05.999" dateTimeFormat string = dateFormat + "T" + timeFormat ) -// getTimeNow returns the current system time -func getTimeNow() time.Time { - return timeNow() -} - -// getTimeNowUTC returns the UTC representation of the current system time -func getTimeNowUTC() time.Time { - return timeNow().UTC() -} - // formatDate returns the time in string format "yyyy-MM-dd" func formatDate(value time.Time) string { return value.Format(dateFormat) diff --git a/timeutil_test.go b/timeutil_test.go index 51bd576..169da48 100644 --- a/timeutil_test.go +++ b/timeutil_test.go @@ -7,71 +7,16 @@ import ( "github.com/stretchr/testify/assert" ) -func TestGetTimeNow(t *testing.T) { - // arrange - var expectedResult = time.Now() - - // mock - createMock(t) - - // expect - timeNowExpected = 1 - timeNow = func() time.Time { - timeNowCalled++ - return expectedResult - } - - // SUT + act - var result = getTimeNow() - - // assert - assert.Equal(t, expectedResult, result) - - // verify - verifyAll(t) -} - -func TestGetTimeNowUTC(t *testing.T) { - // arrange - var dummyResult = time.Now() - var expectedResult = dummyResult.UTC() - - // mock - createMock(t) - - // expect - timeNowExpected = 1 - timeNow = func() time.Time { - timeNowCalled++ - return expectedResult - } - - // SUT + act - var result = getTimeNowUTC() - - // assert - assert.Equal(t, expectedResult, result) - - // verify - verifyAll(t) -} - func TestFormatDate(t *testing.T) { // arrange var dummyTime = time.Date(2345, 6, 7, 8, 9, 10, 11, time.UTC) var expectedResult = "2345-06-07" - // mock - createMock(t) - // SUT + act var result = formatDate(dummyTime) // assert assert.Equal(t, expectedResult, result) - - // verify - verifyAll(t) } func TestFormatTime(t *testing.T) { @@ -79,17 +24,11 @@ func TestFormatTime(t *testing.T) { var dummyTime = time.Date(2345, 6, 7, 8, 9, 10, 11, time.UTC) var expectedResult = "08:09:10" - // mock - createMock(t) - // SUT + act var result = formatTime(dummyTime) // assert assert.Equal(t, expectedResult, result) - - // verify - verifyAll(t) } func TestFormatDateTime(t *testing.T) { @@ -97,15 +36,9 @@ func TestFormatDateTime(t *testing.T) { var dummyTime = time.Date(2345, 6, 7, 8, 9, 10, 11, time.UTC) var expectedResult = "2345-06-07T08:09:10" - // mock - createMock(t) - // SUT + act var result = formatDateTime(dummyTime) // assert assert.Equal(t, expectedResult, result) - - // verify - verifyAll(t) } diff --git a/webRequest.go b/webRequest.go index e9eabda..6e2598c 100644 --- a/webRequest.go +++ b/webRequest.go @@ -1,9 +1,14 @@ package jobrunner import ( + "bytes" "crypto/tls" + "fmt" "io" "net/http" + "net/url" + "strconv" + "strings" "time" ) @@ -19,15 +24,6 @@ func getClientForRequest(sendClientCert bool) *http.Client { return httpClientNoCert } -func clientDo( - httpClient *http.Client, - httpRequest *http.Request, -) (*http.Response, error) { - return httpClient.Do( - httpRequest, - ) -} - func clientDoWithRetry( httpClient *http.Client, httpRequest *http.Request, @@ -38,8 +34,7 @@ func clientDoWithRetry( var responseObject *http.Response var responseError error for { - responseObject, responseError = clientDoFunc( - httpClient, + responseObject, responseError = httpClient.Do( httpRequest, ) if responseError != nil { @@ -56,7 +51,7 @@ func clientDoWithRetry( } else { break } - timeSleep( + time.Sleep( retryDelay, ) } @@ -93,11 +88,11 @@ func initializeHTTPClients( roundTripperWrapper func(originalTransport http.RoundTripper) http.RoundTripper, ) { httpClientWithCert = &http.Client{ - Transport: getHTTPTransportFunc(skipServerCertVerification, clientCertificate, roundTripperWrapper), + Transport: getHTTPTransport(skipServerCertVerification, clientCertificate, roundTripperWrapper), Timeout: webcallTimeout, } httpClientNoCert = &http.Client{ - Transport: getHTTPTransportFunc(skipServerCertVerification, nil, roundTripperWrapper), + Transport: getHTTPTransport(skipServerCertVerification, nil, roundTripperWrapper), Timeout: webcallTimeout, } } @@ -196,15 +191,15 @@ func createQueryString( for _, value := range values { queryStrings = append( queryStrings, - fmtSprintf( + fmt.Sprintf( "%v=%v", - urlQueryEscape(name), - urlQueryEscape(value), + url.QueryEscape(name), + url.QueryEscape(value), ), ) } } - return stringsJoin( + return strings.Join( queryStrings, "&", ) @@ -217,13 +212,13 @@ func generateRequestURL( if len(query) == 0 { return baseURL } - var queryString = createQueryStringFunc( + var queryString = createQueryString( query, ) if queryString == "" { return baseURL } - return fmtSprintf( + return fmt.Sprintf( "%v?%v", baseURL, queryString, @@ -233,16 +228,16 @@ func generateRequestURL( func createHTTPRequest(webRequest *webRequest) (*http.Request, error) { if webRequest == nil || webRequest.session == nil { - return nil, fmtErrorf("WebRequest is nil or contains invalid session") + return nil, fmt.Errorf("WebRequest is nil or contains invalid session") } - var requestURL = generateRequestURLFunc( + var requestURL = generateRequestURL( webRequest.url, webRequest.query, ) - var requestBody = stringsNewReader( + var requestBody = strings.NewReader( webRequest.payload, ) - var requestObject, requestError = httpNewRequest( + var requestObject, requestError = http.NewRequest( webRequest.method, requestURL, requestBody, @@ -250,13 +245,13 @@ func createHTTPRequest(webRequest *webRequest) (*http.Request, error) { if requestError != nil { return nil, requestError } - logWebcallStartFunc( + logWebcallStart( webRequest.session, webRequest.method, webRequest.url, requestURL, ) - logWebcallRequestFunc( + logWebcallRequest( webRequest.session, "Payload", "Content", @@ -268,11 +263,11 @@ func createHTTPRequest(webRequest *webRequest) (*http.Request, error) { requestObject.Header.Add(name, value) } } - logWebcallRequestFunc( + logWebcallRequest( webRequest.session, "Header", "Content", - marshalIgnoreErrorFunc( + marshalIgnoreError( requestObject.Header, ), ) @@ -283,19 +278,19 @@ func createHTTPRequest(webRequest *webRequest) (*http.Request, error) { } func logErrorResponse(session *session, responseError error, startTime time.Time) { - logWebcallResponseFunc( + logWebcallResponse( session, "Error", "Content", "%+v", responseError, ) - logWebcallFinishFunc( + logWebcallFinish( session, "Error", "-1", "%s", - timeSince(startTime), + time.Since(startTime), ) } @@ -305,54 +300,54 @@ func logSuccessResponse(session *session, response *http.Response, startTime tim } var ( responseStatusCode = response.StatusCode - responseBody, _ = ioutilReadAll(response.Body) + responseBody, _ = io.ReadAll(response.Body) responseHeaders = response.Header ) response.Body.Close() - response.Body = ioutilNopCloser( - bytesNewBuffer( + response.Body = io.NopCloser( + bytes.NewBuffer( responseBody, ), ) - logWebcallResponseFunc( + logWebcallResponse( session, "Header", "Content", - marshalIgnoreErrorFunc( + marshalIgnoreError( responseHeaders, ), ) - logWebcallResponseFunc( + logWebcallResponse( session, "Body", "Content", string(responseBody), ) - logWebcallFinishFunc( + logWebcallFinish( session, - httpStatusText(responseStatusCode), - strconvItoa(responseStatusCode), + http.StatusText(responseStatusCode), + strconv.Itoa(responseStatusCode), "%s", - timeSince(startTime), + time.Since(startTime), ) } func doRequestProcessing(webRequest *webRequest) (*http.Response, error) { if webRequest == nil || webRequest.session == nil { - return nil, fmtErrorf("WebRequest is nil or contains invalid session") + return nil, fmt.Errorf("WebRequest is nil or contains invalid session") } - var requestObject, requestError = createHTTPRequestFunc( + var requestObject, requestError = createHTTPRequest( webRequest, ) if requestError != nil { return nil, requestError } - var httpClient = getClientForRequestFunc( + var httpClient = getClientForRequest( webRequest.sendClientCert, ) - var startTime = getTimeNowUTCFunc() - var responseObject, responseError = clientDoWithRetryFunc( + var startTime = time.Now().UTC() + var responseObject, responseError = clientDoWithRetry( httpClient, requestObject, webRequest.connRetry, @@ -360,13 +355,13 @@ func doRequestProcessing(webRequest *webRequest) (*http.Response, error) { webRequest.retryDelay, ) if responseError != nil { - logErrorResponseFunc( + logErrorResponse( webRequest.session, responseError, startTime, ) } else { - logSuccessResponseFunc( + logSuccessResponse( webRequest.session, responseObject, startTime, @@ -383,8 +378,8 @@ func getDataTemplate(session *session, statusCode int, dataReceivers []dataRecei dataTemplate = dataReceiver.dataTemplate } } - if isInterfaceValueNilFunc(dataTemplate) { - logWebcallResponseFunc( + if isInterfaceValueNil(dataTemplate) { + logWebcallResponse( session, "Body", "Receiver", @@ -396,18 +391,18 @@ func getDataTemplate(session *session, statusCode int, dataReceivers []dataRecei } func parseResponse(session *session, body io.ReadCloser, dataTemplate interface{}) error { - var bodyBytes, bodyError = ioutilReadAll( + var bodyBytes, bodyError = io.ReadAll( body, ) if bodyError != nil { return bodyError } - var unmarshalError = tryUnmarshalFunc( + var unmarshalError = tryUnmarshal( string(bodyBytes), dataTemplate, ) if unmarshalError != nil { - logWebcallResponseFunc( + logWebcallResponse( session, "Body", "UnmarshalError", @@ -423,10 +418,10 @@ func parseResponse(session *session, body io.ReadCloser, dataTemplate interface{ func (webRequest *webRequest) Process() (statusCode int, responseHeader http.Header, responseError error) { if webRequest == nil || webRequest.session == nil { - return 0, nil, fmtErrorf("WebRequest is nil or contains invalid session") + return 0, nil, fmt.Errorf("WebRequest is nil or contains invalid session") } var responseObject *http.Response - responseObject, responseError = doRequestProcessingFunc( + responseObject, responseError = doRequestProcessing( webRequest, ) if responseError != nil { @@ -439,12 +434,12 @@ func (webRequest *webRequest) Process() (statusCode int, responseHeader http.Hea if responseObject == nil { return 0, make(http.Header), nil } - var dataTemplate = getDataTemplateFunc( + var dataTemplate = getDataTemplate( webRequest.session, responseObject.StatusCode, webRequest.dataReceivers, ) - responseError = parseResponseFunc( + responseError = parseResponse( webRequest.session, responseObject.Body, dataTemplate, diff --git a/webRequest_test.go b/webRequest_test.go index da55be4..e149c4d 100644 --- a/webRequest_test.go +++ b/webRequest_test.go @@ -6,10 +6,8 @@ import ( "errors" "fmt" "io" - "io/ioutil" - "math/rand" + "math/rand/v2" "net/http" - "net/url" "strconv" "strings" "testing" @@ -17,6 +15,7 @@ import ( "github.com/google/uuid" "github.com/stretchr/testify/assert" + "github.com/zhongjie-cai/gomocker/v2" ) func TestGetClientForRequest_SendClientCert(t *testing.T) { @@ -28,17 +27,11 @@ func TestGetClientForRequest_SendClientCert(t *testing.T) { httpClientWithCert = dummyHTTPClient1 httpClientNoCert = dummyHTTPClient2 - // mock - createMock(t) - // SUT + act var result = getClientForRequest(true) // assert assert.Equal(t, dummyHTTPClient1, result) - - // verify - verifyAll(t) } func TestGetClientForRequest_NoSendClientCert(t *testing.T) { @@ -50,39 +43,11 @@ func TestGetClientForRequest_NoSendClientCert(t *testing.T) { httpClientWithCert = dummyHTTPClient1 httpClientNoCert = dummyHTTPClient2 - // mock - createMock(t) - // SUT + act var result = getClientForRequest(false) // assert assert.Equal(t, dummyHTTPClient2, result) - - // verify - verifyAll(t) -} - -func TestClientDo(t *testing.T) { - // arrange - var dummyClient = &http.Client{} - var dummyRequest, _ = http.NewRequest( - "", - "", - nil, - ) - - // assert - assert.NotPanics( - t, - func() { - // SUT + act - clientDo( - dummyClient, - dummyRequest, - ) - }, - ) } func TestClientDoWithRetry_ConnError_NoRetry(t *testing.T) { @@ -91,21 +56,15 @@ func TestClientDoWithRetry_ConnError_NoRetry(t *testing.T) { var dummyRequestObject = &http.Request{} var dummyConnRetry = 0 var dummyHTTPRetry = map[int]int{} - var dummyRetryDelay = time.Duration(rand.Intn(100)) + var dummyRetryDelay = time.Duration(rand.IntN(100)) var dummyResponseObject = &http.Response{} var dummyResponseError = errors.New("some error") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - clientDoFuncExpected = 1 - clientDoFunc = func(client *http.Client, request *http.Request) (*http.Response, error) { - clientDoFuncCalled++ - assert.Equal(t, dummyClient, client) - assert.Equal(t, dummyRequestObject, request) - return dummyResponseObject, dummyResponseError - } + m.Mock((*http.Client).Do).Expects(dummyClient, dummyRequestObject).Returns(dummyResponseObject, dummyResponseError).Once() // SUT + act var result, err = clientDoWithRetry( @@ -119,9 +78,6 @@ func TestClientDoWithRetry_ConnError_NoRetry(t *testing.T) { // assert assert.Equal(t, dummyResponseObject, result) assert.Equal(t, dummyResponseError, err) - - // verify - verifyAll(t) } func TestClientDoWithRetry_ConnError_RetryOK(t *testing.T) { @@ -130,31 +86,17 @@ func TestClientDoWithRetry_ConnError_RetryOK(t *testing.T) { var dummyRequestObject = &http.Request{} var dummyConnRetry = 2 var dummyHTTPRetry = map[int]int{} - var dummyRetryDelay = time.Duration(rand.Intn(100)) + var dummyRetryDelay = time.Duration(rand.IntN(100)) var dummyResponseObject = &http.Response{} var dummyResponseError = errors.New("some error") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - clientDoFuncExpected = 2 - clientDoFunc = func(client *http.Client, request *http.Request) (*http.Response, error) { - clientDoFuncCalled++ - assert.Equal(t, dummyClient, client) - assert.Equal(t, dummyRequestObject, request) - if clientDoFuncCalled == 1 { - return dummyResponseObject, dummyResponseError - } else if clientDoFuncCalled == 2 { - return dummyResponseObject, nil - } - return nil, nil - } - timeSleepExpected = 1 - timeSleep = func(d time.Duration) { - timeSleepCalled++ - assert.Equal(t, dummyRetryDelay, d) - } + m.Mock((*http.Client).Do).Expects(dummyClient, dummyRequestObject).Returns(dummyResponseObject, dummyResponseError).Once() + m.Mock((*http.Client).Do).Expects(dummyClient, dummyRequestObject).Returns(dummyResponseObject, nil).Once() + m.Mock(time.Sleep).Expects(dummyRetryDelay).Returns().Once() // SUT + act var result, err = clientDoWithRetry( @@ -168,9 +110,6 @@ func TestClientDoWithRetry_ConnError_RetryOK(t *testing.T) { // assert assert.Equal(t, dummyResponseObject, result) assert.NoError(t, err) - - // verify - verifyAll(t) } func TestClientDoWithRetry_ConnError_RetryFail(t *testing.T) { @@ -179,26 +118,16 @@ func TestClientDoWithRetry_ConnError_RetryFail(t *testing.T) { var dummyRequestObject = &http.Request{} var dummyConnRetry = 2 var dummyHTTPRetry = map[int]int{} - var dummyRetryDelay = time.Duration(rand.Intn(100)) + var dummyRetryDelay = time.Duration(rand.IntN(100)) var dummyResponseObject = &http.Response{} var dummyResponseError = errors.New("some error") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - clientDoFuncExpected = 3 - clientDoFunc = func(client *http.Client, request *http.Request) (*http.Response, error) { - clientDoFuncCalled++ - assert.Equal(t, dummyClient, client) - assert.Equal(t, dummyRequestObject, request) - return dummyResponseObject, dummyResponseError - } - timeSleepExpected = 2 - timeSleep = func(d time.Duration) { - timeSleepCalled++ - assert.Equal(t, dummyRetryDelay, d) - } + m.Mock((*http.Client).Do).Expects(dummyClient, dummyRequestObject).Returns(dummyResponseObject, dummyResponseError).Times(3) + m.Mock(time.Sleep).Expects(dummyRetryDelay).Returns().Twice() // SUT + act var result, err = clientDoWithRetry( @@ -212,9 +141,6 @@ func TestClientDoWithRetry_ConnError_RetryFail(t *testing.T) { // assert assert.Equal(t, dummyResponseObject, result) assert.Equal(t, dummyResponseError, err) - - // verify - verifyAll(t) } func TestClientDoWithRetry_HTTPError_NilResponse(t *testing.T) { @@ -223,20 +149,14 @@ func TestClientDoWithRetry_HTTPError_NilResponse(t *testing.T) { var dummyRequestObject = &http.Request{} var dummyConnRetry = rand.Int() var dummyHTTPRetry = map[int]int{} - var dummyRetryDelay = time.Duration(rand.Intn(100)) + var dummyRetryDelay = time.Duration(rand.IntN(100)) var dummyResponseObject *http.Response // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - clientDoFuncExpected = 1 - clientDoFunc = func(client *http.Client, request *http.Request) (*http.Response, error) { - clientDoFuncCalled++ - assert.Equal(t, dummyClient, client) - assert.Equal(t, dummyRequestObject, request) - return dummyResponseObject, nil - } + m.Mock((*http.Client).Do).Expects(dummyClient, dummyRequestObject).Returns(dummyResponseObject, nil).Once() // SUT + act var result, err = clientDoWithRetry( @@ -250,9 +170,6 @@ func TestClientDoWithRetry_HTTPError_NilResponse(t *testing.T) { // assert assert.Equal(t, dummyResponseObject, result) assert.NoError(t, err) - - // verify - verifyAll(t) } func TestClientDoWithRetry_HTTPError_NoRetry(t *testing.T) { @@ -261,20 +178,14 @@ func TestClientDoWithRetry_HTTPError_NoRetry(t *testing.T) { var dummyRequestObject = &http.Request{} var dummyConnRetry = rand.Int() var dummyHTTPRetry = map[int]int{} - var dummyRetryDelay = time.Duration(rand.Intn(100)) + var dummyRetryDelay = time.Duration(rand.IntN(100)) var dummyResponseObject = &http.Response{} // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - clientDoFuncExpected = 1 - clientDoFunc = func(client *http.Client, request *http.Request) (*http.Response, error) { - clientDoFuncCalled++ - assert.Equal(t, dummyClient, client) - assert.Equal(t, dummyRequestObject, request) - return dummyResponseObject, nil - } + m.Mock((*http.Client).Do).Expects(dummyClient, dummyRequestObject).Returns(dummyResponseObject, nil).Once() // SUT + act var result, err = clientDoWithRetry( @@ -288,9 +199,6 @@ func TestClientDoWithRetry_HTTPError_NoRetry(t *testing.T) { // assert assert.Equal(t, dummyResponseObject, result) assert.NoError(t, err) - - // verify - verifyAll(t) } func TestClientDoWithRetry_HTTPError_RetryOK(t *testing.T) { @@ -302,33 +210,19 @@ func TestClientDoWithRetry_HTTPError_RetryOK(t *testing.T) { var dummyHTTPRetry = map[int]int{ dummyStatusCode: 2, } - var dummyRetryDelay = time.Duration(rand.Intn(100)) + var dummyRetryDelay = time.Duration(rand.IntN(100)) var dummyResponseObject1 = &http.Response{ StatusCode: dummyStatusCode, } var dummyResponseObject2 = &http.Response{} // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - clientDoFuncExpected = 2 - clientDoFunc = func(client *http.Client, request *http.Request) (*http.Response, error) { - clientDoFuncCalled++ - assert.Equal(t, dummyClient, client) - assert.Equal(t, dummyRequestObject, request) - if clientDoFuncCalled == 1 { - return dummyResponseObject1, nil - } else if clientDoFuncCalled == 2 { - return dummyResponseObject2, nil - } - return nil, nil - } - timeSleepExpected = 1 - timeSleep = func(d time.Duration) { - timeSleepCalled++ - assert.Equal(t, dummyRetryDelay, d) - } + m.Mock((*http.Client).Do).Expects(dummyClient, dummyRequestObject).Returns(dummyResponseObject1, nil).Once() + m.Mock((*http.Client).Do).Expects(dummyClient, dummyRequestObject).Returns(dummyResponseObject2, nil).Once() + m.Mock(time.Sleep).Expects(dummyRetryDelay).Returns().Once() // SUT + act var result, err = clientDoWithRetry( @@ -342,9 +236,6 @@ func TestClientDoWithRetry_HTTPError_RetryOK(t *testing.T) { // assert assert.Equal(t, dummyResponseObject2, result) assert.NoError(t, err) - - // verify - verifyAll(t) } func TestClientDoWithRetry_HTTPError_RetryFail(t *testing.T) { @@ -356,27 +247,17 @@ func TestClientDoWithRetry_HTTPError_RetryFail(t *testing.T) { var dummyHTTPRetry = map[int]int{ dummyStatusCode: 2, } - var dummyRetryDelay = time.Duration(rand.Intn(100)) + var dummyRetryDelay = time.Duration(rand.IntN(100)) var dummyResponseObject = &http.Response{ StatusCode: dummyStatusCode, } // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - clientDoFuncExpected = 3 - clientDoFunc = func(client *http.Client, request *http.Request) (*http.Response, error) { - clientDoFuncCalled++ - assert.Equal(t, dummyClient, client) - assert.Equal(t, dummyRequestObject, request) - return dummyResponseObject, nil - } - timeSleepExpected = 2 - timeSleep = func(d time.Duration) { - timeSleepCalled++ - assert.Equal(t, dummyRetryDelay, d) - } + m.Mock((*http.Client).Do).Expects(dummyClient, dummyRequestObject).Returns(dummyResponseObject, nil).Times(3) + m.Mock(time.Sleep).Expects(dummyRetryDelay).Returns().Twice() // SUT + act var result, err = clientDoWithRetry( @@ -390,30 +271,20 @@ func TestClientDoWithRetry_HTTPError_RetryFail(t *testing.T) { // assert assert.Equal(t, dummyResponseObject, result) assert.NoError(t, err) - - // verify - verifyAll(t) } func TestGetHTTPTransport_NoClientCert(t *testing.T) { // arrange - var dummySkipServerCertVerification = rand.Intn(100) < 50 + var dummySkipServerCertVerification = rand.IntN(100) < 50 var dummyClientCert *tls.Certificate var dummyRoundTripper = &http.Transport{} - var dummyRoundTripperWrapperExpected int - var dummyRoundTripperWrapperCalled int - var dummyRoundTripperWrapper func(http.RoundTripper) http.RoundTripper + var dummyRoundTripperWrapper = func(rt http.RoundTripper) http.RoundTripper { return nil } // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - dummyRoundTripperWrapperExpected = 1 - dummyRoundTripperWrapper = func(original http.RoundTripper) http.RoundTripper { - dummyRoundTripperWrapperCalled++ - assert.Equal(t, http.DefaultTransport, original) - return dummyRoundTripper - } + m.Mock(dummyRoundTripperWrapper).Expects(http.DefaultTransport).Returns(dummyRoundTripper).Once() // SUT + act var result = getHTTPTransport( @@ -424,31 +295,20 @@ func TestGetHTTPTransport_NoClientCert(t *testing.T) { // assert assert.Equal(t, dummyRoundTripper, result) - - // verify - verifyAll(t) - assert.Equal(t, dummyRoundTripperWrapperExpected, dummyRoundTripperWrapperCalled, "Unexpected number of calls to method dummyRoundTripperWrapper") } func TestGetHTTPTransport_WithClientCert(t *testing.T) { // arrange - var dummySkipServerCertVerification = rand.Intn(100) < 50 + var dummySkipServerCertVerification = rand.IntN(100) < 50 var dummyClientCert = &tls.Certificate{} var dummyRoundTripper = &http.Transport{} - var dummyRoundTripperWrapperExpected int - var dummyRoundTripperWrapperCalled int - var dummyRoundTripperWrapper func(http.RoundTripper) http.RoundTripper + var dummyRoundTripperWrapper = func(rt http.RoundTripper) http.RoundTripper { return nil } // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - dummyRoundTripperWrapperExpected = 1 - dummyRoundTripperWrapper = func(original http.RoundTripper) http.RoundTripper { - dummyRoundTripperWrapperCalled++ - assert.NotEqual(t, http.DefaultTransport, original) - return dummyRoundTripper - } + m.Mock(dummyRoundTripperWrapper).Expects(gomocker.Anything()).Returns(dummyRoundTripper).Once() // SUT + act var result = getHTTPTransport( @@ -459,39 +319,27 @@ func TestGetHTTPTransport_WithClientCert(t *testing.T) { // assert assert.Equal(t, dummyRoundTripper, result) - - // verify - verifyAll(t) - assert.Equal(t, dummyRoundTripperWrapperExpected, dummyRoundTripperWrapperCalled, "Unexpected number of calls to method dummyRoundTripperWrapper") } func TestInitializeHTTPClients(t *testing.T) { // arrange var dummyWebcallTimeout = time.Duration(rand.Int()) - var dummySkipServerCertVerification = rand.Intn(100) < 50 + var dummySkipServerCertVerification = rand.IntN(100) < 50 var dummyClientCert = &tls.Certificate{} var dummyHTTPTransport1 = &http.Transport{MaxConnsPerHost: rand.Int()} var dummyHTTPTransport2 = &http.Transport{MaxConnsPerHost: rand.Int()} var dummyRoundTripperWrapper = func(http.RoundTripper) http.RoundTripper { return nil } // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - getHTTPTransportFuncExpected = 2 - getHTTPTransportFunc = func(skipServerCertVerification bool, clientCertificate *tls.Certificate, roundTripperWrapper func(originalTransport http.RoundTripper) http.RoundTripper) http.RoundTripper { - getHTTPTransportFuncCalled++ - assert.Equal(t, dummySkipServerCertVerification, skipServerCertVerification) - if getHTTPTransportFuncCalled == 1 { - assert.Equal(t, dummyClientCert, clientCertificate) - return dummyHTTPTransport1 - } else if getHTTPTransportFuncCalled == 2 { - assert.Nil(t, clientCertificate) - return dummyHTTPTransport2 - } - functionPointerEquals(t, dummyRoundTripperWrapper, roundTripperWrapper) - return nil - } + m.Mock(getHTTPTransport).Expects(dummySkipServerCertVerification, dummyClientCert, gomocker.Matches(func(value interface{}) bool { + return functionPointerEquals(dummyRoundTripperWrapper, value) + })).Returns(dummyHTTPTransport1).Once() + m.Mock(getHTTPTransport).Expects(dummySkipServerCertVerification, nil, gomocker.Matches(func(value interface{}) bool { + return functionPointerEquals(dummyRoundTripperWrapper, value) + })).Returns(dummyHTTPTransport2).Once() // SUT + act initializeHTTPClients( @@ -508,21 +356,15 @@ func TestInitializeHTTPClients(t *testing.T) { assert.NotNil(t, httpClientNoCert) assert.Equal(t, dummyHTTPTransport2, httpClientNoCert.Transport) assert.Equal(t, dummyWebcallTimeout, httpClientNoCert.Timeout) - - // verify - verifyAll(t) } -func TestWebRequestAddQuery_HappyPath(t *testing.T) { +func TestWebREquestAddQuery_HappyPath(t *testing.T) { // arrange var dummyName = "some name" var dummyValue1 = "some value 1" var dummyValue2 = "some value 2" var dummyValue3 = "some value 3" - // mock - createMock(t) - // SUT var sut = &webRequest{} @@ -548,21 +390,15 @@ func TestWebRequestAddQuery_HappyPath(t *testing.T) { assert.Equal(t, dummyValue1, values[0]) assert.Equal(t, dummyValue2, values[1]) assert.Equal(t, dummyValue3, values[2]) - - // verify - verifyAll(t) } -func TestWebRequestAddHeader_HappyPath(t *testing.T) { +func TestWebREquestAddHeader_HappyPath(t *testing.T) { // arrange var dummyName = "some name" var dummyValue1 = "some value 1" var dummyValue2 = "some value 2" var dummyValue3 = "some value 3" - // mock - createMock(t) - // SUT var sut = &webRequest{} @@ -588,9 +424,6 @@ func TestWebRequestAddHeader_HappyPath(t *testing.T) { assert.Equal(t, dummyValue1, values[0]) assert.Equal(t, dummyValue2, values[1]) assert.Equal(t, dummyValue3, values[2]) - - // verify - verifyAll(t) } func TestWebRequestSetupRetry(t *testing.T) { @@ -600,14 +433,11 @@ func TestWebRequestSetupRetry(t *testing.T) { rand.Int(): rand.Int(), rand.Int(): rand.Int(), } - var dummyRetryDelay = time.Duration(rand.Intn(100)) + var dummyRetryDelay = time.Duration(rand.IntN(100)) // SUT var sut = &webRequest{} - // mock - createMock(t) - // act var result, ok = sut.SetupRetry( dummyConnRetry, @@ -620,9 +450,6 @@ func TestWebRequestSetupRetry(t *testing.T) { assert.Equal(t, dummyConnRetry, result.connRetry) assert.Equal(t, dummyHTTPRetry, result.httpRetry) assert.Equal(t, dummyRetryDelay, result.retryDelay) - - // verify - verifyAll(t) } func TestWebRequestAnticipate(t *testing.T) { @@ -637,9 +464,6 @@ func TestWebRequestAnticipate(t *testing.T) { // SUT var sut = &webRequest{} - // mock - createMock(t) - // act var result, ok = sut.Anticipate( dummyBeginStatusCode1, @@ -660,9 +484,6 @@ func TestWebRequestAnticipate(t *testing.T) { assert.Equal(t, dummyBeginStatusCode2, result.dataReceivers[1].beginStatusCode) assert.Equal(t, dummyEndStatusCode2, result.dataReceivers[1].endStatusCode) assert.Equal(t, &dummyDataTemplate2, result.dataReceivers[1].dataTemplate) - - // verify - verifyAll(t) } func TestCreateQueryString_NilQuery(t *testing.T) { @@ -671,16 +492,10 @@ func TestCreateQueryString_NilQuery(t *testing.T) { var dummyResult = "some result" // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - stringsJoinExpected = 1 - stringsJoin = func(a []string, sep string) string { - stringsJoinCalled++ - assert.Empty(t, a) - assert.Equal(t, "&", sep) - return dummyResult - } + m.Mock(strings.Join).Expects(gomocker.Anything(), "&").Returns(dummyResult).Once() // SUT + act var result = createQueryString( @@ -689,9 +504,6 @@ func TestCreateQueryString_NilQuery(t *testing.T) { // assert assert.Equal(t, dummyResult, result) - - // verify - verifyAll(t) } func TestCreateQueryString_EmptyQuery(t *testing.T) { @@ -700,16 +512,10 @@ func TestCreateQueryString_EmptyQuery(t *testing.T) { var dummyResult = "some result" // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - stringsJoinExpected = 1 - stringsJoin = func(a []string, sep string) string { - stringsJoinCalled++ - assert.Empty(t, a) - assert.Equal(t, "&", sep) - return dummyResult - } + m.Mock(strings.Join).Expects(gomocker.Anything(), "&").Returns(dummyResult).Once() // SUT + act var result = createQueryString( @@ -718,9 +524,6 @@ func TestCreateQueryString_EmptyQuery(t *testing.T) { // assert assert.Equal(t, dummyResult, result) - - // verify - verifyAll(t) } func TestCreateQueryString_EmptyQueryName(t *testing.T) { @@ -731,16 +534,10 @@ func TestCreateQueryString_EmptyQueryName(t *testing.T) { var dummyResult = "some result" // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - stringsJoinExpected = 1 - stringsJoin = func(a []string, sep string) string { - stringsJoinCalled++ - assert.Empty(t, a) - assert.Equal(t, "&", sep) - return dummyResult - } + m.Mock(strings.Join).Expects(gomocker.Anything(), "&").Returns(dummyResult).Once() // SUT + act var result = createQueryString( @@ -749,9 +546,6 @@ func TestCreateQueryString_EmptyQueryName(t *testing.T) { // assert assert.Equal(t, dummyResult, result) - - // verify - verifyAll(t) } func TestCreateQueryString_EmptyQueryValues(t *testing.T) { @@ -763,16 +557,10 @@ func TestCreateQueryString_EmptyQueryValues(t *testing.T) { var dummyResult = "some result" // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - stringsJoinExpected = 1 - stringsJoin = func(a []string, sep string) string { - stringsJoinCalled++ - assert.Empty(t, a) - assert.Equal(t, "&", sep) - return dummyResult - } + m.Mock(strings.Join).Expects(gomocker.Anything(), "&").Returns(dummyResult).Once() // SUT + act var result = createQueryString( @@ -781,62 +569,15 @@ func TestCreateQueryString_EmptyQueryValues(t *testing.T) { // assert assert.Equal(t, dummyResult, result) - - // verify - verifyAll(t) } func TestCreateQueryString_HappyPath(t *testing.T) { // arrange - var dummyNames = []string{ - "some name 1", - "some name 2", - "some name 3", - } - var dummyValues = [][]string{ - {"some value 1-1", "some value 1-2", "some value 1-3"}, - {"some value 2-1", "some value 2-2", "some value 2-3"}, - {"some value 3-1", "some value 3-2", "some value 3-3"}, - } var dummyQuery = map[string][]string{ "": {"empty 1", "empty 2"}, - "some name": {}, - } - var dummyQueryStrings = []string{} - var dummyResult = "some joined query" - - // stub - for i := 0; i < len(dummyNames); i++ { - dummyQuery[dummyNames[i]] = dummyValues[i] - for j := 0; j < len(dummyValues[i]); j++ { - dummyQueryStrings = append( - dummyQueryStrings, - url.QueryEscape(dummyNames[i])+"="+url.QueryEscape(dummyValues[i][j]), - ) - } - } - - // mock - createMock(t) - - // expect - urlQueryEscapeExpected = 18 - urlQueryEscape = func(s string) string { - urlQueryEscapeCalled++ - return url.QueryEscape(s) - } - fmtSprintfExpected = 9 - fmtSprintf = func(format string, a ...interface{}) string { - fmtSprintfCalled++ - return fmt.Sprintf(format, a...) - } - stringsJoinExpected = 1 - stringsJoin = func(a []string, sep string) string { - stringsJoinCalled++ - assert.ElementsMatch(t, dummyQueryStrings, a) - assert.Equal(t, "&", sep) - return dummyResult + "some name": {"some value 1", "some value 2", "some value 3"}, } + var dummyResult = "some+name=some+value+1&some+name=some+value+2&some+name=some+value+3" // SUT + act var result = createQueryString( @@ -845,9 +586,6 @@ func TestCreateQueryString_HappyPath(t *testing.T) { // assert assert.Equal(t, dummyResult, result) - - // verify - verifyAll(t) } func TestGenerateRequestURL_NilQuery(t *testing.T) { @@ -855,9 +593,6 @@ func TestGenerateRequestURL_NilQuery(t *testing.T) { var dummyBaseURL = "some base URL" var dummyQuery map[string][]string = nil - // mock - createMock(t) - // SUT + act var result = generateRequestURL( dummyBaseURL, @@ -866,9 +601,6 @@ func TestGenerateRequestURL_NilQuery(t *testing.T) { // assert assert.Equal(t, dummyBaseURL, result) - - // verify - verifyAll(t) } func TestGenerateRequestURL_EmptyQuery(t *testing.T) { @@ -881,15 +613,10 @@ func TestGenerateRequestURL_EmptyQuery(t *testing.T) { var dummyQueryString string // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - createQueryStringFuncExpected = 1 - createQueryStringFunc = func(query map[string][]string) string { - createQueryStringFuncCalled++ - assert.Equal(t, dummyQuery, query) - return dummyQueryString - } + m.Mock(createQueryString).Expects(dummyQuery).Returns(dummyQueryString).Once() // SUT + act var result = generateRequestURL( @@ -899,9 +626,6 @@ func TestGenerateRequestURL_EmptyQuery(t *testing.T) { // assert assert.Equal(t, dummyBaseURL, result) - - // verify - verifyAll(t) } func TestGenerateRequestURL_Success(t *testing.T) { @@ -915,20 +639,10 @@ func TestGenerateRequestURL_Success(t *testing.T) { var dummyResult = dummyBaseURL + "?" + dummyQueryString // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - createQueryStringFuncExpected = 1 - createQueryStringFunc = func(query map[string][]string) string { - createQueryStringFuncCalled++ - assert.Equal(t, dummyQuery, query) - return dummyQueryString - } - fmtSprintfExpected = 1 - fmtSprintf = func(format string, a ...interface{}) string { - fmtSprintfCalled++ - return fmt.Sprintf(format, a...) - } + m.Mock(createQueryString).Expects(dummyQuery).Returns(dummyQueryString).Once() // SUT + act var result = generateRequestURL( @@ -938,22 +652,6 @@ func TestGenerateRequestURL_Success(t *testing.T) { // assert assert.Equal(t, dummyResult, result) - - // verify - verifyAll(t) -} - -type dummyCustomizationWrapRequest struct { - dummyCustomization - wrapRequest func(Session, *http.Request) *http.Request -} - -func (customization *dummyCustomizationWrapRequest) WrapRequest(session Session, httpRequest *http.Request) *http.Request { - if customization.wrapRequest != nil { - return customization.wrapRequest(session, httpRequest) - } - assert.Fail(customization.t, "Unexpected call to WrapRequest") - return nil } func TestCreateHTTPRequest_NilWebRequest(t *testing.T) { @@ -962,16 +660,10 @@ func TestCreateHTTPRequest_NilWebRequest(t *testing.T) { var dummyError = errors.New("some error message") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - fmtErrorfExpected = 1 - fmtErrorf = func(format string, a ...interface{}) error { - fmtErrorfCalled++ - assert.Equal(t, "WebRequest is nil or contains invalid session", format) - assert.Empty(t, a) - return dummyError - } + m.Mock(fmt.Errorf).Expects("WebRequest is nil or contains invalid session").Returns(dummyError).Once() // SUT + act var result, err = createHTTPRequest( @@ -981,9 +673,6 @@ func TestCreateHTTPRequest_NilWebRequest(t *testing.T) { // assert assert.Nil(t, result) assert.Equal(t, dummyError, err) - - // verify - verifyAll(t) } func TestCreateHTTPRequest_NilWebRequestSession(t *testing.T) { @@ -992,16 +681,10 @@ func TestCreateHTTPRequest_NilWebRequestSession(t *testing.T) { var dummyError = errors.New("some error message") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - fmtErrorfExpected = 1 - fmtErrorf = func(format string, a ...interface{}) error { - fmtErrorfCalled++ - assert.Equal(t, "WebRequest is nil or contains invalid session", format) - assert.Empty(t, a) - return dummyError - } + m.Mock(fmt.Errorf).Expects("WebRequest is nil or contains invalid session").Returns(dummyError).Once() // SUT + act var result, err = createHTTPRequest( @@ -1011,9 +694,6 @@ func TestCreateHTTPRequest_NilWebRequestSession(t *testing.T) { // assert assert.Nil(t, result) assert.Equal(t, dummyError, err) - - // verify - verifyAll(t) } func TestCreateHTTPRequest_RequestError(t *testing.T) { @@ -1035,8 +715,8 @@ func TestCreateHTTPRequest_RequestError(t *testing.T) { rand.Int(): rand.Int(), rand.Int(): rand.Int(), } - var dummySendClientCert = rand.Intn(100) < 50 - var dummyRetryDelay = time.Duration(rand.Intn(100)) + var dummySendClientCert = rand.IntN(100) < 50 + var dummyRetryDelay = time.Duration(rand.IntN(100)) var dummyDataReceivers = []dataReceiver{ {0, 999, nil}, } @@ -1057,30 +737,16 @@ func TestCreateHTTPRequest_RequestError(t *testing.T) { var dummyRequest *http.Request var dummyError = errors.New("some error message") + // stub + var dummyStingsReader = strings.NewReader(dummyPayload) + // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - generateRequestURLFuncExpected = 1 - generateRequestURLFunc = func(baseURL string, query map[string][]string) string { - generateRequestURLFuncCalled++ - assert.Equal(t, dummyURL, baseURL) - assert.Equal(t, dummyQuery, query) - return dummyRequestURL - } - stringsNewReaderExpected = 1 - stringsNewReader = func(s string) *strings.Reader { - stringsNewReaderCalled++ - return strings.NewReader(s) - } - httpNewRequestExpected = 1 - httpNewRequest = func(method, url string, body io.Reader) (*http.Request, error) { - httpNewRequestCalled++ - assert.Equal(t, dummyMethod, method) - assert.Equal(t, dummyRequestURL, url) - assert.NotNil(t, body) - return dummyRequest, dummyError - } + m.Mock(generateRequestURL).Expects(dummyURL, dummyQuery).Returns(dummyRequestURL).Once() + m.Mock(strings.NewReader).Expects(dummyPayload).Returns(dummyStingsReader).Once() + m.Mock(http.NewRequest).Expects(dummyMethod, dummyRequestURL, gomocker.Anything()).Returns(dummyRequest, dummyError).Once() // SUT + act var result, err = createHTTPRequest( @@ -1090,18 +756,13 @@ func TestCreateHTTPRequest_RequestError(t *testing.T) { // assert assert.Nil(t, result) assert.Equal(t, dummyError, err) - - // verify - verifyAll(t) } func TestCreateHTTPRequest_Success(t *testing.T) { // arrange - var dummyCustomizationWrapRequest = &dummyCustomizationWrapRequest{ - dummyCustomization: dummyCustomization{t: t}, - } + var dummyCustomization = &DefaultCustomization{} var dummySession = &session{ - customization: dummyCustomizationWrapRequest, + customization: dummyCustomization, } var dummyMethod = "some method" var dummyURL = "some URL" @@ -1119,8 +780,8 @@ func TestCreateHTTPRequest_Success(t *testing.T) { rand.Int(): rand.Int(), rand.Int(): rand.Int(), } - var dummySendClientCert = rand.Intn(100) < 50 - var dummyRetryDelay = time.Duration(rand.Intn(100)) + var dummySendClientCert = rand.IntN(100) < 50 + var dummyRetryDelay = time.Duration(rand.IntN(100)) var dummyDataReceivers = []dataReceiver{ {0, 999, nil}, } @@ -1142,71 +803,25 @@ func TestCreateHTTPRequest_Success(t *testing.T) { RequestURI: "abc", } var dummyHeaderContent = "some header content" - var customizationWrapRequestExpected int - var customizationWrapRequestCalled int var dummyCustomized = &http.Request{ RequestURI: "def", } + // stub + var dummyStingsReader = strings.NewReader(dummyPayload) + // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - generateRequestURLFuncExpected = 1 - generateRequestURLFunc = func(baseURL string, query map[string][]string) string { - generateRequestURLFuncCalled++ - assert.Equal(t, dummyURL, baseURL) - assert.Equal(t, dummyQuery, query) - return dummyRequestURL - } - stringsNewReaderExpected = 1 - stringsNewReader = func(s string) *strings.Reader { - stringsNewReaderCalled++ - return strings.NewReader(s) - } - httpNewRequestExpected = 1 - httpNewRequest = func(method, url string, body io.Reader) (*http.Request, error) { - httpNewRequestCalled++ - assert.Equal(t, dummyMethod, method) - assert.Equal(t, dummyRequestURL, url) - assert.NotNil(t, body) - return dummyRequest, nil - } - logWebcallStartFuncExpected = 1 - logWebcallStartFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logWebcallStartFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, dummyMethod, category) - assert.Equal(t, dummyURL, subcategory) - assert.Equal(t, dummyRequestURL, messageFormat) - assert.Empty(t, parameters) - } - logWebcallRequestFuncExpected = 2 - logWebcallRequestFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logWebcallRequestFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, "Content", subcategory) - assert.Empty(t, parameters) - if logWebcallRequestFuncCalled == 1 { - assert.Equal(t, "Payload", category) - assert.Equal(t, dummyPayload, messageFormat) - } else if logWebcallRequestFuncCalled == 2 { - assert.Equal(t, "Header", category) - assert.Equal(t, dummyHeaderContent, messageFormat) - } - } - marshalIgnoreErrorFuncExpected = 1 - marshalIgnoreErrorFunc = func(v interface{}) string { - marshalIgnoreErrorFuncCalled++ - return dummyHeaderContent - } - customizationWrapRequestExpected = 1 - dummyCustomizationWrapRequest.wrapRequest = func(session Session, httpRequest *http.Request) *http.Request { - customizationWrapRequestCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, dummyRequest, httpRequest) - return dummyCustomized - } + m.Mock(generateRequestURL).Expects(dummyURL, dummyQuery).Returns(dummyRequestURL).Once() + m.Mock(strings.NewReader).Expects(dummyPayload).Returns(dummyStingsReader).Once() + m.Mock(http.NewRequest).Expects(dummyMethod, dummyRequestURL, gomocker.Anything()).Returns(dummyRequest, nil).Once() + m.Mock(logWebcallStart).Expects(dummySession, dummyMethod, dummyURL, dummyRequestURL).Returns().Once() + m.Mock(logWebcallRequest).Expects(dummySession, "Payload", "Content", dummyPayload).Returns().Once() + m.Mock(logWebcallRequest).Expects(dummySession, "Header", "Content", dummyHeaderContent).Returns().Once() + m.Mock(marshalIgnoreError).Expects(gomocker.Anything()).Returns(dummyHeaderContent).Once() + m.Mock((*DefaultCustomization).WrapRequest).Expects(dummyCustomization, dummySession, dummyRequest).Returns(dummyCustomized).Once() // SUT + act var result, err = createHTTPRequest( @@ -1216,10 +831,6 @@ func TestCreateHTTPRequest_Success(t *testing.T) { // assert assert.Equal(t, dummyCustomized, result) assert.NoError(t, err) - - // verify - verifyAll(t) - assert.Equal(t, customizationWrapRequestExpected, customizationWrapRequestCalled, "Unexpected number of calls to method customization.WrapRequest") } func TestLogErrorResponse(t *testing.T) { @@ -1227,38 +838,15 @@ func TestLogErrorResponse(t *testing.T) { var dummySession = &session{id: uuid.New()} var dummyError = errors.New("some error") var dummyStartTime = time.Now() - var dummyTimeSince = time.Duration(rand.Intn(1000)) + var dummyTimeSince = time.Duration(rand.IntN(1000)) // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - logWebcallResponseFuncExpected = 1 - logWebcallResponseFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logWebcallResponseFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, "Error", category) - assert.Equal(t, "Content", subcategory) - assert.Equal(t, "%+v", messageFormat) - assert.Equal(t, 1, len(parameters)) - assert.Equal(t, dummyError, parameters[0]) - } - timeSinceExpected = 1 - timeSince = func(ts time.Time) time.Duration { - timeSinceCalled++ - assert.Equal(t, dummyStartTime, ts) - return dummyTimeSince - } - logWebcallFinishFuncExpected = 1 - logWebcallFinishFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logWebcallFinishFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, "Error", category) - assert.Equal(t, "-1", subcategory) - assert.Equal(t, "%s", messageFormat) - assert.Equal(t, 1, len(parameters)) - assert.Equal(t, dummyTimeSince, parameters[0]) - } + m.Mock(logWebcallResponse).Expects(dummySession, "Error", "Content", "%+v", dummyError).Returns().Once() + m.Mock(time.Since).Expects(dummyStartTime).Returns(dummyTimeSince).Once() + m.Mock(logWebcallFinish).Expects(dummySession, "Error", "-1", "%s", dummyTimeSince).Returns().Once() // SUT + act logErrorResponse( @@ -1266,9 +854,6 @@ func TestLogErrorResponse(t *testing.T) { dummyError, dummyStartTime, ) - - // verify - verifyAll(t) } func TestLogSuccessResponse_NilResponse(t *testing.T) { @@ -1277,26 +862,20 @@ func TestLogSuccessResponse_NilResponse(t *testing.T) { var dummyResponse *http.Response var dummyStartTime = time.Now() - // mock - createMock(t) - // SUT + act logSuccessResponse( dummySession, dummyResponse, dummyStartTime, ) - - // verify - verifyAll(t) } func TestLogSuccessResponse_ValidResponse(t *testing.T) { // arrange var dummySession = &session{id: uuid.New()} var dummyStatus = "some status" - var dummyStatusCode = rand.Intn(1000) - var dummyBody = ioutil.NopCloser(bytes.NewBufferString("some body")) + var dummyStatusCode = rand.IntN(1000) + var dummyBody = io.NopCloser(bytes.NewBufferString("some body")) var dummyHeader = http.Header{ "foo": []string{"bar"}, "test": []string{"123", "456", "789"}, @@ -1310,81 +889,24 @@ func TestLogSuccessResponse_ValidResponse(t *testing.T) { var dummyResponseBody = string(dummyResponseBytes) var dummyError = errors.New("some error") var dummyBuffer = &bytes.Buffer{} - var dummyNewBody = ioutil.NopCloser(bytes.NewBufferString("some new body")) + var dummyNewBody = io.NopCloser(bytes.NewBufferString("some new body")) var dummyStartTime = time.Now() var dummyHeaderContent = "some header content" - var dummyTimeSince = time.Duration(rand.Intn(1000)) + var dummyTimeSince = time.Duration(rand.IntN(1000)) // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - ioutilReadAllExpected = 1 - ioutilReadAll = func(r io.Reader) ([]byte, error) { - ioutilReadAllCalled++ - assert.Equal(t, dummyBody, r) - return dummyResponseBytes, dummyError - } - bytesNewBufferExpected = 1 - bytesNewBuffer = func(buf []byte) *bytes.Buffer { - bytesNewBufferCalled++ - assert.Equal(t, dummyResponseBytes, buf) - return dummyBuffer - } - ioutilNopCloserExpected = 1 - ioutilNopCloser = func(r io.Reader) io.ReadCloser { - ioutilNopCloserCalled++ - assert.Equal(t, dummyBuffer, r) - return dummyNewBody - } - httpStatusTextExpected = 1 - httpStatusText = func(code int) string { - httpStatusTextCalled++ - assert.Equal(t, dummyStatusCode, code) - return dummyStatus - } - strconvItoaExpected = 1 - strconvItoa = func(i int) string { - strconvItoaCalled++ - assert.Equal(t, dummyStatusCode, i) - return strconv.Itoa(i) - } - logWebcallResponseFuncExpected = 2 - logWebcallResponseFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logWebcallResponseFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, "Content", subcategory) - assert.Empty(t, parameters) - if logWebcallResponseFuncCalled == 1 { - assert.Equal(t, "Header", category) - assert.Equal(t, dummyHeaderContent, messageFormat) - } else if logWebcallResponseFuncCalled == 2 { - assert.Equal(t, "Body", category) - assert.Equal(t, dummyResponseBody, messageFormat) - } - } - marshalIgnoreErrorFuncExpected = 1 - marshalIgnoreErrorFunc = func(v interface{}) string { - marshalIgnoreErrorFuncCalled++ - assert.Equal(t, dummyHeader, v) - return dummyHeaderContent - } - timeSinceExpected = 1 - timeSince = func(ts time.Time) time.Duration { - timeSinceCalled++ - assert.Equal(t, dummyStartTime, ts) - return dummyTimeSince - } - logWebcallFinishFuncExpected = 1 - logWebcallFinishFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logWebcallFinishFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, dummyStatus, category) - assert.Equal(t, strconv.Itoa(dummyStatusCode), subcategory) - assert.Equal(t, "%s", messageFormat) - assert.Equal(t, 1, len(parameters)) - assert.Equal(t, dummyTimeSince, parameters[0]) - } + m.Mock(io.ReadAll).Expects(dummyBody).Returns(dummyResponseBytes, dummyError).Once() + m.Mock(bytes.NewBuffer).Expects(dummyResponseBytes).Returns(dummyBuffer).Once() + m.Mock(io.NopCloser).Expects(dummyBuffer).Returns(dummyNewBody).Once() + m.Mock(http.StatusText).Expects(dummyStatusCode).Returns(dummyStatus).Once() + m.Mock(logWebcallResponse).Expects(dummySession, "Header", "Content", dummyHeaderContent).Returns().Once() + m.Mock(logWebcallResponse).Expects(dummySession, "Body", "Content", dummyResponseBody).Returns().Once() + m.Mock(marshalIgnoreError).Expects(gomocker.Anything()).Returns(dummyHeaderContent).Once() + m.Mock(time.Since).Expects(dummyStartTime).Returns(dummyTimeSince).Once() + m.Mock(logWebcallFinish).Expects(dummySession, dummyStatus, strconv.Itoa(dummyStatusCode), "%s", dummyTimeSince).Returns().Once() // SUT + act logSuccessResponse( @@ -1395,9 +917,6 @@ func TestLogSuccessResponse_ValidResponse(t *testing.T) { // assert assert.Equal(t, dummyNewBody, dummyResponse.Body) - - // verify - verifyAll(t) } func TestDoRequestProcessing_NilWebRequest(t *testing.T) { @@ -1406,16 +925,10 @@ func TestDoRequestProcessing_NilWebRequest(t *testing.T) { var dummyError = errors.New("some error message") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - fmtErrorfExpected = 1 - fmtErrorf = func(format string, a ...interface{}) error { - fmtErrorfCalled++ - assert.Equal(t, "WebRequest is nil or contains invalid session", format) - assert.Empty(t, a) - return dummyError - } + m.Mock(fmt.Errorf).Expects("WebRequest is nil or contains invalid session").Returns(dummyError).Once() // SUT + act var result, err = doRequestProcessing( @@ -1425,9 +938,6 @@ func TestDoRequestProcessing_NilWebRequest(t *testing.T) { // assert assert.Nil(t, result) assert.Equal(t, dummyError, err) - - // verify - verifyAll(t) } func TestDoRequestProcessing_NilWebRequestSession(t *testing.T) { @@ -1436,16 +946,10 @@ func TestDoRequestProcessing_NilWebRequestSession(t *testing.T) { var dummyError = errors.New("some error message") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - fmtErrorfExpected = 1 - fmtErrorf = func(format string, a ...interface{}) error { - fmtErrorfCalled++ - assert.Equal(t, "WebRequest is nil or contains invalid session", format) - assert.Empty(t, a) - return dummyError - } + m.Mock(fmt.Errorf).Expects("WebRequest is nil or contains invalid session").Returns(dummyError).Once() // SUT + act var result, err = doRequestProcessing( @@ -1455,9 +959,6 @@ func TestDoRequestProcessing_NilWebRequestSession(t *testing.T) { // assert assert.Nil(t, result) assert.Equal(t, dummyError, err) - - // verify - verifyAll(t) } func TestDoRequestProcessing_RequestError(t *testing.T) { @@ -1469,15 +970,10 @@ func TestDoRequestProcessing_RequestError(t *testing.T) { var dummyRequestError = errors.New("some error") // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - createHTTPRequestFuncExpected = 1 - createHTTPRequestFunc = func(webRequest *webRequest) (*http.Request, error) { - createHTTPRequestFuncCalled++ - assert.Equal(t, dummyWebRequest, webRequest) - return dummyRequestObject, dummyRequestError - } + m.Mock(createHTTPRequest).Expects(dummyWebRequest).Returns(dummyRequestObject, dummyRequestError).Once() // SUT + act var result, err = doRequestProcessing( @@ -1487,9 +983,6 @@ func TestDoRequestProcessing_RequestError(t *testing.T) { // assert assert.Nil(t, result) assert.Equal(t, dummyRequestError, err) - - // verify - verifyAll(t) } func TestDoRequestProcessing_ResponseError(t *testing.T) { @@ -1500,8 +993,8 @@ func TestDoRequestProcessing_ResponseError(t *testing.T) { rand.Int(): rand.Int(), rand.Int(): rand.Int(), } - var dummySendClientCert = rand.Intn(100) < 50 - var dummyRetryDelay = time.Duration(rand.Intn(100)) + var dummySendClientCert = rand.IntN(100) < 50 + var dummyRetryDelay = time.Duration(rand.IntN(100)) var dummyWebRequest = &webRequest{ session: dummySession, connRetry: dummyConnRetry, @@ -1513,46 +1006,17 @@ func TestDoRequestProcessing_ResponseError(t *testing.T) { var dummyRequestObject = &http.Request{} var dummyResponseObject *http.Response var dummyResponseError = errors.New("some error") - var dummyStartTime = time.Now() + var dummyStartTime = time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC) // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - createHTTPRequestFuncExpected = 1 - createHTTPRequestFunc = func(webRequest *webRequest) (*http.Request, error) { - createHTTPRequestFuncCalled++ - assert.Equal(t, dummyWebRequest, webRequest) - return dummyRequestObject, nil - } - getClientForRequestFuncExpected = 1 - getClientForRequestFunc = func(sendClientCert bool) *http.Client { - getClientForRequestFuncCalled++ - assert.Equal(t, dummySendClientCert, sendClientCert) - return dummyHTTPClient - } - getTimeNowUTCFuncExpected = 1 - getTimeNowUTCFunc = func() time.Time { - getTimeNowUTCFuncCalled++ - return dummyStartTime - } - clientDoWithRetryFuncExpected = 1 - clientDoWithRetryFunc = func(client *http.Client, request *http.Request, connRetry int, httpRetry map[int]int, retryDelay time.Duration) (*http.Response, error) { - clientDoWithRetryFuncCalled++ - assert.Equal(t, dummyHTTPClient, client) - assert.Equal(t, dummyRequestObject, request) - assert.Equal(t, dummyConnRetry, connRetry) - assert.Equal(t, dummyHTTPRetry, httpRetry) - assert.Equal(t, dummyRetryDelay, retryDelay) - return dummyResponseObject, dummyResponseError - } - logErrorResponseFuncExpected = 1 - logErrorResponseFunc = func(session *session, responseError error, startTime time.Time) { - logErrorResponseFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, dummyResponseError, responseError) - assert.Equal(t, dummyStartTime, startTime) - } + m.Mock(createHTTPRequest).Expects(dummyWebRequest).Returns(dummyRequestObject, nil).Once() + m.Mock(getClientForRequest).Expects(dummySendClientCert).Returns(dummyHTTPClient).Once() + m.Mock(time.Now).Expects().Returns(dummyStartTime).Once() + m.Mock(clientDoWithRetry).Expects(dummyHTTPClient, dummyRequestObject, dummyConnRetry, dummyHTTPRetry, dummyRetryDelay).Returns(dummyResponseObject, dummyResponseError).Once() + m.Mock(logErrorResponse).Expects(dummySession, dummyResponseError, dummyStartTime).Returns().Once() // SUT + act var result, err = doRequestProcessing( @@ -1562,9 +1026,6 @@ func TestDoRequestProcessing_ResponseError(t *testing.T) { // assert assert.Equal(t, dummyResponseObject, result) assert.Equal(t, dummyResponseError, err) - - // verify - verifyAll(t) } func TestDoRequestProcessing_ResponseSuccess(t *testing.T) { @@ -1575,8 +1036,8 @@ func TestDoRequestProcessing_ResponseSuccess(t *testing.T) { rand.Int(): rand.Int(), rand.Int(): rand.Int(), } - var dummySendClientCert = rand.Intn(100) < 50 - var dummyRetryDelay = time.Duration(rand.Intn(100)) + var dummySendClientCert = rand.IntN(100) < 50 + var dummyRetryDelay = time.Duration(rand.IntN(100)) var dummyWebRequest = &webRequest{ session: dummySession, connRetry: dummyConnRetry, @@ -1587,46 +1048,17 @@ func TestDoRequestProcessing_ResponseSuccess(t *testing.T) { var dummyHTTPClient = &http.Client{} var dummyRequestObject = &http.Request{} var dummyResponseObject = &http.Response{} - var dummyStartTime = time.Now() + var dummyStartTime = time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC) // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - createHTTPRequestFuncExpected = 1 - createHTTPRequestFunc = func(webRequest *webRequest) (*http.Request, error) { - createHTTPRequestFuncCalled++ - assert.Equal(t, dummyWebRequest, webRequest) - return dummyRequestObject, nil - } - getClientForRequestFuncExpected = 1 - getClientForRequestFunc = func(sendClientCert bool) *http.Client { - getClientForRequestFuncCalled++ - assert.Equal(t, dummySendClientCert, sendClientCert) - return dummyHTTPClient - } - getTimeNowUTCFuncExpected = 1 - getTimeNowUTCFunc = func() time.Time { - getTimeNowUTCFuncCalled++ - return dummyStartTime - } - clientDoWithRetryFuncExpected = 1 - clientDoWithRetryFunc = func(client *http.Client, request *http.Request, connRetry int, httpRetry map[int]int, retryDelay time.Duration) (*http.Response, error) { - clientDoWithRetryFuncCalled++ - assert.Equal(t, dummyHTTPClient, client) - assert.Equal(t, dummyRequestObject, request) - assert.Equal(t, dummyConnRetry, connRetry) - assert.Equal(t, dummyHTTPRetry, httpRetry) - assert.Equal(t, dummyRetryDelay, retryDelay) - return dummyResponseObject, nil - } - logSuccessResponseFuncExpected = 1 - logSuccessResponseFunc = func(session *session, response *http.Response, startTime time.Time) { - logSuccessResponseFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, dummyResponseObject, response) - assert.Equal(t, dummyStartTime, startTime) - } + m.Mock(createHTTPRequest).Expects(dummyWebRequest).Returns(dummyRequestObject, nil).Once() + m.Mock(getClientForRequest).Expects(dummySendClientCert).Returns(dummyHTTPClient).Once() + m.Mock(time.Now).Expects().Returns(dummyStartTime).Once() + m.Mock(clientDoWithRetry).Expects(dummyHTTPClient, dummyRequestObject, dummyConnRetry, dummyHTTPRetry, dummyRetryDelay).Returns(dummyResponseObject, nil).Once() + m.Mock(logSuccessResponse).Expects(dummySession, dummyResponseObject, dummyStartTime).Returns().Once() // SUT + act var result, err = doRequestProcessing( @@ -1636,37 +1068,20 @@ func TestDoRequestProcessing_ResponseSuccess(t *testing.T) { // assert assert.Equal(t, dummyResponseObject, result) assert.NoError(t, err) - - // verify - verifyAll(t) } func TestGetDataTemplate_EmptyDataReceivers(t *testing.T) { // arrange var dummySession = &session{} - var dummyStatusCode = rand.Intn(100) + var dummyStatusCode = rand.IntN(100) var dummyDataReceivers = []dataReceiver{} // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - isInterfaceValueNilFuncExpected = 1 - isInterfaceValueNilFunc = func(i interface{}) bool { - isInterfaceValueNilFuncCalled++ - assert.Nil(t, i) - return true - } - logWebcallResponseFuncExpected = 1 - logWebcallResponseFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logWebcallResponseFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, "Body", category) - assert.Equal(t, "Receiver", subcategory) - assert.Equal(t, "No data template registered for HTTP status %v", messageFormat) - assert.Equal(t, 1, len(parameters)) - assert.Equal(t, dummyStatusCode, parameters[0]) - } + m.Mock(isInterfaceValueNil).Expects(nil).Returns(true).Once() + m.Mock(logWebcallResponse).Expects(dummySession, "Body", "Receiver", "No data template registered for HTTP status %v", dummyStatusCode).Returns().Once() // SUT + act var result = getDataTemplate( @@ -1677,44 +1092,27 @@ func TestGetDataTemplate_EmptyDataReceivers(t *testing.T) { // assert assert.Nil(t, result) - - // verify - verifyAll(t) } func TestGetDataTemplate_NoMatch(t *testing.T) { // arrange var dummySession = &session{} - var dummyStatusCode = rand.Intn(100) + var dummyStatusCode = rand.IntN(100) var dummyDataTemplate string var dummyDataReceivers = []dataReceiver{ { - beginStatusCode: rand.Intn(100) + 100, - endStatusCode: rand.Intn(100) + 200, + beginStatusCode: rand.IntN(100) + 100, + endStatusCode: rand.IntN(100) + 200, dataTemplate: &dummyDataTemplate, }, } // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - isInterfaceValueNilFuncExpected = 1 - isInterfaceValueNilFunc = func(i interface{}) bool { - isInterfaceValueNilFuncCalled++ - assert.Nil(t, i) - return true - } - logWebcallResponseFuncExpected = 1 - logWebcallResponseFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logWebcallResponseFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, "Body", category) - assert.Equal(t, "Receiver", subcategory) - assert.Equal(t, "No data template registered for HTTP status %v", messageFormat) - assert.Equal(t, 1, len(parameters)) - assert.Equal(t, dummyStatusCode, parameters[0]) - } + m.Mock(isInterfaceValueNil).Expects(nil).Returns(true).Once() + m.Mock(logWebcallResponse).Expects(dummySession, "Body", "Receiver", "No data template registered for HTTP status %v", dummyStatusCode).Returns().Once() // SUT + act var result = getDataTemplate( @@ -1725,40 +1123,32 @@ func TestGetDataTemplate_NoMatch(t *testing.T) { // assert assert.Nil(t, result) - - // verify - verifyAll(t) } func TestGetDataTemplate_SingleMatch(t *testing.T) { // arrange var dummySession = &session{} - var dummyStatusCode = rand.Intn(100) + var dummyStatusCode = rand.IntN(100) var dummyDataTemplate1 string var dummyDataTemplate2 int var dummyDataReceivers = []dataReceiver{ { - beginStatusCode: dummyStatusCode - rand.Intn(10), - endStatusCode: dummyStatusCode + 1 + rand.Intn(10), + beginStatusCode: dummyStatusCode - rand.IntN(10), + endStatusCode: dummyStatusCode + 1 + rand.IntN(10), dataTemplate: &dummyDataTemplate1, }, { - beginStatusCode: rand.Intn(100) + 100, - endStatusCode: rand.Intn(100) + 200, + beginStatusCode: rand.IntN(100) + 100, + endStatusCode: rand.IntN(100) + 200, dataTemplate: &dummyDataTemplate2, }, } // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - isInterfaceValueNilFuncExpected = 1 - isInterfaceValueNilFunc = func(i interface{}) bool { - isInterfaceValueNilFuncCalled++ - assert.Equal(t, &dummyDataTemplate1, i) - return false - } + m.Mock(isInterfaceValueNil).Expects(&dummyDataTemplate1).Returns(false).Once() // SUT + act var result = getDataTemplate( @@ -1769,40 +1159,32 @@ func TestGetDataTemplate_SingleMatch(t *testing.T) { // assert assert.Equal(t, &dummyDataTemplate1, result) - - // verify - verifyAll(t) } func TestGetDataTemplate_OverlapMatch(t *testing.T) { // arrange var dummySession = &session{} - var dummyStatusCode = rand.Intn(100) + var dummyStatusCode = rand.IntN(100) var dummyDataTemplate1 string var dummyDataTemplate2 int var dummyDataReceivers = []dataReceiver{ { - beginStatusCode: dummyStatusCode - rand.Intn(10), - endStatusCode: dummyStatusCode + 1 + rand.Intn(10), + beginStatusCode: dummyStatusCode - rand.IntN(10), + endStatusCode: dummyStatusCode + 1 + rand.IntN(10), dataTemplate: &dummyDataTemplate1, }, { - beginStatusCode: dummyStatusCode - rand.Intn(10), - endStatusCode: dummyStatusCode + 1 + rand.Intn(10), + beginStatusCode: dummyStatusCode - rand.IntN(10), + endStatusCode: dummyStatusCode + 1 + rand.IntN(10), dataTemplate: &dummyDataTemplate2, }, } // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - isInterfaceValueNilFuncExpected = 1 - isInterfaceValueNilFunc = func(i interface{}) bool { - isInterfaceValueNilFuncCalled++ - assert.Equal(t, &dummyDataTemplate2, i) - return false - } + m.Mock(isInterfaceValueNil).Expects(&dummyDataTemplate2).Returns(false).Once() // SUT + act var result = getDataTemplate( @@ -1813,29 +1195,21 @@ func TestGetDataTemplate_OverlapMatch(t *testing.T) { // assert assert.Equal(t, &dummyDataTemplate2, result) - - // verify - verifyAll(t) } func TestParseResponse_ReadError(t *testing.T) { // arrange var dummySession = &session{id: uuid.New()} - var dummyBody = ioutil.NopCloser(bytes.NewBufferString("some body")) + var dummyBody = io.NopCloser(bytes.NewBufferString("some body")) var dummyBytes = []byte("some bytes") var dummyError = errors.New("some error") var dummyDataTemplate string // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - ioutilReadAllExpected = 1 - ioutilReadAll = func(r io.Reader) ([]byte, error) { - ioutilReadAllCalled++ - assert.Equal(t, dummyBody, r) - return dummyBytes, dummyError - } + m.Mock(io.ReadAll).Expects(dummyBody).Returns(dummyBytes, dummyError).Once() // SUT + act var err = parseResponse( @@ -1847,45 +1221,23 @@ func TestParseResponse_ReadError(t *testing.T) { // assert assert.Zero(t, dummyDataTemplate) assert.Equal(t, dummyError, err) - - // verify - verifyAll(t) } func TestParseResponse_JSONError(t *testing.T) { // arrange var dummySession = &session{id: uuid.New()} - var dummyBody = ioutil.NopCloser(bytes.NewBufferString("some body")) + var dummyBody = io.NopCloser(bytes.NewBufferString("some body")) var dummyBytes = []byte("some bytes") var dummyError = errors.New("some error") var dummyDataTemplate string // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - ioutilReadAllExpected = 1 - ioutilReadAll = func(r io.Reader) ([]byte, error) { - ioutilReadAllCalled++ - assert.Equal(t, dummyBody, r) - return dummyBytes, nil - } - tryUnmarshalFuncExpected = 1 - tryUnmarshalFunc = func(value string, dataTemplate interface{}) error { - tryUnmarshalFuncCalled++ - assert.Equal(t, string(dummyBytes), value) - return dummyError - } - logWebcallResponseFuncExpected = 1 - logWebcallResponseFunc = func(session *session, category string, subcategory string, messageFormat string, parameters ...interface{}) { - logWebcallResponseFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, "Body", category) - assert.Equal(t, "UnmarshalError", subcategory) - assert.Equal(t, "%+v", messageFormat) - assert.Equal(t, 1, len(parameters)) - assert.Equal(t, dummyError, parameters[0]) - } + m.Mock(io.ReadAll).Expects(dummyBody).Returns(dummyBytes, nil).Once() + m.Mock(tryUnmarshal).Expects(string(dummyBytes), gomocker.Anything()).Returns(dummyError).Once() + m.Mock(logWebcallResponse).Expects(dummySession, "Body", "UnmarshalError", "%+v", dummyError).Returns().Once() // SUT + act var err = parseResponse( @@ -1897,36 +1249,24 @@ func TestParseResponse_JSONError(t *testing.T) { // assert assert.Zero(t, dummyDataTemplate) assert.Equal(t, dummyError, err) - - // verify - verifyAll(t) } func TestParseResponse_HappyPath(t *testing.T) { // arrange var dummySession = &session{id: uuid.New()} - var dummyBody = ioutil.NopCloser(bytes.NewBufferString("some body")) + var dummyBody = io.NopCloser(bytes.NewBufferString("some body")) var dummyData = "some data" var dummyBytes = []byte("\"" + dummyData + "\"") var dummyDataTemplate string // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - ioutilReadAllExpected = 1 - ioutilReadAll = func(r io.Reader) ([]byte, error) { - ioutilReadAllCalled++ - assert.Equal(t, dummyBody, r) - return dummyBytes, nil - } - tryUnmarshalFuncExpected = 1 - tryUnmarshalFunc = func(value string, dataTemplate interface{}) error { - tryUnmarshalFuncCalled++ - assert.Equal(t, string(dummyBytes), value) - (*(dataTemplate).(*string)) = dummyData - return nil - } + m.Mock(io.ReadAll).Expects(dummyBody).Returns(dummyBytes, nil).Once() + m.Mock(tryUnmarshal).Expects(string(dummyBytes), gomocker.Anything()).Returns(nil).SideEffect(func(index int, params ...interface{}) { + (*(params[1]).(*string)) = dummyData + }).Once() // SUT + act var err = parseResponse( @@ -1938,9 +1278,6 @@ func TestParseResponse_HappyPath(t *testing.T) { // assert assert.Equal(t, dummyData, dummyDataTemplate) assert.NoError(t, err) - - // verify - verifyAll(t) } func TestWebRequestProcess_NilWebRequest(t *testing.T) { @@ -1951,27 +1288,18 @@ func TestWebRequestProcess_NilWebRequest(t *testing.T) { var sut *webRequest // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - fmtErrorfExpected = 1 - fmtErrorf = func(format string, a ...interface{}) error { - fmtErrorfCalled++ - assert.Equal(t, "WebRequest is nil or contains invalid session", format) - assert.Empty(t, a) - return dummyError - } + m.Mock(fmt.Errorf).Expects("WebRequest is nil or contains invalid session").Returns(dummyError).Once() // act var result, header, err = sut.Process() // assert - assert.Zero(t, result) - assert.Nil(t, header) + assert.Equal(t, 0, result) + assert.Empty(t, header) assert.Equal(t, dummyError, err) - - // verify - verifyAll(t) } func TestWebRequestProcess_NilWebRequestSession(t *testing.T) { @@ -1982,27 +1310,18 @@ func TestWebRequestProcess_NilWebRequestSession(t *testing.T) { var sut = &webRequest{} // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - fmtErrorfExpected = 1 - fmtErrorf = func(format string, a ...interface{}) error { - fmtErrorfCalled++ - assert.Equal(t, "WebRequest is nil or contains invalid session", format) - assert.Empty(t, a) - return dummyError - } + m.Mock(fmt.Errorf).Expects("WebRequest is nil or contains invalid session").Returns(dummyError).Once() // act var result, header, err = sut.Process() // assert - assert.Zero(t, result) - assert.Nil(t, header) + assert.Equal(t, 0, result) + assert.Empty(t, header) assert.Equal(t, dummyError, err) - - // verify - verifyAll(t) } func TestWebRequestProcess_Error_NilObject(t *testing.T) { @@ -2016,15 +1335,10 @@ func TestWebRequestProcess_Error_NilObject(t *testing.T) { } // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - doRequestProcessingFuncExpected = 1 - doRequestProcessingFunc = func(webRequest *webRequest) (*http.Response, error) { - doRequestProcessingFuncCalled++ - assert.Equal(t, sut, webRequest) - return dummyResponseObject, dummyResponseError - } + m.Mock(doRequestProcessing).Expects(sut).Returns(dummyResponseObject, dummyResponseError).Once() // act var result, header, err = sut.Process() @@ -2033,9 +1347,6 @@ func TestWebRequestProcess_Error_NilObject(t *testing.T) { assert.Equal(t, http.StatusInternalServerError, result) assert.Empty(t, header) assert.Equal(t, dummyResponseError, err) - - // verify - verifyAll(t) } func TestWebRequestProcess_Error_ValidObject(t *testing.T) { @@ -2057,15 +1368,10 @@ func TestWebRequestProcess_Error_ValidObject(t *testing.T) { } // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - doRequestProcessingFuncExpected = 1 - doRequestProcessingFunc = func(webRequest *webRequest) (*http.Response, error) { - doRequestProcessingFuncCalled++ - assert.Equal(t, sut, webRequest) - return dummyResponseObject, dummyResponseError - } + m.Mock(doRequestProcessing).Expects(sut).Returns(dummyResponseObject, dummyResponseError).Once() // act var result, header, err = sut.Process() @@ -2074,9 +1380,6 @@ func TestWebRequestProcess_Error_ValidObject(t *testing.T) { assert.Equal(t, dummyStatusCode, result) assert.Equal(t, http.Header(dummyHeader), header) assert.Equal(t, dummyResponseError, err) - - // verify - verifyAll(t) } func TestWebRequestProcess_Success_NilObject(t *testing.T) { @@ -2090,15 +1393,10 @@ func TestWebRequestProcess_Success_NilObject(t *testing.T) { } // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - doRequestProcessingFuncExpected = 1 - doRequestProcessingFunc = func(webRequest *webRequest) (*http.Response, error) { - doRequestProcessingFuncCalled++ - assert.Equal(t, sut, webRequest) - return dummyResponseObject, dummyResponseError - } + m.Mock(doRequestProcessing).Expects(sut).Returns(dummyResponseObject, dummyResponseError).Once() // act var result, header, err = sut.Process() @@ -2107,9 +1405,6 @@ func TestWebRequestProcess_Success_NilObject(t *testing.T) { assert.Zero(t, result) assert.Empty(t, header) assert.NoError(t, err) - - // verify - verifyAll(t) } func TestWebRequestProcess_Success_ValidObject(t *testing.T) { @@ -2119,7 +1414,7 @@ func TestWebRequestProcess_Success_ValidObject(t *testing.T) { "foo": {"bar"}, "test": {"123", "456", "789"}, } - var dummyBody = ioutil.NopCloser(bytes.NewBufferString("some body")) + var dummyBody = io.NopCloser(bytes.NewBufferString("some body")) var dummyResponseObject = &http.Response{ StatusCode: dummyStatusCode, Header: dummyHeader, @@ -2141,31 +1436,14 @@ func TestWebRequestProcess_Success_ValidObject(t *testing.T) { } // mock - createMock(t) + var m = gomocker.NewMocker(t) // expect - doRequestProcessingFuncExpected = 1 - doRequestProcessingFunc = func(webRequest *webRequest) (*http.Response, error) { - doRequestProcessingFuncCalled++ - assert.Equal(t, sut, webRequest) - return dummyResponseObject, dummyResponseError - } - getDataTemplateFuncExpected = 1 - getDataTemplateFunc = func(session *session, statusCode int, dataReceivers []dataReceiver) interface{} { - getDataTemplateFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, dummyStatusCode, statusCode) - assert.Equal(t, dummyDataReceivers, dataReceivers) - return &dummyDataTemplate - } - parseResponseFuncExpected = 1 - parseResponseFunc = func(session *session, body io.ReadCloser, dataTemplate interface{}) error { - parseResponseFuncCalled++ - assert.Equal(t, dummySession, session) - assert.Equal(t, dummyBody, body) - (*(dataTemplate).(*string)) = dummyData - return dummyParseError - } + m.Mock(doRequestProcessing).Expects(sut).Returns(dummyResponseObject, dummyResponseError).Once() + m.Mock(getDataTemplate).Expects(dummySession, dummyStatusCode, dummyDataReceivers).Returns(&dummyDataTemplate).Once() + m.Mock(parseResponse).Expects(dummySession, dummyBody, gomocker.Anything()).Returns(dummyParseError).SideEffect(func(index int, params ...interface{}) { + (*(params[2]).(*string)) = dummyData + }).Once() // act var result, header, err = sut.Process() @@ -2175,7 +1453,4 @@ func TestWebRequestProcess_Success_ValidObject(t *testing.T) { assert.Equal(t, dummyStatusCode, result) assert.Equal(t, http.Header(dummyHeader), header) assert.Equal(t, dummyParseError, err) - - // verify - verifyAll(t) }