Commits

Lukas Linhart committed 95208db

Hackily converted tests to use django-sane-testing

Comments (0)

Files changed (15)

djangohttpdigest/tests/__init__.py

-from test_simple_digest import *
-from test_digest import *

djangohttpdigest/tests/test_authentication.py

Empty file removed.

djangohttpdigest/tests/test_digest.py

-import re
-import urllib2
-
-from django.test import TestCase
-from django.http import HttpRequest
-from django.core.handlers.wsgi import WSGIRequest
-
-from djangohttpdigest.digest import Digestor, parse_authorization_header
-
-class TestDigestor(TestCase):
-    """ Test digestor, our wrapping class for handling digests """
-    
-    def setUp(self):
-        self.digestor = Digestor(realm='testrealm', method='GET', path='/testapi/simpleprotected/')
-        self.auth_string = 'Digest username="rpgpedia", realm="extproject", nonce="1cc6ab869fca869c2c085d78a3729a66", uri="/extproject/project/fc8afe5e-da35-4fe2-a991-7b26c829cde5/user/rpgpedia/salt/", response="69ead146a246cd51bbd076244d2e455b", opaque="ToDoMoveThisToSettings", algorithm="MD5", qop=auth, nc=00000001, cnonce="a84f8e6cfcd50a75"'
-    
-    def _assertKeyEquals(self, key, value):
-        parsed_header = self.digestor.parse_authorization_header(self.auth_string)
-        self.assertTrue(parsed_header.has_key(key))
-        self.assertEquals(value, parsed_header[key])
-    
-    def test_get_digest_challenge(self):
-        challenge = self.digestor.get_digest_challenge()
-        
-        # check our challenge is compatible with urllib2's resolving
-        if re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', re.I).match(challenge):
-            pass
-        else:
-            self.fail("Challenge %s does not match urllib2's regexp" % challenge)
-    
-    def test_proper_parsing_username(self):
-        self._assertKeyEquals('username', 'rpgpedia')
-
-    def test_proper_parsing_realm(self):
-        self._assertKeyEquals('realm', 'extproject')
-
-    def test_proper_parsing_nonce(self):
-        self._assertKeyEquals('nonce', '1cc6ab869fca869c2c085d78a3729a66')
-
-    def test_proper_parsing_uri(self):
-        self._assertKeyEquals('uri', '/extproject/project/fc8afe5e-da35-4fe2-a991-7b26c829cde5/user/rpgpedia/salt/')
-
-    def test_proper_parsing_response(self):
-        self._assertKeyEquals('response', '69ead146a246cd51bbd076244d2e455b')
-
-    def test_proper_parsing_opaque(self):
-        self._assertKeyEquals('opaque', 'ToDoMoveThisToSettings')
-
-    def test_proper_parsing_algorithm(self):
-        self._assertKeyEquals('algorithm', 'MD5')
-
-    def test_proper_parsing_qop(self):
-        self._assertKeyEquals('qop', 'auth')
-
-    def test_proper_parsing_nc(self):
-        self._assertKeyEquals('nc', '00000001')
-
-    def test_proper_parsing_cnonce(self):
-        self._assertKeyEquals('cnonce', 'a84f8e6cfcd50a75')
-
-    def test_bad_parsing_missing_digest(self):
-        auth_string = 'username="rpgpedia", realm="extproject", nonce="1cc6ab869fca869c2c085d78a3729a66", uri="/extproject/project/fc8afe5e-da35-4fe2-a991-7b26c829cde5/user/rpgpedia/salt/", response="69ead146a246cd51bbd076244d2e455b", opaque="ToDoMoveThisToSettings", algorithm="MD5", qop=auth, nc=00000001, cnonce="a84f8e6cfcd50a75"'
-        self.assertRaises(ValueError, lambda:self.digestor.parse_authorization_header(auth_string))
-    
-class TestSimpleDigest(TestCase):
-    
-    environment = {
-        'HTTP_COOKIE':       '',
-        'PATH_INFO':         '/',
-        'QUERY_STRING':      '',
-        'REQUEST_METHOD':    'GET',
-        'SCRIPT_NAME':       '',
-        'SERVER_NAME':       'testserver',
-        'SERVER_PORT':       '80',
-        'SERVER_PROTOCOL':   'HTTP/1.1',
-    }
-    
-    def test_parse_authorization_header(self):
-        """ Authorization header parsing, for various inputs """
-        self.assertRaises(ValueError, lambda:parse_authorization_header(''))

djangohttpdigest/tests/test_simple_digest.py

-import urllib2
-import logging
-from md5 import md5
-from django.test import TestCase
-
-from djangohttpdigest.client import HttpDigestClient
-
-from module_test import LiveServerTestCase
-
-class TestSimpleDigest(LiveServerTestCase):
-    path = '/testapi/simpleprotected/'
-    url = 'http://localhost:8000'
-    
-    def test_simple_autentization(self):
-        """ Test view protected by simple realm-username-password decorator """
-        
-        
-        # first test that using normal client, path is protected and returns 401
-        response = self.client.get(self.path)
-        self.assertEquals(401, response.status_code)
-        
-        # and that challenge is returned
-        assert len(response['www-authenticate']) > 0
-        assert 'nonce' in response['www-authenticate']
-        
-        #Now use our client ant autentize
-#        client = HttpDigestClient()
-#        client.set_http_authentication(username='username', password='password', path=self.path)
-#        response = client.get(self.path)
-#        self.assertEquals(200, response.status_code)
-        
-    
-    def _check_authentication_compatibility(self, path):
-        
-        # first handle bad path
-        
-        auth_handler = urllib2.HTTPDigestAuthHandler()
-        auth_handler.add_password('simple', self.url, 'username', 'badpassword')
-        opener = urllib2.build_opener(auth_handler)
-        
-        request = urllib2.Request(self.url+path)
-        try:
-            response = opener.open(request)
-            self.fail("Exception expected to be raised")
-        except urllib2.HTTPError, err:
-            self.assertEquals(401, err.code)
-            if err.fp:
-                err.fp.close()
-
-        # then happy path
-        
-        auth_handler = urllib2.HTTPDigestAuthHandler()
-        auth_handler.add_password('simple', self.url, 'username', 'password')
-        opener = urllib2.build_opener(auth_handler)
-        
-        request = urllib2.Request(self.url+path)
-        try:
-            response = opener.open(request)
-        except urllib2.HTTPError, err:
-            if err.fp:
-                error = ": %s" % err.fp.read()
-            else:
-                error = ''
-            logging.error("Error occured while opening HTTP %s" % error)
-            raise
-        self.assertEquals(200, response.code)
-        response.close()
-    
-    def test_autentization_compatible_simple(self):
-        """ Check our server-side autentizations is compatible with standard (urllib2) one """
-        self._check_authentication_compatibility(path='/testapi/simpleprotected/')
-        
-    def test_autentization_compatible_model(self):
-        # add something to test agains
-        from testapi.models import ModelWithRealmSet
-        
-        ModelWithRealmSet.objects.create(realm='simple', username='username', secret=md5("%s:%s:%s" % ("username", "simple", "password")).hexdigest()) 
-        
-        self._check_authentication_compatibility(path='/testapi/modelprotected/')
-

run_tests

-#!/bin/sh
-cd testproject
-#./manage.py test $1
-./livetests.py
-exit $?;

testproject/config.py

 MANAGERS = ADMINS
 
 DATABASE_ENGINE = "sqlite3"
-DATABASE_NAME = "/home/almad/tmp/httpdigesttest.db"
+DATABASE_NAME = "/tmp/httpdigesttest.db"
+TEST_DATABASE_NAME = "/tmp/httpdigesttest.db"
 DATABASE_USER = ""
 DATABASE_PASSWORD = ""
 DATABASE_HOST = "localhost"

testproject/djangohttpdigest

-../djangohttpdigest/

testproject/livetests.py

-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-""" Run webtests """
-
-import sys
-import os, os.path
-
-from django.core.management import setup_environ
-import nose
-from nose.config import Config, all_config_files
-from nose.plugins.manager import DefaultPluginManager
-
-import settings
-setup_environ(settings)
-
-from server_runner import ServerRunner
-
-def run_selenium_tests():
-    
-        # nose config
-        config = Config(files=all_config_files(), plugins=DefaultPluginManager())
-        config.workingDir = os.path.join(os.path.dirname(__file__)) 
-        server_runner = ServerRunner()
-        server_runner.run_server()
-        success = nose.run(config=config)
-        server_runner.stop_server()
-        
-        return success
-
-def main():
-    success = run_selenium_tests()
-    
-    sys.exit(not success)
-    
-if __name__ == '__main__':
-    main()

testproject/server_runner.py

-# -*- coding: utf-8 -*-
-__license__ = """
-   Copyright (c) 2007 Mikeal Rogers
-   Modified for RPGPedia project (c) 2008 by Almad
-
-   Licensed under the Apache License, Version 2.0 (the "License");
-   you may not use this file except in compliance with the License.
-   You may obtain a copy of the License at
-
-       http://www.apache.org/licenses/LICENSE-2.0
-
-   Unless required by applicable law or agreed to in writing, software
-   distributed under the License is distributed on an "AS IS" BASIS,
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-implied.
-   See the License for the specific language governing permissions and
-   limitations under the License.
-
-"""
-
-
-import sys, os
-from time import sleep
-from threading import Thread
-
-import cherrypy
-
-__all__ = ["ServerRunner"]
-
-class ServerRunner(object):
-    
-    def __init__(self, port=8000):
-        self.port = port
-        self.httpd = None
-        self.http_thread = None
-    
-    def run_server(self):
-    
-         import django.core.handlers.wsgi
-         _application = django.core.handlers.wsgi.WSGIHandler()
-    
-         def application(environ, start_response):
-             environ['PATH_INFO'] = environ['SCRIPT_NAME'] + environ['PATH_INFO']
-             return _application(environ, start_response)
-    
-         import cherrypy
-         httpd = cherrypy.wsgiserver.CherryPyWSGIServer(('', self.port), application, server_name='django-test-http')
-         httpd_thread = Thread(target=httpd.start)
-         httpd_thread.start()
-         sleep(.5)
-    
-         self.httpd_thread = httpd_thread
-         self.httpd = httpd
-    
-    def stop_server(self):
-         self.httpd.stop()

testproject/settings.py

 
 MIDDLEWARE_CLASSES = (
     'django.middleware.common.CommonMiddleware',
-    'django.contrib.sessions.middleware.SessionMiddleware',
-    'django.contrib.auth.middleware.AuthenticationMiddleware',
-    'django.middleware.transaction.TransactionMiddleware',
-    'django.middleware.http.SetRemoteAddrFromForwardedFor',
 )
 
 ROOT_URLCONF = 'testproject.urls'
 )
 
 INSTALLED_APPS = (
-    'django.contrib.auth',
-    'django.contrib.contenttypes',
-    'django.contrib.sessions',
-    'django.contrib.sites',
-    'django.contrib.admin',
     'testapi',
     # OK, this is not really installed, but we want our testsuite to eat it
     'djangohttpdigest',

testproject/testapi/views.py

+from django.db.transaction import commit_on_success
 from django.http import HttpResponse
 from djangohttpdigest.decorators import protect_digest, protect_digest_model
 

testproject/tests/__init__.py

+from test_simple_digest import *
+from test_digest import *

testproject/tests/test_authentication.py

Empty file added.

testproject/tests/test_digest.py

+import re
+
+from djangohttpdigest.digest import Digestor, parse_authorization_header
+
+from djangosanetesting import UnitTestCase
+
+class TestDigestor(UnitTestCase):
+    """ Test digestor, our wrapping class for handling digests """
+    
+    def setUp(self):
+        self.digestor = Digestor(realm='testrealm', method='GET', path='/testapi/simpleprotected/')
+        self.auth_string = 'Digest username="rpgpedia", realm="extproject", nonce="1cc6ab869fca869c2c085d78a3729a66", uri="/extproject/project/fc8afe5e-da35-4fe2-a991-7b26c829cde5/user/rpgpedia/salt/", response="69ead146a246cd51bbd076244d2e455b", opaque="ToDoMoveThisToSettings", algorithm="MD5", qop=auth, nc=00000001, cnonce="a84f8e6cfcd50a75"'
+    
+    def _assertKeyEquals(self, key, value):
+        parsed_header = self.digestor.parse_authorization_header(self.auth_string)
+        self.assertTrue(parsed_header.has_key(key))
+        self.assertEquals(value, parsed_header[key])
+    
+    def test_get_digest_challenge(self):
+        challenge = self.digestor.get_digest_challenge()
+        
+        # check our challenge is compatible with urllib2's resolving
+        if re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', re.I).match(challenge):
+            pass
+        else:
+            self.fail("Challenge %s does not match urllib2's regexp" % challenge)
+    
+    def test_proper_parsing_username(self):
+        self._assertKeyEquals('username', 'rpgpedia')
+
+    def test_proper_parsing_realm(self):
+        self._assertKeyEquals('realm', 'extproject')
+
+    def test_proper_parsing_nonce(self):
+        self._assertKeyEquals('nonce', '1cc6ab869fca869c2c085d78a3729a66')
+
+    def test_proper_parsing_uri(self):
+        self._assertKeyEquals('uri', '/extproject/project/fc8afe5e-da35-4fe2-a991-7b26c829cde5/user/rpgpedia/salt/')
+
+    def test_proper_parsing_response(self):
+        self._assertKeyEquals('response', '69ead146a246cd51bbd076244d2e455b')
+
+    def test_proper_parsing_opaque(self):
+        self._assertKeyEquals('opaque', 'ToDoMoveThisToSettings')
+
+    def test_proper_parsing_algorithm(self):
+        self._assertKeyEquals('algorithm', 'MD5')
+
+    def test_proper_parsing_qop(self):
+        self._assertKeyEquals('qop', 'auth')
+
+    def test_proper_parsing_nc(self):
+        self._assertKeyEquals('nc', '00000001')
+
+    def test_proper_parsing_cnonce(self):
+        self._assertKeyEquals('cnonce', 'a84f8e6cfcd50a75')
+
+    def test_bad_parsing_missing_digest(self):
+        auth_string = 'username="rpgpedia", realm="extproject", nonce="1cc6ab869fca869c2c085d78a3729a66", uri="/extproject/project/fc8afe5e-da35-4fe2-a991-7b26c829cde5/user/rpgpedia/salt/", response="69ead146a246cd51bbd076244d2e455b", opaque="ToDoMoveThisToSettings", algorithm="MD5", qop=auth, nc=00000001, cnonce="a84f8e6cfcd50a75"'
+        self.assertRaises(ValueError, lambda:self.digestor.parse_authorization_header(auth_string))
+    
+class TestSimpleDigest(UnitTestCase):
+    
+    environment = {
+        'HTTP_COOKIE':       '',
+        'PATH_INFO':         '/',
+        'QUERY_STRING':      '',
+        'REQUEST_METHOD':    'GET',
+        'SCRIPT_NAME':       '',
+        'SERVER_NAME':       'testserver',
+        'SERVER_PORT':       '80',
+        'SERVER_PROTOCOL':   'HTTP/1.1',
+    }
+    
+    def test_parse_authorization_header(self):
+        """ Authorization header parsing, for various inputs """
+        self.assertRaises(ValueError, lambda:parse_authorization_header(''))

testproject/tests/test_simple_digest.py

+import urllib2
+import logging
+from md5 import md5
+from djangohttpdigest.client import HttpDigestClient
+
+from djangosanetesting import HttpTestCase
+
+class TestSimpleDigest(HttpTestCase):
+    path = '/testapi/simpleprotected/'
+    url = 'http://localhost:8000'
+    
+    def test_simple_autentization(self):
+        """ Test view protected by simple realm-username-password decorator """
+        
+        
+        # first test that using normal client, path is protected and returns 401
+        response = self.client.get(self.path)
+        self.assertEquals(401, response.status_code)
+        
+        # and that challenge is returned
+        assert len(response['www-authenticate']) > 0
+        assert 'nonce' in response['www-authenticate']
+        
+        #Now use our client ant autentize
+#        client = HttpDigestClient()
+#        client.set_http_authentication(username='username', password='password', path=self.path)
+#        response = client.get(self.path)
+#        self.assertEquals(200, response.status_code)
+        
+    
+    def _check_authentication_compatibility(self, path):
+        
+        # first handle bad path
+        
+        auth_handler = urllib2.HTTPDigestAuthHandler()
+        auth_handler.add_password('simple', self.url, 'username', 'badpassword')
+        opener = urllib2.build_opener(auth_handler)
+        
+        request = urllib2.Request(self.url+path)
+        try:
+            response = opener.open(request)
+            self.fail("Exception expected to be raised")
+        except urllib2.HTTPError, err:
+            self.assertEquals(401, err.code)
+            if err.fp:
+                err.fp.close()
+
+        # then happy path
+        
+        auth_handler = urllib2.HTTPDigestAuthHandler()
+        auth_handler.add_password('simple', self.url, 'username', 'password')
+        opener = urllib2.build_opener(auth_handler)
+        
+        request = urllib2.Request(self.url+path)
+        try:
+            response = opener.open(request)
+        except urllib2.HTTPError, err:
+            if err.fp:
+                error = ": %s" % err.fp.read()
+            else:
+                error = ''
+            logging.error("Error occured while opening HTTP %s" % error)
+            raise
+        self.assertEquals(200, response.code)
+        response.close()
+    
+    def test_autentization_compatible_simple(self):
+        """ Check our server-side autentizations is compatible with standard (urllib2) one """
+        self._check_authentication_compatibility(path='/testapi/simpleprotected/')
+        
+    def test_autentization_compatible_model(self):
+        # add something to test agains
+        from testapi.models import ModelWithRealmSet
+        
+        ModelWithRealmSet.objects.create(realm='simple', username='username', secret=md5("%s:%s:%s" % ("username", "simple", "password")).hexdigest()) 
+        
+        self._check_authentication_compatibility(path='/testapi/modelprotected/')
+