Skip to content

Commit 7bbb4a5

Browse files
author
Mike Dirolf
committed
python 2.3 support
mostly not using unittest.assertTrue and assertFalse. also not using decorator syntax, and some missing built-ins (sorted, etc.)
1 parent 75fb46a commit 7bbb4a5

19 files changed

+135
-119
lines changed

gridfs/grid_file.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -110,13 +110,13 @@ def __erase(self):
110110

111111
self.__collection.chunks.remove({"files_id": self.__id})
112112

113-
@property
114113
def closed(self):
115114
return self.__closed
115+
closed = property(closed)
116116

117-
@property
118117
def mode(self):
119118
return self.__mode
119+
mode = property(mode)
120120

121121
def __create_property(field_name, read_only=False):
122122
def getter(self):

pymongo/bson.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -408,7 +408,6 @@ def __new__(cls, bson):
408408
"""
409409
return str.__new__(cls, bson)
410410

411-
@classmethod
412411
def from_dict(cls, dict):
413412
"""Create a new BSON object from a python mapping type (like dict).
414413
@@ -420,6 +419,7 @@ def from_dict(cls, dict):
420419
- `dict`: mapping type representing a Mongo document
421420
"""
422421
return cls(_dict_to_bson(dict))
422+
from_dict = classmethod(from_dict)
423423

424424
def to_dict(self):
425425
"""Get the dictionary representation of this data."""

pymongo/connection.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,10 @@
1414

1515
"""Low level connection to Mongo."""
1616

17+
import sys
1718
import socket
1819
import struct
1920
import types
20-
import traceback
2121
import logging
2222
import threading
2323
import random
@@ -116,7 +116,6 @@ def __pair_with(self, host, port):
116116

117117
self.__find_master()
118118

119-
@classmethod
120119
def paired(cls, left, right=("localhost", 27017),
121120
pool_size=1, auto_start_request=True):
122121
"""Open a new paired connection to Mongo.
@@ -134,6 +133,7 @@ def paired(cls, left, right=("localhost", 27017),
134133
_connect=False)
135134
connection.__pair_with(*right)
136135
return connection
136+
paired = classmethod(paired)
137137

138138
def __increment_id(self):
139139
self.__id_lock.acquire()
@@ -152,7 +152,7 @@ def __master(self, sock):
152152
if result["ismaster"] == 1:
153153
return True
154154
else:
155-
strings = result["remote"].rsplit(":", 1)
155+
strings = result["remote"].split(":", 1)
156156
if len(strings) == 1:
157157
port = 27017
158158
else:
@@ -197,8 +197,9 @@ def __find_master(self):
197197
((host, port), master))
198198
_logger.debug("not master, master is (%r, %r)" % master)
199199
except socket.error:
200-
_logger.debug("could not connect, got: %s" %
201-
traceback.format_exc())
200+
exctype, value = sys.exc_info()[:2]
201+
_logger.debug("could not connect, got: %s %s" %
202+
(exctype, value))
202203
continue
203204
finally:
204205
sock.close()
@@ -273,8 +274,8 @@ def __pick_and_acquire_socket(self):
273274
"""
274275
choices = range(self.__pool_size)
275276
random.shuffle(choices)
276-
choices = sorted(choices, lambda x, y: cmp(self.__thread_count[x],
277-
self.__thread_count[y]))
277+
choices.sort(lambda x, y: cmp(self.__thread_count[x],
278+
self.__thread_count[y]))
278279

279280
for choice in choices:
280281
if self.__locks[choice].acquire(False):

pymongo/objectid.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,6 @@ def url_encode(self):
7272
"""
7373
return self.__id.encode("hex")
7474

75-
@classmethod
7675
def url_decode(cls, encoded_oid):
7776
"""Create an ObjectId from an encoded hex string.
7877
@@ -83,6 +82,7 @@ def url_decode(cls, encoded_oid):
8382
by `url_encode()`)
8483
"""
8584
return cls(encoded_oid.decode("hex"))
85+
url_decode = classmethod(url_decode)
8686

8787
def __str__(self):
8888
return self.__id

pymongo/son.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,6 @@ def __cmp__(self, other):
191191
def __len__(self):
192192
return len(self.keys())
193193

194-
@classmethod
195194
def from_xml(cls, xml):
196195
"""Create an instance of SON from an xml document.
197196
"""
@@ -215,7 +214,7 @@ def make_code(code):
215214
return code.text is not None and Code(code.text) or Code("")
216215

217216
def make_binary(binary):
218-
return binary.text is not None and Binary(base64.b64decode(binary.text)) or Binary("")
217+
return binary.text is not None and Binary(base64.decodestring(binary.text)) or Binary("")
219218

220219
def make_boolean(bool):
221220
return bool.text == "true"
@@ -291,3 +290,4 @@ def make_doc(doc):
291290
doc = tree[1]
292291

293292
return make_doc(doc)
293+
from_xml = classmethod(from_xml)

setup.py

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
#!/usr/bin/env python
22

3+
import sys
4+
35
try:
46
from setuptools import setup
57
except ImportError:
@@ -31,16 +33,27 @@ class custom_build_ext(build_ext):
3133
The C extension speeds up BSON encoding, but is not essential.
3234
"""
3335
def build_extension(self, ext):
34-
try:
35-
build_ext.build_extension(self, ext)
36-
except CCompilerError:
37-
print ""
38-
print ("*" * 62)
39-
print """WARNING: The %s extension module could not
36+
if sys.version_info[:3] >= (2, 4, 0):
37+
try:
38+
build_ext.build_extension(self, ext)
39+
except CCompilerError:
40+
print ""
41+
print ("*" * 62)
42+
print """WARNING: The %s extension module could not
4043
be compiled. No C extensions are essential for PyMongo to run,
4144
although they do result in significant speed improvements.
4245
4346
Above is the ouput showing how the compilation failed.""" % ext.name
47+
print ("*" * 62 + "\n")
48+
else:
49+
print ""
50+
print ("*" * 62)
51+
print """WARNING: The %s extension module is not supported
52+
for this version of Python. No C extensions are essential
53+
for PyMongo to run, although they do result in significant
54+
speed improvements.
55+
56+
Please use Python >= 2.4 to take advantage of the extension.""" % ext.name
4457
print ("*" * 62 + "\n")
4558

4659
setup(

test/test_binary.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,10 @@ def setUp(self):
2727
def test_binary(self):
2828
a_string = "hello world"
2929
a_binary = Binary("hello world")
30-
self.assertTrue(a_binary.startswith("hello"))
31-
self.assertTrue(a_binary.endswith("world"))
32-
self.assertTrue(isinstance(a_binary, Binary))
33-
self.assertFalse(isinstance(a_string, Binary))
30+
self.assert_(a_binary.startswith("hello"))
31+
self.assert_(a_binary.endswith("world"))
32+
self.assert_(isinstance(a_binary, Binary))
33+
self.failIf(isinstance(a_string, Binary))
3434

3535
def test_exceptions(self):
3636
self.assertRaises(TypeError, Binary, None)
@@ -41,8 +41,8 @@ def test_exceptions(self):
4141
self.assertRaises(TypeError, Binary, "hello", "100")
4242
self.assertRaises(ValueError, Binary, "hello", -1)
4343
self.assertRaises(ValueError, Binary, "hello", 256)
44-
self.assertTrue(Binary("hello", 0))
45-
self.assertTrue(Binary("hello", 255))
44+
self.assert_(Binary("hello", 0))
45+
self.assert_(Binary("hello", 255))
4646

4747
def test_subtype(self):
4848
b = Binary("hello")

test/test_bson.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -41,15 +41,15 @@ def test_basic_validation(self):
4141
self.assertRaises(TypeError, is_valid, u"test")
4242
self.assertRaises(TypeError, is_valid, 10.4)
4343

44-
self.assertFalse(is_valid("test"))
44+
self.failIf(is_valid("test"))
4545

4646
# the simplest valid BSON document
47-
self.assertTrue(is_valid("\x05\x00\x00\x00\x00"))
48-
self.assertTrue(is_valid(BSON("\x05\x00\x00\x00\x00")))
49-
self.assertFalse(is_valid("\x04\x00\x00\x00\x00"))
50-
self.assertFalse(is_valid("\x05\x00\x00\x00\x01"))
51-
self.assertFalse(is_valid("\x05\x00\x00\x00"))
52-
self.assertFalse(is_valid("\x05\x00\x00\x00\x00\x00"))
47+
self.assert_(is_valid("\x05\x00\x00\x00\x00"))
48+
self.assert_(is_valid(BSON("\x05\x00\x00\x00\x00")))
49+
self.failIf(is_valid("\x04\x00\x00\x00\x00"))
50+
self.failIf(is_valid("\x05\x00\x00\x00\x01"))
51+
self.failIf(is_valid("\x05\x00\x00\x00"))
52+
self.failIf(is_valid("\x05\x00\x00\x00\x00\x00"))
5353

5454
def test_random_data_is_not_bson(self):
5555
qcheck.check_unittest(self, qcheck.isnt(is_valid), qcheck.gen_string(qcheck.gen_range(0, 40)))
@@ -104,7 +104,7 @@ def helper(dict):
104104
self.assertEqual(dict, (BSON.from_dict(dict)).to_dict())
105105
helper({})
106106
helper({"test": u"hello"})
107-
self.assertTrue(isinstance(BSON.from_dict({"hello": "world"}).to_dict()["hello"],
107+
self.assert_(isinstance(BSON.from_dict({"hello": "world"}).to_dict()["hello"],
108108
types.UnicodeType))
109109
helper({"mike": -10120})
110110
helper({"long": long(10)})

test/test_code.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,10 @@ def setUp(self):
2727
def test_code(self):
2828
a_string = "hello world"
2929
a_code = Code("hello world")
30-
self.assertTrue(a_code.startswith("hello"))
31-
self.assertTrue(a_code.endswith("world"))
32-
self.assertTrue(isinstance(a_code, Code))
33-
self.assertFalse(isinstance(a_string, Code))
30+
self.assert_(a_code.startswith("hello"))
31+
self.assert_(a_code.endswith("world"))
32+
self.assert_(isinstance(a_code, Code))
33+
self.failIf(isinstance(a_string, Code))
3434

3535
def test_repr(self):
3636
c = Code("hello world")

test/test_collection.py

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def make_col(base, name):
4848
self.assertRaises(InvalidName, make_col, self.db.test, "test.")
4949
self.assertRaises(InvalidName, make_col, self.db.test, "tes..t")
5050

51-
self.assertTrue(isinstance(self.db.test, Collection))
51+
self.assert_(isinstance(self.db.test, Collection))
5252
self.assertEqual(self.db.test, self.db["test"])
5353
self.assertEqual(self.db.test, Collection(self.db, "test"))
5454
self.assertEqual(self.db.test.mike, self.db["test.mike"])
@@ -65,7 +65,7 @@ def test_create_index(self):
6565
self.assertRaises(TypeError, db.test.create_index, "hello", "world")
6666

6767
db.test.drop_indexes()
68-
self.assertFalse(db.system.indexes.find_one({"ns": u"pymongo_test.test"}))
68+
self.failIf(db.system.indexes.find_one({"ns": u"pymongo_test.test"}))
6969

7070
db.test.create_index("hello", ASCENDING)
7171
db.test.create_index([("hello", DESCENDING), ("world", ASCENDING)])
@@ -76,15 +76,15 @@ def test_create_index(self):
7676
self.assertEqual(count, 2)
7777

7878
db.test.drop_indexes()
79-
self.assertFalse(db.system.indexes.find_one({"ns": u"pymongo_test.test"}))
79+
self.failIf(db.system.indexes.find_one({"ns": u"pymongo_test.test"}))
8080
db.test.create_index("hello", ASCENDING)
8181
self.assertEqual(db.system.indexes.find_one({"ns": u"pymongo_test.test"}),
8282
SON([(u"name", u"hello_1"),
8383
(u"ns", u"pymongo_test.test"),
8484
(u"key", SON([(u"hello", 1)]))]))
8585

8686
db.test.drop_indexes()
87-
self.assertFalse(db.system.indexes.find_one({"ns": u"pymongo_test.test"}))
87+
self.failIf(db.system.indexes.find_one({"ns": u"pymongo_test.test"}))
8888
db.test.create_index([("hello", DESCENDING), ("world", ASCENDING)])
8989
self.assertEqual(db.system.indexes.find_one({"ns": u"pymongo_test.test"}),
9090
SON([(u"name", u"hello_-1_world_1"),
@@ -145,9 +145,9 @@ def test_index_info(self):
145145
db.test.create_index([("hello", DESCENDING), ("world", ASCENDING)])
146146
self.assertEqual(db.test.index_information()["hello_1"], [("hello", ASCENDING)])
147147
self.assertEqual(len(db.test.index_information()), 2)
148-
self.assertTrue(("hello", DESCENDING) in db.test.index_information()["hello_-1_world_1"])
149-
self.assertTrue(("world", ASCENDING) in db.test.index_information()["hello_-1_world_1"])
150-
self.assertTrue(len(db.test.index_information()["hello_-1_world_1"]) == 2)
148+
self.assert_(("hello", DESCENDING) in db.test.index_information()["hello_-1_world_1"])
149+
self.assert_(("world", ASCENDING) in db.test.index_information()["hello_-1_world_1"])
150+
self.assert_(len(db.test.index_information()["hello_-1_world_1"]) == 2)
151151

152152
def test_options(self):
153153
db = self.db
@@ -184,15 +184,15 @@ def test_find_w_fields(self):
184184

185185
db.test.insert({"x": 1, "mike": "awesome", "extra thing": "abcdefghijklmnopqrstuvwxyz"})
186186
self.assertEqual(1, db.test.count())
187-
self.assertTrue("x" in db.test.find({}).next())
188-
self.assertTrue("mike" in db.test.find({}).next())
189-
self.assertTrue("extra thing" in db.test.find({}).next())
190-
self.assertTrue("x" in db.test.find({}, ["x", "mike"]).next())
191-
self.assertTrue("mike" in db.test.find({}, ["x", "mike"]).next())
192-
self.assertFalse("extra thing" in db.test.find({}, ["x", "mike"]).next())
193-
self.assertFalse("x" in db.test.find({}, ["mike"]).next())
194-
self.assertTrue("mike" in db.test.find({}, ["mike"]).next())
195-
self.assertFalse("extra thing" in db.test.find({}, ["mike"]).next())
187+
self.assert_("x" in db.test.find({}).next())
188+
self.assert_("mike" in db.test.find({}).next())
189+
self.assert_("extra thing" in db.test.find({}).next())
190+
self.assert_("x" in db.test.find({}, ["x", "mike"]).next())
191+
self.assert_("mike" in db.test.find({}, ["x", "mike"]).next())
192+
self.failIf("extra thing" in db.test.find({}, ["x", "mike"]).next())
193+
self.failIf("x" in db.test.find({}, ["mike"]).next())
194+
self.assert_("mike" in db.test.find({}, ["mike"]).next())
195+
self.failIf("extra thing" in db.test.find({}, ["mike"]).next())
196196

197197
def test_find_w_regex(self):
198198
db = self.db
@@ -215,7 +215,7 @@ def test_id_can_be_anything(self):
215215
db.test.remove({})
216216
auto_id = {"hello": "world"}
217217
db.test.insert(auto_id)
218-
self.assertTrue(isinstance(auto_id["_id"], ObjectId))
218+
self.assert_(isinstance(auto_id["_id"], ObjectId))
219219

220220
numeric = {"_id": 240, "hello": "world"}
221221
db.test.insert(numeric)
@@ -227,7 +227,7 @@ def test_id_can_be_anything(self):
227227

228228
for x in db.test.find():
229229
self.assertEqual(x["hello"], u"world")
230-
self.assertTrue("_id" in x)
230+
self.assert_("_id" in x)
231231

232232
def test_iteration(self):
233233
db = self.db

0 commit comments

Comments
 (0)