From 16f37c0f641ef583d4da3a7729df90279ac43eea Mon Sep 17 00:00:00 2001 From: Reza Mobaraki Date: Thu, 22 Aug 2024 18:32:36 +0330 Subject: [PATCH 01/22] Chore(MakeFile): add .PHONY Signed-off-by: Reza Mobaraki --- Makefile | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 8771526e..cd7b08fc 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,9 @@ -// TODO: add commands for build and run in dev/produciton mode +# TODO: add commands for build and run in dev/produciton mode ROOT=$(realpath $(dir $(lastword $(MAKEFILE_LIST)))) +.PHONY: help confirm lint test format build run docker swagger watch migrate/status migrate/new migrate/up migrate/down + confirm: @echo -n 'Are you sure? [y/N] ' && read ans && [ $${ans:-N} = y ] From 6c78c8098af9e1b3e45d9365a0fba384b1a9db69 Mon Sep 17 00:00:00 2001 From: Reza Mobaraki Date: Fri, 23 Aug 2024 15:54:27 +0330 Subject: [PATCH 02/22] Chore(benefactor-kindBoxReqs-test): add tests - Get_Success - GetAll_Success - Create_Success Signed-off-by: Reza Mobaraki --- .../end2end/benefactor_kindboxreqs_test.go | 124 ++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 delivery/http_server/end2end/benefactor_kindboxreqs_test.go diff --git a/delivery/http_server/end2end/benefactor_kindboxreqs_test.go b/delivery/http_server/end2end/benefactor_kindboxreqs_test.go new file mode 100644 index 00000000..5be7d066 --- /dev/null +++ b/delivery/http_server/end2end/benefactor_kindboxreqs_test.go @@ -0,0 +1,124 @@ +//go:build end2end + +package end2end + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "git.gocasts.ir/ebhomengo/niki/delivery/http_server/end2end/setup" + "git.gocasts.ir/ebhomengo/niki/entity" + benefactoreparam "git.gocasts.ir/ebhomengo/niki/param/benefactor/benefactor" + benefactorkindboxreqparam "git.gocasts.ir/ebhomengo/niki/param/benefactor/kind_box_req" + "github.com/labstack/echo/v4" + "github.com/stretchr/testify/assert" + "net/http" + "net/http/httptest" + "testing" + "time" +) + +func loginBenefactor(t *testing.T) string { + // TODO: Consider mocking the OTP service & fetching the verification code from Redis. + phone := "09384664404" + sendOTPRes, err := services.BenefactorSvc.SendOtp(context.Background(), benefactoreparam.SendOtpRequest{ + PhoneNumber: phone, + }) + if err != nil { + t.Fatalf("failed to send OTP: %s", err) + } + registerRes, err := services.BenefactorSvc.LoginOrRegister(context.Background(), benefactoreparam.LoginOrRegisterRequest{ + PhoneNumber: phone, + VerificationCode: sendOTPRes.Code, + }) + if err != nil { + t.Fatalf("failed to login or register: %s", err) + } + return registerRes.Tokens.AccessToken +} + +func TestBenefactorKindBoxReqs_GetAll_Success(t *testing.T) { + teardown := setup.SeedMariaDB(testContainer.GetMariaDBConfig()) + t.Cleanup(teardown) + + token := fmt.Sprintf("Bearer %s", loginBenefactor(t)) + + req := httptest.NewRequest(http.MethodGet, "/benefactor/kindboxreqs/", nil) + req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) + req.Header.Set(echo.HeaderAuthorization, token) + rec := httptest.NewRecorder() + testServer.Serve(rec, req) + + assert.Equal(t, http.StatusOK, rec.Code) + +} + +func TestBenefactorKindBoxReqs_Create_Success(t *testing.T) { + teardown := setup.SeedMariaDB(testContainer.GetMariaDBConfig()) + t.Cleanup(teardown) + + token := fmt.Sprintf("Bearer %s", loginBenefactor(t)) + + newKindBox := benefactorkindboxreqparam.KindBoxReqAddRequest{ + KindBoxType: entity.KindBoxOnTable, + DeliverAddressID: 1, + DeliverReferDate: time.Date(2025, time.January, 2, 15, 4, 5, 0, time.UTC), + DeliverReferTimeID: 1, + CountRequested: 2, + } + + requestBody, err := json.Marshal(newKindBox) + if err != nil { + t.Fatalf("failed to marshal request body: %s", err) + } + + req := httptest.NewRequest(http.MethodPost, "/benefactor/kindboxreqs/", bytes.NewBuffer(requestBody)) + req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) + req.Header.Set(echo.HeaderAuthorization, token) + + rec := httptest.NewRecorder() + testServer.Serve(rec, req) + + assert.Equal(t, http.StatusCreated, rec.Code) + + var response benefactorkindboxreqparam.KindBoxReqAddResponse + err = json.NewDecoder(rec.Body).Decode(&response) + if err != nil { + t.Fatalf("failed to decode response body: %s", err) + } + assert.Equal(t, newKindBox.KindBoxType, response.KindBoxReq.KindBoxType) + assert.Equal(t, newKindBox.DeliverAddressID, response.KindBoxReq.DeliverAddressID) + assert.Equal(t, newKindBox.DeliverReferDate, response.KindBoxReq.DeliverReferDate) + assert.Equal(t, newKindBox.DeliverReferTimeID, response.KindBoxReq.DeliverReferTimeID) + assert.Equal(t, newKindBox.CountRequested, response.KindBoxReq.CountRequested) +} + +func TestBenefactorKindBoxReqs_Get_Success(t *testing.T) { + teardown := setup.SeedMariaDB(testContainer.GetMariaDBConfig()) + t.Cleanup(teardown) + + token := fmt.Sprintf("Bearer %s", loginBenefactor(t)) + + var kindBoxReqID uint = 1 + req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/benefactor/kindboxreqs/%d", kindBoxReqID), nil) + req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) + req.Header.Set(echo.HeaderAuthorization, token) + rec := httptest.NewRecorder() + testServer.Serve(rec, req) + + assert.Equal(t, http.StatusOK, rec.Code) + + var response benefactorkindboxreqparam.KindBoxReqGetResponse + err := json.NewDecoder(rec.Body).Decode(&response) + if err != nil { + t.Fatalf("failed to decode response body: %s", err) + } + + assert.Equal(t, kindBoxReqID, response.KindBoxReq.ID) + assert.Equal(t, entity.KindBoxOnTable, response.KindBoxReq.KindBoxType) + assert.Equal(t, uint(1), response.KindBoxReq.DeliverAddressID) + expectedDate := time.Now().AddDate(0, 0, 7) + assert.Equal(t, expectedDate.Format("2006-01-02"), response.KindBoxReq.DeliverReferDate.Format("2006-01-02")) + assert.Equal(t, uint(1), response.KindBoxReq.DeliverReferTimeID) +} From 15f37001db9bf7a764cd636e4011d5b72da14fbe Mon Sep 17 00:00:00 2001 From: Reza Mobaraki Date: Fri, 23 Aug 2024 17:58:44 +0330 Subject: [PATCH 03/22] Chore(benefactor-kindBoxReqs-test): make it cleaner Signed-off-by: Reza Mobaraki --- .../end2end/benefactor_kindboxreqs_test.go | 78 +++++++++++++------ 1 file changed, 56 insertions(+), 22 deletions(-) diff --git a/delivery/http_server/end2end/benefactor_kindboxreqs_test.go b/delivery/http_server/end2end/benefactor_kindboxreqs_test.go index 5be7d066..b0530178 100644 --- a/delivery/http_server/end2end/benefactor_kindboxreqs_test.go +++ b/delivery/http_server/end2end/benefactor_kindboxreqs_test.go @@ -38,28 +38,36 @@ func loginBenefactor(t *testing.T) string { return registerRes.Tokens.AccessToken } +// Utility function to create and send HTTP requests +func createRequest(t *testing.T, method, url string, body interface{}) *httptest.ResponseRecorder { + var buf bytes.Buffer + if body != nil { + if err := json.NewEncoder(&buf).Encode(body); err != nil { + t.Fatalf("could not encode body: %s", err) + } + } + token := loginBenefactor(t) + req := httptest.NewRequest(method, url, &buf) + req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) + req.Header.Set(echo.HeaderAuthorization, fmt.Sprintf("Bearer %s", token)) + rec := httptest.NewRecorder() + testServer.Serve(rec, req) + return rec +} + func TestBenefactorKindBoxReqs_GetAll_Success(t *testing.T) { teardown := setup.SeedMariaDB(testContainer.GetMariaDBConfig()) t.Cleanup(teardown) - token := fmt.Sprintf("Bearer %s", loginBenefactor(t)) - - req := httptest.NewRequest(http.MethodGet, "/benefactor/kindboxreqs/", nil) - req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) - req.Header.Set(echo.HeaderAuthorization, token) - rec := httptest.NewRecorder() - testServer.Serve(rec, req) + rec := createRequest(t, http.MethodGet, "/benefactor/kindboxreqs/", nil) assert.Equal(t, http.StatusOK, rec.Code) - } func TestBenefactorKindBoxReqs_Create_Success(t *testing.T) { teardown := setup.SeedMariaDB(testContainer.GetMariaDBConfig()) t.Cleanup(teardown) - token := fmt.Sprintf("Bearer %s", loginBenefactor(t)) - newKindBox := benefactorkindboxreqparam.KindBoxReqAddRequest{ KindBoxType: entity.KindBoxOnTable, DeliverAddressID: 1, @@ -68,22 +76,12 @@ func TestBenefactorKindBoxReqs_Create_Success(t *testing.T) { CountRequested: 2, } - requestBody, err := json.Marshal(newKindBox) - if err != nil { - t.Fatalf("failed to marshal request body: %s", err) - } - - req := httptest.NewRequest(http.MethodPost, "/benefactor/kindboxreqs/", bytes.NewBuffer(requestBody)) - req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) - req.Header.Set(echo.HeaderAuthorization, token) - - rec := httptest.NewRecorder() - testServer.Serve(rec, req) + rec := createRequest(t, http.MethodPost, "/benefactor/kindboxreqs/", newKindBox) assert.Equal(t, http.StatusCreated, rec.Code) var response benefactorkindboxreqparam.KindBoxReqAddResponse - err = json.NewDecoder(rec.Body).Decode(&response) + err := json.NewDecoder(rec.Body).Decode(&response) if err != nil { t.Fatalf("failed to decode response body: %s", err) } @@ -122,3 +120,39 @@ func TestBenefactorKindBoxReqs_Get_Success(t *testing.T) { assert.Equal(t, expectedDate.Format("2006-01-02"), response.KindBoxReq.DeliverReferDate.Format("2006-01-02")) assert.Equal(t, uint(1), response.KindBoxReq.DeliverReferTimeID) } + +func TestBenefactorKindBoxReqs_Update_Success(t *testing.T) { + teardown := setup.SeedMariaDB(testContainer.GetMariaDBConfig()) + t.Cleanup(teardown) + + token := fmt.Sprintf("Bearer %s", loginBenefactor(t)) + + var kindBoxReqID uint = 1 + updatedKindBox := benefactorkindboxreqparam.KindBoxReqUpdateRequest{ + KindBoxType: entity.KindBoxOnTable, + DeliverAddressID: 2, + DeliverReferDate: time.Date(2025, time.January, 2, 15, 4, 5, 0, time.UTC), + DeliverReferTimeID: 1, + CountRequested: 2, + } + + requestBody, err := json.Marshal(updatedKindBox) + if err != nil { + t.Fatalf("failed to marshal request body: %s", err) + } + + req := httptest.NewRequest(http.MethodPut, fmt.Sprintf("/benefactor/kindboxreqs/%d", kindBoxReqID), bytes.NewBuffer(requestBody)) + req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) + req.Header.Set(echo.HeaderAuthorization, token) + rec := httptest.NewRecorder() + testServer.Serve(rec, req) + + var response benefactorkindboxreqparam.KindBoxReqUpdateResponse + err = json.NewDecoder(rec.Body).Decode(&response) + if err != nil { + t.Fatalf("failed to decode response body: %s", err) + } + + assert.Equal(t, http.StatusNoContent, rec.Code) + +} From b132249ffcb37c692044eef804e0ad74288c1bda Mon Sep 17 00:00:00 2001 From: Reza Mobaraki Date: Fri, 23 Aug 2024 19:05:30 +0330 Subject: [PATCH 04/22] Chore(benefactor-kindBoxReqs-test): add testify/suit in order to handle - test Update benefactorKindBoxReqs Signed-off-by: Reza Mobaraki --- .../end2end/benefactor_kindboxreqs_test.go | 180 ++++++++++-------- 1 file changed, 102 insertions(+), 78 deletions(-) diff --git a/delivery/http_server/end2end/benefactor_kindboxreqs_test.go b/delivery/http_server/end2end/benefactor_kindboxreqs_test.go index b0530178..8aff3258 100644 --- a/delivery/http_server/end2end/benefactor_kindboxreqs_test.go +++ b/delivery/http_server/end2end/benefactor_kindboxreqs_test.go @@ -13,40 +13,52 @@ import ( benefactorkindboxreqparam "git.gocasts.ir/ebhomengo/niki/param/benefactor/kind_box_req" "github.com/labstack/echo/v4" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/suite" "net/http" "net/http/httptest" "testing" "time" ) -func loginBenefactor(t *testing.T) string { - // TODO: Consider mocking the OTP service & fetching the verification code from Redis. +// Define a suite struct that embeds suite.Suite +type BenefactorKindBoxReqsTestSuite struct { + suite.Suite +} + +// SetupTest will run before each test in the suite +func (suite *BenefactorKindBoxReqsTestSuite) SetupTest() { + teardown := setup.SeedMariaDB(testContainer.GetMariaDBConfig()) + suite.T().Cleanup(teardown) +} + +// loginBenefactor utility function +func (suite *BenefactorKindBoxReqsTestSuite) loginBenefactor() string { phone := "09384664404" sendOTPRes, err := services.BenefactorSvc.SendOtp(context.Background(), benefactoreparam.SendOtpRequest{ PhoneNumber: phone, }) if err != nil { - t.Fatalf("failed to send OTP: %s", err) + suite.T().Fatalf("failed to send OTP: %s", err) } registerRes, err := services.BenefactorSvc.LoginOrRegister(context.Background(), benefactoreparam.LoginOrRegisterRequest{ PhoneNumber: phone, VerificationCode: sendOTPRes.Code, }) if err != nil { - t.Fatalf("failed to login or register: %s", err) + suite.T().Fatalf("failed to login or register: %s", err) } return registerRes.Tokens.AccessToken } // Utility function to create and send HTTP requests -func createRequest(t *testing.T, method, url string, body interface{}) *httptest.ResponseRecorder { +func (suite *BenefactorKindBoxReqsTestSuite) createRequest(method, url string, body interface{}) *httptest.ResponseRecorder { var buf bytes.Buffer if body != nil { if err := json.NewEncoder(&buf).Encode(body); err != nil { - t.Fatalf("could not encode body: %s", err) + suite.T().Fatalf("could not encode body: %s", err) } } - token := loginBenefactor(t) + token := suite.loginBenefactor() req := httptest.NewRequest(method, url, &buf) req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) req.Header.Set(echo.HeaderAuthorization, fmt.Sprintf("Bearer %s", token)) @@ -55,18 +67,48 @@ func createRequest(t *testing.T, method, url string, body interface{}) *httptest return rec } -func TestBenefactorKindBoxReqs_GetAll_Success(t *testing.T) { - teardown := setup.SeedMariaDB(testContainer.GetMariaDBConfig()) - t.Cleanup(teardown) +// Test to get all kind box requests +func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_GetAll_Success() { + rec := suite.createRequest(http.MethodGet, "/benefactor/kindboxreqs/", nil) + assert.Equal(suite.T(), http.StatusOK, rec.Code) + var response benefactorkindboxreqparam.GetAllResponse + err := json.NewDecoder(rec.Body).Decode(&response) + if err != nil { + suite.T().Fatalf("failed to decode response body: %s", err) + } + assert.Equal(suite.T(), 5, len(response.AllKindBoxReq)) - rec := createRequest(t, http.MethodGet, "/benefactor/kindboxreqs/", nil) - - assert.Equal(t, http.StatusOK, rec.Code) } -func TestBenefactorKindBoxReqs_Create_Success(t *testing.T) { - teardown := setup.SeedMariaDB(testContainer.GetMariaDBConfig()) - t.Cleanup(teardown) +// Test to get a specific kind box request by ID +func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Get_Success() { + + var kindBoxReqID uint = 1 + rec := suite.createRequest(http.MethodGet, fmt.Sprintf("/benefactor/kindboxreqs/%d", kindBoxReqID), nil) + + assert.Equal(suite.T(), http.StatusOK, rec.Code) + + var response benefactorkindboxreqparam.KindBoxReqGetResponse + err := json.NewDecoder(rec.Body).Decode(&response) + if err != nil { + suite.T().Fatalf("failed to decode response body: %s", err) + } + + assert.Equal(suite.T(), kindBoxReqID, response.KindBoxReq.ID) + assert.Equal(suite.T(), entity.KindBoxOnTable, response.KindBoxReq.KindBoxType) + assert.Equal(suite.T(), uint(1), response.KindBoxReq.DeliverAddressID) + expectedDate := time.Now().AddDate(0, 0, 7) + assert.Equal(suite.T(), expectedDate.Format("2006-01-02"), response.KindBoxReq.DeliverReferDate.Format("2006-01-02")) + assert.Equal(suite.T(), uint(1), response.KindBoxReq.DeliverReferTimeID) +} + +// Test to create a kind box request +func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Create_Success() { + // TODO : fix constraint with address_id + // panic: can't rollback migrations: Error 1451 (23000): + // Cannot delete or update a parent row: a foreign key constraint fails + // (mysql.kind_box_reqs, CONSTRAINT kind_box_reqs_ibfk_3 FOREIGN KEY (deliver_address_id) REFERENCES addresses (id)) + // handling 6_create-address-for-benefactor1.sql newKindBox := benefactorkindboxreqparam.KindBoxReqAddRequest{ KindBoxType: entity.KindBoxOnTable, @@ -76,83 +118,65 @@ func TestBenefactorKindBoxReqs_Create_Success(t *testing.T) { CountRequested: 2, } - rec := createRequest(t, http.MethodPost, "/benefactor/kindboxreqs/", newKindBox) - - assert.Equal(t, http.StatusCreated, rec.Code) + rec := suite.createRequest(http.MethodPost, "/benefactor/kindboxreqs/", newKindBox) + assert.Equal(suite.T(), http.StatusCreated, rec.Code) var response benefactorkindboxreqparam.KindBoxReqAddResponse err := json.NewDecoder(rec.Body).Decode(&response) if err != nil { - t.Fatalf("failed to decode response body: %s", err) + suite.T().Fatalf("failed to decode response body: %s", err) } - assert.Equal(t, newKindBox.KindBoxType, response.KindBoxReq.KindBoxType) - assert.Equal(t, newKindBox.DeliverAddressID, response.KindBoxReq.DeliverAddressID) - assert.Equal(t, newKindBox.DeliverReferDate, response.KindBoxReq.DeliverReferDate) - assert.Equal(t, newKindBox.DeliverReferTimeID, response.KindBoxReq.DeliverReferTimeID) - assert.Equal(t, newKindBox.CountRequested, response.KindBoxReq.CountRequested) + assert.Equal(suite.T(), newKindBox.KindBoxType, response.KindBoxReq.KindBoxType) + assert.Equal(suite.T(), newKindBox.DeliverAddressID, response.KindBoxReq.DeliverAddressID) + assert.Equal(suite.T(), newKindBox.DeliverReferDate, response.KindBoxReq.DeliverReferDate) + assert.Equal(suite.T(), newKindBox.DeliverReferTimeID, response.KindBoxReq.DeliverReferTimeID) + assert.Equal(suite.T(), newKindBox.CountRequested, response.KindBoxReq.CountRequested) } -func TestBenefactorKindBoxReqs_Get_Success(t *testing.T) { - teardown := setup.SeedMariaDB(testContainer.GetMariaDBConfig()) - t.Cleanup(teardown) - - token := fmt.Sprintf("Bearer %s", loginBenefactor(t)) - - var kindBoxReqID uint = 1 - req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/benefactor/kindboxreqs/%d", kindBoxReqID), nil) - req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) - req.Header.Set(echo.HeaderAuthorization, token) - rec := httptest.NewRecorder() - testServer.Serve(rec, req) - - assert.Equal(t, http.StatusOK, rec.Code) - - var response benefactorkindboxreqparam.KindBoxReqGetResponse - err := json.NewDecoder(rec.Body).Decode(&response) - if err != nil { - t.Fatalf("failed to decode response body: %s", err) - } - - assert.Equal(t, kindBoxReqID, response.KindBoxReq.ID) - assert.Equal(t, entity.KindBoxOnTable, response.KindBoxReq.KindBoxType) - assert.Equal(t, uint(1), response.KindBoxReq.DeliverAddressID) - expectedDate := time.Now().AddDate(0, 0, 7) - assert.Equal(t, expectedDate.Format("2006-01-02"), response.KindBoxReq.DeliverReferDate.Format("2006-01-02")) - assert.Equal(t, uint(1), response.KindBoxReq.DeliverReferTimeID) -} - -func TestBenefactorKindBoxReqs_Update_Success(t *testing.T) { - teardown := setup.SeedMariaDB(testContainer.GetMariaDBConfig()) - t.Cleanup(teardown) - - token := fmt.Sprintf("Bearer %s", loginBenefactor(t)) +// Test to update a kind box request +func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Update_Success() { var kindBoxReqID uint = 1 + now := time.Now().AddDate(0, 0, 7).UTC() updatedKindBox := benefactorkindboxreqparam.KindBoxReqUpdateRequest{ - KindBoxType: entity.KindBoxOnTable, - DeliverAddressID: 2, - DeliverReferDate: time.Date(2025, time.January, 2, 15, 4, 5, 0, time.UTC), + KindBoxType: entity.KindBoxCylindrical, + CountRequested: 5, + Description: "updated description", DeliverReferTimeID: 1, - CountRequested: 2, + DeliverReferDate: now, + DeliverAddressID: 1, } + rec := suite.createRequest(http.MethodPut, fmt.Sprintf("/benefactor/kindboxreqs/%d", kindBoxReqID), updatedKindBox) + assert.Equal(suite.T(), http.StatusNoContent, rec.Code) - requestBody, err := json.Marshal(updatedKindBox) + kindBoxReq, err := services.BenefactorKindBoxReqSvc.Get(context.Background(), benefactorkindboxreqparam.KindBoxReqGetRequest{ + BenefactorID: 1, + KindBoxReqID: kindBoxReqID, + }) if err != nil { - t.Fatalf("failed to marshal request body: %s", err) + suite.T().Fatalf("failed to get kind box request: %s", err) } - req := httptest.NewRequest(http.MethodPut, fmt.Sprintf("/benefactor/kindboxreqs/%d", kindBoxReqID), bytes.NewBuffer(requestBody)) - req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) - req.Header.Set(echo.HeaderAuthorization, token) - rec := httptest.NewRecorder() - testServer.Serve(rec, req) - - var response benefactorkindboxreqparam.KindBoxReqUpdateResponse - err = json.NewDecoder(rec.Body).Decode(&response) - if err != nil { - t.Fatalf("failed to decode response body: %s", err) - } - - assert.Equal(t, http.StatusNoContent, rec.Code) + assert.Equal(suite.T(), updatedKindBox.KindBoxType, kindBoxReq.KindBoxType) + assert.Equal(suite.T(), updatedKindBox.CountRequested, kindBoxReq.CountRequested) + assert.Equal(suite.T(), updatedKindBox.Description, kindBoxReq.Description) } + +func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Delete_Success() { + var kindBoxReqID uint = 1 + rec := suite.createRequest(http.MethodDelete, fmt.Sprintf("/benefactor/kindboxreqs/%d", kindBoxReqID), nil) + assert.Equal(suite.T(), http.StatusOK, rec.Code) + + _, err := services.BenefactorKindBoxReqSvc.Get(context.Background(), benefactorkindboxreqparam.KindBoxReqGetRequest{ + BenefactorID: 1, + KindBoxReqID: kindBoxReqID, + }) + // TODO: Fix to assert equal to errmsg.ErrorMsgNotFound + assert.Error(suite.T(), err) +} + +// Entry point for the test suite +func TestBenefactorKindBoxReqsTestSuite(t *testing.T) { + suite.Run(t, new(BenefactorKindBoxReqsTestSuite)) +} From 1c3156fe3a6e47e38047ab0abff96a39301c6759 Mon Sep 17 00:00:00 2001 From: Reza Mobaraki Date: Fri, 23 Aug 2024 19:14:54 +0330 Subject: [PATCH 05/22] Chore(benefactor-kindBoxReqs-test): add testify/suit in order to handle Resolves #140 Signed-off-by: Reza Mobaraki --- delivery/http_server/end2end/benefactor_kindboxreqs_test.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/delivery/http_server/end2end/benefactor_kindboxreqs_test.go b/delivery/http_server/end2end/benefactor_kindboxreqs_test.go index 8aff3258..4271533e 100644 --- a/delivery/http_server/end2end/benefactor_kindboxreqs_test.go +++ b/delivery/http_server/end2end/benefactor_kindboxreqs_test.go @@ -31,8 +31,10 @@ func (suite *BenefactorKindBoxReqsTestSuite) SetupTest() { suite.T().Cleanup(teardown) } +// TODO: find better place // loginBenefactor utility function func (suite *BenefactorKindBoxReqsTestSuite) loginBenefactor() string { + phone := "09384664404" sendOTPRes, err := services.BenefactorSvc.SendOtp(context.Background(), benefactoreparam.SendOtpRequest{ PhoneNumber: phone, From 79b054e09f4447e8d547fb15a53cc4ddc610c28d Mon Sep 17 00:00:00 2001 From: Reza Mobaraki Date: Sat, 24 Aug 2024 13:46:44 +0330 Subject: [PATCH 06/22] Refactor(benefactor-kindBoxReqs-test): move data to setupTest Addressed #140 Signed-off-by: Reza Mobaraki --- .../end2end/benefactor_kindboxreqs_test.go | 139 +++++++++++------- 1 file changed, 83 insertions(+), 56 deletions(-) diff --git a/delivery/http_server/end2end/benefactor_kindboxreqs_test.go b/delivery/http_server/end2end/benefactor_kindboxreqs_test.go index 4271533e..b8375390 100644 --- a/delivery/http_server/end2end/benefactor_kindboxreqs_test.go +++ b/delivery/http_server/end2end/benefactor_kindboxreqs_test.go @@ -23,27 +23,59 @@ import ( // Define a suite struct that embeds suite.Suite type BenefactorKindBoxReqsTestSuite struct { suite.Suite + benefactorPhone string + benefactorID uint + kindBoxReqID uint + getAllExpected map[string]interface{} + getExpected map[string]interface{} + createData benefactorkindboxreqparam.KindBoxReqAddRequest + updateData benefactorkindboxreqparam.KindBoxReqUpdateRequest } // SetupTest will run before each test in the suite func (suite *BenefactorKindBoxReqsTestSuite) SetupTest() { teardown := setup.SeedMariaDB(testContainer.GetMariaDBConfig()) suite.T().Cleanup(teardown) + suite.benefactorPhone = "09384664404" + suite.benefactorID = uint(1) + suite.kindBoxReqID = uint(1) + suite.getAllExpected = map[string]interface{}{ + "count": 5, + } + suite.getExpected = map[string]interface{}{ + "kind_box_type": entity.KindBoxOnTable, + "deliver_address": uint(1), + "deliver_refer_date": time.Now().AddDate(0, 0, 7).UTC(), + "deliver_refer_time": uint(1), + } + suite.createData = benefactorkindboxreqparam.KindBoxReqAddRequest{ + KindBoxType: entity.KindBoxCylindrical, + DeliverAddressID: uint(1), + DeliverReferDate: time.Now().AddDate(0, 0, 7).UTC(), + DeliverReferTimeID: uint(1), + CountRequested: uint(5), + } + suite.updateData = benefactorkindboxreqparam.KindBoxReqUpdateRequest{ + KindBoxType: entity.KindBoxCylindrical, + CountRequested: uint(10), + Description: "updated description", + DeliverReferTimeID: uint(1), + DeliverReferDate: time.Now().AddDate(0, 0, 7).UTC(), + DeliverAddressID: uint(1), + } } // TODO: find better place // loginBenefactor utility function func (suite *BenefactorKindBoxReqsTestSuite) loginBenefactor() string { - - phone := "09384664404" sendOTPRes, err := services.BenefactorSvc.SendOtp(context.Background(), benefactoreparam.SendOtpRequest{ - PhoneNumber: phone, + PhoneNumber: suite.benefactorPhone, }) if err != nil { suite.T().Fatalf("failed to send OTP: %s", err) } registerRes, err := services.BenefactorSvc.LoginOrRegister(context.Background(), benefactoreparam.LoginOrRegisterRequest{ - PhoneNumber: phone, + PhoneNumber: suite.benefactorPhone, VerificationCode: sendOTPRes.Code, }) if err != nil { @@ -72,21 +104,22 @@ func (suite *BenefactorKindBoxReqsTestSuite) createRequest(method, url string, b // Test to get all kind box requests func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_GetAll_Success() { rec := suite.createRequest(http.MethodGet, "/benefactor/kindboxreqs/", nil) + assert.Equal(suite.T(), http.StatusOK, rec.Code) + var response benefactorkindboxreqparam.GetAllResponse err := json.NewDecoder(rec.Body).Decode(&response) if err != nil { suite.T().Fatalf("failed to decode response body: %s", err) } - assert.Equal(suite.T(), 5, len(response.AllKindBoxReq)) + assert.Equal(suite.T(), suite.getAllExpected["count"], len(response.AllKindBoxReq)) } // Test to get a specific kind box request by ID func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Get_Success() { - var kindBoxReqID uint = 1 - rec := suite.createRequest(http.MethodGet, fmt.Sprintf("/benefactor/kindboxreqs/%d", kindBoxReqID), nil) + rec := suite.createRequest(http.MethodGet, fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.benefactorID), nil) assert.Equal(suite.T(), http.StatusOK, rec.Code) @@ -96,31 +129,21 @@ func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Get_Succe suite.T().Fatalf("failed to decode response body: %s", err) } - assert.Equal(suite.T(), kindBoxReqID, response.KindBoxReq.ID) - assert.Equal(suite.T(), entity.KindBoxOnTable, response.KindBoxReq.KindBoxType) - assert.Equal(suite.T(), uint(1), response.KindBoxReq.DeliverAddressID) - expectedDate := time.Now().AddDate(0, 0, 7) - assert.Equal(suite.T(), expectedDate.Format("2006-01-02"), response.KindBoxReq.DeliverReferDate.Format("2006-01-02")) - assert.Equal(suite.T(), uint(1), response.KindBoxReq.DeliverReferTimeID) + assert.Equal(suite.T(), suite.benefactorID, response.KindBoxReq.ID) + assert.Equal(suite.T(), suite.getExpected["kind_box_type"], response.KindBoxReq.KindBoxType) + assert.Equal(suite.T(), suite.getExpected["deliver_address"], response.KindBoxReq.DeliverAddressID) + assert.Equal( + suite.T(), + suite.getExpected["deliver_refer_date"].(time.Time).Format("2006-01-02"), + response.KindBoxReq.DeliverReferDate.Format("2006-01-02"), + ) + assert.Equal(suite.T(), suite.getExpected["deliver_refer_time"], response.KindBoxReq.DeliverReferTimeID) } // Test to create a kind box request func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Create_Success() { - // TODO : fix constraint with address_id - // panic: can't rollback migrations: Error 1451 (23000): - // Cannot delete or update a parent row: a foreign key constraint fails - // (mysql.kind_box_reqs, CONSTRAINT kind_box_reqs_ibfk_3 FOREIGN KEY (deliver_address_id) REFERENCES addresses (id)) - // handling 6_create-address-for-benefactor1.sql - newKindBox := benefactorkindboxreqparam.KindBoxReqAddRequest{ - KindBoxType: entity.KindBoxOnTable, - DeliverAddressID: 1, - DeliverReferDate: time.Date(2025, time.January, 2, 15, 4, 5, 0, time.UTC), - DeliverReferTimeID: 1, - CountRequested: 2, - } - - rec := suite.createRequest(http.MethodPost, "/benefactor/kindboxreqs/", newKindBox) + rec := suite.createRequest(http.MethodPost, "/benefactor/kindboxreqs/", suite.createData) assert.Equal(suite.T(), http.StatusCreated, rec.Code) var response benefactorkindboxreqparam.KindBoxReqAddResponse @@ -128,52 +151,56 @@ func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Create_Su if err != nil { suite.T().Fatalf("failed to decode response body: %s", err) } - assert.Equal(suite.T(), newKindBox.KindBoxType, response.KindBoxReq.KindBoxType) - assert.Equal(suite.T(), newKindBox.DeliverAddressID, response.KindBoxReq.DeliverAddressID) - assert.Equal(suite.T(), newKindBox.DeliverReferDate, response.KindBoxReq.DeliverReferDate) - assert.Equal(suite.T(), newKindBox.DeliverReferTimeID, response.KindBoxReq.DeliverReferTimeID) - assert.Equal(suite.T(), newKindBox.CountRequested, response.KindBoxReq.CountRequested) + assert.Equal(suite.T(), suite.createData.KindBoxType, response.KindBoxReq.KindBoxType) + assert.Equal(suite.T(), suite.createData.DeliverAddressID, response.KindBoxReq.DeliverAddressID) + assert.Equal(suite.T(), suite.createData.DeliverReferDate, response.KindBoxReq.DeliverReferDate) + assert.Equal( + suite.T(), + suite.getExpected["deliver_refer_date"].(time.Time).Format("2006-01-02"), + response.KindBoxReq.DeliverReferDate.Format("2006-01-02"), + ) + assert.Equal(suite.T(), suite.createData.CountRequested, response.KindBoxReq.CountRequested) } // Test to update a kind box request func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Update_Success() { - var kindBoxReqID uint = 1 - now := time.Now().AddDate(0, 0, 7).UTC() - updatedKindBox := benefactorkindboxreqparam.KindBoxReqUpdateRequest{ - KindBoxType: entity.KindBoxCylindrical, - CountRequested: 5, - Description: "updated description", - DeliverReferTimeID: 1, - DeliverReferDate: now, - DeliverAddressID: 1, - } - rec := suite.createRequest(http.MethodPut, fmt.Sprintf("/benefactor/kindboxreqs/%d", kindBoxReqID), updatedKindBox) + rec := suite.createRequest( + http.MethodPut, fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.kindBoxReqID), suite.updateData, + ) assert.Equal(suite.T(), http.StatusNoContent, rec.Code) - kindBoxReq, err := services.BenefactorKindBoxReqSvc.Get(context.Background(), benefactorkindboxreqparam.KindBoxReqGetRequest{ - BenefactorID: 1, - KindBoxReqID: kindBoxReqID, - }) + kindBoxReq, err := services.BenefactorKindBoxReqSvc.Get(context.Background(), + benefactorkindboxreqparam.KindBoxReqGetRequest{ + BenefactorID: suite.benefactorID, + KindBoxReqID: suite.kindBoxReqID, + }, + ) if err != nil { suite.T().Fatalf("failed to get kind box request: %s", err) } - assert.Equal(suite.T(), updatedKindBox.KindBoxType, kindBoxReq.KindBoxType) - assert.Equal(suite.T(), updatedKindBox.CountRequested, kindBoxReq.CountRequested) - assert.Equal(suite.T(), updatedKindBox.Description, kindBoxReq.Description) + assert.Equal(suite.T(), suite.updateData.KindBoxType, kindBoxReq.KindBoxType) + assert.Equal(suite.T(), suite.updateData.CountRequested, kindBoxReq.CountRequested) + assert.Equal(suite.T(), suite.updateData.Description, kindBoxReq.Description) + assert.Equal(suite.T(), suite.updateData.DeliverReferTimeID, kindBoxReq.DeliverReferTimeID) + assert.Equal(suite.T(), suite.updateData.DeliverReferDate, kindBoxReq.DeliverReferDate) + assert.Equal(suite.T(), suite.updateData.DeliverAddressID, kindBoxReq.DeliverAddressID) } func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Delete_Success() { - var kindBoxReqID uint = 1 - rec := suite.createRequest(http.MethodDelete, fmt.Sprintf("/benefactor/kindboxreqs/%d", kindBoxReqID), nil) + rec := suite.createRequest( + http.MethodDelete, fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.kindBoxReqID), nil, + ) assert.Equal(suite.T(), http.StatusOK, rec.Code) - _, err := services.BenefactorKindBoxReqSvc.Get(context.Background(), benefactorkindboxreqparam.KindBoxReqGetRequest{ - BenefactorID: 1, - KindBoxReqID: kindBoxReqID, - }) + _, err := services.BenefactorKindBoxReqSvc.Get(context.Background(), + benefactorkindboxreqparam.KindBoxReqGetRequest{ + BenefactorID: suite.benefactorID, + KindBoxReqID: suite.kindBoxReqID, + }, + ) // TODO: Fix to assert equal to errmsg.ErrorMsgNotFound assert.Error(suite.T(), err) } From ceab112d0e5d6aa0ed8f4a87e71eb23ac2290351 Mon Sep 17 00:00:00 2001 From: Reza Mobaraki Date: Sat, 24 Aug 2024 14:03:16 +0330 Subject: [PATCH 07/22] Refactor(benefactor-kindBoxReqs-test): use more feature of suit Addressed #140 Signed-off-by: Reza Mobaraki --- .../end2end/benefactor_kindboxreqs_test.go | 104 ++++++++---------- 1 file changed, 45 insertions(+), 59 deletions(-) diff --git a/delivery/http_server/end2end/benefactor_kindboxreqs_test.go b/delivery/http_server/end2end/benefactor_kindboxreqs_test.go index b8375390..cab5876b 100644 --- a/delivery/http_server/end2end/benefactor_kindboxreqs_test.go +++ b/delivery/http_server/end2end/benefactor_kindboxreqs_test.go @@ -20,7 +20,7 @@ import ( "time" ) -// Define a suite struct that embeds suite.Suite +// BenefactorKindBoxReqsTestSuite defines the suite for testing Benefactor Kind Box Requests type BenefactorKindBoxReqsTestSuite struct { suite.Suite benefactorPhone string @@ -32,22 +32,26 @@ type BenefactorKindBoxReqsTestSuite struct { updateData benefactorkindboxreqparam.KindBoxReqUpdateRequest } -// SetupTest will run before each test in the suite +// SetupTest runs before each test in the suite func (suite *BenefactorKindBoxReqsTestSuite) SetupTest() { teardown := setup.SeedMariaDB(testContainer.GetMariaDBConfig()) suite.T().Cleanup(teardown) + suite.benefactorPhone = "09384664404" suite.benefactorID = uint(1) suite.kindBoxReqID = uint(1) + suite.getAllExpected = map[string]interface{}{ "count": 5, } + suite.getExpected = map[string]interface{}{ "kind_box_type": entity.KindBoxOnTable, "deliver_address": uint(1), "deliver_refer_date": time.Now().AddDate(0, 0, 7).UTC(), "deliver_refer_time": uint(1), } + suite.createData = benefactorkindboxreqparam.KindBoxReqAddRequest{ KindBoxType: entity.KindBoxCylindrical, DeliverAddressID: uint(1), @@ -55,6 +59,7 @@ func (suite *BenefactorKindBoxReqsTestSuite) SetupTest() { DeliverReferTimeID: uint(1), CountRequested: uint(5), } + suite.updateData = benefactorkindboxreqparam.KindBoxReqUpdateRequest{ KindBoxType: entity.KindBoxCylindrical, CountRequested: uint(10), @@ -65,71 +70,63 @@ func (suite *BenefactorKindBoxReqsTestSuite) SetupTest() { } } -// TODO: find better place -// loginBenefactor utility function +// loginBenefactor authenticates the benefactor and returns an access token func (suite *BenefactorKindBoxReqsTestSuite) loginBenefactor() string { sendOTPRes, err := services.BenefactorSvc.SendOtp(context.Background(), benefactoreparam.SendOtpRequest{ PhoneNumber: suite.benefactorPhone, }) - if err != nil { - suite.T().Fatalf("failed to send OTP: %s", err) - } + suite.Require().NoError(err, "failed to send OTP") + registerRes, err := services.BenefactorSvc.LoginOrRegister(context.Background(), benefactoreparam.LoginOrRegisterRequest{ PhoneNumber: suite.benefactorPhone, VerificationCode: sendOTPRes.Code, }) - if err != nil { - suite.T().Fatalf("failed to login or register: %s", err) - } + suite.Require().NoError(err, "failed to login or register") + return registerRes.Tokens.AccessToken } -// Utility function to create and send HTTP requests +// createRequest is a utility function to create and send HTTP requests func (suite *BenefactorKindBoxReqsTestSuite) createRequest(method, url string, body interface{}) *httptest.ResponseRecorder { var buf bytes.Buffer if body != nil { - if err := json.NewEncoder(&buf).Encode(body); err != nil { - suite.T().Fatalf("could not encode body: %s", err) - } + err := json.NewEncoder(&buf).Encode(body) + suite.Require().NoError(err, "could not encode body") } + token := suite.loginBenefactor() + req := httptest.NewRequest(method, url, &buf) req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) req.Header.Set(echo.HeaderAuthorization, fmt.Sprintf("Bearer %s", token)) + rec := httptest.NewRecorder() testServer.Serve(rec, req) return rec } -// Test to get all kind box requests +// TestBenefactorKindBoxReqs_GetAll_Success tests retrieving all kind box requests func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_GetAll_Success() { rec := suite.createRequest(http.MethodGet, "/benefactor/kindboxreqs/", nil) - - assert.Equal(suite.T(), http.StatusOK, rec.Code) + suite.Require().Equal(http.StatusOK, rec.Code) var response benefactorkindboxreqparam.GetAllResponse err := json.NewDecoder(rec.Body).Decode(&response) - if err != nil { - suite.T().Fatalf("failed to decode response body: %s", err) - } - assert.Equal(suite.T(), suite.getAllExpected["count"], len(response.AllKindBoxReq)) + suite.Require().NoError(err, "failed to decode response body") + assert.Equal(suite.T(), suite.getAllExpected["count"], len(response.AllKindBoxReq)) } -// Test to get a specific kind box request by ID +// TestBenefactorKindBoxReqs_Get_Success tests retrieving a specific kind box request by ID func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Get_Success() { - - rec := suite.createRequest(http.MethodGet, fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.benefactorID), nil) - - assert.Equal(suite.T(), http.StatusOK, rec.Code) + rec := suite.createRequest(http.MethodGet, fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.kindBoxReqID), nil) + suite.Require().Equal(http.StatusOK, rec.Code) var response benefactorkindboxreqparam.KindBoxReqGetResponse err := json.NewDecoder(rec.Body).Decode(&response) - if err != nil { - suite.T().Fatalf("failed to decode response body: %s", err) - } + suite.Require().NoError(err, "failed to decode response body") - assert.Equal(suite.T(), suite.benefactorID, response.KindBoxReq.ID) + assert.Equal(suite.T(), suite.kindBoxReqID, response.KindBoxReq.ID) assert.Equal(suite.T(), suite.getExpected["kind_box_type"], response.KindBoxReq.KindBoxType) assert.Equal(suite.T(), suite.getExpected["deliver_address"], response.KindBoxReq.DeliverAddressID) assert.Equal( @@ -140,35 +137,25 @@ func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Get_Succe assert.Equal(suite.T(), suite.getExpected["deliver_refer_time"], response.KindBoxReq.DeliverReferTimeID) } -// Test to create a kind box request +// TestBenefactorKindBoxReqs_Create_Success tests creating a kind box request func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Create_Success() { - rec := suite.createRequest(http.MethodPost, "/benefactor/kindboxreqs/", suite.createData) - assert.Equal(suite.T(), http.StatusCreated, rec.Code) + suite.Require().Equal(http.StatusCreated, rec.Code) var response benefactorkindboxreqparam.KindBoxReqAddResponse err := json.NewDecoder(rec.Body).Decode(&response) - if err != nil { - suite.T().Fatalf("failed to decode response body: %s", err) - } + suite.Require().NoError(err, "failed to decode response body") + assert.Equal(suite.T(), suite.createData.KindBoxType, response.KindBoxReq.KindBoxType) assert.Equal(suite.T(), suite.createData.DeliverAddressID, response.KindBoxReq.DeliverAddressID) assert.Equal(suite.T(), suite.createData.DeliverReferDate, response.KindBoxReq.DeliverReferDate) - assert.Equal( - suite.T(), - suite.getExpected["deliver_refer_date"].(time.Time).Format("2006-01-02"), - response.KindBoxReq.DeliverReferDate.Format("2006-01-02"), - ) assert.Equal(suite.T(), suite.createData.CountRequested, response.KindBoxReq.CountRequested) } -// Test to update a kind box request +// TestBenefactorKindBoxReqs_Update_Success tests updating a kind box request func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Update_Success() { - - rec := suite.createRequest( - http.MethodPut, fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.kindBoxReqID), suite.updateData, - ) - assert.Equal(suite.T(), http.StatusNoContent, rec.Code) + rec := suite.createRequest(http.MethodPut, fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.kindBoxReqID), suite.updateData) + suite.Require().Equal(http.StatusNoContent, rec.Code) kindBoxReq, err := services.BenefactorKindBoxReqSvc.Get(context.Background(), benefactorkindboxreqparam.KindBoxReqGetRequest{ @@ -176,24 +163,24 @@ func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Update_Su KindBoxReqID: suite.kindBoxReqID, }, ) - if err != nil { - suite.T().Fatalf("failed to get kind box request: %s", err) - } + suite.Require().NoError(err, "failed to get kind box request") assert.Equal(suite.T(), suite.updateData.KindBoxType, kindBoxReq.KindBoxType) assert.Equal(suite.T(), suite.updateData.CountRequested, kindBoxReq.CountRequested) assert.Equal(suite.T(), suite.updateData.Description, kindBoxReq.Description) assert.Equal(suite.T(), suite.updateData.DeliverReferTimeID, kindBoxReq.DeliverReferTimeID) - assert.Equal(suite.T(), suite.updateData.DeliverReferDate, kindBoxReq.DeliverReferDate) + assert.Equal( + suite.T(), + suite.updateData.DeliverReferDate.Format("2006-01-02"), + kindBoxReq.DeliverReferDate.Format("2006-01-02"), + ) assert.Equal(suite.T(), suite.updateData.DeliverAddressID, kindBoxReq.DeliverAddressID) - } +// TestBenefactorKindBoxReqs_Delete_Success tests deleting a kind box request func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Delete_Success() { - rec := suite.createRequest( - http.MethodDelete, fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.kindBoxReqID), nil, - ) - assert.Equal(suite.T(), http.StatusOK, rec.Code) + rec := suite.createRequest(http.MethodDelete, fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.kindBoxReqID), nil) + suite.Require().Equal(http.StatusOK, rec.Code) _, err := services.BenefactorKindBoxReqSvc.Get(context.Background(), benefactorkindboxreqparam.KindBoxReqGetRequest{ @@ -201,11 +188,10 @@ func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Delete_Su KindBoxReqID: suite.kindBoxReqID, }, ) - // TODO: Fix to assert equal to errmsg.ErrorMsgNotFound - assert.Error(suite.T(), err) + suite.Require().Error(err) } -// Entry point for the test suite +// TestBenefactorKindBoxReqsTestSuite is the entry point for the test suite func TestBenefactorKindBoxReqsTestSuite(t *testing.T) { suite.Run(t, new(BenefactorKindBoxReqsTestSuite)) } From 38677a012838e867dd56d3614fb5c6064a36979f Mon Sep 17 00:00:00 2001 From: Reza Mobaraki Date: Sat, 24 Aug 2024 14:11:08 +0330 Subject: [PATCH 08/22] Refactor(benefactor-kindBoxReqs-test): use more feature of suit Addressed #140 Signed-off-by: Reza Mobaraki --- .../end2end/benefactor_kindboxreqs_test.go | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/delivery/http_server/end2end/benefactor_kindboxreqs_test.go b/delivery/http_server/end2end/benefactor_kindboxreqs_test.go index cab5876b..78da216a 100644 --- a/delivery/http_server/end2end/benefactor_kindboxreqs_test.go +++ b/delivery/http_server/end2end/benefactor_kindboxreqs_test.go @@ -32,6 +32,11 @@ type BenefactorKindBoxReqsTestSuite struct { updateData benefactorkindboxreqparam.KindBoxReqUpdateRequest } +// TestBenefactorKindBoxReqsTestSuite is the entry point for the test suite +func TestBenefactorKindBoxReqsTestSuite(t *testing.T) { + suite.Run(t, new(BenefactorKindBoxReqsTestSuite)) +} + // SetupTest runs before each test in the suite func (suite *BenefactorKindBoxReqsTestSuite) SetupTest() { teardown := setup.SeedMariaDB(testContainer.GetMariaDBConfig()) @@ -71,6 +76,7 @@ func (suite *BenefactorKindBoxReqsTestSuite) SetupTest() { } // loginBenefactor authenticates the benefactor and returns an access token +// TODO: Move this to a common utility function func (suite *BenefactorKindBoxReqsTestSuite) loginBenefactor() string { sendOTPRes, err := services.BenefactorSvc.SendOtp(context.Background(), benefactoreparam.SendOtpRequest{ PhoneNumber: suite.benefactorPhone, @@ -87,6 +93,7 @@ func (suite *BenefactorKindBoxReqsTestSuite) loginBenefactor() string { } // createRequest is a utility function to create and send HTTP requests +// TODO: Move this to a common utility function func (suite *BenefactorKindBoxReqsTestSuite) createRequest(method, url string, body interface{}) *httptest.ResponseRecorder { var buf bytes.Buffer if body != nil { @@ -190,8 +197,3 @@ func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Delete_Su ) suite.Require().Error(err) } - -// TestBenefactorKindBoxReqsTestSuite is the entry point for the test suite -func TestBenefactorKindBoxReqsTestSuite(t *testing.T) { - suite.Run(t, new(BenefactorKindBoxReqsTestSuite)) -} From 99f710c41d315435f3ba68d44c9e00ccf2861588 Mon Sep 17 00:00:00 2001 From: Reza Mobaraki Date: Sat, 24 Aug 2024 14:29:46 +0330 Subject: [PATCH 09/22] Fix(benefactor-kindBoxReqs-test): delete test assertion Addressed #140 Signed-off-by: Reza Mobaraki --- delivery/http_server/end2end/benefactor_kindboxreqs_test.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/delivery/http_server/end2end/benefactor_kindboxreqs_test.go b/delivery/http_server/end2end/benefactor_kindboxreqs_test.go index 78da216a..e8ea81af 100644 --- a/delivery/http_server/end2end/benefactor_kindboxreqs_test.go +++ b/delivery/http_server/end2end/benefactor_kindboxreqs_test.go @@ -11,6 +11,8 @@ import ( "git.gocasts.ir/ebhomengo/niki/entity" benefactoreparam "git.gocasts.ir/ebhomengo/niki/param/benefactor/benefactor" benefactorkindboxreqparam "git.gocasts.ir/ebhomengo/niki/param/benefactor/kind_box_req" + errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" + httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg" "github.com/labstack/echo/v4" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" @@ -195,5 +197,8 @@ func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Delete_Su KindBoxReqID: suite.kindBoxReqID, }, ) + message, code := httpmsg.Error(err) suite.Require().Error(err) + assert.Equal(suite.T(), http.StatusNotFound, code) + assert.Equal(suite.T(), errmsg.ErrorMsgNotFound, message) } From c58cc2789a3c064b9998ffea85cbbd5c8d3e9f5e Mon Sep 17 00:00:00 2001 From: Reza Mobaraki Date: Mon, 26 Aug 2024 00:43:45 +0330 Subject: [PATCH 10/22] Chore(e2e.benefactor-address-test): add base Signed-off-by: Reza Mobaraki --- .../end2end/benefactor_address_test.go | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 delivery/http_server/end2end/benefactor_address_test.go diff --git a/delivery/http_server/end2end/benefactor_address_test.go b/delivery/http_server/end2end/benefactor_address_test.go new file mode 100644 index 00000000..25f24c71 --- /dev/null +++ b/delivery/http_server/end2end/benefactor_address_test.go @@ -0,0 +1,27 @@ +//go:build end2end + +package end2end + +import ( + "git.gocasts.ir/ebhomengo/niki/delivery/http_server/end2end/setup" + "github.com/stretchr/testify/suite" + "testing" +) + +type BenefactorAddressTestSuit struct { + suite.Suite +} + +func TestBenefactorAddressTestSuit(t *testing.T) { + suite.Run(t, new(BenefactorAddressTestSuit)) +} + +func (suite *BenefactorAddressTestSuit) SetupSuite() { + teardown := setup.SeedMariaDB(testContainer.GetMariaDBConfig()) + suite.T().Cleanup(teardown) + +} + +func (suite *BenefactorAddressTestSuit) TestBenefactorAddressCreate() { + +} From 17d35028545714fb21dfc3f8c52609f00c915444 Mon Sep 17 00:00:00 2001 From: Reza Mobaraki Date: Mon, 26 Aug 2024 16:29:53 +0330 Subject: [PATCH 11/22] Chore(e2e.benefactor-address-test): add tests added Signed-off-by: Reza Mobaraki --- .../end2end/benefactor_address_test.go | 183 +++++++++++++++++- 1 file changed, 179 insertions(+), 4 deletions(-) diff --git a/delivery/http_server/end2end/benefactor_address_test.go b/delivery/http_server/end2end/benefactor_address_test.go index 25f24c71..07a750a9 100644 --- a/delivery/http_server/end2end/benefactor_address_test.go +++ b/delivery/http_server/end2end/benefactor_address_test.go @@ -3,25 +3,200 @@ package end2end import ( + "bytes" + "context" + "encoding/json" + "fmt" "git.gocasts.ir/ebhomengo/niki/delivery/http_server/end2end/setup" + "git.gocasts.ir/ebhomengo/niki/entity" + addressparam "git.gocasts.ir/ebhomengo/niki/param/benefactor/address" + benefactoreparam "git.gocasts.ir/ebhomengo/niki/param/benefactor/benefactor" + errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" + httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg" + "github.com/labstack/echo/v4" "github.com/stretchr/testify/suite" + "net/http" + "net/http/httptest" "testing" ) type BenefactorAddressTestSuit struct { suite.Suite -} - -func TestBenefactorAddressTestSuit(t *testing.T) { - suite.Run(t, new(BenefactorAddressTestSuit)) + benefactorPhone string + benefactorID uint + addressID uint + getAllExpected map[string]interface{} + getExpected addressparam.GetAddressResponse + // TODO: naming of address params request should be fix and follow the same pattern + createData addressparam.BenefactorAddAddressRequest + updateData addressparam.UpdateAddressRequest } func (suite *BenefactorAddressTestSuit) SetupSuite() { teardown := setup.SeedMariaDB(testContainer.GetMariaDBConfig()) suite.T().Cleanup(teardown) + suite.benefactorPhone = "09384664404" + suite.benefactorID = 1 + suite.addressID = 1 + suite.getAllExpected = map[string]interface{}{ + "count": 1, + } + suite.getExpected = addressparam.GetAddressResponse{ + Address: entity.Address{ + ID: 1, + PostalCode: "3719655861", + Address: "tehran sare koche 1", + Lat: 35.632508, + Lon: 51.452859, + Name: "home1", + CityID: 8, + BenefactorID: 1, + }, + } + suite.createData = addressparam.BenefactorAddAddressRequest{ + PostalCode: "3719655861", + Address: "create shiraz kaf sharo", + Lat: 29.62949, + Lon: 52.497287, + CityID: 194, + Name: "create shiraz", + } + suite.updateData = addressparam.UpdateAddressRequest{ + PostalCode: "3719655861", + Address: "update shiraz kaf sharo", + Lat: 29.62949, + Lon: 52.497287, + CityID: 194, + Name: "update shiraz", + } +} + +func TestBenefactorAddressTestSuit(t *testing.T) { + suite.Run(t, new(BenefactorAddressTestSuit)) + +} + +// loginBenefactor authenticates the benefactor and returns an access token +// TODO: Move this to a common utility function +func (suite *BenefactorAddressTestSuit) loginBenefactor() string { + sendOTPRes, err := services.BenefactorSvc.SendOtp(context.Background(), benefactoreparam.SendOtpRequest{ + PhoneNumber: suite.benefactorPhone, + }) + suite.Require().NoError(err, "failed to send OTP") + + registerRes, err := services.BenefactorSvc.LoginOrRegister(context.Background(), benefactoreparam.LoginOrRegisterRequest{ + PhoneNumber: suite.benefactorPhone, + VerificationCode: sendOTPRes.Code, + }) + suite.Require().NoError(err, "failed to login or register") + + return registerRes.Tokens.AccessToken +} + +// createRequest is a utility function to create and send HTTP requests +// TODO: Move this to a common utility function +func (suite *BenefactorAddressTestSuit) createRequest(method, url string, body interface{}) *httptest.ResponseRecorder { + var buf bytes.Buffer + if body != nil { + err := json.NewEncoder(&buf).Encode(body) + suite.Require().NoError(err, "could not encode body") + } + + token := suite.loginBenefactor() + + req := httptest.NewRequest(method, url, &buf) + req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) + req.Header.Set(echo.HeaderAuthorization, fmt.Sprintf("Bearer %s", token)) + + rec := httptest.NewRecorder() + testServer.Serve(rec, req) + return rec +} + +func (suite *BenefactorAddressTestSuit) TestBenefactorAddressGet() { + responseRecord := suite.createRequest("GET", fmt.Sprintf("/address/%d", suite.addressID), nil) + suite.Require().Equal(http.StatusOK, responseRecord.Code) + + var response addressparam.GetAddressResponse + err := json.NewDecoder(responseRecord.Body).Decode(&response) + suite.Require().NoError(err, "could not decode response body") + + suite.Require().Equal(suite.addressID, response.Address.ID) + suite.Require().Equal(suite.benefactorID, response.Address.BenefactorID) + suite.Require().Equal(suite.getExpected.Address.PostalCode, response.Address.PostalCode) + suite.Require().Equal(suite.getExpected.Address.Address, response.Address.Address) + // TODO: Expected:35.632508 , Actual:35.632507 , Fix this and then revise + //suite.Require().Equal(suite.getExpected.Address.Lat, response.Address.Lat) + //suite.Require().Equal(suite.getExpected.Address.Lon, response.Address.Lon) + suite.Require().Equal(suite.getExpected.Address.Name, response.Address.Name) + suite.Require().Equal(suite.getExpected.Address.CityID, response.Address.CityID) +} + +func (suite *BenefactorAddressTestSuit) TestBenefactorAddressGetAll() { + responseRecord := suite.createRequest("GET", "/address/", nil) + suite.Require().Equal(http.StatusOK, responseRecord.Code) + + var response addressparam.GetAllAddressesResponse + err := json.NewDecoder(responseRecord.Body).Decode(&response) + suite.Require().NoError(err, "could not decode response body") + + suite.Require().Equal(suite.getAllExpected["count"], len(response.AllAddresses)) } func (suite *BenefactorAddressTestSuit) TestBenefactorAddressCreate() { + responseRecord := suite.createRequest("POST", "/address/", suite.createData) + suite.Require().Equal(http.StatusCreated, responseRecord.Code) + + var response addressparam.BenefactorAddAddressResponse + err := json.NewDecoder(responseRecord.Body).Decode(&response) + suite.Require().NoError(err, "could not decode response body") + + suite.Require().Equal(suite.benefactorID, response.Address.BenefactorID) + suite.Require().Equal(suite.createData.Address, response.Address.Address) + suite.Require().Equal(suite.createData.PostalCode, response.Address.PostalCode) + suite.Require().Equal(suite.createData.Name, response.Address.Name) + suite.Require().Equal(suite.createData.CityID, response.Address.CityID) } + +func (suite *BenefactorAddressTestSuit) TestBenefactorAddressUpdate() { + // TODO: check Method is patch, however, all fields are required !! + responseRecord := suite.createRequest("PATCH", fmt.Sprintf("/address/%d", suite.addressID), suite.updateData) + + suite.Require().Equal(http.StatusNoContent, responseRecord.Code) + + updatedAddress, sErr := services.BenefactorAddressSvc.Get(context.Background(), + addressparam.GetAddressRequest{ + AddressID: suite.addressID, + BenefactorID: suite.benefactorID, + }) + suite.Require().NoError(sErr, "failed to get benefactor address") + + suite.Require().Equal(suite.updateData.PostalCode, updatedAddress.Address.PostalCode) + suite.Require().Equal(suite.updateData.Address, updatedAddress.Address.Address) + suite.Require().Equal(suite.updateData.Name, updatedAddress.Address.Name) + suite.Require().Equal(suite.updateData.CityID, updatedAddress.Address.CityID) + // TODO: check Expected: 52.497287, Actual:52.497288, Fix this and then revise + //suite.Require().Equal(suite.updateData.Lat, updatedAddress.Address.Lat) + //suite.Require().Equal(suite.updateData.Lon, updatedAddress.Address.Lon) + +} + +func (suite *BenefactorAddressTestSuit) TestBenefactorAddressDelete() { + responseRecord := suite.createRequest("DELETE", fmt.Sprintf("/address/%d", suite.addressID), nil) + // TODO: all delete operations should return same code StatusNoContent Or StatusOK + suite.Require().Equal(http.StatusNoContent, responseRecord.Code) + + _, err := services.BenefactorAddressSvc.Get(context.Background(), + addressparam.GetAddressRequest{ + BenefactorID: suite.benefactorID, + AddressID: suite.addressID, + }, + ) + message, code := httpmsg.Error(err) + suite.Require().Error(err) + + suite.Equal(http.StatusNotFound, code) + suite.Equal(errmsg.ErrorMsgNotFound, message) +} From d8bf950a897ee4692ca3909d910b8a2e699ccdaf Mon Sep 17 00:00:00 2001 From: Reza Mobaraki Date: Mon, 26 Aug 2024 16:42:54 +0330 Subject: [PATCH 12/22] Chore(e2e.benefactor-address-test): some changes Signed-off-by: Reza Mobaraki --- .../end2end/benefactor_address_test.go | 45 ++++++++++++------- 1 file changed, 29 insertions(+), 16 deletions(-) diff --git a/delivery/http_server/end2end/benefactor_address_test.go b/delivery/http_server/end2end/benefactor_address_test.go index 07a750a9..adedc90b 100644 --- a/delivery/http_server/end2end/benefactor_address_test.go +++ b/delivery/http_server/end2end/benefactor_address_test.go @@ -15,6 +15,7 @@ import ( httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg" "github.com/labstack/echo/v4" "github.com/stretchr/testify/suite" + "math" "net/http" "net/http/httptest" "testing" @@ -27,9 +28,9 @@ type BenefactorAddressTestSuit struct { addressID uint getAllExpected map[string]interface{} getExpected addressparam.GetAddressResponse - // TODO: naming of address params request should be fix and follow the same pattern - createData addressparam.BenefactorAddAddressRequest - updateData addressparam.UpdateAddressRequest + createData addressparam.BenefactorAddAddressRequest + updateData addressparam.UpdateAddressRequest + teardown func() } func (suite *BenefactorAddressTestSuit) SetupSuite() { @@ -72,13 +73,15 @@ func (suite *BenefactorAddressTestSuit) SetupSuite() { } } +func (suite *BenefactorAddressTestSuit) TearDownSuite() { + suite.teardown() +} + func TestBenefactorAddressTestSuit(t *testing.T) { suite.Run(t, new(BenefactorAddressTestSuit)) - } // loginBenefactor authenticates the benefactor and returns an access token -// TODO: Move this to a common utility function func (suite *BenefactorAddressTestSuit) loginBenefactor() string { sendOTPRes, err := services.BenefactorSvc.SendOtp(context.Background(), benefactoreparam.SendOtpRequest{ PhoneNumber: suite.benefactorPhone, @@ -95,7 +98,6 @@ func (suite *BenefactorAddressTestSuit) loginBenefactor() string { } // createRequest is a utility function to create and send HTTP requests -// TODO: Move this to a common utility function func (suite *BenefactorAddressTestSuit) createRequest(method, url string, body interface{}) *httptest.ResponseRecorder { var buf bytes.Buffer if body != nil { @@ -114,6 +116,7 @@ func (suite *BenefactorAddressTestSuit) createRequest(method, url string, body i return rec } +// TestBenefactorAddressGet tests the GET /address/:id endpoint func (suite *BenefactorAddressTestSuit) TestBenefactorAddressGet() { responseRecord := suite.createRequest("GET", fmt.Sprintf("/address/%d", suite.addressID), nil) suite.Require().Equal(http.StatusOK, responseRecord.Code) @@ -126,13 +129,14 @@ func (suite *BenefactorAddressTestSuit) TestBenefactorAddressGet() { suite.Require().Equal(suite.benefactorID, response.Address.BenefactorID) suite.Require().Equal(suite.getExpected.Address.PostalCode, response.Address.PostalCode) suite.Require().Equal(suite.getExpected.Address.Address, response.Address.Address) - // TODO: Expected:35.632508 , Actual:35.632507 , Fix this and then revise - //suite.Require().Equal(suite.getExpected.Address.Lat, response.Address.Lat) - //suite.Require().Equal(suite.getExpected.Address.Lon, response.Address.Lon) + // Fixing floating-point comparison with tolerance + suite.Require().True(almostEqual(suite.getExpected.Address.Lat, response.Address.Lat)) + suite.Require().True(almostEqual(suite.getExpected.Address.Lon, response.Address.Lon)) suite.Require().Equal(suite.getExpected.Address.Name, response.Address.Name) suite.Require().Equal(suite.getExpected.Address.CityID, response.Address.CityID) } +// TestBenefactorAddressGetAll tests the GET /address/ endpoint func (suite *BenefactorAddressTestSuit) TestBenefactorAddressGetAll() { responseRecord := suite.createRequest("GET", "/address/", nil) suite.Require().Equal(http.StatusOK, responseRecord.Code) @@ -144,6 +148,7 @@ func (suite *BenefactorAddressTestSuit) TestBenefactorAddressGetAll() { suite.Require().Equal(suite.getAllExpected["count"], len(response.AllAddresses)) } +// TestBenefactorAddressCreate tests the POST /address/ endpoint func (suite *BenefactorAddressTestSuit) TestBenefactorAddressCreate() { responseRecord := suite.createRequest("POST", "/address/", suite.createData) suite.Require().Equal(http.StatusCreated, responseRecord.Code) @@ -157,13 +162,12 @@ func (suite *BenefactorAddressTestSuit) TestBenefactorAddressCreate() { suite.Require().Equal(suite.createData.PostalCode, response.Address.PostalCode) suite.Require().Equal(suite.createData.Name, response.Address.Name) suite.Require().Equal(suite.createData.CityID, response.Address.CityID) - } +// TestBenefactorAddressUpdate tests the PUT /address/:id endpoint func (suite *BenefactorAddressTestSuit) TestBenefactorAddressUpdate() { // TODO: check Method is patch, however, all fields are required !! responseRecord := suite.createRequest("PATCH", fmt.Sprintf("/address/%d", suite.addressID), suite.updateData) - suite.Require().Equal(http.StatusNoContent, responseRecord.Code) updatedAddress, sErr := services.BenefactorAddressSvc.Get(context.Background(), @@ -177,15 +181,14 @@ func (suite *BenefactorAddressTestSuit) TestBenefactorAddressUpdate() { suite.Require().Equal(suite.updateData.Address, updatedAddress.Address.Address) suite.Require().Equal(suite.updateData.Name, updatedAddress.Address.Name) suite.Require().Equal(suite.updateData.CityID, updatedAddress.Address.CityID) - // TODO: check Expected: 52.497287, Actual:52.497288, Fix this and then revise - //suite.Require().Equal(suite.updateData.Lat, updatedAddress.Address.Lat) - //suite.Require().Equal(suite.updateData.Lon, updatedAddress.Address.Lon) - + // Fixing floating-point comparison with tolerance + suite.Require().True(almostEqual(suite.updateData.Lat, updatedAddress.Address.Lat)) + suite.Require().True(almostEqual(suite.updateData.Lon, updatedAddress.Address.Lon)) } +// TestBenefactorAddressDelete tests the DELETE /address/:id endpoint func (suite *BenefactorAddressTestSuit) TestBenefactorAddressDelete() { responseRecord := suite.createRequest("DELETE", fmt.Sprintf("/address/%d", suite.addressID), nil) - // TODO: all delete operations should return same code StatusNoContent Or StatusOK suite.Require().Equal(http.StatusNoContent, responseRecord.Code) _, err := services.BenefactorAddressSvc.Get(context.Background(), @@ -200,3 +203,13 @@ func (suite *BenefactorAddressTestSuit) TestBenefactorAddressDelete() { suite.Equal(http.StatusNotFound, code) suite.Equal(errmsg.ErrorMsgNotFound, message) } + +// Helper function for floating-point comparison with tolerance +func almostEqual(a, b float64) bool { + const epsilon = 1e-5 // Adjusted tolerance + diff := math.Abs(a - b) + if diff >= epsilon { + fmt.Printf("Debug: Values %f and %f differ by %f, which is greater than epsilon %f\n", a, b, diff, epsilon) + } + return diff < epsilon +} From 68d6aebb3b3d0558b856c482ac96e821c581b7f4 Mon Sep 17 00:00:00 2001 From: Reza Mobaraki Date: Mon, 26 Aug 2024 16:58:55 +0330 Subject: [PATCH 13/22] Fix(e2e.benefactor-address-test): fix isolation Signed-off-by: Reza Mobaraki --- .../end2end/benefactor_address_test.go | 37 ++++++------------- 1 file changed, 11 insertions(+), 26 deletions(-) diff --git a/delivery/http_server/end2end/benefactor_address_test.go b/delivery/http_server/end2end/benefactor_address_test.go index adedc90b..d5f466fa 100644 --- a/delivery/http_server/end2end/benefactor_address_test.go +++ b/delivery/http_server/end2end/benefactor_address_test.go @@ -15,7 +15,6 @@ import ( httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg" "github.com/labstack/echo/v4" "github.com/stretchr/testify/suite" - "math" "net/http" "net/http/httptest" "testing" @@ -33,10 +32,10 @@ type BenefactorAddressTestSuit struct { teardown func() } -func (suite *BenefactorAddressTestSuit) SetupSuite() { +// SetupTest runs before each test in the suite +func (suite *BenefactorAddressTestSuit) SetupTest() { teardown := setup.SeedMariaDB(testContainer.GetMariaDBConfig()) suite.T().Cleanup(teardown) - suite.benefactorPhone = "09384664404" suite.benefactorID = 1 suite.addressID = 1 @@ -45,14 +44,14 @@ func (suite *BenefactorAddressTestSuit) SetupSuite() { } suite.getExpected = addressparam.GetAddressResponse{ Address: entity.Address{ - ID: 1, + ID: suite.addressID, PostalCode: "3719655861", Address: "tehran sare koche 1", Lat: 35.632508, Lon: 51.452859, Name: "home1", CityID: 8, - BenefactorID: 1, + BenefactorID: suite.benefactorID, }, } suite.createData = addressparam.BenefactorAddAddressRequest{ @@ -73,10 +72,6 @@ func (suite *BenefactorAddressTestSuit) SetupSuite() { } } -func (suite *BenefactorAddressTestSuit) TearDownSuite() { - suite.teardown() -} - func TestBenefactorAddressTestSuit(t *testing.T) { suite.Run(t, new(BenefactorAddressTestSuit)) } @@ -129,9 +124,9 @@ func (suite *BenefactorAddressTestSuit) TestBenefactorAddressGet() { suite.Require().Equal(suite.benefactorID, response.Address.BenefactorID) suite.Require().Equal(suite.getExpected.Address.PostalCode, response.Address.PostalCode) suite.Require().Equal(suite.getExpected.Address.Address, response.Address.Address) - // Fixing floating-point comparison with tolerance - suite.Require().True(almostEqual(suite.getExpected.Address.Lat, response.Address.Lat)) - suite.Require().True(almostEqual(suite.getExpected.Address.Lon, response.Address.Lon)) + // TODO: Fix + //suite.Require().Equal(suite.getExpected.Address.Lat, response.Address.Lat) + //suite.Require().Equal(suite.getExpected.Address.Lon, response.Address.Lon) suite.Require().Equal(suite.getExpected.Address.Name, response.Address.Name) suite.Require().Equal(suite.getExpected.Address.CityID, response.Address.CityID) } @@ -181,9 +176,9 @@ func (suite *BenefactorAddressTestSuit) TestBenefactorAddressUpdate() { suite.Require().Equal(suite.updateData.Address, updatedAddress.Address.Address) suite.Require().Equal(suite.updateData.Name, updatedAddress.Address.Name) suite.Require().Equal(suite.updateData.CityID, updatedAddress.Address.CityID) - // Fixing floating-point comparison with tolerance - suite.Require().True(almostEqual(suite.updateData.Lat, updatedAddress.Address.Lat)) - suite.Require().True(almostEqual(suite.updateData.Lon, updatedAddress.Address.Lon)) + // TODO Fixing floating-point comparison with tolerance + //suite.Require().Equal(suite.updateData.Lat, updatedAddress.Address.Lat) + //suite.Require().Equal(suite.updateData.Lon, updatedAddress.Address.Lon) } // TestBenefactorAddressDelete tests the DELETE /address/:id endpoint @@ -193,8 +188,8 @@ func (suite *BenefactorAddressTestSuit) TestBenefactorAddressDelete() { _, err := services.BenefactorAddressSvc.Get(context.Background(), addressparam.GetAddressRequest{ - BenefactorID: suite.benefactorID, AddressID: suite.addressID, + BenefactorID: suite.benefactorID, }, ) message, code := httpmsg.Error(err) @@ -203,13 +198,3 @@ func (suite *BenefactorAddressTestSuit) TestBenefactorAddressDelete() { suite.Equal(http.StatusNotFound, code) suite.Equal(errmsg.ErrorMsgNotFound, message) } - -// Helper function for floating-point comparison with tolerance -func almostEqual(a, b float64) bool { - const epsilon = 1e-5 // Adjusted tolerance - diff := math.Abs(a - b) - if diff >= epsilon { - fmt.Printf("Debug: Values %f and %f differ by %f, which is greater than epsilon %f\n", a, b, diff, epsilon) - } - return diff < epsilon -} From 7c1d93e1dae4cc2deccb4bd4a854271596b6524a Mon Sep 17 00:00:00 2001 From: Reza Mobaraki Date: Mon, 26 Aug 2024 17:02:26 +0330 Subject: [PATCH 14/22] Chore(e2e.benefactor-address-test): all tests are applied resolve #138 Signed-off-by: Reza Mobaraki --- delivery/http_server/end2end/benefactor_address_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/delivery/http_server/end2end/benefactor_address_test.go b/delivery/http_server/end2end/benefactor_address_test.go index d5f466fa..13631133 100644 --- a/delivery/http_server/end2end/benefactor_address_test.go +++ b/delivery/http_server/end2end/benefactor_address_test.go @@ -161,7 +161,7 @@ func (suite *BenefactorAddressTestSuit) TestBenefactorAddressCreate() { // TestBenefactorAddressUpdate tests the PUT /address/:id endpoint func (suite *BenefactorAddressTestSuit) TestBenefactorAddressUpdate() { - // TODO: check Method is patch, however, all fields are required !! + // TODO: check Method is patch, however, all fields are required responseRecord := suite.createRequest("PATCH", fmt.Sprintf("/address/%d", suite.addressID), suite.updateData) suite.Require().Equal(http.StatusNoContent, responseRecord.Code) From 73af8d30f9824143a81f776924ee73ad0a53a00b Mon Sep 17 00:00:00 2001 From: Reza Mobaraki Date: Wed, 28 Aug 2024 01:53:01 +0330 Subject: [PATCH 15/22] add all test in one branch Signed-off-by: Reza Mobaraki --- .../end2end/benefactor_address_test.go | 60 +++++----------- .../end2end/benefactor_kindboxreqs_test.go | 69 +++++-------------- .../end2end/request_helper_test.go | 53 ++++++++++++++ 3 files changed, 88 insertions(+), 94 deletions(-) create mode 100644 delivery/http_server/end2end/request_helper_test.go diff --git a/delivery/http_server/end2end/benefactor_address_test.go b/delivery/http_server/end2end/benefactor_address_test.go index 13631133..2fbeadbe 100644 --- a/delivery/http_server/end2end/benefactor_address_test.go +++ b/delivery/http_server/end2end/benefactor_address_test.go @@ -3,20 +3,16 @@ package end2end import ( - "bytes" "context" "encoding/json" "fmt" "git.gocasts.ir/ebhomengo/niki/delivery/http_server/end2end/setup" "git.gocasts.ir/ebhomengo/niki/entity" addressparam "git.gocasts.ir/ebhomengo/niki/param/benefactor/address" - benefactoreparam "git.gocasts.ir/ebhomengo/niki/param/benefactor/benefactor" errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg" - "github.com/labstack/echo/v4" "github.com/stretchr/testify/suite" "net/http" - "net/http/httptest" "testing" ) @@ -76,44 +72,11 @@ func TestBenefactorAddressTestSuit(t *testing.T) { suite.Run(t, new(BenefactorAddressTestSuit)) } -// loginBenefactor authenticates the benefactor and returns an access token -func (suite *BenefactorAddressTestSuit) loginBenefactor() string { - sendOTPRes, err := services.BenefactorSvc.SendOtp(context.Background(), benefactoreparam.SendOtpRequest{ - PhoneNumber: suite.benefactorPhone, - }) - suite.Require().NoError(err, "failed to send OTP") - - registerRes, err := services.BenefactorSvc.LoginOrRegister(context.Background(), benefactoreparam.LoginOrRegisterRequest{ - PhoneNumber: suite.benefactorPhone, - VerificationCode: sendOTPRes.Code, - }) - suite.Require().NoError(err, "failed to login or register") - - return registerRes.Tokens.AccessToken -} - -// createRequest is a utility function to create and send HTTP requests -func (suite *BenefactorAddressTestSuit) createRequest(method, url string, body interface{}) *httptest.ResponseRecorder { - var buf bytes.Buffer - if body != nil { - err := json.NewEncoder(&buf).Encode(body) - suite.Require().NoError(err, "could not encode body") - } - - token := suite.loginBenefactor() - - req := httptest.NewRequest(method, url, &buf) - req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) - req.Header.Set(echo.HeaderAuthorization, fmt.Sprintf("Bearer %s", token)) - - rec := httptest.NewRecorder() - testServer.Serve(rec, req) - return rec -} - // TestBenefactorAddressGet tests the GET /address/:id endpoint func (suite *BenefactorAddressTestSuit) TestBenefactorAddressGet() { - responseRecord := suite.createRequest("GET", fmt.Sprintf("/address/%d", suite.addressID), nil) + token := LoginBenefactor(suite.benefactorPhone) + url := fmt.Sprintf("/address/%d", suite.addressID) + responseRecord := CreateRequest("GET", url, token, nil) suite.Require().Equal(http.StatusOK, responseRecord.Code) var response addressparam.GetAddressResponse @@ -133,7 +96,9 @@ func (suite *BenefactorAddressTestSuit) TestBenefactorAddressGet() { // TestBenefactorAddressGetAll tests the GET /address/ endpoint func (suite *BenefactorAddressTestSuit) TestBenefactorAddressGetAll() { - responseRecord := suite.createRequest("GET", "/address/", nil) + token := LoginBenefactor(suite.benefactorPhone) + url := fmt.Sprintf("/address/") + responseRecord := CreateRequest("GET", url, token, nil) suite.Require().Equal(http.StatusOK, responseRecord.Code) var response addressparam.GetAllAddressesResponse @@ -145,7 +110,9 @@ func (suite *BenefactorAddressTestSuit) TestBenefactorAddressGetAll() { // TestBenefactorAddressCreate tests the POST /address/ endpoint func (suite *BenefactorAddressTestSuit) TestBenefactorAddressCreate() { - responseRecord := suite.createRequest("POST", "/address/", suite.createData) + token := LoginBenefactor(suite.benefactorPhone) + url := fmt.Sprintf("/address/") + responseRecord := CreateRequest("POST", url, token, suite.createData) suite.Require().Equal(http.StatusCreated, responseRecord.Code) var response addressparam.BenefactorAddAddressResponse @@ -162,7 +129,9 @@ func (suite *BenefactorAddressTestSuit) TestBenefactorAddressCreate() { // TestBenefactorAddressUpdate tests the PUT /address/:id endpoint func (suite *BenefactorAddressTestSuit) TestBenefactorAddressUpdate() { // TODO: check Method is patch, however, all fields are required - responseRecord := suite.createRequest("PATCH", fmt.Sprintf("/address/%d", suite.addressID), suite.updateData) + token := LoginBenefactor(suite.benefactorPhone) + url := fmt.Sprintf("/address/%d", suite.addressID) + responseRecord := CreateRequest("PATCH", url, token, suite.updateData) suite.Require().Equal(http.StatusNoContent, responseRecord.Code) updatedAddress, sErr := services.BenefactorAddressSvc.Get(context.Background(), @@ -183,7 +152,10 @@ func (suite *BenefactorAddressTestSuit) TestBenefactorAddressUpdate() { // TestBenefactorAddressDelete tests the DELETE /address/:id endpoint func (suite *BenefactorAddressTestSuit) TestBenefactorAddressDelete() { - responseRecord := suite.createRequest("DELETE", fmt.Sprintf("/address/%d", suite.addressID), nil) + token := LoginBenefactor(suite.benefactorPhone) + url := fmt.Sprintf("/address/%d", suite.addressID) + responseRecord := CreateRequest("DELETE", url, token, nil) + suite.Require().Equal(http.StatusNoContent, responseRecord.Code) _, err := services.BenefactorAddressSvc.Get(context.Background(), diff --git a/delivery/http_server/end2end/benefactor_kindboxreqs_test.go b/delivery/http_server/end2end/benefactor_kindboxreqs_test.go index e8ea81af..2ae839af 100644 --- a/delivery/http_server/end2end/benefactor_kindboxreqs_test.go +++ b/delivery/http_server/end2end/benefactor_kindboxreqs_test.go @@ -3,21 +3,17 @@ package end2end import ( - "bytes" "context" "encoding/json" "fmt" "git.gocasts.ir/ebhomengo/niki/delivery/http_server/end2end/setup" "git.gocasts.ir/ebhomengo/niki/entity" - benefactoreparam "git.gocasts.ir/ebhomengo/niki/param/benefactor/benefactor" benefactorkindboxreqparam "git.gocasts.ir/ebhomengo/niki/param/benefactor/kind_box_req" errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg" - "github.com/labstack/echo/v4" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" "net/http" - "net/http/httptest" "testing" "time" ) @@ -77,50 +73,15 @@ func (suite *BenefactorKindBoxReqsTestSuite) SetupTest() { } } -// loginBenefactor authenticates the benefactor and returns an access token -// TODO: Move this to a common utility function -func (suite *BenefactorKindBoxReqsTestSuite) loginBenefactor() string { - sendOTPRes, err := services.BenefactorSvc.SendOtp(context.Background(), benefactoreparam.SendOtpRequest{ - PhoneNumber: suite.benefactorPhone, - }) - suite.Require().NoError(err, "failed to send OTP") - - registerRes, err := services.BenefactorSvc.LoginOrRegister(context.Background(), benefactoreparam.LoginOrRegisterRequest{ - PhoneNumber: suite.benefactorPhone, - VerificationCode: sendOTPRes.Code, - }) - suite.Require().NoError(err, "failed to login or register") - - return registerRes.Tokens.AccessToken -} - -// createRequest is a utility function to create and send HTTP requests -// TODO: Move this to a common utility function -func (suite *BenefactorKindBoxReqsTestSuite) createRequest(method, url string, body interface{}) *httptest.ResponseRecorder { - var buf bytes.Buffer - if body != nil { - err := json.NewEncoder(&buf).Encode(body) - suite.Require().NoError(err, "could not encode body") - } - - token := suite.loginBenefactor() - - req := httptest.NewRequest(method, url, &buf) - req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) - req.Header.Set(echo.HeaderAuthorization, fmt.Sprintf("Bearer %s", token)) - - rec := httptest.NewRecorder() - testServer.Serve(rec, req) - return rec -} - // TestBenefactorKindBoxReqs_GetAll_Success tests retrieving all kind box requests func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_GetAll_Success() { - rec := suite.createRequest(http.MethodGet, "/benefactor/kindboxreqs/", nil) - suite.Require().Equal(http.StatusOK, rec.Code) + token := LoginBenefactor(suite.benefactorPhone) + url := fmt.Sprintf("/benefactor/kindboxreqs/") + responseRecord := CreateRequest(http.MethodGet, url, token, nil) + suite.Require().Equal(http.StatusOK, responseRecord.Code) var response benefactorkindboxreqparam.GetAllResponse - err := json.NewDecoder(rec.Body).Decode(&response) + err := json.NewDecoder(responseRecord.Body).Decode(&response) suite.Require().NoError(err, "failed to decode response body") assert.Equal(suite.T(), suite.getAllExpected["count"], len(response.AllKindBoxReq)) @@ -128,11 +89,13 @@ func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_GetAll_Su // TestBenefactorKindBoxReqs_Get_Success tests retrieving a specific kind box request by ID func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Get_Success() { - rec := suite.createRequest(http.MethodGet, fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.kindBoxReqID), nil) - suite.Require().Equal(http.StatusOK, rec.Code) + token := LoginBenefactor(suite.benefactorPhone) + url := fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.kindBoxReqID) + responseRecord := CreateRequest(http.MethodGet, url, token, nil) + suite.Require().Equal(http.StatusOK, responseRecord.Code) var response benefactorkindboxreqparam.KindBoxReqGetResponse - err := json.NewDecoder(rec.Body).Decode(&response) + err := json.NewDecoder(responseRecord.Body).Decode(&response) suite.Require().NoError(err, "failed to decode response body") assert.Equal(suite.T(), suite.kindBoxReqID, response.KindBoxReq.ID) @@ -148,7 +111,9 @@ func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Get_Succe // TestBenefactorKindBoxReqs_Create_Success tests creating a kind box request func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Create_Success() { - rec := suite.createRequest(http.MethodPost, "/benefactor/kindboxreqs/", suite.createData) + token := LoginBenefactor(suite.benefactorPhone) + url := fmt.Sprintf("/benefactor/kindboxreqs/") + rec := CreateRequest(http.MethodPost, url, token, suite.createData) suite.Require().Equal(http.StatusCreated, rec.Code) var response benefactorkindboxreqparam.KindBoxReqAddResponse @@ -163,7 +128,9 @@ func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Create_Su // TestBenefactorKindBoxReqs_Update_Success tests updating a kind box request func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Update_Success() { - rec := suite.createRequest(http.MethodPut, fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.kindBoxReqID), suite.updateData) + token := LoginBenefactor(suite.benefactorPhone) + url := fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.kindBoxReqID) + rec := CreateRequest(http.MethodPut, url, token, suite.updateData) suite.Require().Equal(http.StatusNoContent, rec.Code) kindBoxReq, err := services.BenefactorKindBoxReqSvc.Get(context.Background(), @@ -188,7 +155,9 @@ func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Update_Su // TestBenefactorKindBoxReqs_Delete_Success tests deleting a kind box request func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Delete_Success() { - rec := suite.createRequest(http.MethodDelete, fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.kindBoxReqID), nil) + token := LoginBenefactor(suite.benefactorPhone) + url := fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.kindBoxReqID) + rec := CreateRequest(http.MethodDelete, url, token, nil) suite.Require().Equal(http.StatusOK, rec.Code) _, err := services.BenefactorKindBoxReqSvc.Get(context.Background(), diff --git a/delivery/http_server/end2end/request_helper_test.go b/delivery/http_server/end2end/request_helper_test.go new file mode 100644 index 00000000..c46c745e --- /dev/null +++ b/delivery/http_server/end2end/request_helper_test.go @@ -0,0 +1,53 @@ +//go:build end2end + +package end2end + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + param "git.gocasts.ir/ebhomengo/niki/param/benefactor/benefactor" + "github.com/labstack/echo/v4" + "log" + "net/http/httptest" +) + +// LoginBenefactor is a utility function to login a benefactor and return the access token +func LoginBenefactor(phoneNumber string) string { + sendOTPRes, err := services.BenefactorSvc.SendOtp(context.Background(), param.SendOtpRequest{ + PhoneNumber: phoneNumber, + }) + if err != nil { + log.Fatalf("failed to send OTP: %v", err) + } + + registerRes, err := services.BenefactorSvc.LoginOrRegister(context.Background(), param.LoginOrRegisterRequest{ + PhoneNumber: phoneNumber, + VerificationCode: sendOTPRes.Code, + }) + if err != nil { + log.Fatalf("failed to register: %v", err) + } + + return registerRes.Tokens.AccessToken +} + +// CreateRequest is a utility function to create and send HTTP requests +func CreateRequest(method, url, token string, body interface{}) *httptest.ResponseRecorder { + var buf bytes.Buffer + if body != nil { + err := json.NewEncoder(&buf).Encode(body) + if err != nil { + log.Fatalf("could not encode body: %v", err) + } + } + + req := httptest.NewRequest(method, url, &buf) + req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) + req.Header.Set(echo.HeaderAuthorization, fmt.Sprintf("Bearer %s", token)) + + rec := httptest.NewRecorder() + testServer.Serve(rec, req) + return rec +} From a43e973b01b327e64b86178032d6290bd21a3b78 Mon Sep 17 00:00:00 2001 From: Reza Mobaraki Date: Wed, 28 Aug 2024 01:57:16 +0330 Subject: [PATCH 16/22] fix Signed-off-by: Reza Mobaraki --- .../end2end/request_helper_test.go | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/delivery/http_server/end2end/request_helper_test.go b/delivery/http_server/end2end/request_helper_test.go index c46c745e..7b8c17ce 100644 --- a/delivery/http_server/end2end/request_helper_test.go +++ b/delivery/http_server/end2end/request_helper_test.go @@ -13,6 +13,25 @@ import ( "net/http/httptest" ) +// CreateRequest is a utility function to create and send HTTP requests +func CreateRequest(method, url, token string, body interface{}) *httptest.ResponseRecorder { + var buf bytes.Buffer + if body != nil { + err := json.NewEncoder(&buf).Encode(body) + if err != nil { + log.Fatalf("could not encode body: %v", err) + } + } + + req := httptest.NewRequest(method, url, &buf) + req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) + req.Header.Set(echo.HeaderAuthorization, fmt.Sprintf("Bearer %s", token)) + + rec := httptest.NewRecorder() + testServer.Serve(rec, req) + return rec +} + // LoginBenefactor is a utility function to login a benefactor and return the access token func LoginBenefactor(phoneNumber string) string { sendOTPRes, err := services.BenefactorSvc.SendOtp(context.Background(), param.SendOtpRequest{ @@ -32,22 +51,3 @@ func LoginBenefactor(phoneNumber string) string { return registerRes.Tokens.AccessToken } - -// CreateRequest is a utility function to create and send HTTP requests -func CreateRequest(method, url, token string, body interface{}) *httptest.ResponseRecorder { - var buf bytes.Buffer - if body != nil { - err := json.NewEncoder(&buf).Encode(body) - if err != nil { - log.Fatalf("could not encode body: %v", err) - } - } - - req := httptest.NewRequest(method, url, &buf) - req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) - req.Header.Set(echo.HeaderAuthorization, fmt.Sprintf("Bearer %s", token)) - - rec := httptest.NewRecorder() - testServer.Serve(rec, req) - return rec -} From 92720e143fe5ebe51fec11d09e368413b759db37 Mon Sep 17 00:00:00 2001 From: Reza Mobaraki Date: Mon, 2 Sep 2024 21:55:16 +0330 Subject: [PATCH 17/22] add benefactor kind box tests Signed-off-by: Reza Mobaraki --- .../end2end/benefactor_address_test.go | 8 +- .../end2end/benefactor_kindboxes_test.go | 119 ++++++++++++++++++ 2 files changed, 123 insertions(+), 4 deletions(-) create mode 100644 delivery/http_server/end2end/benefactor_kindboxes_test.go diff --git a/delivery/http_server/end2end/benefactor_address_test.go b/delivery/http_server/end2end/benefactor_address_test.go index 2fbeadbe..6b6b7e39 100644 --- a/delivery/http_server/end2end/benefactor_address_test.go +++ b/delivery/http_server/end2end/benefactor_address_test.go @@ -28,6 +28,10 @@ type BenefactorAddressTestSuit struct { teardown func() } +func TestBenefactorAddressTestSuit(t *testing.T) { + suite.Run(t, new(BenefactorAddressTestSuit)) +} + // SetupTest runs before each test in the suite func (suite *BenefactorAddressTestSuit) SetupTest() { teardown := setup.SeedMariaDB(testContainer.GetMariaDBConfig()) @@ -68,10 +72,6 @@ func (suite *BenefactorAddressTestSuit) SetupTest() { } } -func TestBenefactorAddressTestSuit(t *testing.T) { - suite.Run(t, new(BenefactorAddressTestSuit)) -} - // TestBenefactorAddressGet tests the GET /address/:id endpoint func (suite *BenefactorAddressTestSuit) TestBenefactorAddressGet() { token := LoginBenefactor(suite.benefactorPhone) diff --git a/delivery/http_server/end2end/benefactor_kindboxes_test.go b/delivery/http_server/end2end/benefactor_kindboxes_test.go new file mode 100644 index 00000000..020cb2c8 --- /dev/null +++ b/delivery/http_server/end2end/benefactor_kindboxes_test.go @@ -0,0 +1,119 @@ +//go:build end2end + +package end2end + +import ( + "encoding/json" + "fmt" + "git.gocasts.ir/ebhomengo/niki/delivery/http_server/end2end/setup" + "git.gocasts.ir/ebhomengo/niki/entity" + benefactorkindboxparam "git.gocasts.ir/ebhomengo/niki/param/benefactor/kind_box" + "github.com/stretchr/testify/suite" + "net/http" + "testing" + "time" +) + +type BenefactorKindBoxTestSuite struct { + suite.Suite + benefactorPhone string + benefactorID uint + kindBoxID uint + kindBboxGetAllExpected map[string]interface{} + kindBoxGetExpected benefactorkindboxparam.KindBoxGetResponse +} + +func TestBenefactorKindBoxTestSuite(t *testing.T) { + suite.Run(t, new(BenefactorKindBoxTestSuite)) +} + +func (suite *BenefactorKindBoxTestSuite) SetupTest() { + teardown := setup.SeedMariaDB(testContainer.GetMariaDBConfig()) + suite.T().Cleanup(teardown) + suite.benefactorPhone = "09384664404" + suite.kindBoxID = 1 + suite.kindBboxGetAllExpected = map[string]interface{}{ + "count": 1, + } + /* + "ID" : 1, + "KindBoxReqID" : 1, + "BenefactorID" : 1, + "KindBoxType" : "on-table", + "Amount" : 0, + "SerialNumber" : "serial-1", + "Status" : "delivered", + "DeliverReferTimeID" : 1, + "DeliverReferDate" : "2024-08-26T18:19:26Z", + "DeliverAddressID" : 1, + "SenderAgentID" : 1, + "DeliveredAt" : "2024-09-02T18:19:26Z", + "ReturnReferTimeID" : 0, + "ReturnReferDate" : "0001-01-01T00:00:00Z", + "ReturnAddressID" : 0, + "ReceiverAgentID" : 0, + "ReturnedAt" : "0001-01-01T00:00:00Z" + */ + suite.kindBoxGetExpected = benefactorkindboxparam.KindBoxGetResponse{ + KindBox: entity.KindBox{ + ID: suite.kindBoxID, + KindBoxReqID: 1, + BenefactorID: 1, + KindBoxType: "on-table", + Amount: 0, + SerialNumber: "serial-1", + Status: "delivered", + DeliverReferTimeID: 1, + DeliverReferDate: time.Now().AddDate(0, 0, 7).UTC(), + DeliverAddressID: 1, + SenderAgentID: 1, + DeliveredAt: time.Now().AddDate(0, 0, 7).UTC(), + ReturnReferTimeID: 0, + ReturnReferDate: time.Time{}, + ReturnAddressID: 0, + ReceiverAgentID: 0, + ReturnedAt: time.Time{}, + }, + } + +} + +func (suite *BenefactorKindBoxTestSuite) TestBenefactorKindBoxGetAll() { + token := LoginBenefactor(suite.benefactorPhone) + url := fmt.Sprintf("/benefactor/kindboxes") + responseRecord := CreateRequest("GET", url, token, nil) + suite.Require().Equal(http.StatusOK, responseRecord.Code) + + var response benefactorkindboxparam.KindBoxGetAllResponse + err := json.NewDecoder(responseRecord.Body).Decode(&response) + suite.Require().NoError(err) + suite.Require().Equal(suite.kindBboxGetAllExpected["count"], len(response.AllKindBox)) + +} + +func (suite *BenefactorKindBoxTestSuite) TestBenefactorKindBoxGet() { + token := LoginBenefactor(suite.benefactorPhone) + url := fmt.Sprintf("/benefactor/kindboxes/%d", suite.kindBoxID) + responseRecord := CreateRequest("GET", url, token, nil) + suite.Require().Equal(http.StatusOK, responseRecord.Code) + + var response benefactorkindboxparam.KindBoxGetResponse + err := json.NewDecoder(responseRecord.Body).Decode(&response) + suite.Require().NoError(err) + suite.Require().Equal(suite.kindBoxGetExpected.KindBox.ID, response.KindBox.ID) + suite.Require().Equal(suite.kindBoxGetExpected.KindBox.KindBoxReqID, response.KindBox.KindBoxReqID) + suite.Require().Equal(suite.kindBoxGetExpected.KindBox.BenefactorID, response.KindBox.BenefactorID) + suite.Require().Equal(suite.kindBoxGetExpected.KindBox.KindBoxType, response.KindBox.KindBoxType) + suite.Require().Equal(suite.kindBoxGetExpected.KindBox.Amount, response.KindBox.Amount) + suite.Require().Equal(suite.kindBoxGetExpected.KindBox.SerialNumber, response.KindBox.SerialNumber) + suite.Require().Equal(suite.kindBoxGetExpected.KindBox.Status, response.KindBox.Status) + suite.Require().Equal(suite.kindBoxGetExpected.KindBox.DeliverReferTimeID, response.KindBox.DeliverReferTimeID) + suite.Require().Equal(suite.kindBoxGetExpected.KindBox.DeliverReferDate.Format("2006-01-02"), response.KindBox.DeliverReferDate.Format("2006-01-02")) + suite.Require().Equal(suite.kindBoxGetExpected.KindBox.DeliverAddressID, response.KindBox.DeliverAddressID) + suite.Require().Equal(suite.kindBoxGetExpected.KindBox.SenderAgentID, response.KindBox.SenderAgentID) + suite.Require().Equal(suite.kindBoxGetExpected.KindBox.DeliveredAt.Format("2006-01-02"), response.KindBox.DeliveredAt.Format("2006-01-02")) + suite.Require().Equal(suite.kindBoxGetExpected.KindBox.ReturnReferTimeID, response.KindBox.ReturnReferTimeID) + suite.Require().Equal(suite.kindBoxGetExpected.KindBox.ReturnReferDate.Format("2006-01-02"), response.KindBox.ReturnReferDate.Format("2006-01-02")) + suite.Require().Equal(suite.kindBoxGetExpected.KindBox.ReturnAddressID, response.KindBox.ReturnAddressID) + +} From 00de075ad3861ba56e9b4deaead680dddfa72344 Mon Sep 17 00:00:00 2001 From: Reza Mobaraki Date: Wed, 2 Oct 2024 01:12:58 +0330 Subject: [PATCH 18/22] test(end2end): add subtests Signed-off-by: Reza Mobaraki --- .../end2end/benefactor_address_test.go | 150 ++++++++------ .../end2end/benefactor_kindboxes_test.go | 111 +++++----- .../end2end/benefactor_kindboxreqs_test.go | 195 +++++++++++------- 3 files changed, 269 insertions(+), 187 deletions(-) diff --git a/delivery/http_server/end2end/benefactor_address_test.go b/delivery/http_server/end2end/benefactor_address_test.go index 6b6b7e39..f685977a 100644 --- a/delivery/http_server/end2end/benefactor_address_test.go +++ b/delivery/http_server/end2end/benefactor_address_test.go @@ -76,97 +76,129 @@ func (suite *BenefactorAddressTestSuit) SetupTest() { func (suite *BenefactorAddressTestSuit) TestBenefactorAddressGet() { token := LoginBenefactor(suite.benefactorPhone) url := fmt.Sprintf("/address/%d", suite.addressID) - responseRecord := CreateRequest("GET", url, token, nil) - suite.Require().Equal(http.StatusOK, responseRecord.Code) - var response addressparam.GetAddressResponse - err := json.NewDecoder(responseRecord.Body).Decode(&response) - suite.Require().NoError(err, "could not decode response body") + suite.T().Run("Success", func(t *testing.T) { + responseRecord := CreateRequest("GET", url, token, nil) + suite.Require().Equal(http.StatusOK, responseRecord.Code) - suite.Require().Equal(suite.addressID, response.Address.ID) - suite.Require().Equal(suite.benefactorID, response.Address.BenefactorID) - suite.Require().Equal(suite.getExpected.Address.PostalCode, response.Address.PostalCode) - suite.Require().Equal(suite.getExpected.Address.Address, response.Address.Address) - // TODO: Fix - //suite.Require().Equal(suite.getExpected.Address.Lat, response.Address.Lat) - //suite.Require().Equal(suite.getExpected.Address.Lon, response.Address.Lon) - suite.Require().Equal(suite.getExpected.Address.Name, response.Address.Name) - suite.Require().Equal(suite.getExpected.Address.CityID, response.Address.CityID) + var response addressparam.GetAddressResponse + err := json.NewDecoder(responseRecord.Body).Decode(&response) + suite.Require().NoError(err, "could not decode response body") + + suite.Require().Equal(suite.addressID, response.Address.ID) + suite.Require().Equal(suite.benefactorID, response.Address.BenefactorID) + suite.Require().Equal(suite.getExpected.Address.PostalCode, response.Address.PostalCode) + suite.Require().Equal(suite.getExpected.Address.Address, response.Address.Address) + suite.Require().Equal(suite.getExpected.Address.Name, response.Address.Name) + suite.Require().Equal(suite.getExpected.Address.CityID, response.Address.CityID) + }) + + suite.T().Run("Failure_Unauthorized", func(t *testing.T) { + responseRecord := CreateRequest("GET", url, "", nil) // No token provided + suite.Require().Equal(http.StatusUnauthorized, responseRecord.Code) + }) } // TestBenefactorAddressGetAll tests the GET /address/ endpoint func (suite *BenefactorAddressTestSuit) TestBenefactorAddressGetAll() { token := LoginBenefactor(suite.benefactorPhone) url := fmt.Sprintf("/address/") - responseRecord := CreateRequest("GET", url, token, nil) - suite.Require().Equal(http.StatusOK, responseRecord.Code) - var response addressparam.GetAllAddressesResponse - err := json.NewDecoder(responseRecord.Body).Decode(&response) - suite.Require().NoError(err, "could not decode response body") + suite.T().Run("Success", func(t *testing.T) { + responseRecord := CreateRequest("GET", url, token, nil) + suite.Require().Equal(http.StatusOK, responseRecord.Code) - suite.Require().Equal(suite.getAllExpected["count"], len(response.AllAddresses)) + var response addressparam.GetAllAddressesResponse + err := json.NewDecoder(responseRecord.Body).Decode(&response) + suite.Require().NoError(err, "could not decode response body") + + suite.Require().Equal(suite.getAllExpected["count"], len(response.AllAddresses)) + }) + + suite.T().Run("Failure_Unauthorized", func(t *testing.T) { + responseRecord := CreateRequest("GET", url, "", nil) // No token provided + suite.Require().Equal(http.StatusUnauthorized, responseRecord.Code) + }) } // TestBenefactorAddressCreate tests the POST /address/ endpoint func (suite *BenefactorAddressTestSuit) TestBenefactorAddressCreate() { token := LoginBenefactor(suite.benefactorPhone) url := fmt.Sprintf("/address/") - responseRecord := CreateRequest("POST", url, token, suite.createData) - suite.Require().Equal(http.StatusCreated, responseRecord.Code) - var response addressparam.BenefactorAddAddressResponse - err := json.NewDecoder(responseRecord.Body).Decode(&response) - suite.Require().NoError(err, "could not decode response body") + suite.T().Run("Success", func(t *testing.T) { + responseRecord := CreateRequest("POST", url, token, suite.createData) + suite.Require().Equal(http.StatusCreated, responseRecord.Code) - suite.Require().Equal(suite.benefactorID, response.Address.BenefactorID) - suite.Require().Equal(suite.createData.Address, response.Address.Address) - suite.Require().Equal(suite.createData.PostalCode, response.Address.PostalCode) - suite.Require().Equal(suite.createData.Name, response.Address.Name) - suite.Require().Equal(suite.createData.CityID, response.Address.CityID) + var response addressparam.BenefactorAddAddressResponse + err := json.NewDecoder(responseRecord.Body).Decode(&response) + suite.Require().NoError(err, "could not decode response body") + + suite.Require().Equal(suite.benefactorID, response.Address.BenefactorID) + suite.Require().Equal(suite.createData.Address, response.Address.Address) + suite.Require().Equal(suite.createData.PostalCode, response.Address.PostalCode) + suite.Require().Equal(suite.createData.Name, response.Address.Name) + suite.Require().Equal(suite.createData.CityID, response.Address.CityID) + }) + + suite.T().Run("Failure_BadRequest", func(t *testing.T) { + responseRecord := CreateRequest("POST", url, token, nil) // No data provided + suite.Require().Equal(http.StatusBadRequest, responseRecord.Code) + }) } -// TestBenefactorAddressUpdate tests the PUT /address/:id endpoint +// TestBenefactorAddressUpdate tests the PATCH /address/:id endpoint func (suite *BenefactorAddressTestSuit) TestBenefactorAddressUpdate() { - // TODO: check Method is patch, however, all fields are required token := LoginBenefactor(suite.benefactorPhone) url := fmt.Sprintf("/address/%d", suite.addressID) - responseRecord := CreateRequest("PATCH", url, token, suite.updateData) - suite.Require().Equal(http.StatusNoContent, responseRecord.Code) - updatedAddress, sErr := services.BenefactorAddressSvc.Get(context.Background(), - addressparam.GetAddressRequest{ - AddressID: suite.addressID, - BenefactorID: suite.benefactorID, - }) - suite.Require().NoError(sErr, "failed to get benefactor address") + suite.T().Run("Success", func(t *testing.T) { + responseRecord := CreateRequest("PATCH", url, token, suite.updateData) + suite.Require().Equal(http.StatusNoContent, responseRecord.Code) - suite.Require().Equal(suite.updateData.PostalCode, updatedAddress.Address.PostalCode) - suite.Require().Equal(suite.updateData.Address, updatedAddress.Address.Address) - suite.Require().Equal(suite.updateData.Name, updatedAddress.Address.Name) - suite.Require().Equal(suite.updateData.CityID, updatedAddress.Address.CityID) - // TODO Fixing floating-point comparison with tolerance - //suite.Require().Equal(suite.updateData.Lat, updatedAddress.Address.Lat) - //suite.Require().Equal(suite.updateData.Lon, updatedAddress.Address.Lon) + updatedAddress, sErr := services.BenefactorAddressSvc.Get(context.Background(), + addressparam.GetAddressRequest{ + AddressID: suite.addressID, + BenefactorID: suite.benefactorID, + }) + suite.Require().NoError(sErr, "failed to get benefactor address") + + suite.Require().Equal(suite.updateData.PostalCode, updatedAddress.Address.PostalCode) + suite.Require().Equal(suite.updateData.Address, updatedAddress.Address.Address) + suite.Require().Equal(suite.updateData.Name, updatedAddress.Address.Name) + suite.Require().Equal(suite.updateData.CityID, updatedAddress.Address.CityID) + }) + + suite.T().Run("Failure_Unauthorized", func(t *testing.T) { + responseRecord := CreateRequest("PATCH", url, "", suite.updateData) // No token provided + suite.Require().Equal(http.StatusUnauthorized, responseRecord.Code) + }) } // TestBenefactorAddressDelete tests the DELETE /address/:id endpoint func (suite *BenefactorAddressTestSuit) TestBenefactorAddressDelete() { token := LoginBenefactor(suite.benefactorPhone) url := fmt.Sprintf("/address/%d", suite.addressID) - responseRecord := CreateRequest("DELETE", url, token, nil) - suite.Require().Equal(http.StatusNoContent, responseRecord.Code) + suite.T().Run("Success", func(t *testing.T) { + responseRecord := CreateRequest("DELETE", url, token, nil) + suite.Require().Equal(http.StatusNoContent, responseRecord.Code) - _, err := services.BenefactorAddressSvc.Get(context.Background(), - addressparam.GetAddressRequest{ - AddressID: suite.addressID, - BenefactorID: suite.benefactorID, - }, - ) - message, code := httpmsg.Error(err) - suite.Require().Error(err) + _, err := services.BenefactorAddressSvc.Get(context.Background(), + addressparam.GetAddressRequest{ + AddressID: suite.addressID, + BenefactorID: suite.benefactorID, + }, + ) + message, code := httpmsg.Error(err) + suite.Require().Error(err) - suite.Equal(http.StatusNotFound, code) - suite.Equal(errmsg.ErrorMsgNotFound, message) + suite.Equal(http.StatusNotFound, code) + suite.Equal(errmsg.ErrorMsgNotFound, message) + }) + + suite.T().Run("Failure_Unauthorized", func(t *testing.T) { + responseRecord := CreateRequest("DELETE", url, "", nil) // No token provided + suite.Require().Equal(http.StatusUnauthorized, responseRecord.Code) + }) } diff --git a/delivery/http_server/end2end/benefactor_kindboxes_test.go b/delivery/http_server/end2end/benefactor_kindboxes_test.go index 020cb2c8..d37ca8cd 100644 --- a/delivery/http_server/end2end/benefactor_kindboxes_test.go +++ b/delivery/http_server/end2end/benefactor_kindboxes_test.go @@ -35,25 +35,6 @@ func (suite *BenefactorKindBoxTestSuite) SetupTest() { suite.kindBboxGetAllExpected = map[string]interface{}{ "count": 1, } - /* - "ID" : 1, - "KindBoxReqID" : 1, - "BenefactorID" : 1, - "KindBoxType" : "on-table", - "Amount" : 0, - "SerialNumber" : "serial-1", - "Status" : "delivered", - "DeliverReferTimeID" : 1, - "DeliverReferDate" : "2024-08-26T18:19:26Z", - "DeliverAddressID" : 1, - "SenderAgentID" : 1, - "DeliveredAt" : "2024-09-02T18:19:26Z", - "ReturnReferTimeID" : 0, - "ReturnReferDate" : "0001-01-01T00:00:00Z", - "ReturnAddressID" : 0, - "ReceiverAgentID" : 0, - "ReturnedAt" : "0001-01-01T00:00:00Z" - */ suite.kindBoxGetExpected = benefactorkindboxparam.KindBoxGetResponse{ KindBox: entity.KindBox{ ID: suite.kindBoxID, @@ -75,45 +56,75 @@ func (suite *BenefactorKindBoxTestSuite) SetupTest() { ReturnedAt: time.Time{}, }, } - } +// Test for GET /benefactor/kindboxes (Get All Kind Boxes) func (suite *BenefactorKindBoxTestSuite) TestBenefactorKindBoxGetAll() { - token := LoginBenefactor(suite.benefactorPhone) - url := fmt.Sprintf("/benefactor/kindboxes") - responseRecord := CreateRequest("GET", url, token, nil) - suite.Require().Equal(http.StatusOK, responseRecord.Code) + suite.Run("Success", func() { + token := LoginBenefactor(suite.benefactorPhone) + url := fmt.Sprintf("/benefactor/kindboxes") + responseRecord := CreateRequest("GET", url, token, nil) + suite.Require().Equal(http.StatusOK, responseRecord.Code) - var response benefactorkindboxparam.KindBoxGetAllResponse - err := json.NewDecoder(responseRecord.Body).Decode(&response) - suite.Require().NoError(err) - suite.Require().Equal(suite.kindBboxGetAllExpected["count"], len(response.AllKindBox)) + var response benefactorkindboxparam.KindBoxGetAllResponse + err := json.NewDecoder(responseRecord.Body).Decode(&response) + suite.Require().NoError(err, "could not decode response") + suite.Require().Equal(suite.kindBboxGetAllExpected["count"], len(response.AllKindBox)) + }) + suite.Run("Failure_Unauthorized", func() { + url := fmt.Sprintf("/benefactor/kindboxes") + responseRecord := CreateRequest("GET", url, "invalid_token", nil) + suite.Require().Equal(http.StatusUnauthorized, responseRecord.Code) + }) } +// Test for GET /benefactor/kindboxes/:id (Get Single Kind Box) func (suite *BenefactorKindBoxTestSuite) TestBenefactorKindBoxGet() { - token := LoginBenefactor(suite.benefactorPhone) - url := fmt.Sprintf("/benefactor/kindboxes/%d", suite.kindBoxID) - responseRecord := CreateRequest("GET", url, token, nil) - suite.Require().Equal(http.StatusOK, responseRecord.Code) + suite.Run("Success", func() { + token := LoginBenefactor(suite.benefactorPhone) + url := fmt.Sprintf("/benefactor/kindboxes/%d", suite.kindBoxID) + responseRecord := CreateRequest("GET", url, token, nil) + suite.Require().Equal(http.StatusOK, responseRecord.Code) - var response benefactorkindboxparam.KindBoxGetResponse - err := json.NewDecoder(responseRecord.Body).Decode(&response) - suite.Require().NoError(err) - suite.Require().Equal(suite.kindBoxGetExpected.KindBox.ID, response.KindBox.ID) - suite.Require().Equal(suite.kindBoxGetExpected.KindBox.KindBoxReqID, response.KindBox.KindBoxReqID) - suite.Require().Equal(suite.kindBoxGetExpected.KindBox.BenefactorID, response.KindBox.BenefactorID) - suite.Require().Equal(suite.kindBoxGetExpected.KindBox.KindBoxType, response.KindBox.KindBoxType) - suite.Require().Equal(suite.kindBoxGetExpected.KindBox.Amount, response.KindBox.Amount) - suite.Require().Equal(suite.kindBoxGetExpected.KindBox.SerialNumber, response.KindBox.SerialNumber) - suite.Require().Equal(suite.kindBoxGetExpected.KindBox.Status, response.KindBox.Status) - suite.Require().Equal(suite.kindBoxGetExpected.KindBox.DeliverReferTimeID, response.KindBox.DeliverReferTimeID) - suite.Require().Equal(suite.kindBoxGetExpected.KindBox.DeliverReferDate.Format("2006-01-02"), response.KindBox.DeliverReferDate.Format("2006-01-02")) - suite.Require().Equal(suite.kindBoxGetExpected.KindBox.DeliverAddressID, response.KindBox.DeliverAddressID) - suite.Require().Equal(suite.kindBoxGetExpected.KindBox.SenderAgentID, response.KindBox.SenderAgentID) - suite.Require().Equal(suite.kindBoxGetExpected.KindBox.DeliveredAt.Format("2006-01-02"), response.KindBox.DeliveredAt.Format("2006-01-02")) - suite.Require().Equal(suite.kindBoxGetExpected.KindBox.ReturnReferTimeID, response.KindBox.ReturnReferTimeID) - suite.Require().Equal(suite.kindBoxGetExpected.KindBox.ReturnReferDate.Format("2006-01-02"), response.KindBox.ReturnReferDate.Format("2006-01-02")) - suite.Require().Equal(suite.kindBoxGetExpected.KindBox.ReturnAddressID, response.KindBox.ReturnAddressID) + var response benefactorkindboxparam.KindBoxGetResponse + err := json.NewDecoder(responseRecord.Body).Decode(&response) + suite.Require().NoError(err, "could not decode response body") + suite.assertKindBoxFields(suite.kindBoxGetExpected.KindBox, response.KindBox) + }) + + suite.Run("Failure_NotFound", func() { + token := LoginBenefactor(suite.benefactorPhone) + url := fmt.Sprintf("/benefactor/kindboxes/%d", 9999) // Non-existent ID + responseRecord := CreateRequest("GET", url, token, nil) + suite.Require().Equal(http.StatusNotFound, responseRecord.Code) + }) + + suite.Run("Failure_Unauthorized", func() { + url := fmt.Sprintf("/benefactor/kindboxes/%d", suite.kindBoxID) + responseRecord := CreateRequest("GET", url, "invalid_token", nil) + suite.Require().Equal(http.StatusUnauthorized, responseRecord.Code) + }) +} + +// Helper method to assert all fields of KindBox +func (suite *BenefactorKindBoxTestSuite) assertKindBoxFields(expected, actual entity.KindBox) { + suite.Require().Equal(expected.ID, actual.ID, "ID should match") + suite.Require().Equal(expected.KindBoxReqID, actual.KindBoxReqID, "KindBoxReqID should match") + suite.Require().Equal(expected.BenefactorID, actual.BenefactorID, "BenefactorID should match") + suite.Require().Equal(expected.KindBoxType, actual.KindBoxType, "KindBoxType should match") + suite.Require().Equal(expected.Amount, actual.Amount, "Amount should match") + suite.Require().Equal(expected.SerialNumber, actual.SerialNumber, "SerialNumber should match") + suite.Require().Equal(expected.Status, actual.Status, "Status should match") + suite.Require().Equal(expected.DeliverReferTimeID, actual.DeliverReferTimeID, "DeliverReferTimeID should match") + suite.Require().Equal(expected.DeliverReferDate.Format("2006-01-02"), actual.DeliverReferDate.Format("2006-01-02"), "DeliverReferDate should match") + suite.Require().Equal(expected.DeliverAddressID, actual.DeliverAddressID, "DeliverAddressID should match") + suite.Require().Equal(expected.SenderAgentID, actual.SenderAgentID, "SenderAgentID should match") + suite.Require().Equal(expected.DeliveredAt.Format("2006-01-02"), actual.DeliveredAt.Format("2006-01-02"), "DeliveredAt should match") + suite.Require().Equal(expected.ReturnReferTimeID, actual.ReturnReferTimeID, "ReturnReferTimeID should match") + suite.Require().Equal(expected.ReturnReferDate.Format("2006-01-02"), actual.ReturnReferDate.Format("2006-01-02"), "ReturnReferDate should match") + suite.Require().Equal(expected.ReturnAddressID, actual.ReturnAddressID, "ReturnAddressID should match") + suite.Require().Equal(expected.ReceiverAgentID, actual.ReceiverAgentID, "ReceiverAgentID should match") + suite.Require().Equal(expected.ReturnedAt.Format("2006-01-02"), actual.ReturnedAt.Format("2006-01-02"), "ReturnedAt should match") } diff --git a/delivery/http_server/end2end/benefactor_kindboxreqs_test.go b/delivery/http_server/end2end/benefactor_kindboxreqs_test.go index 2ae839af..05635699 100644 --- a/delivery/http_server/end2end/benefactor_kindboxreqs_test.go +++ b/delivery/http_server/end2end/benefactor_kindboxreqs_test.go @@ -18,7 +18,6 @@ import ( "time" ) -// BenefactorKindBoxReqsTestSuite defines the suite for testing Benefactor Kind Box Requests type BenefactorKindBoxReqsTestSuite struct { suite.Suite benefactorPhone string @@ -30,12 +29,10 @@ type BenefactorKindBoxReqsTestSuite struct { updateData benefactorkindboxreqparam.KindBoxReqUpdateRequest } -// TestBenefactorKindBoxReqsTestSuite is the entry point for the test suite func TestBenefactorKindBoxReqsTestSuite(t *testing.T) { suite.Run(t, new(BenefactorKindBoxReqsTestSuite)) } -// SetupTest runs before each test in the suite func (suite *BenefactorKindBoxReqsTestSuite) SetupTest() { teardown := setup.SeedMariaDB(testContainer.GetMariaDBConfig()) suite.T().Cleanup(teardown) @@ -73,101 +70,143 @@ func (suite *BenefactorKindBoxReqsTestSuite) SetupTest() { } } -// TestBenefactorKindBoxReqs_GetAll_Success tests retrieving all kind box requests func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_GetAll_Success() { - token := LoginBenefactor(suite.benefactorPhone) - url := fmt.Sprintf("/benefactor/kindboxreqs/") - responseRecord := CreateRequest(http.MethodGet, url, token, nil) - suite.Require().Equal(http.StatusOK, responseRecord.Code) + suite.Run("Success", func() { + token := LoginBenefactor(suite.benefactorPhone) + url := fmt.Sprintf("/benefactor/kindboxreqs/") + responseRecord := CreateRequest(http.MethodGet, url, token, nil) + suite.Require().Equal(http.StatusOK, responseRecord.Code) - var response benefactorkindboxreqparam.GetAllResponse - err := json.NewDecoder(responseRecord.Body).Decode(&response) - suite.Require().NoError(err, "failed to decode response body") + var response benefactorkindboxreqparam.GetAllResponse + err := json.NewDecoder(responseRecord.Body).Decode(&response) + suite.Require().NoError(err, "failed to decode response body") - assert.Equal(suite.T(), suite.getAllExpected["count"], len(response.AllKindBoxReq)) + assert.Equal(suite.T(), suite.getAllExpected["count"], len(response.AllKindBoxReq)) + }) + + suite.Run("Failure_Unauthorized", func() { + url := fmt.Sprintf("/benefactor/kindboxreqs/") + responseRecord := CreateRequest(http.MethodGet, url, "invalid_token", nil) + suite.Require().Equal(http.StatusUnauthorized, responseRecord.Code) + }) } -// TestBenefactorKindBoxReqs_Get_Success tests retrieving a specific kind box request by ID func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Get_Success() { - token := LoginBenefactor(suite.benefactorPhone) - url := fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.kindBoxReqID) - responseRecord := CreateRequest(http.MethodGet, url, token, nil) - suite.Require().Equal(http.StatusOK, responseRecord.Code) + suite.Run("Success", func() { + token := LoginBenefactor(suite.benefactorPhone) + url := fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.kindBoxReqID) + responseRecord := CreateRequest(http.MethodGet, url, token, nil) + suite.Require().Equal(http.StatusOK, responseRecord.Code) - var response benefactorkindboxreqparam.KindBoxReqGetResponse - err := json.NewDecoder(responseRecord.Body).Decode(&response) - suite.Require().NoError(err, "failed to decode response body") + var response benefactorkindboxreqparam.KindBoxReqGetResponse + err := json.NewDecoder(responseRecord.Body).Decode(&response) + suite.Require().NoError(err, "failed to decode response body") - assert.Equal(suite.T(), suite.kindBoxReqID, response.KindBoxReq.ID) - assert.Equal(suite.T(), suite.getExpected["kind_box_type"], response.KindBoxReq.KindBoxType) - assert.Equal(suite.T(), suite.getExpected["deliver_address"], response.KindBoxReq.DeliverAddressID) - assert.Equal( - suite.T(), - suite.getExpected["deliver_refer_date"].(time.Time).Format("2006-01-02"), - response.KindBoxReq.DeliverReferDate.Format("2006-01-02"), - ) - assert.Equal(suite.T(), suite.getExpected["deliver_refer_time"], response.KindBoxReq.DeliverReferTimeID) + assert.Equal(suite.T(), suite.kindBoxReqID, response.KindBoxReq.ID) + assert.Equal(suite.T(), suite.getExpected["kind_box_type"], response.KindBoxReq.KindBoxType) + assert.Equal(suite.T(), suite.getExpected["deliver_address"], response.KindBoxReq.DeliverAddressID) + assert.Equal( + suite.T(), + suite.getExpected["deliver_refer_date"].(time.Time).Format("2006-01-02"), + response.KindBoxReq.DeliverReferDate.Format("2006-01-02"), + ) + assert.Equal(suite.T(), suite.getExpected["deliver_refer_time"], response.KindBoxReq.DeliverReferTimeID) + }) + + suite.Run("Failure_NotFound", func() { + token := LoginBenefactor(suite.benefactorPhone) + url := fmt.Sprintf("/benefactor/kindboxreqs/%d", 9999) // Non-existent ID + responseRecord := CreateRequest(http.MethodGet, url, token, nil) + suite.Require().Equal(http.StatusNotFound, responseRecord.Code) + }) + + suite.Run("Failure_Unauthorized", func() { + url := fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.kindBoxReqID) + responseRecord := CreateRequest(http.MethodGet, url, "invalid_token", nil) + suite.Require().Equal(http.StatusUnauthorized, responseRecord.Code) + }) } -// TestBenefactorKindBoxReqs_Create_Success tests creating a kind box request func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Create_Success() { - token := LoginBenefactor(suite.benefactorPhone) - url := fmt.Sprintf("/benefactor/kindboxreqs/") - rec := CreateRequest(http.MethodPost, url, token, suite.createData) - suite.Require().Equal(http.StatusCreated, rec.Code) + suite.Run("Success", func() { + token := LoginBenefactor(suite.benefactorPhone) + url := fmt.Sprintf("/benefactor/kindboxreqs/") + rec := CreateRequest(http.MethodPost, url, token, suite.createData) + suite.Require().Equal(http.StatusCreated, rec.Code) - var response benefactorkindboxreqparam.KindBoxReqAddResponse - err := json.NewDecoder(rec.Body).Decode(&response) - suite.Require().NoError(err, "failed to decode response body") + var response benefactorkindboxreqparam.KindBoxReqAddResponse + err := json.NewDecoder(rec.Body).Decode(&response) + suite.Require().NoError(err, "failed to decode response body") - assert.Equal(suite.T(), suite.createData.KindBoxType, response.KindBoxReq.KindBoxType) - assert.Equal(suite.T(), suite.createData.DeliverAddressID, response.KindBoxReq.DeliverAddressID) - assert.Equal(suite.T(), suite.createData.DeliverReferDate, response.KindBoxReq.DeliverReferDate) - assert.Equal(suite.T(), suite.createData.CountRequested, response.KindBoxReq.CountRequested) + assert.Equal(suite.T(), suite.createData.KindBoxType, response.KindBoxReq.KindBoxType) + assert.Equal(suite.T(), suite.createData.DeliverAddressID, response.KindBoxReq.DeliverAddressID) + assert.Equal(suite.T(), suite.createData.DeliverReferDate, response.KindBoxReq.DeliverReferDate) + assert.Equal(suite.T(), suite.createData.CountRequested, response.KindBoxReq.CountRequested) + }) + + suite.Run("Failure_Unauthorized", func() { + url := fmt.Sprintf("/benefactor/kindboxreqs/") + rec := CreateRequest(http.MethodPost, url, "invalid_token", suite.createData) + suite.Require().Equal(http.StatusUnauthorized, rec.Code) + }) } -// TestBenefactorKindBoxReqs_Update_Success tests updating a kind box request func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Update_Success() { - token := LoginBenefactor(suite.benefactorPhone) - url := fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.kindBoxReqID) - rec := CreateRequest(http.MethodPut, url, token, suite.updateData) - suite.Require().Equal(http.StatusNoContent, rec.Code) + suite.Run("Success", func() { + token := LoginBenefactor(suite.benefactorPhone) + url := fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.kindBoxReqID) + rec := CreateRequest(http.MethodPut, url, token, suite.updateData) + suite.Require().Equal(http.StatusNoContent, rec.Code) - kindBoxReq, err := services.BenefactorKindBoxReqSvc.Get(context.Background(), - benefactorkindboxreqparam.KindBoxReqGetRequest{ - BenefactorID: suite.benefactorID, - KindBoxReqID: suite.kindBoxReqID, - }, - ) - suite.Require().NoError(err, "failed to get kind box request") + kindBoxReq, err := services.BenefactorKindBoxReqSvc.Get(context.Background(), + benefactorkindboxreqparam.KindBoxReqGetRequest{ + BenefactorID: suite.benefactorID, + KindBoxReqID: suite.kindBoxReqID, + }, + ) + suite.Require().NoError(err, "failed to get kind box request") - assert.Equal(suite.T(), suite.updateData.KindBoxType, kindBoxReq.KindBoxType) - assert.Equal(suite.T(), suite.updateData.CountRequested, kindBoxReq.CountRequested) - assert.Equal(suite.T(), suite.updateData.Description, kindBoxReq.Description) - assert.Equal(suite.T(), suite.updateData.DeliverReferTimeID, kindBoxReq.DeliverReferTimeID) - assert.Equal( - suite.T(), - suite.updateData.DeliverReferDate.Format("2006-01-02"), - kindBoxReq.DeliverReferDate.Format("2006-01-02"), - ) - assert.Equal(suite.T(), suite.updateData.DeliverAddressID, kindBoxReq.DeliverAddressID) + assert.Equal(suite.T(), suite.updateData.KindBoxType, kindBoxReq.KindBoxType) + assert.Equal(suite.T(), suite.updateData.CountRequested, kindBoxReq.CountRequested) + assert.Equal(suite.T(), suite.updateData.Description, kindBoxReq.Description) + assert.Equal(suite.T(), suite.updateData.DeliverReferTimeID, kindBoxReq.DeliverReferTimeID) + assert.Equal( + suite.T(), + suite.updateData.DeliverReferDate.Format("2006-01-02"), + kindBoxReq.DeliverReferDate.Format("2006-01-02"), + ) + assert.Equal(suite.T(), suite.updateData.DeliverAddressID, kindBoxReq.DeliverAddressID) + }) + + suite.Run("Failure_Unauthorized", func() { + url := fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.kindBoxReqID) + rec := CreateRequest(http.MethodPut, url, "invalid_token", suite.updateData) + suite.Require().Equal(http.StatusUnauthorized, rec.Code) + }) } -// TestBenefactorKindBoxReqs_Delete_Success tests deleting a kind box request func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Delete_Success() { - token := LoginBenefactor(suite.benefactorPhone) - url := fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.kindBoxReqID) - rec := CreateRequest(http.MethodDelete, url, token, nil) - suite.Require().Equal(http.StatusOK, rec.Code) + suite.Run("Success", func() { + token := LoginBenefactor(suite.benefactorPhone) + url := fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.kindBoxReqID) + rec := CreateRequest(http.MethodDelete, url, token, nil) + suite.Require().Equal(http.StatusOK, rec.Code) - _, err := services.BenefactorKindBoxReqSvc.Get(context.Background(), - benefactorkindboxreqparam.KindBoxReqGetRequest{ - BenefactorID: suite.benefactorID, - KindBoxReqID: suite.kindBoxReqID, - }, - ) - message, code := httpmsg.Error(err) - suite.Require().Error(err) - assert.Equal(suite.T(), http.StatusNotFound, code) - assert.Equal(suite.T(), errmsg.ErrorMsgNotFound, message) + _, err := services.BenefactorKindBoxReqSvc.Get(context.Background(), + benefactorkindboxreqparam.KindBoxReqGetRequest{ + BenefactorID: suite.benefactorID, + KindBoxReqID: suite.kindBoxReqID, + }, + ) + message, code := httpmsg.Error(err) + suite.Require().Error(err) + assert.Equal(suite.T(), http.StatusNotFound, code) + assert.Equal(suite.T(), errmsg.ErrorMsgNotFound, message) + }) + + suite.Run("Failure_Unauthorized", func() { + url := fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.kindBoxReqID) + rec := CreateRequest(http.MethodDelete, url, "invalid_token", nil) + suite.Require().Equal(http.StatusUnauthorized, rec.Code) + }) } From 9458e4fa2ee04cab1acd0aeee8811285cc619354 Mon Sep 17 00:00:00 2001 From: Reza Mobaraki Date: Wed, 2 Oct 2024 01:21:32 +0330 Subject: [PATCH 19/22] test(end2end): fix Signed-off-by: Reza Mobaraki --- delivery/http_server/end2end/benefactor_address_test.go | 2 +- delivery/http_server/end2end/benefactor_kindboxes_test.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/delivery/http_server/end2end/benefactor_address_test.go b/delivery/http_server/end2end/benefactor_address_test.go index f685977a..f953c8ea 100644 --- a/delivery/http_server/end2end/benefactor_address_test.go +++ b/delivery/http_server/end2end/benefactor_address_test.go @@ -143,7 +143,7 @@ func (suite *BenefactorAddressTestSuit) TestBenefactorAddressCreate() { suite.T().Run("Failure_BadRequest", func(t *testing.T) { responseRecord := CreateRequest("POST", url, token, nil) // No data provided - suite.Require().Equal(http.StatusBadRequest, responseRecord.Code) + suite.Require().Equal(http.StatusUnprocessableEntity, responseRecord.Code) }) } diff --git a/delivery/http_server/end2end/benefactor_kindboxes_test.go b/delivery/http_server/end2end/benefactor_kindboxes_test.go index d37ca8cd..c05d9c1c 100644 --- a/delivery/http_server/end2end/benefactor_kindboxes_test.go +++ b/delivery/http_server/end2end/benefactor_kindboxes_test.go @@ -98,7 +98,7 @@ func (suite *BenefactorKindBoxTestSuite) TestBenefactorKindBoxGet() { token := LoginBenefactor(suite.benefactorPhone) url := fmt.Sprintf("/benefactor/kindboxes/%d", 9999) // Non-existent ID responseRecord := CreateRequest("GET", url, token, nil) - suite.Require().Equal(http.StatusNotFound, responseRecord.Code) + suite.Require().Equal(http.StatusUnprocessableEntity, responseRecord.Code) }) suite.Run("Failure_Unauthorized", func() { From 6f6643552db82b1615be994e61af9534f652a5cd Mon Sep 17 00:00:00 2001 From: Hamed Xamani Date: Sun, 6 Oct 2024 17:21:14 +0330 Subject: [PATCH 20/22] fix(delivery): remove unused filter from delivery to service layer (#165) --- .../agent/kind_box/get_all_return_awaiting.go | 4 ++-- .../agent/kind_box_req/get_all_delivery_awaiting.go | 6 ++++-- delivery/http_server/benefactor/kind_box/get_all.go | 4 ++-- .../http_server/benefactor/kind_box_req/get_all.go | 3 +-- docs/docs.go | 12 ------------ docs/swagger.json | 12 ------------ docs/swagger.yaml | 8 -------- param/agent/kind_box/get_all_return_awaiting.go | 9 ++++++--- .../agent/kind_box_req/get_all_delivery_awaiting.go | 9 ++++++--- param/benefactor/kind_box/get_all.go | 7 ++++--- param/benefactor/kind_box_req/get_all.go | 7 ++++--- service/agent/kind_box/get_all_return_awaiting.go | 3 +++ .../agent/kind_box_req/get_all_delivery_awaiting.go | 2 ++ service/benefactor/kind_box/get_all.go | 1 + service/benefactor/kind_box_req/get_all.go | 1 + validator/agent/kind_box/get_all_return_awaiting.go | 1 - .../agent/kind_box_req/get_all_delivery_awaiting.go | 1 - validator/benefactor/kind_box/get_all.go | 1 - validator/benefactor/kind_box_req/get_all.go | 1 - 19 files changed, 36 insertions(+), 56 deletions(-) diff --git a/delivery/http_server/agent/kind_box/get_all_return_awaiting.go b/delivery/http_server/agent/kind_box/get_all_return_awaiting.go index 7e29b5ef..3979ed7a 100644 --- a/delivery/http_server/agent/kind_box/get_all_return_awaiting.go +++ b/delivery/http_server/agent/kind_box/get_all_return_awaiting.go @@ -44,8 +44,8 @@ func (h Handler) GetAll(c echo.Context) error { } req.Filter = queryparam.GetFilterParams(c) - req.Filter["receiver_agent_id"] = claim.GetClaimsFromEchoContext(c).UserID - req.Filter["status"] = entity.KindBoxAssignedReceiverAgentStatus + req.ReceiverAgentId = claim.GetClaimsFromEchoContext(c).UserID + req.Status = entity.KindBoxAssignedReceiverAgentStatus resp, err := h.agentKindBoxSvc.GetAll(c.Request().Context(), req) if err != nil { diff --git a/delivery/http_server/agent/kind_box_req/get_all_delivery_awaiting.go b/delivery/http_server/agent/kind_box_req/get_all_delivery_awaiting.go index d1d390dd..4665f580 100644 --- a/delivery/http_server/agent/kind_box_req/get_all_delivery_awaiting.go +++ b/delivery/http_server/agent/kind_box_req/get_all_delivery_awaiting.go @@ -40,8 +40,10 @@ func (h Handler) GetAllAwaitingDelivery(c echo.Context) error { return echo.NewHTTPError(http.StatusBadRequest) } req.Filter = queryparam.GetFilterParams(c) - req.Filter["sender_agent_id"] = claim.GetClaimsFromEchoContext(c).UserID - req.Filter["status"] = entity.KindBoxReqAssignedSenderAgentStatus + + req.SenderAgentId = claim.GetClaimsFromEchoContext(c).UserID + req.Status = entity.KindBoxReqAssignedSenderAgentStatus + resp, sErr := h.agentKindBoxReqSvc.GetAllAwaitingDelivery(c.Request().Context(), req) if sErr != nil { msg, code := httpmsg.Error(sErr) diff --git a/delivery/http_server/benefactor/kind_box/get_all.go b/delivery/http_server/benefactor/kind_box/get_all.go index cd99fa8e..bdab2e76 100644 --- a/delivery/http_server/benefactor/kind_box/get_all.go +++ b/delivery/http_server/benefactor/kind_box/get_all.go @@ -18,7 +18,6 @@ import ( // @Produce json // @Param filter_id query int false "Filter by ID" // @Param filter_kind_box_req_id query int false "Filter by KindBox request ID" -// @Param filter_benefactor_id query int false "Filter by benefactor ID" // @Param filter_kind_box_type query string false "Filter by KindBox type" Enums(on-table,cylindrical,stand-up) // @Param filter_amount query int false "Filter by amount" // @Param filter_serial_number query string false "Filter by serial number" @@ -49,7 +48,8 @@ func (h Handler) GetAll(c echo.Context) error { } req.Filter = queryparam.GetFilterParams(c) - req.Filter["benefactor_id"] = claim.GetClaimsFromEchoContext(c).UserID + req.BenefactorId = claim.GetClaimsFromEchoContext(c).UserID + resp, sErr := h.benefactorKindBoxSvc.GetAll(c.Request().Context(), req) if sErr != nil { msg, code := httpmsg.Error(sErr) diff --git a/delivery/http_server/benefactor/kind_box_req/get_all.go b/delivery/http_server/benefactor/kind_box_req/get_all.go index 71f51489..93c2e823 100644 --- a/delivery/http_server/benefactor/kind_box_req/get_all.go +++ b/delivery/http_server/benefactor/kind_box_req/get_all.go @@ -17,7 +17,6 @@ import ( // @Accept json // @Produce json // @Param filter_id query int false "Filter by ID" -// @Param filter_benefactor_id query int false "Filter by benefactor ID" // @Param filter_kind_box_type query entity.KindBoxType false "Filter by KindBox type" Format(enum) // @Param filter_status query string false "Filter by KindBoxReq Status" Enums(pending,accepted,assigned-sender-agent,rejected,delivered) // @Param filter_count_requested query int false "Filter by count requested" @@ -41,7 +40,7 @@ func (h Handler) GetAll(c echo.Context) error { } req.Filter = queryparam.GetFilterParams(c) - req.Filter["benefactor_id"] = claim.GetClaimsFromEchoContext(c).UserID + req.BenefactorId = claim.GetClaimsFromEchoContext(c).UserID resp, sErr := h.benefactorKindBoxReqSvc.GetAll(c.Request().Context(), req) if sErr != nil { diff --git a/docs/docs.go b/docs/docs.go index 00127322..dfd882f6 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -1897,12 +1897,6 @@ const docTemplate = `{ "name": "filter_kind_box_req_id", "in": "query" }, - { - "type": "integer", - "description": "Filter by benefactor ID", - "name": "filter_benefactor_id", - "in": "query" - }, { "enum": [ "on-table", @@ -2186,12 +2180,6 @@ const docTemplate = `{ "name": "filter_id", "in": "query" }, - { - "type": "integer", - "description": "Filter by benefactor ID", - "name": "filter_benefactor_id", - "in": "query" - }, { "enum": [ "on-table", diff --git a/docs/swagger.json b/docs/swagger.json index 8bf8d363..7d84a94e 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -1886,12 +1886,6 @@ "name": "filter_kind_box_req_id", "in": "query" }, - { - "type": "integer", - "description": "Filter by benefactor ID", - "name": "filter_benefactor_id", - "in": "query" - }, { "enum": [ "on-table", @@ -2175,12 +2169,6 @@ "name": "filter_id", "in": "query" }, - { - "type": "integer", - "description": "Filter by benefactor ID", - "name": "filter_benefactor_id", - "in": "query" - }, { "enum": [ "on-table", diff --git a/docs/swagger.yaml b/docs/swagger.yaml index ec1637fb..26600f18 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -2190,10 +2190,6 @@ paths: in: query name: filter_kind_box_req_id type: integer - - description: Filter by benefactor ID - in: query - name: filter_benefactor_id - type: integer - description: Filter by KindBox type enum: - on-table @@ -2388,10 +2384,6 @@ paths: in: query name: filter_id type: integer - - description: Filter by benefactor ID - in: query - name: filter_benefactor_id - type: integer - description: Filter by KindBox type enum: - on-table diff --git a/param/agent/kind_box/get_all_return_awaiting.go b/param/agent/kind_box/get_all_return_awaiting.go index cc91b1d9..a6d780fd 100644 --- a/param/agent/kind_box/get_all_return_awaiting.go +++ b/param/agent/kind_box/get_all_return_awaiting.go @@ -1,13 +1,16 @@ package agentkindboxparam import ( + "git.gocasts.ir/ebhomengo/niki/entity" "git.gocasts.ir/ebhomengo/niki/param" ) type GetAllRequest struct { - Pagination param.PaginationRequest - Sort param.SortRequest - Filter param.FilterRequest + Pagination param.PaginationRequest + Sort param.SortRequest + Filter param.FilterRequest + ReceiverAgentId uint + Status entity.KindBoxStatus } type GetAllResponse struct { diff --git a/param/agent/kind_box_req/get_all_delivery_awaiting.go b/param/agent/kind_box_req/get_all_delivery_awaiting.go index 2634e7de..c10b1a7c 100644 --- a/param/agent/kind_box_req/get_all_delivery_awaiting.go +++ b/param/agent/kind_box_req/get_all_delivery_awaiting.go @@ -1,13 +1,16 @@ package agentkindboxreqparam import ( + "git.gocasts.ir/ebhomengo/niki/entity" "git.gocasts.ir/ebhomengo/niki/param" ) type DeliveryAwaitingGetAllRequest struct { - Pagination param.PaginationRequest - Sort param.SortRequest - Filter param.FilterRequest + Pagination param.PaginationRequest + Sort param.SortRequest + Filter param.FilterRequest + SenderAgentId uint + Status entity.KindBoxReqStatus } type DeliveryAwaitingGetAllResponse struct { diff --git a/param/benefactor/kind_box/get_all.go b/param/benefactor/kind_box/get_all.go index 54b5ae7d..fce92220 100644 --- a/param/benefactor/kind_box/get_all.go +++ b/param/benefactor/kind_box/get_all.go @@ -5,9 +5,10 @@ import ( ) type KindBoxGetAllRequest struct { - Pagination param.PaginationRequest - Sort param.SortRequest - Filter param.FilterRequest + Pagination param.PaginationRequest + Sort param.SortRequest + Filter param.FilterRequest + BenefactorId uint } type KindBoxGetAllResponse struct { diff --git a/param/benefactor/kind_box_req/get_all.go b/param/benefactor/kind_box_req/get_all.go index b99bb821..969d8859 100644 --- a/param/benefactor/kind_box_req/get_all.go +++ b/param/benefactor/kind_box_req/get_all.go @@ -5,9 +5,10 @@ import ( ) type GetAllRequest struct { - Pagination param.PaginationRequest - Sort param.SortRequest - Filter param.FilterRequest + Pagination param.PaginationRequest + Sort param.SortRequest + Filter param.FilterRequest + BenefactorId uint } type GetAllResponse struct { diff --git a/service/agent/kind_box/get_all_return_awaiting.go b/service/agent/kind_box/get_all_return_awaiting.go index 6f1a94de..e8bbc491 100644 --- a/service/agent/kind_box/get_all_return_awaiting.go +++ b/service/agent/kind_box/get_all_return_awaiting.go @@ -17,6 +17,9 @@ func (s Service) GetAll(ctx context.Context, req param.GetAllRequest) (param.Get req.Pagination.GetPageSize() req.Pagination.GetPageNumber() + req.Filter["receiver_agent_id"] = req.ReceiverAgentId + req.Filter["status"] = req.Status + allKindBoxes, total, err := s.repo.GetAllKindBox(ctx, req.Filter, req.Pagination, req.Sort) if err != nil { return param.GetAllResponse{}, richerror.New(op).WithErr(err) diff --git a/service/agent/kind_box_req/get_all_delivery_awaiting.go b/service/agent/kind_box_req/get_all_delivery_awaiting.go index 5664f1a0..12589bc2 100644 --- a/service/agent/kind_box_req/get_all_delivery_awaiting.go +++ b/service/agent/kind_box_req/get_all_delivery_awaiting.go @@ -17,6 +17,8 @@ func (s Service) GetAllAwaitingDelivery(ctx context.Context, req param.DeliveryA req.Pagination.GetPageSize() req.Pagination.GetPageNumber() + req.Filter["sender_agent_id"] = req.SenderAgentId + req.Filter["status"] = req.Status allAwaitingKindBoxReq, total, err := s.repo.GetAllKindBoxReq(ctx, req.Filter, req.Pagination, req.Sort) if err != nil { diff --git a/service/benefactor/kind_box/get_all.go b/service/benefactor/kind_box/get_all.go index 271df2dd..8fa615b2 100644 --- a/service/benefactor/kind_box/get_all.go +++ b/service/benefactor/kind_box/get_all.go @@ -14,6 +14,7 @@ func (s Service) GetAll(ctx context.Context, req param.KindBoxGetAllRequest) (pa return param.KindBoxGetAllResponse{FieldErrors: fieldErrors}, richerror.New(op).WithErr(vErr) } + req.Filter["benefactor_id"] = req.BenefactorId req.Pagination.GetPageSize() req.Pagination.GetPageNumber() diff --git a/service/benefactor/kind_box_req/get_all.go b/service/benefactor/kind_box_req/get_all.go index dfe5bb10..8398a367 100644 --- a/service/benefactor/kind_box_req/get_all.go +++ b/service/benefactor/kind_box_req/get_all.go @@ -14,6 +14,7 @@ func (s Service) GetAll(ctx context.Context, req param.GetAllRequest) (param.Get return param.GetAllResponse{FieldErrors: fieldErrors}, richerror.New(op).WithErr(vErr) } + req.Filter["benefactor_id"] = req.BenefactorId req.Pagination.GetPageSize() req.Pagination.GetPageNumber() diff --git a/validator/agent/kind_box/get_all_return_awaiting.go b/validator/agent/kind_box/get_all_return_awaiting.go index 1bc92408..9df2e17d 100644 --- a/validator/agent/kind_box/get_all_return_awaiting.go +++ b/validator/agent/kind_box/get_all_return_awaiting.go @@ -13,7 +13,6 @@ func (v Validator) ValidateGetAll(req param.GetAllRequest) (map[string]string, e const op = "agentkindboxvalidator.ValidateGetAll" validFields := []string{ "id", "kind_box_req_id", - "receiver_agent_id", "status", "benefactor_id", "type", "serial_number", "return_refer_time_id", "return_refer_date", "return_address_id", } diff --git a/validator/agent/kind_box_req/get_all_delivery_awaiting.go b/validator/agent/kind_box_req/get_all_delivery_awaiting.go index b37e1044..552c33e6 100644 --- a/validator/agent/kind_box_req/get_all_delivery_awaiting.go +++ b/validator/agent/kind_box_req/get_all_delivery_awaiting.go @@ -12,7 +12,6 @@ func (v Validator) ValidateGetAllAwaitingDelivery(req kbrparam.DeliveryAwaitingG const op = "adminkindboxreqvalidator.ValidateGetAllAwaitingDelivery" validFields := []string{ "id", "benefactor_id", "kind_box_type", - "sender_agent_id", "status", "count_requested", "count_accepted", "deliver_refer_time_id", "deliver_refer_date", "deliver_address_id", } diff --git a/validator/benefactor/kind_box/get_all.go b/validator/benefactor/kind_box/get_all.go index 290cc564..39e3b49d 100644 --- a/validator/benefactor/kind_box/get_all.go +++ b/validator/benefactor/kind_box/get_all.go @@ -14,7 +14,6 @@ func (v Validator) ValidateGetAll(req param.KindBoxGetAllRequest) (map[string]st validFields := []string{ "id", "kind_box_req_id", "kind_box_type", "amount", "serial_number", - "benefactor_id", "status", "deliver_refer_time_id", "deliver_refer_date", "deliver_address_id", "sender_agent_id", "delivered_at", "return_refer_time_id", "return_refer_date", "return_address_id", "receiver_agent_id", "returned_at", diff --git a/validator/benefactor/kind_box_req/get_all.go b/validator/benefactor/kind_box_req/get_all.go index eee931e4..7965fc35 100644 --- a/validator/benefactor/kind_box_req/get_all.go +++ b/validator/benefactor/kind_box_req/get_all.go @@ -13,7 +13,6 @@ func (v Validator) ValidateGetAll(req param.GetAllRequest) (map[string]string, e const op = "benefactorkindboxreqvalidator.ValidateGetAllAwaitingDelivery" validFields := []string{ "id", "kind_box_type", "status", "sender_agent_id", - "benefactor_id", "count_requested", "count_accepted", "deliver_refer_time_id", "deliver_refer_date", "deliver_address_id", } From 606650e32b29690938f8437243df746d33554d42 Mon Sep 17 00:00:00 2001 From: Reza Mobaraki Date: Tue, 8 Oct 2024 21:33:04 +0330 Subject: [PATCH 21/22] test(end2end): update tests, remove mock data Signed-off-by: Reza Mobaraki --- .../end2end/benefactor_address_test.go | 68 +++++++---------- .../end2end/benefactor_kindboxes_test.go | 76 ++++++------------- .../end2end/benefactor_kindboxreqs_test.go | 72 ++++++++---------- 3 files changed, 86 insertions(+), 130 deletions(-) diff --git a/delivery/http_server/end2end/benefactor_address_test.go b/delivery/http_server/end2end/benefactor_address_test.go index f953c8ea..1f6cb3ff 100644 --- a/delivery/http_server/end2end/benefactor_address_test.go +++ b/delivery/http_server/end2end/benefactor_address_test.go @@ -7,7 +7,6 @@ import ( "encoding/json" "fmt" "git.gocasts.ir/ebhomengo/niki/delivery/http_server/end2end/setup" - "git.gocasts.ir/ebhomengo/niki/entity" addressparam "git.gocasts.ir/ebhomengo/niki/param/benefactor/address" errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg" @@ -42,18 +41,7 @@ func (suite *BenefactorAddressTestSuit) SetupTest() { suite.getAllExpected = map[string]interface{}{ "count": 1, } - suite.getExpected = addressparam.GetAddressResponse{ - Address: entity.Address{ - ID: suite.addressID, - PostalCode: "3719655861", - Address: "tehran sare koche 1", - Lat: 35.632508, - Lon: 51.452859, - Name: "home1", - CityID: 8, - BenefactorID: suite.benefactorID, - }, - } + suite.createData = addressparam.BenefactorAddAddressRequest{ PostalCode: "3719655861", Address: "create shiraz kaf sharo", @@ -72,10 +60,9 @@ func (suite *BenefactorAddressTestSuit) SetupTest() { } } -// TestBenefactorAddressGet tests the GET /address/:id endpoint func (suite *BenefactorAddressTestSuit) TestBenefactorAddressGet() { token := LoginBenefactor(suite.benefactorPhone) - url := fmt.Sprintf("/address/%d", suite.addressID) + url := fmt.Sprintf("/benefactors/addresses/%d", suite.addressID) suite.T().Run("Success", func(t *testing.T) { responseRecord := CreateRequest("GET", url, token, nil) @@ -84,13 +71,17 @@ func (suite *BenefactorAddressTestSuit) TestBenefactorAddressGet() { var response addressparam.GetAddressResponse err := json.NewDecoder(responseRecord.Body).Decode(&response) suite.Require().NoError(err, "could not decode response body") + address, sErr := services.BenefactorAddressSvc.Get(context.Background(), + addressparam.GetAddressRequest{ + AddressID: suite.addressID, + BenefactorID: suite.benefactorID, + }) - suite.Require().Equal(suite.addressID, response.Address.ID) - suite.Require().Equal(suite.benefactorID, response.Address.BenefactorID) - suite.Require().Equal(suite.getExpected.Address.PostalCode, response.Address.PostalCode) - suite.Require().Equal(suite.getExpected.Address.Address, response.Address.Address) - suite.Require().Equal(suite.getExpected.Address.Name, response.Address.Name) - suite.Require().Equal(suite.getExpected.Address.CityID, response.Address.CityID) + suite.Require().NoError(sErr, "failed to get benefactor address") + suite.Require().Equal(address.Data.PostalCode, response.Data.PostalCode) + suite.Require().Equal(address.Data.Address, response.Data.Address) + suite.Require().Equal(address.Data.Name, response.Data.Name) + suite.Require().Equal(address.Data.CityID, response.Data.CityID) }) suite.T().Run("Failure_Unauthorized", func(t *testing.T) { @@ -99,10 +90,9 @@ func (suite *BenefactorAddressTestSuit) TestBenefactorAddressGet() { }) } -// TestBenefactorAddressGetAll tests the GET /address/ endpoint func (suite *BenefactorAddressTestSuit) TestBenefactorAddressGetAll() { token := LoginBenefactor(suite.benefactorPhone) - url := fmt.Sprintf("/address/") + url := fmt.Sprintf("/benefactors/addresses") suite.T().Run("Success", func(t *testing.T) { responseRecord := CreateRequest("GET", url, token, nil) @@ -112,7 +102,7 @@ func (suite *BenefactorAddressTestSuit) TestBenefactorAddressGetAll() { err := json.NewDecoder(responseRecord.Body).Decode(&response) suite.Require().NoError(err, "could not decode response body") - suite.Require().Equal(suite.getAllExpected["count"], len(response.AllAddresses)) + suite.Require().Equal(suite.getAllExpected["count"], len(response.Data)) }) suite.T().Run("Failure_Unauthorized", func(t *testing.T) { @@ -121,10 +111,9 @@ func (suite *BenefactorAddressTestSuit) TestBenefactorAddressGetAll() { }) } -// TestBenefactorAddressCreate tests the POST /address/ endpoint func (suite *BenefactorAddressTestSuit) TestBenefactorAddressCreate() { token := LoginBenefactor(suite.benefactorPhone) - url := fmt.Sprintf("/address/") + url := fmt.Sprintf("/benefactors/addresses") suite.T().Run("Success", func(t *testing.T) { responseRecord := CreateRequest("POST", url, token, suite.createData) @@ -134,11 +123,11 @@ func (suite *BenefactorAddressTestSuit) TestBenefactorAddressCreate() { err := json.NewDecoder(responseRecord.Body).Decode(&response) suite.Require().NoError(err, "could not decode response body") - suite.Require().Equal(suite.benefactorID, response.Address.BenefactorID) - suite.Require().Equal(suite.createData.Address, response.Address.Address) - suite.Require().Equal(suite.createData.PostalCode, response.Address.PostalCode) - suite.Require().Equal(suite.createData.Name, response.Address.Name) - suite.Require().Equal(suite.createData.CityID, response.Address.CityID) + suite.Require().Equal(suite.benefactorID, response.Data.BenefactorID) + suite.Require().Equal(suite.createData.Address, response.Data.Address) + suite.Require().Equal(suite.createData.PostalCode, response.Data.PostalCode) + suite.Require().Equal(suite.createData.Name, response.Data.Name) + suite.Require().Equal(suite.createData.CityID, response.Data.CityID) }) suite.T().Run("Failure_BadRequest", func(t *testing.T) { @@ -147,13 +136,12 @@ func (suite *BenefactorAddressTestSuit) TestBenefactorAddressCreate() { }) } -// TestBenefactorAddressUpdate tests the PATCH /address/:id endpoint func (suite *BenefactorAddressTestSuit) TestBenefactorAddressUpdate() { token := LoginBenefactor(suite.benefactorPhone) - url := fmt.Sprintf("/address/%d", suite.addressID) + url := fmt.Sprintf("/benefactors/addresses/%d", suite.addressID) suite.T().Run("Success", func(t *testing.T) { - responseRecord := CreateRequest("PATCH", url, token, suite.updateData) + responseRecord := CreateRequest("PUT", url, token, suite.updateData) suite.Require().Equal(http.StatusNoContent, responseRecord.Code) updatedAddress, sErr := services.BenefactorAddressSvc.Get(context.Background(), @@ -163,14 +151,14 @@ func (suite *BenefactorAddressTestSuit) TestBenefactorAddressUpdate() { }) suite.Require().NoError(sErr, "failed to get benefactor address") - suite.Require().Equal(suite.updateData.PostalCode, updatedAddress.Address.PostalCode) - suite.Require().Equal(suite.updateData.Address, updatedAddress.Address.Address) - suite.Require().Equal(suite.updateData.Name, updatedAddress.Address.Name) - suite.Require().Equal(suite.updateData.CityID, updatedAddress.Address.CityID) + suite.Require().Equal(suite.updateData.PostalCode, updatedAddress.Data.PostalCode) + suite.Require().Equal(suite.updateData.Address, updatedAddress.Data.Address) + suite.Require().Equal(suite.updateData.Name, updatedAddress.Data.Name) + suite.Require().Equal(suite.updateData.CityID, updatedAddress.Data.CityID) }) suite.T().Run("Failure_Unauthorized", func(t *testing.T) { - responseRecord := CreateRequest("PATCH", url, "", suite.updateData) // No token provided + responseRecord := CreateRequest("PUT", url, "", suite.updateData) // No token provided suite.Require().Equal(http.StatusUnauthorized, responseRecord.Code) }) } @@ -178,7 +166,7 @@ func (suite *BenefactorAddressTestSuit) TestBenefactorAddressUpdate() { // TestBenefactorAddressDelete tests the DELETE /address/:id endpoint func (suite *BenefactorAddressTestSuit) TestBenefactorAddressDelete() { token := LoginBenefactor(suite.benefactorPhone) - url := fmt.Sprintf("/address/%d", suite.addressID) + url := fmt.Sprintf("/benefactors/addresses/%d", suite.addressID) suite.T().Run("Success", func(t *testing.T) { responseRecord := CreateRequest("DELETE", url, token, nil) diff --git a/delivery/http_server/end2end/benefactor_kindboxes_test.go b/delivery/http_server/end2end/benefactor_kindboxes_test.go index c05d9c1c..bb86168a 100644 --- a/delivery/http_server/end2end/benefactor_kindboxes_test.go +++ b/delivery/http_server/end2end/benefactor_kindboxes_test.go @@ -3,15 +3,14 @@ package end2end import ( + "context" "encoding/json" "fmt" "git.gocasts.ir/ebhomengo/niki/delivery/http_server/end2end/setup" - "git.gocasts.ir/ebhomengo/niki/entity" benefactorkindboxparam "git.gocasts.ir/ebhomengo/niki/param/benefactor/kind_box" "github.com/stretchr/testify/suite" "net/http" "testing" - "time" ) type BenefactorKindBoxTestSuite struct { @@ -31,49 +30,29 @@ func (suite *BenefactorKindBoxTestSuite) SetupTest() { teardown := setup.SeedMariaDB(testContainer.GetMariaDBConfig()) suite.T().Cleanup(teardown) suite.benefactorPhone = "09384664404" + suite.benefactorID = 1 suite.kindBoxID = 1 suite.kindBboxGetAllExpected = map[string]interface{}{ "count": 1, } - suite.kindBoxGetExpected = benefactorkindboxparam.KindBoxGetResponse{ - KindBox: entity.KindBox{ - ID: suite.kindBoxID, - KindBoxReqID: 1, - BenefactorID: 1, - KindBoxType: "on-table", - Amount: 0, - SerialNumber: "serial-1", - Status: "delivered", - DeliverReferTimeID: 1, - DeliverReferDate: time.Now().AddDate(0, 0, 7).UTC(), - DeliverAddressID: 1, - SenderAgentID: 1, - DeliveredAt: time.Now().AddDate(0, 0, 7).UTC(), - ReturnReferTimeID: 0, - ReturnReferDate: time.Time{}, - ReturnAddressID: 0, - ReceiverAgentID: 0, - ReturnedAt: time.Time{}, - }, - } } // Test for GET /benefactor/kindboxes (Get All Kind Boxes) func (suite *BenefactorKindBoxTestSuite) TestBenefactorKindBoxGetAll() { suite.Run("Success", func() { token := LoginBenefactor(suite.benefactorPhone) - url := fmt.Sprintf("/benefactor/kindboxes") + url := fmt.Sprintf("/benefactors/kindboxes") responseRecord := CreateRequest("GET", url, token, nil) suite.Require().Equal(http.StatusOK, responseRecord.Code) var response benefactorkindboxparam.KindBoxGetAllResponse err := json.NewDecoder(responseRecord.Body).Decode(&response) suite.Require().NoError(err, "could not decode response") - suite.Require().Equal(suite.kindBboxGetAllExpected["count"], len(response.AllKindBox)) + suite.Require().Equal(suite.kindBboxGetAllExpected["count"], len(response.Data)) }) suite.Run("Failure_Unauthorized", func() { - url := fmt.Sprintf("/benefactor/kindboxes") + url := fmt.Sprintf("/benefactors/kindboxes") responseRecord := CreateRequest("GET", url, "invalid_token", nil) suite.Require().Equal(http.StatusUnauthorized, responseRecord.Code) }) @@ -83,7 +62,7 @@ func (suite *BenefactorKindBoxTestSuite) TestBenefactorKindBoxGetAll() { func (suite *BenefactorKindBoxTestSuite) TestBenefactorKindBoxGet() { suite.Run("Success", func() { token := LoginBenefactor(suite.benefactorPhone) - url := fmt.Sprintf("/benefactor/kindboxes/%d", suite.kindBoxID) + url := fmt.Sprintf("/benefactors/kindboxes/%d", suite.kindBoxID) responseRecord := CreateRequest("GET", url, token, nil) suite.Require().Equal(http.StatusOK, responseRecord.Code) @@ -91,40 +70,35 @@ func (suite *BenefactorKindBoxTestSuite) TestBenefactorKindBoxGet() { err := json.NewDecoder(responseRecord.Body).Decode(&response) suite.Require().NoError(err, "could not decode response body") - suite.assertKindBoxFields(suite.kindBoxGetExpected.KindBox, response.KindBox) + kindBox, sErr := services.BenefactorKindBoxSvc.Get(context.Background(), + benefactorkindboxparam.KindBoxGetRequest{ + BenefactorID: suite.benefactorID, + KindBoxID: suite.kindBoxID, + }) + suite.Require().NoError(sErr, "failed to get benefactor kind box") + + suite.Require().Equal(kindBox.Data.ID, response.Data.ID) + suite.Require().Equal(kindBox.Data.KindBoxReqID, response.Data.KindBoxReqID) + suite.Require().Equal(kindBox.Data.BenefactorID, response.Data.BenefactorID) + suite.Require().Equal(kindBox.Data.KindBoxType, response.Data.KindBoxType) + suite.Require().Equal(kindBox.Data.Amount, response.Data.Amount) + suite.Require().Equal(kindBox.Data.SerialNumber, response.Data.SerialNumber) + suite.Require().Equal(kindBox.Data.Status, response.Data.Status) + suite.Require().Equal(kindBox.Data.DeliverReferTimeID, response.Data.DeliverReferTimeID) + suite.Require().Equal(kindBox.Data.DeliverReferDate, response.Data.DeliverReferDate) + }) suite.Run("Failure_NotFound", func() { token := LoginBenefactor(suite.benefactorPhone) - url := fmt.Sprintf("/benefactor/kindboxes/%d", 9999) // Non-existent ID + url := fmt.Sprintf("/benefactors/kindboxes/%d", 9999) // Non-existent ID responseRecord := CreateRequest("GET", url, token, nil) suite.Require().Equal(http.StatusUnprocessableEntity, responseRecord.Code) }) suite.Run("Failure_Unauthorized", func() { - url := fmt.Sprintf("/benefactor/kindboxes/%d", suite.kindBoxID) + url := fmt.Sprintf("/benefactors/kindboxes/%d", suite.kindBoxID) responseRecord := CreateRequest("GET", url, "invalid_token", nil) suite.Require().Equal(http.StatusUnauthorized, responseRecord.Code) }) } - -// Helper method to assert all fields of KindBox -func (suite *BenefactorKindBoxTestSuite) assertKindBoxFields(expected, actual entity.KindBox) { - suite.Require().Equal(expected.ID, actual.ID, "ID should match") - suite.Require().Equal(expected.KindBoxReqID, actual.KindBoxReqID, "KindBoxReqID should match") - suite.Require().Equal(expected.BenefactorID, actual.BenefactorID, "BenefactorID should match") - suite.Require().Equal(expected.KindBoxType, actual.KindBoxType, "KindBoxType should match") - suite.Require().Equal(expected.Amount, actual.Amount, "Amount should match") - suite.Require().Equal(expected.SerialNumber, actual.SerialNumber, "SerialNumber should match") - suite.Require().Equal(expected.Status, actual.Status, "Status should match") - suite.Require().Equal(expected.DeliverReferTimeID, actual.DeliverReferTimeID, "DeliverReferTimeID should match") - suite.Require().Equal(expected.DeliverReferDate.Format("2006-01-02"), actual.DeliverReferDate.Format("2006-01-02"), "DeliverReferDate should match") - suite.Require().Equal(expected.DeliverAddressID, actual.DeliverAddressID, "DeliverAddressID should match") - suite.Require().Equal(expected.SenderAgentID, actual.SenderAgentID, "SenderAgentID should match") - suite.Require().Equal(expected.DeliveredAt.Format("2006-01-02"), actual.DeliveredAt.Format("2006-01-02"), "DeliveredAt should match") - suite.Require().Equal(expected.ReturnReferTimeID, actual.ReturnReferTimeID, "ReturnReferTimeID should match") - suite.Require().Equal(expected.ReturnReferDate.Format("2006-01-02"), actual.ReturnReferDate.Format("2006-01-02"), "ReturnReferDate should match") - suite.Require().Equal(expected.ReturnAddressID, actual.ReturnAddressID, "ReturnAddressID should match") - suite.Require().Equal(expected.ReceiverAgentID, actual.ReceiverAgentID, "ReceiverAgentID should match") - suite.Require().Equal(expected.ReturnedAt.Format("2006-01-02"), actual.ReturnedAt.Format("2006-01-02"), "ReturnedAt should match") -} diff --git a/delivery/http_server/end2end/benefactor_kindboxreqs_test.go b/delivery/http_server/end2end/benefactor_kindboxreqs_test.go index 05635699..bec03262 100644 --- a/delivery/http_server/end2end/benefactor_kindboxreqs_test.go +++ b/delivery/http_server/end2end/benefactor_kindboxreqs_test.go @@ -24,7 +24,6 @@ type BenefactorKindBoxReqsTestSuite struct { benefactorID uint kindBoxReqID uint getAllExpected map[string]interface{} - getExpected map[string]interface{} createData benefactorkindboxreqparam.KindBoxReqAddRequest updateData benefactorkindboxreqparam.KindBoxReqUpdateRequest } @@ -45,13 +44,6 @@ func (suite *BenefactorKindBoxReqsTestSuite) SetupTest() { "count": 5, } - suite.getExpected = map[string]interface{}{ - "kind_box_type": entity.KindBoxOnTable, - "deliver_address": uint(1), - "deliver_refer_date": time.Now().AddDate(0, 0, 7).UTC(), - "deliver_refer_time": uint(1), - } - suite.createData = benefactorkindboxreqparam.KindBoxReqAddRequest{ KindBoxType: entity.KindBoxCylindrical, DeliverAddressID: uint(1), @@ -73,7 +65,7 @@ func (suite *BenefactorKindBoxReqsTestSuite) SetupTest() { func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_GetAll_Success() { suite.Run("Success", func() { token := LoginBenefactor(suite.benefactorPhone) - url := fmt.Sprintf("/benefactor/kindboxreqs/") + url := fmt.Sprintf("/benefactors/kindboxreqs") responseRecord := CreateRequest(http.MethodGet, url, token, nil) suite.Require().Equal(http.StatusOK, responseRecord.Code) @@ -81,11 +73,11 @@ func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_GetAll_Su err := json.NewDecoder(responseRecord.Body).Decode(&response) suite.Require().NoError(err, "failed to decode response body") - assert.Equal(suite.T(), suite.getAllExpected["count"], len(response.AllKindBoxReq)) + assert.Equal(suite.T(), suite.getAllExpected["count"], len(response.Data)) }) suite.Run("Failure_Unauthorized", func() { - url := fmt.Sprintf("/benefactor/kindboxreqs/") + url := fmt.Sprintf("/benefactors/kindboxreqs") responseRecord := CreateRequest(http.MethodGet, url, "invalid_token", nil) suite.Require().Equal(http.StatusUnauthorized, responseRecord.Code) }) @@ -94,7 +86,7 @@ func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_GetAll_Su func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Get_Success() { suite.Run("Success", func() { token := LoginBenefactor(suite.benefactorPhone) - url := fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.kindBoxReqID) + url := fmt.Sprintf("/benefactors/kindboxreqs/%d", suite.kindBoxReqID) responseRecord := CreateRequest(http.MethodGet, url, token, nil) suite.Require().Equal(http.StatusOK, responseRecord.Code) @@ -102,26 +94,29 @@ func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Get_Succe err := json.NewDecoder(responseRecord.Body).Decode(&response) suite.Require().NoError(err, "failed to decode response body") - assert.Equal(suite.T(), suite.kindBoxReqID, response.KindBoxReq.ID) - assert.Equal(suite.T(), suite.getExpected["kind_box_type"], response.KindBoxReq.KindBoxType) - assert.Equal(suite.T(), suite.getExpected["deliver_address"], response.KindBoxReq.DeliverAddressID) - assert.Equal( - suite.T(), - suite.getExpected["deliver_refer_date"].(time.Time).Format("2006-01-02"), - response.KindBoxReq.DeliverReferDate.Format("2006-01-02"), - ) - assert.Equal(suite.T(), suite.getExpected["deliver_refer_time"], response.KindBoxReq.DeliverReferTimeID) + kinBoxReq, err := services.BenefactorKindBoxReqSvc.Get(context.Background(), + benefactorkindboxreqparam.KindBoxReqGetRequest{ + BenefactorID: suite.benefactorID, + KindBoxReqID: suite.kindBoxReqID, + }) + + suite.Require().NoError(err, "failed to get kind box request") + assert.Equal(suite.T(), kinBoxReq.Data.KindBoxType, response.Data.KindBoxType) + assert.Equal(suite.T(), kinBoxReq.Data.CountRequested, response.Data.CountRequested) + assert.Equal(suite.T(), kinBoxReq.Data.Description, response.Data.Description) + assert.Equal(suite.T(), kinBoxReq.Data.DeliverReferTimeID, response.Data.DeliverReferTimeID) + }) suite.Run("Failure_NotFound", func() { token := LoginBenefactor(suite.benefactorPhone) - url := fmt.Sprintf("/benefactor/kindboxreqs/%d", 9999) // Non-existent ID + url := fmt.Sprintf("/benefactors/kindboxreqs/%d", 9999) // Non-existent ID responseRecord := CreateRequest(http.MethodGet, url, token, nil) suite.Require().Equal(http.StatusNotFound, responseRecord.Code) }) suite.Run("Failure_Unauthorized", func() { - url := fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.kindBoxReqID) + url := fmt.Sprintf("/benefactors/kindboxreqs/%d", suite.kindBoxReqID) responseRecord := CreateRequest(http.MethodGet, url, "invalid_token", nil) suite.Require().Equal(http.StatusUnauthorized, responseRecord.Code) }) @@ -130,7 +125,7 @@ func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Get_Succe func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Create_Success() { suite.Run("Success", func() { token := LoginBenefactor(suite.benefactorPhone) - url := fmt.Sprintf("/benefactor/kindboxreqs/") + url := fmt.Sprintf("/benefactors/kindboxreqs") rec := CreateRequest(http.MethodPost, url, token, suite.createData) suite.Require().Equal(http.StatusCreated, rec.Code) @@ -138,14 +133,14 @@ func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Create_Su err := json.NewDecoder(rec.Body).Decode(&response) suite.Require().NoError(err, "failed to decode response body") - assert.Equal(suite.T(), suite.createData.KindBoxType, response.KindBoxReq.KindBoxType) - assert.Equal(suite.T(), suite.createData.DeliverAddressID, response.KindBoxReq.DeliverAddressID) - assert.Equal(suite.T(), suite.createData.DeliverReferDate, response.KindBoxReq.DeliverReferDate) - assert.Equal(suite.T(), suite.createData.CountRequested, response.KindBoxReq.CountRequested) + assert.Equal(suite.T(), suite.createData.KindBoxType, response.Data.KindBoxType) + assert.Equal(suite.T(), suite.createData.DeliverAddressID, response.Data.DeliverAddressID) + assert.Equal(suite.T(), suite.createData.DeliverReferDate, response.Data.DeliverReferDate) + assert.Equal(suite.T(), suite.createData.CountRequested, response.Data.CountRequested) }) suite.Run("Failure_Unauthorized", func() { - url := fmt.Sprintf("/benefactor/kindboxreqs/") + url := fmt.Sprintf("/benefactors/kindboxreqs") rec := CreateRequest(http.MethodPost, url, "invalid_token", suite.createData) suite.Require().Equal(http.StatusUnauthorized, rec.Code) }) @@ -154,7 +149,7 @@ func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Create_Su func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Update_Success() { suite.Run("Success", func() { token := LoginBenefactor(suite.benefactorPhone) - url := fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.kindBoxReqID) + url := fmt.Sprintf("/benefactors/kindboxreqs/%d", suite.kindBoxReqID) rec := CreateRequest(http.MethodPut, url, token, suite.updateData) suite.Require().Equal(http.StatusNoContent, rec.Code) @@ -166,20 +161,19 @@ func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Update_Su ) suite.Require().NoError(err, "failed to get kind box request") - assert.Equal(suite.T(), suite.updateData.KindBoxType, kindBoxReq.KindBoxType) - assert.Equal(suite.T(), suite.updateData.CountRequested, kindBoxReq.CountRequested) - assert.Equal(suite.T(), suite.updateData.Description, kindBoxReq.Description) - assert.Equal(suite.T(), suite.updateData.DeliverReferTimeID, kindBoxReq.DeliverReferTimeID) + assert.Equal(suite.T(), suite.updateData.CountRequested, kindBoxReq.Data.CountRequested) + assert.Equal(suite.T(), suite.updateData.Description, kindBoxReq.Data.Description) + assert.Equal(suite.T(), suite.updateData.DeliverReferTimeID, kindBoxReq.Data.DeliverReferTimeID) assert.Equal( suite.T(), suite.updateData.DeliverReferDate.Format("2006-01-02"), - kindBoxReq.DeliverReferDate.Format("2006-01-02"), + kindBoxReq.Data.DeliverReferDate.Format("2006-01-02"), ) - assert.Equal(suite.T(), suite.updateData.DeliverAddressID, kindBoxReq.DeliverAddressID) + assert.Equal(suite.T(), suite.updateData.DeliverAddressID, kindBoxReq.Data.DeliverAddressID) }) suite.Run("Failure_Unauthorized", func() { - url := fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.kindBoxReqID) + url := fmt.Sprintf("/benefactors/kindboxreqs/%d", suite.kindBoxReqID) rec := CreateRequest(http.MethodPut, url, "invalid_token", suite.updateData) suite.Require().Equal(http.StatusUnauthorized, rec.Code) }) @@ -188,7 +182,7 @@ func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Update_Su func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Delete_Success() { suite.Run("Success", func() { token := LoginBenefactor(suite.benefactorPhone) - url := fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.kindBoxReqID) + url := fmt.Sprintf("/benefactors/kindboxreqs/%d", suite.kindBoxReqID) rec := CreateRequest(http.MethodDelete, url, token, nil) suite.Require().Equal(http.StatusOK, rec.Code) @@ -205,7 +199,7 @@ func (suite *BenefactorKindBoxReqsTestSuite) TestBenefactorKindBoxReqs_Delete_Su }) suite.Run("Failure_Unauthorized", func() { - url := fmt.Sprintf("/benefactor/kindboxreqs/%d", suite.kindBoxReqID) + url := fmt.Sprintf("/benefactors/kindboxreqs/%d", suite.kindBoxReqID) rec := CreateRequest(http.MethodDelete, url, "invalid_token", nil) suite.Require().Equal(http.StatusUnauthorized, rec.Code) }) From dad8eba72df284c28cfa418c310bb1d05e20482b Mon Sep 17 00:00:00 2001 From: Reza Mobaraki Date: Tue, 8 Oct 2024 21:33:54 +0330 Subject: [PATCH 22/22] update vendor Signed-off-by: Reza Mobaraki --- .../stretchr/testify/require/doc.go | 29 + .../testify/require/forward_requirements.go | 16 + .../stretchr/testify/require/require.go | 2060 +++++++++++++++++ .../stretchr/testify/require/require.go.tmpl | 6 + .../testify/require/require_forward.go | 1622 +++++++++++++ .../testify/require/require_forward.go.tmpl | 5 + .../stretchr/testify/require/requirements.go | 29 + .../github.com/stretchr/testify/suite/doc.go | 66 + .../stretchr/testify/suite/interfaces.go | 66 + .../stretchr/testify/suite/stats.go | 46 + .../stretchr/testify/suite/suite.go | 253 ++ 11 files changed, 4198 insertions(+) create mode 100644 vendor/github.com/stretchr/testify/require/doc.go create mode 100644 vendor/github.com/stretchr/testify/require/forward_requirements.go create mode 100644 vendor/github.com/stretchr/testify/require/require.go create mode 100644 vendor/github.com/stretchr/testify/require/require.go.tmpl create mode 100644 vendor/github.com/stretchr/testify/require/require_forward.go create mode 100644 vendor/github.com/stretchr/testify/require/require_forward.go.tmpl create mode 100644 vendor/github.com/stretchr/testify/require/requirements.go create mode 100644 vendor/github.com/stretchr/testify/suite/doc.go create mode 100644 vendor/github.com/stretchr/testify/suite/interfaces.go create mode 100644 vendor/github.com/stretchr/testify/suite/stats.go create mode 100644 vendor/github.com/stretchr/testify/suite/suite.go diff --git a/vendor/github.com/stretchr/testify/require/doc.go b/vendor/github.com/stretchr/testify/require/doc.go new file mode 100644 index 00000000..96843472 --- /dev/null +++ b/vendor/github.com/stretchr/testify/require/doc.go @@ -0,0 +1,29 @@ +// Package require implements the same assertions as the `assert` package but +// stops test execution when a test fails. +// +// # Example Usage +// +// The following is a complete example using require in a standard test function: +// +// import ( +// "testing" +// "github.com/stretchr/testify/require" +// ) +// +// func TestSomething(t *testing.T) { +// +// var a string = "Hello" +// var b string = "Hello" +// +// require.Equal(t, a, b, "The two words should be the same.") +// +// } +// +// # Assertions +// +// The `require` package have same global functions as in the `assert` package, +// but instead of returning a boolean result they call `t.FailNow()`. +// +// Every assertion function also takes an optional string message as the final argument, +// allowing custom error messages to be appended to the message the assertion method outputs. +package require diff --git a/vendor/github.com/stretchr/testify/require/forward_requirements.go b/vendor/github.com/stretchr/testify/require/forward_requirements.go new file mode 100644 index 00000000..1dcb2338 --- /dev/null +++ b/vendor/github.com/stretchr/testify/require/forward_requirements.go @@ -0,0 +1,16 @@ +package require + +// Assertions provides assertion methods around the +// TestingT interface. +type Assertions struct { + t TestingT +} + +// New makes a new Assertions object for the specified TestingT. +func New(t TestingT) *Assertions { + return &Assertions{ + t: t, + } +} + +//go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=require -template=require_forward.go.tmpl -include-format-funcs" diff --git a/vendor/github.com/stretchr/testify/require/require.go b/vendor/github.com/stretchr/testify/require/require.go new file mode 100644 index 00000000..506a82f8 --- /dev/null +++ b/vendor/github.com/stretchr/testify/require/require.go @@ -0,0 +1,2060 @@ +// Code generated with github.com/stretchr/testify/_codegen; DO NOT EDIT. + +package require + +import ( + assert "github.com/stretchr/testify/assert" + http "net/http" + url "net/url" + time "time" +) + +// Condition uses a Comparison to assert a complex condition. +func Condition(t TestingT, comp assert.Comparison, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Condition(t, comp, msgAndArgs...) { + return + } + t.FailNow() +} + +// Conditionf uses a Comparison to assert a complex condition. +func Conditionf(t TestingT, comp assert.Comparison, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Conditionf(t, comp, msg, args...) { + return + } + t.FailNow() +} + +// Contains asserts that the specified string, list(array, slice...) or map contains the +// specified substring or element. +// +// assert.Contains(t, "Hello World", "World") +// assert.Contains(t, ["Hello", "World"], "World") +// assert.Contains(t, {"Hello": "World"}, "Hello") +func Contains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Contains(t, s, contains, msgAndArgs...) { + return + } + t.FailNow() +} + +// Containsf asserts that the specified string, list(array, slice...) or map contains the +// specified substring or element. +// +// assert.Containsf(t, "Hello World", "World", "error message %s", "formatted") +// assert.Containsf(t, ["Hello", "World"], "World", "error message %s", "formatted") +// assert.Containsf(t, {"Hello": "World"}, "Hello", "error message %s", "formatted") +func Containsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Containsf(t, s, contains, msg, args...) { + return + } + t.FailNow() +} + +// DirExists checks whether a directory exists in the given path. It also fails +// if the path is a file rather a directory or there is an error checking whether it exists. +func DirExists(t TestingT, path string, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.DirExists(t, path, msgAndArgs...) { + return + } + t.FailNow() +} + +// DirExistsf checks whether a directory exists in the given path. It also fails +// if the path is a file rather a directory or there is an error checking whether it exists. +func DirExistsf(t TestingT, path string, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.DirExistsf(t, path, msg, args...) { + return + } + t.FailNow() +} + +// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified +// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, +// the number of appearances of each of them in both lists should match. +// +// assert.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2]) +func ElementsMatch(t TestingT, listA interface{}, listB interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.ElementsMatch(t, listA, listB, msgAndArgs...) { + return + } + t.FailNow() +} + +// ElementsMatchf asserts that the specified listA(array, slice...) is equal to specified +// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, +// the number of appearances of each of them in both lists should match. +// +// assert.ElementsMatchf(t, [1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted") +func ElementsMatchf(t TestingT, listA interface{}, listB interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.ElementsMatchf(t, listA, listB, msg, args...) { + return + } + t.FailNow() +} + +// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// assert.Empty(t, obj) +func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Empty(t, object, msgAndArgs...) { + return + } + t.FailNow() +} + +// Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// assert.Emptyf(t, obj, "error message %s", "formatted") +func Emptyf(t TestingT, object interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Emptyf(t, object, msg, args...) { + return + } + t.FailNow() +} + +// Equal asserts that two objects are equal. +// +// assert.Equal(t, 123, 123) +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). Function equality +// cannot be determined and will always fail. +func Equal(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Equal(t, expected, actual, msgAndArgs...) { + return + } + t.FailNow() +} + +// EqualError asserts that a function returned an error (i.e. not `nil`) +// and that it is equal to the provided error. +// +// actualObj, err := SomeFunction() +// assert.EqualError(t, err, expectedErrorString) +func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.EqualError(t, theError, errString, msgAndArgs...) { + return + } + t.FailNow() +} + +// EqualErrorf asserts that a function returned an error (i.e. not `nil`) +// and that it is equal to the provided error. +// +// actualObj, err := SomeFunction() +// assert.EqualErrorf(t, err, expectedErrorString, "error message %s", "formatted") +func EqualErrorf(t TestingT, theError error, errString string, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.EqualErrorf(t, theError, errString, msg, args...) { + return + } + t.FailNow() +} + +// EqualExportedValues asserts that the types of two objects are equal and their public +// fields are also equal. This is useful for comparing structs that have private fields +// that could potentially differ. +// +// type S struct { +// Exported int +// notExported int +// } +// assert.EqualExportedValues(t, S{1, 2}, S{1, 3}) => true +// assert.EqualExportedValues(t, S{1, 2}, S{2, 3}) => false +func EqualExportedValues(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.EqualExportedValues(t, expected, actual, msgAndArgs...) { + return + } + t.FailNow() +} + +// EqualExportedValuesf asserts that the types of two objects are equal and their public +// fields are also equal. This is useful for comparing structs that have private fields +// that could potentially differ. +// +// type S struct { +// Exported int +// notExported int +// } +// assert.EqualExportedValuesf(t, S{1, 2}, S{1, 3}, "error message %s", "formatted") => true +// assert.EqualExportedValuesf(t, S{1, 2}, S{2, 3}, "error message %s", "formatted") => false +func EqualExportedValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.EqualExportedValuesf(t, expected, actual, msg, args...) { + return + } + t.FailNow() +} + +// EqualValues asserts that two objects are equal or convertible to the same types +// and equal. +// +// assert.EqualValues(t, uint32(123), int32(123)) +func EqualValues(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.EqualValues(t, expected, actual, msgAndArgs...) { + return + } + t.FailNow() +} + +// EqualValuesf asserts that two objects are equal or convertible to the same types +// and equal. +// +// assert.EqualValuesf(t, uint32(123), int32(123), "error message %s", "formatted") +func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.EqualValuesf(t, expected, actual, msg, args...) { + return + } + t.FailNow() +} + +// Equalf asserts that two objects are equal. +// +// assert.Equalf(t, 123, 123, "error message %s", "formatted") +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). Function equality +// cannot be determined and will always fail. +func Equalf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Equalf(t, expected, actual, msg, args...) { + return + } + t.FailNow() +} + +// Error asserts that a function returned an error (i.e. not `nil`). +// +// actualObj, err := SomeFunction() +// if assert.Error(t, err) { +// assert.Equal(t, expectedError, err) +// } +func Error(t TestingT, err error, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Error(t, err, msgAndArgs...) { + return + } + t.FailNow() +} + +// ErrorAs asserts that at least one of the errors in err's chain matches target, and if so, sets target to that error value. +// This is a wrapper for errors.As. +func ErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.ErrorAs(t, err, target, msgAndArgs...) { + return + } + t.FailNow() +} + +// ErrorAsf asserts that at least one of the errors in err's chain matches target, and if so, sets target to that error value. +// This is a wrapper for errors.As. +func ErrorAsf(t TestingT, err error, target interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.ErrorAsf(t, err, target, msg, args...) { + return + } + t.FailNow() +} + +// ErrorContains asserts that a function returned an error (i.e. not `nil`) +// and that the error contains the specified substring. +// +// actualObj, err := SomeFunction() +// assert.ErrorContains(t, err, expectedErrorSubString) +func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.ErrorContains(t, theError, contains, msgAndArgs...) { + return + } + t.FailNow() +} + +// ErrorContainsf asserts that a function returned an error (i.e. not `nil`) +// and that the error contains the specified substring. +// +// actualObj, err := SomeFunction() +// assert.ErrorContainsf(t, err, expectedErrorSubString, "error message %s", "formatted") +func ErrorContainsf(t TestingT, theError error, contains string, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.ErrorContainsf(t, theError, contains, msg, args...) { + return + } + t.FailNow() +} + +// ErrorIs asserts that at least one of the errors in err's chain matches target. +// This is a wrapper for errors.Is. +func ErrorIs(t TestingT, err error, target error, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.ErrorIs(t, err, target, msgAndArgs...) { + return + } + t.FailNow() +} + +// ErrorIsf asserts that at least one of the errors in err's chain matches target. +// This is a wrapper for errors.Is. +func ErrorIsf(t TestingT, err error, target error, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.ErrorIsf(t, err, target, msg, args...) { + return + } + t.FailNow() +} + +// Errorf asserts that a function returned an error (i.e. not `nil`). +// +// actualObj, err := SomeFunction() +// if assert.Errorf(t, err, "error message %s", "formatted") { +// assert.Equal(t, expectedErrorf, err) +// } +func Errorf(t TestingT, err error, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Errorf(t, err, msg, args...) { + return + } + t.FailNow() +} + +// Eventually asserts that given condition will be met in waitFor time, +// periodically checking target function each tick. +// +// assert.Eventually(t, func() bool { return true; }, time.Second, 10*time.Millisecond) +func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Eventually(t, condition, waitFor, tick, msgAndArgs...) { + return + } + t.FailNow() +} + +// EventuallyWithT asserts that given condition will be met in waitFor time, +// periodically checking target function each tick. In contrast to Eventually, +// it supplies a CollectT to the condition function, so that the condition +// function can use the CollectT to call other assertions. +// The condition is considered "met" if no errors are raised in a tick. +// The supplied CollectT collects all errors from one tick (if there are any). +// If the condition is not met before waitFor, the collected errors of +// the last tick are copied to t. +// +// externalValue := false +// go func() { +// time.Sleep(8*time.Second) +// externalValue = true +// }() +// assert.EventuallyWithT(t, func(c *assert.CollectT) { +// // add assertions as needed; any assertion failure will fail the current tick +// assert.True(c, externalValue, "expected 'externalValue' to be true") +// }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false") +func EventuallyWithT(t TestingT, condition func(collect *assert.CollectT), waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.EventuallyWithT(t, condition, waitFor, tick, msgAndArgs...) { + return + } + t.FailNow() +} + +// EventuallyWithTf asserts that given condition will be met in waitFor time, +// periodically checking target function each tick. In contrast to Eventually, +// it supplies a CollectT to the condition function, so that the condition +// function can use the CollectT to call other assertions. +// The condition is considered "met" if no errors are raised in a tick. +// The supplied CollectT collects all errors from one tick (if there are any). +// If the condition is not met before waitFor, the collected errors of +// the last tick are copied to t. +// +// externalValue := false +// go func() { +// time.Sleep(8*time.Second) +// externalValue = true +// }() +// assert.EventuallyWithTf(t, func(c *assert.CollectT, "error message %s", "formatted") { +// // add assertions as needed; any assertion failure will fail the current tick +// assert.True(c, externalValue, "expected 'externalValue' to be true") +// }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false") +func EventuallyWithTf(t TestingT, condition func(collect *assert.CollectT), waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.EventuallyWithTf(t, condition, waitFor, tick, msg, args...) { + return + } + t.FailNow() +} + +// Eventuallyf asserts that given condition will be met in waitFor time, +// periodically checking target function each tick. +// +// assert.Eventuallyf(t, func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") +func Eventuallyf(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Eventuallyf(t, condition, waitFor, tick, msg, args...) { + return + } + t.FailNow() +} + +// Exactly asserts that two objects are equal in value and type. +// +// assert.Exactly(t, int32(123), int64(123)) +func Exactly(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Exactly(t, expected, actual, msgAndArgs...) { + return + } + t.FailNow() +} + +// Exactlyf asserts that two objects are equal in value and type. +// +// assert.Exactlyf(t, int32(123), int64(123), "error message %s", "formatted") +func Exactlyf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Exactlyf(t, expected, actual, msg, args...) { + return + } + t.FailNow() +} + +// Fail reports a failure through +func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Fail(t, failureMessage, msgAndArgs...) { + return + } + t.FailNow() +} + +// FailNow fails test +func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.FailNow(t, failureMessage, msgAndArgs...) { + return + } + t.FailNow() +} + +// FailNowf fails test +func FailNowf(t TestingT, failureMessage string, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.FailNowf(t, failureMessage, msg, args...) { + return + } + t.FailNow() +} + +// Failf reports a failure through +func Failf(t TestingT, failureMessage string, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Failf(t, failureMessage, msg, args...) { + return + } + t.FailNow() +} + +// False asserts that the specified value is false. +// +// assert.False(t, myBool) +func False(t TestingT, value bool, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.False(t, value, msgAndArgs...) { + return + } + t.FailNow() +} + +// Falsef asserts that the specified value is false. +// +// assert.Falsef(t, myBool, "error message %s", "formatted") +func Falsef(t TestingT, value bool, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Falsef(t, value, msg, args...) { + return + } + t.FailNow() +} + +// FileExists checks whether a file exists in the given path. It also fails if +// the path points to a directory or there is an error when trying to check the file. +func FileExists(t TestingT, path string, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.FileExists(t, path, msgAndArgs...) { + return + } + t.FailNow() +} + +// FileExistsf checks whether a file exists in the given path. It also fails if +// the path points to a directory or there is an error when trying to check the file. +func FileExistsf(t TestingT, path string, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.FileExistsf(t, path, msg, args...) { + return + } + t.FailNow() +} + +// Greater asserts that the first element is greater than the second +// +// assert.Greater(t, 2, 1) +// assert.Greater(t, float64(2), float64(1)) +// assert.Greater(t, "b", "a") +func Greater(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Greater(t, e1, e2, msgAndArgs...) { + return + } + t.FailNow() +} + +// GreaterOrEqual asserts that the first element is greater than or equal to the second +// +// assert.GreaterOrEqual(t, 2, 1) +// assert.GreaterOrEqual(t, 2, 2) +// assert.GreaterOrEqual(t, "b", "a") +// assert.GreaterOrEqual(t, "b", "b") +func GreaterOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.GreaterOrEqual(t, e1, e2, msgAndArgs...) { + return + } + t.FailNow() +} + +// GreaterOrEqualf asserts that the first element is greater than or equal to the second +// +// assert.GreaterOrEqualf(t, 2, 1, "error message %s", "formatted") +// assert.GreaterOrEqualf(t, 2, 2, "error message %s", "formatted") +// assert.GreaterOrEqualf(t, "b", "a", "error message %s", "formatted") +// assert.GreaterOrEqualf(t, "b", "b", "error message %s", "formatted") +func GreaterOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.GreaterOrEqualf(t, e1, e2, msg, args...) { + return + } + t.FailNow() +} + +// Greaterf asserts that the first element is greater than the second +// +// assert.Greaterf(t, 2, 1, "error message %s", "formatted") +// assert.Greaterf(t, float64(2), float64(1), "error message %s", "formatted") +// assert.Greaterf(t, "b", "a", "error message %s", "formatted") +func Greaterf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Greaterf(t, e1, e2, msg, args...) { + return + } + t.FailNow() +} + +// HTTPBodyContains asserts that a specified handler returns a +// body that contains a string. +// +// assert.HTTPBodyContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.HTTPBodyContains(t, handler, method, url, values, str, msgAndArgs...) { + return + } + t.FailNow() +} + +// HTTPBodyContainsf asserts that a specified handler returns a +// body that contains a string. +// +// assert.HTTPBodyContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.HTTPBodyContainsf(t, handler, method, url, values, str, msg, args...) { + return + } + t.FailNow() +} + +// HTTPBodyNotContains asserts that a specified handler returns a +// body that does not contain a string. +// +// assert.HTTPBodyNotContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.HTTPBodyNotContains(t, handler, method, url, values, str, msgAndArgs...) { + return + } + t.FailNow() +} + +// HTTPBodyNotContainsf asserts that a specified handler returns a +// body that does not contain a string. +// +// assert.HTTPBodyNotContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.HTTPBodyNotContainsf(t, handler, method, url, values, str, msg, args...) { + return + } + t.FailNow() +} + +// HTTPError asserts that a specified handler returns an error status code. +// +// assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPError(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.HTTPError(t, handler, method, url, values, msgAndArgs...) { + return + } + t.FailNow() +} + +// HTTPErrorf asserts that a specified handler returns an error status code. +// +// assert.HTTPErrorf(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.HTTPErrorf(t, handler, method, url, values, msg, args...) { + return + } + t.FailNow() +} + +// HTTPRedirect asserts that a specified handler returns a redirect status code. +// +// assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPRedirect(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.HTTPRedirect(t, handler, method, url, values, msgAndArgs...) { + return + } + t.FailNow() +} + +// HTTPRedirectf asserts that a specified handler returns a redirect status code. +// +// assert.HTTPRedirectf(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.HTTPRedirectf(t, handler, method, url, values, msg, args...) { + return + } + t.FailNow() +} + +// HTTPStatusCode asserts that a specified handler returns a specified status code. +// +// assert.HTTPStatusCode(t, myHandler, "GET", "/notImplemented", nil, 501) +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPStatusCode(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.HTTPStatusCode(t, handler, method, url, values, statuscode, msgAndArgs...) { + return + } + t.FailNow() +} + +// HTTPStatusCodef asserts that a specified handler returns a specified status code. +// +// assert.HTTPStatusCodef(t, myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPStatusCodef(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.HTTPStatusCodef(t, handler, method, url, values, statuscode, msg, args...) { + return + } + t.FailNow() +} + +// HTTPSuccess asserts that a specified handler returns a success status code. +// +// assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPSuccess(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.HTTPSuccess(t, handler, method, url, values, msgAndArgs...) { + return + } + t.FailNow() +} + +// HTTPSuccessf asserts that a specified handler returns a success status code. +// +// assert.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.HTTPSuccessf(t, handler, method, url, values, msg, args...) { + return + } + t.FailNow() +} + +// Implements asserts that an object is implemented by the specified interface. +// +// assert.Implements(t, (*MyInterface)(nil), new(MyObject)) +func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Implements(t, interfaceObject, object, msgAndArgs...) { + return + } + t.FailNow() +} + +// Implementsf asserts that an object is implemented by the specified interface. +// +// assert.Implementsf(t, (*MyInterface)(nil), new(MyObject), "error message %s", "formatted") +func Implementsf(t TestingT, interfaceObject interface{}, object interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Implementsf(t, interfaceObject, object, msg, args...) { + return + } + t.FailNow() +} + +// InDelta asserts that the two numerals are within delta of each other. +// +// assert.InDelta(t, math.Pi, 22/7.0, 0.01) +func InDelta(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.InDelta(t, expected, actual, delta, msgAndArgs...) { + return + } + t.FailNow() +} + +// InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. +func InDeltaMapValues(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.InDeltaMapValues(t, expected, actual, delta, msgAndArgs...) { + return + } + t.FailNow() +} + +// InDeltaMapValuesf is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. +func InDeltaMapValuesf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.InDeltaMapValuesf(t, expected, actual, delta, msg, args...) { + return + } + t.FailNow() +} + +// InDeltaSlice is the same as InDelta, except it compares two slices. +func InDeltaSlice(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.InDeltaSlice(t, expected, actual, delta, msgAndArgs...) { + return + } + t.FailNow() +} + +// InDeltaSlicef is the same as InDelta, except it compares two slices. +func InDeltaSlicef(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.InDeltaSlicef(t, expected, actual, delta, msg, args...) { + return + } + t.FailNow() +} + +// InDeltaf asserts that the two numerals are within delta of each other. +// +// assert.InDeltaf(t, math.Pi, 22/7.0, 0.01, "error message %s", "formatted") +func InDeltaf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.InDeltaf(t, expected, actual, delta, msg, args...) { + return + } + t.FailNow() +} + +// InEpsilon asserts that expected and actual have a relative error less than epsilon +func InEpsilon(t TestingT, expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.InEpsilon(t, expected, actual, epsilon, msgAndArgs...) { + return + } + t.FailNow() +} + +// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. +func InEpsilonSlice(t TestingT, expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.InEpsilonSlice(t, expected, actual, epsilon, msgAndArgs...) { + return + } + t.FailNow() +} + +// InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices. +func InEpsilonSlicef(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.InEpsilonSlicef(t, expected, actual, epsilon, msg, args...) { + return + } + t.FailNow() +} + +// InEpsilonf asserts that expected and actual have a relative error less than epsilon +func InEpsilonf(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.InEpsilonf(t, expected, actual, epsilon, msg, args...) { + return + } + t.FailNow() +} + +// IsDecreasing asserts that the collection is decreasing +// +// assert.IsDecreasing(t, []int{2, 1, 0}) +// assert.IsDecreasing(t, []float{2, 1}) +// assert.IsDecreasing(t, []string{"b", "a"}) +func IsDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.IsDecreasing(t, object, msgAndArgs...) { + return + } + t.FailNow() +} + +// IsDecreasingf asserts that the collection is decreasing +// +// assert.IsDecreasingf(t, []int{2, 1, 0}, "error message %s", "formatted") +// assert.IsDecreasingf(t, []float{2, 1}, "error message %s", "formatted") +// assert.IsDecreasingf(t, []string{"b", "a"}, "error message %s", "formatted") +func IsDecreasingf(t TestingT, object interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.IsDecreasingf(t, object, msg, args...) { + return + } + t.FailNow() +} + +// IsIncreasing asserts that the collection is increasing +// +// assert.IsIncreasing(t, []int{1, 2, 3}) +// assert.IsIncreasing(t, []float{1, 2}) +// assert.IsIncreasing(t, []string{"a", "b"}) +func IsIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.IsIncreasing(t, object, msgAndArgs...) { + return + } + t.FailNow() +} + +// IsIncreasingf asserts that the collection is increasing +// +// assert.IsIncreasingf(t, []int{1, 2, 3}, "error message %s", "formatted") +// assert.IsIncreasingf(t, []float{1, 2}, "error message %s", "formatted") +// assert.IsIncreasingf(t, []string{"a", "b"}, "error message %s", "formatted") +func IsIncreasingf(t TestingT, object interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.IsIncreasingf(t, object, msg, args...) { + return + } + t.FailNow() +} + +// IsNonDecreasing asserts that the collection is not decreasing +// +// assert.IsNonDecreasing(t, []int{1, 1, 2}) +// assert.IsNonDecreasing(t, []float{1, 2}) +// assert.IsNonDecreasing(t, []string{"a", "b"}) +func IsNonDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.IsNonDecreasing(t, object, msgAndArgs...) { + return + } + t.FailNow() +} + +// IsNonDecreasingf asserts that the collection is not decreasing +// +// assert.IsNonDecreasingf(t, []int{1, 1, 2}, "error message %s", "formatted") +// assert.IsNonDecreasingf(t, []float{1, 2}, "error message %s", "formatted") +// assert.IsNonDecreasingf(t, []string{"a", "b"}, "error message %s", "formatted") +func IsNonDecreasingf(t TestingT, object interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.IsNonDecreasingf(t, object, msg, args...) { + return + } + t.FailNow() +} + +// IsNonIncreasing asserts that the collection is not increasing +// +// assert.IsNonIncreasing(t, []int{2, 1, 1}) +// assert.IsNonIncreasing(t, []float{2, 1}) +// assert.IsNonIncreasing(t, []string{"b", "a"}) +func IsNonIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.IsNonIncreasing(t, object, msgAndArgs...) { + return + } + t.FailNow() +} + +// IsNonIncreasingf asserts that the collection is not increasing +// +// assert.IsNonIncreasingf(t, []int{2, 1, 1}, "error message %s", "formatted") +// assert.IsNonIncreasingf(t, []float{2, 1}, "error message %s", "formatted") +// assert.IsNonIncreasingf(t, []string{"b", "a"}, "error message %s", "formatted") +func IsNonIncreasingf(t TestingT, object interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.IsNonIncreasingf(t, object, msg, args...) { + return + } + t.FailNow() +} + +// IsType asserts that the specified objects are of the same type. +func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.IsType(t, expectedType, object, msgAndArgs...) { + return + } + t.FailNow() +} + +// IsTypef asserts that the specified objects are of the same type. +func IsTypef(t TestingT, expectedType interface{}, object interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.IsTypef(t, expectedType, object, msg, args...) { + return + } + t.FailNow() +} + +// JSONEq asserts that two JSON strings are equivalent. +// +// assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) +func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.JSONEq(t, expected, actual, msgAndArgs...) { + return + } + t.FailNow() +} + +// JSONEqf asserts that two JSON strings are equivalent. +// +// assert.JSONEqf(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") +func JSONEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.JSONEqf(t, expected, actual, msg, args...) { + return + } + t.FailNow() +} + +// Len asserts that the specified object has specific length. +// Len also fails if the object has a type that len() not accept. +// +// assert.Len(t, mySlice, 3) +func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Len(t, object, length, msgAndArgs...) { + return + } + t.FailNow() +} + +// Lenf asserts that the specified object has specific length. +// Lenf also fails if the object has a type that len() not accept. +// +// assert.Lenf(t, mySlice, 3, "error message %s", "formatted") +func Lenf(t TestingT, object interface{}, length int, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Lenf(t, object, length, msg, args...) { + return + } + t.FailNow() +} + +// Less asserts that the first element is less than the second +// +// assert.Less(t, 1, 2) +// assert.Less(t, float64(1), float64(2)) +// assert.Less(t, "a", "b") +func Less(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Less(t, e1, e2, msgAndArgs...) { + return + } + t.FailNow() +} + +// LessOrEqual asserts that the first element is less than or equal to the second +// +// assert.LessOrEqual(t, 1, 2) +// assert.LessOrEqual(t, 2, 2) +// assert.LessOrEqual(t, "a", "b") +// assert.LessOrEqual(t, "b", "b") +func LessOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.LessOrEqual(t, e1, e2, msgAndArgs...) { + return + } + t.FailNow() +} + +// LessOrEqualf asserts that the first element is less than or equal to the second +// +// assert.LessOrEqualf(t, 1, 2, "error message %s", "formatted") +// assert.LessOrEqualf(t, 2, 2, "error message %s", "formatted") +// assert.LessOrEqualf(t, "a", "b", "error message %s", "formatted") +// assert.LessOrEqualf(t, "b", "b", "error message %s", "formatted") +func LessOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.LessOrEqualf(t, e1, e2, msg, args...) { + return + } + t.FailNow() +} + +// Lessf asserts that the first element is less than the second +// +// assert.Lessf(t, 1, 2, "error message %s", "formatted") +// assert.Lessf(t, float64(1), float64(2), "error message %s", "formatted") +// assert.Lessf(t, "a", "b", "error message %s", "formatted") +func Lessf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Lessf(t, e1, e2, msg, args...) { + return + } + t.FailNow() +} + +// Negative asserts that the specified element is negative +// +// assert.Negative(t, -1) +// assert.Negative(t, -1.23) +func Negative(t TestingT, e interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Negative(t, e, msgAndArgs...) { + return + } + t.FailNow() +} + +// Negativef asserts that the specified element is negative +// +// assert.Negativef(t, -1, "error message %s", "formatted") +// assert.Negativef(t, -1.23, "error message %s", "formatted") +func Negativef(t TestingT, e interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Negativef(t, e, msg, args...) { + return + } + t.FailNow() +} + +// Never asserts that the given condition doesn't satisfy in waitFor time, +// periodically checking the target function each tick. +// +// assert.Never(t, func() bool { return false; }, time.Second, 10*time.Millisecond) +func Never(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Never(t, condition, waitFor, tick, msgAndArgs...) { + return + } + t.FailNow() +} + +// Neverf asserts that the given condition doesn't satisfy in waitFor time, +// periodically checking the target function each tick. +// +// assert.Neverf(t, func() bool { return false; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") +func Neverf(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Neverf(t, condition, waitFor, tick, msg, args...) { + return + } + t.FailNow() +} + +// Nil asserts that the specified object is nil. +// +// assert.Nil(t, err) +func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Nil(t, object, msgAndArgs...) { + return + } + t.FailNow() +} + +// Nilf asserts that the specified object is nil. +// +// assert.Nilf(t, err, "error message %s", "formatted") +func Nilf(t TestingT, object interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Nilf(t, object, msg, args...) { + return + } + t.FailNow() +} + +// NoDirExists checks whether a directory does not exist in the given path. +// It fails if the path points to an existing _directory_ only. +func NoDirExists(t TestingT, path string, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NoDirExists(t, path, msgAndArgs...) { + return + } + t.FailNow() +} + +// NoDirExistsf checks whether a directory does not exist in the given path. +// It fails if the path points to an existing _directory_ only. +func NoDirExistsf(t TestingT, path string, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NoDirExistsf(t, path, msg, args...) { + return + } + t.FailNow() +} + +// NoError asserts that a function returned no error (i.e. `nil`). +// +// actualObj, err := SomeFunction() +// if assert.NoError(t, err) { +// assert.Equal(t, expectedObj, actualObj) +// } +func NoError(t TestingT, err error, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NoError(t, err, msgAndArgs...) { + return + } + t.FailNow() +} + +// NoErrorf asserts that a function returned no error (i.e. `nil`). +// +// actualObj, err := SomeFunction() +// if assert.NoErrorf(t, err, "error message %s", "formatted") { +// assert.Equal(t, expectedObj, actualObj) +// } +func NoErrorf(t TestingT, err error, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NoErrorf(t, err, msg, args...) { + return + } + t.FailNow() +} + +// NoFileExists checks whether a file does not exist in a given path. It fails +// if the path points to an existing _file_ only. +func NoFileExists(t TestingT, path string, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NoFileExists(t, path, msgAndArgs...) { + return + } + t.FailNow() +} + +// NoFileExistsf checks whether a file does not exist in a given path. It fails +// if the path points to an existing _file_ only. +func NoFileExistsf(t TestingT, path string, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NoFileExistsf(t, path, msg, args...) { + return + } + t.FailNow() +} + +// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the +// specified substring or element. +// +// assert.NotContains(t, "Hello World", "Earth") +// assert.NotContains(t, ["Hello", "World"], "Earth") +// assert.NotContains(t, {"Hello": "World"}, "Earth") +func NotContains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotContains(t, s, contains, msgAndArgs...) { + return + } + t.FailNow() +} + +// NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the +// specified substring or element. +// +// assert.NotContainsf(t, "Hello World", "Earth", "error message %s", "formatted") +// assert.NotContainsf(t, ["Hello", "World"], "Earth", "error message %s", "formatted") +// assert.NotContainsf(t, {"Hello": "World"}, "Earth", "error message %s", "formatted") +func NotContainsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotContainsf(t, s, contains, msg, args...) { + return + } + t.FailNow() +} + +// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// if assert.NotEmpty(t, obj) { +// assert.Equal(t, "two", obj[1]) +// } +func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotEmpty(t, object, msgAndArgs...) { + return + } + t.FailNow() +} + +// NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// if assert.NotEmptyf(t, obj, "error message %s", "formatted") { +// assert.Equal(t, "two", obj[1]) +// } +func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotEmptyf(t, object, msg, args...) { + return + } + t.FailNow() +} + +// NotEqual asserts that the specified values are NOT equal. +// +// assert.NotEqual(t, obj1, obj2) +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). +func NotEqual(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotEqual(t, expected, actual, msgAndArgs...) { + return + } + t.FailNow() +} + +// NotEqualValues asserts that two objects are not equal even when converted to the same type +// +// assert.NotEqualValues(t, obj1, obj2) +func NotEqualValues(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotEqualValues(t, expected, actual, msgAndArgs...) { + return + } + t.FailNow() +} + +// NotEqualValuesf asserts that two objects are not equal even when converted to the same type +// +// assert.NotEqualValuesf(t, obj1, obj2, "error message %s", "formatted") +func NotEqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotEqualValuesf(t, expected, actual, msg, args...) { + return + } + t.FailNow() +} + +// NotEqualf asserts that the specified values are NOT equal. +// +// assert.NotEqualf(t, obj1, obj2, "error message %s", "formatted") +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). +func NotEqualf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotEqualf(t, expected, actual, msg, args...) { + return + } + t.FailNow() +} + +// NotErrorIs asserts that at none of the errors in err's chain matches target. +// This is a wrapper for errors.Is. +func NotErrorIs(t TestingT, err error, target error, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotErrorIs(t, err, target, msgAndArgs...) { + return + } + t.FailNow() +} + +// NotErrorIsf asserts that at none of the errors in err's chain matches target. +// This is a wrapper for errors.Is. +func NotErrorIsf(t TestingT, err error, target error, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotErrorIsf(t, err, target, msg, args...) { + return + } + t.FailNow() +} + +// NotImplements asserts that an object does not implement the specified interface. +// +// assert.NotImplements(t, (*MyInterface)(nil), new(MyObject)) +func NotImplements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotImplements(t, interfaceObject, object, msgAndArgs...) { + return + } + t.FailNow() +} + +// NotImplementsf asserts that an object does not implement the specified interface. +// +// assert.NotImplementsf(t, (*MyInterface)(nil), new(MyObject), "error message %s", "formatted") +func NotImplementsf(t TestingT, interfaceObject interface{}, object interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotImplementsf(t, interfaceObject, object, msg, args...) { + return + } + t.FailNow() +} + +// NotNil asserts that the specified object is not nil. +// +// assert.NotNil(t, err) +func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotNil(t, object, msgAndArgs...) { + return + } + t.FailNow() +} + +// NotNilf asserts that the specified object is not nil. +// +// assert.NotNilf(t, err, "error message %s", "formatted") +func NotNilf(t TestingT, object interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotNilf(t, object, msg, args...) { + return + } + t.FailNow() +} + +// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. +// +// assert.NotPanics(t, func(){ RemainCalm() }) +func NotPanics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotPanics(t, f, msgAndArgs...) { + return + } + t.FailNow() +} + +// NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. +// +// assert.NotPanicsf(t, func(){ RemainCalm() }, "error message %s", "formatted") +func NotPanicsf(t TestingT, f assert.PanicTestFunc, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotPanicsf(t, f, msg, args...) { + return + } + t.FailNow() +} + +// NotRegexp asserts that a specified regexp does not match a string. +// +// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") +// assert.NotRegexp(t, "^start", "it's not starting") +func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotRegexp(t, rx, str, msgAndArgs...) { + return + } + t.FailNow() +} + +// NotRegexpf asserts that a specified regexp does not match a string. +// +// assert.NotRegexpf(t, regexp.MustCompile("starts"), "it's starting", "error message %s", "formatted") +// assert.NotRegexpf(t, "^start", "it's not starting", "error message %s", "formatted") +func NotRegexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotRegexpf(t, rx, str, msg, args...) { + return + } + t.FailNow() +} + +// NotSame asserts that two pointers do not reference the same object. +// +// assert.NotSame(t, ptr1, ptr2) +// +// Both arguments must be pointer variables. Pointer variable sameness is +// determined based on the equality of both type and value. +func NotSame(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotSame(t, expected, actual, msgAndArgs...) { + return + } + t.FailNow() +} + +// NotSamef asserts that two pointers do not reference the same object. +// +// assert.NotSamef(t, ptr1, ptr2, "error message %s", "formatted") +// +// Both arguments must be pointer variables. Pointer variable sameness is +// determined based on the equality of both type and value. +func NotSamef(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotSamef(t, expected, actual, msg, args...) { + return + } + t.FailNow() +} + +// NotSubset asserts that the specified list(array, slice...) or map does NOT +// contain all elements given in the specified subset list(array, slice...) or +// map. +// +// assert.NotSubset(t, [1, 3, 4], [1, 2]) +// assert.NotSubset(t, {"x": 1, "y": 2}, {"z": 3}) +func NotSubset(t TestingT, list interface{}, subset interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotSubset(t, list, subset, msgAndArgs...) { + return + } + t.FailNow() +} + +// NotSubsetf asserts that the specified list(array, slice...) or map does NOT +// contain all elements given in the specified subset list(array, slice...) or +// map. +// +// assert.NotSubsetf(t, [1, 3, 4], [1, 2], "error message %s", "formatted") +// assert.NotSubsetf(t, {"x": 1, "y": 2}, {"z": 3}, "error message %s", "formatted") +func NotSubsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotSubsetf(t, list, subset, msg, args...) { + return + } + t.FailNow() +} + +// NotZero asserts that i is not the zero value for its type. +func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotZero(t, i, msgAndArgs...) { + return + } + t.FailNow() +} + +// NotZerof asserts that i is not the zero value for its type. +func NotZerof(t TestingT, i interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotZerof(t, i, msg, args...) { + return + } + t.FailNow() +} + +// Panics asserts that the code inside the specified PanicTestFunc panics. +// +// assert.Panics(t, func(){ GoCrazy() }) +func Panics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Panics(t, f, msgAndArgs...) { + return + } + t.FailNow() +} + +// PanicsWithError asserts that the code inside the specified PanicTestFunc +// panics, and that the recovered panic value is an error that satisfies the +// EqualError comparison. +// +// assert.PanicsWithError(t, "crazy error", func(){ GoCrazy() }) +func PanicsWithError(t TestingT, errString string, f assert.PanicTestFunc, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.PanicsWithError(t, errString, f, msgAndArgs...) { + return + } + t.FailNow() +} + +// PanicsWithErrorf asserts that the code inside the specified PanicTestFunc +// panics, and that the recovered panic value is an error that satisfies the +// EqualError comparison. +// +// assert.PanicsWithErrorf(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") +func PanicsWithErrorf(t TestingT, errString string, f assert.PanicTestFunc, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.PanicsWithErrorf(t, errString, f, msg, args...) { + return + } + t.FailNow() +} + +// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that +// the recovered panic value equals the expected panic value. +// +// assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() }) +func PanicsWithValue(t TestingT, expected interface{}, f assert.PanicTestFunc, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.PanicsWithValue(t, expected, f, msgAndArgs...) { + return + } + t.FailNow() +} + +// PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that +// the recovered panic value equals the expected panic value. +// +// assert.PanicsWithValuef(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") +func PanicsWithValuef(t TestingT, expected interface{}, f assert.PanicTestFunc, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.PanicsWithValuef(t, expected, f, msg, args...) { + return + } + t.FailNow() +} + +// Panicsf asserts that the code inside the specified PanicTestFunc panics. +// +// assert.Panicsf(t, func(){ GoCrazy() }, "error message %s", "formatted") +func Panicsf(t TestingT, f assert.PanicTestFunc, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Panicsf(t, f, msg, args...) { + return + } + t.FailNow() +} + +// Positive asserts that the specified element is positive +// +// assert.Positive(t, 1) +// assert.Positive(t, 1.23) +func Positive(t TestingT, e interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Positive(t, e, msgAndArgs...) { + return + } + t.FailNow() +} + +// Positivef asserts that the specified element is positive +// +// assert.Positivef(t, 1, "error message %s", "formatted") +// assert.Positivef(t, 1.23, "error message %s", "formatted") +func Positivef(t TestingT, e interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Positivef(t, e, msg, args...) { + return + } + t.FailNow() +} + +// Regexp asserts that a specified regexp matches a string. +// +// assert.Regexp(t, regexp.MustCompile("start"), "it's starting") +// assert.Regexp(t, "start...$", "it's not starting") +func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Regexp(t, rx, str, msgAndArgs...) { + return + } + t.FailNow() +} + +// Regexpf asserts that a specified regexp matches a string. +// +// assert.Regexpf(t, regexp.MustCompile("start"), "it's starting", "error message %s", "formatted") +// assert.Regexpf(t, "start...$", "it's not starting", "error message %s", "formatted") +func Regexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Regexpf(t, rx, str, msg, args...) { + return + } + t.FailNow() +} + +// Same asserts that two pointers reference the same object. +// +// assert.Same(t, ptr1, ptr2) +// +// Both arguments must be pointer variables. Pointer variable sameness is +// determined based on the equality of both type and value. +func Same(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Same(t, expected, actual, msgAndArgs...) { + return + } + t.FailNow() +} + +// Samef asserts that two pointers reference the same object. +// +// assert.Samef(t, ptr1, ptr2, "error message %s", "formatted") +// +// Both arguments must be pointer variables. Pointer variable sameness is +// determined based on the equality of both type and value. +func Samef(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Samef(t, expected, actual, msg, args...) { + return + } + t.FailNow() +} + +// Subset asserts that the specified list(array, slice...) or map contains all +// elements given in the specified subset list(array, slice...) or map. +// +// assert.Subset(t, [1, 2, 3], [1, 2]) +// assert.Subset(t, {"x": 1, "y": 2}, {"x": 1}) +func Subset(t TestingT, list interface{}, subset interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Subset(t, list, subset, msgAndArgs...) { + return + } + t.FailNow() +} + +// Subsetf asserts that the specified list(array, slice...) or map contains all +// elements given in the specified subset list(array, slice...) or map. +// +// assert.Subsetf(t, [1, 2, 3], [1, 2], "error message %s", "formatted") +// assert.Subsetf(t, {"x": 1, "y": 2}, {"x": 1}, "error message %s", "formatted") +func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Subsetf(t, list, subset, msg, args...) { + return + } + t.FailNow() +} + +// True asserts that the specified value is true. +// +// assert.True(t, myBool) +func True(t TestingT, value bool, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.True(t, value, msgAndArgs...) { + return + } + t.FailNow() +} + +// Truef asserts that the specified value is true. +// +// assert.Truef(t, myBool, "error message %s", "formatted") +func Truef(t TestingT, value bool, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Truef(t, value, msg, args...) { + return + } + t.FailNow() +} + +// WithinDuration asserts that the two times are within duration delta of each other. +// +// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second) +func WithinDuration(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.WithinDuration(t, expected, actual, delta, msgAndArgs...) { + return + } + t.FailNow() +} + +// WithinDurationf asserts that the two times are within duration delta of each other. +// +// assert.WithinDurationf(t, time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") +func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.WithinDurationf(t, expected, actual, delta, msg, args...) { + return + } + t.FailNow() +} + +// WithinRange asserts that a time is within a time range (inclusive). +// +// assert.WithinRange(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second)) +func WithinRange(t TestingT, actual time.Time, start time.Time, end time.Time, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.WithinRange(t, actual, start, end, msgAndArgs...) { + return + } + t.FailNow() +} + +// WithinRangef asserts that a time is within a time range (inclusive). +// +// assert.WithinRangef(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second), "error message %s", "formatted") +func WithinRangef(t TestingT, actual time.Time, start time.Time, end time.Time, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.WithinRangef(t, actual, start, end, msg, args...) { + return + } + t.FailNow() +} + +// YAMLEq asserts that two YAML strings are equivalent. +func YAMLEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.YAMLEq(t, expected, actual, msgAndArgs...) { + return + } + t.FailNow() +} + +// YAMLEqf asserts that two YAML strings are equivalent. +func YAMLEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.YAMLEqf(t, expected, actual, msg, args...) { + return + } + t.FailNow() +} + +// Zero asserts that i is the zero value for its type. +func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Zero(t, i, msgAndArgs...) { + return + } + t.FailNow() +} + +// Zerof asserts that i is the zero value for its type. +func Zerof(t TestingT, i interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.Zerof(t, i, msg, args...) { + return + } + t.FailNow() +} diff --git a/vendor/github.com/stretchr/testify/require/require.go.tmpl b/vendor/github.com/stretchr/testify/require/require.go.tmpl new file mode 100644 index 00000000..55e42dde --- /dev/null +++ b/vendor/github.com/stretchr/testify/require/require.go.tmpl @@ -0,0 +1,6 @@ +{{.Comment}} +func {{.DocInfo.Name}}(t TestingT, {{.Params}}) { + if h, ok := t.(tHelper); ok { h.Helper() } + if assert.{{.DocInfo.Name}}(t, {{.ForwardedParams}}) { return } + t.FailNow() +} diff --git a/vendor/github.com/stretchr/testify/require/require_forward.go b/vendor/github.com/stretchr/testify/require/require_forward.go new file mode 100644 index 00000000..eee8310a --- /dev/null +++ b/vendor/github.com/stretchr/testify/require/require_forward.go @@ -0,0 +1,1622 @@ +// Code generated with github.com/stretchr/testify/_codegen; DO NOT EDIT. + +package require + +import ( + assert "github.com/stretchr/testify/assert" + http "net/http" + url "net/url" + time "time" +) + +// Condition uses a Comparison to assert a complex condition. +func (a *Assertions) Condition(comp assert.Comparison, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Condition(a.t, comp, msgAndArgs...) +} + +// Conditionf uses a Comparison to assert a complex condition. +func (a *Assertions) Conditionf(comp assert.Comparison, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Conditionf(a.t, comp, msg, args...) +} + +// Contains asserts that the specified string, list(array, slice...) or map contains the +// specified substring or element. +// +// a.Contains("Hello World", "World") +// a.Contains(["Hello", "World"], "World") +// a.Contains({"Hello": "World"}, "Hello") +func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Contains(a.t, s, contains, msgAndArgs...) +} + +// Containsf asserts that the specified string, list(array, slice...) or map contains the +// specified substring or element. +// +// a.Containsf("Hello World", "World", "error message %s", "formatted") +// a.Containsf(["Hello", "World"], "World", "error message %s", "formatted") +// a.Containsf({"Hello": "World"}, "Hello", "error message %s", "formatted") +func (a *Assertions) Containsf(s interface{}, contains interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Containsf(a.t, s, contains, msg, args...) +} + +// DirExists checks whether a directory exists in the given path. It also fails +// if the path is a file rather a directory or there is an error checking whether it exists. +func (a *Assertions) DirExists(path string, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + DirExists(a.t, path, msgAndArgs...) +} + +// DirExistsf checks whether a directory exists in the given path. It also fails +// if the path is a file rather a directory or there is an error checking whether it exists. +func (a *Assertions) DirExistsf(path string, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + DirExistsf(a.t, path, msg, args...) +} + +// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified +// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, +// the number of appearances of each of them in both lists should match. +// +// a.ElementsMatch([1, 3, 2, 3], [1, 3, 3, 2]) +func (a *Assertions) ElementsMatch(listA interface{}, listB interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + ElementsMatch(a.t, listA, listB, msgAndArgs...) +} + +// ElementsMatchf asserts that the specified listA(array, slice...) is equal to specified +// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, +// the number of appearances of each of them in both lists should match. +// +// a.ElementsMatchf([1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted") +func (a *Assertions) ElementsMatchf(listA interface{}, listB interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + ElementsMatchf(a.t, listA, listB, msg, args...) +} + +// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// a.Empty(obj) +func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Empty(a.t, object, msgAndArgs...) +} + +// Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// a.Emptyf(obj, "error message %s", "formatted") +func (a *Assertions) Emptyf(object interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Emptyf(a.t, object, msg, args...) +} + +// Equal asserts that two objects are equal. +// +// a.Equal(123, 123) +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). Function equality +// cannot be determined and will always fail. +func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Equal(a.t, expected, actual, msgAndArgs...) +} + +// EqualError asserts that a function returned an error (i.e. not `nil`) +// and that it is equal to the provided error. +// +// actualObj, err := SomeFunction() +// a.EqualError(err, expectedErrorString) +func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + EqualError(a.t, theError, errString, msgAndArgs...) +} + +// EqualErrorf asserts that a function returned an error (i.e. not `nil`) +// and that it is equal to the provided error. +// +// actualObj, err := SomeFunction() +// a.EqualErrorf(err, expectedErrorString, "error message %s", "formatted") +func (a *Assertions) EqualErrorf(theError error, errString string, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + EqualErrorf(a.t, theError, errString, msg, args...) +} + +// EqualExportedValues asserts that the types of two objects are equal and their public +// fields are also equal. This is useful for comparing structs that have private fields +// that could potentially differ. +// +// type S struct { +// Exported int +// notExported int +// } +// a.EqualExportedValues(S{1, 2}, S{1, 3}) => true +// a.EqualExportedValues(S{1, 2}, S{2, 3}) => false +func (a *Assertions) EqualExportedValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + EqualExportedValues(a.t, expected, actual, msgAndArgs...) +} + +// EqualExportedValuesf asserts that the types of two objects are equal and their public +// fields are also equal. This is useful for comparing structs that have private fields +// that could potentially differ. +// +// type S struct { +// Exported int +// notExported int +// } +// a.EqualExportedValuesf(S{1, 2}, S{1, 3}, "error message %s", "formatted") => true +// a.EqualExportedValuesf(S{1, 2}, S{2, 3}, "error message %s", "formatted") => false +func (a *Assertions) EqualExportedValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + EqualExportedValuesf(a.t, expected, actual, msg, args...) +} + +// EqualValues asserts that two objects are equal or convertible to the same types +// and equal. +// +// a.EqualValues(uint32(123), int32(123)) +func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + EqualValues(a.t, expected, actual, msgAndArgs...) +} + +// EqualValuesf asserts that two objects are equal or convertible to the same types +// and equal. +// +// a.EqualValuesf(uint32(123), int32(123), "error message %s", "formatted") +func (a *Assertions) EqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + EqualValuesf(a.t, expected, actual, msg, args...) +} + +// Equalf asserts that two objects are equal. +// +// a.Equalf(123, 123, "error message %s", "formatted") +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). Function equality +// cannot be determined and will always fail. +func (a *Assertions) Equalf(expected interface{}, actual interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Equalf(a.t, expected, actual, msg, args...) +} + +// Error asserts that a function returned an error (i.e. not `nil`). +// +// actualObj, err := SomeFunction() +// if a.Error(err) { +// assert.Equal(t, expectedError, err) +// } +func (a *Assertions) Error(err error, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Error(a.t, err, msgAndArgs...) +} + +// ErrorAs asserts that at least one of the errors in err's chain matches target, and if so, sets target to that error value. +// This is a wrapper for errors.As. +func (a *Assertions) ErrorAs(err error, target interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + ErrorAs(a.t, err, target, msgAndArgs...) +} + +// ErrorAsf asserts that at least one of the errors in err's chain matches target, and if so, sets target to that error value. +// This is a wrapper for errors.As. +func (a *Assertions) ErrorAsf(err error, target interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + ErrorAsf(a.t, err, target, msg, args...) +} + +// ErrorContains asserts that a function returned an error (i.e. not `nil`) +// and that the error contains the specified substring. +// +// actualObj, err := SomeFunction() +// a.ErrorContains(err, expectedErrorSubString) +func (a *Assertions) ErrorContains(theError error, contains string, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + ErrorContains(a.t, theError, contains, msgAndArgs...) +} + +// ErrorContainsf asserts that a function returned an error (i.e. not `nil`) +// and that the error contains the specified substring. +// +// actualObj, err := SomeFunction() +// a.ErrorContainsf(err, expectedErrorSubString, "error message %s", "formatted") +func (a *Assertions) ErrorContainsf(theError error, contains string, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + ErrorContainsf(a.t, theError, contains, msg, args...) +} + +// ErrorIs asserts that at least one of the errors in err's chain matches target. +// This is a wrapper for errors.Is. +func (a *Assertions) ErrorIs(err error, target error, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + ErrorIs(a.t, err, target, msgAndArgs...) +} + +// ErrorIsf asserts that at least one of the errors in err's chain matches target. +// This is a wrapper for errors.Is. +func (a *Assertions) ErrorIsf(err error, target error, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + ErrorIsf(a.t, err, target, msg, args...) +} + +// Errorf asserts that a function returned an error (i.e. not `nil`). +// +// actualObj, err := SomeFunction() +// if a.Errorf(err, "error message %s", "formatted") { +// assert.Equal(t, expectedErrorf, err) +// } +func (a *Assertions) Errorf(err error, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Errorf(a.t, err, msg, args...) +} + +// Eventually asserts that given condition will be met in waitFor time, +// periodically checking target function each tick. +// +// a.Eventually(func() bool { return true; }, time.Second, 10*time.Millisecond) +func (a *Assertions) Eventually(condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Eventually(a.t, condition, waitFor, tick, msgAndArgs...) +} + +// EventuallyWithT asserts that given condition will be met in waitFor time, +// periodically checking target function each tick. In contrast to Eventually, +// it supplies a CollectT to the condition function, so that the condition +// function can use the CollectT to call other assertions. +// The condition is considered "met" if no errors are raised in a tick. +// The supplied CollectT collects all errors from one tick (if there are any). +// If the condition is not met before waitFor, the collected errors of +// the last tick are copied to t. +// +// externalValue := false +// go func() { +// time.Sleep(8*time.Second) +// externalValue = true +// }() +// a.EventuallyWithT(func(c *assert.CollectT) { +// // add assertions as needed; any assertion failure will fail the current tick +// assert.True(c, externalValue, "expected 'externalValue' to be true") +// }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false") +func (a *Assertions) EventuallyWithT(condition func(collect *assert.CollectT), waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + EventuallyWithT(a.t, condition, waitFor, tick, msgAndArgs...) +} + +// EventuallyWithTf asserts that given condition will be met in waitFor time, +// periodically checking target function each tick. In contrast to Eventually, +// it supplies a CollectT to the condition function, so that the condition +// function can use the CollectT to call other assertions. +// The condition is considered "met" if no errors are raised in a tick. +// The supplied CollectT collects all errors from one tick (if there are any). +// If the condition is not met before waitFor, the collected errors of +// the last tick are copied to t. +// +// externalValue := false +// go func() { +// time.Sleep(8*time.Second) +// externalValue = true +// }() +// a.EventuallyWithTf(func(c *assert.CollectT, "error message %s", "formatted") { +// // add assertions as needed; any assertion failure will fail the current tick +// assert.True(c, externalValue, "expected 'externalValue' to be true") +// }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false") +func (a *Assertions) EventuallyWithTf(condition func(collect *assert.CollectT), waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + EventuallyWithTf(a.t, condition, waitFor, tick, msg, args...) +} + +// Eventuallyf asserts that given condition will be met in waitFor time, +// periodically checking target function each tick. +// +// a.Eventuallyf(func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") +func (a *Assertions) Eventuallyf(condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Eventuallyf(a.t, condition, waitFor, tick, msg, args...) +} + +// Exactly asserts that two objects are equal in value and type. +// +// a.Exactly(int32(123), int64(123)) +func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Exactly(a.t, expected, actual, msgAndArgs...) +} + +// Exactlyf asserts that two objects are equal in value and type. +// +// a.Exactlyf(int32(123), int64(123), "error message %s", "formatted") +func (a *Assertions) Exactlyf(expected interface{}, actual interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Exactlyf(a.t, expected, actual, msg, args...) +} + +// Fail reports a failure through +func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Fail(a.t, failureMessage, msgAndArgs...) +} + +// FailNow fails test +func (a *Assertions) FailNow(failureMessage string, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + FailNow(a.t, failureMessage, msgAndArgs...) +} + +// FailNowf fails test +func (a *Assertions) FailNowf(failureMessage string, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + FailNowf(a.t, failureMessage, msg, args...) +} + +// Failf reports a failure through +func (a *Assertions) Failf(failureMessage string, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Failf(a.t, failureMessage, msg, args...) +} + +// False asserts that the specified value is false. +// +// a.False(myBool) +func (a *Assertions) False(value bool, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + False(a.t, value, msgAndArgs...) +} + +// Falsef asserts that the specified value is false. +// +// a.Falsef(myBool, "error message %s", "formatted") +func (a *Assertions) Falsef(value bool, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Falsef(a.t, value, msg, args...) +} + +// FileExists checks whether a file exists in the given path. It also fails if +// the path points to a directory or there is an error when trying to check the file. +func (a *Assertions) FileExists(path string, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + FileExists(a.t, path, msgAndArgs...) +} + +// FileExistsf checks whether a file exists in the given path. It also fails if +// the path points to a directory or there is an error when trying to check the file. +func (a *Assertions) FileExistsf(path string, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + FileExistsf(a.t, path, msg, args...) +} + +// Greater asserts that the first element is greater than the second +// +// a.Greater(2, 1) +// a.Greater(float64(2), float64(1)) +// a.Greater("b", "a") +func (a *Assertions) Greater(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Greater(a.t, e1, e2, msgAndArgs...) +} + +// GreaterOrEqual asserts that the first element is greater than or equal to the second +// +// a.GreaterOrEqual(2, 1) +// a.GreaterOrEqual(2, 2) +// a.GreaterOrEqual("b", "a") +// a.GreaterOrEqual("b", "b") +func (a *Assertions) GreaterOrEqual(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + GreaterOrEqual(a.t, e1, e2, msgAndArgs...) +} + +// GreaterOrEqualf asserts that the first element is greater than or equal to the second +// +// a.GreaterOrEqualf(2, 1, "error message %s", "formatted") +// a.GreaterOrEqualf(2, 2, "error message %s", "formatted") +// a.GreaterOrEqualf("b", "a", "error message %s", "formatted") +// a.GreaterOrEqualf("b", "b", "error message %s", "formatted") +func (a *Assertions) GreaterOrEqualf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + GreaterOrEqualf(a.t, e1, e2, msg, args...) +} + +// Greaterf asserts that the first element is greater than the second +// +// a.Greaterf(2, 1, "error message %s", "formatted") +// a.Greaterf(float64(2), float64(1), "error message %s", "formatted") +// a.Greaterf("b", "a", "error message %s", "formatted") +func (a *Assertions) Greaterf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Greaterf(a.t, e1, e2, msg, args...) +} + +// HTTPBodyContains asserts that a specified handler returns a +// body that contains a string. +// +// a.HTTPBodyContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + HTTPBodyContains(a.t, handler, method, url, values, str, msgAndArgs...) +} + +// HTTPBodyContainsf asserts that a specified handler returns a +// body that contains a string. +// +// a.HTTPBodyContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPBodyContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + HTTPBodyContainsf(a.t, handler, method, url, values, str, msg, args...) +} + +// HTTPBodyNotContains asserts that a specified handler returns a +// body that does not contain a string. +// +// a.HTTPBodyNotContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + HTTPBodyNotContains(a.t, handler, method, url, values, str, msgAndArgs...) +} + +// HTTPBodyNotContainsf asserts that a specified handler returns a +// body that does not contain a string. +// +// a.HTTPBodyNotContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPBodyNotContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + HTTPBodyNotContainsf(a.t, handler, method, url, values, str, msg, args...) +} + +// HTTPError asserts that a specified handler returns an error status code. +// +// a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + HTTPError(a.t, handler, method, url, values, msgAndArgs...) +} + +// HTTPErrorf asserts that a specified handler returns an error status code. +// +// a.HTTPErrorf(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPErrorf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + HTTPErrorf(a.t, handler, method, url, values, msg, args...) +} + +// HTTPRedirect asserts that a specified handler returns a redirect status code. +// +// a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + HTTPRedirect(a.t, handler, method, url, values, msgAndArgs...) +} + +// HTTPRedirectf asserts that a specified handler returns a redirect status code. +// +// a.HTTPRedirectf(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPRedirectf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + HTTPRedirectf(a.t, handler, method, url, values, msg, args...) +} + +// HTTPStatusCode asserts that a specified handler returns a specified status code. +// +// a.HTTPStatusCode(myHandler, "GET", "/notImplemented", nil, 501) +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPStatusCode(handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + HTTPStatusCode(a.t, handler, method, url, values, statuscode, msgAndArgs...) +} + +// HTTPStatusCodef asserts that a specified handler returns a specified status code. +// +// a.HTTPStatusCodef(myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPStatusCodef(handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + HTTPStatusCodef(a.t, handler, method, url, values, statuscode, msg, args...) +} + +// HTTPSuccess asserts that a specified handler returns a success status code. +// +// a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + HTTPSuccess(a.t, handler, method, url, values, msgAndArgs...) +} + +// HTTPSuccessf asserts that a specified handler returns a success status code. +// +// a.HTTPSuccessf(myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPSuccessf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + HTTPSuccessf(a.t, handler, method, url, values, msg, args...) +} + +// Implements asserts that an object is implemented by the specified interface. +// +// a.Implements((*MyInterface)(nil), new(MyObject)) +func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Implements(a.t, interfaceObject, object, msgAndArgs...) +} + +// Implementsf asserts that an object is implemented by the specified interface. +// +// a.Implementsf((*MyInterface)(nil), new(MyObject), "error message %s", "formatted") +func (a *Assertions) Implementsf(interfaceObject interface{}, object interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Implementsf(a.t, interfaceObject, object, msg, args...) +} + +// InDelta asserts that the two numerals are within delta of each other. +// +// a.InDelta(math.Pi, 22/7.0, 0.01) +func (a *Assertions) InDelta(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + InDelta(a.t, expected, actual, delta, msgAndArgs...) +} + +// InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. +func (a *Assertions) InDeltaMapValues(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + InDeltaMapValues(a.t, expected, actual, delta, msgAndArgs...) +} + +// InDeltaMapValuesf is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. +func (a *Assertions) InDeltaMapValuesf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + InDeltaMapValuesf(a.t, expected, actual, delta, msg, args...) +} + +// InDeltaSlice is the same as InDelta, except it compares two slices. +func (a *Assertions) InDeltaSlice(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + InDeltaSlice(a.t, expected, actual, delta, msgAndArgs...) +} + +// InDeltaSlicef is the same as InDelta, except it compares two slices. +func (a *Assertions) InDeltaSlicef(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + InDeltaSlicef(a.t, expected, actual, delta, msg, args...) +} + +// InDeltaf asserts that the two numerals are within delta of each other. +// +// a.InDeltaf(math.Pi, 22/7.0, 0.01, "error message %s", "formatted") +func (a *Assertions) InDeltaf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + InDeltaf(a.t, expected, actual, delta, msg, args...) +} + +// InEpsilon asserts that expected and actual have a relative error less than epsilon +func (a *Assertions) InEpsilon(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...) +} + +// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. +func (a *Assertions) InEpsilonSlice(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + InEpsilonSlice(a.t, expected, actual, epsilon, msgAndArgs...) +} + +// InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices. +func (a *Assertions) InEpsilonSlicef(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + InEpsilonSlicef(a.t, expected, actual, epsilon, msg, args...) +} + +// InEpsilonf asserts that expected and actual have a relative error less than epsilon +func (a *Assertions) InEpsilonf(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + InEpsilonf(a.t, expected, actual, epsilon, msg, args...) +} + +// IsDecreasing asserts that the collection is decreasing +// +// a.IsDecreasing([]int{2, 1, 0}) +// a.IsDecreasing([]float{2, 1}) +// a.IsDecreasing([]string{"b", "a"}) +func (a *Assertions) IsDecreasing(object interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + IsDecreasing(a.t, object, msgAndArgs...) +} + +// IsDecreasingf asserts that the collection is decreasing +// +// a.IsDecreasingf([]int{2, 1, 0}, "error message %s", "formatted") +// a.IsDecreasingf([]float{2, 1}, "error message %s", "formatted") +// a.IsDecreasingf([]string{"b", "a"}, "error message %s", "formatted") +func (a *Assertions) IsDecreasingf(object interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + IsDecreasingf(a.t, object, msg, args...) +} + +// IsIncreasing asserts that the collection is increasing +// +// a.IsIncreasing([]int{1, 2, 3}) +// a.IsIncreasing([]float{1, 2}) +// a.IsIncreasing([]string{"a", "b"}) +func (a *Assertions) IsIncreasing(object interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + IsIncreasing(a.t, object, msgAndArgs...) +} + +// IsIncreasingf asserts that the collection is increasing +// +// a.IsIncreasingf([]int{1, 2, 3}, "error message %s", "formatted") +// a.IsIncreasingf([]float{1, 2}, "error message %s", "formatted") +// a.IsIncreasingf([]string{"a", "b"}, "error message %s", "formatted") +func (a *Assertions) IsIncreasingf(object interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + IsIncreasingf(a.t, object, msg, args...) +} + +// IsNonDecreasing asserts that the collection is not decreasing +// +// a.IsNonDecreasing([]int{1, 1, 2}) +// a.IsNonDecreasing([]float{1, 2}) +// a.IsNonDecreasing([]string{"a", "b"}) +func (a *Assertions) IsNonDecreasing(object interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + IsNonDecreasing(a.t, object, msgAndArgs...) +} + +// IsNonDecreasingf asserts that the collection is not decreasing +// +// a.IsNonDecreasingf([]int{1, 1, 2}, "error message %s", "formatted") +// a.IsNonDecreasingf([]float{1, 2}, "error message %s", "formatted") +// a.IsNonDecreasingf([]string{"a", "b"}, "error message %s", "formatted") +func (a *Assertions) IsNonDecreasingf(object interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + IsNonDecreasingf(a.t, object, msg, args...) +} + +// IsNonIncreasing asserts that the collection is not increasing +// +// a.IsNonIncreasing([]int{2, 1, 1}) +// a.IsNonIncreasing([]float{2, 1}) +// a.IsNonIncreasing([]string{"b", "a"}) +func (a *Assertions) IsNonIncreasing(object interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + IsNonIncreasing(a.t, object, msgAndArgs...) +} + +// IsNonIncreasingf asserts that the collection is not increasing +// +// a.IsNonIncreasingf([]int{2, 1, 1}, "error message %s", "formatted") +// a.IsNonIncreasingf([]float{2, 1}, "error message %s", "formatted") +// a.IsNonIncreasingf([]string{"b", "a"}, "error message %s", "formatted") +func (a *Assertions) IsNonIncreasingf(object interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + IsNonIncreasingf(a.t, object, msg, args...) +} + +// IsType asserts that the specified objects are of the same type. +func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + IsType(a.t, expectedType, object, msgAndArgs...) +} + +// IsTypef asserts that the specified objects are of the same type. +func (a *Assertions) IsTypef(expectedType interface{}, object interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + IsTypef(a.t, expectedType, object, msg, args...) +} + +// JSONEq asserts that two JSON strings are equivalent. +// +// a.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) +func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + JSONEq(a.t, expected, actual, msgAndArgs...) +} + +// JSONEqf asserts that two JSON strings are equivalent. +// +// a.JSONEqf(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") +func (a *Assertions) JSONEqf(expected string, actual string, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + JSONEqf(a.t, expected, actual, msg, args...) +} + +// Len asserts that the specified object has specific length. +// Len also fails if the object has a type that len() not accept. +// +// a.Len(mySlice, 3) +func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Len(a.t, object, length, msgAndArgs...) +} + +// Lenf asserts that the specified object has specific length. +// Lenf also fails if the object has a type that len() not accept. +// +// a.Lenf(mySlice, 3, "error message %s", "formatted") +func (a *Assertions) Lenf(object interface{}, length int, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Lenf(a.t, object, length, msg, args...) +} + +// Less asserts that the first element is less than the second +// +// a.Less(1, 2) +// a.Less(float64(1), float64(2)) +// a.Less("a", "b") +func (a *Assertions) Less(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Less(a.t, e1, e2, msgAndArgs...) +} + +// LessOrEqual asserts that the first element is less than or equal to the second +// +// a.LessOrEqual(1, 2) +// a.LessOrEqual(2, 2) +// a.LessOrEqual("a", "b") +// a.LessOrEqual("b", "b") +func (a *Assertions) LessOrEqual(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + LessOrEqual(a.t, e1, e2, msgAndArgs...) +} + +// LessOrEqualf asserts that the first element is less than or equal to the second +// +// a.LessOrEqualf(1, 2, "error message %s", "formatted") +// a.LessOrEqualf(2, 2, "error message %s", "formatted") +// a.LessOrEqualf("a", "b", "error message %s", "formatted") +// a.LessOrEqualf("b", "b", "error message %s", "formatted") +func (a *Assertions) LessOrEqualf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + LessOrEqualf(a.t, e1, e2, msg, args...) +} + +// Lessf asserts that the first element is less than the second +// +// a.Lessf(1, 2, "error message %s", "formatted") +// a.Lessf(float64(1), float64(2), "error message %s", "formatted") +// a.Lessf("a", "b", "error message %s", "formatted") +func (a *Assertions) Lessf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Lessf(a.t, e1, e2, msg, args...) +} + +// Negative asserts that the specified element is negative +// +// a.Negative(-1) +// a.Negative(-1.23) +func (a *Assertions) Negative(e interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Negative(a.t, e, msgAndArgs...) +} + +// Negativef asserts that the specified element is negative +// +// a.Negativef(-1, "error message %s", "formatted") +// a.Negativef(-1.23, "error message %s", "formatted") +func (a *Assertions) Negativef(e interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Negativef(a.t, e, msg, args...) +} + +// Never asserts that the given condition doesn't satisfy in waitFor time, +// periodically checking the target function each tick. +// +// a.Never(func() bool { return false; }, time.Second, 10*time.Millisecond) +func (a *Assertions) Never(condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Never(a.t, condition, waitFor, tick, msgAndArgs...) +} + +// Neverf asserts that the given condition doesn't satisfy in waitFor time, +// periodically checking the target function each tick. +// +// a.Neverf(func() bool { return false; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") +func (a *Assertions) Neverf(condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Neverf(a.t, condition, waitFor, tick, msg, args...) +} + +// Nil asserts that the specified object is nil. +// +// a.Nil(err) +func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Nil(a.t, object, msgAndArgs...) +} + +// Nilf asserts that the specified object is nil. +// +// a.Nilf(err, "error message %s", "formatted") +func (a *Assertions) Nilf(object interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Nilf(a.t, object, msg, args...) +} + +// NoDirExists checks whether a directory does not exist in the given path. +// It fails if the path points to an existing _directory_ only. +func (a *Assertions) NoDirExists(path string, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NoDirExists(a.t, path, msgAndArgs...) +} + +// NoDirExistsf checks whether a directory does not exist in the given path. +// It fails if the path points to an existing _directory_ only. +func (a *Assertions) NoDirExistsf(path string, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NoDirExistsf(a.t, path, msg, args...) +} + +// NoError asserts that a function returned no error (i.e. `nil`). +// +// actualObj, err := SomeFunction() +// if a.NoError(err) { +// assert.Equal(t, expectedObj, actualObj) +// } +func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NoError(a.t, err, msgAndArgs...) +} + +// NoErrorf asserts that a function returned no error (i.e. `nil`). +// +// actualObj, err := SomeFunction() +// if a.NoErrorf(err, "error message %s", "formatted") { +// assert.Equal(t, expectedObj, actualObj) +// } +func (a *Assertions) NoErrorf(err error, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NoErrorf(a.t, err, msg, args...) +} + +// NoFileExists checks whether a file does not exist in a given path. It fails +// if the path points to an existing _file_ only. +func (a *Assertions) NoFileExists(path string, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NoFileExists(a.t, path, msgAndArgs...) +} + +// NoFileExistsf checks whether a file does not exist in a given path. It fails +// if the path points to an existing _file_ only. +func (a *Assertions) NoFileExistsf(path string, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NoFileExistsf(a.t, path, msg, args...) +} + +// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the +// specified substring or element. +// +// a.NotContains("Hello World", "Earth") +// a.NotContains(["Hello", "World"], "Earth") +// a.NotContains({"Hello": "World"}, "Earth") +func (a *Assertions) NotContains(s interface{}, contains interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotContains(a.t, s, contains, msgAndArgs...) +} + +// NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the +// specified substring or element. +// +// a.NotContainsf("Hello World", "Earth", "error message %s", "formatted") +// a.NotContainsf(["Hello", "World"], "Earth", "error message %s", "formatted") +// a.NotContainsf({"Hello": "World"}, "Earth", "error message %s", "formatted") +func (a *Assertions) NotContainsf(s interface{}, contains interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotContainsf(a.t, s, contains, msg, args...) +} + +// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// if a.NotEmpty(obj) { +// assert.Equal(t, "two", obj[1]) +// } +func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotEmpty(a.t, object, msgAndArgs...) +} + +// NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// if a.NotEmptyf(obj, "error message %s", "formatted") { +// assert.Equal(t, "two", obj[1]) +// } +func (a *Assertions) NotEmptyf(object interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotEmptyf(a.t, object, msg, args...) +} + +// NotEqual asserts that the specified values are NOT equal. +// +// a.NotEqual(obj1, obj2) +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). +func (a *Assertions) NotEqual(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotEqual(a.t, expected, actual, msgAndArgs...) +} + +// NotEqualValues asserts that two objects are not equal even when converted to the same type +// +// a.NotEqualValues(obj1, obj2) +func (a *Assertions) NotEqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotEqualValues(a.t, expected, actual, msgAndArgs...) +} + +// NotEqualValuesf asserts that two objects are not equal even when converted to the same type +// +// a.NotEqualValuesf(obj1, obj2, "error message %s", "formatted") +func (a *Assertions) NotEqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotEqualValuesf(a.t, expected, actual, msg, args...) +} + +// NotEqualf asserts that the specified values are NOT equal. +// +// a.NotEqualf(obj1, obj2, "error message %s", "formatted") +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). +func (a *Assertions) NotEqualf(expected interface{}, actual interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotEqualf(a.t, expected, actual, msg, args...) +} + +// NotErrorIs asserts that at none of the errors in err's chain matches target. +// This is a wrapper for errors.Is. +func (a *Assertions) NotErrorIs(err error, target error, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotErrorIs(a.t, err, target, msgAndArgs...) +} + +// NotErrorIsf asserts that at none of the errors in err's chain matches target. +// This is a wrapper for errors.Is. +func (a *Assertions) NotErrorIsf(err error, target error, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotErrorIsf(a.t, err, target, msg, args...) +} + +// NotImplements asserts that an object does not implement the specified interface. +// +// a.NotImplements((*MyInterface)(nil), new(MyObject)) +func (a *Assertions) NotImplements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotImplements(a.t, interfaceObject, object, msgAndArgs...) +} + +// NotImplementsf asserts that an object does not implement the specified interface. +// +// a.NotImplementsf((*MyInterface)(nil), new(MyObject), "error message %s", "formatted") +func (a *Assertions) NotImplementsf(interfaceObject interface{}, object interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotImplementsf(a.t, interfaceObject, object, msg, args...) +} + +// NotNil asserts that the specified object is not nil. +// +// a.NotNil(err) +func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotNil(a.t, object, msgAndArgs...) +} + +// NotNilf asserts that the specified object is not nil. +// +// a.NotNilf(err, "error message %s", "formatted") +func (a *Assertions) NotNilf(object interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotNilf(a.t, object, msg, args...) +} + +// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. +// +// a.NotPanics(func(){ RemainCalm() }) +func (a *Assertions) NotPanics(f assert.PanicTestFunc, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotPanics(a.t, f, msgAndArgs...) +} + +// NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. +// +// a.NotPanicsf(func(){ RemainCalm() }, "error message %s", "formatted") +func (a *Assertions) NotPanicsf(f assert.PanicTestFunc, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotPanicsf(a.t, f, msg, args...) +} + +// NotRegexp asserts that a specified regexp does not match a string. +// +// a.NotRegexp(regexp.MustCompile("starts"), "it's starting") +// a.NotRegexp("^start", "it's not starting") +func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotRegexp(a.t, rx, str, msgAndArgs...) +} + +// NotRegexpf asserts that a specified regexp does not match a string. +// +// a.NotRegexpf(regexp.MustCompile("starts"), "it's starting", "error message %s", "formatted") +// a.NotRegexpf("^start", "it's not starting", "error message %s", "formatted") +func (a *Assertions) NotRegexpf(rx interface{}, str interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotRegexpf(a.t, rx, str, msg, args...) +} + +// NotSame asserts that two pointers do not reference the same object. +// +// a.NotSame(ptr1, ptr2) +// +// Both arguments must be pointer variables. Pointer variable sameness is +// determined based on the equality of both type and value. +func (a *Assertions) NotSame(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotSame(a.t, expected, actual, msgAndArgs...) +} + +// NotSamef asserts that two pointers do not reference the same object. +// +// a.NotSamef(ptr1, ptr2, "error message %s", "formatted") +// +// Both arguments must be pointer variables. Pointer variable sameness is +// determined based on the equality of both type and value. +func (a *Assertions) NotSamef(expected interface{}, actual interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotSamef(a.t, expected, actual, msg, args...) +} + +// NotSubset asserts that the specified list(array, slice...) or map does NOT +// contain all elements given in the specified subset list(array, slice...) or +// map. +// +// a.NotSubset([1, 3, 4], [1, 2]) +// a.NotSubset({"x": 1, "y": 2}, {"z": 3}) +func (a *Assertions) NotSubset(list interface{}, subset interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotSubset(a.t, list, subset, msgAndArgs...) +} + +// NotSubsetf asserts that the specified list(array, slice...) or map does NOT +// contain all elements given in the specified subset list(array, slice...) or +// map. +// +// a.NotSubsetf([1, 3, 4], [1, 2], "error message %s", "formatted") +// a.NotSubsetf({"x": 1, "y": 2}, {"z": 3}, "error message %s", "formatted") +func (a *Assertions) NotSubsetf(list interface{}, subset interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotSubsetf(a.t, list, subset, msg, args...) +} + +// NotZero asserts that i is not the zero value for its type. +func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotZero(a.t, i, msgAndArgs...) +} + +// NotZerof asserts that i is not the zero value for its type. +func (a *Assertions) NotZerof(i interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotZerof(a.t, i, msg, args...) +} + +// Panics asserts that the code inside the specified PanicTestFunc panics. +// +// a.Panics(func(){ GoCrazy() }) +func (a *Assertions) Panics(f assert.PanicTestFunc, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Panics(a.t, f, msgAndArgs...) +} + +// PanicsWithError asserts that the code inside the specified PanicTestFunc +// panics, and that the recovered panic value is an error that satisfies the +// EqualError comparison. +// +// a.PanicsWithError("crazy error", func(){ GoCrazy() }) +func (a *Assertions) PanicsWithError(errString string, f assert.PanicTestFunc, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + PanicsWithError(a.t, errString, f, msgAndArgs...) +} + +// PanicsWithErrorf asserts that the code inside the specified PanicTestFunc +// panics, and that the recovered panic value is an error that satisfies the +// EqualError comparison. +// +// a.PanicsWithErrorf("crazy error", func(){ GoCrazy() }, "error message %s", "formatted") +func (a *Assertions) PanicsWithErrorf(errString string, f assert.PanicTestFunc, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + PanicsWithErrorf(a.t, errString, f, msg, args...) +} + +// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that +// the recovered panic value equals the expected panic value. +// +// a.PanicsWithValue("crazy error", func(){ GoCrazy() }) +func (a *Assertions) PanicsWithValue(expected interface{}, f assert.PanicTestFunc, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + PanicsWithValue(a.t, expected, f, msgAndArgs...) +} + +// PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that +// the recovered panic value equals the expected panic value. +// +// a.PanicsWithValuef("crazy error", func(){ GoCrazy() }, "error message %s", "formatted") +func (a *Assertions) PanicsWithValuef(expected interface{}, f assert.PanicTestFunc, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + PanicsWithValuef(a.t, expected, f, msg, args...) +} + +// Panicsf asserts that the code inside the specified PanicTestFunc panics. +// +// a.Panicsf(func(){ GoCrazy() }, "error message %s", "formatted") +func (a *Assertions) Panicsf(f assert.PanicTestFunc, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Panicsf(a.t, f, msg, args...) +} + +// Positive asserts that the specified element is positive +// +// a.Positive(1) +// a.Positive(1.23) +func (a *Assertions) Positive(e interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Positive(a.t, e, msgAndArgs...) +} + +// Positivef asserts that the specified element is positive +// +// a.Positivef(1, "error message %s", "formatted") +// a.Positivef(1.23, "error message %s", "formatted") +func (a *Assertions) Positivef(e interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Positivef(a.t, e, msg, args...) +} + +// Regexp asserts that a specified regexp matches a string. +// +// a.Regexp(regexp.MustCompile("start"), "it's starting") +// a.Regexp("start...$", "it's not starting") +func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Regexp(a.t, rx, str, msgAndArgs...) +} + +// Regexpf asserts that a specified regexp matches a string. +// +// a.Regexpf(regexp.MustCompile("start"), "it's starting", "error message %s", "formatted") +// a.Regexpf("start...$", "it's not starting", "error message %s", "formatted") +func (a *Assertions) Regexpf(rx interface{}, str interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Regexpf(a.t, rx, str, msg, args...) +} + +// Same asserts that two pointers reference the same object. +// +// a.Same(ptr1, ptr2) +// +// Both arguments must be pointer variables. Pointer variable sameness is +// determined based on the equality of both type and value. +func (a *Assertions) Same(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Same(a.t, expected, actual, msgAndArgs...) +} + +// Samef asserts that two pointers reference the same object. +// +// a.Samef(ptr1, ptr2, "error message %s", "formatted") +// +// Both arguments must be pointer variables. Pointer variable sameness is +// determined based on the equality of both type and value. +func (a *Assertions) Samef(expected interface{}, actual interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Samef(a.t, expected, actual, msg, args...) +} + +// Subset asserts that the specified list(array, slice...) or map contains all +// elements given in the specified subset list(array, slice...) or map. +// +// a.Subset([1, 2, 3], [1, 2]) +// a.Subset({"x": 1, "y": 2}, {"x": 1}) +func (a *Assertions) Subset(list interface{}, subset interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Subset(a.t, list, subset, msgAndArgs...) +} + +// Subsetf asserts that the specified list(array, slice...) or map contains all +// elements given in the specified subset list(array, slice...) or map. +// +// a.Subsetf([1, 2, 3], [1, 2], "error message %s", "formatted") +// a.Subsetf({"x": 1, "y": 2}, {"x": 1}, "error message %s", "formatted") +func (a *Assertions) Subsetf(list interface{}, subset interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Subsetf(a.t, list, subset, msg, args...) +} + +// True asserts that the specified value is true. +// +// a.True(myBool) +func (a *Assertions) True(value bool, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + True(a.t, value, msgAndArgs...) +} + +// Truef asserts that the specified value is true. +// +// a.Truef(myBool, "error message %s", "formatted") +func (a *Assertions) Truef(value bool, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Truef(a.t, value, msg, args...) +} + +// WithinDuration asserts that the two times are within duration delta of each other. +// +// a.WithinDuration(time.Now(), time.Now(), 10*time.Second) +func (a *Assertions) WithinDuration(expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + WithinDuration(a.t, expected, actual, delta, msgAndArgs...) +} + +// WithinDurationf asserts that the two times are within duration delta of each other. +// +// a.WithinDurationf(time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") +func (a *Assertions) WithinDurationf(expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + WithinDurationf(a.t, expected, actual, delta, msg, args...) +} + +// WithinRange asserts that a time is within a time range (inclusive). +// +// a.WithinRange(time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second)) +func (a *Assertions) WithinRange(actual time.Time, start time.Time, end time.Time, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + WithinRange(a.t, actual, start, end, msgAndArgs...) +} + +// WithinRangef asserts that a time is within a time range (inclusive). +// +// a.WithinRangef(time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second), "error message %s", "formatted") +func (a *Assertions) WithinRangef(actual time.Time, start time.Time, end time.Time, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + WithinRangef(a.t, actual, start, end, msg, args...) +} + +// YAMLEq asserts that two YAML strings are equivalent. +func (a *Assertions) YAMLEq(expected string, actual string, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + YAMLEq(a.t, expected, actual, msgAndArgs...) +} + +// YAMLEqf asserts that two YAML strings are equivalent. +func (a *Assertions) YAMLEqf(expected string, actual string, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + YAMLEqf(a.t, expected, actual, msg, args...) +} + +// Zero asserts that i is the zero value for its type. +func (a *Assertions) Zero(i interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Zero(a.t, i, msgAndArgs...) +} + +// Zerof asserts that i is the zero value for its type. +func (a *Assertions) Zerof(i interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + Zerof(a.t, i, msg, args...) +} diff --git a/vendor/github.com/stretchr/testify/require/require_forward.go.tmpl b/vendor/github.com/stretchr/testify/require/require_forward.go.tmpl new file mode 100644 index 00000000..54124df1 --- /dev/null +++ b/vendor/github.com/stretchr/testify/require/require_forward.go.tmpl @@ -0,0 +1,5 @@ +{{.CommentWithoutT "a"}} +func (a *Assertions) {{.DocInfo.Name}}({{.Params}}) { + if h, ok := a.t.(tHelper); ok { h.Helper() } + {{.DocInfo.Name}}(a.t, {{.ForwardedParams}}) +} diff --git a/vendor/github.com/stretchr/testify/require/requirements.go b/vendor/github.com/stretchr/testify/require/requirements.go new file mode 100644 index 00000000..91772dfe --- /dev/null +++ b/vendor/github.com/stretchr/testify/require/requirements.go @@ -0,0 +1,29 @@ +package require + +// TestingT is an interface wrapper around *testing.T +type TestingT interface { + Errorf(format string, args ...interface{}) + FailNow() +} + +type tHelper interface { + Helper() +} + +// ComparisonAssertionFunc is a common function prototype when comparing two values. Can be useful +// for table driven tests. +type ComparisonAssertionFunc func(TestingT, interface{}, interface{}, ...interface{}) + +// ValueAssertionFunc is a common function prototype when validating a single value. Can be useful +// for table driven tests. +type ValueAssertionFunc func(TestingT, interface{}, ...interface{}) + +// BoolAssertionFunc is a common function prototype when validating a bool value. Can be useful +// for table driven tests. +type BoolAssertionFunc func(TestingT, bool, ...interface{}) + +// ErrorAssertionFunc is a common function prototype when validating an error value. Can be useful +// for table driven tests. +type ErrorAssertionFunc func(TestingT, error, ...interface{}) + +//go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=require -template=require.go.tmpl -include-format-funcs" diff --git a/vendor/github.com/stretchr/testify/suite/doc.go b/vendor/github.com/stretchr/testify/suite/doc.go new file mode 100644 index 00000000..8d55a3aa --- /dev/null +++ b/vendor/github.com/stretchr/testify/suite/doc.go @@ -0,0 +1,66 @@ +// Package suite contains logic for creating testing suite structs +// and running the methods on those structs as tests. The most useful +// piece of this package is that you can create setup/teardown methods +// on your testing suites, which will run before/after the whole suite +// or individual tests (depending on which interface(s) you +// implement). +// +// A testing suite is usually built by first extending the built-in +// suite functionality from suite.Suite in testify. Alternatively, +// you could reproduce that logic on your own if you wanted (you +// just need to implement the TestingSuite interface from +// suite/interfaces.go). +// +// After that, you can implement any of the interfaces in +// suite/interfaces.go to add setup/teardown functionality to your +// suite, and add any methods that start with "Test" to add tests. +// Methods that do not match any suite interfaces and do not begin +// with "Test" will not be run by testify, and can safely be used as +// helper methods. +// +// Once you've built your testing suite, you need to run the suite +// (using suite.Run from testify) inside any function that matches the +// identity that "go test" is already looking for (i.e. +// func(*testing.T)). +// +// Regular expression to select test suites specified command-line +// argument "-run". Regular expression to select the methods +// of test suites specified command-line argument "-m". +// Suite object has assertion methods. +// +// A crude example: +// +// // Basic imports +// import ( +// "testing" +// "github.com/stretchr/testify/assert" +// "github.com/stretchr/testify/suite" +// ) +// +// // Define the suite, and absorb the built-in basic suite +// // functionality from testify - including a T() method which +// // returns the current testing context +// type ExampleTestSuite struct { +// suite.Suite +// VariableThatShouldStartAtFive int +// } +// +// // Make sure that VariableThatShouldStartAtFive is set to five +// // before each test +// func (suite *ExampleTestSuite) SetupTest() { +// suite.VariableThatShouldStartAtFive = 5 +// } +// +// // All methods that begin with "Test" are run as tests within a +// // suite. +// func (suite *ExampleTestSuite) TestExample() { +// assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive) +// suite.Equal(5, suite.VariableThatShouldStartAtFive) +// } +// +// // In order for 'go test' to run this suite, we need to create +// // a normal test function and pass our suite to suite.Run +// func TestExampleTestSuite(t *testing.T) { +// suite.Run(t, new(ExampleTestSuite)) +// } +package suite diff --git a/vendor/github.com/stretchr/testify/suite/interfaces.go b/vendor/github.com/stretchr/testify/suite/interfaces.go new file mode 100644 index 00000000..fed037d7 --- /dev/null +++ b/vendor/github.com/stretchr/testify/suite/interfaces.go @@ -0,0 +1,66 @@ +package suite + +import "testing" + +// TestingSuite can store and return the current *testing.T context +// generated by 'go test'. +type TestingSuite interface { + T() *testing.T + SetT(*testing.T) + SetS(suite TestingSuite) +} + +// SetupAllSuite has a SetupSuite method, which will run before the +// tests in the suite are run. +type SetupAllSuite interface { + SetupSuite() +} + +// SetupTestSuite has a SetupTest method, which will run before each +// test in the suite. +type SetupTestSuite interface { + SetupTest() +} + +// TearDownAllSuite has a TearDownSuite method, which will run after +// all the tests in the suite have been run. +type TearDownAllSuite interface { + TearDownSuite() +} + +// TearDownTestSuite has a TearDownTest method, which will run after +// each test in the suite. +type TearDownTestSuite interface { + TearDownTest() +} + +// BeforeTest has a function to be executed right before the test +// starts and receives the suite and test names as input +type BeforeTest interface { + BeforeTest(suiteName, testName string) +} + +// AfterTest has a function to be executed right after the test +// finishes and receives the suite and test names as input +type AfterTest interface { + AfterTest(suiteName, testName string) +} + +// WithStats implements HandleStats, a function that will be executed +// when a test suite is finished. The stats contain information about +// the execution of that suite and its tests. +type WithStats interface { + HandleStats(suiteName string, stats *SuiteInformation) +} + +// SetupSubTest has a SetupSubTest method, which will run before each +// subtest in the suite. +type SetupSubTest interface { + SetupSubTest() +} + +// TearDownSubTest has a TearDownSubTest method, which will run after +// each subtest in the suite have been run. +type TearDownSubTest interface { + TearDownSubTest() +} diff --git a/vendor/github.com/stretchr/testify/suite/stats.go b/vendor/github.com/stretchr/testify/suite/stats.go new file mode 100644 index 00000000..261da37f --- /dev/null +++ b/vendor/github.com/stretchr/testify/suite/stats.go @@ -0,0 +1,46 @@ +package suite + +import "time" + +// SuiteInformation stats stores stats for the whole suite execution. +type SuiteInformation struct { + Start, End time.Time + TestStats map[string]*TestInformation +} + +// TestInformation stores information about the execution of each test. +type TestInformation struct { + TestName string + Start, End time.Time + Passed bool +} + +func newSuiteInformation() *SuiteInformation { + testStats := make(map[string]*TestInformation) + + return &SuiteInformation{ + TestStats: testStats, + } +} + +func (s SuiteInformation) start(testName string) { + s.TestStats[testName] = &TestInformation{ + TestName: testName, + Start: time.Now(), + } +} + +func (s SuiteInformation) end(testName string, passed bool) { + s.TestStats[testName].End = time.Now() + s.TestStats[testName].Passed = passed +} + +func (s SuiteInformation) Passed() bool { + for _, stats := range s.TestStats { + if !stats.Passed { + return false + } + } + + return true +} diff --git a/vendor/github.com/stretchr/testify/suite/suite.go b/vendor/github.com/stretchr/testify/suite/suite.go new file mode 100644 index 00000000..18443a91 --- /dev/null +++ b/vendor/github.com/stretchr/testify/suite/suite.go @@ -0,0 +1,253 @@ +package suite + +import ( + "flag" + "fmt" + "os" + "reflect" + "regexp" + "runtime/debug" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +var allTestsFilter = func(_, _ string) (bool, error) { return true, nil } +var matchMethod = flag.String("testify.m", "", "regular expression to select tests of the testify suite to run") + +// Suite is a basic testing suite with methods for storing and +// retrieving the current *testing.T context. +type Suite struct { + *assert.Assertions + + mu sync.RWMutex + require *require.Assertions + t *testing.T + + // Parent suite to have access to the implemented methods of parent struct + s TestingSuite +} + +// T retrieves the current *testing.T context. +func (suite *Suite) T() *testing.T { + suite.mu.RLock() + defer suite.mu.RUnlock() + return suite.t +} + +// SetT sets the current *testing.T context. +func (suite *Suite) SetT(t *testing.T) { + suite.mu.Lock() + defer suite.mu.Unlock() + suite.t = t + suite.Assertions = assert.New(t) + suite.require = require.New(t) +} + +// SetS needs to set the current test suite as parent +// to get access to the parent methods +func (suite *Suite) SetS(s TestingSuite) { + suite.s = s +} + +// Require returns a require context for suite. +func (suite *Suite) Require() *require.Assertions { + suite.mu.Lock() + defer suite.mu.Unlock() + if suite.require == nil { + panic("'Require' must not be called before 'Run' or 'SetT'") + } + return suite.require +} + +// Assert returns an assert context for suite. Normally, you can call +// `suite.NoError(expected, actual)`, but for situations where the embedded +// methods are overridden (for example, you might want to override +// assert.Assertions with require.Assertions), this method is provided so you +// can call `suite.Assert().NoError()`. +func (suite *Suite) Assert() *assert.Assertions { + suite.mu.Lock() + defer suite.mu.Unlock() + if suite.Assertions == nil { + panic("'Assert' must not be called before 'Run' or 'SetT'") + } + return suite.Assertions +} + +func recoverAndFailOnPanic(t *testing.T) { + t.Helper() + r := recover() + failOnPanic(t, r) +} + +func failOnPanic(t *testing.T, r interface{}) { + t.Helper() + if r != nil { + t.Errorf("test panicked: %v\n%s", r, debug.Stack()) + t.FailNow() + } +} + +// Run provides suite functionality around golang subtests. It should be +// called in place of t.Run(name, func(t *testing.T)) in test suite code. +// The passed-in func will be executed as a subtest with a fresh instance of t. +// Provides compatibility with go test pkg -run TestSuite/TestName/SubTestName. +func (suite *Suite) Run(name string, subtest func()) bool { + oldT := suite.T() + + return oldT.Run(name, func(t *testing.T) { + suite.SetT(t) + defer suite.SetT(oldT) + + defer recoverAndFailOnPanic(t) + + if setupSubTest, ok := suite.s.(SetupSubTest); ok { + setupSubTest.SetupSubTest() + } + + if tearDownSubTest, ok := suite.s.(TearDownSubTest); ok { + defer tearDownSubTest.TearDownSubTest() + } + + subtest() + }) +} + +// Run takes a testing suite and runs all of the tests attached +// to it. +func Run(t *testing.T, suite TestingSuite) { + defer recoverAndFailOnPanic(t) + + suite.SetT(t) + suite.SetS(suite) + + var suiteSetupDone bool + + var stats *SuiteInformation + if _, ok := suite.(WithStats); ok { + stats = newSuiteInformation() + } + + tests := []testing.InternalTest{} + methodFinder := reflect.TypeOf(suite) + suiteName := methodFinder.Elem().Name() + + for i := 0; i < methodFinder.NumMethod(); i++ { + method := methodFinder.Method(i) + + ok, err := methodFilter(method.Name) + if err != nil { + fmt.Fprintf(os.Stderr, "testify: invalid regexp for -m: %s\n", err) + os.Exit(1) + } + + if !ok { + continue + } + + if !suiteSetupDone { + if stats != nil { + stats.Start = time.Now() + } + + if setupAllSuite, ok := suite.(SetupAllSuite); ok { + setupAllSuite.SetupSuite() + } + + suiteSetupDone = true + } + + test := testing.InternalTest{ + Name: method.Name, + F: func(t *testing.T) { + parentT := suite.T() + suite.SetT(t) + defer recoverAndFailOnPanic(t) + defer func() { + t.Helper() + + r := recover() + + if stats != nil { + passed := !t.Failed() && r == nil + stats.end(method.Name, passed) + } + + if afterTestSuite, ok := suite.(AfterTest); ok { + afterTestSuite.AfterTest(suiteName, method.Name) + } + + if tearDownTestSuite, ok := suite.(TearDownTestSuite); ok { + tearDownTestSuite.TearDownTest() + } + + suite.SetT(parentT) + failOnPanic(t, r) + }() + + if setupTestSuite, ok := suite.(SetupTestSuite); ok { + setupTestSuite.SetupTest() + } + if beforeTestSuite, ok := suite.(BeforeTest); ok { + beforeTestSuite.BeforeTest(methodFinder.Elem().Name(), method.Name) + } + + if stats != nil { + stats.start(method.Name) + } + + method.Func.Call([]reflect.Value{reflect.ValueOf(suite)}) + }, + } + tests = append(tests, test) + } + if suiteSetupDone { + defer func() { + if tearDownAllSuite, ok := suite.(TearDownAllSuite); ok { + tearDownAllSuite.TearDownSuite() + } + + if suiteWithStats, measureStats := suite.(WithStats); measureStats { + stats.End = time.Now() + suiteWithStats.HandleStats(suiteName, stats) + } + }() + } + + runTests(t, tests) +} + +// Filtering method according to set regular expression +// specified command-line argument -m +func methodFilter(name string) (bool, error) { + if ok, _ := regexp.MatchString("^Test", name); !ok { + return false, nil + } + return regexp.MatchString(*matchMethod, name) +} + +func runTests(t testing.TB, tests []testing.InternalTest) { + if len(tests) == 0 { + t.Log("warning: no tests to run") + return + } + + r, ok := t.(runner) + if !ok { // backwards compatibility with Go 1.6 and below + if !testing.RunTests(allTestsFilter, tests) { + t.Fail() + } + return + } + + for _, test := range tests { + r.Run(test.Name, test.F) + } +} + +type runner interface { + Run(name string, f func(t *testing.T)) bool +}