Skip to content

Commit

Permalink
Merge pull request #5 from Comcast/standUpMachine
Browse files Browse the repository at this point in the history
Initialization first attempt.
  • Loading branch information
schmidtw authored Sep 28, 2017
2 parents 4a75863 + bd934a0 commit 149b5ba
Show file tree
Hide file tree
Showing 12 changed files with 343 additions and 132 deletions.
39 changes: 37 additions & 2 deletions src/glide.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion src/tr1d1um/communication.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ func (tr1 *Tr1SendAndHandle) Send(ch *ConversionHandler, resp http.ResponseWrite
return
}

requestToServer, err := tr1.NewHTTPRequest(http.MethodGet, ch.targetURL, bytes.NewBuffer(wrpPayload))
fullPath := ch.targetURL + baseURI + "/" + version + "/" + wrpMsg.Destination
requestToServer, err := tr1.NewHTTPRequest(http.MethodPost, fullPath, bytes.NewBuffer(wrpPayload))

if err != nil {
resp.WriteHeader(http.StatusInternalServerError)
Expand All @@ -48,6 +49,7 @@ func (tr1 *Tr1SendAndHandle) Send(ch *ConversionHandler, resp http.ResponseWrite

//todo: any more headers to be added here
requestToServer.Header.Set("Content-Type", wrp.JSON.ContentType())
requestToServer.Header.Set("Authorization", req.Header.Get("Authorization"))
respFromServer, err = tr1.timedClient.Do(requestToServer)
return
}
Expand Down
6 changes: 2 additions & 4 deletions src/tr1d1um/communication_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func TestSend(t *testing.T) {
WRPPayload := []byte("payload")
validURL := "http://someValidURL"

tr1 := &Tr1SendAndHandle{log: &logTracker{}, timedClient: &http.Client{Timeout: time.Second}}
tr1 := &Tr1SendAndHandle{log: &LightFakeLogger{}, timedClient: &http.Client{Timeout: time.Second}}
tr1.NewHTTPRequest = http.NewRequest
ch := &ConversionHandler{encodingHelper: mockEncoding, wdmpConvert: mockConversion, targetURL: validURL}

Expand Down Expand Up @@ -89,13 +89,11 @@ func TestSend(t *testing.T) {

func TestHandleResponse(t *testing.T) {
assert := assert.New(t)
tr1 := &Tr1SendAndHandle{log: &logTracker{}, timedClient: &http.Client{Timeout: time.Second}}
tr1 := &Tr1SendAndHandle{log: &LightFakeLogger{}, timedClient: &http.Client{Timeout: time.Second}}
tr1.NewHTTPRequest = http.NewRequest

ch := &ConversionHandler{encodingHelper: mockEncoding, wdmpConvert: mockConversion}

//Cases
//incoming err
t.Run("IncomingErr", func(t *testing.T) {
recorder := httptest.NewRecorder()
tr1.HandleResponse(nil, errors.New(errMsg), nil, recorder)
Expand Down
24 changes: 16 additions & 8 deletions src/tr1d1um/conversion_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ type Vars map[string]string

//ConversionTool lays out the definition of methods to build WDMP from content in an http request
type ConversionTool interface {
GetFlavorFormat(*http.Request, string, string, string) (*GetWDMP, error)
GetFlavorFormat(*http.Request, Vars, string, string, string) (*GetWDMP, error)
SetFlavorFormat(*http.Request) (*SetWDMP, error)
DeleteFlavorFormat(Vars, string) (*DeleteRowWDMP, error)
AddFlavorFormat(io.Reader, Vars, string) (*AddRowWDMP, error)
Expand All @@ -45,14 +45,18 @@ type ConversionWDMP struct {
encodingHelper EncodingTool
}

/* The following functions break down the different cases for requests (https://swagger.webpa.comcast.net/)
containing WDMP content. Their main functionality is to attempt at reading such content, validating it
and subsequently returning a json type encoding of it. Most often this resulting []byte is used as payload for
wrp messages
*/
func (cw *ConversionWDMP) GetFlavorFormat(req *http.Request, attr, namesKey, sep string) (wdmp *GetWDMP, err error) {
//The following functions with names of the form {command}FlavorFormat serve as the low level builders of WDMP objects
// based on the commands they serve for Cloud <-> TR181 devices communication

//GetFlavorFormat constructs a WDMP object out of the contents of a given request. Supports the GET command
func (cw *ConversionWDMP) GetFlavorFormat(req *http.Request, pathVars Vars, attr, namesKey, sep string) (wdmp *GetWDMP, err error) {
wdmp = new(GetWDMP)

if service, _ := cw.GetFromURLPath("service", pathVars); service == "stat" {
return
//todo: maybe we need more validation here
}

if nameGroup := req.FormValue(namesKey); nameGroup != "" {
wdmp.Command = CommandGet
wdmp.Names = strings.Split(nameGroup, sep)
Expand All @@ -69,6 +73,7 @@ func (cw *ConversionWDMP) GetFlavorFormat(req *http.Request, attr, namesKey, sep
return
}

//SetFlavorFormat has analogous functionality to GetFlavorformat but instead supports the various SET commands
func (cw *ConversionWDMP) SetFlavorFormat(req *http.Request) (wdmp *SetWDMP, err error) {
wdmp = new(SetWDMP)

Expand All @@ -78,6 +83,7 @@ func (cw *ConversionWDMP) SetFlavorFormat(req *http.Request) (wdmp *SetWDMP, err
return
}

//DeleteFlavorFormat again has analogous functionality to GetFlavormat but for the DELETE_ROW command
func (cw *ConversionWDMP) DeleteFlavorFormat(urlVars Vars, rowKey string) (wdmp *DeleteRowWDMP, err error) {
wdmp = &DeleteRowWDMP{Command: CommandDeleteRow}

Expand All @@ -90,6 +96,7 @@ func (cw *ConversionWDMP) DeleteFlavorFormat(urlVars Vars, rowKey string) (wdmp
return
}

//AddFlavorFormat supports the ADD_ROW command
func (cw *ConversionWDMP) AddFlavorFormat(input io.Reader, urlVars Vars, tableName string) (wdmp *AddRowWDMP, err error) {
wdmp = &AddRowWDMP{Command: CommandAddRow}

Expand All @@ -107,6 +114,7 @@ func (cw *ConversionWDMP) AddFlavorFormat(input io.Reader, urlVars Vars, tableNa
return
}

//ReplaceFlavorFormat supports the REPLACE_ROWS command
func (cw *ConversionWDMP) ReplaceFlavorFormat(input io.Reader, urlVars Vars, tableName string) (wdmp *ReplaceRowsWDMP, err error) {
wdmp = &ReplaceRowsWDMP{Command: CommandReplaceRows}

Expand Down Expand Up @@ -192,7 +200,7 @@ func (helper *EncodingHelper) EncodeJSON(v interface{}) (data []byte, err error)

//ExtractPayload decodes an encoded wrp message and returns its payload
func (helper *EncodingHelper) ExtractPayload(input io.Reader, format wrp.Format) (payload []byte, err error) {
wrpResponse := &wrp.Message{}
wrpResponse := &wrp.Message{Type: wrp.SimpleRequestResponseMessageType}

if err = wrp.NewDecoder(input, format).Decode(wrpResponse); err == nil {
payload = wrpResponse.Payload
Expand Down
40 changes: 25 additions & 15 deletions src/tr1d1um/conversion_utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ import (
)

var (
sampleNames = []string{"p1", "p2"}
dataType int8 = 3
value string = "someVal"
name string = "someName"
valid = SetParam{Name: &name, Attributes: Attr{"notify": 0}}
sampleNames = []string{"p1", "p2"}
dataType int8 = 3
value = "someVal"
name = "someName"
valid = SetParam{Name: &name, Attributes: Attr{"notify": 0}}
emptyInputBuffer bytes.Buffer
commonVars = Vars{"uThere?": "yes!"}
replaceRows = IndexRow{"0": {"uno": "one", "dos": "two"}}
Expand All @@ -37,17 +37,27 @@ func TestGetFlavorFormat(t *testing.T) {
t.Run("IdealGet", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "http://api/device/config?names=p1,p2", nil)

wdmp, err := c.GetFlavorFormat(req, "attributes", "names", ",")
wdmp, err := c.GetFlavorFormat(req, nil, "attributes", "names", ",")

assert.Nil(err)
assert.EqualValues(wdmpGet, wdmp)
})

t.Run("IdealGetStat", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "http://api/device/mac:112233445566/stat", nil)

wdmp, err := c.GetFlavorFormat(req, map[string]string{"service": "stat"}, "attributes", "names", ",")

assert.Nil(err)
assert.EqualValues(new(GetWDMP), wdmp)
})

t.Run("IdealGetAttr", func(t *testing.T) {

req := httptest.NewRequest(http.MethodGet, "http://api/device/config?names=p1,p2&attributes=attr1",
nil)

wdmp, err := c.GetFlavorFormat(req, "attributes", "names", ",")
wdmp, err := c.GetFlavorFormat(req, nil, "attributes", "names", ",")

assert.Nil(err)
assert.EqualValues(wdmpGetAttrs, wdmp)
Expand All @@ -57,7 +67,7 @@ func TestGetFlavorFormat(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "http://api/device/config?names=",
nil)

_, err := c.GetFlavorFormat(req, "attributes", "names", ",")
_, err := c.GetFlavorFormat(req, nil, "attributes", "names", ",")

assert.NotNil(err)
assert.True(strings.HasPrefix(err.Error(), "names is a required"))
Expand All @@ -67,19 +77,19 @@ func TestGetFlavorFormat(t *testing.T) {
func TestSetFlavorFormat(t *testing.T) {
assert := assert.New(t)
c := ConversionWDMP{&EncodingHelper{}}
commonUrl := "http://device/config?k=v"
commonURL := "http://device/config?k=v"
var req *http.Request

t.Run("DecodeErr", func(t *testing.T) {
invalidBody := bytes.NewBufferString("{")
req = httptest.NewRequest(http.MethodPatch, commonUrl, invalidBody)
req = httptest.NewRequest(http.MethodPatch, commonURL, invalidBody)
_, err := c.SetFlavorFormat(req)
assert.NotNil(err)
})

t.Run("InvalidData", func(t *testing.T) {
emptyBody := bytes.NewBufferString(`{}`)
req = httptest.NewRequest(http.MethodPatch, commonUrl, emptyBody)
req = httptest.NewRequest(http.MethodPatch, commonURL, emptyBody)

_, err := c.SetFlavorFormat(req)
assert.NotNil(err)
Expand Down Expand Up @@ -239,22 +249,22 @@ func TestAddFlavorFormat(t *testing.T) {
func TestGetFromURLPath(t *testing.T) {
assert := assert.New(t)

fakeUrlVar := map[string]string{"k1": "k1v1,k1v2", "k2": "k2v1"}
fakeURLVar := map[string]string{"k1": "k1v1,k1v2", "k2": "k2v1"}
c := ConversionWDMP{}

t.Run("NormalCases", func(t *testing.T) {

k1ValGroup, exists := c.GetFromURLPath("k1", fakeUrlVar)
k1ValGroup, exists := c.GetFromURLPath("k1", fakeURLVar)
assert.True(exists)
assert.EqualValues("k1v1,k1v2", k1ValGroup)

k2ValGroup, exists := c.GetFromURLPath("k2", fakeUrlVar)
k2ValGroup, exists := c.GetFromURLPath("k2", fakeURLVar)
assert.True(exists)
assert.EqualValues("k2v1", k2ValGroup)
})

t.Run("NonNilNonExistent", func(t *testing.T) {
_, exists := c.GetFromURLPath("k3", fakeUrlVar)
_, exists := c.GetFromURLPath("k3", fakeURLVar)
assert.False(exists)
})

Expand Down
12 changes: 4 additions & 8 deletions src/tr1d1um/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package main

import (
"net/http"
"time"

"github.com/Comcast/webpa-common/logging"
"github.com/go-kit/kit/log"
Expand All @@ -13,42 +12,39 @@ import (
type ConversionHandler struct {
infoLogger log.Logger
errorLogger log.Logger
timeOut time.Duration
targetURL string
wdmpConvert ConversionTool
sender SendAndHandle
encodingHelper EncodingTool
}

//ConversionHandler handles the different incoming tr1 requests
func (ch *ConversionHandler) ConversionHandler(origin http.ResponseWriter, req *http.Request) {
func (ch *ConversionHandler) ServeHTTP(origin http.ResponseWriter, req *http.Request) {
var err error
var wdmp interface{}
var urlVars Vars
var urlVars = mux.Vars(req)

switch req.Method {
case http.MethodGet:
wdmp, err = ch.wdmpConvert.GetFlavorFormat(req, "attributes", "names", ",")
wdmp, err = ch.wdmpConvert.GetFlavorFormat(req, urlVars, "attributes", "names", ",")
break

case http.MethodPatch:
wdmp, err = ch.wdmpConvert.SetFlavorFormat(req)
break

case http.MethodDelete:
urlVars = mux.Vars(req)
wdmp, err = ch.wdmpConvert.DeleteFlavorFormat(urlVars, "parameter")
break

case http.MethodPut:
urlVars = mux.Vars(req)
wdmp, err = ch.wdmpConvert.ReplaceFlavorFormat(req.Body, urlVars, "parameter")
break

case http.MethodPost:
urlVars = mux.Vars(req)
wdmp, err = ch.wdmpConvert.AddFlavorFormat(req.Body, urlVars, "parameter")
break

}

if err != nil {
Expand Down
Loading

0 comments on commit 149b5ba

Please sign in to comment.