Swiftpack.co - 417-72KI/MultipartFormDataParser as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
See all packages published by 417-72KI.
417-72KI/MultipartFormDataParser 2.0.0
Testing tool for `multipart/form-data`
⭐️ 12
🕓 16 weeks ago
iOS macOS tvOS
.package(url: "https://github.com/417-72KI/MultipartFormDataParser.git", from: "2.0.0")

MultipartFormDataParser

Actions Status Version Platform GitHub release Swift Package Manager GitHub license

Testing tool for multipart/form-data request in Swift.

When to upload some files via API, we must use multipart/form-data for request. multipart/form-data is defined as RFC-2388

Most famous networking libraries (e.g. Alamofire, APIKit) can implement easily. However, to test if the created request is as expected is difficult and bothering.

This library provides a parser for multipart/form-data request to test it briefly.

let request: URLRequest = ...
do {
    let data = try MultipartFormData.parse(from: request)
    let genbaNeko = try XCTUnwrap(data.element(forName: "genbaNeko"))
    let message = try XCTUnwrap(data.element(forName: "message"))
    XCTAssertNotNil(Image(data: genbaNeko.data))
    XCTAssertEqual(genbaNeko.mimeType, "image/jpeg")
    XCTAssertEqual(message.string, "Hello world!")
} catch {
    XCTFail(error.localizedDescription)
}

Using OHHTTPStubs, we can test a request created by networking libraries easily.

let expectedGenbaNeko: Data = ...

let condition = isHost("localhost") && isPath("/upload")
stub(condition: condition) { request in
    let errorResponse = { (message: String) -> HTTPStubsResponse in
        .init(
            jsonObject: ["status": 403, "error": message],
            statusCode: 403, 
            headers: ["Content-Type": "application/json"]
        )
    }
    do {
        let data = try MultipartFormData.parse(from: request)
        guard let genbaNeko = data.element(forName: "genbaNeko"),
              genbaNeko.data == expectedGenbaNeko else { return errorResponse("Unexpected genbaNeko") }
        guard let message = data.element(forName: "message"),
              message.string == "Hello world!" else { return errorResponse("Unexpected message: \(message)") }
    } catch {
        return .init(error: error)
    }
    return .init(
        jsonObject: ["status": 200],
        statusCode: 200,
        headers: ["Content-Type": "application/json"]
    )
}

Installation

Swift Package Manager (recommended)

Package.swift

dependencies: [
    .package(url: "https://github.com/417-72KI/MultipartFormDataParser.git", from: "2.0.0")
]

CocoaPods

Podfile

pod 'MultipartFormDataParser'

GitHub

link
Stars: 12
Last commit: 3 weeks ago
jonrohan Something's broken? Yell at me @ptrpavlik. Praise and feedback (and money) is also welcome.

Release Notes

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics