Author: Nikolaus Rath <Nikolaus@rath.org>
Forwarded: not-needed
Last-Update: 2014-11-14
Description: Fix test skip conditions

This patch ensures that tests requiring a hardcoded server to
respond with a 200 status are properly skipped if the remote
server returns a redirect instead.

--- a/test/test_examples.py
+++ b/test/test_examples.py
@@ -18,7 +18,8 @@
 import os
 import sys
 import pytest
-from urllib.request import build_opener, ProxyHandler, URLError
+from urllib.request import (build_opener, ProxyHandler, URLError, HTTPRedirectHandler,
+                            HTTPError)
 try:
     import asyncio
 except ImportError:
@@ -26,12 +27,24 @@
 
 basename = os.path.join(os.path.dirname(__file__), '..')
 
+# Yes, this is the way to avoid following redirects with urllib,
+# and it is indeed absolutely terrible. But dependending on the
+# requests module just to run this simple test does not (yet)
+# seem appropriate either.
+class HTTPNoRedirectHandler(HTTPRedirectHandler):
+    def http_error_302(self, url, fp, errcode, errmsg, headers):
+        fp.close()
+        raise HTTPError(url, errcode, errmsg, headers, None)
+
+    http_error_301 = http_error_303 = http_error_307 = http_error_302
+
 def check_url(url):
     '''Skip test if *url* cannot be reached'''
 
-    # Examples ignore proxy settings, so should urllib
-    proxy_handler = ProxyHandler({})
-    opener = build_opener(proxy_handler)
+    # To avoid using proxies (as the examples do), we need to add a proxy
+    # handler, but pass an empty dictionary for the proxy settings. urllib
+    # again...
+    opener = build_opener(ProxyHandler({}), HTTPNoRedirectHandler())
 
     try:
         resp = opener.open(url, None, 15)
