Machx / MockNetworking

Apply URLProtocol to XCTests for Mock Networking API's

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Review why 2 responses coming back in http response test weren't equal

Machx opened this issue · comments

In the test

func testHTTPResponse() throws {
		let url = try XCTUnwrap(URL(string: "https://wwww.apple.com"))
		let response = try XCTUnwrap(HTTPURLResponse(url: url,
									   statusCode: 200,
									   httpVersion: HTTPURLResponse.HTTP_1_1,
									   headerFields: ["thing180":"thing2"]))
		
		MockURLProtocol.register(response: response, for: url)
		defer {
			MockURLProtocol.unregister()
		}
		
		var receivedResponse: URLResponse?
		let expectation = XCTestExpectation()
		URLSession.sessionWith(.ephemeral).downloadTask(with: url) { (url, response, error) in
			receivedResponse = response
			expectation.fulfill()
		}.resume()
		
		wait(for: [expectation], timeout: 5.0)
		
		XCTAssertNotNil(receivedResponse)
		guard let receivedHTTPResponse = receivedResponse as? HTTPURLResponse else {
			XCTFail("Could not convert Response to HTTPURLResponse type")
			return
		}
		XCTAssertEqual(response.url, receivedHTTPResponse.url)
		XCTAssertEqual(response.statusCode, receivedHTTPResponse.statusCode)
		XCTAssertEqual(response.allStringHTTPHeaders(), receivedHTTPResponse.allStringHTTPHeaders())
	}

if you straight ask for the 2 http responses being equal, you will get a negative response back. I suspect that the 2nd response (having gone through URLProtocol) has more fields in it than the one we supplied it to begin with. Should quickly evaluate this and see if a better equality method can be made for the unit test.

Seems at least the mime type is responsible for this

(lldb) po response.mimeType == receivedHTTPResponse.mimeType
false

(lldb) po response.mimeType
nil

(lldb) po receivedResponse?.mimeType
▿ Optional<String>
  - some : "text/plain"

it is part of the equal func

private func isEqual(to other: URLResponse) -> Bool {
        if self === other {
            return true
        }

        return self.url == other.url &&
                self.expectedContentLength == other.expectedContentLength &&
                self.mimeType == other.mimeType &&
                self.textEncodingName == other.textEncodingName
    }

Since the cause of this has been discovered I am going to close this issue. I've opened #20 to address the existing equal implementation and make a better one. When that issue is closed, then this issue will be completely addressed one way or another.