Skip to content

Latest commit

 

History

History
80 lines (69 loc) · 3.72 KB

README.md

File metadata and controls

80 lines (69 loc) · 3.72 KB

MultipartFormDataParser

Actions Status Version Platform GitHub release Swift Package Manager GitHub license

MultipartFormDataParser is a 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.3.1")
]

CocoaPods

Podfile

pod 'MultipartFormDataParser'