Skip to content

Commit

Permalink
Fix backend unit tests (also code quality improvements) (#15)
Browse files Browse the repository at this point in the history
* Fix backend unit tests

- Ensure int value is formatted as such
- This was causing the backend unit tests to fail, possibly by dependency change

* Replace ioutil usage and decapitalize error strings

* Change receiver to be a pointer in order for assignment to persist

If the receiver is not pointer, the struct is copied and the assignment `r.sent = true` has no effect because r will be discarded after the function returns.

---------

Co-authored-by: Richard Cox <[email protected]>
  • Loading branch information
bmo-at-a9s and richard-cox committed Aug 18, 2023
1 parent 6e1a666 commit 4e547a6
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 26 deletions.
58 changes: 36 additions & 22 deletions src/jetstream/plugins/cfapppush/deploy.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/url"
"os"
"path/filepath"
Expand Down Expand Up @@ -120,7 +119,12 @@ func (cfAppPush *CFAppPush) deploy(echoContext echo.Context) error {
log.Debugf("Source %v+", msg)

// Temporary folder for the application source
tempDir, err := ioutil.TempDir("", "cf-push-")
tempDir, err := os.MkdirTemp("", "cf-push-")
if err != nil {
log.Errorf("Error creating temporary directory: %s", err)
return err
}

defer os.RemoveAll(tempDir)

var appDir string
Expand All @@ -137,7 +141,7 @@ func (cfAppPush *CFAppPush) deploy(echoContext echo.Context) error {
case SOURCE_DOCKER_IMG:
stratosProject, appDir, err = getDockerURLSource(clientWebSocket, tempDir, msg)
default:
err = errors.New("Unsupported source type; don't know how to get the source for the application")
err = errors.New("unsupported source type; don't know how to get the source for the application")
}

if err != nil {
Expand All @@ -159,7 +163,7 @@ func (cfAppPush *CFAppPush) deploy(echoContext echo.Context) error {

if msgOverrides.Type != OVERRIDES_SUPPLIED {
log.Errorf("Expected app deploy override but received event with type: %v", msgOverrides.Type)
return errors.New("Expected app deploy override message but received another type")
return errors.New("expected app deploy override message but received another type")
}

log.Debugf("Overrides: %v+", msgOverrides)
Expand Down Expand Up @@ -243,7 +247,7 @@ func (cfAppPush *CFAppPush) deploy(echoContext echo.Context) error {
}

if msg.Type != CLOSE_ACK {
log.Errorf("Expected a close acknowledgement - got: %s", string(msg.Type))
log.Errorf("Expected a close acknowledgement - got: %d", msg.Type)
} else {
log.Debug("Got close acknowledgement from the client")
}
Expand All @@ -269,7 +273,7 @@ func getFolderSource(clientWebSocket *websocket.Conn, tempDir string, msg Socket
path := filepath.Join(tempDir, folder)
err := os.Mkdir(path, 0700)
if err != nil {
return StratosProject{}, tempDir, errors.New("Failed to create folder")
return StratosProject{}, tempDir, errors.New("failed to create folder")
}
}

Expand All @@ -290,7 +294,7 @@ func getFolderSource(clientWebSocket *websocket.Conn, tempDir string, msg Socket

// Expecting a file
if msg.Type != SOURCE_FILE {
return StratosProject{}, tempDir, errors.New("Unexpected web socket message type")
return StratosProject{}, tempDir, errors.New("unexpected web socket message type")
}

log.Debugf("Transferring file: %s", msg.Message)
Expand All @@ -303,12 +307,12 @@ func getFolderSource(clientWebSocket *websocket.Conn, tempDir string, msg Socket
}

if messageType != websocket.BinaryMessage {
return StratosProject{}, tempDir, errors.New("Expecting binary file data")
return StratosProject{}, tempDir, errors.New("expecting binary file data")
}

// Write the file
path := filepath.Join(tempDir, msg.Message)
err = ioutil.WriteFile(path, p, 0644)
err = os.WriteFile(path, p, 0644)
if err != nil {
return StratosProject{}, tempDir, err
}
Expand All @@ -332,14 +336,17 @@ func getFolderSource(clientWebSocket *websocket.Conn, tempDir string, msg Socket
log.Debug("Unpacking archive ......")
unpackPath := filepath.Join(tempDir, "application")
err := os.Mkdir(unpackPath, 0700)
if err != nil {
return StratosProject{}, tempDir, err
}

err = archiver.Unarchive(lastFilePath, unpackPath)
if err != nil {
return StratosProject{}, tempDir, err
}

// Just check to see if we actually unpacked into a root folder
contents, err := ioutil.ReadDir(unpackPath)
contents, err := os.ReadDir(unpackPath)
if err != nil {
return StratosProject{}, tempDir, err
}
Expand All @@ -361,7 +368,7 @@ func getFolderSource(clientWebSocket *websocket.Conn, tempDir string, msg Socket
}

if msg.Type != SOURCE_WAIT_ACK {
return StratosProject{}, tempDir, errors.New("Expecting ACK message to begin deployment")
return StratosProject{}, tempDir, errors.New("expecting ACK message to begin deployment")
}
}

Expand Down Expand Up @@ -396,12 +403,12 @@ func (cfAppPush *CFAppPush) getGitSCMSource(clientWebSocket *websocket.Conn, tem
if len(info.EndpointGUID) != 0 {
parsedURL, err := url.Parse(info.URL)
if err != nil {
return StratosProject{}, tempDir, errors.New("Failed to parse SCM URL")
return StratosProject{}, tempDir, errors.New("failed to parse SCM URL")
}

cnsiRecord, err := cfAppPush.portalProxy.GetCNSIRecord(info.EndpointGUID)
if err != nil {
return StratosProject{}, tempDir, errors.New("Failed to find endpoint with guid " + info.EndpointGUID)
return StratosProject{}, tempDir, errors.New("failed to find endpoint with guid " + info.EndpointGUID)
}

skipSLL = cnsiRecord.SkipSSLValidation
Expand All @@ -410,7 +417,7 @@ func (cfAppPush *CFAppPush) getGitSCMSource(clientWebSocket *websocket.Conn, tem
if isTokenFound {
authTokenDecodedBytes, err := base64.StdEncoding.DecodeString(tokenRecord.AuthToken)
if err != nil {
return StratosProject{}, tempDir, errors.New("Failed to decode auth token")
return StratosProject{}, tempDir, errors.New("failed to decode auth token")
}

var (
Expand All @@ -428,11 +435,11 @@ func (cfAppPush *CFAppPush) getGitSCMSource(clientWebSocket *websocket.Conn, tem
username = tokenRecord.RefreshToken
password = string(authTokenDecodedBytes)
default:
return StratosProject{}, tempDir, fmt.Errorf("Unknown SCM type '%s'", info.SCM)
return StratosProject{}, tempDir, fmt.Errorf("unknown SCM type '%s'", info.SCM)
}

if len(username) == 0 {
return StratosProject{}, tempDir, errors.New("Username is empty")
return StratosProject{}, tempDir, errors.New("username is empty")
}

// mask the credentials for the logs and env var
Expand Down Expand Up @@ -523,12 +530,19 @@ func getDockerURLSource(clientWebSocket *websocket.Conn, tempDir string, msg Soc
applicationData := RawManifestApplication{
Name: info.ApplicationName,
}

manifest := Applications{
Applications: []RawManifestApplication{applicationData},
}

marshalledYaml, err := yaml.Marshal(manifest)
if err != nil {
return StratosProject{}, tempDir, err
}

manifestPath := fmt.Sprintf("%s/manifest.yml", tempDir)
err = ioutil.WriteFile(manifestPath, marshalledYaml, 0600)

err = os.WriteFile(manifestPath, marshalledYaml, 0600)
if err != nil {
log.Warnf("Failed to write manifest in path %s", manifestPath)
return StratosProject{}, tempDir, err
Expand Down Expand Up @@ -577,7 +591,7 @@ func (cfAppPush *CFAppPush) getConfigData(echoContext echo.Context, cnsiGUID str
if !found {
log.Warnf("Failed to retrieve record for CNSI %s", cnsiGUID)
sendErrorMessage(clientWebSocket, err, CLOSE_NO_CNSI_USERTOKEN)
return nil, errors.New("Failed to find token record")
return nil, errors.New("failed to find token record")
}

config := &CFPushAppConfig{
Expand All @@ -602,7 +616,7 @@ func (cfAppPush *CFAppPush) getConfigData(echoContext echo.Context, cnsiGUID str
func cloneRepository(cloneDetails CloneDetails, clientWebSocket *websocket.Conn, tempDir string) (string, error) {

if len(cloneDetails.Branch) == 0 {
err := errors.New("No branch supplied")
err := errors.New("no branch supplied")
log.Infof("Failed to checkout repo %s due to %+v", cloneDetails.LoggerUrl, err)
sendErrorMessage(clientWebSocket, err, CLOSE_FAILED_NO_BRANCH)
return "", err
Expand Down Expand Up @@ -662,12 +676,12 @@ func fetchManifest(repoPath string, stratosProject StratosProject, clientWebSock
if !fileExists(manifestPath) {
manifestPath = filepath.Join(repoPath, "manifest.yaml")
if !fileExists(manifestPath) {
return manifest, manifestPath, fmt.Errorf("Can not find manifest file")
return manifest, manifestPath, fmt.Errorf("can not find manifest file")
}
}

// Read the manifest
data, err := ioutil.ReadFile(manifestPath)
data, err := os.ReadFile(manifestPath)
if err != nil {
log.Warnf("Failed to read manifest in path %s", manifestPath)
sendErrorMessage(clientWebSocket, err, CLOSE_NO_MANIFEST)
Expand Down Expand Up @@ -700,7 +714,7 @@ func fetchManifest(repoPath string, stratosProject StratosProject, clientWebSock
sendErrorMessage(clientWebSocket, err, CLOSE_FAILURE)
return manifest, manifestPath, err
}
ioutil.WriteFile(manifestPath, marshalledYaml, 0600)
os.WriteFile(manifestPath, marshalledYaml, 0600)
}

return manifest, manifestPath, nil
Expand Down
2 changes: 1 addition & 1 deletion src/jetstream/plugins/cfapppush/info.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func (c *CFPushApp) setEndpointInfo(config *configv3.Config) error {
config.SetAccessToken("bearer " + c.config.AuthToken)
// Note: We do not give the refresh token to the CLI code as we do NOT want it to refresh the token
} else {
return errors.New("Did not get a CF /v2/info response")
return errors.New("did not get a CF /v2/info response")
}

return nil
Expand Down
4 changes: 2 additions & 2 deletions src/jetstream/plugins/cfapppush/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,12 @@ func Init(portalProxy interfaces.PortalProxy) (interfaces.StratosPlugin, error)

// GetMiddlewarePlugin gets the middleware plugin for this plugin
func (cfAppPush *CFAppPush) GetMiddlewarePlugin() (interfaces.MiddlewarePlugin, error) {
return nil, errors.New("Not implemented")
return nil, errors.New("not implemented")
}

// GetEndpointPlugin gets the endpoint plugin for this plugin
func (cfAppPush *CFAppPush) GetEndpointPlugin() (interfaces.EndpointPlugin, error) {
return nil, errors.New("Not implemented")
return nil, errors.New("not implemented")
}

// GetRoutePlugin gets the route plugin for this plugin
Expand Down
2 changes: 1 addition & 1 deletion src/jetstream/plugins/cfapppush/push_actor.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ type cfV2Actor struct {
clientWebsocket *websocket.Conn
}

func (r cfV2Actor) sendAppID(application v2action.Application) {
func (r *cfV2Actor) sendAppID(application v2action.Application) {
if !r.sent {
r.msgSender.SendEvent(r.clientWebsocket, APP_GUID_NOTIFY, application.GUID)
r.sent = true
Expand Down

0 comments on commit 4e547a6

Please sign in to comment.