desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Stable de-duplication of library names in the list >>> l = LibraryList([\'/dir1/liba.a\', \'/dir2/libb.a\', \'/dir3/liba.so\']) >>> l.names [\'a\', \'b\'] Returns: list of strings: A list of library names'
@property def names(self):
return list(dedupe((x.split('.')[0][3:] for x in self.basenames)))
'Search flags for the libraries >>> l = LibraryList([\'/dir1/liba.a\', \'/dir2/libb.a\', \'/dir1/liba.so\']) >>> l.search_flags \'-L/dir1 -L/dir2\' Returns: str: A joined list of search flags'
@property def search_flags(self):
return ' '.join([('-L' + x) for x in self.directories])
'Link flags for the libraries >>> l = LibraryList([\'/dir1/liba.a\', \'/dir2/libb.a\', \'/dir1/liba.so\']) >>> l.link_flags \'-la -lb\' Returns: str: A joined list of link flags'
@property def link_flags(self):
return ' '.join([('-l' + name) for name in self.names])
'Search flags + link flags >>> l = LibraryList([\'/dir1/liba.a\', \'/dir2/libb.a\', \'/dir1/liba.so\']) >>> l.ld_flags \'-L/dir1 -L/dir2 -la -lb\' Returns: str: A joined list of search flags and link flags'
@property def ld_flags(self):
return ((self.search_flags + ' ') + self.link_flags)
'Construct a new lock on the file at ``path``. By default, the lock applies to the whole file. Optionally, caller can specify a byte range beginning ``start`` bytes from the start of the file and extending ``length`` bytes from there. This exposes a subset of fcntl locking functionality. It does not currently expose the ``whence`` parameter -- ``whence`` is always ``os.SEEK_SET`` and ``start`` is always evaluated from the beginning of the file.'
def __init__(self, path, start=0, length=0):
self.path = path self._file = None self._reads = 0 self._writes = 0 self._start = start self._length = length self.pid = self.old_pid = None self.host = self.old_host = None
'This takes a lock using POSIX locks (``fnctl.lockf``). The lock is implemented as a spin lock using a nonblocking call to ``lockf()``. On acquiring an exclusive lock, the lock writes this process\'s pid and host to the lock file, in case the holding process needs to be killed later. If the lock times out, it raises a ``LockError``.'
def _lock(self, op, timeout=_default_timeout):
start_time = time.time() while ((time.time() - start_time) < timeout): try: if (op == fcntl.LOCK_EX): if (self._file and (self._file.mode == 'r')): raise LockError(("Can't take exclusive lock on read-only file: %s" % self.path)) if (self._file is None): self._ensure_parent_directory() (os_mode, fd_mode) = ((os.O_RDWR | os.O_CREAT), 'r+') if (os.path.exists(self.path) and (not os.access(self.path, os.W_OK))): (os_mode, fd_mode) = (os.O_RDONLY, 'r') fd = os.open(self.path, os_mode) self._file = os.fdopen(fd, fd_mode) fcntl.lockf(self._file, (op | fcntl.LOCK_NB), self._length, self._start, os.SEEK_SET) self._read_lock_data() if (op == fcntl.LOCK_EX): self._write_lock_data() return except IOError as e: if (e.errno in (errno.EAGAIN, errno.EACCES)): pass else: raise time.sleep(_sleep_time) raise LockError('Timed out waiting for lock.')
'Read PID and host data out of the file if it is there.'
def _read_lock_data(self):
line = self._file.read() if line: (pid, host) = line.strip().split(',') (_, _, self.pid) = pid.rpartition('=') (_, _, self.host) = host.rpartition('=')
'Write PID and host data to the file, recording old values.'
def _write_lock_data(self):
self.old_pid = self.pid self.old_host = self.host self.pid = os.getpid() self.host = socket.getfqdn() self._file.seek(0) self._file.write(('pid=%s,host=%s' % (self.pid, self.host))) self._file.truncate() self._file.flush() os.fsync(self._file.fileno())
'Releases a lock using POSIX locks (``fcntl.lockf``) Releases the lock regardless of mode. Note that read locks may be masquerading as write locks, but this removes either.'
def _unlock(self):
fcntl.lockf(self._file, fcntl.LOCK_UN, self._length, self._start, os.SEEK_SET) self._file.close() self._file = None
'Acquires a recursive, shared lock for reading. Read and write locks can be acquired and released in arbitrary order, but the POSIX lock is held until all local read and write locks are released. Returns True if it is the first acquire and actually acquires the POSIX lock, False if it is a nested transaction.'
def acquire_read(self, timeout=_default_timeout):
if ((self._reads == 0) and (self._writes == 0)): tty.debug('READ LOCK: {0.path}[{0._start}:{0._length}] [Acquiring]'.format(self)) self._lock(fcntl.LOCK_SH, timeout=timeout) tty.debug('READ LOCK: {0.path}[{0._start}:{0._length}] [Acquired]'.format(self)) self._reads += 1 return True else: self._reads += 1 return False
'Acquires a recursive, exclusive lock for writing. Read and write locks can be acquired and released in arbitrary order, but the POSIX lock is held until all local read and write locks are released. Returns True if it is the first acquire and actually acquires the POSIX lock, False if it is a nested transaction.'
def acquire_write(self, timeout=_default_timeout):
if (self._writes == 0): tty.debug('WRITE LOCK: {0.path}[{0._start}:{0._length}] [Acquiring]'.format(self)) self._lock(fcntl.LOCK_EX, timeout=timeout) tty.debug('WRITE LOCK: {0.path}[{0._start}:{0._length}] [Acquired]'.format(self)) self._writes += 1 return True else: self._writes += 1 return False
'Releases a read lock. Returns True if the last recursive lock was released, False if there are still outstanding locks. Does limited correctness checking: if a read lock is released when none are held, this will raise an assertion error.'
def release_read(self):
assert (self._reads > 0) if ((self._reads == 1) and (self._writes == 0)): tty.debug('READ LOCK: {0.path}[{0._start}:{0._length}] [Released]'.format(self)) self._unlock() self._reads -= 1 return True else: self._reads -= 1 return False
'Releases a write lock. Returns True if the last recursive lock was released, False if there are still outstanding locks. Does limited correctness checking: if a read lock is released when none are held, this will raise an assertion error.'
def release_write(self):
assert (self._writes > 0) if ((self._writes == 1) and (self._reads == 0)): tty.debug('WRITE LOCK: {0.path}[{0._start}:{0._length}] [Released]'.format(self)) self._unlock() self._writes -= 1 return True else: self._writes -= 1 return False
'__recvall(bytes) -> data Receive EXACTLY the number of bytes requested from the socket. Blocks until the required number of bytes have been received.'
def __recvall(self, bytes):
data = '' while (len(data) < bytes): data = (data + self.recv((bytes - len(data)))) return data
'setproxy(proxytype, addr[, port[, rdns[, username[, password]]]]) Sets the proxy to be used. proxytype - The type of the proxy to be used. Three types are supported: PROXY_TYPE_SOCKS4 (including socks4a), PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP addr - The address of the server (IP or DNS). port - The port of the server. Defaults to 1080 for SOCKS servers and 8080 for HTTP proxy servers. rdns - Should DNS queries be preformed on the remote side (rather than the local side). The default is True. Note: This has no effect with SOCKS4 servers. username - Username to authenticate with to the server. The default is no authentication. password - Password to authenticate with to the server. Only relevant when username is also provided.'
def setproxy(self, proxytype=None, addr=None, port=None, rdns=True, username=None, password=None):
self.__proxy = (proxytype, addr, port, rdns, username, password)
'__negotiatesocks5(self,destaddr,destport) Negotiates a connection through a SOCKS5 server.'
def __negotiatesocks5(self, destaddr, destport):
if ((self.__proxy[4] != None) and (self.__proxy[5] != None)): self.sendall('\x05\x02\x00\x02') else: self.sendall('\x05\x01\x00') chosenauth = self.__recvall(2) if (chosenauth[0] != '\x05'): self.close() raise GeneralProxyError((1, _generalerrors[1])) if (chosenauth[1] == '\x00'): pass elif (chosenauth[1] == '\x02'): self.sendall((((('\x01' + chr(len(self.__proxy[4]))) + self.__proxy[4]) + chr(len(self.__proxy[5]))) + self.__proxy[5])) authstat = self.__recvall(2) if (authstat[0] != '\x01'): self.close() raise GeneralProxyError((1, _generalerrors[1])) if (authstat[1] != '\x00'): self.close() raise Socks5AuthError((3, _socks5autherrors[3])) else: self.close() if (chosenauth[1] == '\xff'): raise Socks5AuthError((2, _socks5autherrors[2])) else: raise GeneralProxyError((1, _generalerrors[1])) req = '\x05\x01\x00' try: ipaddr = socket.inet_aton(destaddr) req = ((req + '\x01') + ipaddr) except socket.error: if (self.__proxy[3] == True): ipaddr = None req = (((req + '\x03') + chr(len(destaddr))) + destaddr) else: ipaddr = socket.inet_aton(socket.gethostbyname(destaddr)) req = ((req + '\x01') + ipaddr) req = (req + struct.pack('>H', destport)) self.sendall(req) resp = self.__recvall(4) if (resp[0] != '\x05'): self.close() raise GeneralProxyError((1, _generalerrors[1])) elif (resp[1] != '\x00'): self.close() if (ord(resp[1]) <= 8): raise Socks5Error(ord(resp[1]), _socks5errors[ord(resp[1])]) else: raise Socks5Error(9, _socks5errors[9]) elif (resp[3] == '\x01'): boundaddr = self.__recvall(4) elif (resp[3] == '\x03'): resp = (resp + self.recv(1)) boundaddr = self.__recvall(resp[4]) else: self.close() raise GeneralProxyError((1, _generalerrors[1])) boundport = struct.unpack('>H', self.__recvall(2))[0] self.__proxysockname = (boundaddr, boundport) if (ipaddr != None): self.__proxypeername = (socket.inet_ntoa(ipaddr), destport) else: self.__proxypeername = (destaddr, destport)
'getsockname() -> address info Returns the bound IP address and port number at the proxy.'
def getproxysockname(self):
return self.__proxysockname
'getproxypeername() -> address info Returns the IP and port number of the proxy.'
def getproxypeername(self):
return _orgsocket.getpeername(self)
'getpeername() -> address info Returns the IP address and port number of the destination machine (note: getproxypeername returns the proxy)'
def getpeername(self):
return self.__proxypeername
'__negotiatesocks4(self,destaddr,destport) Negotiates a connection through a SOCKS4 server.'
def __negotiatesocks4(self, destaddr, destport):
rmtrslv = False try: ipaddr = socket.inet_aton(destaddr) except socket.error: if (self.__proxy[3] == True): ipaddr = '\x00\x00\x00\x01' rmtrslv = True else: ipaddr = socket.inet_aton(socket.gethostbyname(destaddr)) req = (('\x04\x01' + struct.pack('>H', destport)) + ipaddr) if (self.__proxy[4] != None): req = (req + self.__proxy[4]) req = (req + '\x00') if (rmtrslv == True): req = ((req + destaddr) + '\x00') self.sendall(req) resp = self.__recvall(8) if (resp[0] != '\x00'): self.close() raise GeneralProxyError((1, _generalerrors[1])) if (resp[1] != 'Z'): self.close() if (ord(resp[1]) in (91, 92, 93)): self.close() raise Socks4Error((ord(resp[1]), _socks4errors[(ord(resp[1]) - 90)])) else: raise Socks4Error((94, _socks4errors[4])) self.__proxysockname = (socket.inet_ntoa(resp[4:]), struct.unpack('>H', resp[2:4])[0]) if (rmtrslv != None): self.__proxypeername = (socket.inet_ntoa(ipaddr), destport) else: self.__proxypeername = (destaddr, destport)
'__negotiatehttp(self,destaddr,destport) Negotiates a connection through an HTTP server.'
def __negotiatehttp(self, destaddr, destport):
if (self.__proxy[3] == False): addr = socket.gethostbyname(destaddr) else: addr = destaddr self.sendall(((((((('CONNECT ' + addr) + ':') + str(destport)) + ' HTTP/1.1\r\n') + 'Host: ') + destaddr) + '\r\n\r\n')) resp = self.recv(1) while (resp.find('\r\n\r\n') == (-1)): resp = (resp + self.recv(1)) statusline = resp.splitlines()[0].split(' ', 2) if (statusline[0] not in ('HTTP/1.0', 'HTTP/1.1')): self.close() raise GeneralProxyError((1, _generalerrors[1])) try: statuscode = int(statusline[1]) except ValueError: self.close() raise GeneralProxyError((1, _generalerrors[1])) if (statuscode != 200): self.close() raise HTTPError((statuscode, statusline[2])) self.__proxysockname = ('0.0.0.0', 0) self.__proxypeername = (addr, destport)
'connect(self,despair) Connects to the specified destination through a proxy. destpar - A tuple of the IP/DNS address and the port number. (identical to socket\'s connect). To select the proxy server use setproxy().'
def connect(self, destpair):
if ((type(destpair) in (list, tuple) == False) or (len(destpair) < 2) or (type(destpair[0]) != str) or (type(destpair[1]) != int)): raise GeneralProxyError((5, _generalerrors[5])) if (self.__proxy[0] == PROXY_TYPE_SOCKS5): if (self.__proxy[2] != None): portnum = self.__proxy[2] else: portnum = 1080 _orgsocket.connect(self, (self.__proxy[1], portnum)) self.__negotiatesocks5(destpair[0], destpair[1]) elif (self.__proxy[0] == PROXY_TYPE_SOCKS4): if (self.__proxy[2] != None): portnum = self.__proxy[2] else: portnum = 1080 _orgsocket.connect(self, (self.__proxy[1], portnum)) self.__negotiatesocks4(destpair[0], destpair[1]) elif (self.__proxy[0] == PROXY_TYPE_HTTP): if (self.__proxy[2] != None): portnum = self.__proxy[2] else: portnum = 8080 _orgsocket.connect(self, (self.__proxy[1], portnum)) self.__negotiatehttp(destpair[0], destpair[1]) elif (self.__proxy[0] == None): _orgsocket.connect(self, (destpair[0], destpair[1])) else: raise GeneralProxyError((4, _generalerrors[4]))
'Test to ensure that speculative execution honors LBP, and that they retry appropriately. This test will use various LBP, and ConstantSpeculativeExecutionPolicy settings and ensure the proper number of hosts are queried @since 3.7.0 @jira_ticket PYTHON-218 @expected_result speculative retries should honor max retries, idempotent state of queries, and underlying lbp. @test_category metadata'
@greaterthancass21 def test_speculative_execution(self):
query_to_prime = 'INSERT INTO test3rf.test (k, v) VALUES (0, 1);' prime_query(query_to_prime, then={'delay_in_ms': 4000}) statement = SimpleStatement(query_to_prime, is_idempotent=True) statement_non_idem = SimpleStatement(query_to_prime, is_idempotent=False) result = self.session.execute(statement, execution_profile='spec_ep_brr') self.assertEqual(21, len(result.response_future.attempted_hosts)) result = self.session.execute(statement, execution_profile='spec_ep_rr') self.assertEqual(3, len(result.response_future.attempted_hosts)) result = self.session.execute(statement, execution_profile='spec_ep_rr_lim') self.assertEqual(2, len(result.response_future.attempted_hosts)) result = self.session.execute(statement_non_idem, execution_profile='spec_ep_brr') self.assertEqual(1, len(result.response_future.attempted_hosts)) result = self.session.execute(statement_non_idem) self.assertEqual(1, len(result.response_future.attempted_hosts)) result = self.session.execute(statement) self.assertEqual(1, len(result.response_future.attempted_hosts)) with self.assertRaises(OperationTimedOut): self.session.execute(statement, execution_profile='spec_ep_rr', timeout=0.5) prepared_query_to_prime = 'SELECT * FROM test3rf.test where k = ?' when = {'params': {'k': '0'}, 'param_types': {'k': 'ascii'}} prime_query(prepared_query_to_prime, when=when, then={'delay_in_ms': 4000}) prepared_statement = self.session.prepare(prepared_query_to_prime) result = self.session.execute(prepared_statement, ('0',), execution_profile='spec_ep_brr') self.assertEqual(1, len(result.response_future.attempted_hosts)) prepared_statement.is_idempotent = True result = self.session.execute(prepared_statement, ('0',), execution_profile='spec_ep_brr') self.assertLess(1, len(result.response_future.attempted_hosts))
'Test to ensure the timeout is honored when using speculative execution @since 3.10 @jira_ticket PYTHON-750 @expected_result speculative retries be schedule every fixed period, during the maximum period of the timeout. @test_category metadata'
def test_speculative_and_timeout(self):
prime_query('INSERT INTO test3rf.test (k, v) VALUES (0, 1);', then=NO_THEN) statement = SimpleStatement('INSERT INTO test3rf.test (k, v) VALUES (0, 1);', is_idempotent=True) response_future = self.session.execute_async(statement, execution_profile='spec_ep_brr_lim', timeout=2.2) response_future._event.wait(4) self.assertIsInstance(response_future._final_exception, OperationTimedOut) self.assertEqual(len(response_future.attempted_hosts), 6)
'This information has to be primed for the test harness to run'
def prime_server_versions(self):
system_local_row = {} system_local_row['cql_version'] = CASSANDRA_VERSION system_local_row['release_version'] = (CASSANDRA_VERSION + '-SNAPSHOT') column_types = {'cql_version': 'ascii', 'release_version': 'ascii'} system_local = PrimeQuery('SELECT cql_version, release_version FROM system.local', rows=[system_local_row], column_types=column_types) self.submit_request(system_local)
'Clear all the primed queries from a particular cluster :param cluster_name: cluster to clear queries from'
def clear_all_queries(self, cluster_name=DEFAULT_CLUSTER):
opener = build_opener(HTTPHandler) request = Request('http://{0}/{1}/{2}'.format(self.admin_addr, 'prime', cluster_name)) request.get_method = (lambda : 'DELETE') connection = opener.open(request) return connection.read()
'Test to ensure the hosts are marked as down after a OTO is received. Also to ensure this happens within the expected timeout @since 3.10 @jira_ticket PYTHON-762 @expected_result all the hosts have been marked as down at some point @test_category metadata'
def test_heart_beat_timeout(self):
number_of_dcs = 3 nodes_per_dc = 100 query_to_prime = 'INSERT INTO test3rf.test (k, v) VALUES (0, 1);' idle_heartbeat_timeout = 5 idle_heartbeat_interval = 1 start_and_prime_cluster_defaults(number_of_dcs, nodes_per_dc, CASSANDRA_VERSION) self.addCleanup(stop_simulacron) listener = TrackDownListener() executor = ThreadTracker(max_workers=16) cluster = Cluster(compression=False, idle_heartbeat_interval=idle_heartbeat_interval, idle_heartbeat_timeout=idle_heartbeat_timeout, executor_threads=16, execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(load_balancing_policy=RoundRobinPolicy())}) self.addCleanup(cluster.shutdown) cluster.scheduler.shutdown() cluster.executor = executor cluster.scheduler = _Scheduler(executor) session = cluster.connect(wait_for_all_pools=True) cluster.register_listener(listener) log = logging.getLogger() log.setLevel('CRITICAL') self.addCleanup(log.setLevel, 'DEBUG') prime_query(query_to_prime, then=NO_THEN) futures = [] for _ in range((number_of_dcs * nodes_per_dc)): future = session.execute_async(query_to_prime) futures.append(future) for f in futures: f._event.wait() self.assertIsInstance(f._final_exception, OperationTimedOut) prime_request(PrimeOptions(then=NO_THEN)) time.sleep(((idle_heartbeat_timeout + idle_heartbeat_interval) * 2)) for host in cluster.metadata.all_hosts(): self.assertIn(host, listener.hosts_marked_down) self.assertNotIn('_replace', executor.called_functions)
'Test to ensure the callbacks are correcltly called and the connection is returned when there is an OTO @since 3.12 @jira_ticket PYTHON-630 @expected_result the connection is correctly returned to the pool after an OTO, also the only the errback is called and not the callback when the message finally arrives. @test_category metadata'
def test_callbacks_and_pool_when_oto(self):
start_and_prime_singledc() self.addCleanup(stop_simulacron) cluster = Cluster(protocol_version=PROTOCOL_VERSION, compression=False) session = cluster.connect() self.addCleanup(cluster.shutdown) query_to_prime = 'SELECT * from testkesypace.testtable' server_delay = 2 prime_query(query_to_prime, then={'delay_in_ms': (server_delay * 1000)}) future = session.execute_async(query_to_prime, timeout=1) (callback, errback) = (Mock(name='callback'), Mock(name='errback')) future.add_callbacks(callback, errback) self.assertRaises(OperationTimedOut, future.result) assert_quiescent_pool_state(self, cluster) time.sleep((server_delay + 1)) errback.assert_called_once() callback.assert_not_called()
'Tests that update with if_exists work as expected @since 3.1 @jira_ticket PYTHON-432 @expected_result updates to be applied when primary key exists, otherwise LWT exception to be thrown @test_category object_mapper'
@unittest.skipUnless((PROTOCOL_VERSION >= 2), 'only runs against the cql3 protocol v2.0') def test_update_if_exists(self):
id = uuid4() m = TestIfExistsModel.create(id=id, count=8, text='123456789') m.text = 'changed' m.if_exists().update() m = TestIfExistsModel.get(id=id) self.assertEqual(m.text, 'changed') m.text = 'changed_again' m.if_exists().save() m = TestIfExistsModel.get(id=id) self.assertEqual(m.text, 'changed_again') m = TestIfExistsModel(id=uuid4(), count=44) with self.assertRaises(LWTException) as assertion: m.if_exists().update() self.assertEqual(assertion.exception.existing, {'[applied]': False}) with self.assertRaises(LWTException) as assertion: TestIfExistsModel.objects(id=uuid4()).if_exists().update(count=8) self.assertEqual(assertion.exception.existing, {'[applied]': False})
'Tests that batch update with if_exists work as expected @since 3.1 @jira_ticket PYTHON-432 @expected_result @test_category object_mapper'
@unittest.skipUnless((PROTOCOL_VERSION >= 2), 'only runs against the cql3 protocol v2.0') def test_batch_update_if_exists_success(self):
id = uuid4() m = TestIfExistsModel.create(id=id, count=8, text='123456789') with BatchQuery() as b: m.text = '111111111' m.batch(b).if_exists().update() with self.assertRaises(LWTException) as assertion: with BatchQuery() as b: m = TestIfExistsModel(id=uuid4(), count=42) m.batch(b).if_exists().update() self.assertEqual(assertion.exception.existing, {'[applied]': False}) q = TestIfExistsModel.objects(id=id) self.assertEqual(len(q), 1) tm = q.first() self.assertEqual(tm.count, 8) self.assertEqual(tm.text, '111111111')
'Tests that batch update with with one bad query will still fail with LWTException @since 3.1 @jira_ticket PYTHON-432 @expected_result @test_category object_mapper'
@unittest.skipUnless((PROTOCOL_VERSION >= 2), 'only runs against the cql3 protocol v2.0') def test_batch_mixed_update_if_exists_success(self):
m = TestIfExistsModel2.create(id=1, count=8, text='123456789') with self.assertRaises(LWTException) as assertion: with BatchQuery() as b: m.text = '111111112' m.batch(b).if_exists().update() n = TestIfExistsModel2(id=1, count=10, text='Failure') n.batch(b).if_exists().update() self.assertEqual(assertion.exception.existing.get('[applied]'), False)
'Tests that delete with if_exists work, and throw proper LWT exception when they are are not applied @since 3.1 @jira_ticket PYTHON-432 @expected_result Deletes will be preformed if they exist, otherwise throw LWT exception @test_category object_mapper'
@unittest.skipUnless((PROTOCOL_VERSION >= 2), 'only runs against the cql3 protocol v2.0') def test_delete_if_exists(self):
id = uuid4() m = TestIfExistsModel.create(id=id, count=8, text='123456789') m.if_exists().delete() q = TestIfExistsModel.objects(id=id) self.assertEqual(len(q), 0) m = TestIfExistsModel(id=uuid4(), count=44) with self.assertRaises(LWTException) as assertion: m.if_exists().delete() self.assertEqual(assertion.exception.existing, {'[applied]': False}) with self.assertRaises(LWTException) as assertion: TestIfExistsModel.objects(id=uuid4()).if_exists().delete() self.assertEqual(assertion.exception.existing, {'[applied]': False})
'Tests that batch deletes with if_exists work, and throw proper LWTException when they are are not applied @since 3.1 @jira_ticket PYTHON-432 @expected_result Deletes will be preformed if they exist, otherwise throw LWTException @test_category object_mapper'
@unittest.skipUnless((PROTOCOL_VERSION >= 2), 'only runs against the cql3 protocol v2.0') def test_batch_delete_if_exists_success(self):
id = uuid4() m = TestIfExistsModel.create(id=id, count=8, text='123456789') with BatchQuery() as b: m.batch(b).if_exists().delete() q = TestIfExistsModel.objects(id=id) self.assertEqual(len(q), 0) with self.assertRaises(LWTException) as assertion: with BatchQuery() as b: m = TestIfExistsModel(id=uuid4(), count=42) m.batch(b).if_exists().delete() self.assertEqual(assertion.exception.existing, {'[applied]': False})
'Tests that batch deletes with multiple queries and throw proper LWTException when they are are not all applicable @since 3.1 @jira_ticket PYTHON-432 @expected_result If one delete clause doesn\'t exist all should fail. @test_category object_mapper'
@unittest.skipUnless((PROTOCOL_VERSION >= 2), 'only runs against the cql3 protocol v2.0') def test_batch_delete_mixed(self):
m = TestIfExistsModel2.create(id=3, count=8, text='123456789') with self.assertRaises(LWTException) as assertion: with BatchQuery() as b: m.batch(b).if_exists().delete() n = TestIfExistsModel2(id=3, count=42, text='1111111') n.batch(b).if_exists().delete() self.assertEqual(assertion.exception.existing.get('[applied]'), False) q = TestIfExistsModel2.objects(id=3, count=8) self.assertEqual(len(q), 1)
'tests that if_exists on models update works as expected'
def test_if_exists_included_on_update(self):
with mock.patch.object(self.session, 'execute') as m: TestIfExistsModel(id=uuid4()).if_exists().update(count=8) query = m.call_args[0][0].query_string self.assertIn('IF EXISTS', query)
'tests that if_exists on models delete works as expected'
def test_if_exists_included_on_delete(self):
with mock.patch.object(self.session, 'execute') as m: TestIfExistsModel(id=uuid4()).if_exists().delete() query = m.call_args[0][0].query_string self.assertIn('IF EXISTS', query)
'Tests if exists is used with a counter column model that exception are thrown @since 3.1 @jira_ticket PYTHON-432 @expected_result Deletes will be preformed if they exist, otherwise throw LWTException @test_category object_mapper'
def test_instance_raise_exception(self):
id = uuid4() with self.assertRaises(IfExistsWithCounterColumn): TestIfExistsWithCounterModel.if_exists()
'Tests that creating a table with capitalized column names succeeds'
def test_table_definition(self):
sync_table(LowercaseKeyModel) sync_table(CapitalizedKeyModel) drop_table(LowercaseKeyModel) drop_table(CapitalizedKeyModel)
'Test to ensure that changes to primary keys throw CQLEngineExceptions @since 3.2 @jira_ticket PYTHON-532 @expected_result Attempts to modify primary keys throw an exception @test_category object_mapper'
def test_primary_key_validation(self):
sync_table(PrimaryKeysOnlyModel) self.assertRaises(CQLEngineException, sync_table, PrimaryKeysModelChanged) self.assertRaises(CQLEngineException, sync_table, PrimaryKeysAddedClusteringKey) self.assertRaises(CQLEngineException, sync_table, PrimaryKeysRemovedPk)
'Test to insure when inconsistent changes are made to a table, or type as part of a sync call that the proper logging messages are surfaced @since 3.2 @jira_ticket PYTHON-260 @expected_result warnings are logged @test_category object_mapper'
def test_sync_warnings(self):
mock_handler = MockLoggingHandler() logger = logging.getLogger(management.__name__) logger.addHandler(mock_handler) sync_table(BaseInconsistent) sync_table(ChangedInconsistent) self.assertTrue(('differing from the model type' in mock_handler.messages.get('warning')[0])) if (CASSANDRA_VERSION >= '2.1'): sync_type(DEFAULT_KEYSPACE, BaseInconsistentType) mock_handler.reset() sync_type(DEFAULT_KEYSPACE, ChangedInconsistentType) self.assertTrue(('differing from the model user type' in mock_handler.messages.get('warning')[0])) logger.removeHandler(mock_handler)
'Tests the default table creation, and ensures the table_name is created and surfaced correctly in the table metadata @since 3.1 @jira_ticket PYTHON-337 @expected_result table_name is lower case @test_category object_mapper'
def test_sync_index(self):
sync_table(IndexModel) table_meta = management._get_table_metadata(IndexModel) self.assertIsNotNone(management._get_index_name_by_column(table_meta, 'second_key')) sync_table(IndexModel) table_meta = management._get_table_metadata(IndexModel) self.assertIsNotNone(management._get_index_name_by_column(table_meta, 'second_key'))
'Tests the default table creation, and ensures the table_name is created correctly and surfaced correctly in table metadata @since 3.1 @jira_ticket PYTHON-337 @expected_result table_name is lower case @test_category object_mapper'
def test_sync_index_case_sensitive(self):
sync_table(IndexCaseSensitiveModel) table_meta = management._get_table_metadata(IndexCaseSensitiveModel) self.assertIsNotNone(management._get_index_name_by_column(table_meta, 'second_key')) sync_table(IndexCaseSensitiveModel) table_meta = management._get_table_metadata(IndexCaseSensitiveModel) self.assertIsNotNone(management._get_index_name_by_column(table_meta, 'second_key'))
'Tests that models that have container types with indices can be synced. @since 3.2 @jira_ticket PYTHON-533 @expected_result table_sync should complete without a server error. @test_category object_mapper'
@greaterthancass20 def test_sync_indexed_set(self):
sync_table(TestIndexSetModel) table_meta = management._get_table_metadata(TestIndexSetModel) self.assertIsNotNone(management._get_index_name_by_column(table_meta, 'int_set')) self.assertIsNotNone(management._get_index_name_by_column(table_meta, 'int_list')) self.assertIsNotNone(management._get_index_name_by_column(table_meta, 'text_map')) self.assertIsNotNone(management._get_index_name_by_column(table_meta, 'mixed_tuple'))
'tests that fetch_size is correctly set'
def test_fetch_size(self):
stmt = BaseCQLStatement('table', None, fetch_size=1000) self.assertEqual(stmt.fetch_size, 1000) stmt = BaseCQLStatement('table', None, fetch_size=None) self.assertEqual(stmt.fetch_size, FETCH_SIZE_UNSET) stmt = BaseCQLStatement('table', None) self.assertEqual(stmt.fetch_size, FETCH_SIZE_UNSET)
'Test to verify the execution of BaseCQLStatements using connection.execute @since 3.10 @jira_ticket PYTHON-505 @expected_result inserts a row in C*, updates the rows and then deletes all the rows using BaseCQLStatements @test_category data_types:object_mapper'
def test_insert_statement_execute(self):
partition = uuid4() cluster = 1 st = InsertStatement(self.table_name) st.add_assignment(Column(db_field='partition'), partition) st.add_assignment(Column(db_field='cluster'), cluster) st.add_assignment(Column(db_field='count'), 1) st.add_assignment(Column(db_field='text'), 'text_for_db') st.add_assignment(Column(db_field='text_set'), set(('foo', 'bar'))) st.add_assignment(Column(db_field='text_list'), ['foo', 'bar']) st.add_assignment(Column(db_field='text_map'), {'foo': '1', 'bar': '2'}) execute(st) self._verify_statement(st) where = [WhereClause('partition', EqualsOperator(), partition), WhereClause('cluster', EqualsOperator(), cluster)] st = UpdateStatement(self.table_name, where=where) st.add_assignment(Column(db_field='count'), 2) st.add_assignment(Column(db_field='text'), 'text_for_db_update') st.add_assignment(Column(db_field='text_set'), set(('foo_update', 'bar_update'))) st.add_assignment(Column(db_field='text_list'), ['foo_update', 'bar_update']) st.add_assignment(Column(db_field='text_map'), {'foo': '3', 'bar': '4'}) execute(st) self._verify_statement(st) execute(DeleteStatement(self.table_name, where=where)) self.assertEqual(TestQueryUpdateModel.objects.count(), 0)
'tests that passing a string field into the constructor puts it into a list'
def test_single_field_is_listified(self):
ds = DeleteStatement('table', 'field') self.assertEqual(len(ds.fields), 1) self.assertEqual(ds.fields[0].field, 'field')
'tests that fields are properly added to the select statement'
def test_field_rendering(self):
ds = DeleteStatement('table', ['f1', 'f2']) self.assertTrue(six.text_type(ds).startswith('DELETE "f1", "f2"'), six.text_type(ds)) self.assertTrue(str(ds).startswith('DELETE "f1", "f2"'), str(ds))
'tests that a \'*\' is added if no fields are passed in'
def test_none_fields_rendering(self):
ds = DeleteStatement('table', None) self.assertTrue(six.text_type(ds).startswith('DELETE FROM'), six.text_type(ds)) self.assertTrue(str(ds).startswith('DELETE FROM'), str(ds))
'tests that creating a where statement with a non BaseWhereOperator object fails'
def test_operator_check(self):
with self.assertRaises(StatementException): WhereClause('a', 'b', 'c')
'tests that where clauses are rendered properly'
def test_where_clause_rendering(self):
wc = WhereClause('a', EqualsOperator(), 'c') wc.set_context_id(5) self.assertEqual('"a" = %(5)s', six.text_type(wc), six.text_type(wc)) self.assertEqual('"a" = %(5)s', str(wc), type(wc))
'tests that 2 identical where clauses evaluate as =='
def test_equality_method(self):
wc1 = WhereClause('a', EqualsOperator(), 'c') wc2 = WhereClause('a', EqualsOperator(), 'c') assert (wc1 == wc2)
'tests setting a set to None creates an empty update statement'
def test_null_update(self):
c = SetUpdateClause('s', None, previous=set((1, 2))) c._analyze() c.set_context_id(0) self.assertIsNone(c._assignments) self.assertIsNone(c._additions) self.assertIsNone(c._removals) self.assertEqual(c.get_context_size(), 0) self.assertEqual(str(c), '') ctx = {} c.update_context(ctx) self.assertEqual(ctx, {})
'tests an unchanged value creates an empty update statement'
def test_no_update(self):
c = SetUpdateClause('s', set((1, 2)), previous=set((1, 2))) c._analyze() c.set_context_id(0) self.assertIsNone(c._assignments) self.assertIsNone(c._additions) self.assertIsNone(c._removals) self.assertEqual(c.get_context_size(), 0) self.assertEqual(str(c), '') ctx = {} c.update_context(ctx) self.assertEqual(ctx, {})
'tests assigning a set to an empty set creates a nonempty update statement and nonzero context size.'
def test_update_empty_set(self):
c = SetUpdateClause(field='s', value=set()) c._analyze() c.set_context_id(0) self.assertEqual(c._assignments, set()) self.assertIsNone(c._additions) self.assertIsNone(c._removals) self.assertEqual(c.get_context_size(), 1) self.assertEqual(str(c), '"s" = %(0)s') ctx = {} c.update_context(ctx) self.assertEqual(ctx, {'0': set()})
'tests that updating to a smaller list results in an insert statement'
def test_shrinking_list_update(self):
c = ListUpdateClause('s', [1, 2, 3], previous=[1, 2, 3, 4]) c._analyze() c.set_context_id(0) self.assertEqual(c._assignments, [1, 2, 3]) self.assertIsNone(c._append) self.assertIsNone(c._prepend) self.assertEqual(c.get_context_size(), 1) self.assertEqual(str(c), '"s" = %(0)s') ctx = {} c.update_context(ctx) self.assertEqual(ctx, {'0': [1, 2, 3]})
'tests that passing a string field into the constructor puts it into a list'
def test_single_field_is_listified(self):
ss = SelectStatement('table', 'field') self.assertEqual(ss.fields, ['field'])
'tests that fields are properly added to the select statement'
def test_field_rendering(self):
ss = SelectStatement('table', ['f1', 'f2']) self.assertTrue(six.text_type(ss).startswith('SELECT "f1", "f2"'), six.text_type(ss)) self.assertTrue(str(ss).startswith('SELECT "f1", "f2"'), str(ss))
'tests that a \'*\' is added if no fields are passed in'
def test_none_fields_rendering(self):
ss = SelectStatement('table') self.assertTrue(six.text_type(ss).startswith('SELECT *'), six.text_type(ss)) self.assertTrue(str(ss).startswith('SELECT *'), str(ss))
'tests that the right things happen the the context id'
def test_context_id_update(self):
ss = SelectStatement('table') ss.add_where(Column(db_field='a'), EqualsOperator(), 'b') self.assertEqual(ss.get_context(), {'0': 'b'}) self.assertEqual(str(ss), 'SELECT * FROM table WHERE "a" = %(0)s') ss.update_context_id(5) self.assertEqual(ss.get_context(), {'5': 'b'}) self.assertEqual(str(ss), 'SELECT * FROM table WHERE "a" = %(5)s')
'tests that fields are properly added to the select statement'
def test_table_rendering(self):
us = UpdateStatement('table') self.assertTrue(six.text_type(us).startswith('UPDATE table SET'), six.text_type(us)) self.assertTrue(str(us).startswith('UPDATE table SET'), str(us))
'Test to ensure that when the default keyspace is changed in a session and that session, is set in the connection class, that the new defaul keyspace is honored. @since 3.1 @jira_ticket PYTHON-486 @expected_result CQLENGINE adopts whatever keyspace is passed in vai the set_session method as default @test_category object_mapper'
def test_connection_session_switch(self):
connection.set_session(self.session1) sync_table(TestConnectModel) TCM1 = TestConnectModel.create(id=1, keyspace=self.keyspace1) connection.set_session(self.session2) sync_table(TestConnectModel) TCM2 = TestConnectModel.create(id=1, keyspace=self.keyspace2) connection.set_session(self.session1) self.assertEqual(1, TestConnectModel.objects.count()) self.assertEqual(TestConnectModel.objects.first(), TCM1) connection.set_session(self.session2) self.assertEqual(1, TestConnectModel.objects.count()) self.assertEqual(TestConnectModel.objects.first(), TCM2)
'tests that insertion with if_not_exists work as expected'
@unittest.skipUnless((PROTOCOL_VERSION >= 2), 'only runs against the cql3 protocol v2.0') def test_insert_if_not_exists(self):
id = uuid4() TestIfNotExistsModel.create(id=id, count=8, text='123456789') with self.assertRaises(LWTException) as assertion: TestIfNotExistsModel.if_not_exists().create(id=id, count=9, text='111111111111') with self.assertRaises(LWTException) as assertion: TestIfNotExistsModel.objects(count=9, text='111111111111').if_not_exists().create(id=id) self.assertEqual(assertion.exception.existing, {'count': 8, 'id': id, 'text': '123456789', '[applied]': False}) q = TestIfNotExistsModel.objects(id=id) self.assertEqual(len(q), 1) tm = q.first() self.assertEqual(tm.count, 8) self.assertEqual(tm.text, '123456789')
'tests that batch insertion with if_not_exists work as expected'
@unittest.skipUnless((PROTOCOL_VERSION >= 2), 'only runs against the cql3 protocol v2.0') def test_batch_insert_if_not_exists(self):
id = uuid4() with BatchQuery() as b: TestIfNotExistsModel.batch(b).if_not_exists().create(id=id, count=8, text='123456789') b = BatchQuery() TestIfNotExistsModel.batch(b).if_not_exists().create(id=id, count=9, text='111111111111') with self.assertRaises(LWTException) as assertion: b.execute() self.assertEqual(assertion.exception.existing, {'count': 8, 'id': id, 'text': '123456789', '[applied]': False}) q = TestIfNotExistsModel.objects(id=id) self.assertEqual(len(q), 1) tm = q.first() self.assertEqual(tm.count, 8) self.assertEqual(tm.text, '123456789')
'tests that if_not_exists on models works as expected'
def test_if_not_exists_included_on_create(self):
with mock.patch.object(self.session, 'execute') as m: TestIfNotExistsModel.if_not_exists().create(count=8) query = m.call_args[0][0].query_string self.assertIn('IF NOT EXISTS', query)
'tests if we correctly put \'IF NOT EXISTS\' for insert statement'
def test_if_not_exists_included_on_save(self):
with mock.patch.object(self.session, 'execute') as m: tm = TestIfNotExistsModel(count=8) tm.if_not_exists().save() query = m.call_args[0][0].query_string self.assertIn('IF NOT EXISTS', query)
'ensure we get a queryset description back'
def test_queryset_is_returned_on_class(self):
qs = TestIfNotExistsModel.if_not_exists() self.assertTrue(isinstance(qs, TestIfNotExistsModel.__queryset__), type(qs))
'ensure \'IF NOT EXISTS\' exists in statement when in batch'
def test_batch_if_not_exists(self):
with mock.patch.object(self.session, 'execute') as m: with BatchQuery() as b: TestIfNotExistsModel.batch(b).if_not_exists().create(count=8) self.assertIn('IF NOT EXISTS', m.call_args[0][0].query_string)
'ensures that we properly handle the instance.if_not_exists().save() scenario'
def test_instance_is_returned(self):
o = TestIfNotExistsModel.create(text='whatever') o.text = 'new stuff' o = o.if_not_exists() self.assertEqual(True, o._if_not_exists)
'make sure we don\'t put \'IF NOT EXIST\' in update statements'
def test_if_not_exists_is_not_include_with_query_on_update(self):
o = TestIfNotExistsModel.create(text='whatever') o.text = 'new stuff' o = o.if_not_exists() with mock.patch.object(self.session, 'execute') as m: o.save() query = m.call_args[0][0].query_string self.assertNotIn('IF NOT EXIST', query)
'make sure exception is raised when calling if_not_exists on table with counter column'
def test_instance_raise_exception(self):
id = uuid4() with self.assertRaises(IfNotExistsWithCounterColumn): TestIfNotExistsWithCounterModel.if_not_exists()
'we don\'t expect the model to come back at the end because the deletion timestamp should be in the future'
def test_non_batch(self):
uid = uuid4() tmp = TestTimestampModel.create(id=uid, count=1) TestTimestampModel.get(id=uid).should.be.ok tmp.timestamp(timedelta(seconds=5)).delete() with self.assertRaises(TestTimestampModel.DoesNotExist): TestTimestampModel.get(id=uid) tmp = TestTimestampModel.create(id=uid, count=1) with self.assertRaises(TestTimestampModel.DoesNotExist): TestTimestampModel.get(id=uid) tmp.timestamp(timedelta(seconds=5)) tmp._timestamp.should.be.ok tmp.save() tmp._timestamp.shouldnt.be.ok tmp.timestamp(timedelta(seconds=5)) tmp.update() tmp._timestamp.shouldnt.be.ok
'we don\'t expect the model to come back at the end because the deletion timestamp should be in the future'
def test_blind_delete(self):
uid = uuid4() tmp = TestTimestampModel.create(id=uid, count=1) TestTimestampModel.get(id=uid).should.be.ok TestTimestampModel.objects(id=uid).timestamp(timedelta(seconds=5)).delete() with self.assertRaises(TestTimestampModel.DoesNotExist): TestTimestampModel.get(id=uid) tmp = TestTimestampModel.create(id=uid, count=1) with self.assertRaises(TestTimestampModel.DoesNotExist): TestTimestampModel.get(id=uid)
'we don\'t expect the model to come back at the end because the deletion timestamp should be in the future'
def test_blind_delete_with_datetime(self):
uid = uuid4() tmp = TestTimestampModel.create(id=uid, count=1) TestTimestampModel.get(id=uid).should.be.ok plus_five_seconds = (datetime.now() + timedelta(seconds=5)) TestTimestampModel.objects(id=uid).timestamp(plus_five_seconds).delete() with self.assertRaises(TestTimestampModel.DoesNotExist): TestTimestampModel.get(id=uid) tmp = TestTimestampModel.create(id=uid, count=1) with self.assertRaises(TestTimestampModel.DoesNotExist): TestTimestampModel.get(id=uid)
'Tests to ensure the proper connection priority is honored. Explicit connection should have higest priority, Followed by context query connection Default connection should be honored last. @since 3.7 @jira_ticket PYTHON-613 @expected_result priorities should be honored @test_category object_mapper'
def test_context_connection_priority(self):
TestModel.__connection__ = 'cluster' with ContextQuery(TestModel) as tm: tm.objects.create(partition=1, cluster=1) with ContextQuery(TestModel, connection='fake_cluster') as tm: with self.assertRaises(NoHostAvailable): tm.objects.create(partition=1, cluster=1) with ContextQuery(TestModel, connection='fake_cluster') as tm: tm.objects.using(connection='cluster').create(partition=1, cluster=1) TestModel.__connection__ = None with ContextQuery(TestModel) as tm: with self.assertRaises(NoHostAvailable): tm.objects.create(partition=1, cluster=1)
'Tests to ensure keyspace param is honored @since 3.7 @jira_ticket PYTHON-613 @expected_result Invalid request is thrown @test_category object_mapper'
def test_context_connection_with_keyspace(self):
with ContextQuery(TestModel, connection='cluster', keyspace='ks2') as tm: with self.assertRaises(InvalidRequest): tm.objects.create(partition=1, cluster=1)
'Tests drop and create keyspace with connections explicitly set @since 3.7 @jira_ticket PYTHON-613 @expected_result keyspaces should be created and dropped @test_category object_mapper'
def test_create_drop_keyspace(self):
with self.assertRaises(NoHostAvailable): create_keyspace_simple(self.keyspaces[0], 1) for ks in self.keyspaces: create_keyspace_simple(ks, 1, connections=self.conns) for ks in self.keyspaces: drop_keyspace(ks, connections=self.conns)
'Tests drop and create Table with connections explicitly set @since 3.7 @jira_ticket PYTHON-613 @expected_result Tables should be created and dropped @test_category object_mapper'
def test_create_drop_table(self):
for ks in self.keyspaces: create_keyspace_simple(ks, 1, connections=self.conns) with self.assertRaises(NoHostAvailable): sync_table(TestModel) sync_table(TestModel, connections=self.conns) drop_table(TestModel, connections=self.conns) TestModel.__connection__ = 'cluster' sync_table(TestModel) TestModel.__connection__ = None with self.assertRaises(NoHostAvailable): drop_table(TestModel) TestModel.__connection__ = 'cluster' drop_table(TestModel) TestModel.__connection__ = None for ks in self.keyspaces: drop_keyspace(ks, connections=self.conns)
'Test to ensure that you can register a connection from a session @since 3.8 @jira_ticket PYTHON-649 @expected_result queries should execute appropriately @test_category object_mapper'
def test_connection_creation_from_session(self):
cluster = Cluster([CASSANDRA_IP]) session = cluster.connect() connection_name = 'from_session' conn.register_connection(connection_name, session=session) self.assertIsNotNone(conn.get_connection(connection_name).cluster.metadata.get_host(CASSANDRA_IP)) self.addCleanup(conn.unregister_connection, connection_name) cluster.shutdown()
'Test to ensure that you can register a connection from a list of hosts @since 3.8 @jira_ticket PYTHON-692 @expected_result queries should execute appropriately @test_category object_mapper'
def test_connection_from_hosts(self):
connection_name = 'from_hosts' conn.register_connection(connection_name, hosts=[CASSANDRA_IP]) self.assertIsNotNone(conn.get_connection(connection_name).cluster.metadata.get_host(CASSANDRA_IP)) self.addCleanup(conn.unregister_connection, connection_name)
'Test to validate that invalid parameter combinations for registering connections via session are not tolerated @since 3.8 @jira_ticket PYTHON-649 @expected_result queries should execute appropriately @test_category object_mapper'
def test_connection_param_validation(self):
cluster = Cluster([CASSANDRA_IP]) session = cluster.connect() with self.assertRaises(CQLEngineException): conn.register_connection('bad_coonection1', session=session, consistency='not_null') with self.assertRaises(CQLEngineException): conn.register_connection('bad_coonection2', session=session, lazy_connect='not_null') with self.assertRaises(CQLEngineException): conn.register_connection('bad_coonection3', session=session, retry_connect='not_null') with self.assertRaises(CQLEngineException): conn.register_connection('bad_coonection4', session=session, cluster_options='not_null') with self.assertRaises(CQLEngineException): conn.register_connection('bad_coonection5', hosts='not_null', session=session) cluster.shutdown() cluster.shutdown() cluster.shutdown()
'Test Batch queries with connections explicitly set @since 3.7 @jira_ticket PYTHON-613 @expected_result queries should execute appropriately @test_category object_mapper'
def test_basic_batch_query(self):
with self.assertRaises(NoHostAvailable): with BatchQuery() as b: TestModel.objects.batch(b).create(partition=1, cluster=1) with BatchQuery(connection='cluster') as b: TestModel.objects.batch(b).create(partition=1, cluster=1) with ContextQuery(TestModel, connection='cluster') as tm: obj = tm.objects.get(partition=1, cluster=1) obj.__connection__ = None with self.assertRaises(NoHostAvailable): with BatchQuery() as b: obj.count = 2 obj.batch(b).save() with BatchQuery(connection='cluster') as b: obj.count = 2 obj.batch(b).save()
'Test BatchQuery with Models that have a different connection @since 3.7 @jira_ticket PYTHON-613 @expected_result queries should execute appropriately @test_category object_mapper'
def test_batch_query_different_connection(self):
TestModel.__connection__ = 'cluster' AnotherTestModel.__connection__ = 'cluster2' with self.assertRaises(CQLEngineException): with BatchQuery() as b: TestModel.objects.batch(b).create(partition=1, cluster=1) AnotherTestModel.objects.batch(b).create(partition=1, cluster=1) TestModel.__connection__ = None AnotherTestModel.__connection__ = None with BatchQuery(connection='cluster') as b: TestModel.objects.batch(b).create(partition=1, cluster=1) AnotherTestModel.objects.batch(b).create(partition=1, cluster=1) with ContextQuery(TestModel, AnotherTestModel, connection='cluster') as (tm, atm): obj1 = tm.objects.get(partition=1, cluster=1) obj2 = atm.objects.get(partition=1, cluster=1) obj1.__connection__ = 'cluster' obj2.__connection__ = 'cluster2' obj1.count = 4 obj2.count = 4 with self.assertRaises(CQLEngineException): with BatchQuery() as b: obj1.batch(b).save() obj2.batch(b).save()
'Test that we cannot override a BatchQuery connection per model @since 3.7 @jira_ticket PYTHON-613 @expected_result Proper exceptions should be raised @test_category object_mapper'
def test_batch_query_connection_override(self):
with self.assertRaises(CQLEngineException): with BatchQuery(connection='cluster') as b: TestModel.batch(b).using(connection='test').save() with self.assertRaises(CQLEngineException): with BatchQuery(connection='cluster') as b: TestModel.using(connection='test').batch(b).save() with ContextQuery(TestModel, AnotherTestModel, connection='cluster') as (tm, atm): obj1 = tm.objects.get(partition=1, cluster=1) obj1.__connection__ = None with self.assertRaises(CQLEngineException): with BatchQuery(connection='cluster') as b: obj1.using(connection='test').batch(b).save() with self.assertRaises(CQLEngineException): with BatchQuery(connection='cluster') as b: obj1.batch(b).using(connection='test').save()
'Test keyspace segregation when same connection is used @since 3.7 @jira_ticket PYTHON-613 @expected_result Keyspace segration is honored @test_category object_mapper'
def test_keyspace(self):
self._reset_data() with ContextQuery(TestModel, connection='cluster') as tm: tm.objects.using(keyspace='ks2').create(partition=1, cluster=1) tm.objects.using(keyspace='ks2').create(partition=2, cluster=2) with self.assertRaises(TestModel.DoesNotExist): tm.objects.get(partition=1, cluster=1) obj1 = tm.objects.using(keyspace='ks2').get(partition=1, cluster=1) obj1.count = 2 obj1.save() with self.assertRaises(NoHostAvailable): TestModel.objects.using(keyspace='ks2').get(partition=1, cluster=1) obj2 = TestModel.objects.using(connection='cluster', keyspace='ks2').get(partition=1, cluster=1) self.assertEqual(obj2.count, 2) TestModel.objects(partition=2, cluster=2).using(connection='cluster', keyspace='ks2').update(count=5) obj3 = TestModel.objects.using(connection='cluster', keyspace='ks2').get(partition=2, cluster=2) self.assertEqual(obj3.count, 5) TestModel.objects(partition=2, cluster=2).using(connection='cluster', keyspace='ks2').delete() with self.assertRaises(TestModel.DoesNotExist): TestModel.objects.using(connection='cluster', keyspace='ks2').get(partition=2, cluster=2)
'Test basic connection functionality @since 3.7 @jira_ticket PYTHON-613 @expected_result proper connection should be used @test_category object_mapper'
def test_connection(self):
self._reset_data() with self.assertRaises(NoHostAvailable): TestModel.objects.create(partition=1, cluster=1) TestModel.objects.using(connection='cluster').create(partition=1, cluster=1) TestModel.objects(partition=1, cluster=1).using(connection='cluster').update(count=2) obj1 = TestModel.objects.using(connection='cluster').get(partition=1, cluster=1) self.assertEqual(obj1.count, 2) obj1.using(connection='cluster').update(count=5) obj1 = TestModel.objects.using(connection='cluster').get(partition=1, cluster=1) self.assertEqual(obj1.count, 5) obj1.using(connection='cluster').delete() with self.assertRaises(TestModel.DoesNotExist): TestModel.objects.using(connection='cluster').get(partition=1, cluster=1)
'Batch callbacks should NOT fire if batch is not executed in context manager mode'
def test_callbacks_tied_to_execute(self):
call_history = [] def my_callback(*args, **kwargs): call_history.append(args) with BatchQuery() as batch: batch.add_callback(my_callback) self.assertEqual(len(call_history), 1) class SomeError(Exception, ): pass with self.assertRaises(SomeError): with BatchQuery() as batch: batch.add_callback(my_callback) raise SomeError self.assertEqual(len(call_history), 1) with self.assertRaises(SomeError): with BatchQuery(execute_on_exception=True) as batch: batch.add_callback(my_callback) raise SomeError self.assertEqual(len(call_history), 2)
'Tests that multiple executions of execute on a batch statement logs a warning, and that we don\'t encounter an attribute error. @since 3.1 @jira_ticket PYTHON-445 @expected_result warning message is logged @test_category object_mapper'
def test_callbacks_work_multiple_times(self):
call_history = [] def my_callback(*args, **kwargs): call_history.append(args) with warnings.catch_warnings(record=True) as w: with BatchQuery() as batch: batch.add_callback(my_callback) batch.execute() batch.execute() self.assertEqual(len(w), 2) self.assertRegexpMatches(str(w[0].message), '^Batch.*multiple.*')
'Tests that multiple executions of a batch statement don\'t log a warning when warn_multiple_exec flag is set, and that we don\'t encounter an attribute error. @since 3.1 @jira_ticket PYTHON-445 @expected_result warning message is logged @test_category object_mapper'
def test_disable_multiple_callback_warning(self):
call_history = [] def my_callback(*args, **kwargs): call_history.append(args) with patch('cassandra.cqlengine.query.BatchQuery.warn_multiple_exec', False): with warnings.catch_warnings(record=True) as w: with BatchQuery() as batch: batch.add_callback(my_callback) batch.execute() batch.execute() self.assertFalse(w)
'Validates that when a context query is constructed that the keyspace of the returned model is toggled appropriately @since 3.6 @jira_ticket PYTHON-598 @expected_result default keyspace should be used @test_category query'
def test_context_manager(self):
for ks in self.KEYSPACES: with ContextQuery(TestModel, keyspace=ks) as tm: self.assertEqual(tm.__keyspace__, ks) self.assertEqual(TestModel._get_keyspace(), 'ks1')
'Tests the use of context queries with the default model keyspsace @since 3.6 @jira_ticket PYTHON-598 @expected_result default keyspace should be used @test_category query'
def test_default_keyspace(self):
for i in range(5): TestModel.objects.create(partition=i, cluster=i) with ContextQuery(TestModel) as tm: self.assertEqual(5, len(tm.objects.all())) with ContextQuery(TestModel, keyspace='ks1') as tm: self.assertEqual(5, len(tm.objects.all())) for ks in self.KEYSPACES[1:]: with ContextQuery(TestModel, keyspace=ks) as tm: self.assertEqual(0, len(tm.objects.all()))
'Tests the use of context queries with non default keyspaces @since 3.6 @jira_ticket PYTHON-598 @expected_result queries should be routed to appropriate keyspaces @test_category query'
def test_context_keyspace(self):
for i in range(5): with ContextQuery(TestModel, keyspace='ks4') as tm: tm.objects.create(partition=i, cluster=i) with ContextQuery(TestModel, keyspace='ks4') as tm: self.assertEqual(5, len(tm.objects.all())) self.assertEqual(0, len(TestModel.objects.all())) for ks in self.KEYSPACES[:2]: with ContextQuery(TestModel, keyspace=ks) as tm: self.assertEqual(0, len(tm.objects.all())) with ContextQuery(TestModel, keyspace='ks4') as tm: obj = tm.objects.get(partition=1) obj.update(count=42) self.assertEqual(42, tm.objects.get(partition=1).count)
'Tests the use of multiple models with the context manager @since 3.7 @jira_ticket PYTHON-613 @expected_result all models are properly updated with the context @test_category query'
def test_context_multiple_models(self):
with ContextQuery(TestModel, TestModel, keyspace='ks4') as (tm1, tm2): self.assertNotEqual(tm1, tm2) self.assertEqual(tm1.__keyspace__, 'ks4') self.assertEqual(tm2.__keyspace__, 'ks4')
'Tests that invalid parameters are raised by the context manager @since 3.7 @jira_ticket PYTHON-613 @expected_result a ValueError is raised when passing invalid parameters @test_category query'
def test_context_invalid_parameters(self):
with self.assertRaises(ValueError): with ContextQuery(keyspace='ks2'): pass with self.assertRaises(ValueError): with ContextQuery(42) as tm: pass with self.assertRaises(ValueError): with ContextQuery(TestModel, 42): pass with self.assertRaises(ValueError): with ContextQuery(TestModel, unknown_param=42): pass with self.assertRaises(ValueError): with ContextQuery(TestModel, keyspace='ks2', unknown_param=42): pass
'tests where symbols are looked up properly'
def test_symbol_lookup(self):
def check_lookup(symbol, expected): op = BaseWhereOperator.get_operator(symbol) self.assertEqual(op, expected) check_lookup('EQ', EqualsOperator) check_lookup('NE', NotEqualsOperator) check_lookup('IN', InOperator) check_lookup('GT', GreaterThanOperator) check_lookup('GTE', GreaterThanOrEqualOperator) check_lookup('LT', LessThanOperator) check_lookup('LTE', LessThanOrEqualOperator) check_lookup('CONTAINS', ContainsOperator)
'tests symbols are rendered properly'
def test_operator_rendering(self):
self.assertEqual('=', six.text_type(EqualsOperator())) self.assertEqual('!=', six.text_type(NotEqualsOperator())) self.assertEqual('IN', six.text_type(InOperator())) self.assertEqual('>', six.text_type(GreaterThanOperator())) self.assertEqual('>=', six.text_type(GreaterThanOrEqualOperator())) self.assertEqual('<', six.text_type(LessThanOperator())) self.assertEqual('<=', six.text_type(LessThanOrEqualOperator())) self.assertEqual('CONTAINS', six.text_type(ContainsOperator()))
''
def test_an_instance_evaluates_as_equal_to_itself(self):
assert (self.t0 == self.t0)
''
def test_two_instances_referencing_the_same_rows_and_different_values_evaluate_not_equal(self):
t0 = TestModel.get(id=self.t0.id) t0.text = 'bleh' assert (t0 != self.t0)
''
def test_two_instances_referencing_the_same_rows_and_values_evaluate_equal(self):
t0 = TestModel.get(id=self.t0.id) assert (t0 == self.t0)
''
def test_two_instances_referencing_different_rows_evaluate_to_not_equal(self):
assert (self.t0 != self.t1)
'tests calling udpate on models with no values passed in'
def test_update_model(self):
m0 = TestUpdateModel.create(count=5, text='monkey') m1 = TestUpdateModel.get(partition=m0.partition, cluster=m0.cluster) m1.count = 6 m1.save() m0.text = 'monkey land' m0.update() m2 = TestUpdateModel.get(partition=m0.partition, cluster=m0.cluster) self.assertEqual(m2.count, m1.count) self.assertEqual(m2.text, m0.text) m0.update(partition=m0.partition, cluster=m0.cluster) with self.assertRaises(ValidationError): m0.update(partition=m0.partition, cluster=20) with self.assertRaises(ValidationError): m0.update(invalid_column=20)