github.com/keltia/go-ipfs@v0.3.8-0.20150909044612-210793031c63/blocks/blockstore/write_cache_test.go (about)

     1  package blockstore
     2  
     3  import (
     4  	"testing"
     5  
     6  	ds "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
     7  	dsq "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore/query"
     8  	syncds "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore/sync"
     9  	"github.com/ipfs/go-ipfs/blocks"
    10  )
    11  
    12  func TestReturnsErrorWhenSizeNegative(t *testing.T) {
    13  	bs := NewBlockstore(syncds.MutexWrap(ds.NewMapDatastore()))
    14  	_, err := WriteCached(bs, -1)
    15  	if err != nil {
    16  		return
    17  	}
    18  	t.Fail()
    19  }
    20  
    21  func TestRemoveCacheEntryOnDelete(t *testing.T) {
    22  	b := blocks.NewBlock([]byte("foo"))
    23  	cd := &callbackDatastore{f: func() {}, ds: ds.NewMapDatastore()}
    24  	bs := NewBlockstore(syncds.MutexWrap(cd))
    25  	cachedbs, err := WriteCached(bs, 1)
    26  	if err != nil {
    27  		t.Fatal(err)
    28  	}
    29  	cachedbs.Put(b)
    30  
    31  	writeHitTheDatastore := false
    32  	cd.SetFunc(func() {
    33  		writeHitTheDatastore = true
    34  	})
    35  
    36  	cachedbs.DeleteBlock(b.Key())
    37  	cachedbs.Put(b)
    38  	if !writeHitTheDatastore {
    39  		t.Fail()
    40  	}
    41  }
    42  
    43  func TestElideDuplicateWrite(t *testing.T) {
    44  	cd := &callbackDatastore{f: func() {}, ds: ds.NewMapDatastore()}
    45  	bs := NewBlockstore(syncds.MutexWrap(cd))
    46  	cachedbs, err := WriteCached(bs, 1)
    47  	if err != nil {
    48  		t.Fatal(err)
    49  	}
    50  
    51  	b1 := blocks.NewBlock([]byte("foo"))
    52  
    53  	cachedbs.Put(b1)
    54  	cd.SetFunc(func() {
    55  		t.Fatal("write hit the datastore")
    56  	})
    57  	cachedbs.Put(b1)
    58  }
    59  
    60  type callbackDatastore struct {
    61  	f  func()
    62  	ds ds.Datastore
    63  }
    64  
    65  func (c *callbackDatastore) SetFunc(f func()) { c.f = f }
    66  
    67  func (c *callbackDatastore) Put(key ds.Key, value interface{}) (err error) {
    68  	c.f()
    69  	return c.ds.Put(key, value)
    70  }
    71  
    72  func (c *callbackDatastore) Get(key ds.Key) (value interface{}, err error) {
    73  	c.f()
    74  	return c.ds.Get(key)
    75  }
    76  
    77  func (c *callbackDatastore) Has(key ds.Key) (exists bool, err error) {
    78  	c.f()
    79  	return c.ds.Has(key)
    80  }
    81  
    82  func (c *callbackDatastore) Delete(key ds.Key) (err error) {
    83  	c.f()
    84  	return c.ds.Delete(key)
    85  }
    86  
    87  func (c *callbackDatastore) Query(q dsq.Query) (dsq.Results, error) {
    88  	c.f()
    89  	return c.ds.Query(q)
    90  }
    91  
    92  func (c *callbackDatastore) Batch() (ds.Batch, error) {
    93  	return ds.NewBasicBatch(c), nil
    94  }