desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Test to ensure that on down calls to clusters with connections still active don\'t result in a host being marked down. The second part of the test kills the connection then invokes on_down, and ensures the state changes for host\'s metadata. @since 3.7 @jira_ticket PYTHON-498 @expected_result host should never be togg...
def test_down_event_with_active_connection(self):
with Cluster(protocol_version=PROTOCOL_VERSION) as cluster: session = cluster.connect(wait_for_all_pools=True) random_host = cluster.metadata.all_hosts()[0] cluster.on_down(random_host, False) for _ in range(10): new_host = cluster.metadata.all_hosts()[0] self...
'Test duplicate RPC addresses. Modifies the system.peers table to make hosts have the same rpc address. Ensures such hosts are filtered out and a message is logged @since 3.4 @jira_ticket PYTHON-366 @expected_result only one hosts\' metadata will be populated @test_category metadata'
def test_duplicate(self):
mock_handler = MockLoggingHandler() logger = logging.getLogger(cassandra.cluster.__name__) logger.addHandler(mock_handler) test_cluster = Cluster(protocol_version=PROTOCOL_VERSION, load_balancing_policy=self.load_balancing_policy) test_cluster.connect() warnings = mock_handler.messages.get('warn...
'Test cluster connection with protocol v5 and beta flag not set @since 3.7.0 @jira_ticket PYTHON-614 @expected_result client shouldn\'t connect with V5 and no beta flag set @test_category connection'
@protocolv5 def test_invalid_protocol_version_beta_option(self):
cluster = Cluster(protocol_version=cassandra.ProtocolVersion.MAX_SUPPORTED, allow_beta_protocol_version=False) try: with self.assertRaises(NoHostAvailable): cluster.connect() except Exception as e: self.fail('Unexpected error encountered {0}'.format(e.message))
'Test cluster connection with protocol version 5 and beta flag set @since 3.7.0 @jira_ticket PYTHON-614 @expected_result client should connect with protocol v5 and beta flag set. @test_category connection'
@protocolv5 def test_valid_protocol_version_beta_options_connect(self):
cluster = Cluster(protocol_version=cassandra.ProtocolVersion.MAX_SUPPORTED, allow_beta_protocol_version=True) session = cluster.connect() self.assertEqual(cluster.protocol_version, cassandra.ProtocolVersion.MAX_SUPPORTED) self.assertTrue(session.execute('select release_version from system.local...
'Tests that byte strings in Python maps to blob type in Cassandra'
def test_can_insert_blob_type_as_string(self):
s = self.session s.execute('CREATE TABLE blobstring (a ascii PRIMARY KEY, b blob)') params = ['key1', 'blobbyblob'] query = 'INSERT INTO blobstring (a, b) VALUES (%s, %s)' if (six.PY2 and (self.cql_version >= (3, 1, 0))): if (self.cass_version >= ...
'Tests that blob type in Cassandra maps to bytearray in Python'
def test_can_insert_blob_type_as_bytearray(self):
s = self.session s.execute('CREATE TABLE blobbytes (a ascii PRIMARY KEY, b blob)') params = ['key1', bytearray('blob1')] s.execute('INSERT INTO blobbytes (a, b) VALUES (%s, %s)', params) results = s.execute('SELECT * FROM blobbytes')[0] for (...
'Simple test to ensure the DesBytesTypeByteArray deserializer functionally works @since 3.1 @jira_ticket PYTHON-503 @expected_result byte array should be deserialized appropriately. @test_category queries:custom_payload'
@unittest.skipIf((not hasattr(cassandra, 'deserializers')), 'Cython required for to test DesBytesTypeArray deserializer') def test_des_bytes_type_array(self):
original = None try: original = cassandra.deserializers.DesBytesType cassandra.deserializers.DesBytesType = cassandra.deserializers.DesBytesTypeByteArray s = self.session s.execute('CREATE TABLE blobbytes2 (a ascii PRIMARY KEY, b blob)') params = [...
'Test insertion of all datatype primitives'
def test_can_insert_primitive_datatypes(self):
c = Cluster(protocol_version=PROTOCOL_VERSION) s = c.connect(self.keyspace_name) alpha_type_list = ['zz int PRIMARY KEY'] col_names = ['zz'] start_index = ord('a') for (i, datatype) in enumerate(PRIMITIVE_DATATYPES): alpha_type_list.append('{0} {1}'.format(chr((start_index + ...
'Test insertion of all collection types'
def test_can_insert_collection_datatypes(self):
c = Cluster(protocol_version=PROTOCOL_VERSION) s = c.connect(self.keyspace_name) s.encoder.mapping[tuple] = s.encoder.cql_encode_tuple alpha_type_list = ['zz int PRIMARY KEY'] col_names = ['zz'] start_index = ord('a') for (i, collection_type) in enumerate(COLLECTION_TYPES): ...
'Test insertion of empty strings and null values'
def test_can_insert_empty_strings_and_nulls(self):
s = self.session alpha_type_list = ['zz int PRIMARY KEY'] col_names = [] string_types = set(('ascii', 'text', 'varchar')) string_columns = set('') non_string_types = ((PRIMITIVE_DATATYPES - string_types) - set(('blob', 'date', 'inet', 'time', 'timestamp'))) non_string_columns = set(...
'Ensure Int32Type supports empty values'
def test_can_insert_empty_values_for_int32(self):
s = self.session execute_until_pass(s, 'CREATE TABLE empty_values (a text PRIMARY KEY, b int)') execute_until_pass(s, "INSERT INTO empty_values (a, b) VALUES ('a', blobAsInt(0x))") try: Int32Type.support_empty_values = True results = execute_u...
'Ensure timezone-aware datetimes are converted to timestamps correctly'
def test_timezone_aware_datetimes_are_timestamps(self):
try: import pytz except ImportError as exc: raise unittest.SkipTest(('pytz is not available: %r' % (exc,))) dt = datetime(1997, 8, 29, 11, 14) eastern_tz = pytz.timezone('US/Eastern') eastern_tz.localize(dt) s = self.session s.execute('CREATE TABLE tz_aware ...
'Basic test of tuple functionality'
def test_can_insert_tuples(self):
if (self.cass_version < (2, 1, 0)): raise unittest.SkipTest('The tuple type was introduced in Cassandra 2.1') c = Cluster(protocol_version=PROTOCOL_VERSION) s = c.connect(self.keyspace_name) s.encoder.mapping[tuple] = s.encoder.cql_encode_tuple s.execute('CREATE TABLE...
'Test tuple types of lengths of 1, 2, 3, and 384 to ensure edge cases work as expected.'
def test_can_insert_tuples_with_varying_lengths(self):
if (self.cass_version < (2, 1, 0)): raise unittest.SkipTest('The tuple type was introduced in Cassandra 2.1') c = Cluster(protocol_version=PROTOCOL_VERSION) s = c.connect(self.keyspace_name) s.row_factory = dict_factory s.encoder.mapping[tuple] = s.encoder.cql_encode_tup...
'Ensure tuple subtypes are appropriately handled.'
def test_can_insert_tuples_all_primitive_datatypes(self):
if (self.cass_version < (2, 1, 0)): raise unittest.SkipTest('The tuple type was introduced in Cassandra 2.1') c = Cluster(protocol_version=PROTOCOL_VERSION) s = c.connect(self.keyspace_name) s.encoder.mapping[tuple] = s.encoder.cql_encode_tuple s.execute(('CREATE TABL...
'Ensure tuple subtypes are appropriately handled for maps, sets, and lists.'
def test_can_insert_tuples_all_collection_datatypes(self):
if (self.cass_version < (2, 1, 0)): raise unittest.SkipTest('The tuple type was introduced in Cassandra 2.1') c = Cluster(protocol_version=PROTOCOL_VERSION) s = c.connect(self.keyspace_name) s.row_factory = dict_factory s.encoder.mapping[tuple] = s.encoder.cql_encode_tup...
'Helper method for creating nested tuple schema'
def nested_tuples_schema_helper(self, depth):
if (depth == 0): return 'int' else: return ('tuple<%s>' % self.nested_tuples_schema_helper((depth - 1)))
'Helper method for creating nested tuples'
def nested_tuples_creator_helper(self, depth):
if (depth == 0): return 303 else: return (self.nested_tuples_creator_helper((depth - 1)),)
'Ensure nested are appropriately handled.'
def test_can_insert_nested_tuples(self):
if (self.cass_version < (2, 1, 0)): raise unittest.SkipTest('The tuple type was introduced in Cassandra 2.1') c = Cluster(protocol_version=PROTOCOL_VERSION) s = c.connect(self.keyspace_name) s.row_factory = dict_factory s.encoder.mapping[tuple] = s.encoder.cql_encode_tup...
'Test tuples with null and empty string fields.'
def test_can_insert_tuples_with_nulls(self):
if (self.cass_version < (2, 1, 0)): raise unittest.SkipTest('The tuple type was introduced in Cassandra 2.1') s = self.session s.execute('CREATE TABLE tuples_nulls (k int PRIMARY KEY, t frozen<tuple<text, int, uuid, blob>>)') insert = s.prepa...
'Test to ensure unicode strings can be used in a query'
def test_can_insert_unicode_query_string(self):
s = self.session s.execute(u"SELECT * FROM system.local WHERE key = 'ef\u2052ef'") s.execute(u'SELECT * FROM system.local WHERE key = %s', (u'fe\u2051fe',))
'Test to ensure that CompositeTypes can be used in a query'
def test_can_read_composite_type(self):
s = self.session s.execute("\n CREATE TABLE composites (\n a int PRIMARY KEY,\n b 'org.apache.cassandra.db.marshal.Com...
'Test to insure that Infinity -Infinity and NaN are supported by the python driver. @since 3.0.0 @jira_ticket PYTHON-282 @expected_result nan, inf and -inf can be inserted and selected correctly. @test_category data_types'
@notprotocolv1 def test_special_float_cql_encoding(self):
s = self.session s.execute('\n CREATE TABLE float_cql_encoding (\n f float PRIMARY KEY,\n d double\n ...
'Test to validate that decimal deserialization works correctly in with our cython extensions @since 3.0.0 @jira_ticket PYTHON-212 @expected_result no exceptions are thrown, decimal is decoded correctly @test_category data_types serialization'
@cythontest def test_cython_decimal(self):
self.session.execute('CREATE TABLE {0} (dc decimal PRIMARY KEY)'.format(self.function_table_name)) try: self.session.execute('INSERT INTO {0} (dc) VALUES (-1.08430792318105707)'.format(self.function_table_name)) results = self.session.execute('SELECT * FROM...
'Test to write several Duration values to the database and verify they can be read correctly. The verify than an exception is arisen if the value is too big @since 3.10 @jira_ticket PYTHON-747 @expected_result the read value in C* matches the written one @test_category data_types serialization'
@greaterthanorequalcass3_10 def test_smoke_duration_values(self):
self.session.execute('\n CREATE TABLE duration_smoke (k int primary key, v duration)\n ') self.addCleanup(self.session.execute, 'DROP TABLE duration_smoke') prepared = self.session.pre...
'Test to validate that nested type serialization works on various protocol versions. Provided the version of cassandra is greater the 2.1.3 we would expect to nested to types to work at all protocol versions. @since 3.0.0 @jira_ticket PYTHON-215 @expected_result no exceptions are thrown @test_category data_types serial...
@greaterthancass21 @lessthancass30 def test_nested_types_with_protocol_version(self):
ddl = 'CREATE TABLE {0}.t (\n k int PRIMARY KEY,\n v list<frozen<set<int>>>)'.format(self.keyspace_name) self.session.execute(ddl) ddl = 'CREATE TABLE {0}....
'Test to ensure that non frozen udt\'s work with C* >3.6. @since 3.7.0 @jira_ticket PYTHON-498 @expected_result Non frozen UDT\'s are supported @test_category data_types, udt'
@greaterthanorequalcass36 def test_non_frozen_udts(self):
self.session.execute('USE {0}'.format(self.keyspace_name)) self.session.execute('CREATE TYPE user (state text, has_corn boolean)') self.session.execute('CREATE TABLE {0} (a int PRIMARY KEY, b user)'.format(self.function_table_name)) User = namedtuple('user', ...
'Test the insertion of unprepared, registered UDTs'
def test_can_insert_unprepared_registered_udts(self):
c = Cluster(protocol_version=PROTOCOL_VERSION) s = c.connect(self.keyspace_name, wait_for_all_pools=True) s.execute('CREATE TYPE user (age int, name text)') s.execute('CREATE TABLE mytable (a int PRIMARY KEY, b frozen<user>)') User = namedtuple('user', ('age...
'Test the registration of UDTs before session creation'
def test_can_register_udt_before_connecting(self):
c = Cluster(protocol_version=PROTOCOL_VERSION) s = c.connect(wait_for_all_pools=True) s.execute("\n CREATE KEYSPACE udt_test_register_before_connecting\n WITH replication = { 'class' : 'Simp...
'Test the insertion of prepared, unregistered UDTs'
def test_can_insert_prepared_unregistered_udts(self):
c = Cluster(protocol_version=PROTOCOL_VERSION) s = c.connect(self.keyspace_name, wait_for_all_pools=True) s.execute('CREATE TYPE user (age int, name text)') s.execute('CREATE TABLE mytable (a int PRIMARY KEY, b frozen<user>)') User = namedtuple('user', ('age...
'Test the insertion of prepared, registered UDTs'
def test_can_insert_prepared_registered_udts(self):
c = Cluster(protocol_version=PROTOCOL_VERSION) s = c.connect(self.keyspace_name, wait_for_all_pools=True) s.execute('CREATE TYPE user (age int, name text)') User = namedtuple('user', ('age', 'name')) c.register_user_type(self.keyspace_name, 'user', User) s.execute('CREATE TA...
'Test the insertion of UDTs with null and empty string fields'
def test_can_insert_udts_with_nulls(self):
c = Cluster(protocol_version=PROTOCOL_VERSION) s = c.connect(self.keyspace_name, wait_for_all_pools=True) s.execute('CREATE TYPE user (a text, b int, c uuid, d blob)') User = namedtuple('user', ('a', 'b', 'c', 'd')) c.register_user_type(self.keyspace_name, 'user', User)...
'Test for ensuring extra-lengthy udts are properly inserted'
def test_can_insert_udts_with_varying_lengths(self):
c = Cluster(protocol_version=PROTOCOL_VERSION) s = c.connect(self.keyspace_name, wait_for_all_pools=True) MAX_TEST_LENGTH = 254 s.execute('CREATE TYPE lengthy_udt ({0})'.format(', '.join(['v_{0} int'.format(i) for i in range(MAX_TEST_LENGTH)]))) s.execute('CREATE TABLE mytable ...
'Test for ensuring nested registered udts are properly inserted'
def test_can_insert_nested_registered_udts(self):
c = Cluster(protocol_version=PROTOCOL_VERSION) s = c.connect(self.keyspace_name, wait_for_all_pools=True) s.row_factory = dict_factory MAX_NESTING_DEPTH = 16 self.nested_udt_schema_helper(s, MAX_NESTING_DEPTH) udts = [] udt = namedtuple('depth_0', ('age', 'name')) udts.append(udt) c....
'Test for ensuring nested unregistered udts are properly inserted'
def test_can_insert_nested_unregistered_udts(self):
c = Cluster(protocol_version=PROTOCOL_VERSION) s = c.connect(self.keyspace_name, wait_for_all_pools=True) s.row_factory = dict_factory MAX_NESTING_DEPTH = 16 self.nested_udt_schema_helper(s, MAX_NESTING_DEPTH) udts = [] udt = namedtuple('depth_0', ('age', 'name')) udts.append(udt) fo...
'Test for ensuring nested udts are inserted correctly when the created namedtuples are use names that are different the cql type.'
def test_can_insert_nested_registered_udts_with_different_namedtuples(self):
c = Cluster(protocol_version=PROTOCOL_VERSION) s = c.connect(self.keyspace_name, wait_for_all_pools=True) s.row_factory = dict_factory MAX_NESTING_DEPTH = 16 self.nested_udt_schema_helper(s, MAX_NESTING_DEPTH) udts = [] udt = namedtuple('level_0', ('age', 'name')) udts.append(udt) c....
'Test for ensuring that an error is raised for operating on a nonexisting udt or an invalid keyspace'
def test_raise_error_on_nonexisting_udts(self):
c = Cluster(protocol_version=PROTOCOL_VERSION) s = c.connect(self.keyspace_name, wait_for_all_pools=True) User = namedtuple('user', ('age', 'name')) with self.assertRaises(UserTypeDoesNotExist): c.register_user_type('some_bad_keyspace', 'user', User) with self.assertRaises(UserTypeDoesNotExi...
'Test for inserting various types of PRIMITIVE_DATATYPES into UDT\'s'
def test_can_insert_udt_all_datatypes(self):
c = Cluster(protocol_version=PROTOCOL_VERSION) s = c.connect(self.keyspace_name, wait_for_all_pools=True) alpha_type_list = [] start_index = ord('a') for (i, datatype) in enumerate(PRIMITIVE_DATATYPES): alpha_type_list.append('{0} {1}'.format(chr((start_index + i)), datatype)) s.execu...
'Test for inserting various types of COLLECTION_TYPES into UDT\'s'
def test_can_insert_udt_all_collection_datatypes(self):
c = Cluster(protocol_version=PROTOCOL_VERSION) s = c.connect(self.keyspace_name, wait_for_all_pools=True) alpha_type_list = [] start_index = ord('a') for (i, collection_type) in enumerate(COLLECTION_TYPES): for (j, datatype) in enumerate(PRIMITIVE_DATATYPES_KEYS): if (collection_...
'Test for inserting various types of nested COLLECTION_TYPES into tables and UDTs'
def test_can_insert_nested_collections(self):
if (self.cass_version < (2, 1, 3)): raise unittest.SkipTest('Support for nested collections was introduced in Cassandra 2.1.3') c = Cluster(protocol_version=PROTOCOL_VERSION) s = c.connect(self.keyspace_name, wait_for_all_pools=True) s.encoder.mapping[tuple] = s.encoder.c...
'PYTHON-413'
def test_non_alphanum_identifiers(self):
s = self.session non_alphanum_name = 'test.field@#$%@%#!' type_name = 'type2' s.execute(('CREATE TYPE "%s" ("%s" text)' % (non_alphanum_name, non_alphanum_name))) s.execute(('CREATE TYPE %s ("%s" text)' % (type_name, non_alphanum_name))) s.execute(('CREATE TABLE %s ...
'Test to ensure that altered UDT\'s are properly surfaced without needing to restart the underlying session. @since 3.0.0 @jira_ticket PYTHON-226 @expected_result UDT\'s will reflect added columns without a session restart. @test_category data_types, udt'
@lessthancass30 def test_alter_udt(self):
self.session.set_keyspace(self.keyspace_name) self.session.execute('CREATE TYPE typetoalter (a int)') typetoalter = namedtuple('typetoalter', 'a') self.session.execute('CREATE TABLE {0} (pk int primary key, typetoalter frozen<typetoalter>)'.format(self.function_table_...
'Test to validate paging state api @since 3.7.0 @jira_ticket PYTHON-200 @expected_result paging state should returned should be accurate, and allow for queries to be resumed. @test_category queries'
def test_paging_state(self):
statements_and_params = zip(cycle(['INSERT INTO test3rf.test (k, v) VALUES (%s, 0)']), [(i,) for i in range(100)]) execute_concurrent(self.session, list(statements_and_params)) list_all_results = [] self.session.default_fetch_size = 3 result_set = self.session.execute('SELECT ...
'Test to validate callback api @since 3.9.0 @jira_ticket PYTHON-733 @expected_result callbacks shouldn\'t be called twice per message and the fetch_size should be handled in a transparent way to the user @test_category queries'
def test_paging_callbacks(self):
statements_and_params = zip(cycle(['INSERT INTO test3rf.test (k, v) VALUES (%s, 0)']), [(i,) for i in range(100)]) execute_concurrent(self.session, list(statements_and_params)) prepared = self.session.prepare('SELECT * FROM test3rf.test') for fetch_size in (2, 3, 7, 10, 99,...
'Ensure per-statement fetch_sizes override the default fetch size.'
def test_fetch_size(self):
statements_and_params = zip(cycle(['INSERT INTO test3rf.test (k, v) VALUES (%s, 0)']), [(i,) for i in range(100)]) execute_concurrent(self.session, list(statements_and_params)) prepared = self.session.prepare('SELECT * FROM test3rf.test') self.session.default_fetch_size = 1...
'Code coverage to ensure trace prints to string without error'
def test_trace_prints_okay(self):
query = 'SELECT * FROM system.local' statement = SimpleStatement(query) rs = self.session.execute(statement, trace=True) trace = rs.get_query_trace() self.assertTrue(trace.events) str(trace) for event in trace.events: str(event)
'Test to validate, new column deserialization message @since 3.7.0 @jira_ticket PYTHON-361 @expected_result Special failed decoding message should be present @test_category tracing'
def test_row_error_message(self):
self.session.execute('CREATE TABLE {0}.{1} (k int PRIMARY KEY, v timestamp)'.format(self.keyspace_name, self.function_table_name)) ss = SimpleStatement('INSERT INTO {0}.{1} (k, v) VALUES (1, 1000000000000000)'.format(self.keyspace_name, self.function_table_name)) ...
'Test to validate that client trace contains client ip information. creates a simple query and ensures that the client trace information is present. This will only be the case if the c* version is 2.2 or greater @since 2.6.0 @jira_ticket PYTHON-435 @expected_result client address should be present in C* >= 2.2, otherwi...
@local @greaterthanprotocolv3 def test_client_ip_in_trace(self):
query = 'SELECT * FROM system.local' statement = SimpleStatement(query) response_future = self.session.execute_async(statement, trace=True) response_future.result() trace = response_future.get_query_trace(max_wait=10.0) client_ip = trace.client pat = re.compile('127.0.0.\\d{1,3}') ...
'Test to ensure that CL is set correctly honored when executing trace queries. @since 3.3 @jira_ticket PYTHON-435 @expected_result Consistency Levels set on get_query_trace should be honored'
def test_trace_cl(self):
query = 'SELECT * FROM system.local' statement = SimpleStatement(query) response_future = self.session.execute_async(statement, trace=True) response_future.result() with self.assertRaises(Unavailable): response_future.get_query_trace(query_cl=ConsistencyLevel.THREE) self.assertI...
'Tests to ensure that partial tracing works. Creates a table and runs an insert. Then attempt a query with tracing enabled. After the query is run we delete the duration information associated with the trace, and attempt to populate the tracing information. Should fail with wait_for_complete=True, succeed for False. @s...
@notwindows def test_incomplete_query_trace(self):
self.session.execute('CREATE TABLE {0} (k INT, i INT, PRIMARY KEY(k, i))'.format(self.keyspace_table_name)) self.session.execute('INSERT INTO {0} (k, i) VALUES (0, 1)'.format(self.keyspace_table_name)) response_future = self.session.execute_async('SELECT i ...
'Test to ensure column_types are set as part of the result set @since 3.8 @jira_ticket PYTHON-648 @expected_result column_names should be preset. @test_category queries basic'
def test_query_by_id(self):
create_table = 'CREATE TABLE {0}.{1} (id int primary key, m map<int, text>)'.format(self.keyspace_name, self.function_table_name) self.session.execute(create_table) self.session.execute((((('insert into ' + self.keyspace_name) + '.') + self.function_table_name) + " (id, ...
'Test to validate the columns are present on the result set. Preforms a simple query against a table then checks to ensure column names are correct and present and correct. @since 3.0.0 @jira_ticket PYTHON-439 @expected_result column_names should be preset. @test_category queries basic'
def test_column_names(self):
create_table = 'CREATE TABLE {0}.{1}(\n user TEXT,\n game TEXT,\n ...
'Simple code coverage to ensure routing_keys can be accessed'
def test_routing_key(self):
prepared = self.session.prepare('\n INSERT INTO test3rf.test (k, v) VALUES (?, ?)\n ') self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind((1, None)) self.assertEqu...
'Ensure when routing_key_indexes are blank, the routing key should be None'
def test_empty_routing_key_indexes(self):
prepared = self.session.prepare('\n INSERT INTO test3rf.test (k, v) VALUES (?, ?)\n ') prepared.routing_key_indexes = None self.assertIsInstance(prepared, PreparedStatement) bound = pre...
'Basic test that ensures _set_routing_key() overrides the current routing key'
def test_predefined_routing_key(self):
prepared = self.session.prepare('\n INSERT INTO test3rf.test (k, v) VALUES (?, ?)\n ') self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind((1, None)) bound._set_rou...
'Basic test that uses a fake routing_key_index'
def test_multiple_routing_key_indexes(self):
prepared = self.session.prepare('\n INSERT INTO test3rf.test (k, v) VALUES (?, ?)\n ') self.assertIsInstance(prepared, PreparedStatement) prepared.routing_key_indexes = [0, 1] bound = p...
'Ensure that bound.keyspace works as expected'
def test_bound_keyspace(self):
prepared = self.session.prepare('\n INSERT INTO test3rf.test (k, v) VALUES (?, ?)\n ') self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind((1, 2)) self.assertEqual(...
'Test to validate that result metadata is appropriately populated across protocol version In protocol version 1 result metadata is retrieved everytime the statement is issued. In all other protocol versions it\'s set once upon the prepare, then re-used. This test ensures that it manifests it\'s self the same across mul...
def test_prepared_metadata_generation(self):
base_line = None for proto_version in get_supported_protocol_versions(): beta_flag = (True if (proto_version in ProtocolVersion.BETA_VERSIONS) else False) cluster = Cluster(protocol_version=proto_version, allow_beta_protocol_version=beta_flag) session = cluster.connect() select_s...
'Test to validate prepare_on_all_hosts flag is honored. Use a special ForcedHostSwitchPolicy to ensure prepared queries are cycled over nodes that should not have them prepared. Check the logs to insure they are being re-prepared on those nodes @since 3.4.0 @jira_ticket PYTHON-556 @expected_result queries will have to ...
def test_prepare_on_all_hosts(self):
white_list = ForcedHostSwitchPolicy() clus = Cluster(load_balancing_policy=white_list, protocol_version=PROTOCOL_VERSION, prepare_on_all_hosts=False, reprepare_on_up=False) self.addCleanup(clus.shutdown) session = clus.connect(wait_for_all_pools=True) mock_handler = MockLoggingHandler() logger =...
'Test to validate a prepared statement used inside a batch statement is correctly handled by the driver @since 3.10 @jira_ticket PYTHON-706 @expected_result queries will have to re-prepared on hosts that aren\'t the control connection and the batch statement will be sent.'
def test_prepare_batch_statement(self):
white_list = ForcedHostSwitchPolicy() clus = Cluster(load_balancing_policy=white_list, protocol_version=PROTOCOL_VERSION, prepare_on_all_hosts=False, reprepare_on_up=False) self.addCleanup(clus.shutdown) table = ('test3rf.%s' % self._testMethodName.lower()) session = clus.connect(wait_for_all_pools=...
'Test to validate a prepared statement used inside a batch statement is correctly handled by the driver. The metadata might be updated when a table is altered. This tests combines queries not being prepared and an update of the prepared statement metadata @since 3.10 @jira_ticket PYTHON-706 @expected_result queries wil...
def test_prepare_batch_statement_after_alter(self):
white_list = ForcedHostSwitchPolicy() clus = Cluster(load_balancing_policy=white_list, protocol_version=PROTOCOL_VERSION, prepare_on_all_hosts=False, reprepare_on_up=False) self.addCleanup(clus.shutdown) table = ('test3rf.%s' % self._testMethodName.lower()) session = clus.connect(wait_for_all_pools=...
'Highlight the format of printing SimpleStatements'
def test_simple_statement(self):
ss = SimpleStatement('SELECT * FROM test3rf.test', consistency_level=ConsistencyLevel.ONE) self.assertEqual(str(ss), '<SimpleStatement query="SELECT * FROM test3rf.test", consistency=ONE>')
'Highlight the difference between Prepared and Bound statements'
def test_prepared_statement(self):
cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect() prepared = session.prepare('INSERT INTO test3rf.test (k, v) VALUES (?, ?)') prepared.consistency_level = ConsistencyLevel.ONE self.assertEqual(str(prepared), '<PreparedStatement query="INSERT ...
'Test is skipped if run with cql version < 2'
def setUp(self):
if (PROTOCOL_VERSION < 2): raise unittest.SkipTest(('Protocol 2.0+ is required for Lightweight transactions, currently testing against %r' % (PROTOCOL_VERSION,))) self.cluster = Cluster(protocol_version=PROTOCOL_VERSION) self.session = self.cluster.connect() ddl = '...
'Shutdown cluster'
def tearDown(self):
self.session.execute('DROP TABLE test3rf.lwt') self.cluster.shutdown()
'Test for PYTHON-91 "Connection closed after LWT timeout" Verifies that connection to the cluster is not shut down when timeout occurs. Number of iterations can be specified with LWT_ITERATIONS environment variable. Default value is 1000'
def test_no_connection_refused_on_timeout(self):
insert_statement = self.session.prepare('INSERT INTO test3rf.lwt (k, v) VALUES (0, 0) IF NOT EXISTS') delete_statement = self.session.prepare('DELETE FROM test3rf.lwt WHERE k = 0 IF EXISTS') iterations = int(os.getenv('LWT_ITERATIONS', 1000)) stateme...
'batch routing key is inherited from BoundStatement'
def test_rk_from_bound(self):
bound = self.prepared.bind((1, None)) batch = BatchStatement() batch.add(bound) self.assertIsNotNone(batch.routing_key) self.assertEqual(batch.routing_key, bound.routing_key)
'batch routing key is inherited from SimpleStatement'
def test_rk_from_simple(self):
batch = BatchStatement() batch.add(self.simple_statement) self.assertIsNotNone(batch.routing_key) self.assertEqual(batch.routing_key, self.simple_statement.routing_key)
'compound batch inherits the first routing key of the first added statement (bound statement is first)'
def test_inherit_first_rk_bound(self):
bound = self.prepared.bind((100000000, None)) batch = BatchStatement() batch.add('ss with no rk') batch.add(bound) batch.add(self.simple_statement) for i in range(3): batch.add(self.prepared, (i, i)) self.assertIsNotNone(batch.routing_key) self.assertEqual(batch.routing_...
'compound batch inherits the first routing key of the first added statement (Simplestatement is first)'
def test_inherit_first_rk_simple_statement(self):
bound = self.prepared.bind((1, None)) batch = BatchStatement() batch.add('ss with no rk') batch.add(self.simple_statement) batch.add(bound) for i in range(10): batch.add(self.prepared, (i, i)) self.assertIsNotNone(batch.routing_key) self.assertEqual(batch.routing_key, se...
'compound batch inherits the first routing key of the first added statement (prepared statement is first)'
def test_inherit_first_rk_prepared_param(self):
bound = self.prepared.bind((2, None)) batch = BatchStatement() batch.add('ss with no rk') batch.add(self.prepared, (1, 0)) batch.add(bound) batch.add(self.simple_statement) self.assertIsNotNone(batch.routing_key) self.assertEqual(batch.routing_key, self.prepared.bind((1, 0)).rou...
'Test to ensure that cql filtering where clauses are properly supported in the python driver. test_mv_filtering Tests that various complex MV where clauses produce the correct results. It also validates that these results and the grammar is supported appropriately. @since 3.0.0 @jira_ticket PYTHON-399 @expected_result ...
def test_mv_filtering(self):
create_table = 'CREATE TABLE {0}.scores(\n user TEXT,\n game TEXT,\n ...
'Test to validate that unicode query strings are handled appropriately by various query types @since 3.0.0 @jira_ticket PYTHON-334 @expected_result no unicode exceptions are thrown @test_category query'
def test_unicode(self):
unicode_text = u'Fran\xe7ois' batch = BatchStatement(BatchType.LOGGED) batch.add(u'INSERT INTO {0}.{1} (k, v) VALUES (%s, %s)'.format(self.keyspace_name, self.function_table_name), (0, unicode_text)) self.session.execute(batch) self.session.execute(u'INSERT INTO {0}.{1} ...
'Test to validate that generator based results are surfaced correctly Repeatedly inserts data into a a table and attempts to query it. It then validates that the results are returned in the order expected @since 2.7.0 @jira_ticket PYTHON-123 @expected_result all data should be returned in order. @test_category queries:...
def test_execute_concurrent_with_args_generator(self):
for num_statements in (0, 1, 2, 7, 10, 99, 100, 101, 199, 200, 201): statement = SimpleStatement('INSERT INTO test3rf.test (k, v) VALUES (%s, %s)', consistency_level=ConsistencyLevel.QUORUM) parameters = [(i, i) for i in range(num_statements)] results = self.execute_conc...
'Test to validate that generator based results are surfaced correctly when paging is used Inserts data into a a table and attempts to query it. It then validates that the results are returned as expected (no order specified) @since 2.7.0 @jira_ticket PYTHON-123 @expected_result all data should be returned in order. @te...
def test_execute_concurrent_paged_result_generator(self):
if (PROTOCOL_VERSION < 2): raise unittest.SkipTest(('Protocol 2+ is required for Paging, currently testing against %r' % (PROTOCOL_VERSION,))) num_statements = 201 statement = SimpleStatement('INSERT INTO test3rf.test (k, v) VALUES (%s, %s)', consisten...
'Test to validate that custom protocol handlers work with raw row results Connect and validate that the normal protocol handler is used. Re-Connect and validate that the custom protocol handler is used. Re-Connect and validate that the normal protocol handler is used. @since 2.7 @jira_ticket PYTHON-313 @expected_result...
def test_custom_raw_uuid_row_results(self):
cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect(keyspace='custserdes') session.row_factory = tuple_factory result = session.execute('SELECT schema_version FROM system.local') uuid_type = result[0][0] self.assertEqual(type(uuid_type), uuid.UUID) session...
'Test to validate that custom protocol handlers work with varying types of results Connect, create a table with all sorts of data. Query the data, make the sure the custom results handler is used correctly. @since 2.7 @jira_ticket PYTHON-313 @expected_result custom protocol handler is invoked with various result types ...
def test_custom_raw_row_results_all_types(self):
cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect(keyspace='custserdes') session.client_protocol_handler = CustomProtocolHandlerResultMessageTracked session.row_factory = tuple_factory colnames = create_table_with_all_types('alltypes', session, 1) columns_string = ',...
'Test to validate that the _PAGE_SIZE_FLAG is not treated correctly in V4 if the flags are written using write_uint instead of write_int @since 3.9 @jira_ticket PYTHON-713 @expected_result the fetch_size=1 parameter will be ignored @test_category connection'
@greaterthanorequalcass30 def test_protocol_divergence_v4_fail_by_flag_uses_int(self):
self._protocol_divergence_fail_by_flag_uses_int(ProtocolVersion.V4, uses_int_query_flag=False, int_flag=True)
'Test to validate that client warnings can be surfaced @since 2.6.0 @jira_ticket PYTHON-315 @expected_result valid warnings returned @test_assumptions - batch_size_warn_threshold_in_kb: 5 @test_category queries:client_warning'
def test_warning_basic(self):
future = self.session.execute_async(self.warn_batch) future.result() self.assertEqual(len(future.warnings), 1) self.assertRegexpMatches(future.warnings[0], 'Batch.*exceeding.*')
'Test to validate client warning with tracing @since 2.6.0 @jira_ticket PYTHON-315 @expected_result valid warnings returned @test_assumptions - batch_size_warn_threshold_in_kb: 5 @test_category queries:client_warning'
def test_warning_with_trace(self):
future = self.session.execute_async(self.warn_batch, trace=True) future.result() self.assertEqual(len(future.warnings), 1) self.assertRegexpMatches(future.warnings[0], 'Batch.*exceeding.*') self.assertIsNotNone(future.get_query_trace())
'Test to validate client warning with custom payload @since 2.6.0 @jira_ticket PYTHON-315 @expected_result valid warnings returned @test_assumptions - batch_size_warn_threshold_in_kb: 5 @test_category queries:client_warning'
@local def test_warning_with_custom_payload(self):
payload = {'key': 'value'} future = self.session.execute_async(self.warn_batch, custom_payload=payload) future.result() self.assertEqual(len(future.warnings), 1) self.assertRegexpMatches(future.warnings[0], 'Batch.*exceeding.*') self.assertDictEqual(future.custom_payload, payload)
'Test to validate client warning with tracing and client warning @since 2.6.0 @jira_ticket PYTHON-315 @expected_result valid warnings returned @test_assumptions - batch_size_warn_threshold_in_kb: 5 @test_category queries:client_warning'
@local def test_warning_with_trace_and_custom_payload(self):
payload = {'key': 'value'} future = self.session.execute_async(self.warn_batch, trace=True, custom_payload=payload) future.result() self.assertEqual(len(future.warnings), 1) self.assertRegexpMatches(future.warnings[0], 'Batch.*exceeding.*') self.assertIsNotNone(future.get_query_trace()) self...
'Check to ensure that the broadcast and listen adresss is populated correctly @since 3.3 @jira_ticket PYTHON-332 @expected_result They are populated for C*> 2.1.6, 2.2.0 @test_category metadata'
@local def test_broadcast_listen_address(self):
for host in self.cluster.metadata.all_hosts(): self.assertIsNotNone(host.broadcast_address) con = self.cluster.control_connection.get_connections()[0] local_host = con.host listen_addrs = [host.listen_address for host in self.cluster.metadata.all_hosts()] self.assertTrue((local_host in liste...
'Checks the hosts release version and validates that it is equal to the Cassandra version we are using in our test harness. @since 3.3 @jira_ticket PYTHON-301 @expected_result host.release version should match our specified Cassandra version. @test_category metadata'
def test_host_release_version(self):
for host in self.cluster.metadata.all_hosts(): self.assertTrue(host.release_version.startswith(CASSANDRA_VERSION))
'Checks to ensure that hosts that are not resolvable are excluded from the contact point list. @since 3.6 @jira_ticket PYTHON-549 @expected_result Invalid hosts on the contact list should be excluded @test_category metadata'
def test_bad_contact_point(self):
self.assertEqual(len(self.cluster.metadata.all_hosts()), 3)
'Checks to ensure that schema metadata_enabled, and token_metadata_enabled flags work correctly. @since 3.3 @jira_ticket PYTHON-327 @expected_result schema metadata will not be populated when schema_metadata_enabled is fause token_metadata will be missing when token_metadata is set to false @test_category metadata'
def test_schema_metadata_disable(self):
no_schema = Cluster(schema_metadata_enabled=False) no_schema_session = no_schema.connect() self.assertEqual(len(no_schema.metadata.keyspaces), 0) self.assertEqual(no_schema.metadata.export_schema_as_string(), '') no_token = Cluster(token_metadata_enabled=False) no_token_session = no_token.connec...
'Simple test to ensure that the metatdata associated with cluster ordering is surfaced is surfaced correctly. Creates a table with a few clustering keys. Then checks the clustering order associated with clustering columns and ensure it\'s set correctly. @since 3.0.0 @jira_ticket PYTHON-402 @expected_result is_reversed ...
def test_cluster_column_ordering_reversed_metadata(self):
create_statement = self.make_create_statement(['a'], ['b', 'c'], ['d'], compact=True) create_statement += ' AND CLUSTERING ORDER BY (b ASC, c DESC)' self.session.execute(create_statement) tablemeta = self.get_table_metadata() b_column = tablemeta.columns['b'] self.assertF...
'test options for non-size-tiered compaction strategy Creates a table with LeveledCompactionStrategy, specifying one non-default option. Verifies that the option is present in generated CQL, and that other legacy table parameters (min_threshold, max_threshold) are not included. @since 2.6.0 @jira_ticket PYTHON-352 @exp...
def test_non_size_tiered_compaction(self):
create_statement = self.make_create_statement(['a'], [], ['b', 'c']) create_statement += "WITH COMPACTION = {'class': 'LeveledCompactionStrategy', 'tombstone_threshold': '0.3'}" self.session.execute(create_statement) table_meta = self.get_table_metadata() cql = table_meta.export_as...
'test for synchronously refreshing all cluster metadata test_refresh_schema_metadata tests all cluster metadata is refreshed when calling refresh_schema_metadata(). It creates a second cluster object with schema_event_refresh_window=-1 such that schema refreshes are disabled for schema change push events. It then alter...
def test_refresh_schema_metadata(self):
cluster2 = Cluster(protocol_version=PROTOCOL_VERSION, schema_event_refresh_window=(-1)) cluster2.connect() self.assertNotIn('new_keyspace', cluster2.metadata.keyspaces) self.session.execute("CREATE KEYSPACE new_keyspace WITH replication = {'class': 'SimpleStrategy', 'replication_...
'test for synchronously refreshing keyspace metadata test_refresh_keyspace_metadata tests that keyspace metadata is refreshed when calling refresh_keyspace_metadata(). It creates a second cluster object with schema_event_refresh_window=-1 such that schema refreshes are disabled for schema change push events. It then al...
def test_refresh_keyspace_metadata(self):
cluster2 = Cluster(protocol_version=PROTOCOL_VERSION, schema_event_refresh_window=(-1)) cluster2.connect() self.assertTrue(cluster2.metadata.keyspaces[self.keyspace_name].durable_writes) self.session.execute('ALTER KEYSPACE {0} WITH durable_writes = false'.format(self.keyspace_name)) ...
'test for synchronously refreshing table metadata test_refresh_table_metatadata tests that table metadata is refreshed when calling test_refresh_table_metatadata(). It creates a second cluster object with schema_event_refresh_window=-1 such that schema refreshes are disabled for schema change push events. It then alter...
def test_refresh_table_metadata(self):
table_name = 'test' self.session.execute('CREATE TABLE {0}.{1} (a int PRIMARY KEY, b text)'.format(self.keyspace_name, table_name)) cluster2 = Cluster(protocol_version=PROTOCOL_VERSION, schema_event_refresh_window=(-1)) cluster2.connect() self.assertNotIn('c', cluster2.metada...
'test for synchronously refreshing materialized view metadata test_refresh_table_metadata_for_materialized_views tests that materialized view metadata is refreshed when calling test_refresh_table_metatadata() with the materialized view name as the table. It creates a second cluster object with schema_event_refresh_wind...
def test_refresh_metadata_for_mv(self):
if (CASS_SERVER_VERSION < (3, 0)): raise unittest.SkipTest('Materialized views require Cassandra 3.0+') self.session.execute('CREATE TABLE {0}.{1} (a int PRIMARY KEY, b text)'.format(self.keyspace_name, self.function_table_name)) cluster2 = Cluster(protocol_versio...
'test for synchronously refreshing UDT metadata in keyspace test_refresh_user_type_metadata tests that UDT metadata in a keyspace is refreshed when calling refresh_user_type_metadata(). It creates a second cluster object with schema_event_refresh_window=-1 such that schema refreshes are disabled for schema change push ...
def test_refresh_user_type_metadata(self):
if (PROTOCOL_VERSION < 3): raise unittest.SkipTest('Protocol 3+ is required for UDTs, currently testing against {0}'.format(PROTOCOL_VERSION)) cluster2 = Cluster(protocol_version=PROTOCOL_VERSION, schema_event_refresh_window=(-1)) cluster2.connect() self.assertEqual(cl...
'Test to insure that protocol v1/v2 surface UDT metadata changes @since 3.7.0 @jira_ticket PYTHON-106 @expected_result UDT metadata in the keyspace should be updated regardless of protocol version @test_category metadata'
def test_refresh_user_type_metadata_proto_2(self):
supported_versions = get_supported_protocol_versions() if ((2 not in supported_versions) or (CASSANDRA_VERSION < '2.1')): raise unittest.SkipTest('Protocol versions 1 and 2 are not supported in Cassandra version '.format(CASSANDRA_VERSION)) for protocol_version in (1...
'test for synchronously refreshing UDF metadata in keyspace test_refresh_user_function_metadata tests that UDF metadata in a keyspace is refreshed when calling refresh_user_function_metadata(). It creates a second cluster object with schema_event_refresh_window=-1 such that schema refreshes are disabled for schema chan...
def test_refresh_user_function_metadata(self):
if (PROTOCOL_VERSION < 4): raise unittest.SkipTest('Protocol 4+ is required for UDFs, currently testing against {0}'.format(PROTOCOL_VERSION)) cluster2 = Cluster(protocol_version=PROTOCOL_VERSION, schema_event_refresh_window=(-1)) cluster2.connect() self.assertEqual(cl...
'test for synchronously refreshing UDA metadata in keyspace test_refresh_user_aggregate_metadata tests that UDA metadata in a keyspace is refreshed when calling refresh_user_aggregate_metadata(). It creates a second cluster object with schema_event_refresh_window=-1 such that schema refreshes are disabled for schema ch...
def test_refresh_user_aggregate_metadata(self):
if (PROTOCOL_VERSION < 4): raise unittest.SkipTest('Protocol 4+ is required for UDAs, currently testing against {0}'.format(PROTOCOL_VERSION)) cluster2 = Cluster(protocol_version=PROTOCOL_VERSION, schema_event_refresh_window=(-1)) cluster2.connect() self.assertEqual(cl...
'test multiple indices on the same column. Creates a table and two indices. Ensures that both indices metatdata is surface appropriately. @since 3.0.0 @jira_ticket PYTHON-276 @expected_result IndexMetadata is appropriately surfaced @test_category metadata'
def test_multiple_indices(self):
if (CASS_SERVER_VERSION < (3, 0)): raise unittest.SkipTest('Materialized views require Cassandra 3.0+') self.session.execute('CREATE TABLE {0}.{1} (a int PRIMARY KEY, b map<text, int>)'.format(self.keyspace_name, self.function_table_name)) self.session.execute(...
'Test export schema functionality'
def test_export_schema(self):
cluster = Cluster(protocol_version=PROTOCOL_VERSION) cluster.connect() self.assertIsInstance(cluster.metadata.export_schema_as_string(), six.string_types) cluster.shutdown()
'Test export keyspace schema functionality'
def test_export_keyspace_schema(self):
cluster = Cluster(protocol_version=PROTOCOL_VERSION) cluster.connect() for keyspace in cluster.metadata.keyspaces: keyspace_metadata = cluster.metadata.keyspaces[keyspace] self.assertIsInstance(keyspace_metadata.export_as_string(), six.string_types) self.assertIsInstance(keyspace_met...
'Test udt exports'
def test_export_keyspace_schema_udts(self):
if (CASS_SERVER_VERSION < (2, 1, 0)): raise unittest.SkipTest('UDTs were introduced in Cassandra 2.1') if (PROTOCOL_VERSION < 3): raise unittest.SkipTest(('Protocol 3.0+ is required for UDT change events, currently testing against %r' % (PROTOCOL_V...