Skip to content

Commit 9ed7d09

Browse files
authored
Enable all default golangci-lint linters and fix issues related (#37)
* turn on default linters and fix warnings/errors as a result Signed-off-by: Jordan Dubrick <jdubrick@redhat.com> * cleanup forgotten commented out block Signed-off-by: Jordan Dubrick <jdubrick@redhat.com> * potential increase in code cov for resp body closing Signed-off-by: Jordan Dubrick <jdubrick@redhat.com> * fix lint error in test case Signed-off-by: Jordan Dubrick <jdubrick@redhat.com> * revert redundant code coverage changes Signed-off-by: Jordan Dubrick <jdubrick@redhat.com> * update defer statements and add test cases for them Signed-off-by: Jordan Dubrick <jdubrick@redhat.com> * add test cases for detector.go Signed-off-by: Jordan Dubrick <jdubrick@redhat.com> * add unit tests for DownloadDevfileTypesFromRegistry Signed-off-by: Jordan Dubrick <jdubrick@redhat.com> * consolidate closinghttp code to reduce redundancy Signed-off-by: Jordan Dubrick <jdubrick@redhat.com> * update testing for httpclose to use mock server Signed-off-by: Jordan Dubrick <jdubrick@redhat.com> * add more unit tests for code coverage Signed-off-by: Jordan Dubrick <jdubrick@redhat.com> * reintroduce err handling for closehttpresponsebody to combat warning Signed-off-by: Jordan Dubrick <jdubrick@redhat.com> * mock error for closing http body Signed-off-by: Jordan Dubrick <jdubrick@redhat.com> --------- Signed-off-by: Jordan Dubrick <jdubrick@redhat.com>
1 parent 719af19 commit 9ed7d09

File tree

16 files changed

+239
-51
lines changed

16 files changed

+239
-51
lines changed

.golangci.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ linters:
1818
# Default: false
1919
# TODO(rm3l): all default linters are disabled in the context of https://github.com/devfile/api/issues/1257 (to just enforce that io/ioutil is not used anymore),
2020
# but we should think about enabling all the default linters and fix the issues reported.
21-
disable-all: true
21+
disable-all: false
2222
enable:
2323
# Go linter that checks if package imports are in a list of acceptable packages
2424
- depguard

pkg/apis/enricher/docker_enricher.go

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,19 +32,16 @@ func (d DockerEnricher) GetSupportedLanguages() []string {
3232

3333
func (d DockerEnricher) DoEnrichLanguage(language *model.Language, _ *[]string) {
3434
// The Dockerfile language does not contain frameworks
35-
return
3635
}
3736

3837
func (d DockerEnricher) DoEnrichComponent(component *model.Component, _ model.DetectionSettings, _ *context.Context) {
3938
projectName := GetDefaultProjectName(component.Path)
4039
component.Name = projectName
4140

42-
var ports []int
43-
ports = GetPortsFromDockerFile(component.Path)
41+
ports := GetPortsFromDockerFile(component.Path)
4442
if len(ports) > 0 {
4543
component.Ports = ports
4644
}
47-
return
4845
}
4946

5047
func (d DockerEnricher) IsConfigValidForComponentDetection(language string, config string) bool {

pkg/apis/enricher/enricher.go

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -126,11 +126,10 @@ func GetPortsFromDockerFile(root string) []int {
126126
cleanFilePath := filepath.Clean(filePath)
127127
file, err := os.Open(cleanFilePath)
128128
if err == nil {
129-
defer func() error {
129+
defer func(){
130130
if err := file.Close(); err != nil {
131-
return fmt.Errorf("error closing file: %s", err)
131+
fmt.Printf("error closing file: %s", err)
132132
}
133-
return nil
134133
}()
135134
return utils.ReadPortsFromDockerfile(file)
136135
}

pkg/apis/enricher/framework/dotnet/dotnet_detector.go

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -64,20 +64,23 @@ func getFrameworks(configFilePath string) string {
6464
cleanConfigPath := filepath.Clean(configFilePath)
6565
xmlFile, err := os.Open(cleanConfigPath)
6666
if err != nil {
67+
fmt.Printf("error opening file: %s", err)
68+
return ""
69+
}
70+
byteValue, err := io.ReadAll(xmlFile)
71+
if err != nil {
72+
fmt.Printf("error reading file: %s", err)
6773
return ""
6874
}
69-
byteValue, _ := io.ReadAll(xmlFile)
70-
7175
var proj schema.DotNetProject
7276
err = xml.Unmarshal(byteValue, &proj)
7377
if err != nil {
7478
return ""
7579
}
76-
defer func() error {
80+
defer func(){
7781
if err := xmlFile.Close(); err != nil {
78-
return fmt.Errorf("error closing file: %s", err)
82+
fmt.Printf("error closing file: %s", err)
7983
}
80-
return nil
8184
}()
8285
if proj.PropertyGroup.TargetFramework != "" {
8386
return proj.PropertyGroup.TargetFramework

pkg/apis/enricher/framework/javascript/nodejs/nuxt_detector.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ func (n NuxtDetector) DoFrameworkDetection(language *model.Language, config stri
4545

4646
// DoPortsDetection searches for the port in package.json, and nuxt.config.js
4747
func (n NuxtDetector) DoPortsDetection(component *model.Component, ctx *context.Context) {
48-
ports := []int{}
48+
var ports []int
4949
regexes := []string{`--port=(\d*)`}
5050
// check if port is set in start script in package.json
5151
port := getPortFromStartScript(component.Path, regexes)

pkg/apis/enricher/framework/javascript/nodejs/vue_detector.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ func (v VueDetector) DoFrameworkDetection(language *model.Language, config strin
4646
// DoPortsDetection searches for the port in package.json, .env file, and vue.config.js
4747
func (v VueDetector) DoPortsDetection(component *model.Component, ctx *context.Context) {
4848
regexes := []string{`--port (\d*)`, `PORT=(\d*)`}
49-
ports := []int{}
49+
var ports []int
5050
// check if --port or PORT is set in start script in package.json
5151
port := getPortFromStartScript(component.Path, regexes)
5252
if utils.IsValidPort(port) {

pkg/apis/recognizer/devfile_recognizer.go

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -242,12 +242,8 @@ var DownloadDevfileTypesFromRegistry = func(url string, filter model.DevfileFilt
242242
if err != nil {
243243
return []model.DevfileType{}, err
244244
}
245-
defer func() error {
246-
if err := resp.Body.Close(); err != nil {
247-
return fmt.Errorf("error closing file: %s", err)
248-
}
249-
return nil
250-
}()
245+
246+
defer utils.CloseHttpResponseBody(resp)
251247

252248
// Check server response
253249
if resp.StatusCode != http.StatusOK {

pkg/apis/recognizer/devfile_recognizer_test.go

Lines changed: 67 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@ import (
1616
"reflect"
1717
"runtime"
1818
"testing"
19+
"net/http"
20+
"net/http/httptest"
21+
"encoding/json"
1922

2023
"github.com/devfile/alizer/pkg/apis/model"
2124
"github.com/stretchr/testify/assert"
@@ -137,6 +140,69 @@ func TestDetectLaravelDevfile(t *testing.T) {
137140
detectDevfiles(t, "laravel", []string{"php-laravel"})
138141
}
139142

143+
func TestDownloadDevfileTypesFromRegistry(t *testing.T){
144+
145+
server := httptest.NewServer(http.HandlerFunc(
146+
func(w http.ResponseWriter, r *http.Request){
147+
//Verify url was set properly
148+
if r.URL.Path != "/v2index" {
149+
t.Errorf("URL was incorrect, expected /v2index and got %s", r.URL.Path)
150+
}
151+
152+
response := []model.DevfileType{model.DevfileType{
153+
Name: "mocked-stack",
154+
Language: "python",
155+
ProjectType: "python",
156+
Tags: []string{"python"},
157+
Versions: []model.Version{},
158+
}}
159+
160+
responseJSON, _ := json.Marshal(response)
161+
w.Header().Set("Content-Type", "application/json")
162+
w.WriteHeader(http.StatusOK)
163+
_, err := w.Write(responseJSON)
164+
assert.NoError(t, err)
165+
}))
166+
defer server.Close()
167+
168+
169+
tests := []struct {
170+
name string
171+
filter model.DevfileFilter
172+
expectedDevfileType []model.DevfileType
173+
url string
174+
expectingErr bool
175+
}{
176+
{
177+
name: "Successful Download",
178+
filter: model.DevfileFilter{},
179+
expectedDevfileType: []model.DevfileType{model.DevfileType{
180+
Name: "mocked-stack",
181+
Language: "python",
182+
ProjectType: "python",
183+
Tags: []string{"python"},
184+
Versions: []model.Version{},
185+
}},
186+
url: server.URL,
187+
expectingErr: false,
188+
},
189+
{
190+
name: "Unsuccessful Download",
191+
filter: model.DevfileFilter{},
192+
expectedDevfileType: []model.DevfileType{},
193+
url: "fake-path",
194+
expectingErr: true,
195+
},
196+
}
197+
198+
for _, tt := range tests {
199+
t.Run(tt.name, func(t *testing.T) {
200+
devfileTypes, _ := DownloadDevfileTypesFromRegistry(tt.url, tt.filter)
201+
assert.EqualValues(t, devfileTypes, tt.expectedDevfileType)
202+
})
203+
}
204+
}
205+
140206
func TestGetUrlWithVersions(t *testing.T) {
141207
tests := []struct {
142208
name string
@@ -790,4 +856,4 @@ func getTestProjectPath(folder string) string {
790856
_, b, _, _ := runtime.Caller(0)
791857
basepath := filepath.Dir(b)
792858
return filepath.Join(basepath, "..", "..", "..", "resources/projects", folder)
793-
}
859+
}

pkg/utils/detector.go

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import (
2626
"regexp"
2727
"strconv"
2828
"strings"
29+
"net/http"
2930

3031
"github.com/devfile/alizer/pkg/apis/model"
3132
"github.com/devfile/alizer/pkg/schema"
@@ -134,19 +135,18 @@ func GetPomFileContent(pomFilePath string) (schema.Pom, error) {
134135
if err != nil {
135136
return schema.Pom{}, err
136137
}
137-
byteValue, _ := io.ReadAll(xmlFile)
138-
138+
byteValue, err := io.ReadAll(xmlFile)
139+
if err != nil {
140+
return schema.Pom{}, err
141+
}
142+
139143
var pom schema.Pom
140144
err = xml.Unmarshal(byteValue, &pom)
141145
if err != nil {
142146
return schema.Pom{}, err
143147
}
144-
defer func() error {
145-
if err := xmlFile.Close(); err != nil {
146-
return fmt.Errorf("error closing file: %s", err)
147-
}
148-
return nil
149-
}()
148+
149+
defer CloseFile(xmlFile)
150150
return pom, nil
151151
}
152152

@@ -353,12 +353,7 @@ func GetEnvVarsFromDockerFile(root string) ([]model.EnvVar, error) {
353353
cleanFilePath := filepath.Clean(filePath)
354354
file, err := os.Open(cleanFilePath)
355355
if err == nil {
356-
defer func() error {
357-
if err := file.Close(); err != nil {
358-
return fmt.Errorf("error closing file: %s", err)
359-
}
360-
return nil
361-
}()
356+
defer CloseFile(file)
362357
return readEnvVarsFromDockerfile(file)
363358
}
364359
}
@@ -751,3 +746,15 @@ func NormalizeSplit(file string) (string, string) {
751746
}
752747
return dir, fileName
753748
}
749+
750+
func CloseHttpResponseBody(resp *http.Response){
751+
if err := resp.Body.Close(); err != nil {
752+
fmt.Printf("error closing file: %s", err)
753+
}
754+
}
755+
756+
func CloseFile(file *os.File){
757+
if err := file.Close(); err != nil {
758+
fmt.Printf("error closing file: %s", err)
759+
}
760+
}

pkg/utils/detector_test.go

Lines changed: 113 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@ import (
77
"reflect"
88
"regexp"
99
"testing"
10+
"net/http"
11+
"net/http/httptest"
12+
"io"
13+
"fmt"
1014

1115
"github.com/devfile/alizer/pkg/apis/model"
1216
"github.com/devfile/alizer/pkg/schema"
@@ -591,7 +595,8 @@ func TestIsTagInPomXMLFile(t *testing.T) {
591595

592596
func TestGetPomFileContent(t *testing.T) {
593597
missingFileErr := "no such file or directory"
594-
598+
badXmlFileErr := "XML syntax error on line 1: expected attribute name in element"
599+
595600
testCases := []struct {
596601
name string
597602
filePath string
@@ -638,6 +643,12 @@ func TestGetPomFileContent(t *testing.T) {
638643
expectedResult: schema.Pom{},
639644
expectedError: &missingFileErr,
640645
},
646+
{
647+
name: "Case 3: File is unreadable (cannot unmarshal)",
648+
filePath: "testdata/bad-xml.xml",
649+
expectedResult: schema.Pom{},
650+
expectedError: &badXmlFileErr,
651+
},
641652
}
642653

643654
for _, tt := range testCases {
@@ -1948,3 +1959,104 @@ func TestGetApplicationFileInfo(t *testing.T) {
19481959
})
19491960
}
19501961
}
1962+
1963+
type errorBodyCloser struct {
1964+
io.Reader
1965+
}
1966+
1967+
func (ebc *errorBodyCloser) Close() error {
1968+
return fmt.Errorf("mocked error closing body")
1969+
}
1970+
1971+
func TestCloseHttpResponseBody(t *testing.T){
1972+
server := httptest.NewServer(http.HandlerFunc(
1973+
func(w http.ResponseWriter, r *http.Request){
1974+
w.WriteHeader(http.StatusOK)
1975+
_, err := w.Write([]byte(`{"test": "values"}`))
1976+
assert.NoError(t, err)
1977+
}))
1978+
defer server.Close()
1979+
1980+
tests := []struct {
1981+
name string
1982+
url string
1983+
expectErr bool
1984+
expectedOut string
1985+
}{
1986+
{
1987+
name: "Case 1: Successful Closing of File",
1988+
url: server.URL,
1989+
expectErr: false,
1990+
expectedOut: "",
1991+
},
1992+
{
1993+
name: "Case 2: Failure Closing File",
1994+
url: server.URL,
1995+
expectErr: true,
1996+
expectedOut: "error closing file: mocked error closing body",
1997+
},
1998+
}
1999+
2000+
for _, tt := range tests {
2001+
t.Run(tt.name, func(t *testing.T) {
2002+
resp, err := http.Get(tt.url)
2003+
assert.Empty(t, err)
2004+
2005+
// Below section handles the capturing of the fmt.Printf in the func being tested
2006+
captureStdout := os.Stdout
2007+
r, w, _ := os.Pipe()
2008+
os.Stdout = w
2009+
if tt.expectErr {
2010+
resp = &http.Response{
2011+
Body: &errorBodyCloser{},
2012+
}
2013+
}
2014+
CloseHttpResponseBody(resp)
2015+
w.Close()
2016+
out, _ := io.ReadAll(r)
2017+
os.Stdout = captureStdout
2018+
assert.EqualValues(t, tt.expectedOut, string(out))
2019+
2020+
})
2021+
}
2022+
}
2023+
2024+
func TestCloseFile(t *testing.T){
2025+
tests := []struct {
2026+
name string
2027+
expectErr bool
2028+
expectedOut string
2029+
}{
2030+
{
2031+
name: "Case 1: Filed closed",
2032+
expectErr: false,
2033+
expectedOut: "",
2034+
},
2035+
{
2036+
name: "Case 2: File not closed",
2037+
expectErr: true,
2038+
expectedOut: "error closing file: close testdata/pom-dependency.xml: file already closed",
2039+
},
2040+
}
2041+
2042+
file_path := "testdata/pom-dependency.xml"
2043+
2044+
for _, tt := range tests {
2045+
t.Run(tt.name, func(t *testing.T) {
2046+
open_file, _ := os.Open(file_path)
2047+
// Below section handles the capturing of the fmt.Printf in the func being tested
2048+
captureStdout := os.Stdout
2049+
r, w, _ := os.Pipe()
2050+
os.Stdout = w
2051+
// Mocking the hit of a close failure by preclosing the file
2052+
if tt.expectErr {
2053+
open_file.Close()
2054+
}
2055+
CloseFile(open_file)
2056+
w.Close()
2057+
out, _ := io.ReadAll(r)
2058+
os.Stdout = captureStdout
2059+
assert.EqualValues(t, tt.expectedOut, string(out))
2060+
})
2061+
}
2062+
}

0 commit comments

Comments
 (0)