|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the SwiftNIO open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2021 Apple Inc. and the SwiftNIO project authors |
| 6 | +// Licensed under Apache License v2.0 |
| 7 | +// |
| 8 | +// See LICENSE.txt for license information |
| 9 | +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors |
| 10 | +// |
| 11 | +// SPDX-License-Identifier: Apache-2.0 |
| 12 | +// |
| 13 | +//===----------------------------------------------------------------------===// |
| 14 | + |
| 15 | +import Foundation |
| 16 | +import XCTest |
| 17 | +import NIO |
| 18 | +import NIOFoundationCompat |
| 19 | + |
| 20 | +class JSONSerializationByteBufferTest: XCTestCase { |
| 21 | + |
| 22 | + func testSerializationRoundTrip() { |
| 23 | + |
| 24 | + let array = ["String1", "String2", "String3"] |
| 25 | + let dictionary = ["key1": "val1", "key2": "val2", "key3": "val3"] |
| 26 | + |
| 27 | + var dataArray = Data() |
| 28 | + var dataDictionary = Data() |
| 29 | + |
| 30 | + XCTAssertTrue(JSONSerialization.isValidJSONObject(array), "Array object cannot be converted to JSON") |
| 31 | + XCTAssertTrue(JSONSerialization.isValidJSONObject(dictionary), "Dictionary object cannot be converted to JSON") |
| 32 | + |
| 33 | + XCTAssertNoThrow(dataArray = try JSONSerialization.data(withJSONObject: array, options: .prettyPrinted)) |
| 34 | + XCTAssertNoThrow(dataDictionary = try JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted)) |
| 35 | + |
| 36 | + let arrayByteBuffer = ByteBuffer(data: dataArray) |
| 37 | + let dictByteBuffer = ByteBuffer(data: dataDictionary) |
| 38 | + |
| 39 | + var foundationArray: [String] = [] |
| 40 | + var foundationDict: [String: String] = [:] |
| 41 | + |
| 42 | + // Mutable containers comparison. |
| 43 | + XCTAssertNoThrow(foundationArray = try JSONSerialization.jsonObject(with: arrayByteBuffer, options: .mutableContainers) as! [String]) |
| 44 | + XCTAssertEqual(foundationArray, array) |
| 45 | + |
| 46 | + XCTAssertNoThrow(foundationDict = try JSONSerialization.jsonObject(with: dictByteBuffer, options: .mutableContainers) as! [String : String]) |
| 47 | + XCTAssertEqual(foundationDict, dictionary) |
| 48 | + |
| 49 | + // Mutable leaves comparison. |
| 50 | + XCTAssertNoThrow(foundationArray = try JSONSerialization.jsonObject(with: arrayByteBuffer, options: .mutableLeaves) as! [String]) |
| 51 | + XCTAssertEqual(foundationArray, array) |
| 52 | + |
| 53 | + XCTAssertNoThrow(foundationDict = try JSONSerialization.jsonObject(with: dictByteBuffer, options: .mutableLeaves) as! [String : String]) |
| 54 | + XCTAssertEqual(foundationDict, dictionary) |
| 55 | + } |
| 56 | +} |
0 commit comments