Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to purposely create a malformed URL in Swift

I have the following Swift extension on NSURL

public extension NSURL {

    func getQueryItemValueForKey(key: String) -> String? {
        guard let components = NSURLComponents(URL: self, resolvingAgainstBaseURL: false) else {
            return nil
        }

        guard let queryItems = components.queryItems else { return nil }
        return queryItems.filter {
            $0.name == key
            }.first?.value
    }

}

I am writing unit tests for it but I am unable to get 100% code coverage as I don't seem to be able to get NSURLComponents(URL: self, resolvingAgainstBaseURL: false) to return nil. From what I understand, this requires a malformed URL but I am struggling to create one.

I have tried:

  • let url = NSURL(string: "")
  • let url = NSURL(string: "http://www.example")
  • let url = NSURL(string: "http://www.exam ple.com")
  • let url = NSURL(string: "http://www.example.com/?param1=äëīòú")

And some others that I lost track of. I know this is probably something blatantly obvious but i'm lost at the moment. So, how do I create a malformed URL in Swift?

like image 508
Hodson Avatar asked May 20 '16 11:05

Hodson


People also ask

How do I create a malformed URL?

let url = NSURL(string: "http://www.example") let url = NSURL(string: "http://www.exam ple.com") let url = NSURL(string: "http://www.example.com/?param1=äëīòú")

What is a malformed URL?

This violation indicates that a request that was not created by a browser, and does not comply with HTTP standards, has been sent to the server. This may be the result of of an HTTP request being manually crafted or of a client tunneling other protocols over HTTP.


1 Answers

As found in my research, you can produce a url that is malformed for NSURLComponents but not for NSURL by using negative port number (probably there are more cases but not sure):

let example = "http://example.com:-80/"
let url = NSURL(string: example)
print("url:\(url)") //prints out url:Optional(http://example.com:-80/)
if let url = url {
    let comps = NSURLComponents(URL: url, resolvingAgainstBaseURL: false)
    print("comps:\(comps)") //prints out comps:nil
}
like image 128
invisible_hand Avatar answered Oct 20 '22 15:10

invisible_hand