'Test HTTP Basic auth'

def test_basic_auth(self):

    r = router(prefer_basic_auth=True)
    with TestServer(r.dispatch) as server:
        r.auth_controller.log = server.log
        conn = server.connect()
        conn.request(u'GET', u'/open')
        r = conn.getresponse()
        self.ae(r.status, httplib.OK)
        self.ae(r.read(), 'open')
        conn.request(u'GET', u'/closed')
        r = conn.getresponse()
        self.ae(r.status, httplib.UNAUTHORIZED)
        self.ae(r.getheader(u'WWW-Authenticate'), ('Basic    realm="%s"' % bytes(REALM)))
        self.assertFalse(r.read())
        conn.request(u'GET', u'/closed', headers={u'Authorization': ('Basic    ' + base64.standard_b64encode('testuser:testpw'))})
        r = conn.getresponse()
        self.ae(r.read(), 'closed')
        self.ae(r.status, httplib.OK)
        self.ae('closed', urlopen(server, method=u'basic').read())
        self.ae('closed', urlopen(server, un=u'!@#$%^&*()-=_+', pw=u'!@#$%^&*()-=_+', method=u'basic').read())
        def request(un=u'testuser', pw=u'testpw'):
            conn.request(u'GET', u'/closed', headers={u'Authorization': ('Basic    ' + base64.standard_b64encode(bytes((u'%s:%s' % (un, pw)))))})
            r = conn.getresponse()
            return (r.status, r.read())
        warnings = []
        server.loop.log.warn = (lambda *args, **kwargs: warnings.append(u'    '.join(args)))
        self.ae((httplib.OK, 'closed'), request())
        self.ae((httplib.UNAUTHORIZED, ''), request(u'x', u'y'))
        self.ae((httplib.BAD_REQUEST, 'The    username    or    password    was    empty'), request(u'', u''))
        self.ae(1, len(warnings))
        self.ae((httplib.UNAUTHORIZED, ''), request(u'testuser', u'y'))
        self.ae((httplib.BAD_REQUEST, 'The    username    or    password    was    empty'), request(u'testuser', u''))
        self.ae((httplib.BAD_REQUEST, 'The    username    or    password    was    empty'), request(u''))
        self.ae((httplib.UNAUTHORIZED, ''), request(u'asf', u'testpw'))
