WithConnectedSocketTests.swift 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * Copyright 2022, 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 EchoImplementation
  17. import EchoModel
  18. import NIOCore
  19. import NIOPosix
  20. import XCTest
  21. @testable import GRPC
  22. class WithConnectedSockettests: GRPCTestCase {
  23. func testWithConnectedSocket() throws {
  24. let group = NIOPosix.MultiThreadedEventLoopGroup(numberOfThreads: 1)
  25. defer {
  26. XCTAssertNoThrow(try group.syncShutdownGracefully())
  27. }
  28. let path = "/tmp/grpc-\(getpid()).sock"
  29. // Setup a server.
  30. let server = try Server.insecure(group: group)
  31. .withServiceProviders([EchoProvider()])
  32. .withLogger(self.serverLogger)
  33. .bind(unixDomainSocketPath: path)
  34. .wait()
  35. defer {
  36. XCTAssertNoThrow(try server.close().wait())
  37. }
  38. #if os(Linux)
  39. let sockStream = CInt(SOCK_STREAM.rawValue)
  40. #else
  41. let sockStream = SOCK_STREAM
  42. #endif
  43. let clientSocket = socket(AF_UNIX, sockStream, 0)
  44. XCTAssert(clientSocket != -1)
  45. let addr = try SocketAddress(unixDomainSocketPath: path)
  46. addr.withSockAddr { addr, size in
  47. let ret = connect(clientSocket, addr, UInt32(size))
  48. XCTAssert(ret != -1)
  49. }
  50. let flags = fcntl(clientSocket, F_GETFL, 0)
  51. XCTAssert(flags != -1)
  52. XCTAssert(fcntl(clientSocket, F_SETFL, flags | O_NONBLOCK) == 0)
  53. let connection = ClientConnection.insecure(group: group)
  54. .withBackgroundActivityLogger(self.clientLogger)
  55. .withConnectedSocket(clientSocket)
  56. defer {
  57. XCTAssertNoThrow(try connection.close().wait())
  58. }
  59. let client = Echo_EchoNIOClient(channel: connection)
  60. let resp = try client.get(Echo_EchoRequest(text: "Hello")).response.wait()
  61. XCTAssertEqual(resp.text, "Swift echo get: Hello")
  62. }
  63. }