mirror of
https://github.com/keven1024/015.git
synced 2026-05-26 07:08:02 +00:00
67 lines
1.8 KiB
Go
67 lines
1.8 KiB
Go
package services
|
||
|
||
import (
|
||
"fmt"
|
||
"os"
|
||
"path/filepath"
|
||
"runtime"
|
||
"testing"
|
||
"worker/internal/services"
|
||
"worker/internal/utils"
|
||
|
||
"github.com/stretchr/testify/assert"
|
||
)
|
||
|
||
func TestCompressPNGHappyPath(t *testing.T) {
|
||
tmp := t.TempDir()
|
||
filePath := filepath.Join(tmp, "test.png")
|
||
// 从 test/resource 复制真实 PNG,路径基于当前测试文件位置
|
||
_, self, _, _ := runtime.Caller(0)
|
||
srcPath := filepath.Join(filepath.Dir(self), "..", "resource", "test.png")
|
||
err := utils.CopyFile(srcPath, filePath)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
got, err := services.CompressImage(filePath, "image/png")
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
assert.Equal(t, got, filePath+"_compressed")
|
||
origInfo, err := os.Stat(filePath)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
compInfo, err := os.Stat(got)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
assert.NotEqual(t, origInfo.Size(), compInfo.Size())
|
||
fmt.Printf("原图: %d | 压缩后: %d | 压缩率: %f%%\n", origInfo.Size(), compInfo.Size(), float64(origInfo.Size())/float64(compInfo.Size())*100)
|
||
}
|
||
|
||
func TestCompressJPEGHappyPath(t *testing.T) {
|
||
tmp := t.TempDir()
|
||
filePath := filepath.Join(tmp, "test.jpg")
|
||
_, self, _, _ := runtime.Caller(0)
|
||
srcPath := filepath.Join(filepath.Dir(self), "..", "resource", "test.jpg")
|
||
err := utils.CopyFile(srcPath, filePath)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
got, err := services.CompressImage(filePath, "image/jpeg")
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
assert.Equal(t, got, filePath+"_compressed")
|
||
origInfo, err := os.Stat(filePath)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
compInfo, err := os.Stat(got)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
assert.NotEqual(t, origInfo.Size(), compInfo.Size())
|
||
fmt.Printf("原图: %d | 压缩后: %d | 压缩率: %f%%\n", origInfo.Size(), compInfo.Size(), float64(origInfo.Size())/float64(compInfo.Size())*100)
|
||
}
|