ALR/internal/dlcache/dlcache_test.go

112 lines
2.3 KiB
Go
Raw Permalink Normal View History

2024-01-22 10:36:06 +00:00
/*
2024-05-05 10:32:08 +00:00
* ALR - Any Linux Repository
* Copyright (C) 2024 Евгений Храмов
2024-01-22 10:36:06 +00:00
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package dlcache_test
import (
"context"
"crypto/sha1"
"encoding/hex"
"io"
"os"
"path/filepath"
"testing"
2024-05-05 10:32:08 +00:00
"plemya-x.ru/alr/internal/config"
"plemya-x.ru/alr/internal/dlcache"
2024-01-22 10:36:06 +00:00
)
func init() {
2024-05-05 10:32:08 +00:00
dir, err := os.MkdirTemp("/tmp", "alr-dlcache-test.*")
2024-01-22 10:36:06 +00:00
if err != nil {
panic(err)
}
config.GetPaths(context.Background()).RepoDir = dir
}
2025-01-14 09:59:00 +00:00
type TestALRConfig struct {
CacheDir string
}
func (c *TestALRConfig) GetPaths(ctx context.Context) *config.Paths {
return &config.Paths{
CacheDir: c.CacheDir,
}
}
func prepare(t *testing.T) *TestALRConfig {
t.Helper()
dir, err := os.MkdirTemp("/tmp", "alr-dlcache-test.*")
if err != nil {
panic(err)
}
return &TestALRConfig{
CacheDir: dir,
}
}
func cleanup(t *testing.T, cfg *TestALRConfig) {
t.Helper()
os.Remove(cfg.CacheDir)
}
2024-01-22 10:36:06 +00:00
func TestNew(t *testing.T) {
2025-01-14 09:59:00 +00:00
cfg := prepare(t)
defer cleanup(t, cfg)
dc := dlcache.New(cfg)
ctx := context.Background()
2024-01-22 10:36:06 +00:00
const id = "https://example.com"
2025-01-14 09:59:00 +00:00
dir, err := dc.New(ctx, id)
2024-01-22 10:36:06 +00:00
if err != nil {
t.Errorf("Expected no error, got %s", err)
}
2025-01-14 09:59:00 +00:00
exp := filepath.Join(dc.BasePath(ctx), sha1sum(id))
2024-01-22 10:36:06 +00:00
if dir != exp {
t.Errorf("Expected %s, got %s", exp, dir)
}
fi, err := os.Stat(dir)
if err != nil {
t.Errorf("stat: expected no error, got %s", err)
}
if !fi.IsDir() {
t.Errorf("Expected cache item to be a directory")
}
2025-01-14 09:59:00 +00:00
dir2, ok := dc.Get(ctx, id)
2024-01-22 10:36:06 +00:00
if !ok {
t.Errorf("Expected Get() to return valid value")
}
if dir2 != dir {
t.Errorf("Expected %s from Get(), got %s", dir, dir2)
}
}
func sha1sum(id string) string {
h := sha1.New()
_, _ = io.WriteString(h, id)
return hex.EncodeToString(h.Sum(nil))
}