add Queue.Walk()

This commit is contained in:
rick 2013-10-18 18:09:57 -06:00 committed by Rick Olson
parent e0018ef220
commit 7bf0709685
2 changed files with 61 additions and 0 deletions

@ -8,6 +8,7 @@ import (
"fmt" "fmt"
"github.com/streadway/simpleuuid" "github.com/streadway/simpleuuid"
"io" "io"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"time" "time"
@ -33,6 +34,8 @@ type Queue struct {
Dir *QueueDir Dir *QueueDir
} }
type WalkFunc func(id string, body []byte) error
func (q *Queue) Add(reader io.Reader) (string, error) { func (q *Queue) Add(reader io.Reader) (string, error) {
uuid, err := simpleuuid.NewTime(time.Now()) uuid, err := simpleuuid.NewTime(time.Now())
if err != nil { if err != nil {
@ -48,6 +51,30 @@ func (q *Queue) Add(reader io.Reader) (string, error) {
return id, err return id, err
} }
func (q *Queue) Walk(cb WalkFunc) error {
return filepath.Walk(q.Path, func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}
if err != nil {
return err
}
file, err := os.Open(path)
if err != nil {
return err
}
body, err := ioutil.ReadAll(file)
if err != nil {
return err
}
return cb(filepath.Base(path), body)
})
}
func (q *Queue) AddString(body string) (string, error) { func (q *Queue) AddString(body string) (string, error) {
return q.Add(bytes.NewBufferString(body)) return q.Add(bytes.NewBufferString(body))
} }

@ -30,7 +30,41 @@ func TestAdd(t *testing.T) {
assert.Equal(t, "BOOM", string(by)) assert.Equal(t, "BOOM", string(by))
} }
func TestWalk(t *testing.T) {
q := Setup(t)
defer q.Teardown()
id1, err := q.Queue.AddString("BOOM0")
if err != nil {
t.Fatalf("Cannot add to queue: %s", err)
} }
id2, err := q.Queue.AddString("BOOM1")
if err != nil {
t.Fatalf("Cannot add to queue: %s", err)
}
seen := make(map[string]bool)
q.Queue.Walk(func(id string, body []byte) error {
if err != nil {
t.Errorf("Error reading queue data for %s: %s", id, err)
}
seen[id] = true
if id == id1 {
assert.Equal(t, id1, id)
} else if id == id2 {
assert.Equal(t, id2, id)
} else {
t.Errorf("Weird ID: %s", id)
}
return nil
})
assert.Equal(t, 2, len(seen))
} }
func TestMove(t *testing.T) { func TestMove(t *testing.T) {