diff options
Diffstat (limited to 'mediagoblin/tests')
-rw-r--r-- | mediagoblin/tests/test_auth.py | 73 | ||||
-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 | 95 | ||||
-rw-r--r-- | mediagoblin/tests/test_mgoblin_app.ini | 6 | ||||
-rw-r--r-- | mediagoblin/tests/test_migrations.py | 4 | ||||
-rw-r--r-- | mediagoblin/tests/test_misc.py | 26 | ||||
-rw-r--r-- | mediagoblin/tests/test_paste.ini | 2 | ||||
-rw-r--r-- | mediagoblin/tests/test_storage.py | 27 | ||||
-rw-r--r-- | mediagoblin/tests/test_submission.py | 49 | ||||
-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 | 64 |
13 files changed, 301 insertions, 85 deletions
diff --git a/mediagoblin/tests/test_auth.py b/mediagoblin/tests/test_auth.py index 40961eca..411b4539 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 @@ -89,7 +89,6 @@ def test_register_views(test_app): form = context['register_form'] assert form.username.errors == [u'This field is required.'] assert form.password.errors == [u'This field is required.'] - assert form.confirm_password.errors == [u'This field is required.'] assert form.email.errors == [u'This field is required.'] # Try to register with fields that are known to be invalid @@ -101,7 +100,6 @@ def test_register_views(test_app): '/auth/register/', { 'username': 'l', 'password': 'o', - 'confirm_password': 'o', 'email': 'l'}) context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/register.html'] form = context['register_form'] @@ -125,18 +123,6 @@ def test_register_views(test_app): assert form.email.errors == [ u'Invalid email address.'] - ## mismatching passwords - template.clear_test_template_context() - test_app.post( - '/auth/register/', { - 'password': 'herpderp', - 'confirm_password': 'derpherp'}) - context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/register.html'] - form = context['register_form'] - - assert form.password.errors == [ - u'Passwords must match.'] - ## At this point there should be no users in the database ;) assert not mg_globals.database.User.find().count() @@ -147,7 +133,6 @@ def test_register_views(test_app): '/auth/register/', { 'username': 'happygirl', 'password': 'iamsohappy', - 'confirm_password': 'iamsohappy', 'email': 'happygrrl@example.org'}) response.follow() @@ -162,13 +147,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 +170,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 +187,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 +201,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 # ----------------- @@ -227,7 +212,6 @@ def test_register_views(test_app): '/auth/register/', { 'username': 'happygirl', 'password': 'iamsohappy2', - 'confirm_password': 'iamsohappy2', 'email': 'happygrrl2@example.org'}) context = template.TEMPLATE_TEST_CONTEXT[ @@ -249,9 +233,9 @@ def test_register_views(test_app): ## Did we redirect to the proper page? Use the right template? assert_equal( urlparse.urlsplit(response.location)[2], - '/auth/forgot_password/email_sent/') + '/auth/login/') assert template.TEMPLATE_TEST_CONTEXT.has_key( - 'mediagoblin/auth/fp_email_sent.html') + 'mediagoblin/auth/login.html') ## Make sure link to change password is sent by email assert len(mail.EMAIL_TEST_INBOX) == 1 @@ -269,28 +253,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 @@ -304,11 +288,10 @@ def test_register_views(test_app): '/auth/forgot_password/verify/', { 'userid': parsed_get_params['userid'], 'password': 'iamveryveryhappy', - 'confirm_password': 'iamveryveryhappy', 'token': parsed_get_params['token']}) response.follow() assert template.TEMPLATE_TEST_CONTEXT.has_key( - 'mediagoblin/auth/fp_changed_success.html') + 'mediagoblin/auth/login.html') ## Verify step 2.2 of password-change works -- login w/ new password success template.clear_test_template_context() @@ -332,11 +315,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 +391,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..55f34b42 --- /dev/null +++ b/mediagoblin/tests/test_edit.py @@ -0,0 +1,95 @@ +# 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/account/', { + 'old_password': 'toast', + 'new_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/account/', { + 'old_password': 'toast', + 'new_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 ab32cccc..c91ed92b 100644 --- a/mediagoblin/tests/test_mgoblin_app.ini +++ b/mediagoblin/tests/test_mgoblin_app.ini @@ -1,13 +1,15 @@ [mediagoblin] -direct_remote_path = /mgoblin_static/ +direct_remote_path = /test_static/ email_sender_address = "notice@mediagoblin.example.org" email_debug_mode = true db_name = __mediagoblin_tests__ # tag parsing -tags_delimiter = "," tags_max_length = 50 +# So we can start to test attachments: +allow_attachments = True + # Celery shouldn't be set up by the application as it's setup via # mediagoblin.init.celery.from_celery celery_setup_elsewhere = true diff --git a/mediagoblin/tests/test_migrations.py b/mediagoblin/tests/test_migrations.py index e7cef0a1..8e573f5a 100644 --- a/mediagoblin/tests/test_migrations.py +++ b/mediagoblin/tests/test_migrations.py @@ -20,10 +20,10 @@ from pymongo import Connection from mediagoblin.tests.tools import ( install_fixtures_simple, assert_db_meets_expected) -from mediagoblin.db.util import ( +from mediagoblin.db.mongo.util import ( RegisterMigration, MigrationManager, ObjectId, MissingCurrentMigration) -from mediagoblin.db.migrations import add_table_field +from mediagoblin.db.mongo.migrations import add_table_field # This one will get filled with local migrations TEST_MIGRATION_REGISTRY = {} 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_paste.ini b/mediagoblin/tests/test_paste.ini index e7574b7a..bd57994b 100644 --- a/mediagoblin/tests/test_paste.ini +++ b/mediagoblin/tests/test_paste.ini @@ -5,7 +5,7 @@ debug = true use = egg:Paste#urlmap / = mediagoblin /mgoblin_media/ = publicstore_serve -/mgoblin_static/ = mediagoblin_static +/test_static/ = mediagoblin_static [app:mediagoblin] use = egg:mediagoblin#app 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..b3c11249 100644 --- a/mediagoblin/tests/test_submission.py +++ b/mediagoblin/tests/test_submission.py @@ -1,3 +1,4 @@ + # GNU MediaGoblin -- federated, autonomous media hosting # Copyright (C) 2011 MediaGoblin contributors. See AUTHORS. # @@ -16,11 +17,12 @@ import urlparse import pkg_resources +import re 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,21 +47,21 @@ 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 + self.login() + + def login(self): self.test_app.post( '/auth/login/', { 'username': u'chris', 'password': 'toast'}) + def logout(self): + self.test_app.get('/auth/logout/') + def test_missing_fields(self): # Test blank form # --------------- @@ -99,6 +101,14 @@ class TestSubmission: assert template.TEMPLATE_TEST_CONTEXT.has_key( 'mediagoblin/user_pages/user.html') + # Make sure the media view is at least reachable, logged in... + self.test_app.get('/u/chris/m/normal-upload-1/') + # ... and logged out too. + self.logout() + self.test_app.get('/u/chris/m/normal-upload-1/') + # Log back in for the remaining tests. + self.login() + # Test PNG # -------- template.clear_test_template_context() @@ -176,8 +186,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 +206,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 +218,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 +232,8 @@ 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 re.match(r'^Could not extract any file extension from ".*?"$', str(form.file.errors[0])) + assert len(form.file.errors) == 1 # NOTE: The following 2 tests will ultimately fail, but they # *will* pass the initial form submission step. Instead, @@ -243,10 +254,10 @@ class TestSubmission: entry = mg_globals.database.MediaEntry.find_one( {'title': 'Malicious Upload 2'}) - assert_equal(entry['state'], 'failed') + 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 # ------------------------------------------- @@ -263,7 +274,7 @@ class TestSubmission: entry = mg_globals.database.MediaEntry.find_one( {'title': 'Malicious Upload 3'}) - assert_equal(entry['state'], 'failed') + 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 cf84da14..49a3d33e 100644 --- a/mediagoblin/tests/tools.py +++ b/mediagoblin/tests/tools.py @@ -21,10 +21,13 @@ import os, shutil from paste.deploy import loadapp from webtest import TestApp +from mediagoblin import mg_globals 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__' @@ -49,6 +52,45 @@ $ CELERY_CONFIG_MODULE=mediagoblin.init.celery.from_tests ./bin/nosetests""" class BadCeleryEnviron(Exception): pass +class TestingMeddleware(BaseMeddleware): + """ + Meddleware for the Unit tests + + It might make sense to perform some tests on all + requests/responses. Or prepare them in a special + manner. For example all html responses could be tested + for being valid html *after* being rendered. + + This module is getting inserted at the front of the + meddleware list, which means: requests are handed here + first, responses last. So this wraps up the "normal" + app. + + If you need to add a test, either add it directly to + the appropiate process_request or process_response, or + create a new method and call it from process_*. + """ + + def process_response(self, request, response): + # All following tests should be for html only! + if response.content_type != "text/html": + # Get out early + return + + # If the template contains a reference to + # /mgoblin_static/ instead of using + # /request.staticdirect(), error out here. + # This could probably be implemented as a grep on + # the shipped templates easier... + if response.text.find("/mgoblin_static/") >= 0: + raise AssertionError( + "Response HTML contains reference to /mgoblin_static/ " + "instead of staticdirect. Request was for: " + + request.full_path) + + return + + def suicide_if_bad_celery_environ(): if not os.environ.get('CELERY_CONFIG_MODULE') == \ 'mediagoblin.init.celery.from_tests': @@ -103,6 +145,12 @@ def get_test_app(dump_old_app=True): test_app = loadapp( 'config:' + TEST_SERVER_CONFIG) + # 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.meddleware.insert(0, TestingMeddleware(mg_globals.app)) + app = TestApp(test_app) MGOBLIN_APP = app @@ -153,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 |