Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: WEOS-1342 As a developer I should be able have a datetime field automatically update on update #127

Merged
merged 23 commits into from
Mar 17, 2022
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
e244c5d
feature/WEOS-1359 Update time values by flag on route
atoniaw Feb 24, 2022
f5589b8
feature:WEOS-1116
RandyDeo Feb 25, 2022
e1bfa48
Changes by User
RandyDeo Feb 25, 2022
090e694
WEOS-1359 fixed possible model panic
atoniaw Feb 28, 2022
90bc8f7
WEOS-1359 Delete binary
atoniaw Feb 28, 2022
87e0388
Merge pull request #125 from wepala/WEOS-1359
atoniaw Feb 28, 2022
aaf46b3
Merge remote-tracking branch 'origin/feature/WEOS-1342' into feature/…
shaniah868 Feb 28, 2022
790ed0c
Merge branch 'dev' into feature/WEOS-1342
RandyDeo Mar 2, 2022
dd0b206
Merge branch 'dev' into feature/WEOS-1342
RandyDeo Mar 4, 2022
0d6ff00
Merge branch 'dev' into feature/WEOS-1342
shaniah868 Mar 8, 2022
33fe13c
doc: WEOS-1342 Added scenarios to cover using the x-update extension …
akeemphilbert Mar 9, 2022
8323b48
feature: WEOS-1342
RandyDeo Mar 10, 2022
d372af2
feature: WEOS-1342
RandyDeo Mar 10, 2022
e3e6893
feature: WEOS-1342
RandyDeo Mar 11, 2022
6680d05
feature: WEOS-1342
RandyDeo Mar 11, 2022
75b1fe9
feature: WEOS-1342
RandyDeo Mar 11, 2022
feeece6
Merge branch 'dev' into feature/WEOS-1342
RandyDeo Mar 11, 2022
6eb36e3
Merge branch 'dev' into feature/WEOS-1342
RandyDeo Mar 15, 2022
9176aa6
feature: WEOS-1342
RandyDeo Mar 15, 2022
0bd06ce
Merge branch 'dev' into feature/WEOS-1342
RandyDeo Mar 16, 2022
cf388bb
Merge branch 'dev' into feature/WEOS-1342
shaniah868 Mar 16, 2022
70c9aaf
feature: WEOS-1342 As a developer I should be able have a datetime fi…
shaniah868 Mar 16, 2022
d082973
Merge remote-tracking branch 'origin/feature/WEOS-1342' into feature/…
shaniah868 Mar 16, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions api.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,14 @@ components:
lastUpdated:
type: string
format: date-time
x-update:
- Add Blog
- Update Blog
created:
type: string
format: date-time
x-update:
- Add Blog
required:
- title
- url
Expand Down
1 change: 1 addition & 0 deletions context/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const HeaderXLogLevel = "X-LOG-LEVEL"

//add more keys here if needed
const ACCOUNT_ID ContextKey = "ACCOUNT_ID"
const OPERATION_ID = "OPERATION_ID"
const USER_ID ContextKey = "USER_ID"
const LOG_LEVEL ContextKey = "LOG_LEVEL"
const REQUEST_ID ContextKey = "REQUEST_ID"
Expand Down
31 changes: 31 additions & 0 deletions controllers/rest/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,37 @@ func (p *RESTAPI) Initialize(ctxt context.Context) error {
}
}

//this ranges over the paths and pulls out the operationIDs into an array
opIDs := []string{}
idFound := false
for _, pathData := range p.Swagger.Paths {
for _, op := range pathData.Operations() {
if op.OperationID != "" {
opIDs = append(opIDs, op.OperationID)
}
}
}

//this ranges over the properties, pulls the x-update and them compares it against the valid operation ids in the yaml
for _, scheme := range p.Swagger.Components.Schemas {
for _, prop := range scheme.Value.Properties {
xUpdate := []string{}
xUpdateBytes, _ := json.Marshal(prop.Value.Extensions["x-update"])
json.Unmarshal(xUpdateBytes, &xUpdate)
for _, r := range xUpdate {
idFound = false
for _, id := range opIDs {
if r == id {
idFound = true
}
}
if !idFound {
return fmt.Errorf("provided x-update operation id: %s is invalid", r)
}
}
}
}

//get the database schema
schemas = CreateSchema(ctxt, p.EchoInstance(), p.Swagger)
p.Schemas = schemas
Expand Down
44 changes: 44 additions & 0 deletions controllers/rest/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package rest_test
import (
"bytes"
"encoding/json"
"github.com/labstack/echo/v4"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
Expand Down Expand Up @@ -457,3 +459,45 @@ func TestRESTAPI_Initialize_DefaultResponseMiddlware(t *testing.T) {
os.Remove("test.db")
time.Sleep(1 * time.Second)
}

func TestRESTAPI_Integration_AutomaticallyUpdateDateTime(t *testing.T) {
tapi, err := api.New("./fixtures/blog.yaml")
if err != nil {
t.Fatalf("un expected error loading spec '%s'", err)
}
err = tapi.Initialize(nil)
if err != nil {
t.Fatalf("un expected error loading spec '%s'", err)
}
e := tapi.EchoInstance()
t.Run("automatically updating create", func(t *testing.T) {
mockBlog := map[string]interface{}{"title": "Test Blog", "url": "www.testBlog.com"}
reqBytes, err := json.Marshal(mockBlog)
if err != nil {
t.Fatalf("error setting up request %s", err)
}
body := bytes.NewReader(reqBytes)
resp := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/blogs", body)
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
e.ServeHTTP(resp, req)
if resp.Result().StatusCode != http.StatusCreated {
t.Errorf("expected the response code to be %d, got %d", http.StatusCreated, resp.Result().StatusCode)
}
defer resp.Result().Body.Close()
tResults, err := ioutil.ReadAll(resp.Result().Body)
if err != nil {
t.Errorf("unexpect error: %s", err)
}
results := map[string]interface{}{}
err = json.Unmarshal(tResults, &results)
if err != nil {
t.Errorf("unexpect error: %s", err)
}
if results["created"] == nil || results["lastUpdated"] == nil {
t.Errorf("unexpect error expected to find created and lastUpdated")
}

})

}
5 changes: 5 additions & 0 deletions controllers/rest/fixtures/blog.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,14 @@ components:
lastUpdated:
type: string
format: date-time
x-update:
- Add Blog
- Update Blog
created:
type: string
format: date-time
x-update:
- Add Blog
required:
- title
- url
Expand Down
3 changes: 3 additions & 0 deletions controllers/rest/middleware_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ func Context(api *RESTAPI, projection projections.Projection, commandDispatcher

cc, err = parseResponses(c, cc, operation)

//add OperationID to context
cc = context.WithValue(cc, weosContext.OPERATION_ID, operation.OperationID)

//parse request body based on content type
var payload []byte
ct := c.Request().Header.Get("Content-Type")
Expand Down
22 changes: 22 additions & 0 deletions controllers/rest/middleware_context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -561,4 +561,26 @@ func TestContext(t *testing.T) {
e.GET("/blogs/:id", handler)
e.ServeHTTP(resp, req)
})

t.Run("add operationId to context", func(t *testing.T) {
path := swagger.Paths.Find("/blogs")
mw := rest.Context(restApi, nil, nil, nil, entityFactory, path, path.Get)
handler := mw(func(ctxt echo.Context) error {
//check that certain parameters are in the context
cc := ctxt.Request().Context()
value := cc.Value(context.OPERATION_ID)
if value == nil {
t.Fatalf("expected the operation id to have a value")
}
if value.(string) != "Get Blogs" {
t.Fatalf("expected the operation id to be Get Blogs")
}
return nil
})
e := echo.New()
resp := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/blogs", nil)
e.GET("/blogs", handler)
e.ServeHTTP(resp, req)
})
}
62 changes: 59 additions & 3 deletions end2end_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import (
"encoding/json"
"errors"
"fmt"
weosContext "github.com/wepala/weos/context"
"io"
weosContext "github.com/wepala/weos/context"
"mime/multipart"
"net/http"
"net/http/httptest"
Expand Down Expand Up @@ -72,6 +72,8 @@ var filters string
var enumErr error
var token string
var contextWithValues context.Context
var createdDate interface{}
var updatedDate interface{}
var mockProjections map[string]*ProjectionMock
var mockEventStores map[string]*EventRepositoryMock

Expand Down Expand Up @@ -500,6 +502,8 @@ func theIsCreated(contentType string, details *godog.Table) error {
}
}

createdDate = contentEntity["created"]

contentTypeID[strings.ToLower(contentType)] = true
return nil
}
Expand Down Expand Up @@ -750,7 +754,11 @@ func theServiceIsRunning() error {
})
err := API.Initialize(scenarioContext)
if err != nil {
return err
if strings.Contains(err.Error(), "provided x-update operation id") {
errs = err
} else {
return err
}
}
proj, err := API.GetProjection("Default")
if err == nil {
Expand Down Expand Up @@ -901,6 +909,8 @@ func theIsUpdated(contentType string, details *godog.Table) error {
}
}

updatedDate = contentEntity["updated"]

contentTypeID[strings.ToLower(contentType)] = true
return nil
}
Expand Down Expand Up @@ -1689,6 +1699,50 @@ func theProjectionIsNotCalled(arg1 string) error {
return fmt.Errorf("projection '%s' not found", arg1)
}

func anErrorIsReturned() error {
if !strings.Contains(errs.Error(), "provided x-update operation id") {
return fmt.Errorf("expected the error to contain: %s, got %s", "provided x-update operation id", errs.Error())
}
return nil
}

func theFieldShouldHaveTodaysDate(field string) error {

timeNow := time.Now()
todaysDate := timeNow.Format("2006-01-02")

switch dbconfig.Driver {
case "postgres", "mysql":
switch field {
RandyDeo marked this conversation as resolved.
Show resolved Hide resolved
case "created":
crDate := createdDate.(time.Time).Format("2006-01-02")
if !strings.Contains(crDate, todaysDate) {
return fmt.Errorf("expected the created date: %s to contain the current date: %s ", crDate, todaysDate)
}
case "updated":
upDate := updatedDate.(time.Time).Format("2006-01-02")
if !strings.Contains(upDate, todaysDate) {
return fmt.Errorf("expected the created date: %s to contain the current date: %s ", upDate, todaysDate)
}
}
case "sqlite3":
switch field {
case "created":
crDate := createdDate.(string)
if !strings.Contains(crDate, todaysDate) {
return fmt.Errorf("expected the created date: %s to contain the current date: %s ", crDate, todaysDate)
}
case "updated":
upDate := updatedDate.(string)
if !strings.Contains(upDate, todaysDate) {
return fmt.Errorf("expected the created date: %s to contain the current date: %s ", upDate, todaysDate)
}
}
}

return nil
}

func InitializeScenario(ctx *godog.ScenarioContext) {
ctx.Before(reset)
ctx.After(func(ctx context.Context, sc *godog.Scenario, err error) (context.Context, error) {
Expand Down Expand Up @@ -1787,6 +1841,8 @@ func InitializeScenario(ctx *godog.ScenarioContext) {
ctx.Step(`^"([^"]*)" defines an event store "([^"]*)"$`, definesAnEventStore)
ctx.Step(`^"([^"]*)" set the default event store as "([^"]*)"$`, setTheDefaultEventStoreAs)
ctx.Step(`^the projection "([^"]*)" is not called$`, theProjectionIsNotCalled)
ctx.Step(`^an error is returned$`, anErrorIsReturned)
ctx.Step(`^the "([^"]*)" field should have today\'s date$`, theFieldShouldHaveTodaysDate)
}

func TestBDD(t *testing.T) {
Expand All @@ -1798,7 +1854,7 @@ func TestBDD(t *testing.T) {
Format: "pretty",
Tags: "~long && ~skipped",
//Tags: "focus1",
//Tags: "WEOS-1315 && ~skipped",
//Tags: "WEOS-1110 && ~skipped",
},
}.Run()
if status != 0 {
Expand Down
Loading