Skip to content

Commit 802ccde

Browse files
authored
[test] Add more tests for coverage (#46)
1 parent ea4cbb7 commit 802ccde

File tree

10 files changed

+300
-104
lines changed

10 files changed

+300
-104
lines changed

cmd/licenses.go

Lines changed: 14 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -1,82 +1,34 @@
11
package cmd
22

33
import (
4-
"fmt"
5-
"strings"
6-
74
"github.com/cacoco/codemetagenerator/internal/utils"
8-
"github.com/ohler55/ojg/oj"
95
"github.com/spf13/cobra"
106
)
117

12-
func validateLicenseId(basedir string) func(string) error {
13-
return func(id string) error {
14-
supportedLicenses := SupportedLicenses.getSupportedLicenses()
15-
if supportedLicenses == nil {
16-
return fmt.Errorf("SPDX licenses have not be downloaded, please run `codemeta licenses refresh` to download the SPDX licenses")
17-
}
18-
for _, license := range supportedLicenses {
19-
if license == id {
20-
return nil
21-
}
22-
}
23-
return fmt.Errorf("invalid SPDX license ID: " + id + ", see: https://spdx.org/licenses/ for a list of valid values")
24-
}
25-
}
26-
27-
func getLicenseReference(basedir string, id string) (*string, error) {
28-
bytes, err := utils.LoadFile(utils.GetLicensesFilePath(basedir))
29-
if err != nil {
30-
return nil, err
31-
}
32-
var licenses map[string]string
33-
err = oj.Unmarshal(bytes, &licenses)
34-
35-
if err != nil {
36-
return nil, err
37-
}
38-
39-
reference, ok := licenses[id]
40-
if !ok {
41-
return nil, fmt.Errorf("Invalid license ID: " + id)
8+
func licenses(writer utils.Writer) ([]string, error) {
9+
supportedLicenses := SupportedLicenses.getSupportedLicenses()
10+
// list licenses
11+
var list []string = make([]string, 0)
12+
for _, license := range supportedLicenses {
13+
list = append(list, license)
14+
writer.Println(license)
4215
}
43-
return &reference, nil
16+
return list, nil
4417
}
4518

4619
// licensesCmd represents the licenses command
4720
var licensesCmd = &cobra.Command{
4821
Use: "licenses [refresh]",
49-
Args: cobra.RangeArgs(0, 1),
50-
Short: "List or refresh cached SPDX (https://spdx.org/licenses/) license IDs",
22+
Args: cobra.NoArgs,
23+
Short: "List current SPDX IDs (https://spdx.org/licenses/)",
5124
Long: `
52-
Use this command to list license SPDX ids from the https://spdx.org/licenses/.
25+
Use this command to list currently supported SPDX IDs from https://spdx.org/licenses/.
5326
5427
This is a long list and as such you may want to pipe the output into "more" or
55-
"less" to view it.
56-
57-
Pass the "refresh" argument to update the cached list of licenses.`,
28+
"less" to view it. See: https://spdx.dev/learn/handling-license-info/#why`,
5829
RunE: func(cmd *cobra.Command, args []string) error {
59-
writer := &utils.StdoutWriter{}
60-
61-
if len(args) == 0 {
62-
supportedLicenses := SupportedLicenses.getSupportedLicenses()
63-
// list licenses
64-
for _, license := range supportedLicenses {
65-
fmt.Println(license)
66-
}
67-
return nil
68-
} else if len(args) == 1 && args[0] == "refresh" {
69-
// update licenses file
70-
err := downloadSPDXLicenses(utils.UserHomeDir, utils.MkHttpClient(), true)
71-
if err != nil {
72-
handleErr(writer, err)
73-
return fmt.Errorf("unable to update SPDX licenses file: %s", err.Error())
74-
}
75-
fmt.Println("✅ Successfully updated SPDX licenses file.")
76-
return nil
77-
} else {
78-
return fmt.Errorf("unrecognized argument(s): '%s'", strings.Join(args, " "))
79-
}
30+
_, err := licenses(&utils.StdoutWriter{})
31+
return err
8032
},
8133
}
8234

cmd/licenses_test.go

Lines changed: 19 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,16 @@
11
package cmd
22

33
import (
4+
"bytes"
45
"os"
56
"testing"
67

78
"github.com/cacoco/codemetagenerator/internal/utils"
89
"github.com/onsi/gomega"
10+
"github.com/spf13/cobra"
911
)
1012

11-
func TestGetLicenseReference(t *testing.T) {
12-
g := gomega.NewWithT(t)
13-
14-
temp := t.TempDir()
15-
// setup
16-
os.Mkdir(utils.GetHomeDir(temp), 0755)
17-
file, le := os.ReadFile("../testdata/spdx-licenses.json")
18-
if le != nil {
19-
t.Errorf("Unexpected error: %v", le)
20-
}
21-
we := utils.WriteFile(utils.GetLicensesFilePath(temp), file)
22-
if we != nil {
23-
t.Errorf("Unexpected error: %v", we)
24-
}
25-
26-
reference, err := getLicenseReference(temp, "Apache-2.0")
27-
if err != nil {
28-
t.Errorf("Unexpected error: %v", err)
29-
}
30-
g.Ω(*reference).Should(gomega.Equal("https://spdx.org/licenses/Apache-2.0.html"))
31-
}
32-
33-
func reset() {
34-
SupportedLicenses = Licenses{}
35-
}
36-
37-
func TestValidateLicenseId1(t *testing.T) {
13+
func Test_ExecuteLicensesCmd(t *testing.T) {
3814
g := gomega.NewWithT(t)
3915

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

59-
var validateFn = validateLicenseId(temp)
60-
err = validateFn("Apache-2.0")
61-
g.Expect(err).To(gomega.BeNil())
62-
}
63-
64-
func TestValidateLicenseId2(t *testing.T) {
65-
g := gomega.NewWithT(t)
36+
var list []string
37+
licensesCmd := &cobra.Command{Use: "licenses", RunE: func(cmd *cobra.Command, args []string) error {
38+
list, err = licenses(&writer)
39+
return err
40+
},
41+
}
42+
buf := bytes.NewBufferString("")
43+
licensesCmd.SetOut(buf)
44+
licensesCmd.SetErr(buf)
45+
licensesCmd.SetArgs([]string{})
6646

67-
temp := t.TempDir()
47+
err = licensesCmd.Execute()
48+
if err != nil {
49+
t.Errorf("Unexpected error: %v", err)
50+
}
6851

69-
// SupportedLicenses is nil, should error
70-
var validateFn = validateLicenseId(temp)
71-
err := validateFn("Apache-2.0")
72-
g.Expect(err).ToNot(gomega.BeNil())
52+
g.Ω(list).Should(gomega.Equal(*supported))
7353
}

cmd/new.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -115,15 +115,15 @@ func new(basedir string, reader utils.Reader, writer utils.Writer, inFile string
115115
return err
116116
}
117117

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

124124
var licenseDetailsUrl string
125125
if (*license) != "" {
126-
referenceUrl, err := getLicenseReference(basedir, *license)
126+
referenceUrl, err := getLicenseReference(writer, basedir, *license)
127127
if err != nil {
128128
handleErr(writer, err)
129129
return writer.Errorf("unable to create new license details URL")

cmd/refresh.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package cmd
2+
3+
import (
4+
"net/http"
5+
6+
"github.com/cacoco/codemetagenerator/internal/utils"
7+
"github.com/spf13/cobra"
8+
)
9+
10+
func refresh(writer utils.Writer, basedir string, httpClient *http.Client) error {
11+
// update licenses file
12+
err := downloadSPDXLicenses(basedir, httpClient, true)
13+
if err != nil {
14+
handleErr(writer, err)
15+
return writer.Errorf("unable to update SPDX licenses file: %s", err.Error())
16+
}
17+
writer.Println("✅ Successfully updated SPDX licenses file.")
18+
return nil
19+
}
20+
21+
// refreshCmd represents the refresh command
22+
var refreshCmd = &cobra.Command{
23+
Use: "refresh",
24+
Short: "Refresh the list of current SPDX IDs (https://spdx.org/licenses/)",
25+
Long: `
26+
Use this command to refresh the stored list of currently supported SPDX IDs from https://spdx.org/licenses/.
27+
28+
See: https://spdx.dev/learn/handling-license-info/#why`,
29+
RunE: func(cmd *cobra.Command, args []string) error {
30+
return refresh(&utils.StdoutWriter{}, utils.UserHomeDir, utils.MkHttpClient())
31+
},
32+
}
33+
34+
func init() {
35+
licensesCmd.AddCommand(refreshCmd)
36+
}

cmd/refresh_test.go

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package cmd
2+
3+
import (
4+
"bytes"
5+
"os"
6+
"testing"
7+
8+
"github.com/cacoco/codemetagenerator/internal/utils"
9+
"github.com/ohler55/ojg/oj"
10+
"github.com/onsi/gomega"
11+
"github.com/spf13/cobra"
12+
)
13+
14+
func Test_ExecuteRefreshCmd(t *testing.T) {
15+
g := gomega.NewWithT(t)
16+
17+
temp := t.TempDir()
18+
// setup
19+
os.Mkdir(utils.GetHomeDir(temp), 0755)
20+
file, err := os.ReadFile("../testdata/spdx-full-licenses.json")
21+
if err != nil {
22+
t.Errorf("Unexpected error: %v", err)
23+
}
24+
var stack utils.Stack[string]
25+
stack.Push(string(file))
26+
httpClient := utils.NewTestHttpClient(&stack)
27+
writer := utils.TestWriter{}
28+
29+
refreshCmd := &cobra.Command{Use: "refresh", RunE: func(cmd *cobra.Command, args []string) error {
30+
return refresh(writer, temp, httpClient)
31+
},
32+
}
33+
buf := bytes.NewBufferString("")
34+
refreshCmd.SetOut(buf)
35+
refreshCmd.SetErr(buf)
36+
refreshCmd.SetArgs([]string{})
37+
38+
err = refreshCmd.Execute()
39+
if err != nil {
40+
t.Errorf("Unexpected error: %v", err)
41+
}
42+
43+
// read converted test file
44+
var expected map[string]string = make(map[string]string)
45+
file, err = os.ReadFile("../testdata/spdx-licenses.json")
46+
if err != nil {
47+
t.Errorf("Unexpected error: %v", err)
48+
}
49+
oj.Unmarshal(file, &expected)
50+
51+
var actual map[string]string = make(map[string]string)
52+
fileBytes, err := utils.LoadFile(utils.GetLicensesFilePath(temp))
53+
if err != nil {
54+
t.Errorf("Unexpected error: %v", err)
55+
}
56+
oj.Unmarshal(fileBytes, &actual)
57+
58+
// check "downloaded" file against converted test file
59+
g.Ω(actual).Should(gomega.Equal(expected))
60+
}

cmd/root.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"sync"
88

99
"github.com/cacoco/codemetagenerator/internal/utils"
10+
"github.com/ohler55/ojg/oj"
1011
"github.com/spf13/cobra"
1112
)
1213

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

20+
func validateLicenseId(writer utils.Writer, basedir string) func(string) error {
21+
return func(id string) error {
22+
supportedLicenses := SupportedLicenses.getSupportedLicenses()
23+
if supportedLicenses == nil {
24+
return writer.Errorf("SPDX licenses have not be downloaded, please run `codemeta licenses refresh` to download the SPDX licenses")
25+
}
26+
for _, license := range supportedLicenses {
27+
if license == id {
28+
return nil
29+
}
30+
}
31+
return writer.Errorf("invalid SPDX license ID: " + id + ", see: https://spdx.org/licenses/ for a list of valid values")
32+
}
33+
}
34+
35+
func getLicenseReference(writer utils.Writer, basedir string, id string) (*string, error) {
36+
bytes, err := utils.LoadFile(utils.GetLicensesFilePath(basedir))
37+
if err != nil {
38+
return nil, err
39+
}
40+
var licenses map[string]string
41+
err = oj.Unmarshal(bytes, &licenses)
42+
43+
if err != nil {
44+
return nil, err
45+
}
46+
47+
reference, ok := licenses[id]
48+
if !ok {
49+
return nil, writer.Errorf("Invalid license ID: " + id)
50+
}
51+
return &reference, nil
52+
}
53+
1954
func loadSupportedLicenses(basedir string, httpClient *http.Client) (*[]string, error) {
2055
// if the licenses file doesn't exist, download a new SPDX file and cache it
2156
if _, err := os.Stat(utils.GetLicensesFilePath(basedir)); os.IsNotExist(err) {

0 commit comments

Comments
 (0)