diff --git a/server/handlers/admin.go b/server/handlers/admin.go index 3ad3cdc..4e3202a 100644 --- a/server/handlers/admin.go +++ b/server/handlers/admin.go @@ -72,6 +72,17 @@ func (a *Admin) AddMocks(c echo.Context) error { } for _, mock := range mocks { + if mock.MockID != "" { // user has defined own mock ID + _, err := a.mocksServices.GetMockByID(sessionID, mock.MockID) + if err == nil { + return echo.NewHTTPError(http.StatusConflict, "Mock ID: "+mock.MockID+" already exists.") + } + + if err != types.MockNotFound { + return echo.NewHTTPError(http.StatusInternalServerError, err.Error()) + } + } + if _, err := a.mocksServices.AddMock(sessionID, mock); err != nil { return echo.NewHTTPError(http.StatusNotFound, err.Error()) } diff --git a/server/types/mock.go b/server/types/mock.go index 83e62a8..6974e4a 100644 --- a/server/types/mock.go +++ b/server/types/mock.go @@ -24,6 +24,7 @@ func (m Mocks) Clone() Mocks { } type Mock struct { + MockID string `json:"mockId,omitempty" yaml:"mockId"` Request MockRequest `json:"request,omitempty" yaml:"request"` Response *MockResponse `json:"response,omitempty" yaml:"response,omitempty"` Context *MockContext `json:"context,omitempty" yaml:"context,omitempty"` @@ -67,7 +68,11 @@ func (m *Mock) Validate() error { func (m *Mock) Init() { m.State = &MockState{ CreationDate: time.Now(), - ID: shortid.MustGenerate(), + } + if m.MockID != "" { + m.State.ID = m.MockID + } else { + m.State.ID = shortid.MustGenerate() } if m.Context == nil { diff --git a/tests/data/basic_mock_with_id.yml b/tests/data/basic_mock_with_id.yml new file mode 100644 index 0000000..c5f3ca2 --- /dev/null +++ b/tests/data/basic_mock_with_id.yml @@ -0,0 +1,8 @@ +- request: + path: /test + response: + headers: + Content-Type: application/json + body: > + {"message": "test"} + mockId: "1" diff --git a/tests/features/use_mocks_with_own_id.yml b/tests/features/use_mocks_with_own_id.yml new file mode 100644 index 0000000..69e4893 --- /dev/null +++ b/tests/features/use_mocks_with_own_id.yml @@ -0,0 +1,33 @@ +name: Use mocks to respond +version: "2" +testcases: + - name: Use basic mock with id + steps: + - type: http + method: POST + url: http://localhost:8081/mocks?reset=true + bodyFile: ../data/basic_mock_with_id.yml + assertions: + - result.statuscode ShouldEqual 200 + - result.bodyjson.message ShouldEqual "Mocks registered successfully" + + - type: http + method: GET + url: http://localhost:8080/test + assertions: + - result.statuscode ShouldEqual 200 + - result.bodyjson.message ShouldEqual test + + - type: http + method: GET + url: http://localhost:8081/mocks + assertions: + - result.bodyjson.__len__ ShouldEqual 1 + - result.bodyjson.bodyjson0.state.id ShouldEqual 1 + + - type: http + method: POST + url: http://localhost:8081/mocks + bodyFile: ../data/basic_mock_with_id.yml + assertions: + - result.statuscode ShouldEqual 409 \ No newline at end of file