Skip to content

Commit

Permalink
Revert "Remove support for streaming content for non-breaking release"
Browse files Browse the repository at this point in the history
This reverts commit 3c416cc.
  • Loading branch information
kylef committed Sep 28, 2016
1 parent 0bdde6b commit 2661dd9
Show file tree
Hide file tree
Showing 7 changed files with 149 additions and 132 deletions.
3 changes: 1 addition & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
# Mockingjay Changelog

## Future
## Master
### Breaking

- Responses now use a `Download` enum instead of an optional `NSData`. This
Expand Down
6 changes: 3 additions & 3 deletions Mockingjay/Builders.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ public func failure(error:NSError) -> (request:NSURLRequest) -> Response {
return { _ in return .Failure(error) }
}

public func http(status:Int = 200, headers:[String:String]? = nil, data:NSData? = nil) -> (request:NSURLRequest) -> Response {
public func http(status:Int = 200, headers:[String:String]? = nil, download:Download=nil) -> (request:NSURLRequest) -> Response {
return { (request:NSURLRequest) in
if let response = NSHTTPURLResponse(URL: request.URL!, statusCode: status, HTTPVersion: nil, headerFields: headers) {
return Response.Success(response, data)
return Response.Success(response, download)
}

return .Failure(NSError(domain: NSInternalInconsistencyException, code: 0, userInfo: [NSLocalizedDescriptionKey: "Failed to construct response for stub."]))
Expand All @@ -43,6 +43,6 @@ public func jsonData(data: NSData, status: Int = 200, headers: [String:String]?
headers["Content-Type"] = "application/json; charset=utf-8"
}

return http(status, headers: headers, data: data)(request:request)
return http(status, headers: headers, download: .Content(data))(request:request)
}
}
2 changes: 1 addition & 1 deletion Mockingjay/Mockingjay.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public func ==(lhs:Download, rhs:Download) -> Bool {
}

public enum Response : Equatable {
case Success(NSURLResponse, NSData?)
case Success(NSURLResponse, Download)
case Failure(NSError)
}

Expand Down
22 changes: 15 additions & 7 deletions Mockingjay/MockingjayProtocol.swift
Original file line number Diff line number Diff line change
Expand Up @@ -91,14 +91,22 @@ public class MockingjayProtocol : NSURLProtocol {
switch stub.builder(request) {
case .Failure(let error):
client?.URLProtocol(self, didFailWithError: error)
case .Success(let response, let data):
client?.URLProtocol(self, didReceiveResponse: response, cacheStoragePolicy: .NotAllowed)

if let data = data {
case .Success(var response, let download):
let headers = self.request.allHTTPHeaderFields

switch(download) {
case .Content(var data):
applyRangeFromHTTPHeaders(headers, toData: &data, andUpdateResponse: &response)
client?.URLProtocol(self, didLoadData: data)
client?.URLProtocolDidFinishLoading(self)
case .StreamContent(data: var data, inChunksOf: let bytes):
applyRangeFromHTTPHeaders(headers, toData: &data, andUpdateResponse: &response)
self.download(data, inChunksOfBytes: bytes)
return
case .NoContent:
client?.URLProtocol(self, didReceiveResponse: response, cacheStoragePolicy: .NotAllowed)
client?.URLProtocolDidFinishLoading(self)
}

client?.URLProtocolDidFinishLoading(self)
}
} else {
let error = NSError(domain: NSInternalInconsistencyException, code: 0, userInfo: [ NSLocalizedDescriptionKey: "Handling request without a matching stub." ])
Expand Down Expand Up @@ -189,4 +197,4 @@ extension NSRange {
let endLoc = self.location + self.length - 1
return "bytes " + String(self.location) + "-" + String(endLoc) + "/" + String(fullLength)
}
}
}
78 changes: 44 additions & 34 deletions MockingjayTests/BuildersTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,37 +38,42 @@ class FailureBuilderTests : XCTestCase {
XCTFail("Test Failure")
}
}

// func testHTTPDownloadStream() {
// let request = NSURLRequest(URL: NSURL(string: "http://test.com/")!)
// let response = http(download: .StreamContent(data: NSData(), inChunksOf: 1024))(request: request)
//
// switch response {
// case let .Success(_, download):
// switch download {
// case let .StreamContent(data: _, inChunksOf: bytes):
// XCTAssertEqual(bytes, 1024)
// default:
// XCTFail("Test Failure")
// }
// case let .Failure(error):
// XCTFail("Test Failure: " + error.debugDescription)
// }
// }

func testHTTPDownloadStream() {
let request = NSURLRequest(URL: NSURL(string: "http://test.com/")!)
let response = http(download: .StreamContent(data: NSData(), inChunksOf: 1024))(request: request)

switch response {
case let .Success(_, download):
switch download {
case let .StreamContent(data: _, inChunksOf: bytes):
XCTAssertEqual(bytes, 1024)
default:
XCTFail("Test Failure")
}
case let .Failure(error):
XCTFail("Test Failure: " + error.debugDescription)
}
}
func testJSON() {
let request = NSURLRequest(URL: NSURL(string: "http://test.com/")!)
let response = json(["A"])(request: request)

switch response {
case let .Success(response, data):
if let response = response as? NSHTTPURLResponse {
XCTAssertEqual(response.statusCode, 200)
XCTAssertEqual(response.MIMEType!, "application/json")
XCTAssertEqual(response.textEncodingName!, "utf-8")
let body = NSString(data: data!, encoding:NSUTF8StringEncoding) as! String
XCTAssertEqual(body, "[\"A\"]")
} else {
case let .Success(response, download):
switch download {
case .Content(let data):
if let response = response as? NSHTTPURLResponse {
XCTAssertEqual(response.statusCode, 200)
XCTAssertEqual(response.MIMEType!, "application/json")
XCTAssertEqual(response.textEncodingName!, "utf-8")
let body = NSString(data:data, encoding:NSUTF8StringEncoding) as! String
XCTAssertEqual(body, "[\"A\"]")
} else {
XCTFail("Test Failure")
}
default:
XCTFail("Test Failure")
}
default:
Expand All @@ -84,16 +89,21 @@ class FailureBuilderTests : XCTestCase {
let response = jsonData(data)(request: request)

switch response {
case let .Success(response, data):
guard let response = response as? NSHTTPURLResponse else {
case let .Success(response, download):
switch download {
case .Content(let data):
guard let response = response as? NSHTTPURLResponse else {
XCTFail("Test Failure")
return
}
XCTAssertEqual(response.statusCode, 200)
XCTAssertEqual(response.MIMEType!, "application/json")
XCTAssertEqual(response.textEncodingName!, "utf-8")
let body = NSString(data:data, encoding:NSUTF8StringEncoding) as! String
XCTAssertEqual(body, "[\"B\"]")
default:
XCTFail("Test Failure")
return
}
XCTAssertEqual(response.statusCode, 200)
XCTAssertEqual(response.MIMEType!, "application/json")
XCTAssertEqual(response.textEncodingName!, "utf-8")
let body = NSString(data:data!, encoding:NSUTF8StringEncoding) as! String
XCTAssertEqual(body, "[\"B\"]")
default:
XCTFail("Test Failure")
}
Expand Down
164 changes: 82 additions & 82 deletions MockingjayTests/MockingjayAsyncProtocolTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,90 +32,90 @@ class MockingjayAsyncProtocolTests: XCTestCase, NSURLSessionDataDelegate {

// MARK: Tests

// func testDownloadOfTextInChunks() {
// let request = NSURLRequest(URL: NSURL(string: "https://fuller.li/")!)
// let stubResponse = NSURLResponse(URL: request.URL!, MIMEType: "text/plain", expectedContentLength: 6, textEncodingName: "utf-8")
// let stubData = "Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!
//
// MockingjayProtocol.addStub({ (requestedRequest) -> (Bool) in
// return true
// }) { (request) -> (Response) in
// return Response.Success(stubResponse, .StreamContent(data: stubData, inChunksOf: 22))
// }
//
// let urlSession = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue.currentQueue())
// let dataTask = urlSession.dataTaskWithRequest(request)
// dataTask.resume()
//
// let mutableData = NSMutableData()
// while mutableData.length < stubData.length {
// let expectation = expectationWithDescription("testProtocolCanReturnedDataInChunks")
// self.didReceiveDataHandler = { (session: NSURLSession, dataTask: NSURLSessionDataTask, data: NSData) in
// mutableData.appendData(data)
// expectation.fulfill()
// }
// waitForExpectationsWithTimeout(2.0, handler: nil)
// }
// XCTAssertEqual(mutableData, stubData)
// }
func testDownloadOfTextInChunks() {
let request = NSURLRequest(URL: NSURL(string: "https://fuller.li/")!)
let stubResponse = NSURLResponse(URL: request.URL!, MIMEType: "text/plain", expectedContentLength: 6, textEncodingName: "utf-8")
let stubData = "Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!

MockingjayProtocol.addStub({ (requestedRequest) -> (Bool) in
return true
}) { (request) -> (Response) in
return Response.Success(stubResponse, .StreamContent(data: stubData, inChunksOf: 22))
}

let urlSession = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue.currentQueue())
let dataTask = urlSession.dataTaskWithRequest(request)
dataTask.resume()

let mutableData = NSMutableData()
while mutableData.length < stubData.length {
let expectation = expectationWithDescription("testProtocolCanReturnedDataInChunks")
self.didReceiveDataHandler = { (session: NSURLSession, dataTask: NSURLSessionDataTask, data: NSData) in
mutableData.appendData(data)
expectation.fulfill()
}
waitForExpectationsWithTimeout(2.0, handler: nil)
}
XCTAssertEqual(mutableData, stubData)
}

// func testDownloadOfAudioFileInChunks() {
// let request = NSURLRequest(URL: NSURL(string: "https://fuller.li/")!)
// let path = NSBundle(forClass: self.classForCoder).pathForResource("TestAudio", ofType: "m4a")
// let data = NSData(contentsOfFile: path!)!
//
// let stubResponse = NSHTTPURLResponse(URL: request.URL!, statusCode: 200, HTTPVersion: "1.1", headerFields: ["Content-Length" : String(data.length)])!
//
// MockingjayProtocol.addStub({ (requestedRequest) -> (Bool) in
// return true
// }) { (request) -> (Response) in
// return Response.Success(stubResponse, Download.StreamContent(data: data, inChunksOf: 2000))
// }
// let urlSession = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue.currentQueue())
// let dataTask = urlSession.dataTaskWithRequest(request)
// dataTask.resume()
//
// let mutableData = NSMutableData()
// while mutableData.length < data.length {
// let expectation = expectationWithDescription("testProtocolCanReturnedDataInChunks")
// self.didReceiveDataHandler = { (session: NSURLSession, dataTask: NSURLSessionDataTask, data: NSData) in
// mutableData.appendData(data)
// expectation.fulfill()
// }
// waitForExpectationsWithTimeout(2.0, handler: nil)
// }
// XCTAssertEqual(mutableData, data)
// }
func testDownloadOfAudioFileInChunks() {
let request = NSURLRequest(URL: NSURL(string: "https://fuller.li/")!)
let path = NSBundle(forClass: self.classForCoder).pathForResource("TestAudio", ofType: "m4a")
let data = NSData(contentsOfFile: path!)!

let stubResponse = NSHTTPURLResponse(URL: request.URL!, statusCode: 200, HTTPVersion: "1.1", headerFields: ["Content-Length" : String(data.length)])!

MockingjayProtocol.addStub({ (requestedRequest) -> (Bool) in
return true
}) { (request) -> (Response) in
return Response.Success(stubResponse, Download.StreamContent(data: data, inChunksOf: 2000))
}
let urlSession = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue.currentQueue())
let dataTask = urlSession.dataTaskWithRequest(request)
dataTask.resume()

let mutableData = NSMutableData()
while mutableData.length < data.length {
let expectation = expectationWithDescription("testProtocolCanReturnedDataInChunks")
self.didReceiveDataHandler = { (session: NSURLSession, dataTask: NSURLSessionDataTask, data: NSData) in
mutableData.appendData(data)
expectation.fulfill()
}
waitForExpectationsWithTimeout(2.0, handler: nil)
}
XCTAssertEqual(mutableData, data)
}

// func testByteRanges() {
// let length = 100000
// let request = NSMutableURLRequest(URL: NSURL(string: "https://fuller.li/")!)
// request.addValue("bytes=50000-149999", forHTTPHeaderField: "Range")
// let path = NSBundle(forClass: self.classForCoder).pathForResource("TestAudio", ofType: "m4a")
// let data = NSData(contentsOfFile: path!)!
//
// let stubResponse = NSHTTPURLResponse(URL: request.URL!, statusCode: 200, HTTPVersion: "1.1", headerFields: ["Content-Length" : String(length)])!
// MockingjayProtocol.addStub({ (requestedRequest) -> (Bool) in
// return true
// }) { (request) -> (Response) in
// return Response.Success(stubResponse, .StreamContent(data: data, inChunksOf: 2000))
// }
//
// let urlSession = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue.currentQueue())
// let dataTask = urlSession.dataTaskWithRequest(request)
// dataTask.resume()
//
// let mutableData = NSMutableData()
// while mutableData.length < length {
// let expectation = expectationWithDescription("testProtocolCanReturnedDataInChunks")
// self.didReceiveDataHandler = { (session: NSURLSession, dataTask: NSURLSessionDataTask, data: NSData) in
// mutableData.appendData(data)
// expectation.fulfill()
// }
// waitForExpectationsWithTimeout(2.0, handler: nil)
// }
// XCTAssertEqual(mutableData, data.subdataWithRange(NSMakeRange(50000, length)))
// }
func testByteRanges() {
let length = 100000
let request = NSMutableURLRequest(URL: NSURL(string: "https://fuller.li/")!)
request.addValue("bytes=50000-149999", forHTTPHeaderField: "Range")
let path = NSBundle(forClass: self.classForCoder).pathForResource("TestAudio", ofType: "m4a")
let data = NSData(contentsOfFile: path!)!

let stubResponse = NSHTTPURLResponse(URL: request.URL!, statusCode: 200, HTTPVersion: "1.1", headerFields: ["Content-Length" : String(length)])!
MockingjayProtocol.addStub({ (requestedRequest) -> (Bool) in
return true
}) { (request) -> (Response) in
return Response.Success(stubResponse, .StreamContent(data: data, inChunksOf: 2000))
}

let urlSession = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue.currentQueue())
let dataTask = urlSession.dataTaskWithRequest(request)
dataTask.resume()

let mutableData = NSMutableData()
while mutableData.length < length {
let expectation = expectationWithDescription("testProtocolCanReturnedDataInChunks")
self.didReceiveDataHandler = { (session: NSURLSession, dataTask: NSURLSessionDataTask, data: NSData) in
mutableData.appendData(data)
expectation.fulfill()
}
waitForExpectationsWithTimeout(2.0, handler: nil)
}
XCTAssertEqual(mutableData, data.subdataWithRange(NSMakeRange(50000, length)))
}

// MARK: NSURLSessionDataDelegate
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
Expand Down
6 changes: 3 additions & 3 deletions MockingjayTests/MockingjayProtocolTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ class MockingjayProtocolTests : XCTestCase {
MockingjayProtocol.addStub({ (requestedRequest) -> (Bool) in
return true
}) { (request) -> (Response) in
return Response.Success(stubResponse, stubData)
return Response.Success(stubResponse, .Content(stubData))
}

var response:NSURLResponse?
Expand All @@ -89,13 +89,13 @@ class MockingjayProtocolTests : XCTestCase {
MockingjayProtocol.addStub({ (requestedRequest) -> (Bool) in
return true
}) { (request) -> (Response) in
return Response.Success(stubResponse, stub1Data)
return Response.Success(stubResponse, .Content(stub1Data))
}

MockingjayProtocol.addStub({ (requestedRequest) -> (Bool) in
return true
}) { (request) -> (Response) in
return Response.Success(stubResponse, stub2Data)
return Response.Success(stubResponse, .Content(stub2Data))
}

var response:NSURLResponse?
Expand Down

0 comments on commit 2661dd9

Please sign in to comment.