Skip to content

Commit

Permalink
fix several deprecation warnings
Browse files Browse the repository at this point in the history
adding -Werror flag to pytest configuration
so we can flush all of those with the test we have
so we won't have user of the driver running into those
and get them fixed address as soon as we support new
python versions
  • Loading branch information
fruch committed Dec 17, 2024
1 parent 7e0c785 commit f513e5b
Show file tree
Hide file tree
Showing 32 changed files with 131 additions and 74 deletions.
2 changes: 1 addition & 1 deletion cassandra/cqlengine/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,7 @@ def setup(
:param int consistency: The global default :class:`~.ConsistencyLevel` - default is the same as :attr:`.Session.default_consistency_level`
:param bool lazy_connect: True if should not connect until first use
:param bool retry_connect: True if we should retry to connect even if there was a connection failure initially
:param \*\*kwargs: Pass-through keyword arguments for :class:`cassandra.cluster.Cluster`
:param kwargs: Pass-through keyword arguments for :class:`cassandra.cluster.Cluster`
"""

from cassandra.cqlengine import models
Expand Down
8 changes: 4 additions & 4 deletions cassandra/cqlengine/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,8 +205,8 @@ def add_callback(self, fn, *args, **kwargs):
:param fn: Callable object
:type fn: callable
:param \*args: Positional arguments to be passed to the callback at the time of execution
:param \*\*kwargs: Named arguments to be passed to the callback at the time of execution
:param args: Positional arguments to be passed to the callback at the time of execution
:param kwargs: Named arguments to be passed to the callback at the time of execution
"""
if not callable(fn):
raise ValueError("Value for argument 'fn' is {0} and is not a callable object.".format(type(fn)))
Expand Down Expand Up @@ -276,8 +276,8 @@ class ContextQuery(object):
A Context manager to allow a Model to switch context easily. Presently, the context only
specifies a keyspace for model IO.
:param \*args: One or more models. A model should be a class type, not an instance.
:param \*\*kwargs: (optional) Context parameters: can be *keyspace* or *connection*
:param args: One or more models. A model should be a class type, not an instance.
:param kwargs: (optional) Context parameters: can be *keyspace* or *connection*
For example:
Expand Down
4 changes: 2 additions & 2 deletions cassandra/datastax/cloud/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

_HAS_SSL = True
try:
from ssl import SSLContext, PROTOCOL_TLS, CERT_REQUIRED
from ssl import SSLContext, PROTOCOL_TLS_CLIENT, CERT_REQUIRED
except:
_HAS_SSL = False

Expand Down Expand Up @@ -169,7 +169,7 @@ def parse_metadata_info(config, http_data):


def _ssl_context_from_cert(ca_cert_location, cert_location, key_location):
ssl_context = SSLContext(PROTOCOL_TLS)
ssl_context = SSLContext(PROTOCOL_TLS_CLIENT)
ssl_context.load_verify_locations(ca_cert_location)
ssl_context.verify_mode = CERT_REQUIRED
ssl_context.load_cert_chain(certfile=cert_location, keyfile=key_location)
Expand Down
2 changes: 1 addition & 1 deletion cassandra/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
from cassandra import DriverException

DATETIME_EPOC = datetime.datetime(1970, 1, 1)
UTC_DATETIME_EPOC = datetime.datetime.utcfromtimestamp(0)
UTC_DATETIME_EPOC = datetime.datetime.fromtimestamp(0, tz=datetime.timezone.utc)

_nan = float('nan')

Expand Down
15 changes: 15 additions & 0 deletions pytest.ini
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,18 @@ log_format = %(asctime)s.%(msecs)03d %(levelname)s [%(module)s:%(lineno)s]: %(me
log_level = DEBUG
log_date_format = %Y-%m-%d %H:%M:%S
xfail_strict=true

filterwarnings =
error
ignore::pytest.PytestCollectionWarning
ignore::ResourceWarning
ignore:distutils Version classes are deprecated:DeprecationWarning:eventlet.support.greenlets
ignore:X509Extension support in pyOpenSSL is deprecated.:DeprecationWarning
ignore:CRL support in pyOpenSSL is deprecated:DeprecationWarning
ignore:sign\(\) is deprecated:DeprecationWarning
ignore:verify\(\) is deprecated:DeprecationWarning
ignore:pkg_resources is deprecated as an API:DeprecationWarning:gevent.events
ignore:.*pkg_resources.declare_namespace.*:DeprecationWarning
ignore:"@coroutine" decorator is deprecated since Python 3.8:DeprecationWarning:asynctest.*
ignore:The asyncore module is deprecated and will be removed in Python 3.12.*:DeprecationWarning
ignore:CSR support in pyOpenSSL is deprecated.*:DeprecationWarning
2 changes: 1 addition & 1 deletion tests/integration/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def get_server_versions():

c = TestCluster()
s = c.connect()
row = s.execute('SELECT cql_version, release_version FROM system.local')[0]
row = s.execute('SELECT cql_version, release_version FROM system.local').one()

cass_version = _tuple_version(row.release_version)
cql_version = _tuple_version(row.cql_version)
Expand Down
2 changes: 1 addition & 1 deletion tests/integration/cqlengine/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def wrapped_function(*args, **kwargs):
# DeMonkey Patch our code
cassandra.cqlengine.connection.execute = original_function
# Check to see if we have a pre-existing test case to work from.
if len(args) is 0:
if len(args) == 0:
test_case = unittest.TestCase("__init__")
else:
test_case = args[0]
Expand Down
10 changes: 5 additions & 5 deletions tests/integration/cqlengine/columns/test_counter_column.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,9 @@ def tearDownClass(cls):

def test_updates(self):
""" Tests that counter updates work as intended """
instance = TestCounterModel.create()
instance = TestCounterModel()
instance.counter += 5
instance.save()
instance.update()

actual = TestCounterModel.get(partition=instance.partition)
assert actual.counter == 5
Expand All @@ -102,7 +102,7 @@ def test_update_from_none(self):
""" Tests that updating from None uses a create statement """
instance = TestCounterModel()
instance.counter += 1
instance.save()
instance.update()

new = TestCounterModel.get(partition=instance.partition)
assert new.counter == 1
Expand All @@ -114,15 +114,15 @@ def test_new_instance_defaults_to_zero(self):

def test_save_after_no_update(self):
expected_value = 15
instance = TestCounterModel.create()
instance = TestCounterModel()
instance.update(counter=expected_value)

# read back
instance = TestCounterModel.get(partition=instance.partition)
self.assertEqual(instance.counter, expected_value)

# save after doing nothing
instance.save()
instance.update()
self.assertEqual(instance.counter, expected_value)

# make sure there was no increment
Expand Down
4 changes: 3 additions & 1 deletion tests/integration/cqlengine/connections/test_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# limitations under the License.

import unittest
import pytest


from cassandra import ConsistencyLevel
Expand Down Expand Up @@ -129,7 +130,8 @@ class ConnectionModel(Model):
key = columns.Integer(primary_key=True)
some_data = columns.Text()


@pytest.mark.filterwarnings("ignore:Setting the consistency level at the session level will be removed")
@pytest.mark.filterwarnings("ignore:Legacy execution parameters will be removed")
class ConnectionInitTest(unittest.TestCase):
def test_default_connection_uses_legacy(self):
connection.default()
Expand Down
2 changes: 2 additions & 0 deletions tests/integration/cqlengine/management/test_management.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
import pytest

import mock
import logging
Expand Down Expand Up @@ -379,6 +380,7 @@ class TestIndexSetModel(Model):
mixed_tuple = columns.Tuple(columns.Text, columns.Integer, columns.Text, index=True)


@pytest.mark.filterwarnings("ignore:Model __table_name_case_sensitive__ will be removed")
class IndexTests(BaseCassEngTestCase):

def setUp(self):
Expand Down
2 changes: 2 additions & 0 deletions tests/integration/cqlengine/model/test_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
import pytest

from mock import patch

Expand Down Expand Up @@ -125,6 +126,7 @@ class TestModel(Model):
# .. but we can still get the bare CF name
self.assertEqual(TestModel.column_family_name(include_keyspace=False), "test_model")

@pytest.mark.filterwarnings("ignore:__table_name_case_sensitive__ will be removed")
def test_column_family_case_sensitive(self):
"""
Test to ensure case sensitivity is honored when __table_name_case_sensitive__ flag is set
Expand Down
4 changes: 2 additions & 2 deletions tests/integration/cqlengine/query/test_queryoperators.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,6 @@ def test_named_table_pk_token_function(self):
query = named.all().limit(1)
first_page = list(query)
last = first_page[-1]
self.assertTrue(len(first_page) is 1)
self.assertTrue(len(first_page) == 1)
next_page = list(query.filter(pk__token__gt=functions.Token(last.key)))
self.assertTrue(len(next_page) is 1)
self.assertTrue(len(next_page) == 1)
13 changes: 7 additions & 6 deletions tests/integration/standard/test_cluster.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

# Copyright DataStax, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand Down Expand Up @@ -150,7 +151,7 @@ def test_raise_error_on_control_connection_timeout(self):
get_node(1).pause()
cluster = TestCluster(contact_points=['127.0.0.1'], connect_timeout=1)

with self.assertRaisesRegex(NoHostAvailable, "OperationTimedOut\('errors=Timed out creating connection \(1 seconds\)"):
with self.assertRaisesRegex(NoHostAvailable, r"OperationTimedOut\('errors=Timed out creating connection \(1 seconds\)"):
cluster.connect()
cluster.shutdown()

Expand Down Expand Up @@ -899,7 +900,7 @@ def test_profile_load_balancing(self):

# use a copied instance and override the row factory
# assert last returned value can be accessed as a namedtuple so we can prove something different
named_tuple_row = rs[0]
named_tuple_row = rs.one()
self.assertIsInstance(named_tuple_row, tuple)
self.assertTrue(named_tuple_row.release_version)

Expand Down Expand Up @@ -1390,7 +1391,7 @@ def test_simple_nested(self):
with cluster.connect() as session:
self.assertFalse(cluster.is_shutdown)
self.assertFalse(session.is_shutdown)
self.assertTrue(session.execute('select release_version from system.local')[0])
self.assertTrue(session.execute('select release_version from system.local').one())
self.assertTrue(session.is_shutdown)
self.assertTrue(cluster.is_shutdown)

Expand Down Expand Up @@ -1428,7 +1429,7 @@ def test_session_no_cluster(self):
self.assertFalse(cluster.is_shutdown)
self.assertFalse(session.is_shutdown)
self.assertFalse(unmanaged_session.is_shutdown)
self.assertTrue(session.execute('select release_version from system.local')[0])
self.assertTrue(session.execute('select release_version from system.local').one())
self.assertTrue(session.is_shutdown)
self.assertFalse(cluster.is_shutdown)
self.assertFalse(unmanaged_session.is_shutdown)
Expand Down Expand Up @@ -1567,7 +1568,7 @@ def test_deprecation_warnings_legacy_parameters(self):
@test_category logs
"""
with warnings.catch_warnings(record=True) as w:
with warnings.catch_warnings(record=True, action='once') as w:
TestCluster(load_balancing_policy=RoundRobinPolicy())
logging.info(w)
self.assertGreaterEqual(len(w), 1)
Expand All @@ -1586,7 +1587,7 @@ def test_deprecation_warnings_meta_refreshed(self):
@test_category logs
"""
with warnings.catch_warnings(record=True) as w:
with warnings.catch_warnings(record=True, action='once') as w:
cluster = TestCluster()
cluster.set_meta_refresh_enabled(True)
logging.info(w)
Expand Down
4 changes: 2 additions & 2 deletions tests/integration/standard/test_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ def wait_for_connections(self, host, cluster):
while(retry < 300):
retry += 1
connections = self.fetch_connections(host, cluster)
if len(connections) is not 0:
if len(connections) != 0:
return connections
time.sleep(.1)
self.fail("No new connections found")
Expand All @@ -190,7 +190,7 @@ def wait_for_no_connections(self, host, cluster):
while(retry < 100):
retry += 1
connections = self.fetch_connections(host, cluster)
if len(connections) is 0:
if len(connections) == 0:
return
time.sleep(.5)
self.fail("Connections never cleared")
Expand Down
12 changes: 6 additions & 6 deletions tests/integration/standard/test_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ def test_bad_contact_point(self):

# verify the un-existing host was filtered
for host in self.cluster.metadata.all_hosts():
self.assertNotEquals(host.endpoint.address, '126.0.0.186')
self.assertNotEqual(host.endpoint.address, '126.0.0.186')


class SchemaMetadataTests(BasicSegregatedKeyspaceUnitTestCase):
Expand Down Expand Up @@ -163,8 +163,8 @@ def test_schema_metadata_disable(self):
query = "SELECT * FROM system.local"
no_schema_rs = no_schema_session.execute(query)
no_token_rs = no_token_session.execute(query)
self.assertIsNotNone(no_schema_rs[0])
self.assertIsNotNone(no_token_rs[0])
self.assertIsNotNone(no_schema_rs.one())
self.assertIsNotNone(no_token_rs.one())
no_schema.shutdown()
no_token.shutdown()

Expand Down Expand Up @@ -1675,7 +1675,7 @@ def test_function_no_parameters(self):

with self.VerifiedFunction(self, **kwargs) as vf:
fn_meta = self.keyspace_function_meta[vf.signature]
self.assertRegex(fn_meta.as_cql_query(), "CREATE FUNCTION.*%s\(\) .*" % kwargs['name'])
self.assertRegex(fn_meta.as_cql_query(), r"CREATE FUNCTION.*%s\(\) .*" % kwargs['name'])

def test_functions_follow_keyspace_alter(self):
"""
Expand Down Expand Up @@ -1723,12 +1723,12 @@ def test_function_cql_called_on_null(self):
kwargs['called_on_null_input'] = True
with self.VerifiedFunction(self, **kwargs) as vf:
fn_meta = self.keyspace_function_meta[vf.signature]
self.assertRegex(fn_meta.as_cql_query(), "CREATE FUNCTION.*\) CALLED ON NULL INPUT RETURNS .*")
self.assertRegex(fn_meta.as_cql_query(), r"CREATE FUNCTION.*\) CALLED ON NULL INPUT RETURNS .*")

kwargs['called_on_null_input'] = False
with self.VerifiedFunction(self, **kwargs) as vf:
fn_meta = self.keyspace_function_meta[vf.signature]
self.assertRegex(fn_meta.as_cql_query(), "CREATE FUNCTION.*\) RETURNS NULL ON NULL INPUT RETURNS .*")
self.assertRegex(fn_meta.as_cql_query(), r"CREATE FUNCTION.*\) RETURNS NULL ON NULL INPUT RETURNS .*")


@requires_java_udf
Expand Down
18 changes: 9 additions & 9 deletions tests/integration/standard/test_query.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ def test_client_ip_in_trace(self):
client_ip = trace.client

# Ip address should be in the local_host range
pat = re.compile("127.0.0.\d{1,3}")
pat = re.compile(r"127.0.0.\d{1,3}")

# Ensure that ip is set
self.assertIsNotNone(client_ip, "Client IP was not set in trace with C* >= 2.2")
Expand Down Expand Up @@ -496,9 +496,9 @@ def test_prepared_metadata_generation(self):
future = session.execute_async(select_statement)
results = future.result()
if base_line is None:
base_line = results[0]._asdict().keys()
base_line = results.one()._asdict().keys()
else:
self.assertEqual(base_line, results[0]._asdict().keys())
self.assertEqual(base_line, results.one()._asdict().keys())
cluster.shutdown()


Expand Down Expand Up @@ -815,7 +815,7 @@ def test_conditional_update(self):
result = future.result()
self.assertEqual(future.message.serial_consistency_level, ConsistencyLevel.SERIAL)
self.assertTrue(result)
self.assertFalse(result[0].applied)
self.assertFalse(result.one().applied)

statement = SimpleStatement(
"UPDATE test3rf.test SET v=1 WHERE k=0 IF v=0",
Expand All @@ -825,7 +825,7 @@ def test_conditional_update(self):
result = future.result()
self.assertEqual(future.message.serial_consistency_level, ConsistencyLevel.LOCAL_SERIAL)
self.assertTrue(result)
self.assertTrue(result[0].applied)
self.assertTrue(result.one().applied)

def test_conditional_update_with_prepared_statements(self):
self.session.execute("INSERT INTO test3rf.test (k, v) VALUES (0, 0)")
Expand All @@ -837,7 +837,7 @@ def test_conditional_update_with_prepared_statements(self):
result = future.result()
self.assertEqual(future.message.serial_consistency_level, ConsistencyLevel.SERIAL)
self.assertTrue(result)
self.assertFalse(result[0].applied)
self.assertFalse(result.one().applied)

statement = self.session.prepare(
"UPDATE test3rf.test SET v=1 WHERE k=0 IF v=0")
Expand All @@ -847,7 +847,7 @@ def test_conditional_update_with_prepared_statements(self):
result = future.result()
self.assertEqual(future.message.serial_consistency_level, ConsistencyLevel.LOCAL_SERIAL)
self.assertTrue(result)
self.assertTrue(result[0].applied)
self.assertTrue(result.one().applied)

def test_conditional_update_with_batch_statements(self):
self.session.execute("INSERT INTO test3rf.test (k, v) VALUES (0, 0)")
Expand All @@ -858,7 +858,7 @@ def test_conditional_update_with_batch_statements(self):
result = future.result()
self.assertEqual(future.message.serial_consistency_level, ConsistencyLevel.SERIAL)
self.assertTrue(result)
self.assertFalse(result[0].applied)
self.assertFalse(result.one().applied)

statement = BatchStatement(serial_consistency_level=ConsistencyLevel.LOCAL_SERIAL)
statement.add("UPDATE test3rf.test SET v=1 WHERE k=0 IF v=0")
Expand All @@ -867,7 +867,7 @@ def test_conditional_update_with_batch_statements(self):
result = future.result()
self.assertEqual(future.message.serial_consistency_level, ConsistencyLevel.LOCAL_SERIAL)
self.assertTrue(result)
self.assertTrue(result[0].applied)
self.assertTrue(result.one().applied)

def test_bad_consistency_level(self):
statement = SimpleStatement("foo")
Expand Down
2 changes: 1 addition & 1 deletion tests/integration/standard/test_routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def insert_select_token(self, insert, select, key_values):

my_token = s.cluster.metadata.token_map.token_class.from_key(bound.routing_key)

cass_token = s.execute(select, key_values)[0][0]
cass_token = s.execute(select, key_values).one()[0]
token = s.cluster.metadata.token_map.token_class(cass_token)
self.assertEqual(my_token, token)

Expand Down
Loading

0 comments on commit f513e5b

Please sign in to comment.