// DataExtensionsTests.swift - Copyright 2024 SwifterSwift

@testable import SwifterSwift
import XCTest

#if canImport(Foundation)
import Foundation

final class DataExtensionsTests: XCTestCase {
    func testString() {
        let dataFromString = Data("hello".utf8)
        XCTAssertNotNil(dataFromString)
        XCTAssertNotNil(dataFromString.string(encoding: .utf8))
        XCTAssertEqual(dataFromString.string(encoding: .utf8), "hello")
    }

    func testBytes() {
        let dataFromString = Data("hello".utf8)
        let bytes = dataFromString.bytes
        XCTAssertNotNil(bytes)
        XCTAssertEqual(bytes.count, 5)
    }

    func testJsonObject() {
        let invalidData = Data("hello".utf8)
        XCTAssertThrowsError(try invalidData.jsonObject())
        XCTAssertThrowsError(try invalidData.jsonObject(options: [.allowFragments]))

        let stringData = Data("\"hello\"".utf8)
        XCTAssertThrowsError(try stringData.jsonObject())
        XCTAssertEqual((try? stringData.jsonObject(options: [.allowFragments])) as? String, "hello")

        let objectData = Data("{\"message\": \"hello\"}".utf8)
        let object = (try? objectData.jsonObject()) as? [String: String]
        XCTAssertNotNil(object)
        XCTAssertEqual(object?["message"], "hello")

        let arrayData = Data("[\"hello\"]".utf8)
        let array = (try? arrayData.jsonObject()) as? [String]
        XCTAssertNotNil(array)
        XCTAssertEqual(array?.first, "hello")
    }
}

#endif
