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')
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()
response = test_app.post(url, data, **kwargs)
@ -78,7 +78,7 @@ class TestAPI(object):
headers=self.http_auth_headers())
assert response.body == \
'{"username": "joapi", "email": "joapi@example.com"}'
b'{"email": "joapi@example.com", "username": "joapi"}'
def test_2_test_submission(self, 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
# 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.db.models import User

View File

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

View File

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

View File

@ -16,8 +16,11 @@
import pkg_resources
import pytest
import mock
import six
try:
import mock
except ImportError:
import unittest.mock as mock
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
# methods, and so it makes sense to test them here.
from __future__ import print_function
from mediagoblin.db.base import Session
from mediagoblin.db.models import MediaEntry, User, Privilege
from mediagoblin.tests import MGClientTestCase
from mediagoblin.tests.tools import fixture_add_user
import mock
try:
import mock
except ImportError:
import unittest.mock as mock
import pytest
@ -205,7 +210,7 @@ def test_media_data_init(test_app):
obj_in_session = 0
for obj in Session():
obj_in_session += 1
print repr(obj)
print(repr(obj))
assert obj_in_session == 0

View File

@ -17,7 +17,8 @@
import cgi
import pytest
from urlparse import parse_qs, urlparse
from six.moves.urllib.parse import parse_qs, urlparse
from oauthlib.oauth1 import Client
@ -52,8 +53,8 @@ class TestOAuth(object):
def register_client(self, **kwargs):
""" Regiters a client with the API """
kwargs["type"] = "client_associate"
kwargs["type"] = "client_associate"
kwargs["application_type"] = kwargs.get("application_type", "native")
return self.test_app.post("/api/client/register", kwargs)
@ -63,7 +64,7 @@ class TestOAuth(object):
client_info = response.json
client = self.db.Client.query.filter_by(id=client_info["client_id"]).first()
assert response.status_int == 200
assert client is not None
@ -81,7 +82,7 @@ class TestOAuth(object):
client_info = response.json
client = self.db.Client.query.filter_by(id=client_info["client_id"]).first()
assert client is not None
assert client.secret == client_info["client_secret"]
assert client.application_type == query["application_type"]
@ -163,4 +164,4 @@ class TestOAuth(object):
assert request_token.client == client.id
assert request_token.used == False
assert request_token.callback == request_query["oauth_callback"]

View File

@ -20,7 +20,7 @@ import logging
import pytest
import six
from urlparse import parse_qs, urlparse
from six.moves.urllib.parse import parse_qs, urlparse
from mediagoblin import mg_globals
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
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import urlparse
import pkg_resources
import pytest
import mock
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.consumer")

View File

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

View File

@ -224,7 +224,7 @@ def test_hook_handle():
assert pluginapi.hook_handle(
"nothing_handling", call_log, unhandled_okay=True) is None
assert call_log == []
# Multiple provided, go with the first!
call_log = []
assert pluginapi.hook_handle(
@ -348,7 +348,7 @@ def test_modify_context(context_modified_app):
"""
# Specific thing passed into a page
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
global thing: globally appended!
@ -357,7 +357,7 @@ doubleme: happyhappy"""
# General test, should have global context variable only
result = context_modified_app.get("/modify_context/")
assert result.body.strip() == """General page!
assert result.body.strip() == b"""General page!
global thing: globally appended!
lol: cats

View File

@ -14,6 +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/>.
import six
import pytest
from datetime import date, timedelta
from webtest import AppError
@ -79,7 +80,7 @@ class TestPrivilegeFunctionality:
response = self.test_app.get('/')
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
# hasn't happened yet
#----------------------------------------------------------------------
@ -92,7 +93,7 @@ class TestPrivilegeFunctionality:
response = self.test_app.get('/')
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
# has already happened
@ -107,7 +108,7 @@ class TestPrivilegeFunctionality:
response = self.test_app.get('/')
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):
# The various actions that require privileges (ex. reporting,
@ -127,14 +128,16 @@ class TestPrivilegeFunctionality:
#----------------------------------------------------------------------
with pytest.raises(AppError) as excinfo:
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:
response = self.do_post({'upload_files':[('file',GOOD_JPG)],
'title':u'Normal Upload 1'},
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
#----------------------------------------------------------------------
@ -149,50 +152,58 @@ class TestPrivilegeFunctionality:
media_uri_slug = '/u/{0}/m/{1}/'.format(self.admin_user.username,
media_entry.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()
with pytest.raises(AppError) as excinfo:
response = self.test_app.post(
media_uri_id + 'comment/add/',
{'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
#----------------------------------------------------------------------
with pytest.raises(AppError) as excinfo:
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:
response = self.do_post(
{'report_reason':u'Testing Reports #1',
'reporter_id':u'3'},
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
# or admin privileges
#----------------------------------------------------------------------
with pytest.raises(AppError) as excinfo:
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:
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:
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:
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:
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()
@ -202,4 +213,5 @@ class TestPrivilegeFunctionality:
'targeted_user':self.admin_user.id},
url='/mod/reports/1/')
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
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import six
if six.PY2: # this hack only work in Python 2
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import os
import pytest
import six
import six.moves.urllib.parse as urlparse

View File

@ -112,7 +112,7 @@ def _ifd_tag_to_dict(tag):
'field_length': tag.field_length,
'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
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
for val in tag.values]
else:
if isinstance(tag.values, str):
if isinstance(tag.values, six.binary_type):
# Force UTF-8, so that it fits into the DB
data['values'] = tag.values.decode('utf8', 'replace')
else:
@ -134,7 +134,8 @@ def _ratio_to_list(ratio):
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):