Search for assertURLEquals

During unittest, I would like to compare the generated URL with the static one defined in the test. For this comparison, it would be nice to have TestCase.assertURLEqual or the like, which would allow you to compare two URLs in a string format and result in True if all components of the request and fragment were present and were equal, but not necessarily in order.

Before I start implementing this myself, does this function already exist?

+4
source share
2 answers

I don’t know if there is something built-in, but you can just use urlparse and check yourself for query parameters, since the order is taken into account by default.

 >>> import urlparse >>> url1 = 'http://google.com/?a=1&b=2' >>> url2 = 'http://google.com/?b=2&a=1' >>> # parse url ignoring query params order ... def parse_url(url): ... u = urlparse.urlparse(url) ... q = u.query ... u = urlparse.urlparse(u.geturl().replace(q, '')) ... return (u, urlparse.parse_qs(q)) ... >>> parse_url(url1) (ParseResult(scheme='http', netloc='google.com', path='/', params='', query='', fragment=''), {'a': ['1'], 'b': ['2']}) >>> def assert_url_equals(url1, url2): ... return parse_url(url1) == parse_url(url1) ... >>> assert_url_equals(url1, url2) True 
+1
source

Well, this is not so difficult to implement with urlparse in the standard library:

 from urlparse import urlparse, parse_qs def urlEq(url1, url2): pr1 = urlparse(url1) pr2 = urlparse(url2) return (pr1.scheme == pr2.scheme and pr1.netloc == pr2.netloc and pr1.path == pr2.path and parse_qs(pr1.query) == parse_qs(pr2.query)) # Prints True print urlEq("http://foo.com/blah?bar=1&foo=2", "http://foo.com/blah?foo=2&bar=1") # Prints False print urlEq("http://foo.com/blah?bar=1&foo=2", "http://foo.com/blah?foo=4&bar=1") 

Basically, compare everything that is parsed from the URL, but use parse_qs to get the dictionary from the query string.

+1
source

Source: https://habr.com/ru/post/1442171/


All Articles