github.com/avahowell/sia@v0.5.1-beta.0.20160524050156-83dcc3d37c94/modules/renter/contractor/persist_test.go (about)

     1  package contractor
     2  
     3  import (
     4  	"os"
     5  	"testing"
     6  
     7  	"github.com/NebulousLabs/Sia/build"
     8  	"github.com/NebulousLabs/Sia/modules"
     9  	"github.com/NebulousLabs/Sia/types"
    10  )
    11  
    12  // memPersist implements the persister interface in-memory.
    13  type memPersist contractorPersist
    14  
    15  func (m *memPersist) save(data contractorPersist) error     { *m = memPersist(data); return nil }
    16  func (m *memPersist) saveSync(data contractorPersist) error { *m = memPersist(data); return nil }
    17  func (m memPersist) load(data *contractorPersist) error     { *data = contractorPersist(m); return nil }
    18  
    19  // TestSaveLoad tests that the contractor can save and load itself.
    20  func TestSaveLoad(t *testing.T) {
    21  	// create contractor with mocked persist dependency
    22  	c := &Contractor{
    23  		contracts: make(map[types.FileContractID]modules.RenterContract),
    24  	}
    25  	c.persist = new(memPersist)
    26  
    27  	// add some fake contracts
    28  	c.contracts = map[types.FileContractID]modules.RenterContract{
    29  		{0}: {NetAddress: "foo"},
    30  		{1}: {NetAddress: "bar"},
    31  		{2}: {NetAddress: "baz"},
    32  	}
    33  	// save and reload
    34  	err := c.save()
    35  	if err != nil {
    36  		t.Fatal(err)
    37  	}
    38  	err = c.load()
    39  	if err != nil {
    40  		t.Fatal(err)
    41  	}
    42  	// check that contracts were restored
    43  	_, ok0 := c.contracts[types.FileContractID{0}]
    44  	_, ok1 := c.contracts[types.FileContractID{1}]
    45  	_, ok2 := c.contracts[types.FileContractID{2}]
    46  	if !ok0 || !ok1 || !ok2 {
    47  		t.Fatal("contracts were not restored properly:", c.contracts)
    48  	}
    49  
    50  	// use stdPersist instead of mock
    51  	c.persist = newPersist(build.TempDir("contractor", "TestSaveLoad"))
    52  	os.MkdirAll(build.TempDir("contractor", "TestSaveLoad"), 0700)
    53  
    54  	// save and reload
    55  	err = c.save()
    56  	if err != nil {
    57  		t.Fatal(err)
    58  	}
    59  	err = c.load()
    60  	if err != nil {
    61  		t.Fatal(err)
    62  	}
    63  	// check that contracts were restored
    64  	_, ok0 = c.contracts[types.FileContractID{0}]
    65  	_, ok1 = c.contracts[types.FileContractID{1}]
    66  	_, ok2 = c.contracts[types.FileContractID{2}]
    67  	if !ok0 || !ok1 || !ok2 {
    68  		t.Fatal("contracts were not restored properly:", c.contracts)
    69  	}
    70  }