You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
import Foundation
classMockURLProtocol:URLProtocol{staticvarrequestHandler:((URLRequest)throws->(HTTPURLResponse,Data?))?overrideclassfunc canInit(with request:URLRequest)->Bool{
// Handle all types of requests
returntrue}overrideclassfunc canonicalRequest(for request:URLRequest)->URLRequest{
// Return the original request
return request
}overridefunc startLoading(){guardlet handler =MockURLProtocol.requestHandler else{fatalError("Handler is not set.")}do{let(response, data)=tryhandler(request)
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy:.notAllowed)iflet data = data {
client?.urlProtocol(self, didLoad: data)}
client?.urlProtocolDidFinishLoading(self)}catch{
client?.urlProtocol(self, didFailWithError: error)}}overridefunc stopLoading(){
// Required method; nothing to clean up.
}}import XCTest
@testableimport NetTime
finalclassUnitTests:XCTestCase{
/**
* Tests that `Date.updateTime` handles missing `Date` header gracefully.
*/
func testUpdateTimeWithMissingDateHeader(){
// Create a mock URL session that returns a response without the `Date` header
leturl=URL(string:"https://example.com")!
letconfiguration=URLSessionConfiguration.ephemeral
configuration.protocolClasses =[MockURLProtocol.self]letsession=URLSession(configuration: configuration)MockURLProtocol.requestHandler ={ request inletresponse=HTTPURLResponse(
url: request.url!,
statusCode:200,
httpVersion:nil,
headerFields:[:])!
return(response,nil)}letexpectation=self.expectation(description:"Completion handler invoked")Date.updateTime(with: url, session: session){ result inif case .failure(let error)= result {XCTAssertEqual(error,.missingDateHeader)}else{XCTFail("Expected failure due to missing Date header")}
expectation.fulfill()}waitForExpectations(timeout:5, handler:nil)}}import XCTest
@testableimport NetTime
finalclassUnitTests:XCTestCase{
/**
* Tests `Date.updateTime` with a custom date formatter.
*/
func testUpdateTimeWithCustomDateFormatter(){
// Assume that we have modified the Date.updateTime method to accept a custom formatter
letcustomFormatter=DateFormatter()
customFormatter.dateFormat ="yyyy-MM-dd'T'HH:mm:ssZ"
customFormatter.locale =Locale(identifier:"en_US_POSIX")
customFormatter.timeZone =TimeZone(secondsFromGMT:0)
// Create a mock URL session that returns a date in custom format
leturl=URL(string:"https://example.com")!
letconfiguration=URLSessionConfiguration.ephemeral
configuration.protocolClasses =[MockURLProtocol.self]letsession=URLSession(configuration: configuration)MockURLProtocol.requestHandler ={ request inletheaders=["Date":"2025-01-12T17:44:00+0000"]letresponse=HTTPURLResponse(
url: request.url!,
statusCode:200,
httpVersion:nil,
headerFields: headers
)!
return(response,nil)}letexpectation=self.expectation(description:"Completion handler invoked")Date.updateTime(with: url, session: session, formatter: customFormatter){ result inif case .success = result {
// Verify that timeGap is set correctly
XCTAssertNotEqual(Date.timeGap,0,"Expected timeGap to be updated")}else{XCTFail("Expected success when using custom date formatter")}
expectation.fulfill()}waitForExpectations(timeout:5, handler:nil)}}import XCTest
@testableimport NetTime
finalclassUnitTests:XCTestCase{
/**
* Tests that `Date.updateTime` handles network failures.
*/
func testUpdateTimeWithNetworkFailure(){
// Create a mock URL session that simulates a network error
leturl=URL(string:"https://example.com")!
letconfiguration=URLSessionConfiguration.ephemeral
configuration.protocolClasses =[MockURLProtocol.self]letsession=URLSession(configuration: configuration)MockURLProtocol.requestHandler ={ request inthrowNSError(domain: NSURLErrorDomain, code: NSURLErrorNotConnectedToInternet, userInfo:nil)}letexpectation=self.expectation(description:"Completion handler invoked")Date.updateTime(with: url, session: session){ result inif case .failure(let error)= result {XCTAssertEqual(error,.networkError(NSError(domain: NSURLErrorDomain, code: NSURLErrorNotConnectedToInternet, userInfo:nil)))}else{XCTFail("Expected failure due to network error")}
expectation.fulfill()}waitForExpectations(timeout:5, handler:nil)}}
The text was updated successfully, but these errors were encountered:
The text was updated successfully, but these errors were encountered: