当前位置: 首页>>代码示例>>Golang>>正文


Golang context.Background函数代码示例

本文整理汇总了Golang中golang.org/x/net/context.Background函数的典型用法代码示例。如果您正苦于以下问题:Golang Background函数的具体用法?Golang Background怎么用?Golang Background使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Background函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: TestNodeCertificateRenewalsDoNotRequireToken

func TestNodeCertificateRenewalsDoNotRequireToken(t *testing.T) {
	tc := testutils.NewTestCA(t)
	defer tc.Stop()

	csr, _, err := ca.GenerateNewCSR()
	assert.NoError(t, err)

	role := api.NodeRoleManager
	issueRequest := &api.IssueNodeCertificateRequest{CSR: csr, Role: role}
	issueResponse, err := tc.NodeCAClients[2].IssueNodeCertificate(context.Background(), issueRequest)
	assert.NoError(t, err)
	assert.NotNil(t, issueResponse.NodeID)
	assert.Equal(t, api.NodeMembershipAccepted, issueResponse.NodeMembership)

	statusRequest := &api.NodeCertificateStatusRequest{NodeID: issueResponse.NodeID}
	statusResponse, err := tc.NodeCAClients[2].NodeCertificateStatus(context.Background(), statusRequest)
	assert.NoError(t, err)
	assert.Equal(t, api.IssuanceStateIssued, statusResponse.Status.State)
	assert.NotNil(t, statusResponse.Certificate.Certificate)
	assert.Equal(t, role, statusResponse.Certificate.Role)

	role = api.NodeRoleWorker
	issueRequest = &api.IssueNodeCertificateRequest{CSR: csr, Role: role}
	issueResponse, err = tc.NodeCAClients[1].IssueNodeCertificate(context.Background(), issueRequest)
	require.NoError(t, err)
	assert.NotNil(t, issueResponse.NodeID)
	assert.Equal(t, api.NodeMembershipAccepted, issueResponse.NodeMembership)

	statusRequest = &api.NodeCertificateStatusRequest{NodeID: issueResponse.NodeID}
	statusResponse, err = tc.NodeCAClients[2].NodeCertificateStatus(context.Background(), statusRequest)
	require.NoError(t, err)
	assert.Equal(t, api.IssuanceStateIssued, statusResponse.Status.State)
	assert.NotNil(t, statusResponse.Certificate.Certificate)
	assert.Equal(t, role, statusResponse.Certificate.Role)
}
开发者ID:yongtang,项目名称:swarmkit,代码行数:35,代码来源:server_test.go

示例2: TestShardConnStreamingRetry

func TestShardConnStreamingRetry(t *testing.T) {
	// ERR_RETRY
	s := createSandbox("TestShardConnStreamingRetry")
	sbc := &sandboxConn{mustFailRetry: 1}
	s.MapTestConn("0", sbc)
	sdc := NewShardConn(context.Background(), new(sandboxTopo), "aa", "TestShardConnStreamingRetry", "0", topodatapb.TabletType_REPLICA, 10*time.Millisecond, 3, connTimeoutTotal, connTimeoutPerConn, connLife, connectTimings)
	_, err := sdc.StreamExecute(context.Background(), "query", nil, 0)
	if err != nil {
		t.Errorf("want nil, got %v", err)
	}
	if s.DialCounter != 2 {
		t.Errorf("want 2, got %v", s.DialCounter)
	}
	if execCount := sbc.ExecCount.Get(); execCount != 2 {
		t.Errorf("want 2, got %v", execCount)
	}

	// ERR_FATAL
	s.Reset()
	sbc = &sandboxConn{mustFailFatal: 1}
	s.MapTestConn("0", sbc)
	sdc = NewShardConn(context.Background(), new(sandboxTopo), "aa", "TestShardConnStreamingRetry", "0", topodatapb.TabletType_REPLICA, 10*time.Millisecond, 3, connTimeoutTotal, connTimeoutPerConn, connLife, connectTimings)
	_, err = sdc.StreamExecute(context.Background(), "query", nil, 0)
	want := "shard, host: TestShardConnStreamingRetry.0.replica, host:\"0\" port_map:<key:\"vt\" value:1 > , fatal: err"
	if err == nil || err.Error() != want {
		t.Errorf("want %v, got %v", want, err)
	}
	if s.DialCounter != 1 {
		t.Errorf("want 1, got %v", s.DialCounter)
	}
	if execCount := sbc.ExecCount.Get(); execCount != 1 {
		t.Errorf("want 1, got %v", execCount)
	}
}
开发者ID:aaijazi,项目名称:vitess,代码行数:34,代码来源:shard_conn_flaky_test.go

示例3: TestCacheWithErrors

// TestCacheWithErrors will test we properly return cached errors.
func TestCacheWithErrors(t *testing.T) {
	ft := &fakeTopo{keyspace: "test_ks"}
	rsts := NewResilientSrvTopoServer(ft, "TestCacheWithErrors")

	// ask for the known keyspace, that populates the cache
	_, err := rsts.GetSrvKeyspace(context.Background(), "", "test_ks")
	if err != nil {
		t.Fatalf("GetSrvKeyspace got unexpected error: %v", err)
	}

	// now make the topo server fail, and ask again, should get cached
	// value, not even ask underlying guy
	ft.keyspace = "another_test_ks"
	_, err = rsts.GetSrvKeyspace(context.Background(), "", "test_ks")
	if err != nil {
		t.Fatalf("GetSrvKeyspace got unexpected error: %v", err)
	}

	// now reduce TTL to nothing, so we won't use cache, and ask again
	rsts.cacheTTL = 0
	_, err = rsts.GetSrvKeyspace(context.Background(), "", "test_ks")
	if err != nil {
		t.Fatalf("GetSrvKeyspace got unexpected error: %v", err)
	}
}
开发者ID:haoqoo,项目名称:vitess,代码行数:26,代码来源:srv_topo_server_test.go

示例4: TestQueryExecutorPlanSetMaxDmlRows

func TestQueryExecutorPlanSetMaxDmlRows(t *testing.T) {
	setUpQueryExecutorTest()
	want := &mproto.QueryResult{}
	vtMaxDmlRows := int64(256)
	setQuery := fmt.Sprintf("set vt_max_dml_rows = %d", vtMaxDmlRows)
	qre, sqlQuery := newTestQueryExecutor(
		setQuery, context.Background(), enableRowCache|enableStrict)
	defer sqlQuery.disallowQueries()
	checkPlanID(t, planbuilder.PLAN_SET, qre.plan.PlanId)
	got := qre.Execute()
	if !reflect.DeepEqual(got, want) {
		t.Fatalf("query executor Execute() = %v, want: %v", got, want)
	}
	if qre.qe.maxDMLRows.Get() != vtMaxDmlRows {
		t.Fatalf("set query failed, expected to have vt_max_dml_rows: %d, but got: %d", vtMaxDmlRows, qre.qe.maxDMLRows.Get())
	}
	// set vt_max_result_size fail
	setQuery = "set vt_max_dml_rows = 0"
	qre, sqlQuery = newTestQueryExecutor(
		setQuery, context.Background(), enableRowCache|enableStrict)
	defer sqlQuery.disallowQueries()
	checkPlanID(t, planbuilder.PLAN_SET, qre.plan.PlanId)
	defer handleAndVerifyTabletError(t, "vt_max_dml_rows out of range, should always larger than 0", ErrFail)
	qre.Execute()
}
开发者ID:UGuarder,项目名称:vitess,代码行数:25,代码来源:query_executor_test.go

示例5: postFreeze

func postFreeze(
	c cluster.Cluster, freeze bool, timeout time.Duration,
) (serverpb.ClusterFreezeResponse, error) {
	httpClient := cluster.HTTPClient
	httpClient.Timeout = timeout

	var resp serverpb.ClusterFreezeResponse
	log.Infof(context.Background(), "requesting: freeze=%t, timeout=%s", freeze, timeout)
	cb := func(v proto.Message) {
		oldNum := resp.RangesAffected
		resp = *v.(*serverpb.ClusterFreezeResponse)
		if oldNum > resp.RangesAffected {
			resp.RangesAffected = oldNum
		}
		if (resp != serverpb.ClusterFreezeResponse{}) {
			log.Infof(context.Background(), "%+v", &resp)
		}
	}
	err := httputil.StreamJSON(
		httpClient,
		c.URL(0)+"/_admin/v1/cluster/freeze",
		&serverpb.ClusterFreezeRequest{Freeze: freeze},
		&serverpb.ClusterFreezeResponse{},
		cb,
	)
	return resp, err
}
开发者ID:knz,项目名称:cockroach,代码行数:27,代码来源:freeze_test.go

示例6: TestListIterationBySpace

func (test *TestIterationRepository) TestListIterationBySpace() {
	t := test.T()
	resource.Require(t, resource.Database)

	repo := iteration.NewIterationRepository(test.DB)

	spaceID := uuid.NewV4()

	for i := 0; i < 3; i++ {
		start := time.Now()
		end := start.Add(time.Hour * (24 * 8 * 3))
		name := "Sprint #2" + strconv.Itoa(i)

		i := iteration.Iteration{
			Name:    name,
			SpaceID: spaceID,
			StartAt: &start,
			EndAt:   &end,
		}
		repo.Create(context.Background(), &i)
	}
	repo.Create(context.Background(), &iteration.Iteration{
		Name:    "Other Spring #2",
		SpaceID: uuid.NewV4(),
	})

	its, err := repo.List(context.Background(), spaceID)
	assert.Nil(t, err)
	assert.Len(t, its, 3)
}
开发者ID:Ritsyy,项目名称:almighty-core,代码行数:30,代码来源:iteration_test.go

示例7: TestCreateAndOpen

func TestCreateAndOpen(t *testing.T) {
	// Verify that we can successfully create a fresh index pack.
	path := filepath.Join(tempDir, "TestIndexPack")
	pack, err := Create(context.Background(), path, UnitType((*cpb.CompilationUnit)(nil)))
	if err != nil {
		t.Fatalf("Unable to create index pack %q: %v", path, err)
	}
	t.Logf("Created index pack: %#v", pack)
	testArchive = pack

	// Creating over an existing directory doesn't work.
	if alt, err := Create(context.Background(), path); err == nil {
		t.Errorf("Create should fail for existing path %q, but returned %v", path, alt)
	}

	// Opening a non-existent pack doesn't work.
	if alt, err := Open(context.Background(), path+"NoneSuch"); err == nil {
		t.Errorf("Open should fail for %q, but returned %v", path+"NoneSuch", alt)
	}

	// Opening the index pack we created for the test should work.
	if _, err := Open(context.Background(), path); err != nil {
		t.Errorf("Error opening existing path %q: %v", path, err)
	}
}
开发者ID:herberteuler,项目名称:kythe,代码行数:25,代码来源:indexpack_test.go

示例8: commandSucceeds

func commandSucceeds(t *testing.T, client vtworkerclient.Client) {
	logs, errFunc, err := client.ExecuteVtworkerCommand(context.Background(), []string{"Ping", "pong"})
	if err != nil {
		t.Fatalf("Cannot execute remote command: %v", err)
	}

	count := 0
	for e := range logs {
		expected := "Ping command was called with message: 'pong'.\n"
		if logutil.EventString(e) != expected {
			t.Errorf("Got unexpected log line '%v' expected '%v'", e.String(), expected)
		}
		count++
	}
	if count != 1 {
		t.Errorf("Didn't get expected log line only, got %v lines", count)
	}

	if err := errFunc(); err != nil {
		t.Fatalf("Remote error: %v", err)
	}

	logs, errFunc, err = client.ExecuteVtworkerCommand(context.Background(), []string{"Reset"})
	if err != nil {
		t.Fatalf("Cannot execute remote command: %v", err)
	}
	for range logs {
	}
	if err := errFunc(); err != nil {
		t.Fatalf("Cannot execute remote command: %v", err)
	}
}
开发者ID:littleyang,项目名称:vitess,代码行数:32,代码来源:client_testsuite.go

示例9: TestDeleteComment

func (test *TestCommentRepository) TestDeleteComment() {
	t := test.T()
	resource.Require(t, resource.Database)

	defer cleaner.DeleteCreatedEntities(test.DB)()

	repo := comment.NewCommentRepository(test.DB)

	parentID := "AA"
	c := &comment.Comment{
		ParentID:  parentID,
		Body:      "Test AA",
		CreatedBy: uuid.NewV4(),
		ID:        uuid.NewV4(),
	}

	repo.Create(context.Background(), c)
	if c.ID == uuid.Nil {
		t.Errorf("Comment was not created, ID nil")
	}

	c.Body = "Test AB"
	err := repo.Delete(context.Background(), c.ID)

	if err != nil {
		t.Error("Failed to Delete", err.Error())
	}

}
开发者ID:Ritsyy,项目名称:almighty-core,代码行数:29,代码来源:comment_test.go

示例10: testGossipPeeringsInner

func testGossipPeeringsInner(t *testing.T, c cluster.Cluster, cfg cluster.TestConfig) {
	num := c.NumNodes()

	deadline := timeutil.Now().Add(cfg.Duration)

	waitTime := longWaitTime
	if cfg.Duration < waitTime {
		waitTime = shortWaitTime
	}

	for timeutil.Now().Before(deadline) {
		checkGossip(t, c, waitTime, hasPeers(num))

		// Restart the first node.
		log.Infof(context.Background(), "restarting node 0")
		if err := c.Restart(0); err != nil {
			t.Fatal(err)
		}
		checkGossip(t, c, waitTime, hasPeers(num))

		// Restart another node (if there is one).
		var pickedNode int
		if num > 1 {
			pickedNode = rand.Intn(num-1) + 1
		}
		log.Infof(context.Background(), "restarting node %d", pickedNode)
		if err := c.Restart(pickedNode); err != nil {
			t.Fatal(err)
		}
		checkGossip(t, c, waitTime, hasPeers(num))
	}
}
开发者ID:yangxuanjia,项目名称:cockroach,代码行数:32,代码来源:gossip_peerings_test.go

示例11: TestGetters

func TestGetters(t *testing.T) {
	assert.False(t, IsAuthenticatedFromContext(context.Background()))
	_, err := PoliciesFromContext(context.Background())
	assert.NotNil(t, err)
	_, err = SubjectFromContext(context.Background())
	assert.NotNil(t, err)
	_, err = TokenFromContext(context.Background())
	assert.NotNil(t, err)

	ctx := context.Background()
	claims := hjwt.ClaimsCarrier{"sub": "peter"}
	token := &jwt.Token{Valid: true}
	policies := []policy.Policy{}
	ctx = NewContextFromAuthValues(ctx, claims, token, policies)

	assert.True(t, IsAuthenticatedFromContext(ctx))
	policiesContext, err := PoliciesFromContext(ctx)
	assert.Nil(t, err)
	assert.Equal(t, policies, policiesContext)

	subjectContext, err := SubjectFromContext(ctx)
	assert.Nil(t, err)
	assert.Equal(t, claims.GetSubject(), subjectContext)

	tokenContext, err := TokenFromContext(ctx)
	assert.Nil(t, err)
	assert.Equal(t, token, tokenContext)
}
开发者ID:lmineiro,项目名称:hydra,代码行数:28,代码来源:auth_test.go

示例12: TestShardConnBegin

func TestShardConnBegin(t *testing.T) {
	testShardConnGeneric(t, "TestShardConnBegin", func() error {
		sdc := NewShardConn(context.Background(), new(sandboxTopo), "aa", "TestShardConnBegin", "0", "", 1*time.Millisecond, 3, connTimeoutTotal, connTimeoutPerConn, 24*time.Hour, connectTimings)
		_, err := sdc.Begin(context.Background())
		return err
	})
}
开发者ID:pranjal5215,项目名称:vitess,代码行数:7,代码来源:shard_conn_test.go

示例13: TestScatterConnRollback

func TestScatterConnRollback(t *testing.T) {
	s := createSandbox("TestScatterConnRollback")
	sbc0 := &sandboxConn{}
	s.MapTestConn("0", sbc0)
	sbc1 := &sandboxConn{}
	s.MapTestConn("1", sbc1)
	stc := NewScatterConn(nil, topo.Server{}, new(sandboxTopo), "", "aa", retryDelay, retryCount, connTimeoutTotal, connTimeoutPerConn, connLife, "")

	// Sequence the executes to ensure commit order
	session := NewSafeSession(&proto.Session{InTransaction: true})
	stc.Execute(context.Background(), "query1", nil, "TestScatterConnRollback", []string{"0"}, pb.TabletType_REPLICA, session, false)
	stc.Execute(context.Background(), "query1", nil, "TestScatterConnRollback", []string{"0", "1"}, pb.TabletType_REPLICA, session, false)
	err := stc.Rollback(context.Background(), session)
	if err != nil {
		t.Errorf("want nil, got %v", err)
	}
	wantSession := proto.Session{}
	if !reflect.DeepEqual(wantSession, *session.Session) {
		t.Errorf("want\n%#v, got\n%#v", wantSession, *session.Session)
	}
	if rollbackCount := sbc0.RollbackCount.Get(); rollbackCount != 1 {
		t.Errorf("want 1, got %d", rollbackCount)
	}
	if rollbackCount := sbc1.RollbackCount.Get(); rollbackCount != 1 {
		t.Errorf("want 1, got %d", rollbackCount)
	}
}
开发者ID:richarwu,项目名称:vitess,代码行数:27,代码来源:scatter_conn_test.go

示例14: TestMultiExecs

func TestMultiExecs(t *testing.T) {
	s := createSandbox("TestMultiExecs")
	sbc0 := &sandboxConn{}
	s.MapTestConn("0", sbc0)
	sbc1 := &sandboxConn{}
	s.MapTestConn("1", sbc1)
	stc := NewScatterConn(nil, topo.Server{}, new(sandboxTopo), "", "aa", retryDelay, retryCount, connTimeoutTotal, connTimeoutPerConn, connLife, "")
	shardVars := map[string]map[string]interface{}{
		"0": map[string]interface{}{
			"bv0": 0,
		},
		"1": map[string]interface{}{
			"bv1": 1,
		},
	}
	_, _ = stc.ExecuteMulti(context.Background(), "query", "TestMultiExecs", shardVars, pb.TabletType_REPLICA, nil, false)
	if !reflect.DeepEqual(sbc0.Queries[0].BindVariables, shardVars["0"]) {
		t.Errorf("got %+v, want %+v", sbc0.Queries[0].BindVariables, shardVars["0"])
	}
	if !reflect.DeepEqual(sbc1.Queries[0].BindVariables, shardVars["1"]) {
		t.Errorf("got %+v, want %+v", sbc0.Queries[0].BindVariables, shardVars["1"])
	}
	sbc0.Queries = nil
	sbc1.Queries = nil
	_ = stc.StreamExecuteMulti(context.Background(), "query", "TestMultiExecs", shardVars, pb.TabletType_REPLICA, func(*mproto.QueryResult) error {
		return nil
	})
	if !reflect.DeepEqual(sbc0.Queries[0].BindVariables, shardVars["0"]) {
		t.Errorf("got %+v, want %+v", sbc0.Queries[0].BindVariables, shardVars["0"])
	}
	if !reflect.DeepEqual(sbc1.Queries[0].BindVariables, shardVars["1"]) {
		t.Errorf("got %+v, want %+v", sbc0.Queries[0].BindVariables, shardVars["1"])
	}
}
开发者ID:richarwu,项目名称:vitess,代码行数:34,代码来源:scatter_conn_test.go

示例15: runMVCCConditionalPut

func runMVCCConditionalPut(emk engineMaker, valueSize int, createFirst bool, b *testing.B) {
	rng, _ := randutil.NewPseudoRand()
	value := roachpb.MakeValueFromBytes(randutil.RandBytes(rng, valueSize))
	keyBuf := append(make([]byte, 0, 64), []byte("key-")...)

	eng := emk(b, fmt.Sprintf("cput_%d", valueSize))
	defer eng.Close()

	b.SetBytes(int64(valueSize))
	var expected *roachpb.Value
	if createFirst {
		for i := 0; i < b.N; i++ {
			key := roachpb.Key(encoding.EncodeUvarintAscending(keyBuf[:4], uint64(i)))
			ts := makeTS(timeutil.Now().UnixNano(), 0)
			if err := MVCCPut(context.Background(), eng, nil, key, ts, value, nil); err != nil {
				b.Fatalf("failed put: %s", err)
			}
		}
		expected = &value
	}

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		key := roachpb.Key(encoding.EncodeUvarintAscending(keyBuf[:4], uint64(i)))
		ts := makeTS(timeutil.Now().UnixNano(), 0)
		if err := MVCCConditionalPut(context.Background(), eng, nil, key, ts, value, expected, nil); err != nil {
			b.Fatalf("failed put: %s", err)
		}
	}

	b.StopTimer()
}
开发者ID:knz,项目名称:cockroach,代码行数:33,代码来源:bench_test.go


注:本文中的golang.org/x/net/context.Background函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。