Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 
 

96 rader
2.2 KiB

  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package tls
  5. import (
  6. "rand";
  7. "reflect";
  8. "testing";
  9. "testing/quick";
  10. )
  11. var tests = []interface{}{
  12. &clientHelloMsg{},
  13. &clientKeyExchangeMsg{},
  14. &finishedMsg{},
  15. }
  16. type testMessage interface {
  17. marshal() []byte;
  18. unmarshal([]byte) bool;
  19. }
  20. func TestMarshalUnmarshal(t *testing.T) {
  21. rand := rand.New(rand.NewSource(0));
  22. for i, iface := range tests {
  23. ty := reflect.NewValue(iface).Type();
  24. for j := 0; j < 100; j++ {
  25. v, ok := quick.Value(ty, rand);
  26. if !ok {
  27. t.Errorf("#%d: failed to create value", i);
  28. break;
  29. }
  30. m1 := v.Interface().(testMessage);
  31. marshaled := m1.marshal();
  32. m2 := iface.(testMessage);
  33. if !m2.unmarshal(marshaled) {
  34. t.Errorf("#%d failed to unmarshal %#v", i, m1);
  35. break;
  36. }
  37. m2.marshal(); // to fill any marshal cache in the message
  38. if !reflect.DeepEqual(m1, m2) {
  39. t.Errorf("#%d got:%#v want:%#v", i, m1, m2);
  40. break;
  41. }
  42. // Now check that all prefixes are invalid.
  43. for j := 0; j < len(marshaled); j++ {
  44. if m2.unmarshal(marshaled[0:j]) {
  45. t.Errorf("#%d unmarshaled a prefix of length %d of %#v", i, j, m1);
  46. break;
  47. }
  48. }
  49. }
  50. }
  51. }
  52. func randomBytes(n int, rand *rand.Rand) []byte {
  53. r := make([]byte, n);
  54. for i := 0; i < n; i++ {
  55. r[i] = byte(rand.Int31());
  56. }
  57. return r;
  58. }
  59. func (*clientHelloMsg) Generate(rand *rand.Rand, size int) reflect.Value {
  60. m := &clientHelloMsg{};
  61. m.major = uint8(rand.Intn(256));
  62. m.minor = uint8(rand.Intn(256));
  63. m.random = randomBytes(32, rand);
  64. m.sessionId = randomBytes(rand.Intn(32), rand);
  65. m.cipherSuites = make([]uint16, rand.Intn(63) + 1);
  66. for i := 0; i < len(m.cipherSuites); i++ {
  67. m.cipherSuites[i] = uint16(rand.Int31());
  68. }
  69. m.compressionMethods = randomBytes(rand.Intn(63) + 1, rand);
  70. return reflect.NewValue(m);
  71. }
  72. func (*clientKeyExchangeMsg) Generate(rand *rand.Rand, size int) reflect.Value {
  73. m := &clientKeyExchangeMsg{};
  74. m.ciphertext = randomBytes(rand.Intn(1000), rand);
  75. return reflect.NewValue(m);
  76. }
  77. func (*finishedMsg) Generate(rand *rand.Rand, size int) reflect.Value {
  78. m := &finishedMsg{};
  79. m.verifyData = randomBytes(12, rand);
  80. return reflect.NewValue(m);
  81. }