diff --git a/pymongo/common.py b/pymongo/common.py index 8fc99d296..239bd4819 100644 --- a/pymongo/common.py +++ b/pymongo/common.py @@ -111,8 +111,8 @@ def validate_boolean_or_string(option, value): """Validates that value is True, False, 'true', or 'false'.""" if isinstance(value, string_type): if value not in ('true', 'false'): - raise ConfigurationError("The value of %s must be " - "'true' or 'false'" % (option,)) + raise ValueError("The value of %s must be " + "'true' or 'false'" % (option,)) return value == 'true' return validate_boolean(option, value) @@ -124,8 +124,8 @@ def validate_integer(option, value): return value elif isinstance(value, string_type): if not value.isdigit(): - raise ConfigurationError("The value of %s must be " - "an integer" % (option,)) + raise ValueError("The value of %s must be " + "an integer" % (option,)) return int(value) raise TypeError("Wrong type for %s, value must be an integer" % (option,)) @@ -135,8 +135,8 @@ def validate_positive_integer(option, value): """ val = validate_integer(option, value) if val < 0: - raise ConfigurationError("The value of %s must be " - "a positive integer" % (option,)) + raise ValueError("The value of %s must be " + "a positive integer" % (option,)) return val @@ -195,17 +195,19 @@ def validate_positive_float(option, value): """Validates that 'value' is a float, or can be converted to one, and is positive. """ - err = ConfigurationError("%s must be a positive int or float" % (option,)) + errmsg = "%s must be an integer or float" % (option,) try: value = float(value) - except (ValueError, TypeError): - raise err + except ValueError: + raise ValueError(errmsg) + except TypeError: + raise TypeError(errmsg) # float('inf') doesn't work in 2.4 or 2.5 on Windows, so just cap floats at # one billion - this is a reasonable approximation for infinity if not 0 < value < 1e9: - raise err - + raise ValueError("%s must be greater than 0 and " + "less than one billion" % (option,)) return value @@ -222,8 +224,7 @@ def validate_read_preference(dummy, value): """Validate a read preference. """ if not isinstance(value, ServerMode): - raise ConfigurationError("%r is not a " - "valid read preference." % (value,)) + raise TypeError("%r is not a read preference." % (value,)) return value @@ -233,7 +234,7 @@ def validate_read_preference_mode(dummy, name): try: return read_pref_mode_from_name(name) except ValueError: - raise ConfigurationError("Not a valid read preference") + raise ValueError("%s is not a valid read preference" % (name,)) def validate_auth_mechanism(option, value): @@ -243,8 +244,7 @@ def validate_auth_mechanism(option, value): # unsupported, may be removed at any time. You have # been warned. if value not in MECHANISMS and value != 'CRAM-MD5': - raise ConfigurationError("%s must be in " - "%s" % (option, MECHANISMS)) + raise ValueError("%s must be in %s" % (option, tuple(MECHANISMS))) return value @@ -254,9 +254,9 @@ def validate_uuid_representation(dummy, value): try: return _UUID_REPRESENTATIONS[value] except KeyError: - raise ConfigurationError("%s is an invalid UUID representation. " - "Must be one of " - "%s" % (value, tuple(_UUID_REPRESENTATIONS))) + raise ValueError("%s is an invalid UUID representation. " + "Must be one of " + "%s" % (value, tuple(_UUID_REPRESENTATIONS))) def validate_read_preference_tags(name, value): @@ -274,8 +274,8 @@ def validate_read_preference_tags(name, value): tag_sets.append(dict([tag.split(":") for tag in tag_set.split(",")])) except Exception: - raise ConfigurationError("%r not a valid " - "value for %s" % (tag_set, name)) + raise ValueError("%r not a valid " + "value for %s" % (tag_set, name)) return tag_sets @@ -290,23 +290,22 @@ def validate_auth_mechanism_properties(option, value): try: key, val = opt.split(':') if key not in _MECHANISM_PROPS: - raise ConfigurationError("%s is not a supported auth " - "mechanism property. Must be one of " - "%s." % (key, tuple(_MECHANISM_PROPS))) + raise ValueError("%s is not a supported auth " + "mechanism property. Must be one of " + "%s." % (key, tuple(_MECHANISM_PROPS))) props[key] = val except ValueError: - raise ConfigurationError("auth mechanism properties must be " - "key:value pairs like SERVICE_NAME:" - "mongodb, not %s." % (opt,)) + raise ValueError("auth mechanism properties must be " + "key:value pairs like SERVICE_NAME:" + "mongodb, not %s." % (opt,)) return props def validate_document_class(option, value): """Validate the document_class option.""" if not issubclass(value, collections.MutableMapping): - raise ConfigurationError("%s must be dict, bson.son.SON, or another " - "sublass of " - "collections.MutableMapping" % (option,)) + raise TypeError("%s must be dict, bson.son.SON, or another " + "sublass of collections.MutableMapping" % (option,)) return value diff --git a/pymongo/read_preferences.py b/pymongo/read_preferences.py index 245f3ed94..8fb6553b8 100644 --- a/pymongo/read_preferences.py +++ b/pymongo/read_preferences.py @@ -45,16 +45,16 @@ def _validate_tag_sets(tag_sets): return tag_sets if not isinstance(tag_sets, list): - raise ConfigurationError(( + raise TypeError(( "Tag sets %r invalid, must be a list") % (tag_sets,)) if len(tag_sets) == 0: - raise ConfigurationError(( + raise ValueError(( "Tag sets %r invalid, must be None or contain at least one set of" " tags") % (tag_sets,)) for tags in tag_sets: if not isinstance(tags, Mapping): - raise ConfigurationError( + raise TypeError( "Tag set %r invalid, must be an instance of dict, " "bson.son.SON or other type that inherits from " "collection.Mapping" % (tags,)) diff --git a/pymongo/ssl_support.py b/pymongo/ssl_support.py index 1ca7f5633..8f5ddd9c5 100644 --- a/pymongo/ssl_support.py +++ b/pymongo/ssl_support.py @@ -38,9 +38,9 @@ if HAVE_SSL: return value elif value in (CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED): return value - raise ConfigurationError("The value of %s must be one of: " - "`ssl.CERT_NONE`, `ssl.CERT_OPTIONAL` or " - "`ssl.CERT_REQUIRED" % (option,)) + raise ValueError("The value of %s must be one of: " + "`ssl.CERT_NONE`, `ssl.CERT_OPTIONAL` or " + "`ssl.CERT_REQUIRED" % (option,)) def get_ssl_context(*args): """Create and return an SSLContext object.""" diff --git a/pymongo/uri_parser.py b/pymongo/uri_parser.py index 52ee69c18..736fbc6d4 100644 --- a/pymongo/uri_parser.py +++ b/pymongo/uri_parser.py @@ -104,9 +104,9 @@ def parse_ipv6_literal_host(entity, default_port): specified in entity. """ if entity.find(']') == -1: - raise ConfigurationError("an IPv6 address literal must be " - "enclosed in '[' and ']' according " - "to RFC 2732.") + raise ValueError("an IPv6 address literal must be " + "enclosed in '[' and ']' according " + "to RFC 2732.") i = entity.find(']:') if i == -1: return entity[1:-1], default_port @@ -131,14 +131,14 @@ def parse_host(entity, default_port=DEFAULT_PORT): host, port = parse_ipv6_literal_host(entity, default_port) elif entity.find(':') != -1: if entity.count(':') > 1: - raise ConfigurationError("Reserved characters such as ':' must be " - "escaped according RFC 2396. An IPv6 " - "address literal must be enclosed in '[' " - "and ']' according to RFC 2732.") + raise ValueError("Reserved characters such as ':' must be " + "escaped according RFC 2396. An IPv6 " + "address literal must be enclosed in '[' " + "and ']' according to RFC 2732.") host, port = host.split(':', 1) if isinstance(port, string_type): if not port.isdigit(): - raise ConfigurationError("Port number must be an integer.") + raise ValueError("Port number must be an integer.") port = int(port) # Normalize hostname to lowercase, since DNS is case-insensitive: diff --git a/pymongo/write_concern.py b/pymongo/write_concern.py index fa393dcff..2f4f83973 100644 --- a/pymongo/write_concern.py +++ b/pymongo/write_concern.py @@ -19,7 +19,7 @@ from pymongo.errors import ConfigurationError class WriteConcern(object): """WriteConcern - + :Parameters: - `w`: (integer or string) Used with replication, write operations will block until they have been replicated to the specified number @@ -53,17 +53,17 @@ class WriteConcern(object): if wtimeout is not None: if not isinstance(wtimeout, integer_types): - raise ConfigurationError("wtimeout must be an integer") + raise TypeError("wtimeout must be an integer") self.__document["wtimeout"] = wtimeout if j is not None: if not isinstance(j, bool): - raise ConfigurationError("j must be True or False") + raise TypeError("j must be True or False") self.__document["j"] = j if fsync is not None: if not isinstance(fsync, bool): - raise ConfigurationError("fsync must be True or False") + raise TypeError("fsync must be True or False") if j and fsync: raise ConfigurationError("Can't set both j " "and fsync at the same time") @@ -76,7 +76,7 @@ class WriteConcern(object): if isinstance(w, integer_types): self.__acknowledged = w > 0 elif not isinstance(w, string_type): - raise ConfigurationError("w must be an integer or string") + raise TypeError("w must be an integer or string") self.__document["w"] = w @property diff --git a/test/test_client.py b/test/test_client.py index 4d319f0ea..fbc1807a1 100644 --- a/test/test_client.py +++ b/test/test_client.py @@ -506,16 +506,16 @@ class TestClient(IntegrationTest): c = connected(rs_or_single_client(socketTimeoutMS=None)) self.assertEqual(None, get_pool(c).opts.socket_timeout) - self.assertRaises(ConfigurationError, + self.assertRaises(ValueError, rs_or_single_client, socketTimeoutMS=0) - self.assertRaises(ConfigurationError, + self.assertRaises(ValueError, rs_or_single_client, socketTimeoutMS=-1) - self.assertRaises(ConfigurationError, + self.assertRaises(ValueError, rs_or_single_client, socketTimeoutMS=1e10) - self.assertRaises(ConfigurationError, + self.assertRaises(ValueError, rs_or_single_client, socketTimeoutMS='foo') def test_socket_timeout(self): @@ -550,7 +550,7 @@ class TestClient(IntegrationTest): self.assertTrue(get_pool(client).opts.socket_keepalive) def test_tz_aware(self): - self.assertRaises(ConfigurationError, MongoClient, tz_aware='foo') + self.assertRaises(ValueError, MongoClient, tz_aware='foo') aware = rs_or_single_client(tz_aware=True) naive = self.client diff --git a/test/test_pooling.py b/test/test_pooling.py index 8e4ec8c31..e659127ed 100644 --- a/test/test_pooling.py +++ b/test/test_pooling.py @@ -169,11 +169,11 @@ class _TestPoolingBase(unittest.TestCase): class TestPooling(_TestPoolingBase): def test_max_pool_size_validation(self): self.assertRaises( - ConfigurationError, MongoClient, host=host, port=port, + ValueError, MongoClient, host=host, port=port, max_pool_size=-1) self.assertRaises( - ConfigurationError, MongoClient, host=host, port=port, + ValueError, MongoClient, host=host, port=port, max_pool_size='foo') c = MongoClient(host=host, port=port, max_pool_size=100) diff --git a/test/test_read_preferences.py b/test/test_read_preferences.py index 0bdf2dd4f..9a4ba6a4a 100644 --- a/test/test_read_preferences.py +++ b/test/test_read_preferences.py @@ -97,7 +97,7 @@ class TestReadPreferences(TestReadPreferencesBase): rs_client(read_preference=mode).read_preference) self.assertRaises( - ConfigurationError, + TypeError, rs_client, read_preference='foo') def test_tag_sets_validation(self): @@ -124,14 +124,14 @@ class TestReadPreferences(TestReadPreferencesBase): [{'k': 'v'}, {}], rs_client(read_preference=S).read_preference.tag_sets) - self.assertRaises(ConfigurationError, Secondary, tag_sets=[]) + self.assertRaises(ValueError, Secondary, tag_sets=[]) # One dict not ok, must be a list of dicts - self.assertRaises(ConfigurationError, Secondary, tag_sets={'k': 'v'}) + self.assertRaises(TypeError, Secondary, tag_sets={'k': 'v'}) - self.assertRaises(ConfigurationError, Secondary, tag_sets='foo') + self.assertRaises(TypeError, Secondary, tag_sets='foo') - self.assertRaises(ConfigurationError, Secondary, tag_sets=['foo']) + self.assertRaises(TypeError, Secondary, tag_sets=['foo']) def test_threshold_validation(self): self.assertEqual(17, rs_client( @@ -147,8 +147,8 @@ class TestReadPreferences(TestReadPreferencesBase): ).local_threshold_ms) def test_primary(self): - self.assertReadsFrom('primary', - read_preference=ReadPreference.PRIMARY) + self.assertReadsFrom( + 'primary', read_preference=ReadPreference.PRIMARY) def test_primary_with_tags(self): # Tags not allowed with PRIMARY @@ -157,16 +157,16 @@ class TestReadPreferences(TestReadPreferencesBase): rs_client, tag_sets=[{'dc': 'ny'}]) def test_primary_preferred(self): - self.assertReadsFrom('primary', - read_preference=ReadPreference.PRIMARY_PREFERRED) + self.assertReadsFrom( + 'primary', read_preference=ReadPreference.PRIMARY_PREFERRED) def test_secondary(self): - self.assertReadsFrom('secondary', - read_preference=ReadPreference.SECONDARY) + self.assertReadsFrom( + 'secondary', read_preference=ReadPreference.SECONDARY) def test_secondary_preferred(self): - self.assertReadsFrom('secondary', - read_preference=ReadPreference.SECONDARY_PREFERRED) + self.assertReadsFrom( + 'secondary', read_preference=ReadPreference.SECONDARY_PREFERRED) def test_nearest(self): # With high localThresholdMS, expect to read from any @@ -194,7 +194,8 @@ class TestReadPreferences(TestReadPreferencesBase): server.description.round_trip_time) for server in c._get_topology().select_servers(any_server_selector)) - self.assertFalse(not_used, + self.assertFalse( + not_used, "Expected to use primary and all secondaries for mode NEAREST," " but didn't use %s\nlatencies: %s" % (not_used, latencies)) @@ -396,14 +397,11 @@ class TestMongosConnection(IntegrationTest): # Test non-PRIMARY modes which can be combined with tags for mode, mongos_mode in ( - (PrimaryPreferred, 'primaryPreferred'), - (Secondary, 'secondary'), - (SecondaryPreferred, 'secondaryPreferred'), - (Nearest, 'nearest'), - ): - for tag_sets in ( - None, [{}] - ): + (PrimaryPreferred, 'primaryPreferred'), + (Secondary, 'secondary'), + (SecondaryPreferred, 'secondaryPreferred'), + (Nearest, 'nearest')): + for tag_sets in (None, [{}]): # Create a client e.g. with read_preference=NEAREST c = connected(single_client( host, port, read_preference=mode(tag_sets=tag_sets))) @@ -441,10 +439,9 @@ class TestMongosConnection(IntegrationTest): '$readPreference' in cursor._Cursor__query_spec()) for tag_sets in ( - [{'dc': 'la'}], - [{'dc': 'la'}, {'dc': 'sf'}], - [{'dc': 'la'}, {'dc': 'sf'}, {}], - ): + [{'dc': 'la'}], + [{'dc': 'la'}, {'dc': 'sf'}], + [{'dc': 'la'}, {'dc': 'sf'}, {}]): c = connected(single_client( host, port, read_preference=mode(tag_sets=tag_sets))) diff --git a/test/test_ssl.py b/test/test_ssl.py index 31a9793de..9908724de 100644 --- a/test/test_ssl.py +++ b/test/test_ssl.py @@ -20,12 +20,6 @@ import sys sys.path[0:0] = [""] -try: - from ssl import CertificateError -except ImportError: - # Backport. - from pymongo.ssl_match_hostname import CertificateError - try: from urllib.parse import quote_plus except ImportError: @@ -134,7 +128,7 @@ class TestClientSSL(unittest.TestCase): def test_config_ssl(self): # Tests various ssl configurations - self.assertRaises(ConfigurationError, MongoClient, ssl='foo') + self.assertRaises(ValueError, MongoClient, ssl='foo') self.assertRaises(ConfigurationError, MongoClient, ssl=False, diff --git a/test/test_uri_parser.py b/test/test_uri_parser.py index 68bd959ea..83c0a172a 100644 --- a/test/test_uri_parser.py +++ b/test/test_uri_parser.py @@ -79,16 +79,16 @@ class TestURI(unittest.TestCase): split_hosts('/tmp/mongodb-27017.sock')) self.assertEqual([('/tmp/mongodb-27017.sock', None), ('example.com', 27017)], - split_hosts('/tmp/mongodb-27017.sock,' - 'example.com:27017')) + split_hosts('/tmp/mongodb-27017.sock,' + 'example.com:27017')) self.assertEqual([('example.com', 27017), ('/tmp/mongodb-27017.sock', None)], - split_hosts('example.com:27017,' - '/tmp/mongodb-27017.sock')) - self.assertRaises(ConfigurationError, split_hosts, '::1', 27017) - self.assertRaises(ConfigurationError, split_hosts, '[::1:27017') - self.assertRaises(ConfigurationError, split_hosts, '::1') - self.assertRaises(ConfigurationError, split_hosts, '::1]:27017') + split_hosts('example.com:27017,' + '/tmp/mongodb-27017.sock')) + self.assertRaises(ValueError, split_hosts, '::1', 27017) + self.assertRaises(ValueError, split_hosts, '[::1:27017') + self.assertRaises(ValueError, split_hosts, '::1') + self.assertRaises(ValueError, split_hosts, '::1]:27017') self.assertEqual([('::1', 27017)], split_hosts('[::1]:27017')) self.assertEqual([('::1', 27017)], split_hosts('[::1]')) @@ -96,19 +96,19 @@ class TestURI(unittest.TestCase): self.assertRaises(ConfigurationError, split_options, 'foo') self.assertRaises(ConfigurationError, split_options, 'foo=bar') self.assertRaises(ConfigurationError, split_options, 'foo=bar;foo') - self.assertRaises(ConfigurationError, split_options, 'socketTimeoutMS=foo') - self.assertRaises(ConfigurationError, split_options, 'socketTimeoutMS=0.0') - self.assertRaises(ConfigurationError, split_options, 'connectTimeoutMS=foo') - self.assertRaises(ConfigurationError, split_options, 'connectTimeoutMS=0.0') - self.assertRaises(ConfigurationError, split_options, 'connectTimeoutMS=1e100000') - self.assertRaises(ConfigurationError, split_options, 'connectTimeoutMS=-1e100000') + self.assertRaises(ValueError, split_options, 'socketTimeoutMS=foo') + self.assertRaises(ValueError, split_options, 'socketTimeoutMS=0.0') + self.assertRaises(ValueError, split_options, 'connectTimeoutMS=foo') + self.assertRaises(ValueError, split_options, 'connectTimeoutMS=0.0') + self.assertRaises(ValueError, split_options, 'connectTimeoutMS=1e100000') + self.assertRaises(ValueError, split_options, 'connectTimeoutMS=-1e100000') # On most platforms float('inf') and float('-inf') represent # +/- infinity, although on Python 2.4 and 2.5 on Windows those # expressions are invalid if not (sys.platform == "win32" and sys.version_info <= (2, 5)): - self.assertRaises(ConfigurationError, split_options, 'connectTimeoutMS=inf') - self.assertRaises(ConfigurationError, split_options, 'connectTimeoutMS=-inf') + self.assertRaises(ValueError, split_options, 'connectTimeoutMS=inf') + self.assertRaises(ValueError, split_options, 'connectTimeoutMS=-inf') self.assertTrue(split_options('socketTimeoutMS=300')) self.assertTrue(split_options('connectTimeoutMS=300')) @@ -121,11 +121,11 @@ class TestURI(unittest.TestCase): self.assertTrue(isinstance(split_options('w=5.5')['w'], string_type)) self.assertTrue(split_options('w=foo')) self.assertTrue(split_options('w=majority')) - self.assertRaises(ConfigurationError, split_options, 'wtimeoutms=foo') - self.assertRaises(ConfigurationError, split_options, 'wtimeoutms=5.5') + self.assertRaises(ValueError, split_options, 'wtimeoutms=foo') + self.assertRaises(ValueError, split_options, 'wtimeoutms=5.5') self.assertTrue(split_options('wtimeoutms=500')) - self.assertRaises(ConfigurationError, split_options, 'fsync=foo') - self.assertRaises(ConfigurationError, split_options, 'fsync=5.5') + self.assertRaises(ValueError, split_options, 'fsync=foo') + self.assertRaises(ValueError, split_options, 'fsync=5.5') self.assertEqual({'fsync': True}, split_options('fsync=true')) self.assertEqual({'fsync': False}, split_options('fsync=false')) self.assertEqual({'authmechanism': 'GSSAPI'}, @@ -134,7 +134,7 @@ class TestURI(unittest.TestCase): split_options('authMechanism=MONGODB-CR')) self.assertEqual({'authmechanism': 'SCRAM-SHA-1'}, split_options('authMechanism=SCRAM-SHA-1')) - self.assertRaises(ConfigurationError, + self.assertRaises(ValueError, split_options, 'authMechanism=foo') self.assertEqual({'authsource': 'foobar'}, split_options('authSource=foobar')) # maxPoolSize isn't yet a documented URI option. @@ -143,7 +143,7 @@ class TestURI(unittest.TestCase): def test_parse_uri(self): self.assertRaises(InvalidURI, parse_uri, "http://foobar.com") self.assertRaises(InvalidURI, parse_uri, "http://foo@foobar.com") - self.assertRaises(ConfigurationError, + self.assertRaises(ValueError, parse_uri, "mongodb://::1", 27017) orig = { @@ -368,7 +368,7 @@ class TestURI(unittest.TestCase): "@localhost/foo?uuidrepresentation=" "javaLegacy")) - self.assertRaises(ConfigurationError, parse_uri, + self.assertRaises(ValueError, parse_uri, "mongodb://user%40domain.com:password" "@localhost/foo?uuidrepresentation=notAnOption")