Add unit tests for parsing browser requests, enable Travis (#15)

This commit is contained in:
Maxim Baz
2018-04-18 22:52:34 +02:00
committed by GitHub
parent 01a808e2ce
commit d24b54e8b6
7 changed files with 157 additions and 31 deletions

View File

@@ -30,8 +30,29 @@ type request struct {
// Process handles browser request
func Process() {
requestLength := parseRequestLength()
request := parseRequest(requestLength)
requestLength, err := parseRequestLength(os.Stdin)
if err != nil {
log.Error("Unable to parse the length of the browser request: ", err)
response.SendErrorAndExit(
errors.CodeParseRequestLength,
&map[errors.Field]string{
errors.FieldMessage: "Unable to parse the length of the browser request",
errors.FieldError: err.Error(),
},
)
}
request, err := parseRequest(requestLength, os.Stdin)
if err != nil {
log.Error("Unable to parse the browser request: ", err)
response.SendErrorAndExit(
errors.CodeParseRequest,
&map[errors.Field]string{
errors.FieldMessage: "Unable to parse the browser request",
errors.FieldError: err.Error(),
},
)
}
switch request.Action {
case "configure":
@@ -52,35 +73,21 @@ func Process() {
}
}
// Request length is the first 4 bytes in LittleEndian encoding on stdin
func parseRequestLength() uint32 {
// Request length is the first 4 bytes in LittleEndian encoding
func parseRequestLength(input io.Reader) (uint32, error) {
var length uint32
if err := binary.Read(os.Stdin, binary.LittleEndian, &length); err != nil {
log.Error("Unable to parse the length of the browser request: ", err)
response.SendErrorAndExit(
errors.CodeParseRequestLength,
&map[errors.Field]string{
errors.FieldMessage: "Unable to parse the length of the browser request",
errors.FieldError: err.Error(),
},
)
if err := binary.Read(input, binary.LittleEndian, &length); err != nil {
return 0, err
}
return length
return length, nil
}
// Request is a json with a predefined structure
func parseRequest(messageLength uint32) request {
func parseRequest(messageLength uint32, input io.Reader) (*request, error) {
var parsed request
reader := &io.LimitedReader{R: os.Stdin, N: int64(messageLength)}
reader := &io.LimitedReader{R: input, N: int64(messageLength)}
if err := json.NewDecoder(reader).Decode(&parsed); err != nil {
log.Error("Unable to parse the browser request: ", err)
response.SendErrorAndExit(
errors.CodeParseRequest,
&map[errors.Field]string{
errors.FieldMessage: "Unable to parse the browser request",
errors.FieldError: err.Error(),
},
)
return nil, err
}
return parsed
return &parsed, nil
}