UserInfoTests.swift 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * Copyright 2020, 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 GRPC
  17. class UserInfoTests: GRPCTestCase {
  18. func testWithSubscript() {
  19. var userInfo = UserInfo()
  20. userInfo[FooKey.self] = "foo"
  21. assertThat(userInfo[FooKey.self], .is("foo"))
  22. userInfo[BarKey.self] = 42
  23. assertThat(userInfo[BarKey.self], .is(42))
  24. userInfo[FooKey.self] = nil
  25. assertThat(userInfo[FooKey.self], .is(.none()))
  26. userInfo[BarKey.self] = nil
  27. assertThat(userInfo[BarKey.self], .is(.none()))
  28. }
  29. func testWithExtensions() {
  30. var userInfo = UserInfo()
  31. userInfo.foo = "foo"
  32. assertThat(userInfo.foo, .is("foo"))
  33. userInfo.bar = 42
  34. assertThat(userInfo.bar, .is(42))
  35. userInfo.foo = nil
  36. assertThat(userInfo.foo, .is(.none()))
  37. userInfo.bar = nil
  38. assertThat(userInfo.bar, .is(.none()))
  39. }
  40. func testDescription() {
  41. var userInfo = UserInfo()
  42. assertThat(String(describing: userInfo), .is("[]"))
  43. // (We can't test with multiple values since ordering isn't stable.)
  44. userInfo.foo = "foo"
  45. assertThat(String(describing: userInfo), .is("[FooKey: foo]"))
  46. }
  47. }
  48. private enum FooKey: UserInfoKey {
  49. typealias Value = String
  50. }
  51. private enum BarKey: UserInfoKey {
  52. typealias Value = Int
  53. }
  54. extension UserInfo {
  55. fileprivate var foo: FooKey.Value? {
  56. get {
  57. return self[FooKey.self]
  58. }
  59. set {
  60. self[FooKey.self] = newValue
  61. }
  62. }
  63. fileprivate var bar: BarKey.Value? {
  64. get {
  65. return self[BarKey.self]
  66. }
  67. set {
  68. self[BarKey.self] = newValue
  69. }
  70. }
  71. }