Skip to content

Commit

Permalink
[test] Add more tests for coverage (#46)
Browse files Browse the repository at this point in the history
  • Loading branch information
cacoco authored Feb 12, 2024
1 parent ea4cbb7 commit 802ccde
Show file tree
Hide file tree
Showing 10 changed files with 300 additions and 104 deletions.
76 changes: 14 additions & 62 deletions cmd/licenses.go
Original file line number Diff line number Diff line change
@@ -1,82 +1,34 @@
package cmd

import (
"fmt"
"strings"

"github.com/cacoco/codemetagenerator/internal/utils"
"github.com/ohler55/ojg/oj"
"github.com/spf13/cobra"
)

func validateLicenseId(basedir string) func(string) error {
return func(id string) error {
supportedLicenses := SupportedLicenses.getSupportedLicenses()
if supportedLicenses == nil {
return fmt.Errorf("SPDX licenses have not be downloaded, please run `codemeta licenses refresh` to download the SPDX licenses")
}
for _, license := range supportedLicenses {
if license == id {
return nil
}
}
return fmt.Errorf("invalid SPDX license ID: " + id + ", see: https://spdx.org/licenses/ for a list of valid values")
}
}

func getLicenseReference(basedir string, id string) (*string, error) {
bytes, err := utils.LoadFile(utils.GetLicensesFilePath(basedir))
if err != nil {
return nil, err
}
var licenses map[string]string
err = oj.Unmarshal(bytes, &licenses)

if err != nil {
return nil, err
}

reference, ok := licenses[id]
if !ok {
return nil, fmt.Errorf("Invalid license ID: " + id)
func licenses(writer utils.Writer) ([]string, error) {
supportedLicenses := SupportedLicenses.getSupportedLicenses()
// list licenses
var list []string = make([]string, 0)
for _, license := range supportedLicenses {
list = append(list, license)
writer.Println(license)
}
return &reference, nil
return list, nil
}

// licensesCmd represents the licenses command
var licensesCmd = &cobra.Command{
Use: "licenses [refresh]",
Args: cobra.RangeArgs(0, 1),
Short: "List or refresh cached SPDX (https://spdx.org/licenses/) license IDs",
Args: cobra.NoArgs,
Short: "List current SPDX IDs (https://spdx.org/licenses/)",
Long: `
Use this command to list license SPDX ids from the https://spdx.org/licenses/.
Use this command to list currently supported SPDX IDs from https://spdx.org/licenses/.
This is a long list and as such you may want to pipe the output into "more" or
"less" to view it.
Pass the "refresh" argument to update the cached list of licenses.`,
"less" to view it. See: https://spdx.dev/learn/handling-license-info/#why`,
RunE: func(cmd *cobra.Command, args []string) error {
writer := &utils.StdoutWriter{}

if len(args) == 0 {
supportedLicenses := SupportedLicenses.getSupportedLicenses()
// list licenses
for _, license := range supportedLicenses {
fmt.Println(license)
}
return nil
} else if len(args) == 1 && args[0] == "refresh" {
// update licenses file
err := downloadSPDXLicenses(utils.UserHomeDir, utils.MkHttpClient(), true)
if err != nil {
handleErr(writer, err)
return fmt.Errorf("unable to update SPDX licenses file: %s", err.Error())
}
fmt.Println("✅ Successfully updated SPDX licenses file.")
return nil
} else {
return fmt.Errorf("unrecognized argument(s): '%s'", strings.Join(args, " "))
}
_, err := licenses(&utils.StdoutWriter{})
return err
},
}

Expand Down
58 changes: 19 additions & 39 deletions cmd/licenses_test.go
Original file line number Diff line number Diff line change
@@ -1,40 +1,16 @@
package cmd

import (
"bytes"
"os"
"testing"

"github.com/cacoco/codemetagenerator/internal/utils"
"github.com/onsi/gomega"
"github.com/spf13/cobra"
)

func TestGetLicenseReference(t *testing.T) {
g := gomega.NewWithT(t)

temp := t.TempDir()
// setup
os.Mkdir(utils.GetHomeDir(temp), 0755)
file, le := os.ReadFile("../testdata/spdx-licenses.json")
if le != nil {
t.Errorf("Unexpected error: %v", le)
}
we := utils.WriteFile(utils.GetLicensesFilePath(temp), file)
if we != nil {
t.Errorf("Unexpected error: %v", we)
}

reference, err := getLicenseReference(temp, "Apache-2.0")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
g.Ω(*reference).Should(gomega.Equal("https://spdx.org/licenses/Apache-2.0.html"))
}

func reset() {
SupportedLicenses = Licenses{}
}

func TestValidateLicenseId1(t *testing.T) {
func Test_ExecuteLicensesCmd(t *testing.T) {
g := gomega.NewWithT(t)

temp := t.TempDir()
Expand All @@ -55,19 +31,23 @@ func TestValidateLicenseId1(t *testing.T) {
}
SupportedLicenses.setSupportedLicenses(*supported)
defer reset() // make sure to reset the global variable
writer := utils.TestWriter{}

var validateFn = validateLicenseId(temp)
err = validateFn("Apache-2.0")
g.Expect(err).To(gomega.BeNil())
}

func TestValidateLicenseId2(t *testing.T) {
g := gomega.NewWithT(t)
var list []string
licensesCmd := &cobra.Command{Use: "licenses", RunE: func(cmd *cobra.Command, args []string) error {
list, err = licenses(&writer)
return err
},
}
buf := bytes.NewBufferString("")
licensesCmd.SetOut(buf)
licensesCmd.SetErr(buf)
licensesCmd.SetArgs([]string{})

temp := t.TempDir()
err = licensesCmd.Execute()
if err != nil {
t.Errorf("Unexpected error: %v", err)
}

// SupportedLicenses is nil, should error
var validateFn = validateLicenseId(temp)
err := validateFn("Apache-2.0")
g.Expect(err).ToNot(gomega.BeNil())
g.Ω(list).Should(gomega.Equal(*supported))
}
4 changes: 2 additions & 2 deletions cmd/new.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,15 +115,15 @@ func new(basedir string, reader utils.Reader, writer utils.Writer, inFile string
return err
}

validateFn := validateLicenseId(basedir)
validateFn := validateLicenseId(writer, basedir)
license, err := utils.MkPrompt(&stdin, &stdout, "Enter the SPDX license ID for the project (see: https://spdx.org/licenses/)", validateFn)
if err != nil {
return err
}

var licenseDetailsUrl string
if (*license) != "" {
referenceUrl, err := getLicenseReference(basedir, *license)
referenceUrl, err := getLicenseReference(writer, basedir, *license)
if err != nil {
handleErr(writer, err)
return writer.Errorf("unable to create new license details URL")
Expand Down
36 changes: 36 additions & 0 deletions cmd/refresh.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package cmd

import (
"net/http"

"github.com/cacoco/codemetagenerator/internal/utils"
"github.com/spf13/cobra"
)

func refresh(writer utils.Writer, basedir string, httpClient *http.Client) error {
// update licenses file
err := downloadSPDXLicenses(basedir, httpClient, true)
if err != nil {
handleErr(writer, err)
return writer.Errorf("unable to update SPDX licenses file: %s", err.Error())
}
writer.Println("✅ Successfully updated SPDX licenses file.")
return nil
}

// refreshCmd represents the refresh command
var refreshCmd = &cobra.Command{
Use: "refresh",
Short: "Refresh the list of current SPDX IDs (https://spdx.org/licenses/)",
Long: `
Use this command to refresh the stored list of currently supported SPDX IDs from https://spdx.org/licenses/.
See: https://spdx.dev/learn/handling-license-info/#why`,
RunE: func(cmd *cobra.Command, args []string) error {
return refresh(&utils.StdoutWriter{}, utils.UserHomeDir, utils.MkHttpClient())
},
}

func init() {
licensesCmd.AddCommand(refreshCmd)
}
60 changes: 60 additions & 0 deletions cmd/refresh_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package cmd

import (
"bytes"
"os"
"testing"

"github.com/cacoco/codemetagenerator/internal/utils"
"github.com/ohler55/ojg/oj"
"github.com/onsi/gomega"
"github.com/spf13/cobra"
)

func Test_ExecuteRefreshCmd(t *testing.T) {
g := gomega.NewWithT(t)

temp := t.TempDir()
// setup
os.Mkdir(utils.GetHomeDir(temp), 0755)
file, err := os.ReadFile("../testdata/spdx-full-licenses.json")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
var stack utils.Stack[string]
stack.Push(string(file))
httpClient := utils.NewTestHttpClient(&stack)
writer := utils.TestWriter{}

refreshCmd := &cobra.Command{Use: "refresh", RunE: func(cmd *cobra.Command, args []string) error {
return refresh(writer, temp, httpClient)
},
}
buf := bytes.NewBufferString("")
refreshCmd.SetOut(buf)
refreshCmd.SetErr(buf)
refreshCmd.SetArgs([]string{})

err = refreshCmd.Execute()
if err != nil {
t.Errorf("Unexpected error: %v", err)
}

// read converted test file
var expected map[string]string = make(map[string]string)
file, err = os.ReadFile("../testdata/spdx-licenses.json")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
oj.Unmarshal(file, &expected)

var actual map[string]string = make(map[string]string)
fileBytes, err := utils.LoadFile(utils.GetLicensesFilePath(temp))
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
oj.Unmarshal(fileBytes, &actual)

// check "downloaded" file against converted test file
g.Ω(actual).Should(gomega.Equal(expected))
}
35 changes: 35 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"sync"

"github.com/cacoco/codemetagenerator/internal/utils"
"github.com/ohler55/ojg/oj"
"github.com/spf13/cobra"
)

Expand All @@ -16,6 +17,40 @@ func SetVersionInfo(version, commit, date string) {
rootCmd.Version = fmt.Sprintf("%s (Built on %s from Git SHA %s)", version, date, commit)
}

func validateLicenseId(writer utils.Writer, basedir string) func(string) error {
return func(id string) error {
supportedLicenses := SupportedLicenses.getSupportedLicenses()
if supportedLicenses == nil {
return writer.Errorf("SPDX licenses have not be downloaded, please run `codemeta licenses refresh` to download the SPDX licenses")
}
for _, license := range supportedLicenses {
if license == id {
return nil
}
}
return writer.Errorf("invalid SPDX license ID: " + id + ", see: https://spdx.org/licenses/ for a list of valid values")
}
}

func getLicenseReference(writer utils.Writer, basedir string, id string) (*string, error) {
bytes, err := utils.LoadFile(utils.GetLicensesFilePath(basedir))
if err != nil {
return nil, err
}
var licenses map[string]string
err = oj.Unmarshal(bytes, &licenses)

if err != nil {
return nil, err
}

reference, ok := licenses[id]
if !ok {
return nil, writer.Errorf("Invalid license ID: " + id)
}
return &reference, nil
}

func loadSupportedLicenses(basedir string, httpClient *http.Client) (*[]string, error) {
// if the licenses file doesn't exist, download a new SPDX file and cache it
if _, err := os.Stat(utils.GetLicensesFilePath(basedir)); os.IsNotExist(err) {
Expand Down
Loading

0 comments on commit 802ccde

Please sign in to comment.