Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

curl -i -X DELETE http://localhost:9015/v1/baremetalcluster/alpha/beta/container_images/asdf246

...


How To Write ICN Unit Tests in Go using Testify

Go version used is go1.12.9

To install Go, follow the instructions on the official site, (https://golang.org/doc/install).

Testify documentation can be found on Github, https://github.com/stretchr/testify


The first question I ask myself before I write a unit test is, "what do I want to test?" In this case, I'll test a method called GetDirPath in my Go pkg called image.go.

GetDirPath uses the Go core packages user and path to return a file path.

type Imports interface {

GetHomeDir() (string, error)

}


type ImageClient struct {

dirService Imports

storeName string

tagMeta   string

}
func (v *ImageClient) GetDirPath(imageName string) (string, string, error) {

home, err := v.GetHomeDir()

dirPath := path.Join(home, "images", v.storeName)

filePath := path.Join(dirPath, imageName)

return filePath, dirPath, err

}

func (v *ImageClient) GetHomeDir() (string, error) {

u, err := user.Current()

if err != nil {

 return "", pkgerrors.Wrap(err, "Current user")

}

home := u.HomeDir

return home, nil

}


To Do - Explain

To test, I'll create the test file image_test.go. A test for the GetDirPath could look like this:

import (

  "fmt"

  "testing"

  "github.com/stretchr/testify/mock"

)

type mockImports struct {

  mock.Mock

}

func (m *mockImports) GetHomeDir() (string, error) {

  fmt.Println("Mocked Get User")

  args := m.Called()

  return args.String(0), args.Error(1)

}

func TestService(t *testing.T) {

  myImports := new(mockImports)

  myImports.On("GetHomeDir").Return("home", nil)

  imageClient := ImageClient{myImports, "test_image", "test_meta"}

  //testClient := FooImageClient()

  _, dir, err := imageClient.GetDirPath("test")

  if err != nil {

    t.Errorf("Path was incorrect, got: %q, want: %q.", dir, "some_path")

  }

}


To Do - Explain



References:

  1. https://restfulapi.net/rest-architectural-constraints/

...