Skip to content

Commit da874c2

Browse files
Lorak-mmkdkropachev
authored andcommitted
tests: Get rid of self.fail calls
They can be replaced, depending on situation, with: - assert - pytest.raises - pytest.fail
1 parent afc6e0b commit da874c2

15 files changed

+51
-81
lines changed

tests/integration/cqlengine/columns/test_counter_column.py

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
# limitations under the License.
1414

1515
from uuid import uuid4
16+
import pytest
1617

1718
from cassandra.cqlengine import columns
1819
from cassandra.cqlengine.management import sync_table, drop_table
@@ -32,37 +33,28 @@ class TestClassConstruction(BaseCassEngTestCase):
3233

3334
def test_defining_a_non_counter_column_fails(self):
3435
""" Tests that defining a non counter column field in a model with a counter column fails """
35-
try:
36+
with pytest.raises(ModelDefinitionException):
3637
class model(Model):
3738
partition = columns.UUID(primary_key=True, default=uuid4)
3839
counter = columns.Counter()
3940
text = columns.Text()
40-
self.fail("did not raise expected ModelDefinitionException")
41-
except ModelDefinitionException:
42-
pass
4341

4442

4543
def test_defining_a_primary_key_counter_column_fails(self):
4644
""" Tests that defining primary keys on counter columns fails """
47-
try:
45+
with pytest.raises(TypeError):
4846
class model(Model):
4947
partition = columns.UUID(primary_key=True, default=uuid4)
5048
cluster = columns.Counter(primary_ley=True)
5149
counter = columns.Counter()
52-
self.fail("did not raise expected TypeError")
53-
except TypeError:
54-
pass
5550

5651
# force it
57-
try:
52+
with pytest.raises(ModelDefinitionException):
5853
class model(Model):
5954
partition = columns.UUID(primary_key=True, default=uuid4)
6055
cluster = columns.Counter()
6156
cluster.primary_key = True
6257
counter = columns.Counter()
63-
self.fail("did not raise expected ModelDefinitionException")
64-
except ModelDefinitionException:
65-
pass
6658

6759

6860
class TestCounterColumn(BaseCassEngTestCase):

tests/integration/long/test_consistency.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import sys
1818
import time
1919
import traceback
20+
import pytest
2021

2122
from cassandra import ConsistencyLevel, OperationTimedOut, ReadTimeout, WriteTimeout, Unavailable
2223
from cassandra.cluster import ExecutionProfile, EXEC_PROFILE_DEFAULT
@@ -51,12 +52,12 @@ def setUp(self):
5152
self.coordinator_stats = CoordinatorStats()
5253

5354
def _cl_failure(self, consistency_level, e):
54-
self.fail('Instead of success, saw %s for CL.%s:\n\n%s' % (
55+
pytest.fail('Instead of success, saw %s for CL.%s:\n\n%s' % (
5556
e, ConsistencyLevel.value_to_name[consistency_level],
5657
traceback.format_exc()))
5758

5859
def _cl_expected_failure(self, cl):
59-
self.fail('Test passed at ConsistencyLevel.%s:\n\n%s' % (
60+
pytest.fail('Test passed at ConsistencyLevel.%s:\n\n%s' % (
6061
ConsistencyLevel.value_to_name[cl], traceback.format_exc()))
6162

6263
def _insert(self, session, keyspace, count, consistency_level=ConsistencyLevel.ONE):
@@ -360,6 +361,3 @@ def test_pool_with_host_down(self):
360361
start(node_to_stop)
361362
wait_for_up(cluster, node_to_stop)
362363
cluster.shutdown()
363-
364-
365-

tests/integration/long/test_loadbalancingpolicies.py

Lines changed: 8 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
import struct
1717
import sys
1818
import traceback
19+
import pytest
1920
from cassandra import cqltypes
2021

2122
from cassandra import ConsistencyLevel, Unavailable, OperationTimedOut, ReadTimeout, ReadFailure, \
@@ -397,11 +398,8 @@ def test_dc_aware_roundrobin_one_remote_host(self):
397398
self.coordinator_stats.reset_counts()
398399
force_stop(2)
399400

400-
try:
401+
with pytest.raises(NoHostAvailable):
401402
self._query(session, keyspace)
402-
self.fail()
403-
except NoHostAvailable:
404-
pass
405403

406404
def test_token_aware(self):
407405
keyspace = 'test_token_aware'
@@ -436,13 +434,11 @@ def token_aware(self, keyspace, use_prepared=False):
436434
force_stop(2)
437435
self._wait_for_nodes_down([2], cluster)
438436

439-
try:
437+
with pytest.raises(Unavailable) as e:
440438
self._query(session, keyspace, use_prepared=use_prepared)
441-
self.fail()
442-
except Unavailable as e:
443-
assert e.consistency == 1
444-
assert e.required_replicas == 1
445-
assert e.alive_replicas == 0
439+
assert e.value.consistency == 1
440+
assert e.value.required_replicas == 1
441+
assert e.value.alive_replicas == 0
446442

447443
self.coordinator_stats.reset_counts()
448444
start(2)
@@ -458,11 +454,8 @@ def token_aware(self, keyspace, use_prepared=False):
458454
stop(2)
459455
self._wait_for_nodes_down([2], cluster)
460456

461-
try:
457+
with pytest.raises(Unavailable):
462458
self._query(session, keyspace, use_prepared=use_prepared)
463-
self.fail()
464-
except Unavailable:
465-
pass
466459

467460
self.coordinator_stats.reset_counts()
468461
start(2)
@@ -717,11 +710,8 @@ def test_white_list(self):
717710
force_stop(2)
718711
self._wait_for_nodes_down([2])
719712

720-
try:
713+
with pytest.raises(NoHostAvailable):
721714
self._query(session, keyspace)
722-
self.fail()
723-
except NoHostAvailable:
724-
pass
725715

726716
def test_black_list_with_host_filter_policy(self):
727717
"""

tests/integration/standard/test_cluster.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import warnings
2525
from packaging.version import Version
2626
import os
27+
import pytest
2728

2829
import cassandra
2930
from cassandra.cluster import NoHostAvailable, ExecutionProfile, EXEC_PROFILE_DEFAULT, ControlConnection, Cluster
@@ -1490,7 +1491,7 @@ def test_invalid_protocol_version_beta_option(self):
14901491
with self.assertRaises(NoHostAvailable):
14911492
cluster.connect()
14921493
except Exception as e:
1493-
self.fail("Unexpected error encountered {0}".format(e.message))
1494+
pytest.fail("Unexpected error encountered {0}".format(e.message))
14941495

14951496
@protocolv6
14961497
def test_valid_protocol_version_beta_options_connect(self):

tests/integration/standard/test_connection.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
from threading import Thread, Event
2323
import time
2424
from unittest import SkipTest
25+
import pytest
2526

2627
from cassandra import ConsistencyLevel, OperationTimedOut, DependencyException
2728
from cassandra.cluster import NoHostAvailable, ConnectionShutdown, ExecutionProfile, EXEC_PROFILE_DEFAULT
@@ -179,7 +180,7 @@ def wait_for_connections(self, host, cluster):
179180
if connections:
180181
return connections
181182
time.sleep(.1)
182-
self.fail("No new connections found")
183+
pytest.fail("No new connections found")
183184

184185
def wait_for_no_connections(self, host, cluster):
185186
retry = 0
@@ -189,7 +190,7 @@ def wait_for_no_connections(self, host, cluster):
189190
if not connections:
190191
return
191192
time.sleep(.5)
192-
self.fail("Connections never cleared")
193+
pytest.fail("Connections never cleared")
193194

194195

195196
class ConnectionTests(object):

tests/integration/standard/test_metadata.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1349,8 +1349,7 @@ def send_msg(self, msg, request_id, cb, encoder=ProtocolHandler.encode_message,
13491349
for stmt in stmts:
13501350
if "SELECT now() FROM system.local WHERE key='local'" in stmt:
13511351
continue
1352-
if "USING TIMEOUT 2000ms" not in stmt:
1353-
self.fail(f"query `{stmt}` does not contain `USING TIMEOUT 2000ms`")
1352+
assert "USING TIMEOUT 2000ms" in stmt, f"query `{stmt}` does not contain `USING TIMEOUT 2000ms`"
13541353

13551354

13561355
class KeyspaceAlterMetadata(unittest.TestCase):

tests/integration/standard/test_query.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -937,13 +937,13 @@ def test_no_connection_refused_on_timeout(self):
937937
# In this case result is an exception
938938
exception_type = type(result).__name__
939939
if exception_type == "NoHostAvailable":
940-
self.fail("PYTHON-91: Disconnected from Cassandra: %s" % result.message)
940+
pytest.fail("PYTHON-91: Disconnected from Cassandra: %s" % result.message)
941941
if exception_type in ["WriteTimeout", "WriteFailure", "ReadTimeout", "ReadFailure", "ErrorMessageSub"]:
942942
if type(result).__name__ in ["WriteTimeout", "WriteFailure"]:
943943
received_timeout = True
944944
continue
945945

946-
self.fail("Unexpected exception %s: %s" % (exception_type, result.message))
946+
pytest.fail("Unexpected exception %s: %s" % (exception_type, result.message))
947947

948948
# Make sure test passed
949949
assert received_timeout

tests/integration/standard/test_query_paging.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020

2121
from itertools import cycle, count
2222
from threading import Event
23+
import pytest
2324

2425
from cassandra import ConsistencyLevel
2526
from cassandra.cluster import EXEC_PROFILE_DEFAULT, ExecutionProfile
@@ -289,7 +290,7 @@ def handle_page(rows, future, counter, number_of_calls):
289290

290291
def handle_error(err):
291292
event.set()
292-
self.fail(err)
293+
pytest.fail(err)
293294

294295
future.add_callbacks(callback=handle_page, callback_args=(future, counter, number_of_calls),
295296
errback=handle_error)

tests/integration/standard/test_row_factories.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
BasicSharedKeyspaceUnitTestCaseWFunctionTable, BasicSharedKeyspaceUnitTestCase, execute_until_pass, TestCluster
1717

1818
import unittest
19+
import pytest
1920

2021
from cassandra.cluster import ResultSet, ExecutionProfile, EXEC_PROFILE_DEFAULT
2122
from cassandra.query import tuple_factory, named_tuple_factory, dict_factory, ordered_dict_factory
@@ -194,7 +195,7 @@ def test_no_exception_on_select(self):
194195
try:
195196
self.session.execute('SELECT * FROM test1rf.table_num_col')
196197
except ValueError as e:
197-
self.fail("Unexpected ValueError exception: %s" % e.message)
198+
pytest.fail("Unexpected ValueError exception: %s" % e.message)
198199

199200
def test_can_select_using_alias(self):
200201
"""
@@ -206,7 +207,7 @@ def test_can_select_using_alias(self):
206207
try:
207208
self.session.execute('SELECT key, "626972746864617465" AS my_col from test1rf.table_num_col')
208209
except ValueError as e:
209-
self.fail("Unexpected ValueError exception: %s" % e.message)
210+
pytest.fail("Unexpected ValueError exception: %s" % e.message)
210211

211212
def test_can_select_with_dict_factory(self):
212213
"""
@@ -218,4 +219,4 @@ def test_can_select_with_dict_factory(self):
218219
try:
219220
cluster.connect().execute('SELECT * FROM test1rf.table_num_col')
220221
except ValueError as e:
221-
self.fail("Unexpected ValueError exception: %s" % e.message)
222+
pytest.fail("Unexpected ValueError exception: %s" % e.message)

tests/integration/standard/test_single_interface.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
# limitations under the License.
1414

1515
import unittest
16+
import pytest
1617

1718
from cassandra import ConsistencyLevel
1819
from cassandra.query import SimpleStatement
@@ -58,11 +59,9 @@ def test_single_interface(self):
5859
assert endpoint.address == host.broadcast_rpc_address
5960
assert endpoint.port == host.broadcast_rpc_port
6061

61-
if host.broadcast_rpc_port in broadcast_rpc_ports:
62-
self.fail("Duplicate broadcast_rpc_port")
62+
assert host.broadcast_rpc_port not in broadcast_rpc_ports, "Duplicate broadcast_rpc_port"
6363
broadcast_rpc_ports.append(host.broadcast_rpc_port)
64-
if host.broadcast_port in broadcast_ports:
65-
self.fail("Duplicate broadcast_port")
64+
assert host.broadcast_port not in broadcast_ports, "Duplicate broadcast_port"
6665
broadcast_ports.append(host.broadcast_port)
6766

6867
for _ in range(1, 100):

0 commit comments

Comments
 (0)