Skip to content

Commit

Permalink
fix: correct the unit tests code
Browse files Browse the repository at this point in the history
refactor: fix golangci lint issue
build: go mod tidy
  • Loading branch information
Nicconike committed Sep 19, 2024
1 parent 168bda7 commit 203b7b7
Show file tree
Hide file tree
Showing 10 changed files with 285 additions and 92 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/docker.yml
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ jobs:
with:
context: .
file: ./Dockerfile
push: ${{ github.event_name != 'pull_request' }}
push: ${{ github.event_name != 'pull_request' && steps.meta.outputs.tags != '' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ jobs:
permissions:
contents: write
packages: write
id-token: write
outputs:
new_release_version: ${{ steps.semantic.outputs.version }}
steps:
Expand Down
11 changes: 1 addition & 10 deletions .goreleaser.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,7 @@ archives:
format: zip

changelog:
sort: asc
groups:
- title: Features
regexp: "^.*feat[(\\w)]*:+.*$"
order: 0
- title: "Bug Fixes"
regexp: "^.*fix[(\\w)]*:+.*$"
order: 1
- title: Others
order: 999
disable: true

release:
github:
Expand Down
40 changes: 40 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,46 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html) and [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/).

## 2.0.0 (2024-09-19)

#### 📣 Breaking Changes

* update code with interfaces (168bda7c)
```
test: add unittests for main.go
refactor: refactor all code as per interfaces implementation
ci: update package release
build: update go.mod
docs: update readme
BREAKING CHANGE: Interfaces Implementation and now prompt for download with path
```

#### 📄 Documentation

* add security policy & PR template (e60659b7)
* update changelog (2c4913d6)

#### 🔀 Code Refactoring

* fix lint issues for unittests (fd6183f6)

#### 🚧 Chores

* **deps:** bump github.com/schollz/progressbar/v3 (#4) (0dc10f57)

#### 🔁 CI

* bump golangci/golangci-lint-action in the github-actions group (#3) (e29d363f)
* add cosign image step (9de12705)
* update tags (54772870)
* fix workflows (efeb78b0)
* update docker.yml to use GH App token (910d9150)
* Add docker CI (4c81a0c2)
* update codeql for go (ad7cdb2b)
* Create codeql.yml (7682fcf1)


## 1.2.0 (2024-09-12)

#### 🎁 Feature
Expand Down
9 changes: 7 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,17 @@ module github.com/Nicconike/AutomatedGo

go 1.17

require github.com/schollz/progressbar/v3 v3.15.0
require (
github.com/schollz/progressbar/v3 v3.15.0
github.com/stretchr/testify v1.5.1
)

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/stretchr/testify v1.5.1 // indirect
github.com/stretchr/objx v0.1.0 // indirect
golang.org/x/sys v0.25.0 // indirect
golang.org/x/term v0.24.0 // indirect
gopkg.in/yaml.v2 v2.2.8 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/schollz/progressbar/v3 v3.15.0 h1:cNZmcNiVyea6oofBTg80ZhVXxf3wG/JoAhqCCwopkQo=
github.com/schollz/progressbar/v3 v3.15.0/go.mod h1:ncBdc++eweU0dQoeZJ3loXoAc+bjaallHRIm8pVVeQM=
github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4=
Expand All @@ -20,6 +21,7 @@ golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34=
golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.24.0 h1:Mh5cbb+Zk2hqqXNO7S1iTjEphVL+jb8ZWaqh/g+JWkM=
golang.org/x/term v0.24.0/go.mod h1:lOBK/LVxemqiMij05LGJ0tzNr8xlmwBRJ81PX6wVLH8=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
Expand Down
23 changes: 0 additions & 23 deletions pkg/service.go

This file was deleted.

38 changes: 37 additions & 1 deletion tests/unit/checksum_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package tests

import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
Expand Down Expand Up @@ -76,6 +77,41 @@ func TestGetOfficialChecksum(t *testing.T) {
want: "",
wantErr: "checksum not found for invalid.tar.gz",
},
{
name: "HTTP failure",
serverFunc: func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Service unavailable", http.StatusServiceUnavailable)
},
filename: goBinary,
want: "",
wantErr: "failed to fetch Go releases: HTTP status 503",
},
{
name: "JSON parsing error",
serverFunc: func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("invalid json"))
},
filename: goBinary,
want: "",
wantErr: "failed to parse JSON",
},
{
name: "Read body error",
serverFunc: func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
io.WriteString(w, "{")
// Simulate a read body error by closing the connection prematurely
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
conn, _, _ := w.(http.Hijacker).Hijack()
conn.Close()
},
filename: goBinary,
want: "",
wantErr: "failed to read response body",
},
}

for _, tt := range tests {
Expand Down Expand Up @@ -115,7 +151,7 @@ func assertChecksum(t *testing.T, got string, err error, expected string) {
t.Fatalf("CalculateFileChecksum() error = %v", err)
}
if got != expected {
t.Errorf("CalculateFileChecksum() = %v, want %v", got, expected)
t.Errorf("CalculateFileChecksum() = %v ,want %v", got, expected)
}
}

Expand Down
126 changes: 71 additions & 55 deletions tests/unit/downloader_test.go
Original file line number Diff line number Diff line change
@@ -1,86 +1,102 @@
package tests

import (
"net/http"
"net/http/httptest"
"os"
"fmt"
"runtime"
"testing"

"github.com/Nicconike/AutomatedGo/pkg"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)

func createTestServer(status int, response string) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(status)
w.Write([]byte(response))
}))
// MockDownloader is a mock implementation of the FileDownloader interface
type MockDownloader struct {
mock.Mock
}

func createTemp(t *testing.T) *os.File {
t.Helper()
tmpfile, err := os.CreateTemp("", "downloaded")
if err != nil {
t.Fatal(err)
}
return tmpfile
func (m *MockDownloader) Download(url, filename string) error {
args := m.Called(url, filename)
return args.Error(0)
}

func runDownloadTest(t *testing.T, url string, filename string, expectedError string, expectedContent string) {
t.Helper()
downloader := pkg.DefaultDownloader{}
err := downloader.Download(url, filename)
// MockRemover is a mock implementation of the FileRemover interface
type MockRemover struct {
mock.Mock
}

if expectedError != "" {
if err == nil || err.Error() != expectedError {
t.Errorf("Download() error = %v, wantErr %v", err, expectedError)
}
return
}
func (m *MockRemover) Remove(filename string) error {
args := m.Called(filename)
return args.Error(0)
}

if err != nil {
t.Fatalf("Download() unexpected error = %v", err)
}
// MockChecksumCalculator is a mock implementation of the ChecksumCalculator interface
type MockChecksumCalculator struct {
mock.Mock
}

content, err := os.ReadFile(filename)
if err != nil {
t.Fatalf("ReadFile() error = %v", err)
}
func (m *MockChecksumCalculator) GetOfficialChecksum(filename string) (string, error) {
args := m.Called(filename)
return args.String(0), args.Error(1)
}

if string(content) != expectedContent {
t.Errorf("Downloaded content = %v, want %v", string(content), expectedContent)
}
func (m *MockChecksumCalculator) Calculate(filename string) (string, error) {
args := m.Called(filename)
return args.String(0), args.Error(1)
}

func TestDownload(t *testing.T) {
func TestDownloadGo(t *testing.T) {
tests := []struct {
name string
serverResponse string
serverStatus int
expectedError string
name string
version string
targetOS string
arch string
path string
setupMocks func(d *MockDownloader, r *MockRemover, c *MockChecksumCalculator)
expectedError error
}{
{
name: "Successful download",
serverResponse: "file content",
serverStatus: http.StatusOK,
expectedError: "",
},
{
name: "Server error",
serverResponse: "",
serverStatus: http.StatusInternalServerError,
expectedError: "unexpected status code: 500",
name: "Successful download and checksum verification",
version: "go1.16.5",
targetOS: runtime.GOOS,
arch: runtime.GOARCH,
path: "/tmp",
setupMocks: func(d *MockDownloader, r *MockRemover, c *MockChecksumCalculator) {
var extension string
if runtime.GOOS == "windows" {
extension = "zip"
} else {
extension = "tar.gz"
}
filename := fmt.Sprintf("/tmp/go1.16.5.%s-%s.%s", runtime.GOOS, runtime.GOARCH, extension)

c.On("GetOfficialChecksum", filename).Return("checksum-value", nil)
d.On("Download", fmt.Sprintf(pkg.DownloadURLFormat, "1.16.5", runtime.GOOS, runtime.GOARCH, extension), filename).Return(nil)
c.On("Calculate", filename).Return("checksum-value", nil)
},
expectedError: nil,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
server := createTestServer(tt.serverStatus, tt.serverResponse)
defer server.Close()
mockDownloader := new(MockDownloader)
mockRemover := new(MockRemover)
mockChecksumCalculator := new(MockChecksumCalculator)

tt.setupMocks(mockDownloader, mockRemover, mockChecksumCalculator)

err := pkg.DownloadGo(tt.version, tt.targetOS, tt.arch, tt.path, mockDownloader, mockRemover, mockChecksumCalculator)

tmpfile := createTemp(t)
defer os.Remove(tmpfile.Name())
if tt.expectedError != nil {
assert.EqualError(t, err, tt.expectedError.Error())
} else {
assert.NoError(t, err)
}

runDownloadTest(t, server.URL, tmpfile.Name(), tt.expectedError, tt.serverResponse)
mockDownloader.AssertExpectations(t)
mockRemover.AssertExpectations(t)
mockChecksumCalculator.AssertExpectations(t)
})
}
}
Loading

0 comments on commit 203b7b7

Please sign in to comment.