arlo-cleaner/monitor/arlo_test.go

140 lines
2.6 KiB
Go
Executable File

package monitor
import (
"crypto/rand"
"fmt"
"io/ioutil"
"local/sandbox/arlo-cleaner/arlo"
"local/sandbox/arlo-cleaner/config"
"local/sandbox/arlo-cleaner/rclone"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path"
"strings"
"testing"
"time"
)
func TestArloPickRipe(t *testing.T) {
a := &Arlo{}
config.ArloBPS = 1
cases := map[string]struct {
videoCnt int
confCap int64
outLen int
}{
"prune none": {
videoCnt: 5,
confCap: 5,
outLen: 0,
},
"prune one": {
videoCnt: 5,
confCap: 4,
outLen: 1,
},
"prune all": {
videoCnt: 5,
confCap: 0,
outLen: 5,
},
}
for name, c := range cases {
videos := make([]*arlo.Video, c.videoCnt)
for i := range videos {
b := make([]byte, 1)
rand.Read(b)
videos[i] = &arlo.Video{
Duration: time.Second,
Created: time.Now().Add(-24 * 365 * time.Hour * time.Duration(int(b[0]))),
Loc: &url.URL{},
}
}
config.ArloCapacity = int64(c.confCap)
videos = a.pickRipe(videos)
if len(videos) != c.outLen {
t.Errorf("%s: want %v videos, got %v", name, c.outLen, len(videos))
}
for i := 0; i < len(videos)-1; i++ {
if videos[i].Created.After(videos[i+1].Created) {
t.Error(videos)
}
}
}
}
func TestArloArchive(t *testing.T) {
a, def := mockArlo(t)
defer def()
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello\n")
}))
defer s.Close()
url, _ := url.Parse(s.URL)
url.Path = "my_video.mp4"
q := url.Query()
q.Set("hello", ".world.")
url.RawQuery = q.Encode()
video := &arlo.Video{
Loc: url,
Created: time.Now(),
Device: "device",
}
if err := a.archive(video); err != nil {
t.Fatal(err)
}
path := path.Join(
config.RCloneName,
fmt.Sprintf("%02d", video.Created.Year()),
fmt.Sprintf("%02d", video.Created.Month()),
fmt.Sprintf("%02d", video.Created.Day()),
video.Key(),
)
path = strings.TrimPrefix(path, "local:")
if b, err := ioutil.ReadFile(path); err != nil {
t.Fatal(err)
} else if v := string(b); v != "Hello\n" {
t.Fatal(v)
} else if err := os.Remove(path); err != nil {
t.Fatal(err)
}
}
func mockArlo(t *testing.T) (*Arlo, func()) {
f, err := ioutil.TempFile(os.TempDir(), "rclone.conf.*")
if err != nil {
t.Fatal(err)
}
f.Write([]byte(`
[local]
type = local
`))
f.Close()
was := os.Args
os.Args = []string{"foo", "-rcconf", f.Name(), "-rcname", "local:" + path.Dir(f.Name())}
if err := config.Refresh(); err != nil {
t.Fatal(err)
}
rclone, err := rclone.New()
if err != nil {
t.Fatal(err)
}
a := &Arlo{
arlo: &arlo.Arlo{},
rclone: rclone,
}
return a, func() {
os.Remove(f.Name())
os.Args = was
}
}