github.com/neatlab/neatio@v1.7.3-0.20220425043230-d903e92fcc75/network/node/service_test.go (about)

     1  package node
     2  
     3  import (
     4  	"fmt"
     5  	"io/ioutil"
     6  	"os"
     7  	"path/filepath"
     8  	"testing"
     9  )
    10  
    11  func TestContextDatabases(t *testing.T) {
    12  
    13  	dir, err := ioutil.TempDir("", "")
    14  	if err != nil {
    15  		t.Fatalf("failed to create temporary data directory: %v", err)
    16  	}
    17  	defer os.RemoveAll(dir)
    18  
    19  	if _, err := os.Stat(filepath.Join(dir, "database")); err == nil {
    20  		t.Fatalf("non-created database already exists")
    21  	}
    22  
    23  	ctx := &ServiceContext{config: &Config{Name: "unit-test", DataDir: dir}}
    24  	db, err := ctx.OpenDatabase("persistent", 0, 0)
    25  	if err != nil {
    26  		t.Fatalf("failed to open persistent database: %v", err)
    27  	}
    28  	db.Close()
    29  
    30  	if _, err := os.Stat(filepath.Join(dir, "unit-test", "persistent")); err != nil {
    31  		t.Fatalf("persistent database doesn't exists: %v", err)
    32  	}
    33  
    34  	ctx = &ServiceContext{config: &Config{DataDir: ""}}
    35  	db, err = ctx.OpenDatabase("ephemeral", 0, 0)
    36  	if err != nil {
    37  		t.Fatalf("failed to open ephemeral database: %v", err)
    38  	}
    39  	db.Close()
    40  
    41  	if _, err := os.Stat(filepath.Join(dir, "ephemeral")); err == nil {
    42  		t.Fatalf("ephemeral database exists")
    43  	}
    44  }
    45  
    46  func TestContextServices(t *testing.T) {
    47  	stack, err := New(testNodeConfig())
    48  	if err != nil {
    49  		t.Fatalf("failed to create protocol stack: %v", err)
    50  	}
    51  
    52  	verifier := func(ctx *ServiceContext) (Service, error) {
    53  		var objA *NoopServiceA
    54  		if ctx.Service(&objA) != nil {
    55  			return nil, fmt.Errorf("former service not found")
    56  		}
    57  		var objB *NoopServiceB
    58  		if err := ctx.Service(&objB); err != ErrServiceUnknown {
    59  			return nil, fmt.Errorf("latters lookup error mismatch: have %v, want %v", err, ErrServiceUnknown)
    60  		}
    61  		return new(NoopService), nil
    62  	}
    63  
    64  	if err := stack.Register(NewNoopServiceA); err != nil {
    65  		t.Fatalf("former failed to register service: %v", err)
    66  	}
    67  	if err := stack.Register(verifier); err != nil {
    68  		t.Fatalf("failed to register service verifier: %v", err)
    69  	}
    70  	if err := stack.Register(NewNoopServiceB); err != nil {
    71  		t.Fatalf("latter failed to register service: %v", err)
    72  	}
    73  
    74  	if err := stack.Start(); err != nil {
    75  		t.Fatalf("failed to start stack: %v", err)
    76  	}
    77  	defer stack.Stop()
    78  }