ServerContextTests.swift 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 GRPCCore
  17. import Testing
  18. @Suite("ServerContext")
  19. struct ServerContextTests {
  20. @Suite("CancellationHandle")
  21. struct CancellationHandle {
  22. @Test("Is cancelled")
  23. @available(gRPCSwift 2.0, *)
  24. func isCancelled() async throws {
  25. await withServerContextRPCCancellationHandle { handle in
  26. #expect(!handle.isCancelled)
  27. handle.cancel()
  28. #expect(handle.isCancelled)
  29. }
  30. }
  31. @Test("Wait for cancellation")
  32. @available(gRPCSwift 2.0, *)
  33. func waitForCancellation() async throws {
  34. await withServerContextRPCCancellationHandle { handle in
  35. await withTaskGroup(of: Void.self) { group in
  36. group.addTask {
  37. try? await handle.cancelled
  38. }
  39. handle.cancel()
  40. await group.waitForAll()
  41. }
  42. }
  43. }
  44. @Test("Binds task local")
  45. @available(gRPCSwift 2.0, *)
  46. func bindsTaskLocal() async throws {
  47. await withServerContextRPCCancellationHandle { handle in
  48. let signal = AsyncStream.makeStream(of: Void.self)
  49. await withRPCCancellationHandler {
  50. handle.cancel()
  51. for await _ in signal.stream {}
  52. } onCancelRPC: {
  53. // If the task local wasn't bound, this wouldn't run.
  54. signal.continuation.finish()
  55. }
  56. }
  57. }
  58. }
  59. }