ServerValueCodingTests.swift 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * Copyright 2020 Google LLC
  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 FirebaseDatabase
  17. import FirebaseDatabaseSwift
  18. import Foundation
  19. import XCTest
  20. class ServerTimestampTests: XCTestCase {
  21. func testDateRoundTrip() throws {
  22. struct Model: Codable, Equatable {
  23. @ServerTimestamp var timestamp: Date?
  24. }
  25. let model = Model(timestamp: Date(timeIntervalSince1970: 123_456_789.123))
  26. let dict = ["timestamp": 123_456_789_123]
  27. assertThat(model).roundTrips(to: dict)
  28. }
  29. func testTimestampEncoding() throws {
  30. struct Model: Codable, Equatable {
  31. @ServerTimestamp var timestamp: Date?
  32. }
  33. let model = Model()
  34. let dict = ["timestamp": [".sv": "timestamp"]]
  35. // We can't round trip since we only decode values as Ints
  36. // (for Date conversion) and never as the magic value.
  37. assertThat(model).encodes(to: dict)
  38. }
  39. }
  40. private struct CurrencyAmount: Codable, Equatable, Hashable, AdditiveArithmetic {
  41. static var zero: Self = CurrencyAmount(value: 0)
  42. static func + (lhs: Self, rhs: Self) -> Self {
  43. return Self(value: lhs.value + rhs.value)
  44. }
  45. static func += (lhs: inout Self, rhs: Self) {
  46. lhs.value += rhs.value
  47. }
  48. static func - (lhs: Self, rhs: Self) -> Self {
  49. return CurrencyAmount(value: lhs.value - rhs.value)
  50. }
  51. static func -= (lhs: inout Self, rhs: Self) {
  52. lhs.value -= rhs.value
  53. }
  54. var value: Decimal
  55. func encode(to encoder: Encoder) throws {
  56. var container = encoder.singleValueContainer()
  57. try container.encode(value)
  58. }
  59. init(value: Decimal) {
  60. self.value = value
  61. }
  62. init(from decoder: Decoder) throws {
  63. let container = try decoder.singleValueContainer()
  64. value = try container.decode(Decimal.self)
  65. }
  66. }
  67. extension CurrencyAmount: ExpressibleByIntegerLiteral {
  68. public init(integerLiteral value: Int) {
  69. self.value = Decimal(value)
  70. }
  71. }
  72. extension CurrencyAmount: ExpressibleByFloatLiteral {
  73. public init(floatLiteral value: Double) {
  74. self.value = Decimal(value)
  75. }
  76. }