GRPCMessageFramerTests.swift 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * Copyright 2024, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import NIOCore
  17. import XCTest
  18. @testable import GRPCHTTP2Core
  19. final class GRPCMessageFramerTests: XCTestCase {
  20. func testSingleWrite() throws {
  21. var framer = GRPCMessageFramer()
  22. framer.append(Array(repeating: 42, count: 128), compress: false)
  23. var buffer = try XCTUnwrap(framer.next())
  24. let (compressed, length) = try XCTUnwrap(buffer.readMessageHeader())
  25. XCTAssertFalse(compressed)
  26. XCTAssertEqual(length, 128)
  27. XCTAssertEqual(buffer.readSlice(length: Int(length)), ByteBuffer(repeating: 42, count: 128))
  28. XCTAssertEqual(buffer.readableBytes, 0)
  29. // No more bufers.
  30. XCTAssertNil(try framer.next())
  31. }
  32. func testMultipleWrites() throws {
  33. var framer = GRPCMessageFramer()
  34. let messages = 100
  35. for _ in 0 ..< messages {
  36. framer.append(Array(repeating: 42, count: 128), compress: false)
  37. }
  38. var buffer = try XCTUnwrap(framer.next())
  39. for _ in 0 ..< messages {
  40. let (compressed, length) = try XCTUnwrap(buffer.readMessageHeader())
  41. XCTAssertFalse(compressed)
  42. XCTAssertEqual(length, 128)
  43. XCTAssertEqual(buffer.readSlice(length: Int(length)), ByteBuffer(repeating: 42, count: 128))
  44. }
  45. XCTAssertEqual(buffer.readableBytes, 0)
  46. // No more bufers.
  47. XCTAssertNil(try framer.next())
  48. }
  49. }
  50. extension ByteBuffer {
  51. mutating func readMessageHeader() -> (Bool, UInt32)? {
  52. if let (compressed, length) = self.readMultipleIntegers(as: (UInt8, UInt32).self) {
  53. return (compressed != 0, length)
  54. } else {
  55. return nil
  56. }
  57. }
  58. }