Golang Panics示例

说明

golang panics示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: github.com/stretchr/testify/assert

示例#1
文件: envconf_test.go 项目: sboehmann/envconf

func TestInt(t *testing.T) {
	assert := assert.New(t)

	UnsetKey("envconf_test1")
	UnsetKey("envconf_test2")

	v, ok := GetInt("envconf_test1")
	assert.False(ok)
	assert.Zero(v)
	assert.Panics(func() { MustGetInt("envconf_test1") })

	SetString("envconf_test1", "blahBlah")
	v, ok = GetInt("envconf_test1")
	assert.False(ok)
	assert.Zero(v)
	assert.Panics(func() { MustGetInt("envconf_test1") })

	SetString("envconf_test1", "42")
	v, ok = GetInt("envconf_test1")
	assert.True(ok)
	assert.Equal(42, v)
	assert.Equal(42, MustGetInt("envconf_test1"))

	SetDefaultInt("envconf_test1", -5)
	v, ok = GetInt("envconf_test1")
	assert.True(ok)
	assert.Equal(42, v)
	assert.Equal(42, MustGetInt("envconf_test1"))

	SetDefaultInt("envconf_test2", -33)
	v, ok = GetInt("envconf_test2")
	assert.True(ok)
	assert.Equal(-33, v)
	assert.Equal(-33, MustGetInt("envconf_test2"))
}

示例#2
文件: blockchain_test.go 项目: keepwalking1234/skycoin

func TestLoadBlockchainPrivate(t *testing.T) {
	defer cleanupVisor()
	cleanupVisor()

	// No filename should return fresh blockchain
	bc := loadBlockchain("")
	assert.Equal(t, len(bc.Blocks), 0)

	// Filename with no file should return fresh blockchain
	assertFileNotExists(t, testBlockchainFile)
	bc = loadBlockchain(testBlockchainFile)
	assert.Equal(t, len(bc.Blocks), 0)

	// Loading an empty blockchain should panic
	assert.Nil(t, SaveBlockchain(bc, testBlockchainFile))
	assertFileExists(t, testBlockchainFile)
	assert.Panics(t, func() { loadBlockchain(testBlockchainFile) })

	// Loading a corrupt blockchain should panic
	corruptFile(t, testBlockchainFile)
	assert.Panics(t, func() { loadBlockchain(testBlockchainFile) })
	cleanupVisor()

	// Loading a valid blockchain should be safe
	vc := newMasterVisorConfig(t)
	vc.BlockchainFile = testBlockchainFile
	v := NewVisor(vc)
	assert.Nil(t, transferCoinsToSelf(v, v.Config.MasterKeys.Address))
	assert.Equal(t, len(v.blockchain.Blocks), 2)
	assert.Nil(t, v.SaveBlockchain())
	assertFileExists(t, testBlockchainFile)
	bc = loadBlockchain(testBlockchainFile)
	assert.Equal(t, v.blockchain, bc)
}

示例#3
文件: crypto_test.go 项目: keepwalking1234/skycoin

func TestPubKeyFromSecKey(t *testing.T) {
	p, s := GenerateKeyPair()
	assert.Equal(t, PubKeyFromSecKey(s), p)
	assert.Panics(t, func() { PubKeyFromSecKey(SecKey{}) })
	assert.Panics(t, func() { PubKeyFromSecKey(NewSecKey(randBytes(t, 99))) })
	assert.Panics(t, func() { PubKeyFromSecKey(NewSecKey(randBytes(t, 31))) })
}

示例#4
文件: transactions_test.go 项目: up4k/skycoin

func TestTransactionSignInputs(t *testing.T) {
	tx := &Transaction{}
	// Panics if txns already signed
	tx.Head.Sigs = append(tx.Head.Sigs, Sig{})
	assert.Panics(t, func() { tx.SignInputs([]SecKey{}) })
	// Panics if not enough keys
	tx = &Transaction{}
	ux, s := makeUxOutWithSecret(t)
	tx.PushInput(ux.Hash())
	ux2, s2 := makeUxOutWithSecret(t)
	tx.PushInput(ux2.Hash())
	tx.PushOutput(makeAddress(), 40, 80)
	assert.Equal(t, len(tx.Head.Sigs), 0)
	assert.Panics(t, func() { tx.SignInputs([]SecKey{s}) })
	assert.Equal(t, len(tx.Head.Sigs), 0)
	// Valid signing
	h := tx.hashInner()
	assert.NotPanics(t, func() { tx.SignInputs([]SecKey{s, s2}) })
	assert.Equal(t, len(tx.Head.Sigs), 2)
	assert.Equal(t, tx.hashInner(), h)
	p := PubKeyFromSecKey(s)
	a := AddressFromPubKey(p)
	p = PubKeyFromSecKey(s2)
	a2 := AddressFromPubKey(p)
	assert.Nil(t, ChkSig(a, h, tx.Head.Sigs[0]))
	assert.Nil(t, ChkSig(a2, h, tx.Head.Sigs[1]))
	assert.NotNil(t, ChkSig(a, h, tx.Head.Sigs[1]))
	assert.NotNil(t, ChkSig(a2, h, tx.Head.Sigs[0]))
}

示例#5
文件: list_test.go 项目: arv/noms-old

func TestListSlice(t *testing.T) {
	assert := assert.New(t)

	l1 := NewList()
	l1 = l1.Append(Int32(0), Int32(1), Int32(2), Int32(3))
	l2 := l1.Slice(1, 3)
	assert.Equal(uint64(4), l1.Len())
	assert.Equal(uint64(2), l2.Len())
	assert.Equal(Int32(1), l2.Get(0))
	assert.Equal(Int32(2), l2.Get(1))

	l3 := l1.Slice(0, 0)
	assert.Equal(uint64(0), l3.Len())
	l3 = l1.Slice(1, 1)
	assert.Equal(uint64(0), l3.Len())
	l3 = l1.Slice(1, 2)
	assert.Equal(uint64(1), l3.Len())
	assert.Equal(Int32(1), l3.Get(0))
	l3 = l1.Slice(0, l1.Len())
	assert.True(l1.Equals(l3))

	assert.Panics(func() {
		l3 = l1.Slice(0, l1.Len()+1)
	})
	assert.Panics(func() {
		l3 = l1.Slice(l1.Len()+1, l1.Len()+2)
	})
}

示例#6
文件: pkcs7_test.go 项目: marcopaganini/rclone

func TestUnpad(t *testing.T) {
	// We've tested the OK decoding in TestPad, now test the error cases
	for _, test := range []struct {
		n   int
		in  string
		err error
	}{
		{8, "", ErrorPaddingNotFound},
		{8, "1", ErrorPaddingNotAMultiple},
		{8, "12", ErrorPaddingNotAMultiple},
		{8, "123", ErrorPaddingNotAMultiple},
		{8, "1234", ErrorPaddingNotAMultiple},
		{8, "12345", ErrorPaddingNotAMultiple},
		{8, "123456", ErrorPaddingNotAMultiple},
		{8, "1234567", ErrorPaddingNotAMultiple},
		{8, "1234567\xFF", ErrorPaddingTooLong},
		{8, "1234567\x09", ErrorPaddingTooLong},
		{8, "1234567\x00", ErrorPaddingTooShort},
		{8, "123456\x01\x02", ErrorPaddingNotAllTheSame},
		{8, "\x07\x08\x08\x08\x08\x08\x08\x08", ErrorPaddingNotAllTheSame},
	} {
		result, actualErr := Unpad(test.n, []byte(test.in))
		assert.Equal(t, test.err, actualErr, fmt.Sprintf("Unpad %d %q", test.n, test.in))
		assert.Equal(t, result, []byte(nil))
	}
	assert.Panics(t, func() { _, _ = Unpad(1, []byte("")) }, "bad multiple")
	assert.Panics(t, func() { _, _ = Unpad(256, []byte("")) }, "bad multiple")
}

示例#7
文件: cors_test.go 项目: globalways/contrib

func TestBadConfig(t *testing.T) {
	assert.Panics(t, func() { New(Options{}) })
	assert.Panics(t, func() {
		New(Config{
			AllowAllOrigins: true,
			AllowedOrigins:  []string{"http://google.com"},
		})
	})
	assert.Panics(t, func() {
		New(Config{
			AllowAllOrigins: true,
			AllowOriginFunc: func(origin string) bool { return false },
		})
	})
	assert.Panics(t, func() {
		New(Config{
			AllowedOrigins:  []string{"http://google.com"},
			AllowOriginFunc: func(origin string) bool { return false },
		})
	})
	assert.Panics(t, func() {
		New(Config{
			AllowedOrigins: []string{"google.com"},
		})
	})
}

示例#8
文件: promisify_test.go 项目: augustoroman/promise

func TestPromiseRejected(t *testing.T) {
	defer time.AfterFunc(time.Second, t.FailNow).Stop() // limit test to 1 second running time.

	done1, done2, done3 := make(incrementor, 1), make(incrementor, 1), make(incrementor, 1)
	var a Promise
	a2 := a.Then(panicIfCalled, done1.process)
	a3 := a2.Then(panicIfCalled, done2.process)
	a3.Then(panicIfCalled, done3.process)

	// Validate that nothing happens while it's pending.
	select {
	case <-done1:
		t.Fatal("Wasn't supposed to receive yet!")
	case <-time.After(10 * time.Millisecond):
		// yay!
	}

	// Resolve the promise and trigger the downstream dependencies.
	assert.Equal(t, a.Reject(1), 1)
	assert.Equal(t, <-done1, 1)
	assert.Equal(t, <-done2, 2)
	assert.Equal(t, <-done3, 3)

	// Can't resolve more than once:
	assert.Panics(t, func() { a.Resolve(2) })
	assert.Panics(t, func() { a2.Reject(3) })

	// Subsequent calls to then are immediately queued.
	a.Then(panicIfCalled, done1.process)
	assert.Equal(t, <-done1, 1)
}

示例#9
文件: invalid_setup_test.go 项目: ae6rt/goref

func TestInvalidHandler(t *testing.T) {
	router := New(Context{})

	assert.Panics(t, func() {
		router.Get("/action", 1)
	})

	assert.Panics(t, func() {
		router.Get("/action", (*Context).InvalidHandler)
	})

	// Returns a string:
	assert.Panics(t, func() {
		router.Get("/action", (*Context).InvalidHandler2)
	})

	// Two writer inputs:
	assert.Panics(t, func() {
		router.Get("/action", (*Context).InvalidHandler3)
	})

	// Wrong context type:
	assert.Panics(t, func() {
		router.Get("/action", (*invalidSubcontext).Handler)
	})

	//
}

示例#10
文件: command_test.go 项目: jmptrader/commander

func TestCommand_makeCommand(t *testing.T) {

	c := makeCommand(commandString, "", "", HandlerFunc)

	if assert.NotNil(t, c) {
		assert.Equal(t, c.definition, commandString)
		assert.Equal(t, len(c.arguments), 4)
		assert.Equal(t, c.arguments[0].literal, "create")
		assert.Equal(t, c.arguments[1].identifier, "kind")
		assert.Equal(t, c.arguments[1].list[0], "project")
		assert.Equal(t, c.arguments[1].list[1], "account")
		assert.Equal(t, c.arguments[2].identifier, "name")
		assert.Equal(t, c.arguments[2].captureType, "string")
		assert.Equal(t, c.arguments[3].identifier, "description")
		assert.Equal(t, c.arguments[3].captureType, "string")
		assert.True(t, c.arguments[3].isOptional())
		assert.True(t, c.arguments[3].isVariable())
	}

	assert.Panics(t, func() {
		_ = makeCommand(commandStringTwoOptionalVariableBad, "", "", HandlerFunc)
	})

	assert.Panics(t, func() {
		_ = makeCommand(commandStringOptionalBad, "", "", HandlerFunc)
	})

	assert.Panics(t, func() {
		_ = makeCommand(commandString, "", "", nil)
	})

}

示例#11
文件: blockchain_test.go 项目: up4k/skycoin

func TestVerifyTransactionInputs(t *testing.T) {
	bc := NewBlockchain()
	bc.CreateMasterGenesisBlock(genAddress)
	tx := makeTransactionForChain(t, bc)
	// Valid txn
	uxIn, err := bc.Unspent.GetMultiple(tx.In)
	assert.Nil(t, err)
	assert.Nil(t, verifyTransactionInputs(tx, uxIn))
	// Bad sigs
	sig := tx.Head.Sigs[0]
	tx.Head.Sigs[0] = Sig{}
	assert.NotNil(t, verifyTransactionInputs(tx, uxIn))
	// Too many uxIn
	tx.Head.Sigs[0] = sig
	uxIn, err = bc.Unspent.GetMultiple(tx.In)
	assert.Nil(t, err)
	assert.Equal(t, len(uxIn), len(tx.In))
	uxIn = append(uxIn, makeUxOut(t))
	assert.True(t, DebugLevel2)
	assert.Panics(t, func() { verifyTransactionInputs(tx, uxIn) })
	// ux hash mismatch
	uxIn, err = bc.Unspent.GetMultiple(tx.In)
	assert.Nil(t, err)
	tx.In[0] = SHA256{}
	assert.Panics(t, func() { verifyTransactionInputs(tx, uxIn) })
}

示例#12
文件: coords_test_functions.go 项目: jesseeichar/gotopo

func CoordsInsertTestImpl(t *testing.T, simpleCoords geom.ReadWriteCoords, pointFactory func(...float64) geom.Point) {
	assert.True(t, simpleCoords.IsEmpty())

	assert.Panics(t, func() { simpleCoords.Insert(1, pointFactory(66, 32)) })
	assert.Equal(t, 0, int(simpleCoords.NumCoords()), "Number of coordinates should be the 0")

	assert.True(t, simpleCoords.IsEmpty())

	simpleCoords.Insert(0, pointFactory(1, 2))
	assert.Equal(t, int(simpleCoords.NumCoords()), 1, "Number of coordinates should be the 1")
	assert.Equal(t, []float64{1, 2}, simpleCoords.Get(0).ToArray(), fmt.Sprintf("Incorrect first coordinate in %v", simpleCoords))

	assert.False(t, simpleCoords.IsEmpty())

	assert.Panics(t, func() { simpleCoords.Insert(2, pointFactory(66, 32)) })
	assert.Equal(t, 1, int(simpleCoords.NumCoords()), "Number of coordinates should be the 1")
	assert.Equal(t, []float64{1, 2}, simpleCoords.Get(0).ToArray(), fmt.Sprintf("Incorrect first coordinate in %v", simpleCoords))

	simpleCoords.Insert(0, pointFactory(-1, 0))
	assert.Equal(t, 2, int(simpleCoords.NumCoords()), "Number of coordinates should be the 2")
	assert.Equal(t, []float64{-1, 0}, simpleCoords.Get(0).ToArray(), fmt.Sprintf("Incorrect first coordinate in %v", simpleCoords))
	assert.Equal(t, []float64{1, 2}, simpleCoords.Get(1).ToArray(), fmt.Sprintf("Incorrect first coordinate in %v", simpleCoords))

	simpleCoords.Insert(1, pointFactory(1, 1))
	assert.Equal(t, 3, int(simpleCoords.NumCoords()), "Number of coordinates should be the 3")
	assert.Equal(t, []float64{-1, 0}, simpleCoords.Get(0).ToArray(), fmt.Sprintf("Incorrect first coordinate in %v", simpleCoords))
	assert.Equal(t, []float64{1, 1}, simpleCoords.Get(1).ToArray(), fmt.Sprintf("Incorrect first coordinate in %v", simpleCoords))
	assert.Equal(t, []float64{1, 2}, simpleCoords.Get(2).ToArray(), fmt.Sprintf("Incorrect first coordinate in %v", simpleCoords))

	assert.Panics(t, func() { simpleCoords.Insert(1, pointFactory(1, 1, 4)) })
	assert.Equal(t, 3, int(simpleCoords.NumCoords()), "Number of coordinates should be the 3")
	assert.Equal(t, []float64{-1, 0}, simpleCoords.Get(0).ToArray(), fmt.Sprintf("Incorrect first coordinate in %v", simpleCoords))
	assert.Equal(t, []float64{1, 1}, simpleCoords.Get(1).ToArray(), fmt.Sprintf("Incorrect first coordinate in %v", simpleCoords))
	assert.Equal(t, []float64{1, 2}, simpleCoords.Get(2).ToArray(), fmt.Sprintf("Incorrect first coordinate in %v", simpleCoords))
}

示例#13
文件: coords_test_functions.go 项目: jesseeichar/gotopo

func CoordsSetTestImpl(t *testing.T, pointFactory func(...float64) geom.Point, coordsFunc func([]float64) geom.ReadWriteCoords) {
	simpleCoords := coordsFunc([]float64{1, 2, 3, 4, 5, 6})

	assert.False(t, simpleCoords.IsEmpty())

	simpleCoords.Set(1, pointFactory(30, 40))
	assert.Equal(t, 3, int(simpleCoords.NumCoords()), "Number of coordinates should be the 3")
	assert.Equal(t, []float64{1, 2}, simpleCoords.Get(0).ToArray(), fmt.Sprintf("Incorrect first coordinate in %v", simpleCoords))
	assert.Equal(t, []float64{30, 40}, simpleCoords.Get(1).ToArray(), fmt.Sprintf("Incorrect first coordinate in %v", simpleCoords))
	assert.Equal(t, []float64{5, 6}, simpleCoords.Get(2).ToArray(), fmt.Sprintf("Incorrect first coordinate in %v", simpleCoords))

	simpleCoords.Set(0, pointFactory(10, 20))
	assert.Equal(t, int(simpleCoords.NumCoords()), 3, "Number of coordinates should be the 3")
	assert.Equal(t, []float64{10, 20}, simpleCoords.Get(0).ToArray(), fmt.Sprintf("Incorrect first coordinate in %v", simpleCoords))
	assert.Equal(t, []float64{30, 40}, simpleCoords.Get(1).ToArray(), fmt.Sprintf("Incorrect first coordinate in %v", simpleCoords))
	assert.Equal(t, []float64{5, 6}, simpleCoords.Get(2).ToArray(), fmt.Sprintf("Incorrect first coordinate in %v", simpleCoords))

	simpleCoords.Set(2, pointFactory(50, 60))
	assert.Equal(t, int(simpleCoords.NumCoords()), 3, "Number of coordinates should be the 3")
	assert.Equal(t, []float64{10, 20}, simpleCoords.Get(0).ToArray(), fmt.Sprintf("Incorrect first coordinate in %v", simpleCoords))
	assert.Equal(t, []float64{30, 40}, simpleCoords.Get(1).ToArray(), fmt.Sprintf("Incorrect first coordinate in %v", simpleCoords))
	assert.Equal(t, []float64{50, 60}, simpleCoords.Get(2).ToArray(), fmt.Sprintf("Incorrect first coordinate in %v", simpleCoords))

	assert.Panics(t, func() { simpleCoords.Set(3, pointFactory(99, 9)) })
	assert.Equal(t, int(simpleCoords.NumCoords()), 3, "Number of coordinates should be the 3")
	assert.Equal(t, []float64{10, 20}, simpleCoords.Get(0).ToArray(), fmt.Sprintf("Incorrect first coordinate in %v", simpleCoords))
	assert.Equal(t, []float64{30, 40}, simpleCoords.Get(1).ToArray(), fmt.Sprintf("Incorrect first coordinate in %v", simpleCoords))
	assert.Equal(t, []float64{50, 60}, simpleCoords.Get(2).ToArray(), fmt.Sprintf("Incorrect first coordinate in %v", simpleCoords))

	assert.Panics(t, func() { simpleCoords.Set(2, pointFactory(99, 99, 99)) })
	assert.Equal(t, int(simpleCoords.NumCoords()), 3, "Number of coordinates should be the 3")
	assert.Equal(t, []float64{10, 20}, simpleCoords.Get(0).ToArray(), fmt.Sprintf("Incorrect first coordinate in %v", simpleCoords))
	assert.Equal(t, []float64{30, 40}, simpleCoords.Get(1).ToArray(), fmt.Sprintf("Incorrect first coordinate in %v", simpleCoords))
	assert.Equal(t, []float64{50, 60}, simpleCoords.Get(2).ToArray(), fmt.Sprintf("Incorrect first coordinate in %v", simpleCoords))
}

示例#14
文件: tracer_test.go 项目: jmptrader/tracer

func TestTracer_TraceWithInvalidLevels(t *testing.T) {

	assert.Panics(t, func() {

		tracer := New(LevelDebug)

		tracer.Trace(LevelEverything, "%s", "test")

	}, "Trace LevelEverything")

	assert.Panics(t, func() {

		tracer := New(LevelDebug)

		tracer.Trace(LevelNothing, "%s", "test")

	}, "Trace LevelNothing")

	assert.Panics(t, func() {

		tracer := New(LevelDebug)

		tracer.Trace(LevelEverything-1, "%s", "test")

	}, "Trace too low")

	assert.Panics(t, func() {

		tracer := New(LevelDebug)

		tracer.Trace(LevelNothing+1, "%s", "test")

	}, "Trace too high")

}

示例#15
文件: logger_test.go 项目: osamingo/logrusow

func TestPanic(t *testing.T) {

	// only message

	dummy.Reset()

	msg := "panic test message"
	err := errors.New("dummy")
	assert.Panics(t, func() { Panic(msg, err) })

	m := map[string]interface{}{}
	assert.NoError(t, json.NewDecoder(dummy).Decode(&m))

	assert.Equal(t, msg, m["msg"])
	assert.Equal(t, logrus.PanicLevel.String(), m["level"])
	assert.Equal(t, err.Error(), m[logrus.ErrorKey])
	assert.Nil(t, m["id"])

	// with fields

	dummy.Reset()

	id := "vytxeTZskVKR7C7WgdSP3d"
	assert.Panics(t, func() { Panic(msg, err, logrus.Fields{"id": id}) })

	m = map[string]interface{}{}
	assert.NoError(t, json.NewDecoder(dummy).Decode(&m))

	assert.Equal(t, msg, m["msg"])
	assert.Equal(t, logrus.PanicLevel.String(), m["level"])
	assert.Equal(t, err.Error(), m[logrus.ErrorKey])
	assert.Equal(t, id, m["id"])
}

示例#16
文件: wire_test.go 项目: natebrennand/dynago

func TestWireDecode(t *testing.T) {
	assert := assert.New(t)
	assert.Panics(func() { wireDecode(42) })
	decodeTest := func(k string, v interface{}) interface{} {
		return wireDecode(map[string]interface{}{k: v})
	}

	mapVal := map[string]interface{}{
		"Key1": map[string]interface{}{"S": "ABC"},
		"Key2": map[string]interface{}{"N": "123"},
	}
	listVal := []interface{}{mapVal["Key1"], mapVal["Key2"]}

	// Boolean
	assert.Equal(true, decodeTest("BOOL", true))
	assert.Equal(false, decodeTest("BOOL", false))
	// Binary
	assert.Equal([]byte("ABC"), decodeTest("B", "QUJD"))
	assert.Equal(BinarySet{[]byte("ABC"), []byte("AB")}, decodeTest("BS", []interface{}{"QUJD", "QUI="}))
	assert.Panics(func() { decodeTest("B", "QUJD=") })
	// Lists (heterogeneous)
	assert.Equal(List{"ABC", Number("123")}, decodeTest("L", listVal))
	// Maps (heterogeneous)
	assert.Equal(Document{"Key1": "ABC", "Key2": Number("123")}, decodeTest("M", mapVal))
	// Nil
	assert.Equal(nil, decodeTest("NULL", true))
	// Number
	assert.Equal(Number("45"), decodeTest("N", "45"))
	assert.Equal(NumberSet{"123", "456"}, decodeTest("NS", []interface{}{"123", "456"}))
	// Strings
	assert.Equal("FooBar", decodeTest("S", "FooBar"))
	assert.Equal(StringSet{"A", "B"}, decodeTest("SS", []interface{}{"A", "B"}))
}

示例#17
文件: ba_test.go 项目: tiborv/go-bitarray

func TestSubSection(t *testing.T) {
	assert := assert.New(t)

	test := NewBitArray("101")

	assert.Equal(test.SubSlice(0, 1).String(), "1")
	assert.Equal(test.SubSlice(1, 2).String(), "01")
	assert.Equal(test.SubSlice(0, 3).String(), "101")
	assert.Equal(test.SubSlice(0).String(), "101")
	assert.Equal(test.SubSlice(1).String(), "01")

	test2 := NewBitArray("011")

	assert.Equal(GetConcat(0, test, test2).SubSlice(0, 2).String(), "10")
	assert.Equal(GetConcat(1, test, test2).SubSlice(0, 2).String(), "01")
	assert.Equal(GetConcat(2, test, test2).SubSlice(0, 2).String(), "11")

	assert.Panics(func() {
		test.SubSlice(999)
	})

	assert.Panics(func() {
		test.SubSlice(0, 1, 2, 3)
	})
	assert.Panics(func() {
		test.SubSlice(2, -1)
	})
}

示例#18
文件: iterutil_test.go 项目: roessland/gopkg

func TestCartesianPower(t *testing.T) {
	var tuples <-chan []int64

	// (Z_1)**1 = { (0) }
	tuples = CartesianPower(1, 1)
	assert.Equal(t, []int64{0}, <-tuples, "they should be equal")
	assert.Nil(t, <-tuples, "channel should be closed")

	// (Z_1)**2 = { (0,0) }
	tuples = CartesianPower(1, 2)
	assert.Equal(t, []int64{0, 0}, <-tuples, "they should be equal")
	assert.Nil(t, <-tuples, "channel should be closed")

	// (Z_2)**2 = { (0,0), (0,1), (1,0), (1,1) }
	tuples = CartesianPower(2, 2)
	assert.Equal(t, []int64{0, 0}, <-tuples, "they should be equal")
	assert.Equal(t, []int64{0, 1}, <-tuples, "they should be equal")
	assert.Equal(t, []int64{1, 0}, <-tuples, "they should be equal")
	assert.Equal(t, []int64{1, 1}, <-tuples, "they should be equal")
	assert.Nil(t, <-tuples, "channel should be closed")

	// (Z_5)**1 = { (0), (1), (2), (3), (4) }
	tuples = CartesianPower(5, 1)
	assert.Equal(t, []int64{0}, <-tuples, "they should be equal")
	assert.Equal(t, []int64{1}, <-tuples, "they should be equal")
	assert.Equal(t, []int64{2}, <-tuples, "they should be equal")
	assert.Equal(t, []int64{3}, <-tuples, "they should be equal")
	assert.Equal(t, []int64{4}, <-tuples, "they should be equal")
	assert.Nil(t, <-tuples, "channel should be closed")

	// Panics
	assert.Panics(t, func() { CartesianPower(0, 1) }, "too small n")
	assert.Panics(t, func() { CartesianPower(5, -1) }, "too small power")
}

示例#19
文件: pkcs7_test.go 项目: marcopaganini/rclone

func TestPad(t *testing.T) {
	for _, test := range []struct {
		n        int
		in       string
		expected string
	}{
		{8, "", "\x08\x08\x08\x08\x08\x08\x08\x08"},
		{8, "1", "1\x07\x07\x07\x07\x07\x07\x07"},
		{8, "12", "12\x06\x06\x06\x06\x06\x06"},
		{8, "123", "123\x05\x05\x05\x05\x05"},
		{8, "1234", "1234\x04\x04\x04\x04"},
		{8, "12345", "12345\x03\x03\x03"},
		{8, "123456", "123456\x02\x02"},
		{8, "1234567", "1234567\x01"},
		{8, "abcdefgh", "abcdefgh\x08\x08\x08\x08\x08\x08\x08\x08"},
		{8, "abcdefgh1", "abcdefgh1\x07\x07\x07\x07\x07\x07\x07"},
		{8, "abcdefgh12", "abcdefgh12\x06\x06\x06\x06\x06\x06"},
		{8, "abcdefgh123", "abcdefgh123\x05\x05\x05\x05\x05"},
		{8, "abcdefgh1234", "abcdefgh1234\x04\x04\x04\x04"},
		{8, "abcdefgh12345", "abcdefgh12345\x03\x03\x03"},
		{8, "abcdefgh123456", "abcdefgh123456\x02\x02"},
		{8, "abcdefgh1234567", "abcdefgh1234567\x01"},
		{8, "abcdefgh12345678", "abcdefgh12345678\x08\x08\x08\x08\x08\x08\x08\x08"},
		{16, "", "\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10"},
		{16, "a", "a\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f"},
	} {
		actual := Pad(test.n, []byte(test.in))
		assert.Equal(t, test.expected, string(actual), fmt.Sprintf("Pad %d %q", test.n, test.in))
		recovered, err := Unpad(test.n, actual)
		assert.NoError(t, err)
		assert.Equal(t, []byte(test.in), recovered, fmt.Sprintf("Unpad %d %q", test.n, test.in))
	}
	assert.Panics(t, func() { Pad(1, []byte("")) }, "bad multiple")
	assert.Panics(t, func() { Pad(256, []byte("")) }, "bad multiple")
}

示例#20
文件: build_step_test.go 项目: thought-machine/please

func TestLicenceEnforcement(t *testing.T) {
	state, target := newState("//pkg:good")
	state.Config.Licences.Reject = append(state.Config.Licences.Reject, "gpl")
	state.Config.Licences.Accept = append(state.Config.Licences.Accept, "mit")

	// Target specifying no licence should not panic.
	checkLicences(state, target)

	// A license (non case sensitive) that is not in the list of accepted licenses will panic.
	assert.Panics(t, func() {
		target.Licences = append(target.Licences, "Bsd")
		checkLicences(state, target)
	}, "A target with a non-accepted licence will panic")

	// Accepting bsd should resolve the panic
	state.Config.Licences.Accept = append(state.Config.Licences.Accept, "BSD")
	checkLicences(state, target)

	// Now construct a new "bad" target.
	state, target = newState("//pkg:bad")
	state.Config.Licences.Reject = append(state.Config.Licences.Reject, "gpl")
	state.Config.Licences.Accept = append(state.Config.Licences.Accept, "mit")

	// Adding an explicitly rejected licence should panic no matter what.
	target.Licences = append(target.Licences, "GPL")
	assert.Panics(t, func() {
		checkLicences(state, target)
	}, "Trying to add GPL should panic (case insensitive)")
}

示例#21
文件: transactions_test.go 项目: up4k/skycoin

func TestTransactionSignInput(t *testing.T) {
	tx := &Transaction{}
	// Panics if too many inputs exist
	tx.In = append(tx.In, make([]SHA256, math.MaxUint16+2)...)
	_, s := GenerateKeyPair()
	assert.Panics(t, func() { tx.signInput(0, s, SHA256{}) })

	// Panics if idx too large for number of inputs
	tx = &Transaction{}
	ux, s := makeUxOutWithSecret(t)
	tx.PushInput(ux.Hash())
	assert.Panics(t, func() { tx.signInput(1, s, SHA256{}) })

	// Sigs should be extended if needed
	assert.Equal(t, len(tx.Head.Sigs), 0)
	ux2, s2 := makeUxOutWithSecret(t)
	tx.PushInput(ux2.Hash())
	tx.signInput(1, s2, tx.hashInner())
	assert.Equal(t, len(tx.Head.Sigs), 2)
	assert.Equal(t, tx.Head.Sigs[0], Sig{})
	assert.NotEqual(t, tx.Head.Sigs[1], Sig{})
	// Signing the earlier sig should be ok
	tx.signInput(0, s, tx.hashInner())
	assert.Equal(t, len(tx.Head.Sigs), 2)
	assert.NotEqual(t, tx.Head.Sigs[0], Sig{})
	assert.NotEqual(t, tx.Head.Sigs[1], Sig{})
}

示例#22
文件: types_test.go 项目: ralph-tice/dynago

func TestDocumentGetBool(t *testing.T) {
	var doc dynago.Document
	for _, n := range []string{"1", "-1", "5", "100"} {
		doc = dynago.Document{"val": dynago.Number(n)}
		assert.Equal(t, true, doc.GetBool("val"))
	}
	doc = dynago.Document{"val": dynago.Number("0")}
	assert.Equal(t, false, doc.GetBool("val"))

	doc = dynago.Document{}
	assert.Equal(t, false, doc.GetBool("val"))

	doc = dynago.Document{"val": nil}
	assert.Equal(t, false, doc.GetBool("val"))

	doc = dynago.Document{"val": dynago.Number("b")}
	assert.Panics(t, func() {
		doc.GetBool("val")
	})

	doc = dynago.Document{"val": "hello"}
	assert.Panics(t, func() {
		doc.GetBool("val")
	})

	doc = dynago.Document{"val": true}
	assert.Equal(t, true, doc.GetBool("val"))

	doc = dynago.Document{"val": false}
	assert.Equal(t, false, doc.GetBool("val"))

}

示例#23
文件: list_test.go 项目: arv/noms-old

func TestListType(t *testing.T) {
	assert := assert.New(t)

	l := NewList(Int32(0))
	assert.True(l.Type().Equals(MakeCompoundType(ListKind, MakePrimitiveType(ValueKind))))

	tr := MakeCompoundType(ListKind, MakePrimitiveType(Uint8Kind))
	l2 := newListLeaf(tr, []Value{Uint8(0), Uint8(1)}...)
	assert.Equal(tr, l2.Type())

	l3 := l2.Slice(0, 1)
	assert.True(tr.Equals(l3.Type()))
	l3 = l2.Remove(0, 1)
	assert.True(tr.Equals(l3.Type()))
	l3 = l2.RemoveAt(0)
	assert.True(tr.Equals(l3.Type()))

	l3 = l2.Set(0, Uint8(11))
	assert.True(tr.Equals(l3.Type()))
	l3 = l2.Append(Uint8(2))
	assert.True(tr.Equals(l3.Type()))
	l3 = l2.Insert(0, Uint8(3))
	assert.True(tr.Equals(l3.Type()))

	assert.Panics(func() { l2.Set(0, NewString("")) })
	assert.Panics(func() { l2.Append(NewString("")) })
	assert.Panics(func() { l2.Insert(0, NewString("")) })
}

示例#24
文件: blockchain_test.go 项目: keepwalking1234/skycoin

func TestVerifyTransactionInputs(t *testing.T) {
	bc := NewBlockchain()
	bc.CreateGenesisBlock(genAddress, _genTime, _genCoins)
	_, ux := addBlockToBlockchain(t, bc)
	// Valid txn
	tx, _ := makeTransactionForChainWithHoursFee(t, bc, ux, genSecret, 100, 50)
	uxIn, err := bc.Unspent.GetMultiple(tx.In)
	assert.Nil(t, err)
	assert.Nil(t, verifyTransactionInputs(tx, uxIn))
	// Bad sigs
	sig := tx.Sigs[0]
	tx.Sigs[0] = cipher.Sig{}
	assert.NotNil(t, verifyTransactionInputs(tx, uxIn))
	// Too many uxIn
	tx.Sigs[0] = sig
	uxIn, err = bc.Unspent.GetMultiple(tx.In)
	assert.Nil(t, err)
	assert.Equal(t, len(uxIn), len(tx.In))
	uxIn = append(uxIn, makeUxOut(t))
	assert.True(t, DebugLevel2)
	assert.Panics(t, func() { verifyTransactionInputs(tx, uxIn) })
	// ux hash mismatch
	uxIn, err = bc.Unspent.GetMultiple(tx.In)
	assert.Nil(t, err)
	tx.In[0] = cipher.SHA256{}
	assert.Panics(t, func() { verifyTransactionInputs(tx, uxIn) })
}

示例#25
文件: simple_test.go 项目: JmAbuDabi/skycoin

func TestMustLoadWalletEntry(t *testing.T) {
	defer cleanupWallets()
	// File doesn't exist, panics
	assertFileNotExists(t, testWalletEntryFile)
	assert.Panics(t, func() { MustLoadWalletEntry(testWalletEntryFile) })
	cleanupWallets()

	// Valid file loads
	we := NewWalletEntry()
	rwe := NewReadableWalletEntry(&we)
	assert.Nil(t, rwe.Save(testWalletEntryFile))
	assertFileMode(t, testWalletEntryFile, 0600)
	assertFileExists(t, testWalletEntryFile)
	we2 := MustLoadWalletEntry(testWalletEntryFile)
	assert.Equal(t, we, we2)

	// Invalid entry panics
	we.Public = cipher.PubKey{}
	rwe = NewReadableWalletEntry(&we)
	cleanupWallets()
	assert.Nil(t, rwe.Save(testWalletEntryFile))
	assertFileMode(t, testWalletEntryFile, 0600)
	assertFileExists(t, testWalletEntryFile)
	assert.Panics(t, func() { MustLoadWalletEntry(testWalletEntryFile) })
}

示例#26
文件: blockchain_test.go 项目: skycoin/skycoin

func TestNewBlock(t *testing.T) {
	// TODO -- update this test for newBlock changes
	prev := coin.Block{Head: coin.BlockHeader{Version: 0x02, Time: 100, BkSeq: 98}}
	unsp := coin.NewUnspentPool()
	unsp.XorHash = randSHA256()
	txns := coin.Transactions{coin.Transaction{}}
	// invalid txn fees panics
	assert.Panics(t, func() { coin.NewBlock(prev, 133, unsp, txns, _badFeeCalc) })
	// no txns panics
	assert.Panics(t, func() {
		coin.NewBlock(prev, 133, unsp, nil, _feeCalc)
	})
	assert.Panics(t, func() {
		coin.NewBlock(prev, 133, unsp, coin.Transactions{}, _feeCalc)
	})
	// valid block is fine
	fee := uint64(121)
	currentTime := uint64(133)
	b := coin.NewBlock(prev, currentTime, unsp, txns, _makeFeeCalc(fee))
	assert.Equal(t, b.Body.Transactions, txns)
	assert.Equal(t, b.Head.Fee, fee*uint64(len(txns)))
	assert.Equal(t, b.Body, coin.BlockBody{txns})
	assert.Equal(t, b.Head.PrevHash, prev.HashHeader())
	assert.Equal(t, b.Head.Time, currentTime)
	assert.Equal(t, b.Head.BkSeq, prev.Head.BkSeq+1)
	assert.Equal(t, b.Head.UxHash,
		unsp.GetUxHash())
}

示例#27
文件: blockchain_test.go 项目: keepwalking1234/skycoin

func TestCreateGenesisBlock(t *testing.T) {
	defer cleanupVisor()
	// Test as master, successful
	vc := newMasterVisorConfig(t)
	v := NewMinimalVisor(vc)
	assert.True(t, v.Config.IsMaster)
	assert.Equal(t, len(v.blockchain.Blocks), 0)
	assert.Equal(t, len(v.blockSigs.Sigs), 0)
	sb := v.CreateGenesisBlock()
	assert.NotEqual(t, sb.Block, coin.Block{})
	assert.NotEqual(t, sb.Sig, cipher.Sig{})
	assert.Equal(t, len(v.blockchain.Blocks), 1)
	assert.Equal(t, len(v.blockSigs.Sigs), 1)
	assert.Nil(t, v.blockSigs.Verify(vc.MasterKeys.Public, v.blockchain))

	// Test as not master, successful
	vc = newGenesisConfig(t)
	v = NewMinimalVisor(vc)
	assert.False(t, v.Config.IsMaster)
	assert.Equal(t, len(v.blockchain.Blocks), 0)
	assert.Equal(t, len(v.blockSigs.Sigs), 0)
	sb = v.CreateGenesisBlock()
	assert.NotEqual(t, sb.Block, coin.Block{})
	assert.NotEqual(t, sb.Sig, cipher.Sig{})
	assert.Equal(t, len(v.blockchain.Blocks), 1)
	assert.Equal(t, len(v.blockSigs.Sigs), 1)
	assert.Nil(t, v.blockSigs.Verify(vc.MasterKeys.Public, v.blockchain))
	assert.Equal(t, v.Config.GenesisSignature, sb.Sig)
	assert.Equal(t, v.blockchain.Blocks[0].Header.Time, v.Config.GenesisTimestamp)

	// Test as master, blockSigs invalid for pubkey
	vc = newMasterVisorConfig(t)
	vc.MasterKeys.Public = cipher.PubKey{}
	v = NewMinimalVisor(vc)
	assert.True(t, v.Config.IsMaster)
	assert.Equal(t, len(v.blockchain.Blocks), 0)
	assert.Equal(t, len(v.blockSigs.Sigs), 0)
	assert.Panics(t, func() { v.CreateGenesisBlock() })

	// Test as not master, blockSigs invalid for pubkey
	vc = newGenesisConfig(t)
	vc.MasterKeys.Public = cipher.PubKey{}
	v = NewMinimalVisor(vc)
	assert.False(t, v.Config.IsMaster)
	assert.Equal(t, len(v.blockchain.Blocks), 0)
	assert.Equal(t, len(v.blockSigs.Sigs), 0)
	assert.Panics(t, func() { v.CreateGenesisBlock() })

	// Test as master, signing failed
	vc = newMasterVisorConfig(t)
	vc.MasterKeys.Secret = cipher.SecKey{}
	assert.Equal(t, vc.MasterKeys.Secret, cipher.SecKey{})
	v = NewMinimalVisor(vc)
	assert.True(t, v.Config.IsMaster)
	assert.Equal(t, v.Config, vc)
	assert.Equal(t, v.Config.MasterKeys.Secret, cipher.SecKey{})
	assert.Equal(t, len(v.blockchain.Blocks), 0)
	assert.Equal(t, len(v.blockSigs.Sigs), 0)
	assert.Panics(t, func() { v.CreateGenesisBlock() })
}

示例#28
文件: commander_test.go 项目: jmptrader/commander

func TestCommander_Map(t *testing.T) {

	sharedCommander = new(commander)

	Map(commandString, "", "", func(objx.Map) {
	})

	assert.Equal(t, len(sharedCommander.commands), 1)

	Map(DefaultCommand, "", "", func(objx.Map) {
	})

	assert.Equal(t, len(sharedCommander.commands), 2)

	assert.Panics(t, func() {
		Map(DefaultCommand, "", "", func(objx.Map) {
		})
	})

	assert.Panics(t, func() {
		Map(commandString, "", "", func(objx.Map) {
		})
	})

}

示例#29
文件: authentication_test.go 项目: nazwa/Galaxy-Empires

func TestAuthenticationSetUp(t *testing.T) {
	assert.Panics(t, func() {
		Authentication([]byte(""))
	})
	assert.NotPanics(t, func() {
		Authentication(TEST_AUTH_KEY)
	})

	validTokenText, err := mockLoginToken("10", time.Now().Add(10*time.Second), TEST_AUTH_KEY)
	assert.NoError(t, err)

	handler := Authentication(TEST_AUTH_KEY)

	// Run the handler with a valid token
	c := createGinContext(validTokenText)
	assert.NotPanics(t, func() {
		handler(c)
	})

	assert.Empty(t, c.Errors)
	assert.Equal(t, "10", c.MustGet(AuthUserIDKey))
	assert.IsType(t, &jwt.Token{}, c.MustGet(AuthTokenKey))

	// Run the handler with invalid token
	// There is no easy way to create a gin writer to properly detect response
	// Go will panic when Authentication tries to add error to an empty Writer object
	// So we can assume that the validation failed and user is not allowed through :)
	c = createGinContext("RANDOM TOKEN TEXT")
	assert.Panics(t, func() {
		handler(c)
	})
}

示例#30
文件: envconf_test.go 项目: sboehmann/envconf

func TestFloat64(t *testing.T) {
	assert := assert.New(t)

	UnsetKey("envconf_test1")
	UnsetKey("envconf_test2")

	v, ok := GetFloat64("envconf_test1")
	assert.False(ok)
	assert.Zero(v)
	assert.Panics(func() { MustGetFloat64("envconf_test1") })

	SetString("envconf_test1", "blahBlah")
	v, ok = GetFloat64("envconf_test1")
	assert.False(ok)
	assert.Zero(v)
	assert.Panics(func() { MustGetFloat64("envconf_test1") })

	SetString("envconf_test1", "83.3")
	v, ok = GetFloat64("envconf_test1")
	assert.True(ok)
	assert.True(floatEquals(83.3, v))
	assert.True(floatEquals(83.3, MustGetFloat64("envconf_test1")))

	SetDefaultFloat64("envconf_test1", -434.43202)
	v, ok = GetFloat64("envconf_test1")
	assert.True(ok)
	assert.True(floatEquals(83.3, v))
	assert.True(floatEquals(83.3, MustGetFloat64("envconf_test1")))

	SetDefaultFloat64("envconf_test2", -0.3424562)
	v, ok = GetFloat64("envconf_test2")
	assert.True(ok)
	assert.True(floatEquals(-0.3424562, v))
	assert.True(floatEquals(-0.3424562, MustGetFloat64("envconf_test2")))
}

展开阅读全文