Skip to content

Commit

Permalink
Fix Metadata's description for prettier printing (#2185)
Browse files Browse the repository at this point in the history
This PR changes `Metadata`'s description to include quotes around string
values.

From this:

```
[("some-key", some-value)]
```

to this:

```
[("some-key", "some-value")]
```

---------

Co-authored-by: George Barnett <[email protected]>
  • Loading branch information
gjcairo and glbrntt authored Jan 31, 2025
1 parent f163392 commit eea6b49
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
19 changes: 18 additions & 1 deletion Sources/GRPCCore/Metadata.swift
Original file line number Diff line number Diff line change
Expand Up @@ -494,7 +494,13 @@ extension Metadata.Value: ExpressibleByArrayLiteral {

extension Metadata: CustomStringConvertible {
public var description: String {
String(describing: self.map({ ($0.key, $0.value) }))
if self.isEmpty {
return "[:]"
} else {
let elements = self.map { "\(String(reflecting: $0.key)): \(String(reflecting: $0.value))" }
.joined(separator: ", ")
return "[\(elements)]"
}
}
}

Expand All @@ -508,3 +514,14 @@ extension Metadata.Value: CustomStringConvertible {
}
}
}

extension Metadata.Value: CustomDebugStringConvertible {
public var debugDescription: String {
switch self {
case .string(let stringValue):
return String(reflecting: stringValue)
case .binary(let binaryValue):
return String(reflecting: binaryValue)
}
}
}
30 changes: 30 additions & 0 deletions Tests/GRPCCoreTests/MetadataTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -314,4 +314,34 @@ struct MetadataTests {
)
}
}

@Suite("Description")
struct Description {
let metadata: Metadata = [
"key1": "value1",
"key2": "value2",
"key-bin": .binary([1, 2, 3]),
]

@Test("Metadata")
func describeMetadata() async throws {
#expect("\(self.metadata)" == #"["key1": "value1", "key2": "value2", "key-bin": [1, 2, 3]]"#)
}

@Test("Metadata.Value")
func describeMetadataValue() async throws {
for (key, value) in self.metadata {
switch key {
case "key1":
#expect("\(value)" == "value1")
case "key2":
#expect("\(value)" == "value2")
case "key-bin":
#expect("\(value)" == "[1, 2, 3]")
default:
Issue.record("Should not have reached this point")
}
}
}
}
}

0 comments on commit eea6b49

Please sign in to comment.