github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/apiserver/websocket/websockettest/errors.go (about)

     1  // Copyright 2017 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package websockettest
     5  
     6  import (
     7  	"bufio"
     8  	"encoding/json"
     9  
    10  	"github.com/gorilla/websocket"
    11  	jc "github.com/juju/testing/checkers"
    12  	gc "gopkg.in/check.v1"
    13  
    14  	"github.com/juju/juju/apiserver/params"
    15  )
    16  
    17  // AssertWebsocketClosed checks that the given websocket connection
    18  // is closed.
    19  func AssertWebsocketClosed(c *gc.C, ws *websocket.Conn) {
    20  	_, _, err := ws.NextReader()
    21  	goodClose := []int{
    22  		websocket.CloseNormalClosure,
    23  		websocket.CloseGoingAway,
    24  		websocket.CloseNoStatusReceived,
    25  	}
    26  	c.Logf("%#v", err)
    27  	c.Assert(websocket.IsCloseError(err, goodClose...), jc.IsTrue)
    28  }
    29  
    30  // AssertJSONError checks the JSON encoded error returned by the log
    31  // and logsink APIs matches the expected value.
    32  func AssertJSONError(c *gc.C, ws *websocket.Conn, expected string) {
    33  	errResult := ReadJSONErrorLine(c, ws)
    34  	c.Assert(errResult.Error, gc.NotNil)
    35  	c.Assert(errResult.Error.Message, gc.Matches, expected)
    36  }
    37  
    38  // AssertJSONInitialErrorNil checks the JSON encoded error returned by the log
    39  // and logsink APIs are nil.
    40  func AssertJSONInitialErrorNil(c *gc.C, ws *websocket.Conn) {
    41  	errResult := ReadJSONErrorLine(c, ws)
    42  	c.Assert(errResult.Error, gc.IsNil)
    43  }
    44  
    45  // ReadJSONErrorLine returns the error line returned by the log and
    46  // logsink APIS.
    47  func ReadJSONErrorLine(c *gc.C, ws *websocket.Conn) params.ErrorResult {
    48  	messageType, reader, err := ws.NextReader()
    49  	c.Assert(err, jc.ErrorIsNil)
    50  	c.Assert(messageType, gc.Equals, websocket.TextMessage)
    51  	line, err := bufio.NewReader(reader).ReadSlice('\n')
    52  	c.Assert(err, jc.ErrorIsNil)
    53  	var errResult params.ErrorResult
    54  	err = json.Unmarshal(line, &errResult)
    55  	c.Assert(err, jc.ErrorIsNil)
    56  	return errResult
    57  }