diff options
Diffstat (limited to 'mediagoblin/tests')
21 files changed, 441 insertions, 163 deletions
diff --git a/mediagoblin/tests/test_api.py b/mediagoblin/tests/test_api.py index 25ce852b..cff25776 100644 --- a/mediagoblin/tests/test_api.py +++ b/mediagoblin/tests/test_api.py @@ -44,7 +44,6 @@ EVIL_PNG = resource('evil.png') BIG_BLUE = resource('bigblue.png') -@pytest.mark.usefixtures("test_app") class TestAPI(object): def setup(self): self.db = mg_globals.database diff --git a/mediagoblin/tests/test_auth.py b/mediagoblin/tests/test_auth.py index f9fe8ed1..755727f9 100644 --- a/mediagoblin/tests/test_auth.py +++ b/mediagoblin/tests/test_auth.py @@ -17,8 +17,6 @@ import urlparse import datetime -from nose.tools import assert_equal - from mediagoblin import mg_globals from mediagoblin.auth import lib as auth_lib from mediagoblin.db.models import User @@ -101,8 +99,8 @@ def test_register_views(test_app): context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/register.html'] form = context['register_form'] - assert_equal (form.username.errors, [u'Field must be between 3 and 30 characters long.']) - assert_equal (form.password.errors, [u'Field must be between 5 and 1024 characters long.']) + assert form.username.errors == [u'Field must be between 3 and 30 characters long.'] + assert form.password.errors == [u'Field must be between 5 and 1024 characters long.'] ## bad form template.clear_test_template_context() @@ -113,11 +111,11 @@ def test_register_views(test_app): context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/register.html'] form = context['register_form'] - assert_equal (form.username.errors, [u'This field does not take email addresses.']) - assert_equal (form.email.errors, [u'This field requires an email address.']) + assert form.username.errors == [u'This field does not take email addresses.'] + assert form.email.errors == [u'This field requires an email address.'] ## At this point there should be no users in the database ;) - assert_equal(User.query.count(), 0) + assert User.query.count() == 0 # Successful register # ------------------- @@ -130,9 +128,7 @@ def test_register_views(test_app): response.follow() ## Did we redirect to the proper page? Use the right template? - assert_equal( - urlparse.urlsplit(response.location)[2], - '/u/happygirl/') + assert urlparse.urlsplit(response.location)[2] == '/u/happygirl/' assert 'mediagoblin/user_pages/user.html' in template.TEMPLATE_TEST_CONTEXT ## Make sure user is in place @@ -223,9 +219,7 @@ def test_register_views(test_app): response.follow() ## Did we redirect to the proper page? Use the right template? - assert_equal( - urlparse.urlsplit(response.location)[2], - '/auth/login/') + assert urlparse.urlsplit(response.location)[2] == '/auth/login/' assert 'mediagoblin/auth/login.html' in template.TEMPLATE_TEST_CONTEXT ## Make sure link to change password is sent by email @@ -256,7 +250,7 @@ def test_register_views(test_app): response = test_app.get( "/auth/forgot_password/verify/?userid=%s&token=total_bs" % unicode( new_user.id), status=404) - assert_equal(response.status.split()[0], u'404') # status="404 NOT FOUND" + assert response.status.split()[0] == u'404' # status="404 NOT FOUND" ## Try using an expired token to change password, shouldn't work template.clear_test_template_context() @@ -265,7 +259,7 @@ def test_register_views(test_app): new_user.fp_token_expire = datetime.datetime.now() new_user.save() response = test_app.get("%s?%s" % (path, get_params), status=404) - assert_equal(response.status.split()[0], u'404') # status="404 NOT FOUND" + assert response.status.split()[0] == u'404' # status="404 NOT FOUND" new_user.fp_token_expire = real_token_expiration new_user.save() @@ -293,9 +287,7 @@ def test_register_views(test_app): # User should be redirected response.follow() - assert_equal( - urlparse.urlsplit(response.location)[2], - '/') + assert urlparse.urlsplit(response.location)[2] == '/' assert 'mediagoblin/root.html' in template.TEMPLATE_TEST_CONTEXT @@ -370,9 +362,7 @@ def test_authentication_views(test_app): # User should be redirected response.follow() - assert_equal( - urlparse.urlsplit(response.location)[2], - '/') + assert urlparse.urlsplit(response.location)[2] == '/' assert 'mediagoblin/root.html' in template.TEMPLATE_TEST_CONTEXT # Make sure user is in the session @@ -387,9 +377,7 @@ def test_authentication_views(test_app): # Should be redirected to index page response.follow() - assert_equal( - urlparse.urlsplit(response.location)[2], - '/') + assert urlparse.urlsplit(response.location)[2] == '/' assert 'mediagoblin/root.html' in template.TEMPLATE_TEST_CONTEXT # Make sure the user is not in the session @@ -405,6 +393,4 @@ def test_authentication_views(test_app): 'username': u'chris', 'password': 'toast', 'next' : '/u/chris/'}) - assert_equal( - urlparse.urlsplit(response.location)[2], - '/u/chris/') + assert urlparse.urlsplit(response.location)[2] == '/u/chris/' diff --git a/mediagoblin/tests/test_cache.py b/mediagoblin/tests/test_cache.py deleted file mode 100644 index 403173cd..00000000 --- a/mediagoblin/tests/test_cache.py +++ /dev/null @@ -1,50 +0,0 @@ -# GNU MediaGoblin -- federated, autonomous media hosting -# Copyright (C) 2011, 2012 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 - - -DATA_TO_CACHE = { - 'herp': 'derp', - 'lol': 'cats'} - - -def _get_some_data(key): - """ - Stuid function that makes use of some caching. - """ - some_data_cache = mg_globals.cache.get_cache('sum_data') - if some_data_cache.has_key(key): - return some_data_cache.get(key) - - value = DATA_TO_CACHE.get(key) - some_data_cache.put(key, value) - return value - - -def test_cache_working(test_app): - some_data_cache = mg_globals.cache.get_cache('sum_data') - assert not some_data_cache.has_key('herp') - assert _get_some_data('herp') == 'derp' - assert some_data_cache.get('herp') == 'derp' - # should get the same value again - assert _get_some_data('herp') == 'derp' - - # now we force-change it, but the function should use the cached - # version - some_data_cache.put('herp', 'pred') - assert _get_some_data('herp') == 'pred' diff --git a/mediagoblin/tests/test_collections.py b/mediagoblin/tests/test_collections.py index d4d3af71..87782f30 100644 --- a/mediagoblin/tests/test_collections.py +++ b/mediagoblin/tests/test_collections.py @@ -16,7 +16,6 @@ from mediagoblin.tests.tools import fixture_add_collection, fixture_add_user from mediagoblin.db.models import Collection, User -from nose.tools import assert_equal def test_user_deletes_collection(test_app): @@ -30,4 +29,4 @@ def test_user_deletes_collection(test_app): user.delete() cnt2 = Collection.query.count() - assert_equal(cnt1, cnt2 + 1) + assert cnt1 == cnt2 + 1 diff --git a/mediagoblin/tests/test_edit.py b/mediagoblin/tests/test_edit.py index f1f0baba..cda2607f 100644 --- a/mediagoblin/tests/test_edit.py +++ b/mediagoblin/tests/test_edit.py @@ -14,7 +14,7 @@ # 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 +import pytest from mediagoblin import mg_globals from mediagoblin.db.models import User @@ -69,7 +69,7 @@ class TestUserEdit(object): }) # Check for redirect on success - assert_equal(res.status_int, 302) + assert res.status_int == 302 # test_user has to be fetched again in order to have the current values test_user = User.query.filter_by(username=u'chris').first() assert bcrypt_check_password('123456', test_user.pw_hash) @@ -99,7 +99,7 @@ class TestUserEdit(object): 'url': u'http://dustycloud.org/'}, expect_errors=True) # Should redirect to /u/chris/edit/ - assert_equal (res.status_int, 302) + assert res.status_int == 302 assert res.headers['Location'].endswith("/u/chris/edit/") res = test_app.post( @@ -108,8 +108,8 @@ class TestUserEdit(object): 'url': u'http://dustycloud.org/'}) test_user = User.query.filter_by(username=u'chris').first() - assert_equal(test_user.bio, u'I love toast!') - assert_equal(test_user.url, u'http://dustycloud.org/') + assert test_user.bio == u'I love toast!' + assert test_user.url == u'http://dustycloud.org/' # change a different user than the logged in (should fail with 403) fixture_add_user(username=u"foo") @@ -117,7 +117,7 @@ class TestUserEdit(object): '/u/foo/edit/', { 'bio': u'I love toast!', 'url': u'http://dustycloud.org/'}, expect_errors=True) - assert_equal(res.status_int, 403) + assert res.status_int == 403 # test changing the bio and the URL inproperly too_long_bio = 150 * 'T' + 150 * 'o' + 150 * 'a' + 150 * 's' + 150* 't' @@ -129,10 +129,13 @@ class TestUserEdit(object): 'url': 'this-is-no-url'}) # Check form errors - context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/edit/edit_profile.html'] + context = template.TEMPLATE_TEST_CONTEXT[ + 'mediagoblin/edit/edit_profile.html'] form = context['form'] - assert_equal(form.bio.errors, [u'Field must be between 0 and 500 characters long.']) - assert_equal(form.url.errors, [u'This address contains errors']) + assert form.bio.errors == [ + u'Field must be between 0 and 500 characters long.'] + assert form.url.errors == [ + u'This address contains errors'] # test changing the url inproperly diff --git a/mediagoblin/tests/test_globals.py b/mediagoblin/tests/test_globals.py index d3722140..fe3088f8 100644 --- a/mediagoblin/tests/test_globals.py +++ b/mediagoblin/tests/test_globals.py @@ -14,7 +14,7 @@ # 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_raises +import pytest from mediagoblin import mg_globals @@ -36,7 +36,7 @@ class TestGlobals(object): assert mg_globals.public_store == 'my favorite public_store!' assert mg_globals.queue_store == 'my favorite queue_store!' - assert_raises( + pytest.raises( AssertionError, mg_globals.setup_globals, - no_such_global_foo = "Dummy") + no_such_global_foo="Dummy") diff --git a/mediagoblin/tests/test_mgoblin_app.ini b/mediagoblin/tests/test_mgoblin_app.ini index 42d3785a..b78abe64 100644 --- a/mediagoblin/tests/test_mgoblin_app.ini +++ b/mediagoblin/tests/test_mgoblin_app.ini @@ -23,10 +23,6 @@ base_url = /mgoblin_media/ [storage:queuestore] base_dir = %(here)s/test_user_dev/media/queue -[beaker.cache] -data_dir = %(here)s/test_user_dev/beaker/cache/data -lock_dir = %(here)s/test_user_dev/beaker/cache/lock - [celery] CELERY_ALWAYS_EAGER = true CELERY_RESULT_DBURI = "sqlite:///%(here)s/test_user_dev/celery.db" diff --git a/mediagoblin/tests/test_misc.py b/mediagoblin/tests/test_misc.py index 7143938e..755d863f 100644 --- a/mediagoblin/tests/test_misc.py +++ b/mediagoblin/tests/test_misc.py @@ -14,8 +14,6 @@ # 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.db.base import Session from mediagoblin.db.models import User, MediaEntry, MediaComment from mediagoblin.tests.tools import fixture_add_user, fixture_media_entry @@ -23,7 +21,7 @@ from mediagoblin.tests.tools import fixture_add_user, fixture_media_entry def test_404_for_non_existent(test_app): res = test_app.get('/does-not-exist/', expect_errors=True) - assert_equal(res.status_int, 404) + assert res.status_int == 404 def test_user_deletes_other_comments(test_app): @@ -58,11 +56,11 @@ def test_user_deletes_other_comments(test_app): cmt_cnt2 = MediaComment.query.count() # One user deleted - assert_equal(usr_cnt2, usr_cnt1 - 1) + assert usr_cnt2 == usr_cnt1 - 1 # One media gone - assert_equal(med_cnt2, med_cnt1 - 1) + assert med_cnt2 == med_cnt1 - 1 # Three of four comments gone. - assert_equal(cmt_cnt2, cmt_cnt1 - 3) + assert cmt_cnt2 == cmt_cnt1 - 3 User.query.get(user_b.id).delete() @@ -71,11 +69,11 @@ def test_user_deletes_other_comments(test_app): cmt_cnt2 = MediaComment.query.count() # All users gone - assert_equal(usr_cnt2, usr_cnt1 - 2) + assert usr_cnt2 == usr_cnt1 - 2 # All media gone - assert_equal(med_cnt2, med_cnt1 - 2) + assert med_cnt2 == med_cnt1 - 2 # All comments gone - assert_equal(cmt_cnt2, cmt_cnt1 - 4) + assert cmt_cnt2 == cmt_cnt1 - 4 def test_media_deletes_broken_attachment(test_app): diff --git a/mediagoblin/tests/test_modelmethods.py b/mediagoblin/tests/test_modelmethods.py index a5739ed5..427aa47c 100644 --- a/mediagoblin/tests/test_modelmethods.py +++ b/mediagoblin/tests/test_modelmethods.py @@ -17,8 +17,6 @@ # Maybe not every model needs a test, but some models have special # methods, and so it makes sense to test them here. -from nose.tools import assert_equal - from mediagoblin.db.base import Session from mediagoblin.db.models import MediaEntry @@ -166,4 +164,4 @@ def test_media_data_init(test_app): for obj in Session(): obj_in_session += 1 print repr(obj) - assert_equal(obj_in_session, 0) + assert obj_in_session == 0 diff --git a/mediagoblin/tests/test_paste.ini b/mediagoblin/tests/test_paste.ini index 875b4f65..91ecbb84 100644 --- a/mediagoblin/tests/test_paste.ini +++ b/mediagoblin/tests/test_paste.ini @@ -9,7 +9,6 @@ use = egg:Paste#urlmap [app:mediagoblin] use = egg:mediagoblin#app -filter-with = beaker config = %(here)s/mediagoblin.ini [app:publicstore_serve] @@ -20,14 +19,6 @@ document_root = %(here)s/test_user_dev/media/public use = egg:Paste#static document_root = %(here)s/mediagoblin/static/ -[filter:beaker] -use = egg:Beaker#beaker_session -cache_dir = %(here)s/test_user_dev/beaker -beaker.session.key = mediagoblin -# beaker.session.secret = somesupersecret -beaker.session.data_dir = %(here)s/test_user_dev/beaker/sessions/data -beaker.session.lock_dir = %(here)s/test_user_dev/beaker/sessions/lock - [celery] CELERY_ALWAYS_EAGER = true diff --git a/mediagoblin/tests/test_pluginapi.py b/mediagoblin/tests/test_pluginapi.py index 315a95da..d40a5081 100644 --- a/mediagoblin/tests/test_pluginapi.py +++ b/mediagoblin/tests/test_pluginapi.py @@ -15,11 +15,13 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. import sys + from configobj import ConfigObj +import pytest + from mediagoblin import mg_globals from mediagoblin.init.plugins import setup_plugins from mediagoblin.tools import pluginapi -from nose.tools import eq_ def with_cleanup(*modules_to_delete): @@ -97,7 +99,7 @@ def test_no_plugins(): setup_plugins() # Make sure we didn't load anything. - eq_(len(pman.plugins), 0) + assert len(pman.plugins) == 0 @with_cleanup('mediagoblin.plugins.sampleplugin') @@ -117,14 +119,14 @@ def test_one_plugin(): setup_plugins() # Make sure we only found one plugin - eq_(len(pman.plugins), 1) + assert len(pman.plugins) == 1 # Make sure the plugin is the one we think it is. - eq_(pman.plugins[0], 'mediagoblin.plugins.sampleplugin') + assert pman.plugins[0] == 'mediagoblin.plugins.sampleplugin' # Make sure there was one hook registered - eq_(len(pman.hooks), 1) + assert len(pman.hooks) == 1 # Make sure _setup_plugin_called was called once import mediagoblin.plugins.sampleplugin - eq_(mediagoblin.plugins.sampleplugin._setup_plugin_called, 1) + assert mediagoblin.plugins.sampleplugin._setup_plugin_called == 1 @with_cleanup('mediagoblin.plugins.sampleplugin') @@ -145,14 +147,14 @@ def test_same_plugin_twice(): setup_plugins() # Make sure we only found one plugin - eq_(len(pman.plugins), 1) + assert len(pman.plugins) == 1 # Make sure the plugin is the one we think it is. - eq_(pman.plugins[0], 'mediagoblin.plugins.sampleplugin') + assert pman.plugins[0] == 'mediagoblin.plugins.sampleplugin' # Make sure there was one hook registered - eq_(len(pman.hooks), 1) + assert len(pman.hooks) == 1 # Make sure _setup_plugin_called was called once import mediagoblin.plugins.sampleplugin - eq_(mediagoblin.plugins.sampleplugin._setup_plugin_called, 1) + assert mediagoblin.plugins.sampleplugin._setup_plugin_called == 1 @with_cleanup() @@ -172,4 +174,112 @@ def test_disabled_plugin(): setup_plugins() # Make sure we didn't load the plugin - eq_(len(pman.plugins), 0) + assert len(pman.plugins) == 0 + + +@with_cleanup() +def test_callable_runone(): + """ + Test the callable_runone method + """ + cfg = build_config([ + ('mediagoblin', {}, []), + ('plugins', {}, [ + ('mediagoblin.tests.testplugins.callables1', {}, []), + ('mediagoblin.tests.testplugins.callables2', {}, []), + ('mediagoblin.tests.testplugins.callables3', {}, []), + ]) + ]) + + mg_globals.app_config = cfg['mediagoblin'] + mg_globals.global_config = cfg + + setup_plugins() + + # Just one hook provided + call_log = [] + assert pluginapi.callable_runone( + "just_one", call_log) == "Called just once" + assert call_log == ["expect this one call"] + + # Nothing provided and unhandled not okay + call_log = [] + with pytest.raises(pluginapi.UnhandledCallable): + pluginapi.callable_runone( + "nothing_handling", call_log) + assert call_log == [] + + # Nothing provided and unhandled okay + call_log = [] + assert pluginapi.callable_runone( + "nothing_handling", call_log, unhandled_okay=True) is None + assert call_log == [] + + # Multiple provided, go with the first! + call_log = [] + assert pluginapi.callable_runone( + "multi_handle", call_log) == "the first returns" + assert call_log == ["Hi, I'm the first"] + + # Multiple provided, one has CantHandleIt + call_log = [] + assert pluginapi.callable_runone( + "multi_handle_with_canthandle", + call_log) == "the second returns" + assert call_log == ["Hi, I'm the second"] + + +@with_cleanup() +def test_callable_runall(): + """ + Test the callable_runall method + """ + cfg = build_config([ + ('mediagoblin', {}, []), + ('plugins', {}, [ + ('mediagoblin.tests.testplugins.callables1', {}, []), + ('mediagoblin.tests.testplugins.callables2', {}, []), + ('mediagoblin.tests.testplugins.callables3', {}, []), + ]) + ]) + + mg_globals.app_config = cfg['mediagoblin'] + mg_globals.global_config = cfg + + setup_plugins() + + # Just one hook, check results + call_log = [] + assert pluginapi.callable_runall( + "just_one", call_log) == ["Called just once", None, None] + assert call_log == ["expect this one call"] + + # None provided, check results + call_log = [] + assert pluginapi.callable_runall( + "nothing_handling", call_log) == [] + assert call_log == [] + + # Multiple provided, check results + call_log = [] + assert pluginapi.callable_runall( + "multi_handle", call_log) == [ + "the first returns", + "the second returns", + "the third returns", + ] + assert call_log == [ + "Hi, I'm the first", + "Hi, I'm the second", + "Hi, I'm the third"] + + # Multiple provided, one has CantHandleIt, check results + call_log = [] + assert pluginapi.callable_runall( + "multi_handle_with_canthandle", call_log) == [ + "the second returns", + "the third returns", + ] + assert call_log == [ + "Hi, I'm the second", + "Hi, I'm the third"] diff --git a/mediagoblin/tests/test_session.py b/mediagoblin/tests/test_session.py new file mode 100644 index 00000000..78d790eb --- /dev/null +++ b/mediagoblin/tests/test_session.py @@ -0,0 +1,30 @@ +# GNU MediaGoblin -- federated, autonomous media hosting +# Copyright (C) 2011, 2012 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.tools import session + +def test_session(): + sess = session.Session() + assert not sess + assert not sess.is_updated() + sess['user_id'] = 27 + assert sess + assert not sess.is_updated() + sess.save() + assert sess.is_updated() + sess.delete() + assert not sess + assert sess.is_updated() diff --git a/mediagoblin/tests/test_storage.py b/mediagoblin/tests/test_storage.py index 61326ae9..749f7b07 100644 --- a/mediagoblin/tests/test_storage.py +++ b/mediagoblin/tests/test_storage.py @@ -18,7 +18,7 @@ import os import tempfile -from nose.tools import assert_raises, assert_equal, assert_true +import pytest from werkzeug.utils import secure_filename from mediagoblin import storage @@ -41,10 +41,8 @@ def test_clean_listy_filepath(): assert storage.clean_listy_filepath( ['../../../etc/', 'passwd']) == expected - assert_raises( - storage.InvalidFilepath, - storage.clean_listy_filepath, - ['../../', 'linooks.jpg']) + with pytest.raises(storage.InvalidFilepath): + storage.clean_listy_filepath(['../../', 'linooks.jpg']) class FakeStorageSystem(): @@ -78,10 +76,10 @@ def test_storage_system_from_config(): 'garbage_arg': 'garbage_arg', 'storage_class': 'mediagoblin.tests.test_storage:FakeStorageSystem'}) - assert_equal(this_storage.foobie, 'eiboof') - assert_equal(this_storage.blech, 'hcelb') - assert_equal(unicode(this_storage.__class__), - u'mediagoblin.tests.test_storage.FakeStorageSystem') + assert this_storage.foobie == 'eiboof' + assert this_storage.blech == 'hcelb' + assert unicode(this_storage.__class__) == \ + u'mediagoblin.tests.test_storage.FakeStorageSystem' ########################## @@ -89,7 +87,7 @@ def test_storage_system_from_config(): ########################## def get_tmp_filestorage(mount_url=None, fake_remote=False): - tmpdir = tempfile.mkdtemp() + tmpdir = tempfile.mkdtemp(prefix="test_gmg_storage") if fake_remote: this_storage = FakeRemoteStorage(tmpdir, mount_url) else: @@ -108,11 +106,13 @@ def test_basic_storage__resolve_filepath(): assert result == os.path.join( tmpdir, 'etc/passwd') - assert_raises( + pytest.raises( storage.InvalidFilepath, this_storage._resolve_filepath, ['../../', 'etc', 'passwd']) + os.rmdir(tmpdir) + def test_basic_storage_file_exists(): tmpdir, this_storage = get_tmp_filestorage() @@ -126,6 +126,8 @@ def test_basic_storage_file_exists(): assert not this_storage.file_exists(['dir1', 'dir2', 'thisfile.lol']) assert not this_storage.file_exists(['dnedir1', 'dnedir2', 'somefile.lol']) + this_storage.delete_file(['dir1', 'dir2', 'filename.txt']) + def test_basic_storage_get_unique_filepath(): tmpdir, this_storage = get_tmp_filestorage() @@ -146,6 +148,8 @@ def test_basic_storage_get_unique_filepath(): assert len(new_filename) > len('filename.txt') assert new_filename == secure_filename(new_filename) + os.remove(filename) + def test_basic_storage_get_file(): tmpdir, this_storage = get_tmp_filestorage() @@ -182,6 +186,10 @@ def test_basic_storage_get_file(): with this_storage.get_file(['testydir', 'testyfile.txt']) as testyfile: assert testyfile.read() == 'testy file! so testy.' + this_storage.delete_file(filepath) + this_storage.delete_file(new_filepath) + this_storage.delete_file(['testydir', 'testyfile.txt']) + def test_basic_storage_delete_file(): tmpdir, this_storage = get_tmp_filestorage() @@ -205,10 +213,11 @@ def test_basic_storage_delete_file(): def test_basic_storage_url_for_file(): # Not supplying a base_url should actually just bork. tmpdir, this_storage = get_tmp_filestorage() - assert_raises( + pytest.raises( storage.NoWebServing, this_storage.file_url, ['dir1', 'dir2', 'filename.txt']) + os.rmdir(tmpdir) # base_url without domain tmpdir, this_storage = get_tmp_filestorage('/media/') @@ -216,6 +225,7 @@ def test_basic_storage_url_for_file(): ['dir1', 'dir2', 'filename.txt']) expected = '/media/dir1/dir2/filename.txt' assert result == expected + os.rmdir(tmpdir) # base_url with domain tmpdir, this_storage = get_tmp_filestorage( @@ -224,6 +234,7 @@ def test_basic_storage_url_for_file(): ['dir1', 'dir2', 'filename.txt']) expected = 'http://media.example.org/ourmedia/dir1/dir2/filename.txt' assert result == expected + os.rmdir(tmpdir) def test_basic_storage_get_local_path(): @@ -237,10 +248,13 @@ def test_basic_storage_get_local_path(): assert result == expected + os.rmdir(tmpdir) + def test_basic_storage_is_local(): tmpdir, this_storage = get_tmp_filestorage() assert this_storage.local_storage is True + os.rmdir(tmpdir) def test_basic_storage_copy_locally(): @@ -255,9 +269,13 @@ def test_basic_storage_copy_locally(): new_file_dest = os.path.join(dest_tmpdir, 'file2.txt') this_storage.copy_locally(filepath, new_file_dest) + this_storage.delete_file(filepath) assert file(new_file_dest).read() == 'Testing this file' + os.remove(new_file_dest) + os.rmdir(dest_tmpdir) + def _test_copy_local_to_storage_works(tmpdir, this_storage): local_filename = tempfile.mktemp() @@ -267,10 +285,14 @@ def _test_copy_local_to_storage_works(tmpdir, this_storage): this_storage.copy_local_to_storage( local_filename, ['dir1', 'dir2', 'copiedto.txt']) + os.remove(local_filename) + assert file( os.path.join(tmpdir, 'dir1/dir2/copiedto.txt'), 'r').read() == 'haha' + this_storage.delete_file(['dir1', 'dir2', 'copiedto.txt']) + def test_basic_storage_copy_local_to_storage(): tmpdir, this_storage = get_tmp_filestorage() diff --git a/mediagoblin/tests/test_submission.py b/mediagoblin/tests/test_submission.py index ddb8cefd..ac714252 100644 --- a/mediagoblin/tests/test_submission.py +++ b/mediagoblin/tests/test_submission.py @@ -21,7 +21,6 @@ sys.setdefaultencoding('utf-8') import urlparse import os -from nose.tools import assert_equal, assert_true from pkg_resources import resource_filename from mediagoblin.tests.tools import fixture_add_user @@ -87,7 +86,7 @@ class TestSubmission: def check_comments(self, request, media_id, count): comments = request.db.MediaComment.find({'media_entry': media_id}) - assert_equal(count, len(list(comments))) + assert count == len(list(comments)) def test_missing_fields(self, test_app): self._setup(test_app) @@ -95,21 +94,21 @@ class TestSubmission: # Test blank form # --------------- response, form = self.do_post({}, *FORM_CONTEXT) - assert_equal(form.file.errors, [u'You must provide a file.']) + assert form.file.errors == [u'You must provide a file.'] # Test blank file # --------------- response, form = self.do_post({'title': u'test title'}, *FORM_CONTEXT) - assert_equal(form.file.errors, [u'You must provide a file.']) + assert form.file.errors == [u'You must provide a file.'] def check_url(self, response, path): - assert_equal(urlparse.urlsplit(response.location)[2], path) + assert urlparse.urlsplit(response.location)[2] == path def check_normal_upload(self, title, filename): response, context = self.do_post({'title': title}, do_follow=True, **self.upload_data(filename)) self.check_url(response, '/u/{0}/'.format(self.test_user.username)) - assert_true('mediagoblin/user_pages/user.html' in context) + assert 'mediagoblin/user_pages/user.html' in context # Make sure the media view is at least reachable, logged in... url = '/u/{0}/m/{1}/'.format(self.test_user.username, title.lower().replace(' ', '-')) @@ -129,7 +128,7 @@ class TestSubmission: def check_media(self, request, find_data, count=None): media = MediaEntry.find(find_data) if count is not None: - assert_equal(media.count(), count) + assert media.count() == count if count == 0: return return media[0] @@ -156,10 +155,10 @@ class TestSubmission: 'tags': BAD_TAG_STRING}, *FORM_CONTEXT, **self.upload_data(GOOD_JPG)) - assert_equal(form.tags.errors, [ + assert form.tags.errors == [ u'Tags must be shorter than 50 characters. ' \ 'Tags that are too long: ' \ - 'ffffffffffffffffffffffffffuuuuuuuuuuuuuuuuuuuuuuuuuu']) + 'ffffffffffffffffffffffffffuuuuuuuuuuuuuuuuuuuuuuuuuu'] def test_delete(self, test_app): self._setup(test_app) @@ -180,7 +179,7 @@ class TestSubmission: 'slug': u"Balanced=Goblin", 'tags': u''}) media = self.check_media(request, {'title': u'Balanced Goblin'}, 1) - assert_equal(media.slug, u"balanced-goblin") + assert media.slug == u"balanced-goblin" # Add a comment, so we can test for its deletion later. self.check_comments(request, media_id, 0) @@ -216,7 +215,7 @@ class TestSubmission: response, form = self.do_post({'title': u'Malicious Upload 1'}, *FORM_CONTEXT, **self.upload_data(EVIL_FILE)) - assert_equal(len(form.file.errors), 1) + assert len(form.file.errors) == 1 assert 'Sorry, I don\'t support that file type :(' == \ str(form.file.errors[0]) @@ -231,8 +230,8 @@ class TestSubmission: **self.upload_data(GOOD_JPG)) media = self.check_media(request, {'title': u'Balanced Goblin'}, 1) - assert_equal(media.media_type, u'mediagoblin.media_types.image') - assert_equal(media.media_manager, img_MEDIA_MANAGER) + assert media.media_type == u'mediagoblin.media_types.image' + assert media.media_manager == img_MEDIA_MANAGER def test_sniffing(self, test_app): @@ -267,8 +266,8 @@ class TestSubmission: **self.upload_data(filename)) self.check_url(response, '/u/{0}/'.format(self.test_user.username)) entry = mg_globals.database.MediaEntry.find_one({'title': title}) - assert_equal(entry.state, 'failed') - assert_equal(entry.fail_error, u'mediagoblin.processing:BadMediaFail') + assert entry.state == 'failed' + assert entry.fail_error == u'mediagoblin.processing:BadMediaFail' def test_evil_jpg(self, test_app): self._setup(test_app) @@ -289,7 +288,7 @@ class TestSubmission: self.check_normal_upload(u"With GPS data", GPS_JPG) media = self.check_media(None, {"title": u"With GPS data"}, 1) - assert_equal(media.media_data.gps_latitude, 59.336666666666666) + assert media.media_data.gps_latitude == 59.336666666666666 def test_processing(self, test_app): self._setup(test_app) @@ -309,8 +308,8 @@ class TestSubmission: filename = os.path.join( public_store_dir, *media.media_files.get(key, [])) - assert_true(filename.endswith('_' + basename)) + assert filename.endswith('_' + basename) # Is it smaller than the last processed image we looked at? size = os.stat(filename).st_size - assert_true(last_size > size) + assert last_size > size last_size = size diff --git a/mediagoblin/tests/test_timesince.py b/mediagoblin/tests/test_timesince.py new file mode 100644 index 00000000..1f8a082b --- /dev/null +++ b/mediagoblin/tests/test_timesince.py @@ -0,0 +1,57 @@ +# GNU MediaGoblin -- federated, autonomous media hosting +# Copyright (C) 2011, 2012 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 datetime import datetime, timedelta + +from mediagoblin.tools.timesince import is_aware, timesince + + +def test_timesince(test_app): + test_time = datetime.now() + + # it should ignore second and microseconds + assert timesince(test_time, test_time + timedelta(microseconds=1)) == "0 minutes" + assert timesince(test_time, test_time + timedelta(seconds=1)) == "0 minutes" + + # test minutes, hours, days, weeks, months and years (singular and plural) + assert timesince(test_time, test_time + timedelta(minutes=1)) == "1 minute" + assert timesince(test_time, test_time + timedelta(minutes=2)) == "2 minutes" + + assert timesince(test_time, test_time + timedelta(hours=1)) == "1 hour" + assert timesince(test_time, test_time + timedelta(hours=2)) == "2 hours" + + assert timesince(test_time, test_time + timedelta(days=1)) == "1 day" + assert timesince(test_time, test_time + timedelta(days=2)) == "2 days" + + assert timesince(test_time, test_time + timedelta(days=7)) == "1 week" + assert timesince(test_time, test_time + timedelta(days=14)) == "2 weeks" + + assert timesince(test_time, test_time + timedelta(days=30)) == "1 month" + assert timesince(test_time, test_time + timedelta(days=60)) == "2 months" + + assert timesince(test_time, test_time + timedelta(days=365)) == "1 year" + assert timesince(test_time, test_time + timedelta(days=730)) == "2 years" + + # okay now we want to test combinations + # e.g. 1 hour, 5 days + assert timesince(test_time, test_time + timedelta(days=5, hours=1)) == "5 days, 1 hour" + + assert timesince(test_time, test_time + timedelta(days=15)) == "2 weeks, 1 day" + + assert timesince(test_time, test_time + timedelta(days=97)) == "3 months, 1 week" + + assert timesince(test_time, test_time + timedelta(days=2250)) == "6 years, 2 months" + diff --git a/mediagoblin/tests/test_workbench.py b/mediagoblin/tests/test_workbench.py index 3b2fc2c6..9cd49671 100644 --- a/mediagoblin/tests/test_workbench.py +++ b/mediagoblin/tests/test_workbench.py @@ -26,8 +26,13 @@ from mediagoblin.tests.test_storage import get_tmp_filestorage class TestWorkbench(object): def setup(self): + self.workbench_base = tempfile.mkdtemp(prefix='gmg_workbench_testing') self.workbench_manager = workbench.WorkbenchManager( - os.path.join(tempfile.gettempdir(), u'mgoblin_workbench_testing')) + self.workbench_base) + + def teardown(self): + # If the workbench is empty, this should work. + os.rmdir(self.workbench_base) def test_create_workbench(self): workbench = self.workbench_manager.create() @@ -70,6 +75,7 @@ class TestWorkbench(object): filename = this_workbench.localized_file(this_storage, filepath) assert filename == os.path.join( tmpdir, 'dir1/dir2/ourfile.txt') + this_storage.delete_file(filepath) # with a fake remote file storage tmpdir, this_storage = get_tmp_filestorage(fake_remote=True) @@ -95,6 +101,9 @@ class TestWorkbench(object): assert filename == os.path.join( this_workbench.dir, 'thisfile.text') + this_storage.delete_file(filepath) + this_workbench.destroy() + def test_workbench_decorator(self): """Test @get_workbench decorator and automatic cleanup""" # The decorator needs mg_globals.workbench_manager diff --git a/mediagoblin/tests/testplugins/__init__.py b/mediagoblin/tests/testplugins/__init__.py new file mode 100644 index 00000000..621845ba --- /dev/null +++ b/mediagoblin/tests/testplugins/__init__.py @@ -0,0 +1,15 @@ +# GNU MediaGoblin -- federated, autonomous media hosting +# Copyright (C) 2011, 2012 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/>. diff --git a/mediagoblin/tests/testplugins/callables1/__init__.py b/mediagoblin/tests/testplugins/callables1/__init__.py new file mode 100644 index 00000000..9c278b49 --- /dev/null +++ b/mediagoblin/tests/testplugins/callables1/__init__.py @@ -0,0 +1,41 @@ +# GNU MediaGoblin -- federated, autonomous media hosting +# Copyright (C) 2011, 2012 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.tools.pluginapi import CantHandleIt + +def setup_plugin(): + pass + + +def just_one(call_log): + call_log.append("expect this one call") + return "Called just once" + + +def multi_handle(call_log): + call_log.append("Hi, I'm the first") + return "the first returns" + +def multi_handle_with_canthandle(call_log): + raise CantHandleIt("I just can't accept this stupid method") + + +hooks = { + 'setup': setup_plugin, + 'just_one': just_one, + 'multi_handle': multi_handle, + 'multi_handle_with_canthandle': multi_handle_with_canthandle, + } diff --git a/mediagoblin/tests/testplugins/callables2/__init__.py b/mediagoblin/tests/testplugins/callables2/__init__.py new file mode 100644 index 00000000..aaab5b21 --- /dev/null +++ b/mediagoblin/tests/testplugins/callables2/__init__.py @@ -0,0 +1,38 @@ +# GNU MediaGoblin -- federated, autonomous media hosting +# Copyright (C) 2011, 2012 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/>. + +def setup_plugin(): + pass + + +def just_one(call_log): + assert "SHOULD NOT HAPPEN" + +def multi_handle(call_log): + call_log.append("Hi, I'm the second") + return "the second returns" + +def multi_handle_with_canthandle(call_log): + call_log.append("Hi, I'm the second") + return "the second returns" + + +hooks = { + 'setup': setup_plugin, + 'just_one': just_one, + 'multi_handle': multi_handle, + 'multi_handle_with_canthandle': multi_handle_with_canthandle, + } diff --git a/mediagoblin/tests/testplugins/callables3/__init__.py b/mediagoblin/tests/testplugins/callables3/__init__.py new file mode 100644 index 00000000..8d0c9c25 --- /dev/null +++ b/mediagoblin/tests/testplugins/callables3/__init__.py @@ -0,0 +1,38 @@ +# GNU MediaGoblin -- federated, autonomous media hosting +# Copyright (C) 2011, 2012 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/>. + +def setup_plugin(): + pass + + +def just_one(call_log): + assert "SHOULD NOT HAPPEN" + +def multi_handle(call_log): + call_log.append("Hi, I'm the third") + return "the third returns" + +def multi_handle_with_canthandle(call_log): + call_log.append("Hi, I'm the third") + return "the third returns" + + +hooks = { + 'setup': setup_plugin, + 'just_one': just_one, + 'multi_handle': multi_handle, + 'multi_handle_with_canthandle': multi_handle_with_canthandle, + } diff --git a/mediagoblin/tests/tools.py b/mediagoblin/tests/tools.py index b68d55e8..52635e18 100644 --- a/mediagoblin/tests/tools.py +++ b/mediagoblin/tests/tools.py @@ -45,14 +45,13 @@ TEST_USER_DEV = pkg_resources.resource_filename( 'mediagoblin.tests', 'test_user_dev') -USER_DEV_DIRECTORIES_TO_SETUP = [ - 'media/public', 'media/queue', - 'beaker/sessions/data', 'beaker/sessions/lock'] +USER_DEV_DIRECTORIES_TO_SETUP = ['media/public', 'media/queue'] BAD_CELERY_MESSAGE = """\ Sorry, you *absolutely* must run tests with the mediagoblin.init.celery.from_tests module. Like so: -$ CELERY_CONFIG_MODULE=mediagoblin.init.celery.from_tests {0}\ + +$ CELERY_CONFIG_MODULE=mediagoblin.init.celery.from_tests {0} """.format(sys.argv[0]) |