Skip to content

Commit

Permalink
test: add unit tests for service.go
Browse files Browse the repository at this point in the history
ci: add cleanup to release workflow
  • Loading branch information
Nicconike committed Oct 17, 2024
1 parent 9ca3e3f commit 96f47d2
Show file tree
Hide file tree
Showing 5 changed files with 211 additions and 93 deletions.
90 changes: 0 additions & 90 deletions .github/workflows/cleanup.yml

This file was deleted.

81 changes: 81 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,84 @@ jobs:
if: steps.semantic.outputs.version != ''
run: |
go list -m github.com/Nicconike/AutomatedGo/v2@v${{ steps.semantic.outputs.version }}
cleanup:
runs-on: ubuntu-latest
name: Cleanup
needs: release
permissions:
contents: read
packages: write
id-token: write
steps:
- name: Checkout Repo
uses: actions/checkout@v4

- name: Login to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ vars.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_TOKEN }}

- name: Login to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}

- name: Delete Old Docker Hub Tags
run: |
echo "Fetching Docker Hub tags..."
tags=$(curl -s -H "Authorization: Bearer ${{ secrets.DOCKER_TOKEN }}" "https://hub.docker.com/v2/repositories/${{ vars.DOCKER_USERNAME }}/automatedgo/tags" | jq -r '.results[].name')
echo "Tags found in Docker Hub:"
echo "$tags"
latest_tag=$(echo "$tags" | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | sort -rV | head -n 1)
echo "Latest semantic version tag is $latest_tag"
for tag in $tags; do
if [[ "$tag" != "master" && "$tag" != "$latest_tag" ]]; then
echo "Deleting tag $tag from Docker Hub"
curl -X DELETE -H "Authorization: Bearer ${{ secrets.DOCKER_TOKEN }}" "https://hub.docker.com/v2/repositories/${{ vars.DOCKER_USERNAME }}/automatedgo/tags/$tag/"
else
echo "Keeping tag $tag"
fi
done
- name: Delete Old GHCR Tags
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
REPO_OWNER: ${{ github.repository_owner }}
PACKAGE_NAME: "AutomatedGo"
run: |
echo "Fetching GHCR tags..."
page=1
all_tags=""
while true; do
tags=$(curl -s -H "Authorization: Bearer $GITHUB_TOKEN" \
"https://api.github.com/user/packages/container/$PACKAGE_NAME/versions?per_page=100&page=$page" | jq -r '.[].metadata.container.tags[]')
if [ -z "$tags" ]; then
break
fi
all_tags="$all_tags $tags"
((page++))
done
echo "Tags found in GHCR:"
echo "$all_tags"
latest_tag=$(echo "$all_tags" | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | sort -rV | head -n 1)
echo "Latest semantic version tag is $latest_tag"
for tag in $all_tags; do
if [[ "$tag" != "master" && "$tag" != "$latest_tag" ]]; then
echo "Deleting tag $tag from GHCR"
version_id=$(curl -s -H "Authorization: Bearer $GITHUB_TOKEN" \
"https://api.github.com/user/packages/container/$PACKAGE_NAME/versions" | \
jq -r ".[] | select(.metadata.container.tags[] == \"$tag\") | .id")
if [ -n "$version_id" ]; then
curl -X DELETE -H "Authorization: Bearer $GITHUB_TOKEN" \
"https://api.github.com/user/packages/container/$PACKAGE_NAME/versions/$version_id"
else
echo "Warning: Could not find version ID for tag $tag"
fi
else
echo "Keeping tag $tag"
fi
done
3 changes: 1 addition & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
# AutomatedGo🐿️
[![Release](https://github.com/Nicconike/AutomatedGo/actions/workflows/release.yml/badge.svg)](https://github.com/Nicconike/AutomatedGo/actions/workflows/release.yml)
[![Publish Packages](https://github.com/Nicconike/AutomatedGo/actions/workflows/docker.yml/badge.svg)](https://github.com/Nicconike/AutomatedGo/actions/workflows/docker.yml)
[![CodeQL](https://github.com/Nicconike/AutomatedGo/actions/workflows/codeql.yml/badge.svg)](https://github.com/Nicconike/AutomatedGo/actions/workflows/codeql.yml)
[![Code Coverage](https://github.com/Nicconike/AutomatedGo/actions/workflows/coverage.yml/badge.svg)](https://github.com/Nicconike/AutomatedGo/actions/workflows/coverage.yml)
[![Go Report Card](https://goreportcard.com/badge/github.com/Nicconike/AutomatedGo)](https://goreportcard.com/report/github.com/Nicconike/AutomatedGo)
Expand Down Expand Up @@ -82,7 +81,7 @@ This will check the specified file for the current Go version, compare it with t
```
![JSON Example with OS](https://github.com/Nicconike/AutomatedGo/blob/master/assets/json_example_os_arch.png)

> Also, checkout the example implemntation for AutomatedGo at [test-AutomatedGo](https://github.com/Nicconike/test-AutomatedGo) repository.
> Also, checkout the example implementation for AutomatedGo at [test-AutomatedGo](https://github.com/Nicconike/test-AutomatedGo) repository.
## Supported File Types

Expand Down
57 changes: 56 additions & 1 deletion tests/unit/downloader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package tests
import (
"bytes"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"

Expand Down Expand Up @@ -31,6 +33,59 @@ func (m *MockRemover) Remove(filename string) error {
return args.Error(0)
}

func TestDownload(t *testing.T) {
tests := []struct {
name string
serverResponse func(w http.ResponseWriter, r *http.Request)
expectedError string
}{
{
name: "Successful download",
serverResponse: func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("file content"))

Check failure on line 46 in tests/unit/downloader_test.go

View workflow job for this annotation

GitHub Actions / Lint

Error return value of `w.Write` is not checked (errcheck)
},
expectedError: "",
},
{
name: "Server error",
serverResponse: func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
},
expectedError: "unexpected status code: 500",
},
{
name: "Not Found error",
serverResponse: func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
},
expectedError: "unexpected status code: 404",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create a test server
server := httptest.NewServer(http.HandlerFunc(tt.serverResponse))
defer server.Close()

// Create a DefaultDownloader
downloader := &pkg.DefaultDownloader{}

// Perform the download
err := downloader.Download(server.URL, "test.file")

// Check the error
if tt.expectedError != "" {
assert.Error(t, err)
assert.Contains(t, err.Error(), tt.expectedError)
} else {
assert.NoError(t, err)
}
})
}
}

// MockChecksumCalculator is a mock implementation of the ChecksumCalculator interface
type MockChecksumCalculator struct {
mock.Mock
Expand Down Expand Up @@ -74,7 +129,7 @@ func TestDownloadGo(t *testing.T) {
{
name: "Download with user input for OS and Arch",
config: pkg.DownloadConfig{
Version: "1.16.5",
Version: "1.18.5",
Path: "",
Input: strings.NewReader("linux\namd64\n"),
Output: &bytes.Buffer{},
Expand Down
73 changes: 73 additions & 0 deletions tests/unit/service_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package tests

import (
"bytes"
"testing"

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

// Mock implementations
type MockFileDownloader struct {
mock.Mock
}

func (m *MockFileDownloader) Download(url, filename string) error {
args := m.Called(url, filename)
return args.Error(0)
}

type MockFileRemover struct {
mock.Mock
}

func (m *MockFileRemover) Remove(filename string) error {
args := m.Called(filename)
return args.Error(0)
}

// func TestVersionServiceGetCurrentVersion(t *testing.T) {
// vs := &pkg.VersionService{}
// _, err := vs.GetCurrentVersion("testfile", "1.0.0")
// assert.NoError(t, err)
// }

func TestVersionServiceGetLatestVersion(t *testing.T) {
vs := &pkg.VersionService{}
_, err := vs.GetLatestVersion()
assert.NoError(t, err)
}

func TestVersionServiceIsNewer(t *testing.T) {
vs := &pkg.VersionService{}
result := vs.IsNewer("1.2.0", "1.1.0")
assert.True(t, result)
}

func TestVersionServiceDownloadGo(t *testing.T) {
mockDownloader := new(MockFileDownloader)
mockRemover := new(MockFileRemover)
mockChecksum := new(MockChecksumCalculator)

vs := &pkg.VersionService{
Downloader: mockDownloader,
Remover: mockRemover,
Checksum: mockChecksum,
}

mockChecksum.On("GetOfficialChecksum", mock.Anything).Return("checksum", nil)
mockDownloader.On("Download", mock.Anything, mock.Anything).Return(nil)
mockChecksum.On("Calculate", mock.Anything).Return("checksum", nil)

input := bytes.NewBufferString("")
output := &bytes.Buffer{}

err := vs.DownloadGo("1.16.5", "linux", "amd64", "/tmp", input, output)
assert.NoError(t, err)

mockDownloader.AssertExpectations(t)
mockRemover.AssertExpectations(t)
mockChecksum.AssertExpectations(t)
}

0 comments on commit 96f47d2

Please sign in to comment.