本文整理汇总了Golang中gx/ipfs/QmZy2y8t9zQH2a1b8q2ZSLKp17ATuJoCNxxyMFG5qFExpt/go-net/context.Background函数的典型用法代码示例。如果您正苦于以下问题:Golang Background函数的具体用法?Golang Background怎么用?Golang Background使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Background函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestClientOverMax
func TestClientOverMax(t *testing.T) {
rs := NewServer()
k := key.Key("hello")
numProvidersForHelloKey := 100
for i := 0; i < numProvidersForHelloKey; i++ {
pi := testutil.RandIdentityOrFatal(t)
err := rs.Client(pi).Provide(context.Background(), k)
if err != nil {
t.Fatal(err)
}
}
max := 10
pi := testutil.RandIdentityOrFatal(t)
client := rs.Client(pi)
providersFromClient := client.FindProvidersAsync(context.Background(), k, max)
i := 0
for _ = range providersFromClient {
i++
}
if i != max {
t.Fatal("Too many providers returned")
}
}
示例2: TestAddLink
func TestAddLink(t *testing.T) {
ds := mdtest.Mock()
fishnode := &dag.Node{
Data: []byte("fishcakes!"),
}
fk, err := ds.Add(fishnode)
if err != nil {
t.Fatal(err)
}
nd := new(dag.Node)
nnode, err := addLink(context.Background(), ds, nd, "fish", fishnode)
if err != nil {
t.Fatal(err)
}
fnprime, err := nnode.GetLinkedNode(context.Background(), ds, "fish")
if err != nil {
t.Fatal(err)
}
fnpkey, err := fnprime.Key()
if err != nil {
t.Fatal(err)
}
if fnpkey != fk {
t.Fatal("wrong child node found!")
}
}
示例3: TestEnumerateChildren
func TestEnumerateChildren(t *testing.T) {
bsi := bstest.Mocks(1)
ds := NewDAGService(bsi[0])
read := io.LimitReader(u.NewTimeSeededRand(), 1024*1024)
root, err := imp.BuildDagFromReader(ds, chunk.NewSizeSplitter(read, 512))
if err != nil {
t.Fatal(err)
}
ks := key.NewKeySet()
err = EnumerateChildren(context.Background(), ds, root, ks, false)
if err != nil {
t.Fatal(err)
}
var traverse func(n *Node)
traverse = func(n *Node) {
// traverse dag and check
for _, lnk := range n.Links {
k := key.Key(lnk.Hash)
if !ks.Has(k) {
t.Fatal("missing key in set!")
}
child, err := ds.Get(context.Background(), k)
if err != nil {
t.Fatal(err)
}
traverse(child)
}
}
traverse(root)
}
示例4: TestRoutingResolve
func TestRoutingResolve(t *testing.T) {
dstore := dssync.MutexWrap(ds.NewMapDatastore())
serv := mockrouting.NewServer()
id := testutil.RandIdentityOrFatal(t)
d := serv.ClientWithDatastore(context.Background(), id, dstore)
resolver := NewRoutingResolver(d, 0)
publisher := NewRoutingPublisher(d, dstore)
privk, pubk, err := testutil.RandTestKeyPair(512)
if err != nil {
t.Fatal(err)
}
h := path.FromString("/ipfs/QmZULkCELmmk5XNfCgTnCyFgAVxBRBXyDHGGMVoLFLiXEN")
err = publisher.Publish(context.Background(), privk, h)
if err != nil {
t.Fatal(err)
}
pubkb, err := pubk.Bytes()
if err != nil {
t.Fatal(err)
}
pkhash := u.Hash(pubkb)
res, err := resolver.Resolve(context.Background(), key.Key(pkhash).Pretty())
if err != nil {
t.Fatal(err)
}
if res != h {
t.Fatal("Got back incorrect value.")
}
}
示例5: TestClientFindProviders
func TestClientFindProviders(t *testing.T) {
pi := testutil.RandIdentityOrFatal(t)
rs := NewServer()
client := rs.Client(pi)
k := key.Key("hello")
err := client.Provide(context.Background(), k)
if err != nil {
t.Fatal(err)
}
// This is bad... but simulating networks is hard
time.Sleep(time.Millisecond * 300)
max := 100
providersFromClient := client.FindProvidersAsync(context.Background(), key.Key("hello"), max)
isInClient := false
for pi := range providersFromClient {
if pi.ID == pi.ID {
isInClient = true
}
}
if !isInClient {
t.Fatal("Despite client providing key, client didn't receive peer when finding providers")
}
}
示例6: TestLimitedStreams
func TestLimitedStreams(t *testing.T) {
mn, err := FullMeshConnected(context.Background(), 2)
if err != nil {
t.Fatal(err)
}
var wg sync.WaitGroup
messages := 4
messageSize := 500
handler := func(s inet.Stream) {
b := make([]byte, messageSize)
for i := 0; i < messages; i++ {
if _, err := io.ReadFull(s, b); err != nil {
log.Fatal(err)
}
if !bytes.Equal(b[:4], []byte("ping")) {
log.Fatal("bytes mismatch")
}
wg.Done()
}
s.Close()
}
hosts := mn.Hosts()
for _, h := range mn.Hosts() {
h.SetStreamHandler(protocol.TestingID, handler)
}
peers := mn.Peers()
links := mn.LinksBetweenPeers(peers[0], peers[1])
// 1000 byte per second bandwidth
bps := float64(1000)
opts := links[0].Options()
opts.Bandwidth = bps
for _, link := range links {
link.SetOptions(opts)
}
ctx := context.Background()
s, err := hosts[0].NewStream(ctx, protocol.TestingID, hosts[1].ID())
if err != nil {
t.Fatal(err)
}
filler := make([]byte, messageSize-4)
data := append([]byte("ping"), filler...)
before := time.Now()
for i := 0; i < messages; i++ {
wg.Add(1)
if _, err := s.Write(data); err != nil {
panic(err)
}
}
wg.Wait()
if !within(time.Since(before), time.Duration(time.Second*2), time.Second/3) {
t.Fatal("Expected 2ish seconds but got ", time.Since(before))
}
}
示例7: TestCanceledContext
// TODO does dht ensure won't receive self as a provider? probably not.
func TestCanceledContext(t *testing.T) {
rs := NewServer()
k := key.Key("hello")
// avoid leaking goroutine, without using the context to signal
// (we want the goroutine to keep trying to publish on a
// cancelled context until we've tested it doesnt do anything.)
done := make(chan struct{})
defer func() { done <- struct{}{} }()
t.Log("async'ly announce infinite stream of providers for key")
i := 0
go func() { // infinite stream
for {
select {
case <-done:
t.Log("exiting async worker")
return
default:
}
pi, err := testutil.RandIdentity()
if err != nil {
t.Error(err)
}
err = rs.Client(pi).Provide(context.Background(), k)
if err != nil {
t.Error(err)
}
i++
}
}()
local := testutil.RandIdentityOrFatal(t)
client := rs.Client(local)
t.Log("warning: max is finite so this test is non-deterministic")
t.Log("context cancellation could simply take lower priority")
t.Log("and result in receiving the max number of results")
max := 1000
t.Log("cancel the context before consuming")
ctx, cancelFunc := context.WithCancel(context.Background())
cancelFunc()
providers := client.FindProvidersAsync(ctx, k, max)
numProvidersReturned := 0
for _ = range providers {
numProvidersReturned++
}
t.Log(numProvidersReturned)
if numProvidersReturned == max {
t.Fatal("Context cancel had no effect")
}
}
示例8: TestDoubleGet
func TestDoubleGet(t *testing.T) {
net := tn.VirtualNetwork(mockrouting.NewServer(), delay.Fixed(kNetworkDelay))
sg := NewTestSessionGenerator(net)
defer sg.Close()
bg := blocksutil.NewBlockGenerator()
t.Log("Test a one node trying to get one block from another")
instances := sg.Instances(2)
blocks := bg.Blocks(1)
ctx1, cancel1 := context.WithCancel(context.Background())
blkch1, err := instances[1].Exchange.GetBlocks(ctx1, []key.Key{blocks[0].Key()})
if err != nil {
t.Fatal(err)
}
ctx2, cancel2 := context.WithCancel(context.Background())
defer cancel2()
blkch2, err := instances[1].Exchange.GetBlocks(ctx2, []key.Key{blocks[0].Key()})
if err != nil {
t.Fatal(err)
}
// ensure both requests make it into the wantlist at the same time
time.Sleep(time.Millisecond * 100)
cancel1()
_, ok := <-blkch1
if ok {
t.Fatal("expected channel to be closed")
}
err = instances[0].Exchange.HasBlock(blocks[0])
if err != nil {
t.Fatal(err)
}
blk, ok := <-blkch2
if !ok {
t.Fatal("expected to get the block here")
}
t.Log(blk)
for _, inst := range instances {
err := inst.Exchange.Close()
if err != nil {
t.Fatal(err)
}
}
}
示例9: TestMultiWrite
func TestMultiWrite(t *testing.T) {
dserv := getMockDagServ(t)
_, n := getNode(t, dserv, 0)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
dagmod, err := NewDagModifier(ctx, n, dserv, sizeSplitterGen(512))
if err != nil {
t.Fatal(err)
}
data := make([]byte, 4000)
u.NewTimeSeededRand().Read(data)
for i := 0; i < len(data); i++ {
n, err := dagmod.WriteAt(data[i:i+1], int64(i))
if err != nil {
t.Fatal(err)
}
if n != 1 {
t.Fatal("Somehow wrote the wrong number of bytes! (n != 1)")
}
size, err := dagmod.Size()
if err != nil {
t.Fatal(err)
}
if size != int64(i+1) {
t.Fatal("Size was reported incorrectly")
}
}
nd, err := dagmod.GetNode()
if err != nil {
t.Fatal(err)
}
read, err := uio.NewDagReader(context.Background(), nd, dserv)
if err != nil {
t.Fatal(err)
}
rbuf, err := ioutil.ReadAll(read)
if err != nil {
t.Fatal(err)
}
err = arrComp(rbuf, data)
if err != nil {
t.Fatal(err)
}
}
示例10: testInsert
func testInsert(t *testing.T, e *Editor, path, data string, create bool, experr string) {
child := &dag.Node{Data: []byte(data)}
ck, err := e.tmp.Add(child)
if err != nil {
t.Fatal(err)
}
var c func() *dag.Node
if create {
c = func() *dag.Node {
return &dag.Node{}
}
}
err = e.InsertNodeAtPath(context.Background(), path, child, c)
if experr != "" {
var got string
if err != nil {
got = err.Error()
}
if got != experr {
t.Fatalf("expected '%s' but got '%s'", experr, got)
}
return
}
if err != nil {
t.Fatal(err, path, data, create, experr)
}
assertNodeAtPath(t, e.tmp, e.root, path, ck)
}
示例11: RunSupernodePutRecordGetRecord
func RunSupernodePutRecordGetRecord(conf testutil.LatencyConfig) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
servers, clients, err := InitializeSupernodeNetwork(ctx, 2, 2, conf)
if err != nil {
return err
}
for _, n := range append(servers, clients...) {
defer n.Close()
}
putter := clients[0]
getter := clients[1]
k := key.Key("key")
note := []byte("a note from putter")
if err := putter.Routing.PutValue(ctx, k, note); err != nil {
return fmt.Errorf("failed to put value: %s", err)
}
received, err := getter.Routing.GetValue(ctx, k)
if err != nil {
return fmt.Errorf("failed to get value: %s", err)
}
if 0 != bytes.Compare(note, received) {
return errors.New("record doesn't match")
}
cancel()
return nil
}
示例12: TestSeekingConsistency
func TestSeekingConsistency(t *testing.T) {
nbytes := int64(128 * 1024)
ds := mdtest.Mock()
nd, should := getTestDag(t, ds, nbytes, 500)
rs, err := uio.NewDagReader(context.Background(), nd, ds)
if err != nil {
t.Fatal(err)
}
out := make([]byte, nbytes)
for coff := nbytes - 4096; coff >= 0; coff -= 4096 {
t.Log(coff)
n, err := rs.Seek(coff, os.SEEK_SET)
if err != nil {
t.Fatal(err)
}
if n != coff {
t.Fatal("wasnt able to seek to the right position")
}
nread, err := rs.Read(out[coff : coff+4096])
if err != nil {
t.Fatal(err)
}
if nread != 4096 {
t.Fatal("didnt read the correct number of bytes")
}
}
err = arrComp(out, should)
if err != nil {
t.Fatal(err)
}
}
示例13: TestSeekToAlmostBegin
func TestSeekToAlmostBegin(t *testing.T) {
ds := mdtest.Mock()
nd, should := getTestDag(t, ds, 10*1024, 500)
rs, err := uio.NewDagReader(context.Background(), nd, ds)
if err != nil {
t.Fatal(err)
}
n, err := io.CopyN(ioutil.Discard, rs, 1024*4)
if err != nil {
t.Fatal(err)
}
if n != 4096 {
t.Fatal("Copy didnt copy enough bytes")
}
seeked, err := rs.Seek(1, os.SEEK_SET)
if err != nil {
t.Fatal(err)
}
if seeked != 1 {
t.Fatal("Failed to seek to almost beginning")
}
dagrArrComp(t, rs, should[1:])
}
示例14: TestGetBlocksSequential
func TestGetBlocksSequential(t *testing.T) {
var servs = Mocks(4)
for _, s := range servs {
defer s.Close()
}
bg := blocksutil.NewBlockGenerator()
blks := bg.Blocks(50)
var keys []key.Key
for _, blk := range blks {
keys = append(keys, blk.Key())
servs[0].AddBlock(blk)
}
t.Log("one instance at a time, get blocks concurrently")
for i := 1; i < len(servs); i++ {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*50)
defer cancel()
out := servs[i].GetBlocks(ctx, keys)
gotten := make(map[key.Key]blocks.Block)
for blk := range out {
if _, ok := gotten[blk.Key()]; ok {
t.Fatal("Got duplicate block!")
}
gotten[blk.Key()] = blk
}
if len(gotten) != len(blks) {
t.Fatalf("Didnt get enough blocks back: %d/%d", len(gotten), len(blks))
}
}
}
示例15: TestBuilderConsistency
func TestBuilderConsistency(t *testing.T) {
nbytes := 100000
buf := new(bytes.Buffer)
io.CopyN(buf, u.NewTimeSeededRand(), int64(nbytes))
should := dup(buf.Bytes())
dagserv := mdtest.Mock()
nd, err := buildTestDag(dagserv, chunk.DefaultSplitter(buf))
if err != nil {
t.Fatal(err)
}
r, err := uio.NewDagReader(context.Background(), nd, dagserv)
if err != nil {
t.Fatal(err)
}
out, err := ioutil.ReadAll(r)
if err != nil {
t.Fatal(err)
}
err = arrComp(out, should)
if err != nil {
t.Fatal(err)
}
}