diff options
Diffstat (limited to 'mediagoblin/tests')
-rw-r--r-- | mediagoblin/tests/test_auth.py | 50 | ||||
-rw-r--r-- | mediagoblin/tests/test_celery_setup.py | 4 | ||||
-rw-r--r-- | mediagoblin/tests/test_csrf_middleware.py | 21 | ||||
-rw-r--r-- | mediagoblin/tests/test_edit.py | 99 | ||||
-rw-r--r-- | mediagoblin/tests/test_mgoblin_app.ini | 1 | ||||
-rw-r--r-- | mediagoblin/tests/test_misc.py | 26 | ||||
-rw-r--r-- | mediagoblin/tests/test_storage.py | 27 | ||||
-rw-r--r-- | mediagoblin/tests/test_submission.py | 28 | ||||
-rw-r--r-- | mediagoblin/tests/test_tags.py | 9 | ||||
-rw-r--r-- | mediagoblin/tests/test_tests.py | 6 | ||||
-rw-r--r-- | mediagoblin/tests/tools.py | 34 |
11 files changed, 235 insertions, 70 deletions
diff --git a/mediagoblin/tests/test_auth.py b/mediagoblin/tests/test_auth.py index 40961eca..d3b8caf1 100644 --- a/mediagoblin/tests/test_auth.py +++ b/mediagoblin/tests/test_auth.py @@ -20,7 +20,7 @@ import datetime from nose.tools import assert_equal from mediagoblin.auth import lib as auth_lib -from mediagoblin.tests.tools import setup_fresh_app +from mediagoblin.tests.tools import setup_fresh_app, fixture_add_user from mediagoblin import mg_globals from mediagoblin.tools import template, mail @@ -162,13 +162,13 @@ def test_register_views(test_app): new_user = mg_globals.database.User.find_one( {'username': 'happygirl'}) assert new_user - assert new_user['status'] == u'needs_email_verification' - assert new_user['email_verified'] == False + assert new_user.status == u'needs_email_verification' + assert new_user.email_verified == False ## Make sure user is logged in request = template.TEMPLATE_TEST_CONTEXT[ 'mediagoblin/user_pages/user.html']['request'] - assert request.session['user_id'] == unicode(new_user['_id']) + assert request.session['user_id'] == unicode(new_user._id) ## Make sure we get email confirmation, and try verifying assert len(mail.EMAIL_TEST_INBOX) == 1 @@ -185,15 +185,15 @@ def test_register_views(test_app): ### user should have these same parameters assert parsed_get_params['userid'] == [ - unicode(new_user['_id'])] + unicode(new_user._id)] assert parsed_get_params['token'] == [ - new_user['verification_key']] + new_user.verification_key] ## Try verifying with bs verification key, shouldn't work template.clear_test_template_context() response = test_app.get( "/auth/verify_email/?userid=%s&token=total_bs" % unicode( - new_user['_id'])) + new_user._id)) response.follow() context = template.TEMPLATE_TEST_CONTEXT[ 'mediagoblin/user_pages/user.html'] @@ -202,8 +202,8 @@ def test_register_views(test_app): new_user = mg_globals.database.User.find_one( {'username': 'happygirl'}) assert new_user - assert new_user['status'] == u'needs_email_verification' - assert new_user['email_verified'] == False + assert new_user.status == u'needs_email_verification' + assert new_user.email_verified == False ## Verify the email activation works template.clear_test_template_context() @@ -216,8 +216,8 @@ def test_register_views(test_app): new_user = mg_globals.database.User.find_one( {'username': 'happygirl'}) assert new_user - assert new_user['status'] == u'active' - assert new_user['email_verified'] == True + assert new_user.status == u'active' + assert new_user.email_verified == True # Uniqueness checks # ----------------- @@ -269,28 +269,28 @@ def test_register_views(test_app): # user should have matching parameters new_user = mg_globals.database.User.find_one({'username': 'happygirl'}) - assert parsed_get_params['userid'] == [unicode(new_user['_id'])] - assert parsed_get_params['token'] == [new_user['fp_verification_key']] + assert parsed_get_params['userid'] == [unicode(new_user._id)] + assert parsed_get_params['token'] == [new_user.fp_verification_key] ### The forgotten password token should be set to expire in ~ 10 days # A few ticks have expired so there are only 9 full days left... - assert (new_user['fp_token_expire'] - datetime.datetime.now()).days == 9 + assert (new_user.fp_token_expire - datetime.datetime.now()).days == 9 ## Try using a bs password-changing verification key, shouldn't work template.clear_test_template_context() response = test_app.get( "/auth/forgot_password/verify/?userid=%s&token=total_bs" % unicode( - new_user['_id']), status=400) - assert response.status == '400 Bad Request' + new_user._id), status=404) + assert_equal(response.status, '404 Not Found') ## Try using an expired token to change password, shouldn't work template.clear_test_template_context() - real_token_expiration = new_user['fp_token_expire'] - new_user['fp_token_expire'] = datetime.datetime.now() + real_token_expiration = new_user.fp_token_expire + new_user.fp_token_expire = datetime.datetime.now() new_user.save() - response = test_app.get("%s?%s" % (path, get_params), status=400) - assert response.status == '400 Bad Request' - new_user['fp_token_expire'] = real_token_expiration + response = test_app.get("%s?%s" % (path, get_params), status=404) + assert_equal(response.status, '404 Not Found') + new_user.fp_token_expire = real_token_expiration new_user.save() ## Verify step 1 of password-change works -- can see form to change password @@ -332,11 +332,7 @@ def test_authentication_views(test_app): Test logging in and logging out """ # Make a new user - test_user = mg_globals.database.User() - test_user['username'] = u'chris' - test_user['email'] = u'chris@example.com' - test_user['pw_hash'] = auth_lib.bcrypt_gen_password_hash('toast') - test_user.save() + test_user = fixture_add_user(active_user=False) # Get login # --------- @@ -412,7 +408,7 @@ def test_authentication_views(test_app): # Make sure user is in the session context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/root.html'] session = context['request'].session - assert session['user_id'] == unicode(test_user['_id']) + assert session['user_id'] == unicode(test_user._id) # Successful logout # ----------------- diff --git a/mediagoblin/tests/test_celery_setup.py b/mediagoblin/tests/test_celery_setup.py index 348a4357..19a9b899 100644 --- a/mediagoblin/tests/test_celery_setup.py +++ b/mediagoblin/tests/test_celery_setup.py @@ -50,7 +50,7 @@ def test_setup_celery_from_config(): assert isinstance(fake_celery_module.CELERYD_ETA_SCHEDULER_PRECISION, float) assert fake_celery_module.CELERY_RESULT_PERSISTENT is True assert fake_celery_module.CELERY_IMPORTS == [ - 'foo.bar.baz', 'this.is.an.import', 'mediagoblin.process_media'] + 'foo.bar.baz', 'this.is.an.import', 'mediagoblin.processing'] assert fake_celery_module.CELERY_MONGODB_BACKEND_SETTINGS == { 'database': 'mediagoblin'} assert fake_celery_module.CELERY_RESULT_BACKEND == 'mongodb' @@ -74,7 +74,7 @@ def test_setup_celery_from_config(): assert isinstance(fake_celery_module.CELERYD_ETA_SCHEDULER_PRECISION, float) assert fake_celery_module.CELERY_RESULT_PERSISTENT is False assert fake_celery_module.CELERY_IMPORTS == [ - 'baz.bar.foo', 'import.is.a.this', 'mediagoblin.process_media'] + 'baz.bar.foo', 'import.is.a.this', 'mediagoblin.processing'] assert fake_celery_module.CELERY_MONGODB_BACKEND_SETTINGS == { 'database': 'captain_lollerskates', 'host': 'mongodb.example.org', diff --git a/mediagoblin/tests/test_csrf_middleware.py b/mediagoblin/tests/test_csrf_middleware.py index 691f10b9..c8fca23a 100644 --- a/mediagoblin/tests/test_csrf_middleware.py +++ b/mediagoblin/tests/test_csrf_middleware.py @@ -27,7 +27,7 @@ from mediagoblin import mg_globals def test_csrf_cookie_set(test_app): cookie_name = mg_globals.app_config['csrf_cookie_name'] - + # get login page response = test_app.get('/auth/login/') @@ -69,3 +69,22 @@ def test_csrf_token_must_match(test_app): mg_globals.app_config['csrf_cookie_name'])}, extra_environ={'gmg.verify_csrf': True}).\ status_int == 200 + +@setup_fresh_app +def test_csrf_exempt(test_app): + + # monkey with the views to decorate a known endpoint + import mediagoblin.auth.views + from mediagoblin.meddleware.csrf import csrf_exempt + + mediagoblin.auth.views.login = csrf_exempt( + mediagoblin.auth.views.login + ) + + # construct a request with no cookie or form token + assert test_app.post('/auth/login/', + extra_environ={'gmg.verify_csrf': True}, + expect_errors=False).status_int == 200 + + # restore the CSRF protection in case other tests expect it + mediagoblin.auth.views.login.csrf_enabled = True diff --git a/mediagoblin/tests/test_edit.py b/mediagoblin/tests/test_edit.py new file mode 100644 index 00000000..0cf71e9b --- /dev/null +++ b/mediagoblin/tests/test_edit.py @@ -0,0 +1,99 @@ +# GNU MediaGoblin -- federated, autonomous media hosting +# Copyright (C) 2011 MediaGoblin contributors. See AUTHORS. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +from mediagoblin import mg_globals +from mediagoblin.tests.tools import setup_fresh_app, fixture_add_user +from mediagoblin.tools import template +from mediagoblin.auth.lib import bcrypt_check_password + + +@setup_fresh_app +def test_change_password(test_app): + """Test changing password correctly and incorrectly""" + # set up new user + test_user = fixture_add_user() + + test_app.post( + '/auth/login/', { + 'username': u'chris', + 'password': 'toast'}) + + # test that the password can be changed + # template.clear_test_template_context() + test_app.post( + '/edit/profile/', { + 'bio': u'', + 'url': u'', + 'old_password': 'toast', + 'new_password': '123456', + 'confirm_password': '123456'}) + + # test_user has to be fetched again in order to have the current values + test_user = mg_globals.database.User.one({'username': 'chris'}) + + assert bcrypt_check_password('123456', test_user.pw_hash) + + # test that the password cannot be changed if the given old_password + # is wrong + # template.clear_test_template_context() + test_app.post( + '/edit/profile/', { + 'bio': u'', + 'url': u'', + 'old_password': 'toast', + 'new_password': '098765', + 'confirm_password': '098765'}) + + test_user = mg_globals.database.User.one({'username': 'chris'}) + + assert not bcrypt_check_password('098765', test_user.pw_hash) + + +@setup_fresh_app +def change_bio_url(test_app): + """Test changing bio and URL""" + # set up new user + test_user = fixture_add_user() + + # test changing the bio and the URL properly + test_app.post( + '/edit/profile/', { + 'bio': u'I love toast!', + 'url': u'http://dustycloud.org/'}) + + test_user = mg_globals.database.User.one({'username': 'chris'}) + + assert test_user.bio == u'I love toast!' + assert test_user.url == u'http://dustycloud.org/' + + # test changing the bio and the URL inproperly + too_long_bio = 150 * 'T' + 150 * 'o' + 150 * 'a' + 150 * 's' + 150* 't' + + test_app.post( + '/edit/profile/', { + # more than 500 characters + 'bio': too_long_bio, + 'url': 'this-is-no-url'}) + + test_user = mg_globals.database.User.one({'username': 'chris'}) + + context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/edit/edit_profile.html'] + form = context['edit_profile_form'] + + assert form.bio.errors == [u'Field must be between 0 and 500 characters long.'] + assert form.url.errors == [u'Improperly formed URL'] + + # test changing the url inproperly diff --git a/mediagoblin/tests/test_mgoblin_app.ini b/mediagoblin/tests/test_mgoblin_app.ini index f979e810..2525a4f9 100644 --- a/mediagoblin/tests/test_mgoblin_app.ini +++ b/mediagoblin/tests/test_mgoblin_app.ini @@ -5,7 +5,6 @@ email_debug_mode = true db_name = __mediagoblin_tests__ # tag parsing -tags_delimiter = "," tags_max_length = 50 # Celery shouldn't be set up by the application as it's setup via diff --git a/mediagoblin/tests/test_misc.py b/mediagoblin/tests/test_misc.py new file mode 100644 index 00000000..09623355 --- /dev/null +++ b/mediagoblin/tests/test_misc.py @@ -0,0 +1,26 @@ +# GNU MediaGoblin -- federated, autonomous media hosting +# Copyright (C) 2011 MediaGoblin contributors. See AUTHORS. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +from nose.tools import assert_equal + +from mediagoblin.tests.tools import setup_fresh_app + + +@setup_fresh_app +def test_404_for_non_existent(test_app): + assert_equal(test_app.get('/does-not-exist/', + expect_errors=True).status_int, + 404) diff --git a/mediagoblin/tests/test_storage.py b/mediagoblin/tests/test_storage.py index 46ecb2ec..eab4d032 100644 --- a/mediagoblin/tests/test_storage.py +++ b/mediagoblin/tests/test_storage.py @@ -57,6 +57,10 @@ class FakeRemoteStorage(storage.filestorage.BasicFileStorage): # should force copying to the workbench local_storage = False + def copy_local_to_storage(self, *args, **kwargs): + return storage.StorageInterface.copy_local_to_storage( + self, *args, **kwargs) + def test_storage_system_from_config(): this_storage = storage.storage_system_from_config( @@ -252,3 +256,26 @@ def test_basic_storage_copy_locally(): this_storage.copy_locally(filepath, new_file_dest) assert file(new_file_dest).read() == 'Testing this file' + + +def _test_copy_local_to_storage_works(tmpdir, this_storage): + local_filename = tempfile.mktemp() + with file(local_filename, 'w') as tmpfile: + tmpfile.write('haha') + + this_storage.copy_local_to_storage( + local_filename, ['dir1', 'dir2', 'copiedto.txt']) + + assert file( + os.path.join(tmpdir, 'dir1/dir2/copiedto.txt'), + 'r').read() == 'haha' + + +def test_basic_storage_copy_local_to_storage(): + tmpdir, this_storage = get_tmp_filestorage() + _test_copy_local_to_storage_works(tmpdir, this_storage) + + +def test_general_storage_copy_local_to_storage(): + tmpdir, this_storage = get_tmp_filestorage(fake_remote=True) + _test_copy_local_to_storage_works(tmpdir, this_storage) diff --git a/mediagoblin/tests/test_submission.py b/mediagoblin/tests/test_submission.py index 1c657e6c..7c372745 100644 --- a/mediagoblin/tests/test_submission.py +++ b/mediagoblin/tests/test_submission.py @@ -19,8 +19,8 @@ import pkg_resources from nose.tools import assert_equal, assert_true, assert_false -from mediagoblin.auth import lib as auth_lib -from mediagoblin.tests.tools import setup_fresh_app, get_test_app +from mediagoblin.tests.tools import setup_fresh_app, get_test_app, \ + fixture_add_user from mediagoblin import mg_globals from mediagoblin.tools import template, common @@ -45,13 +45,7 @@ class TestSubmission: # TODO: Possibly abstract into a decorator like: # @as_authenticated_user('chris') - test_user = mg_globals.database.User() - test_user['username'] = u'chris' - test_user['email'] = u'chris@example.com' - test_user['email_verified'] = True - test_user['status'] = u'active' - test_user['pw_hash'] = auth_lib.bcrypt_gen_password_hash('toast') - test_user.save() + test_user = fixture_add_user() self.test_user = test_user @@ -176,8 +170,8 @@ class TestSubmission: response = self.test_app.post( request.urlgen('mediagoblin.user_pages.media_confirm_delete', # No work: user=media.uploader().username, - user=self.test_user['username'], - media=media['_id']), + user=self.test_user.username, + media=media._id), # no value means no confirm {}) @@ -196,8 +190,8 @@ class TestSubmission: response = self.test_app.post( request.urlgen('mediagoblin.user_pages.media_confirm_delete', # No work: user=media.uploader().username, - user=self.test_user['username'], - media=media['_id']), + user=self.test_user.username, + media=media._id), {'confirm': 'y'}) response.follow() @@ -208,7 +202,7 @@ class TestSubmission: # Does media entry still exist? assert_false( request.db.MediaEntry.find( - {'_id': media['_id']}).count()) + {'_id': media._id}).count()) def test_malicious_uploads(self): # Test non-suppoerted file with non-supported extension @@ -222,7 +216,7 @@ class TestSubmission: context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/submit/start.html'] form = context['submit_form'] - assert form.file.errors == ['The file doesn\'t seem to be an image!'] + assert form.file.errors == [u'Invalid file type.'] # NOTE: The following 2 tests will ultimately fail, but they # *will* pass the initial form submission step. Instead, @@ -246,7 +240,7 @@ class TestSubmission: assert_equal(entry['state'], 'failed') assert_equal( entry['fail_error'], - u'mediagoblin.process_media.errors:BadMediaFail') + u'mediagoblin.processing:BadMediaFail') # Test non-supported file with .png extension # ------------------------------------------- @@ -266,4 +260,4 @@ class TestSubmission: assert_equal(entry['state'], 'failed') assert_equal( entry['fail_error'], - u'mediagoblin.process_media.errors:BadMediaFail') + u'mediagoblin.processing:BadMediaFail') diff --git a/mediagoblin/tests/test_tags.py b/mediagoblin/tests/test_tags.py index a05831c9..583c1a55 100644 --- a/mediagoblin/tests/test_tags.py +++ b/mediagoblin/tests/test_tags.py @@ -39,11 +39,4 @@ def test_list_of_dicts_conversion(test_app): # Make sure converting the list of dicts to a string works assert text.media_tags_as_string([{'name': u'yin', 'slug': u'yin'}, {'name': u'yang', 'slug': u'yang'}]) == \ - u'yin,yang' - - # If the tag delimiter is a space then we expect different results - mg_globals.app_config['tags_delimiter'] = u' ' - assert text.convert_to_tag_list_of_dicts('unicorn ceramic nazi') == [ - {'name': u'unicorn', 'slug': u'unicorn'}, - {'name': u'ceramic', 'slug': u'ceramic'}, - {'name': u'nazi', 'slug': u'nazi'}] + u'yin, yang' diff --git a/mediagoblin/tests/test_tests.py b/mediagoblin/tests/test_tests.py index bc5f9a8d..25bb52b3 100644 --- a/mediagoblin/tests/test_tests.py +++ b/mediagoblin/tests/test_tests.py @@ -27,9 +27,9 @@ def test_get_test_app_wipes_db(): assert mg_globals.database.User.find().count() == 0 new_user = mg_globals.database.User() - new_user['username'] = u'lolcat' - new_user['email'] = u'lol@cats.example.org' - new_user['pw_hash'] = u'pretend_this_is_a_hash' + new_user.username = u'lolcat' + new_user.email = u'lol@cats.example.org' + new_user.pw_hash = u'pretend_this_is_a_hash' new_user.save() assert mg_globals.database.User.find().count() == 1 diff --git a/mediagoblin/tests/tools.py b/mediagoblin/tests/tools.py index 420d9ba8..49a3d33e 100644 --- a/mediagoblin/tests/tools.py +++ b/mediagoblin/tests/tools.py @@ -26,6 +26,8 @@ from mediagoblin.tools import testing from mediagoblin.init.config import read_mediagoblin_config from mediagoblin.decorators import _make_safe from mediagoblin.db.open import setup_connection_and_db_from_config +from mediagoblin.meddleware import BaseMeddleware +from mediagoblin.auth.lib import bcrypt_gen_password_hash MEDIAGOBLIN_TEST_DB_NAME = u'__mediagoblin_tests__' @@ -50,9 +52,9 @@ $ CELERY_CONFIG_MODULE=mediagoblin.init.celery.from_tests ./bin/nosetests""" class BadCeleryEnviron(Exception): pass -class TestingMiddleware(object): +class TestingMeddleware(BaseMeddleware): """ - Middleware for the Unit tests + Meddleware for the Unit tests It might make sense to perform some tests on all requests/responses. Or prepare them in a special @@ -60,7 +62,7 @@ class TestingMiddleware(object): for being valid html *after* being rendered. This module is getting inserted at the front of the - middleware list, which means: requests are handed here + meddleware list, which means: requests are handed here first, responses last. So this wraps up the "normal" app. @@ -69,12 +71,6 @@ class TestingMiddleware(object): create a new method and call it from process_*. """ - def __init__(self, mg_app): - self.app = mg_app - - def process_request(self, request): - pass - def process_response(self, request, response): # All following tests should be for html only! if response.content_type != "text/html": @@ -149,11 +145,11 @@ def get_test_app(dump_old_app=True): test_app = loadapp( 'config:' + TEST_SERVER_CONFIG) - # Insert the TestingMiddleware, which can do some + # Insert the TestingMeddleware, which can do some # sanity checks on every request/response. # Doing it this way is probably not the cleanest way. # We'll fix it, when we have plugins! - mg_globals.app.middleware.insert(0, TestingMiddleware(mg_globals.app)) + mg_globals.app.meddleware.insert(0, TestingMeddleware(mg_globals.app)) app = TestApp(test_app) MGOBLIN_APP = app @@ -205,3 +201,19 @@ def assert_db_meets_expected(db, expected): document = collection.find_one({'_id': expected_document['_id']}) assert document is not None # make sure it exists assert document == expected_document # make sure it matches + + +def fixture_add_user(username = u'chris', password = 'toast', + active_user = True): + test_user = mg_globals.database.User() + test_user.username = username + test_user.email = username + u'@example.com' + if password is not None: + test_user.pw_hash = bcrypt_gen_password_hash(password) + if active_user: + test_user.email_verified = True + test_user.status = u'active' + + test_user.save() + + return test_user |