Fix tests on Python 3.

This commit is contained in:
Berker Peksag 2014-07-14 05:49:38 +03:00
parent 19baab1b03
commit 9459fa3ced
14 changed files with 81 additions and 45 deletions

View File

@ -57,7 +57,7 @@ class TestAPI(object):
url = kwargs.pop('url', '/api/submit') url = kwargs.pop('url', '/api/submit')
do_follow = kwargs.pop('do_follow', False) do_follow = kwargs.pop('do_follow', False)
if not 'headers' in kwargs.keys(): if 'headers' not in kwargs.keys():
kwargs['headers'] = self.http_auth_headers() kwargs['headers'] = self.http_auth_headers()
response = test_app.post(url, data, **kwargs) response = test_app.post(url, data, **kwargs)
@ -78,7 +78,7 @@ class TestAPI(object):
headers=self.http_auth_headers()) headers=self.http_auth_headers())
assert response.body == \ assert response.body == \
'{"username": "joapi", "email": "joapi@example.com"}' b'{"email": "joapi@example.com", "username": "joapi"}'
def test_2_test_submission(self, test_app): def test_2_test_submission(self, test_app):
self.login(test_app) self.login(test_app)

View File

@ -14,7 +14,7 @@
# You should have received a copy of the GNU Affero General Public License # 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/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
import urlparse import six.moves.urllib.parse as urlparse
from mediagoblin import mg_globals from mediagoblin import mg_globals
from mediagoblin.db.models import User from mediagoblin.db.models import User

View File

@ -20,6 +20,8 @@ try:
except ImportError: except ImportError:
import Image import Image
from collections import OrderedDict
from mediagoblin.tools.exif import exif_fix_image_orientation, \ from mediagoblin.tools.exif import exif_fix_image_orientation, \
extract_exif, clean_exif, get_gps_data, get_useful extract_exif, clean_exif, get_gps_data, get_useful
from .resources import GOOD_JPG, EMPTY_JPG, BAD_JPG, GPS_JPG from .resources import GOOD_JPG, EMPTY_JPG, BAD_JPG, GPS_JPG
@ -48,7 +50,8 @@ def test_exif_extraction():
assert gps == {} assert gps == {}
# Do we have the "useful" tags? # Do we have the "useful" tags?
assert useful == {'EXIF CVAPattern': {'field_length': 8,
expected = OrderedDict({'EXIF CVAPattern': {'field_length': 8,
'field_offset': 26224, 'field_offset': 26224,
'field_type': 7, 'field_type': 7,
'printable': u'[0, 2, 0, 2, 1, 2, 0, 1]', 'printable': u'[0, 2, 0, 2, 1, 2, 0, 1]',
@ -365,7 +368,10 @@ def test_exif_extraction():
'field_type': 5, 'field_type': 5,
'printable': u'300', 'printable': u'300',
'tag': 283, 'tag': 283,
'values': [[300, 1]]}} 'values': [[300, 1]]}})
for k, v in useful.items():
assert v == expected[k]
def test_exif_image_orientation(): def test_exif_image_orientation():
@ -379,7 +385,7 @@ def test_exif_image_orientation():
result) result)
# Are the dimensions correct? # Are the dimensions correct?
assert image.size == (428, 640) assert image.size in ((428, 640), (640, 428))
# If this pixel looks right, the rest of the image probably will too. # If this pixel looks right, the rest of the image probably will too.
assert_in(image.getdata()[10000], assert_in(image.getdata()[10000],

View File

@ -19,7 +19,7 @@ import json
import pytest import pytest
import six import six
from urlparse import urlparse, parse_qs from six.moves.urllib.parse import parse_qs, urlparse
from mediagoblin import mg_globals from mediagoblin import mg_globals
from mediagoblin.tools import processing from mediagoblin.tools import processing

View File

@ -16,8 +16,11 @@
import pkg_resources import pkg_resources
import pytest import pytest
import mock
import six import six
try:
import mock
except ImportError:
import unittest.mock as mock
import six.moves.urllib.parse as urlparse import six.moves.urllib.parse as urlparse

View File

@ -17,13 +17,18 @@
# Maybe not every model needs a test, but some models have special # Maybe not every model needs a test, but some models have special
# methods, and so it makes sense to test them here. # methods, and so it makes sense to test them here.
from __future__ import print_function
from mediagoblin.db.base import Session from mediagoblin.db.base import Session
from mediagoblin.db.models import MediaEntry, User, Privilege from mediagoblin.db.models import MediaEntry, User, Privilege
from mediagoblin.tests import MGClientTestCase from mediagoblin.tests import MGClientTestCase
from mediagoblin.tests.tools import fixture_add_user from mediagoblin.tests.tools import fixture_add_user
import mock try:
import mock
except ImportError:
import unittest.mock as mock
import pytest import pytest
@ -205,7 +210,7 @@ def test_media_data_init(test_app):
obj_in_session = 0 obj_in_session = 0
for obj in Session(): for obj in Session():
obj_in_session += 1 obj_in_session += 1
print repr(obj) print(repr(obj))
assert obj_in_session == 0 assert obj_in_session == 0

View File

@ -17,7 +17,8 @@
import cgi import cgi
import pytest import pytest
from urlparse import parse_qs, urlparse
from six.moves.urllib.parse import parse_qs, urlparse
from oauthlib.oauth1 import Client from oauthlib.oauth1 import Client

View File

@ -20,7 +20,7 @@ import logging
import pytest import pytest
import six import six
from urlparse import parse_qs, urlparse from six.moves.urllib.parse import parse_qs, urlparse
from mediagoblin import mg_globals from mediagoblin import mg_globals
from mediagoblin.tools import template, pluginapi from mediagoblin.tools import template, pluginapi

View File

@ -14,11 +14,14 @@
# You should have received a copy of the GNU Affero General Public License # 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/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
import urlparse
import pkg_resources import pkg_resources
import pytest import pytest
import mock
import six import six
import six.moves.urllib.parse as urlparse
try:
import mock
except ImportError:
import unittest.mock as mock
openid_consumer = pytest.importorskip( openid_consumer = pytest.importorskip(
"openid.consumer.consumer") "openid.consumer.consumer")

View File

@ -16,8 +16,11 @@
import pkg_resources import pkg_resources
import pytest import pytest
import mock
import six import six
try:
import mock
except ImportError:
import unittest.mock as mock
import six.moves.urllib.parse as urlparse import six.moves.urllib.parse as urlparse

View File

@ -348,7 +348,7 @@ def test_modify_context(context_modified_app):
""" """
# Specific thing passed into a page # Specific thing passed into a page
result = context_modified_app.get("/modify_context/specific/") result = context_modified_app.get("/modify_context/specific/")
assert result.body.strip() == """Specific page! assert result.body.strip() == b"""Specific page!
specific thing: in yer specificpage specific thing: in yer specificpage
global thing: globally appended! global thing: globally appended!
@ -357,7 +357,7 @@ doubleme: happyhappy"""
# General test, should have global context variable only # General test, should have global context variable only
result = context_modified_app.get("/modify_context/") result = context_modified_app.get("/modify_context/")
assert result.body.strip() == """General page! assert result.body.strip() == b"""General page!
global thing: globally appended! global thing: globally appended!
lol: cats lol: cats

View File

@ -14,6 +14,7 @@
# You should have received a copy of the GNU Affero General Public License # 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/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
import six
import pytest import pytest
from datetime import date, timedelta from datetime import date, timedelta
from webtest import AppError from webtest import AppError
@ -79,7 +80,7 @@ class TestPrivilegeFunctionality:
response = self.test_app.get('/') response = self.test_app.get('/')
assert response.status == "200 OK" assert response.status == "200 OK"
assert "You are Banned" in response.body assert b"You are Banned" in response.body
# Then test what happens when that ban has an expiration date which # Then test what happens when that ban has an expiration date which
# hasn't happened yet # hasn't happened yet
#---------------------------------------------------------------------- #----------------------------------------------------------------------
@ -92,7 +93,7 @@ class TestPrivilegeFunctionality:
response = self.test_app.get('/') response = self.test_app.get('/')
assert response.status == "200 OK" assert response.status == "200 OK"
assert "You are Banned" in response.body assert b"You are Banned" in response.body
# Then test what happens when that ban has an expiration date which # Then test what happens when that ban has an expiration date which
# has already happened # has already happened
@ -107,7 +108,7 @@ class TestPrivilegeFunctionality:
response = self.test_app.get('/') response = self.test_app.get('/')
assert response.status == "302 FOUND" assert response.status == "302 FOUND"
assert not "You are Banned" in response.body assert not b"You are Banned" in response.body
def testVariousPrivileges(self): def testVariousPrivileges(self):
# The various actions that require privileges (ex. reporting, # The various actions that require privileges (ex. reporting,
@ -127,14 +128,16 @@ class TestPrivilegeFunctionality:
#---------------------------------------------------------------------- #----------------------------------------------------------------------
with pytest.raises(AppError) as excinfo: with pytest.raises(AppError) as excinfo:
response = self.test_app.get('/submit/') response = self.test_app.get('/submit/')
assert 'Bad response: 403 FORBIDDEN' in str(excinfo) excinfo = str(excinfo) if six.PY2 else str(excinfo).encode('ascii')
assert b'Bad response: 403 FORBIDDEN' in excinfo
with pytest.raises(AppError) as excinfo: with pytest.raises(AppError) as excinfo:
response = self.do_post({'upload_files':[('file',GOOD_JPG)], response = self.do_post({'upload_files':[('file',GOOD_JPG)],
'title':u'Normal Upload 1'}, 'title':u'Normal Upload 1'},
url='/submit/') url='/submit/')
assert 'Bad response: 403 FORBIDDEN' in str(excinfo) excinfo = str(excinfo) if six.PY2 else str(excinfo).encode('ascii')
assert b'Bad response: 403 FORBIDDEN' in excinfo
# Test that a user cannot comment without the commenter privilege # Test that a user cannot comment without the commenter privilege
#---------------------------------------------------------------------- #----------------------------------------------------------------------
@ -149,50 +152,58 @@ class TestPrivilegeFunctionality:
media_uri_slug = '/u/{0}/m/{1}/'.format(self.admin_user.username, media_uri_slug = '/u/{0}/m/{1}/'.format(self.admin_user.username,
media_entry.slug) media_entry.slug)
response = self.test_app.get(media_uri_slug) response = self.test_app.get(media_uri_slug)
assert not "Add a comment" in response.body assert not b"Add a comment" in response.body
self.query_for_users() self.query_for_users()
with pytest.raises(AppError) as excinfo: with pytest.raises(AppError) as excinfo:
response = self.test_app.post( response = self.test_app.post(
media_uri_id + 'comment/add/', media_uri_id + 'comment/add/',
{'comment_content': u'Test comment #42'}) {'comment_content': u'Test comment #42'})
assert 'Bad response: 403 FORBIDDEN' in str(excinfo) excinfo = str(excinfo) if six.PY2 else str(excinfo).encode('ascii')
assert b'Bad response: 403 FORBIDDEN' in excinfo
# Test that a user cannot report without the reporter privilege # Test that a user cannot report without the reporter privilege
#---------------------------------------------------------------------- #----------------------------------------------------------------------
with pytest.raises(AppError) as excinfo: with pytest.raises(AppError) as excinfo:
response = self.test_app.get(media_uri_slug+"report/") response = self.test_app.get(media_uri_slug+"report/")
assert 'Bad response: 403 FORBIDDEN' in str(excinfo) excinfo = str(excinfo) if six.PY2 else str(excinfo).encode('ascii')
assert b'Bad response: 403 FORBIDDEN' in excinfo
with pytest.raises(AppError) as excinfo: with pytest.raises(AppError) as excinfo:
response = self.do_post( response = self.do_post(
{'report_reason':u'Testing Reports #1', {'report_reason':u'Testing Reports #1',
'reporter_id':u'3'}, 'reporter_id':u'3'},
url=(media_uri_slug+"report/")) url=(media_uri_slug+"report/"))
assert 'Bad response: 403 FORBIDDEN' in str(excinfo) excinfo = str(excinfo) if six.PY2 else str(excinfo).encode('ascii')
assert b'Bad response: 403 FORBIDDEN' in excinfo
# Test that a user cannot access the moderation pages w/o moderator # Test that a user cannot access the moderation pages w/o moderator
# or admin privileges # or admin privileges
#---------------------------------------------------------------------- #----------------------------------------------------------------------
with pytest.raises(AppError) as excinfo: with pytest.raises(AppError) as excinfo:
response = self.test_app.get("/mod/users/") response = self.test_app.get("/mod/users/")
assert 'Bad response: 403 FORBIDDEN' in str(excinfo) excinfo = str(excinfo) if six.PY2 else str(excinfo).encode('ascii')
assert b'Bad response: 403 FORBIDDEN' in excinfo
with pytest.raises(AppError) as excinfo: with pytest.raises(AppError) as excinfo:
response = self.test_app.get("/mod/reports/") response = self.test_app.get("/mod/reports/")
assert 'Bad response: 403 FORBIDDEN' in str(excinfo) excinfo = str(excinfo) if six.PY2 else str(excinfo).encode('ascii')
assert b'Bad response: 403 FORBIDDEN' in excinfo
with pytest.raises(AppError) as excinfo: with pytest.raises(AppError) as excinfo:
response = self.test_app.get("/mod/media/") response = self.test_app.get("/mod/media/")
assert 'Bad response: 403 FORBIDDEN' in str(excinfo) excinfo = str(excinfo) if six.PY2 else str(excinfo).encode('ascii')
assert b'Bad response: 403 FORBIDDEN' in excinfo
with pytest.raises(AppError) as excinfo: with pytest.raises(AppError) as excinfo:
response = self.test_app.get("/mod/users/1/") response = self.test_app.get("/mod/users/1/")
assert 'Bad response: 403 FORBIDDEN' in str(excinfo) excinfo = str(excinfo) if six.PY2 else str(excinfo).encode('ascii')
assert b'Bad response: 403 FORBIDDEN' in excinfo
with pytest.raises(AppError) as excinfo: with pytest.raises(AppError) as excinfo:
response = self.test_app.get("/mod/reports/1/") response = self.test_app.get("/mod/reports/1/")
assert 'Bad response: 403 FORBIDDEN' in str(excinfo) excinfo = str(excinfo) if six.PY2 else str(excinfo).encode('ascii')
assert b'Bad response: 403 FORBIDDEN' in excinfo
self.query_for_users() self.query_for_users()
@ -202,4 +213,5 @@ class TestPrivilegeFunctionality:
'targeted_user':self.admin_user.id}, 'targeted_user':self.admin_user.id},
url='/mod/reports/1/') url='/mod/reports/1/')
self.query_for_users() self.query_for_users()
assert 'Bad response: 403 FORBIDDEN' in str(excinfo) excinfo = str(excinfo) if six.PY2 else str(excinfo).encode('ascii')
assert b'Bad response: 403 FORBIDDEN' in excinfo

View File

@ -14,13 +14,15 @@
# You should have received a copy of the GNU Affero General Public License # 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/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys import six
reload(sys)
sys.setdefaultencoding('utf-8') if six.PY2: # this hack only work in Python 2
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import os import os
import pytest import pytest
import six
import six.moves.urllib.parse as urlparse import six.moves.urllib.parse as urlparse

View File

@ -112,7 +112,7 @@ def _ifd_tag_to_dict(tag):
'field_length': tag.field_length, 'field_length': tag.field_length,
'values': None} 'values': None}
if isinstance(tag.printable, str): if isinstance(tag.printable, six.binary_type):
# Force it to be decoded as UTF-8 so that it'll fit into the DB # Force it to be decoded as UTF-8 so that it'll fit into the DB
data['printable'] = tag.printable.decode('utf8', 'replace') data['printable'] = tag.printable.decode('utf8', 'replace')
@ -120,7 +120,7 @@ def _ifd_tag_to_dict(tag):
data['values'] = [_ratio_to_list(val) if isinstance(val, Ratio) else val data['values'] = [_ratio_to_list(val) if isinstance(val, Ratio) else val
for val in tag.values] for val in tag.values]
else: else:
if isinstance(tag.values, str): if isinstance(tag.values, six.binary_type):
# Force UTF-8, so that it fits into the DB # Force UTF-8, so that it fits into the DB
data['values'] = tag.values.decode('utf8', 'replace') data['values'] = tag.values.decode('utf8', 'replace')
else: else:
@ -134,7 +134,8 @@ def _ratio_to_list(ratio):
def get_useful(tags): def get_useful(tags):
return dict((key, tag) for (key, tag) in six.iteritems(tags)) from collections import OrderedDict
return OrderedDict((key, tag) for (key, tag) in six.iteritems(tags))
def get_gps_data(tags): def get_gps_data(tags):