Golang bytes.Equal类(方法)实例源码

下面列出了Golang bytes.Equal 类(方法)源码代码实例,从而了解它的用法。

作者:ds2de    项目:gc   
func TestTeeReader(t *testing.T) {
	src := []byte("hello, world")
	dst := make([]byte, len(src))
	rb := bytes.NewBuffer(src)
	wb := new(bytes.Buffer)
	r := TeeReader(rb, wb)
	if n, err := ReadFull(r, dst); err != nil || n != len(src) {
		t.Fatalf("ReadFull(r, dst) = %d, %v; want %d, nil", n, err, len(src))
	}
	if !bytes.Equal(dst, src) {
		t.Errorf("bytes read = %q want %q", dst, src)
	}
	if !bytes.Equal(wb.Bytes(), src) {
		t.Errorf("bytes written = %q want %q", wb.Bytes(), src)
	}
	if n, err := r.Read(dst); n != 0 || err != EOF {
		t.Errorf("r.Read at EOF = %d, %v want 0, EOF", n, err)
	}
	rb = bytes.NewBuffer(src)
	pr, pw := Pipe()
	pr.Close()
	r = TeeReader(rb, pw)
	if n, err := ReadFull(r, dst); n != 0 || err != ErrClosedPipe {
		t.Errorf("closed tee: ReadFull(r, dst) = %d, %v; want 0, EPIPE", n, err)
	}
}

作者:ZhuZhengy    项目:eris-d   
func validatePrecommit(t *testing.T, cs *ConsensusState, thisRound, lockRound int, privVal *types.PrivValidator, votedBlockHash, lockedBlockHash []byte) {
	precommits := cs.Votes.Precommits(thisRound)
	var vote *types.Vote
	if vote = precommits.GetByAddress(privVal.Address); vote == nil {
		panic("Failed to find precommit from validator")
	}

	if votedBlockHash == nil {
		if vote.BlockHash != nil {
			panic("Expected precommit to be for nil")
		}
	} else {
		if !bytes.Equal(vote.BlockHash, votedBlockHash) {
			panic("Expected precommit to be for proposal block")
		}
	}

	if lockedBlockHash == nil {
		if cs.LockedRound != lockRound || cs.LockedBlock != nil {
			panic(fmt.Sprintf("Expected to be locked on nil at round %d. Got locked at round %d with block %v", lockRound, cs.LockedRound, cs.LockedBlock))
		}
	} else {
		if cs.LockedRound != lockRound || !bytes.Equal(cs.LockedBlock.Hash(), lockedBlockHash) {
			panic(fmt.Sprintf("Expected block to be locked on round %d, got %d. Got locked block %X, expected %X", lockRound, cs.LockedRound, cs.LockedBlock.Hash(), lockedBlockHash))
		}
	}

}

作者:haltingstat    项目:secp256k1-g   
func TestMain2(t *testing.T) {

	fail := false
	for i := 0; i < 6*1024; i++ {

		seed := RandByte(32)
		//seed2 := RandByte(32)

		pubkey1, seckey1 := _GenerateDeterministicKeyPair(seed)
		pubkey2, seckey2 := GenerateDeterministicKeyPair(seed)

		if bytes.Equal(seckey1, seckey2) == false {
			fail = true
			log.Printf("deterministic seckeys do not match %d", i)
		}
		if bytes.Equal(pubkey1, pubkey2) == false {
			fail = true
			log.Printf("deterministic pubkeys do not match %d", i)
		}
	}

	if fail == true {
		log.Fatal("Failed")
	}
}

作者:carriercom    项目:interplanetar   
func TestMarshaling(t *testing.T) {

	test := func(d1 []byte, rid1 RequestID) {
		d2, err := wrapData(d1, rid1)
		if err != nil {
			t.Error(err)
		}

		d3, rid2, err := unwrapData(d2)
		if err != nil {
			t.Error(err)
		}

		d4, err := wrapData(d3, rid1)
		if err != nil {
			t.Error(err)
		}

		if !bytes.Equal(rid2, rid1) {
			t.Error("RequestID fail")
		}

		if !bytes.Equal(d1, d3) {
			t.Error("unmarshalled data should be the same")
		}

		if !bytes.Equal(d2, d4) {
			t.Error("marshalled data should be the same")
		}
	}

	test([]byte("foo"), []byte{1, 2, 3, 4})
	test([]byte("bar"), nil)
}

作者:hvaar    项目:cockroac   
func TestMakeKey(t *testing.T) {
	if !bytes.Equal(makeKey(roachpb.Key("A"), roachpb.Key("B")), roachpb.Key("AB")) ||
		!bytes.Equal(makeKey(roachpb.Key("A")), roachpb.Key("A")) ||
		!bytes.Equal(makeKey(roachpb.Key("A"), roachpb.Key("B"), roachpb.Key("C")), roachpb.Key("ABC")) {
		t.Fatalf("MakeKey is broken")
	}
}

作者:CowLe    项目:vites   
func TestLineTooLong(t *testing.T) {
	data := make([]byte, 0)
	for i := 0; i < minReadBufferSize*5/2; i++ {
		data = append(data, '0'+byte(i%10))
	}
	buf := bytes.NewBuffer(data)
	l := bufio.NewReaderSize(buf, minReadBufferSize)
	line, isPrefix, err := l.ReadLine()
	if !isPrefix || !bytes.Equal(line, data[:minReadBufferSize]) || err != nil {
		t.Errorf("bad result for first line: got %q want %q %v", line, data[:minReadBufferSize], err)
	}
	data = data[len(line):]
	line, isPrefix, err = l.ReadLine()
	if !isPrefix || !bytes.Equal(line, data[:minReadBufferSize]) || err != nil {
		t.Errorf("bad result for second line: got %q want %q %v", line, data[:minReadBufferSize], err)
	}
	data = data[len(line):]
	line, isPrefix, err = l.ReadLine()
	if isPrefix || !bytes.Equal(line, data[:minReadBufferSize/2]) || err != nil {
		t.Errorf("bad result for third line: got %q want %q %v", line, data[:minReadBufferSize/2], err)
	}
	line, isPrefix, err = l.ReadLine()
	if isPrefix || err == nil {
		t.Errorf("expected no more lines: %x %s", line, err)
	}
}

作者:mark-adam    项目:clien   
// Test that sealing a message and then opening it works and returns
// the original message.
func TestSealOpen(t *testing.T) {
	kp1, kp2 := makeKeyPairsOrBust(t)

	expectedData := []byte{0, 1, 2, 3, 4}
	nonce := [24]byte{5, 6, 7, 8}

	encryptedData := boxSeal(expectedData, nonce, kp1.Public, kp2.Private)

	data, err := boxOpen(encryptedData, nonce, kp2.Public, kp1.Private)
	if err != nil {
		t.Fatal(err)
	}

	if !bytes.Equal(data, expectedData) {
		t.Errorf("Expected %v, got %v", expectedData, data)
	}

	// Apparently, you can open a message you yourself have sealed.

	data, err = boxOpen(encryptedData, nonce, kp1.Public, kp2.Private)
	if err != nil {
		t.Fatal(err)
	}

	if !bytes.Equal(data, expectedData) {
		t.Errorf("Expected %v, got %v", expectedData, data)
	}
}

作者:GOGOGO    项目:go   
// Trying to add packet to existing message or creating new message
//
// For TCP message unique id is Acknowledgment number (see tcp_packet.go)
func (t *Listener) processTCPPacket(packet *TCPPacket) {
	defer func() { recover() }()

	var message *TCPMessage

	if parentAck, ok := t.seqWithData[packet.Seq]; ok {
		t.ackAliases[packet.Ack] = parentAck
		delete(t.seqWithData, packet.Seq)
	}

	if alias, ok := t.ackAliases[packet.Ack]; ok {
		packet.Ack = alias
	}

	mID := packet.Addr.String() + strconv.Itoa(int(packet.SrcPort)) + strconv.Itoa(int(packet.Ack))
	message, ok := t.messages[mID]

	if !ok {
		// We sending messageDelChan channel, so message object can communicate with Listener and notify it if message completed
		message = NewTCPMessage(mID, t.messageDelChan, packet.Ack)
		t.messages[mID] = message
	}

	if bytes.Equal(packet.Data[0:4], bPOST) {
		if bytes.Equal(packet.Data[len(packet.Data)-24:len(packet.Data)-4], bExpect100ContinueCheck) {
			t.seqWithData[packet.Seq+uint32(len(packet.Data))] = packet.Ack

			// Removing `Expect: 100-continue` header
			packet.Data = append(packet.Data[:len(packet.Data)-24], packet.Data[len(packet.Data)-2:]...)
		}
	}

	// Adding packet to message
	message.packetsChan <- packet
}

作者:bbandi    项目:cfss   
// Tests on verifying the rebundle flag and error code in Bundle.Status when rebundling.
func TestRebundleFromPEM(t *testing.T) {
	newBundler := newCustomizedBundlerFromFile(t, testCFSSLRootBundle, interL1, "")
	newBundle, err := newBundler.BundleFromPEMorDER(expiredBundlePEM, nil, Optimal, "")
	if err != nil {
		t.Fatalf("Re-bundle failed. %s", err.Error())
	}
	newChain := newBundle.Chain

	if len(newChain) != 2 {
		t.Fatalf("Expected bundle chain length is 2. Got %d.", len(newChain))
	}

	expiredChain, _ := helpers.ParseCertificatesPEM(expiredBundlePEM)
	for i, cert := range newChain {
		old := expiredChain[i]
		if i == 0 {
			if !bytes.Equal(old.Signature, cert.Signature) {
				t.Fatal("Leaf cert should be the same.")
			}
		} else {
			if bytes.Equal(old.Signature, cert.Signature) {
				t.Fatal("Intermediate cert should be different.")
			}
		}
	}
	// The status must be {Code: ExpiringBit is not set, IsRebundled:true, ExpiringSKIs:{}}
	if len(newBundle.Status.ExpiringSKIs) != 0 || !newBundle.Status.IsRebundled || newBundle.Status.Code&errors.BundleExpiringBit != 0 {
		t.Fatal("Rebundle Status is incorrect.")
	}

}

作者:ale    项目:der-asci   
func TestParseTag(t *testing.T) {
	for i, tt := range parseTagTests {
		tag, rest, ok := parseTag(tt.in)
		if !tt.ok {
			if ok {
				t.Errorf("%d. parseTag(%v) unexpectedly succeeded.", i, tt.in)
			} else if !bytes.Equal(rest, tt.in) {
				t.Errorf("%d. parseTag(%v) did not preserve input.", i, tt.in)
			}
		} else {
			if !ok {
				t.Errorf("%d. parseTag(%v) unexpectedly failed.", i, tt.in)
			} else if tag != tt.tag || len(rest) != 0 {
				t.Errorf("%d. parseTag(%v) = %v, %v wanted %v, [].", i, tt.in, tag, rest, tt.tag)
			}

			// Test again with trailing data.
			in := make([]byte, len(tt.in)+5)
			copy(in, tt.in)
			tag, rest, ok = parseTag(in)
			if !ok {
				t.Errorf("%d. parseTag(%v) unexpectedly failed.", i, in)
			} else if tag != tt.tag || !bytes.Equal(rest, in[len(tt.in):]) {
				t.Errorf("%d. parseTag(%v) = %v, %v wanted %v, %v.", i, in, tag, rest, tt.tag, in[len(tt.in):])
			}
		}
	}
}

作者:jimmyson    项目:btc   
// TestFilterAddCrossProtocol tests the MsgFilterAdd API when encoding with the
// latest protocol version and decoding with BIP0031Version.
func TestFilterAddCrossProtocol(t *testing.T) {
	data := []byte{0x01, 0x02}
	msg := wire.NewMsgFilterAdd(data)
	if !bytes.Equal(msg.Data, data) {
		t.Errorf("should get same data back out")
	}

	// Encode with latest protocol version.
	var buf bytes.Buffer
	err := msg.BtcEncode(&buf, wire.ProtocolVersion)
	if err != nil {
		t.Errorf("encode of MsgFilterAdd failed %v err <%v>", msg, err)
	}

	// Decode with old protocol version.
	var readmsg wire.MsgFilterAdd
	err = readmsg.BtcDecode(&buf, wire.BIP0031Version)
	if err == nil {
		t.Errorf("decode of MsgFilterAdd succeeded when it shouldn't "+
			"have %v", msg)
	}

	// Since one of the protocol versions doesn't support the filteradd
	// message, make sure the data didn't get encoded and decoded back out.
	if bytes.Equal(msg.Data, readmsg.Data) {
		t.Error("should not get same data for cross protocol")
	}

}

作者:matomes    项目:rk   
// QuoteVerify verifies that a quote was genuinely provided by the TPM. It
// takes the quote data, quote validation blob, public half of the AIK,
// current PCR values and the nonce used in the original quote request. It
// then verifies that the validation block is a valid signature for the
// quote data, that the secrets are the same (in order to avoid replay
// attacks), and that the PCR values are the same. It returns an error if
// any stage of the validation fails.
func QuoteVerify(data []byte, validation []byte, aikpub []byte, pcrvalues [][]byte, secret []byte) error {
	n := big.NewInt(0)
	n.SetBytes(aikpub)
	e := 65537

	pKey := rsa.PublicKey{N: n, E: int(e)}

	dataHash := sha1.Sum(data[:])

	err := rsa.VerifyPKCS1v15(&pKey, crypto.SHA1, dataHash[:], validation)
	if err != nil {
		return err
	}

	pcrHash := data[8:28]
	nonceHash := data[28:48]

	secretHash := sha1.Sum(secret[:])

	if bytes.Equal(secretHash[:], nonceHash) == false {
		return fmt.Errorf("Secret doesn't match")
	}

	pcrComposite := []byte{0x00, 0x02, 0xff, 0xff, 0x00, 0x00, 0x01, 0x40}
	for i := 0; i < 16; i++ {
		pcrComposite = append(pcrComposite, pcrvalues[i]...)
	}
	pcrCompositeHash := sha1.Sum(pcrComposite[:])

	if bytes.Equal(pcrCompositeHash[:], pcrHash) == false {
		return fmt.Errorf("PCR values don't match")
	}

	return nil
}

作者:jpitti    项目:toxiprox   
func TestMultiReadWrite(t *testing.T) {
	send := []byte("hello world, this message is longer")
	c := make(chan *StreamChunk)
	writer := NewChanWriter(c)
	reader := NewChanReader(c)
	go func() {
		writer.Write(send[:9])
		writer.Write(send[9:19])
		writer.Write(send[19:])
		writer.Close()
	}()
	buf := make([]byte, 10)
	read := 0
	for i := 0; i < len(send)/10; i++ {
		n, err := reader.Read(buf)
		if err != nil {
			t.Fatal("Couldn't read from stream", err)
		}
		if !bytes.Equal(buf[:n], send[read:read+n]) {
			t.Fatal("Got wrong message from stream", string(buf))
		}
		read += n
	}
	n, err := reader.Read(buf)
	if err != io.EOF {
		t.Fatal("Read returned wrong error after close:", err)
	}
	if !bytes.Equal(buf[:n], send[len(send)-n:]) {
		t.Fatal("Got wrong message from stream", string(buf[:n]))
	}
}

作者:mynameisfibe    项目:ns   
func (p *ProtocolV2) Exec(client *ClientV2, params [][]byte) ([]byte, error) {
	switch {
	case bytes.Equal(params[0], []byte("FIN")):
		return p.FIN(client, params)
	case bytes.Equal(params[0], []byte("RDY")):
		return p.RDY(client, params)
	case bytes.Equal(params[0], []byte("REQ")):
		return p.REQ(client, params)
	case bytes.Equal(params[0], []byte("PUB")):
		return p.PUB(client, params)
	case bytes.Equal(params[0], []byte("MPUB")):
		return p.MPUB(client, params)
	case bytes.Equal(params[0], []byte("NOP")):
		return p.NOP(client, params)
	case bytes.Equal(params[0], []byte("TOUCH")):
		return p.TOUCH(client, params)
	case bytes.Equal(params[0], []byte("IDENTIFY")):
		return p.IDENTIFY(client, params)
	case bytes.Equal(params[0], []byte("SUB")):
		return p.SUB(client, params)
	case bytes.Equal(params[0], []byte("CLS")):
		return p.CLS(client, params)
	}
	return nil, util.NewFatalClientErr(nil, "E_INVALID", fmt.Sprintf("invalid command %s", params[0]))
}

作者:rthornton12    项目:v   
func TestSectionTableMerge(t *testing.T) {
	o1 := vm.NewObject()
	o1.SecTab = vm.SectionTable{
		vm.TEXT: []byte{0x1, 0x2},
		vm.DATA: []byte{0xa, 0xb, 0xc},
	}
	o2 := vm.NewObject()
	o2.SecTab = vm.SectionTable{
		vm.TEXT: []byte{0x3, 0x4},
		vm.DATA: []byte{0xd, 0xe, 0xf},
	}

	if err := o1.Merge(o2); err != nil {
		log.Fatal(err)
	}

	text := []byte{0x1, 0x2, 0x3, 0x4}
	data := []byte{0xa, 0xb, 0xc, 0xd, 0xe, 0xf}

	if !bytes.Equal(o1.SecTab[vm.TEXT], text) {
		t.Fatal("expected", text, "got", o1.SecTab[vm.TEXT])
	}
	if !bytes.Equal(o1.SecTab[vm.DATA], data) {
		t.Fatal("expected", data, "got", o1.SecTab[vm.DATA])
	}
}

作者:postfi    项目:cryptobox-n   
// Validate symmetric decryption with Twofish:
//	* ensure the previously encrypted ciphertext can be successfully
//	  decrypted
//	* ensure decryption fails when ciphertext is too short
//	* ensure decryption with invalid Twofish key fails
//	* ensure decryption with the wrong key fails to recover the plaintext
func TestDecrypt(t *testing.T) {
	out, err := decrypt(testKey[:32], testCT)
	if err != nil {
		fmt.Println("secretbox: decrypt failed")
		fmt.Printf("\t%v\n", err)
		t.FailNow()
	} else if !bytes.Equal(out, testMsg) {
		fmt.Println("secretbox: decrypted message doesn't match original")
		t.FailNow()
	}

	_, err = decrypt(testKey[:], testCT[:4])
	if err == nil {
		fmt.Println("secretbox: decryption should fail when ciphertext is too short")
		t.FailNow()
	}

	_, err = decrypt(testKey[:], testCT)
	if err == nil {
		fmt.Println("secretbox: decryption should fail with invalid key")
		t.FailNow()
	}

	var badKey [32]byte
	out, err = decrypt(badKey[:], testCT)
	if err != nil {
		fmt.Println("secretbox: decrypt failed")
		fmt.Printf("\t%v\n", err)
		t.FailNow()
	} else if bytes.Equal(out, testMsg) {
		fmt.Println("secretbox: decrypted message shouldn't match original")
		t.FailNow()
	}
}

作者:CedarLogi    项目:go-ethereu   
func TestNodeID(t *testing.T) {
	nid := []byte{1, 2, 3, 4, 5, 6}
	SetNodeInterface("")
	s := NodeInterface()
	if s == "" || s == "user" {
		t.Errorf("NodeInterface %q after SetInteface\n", s)
	}
	node1 := NodeID()
	if node1 == nil {
		t.Errorf("NodeID nil after SetNodeInterface\n", s)
	}
	SetNodeID(nid)
	s = NodeInterface()
	if s != "user" {
		t.Errorf("Expected NodeInterface %q got %q\n", "user", s)
	}
	node2 := NodeID()
	if node2 == nil {
		t.Errorf("NodeID nil after SetNodeID\n", s)
	}
	if bytes.Equal(node1, node2) {
		t.Errorf("NodeID not changed after SetNodeID\n", s)
	} else if !bytes.Equal(nid, node2) {
		t.Errorf("NodeID is %x, expected %x\n", node2, nid)
	}
}

作者:ds2de    项目:gc   
func TestDecryptOAEP(t *testing.T) {
	random := rand.Reader

	sha1 := sha1.New()
	n := new(big.Int)
	d := new(big.Int)
	for i, test := range testEncryptOAEPData {
		n.SetString(test.modulus, 16)
		d.SetString(test.d, 16)
		private := new(PrivateKey)
		private.PublicKey = PublicKey{n, test.e}
		private.D = d

		for j, message := range test.msgs {
			out, err := DecryptOAEP(sha1, nil, private, message.out, nil)
			if err != nil {
				t.Errorf("#%d,%d error: %s", i, j, err)
			} else if !bytes.Equal(out, message.in) {
				t.Errorf("#%d,%d bad result: %#v (want %#v)", i, j, out, message.in)
			}

			// Decrypt with blinding.
			out, err = DecryptOAEP(sha1, random, private, message.out, nil)
			if err != nil {
				t.Errorf("#%d,%d (blind) error: %s", i, j, err)
			} else if !bytes.Equal(out, message.in) {
				t.Errorf("#%d,%d (blind) bad result: %#v (want %#v)", i, j, out, message.in)
			}
		}
		if testing.Short() {
			break
		}
	}
}

作者:nikandfo    项目:goleveld   
func compareBatch(t *testing.T, b1, b2 *Batch) {
	if b1.seq != b2.seq {
		t.Errorf("invalid seq number want %d, got %d", b1.seq, b2.seq)
	}
	if b1.Len() != b2.Len() {
		t.Fatalf("invalid record length want %d, got %d", b1.Len(), b2.Len())
	}
	p1, p2 := new(testBatch), new(testBatch)
	err := b1.Replay(p1)
	if err != nil {
		t.Fatal("error when replaying batch 1: ", err)
	}
	err = b2.Replay(p2)
	if err != nil {
		t.Fatal("error when replaying batch 2: ", err)
	}
	for i := range p1.rec {
		r1, r2 := p1.rec[i], p2.rec[i]
		if r1.kt != r2.kt {
			t.Errorf("invalid type on record '%d' want %d, got %d", i, r1.kt, r2.kt)
		}
		if !bytes.Equal(r1.key, r2.key) {
			t.Errorf("invalid key on record '%d' want %s, got %s", i, string(r1.key), string(r2.key))
		}
		if r1.kt == ktVal {
			if !bytes.Equal(r1.value, r2.value) {
				t.Errorf("invalid value on record '%d' want %s, got %s", i, string(r1.value), string(r2.value))
			}
		}
	}
}

作者:2theto    项目:g   
func TestOFB(t *testing.T) {
	for _, tt := range ofbTests {
		test := tt.name

		c, err := aes.NewCipher(tt.key)
		if err != nil {
			t.Errorf("%s: NewCipher(%d bytes) = %s", test, len(tt.key), err)
			continue
		}

		for j := 0; j <= 5; j += 5 {
			plaintext := tt.in[0 : len(tt.in)-j]
			ofb := cipher.NewOFB(c, tt.iv)
			ciphertext := make([]byte, len(plaintext))
			ofb.XORKeyStream(ciphertext, plaintext)
			if !bytes.Equal(ciphertext, tt.out[:len(plaintext)]) {
				t.Errorf("%s/%d: encrypting\ninput % x\nhave % x\nwant % x", test, len(plaintext), plaintext, ciphertext, tt.out)
			}
		}

		for j := 0; j <= 5; j += 5 {
			ciphertext := tt.out[0 : len(tt.in)-j]
			ofb := cipher.NewOFB(c, tt.iv)
			plaintext := make([]byte, len(ciphertext))
			ofb.XORKeyStream(plaintext, ciphertext)
			if !bytes.Equal(plaintext, tt.in[:len(ciphertext)]) {
				t.Errorf("%s/%d: decrypting\nhave % x\nwant % x", test, len(ciphertext), plaintext, tt.in)
			}
		}

		if t.Failed() {
			break
		}
	}
}


问题


面经


文章

微信
公众号

扫码关注公众号