Quellcode durchsuchen

Added tests around all response serializers raising the code coverage.

Christian Noon vor 10 Jahren
Ursprung
Commit
becb34c8c8

+ 6 - 0
Alamofire.xcodeproj/project.pbxproj

@@ -7,6 +7,8 @@
 	objects = {
 
 /* Begin PBXBuildFile section */
+		4C0B58391B747A4400C0B99C /* ResponseSerializationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C0B58381B747A4400C0B99C /* ResponseSerializationTests.swift */; };
+		4C0B583A1B747A4400C0B99C /* ResponseSerializationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C0B58381B747A4400C0B99C /* ResponseSerializationTests.swift */; };
 		4C0E5BF81B673D3400816CCC /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C0E5BF71B673D3400816CCC /* Result.swift */; };
 		4C0E5BF91B673D3400816CCC /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C0E5BF71B673D3400816CCC /* Result.swift */; };
 		4C1DC8541B68908E00476DE3 /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C1DC8531B68908E00476DE3 /* Error.swift */; };
@@ -131,6 +133,7 @@
 /* End PBXContainerItemProxy section */
 
 /* Begin PBXFileReference section */
+		4C0B58381B747A4400C0B99C /* ResponseSerializationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResponseSerializationTests.swift; sourceTree = "<group>"; };
 		4C0E5BF71B673D3400816CCC /* Result.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Result.swift; sourceTree = "<group>"; };
 		4C1DC8531B68908E00476DE3 /* Error.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Error.swift; sourceTree = "<group>"; };
 		4C23EB421B327C5B0090E0BC /* MultipartFormData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MultipartFormData.swift; sourceTree = "<group>"; };
@@ -244,6 +247,7 @@
 				4C341BB91B1A865A00C1B34D /* CacheTests.swift */,
 				F8111E5B19A9674D0040E7D1 /* DownloadTests.swift */,
 				4C3238E61B3604DB00FE04AE /* MultipartFormDataTests.swift */,
+				4C0B58381B747A4400C0B99C /* ResponseSerializationTests.swift */,
 				4C33A1421B52089C00873DFF /* ServerTrustPolicyTests.swift */,
 				F86AEFE51AE6A282007D9C76 /* TLSEvaluationTests.swift */,
 				F8111E5F19A9674D0040E7D1 /* UploadTests.swift */,
@@ -742,6 +746,7 @@
 				4CA028C51B7466C500C84163 /* ResultTests.swift in Sources */,
 				4CCFA79A1B2BE71600B6F460 /* URLProtocolTests.swift in Sources */,
 				F86AEFE71AE6A312007D9C76 /* TLSEvaluationTests.swift in Sources */,
+				4C0B58391B747A4400C0B99C /* ResponseSerializationTests.swift in Sources */,
 				F8858DDD19A96B4300F55F93 /* RequestTests.swift in Sources */,
 				4C256A531B096C770065714F /* BaseTestCase.swift in Sources */,
 				F8E6024519CB46A800A3E7F1 /* AuthenticationTests.swift in Sources */,
@@ -764,6 +769,7 @@
 				4CA028C61B7466C500C84163 /* ResultTests.swift in Sources */,
 				4CCFA79B1B2BE71600B6F460 /* URLProtocolTests.swift in Sources */,
 				F829C6BE1A7A950600A2CD59 /* ParameterEncodingTests.swift in Sources */,
+				4C0B583A1B747A4400C0B99C /* ResponseSerializationTests.swift in Sources */,
 				F829C6BF1A7A950600A2CD59 /* RequestTests.swift in Sources */,
 				4C256A541B096C770065714F /* BaseTestCase.swift in Sources */,
 				F829C6C01A7A950600A2CD59 /* ManagerTests.swift in Sources */,

+ 12 - 10
Source/ResponseSerialization.swift

@@ -22,7 +22,7 @@
 
 import Foundation
 
-// MARK: - ResponseSerializer
+// MARK: ResponseSerializer
 
 /**
     The type in which all response serializers must conform to in order to serialize a response.
@@ -37,6 +37,8 @@ public protocol ResponseSerializer {
     var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?) -> Result<SerializedObject> { get }
 }
 
+// MARK: -
+
 /**
     A generic `ResponseSerializer` used to serialize a request, response, and data into a serialized object.
 */
@@ -129,7 +131,7 @@ extension Request {
         - returns: A data response serializer.
     */
     public static func dataResponseSerializer() -> GenericResponseSerializer<NSData> {
-        return GenericResponseSerializer { request, response, data in
+        return GenericResponseSerializer { _, _, data in
             guard let validData = data else {
                 let failureReason = "Data could not be serialized. Input data was nil."
                 let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
@@ -170,8 +172,8 @@ extension Request {
         -> GenericResponseSerializer<String>
     {
         return GenericResponseSerializer { _, response, data in
-            guard let validData = data where validData.length > 0 else {
-                let failureReason = "String could not be serialized. Input data was nil or contained zero bytes."
+            guard let validData = data else {
+                let failureReason = "String could not be serialized because input data was nil."
                 let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
                 return .Failure(data, error)
             }
@@ -234,9 +236,9 @@ extension Request {
         options options: NSJSONReadingOptions = .AllowFragments)
         -> GenericResponseSerializer<AnyObject>
     {
-        return GenericResponseSerializer { request, response, data in
-            guard let validData = data where validData.length > 0 else {
-                let failureReason = "JSON could not be serialized. Input data was nil or contained zero bytes."
+        return GenericResponseSerializer { _, _, data in
+            guard let validData = data else {
+                let failureReason = "JSON could not be serialized because input data was nil."
                 let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
                 return .Failure(data, error)
             }
@@ -288,9 +290,9 @@ extension Request {
         options options: NSPropertyListReadOptions = NSPropertyListReadOptions())
         -> GenericResponseSerializer<AnyObject>
     {
-        return GenericResponseSerializer { request, response, data in
-            guard let validData = data where validData.length > 0 else {
-                let failureReason = "Property list could not be serialized. Input data was nil or contained zero bytes."
+        return GenericResponseSerializer { _, _, data in
+            guard let validData = data else {
+                let failureReason = "Property list could not be serialized because input data was nil."
                 let error = Error.errorWithCode(.PropertyListSerializationFailed, failureReason: failureReason)
                 return .Failure(data, error)
             }

+ 363 - 0
Tests/ResponseSerializationTests.swift

@@ -0,0 +1,363 @@
+// ResponseSerializationTests.swift
+//
+// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+import Alamofire
+import Foundation
+import XCTest
+
+class ResponseSerializationTestCase: BaseTestCase {
+
+    // MARK: - Data Response Serializer Tests
+
+    func testThatDataResponseSerializerSucceedsWhenDataIsNotNil() {
+        // Given
+        let serializer = Request.dataResponseSerializer()
+        let data = "data".dataUsingEncoding(NSUTF8StringEncoding)!
+
+        // When
+        let result = serializer.serializeResponse(nil, nil, data)
+
+        // Then
+        XCTAssertTrue(result.isSuccess, "result is success should be true")
+        XCTAssertNotNil(result.value, "result value should not be nil")
+        XCTAssertNil(result.data, "result data should be nil")
+        XCTAssertNil(result.error, "result error should be nil")
+    }
+
+    func testThatDataResponseSerializerFailsWhenDataIsNil() {
+        // Given
+        let serializer = Request.dataResponseSerializer()
+
+        // When
+        let result = serializer.serializeResponse(nil, nil, nil)
+
+        // Then
+        XCTAssertTrue(result.isFailure, "result is failure should be true")
+        XCTAssertNil(result.value, "result value should be nil")
+        XCTAssertNil(result.data, "result data should be nil")
+        XCTAssertNotNil(result.error, "result error should not be nil")
+
+        if let error = result.error {
+            XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
+            XCTAssertEqual(error.code, Error.Code.DataSerializationFailed.rawValue, "error code should match expected value")
+        } else {
+            XCTFail("error should not be nil")
+        }
+    }
+
+    // MARK: - String Response Serializer Tests
+
+    func testThatStringResponseSerializerFailsWhenDataIsNil() {
+        // Given
+        let serializer = Request.stringResponseSerializer()
+
+        // When
+        let result = serializer.serializeResponse(nil, nil, nil)
+
+        // Then
+        XCTAssertTrue(result.isFailure, "result is failure should be true")
+        XCTAssertNil(result.value, "result value should be nil")
+        XCTAssertNil(result.data, "result data should be nil")
+        XCTAssertNotNil(result.error, "result error should not be nil")
+
+        if let error = result.error {
+            XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
+            XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value")
+        } else {
+            XCTFail("error should not be nil")
+        }
+    }
+
+    func testThatStringResponseSerializerSucceedsWhenDataIsEmpty() {
+        // Given
+        let serializer = Request.stringResponseSerializer()
+
+        // When
+        let result = serializer.serializeResponse(nil, nil, NSData())
+
+        // Then
+        XCTAssertTrue(result.isSuccess, "result is success should be true")
+        XCTAssertNotNil(result.value, "result value should not be nil")
+        XCTAssertNil(result.data, "result data should be nil")
+        XCTAssertNil(result.error, "result error should be nil")
+    }
+
+    func testThatStringResponseSerializerSucceedsWithUTF8DataAndNoProvidedEncoding() {
+        let serializer = Request.stringResponseSerializer()
+        let data = "data".dataUsingEncoding(NSUTF8StringEncoding)!
+
+        // When
+        let result = serializer.serializeResponse(nil, nil, data)
+
+        // Then
+        XCTAssertTrue(result.isSuccess, "result is success should be true")
+        XCTAssertNotNil(result.value, "result value should not be nil")
+        XCTAssertNil(result.data, "result data should be nil")
+        XCTAssertNil(result.error, "result error should be nil")
+    }
+
+    func testThatStringResponseSerializerSucceedsWithUTF8DataAndUTF8ProvidedEncoding() {
+        let serializer = Request.stringResponseSerializer(encoding: NSUTF8StringEncoding)
+        let data = "data".dataUsingEncoding(NSUTF8StringEncoding)!
+
+        // When
+        let result = serializer.serializeResponse(nil, nil, data)
+
+        // Then
+        XCTAssertTrue(result.isSuccess, "result is success should be true")
+        XCTAssertNotNil(result.value, "result value should not be nil")
+        XCTAssertNil(result.data, "result data should be nil")
+        XCTAssertNil(result.error, "result error should be nil")
+    }
+
+    func testThatStringResponseSerializerSucceedsWithUTF8DataUsingResponseTextEncodingName() {
+        let serializer = Request.stringResponseSerializer()
+        let data = "data".dataUsingEncoding(NSUTF8StringEncoding)!
+        let response = NSHTTPURLResponse(
+            URL: NSURL(string: "https://httpbin.org/get")!,
+            statusCode: 200,
+            HTTPVersion: "HTTP/1.1",
+            headerFields: ["Content-Type": "image/jpeg; charset=utf-8"]
+        )
+
+        // When
+        let result = serializer.serializeResponse(nil, response, data)
+
+        // Then
+        XCTAssertTrue(result.isSuccess, "result is success should be true")
+        XCTAssertNotNil(result.value, "result value should not be nil")
+        XCTAssertNil(result.data, "result data should be nil")
+        XCTAssertNil(result.error, "result error should be nil")
+    }
+
+    func testThatStringResponseSerializerFailsWithUTF32DataAndUTF8ProvidedEncoding() {
+        // Given
+        let serializer = Request.stringResponseSerializer(encoding: NSUTF8StringEncoding)
+        let data = "random data".dataUsingEncoding(NSUTF32StringEncoding)!
+
+        // When
+        let result = serializer.serializeResponse(nil, nil, data)
+
+        // Then
+        XCTAssertTrue(result.isFailure, "result is failure should be true")
+        XCTAssertNil(result.value, "result value should be nil")
+        XCTAssertNotNil(result.data, "result data should not be nil")
+        XCTAssertNotNil(result.error, "result error should not be nil")
+
+        if let error = result.error {
+            XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
+            XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value")
+        } else {
+            XCTFail("error should not be nil")
+        }
+    }
+
+    func testThatStringResponseSerializerFailsWithUTF32DataAndUTF8ResponseEncoding() {
+        // Given
+        let serializer = Request.stringResponseSerializer()
+        let data = "random data".dataUsingEncoding(NSUTF32StringEncoding)!
+        let response = NSHTTPURLResponse(
+            URL: NSURL(string: "https://httpbin.org/get")!,
+            statusCode: 200,
+            HTTPVersion: "HTTP/1.1",
+            headerFields: ["Content-Type": "image/jpeg; charset=utf-8"]
+        )
+
+        // When
+        let result = serializer.serializeResponse(nil, response, data)
+
+        // Then
+        XCTAssertTrue(result.isFailure, "result is failure should be true")
+        XCTAssertNil(result.value, "result value should be nil")
+        XCTAssertNotNil(result.data, "result data should not be nil")
+        XCTAssertNotNil(result.error, "result error should not be nil")
+
+        if let error = result.error {
+            XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
+            XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value")
+        } else {
+            XCTFail("error should not be nil")
+        }
+    }
+
+    // MARK: - JSON Response Serializer Tests
+
+    func testThatJSONResponseSerializerFailsWhenDataIsNil() {
+        // Given
+        let serializer = Request.JSONResponseSerializer()
+
+        // When
+        let result = serializer.serializeResponse(nil, nil, nil)
+
+        // Then
+        XCTAssertTrue(result.isFailure, "result is failure should be true")
+        XCTAssertNil(result.value, "result value should be nil")
+        XCTAssertNil(result.data, "result data should be nil")
+        XCTAssertNotNil(result.error, "result error should not be nil")
+
+        if let error = result.error {
+            XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
+            XCTAssertEqual(error.code, Error.Code.JSONSerializationFailed.rawValue, "error code should match expected value")
+        } else {
+            XCTFail("error should not be nil")
+        }
+    }
+
+    func testThatJSONResponseSerializerFailsWhenDataIsEmpty() {
+        // Given
+        let serializer = Request.JSONResponseSerializer()
+
+        // When
+        let result = serializer.serializeResponse(nil, nil, NSData())
+
+        // Then
+        XCTAssertTrue(result.isFailure, "result is failure should be true")
+        XCTAssertNil(result.value, "result value should be nil")
+        XCTAssertNotNil(result.data, "result data should not be nil")
+        XCTAssertNotNil(result.error, "result error should not be nil")
+
+        if let error = result.error {
+            XCTAssertEqual(error.domain, NSCocoaErrorDomain, "error domain should match expected value")
+            XCTAssertEqual(error.code, 3840, "error code should match expected value")
+        } else {
+            XCTFail("error should not be nil")
+        }
+    }
+
+    func testThatJSONResponseSerializerSucceedsWhenDataIsValidJSON() {
+        // Given
+        let serializer = Request.stringResponseSerializer()
+        let data = "{\"json\": true}".dataUsingEncoding(NSUTF8StringEncoding)!
+
+        // When
+        let result = serializer.serializeResponse(nil, nil, data)
+
+        // Then
+        XCTAssertTrue(result.isSuccess, "result is success should be true")
+        XCTAssertNotNil(result.value, "result value should not be nil")
+        XCTAssertNil(result.data, "result data should be nil")
+        XCTAssertNil(result.error, "result error should be nil")
+    }
+
+    func testThatJSONResponseSerializerFailsWhenDataIsInvalidJSON() {
+        // Given
+        let serializer = Request.JSONResponseSerializer()
+        let data = "definitely not valid json".dataUsingEncoding(NSUTF8StringEncoding)!
+
+        // When
+        let result = serializer.serializeResponse(nil, nil, data)
+
+        // Then
+        XCTAssertTrue(result.isFailure, "result is failure should be true")
+        XCTAssertNil(result.value, "result value should be nil")
+        XCTAssertNotNil(result.data, "result data should not be nil")
+        XCTAssertNotNil(result.error, "result error should not be nil")
+
+        if let error = result.error {
+            XCTAssertEqual(error.domain, NSCocoaErrorDomain, "error domain should match expected value")
+            XCTAssertEqual(error.code, 3840, "error code should match expected value")
+        } else {
+            XCTFail("error should not be nil")
+        }
+    }
+
+    // MARK: - Property List Response Serializer Tests
+
+    func testThatPropertyListResponseSerializerFailsWhenDataIsNil() {
+        // Given
+        let serializer = Request.propertyListResponseSerializer()
+
+        // When
+        let result = serializer.serializeResponse(nil, nil, nil)
+
+        // Then
+        XCTAssertTrue(result.isFailure, "result is failure should be true")
+        XCTAssertNil(result.value, "result value should be nil")
+        XCTAssertNil(result.data, "result data should be nil")
+        XCTAssertNotNil(result.error, "result error should not be nil")
+
+        if let error = result.error {
+            XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
+            XCTAssertEqual(error.code, Error.Code.PropertyListSerializationFailed.rawValue, "error code should match expected value")
+        } else {
+            XCTFail("error should not be nil")
+        }
+    }
+
+    func testThatPropertyListResponseSerializerFailsWhenDataIsEmpty() {
+        // Given
+        let serializer = Request.propertyListResponseSerializer()
+
+        // When
+        let result = serializer.serializeResponse(nil, nil, NSData())
+
+        // Then
+        XCTAssertTrue(result.isFailure, "result is failure should be true")
+        XCTAssertNil(result.value, "result value should be nil")
+        XCTAssertNotNil(result.data, "result data should not be nil")
+        XCTAssertNotNil(result.error, "result error should not be nil")
+
+        if let error = result.error {
+            XCTAssertEqual(error.domain, NSCocoaErrorDomain, "error domain should match expected value")
+            XCTAssertEqual(error.code, 3840, "error code should match expected value")
+        } else {
+            XCTFail("error should not be nil")
+        }
+    }
+
+    func testThatPropertyListResponseSerializerSucceedsWhenDataIsValidPropertyListData() {
+        // Given
+        let serializer = Request.propertyListResponseSerializer()
+        let data = NSKeyedArchiver.archivedDataWithRootObject(["foo": "bar"])
+
+        // When
+        let result = serializer.serializeResponse(nil, nil, data)
+
+        // Then
+        XCTAssertTrue(result.isSuccess, "result is success should be true")
+        XCTAssertNotNil(result.value, "result value should not be nil")
+        XCTAssertNil(result.data, "result data should be nil")
+        XCTAssertNil(result.error, "result error should be nil")
+    }
+
+    func testThatPropertyListResponseSerializerFailsWhenDataIsInvalidPropertyListData() {
+        // Given
+        let serializer = Request.JSONResponseSerializer()
+        let data = "definitely not valid plist data".dataUsingEncoding(NSUTF8StringEncoding)!
+
+        // When
+        let result = serializer.serializeResponse(nil, nil, data)
+
+        // Then
+        XCTAssertTrue(result.isFailure, "result is failure should be true")
+        XCTAssertNil(result.value, "result value should be nil")
+        XCTAssertNotNil(result.data, "result data should not be nil")
+        XCTAssertNotNil(result.error, "result error should not be nil")
+
+        if let error = result.error {
+            XCTAssertEqual(error.domain, NSCocoaErrorDomain, "error domain should match expected value")
+            XCTAssertEqual(error.code, 3840, "error code should match expected value")
+        } else {
+            XCTFail("error should not be nil")
+        }
+    }
+}