Home > Mobile >  Create HTTPCookieStorage for testing
Create HTTPCookieStorage for testing

Time:10-01

I'm attempting to Unit test some of my network code. I'm trying to write a test that verifies that HTTPCookies from a given HTTPCookieStorage is actually added to URLRequest headers.

So, I need a HTTPCookieStorage with a HTTPCookie inside. I attempt to create it like this:

let cookie = HTTPCookie(properties: [
    .name: "name",
    .value: "value",
    .domain: ".example.com",
    .path: "/",
    .expires: Date(timeIntervalSinceNow: 10),
    .comment: "Test cookie"
])!

let url = URL(string: "www.example.com")!

let cookieStorage = HTTPCookieStorage()
cookieStorage.cookieAcceptPolicy = .always
cookieStorage.setCookies([someCookie], for: url, mainDocumentURL: nil)

But at this point cookieStorage is still empty.. I've also tried with:

cookieStorage.setCookie(cookie)

which also ignore the cookie..

Why is the cookie ignored, and how can I create a HTTPCookieStorage with predictable cookies for unit testing?

CodePudding user response:

I'd suggest using the shared instance of the HTTPCookieStorage. Also, if you use setCookie(_:) it should work:

let cookie = HTTPCookie(properties: [
    .name: "name",
    .value: "value",
    .domain: ".example.com",
    .path: "/",
    .expires: Date(timeIntervalSinceNow: 10),
    .comment: "Test cookie"
])!

let cs = HTTPCookieStorage.shared
cs.setCookie(cookie)
print(cs.cookies!)
/*
 [<NSHTTPCookie
     version:0
     name:name
     value:value
     expiresDate:'2021-09-30 10:08:16  0000'
     created:'2021-09-30 10:08:06  0000'
     sessionOnly:FALSE
     domain:.example.com
     partition:none
     sameSite:none
     path:/
     isSecure:FALSE
  path:"/" isSecure:FALSE    comment:'Test cookie'
 >]
 */

CodePudding user response:

/**
    @class NSHTTPCookieStorage 
    @discussion NSHTTPCookieStorage implements a singleton object (shared
    instance) which manages the shared cookie store.  It has methods
    to allow clients to set and remove cookies, and get the current
    set of cookies.  It also has convenience methods to parse and
    generate cookie-related HTTP header fields.
*/

Use HTTPCookieStorage.shared or HTTPCookieStorage.sharedCookieStorage(forGroupContainerIdentifier identifier: String)

  • Related