implemented NewPersistorWithIndex() and test

This commit is contained in:
Florian Schlegel
2017-02-14 11:23:11 +01:00
parent 7155587302
commit e8935ddff9
2 changed files with 65 additions and 0 deletions
+12
View File
@@ -24,6 +24,18 @@ type Persistor struct {
// ~ CONSTRUCTOR
//------------------------------------------------------------------
func NewPersistorWithIndex(mongoURL string, collection string, index mgo.Index) (p *Persistor, err error) {
p, err = NewPersistor(mongoURL, collection)
if err != nil {
return
}
err = p.GetCollection().EnsureIndex(index)
if err != nil {
return
}
return p, nil
}
// NewPersistor constructor
func NewPersistor(mongoURL string, collection string) (p *Persistor, err error) {
parsedURL, err := url.Parse(mongoURL)
+53
View File
@@ -0,0 +1,53 @@
package persistence
import (
"testing"
"gopkg.in/mgo.v2"
)
type Foo struct {
FirstName string
LastName string
}
func TestPersistenceIndex(t *testing.T) {
index := mgo.Index{
Key: []string{"firstname", "lastname"},
Unique: true,
Background: true,
}
p, err := NewPersistorWithIndex("mongodb://dockerhost/test", "testindex", index)
if err != nil {
t.Fatal(err)
}
err = p.GetCollection().EnsureIndex(index)
if err != nil {
t.Fatal(err)
}
err = p.GetCollection().Insert(&Foo{
FirstName: "Foo",
LastName: "Bar",
})
if err != nil {
t.Fatal(err)
}
err = p.GetCollection().Insert(&Foo{
FirstName: "Flo",
LastName: "Bar",
})
if err != nil {
t.Fatal(err)
}
err = p.GetCollection().Insert(&Foo{
FirstName: "Flo",
LastName: "Bar",
})
if err == nil {
t.Fail()
t.Log("Did not expected that one to work!")
}
if err != nil {
t.Log("Error: " + err.Error())
}
}