本文整理汇总了Golang中github.com/cockroachdb/cockroach/testutils.IsError函数的典型用法代码示例。如果您正苦于以下问题:Golang IsError函数的具体用法?Golang IsError怎么用?Golang IsError使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了IsError函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestBadRequest
func TestBadRequest(t *testing.T) {
defer leaktest.AfterTest(t)
s := server.StartTestServer(t)
db := createTestClient(t, s.Stopper(), s.ServingAddr())
defer s.Stop()
// Write key "a".
if err := db.Put("a", "value"); err != nil {
t.Fatal(err)
}
if _, err := db.Scan("a", "a", 0); !testutils.IsError(err, "truncation resulted in empty batch") {
t.Fatalf("unexpected error on scan with startkey == endkey: %v", err)
}
if _, err := db.ReverseScan("a", "a", 0); !testutils.IsError(err, "truncation resulted in empty batch") {
t.Fatalf("unexpected error on reverse scan with startkey == endkey: %v", err)
}
if err := db.DelRange("x", "a"); !testutils.IsError(err, "truncation resulted in empty batch") {
t.Fatalf("unexpected error on deletion on [x, a): %v", err)
}
if err := db.DelRange("", "z"); !testutils.IsError(err, "must be greater than LocalMax") {
t.Fatalf("unexpected error on deletion on [KeyMin, z): %v", err)
}
}
示例2: TestRollbackToSavepointStatement
// TestRollbackToSavepointStatement tests that issuing a RESTART outside of a
// txn produces the proper error.
func TestRollbackToSavepointStatement(t *testing.T) {
defer leaktest.AfterTest(t)()
params, _ := createTestServerParams()
s, sqlDB, _ := serverutils.StartServer(t, params)
defer s.Stopper().Stop()
// ROLLBACK TO SAVEPOINT without a transaction
_, err := sqlDB.Exec("ROLLBACK TO SAVEPOINT cockroach_restart")
if !testutils.IsError(err, "the transaction is not in a retriable state") {
t.Fatalf("expected to fail here. err: %v", err)
}
// ROLLBACK TO SAVEPOINT with a wrong name
_, err = sqlDB.Exec("ROLLBACK TO SAVEPOINT foo")
if !testutils.IsError(err, "SAVEPOINT not supported except for COCKROACH_RESTART") {
t.Fatalf("expected to fail here. err: %v", err)
}
// ROLLBACK TO SAVEPOINT in a non-retriable transaction
tx, err := sqlDB.Begin()
if err != nil {
t.Fatal(err)
}
if _, err := tx.Exec("SAVEPOINT cockroach_restart"); err != nil {
t.Fatal(err)
}
if _, err = tx.Exec("BOGUS SQL STATEMENT"); err == nil {
t.Fatalf("expected to fail here. err: %v", err)
}
_, err = tx.Exec("ROLLBACK TO SAVEPOINT cockroach_restart")
if !testutils.IsError(err,
"SAVEPOINT COCKROACH_RESTART has not been used or a non-retriable error was encountered") {
t.Fatalf("expected to fail here. err: %v", err)
}
}
示例3: TestCommitWaitState
// Test that rando commands while in COMMIT_WAIT return a particular error.
func TestCommitWaitState(t *testing.T) {
defer leaktest.AfterTest(t)()
params, _ := createTestServerParams()
s, sqlDB, _ := serverutils.StartServer(t, params)
defer s.Stopper().Stop()
if _, err := sqlDB.Exec(`
CREATE DATABASE t; CREATE TABLE t.test (k INT PRIMARY KEY, v TEXT);
`); err != nil {
t.Fatal(err)
}
tx, err := sqlDB.Begin()
if err != nil {
t.Fatal(err)
}
if _, err := tx.Exec(
"SAVEPOINT cockroach_restart; RELEASE cockroach_restart;"); err != nil {
t.Fatal(err)
}
_, err = tx.Exec("INSERT INTO t.test (k, v) VALUES (0, 'sentinel');")
if !testutils.IsError(err, "current transaction is committed") {
t.Fatal(err)
}
// Rollback should respond with a COMMIT command tag.
err = tx.Rollback()
if !testutils.IsError(err, "unexpected command tag COMMIT") {
t.Fatal(err)
}
}
示例4: TestRestartStatement
// TestRestartStatement tests that issuing a RESTART outside of a txn produces
// the proper error.
func TestRestartStatement(t *testing.T) {
defer leaktest.AfterTest(t)()
server, sqlDB, _ := setup(t)
defer cleanup(server, sqlDB)
// RESTART without a transaction
_, err := sqlDB.Exec("RESTART TRANSACTION")
if !testutils.IsError(err, "the transaction is not in a retriable state") {
t.Fatal("expected to fail here. err: ", err)
}
// RESTART in a non-retriable transaction
tx, err := sqlDB.Begin()
if err != nil {
t.Fatal(err)
}
if _, err := tx.Exec("RETRY INTENT"); err != nil {
t.Fatal(err)
}
if _, err = tx.Exec("BOGUS SQL STATEMENT"); err == nil {
t.Fatalf("expected to fail here. err: %s", err)
}
_, err = tx.Exec("RESTART TRANSACTION")
if !testutils.IsError(err,
"RETRY INTENT has not been used or a non-retriable error was encountered") {
t.Fatal("expected to fail here. err: ", err)
}
}
示例5: TestCommitWaitState
// Test that rando commands while in COMMIT_WAIT return a particular error.
func TestCommitWaitState(t *testing.T) {
defer leaktest.AfterTest(t)()
server, sqlDB, _ := setup(t)
defer cleanup(server, sqlDB)
if _, err := sqlDB.Exec(`
CREATE DATABASE t; CREATE TABLE t.test (k INT PRIMARY KEY, v TEXT);
`); err != nil {
t.Fatal(err)
}
tx, err := sqlDB.Begin()
if err != nil {
t.Fatal(err)
}
if _, err := tx.Exec("RETRY INTENT; RELEASE;"); err != nil {
t.Fatal(err)
}
_, err = tx.Exec("INSERT INTO t.test (k, v) VALUES (0, 'sentinel');")
if !testutils.IsError(err, "current transaction is committed") {
t.Fatal(err)
}
// Rollback should respond with a COMMIT command tag.
err = tx.Rollback()
if !testutils.IsError(err, "unexpected command tag COMMIT") {
t.Fatal(err)
}
}
示例6: TestBatchError
// TestBatchError verifies that Range returns an error if a request has an invalid range.
func TestBatchError(t *testing.T) {
testCases := []struct {
req [2]string
errMsg string
}{
{
req: [2]string{"\xff\xff\xff\xff", "a"},
errMsg: "must be less than KeyMax",
},
{
req: [2]string{"a", "\xff\xff\xff\xff"},
errMsg: "must be less than or equal to KeyMax",
},
}
for i, c := range testCases {
var ba roachpb.BatchRequest
ba.Add(&roachpb.ScanRequest{Span: roachpb.Span{Key: roachpb.Key(c.req[0]), EndKey: roachpb.Key(c.req[1])}})
if _, err := Range(ba); !testutils.IsError(err, c.errMsg) {
t.Errorf("%d: unexpected error %v", i, err)
}
}
// Test a case where a non-range request has an end key.
var ba roachpb.BatchRequest
ba.Add(&roachpb.GetRequest{Span: roachpb.Span{Key: roachpb.Key("a"), EndKey: roachpb.Key("b")}})
if _, err := Range(ba); !testutils.IsError(err, "end key specified for non-range operation") {
t.Errorf("unexpected error %v", err)
}
}
示例7: TestApplySnapshotDenyPreemptive
func TestApplySnapshotDenyPreemptive(t *testing.T) {
defer leaktest.AfterTest(t)()
var tc testContext
tc.Start(t)
defer tc.Stop()
key := roachpb.RKey("a")
realRng := tc.store.LookupReplica(key, nil)
// Use Raft to get a nontrivial term for our snapshot.
if pErr := realRng.redirectOnOrAcquireLease(context.Background()); pErr != nil {
t.Fatal(pErr)
}
snap, err := realRng.GetSnapshot()
if err != nil {
t.Fatal(err)
}
// Make sure that the Term is behind our first range term (raftInitialLogTerm)
snap.Metadata.Term--
// Create an uninitialized version of the first range. This is only ok
// because in the case we test, there's an error (and so we don't clobber
// our actual first range in the Store). If we want snapshots to apply
// successfully during tests, we need to adapt the snapshots to a new
// RangeID first and generally do a lot more work.
rng, err := NewReplica(&roachpb.RangeDescriptor{RangeID: 1}, tc.store, 0)
if err != nil {
t.Fatal(err)
}
if _, err := rng.applySnapshot(snap, raftpb.HardState{}); !testutils.IsError(
err, "cannot apply preemptive snapshot from past term",
) {
t.Fatal(err)
}
// Do something that extends the Raft log past what we have in the
// snapshot.
put := putArgs(roachpb.Key("a"), []byte("foo"))
if _, pErr := tc.SendWrapped(&put); pErr != nil {
t.Fatal(pErr)
}
snap.Metadata.Term++ // restore the "real" term of the snapshot
if _, err := rng.applySnapshot(snap, raftpb.HardState{}); !testutils.IsError(
err, "would erase acknowledged log entries",
) {
t.Fatal(err)
}
}
示例8: TestKVDBInternalMethods
// TestKVDBInternalMethods verifies no internal methods are available
// HTTP DB interface.
func TestKVDBInternalMethods(t *testing.T) {
defer leaktest.AfterTest(t)
t.Skip("test broken & disabled; obsolete after after #2271")
s := server.StartTestServer(t)
defer s.Stop()
testCases := []proto.Request{
&proto.HeartbeatTxnRequest{},
&proto.GCRequest{},
&proto.PushTxnRequest{},
&proto.RangeLookupRequest{},
&proto.ResolveIntentRequest{},
&proto.ResolveIntentRangeRequest{},
&proto.MergeRequest{},
&proto.TruncateLogRequest{},
&proto.LeaderLeaseRequest{},
&proto.EndTransactionRequest{
InternalCommitTrigger: &proto.InternalCommitTrigger{},
},
}
// Verify internal methods experience bad request errors.
db := createTestClient(t, s.Stopper(), s.ServingAddr())
for i, args := range testCases {
args.Header().Key = proto.Key("a")
if proto.IsRange(args) {
args.Header().EndKey = args.Header().Key.Next()
}
b := &client.Batch{}
b.InternalAddCall(proto.Call{Args: args, Reply: args.CreateReply()})
err := db.Run(b).GoError()
if err == nil {
t.Errorf("%d: unexpected success calling %s", i, args.Method())
} else if !testutils.IsError(err, "(couldn't find method|contains commit trigger)") {
t.Errorf("%d: expected missing method %s; got %s", i, args.Method(), err)
}
// Verify same but within a Batch request.
ba := &proto.BatchRequest{}
ba.Add(args)
b = &client.Batch{}
b.InternalAddCall(proto.Call{Args: ba, Reply: &proto.BatchResponse{}})
if err := db.Run(b).GoError(); err == nil {
t.Errorf("%d: unexpected success calling %s", i, args.Method())
} else if !testutils.IsError(err, "(contains an internal request|contains commit trigger)") {
t.Errorf("%d: expected disallowed method error %s; got %s", i, args.Method(), err)
}
}
}
示例9: TestEvalExprError
func TestEvalExprError(t *testing.T) {
testData := []struct {
expr string
expected string
}{
{`1 % 0`, `zero modulus`},
{`1 / 0`, `division by zero`},
{`'2010-09-28 12:00:00.1'::date`, `parsing time "2010-09-28 12:00:00.1": extra text`},
{`'2010-09-28 12:00.1 MST'::timestamp`, `parsing time "2010-09-28 12:00.1 MST" as "2006-01-02 15:04:05.999999999 MST": cannot parse ".1 MST" as ":"`},
{`'11h2m'::interval / 0`, `division by zero`},
{`'hello' || b'world'`, `unsupported binary operator: <string> || <bytes>`},
{`b'\xff\xfe\xfd'::string`, `invalid utf8: "\xff\xfe\xfd"`},
// TODO(pmattis): Check for overflow.
// {`~0 + 1`, `0`},
}
for _, d := range testData {
q, err := ParseTraditional("SELECT " + d.expr)
if err != nil {
t.Fatalf("%s: %v", d.expr, err)
}
expr := q[0].(*Select).Exprs[0].Expr
if _, err := defaultContext.EvalExpr(expr); !testutils.IsError(err, regexp.QuoteMeta(d.expected)) {
t.Errorf("%s: expected %s, but found %v", d.expr, d.expected, err)
}
}
}
示例10: TestTypeCheckSameTypedExprsError
func TestTypeCheckSameTypedExprsError(t *testing.T) {
floatConst := func(s string) Expr {
return &NumVal{Value: constant.MakeFromLiteral(s, token.FLOAT, 0), OrigString: s}
}
floatIntMismatchErr := `expected .* to be of type (float|int), found type (float|int)`
paramErr := `could not determine data type of parameter .*`
testData := []struct {
args MapArgs
desired Datum
exprs []Expr
expectedErr string
}{
{nil, nil, []Expr{NewDInt(1), floatConst("1.1")}, floatIntMismatchErr},
{nil, nil, []Expr{NewDInt(1), NewDFloat(1)}, floatIntMismatchErr},
{MapArgs{"a": TypeInt}, nil, []Expr{NewDFloat(1.1), ValArg{"a"}}, floatIntMismatchErr},
{MapArgs{"a": TypeInt}, nil, []Expr{floatConst("1.1"), ValArg{"a"}}, floatIntMismatchErr},
{MapArgs{"a": TypeFloat, "b": TypeInt}, nil, []Expr{ValArg{"b"}, ValArg{"a"}}, floatIntMismatchErr},
{nil, nil, []Expr{ValArg{"b"}, ValArg{"a"}}, paramErr},
}
for i, d := range testData {
forEachPerm(d.exprs, 0, func(exprs []Expr) {
if _, _, err := typeCheckSameTypedExprs(d.args, d.desired, exprs...); !testutils.IsError(err, d.expectedErr) {
t.Errorf("%d: expected %s, but found %v", i, d.expectedErr, err)
}
})
}
}
示例11: TestScanError
func TestScanError(t *testing.T) {
testData := []struct {
sql string
err string
}{
{`1e`, "invalid floating point literal"},
{`1e-`, "invalid floating point literal"},
{`1e+`, "invalid floating point literal"},
{`0x`, "invalid hexadecimal literal"},
{`1x`, "invalid hexadecimal literal"},
{`1.x`, "invalid hexadecimal literal"},
{`1.0x`, "invalid hexadecimal literal"},
{`0x0x`, "invalid hexadecimal literal"},
{`00x0x`, "invalid hexadecimal literal"},
{`9223372036854775809`, "integer value out of range"},
{`$9223372036854775809`, "integer value out of range"},
}
for _, d := range testData {
s := makeScanner(d.sql, Traditional)
var lval sqlSymType
id := s.Lex(&lval)
if id != ERROR {
t.Errorf("%s: expected ERROR, but found %d", d.sql, id)
}
if !testutils.IsError(errors.New(lval.str), d.err) {
t.Errorf("%s: expected %s, but found %s", d.sql, d.err, lval.str)
}
}
}
示例12: TestTxnAbortCount
func TestTxnAbortCount(t *testing.T) {
defer leaktest.AfterTest(t)()
_, sender, cleanupFn := setupMetricsTest(t)
defer cleanupFn()
value := []byte("value")
db := client.NewDB(sender)
intentionalErrText := "intentional error to cause abort"
// Test aborted transaction.
if err := db.Txn(func(txn *client.Txn) error {
key := []byte("key-abort")
if err := txn.SetIsolation(roachpb.SNAPSHOT); err != nil {
return err
}
if err := txn.Put(key, value); err != nil {
t.Fatal(err)
}
return errors.New(intentionalErrText)
}); !testutils.IsError(err, intentionalErrText) {
t.Fatalf("unexpected error: %s", err)
}
teardownHeartbeats(sender)
checkTxnMetrics(t, sender, "abort txn", 0, 0, 0, 1, 0)
}
示例13: TestTxnCoordSenderErrorWithIntent
// TestTxnCoordSenderErrorWithIntent validates that if a transactional request
// returns an error but also indicates a Writing transaction, the coordinator
// tracks it just like a successful request.
func TestTxnCoordSenderErrorWithIntent(t *testing.T) {
defer leaktest.AfterTest(t)
stopper := stop.NewStopper()
manual := hlc.NewManualClock(0)
clock := hlc.NewClock(manual.UnixNano)
clock.SetMaxOffset(20)
ts := NewTxnCoordSender(senderFn(func(_ context.Context, ba roachpb.BatchRequest) (*roachpb.BatchResponse, *roachpb.Error) {
txn := ba.Txn.Clone()
txn.Writing = true
return nil, roachpb.NewError(roachpb.NewTransactionRetryError(txn))
}), clock, false, nil, stopper)
defer stopper.Stop()
var ba roachpb.BatchRequest
key := roachpb.Key("test")
ba.Add(&roachpb.BeginTransactionRequest{Span: roachpb.Span{Key: key}})
ba.Add(&roachpb.PutRequest{Span: roachpb.Span{Key: key}})
ba.Add(&roachpb.EndTransactionRequest{})
ba.Txn = &roachpb.Transaction{Name: "test"}
if _, pErr := ts.Send(context.Background(), ba); !testutils.IsError(pErr.GoError(), "retry txn") {
t.Fatalf("unexpected error: %v", pErr)
}
defer teardownHeartbeats(ts)
ts.Lock()
defer ts.Unlock()
if len(ts.txns) != 1 {
t.Fatalf("expected transaction to be tracked")
}
}
示例14: TestWrongTxnRetry
// Tests that a retryable error for an inner txn doesn't cause the outer txn to
// be retried.
func TestWrongTxnRetry(t *testing.T) {
defer leaktest.AfterTest(t)()
db := NewDB(newTestSender(nil, nil))
var retries int
txnClosure := func(outerTxn *Txn) error {
log.Infof(context.Background(), "outer retry")
retries++
// Ensure the KV transaction is created.
if err := outerTxn.Put("a", "b"); err != nil {
t.Fatal(err)
}
var execOpt TxnExecOptions
execOpt.AutoRetry = false
err := outerTxn.Exec(
execOpt,
func(innerTxn *Txn, opt *TxnExecOptions) error {
// Ensure the KV transaction is created.
if err := innerTxn.Put("x", "y"); err != nil {
t.Fatal(err)
}
return roachpb.NewErrorWithTxn(&roachpb.TransactionPushError{
PusheeTxn: outerTxn.Proto}, &innerTxn.Proto).GoError()
})
return err
}
if err := db.Txn(context.TODO(), txnClosure); !testutils.IsError(err, "failed to push") {
t.Fatal(err)
}
if retries != 1 {
t.Fatalf("unexpected retries: %d", retries)
}
}
示例15: TestAuthentication
// TestAuthentication tests authentication for the KV endpoint.
func TestAuthentication(t *testing.T) {
defer leaktest.AfterTest(t)()
s, _, _ := serverutils.StartServer(t, base.TestServerArgs{})
defer s.Stopper().Stop()
var b1 client.Batch
b1.Put("a", "b")
// Create a node user client and call Run() on it which lets us build our own
// request, specifying the user.
db1 := createTestClientForUser(t, s.Stopper(), s.ServingAddr(), security.NodeUser)
if err := db1.Run(&b1); err != nil {
t.Fatal(err)
}
var b2 client.Batch
b2.Put("c", "d")
// Try again, but this time with certs for a non-node user (even the root
// user has no KV permissions).
db2 := createTestClientForUser(t, s.Stopper(), s.ServingAddr(), security.RootUser)
if err := db2.Run(&b2); !testutils.IsError(err, "is not allowed") {
t.Fatal(err)
}
}