-2

I have a simple package in my Go program to generate a hash ID.

I've also written a test for it but not able to understand why I'm only getting 83% of statements covered.

Below is my package function code:

package hashgen

import (
    "math/rand"
    "time"

    "github.com/speps/go-hashids"
)

// GenHash function will generate a unique Hash using the current time in Unix epoch format as the seed
func GenHash() (string, error) {

    UnixTime := time.Now().UnixNano()
    IntUnixTime := int(UnixTime)

    hd := hashids.NewData()
    hd.Salt = "test"
    hd.MinLength = 30
    h, err := hashids.NewWithData(hd)
    if err != nil {
        return "", err
    }
    e, err := h.Encode([]int{IntUnixTime, IntUnixTime + rand.Intn(1000)})

    if err != nil {
        return "", err
    }

    return e, nil
}

Below is my test code:

package hashgen

import (
    "testing"

    "github.com/stretchr/testify/assert"
)

func TestGenHash(t *testing.T) {
    hash, err := GenHash()
    if err != nil {
        assert.Error(t, err, "Not able to generate Hash")

    }
    assert.Nil(t, err)
    assert.True(t, len(hash) > 0)
}

Running Go test with coverprofile mentions that following portions are not covered by the test:

if err != nil {
        return "", err
    }

Any advice?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Luca Brasi
  • 681
  • 2
  • 12
  • 28
  • 3
    Do you test with an input that causes `hashids.NewWithData(hd)` to return an error? If not, then the body of the `if` will never be executed, so your tests don't cover it. – hnefatl Feb 07 '19 at 08:27
  • 1
    I suggest using an editor that shows which lines are covered in real time. Atom does this. I expect VS Code, Goland, or any other popular editor/IDE does the same. – Jonathan Hall Feb 07 '19 at 08:29
  • 1
    `go test -coverprofile=coverage.out && go tool cover -html=coverage.out` and you'll see. – Volker Feb 07 '19 at 08:44

1 Answers1

-2

Thanks for the replies.

I broken down my function GenHash() into smaller pieces to test the errors returned by the go-hashids package. Now I'm able to increase the test coverage percentage.

enter image description here

package hashgen

import (
    "testing"

    "github.com/stretchr/testify/assert"
)

func TestGenHash(t *testing.T) {
    hash, err := GenHash()
    if err != nil {
        assert.Error(t, err, "Not able to generate Hash")

    }
    assert.Nil(t, err)
    assert.True(t, len(hash) > 0)
}

func TestNewhdData(t *testing.T) {
    hd := newhdData()

    assert.NotNil(t, hd)
}

func TestNewHashID(t *testing.T) {
    hd := newhdData()

    hd.Alphabet = "A "
    hd.Salt = "test"
    hd.MinLength = 30

    _, err := newHashID(hd)

    assert.Errorf(t, err, "HashIDData does not meet requirements: %v", err)

}
Luca Brasi
  • 681
  • 2
  • 12
  • 28