From ff0fc3df89aaab06d559f067cb898ebc896280e9 Mon Sep 17 00:00:00 2001 From: Jan-Erik Rediger Date: Wed, 29 Oct 2025 11:59:17 +0100 Subject: [PATCH] Swift: Decode object metric dataa from its snake case JSON form --- .../ios/Glean/Metrics/ObjectMetric.swift | 1 + .../Metrics/ObjectMetricTests.swift | 34 +++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/glean-core/ios/Glean/Metrics/ObjectMetric.swift b/glean-core/ios/Glean/Metrics/ObjectMetric.swift index 4cdb44c613..676153afdd 100644 --- a/glean-core/ios/Glean/Metrics/ObjectMetric.swift +++ b/glean-core/ios/Glean/Metrics/ObjectMetric.swift @@ -81,6 +81,7 @@ public final class ObjectMetricType: Sendable { public func testGetValue(_ pingName: String? = nil) -> K? { guard let data = self.inner.testGetValue(pingName) else { return nil } let jsonDecoder = JSONDecoder() + jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase return try! jsonDecoder.decode(K.self, from: Data(data.utf8)) } diff --git a/glean-core/ios/GleanTests/Metrics/ObjectMetricTests.swift b/glean-core/ios/GleanTests/Metrics/ObjectMetricTests.swift index 5eeac99ed9..388f2dc95d 100644 --- a/glean-core/ios/GleanTests/Metrics/ObjectMetricTests.swift +++ b/glean-core/ios/GleanTests/Metrics/ObjectMetricTests.swift @@ -8,6 +8,7 @@ import XCTest struct BalloonsObjectItem: Decodable, Equatable, ObjectSerialize { var colour: String? var diameter: Int64? + var anotherValue: Bool? func intoSerializedObject() -> String { var data: [String] = [] @@ -21,6 +22,11 @@ struct BalloonsObjectItem: Decodable, Equatable, ObjectSerialize { elem.append(val.intoSerializedObject()) data.append(elem) } + if let val = self.anotherValue { + var elem = "\"another_value\":" + elem.append(val.intoSerializedObject()) + data.append(elem) + } let obj = data.joined(separator: ",") let json = "{" + obj + "}" return json @@ -132,4 +138,32 @@ class ObjectMetricTypeTests: XCTestCase { XCTAssertEqual(2, snapshot.count) XCTAssertEqual(expected, snapshot) } + + func testObjectDecodesFromSnakeCase() { + let metric = ObjectMetricType(CommonMetricData( + category: "test", + name: "balloon", + sendInPings: ["store1"], + lifetime: .ping, + disabled: false + )) + + XCTAssertNil(metric.testGetValue()) + + var balloons: BalloonsObject = [] + balloons.append(BalloonsObjectItem(colour: "red", diameter: 5, anotherValue: true)) + balloons.append(BalloonsObjectItem(colour: "green", anotherValue: false)) + metric.set(balloons) + + let snapshot = metric.testGetValue()! + XCTAssertNotNil(snapshot) + XCTAssertEqual(2, snapshot.count) + + XCTAssertEqual(snapshot[0].colour, "red") + XCTAssertEqual(snapshot[0].diameter, 5) + XCTAssertEqual(snapshot[0].anotherValue, true) + XCTAssertEqual(snapshot[1].colour, "green") + XCTAssertNil(snapshot[1].diameter) + XCTAssertEqual(snapshot[1].anotherValue, false) + } }