request_test.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package sarama
  2. import (
  3. "bytes"
  4. "reflect"
  5. "testing"
  6. )
  7. type testRequestBody struct {
  8. }
  9. func (s *testRequestBody) key() int16 {
  10. return 0x666
  11. }
  12. func (s *testRequestBody) version() int16 {
  13. return 0xD2
  14. }
  15. func (s *testRequestBody) encode(pe packetEncoder) error {
  16. return pe.putString("abc")
  17. }
  18. // not specific to request tests, just helper functions for testing structures that
  19. // implement the encoder or decoder interfaces that needed somewhere to live
  20. func testEncodable(t *testing.T, name string, in encoder, expect []byte) {
  21. packet, err := encode(in)
  22. if err != nil {
  23. t.Error(err)
  24. } else if !bytes.Equal(packet, expect) {
  25. t.Error("Encoding", name, "failed\ngot ", packet, "\nwant", expect)
  26. }
  27. }
  28. func testDecodable(t *testing.T, name string, out decoder, in []byte) {
  29. err := decode(in, out)
  30. if err != nil {
  31. t.Error("Decoding", name, "failed:", err)
  32. }
  33. }
  34. func testRequest(t *testing.T, name string, rb requestBody, expected []byte) {
  35. // Encoder request
  36. req := &request{correlationID: 123, clientID: "foo", body: rb}
  37. packet, err := encode(req)
  38. headerSize := 14 + len("foo")
  39. if err != nil {
  40. t.Error(err)
  41. } else if !bytes.Equal(packet[headerSize:], expected) {
  42. t.Error("Encoding", name, "failed\ngot ", packet, "\nwant", expected)
  43. }
  44. // Decoder request
  45. decoded, err := decodeRequest(bytes.NewReader(packet))
  46. if err != nil {
  47. t.Error("Failed to decode request", err)
  48. } else if decoded.correlationID != 123 || decoded.clientID != "foo" {
  49. t.Errorf("Decoded header is not valid: %v", decoded)
  50. } else if !reflect.DeepEqual(rb, decoded.body) {
  51. t.Errorf("Decoded request does not match the encoded one\nencoded: %v\ndecoded: %v", rb, decoded)
  52. }
  53. }
  54. func testResponse(t *testing.T, name string, res encoder, expected []byte) {
  55. encoded, err := encode(res)
  56. if err != nil {
  57. t.Error(err)
  58. } else if expected != nil && !bytes.Equal(encoded, expected) {
  59. t.Error("Encoding", name, "failed\ngot ", encoded, "\nwant", expected)
  60. }
  61. decoded := reflect.New(reflect.TypeOf(res).Elem()).Interface().(decoder)
  62. if err := decode(encoded, decoded); err != nil {
  63. t.Error("Decoding", name, "failed:", err)
  64. }
  65. if !reflect.DeepEqual(decoded, res) {
  66. t.Errorf("Decoded response does not match the encoded one\nencoded: %#v\ndecoded: %#v", res, decoded)
  67. }
  68. }