desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'tests calling update on models with values passed in'
| def test_update_values(self):
| m0 = TestUpdateModel.create(count=5, text='monkey')
m1 = TestUpdateModel.get(partition=m0.partition, cluster=m0.cluster)
m1.count = 6
m1.save()
m0.update(text='monkey land')
self.assertEqual(m0.text, 'monkey land')
m2 = TestUpdateModel.get(partition=m0.partition, cluster=m0.cluster)
self.assertEqual(m2.count, m1.count)
self.assertEqual(m2.text, m0.text)
|
'Tests that calling update on a model with no changes will do nothing.'
| def test_noop_model_direct_update(self):
| m0 = TestUpdateModel.create(count=5, text='monkey')
with patch.object(self.session, 'execute') as execute:
m0.update()
assert (execute.call_count == 0)
with patch.object(self.session, 'execute') as execute:
m0.update(count=5)
assert (execute.call_count == 0)
with patch.object(self.session, 'execute') as execute:
m0.update(partition=m0.partition)
with patch.object(self.session, 'execute') as execute:
m0.update(cluster=m0.cluster)
|
'Tests that assigning the same value on a model will do nothing.'
| def test_noop_model_assignation_update(self):
| m0 = TestUpdateModel.create(count=5, text='monkey')
m1 = TestUpdateModel.get(partition=m0.partition, cluster=m0.cluster)
with patch.object(self.session, 'execute') as execute:
m1.save()
assert (execute.call_count == 0)
with patch.object(self.session, 'execute') as execute:
m1.count = 5
m1.save()
assert (execute.call_count == 0)
with patch.object(self.session, 'execute') as execute:
m1.partition = m0.partition
m1.save()
assert (execute.call_count == 0)
with patch.object(self.session, 'execute') as execute:
m1.cluster = m0.cluster
m1.save()
assert (execute.call_count == 0)
|
'tests that passing in a kwarg to the update method that isn\'t a column will fail'
| def test_invalid_update_kwarg(self):
| m0 = TestUpdateModel.create(count=5, text='monkey')
with self.assertRaises(ValidationError):
m0.update(numbers=20)
|
'tests that attempting to update the value of a primary key will fail'
| def test_primary_key_update_failure(self):
| m0 = TestUpdateModel.create(count=5, text='monkey')
with self.assertRaises(ValidationError):
m0.update(partition=uuid4())
|
'Updating a row with a new Model instance shouldn\'t set columns to defaults
@since 3.9
@jira_ticket PYTHON-657
@expected_result column value should not change
@test_category object_mapper'
| def test_value_override_with_default(self):
| first_udt = UDT(age=1, mf={2: 2}, dummy_udt=0)
initial = ModelWithDefault(id=1, mf={0: 0}, dummy=0, udt=first_udt, udt_default=first_udt)
initial.save()
self.assertEqual(ModelWithDefault.get()._as_dict(), {'id': 1, 'dummy': 0, 'mf': {0: 0}, 'udt': first_udt, 'udt_default': first_udt})
second_udt = UDT(age=1, mf={3: 3}, dummy_udt=12)
second = ModelWithDefault(id=1)
second.update(mf={0: 1}, udt=second_udt)
self.assertEqual(ModelWithDefault.get()._as_dict(), {'id': 1, 'dummy': 0, 'mf': {0: 1}, 'udt': second_udt, 'udt_default': first_udt})
|
'Check if the we try to update with the default value, the update
happens correctly
@since 3.9
@jira_ticket PYTHON-657
@expected_result column value should be updated
:return:'
| def test_value_is_written_if_is_default(self):
| initial = ModelWithDefault(id=1)
initial.mf = {0: 0}
initial.dummy = 42
initial.udt_default = self.udt_default
initial.update()
self.assertEqual(ModelWithDefault.get()._as_dict(), {'id': 1, 'dummy': 42, 'mf': {0: 0}, 'udt': None, 'udt_default': self.udt_default})
|
'Check if the we try to update with None under particular
circumstances, it works correctly
@since 3.9
@jira_ticket PYTHON-657
@expected_result column value should be updated to None
@test_category object_mapper
:return:'
| def test_null_update_is_respected(self):
| ModelWithDefault.create(id=1, mf={0: 0}).save()
q = ModelWithDefault.objects.all().allow_filtering()
obj = q.filter(id=1).get()
updated_udt = UDT(age=1, mf={2: 2}, dummy_udt=None)
obj.update(dummy=None, udt_default=updated_udt)
self.assertEqual(ModelWithDefault.get()._as_dict(), {'id': 1, 'dummy': None, 'mf': {0: 0}, 'udt': None, 'udt_default': updated_udt})
|
'Test the updates work as expected when an object is deleted
@since 3.9
@jira_ticket PYTHON-657
@expected_result the non updated column is None and the
updated column has the set value
@test_category object_mapper'
| def test_only_set_values_is_updated(self):
| ModelWithDefault.create(id=1, mf={1: 1}, dummy=1).save()
item = ModelWithDefault.filter(id=1).first()
ModelWithDefault.objects(id=1).delete()
item.mf = {1: 2}
(udt, udt_default) = (UDT(age=1, mf={2: 3}), UDT(age=1, mf={2: 3}))
(item.udt, item.udt_default) = (udt, udt_default)
item.save()
self.assertEqual(ModelWithDefault.get()._as_dict(), {'id': 1, 'dummy': None, 'mf': {1: 2}, 'udt': udt, 'udt_default': udt_default})
|
'Test the updates work as expected on Map objects
@since 3.9
@jira_ticket PYTHON-657
@expected_result the row is updated when the Map object is
reduced
@test_category object_mapper'
| def test_collections(self):
| (udt, udt_default) = (UDT(age=1, mf={1: 1, 2: 1}), UDT(age=1, mf={1: 1, 2: 1}))
ModelWithDefault.create(id=1, mf={1: 1, 2: 1}, dummy=1, udt=udt, udt_default=udt_default).save()
item = ModelWithDefault.filter(id=1).first()
(udt, udt_default) = (UDT(age=1, mf={2: 1}), UDT(age=1, mf={2: 1}))
item.update(mf={2: 1}, udt=udt, udt_default=udt_default)
self.assertEqual(ModelWithDefault.get()._as_dict(), {'id': 1, 'dummy': 1, 'mf': {2: 1}, 'udt': udt, 'udt_default': udt_default})
|
'Test the updates work as expected when an object is deleted
@since 3.9
@jira_ticket PYTHON-657
@expected_result the non updated column is None and the
updated column has the set value
@test_category object_mapper'
| def test_collection_with_default(self):
| sync_table(ModelWithDefaultCollection)
(udt, udt_default) = (UDT(age=1, mf={6: 6}), UDT(age=1, mf={6: 6}))
item = ModelWithDefaultCollection.create(id=1, mf={1: 1}, dummy=1, udt=udt, udt_default=udt_default).save()
self.assertEqual(ModelWithDefaultCollection.objects.get(id=1)._as_dict(), {'id': 1, 'dummy': 1, 'mf': {1: 1}, 'udt': udt, 'udt_default': udt_default})
(udt, udt_default) = (UDT(age=1, mf={5: 5}), UDT(age=1, mf={5: 5}))
item.update(mf={2: 2}, udt=udt, udt_default=udt_default)
self.assertEqual(ModelWithDefaultCollection.objects.get(id=1)._as_dict(), {'id': 1, 'dummy': 1, 'mf': {2: 2}, 'udt': udt, 'udt_default': udt_default})
(udt, udt_default) = (UDT(age=1, mf=None), UDT(age=1, mf=None))
(expected_udt, expected_udt_default) = (UDT(age=1, mf={}), UDT(age=1, mf={}))
item.update(mf=None, udt=udt, udt_default=udt_default)
self.assertEqual(ModelWithDefaultCollection.objects.get(id=1)._as_dict(), {'id': 1, 'dummy': 1, 'mf': {}, 'udt': expected_udt, 'udt_default': expected_udt_default})
udt_default = UDT(age=1, mf={2: 2}, dummy_udt=42)
item = ModelWithDefaultCollection.create(id=2, dummy=2)
self.assertEqual(ModelWithDefaultCollection.objects.get(id=2)._as_dict(), {'id': 2, 'dummy': 2, 'mf': {2: 2}, 'udt': None, 'udt_default': udt_default})
(udt, udt_default) = (UDT(age=1, mf={1: 1, 6: 6}), UDT(age=1, mf={1: 1, 6: 6}))
item.update(mf={1: 1, 4: 4}, udt=udt, udt_default=udt_default)
self.assertEqual(ModelWithDefaultCollection.objects.get(id=2)._as_dict(), {'id': 2, 'dummy': 2, 'mf': {1: 1, 4: 4}, 'udt': udt, 'udt_default': udt_default})
item.update(udt_default=None)
self.assertEqual(ModelWithDefaultCollection.objects.get(id=2)._as_dict(), {'id': 2, 'dummy': 2, 'mf': {1: 1, 4: 4}, 'udt': udt, 'udt_default': None})
udt_default = UDT(age=1, mf={2: 2})
item.update(udt_default=udt_default)
self.assertEqual(ModelWithDefaultCollection.objects.get(id=2)._as_dict(), {'id': 2, 'dummy': 2, 'mf': {1: 1, 4: 4}, 'udt': udt, 'udt_default': udt_default})
|
'Test the to_python and to_database are correctly called on UDTs
@since 3.10
@jira_ticket PYTHON-743
@expected_result the int value is correctly converted to utils.Time
and written to C*
@test_category object_mapper'
| def test_udt_to_python(self):
| item = ModelWithDefault(id=1)
item.save()
user_to_update = UDT()
user_to_update.time_col = 10
item.update(udt=user_to_update)
(udt, udt_default) = (UDT(time_col=10), UDT(age=1, mf={2: 2}))
self.assertEqual(ModelWithDefault.objects.get(id=1)._as_dict(), {'id': 1, 'dummy': 42, 'mf': {}, 'udt': udt, 'udt_default': udt_default})
|
'Test for inserting all column types as empty into a UserType as None\'s
test_can_insert_udts_with_nones tests that each cqlengine column type can be inserted into a UserType as None\'s.
It first creates a UserType that has each cqlengine column type, and a corresponding table/Model. It then creates
a UserType instance where all the fields are None\'s and inserts the UserType as an instance of the Model. Finally,
it verifies that each column read from the UserType from Cassandra is None.
@since 2.5.0
@jira_ticket PYTHON-251
@expected_result The UserType is inserted with each column type, and the resulting read yields None\'s for each column.
@test_category data_types:udt'
| def test_can_insert_udts_with_nones(self):
| sync_table(AllDatatypesModel)
self.addCleanup(drop_table, AllDatatypesModel)
input = AllDatatypes(a=None, b=None, c=None, d=None, e=None, f=None, g=None, h=None, i=None, j=None, k=None, l=None, m=None, n=None)
AllDatatypesModel.create(id=0, data=input)
self.assertEqual(1, AllDatatypesModel.objects.count())
output = AllDatatypesModel.objects.first().data
self.assertEqual(input, output)
|
'Test for inserting all column types into a UserType
test_can_insert_udts_with_all_datatypes tests that each cqlengine column type can be inserted into a UserType.
It first creates a UserType that has each cqlengine column type, and a corresponding table/Model. It then creates
a UserType instance where all the fields have corresponding data, and inserts the UserType as an instance of the Model.
Finally, it verifies that each column read from the UserType from Cassandra is the same as the input parameters.
@since 2.5.0
@jira_ticket PYTHON-251
@expected_result The UserType is inserted with each column type, and the resulting read yields proper data for each column.
@test_category data_types:udt'
| def test_can_insert_udts_with_all_datatypes(self):
| sync_table(AllDatatypesModel)
self.addCleanup(drop_table, AllDatatypesModel)
input = AllDatatypes(a='ascii', b=((2 ** 63) - 1), c=bytearray('hello world'), d=True, e=datetime.utcfromtimestamp(872835240), f=Decimal('12.3E+7'), g=2.39, h=3.4028234663852886e+38, i='123.123.123.123', j=2147483647, k='text', l=UUID('FE2B4360-28C6-11E2-81C1-0800200C9A66'), m=UUID('067e6162-3b6f-4ae2-a171-2470b63dff00'), n=int((str(2147483647) + '000')))
AllDatatypesModel.create(id=0, data=input)
self.assertEqual(1, AllDatatypesModel.objects.count())
output = AllDatatypesModel.objects.first().data
for i in range(ord('a'), (ord('a') + 14)):
self.assertEqual(input[chr(i)], output[chr(i)])
|
'Test for inserting all protocol v4 column types into a UserType
test_can_insert_udts_protocol_v4_datatypes tests that each protocol v4 cqlengine column type can be inserted
into a UserType. It first creates a UserType that has each protocol v4 cqlengine column type, and a corresponding
table/Model. It then creates a UserType instance where all the fields have corresponding data, and inserts the
UserType as an instance of the Model. Finally, it verifies that each column read from the UserType from Cassandra
is the same as the input parameters.
@since 2.6.0
@jira_ticket PYTHON-245
@expected_result The UserType is inserted with each protocol v4 column type, and the resulting read yields proper data for each column.
@test_category data_types:udt'
| def test_can_insert_udts_protocol_v4_datatypes(self):
| if (PROTOCOL_VERSION < 4):
raise unittest.SkipTest('Protocol v4 datatypes in UDTs require native protocol 4+, currently using: {0}'.format(PROTOCOL_VERSION))
class Allv4Datatypes(UserType, ):
a = columns.Date()
b = columns.SmallInt()
c = columns.Time()
d = columns.TinyInt()
class Allv4DatatypesModel(Model, ):
id = columns.Integer(primary_key=True)
data = columns.UserDefinedType(Allv4Datatypes)
sync_table(Allv4DatatypesModel)
self.addCleanup(drop_table, Allv4DatatypesModel)
input = Allv4Datatypes(a=Date(date(1970, 1, 1)), b=32523, c=Time(time(16, 47, 25, 7)), d=123)
Allv4DatatypesModel.create(id=0, data=input)
self.assertEqual(1, Allv4DatatypesModel.objects.count())
output = Allv4DatatypesModel.objects.first().data
for i in range(ord('a'), (ord('a') + 3)):
self.assertEqual(input[chr(i)], output[chr(i)])
|
'Test for inserting collections of user types using cql engine.
test_nested_udts_inserts Constructs a model that contains a list of usertypes. It will then attempt to insert
them. The expectation is that no exception is thrown during insert. For sanity sake we also validate that our
input and output values match. This combination of model, and UT produces a syntax error in 2.5.1 due to
improper quoting around the names collection.
@since 2.6.0
@jira_ticket PYTHON-311
@expected_result No syntax exception thrown
@test_category data_types:udt'
| def test_nested_udts_inserts(self):
| class Name(UserType, ):
type_name__ = 'header'
name = columns.Text()
value = columns.Text()
class Container(Model, ):
id = columns.UUID(primary_key=True, default=uuid4)
names = columns.List(columns.UserDefinedType(Name))
names = []
for i in range(0, 10):
names.append(Name(name='name{0}'.format(i), value='value{0}'.format(i)))
sync_table(Container)
self.addCleanup(drop_table, Container)
Container.create(id=UUID('FE2B4360-28C6-11E2-81C1-0800200C9A66'), names=names)
self.assertEqual(1, Container.objects.count())
names_output = Container.objects.first().names
self.assertEqual(names_output, names)
|
'Test for inserting models with unicode and udt columns.
test_udts_with_unicode constructs a model with a user defined type. It then attempts to insert that model with
a unicode primary key. It will also attempt to upsert a udt that contains unicode text.
@since 3.0.0
@jira_ticket PYTHON-353
@expected_result No exceptions thrown
@test_category data_types:udt'
| def test_udts_with_unicode(self):
| ascii_name = 'normal name'
unicode_name = u'Fran\xe7ois'
class UserModelText(Model, ):
id = columns.Text(primary_key=True)
info = columns.UserDefinedType(User)
sync_table(UserModelText)
self.addCleanup(drop_table, UserModelText)
user_template_ascii = User(age=25, name=ascii_name)
user_template_unicode = User(age=25, name=unicode_name)
UserModelText.create(id=ascii_name, info=user_template_unicode)
UserModelText.create(id=unicode_name, info=user_template_ascii)
UserModelText.create(id=unicode_name, info=user_template_unicode)
|
'Tests for db_field override
Tests to ensure that udt\'s in models can specify db_field for a particular field and that it will be honored.
@since 3.1.0
@jira_ticket PYTHON-346
@expected_result The actual cassandra column will use the db_field specified.
@test_category data_types:udt'
| def test_db_field_override(self):
| class db_field_different(UserType, ):
age = columns.Integer(db_field='a')
name = columns.Text(db_field='n')
class TheModel(Model, ):
id = columns.Integer(primary_key=True)
info = columns.UserDefinedType(db_field_different)
sync_table(TheModel)
self.addCleanup(drop_table, TheModel)
cluster = connection.get_cluster()
type_meta = cluster.metadata.keyspaces[TheModel._get_keyspace()].user_types[db_field_different.type_name()]
type_fields = (db_field_different.age.column, db_field_different.name.column)
self.assertEqual(len(type_meta.field_names), len(type_fields))
for f in type_fields:
self.assertIn(f.db_field_name, type_meta.field_names)
id = 0
age = 42
name = 'John'
info = db_field_different(age=age, name=name)
TheModel.create(id=id, info=info)
self.assertEqual(1, TheModel.objects.count())
john = TheModel.objects.first()
self.assertEqual(john.id, id)
info = john.info
self.assertIsInstance(info, db_field_different)
self.assertEqual(info.age, age)
self.assertEqual(info.name, name)
self.assertEqual(info.a, age)
self.assertEqual(info.n, name)
|
'Tests for db_field UserTypeDefinitionException
Test so that when we override a model\'s default field witha db_field that it errors appropriately
@since 3.1.0
@jira_ticket PYTHON-346
@expected_result Setting a db_field to an existing field causes an exception to occur.
@test_category data_types:udt'
| def test_db_field_overload(self):
| with self.assertRaises(UserTypeDefinitionException):
class something_silly(UserType, ):
first_col = columns.Integer()
second_col = columns.Text(db_field='first_col')
with self.assertRaises(UserTypeDefinitionException):
class something_silly_2(UserType, ):
first_col = columns.Integer(db_field='second_col')
second_col = columns.Text()
|
'Test that default types are set on object creation for UDTs
@since 3.7.0
@jira_ticket PYTHON-606
@expected_result Default values should be set.
@test_category data_types:udt'
| def test_default_values(self):
| class NestedUdt(UserType, ):
test_id = columns.UUID(default=uuid4)
something = columns.Text()
default_text = columns.Text(default='default text')
class OuterModel(Model, ):
name = columns.Text(primary_key=True)
first_name = columns.Text()
nested = columns.List(columns.UserDefinedType(NestedUdt))
simple = columns.UserDefinedType(NestedUdt)
sync_table(OuterModel)
self.addCleanup(drop_table, OuterModel)
t = OuterModel.create(name='test1')
t.nested = [NestedUdt(something='test')]
t.simple = NestedUdt(something='')
t.save()
self.assertIsNotNone(t.nested[0].test_id)
self.assertEqual(t.nested[0].default_text, 'default text')
self.assertIsNotNone(t.simple.test_id)
self.assertEqual(t.simple.default_text, 'default text')
|
'Test to verify restrictions are honored and that validate is called
for each member of the UDT when an updated is attempted
@since 3.10
@jira_ticket PYTHON-505
@expected_result a validation error is arisen due to the name being
too long
@test_category data_types:object_mapper'
| def test_udt_validate(self):
| class UserValidate(UserType, ):
age = columns.Integer()
name = columns.Text(max_length=2)
class UserModelValidate(Model, ):
id = columns.Integer(primary_key=True)
info = columns.UserDefinedType(UserValidate)
sync_table(UserModelValidate)
self.addCleanup(drop_table, UserModelValidate)
user = UserValidate(age=1, name='Robert')
item = UserModelValidate(id=1, info=user)
with self.assertRaises(ValidationError):
item.save()
|
'Test to verify restrictions are honored and that validate is called
on the default value
@since 3.10
@jira_ticket PYTHON-505
@expected_result a validation error is arisen due to the name being
too long
@test_category data_types:object_mapper'
| def test_udt_validate_with_default(self):
| class UserValidateDefault(UserType, ):
age = columns.Integer()
name = columns.Text(max_length=2, default='Robert')
class UserModelValidateDefault(Model, ):
id = columns.Integer(primary_key=True)
info = columns.UserDefinedType(UserValidateDefault)
sync_table(UserModelValidateDefault)
self.addCleanup(drop_table, UserModelValidateDefault)
user = UserValidateDefault(age=1)
item = UserModelValidateDefault(id=1, info=user)
with self.assertRaises(ValidationError):
item.save()
|
'Tests that models can be saved and retrieved'
| def test_clustering_order(self):
| items = list(range(20))
random.shuffle(items)
for i in items:
TestModel.create(id=1, clustering_key=i)
values = list(TestModel.objects.values_list('clustering_key', flat=True))
self.assertEqual(values, sorted(items, reverse=True))
|
'Tests that models can be saved and retrieved'
| def test_clustering_order_more_complex(self):
| sync_table(TestClusteringComplexModel)
items = list(range(20))
random.shuffle(items)
for i in items:
TestClusteringComplexModel.create(id=1, clustering_key=i, some_value=2)
values = list(TestClusteringComplexModel.objects.values_list('some_value', flat=True))
self.assertEqual(([2] * 20), values)
drop_table(TestClusteringComplexModel)
|
'Tests that models can be saved and retrieved, using the create method.'
| def test_model_save_and_load(self):
| tm = TestModel.create(count=8, text='123456789')
self.assertIsInstance(tm, TestModel)
tm2 = TestModel.objects(id=tm.pk).first()
self.assertIsInstance(tm2, TestModel)
for cname in tm._columns.keys():
self.assertEqual(getattr(tm, cname), getattr(tm2, cname))
|
'Tests that models can be saved and retrieved, this time using the
natural model instantiation.'
| def test_model_instantiation_save_and_load(self):
| tm = TestModel(count=8, text='123456789')
self.assertIsNotNone(tm['id'])
self.assertEqual(tm.count, 8)
self.assertEqual(tm.text, '123456789')
tm.save()
tm2 = TestModel.objects(id=tm.id).first()
for cname in tm._columns.keys():
self.assertEqual(getattr(tm, cname), getattr(tm2, cname))
|
'Tests that columns of an instance can be read as a dict.'
| def test_model_read_as_dict(self):
| tm = TestModel.create(count=8, text='123456789', a_bool=True)
column_dict = {'id': tm.id, 'count': tm.count, 'text': tm.text, 'a_bool': tm.a_bool}
self.assertEqual(sorted(tm.keys()), sorted(column_dict.keys()))
self.assertSetEqual(set(tm.values()), set(column_dict.values()))
self.assertEqual(sorted(tm.items(), key=itemgetter(0)), sorted(column_dict.items(), key=itemgetter(0)))
self.assertEqual(len(tm), len(column_dict))
for column_id in column_dict.keys():
self.assertEqual(tm[column_id], column_dict[column_id])
tm['count'] = 6
self.assertEqual(tm.count, 6)
|
'Tests that subsequent saves after initial model creation work'
| def test_model_updating_works_properly(self):
| tm = TestModel.objects.create(count=8, text='123456789')
tm.count = 100
tm.a_bool = True
tm.save()
tm2 = TestModel.objects(id=tm.pk).first()
self.assertEqual(tm.count, tm2.count)
self.assertEqual(tm.a_bool, tm2.a_bool)
|
'Tests that an instance\'s delete method deletes the instance'
| def test_model_deleting_works_properly(self):
| tm = TestModel.create(count=8, text='123456789')
tm.delete()
tm2 = TestModel.objects(id=tm.pk).first()
self.assertIsNone(tm2)
|
''
| def test_column_deleting_works_properly(self):
| tm = TestModel.create(count=8, text='123456789')
tm.text = None
tm.save()
tm2 = TestModel.objects(id=tm.pk).first()
self.assertIsInstance(tm2, TestModel)
self.assertTrue((tm2.text is None))
self.assertTrue((tm2._values['text'].previous_value is None))
|
''
| def test_a_sensical_error_is_raised_if_you_try_to_create_a_table_twice(self):
| sync_table(TestModel)
sync_table(TestModel)
|
'Test for inserting all column types into a Model
test_can_insert_model_with_all_column_types tests that each cqlengine column type can be inserted into a Model.
It first creates a Model that has each cqlengine column type. It then creates a Model instance where all the fields
have corresponding data, which performs the insert into the Cassandra table.
Finally, it verifies that each column read from the Model from Cassandra is the same as the input parameters.
@since 2.6.0
@jira_ticket PYTHON-246
@expected_result The Model is inserted with each column type, and the resulting read yields proper data for each column.
@test_category data_types:primitive'
| @greaterthanorequalcass3_10
def test_can_insert_model_with_all_column_types(self):
| class AllDatatypesModel(Model, ):
id = columns.Integer(primary_key=True)
a = columns.Ascii()
b = columns.BigInt()
c = columns.Blob()
d = columns.Boolean()
e = columns.DateTime()
f = columns.Decimal()
g = columns.Double()
h = columns.Float()
i = columns.Inet()
j = columns.Integer()
k = columns.Text()
l = columns.TimeUUID()
m = columns.UUID()
n = columns.VarInt()
o = columns.Duration()
sync_table(AllDatatypesModel)
input = ['ascii', ((2 ** 63) - 1), bytearray('hello world'), True, datetime.utcfromtimestamp(872835240), Decimal('12.3E+7'), 2.39, 3.4028234663852886e+38, '123.123.123.123', 2147483647, 'text', UUID('FE2B4360-28C6-11E2-81C1-0800200C9A66'), UUID('067e6162-3b6f-4ae2-a171-2470b63dff00'), int((str(2147483647) + '000'))]
AllDatatypesModel.create(id=0, a='ascii', b=((2 ** 63) - 1), c=bytearray('hello world'), d=True, e=datetime.utcfromtimestamp(872835240), f=Decimal('12.3E+7'), g=2.39, h=3.4028234663852886e+38, i='123.123.123.123', j=2147483647, k='text', l=UUID('FE2B4360-28C6-11E2-81C1-0800200C9A66'), m=UUID('067e6162-3b6f-4ae2-a171-2470b63dff00'), n=int((str(2147483647) + '000')), o=Duration(2, 3, 4))
self.assertEqual(1, AllDatatypesModel.objects.count())
output = AllDatatypesModel.objects.first()
for (i, i_char) in enumerate(range(ord('a'), (ord('a') + 14))):
self.assertEqual(input[i], output[chr(i_char)])
|
'Test for inserting all protocol v4 column types into a Model
test_can_insert_model_with_all_protocol_v4_column_types tests that each cqlengine protocol v4 column type can be
inserted into a Model. It first creates a Model that has each cqlengine protocol v4 column type. It then creates
a Model instance where all the fields have corresponding data, which performs the insert into the Cassandra table.
Finally, it verifies that each column read from the Model from Cassandra is the same as the input parameters.
@since 2.6.0
@jira_ticket PYTHON-245
@expected_result The Model is inserted with each protocol v4 column type, and the resulting read yields proper data for each column.
@test_category data_types:primitive'
| def test_can_insert_model_with_all_protocol_v4_column_types(self):
| if (PROTOCOL_VERSION < 4):
raise unittest.SkipTest('Protocol v4 datatypes require native protocol 4+, currently using: {0}'.format(PROTOCOL_VERSION))
class v4DatatypesModel(Model, ):
id = columns.Integer(primary_key=True)
a = columns.Date()
b = columns.SmallInt()
c = columns.Time()
d = columns.TinyInt()
sync_table(v4DatatypesModel)
input = [Date(date(1970, 1, 1)), 32523, Time(time(16, 47, 25, 7)), 123]
v4DatatypesModel.create(id=0, a=date(1970, 1, 1), b=32523, c=time(16, 47, 25, 7), d=123)
self.assertEqual(1, v4DatatypesModel.objects.count())
output = v4DatatypesModel.objects.first()
for (i, i_char) in enumerate(range(ord('a'), (ord('a') + 3))):
self.assertEqual(input[i], output[chr(i_char)])
|
'Test for inserting single-precision and double-precision values into a Float and Double columns
@since 2.6.0
@changed 3.0.0 removed deprecated Float(double_precision) parameter
@jira_ticket PYTHON-246
@expected_result Each floating point column type is able to hold their respective precision values.
@test_category data_types:primitive'
| def test_can_insert_double_and_float(self):
| class FloatingPointModel(Model, ):
id = columns.Integer(primary_key=True)
f = columns.Float()
d = columns.Double()
sync_table(FloatingPointModel)
FloatingPointModel.create(id=0, f=2.39)
output = FloatingPointModel.objects.first()
self.assertEqual(2.390000104904175, output.f)
FloatingPointModel.create(id=0, f=3.4028234663852886e+38, d=2.39)
output = FloatingPointModel.objects.first()
self.assertEqual(3.4028234663852886e+38, output.f)
self.assertEqual(2.39, output.d)
FloatingPointModel.create(id=0, d=3.4028234663852886e+38)
output = FloatingPointModel.objects.first()
self.assertEqual(3.4028234663852886e+38, output.d)
|
'Test update of column value of None with save() function.
Under specific scenarios calling save on a None value wouldn\'t update
previous values. This issue only manifests with a new instantiation of the model,
if existing model is modified and updated the issue will not occur.
@since 3.0.0
@jira_ticket PYTHON-475
@expected_result column value should be updated to None
@test_category object_mapper'
| def test_save_to_none(self):
| partition = uuid4()
cluster = 1
text = 'set'
text_list = ['set']
text_set = set(('set',))
text_map = {'set': 'set'}
initial = TestModelSave(partition=partition, cluster=cluster, text=text, text_list=text_list, text_set=text_set, text_map=text_map)
initial.save()
current = TestModelSave.objects.get(partition=partition, cluster=cluster)
self.assertEqual(current.text, text)
self.assertEqual(current.text_list, text_list)
self.assertEqual(current.text_set, text_set)
self.assertEqual(current.text_map, text_map)
next = TestModelSave(partition=partition, cluster=cluster, text=None, text_list=None, text_set=None, text_map=None)
next.save()
current = TestModelSave.objects.get(partition=partition, cluster=cluster)
self.assertEqual(current.text, None)
self.assertEqual(current.text_list, [])
self.assertEqual(current.text_set, set())
self.assertEqual(current.text_map, {})
|
''
| def test_reserved_cql_words_can_be_used_as_column_names(self):
| sync_table(ReservedWordModel)
model1 = ReservedWordModel.create(token='1', insert=5)
model2 = ReservedWordModel.filter(token='1')
self.assertTrue((len(model2) == 1))
self.assertTrue((model1.token == model2[0].token))
self.assertTrue((model1.insert == model2[0].insert))
|
'Compares the routing key generated by simple partition key using the model with the one generated by the equivalent
bound statement. It also verifies basic operations work with no routing key
@since 3.2
@jira_ticket PYTHON-505
@expected_result they shouldn\'t match
@test_category object_mapper'
| def test_routing_key_is_ignored(self):
| prepared = self.session.prepare('\n INSERT INTO {0}.basic_model_no_routing (k, v) VALUES (?, ?)\n '.format(DEFAULT_KEYSPACE))
bound = prepared.bind((1, 2))
mrk = BasicModelNoRouting._routing_key_from_values([1], self.session.cluster.protocol_version)
simple = SimpleStatement('')
simple.routing_key = mrk
self.assertNotEqual(bound.routing_key, simple.routing_key)
t = BasicModelNoRouting.create(k=2, v=3)
t.update(v=4).save()
f = BasicModelNoRouting.objects.filter(k=2).first()
self.assertEqual(t, f)
t.delete()
self.assertEqual(BasicModelNoRouting.objects.count(), 0)
|
'Compares the routing key generated by simple partition key using the model with the one generated by the equivalent
bound statement
@since 3.2
@jira_ticket PYTHON-535
@expected_result they should match
@test_category object_mapper'
| def test_routing_key_generation_basic(self):
| prepared = self.session.prepare('\n INSERT INTO {0}.basic_model_routing (k, v) VALUES (?, ?)\n '.format(DEFAULT_KEYSPACE))
bound = prepared.bind((1, 2))
mrk = BasicModel._routing_key_from_values([1], self.session.cluster.protocol_version)
simple = SimpleStatement('')
simple.routing_key = mrk
self.assertEqual(bound.routing_key, simple.routing_key)
|
'Compares the routing key generated by composite partition key using the model with the one generated by the equivalent
bound statement
@since 3.2
@jira_ticket PYTHON-535
@expected_result they should match
@test_category object_mapper'
| def test_routing_key_generation_multi(self):
| prepared = self.session.prepare('\n INSERT INTO {0}.basic_model_routing_multi (k, v) VALUES (?, ?)\n '.format(DEFAULT_KEYSPACE))
bound = prepared.bind((1, 2))
mrk = BasicModelMulti._routing_key_from_values([1, 2], self.session.cluster.protocol_version)
simple = SimpleStatement('')
simple.routing_key = mrk
self.assertEqual(bound.routing_key, simple.routing_key)
|
'Compares the routing key generated by complex composite partition key using the model with the one generated by the equivalent
bound statement
@since 3.2
@jira_ticket PYTHON-535
@expected_result they should match
@test_category object_mapper'
| def test_routing_key_generation_complex(self):
| prepared = self.session.prepare('\n INSERT INTO {0}.complex_model_routing (partition, cluster, count, text, float, text_2) VALUES (?, ?, ?, ?, ?, ?)\n '.format(DEFAULT_KEYSPACE))
partition = uuid4()
cluster = 1
count = 2
text = 'text'
float = 1.2
text_2 = 'text_2'
bound = prepared.bind((partition, cluster, count, text, float, text_2))
mrk = ComplexModelRouting._routing_key_from_values([partition, cluster, text, float], self.session.cluster.protocol_version)
simple = SimpleStatement('')
simple.routing_key = mrk
self.assertEqual(bound.routing_key, simple.routing_key)
|
'Test to ensure that statement partition key generation is in the correct order
@since 3.2
@jira_ticket PYTHON-535
@expected_result .
@test_category object_mapper'
| def test_partition_key_index(self):
| self._check_partition_value_generation(BasicModel, SelectStatement(BasicModel.__table_name__))
self._check_partition_value_generation(BasicModel, DeleteStatement(BasicModel.__table_name__))
self._check_partition_value_generation(BasicModelMulti, SelectStatement(BasicModelMulti.__table_name__))
self._check_partition_value_generation(BasicModelMulti, DeleteStatement(BasicModelMulti.__table_name__))
self._check_partition_value_generation(ComplexModelRouting, SelectStatement(ComplexModelRouting.__table_name__))
self._check_partition_value_generation(ComplexModelRouting, DeleteStatement(ComplexModelRouting.__table_name__))
self._check_partition_value_generation(BasicModel, SelectStatement(BasicModel.__table_name__), reverse=True)
self._check_partition_value_generation(BasicModel, DeleteStatement(BasicModel.__table_name__), reverse=True)
self._check_partition_value_generation(BasicModelMulti, SelectStatement(BasicModelMulti.__table_name__), reverse=True)
self._check_partition_value_generation(BasicModelMulti, DeleteStatement(BasicModelMulti.__table_name__), reverse=True)
self._check_partition_value_generation(ComplexModelRouting, SelectStatement(ComplexModelRouting.__table_name__), reverse=True)
self._check_partition_value_generation(ComplexModelRouting, DeleteStatement(ComplexModelRouting.__table_name__), reverse=True)
|
'This generates a some statements based on the partition_key_index of the model.
It then validates that order of the partition key values in the statement matches the index
specified in the models partition_key_index'
| def _check_partition_value_generation(self, model, state, reverse=False):
| uuid = uuid4()
values = {'k': 5, 'v': 3, 'partition': uuid, 'cluster': 6, 'count': 42, 'text': 'text', 'float': 3.1415, 'text_2': 'text_2'}
res = dict(((v, k) for (k, v) in values.items()))
items = list(model._partition_key_index.items())
if reverse:
items.reverse()
for (partition_key, position) in items:
wc = WhereClause(partition_key, EqualsOperator(), values.get(partition_key))
state._add_where_clause(wc)
for (indx, value) in enumerate(state.partition_key_values(model._partition_key_index)):
name = res.get(value)
self.assertEqual(indx, model._partition_key_index.get(name))
|
'Tests that column attributes are moved to a _columns dict
and replaced with simple value attributes'
| def test_column_attributes_handled_correctly(self):
| class TestModel(Model, ):
id = columns.UUID(primary_key=True, default=(lambda : uuid4()))
text = columns.Text()
self.assertHasAttr(TestModel, '_columns')
self.assertHasAttr(TestModel, 'id')
self.assertHasAttr(TestModel, 'text')
inst = TestModel()
self.assertHasAttr(inst, 'id')
self.assertHasAttr(inst, 'text')
self.assertIsNotNone(inst.id)
self.assertIsNone(inst.text)
|
'Tests defaults and user-provided values on instantiation.'
| def test_values_on_instantiation(self):
| class TestPerson(Model, ):
first_name = columns.Text(primary_key=True, default='kevin')
last_name = columns.Text(default='deldycke')
inst1 = TestPerson()
self.assertHasAttr(inst1, 'first_name')
self.assertHasAttr(inst1, 'last_name')
self.assertEqual(inst1.first_name, 'kevin')
self.assertEqual(inst1.last_name, 'deldycke')
inst2 = TestPerson(first_name='bob', last_name='joe')
self.assertEqual(inst2.first_name, 'bob')
self.assertEqual(inst2.last_name, 'joe')
|
'Tests that the db_map is properly defined
-the db_map allows columns'
| def test_db_map(self):
| class WildDBNames(Model, ):
id = columns.UUID(primary_key=True, default=(lambda : uuid4()))
content = columns.Text(db_field='words_and_whatnot')
numbers = columns.Integer(db_field='integers_etc')
db_map = WildDBNames._db_map
self.assertEqual(db_map['words_and_whatnot'], 'content')
self.assertEqual(db_map['integers_etc'], 'numbers')
|
'Tests that trying to create conflicting db column names will fail'
| def test_attempting_to_make_duplicate_column_names_fails(self):
| with self.assertRaisesRegexp(ModelException, '.*more than once$'):
class BadNames(Model, ):
words = columns.Text(primary_key=True)
content = columns.Text(db_field='words')
|
'Tests that the _columns dics retains the ordering of the class definition'
| def test_column_ordering_is_preserved(self):
| class Stuff(Model, ):
id = columns.UUID(primary_key=True, default=(lambda : uuid4()))
words = columns.Text()
content = columns.Text()
numbers = columns.Integer()
self.assertEqual([x for x in Stuff._columns.keys()], ['id', 'words', 'content', 'numbers'])
|
'Tests that instance value managers are isolated from other instances'
| def test_value_managers_are_keeping_model_instances_isolated(self):
| class Stuff(Model, ):
id = columns.UUID(primary_key=True, default=(lambda : uuid4()))
num = columns.Integer()
inst1 = Stuff(num=5)
inst2 = Stuff(num=7)
self.assertNotEqual(inst1.num, inst2.num)
self.assertEqual(inst1.num, 5)
self.assertEqual(inst2.num, 7)
|
'Tests that fields defined on the super class are inherited properly'
| def test_superclass_fields_are_inherited(self):
| class TestModel(Model, ):
id = columns.UUID(primary_key=True, default=(lambda : uuid4()))
text = columns.Text()
class InheritedModel(TestModel, ):
numbers = columns.Integer()
assert ('text' in InheritedModel._columns)
assert ('numbers' in InheritedModel._columns)
|
'Tests that auto column family name generation works as expected'
| def test_column_family_name_generation(self):
| class TestModel(Model, ):
id = columns.UUID(primary_key=True, default=(lambda : uuid4()))
text = columns.Text()
assert (TestModel.column_family_name(include_keyspace=False) == 'test_model')
|
'Test compound partition key definition'
| def test_partition_keys(self):
| class ModelWithPartitionKeys(Model, ):
id = columns.UUID(primary_key=True, default=(lambda : uuid4()))
c1 = columns.Text(primary_key=True)
p1 = columns.Text(partition_key=True)
p2 = columns.Text(partition_key=True)
cols = ModelWithPartitionKeys._columns
self.assertTrue(cols['c1'].primary_key)
self.assertFalse(cols['c1'].partition_key)
self.assertTrue(cols['p1'].primary_key)
self.assertTrue(cols['p1'].partition_key)
self.assertTrue(cols['p2'].primary_key)
self.assertTrue(cols['p2'].partition_key)
obj = ModelWithPartitionKeys(p1='a', p2='b')
self.assertEqual(obj.pk, ('a', 'b'))
|
'Tests that columns that can be deleted have the del attribute'
| def test_del_attribute_is_assigned_properly(self):
| class DelModel(Model, ):
id = columns.UUID(primary_key=True, default=(lambda : uuid4()))
key = columns.Integer(primary_key=True)
data = columns.Integer(required=False)
model = DelModel(key=4, data=5)
del model.data
with self.assertRaises(AttributeError):
del model.key
|
'Tests that DoesNotExist exceptions are not the same exception between models'
| def test_does_not_exist_exceptions_are_not_shared_between_model(self):
| class Model1(Model, ):
id = columns.UUID(primary_key=True, default=(lambda : uuid4()))
class Model2(Model, ):
id = columns.UUID(primary_key=True, default=(lambda : uuid4()))
try:
raise Model1.DoesNotExist
except Model2.DoesNotExist:
assert False, 'Model1 exception should not be caught by Model2'
except Model1.DoesNotExist:
pass
|
'Tests that a DoesNotExist exception can be caught by it\'s parent class DoesNotExist'
| def test_does_not_exist_inherits_from_superclass(self):
| class Model1(Model, ):
id = columns.UUID(primary_key=True, default=(lambda : uuid4()))
class Model2(Model1, ):
pass
try:
raise Model2.DoesNotExist
except Model1.DoesNotExist:
pass
except Exception:
assert False, 'Model2 exception should not be caught by Model1'
|
'Test to ensure case senstivity is not honored by default honored
@since 3.1
@jira_ticket PYTHON-337
@expected_result table_names arel lowercase
@test_category object_mapper'
| def test_proper_table_naming_case_insensitive(self):
| self.assertEqual(self.RenamedCaseInsensitiveTest.column_family_name(include_keyspace=False), 'manual_name')
self.assertEqual(self.RenamedCaseInsensitiveTest.column_family_name(include_keyspace=True), 'whatever.manual_name')
|
'Test to ensure case is honored when the flag is correctly set.
@since 3.1
@jira_ticket PYTHON-337
@expected_result table_name case is honored.
@test_category object_mapper'
| def test_proper_table_naming_case_sensitive(self):
| self.assertEqual(self.RenamedCaseSensitiveTest.column_family_name(include_keyspace=False), '"Manual_Name"')
self.assertEqual(self.RenamedCaseSensitiveTest.column_family_name(include_keyspace=True), 'whatever."Manual_Name"')
|
'Tests that an id field is not automatically generated on abstract classes'
| def test_id_field_is_not_created(self):
| assert (not hasattr(AbstractModel, 'id'))
assert (not hasattr(AbstractModelWithCol, 'id'))
|
'Tests that __abstract__ attribute is not inherited'
| def test_abstract_attribute_is_not_inherited(self):
| assert (not ConcreteModel.__abstract__)
assert (not ConcreteModelWithCol.__abstract__)
|
'Attempting to save a model from an abstract model should fail'
| def test_attempting_to_save_abstract_model_fails(self):
| with self.assertRaises(CQLEngineException):
AbstractModelWithFullCols.create(pkey=1, data=2)
|
'Attempting to create a table from an abstract model should fail'
| def test_attempting_to_create_abstract_table_fails(self):
| from cassandra.cqlengine.management import sync_table
with self.assertRaises(CQLEngineException):
sync_table(AbstractModelWithFullCols)
|
'Tests attempting to execute query with an abstract model fails'
| def test_attempting_query_on_abstract_model_fails(self):
| with self.assertRaises(CQLEngineException):
iter(AbstractModelWithFullCols.objects(pkey=5)).next()
|
'Tests that columns defined in the abstract class are inherited into the concrete class'
| def test_abstract_columns_are_inherited(self):
| assert hasattr(ConcreteModelWithCol, 'pkey')
assert isinstance(ConcreteModelWithCol.pkey, ColumnQueryEvaluator)
assert isinstance(ConcreteModelWithCol._columns['pkey'], columns.Column)
|
'Tests that models with inherited abstract classes can be created, and have io performed'
| def test_concrete_class_table_creation_cycle(self):
| from cassandra.cqlengine.management import sync_table, drop_table
sync_table(ConcreteModelWithCol)
w1 = ConcreteModelWithCol.create(pkey=5, data=6)
w2 = ConcreteModelWithCol.create(pkey=6, data=7)
r1 = ConcreteModelWithCol.get(pkey=5)
r2 = ConcreteModelWithCol.get(pkey=6)
assert (w1.pkey == r1.pkey)
assert (w1.data == r1.data)
assert (w2.pkey == r2.pkey)
assert (w2.data == r2.data)
drop_table(ConcreteModelWithCol)
|
'Tests that defining a model with more than one discriminator column fails'
| def test_multiple_discriminator_value_failure(self):
| with self.assertRaises(models.ModelDefinitionException):
class M(models.Model, ):
partition = columns.Integer(primary_key=True)
type1 = columns.Integer(discriminator_column=True)
type2 = columns.Integer(discriminator_column=True)
|
'Tests that discriminator_column attribute is not inherited'
| def test_discriminator_value_inheritance(self):
| class Base(models.Model, ):
partition = columns.Integer(primary_key=True)
type1 = columns.Integer(discriminator_column=True)
class M1(Base, ):
__discriminator_value__ = 1
class M2(M1, ):
pass
assert (M2.__discriminator_value__ is None)
|
'Tests that the model meta class configures inherited models properly'
| def test_inheritance_metaclass(self):
| class Base(models.Model, ):
partition = columns.Integer(primary_key=True)
type1 = columns.Integer(discriminator_column=True)
class M1(Base, ):
__discriminator_value__ = 1
assert Base._is_polymorphic
assert M1._is_polymorphic
assert Base._is_polymorphic_base
assert (not M1._is_polymorphic_base)
assert (Base._discriminator_column is Base._columns['type1'])
assert (M1._discriminator_column is M1._columns['type1'])
assert (Base._discriminator_column_name == 'type1')
assert (M1._discriminator_column_name == 'type1')
|
'tests the model equality functionality'
| def test_instance_equality(self):
| class EqualityModel(Model, ):
pk = columns.Integer(primary_key=True)
m0 = EqualityModel(pk=0)
m1 = EqualityModel(pk=1)
self.assertEqual(m0, m0)
self.assertNotEqual(m0, m1)
|
'tests the model equality functionality'
| def test_model_equality(self):
| class EqualityModel0(Model, ):
pk = columns.Integer(primary_key=True)
class EqualityModel1(Model, ):
kk = columns.Integer(primary_key=True)
m0 = EqualityModel0(pk=0)
m1 = EqualityModel1(kk=1)
self.assertEqual(m0, m0)
self.assertNotEqual(m0, m1)
|
'Test for CQL keywords as names
test_keywords_as_names tests that CQL keywords are properly and automatically quoted in cqlengine. It creates
a keyspace, keyspace, which should be automatically quoted to "keyspace" in CQL. It then creates a table, table,
which should also be automatically quoted to "table". It then verfies that operations can be done on the
"keyspace"."table" which has been created. It also verifies that table alternations work and operations can be
performed on the altered table.
@since 2.6.0
@jira_ticket PYTHON-244
@expected_result Cqlengine should quote CQL keywords properly when creating keyspaces and tables.
@test_category schema:generation'
| def test_keywords_as_names(self):
| create_keyspace_simple('keyspace', 1)
class table(Model, ):
__keyspace__ = 'keyspace'
select = columns.Integer(primary_key=True)
table = columns.Text()
drop_table(table)
sync_table(table)
created = table.create(select=0, table='table')
selected = table.objects(select=0)[0]
self.assertEqual(created.select, selected.select)
self.assertEqual(created.table, selected.table)
class table(Model, ):
__keyspace__ = 'keyspace'
select = columns.Integer(primary_key=True)
table = columns.Text()
where = columns.Text()
sync_table(table)
created = table.create(select=1, table='table')
selected = table.objects(select=1)[0]
self.assertEqual(created.select, selected.select)
self.assertEqual(created.table, selected.table)
self.assertEqual(created.where, selected.where)
drop_keyspace('keyspace')
|
'Test to ensure case sensitivity is honored when __table_name_case_sensitive__ flag is set
@since 3.1
@jira_ticket PYTHON-337
@expected_result table_name case is respected
@test_category object_mapper'
| def test_column_family_case_sensitive(self):
| class TestModel(Model, ):
__table_name__ = 'TestModel'
__table_name_case_sensitive__ = True
k = columns.Integer(primary_key=True)
self.assertEqual(TestModel.column_family_name(), ('%s."TestModel"' % (models.DEFAULT_KEYSPACE,)))
TestModel.__keyspace__ = 'my_test_keyspace'
self.assertEqual(TestModel.column_family_name(), ('%s."TestModel"' % (TestModel.__keyspace__,)))
del TestModel.__keyspace__
with patch('cassandra.cqlengine.models.DEFAULT_KEYSPACE', None):
self.assertRaises(CQLEngineException, TestModel.column_family_name)
self.assertEqual(TestModel.column_family_name(include_keyspace=False), '"TestModel"')
|
'should raise exception when model defines column that conflicts with built-in attribute'
| def test_model_with_attribute_name_conflict(self):
| with self.assertRaises(ModelDefinitionException):
class IllegalTimestampColumnModel(Model, ):
my_primary_key = columns.Integer(primary_key=True)
timestamp = columns.BigInt()
|
'should raise exception when model defines column that conflicts with built-in method'
| def test_model_with_method_name_conflict(self):
| with self.assertRaises(ModelDefinitionException):
class IllegalFilterColumnModel(Model, ):
my_primary_key = columns.Integer(primary_key=True)
filter = columns.Text()
|
'Test to ensure overwriting of primary keys in model inheritance is allowed
This is currently only an issue in PyPy. When PYTHON-504 is introduced this should
be updated error out and warn the user
@since 3.6.0
@jira_ticket PYTHON-576
@expected_result primary keys can be overwritten via inheritance
@test_category object_mapper'
| def test_model_over_write(self):
| class TimeModelBase(Model, ):
uuid = columns.TimeUUID(primary_key=True)
class DerivedTimeModel(TimeModelBase, ):
__table_name__ = 'derived_time'
uuid = columns.TimeUUID(primary_key=True, partition_key=True)
value = columns.Text(required=False)
drop_table(DerivedTimeModel)
sync_table(DerivedTimeModel)
uuid_value = uuid1()
uuid_value2 = uuid1()
DerivedTimeModel.create(uuid=uuid_value, value='first')
DerivedTimeModel.create(uuid=uuid_value2, value='second')
DerivedTimeModel.objects.filter(uuid=uuid_value)
|
'tests that sets are set() by default, should never be none
:return:'
| def test_empty_set_initial(self):
| m = TestSetModel.create()
m.int_set.add(5)
m.save()
|
'Tests that a basic usage works as expected'
| def test_io_success(self):
| m1 = TestSetModel.create(int_set=set((1, 2)), text_set=set(('kai', 'andreas')))
m2 = TestSetModel.get(partition=m1.partition)
self.assertIsInstance(m2.int_set, set)
self.assertIsInstance(m2.text_set, set)
self.assertIn(1, m2.int_set)
self.assertIn(2, m2.int_set)
self.assertIn('kai', m2.text_set)
self.assertIn('andreas', m2.text_set)
|
'Tests that attempting to use the wrong types will raise an exception'
| def test_type_validation(self):
| self.assertRaises(ValidationError, TestSetModel.create, **{'int_set': set(('string', True)), 'text_set': set((1, 3.0))})
|
'Tests that big collections are detected and raise an exception.'
| def test_element_count_validation(self):
| while True:
try:
TestSetModel.create(text_set=set((str(uuid4()) for i in range(65535))))
break
except WriteTimeout:
(ex_type, ex, tb) = sys.exc_info()
log.warning('{0}: {1} Backtrace: {2}'.format(ex_type.__name__, ex, traceback.extract_tb(tb)))
del tb
except OperationTimedOut:
self.assertFalse(CASSANDRA_IP.startswith('127.0.0.'))
self.assertRaises(ValidationError, TestSetModel.create, **{'text_set': set((str(uuid4()) for i in range(65536)))})
|
'Tests that partial udpates work as expected'
| def test_partial_updates(self):
| m1 = TestSetModel.create(int_set=set((1, 2, 3, 4)))
m1.int_set.add(5)
m1.int_set.remove(1)
self.assertEqual(m1.int_set, set((2, 3, 4, 5)))
m1.save()
m2 = TestSetModel.get(partition=m1.partition)
self.assertEqual(m2.int_set, set((2, 3, 4, 5)))
|
'Tests that columns instantiated with a column class work properly
and that the class is instantiated in the constructor'
| def test_instantiation_with_column_class(self):
| column = columns.Set(columns.Text)
self.assertIsInstance(column.value_col, columns.Text)
|
'Tests that columns instantiated with a column instance work properly'
| def test_instantiation_with_column_instance(self):
| column = columns.Set(columns.Text(min_length=100))
self.assertIsInstance(column.value_col, columns.Text)
|
'Tests that to_python of value column is called'
| def test_to_python(self):
| column = columns.Set(JsonTestColumn)
val = set((1, 2, 3))
db_val = column.to_database(val)
self.assertEqual(db_val, set((json.dumps(v) for v in val)))
py_val = column.to_python(db_val)
self.assertEqual(py_val, val)
|
'tests that the default empty container is not saved if it hasn\'t been updated'
| def test_default_empty_container_saving(self):
| pkey = uuid4()
TestSetModel.create(partition=pkey, int_set=set((3, 4)))
TestSetModel.create(partition=pkey)
m = TestSetModel.get(partition=pkey)
self.assertEqual(m.int_set, set((3, 4)))
|
'Tests that a basic usage works as expected'
| def test_io_success(self):
| m1 = TestListModel.create(int_list=[1, 2], text_list=['kai', 'andreas'])
m2 = TestListModel.get(partition=m1.partition)
self.assertIsInstance(m2.int_list, list)
self.assertIsInstance(m2.text_list, list)
self.assertEqual(len(m2.int_list), 2)
self.assertEqual(len(m2.text_list), 2)
self.assertEqual(m2.int_list[0], 1)
self.assertEqual(m2.int_list[1], 2)
self.assertEqual(m2.text_list[0], 'kai')
self.assertEqual(m2.text_list[1], 'andreas')
|
'Tests that attempting to use the wrong types will raise an exception'
| def test_type_validation(self):
| self.assertRaises(ValidationError, TestListModel.create, **{'int_list': ['string', True], 'text_list': [1, 3.0]})
|
'Tests that big collections are detected and raise an exception.'
| def test_element_count_validation(self):
| while True:
try:
TestListModel.create(text_list=[str(uuid4()) for i in range(65535)])
break
except WriteTimeout:
(ex_type, ex, tb) = sys.exc_info()
log.warn('{0}: {1} Backtrace: {2}'.format(ex_type.__name__, ex, traceback.extract_tb(tb)))
del tb
self.assertRaises(ValidationError, TestListModel.create, **{'text_list': [str(uuid4()) for _ in range(65536)]})
|
'Tests that partial udpates work as expected'
| def test_partial_updates(self):
| full = list(range(10))
initial = full[3:7]
m1 = TestListModel.create(int_list=initial)
m1.int_list = full
m1.save()
if is_prepend_reversed():
expected = (full[2::(-1)] + full[3:])
else:
expected = full
m2 = TestListModel.get(partition=m1.partition)
self.assertEqual(list(m2.int_list), expected)
|
'Tests that columns instantiated with a column class work properly
and that the class is instantiated in the constructor'
| def test_instantiation_with_column_class(self):
| column = columns.List(columns.Text)
self.assertIsInstance(column.value_col, columns.Text)
|
'Tests that columns instantiated with a column instance work properly'
| def test_instantiation_with_column_instance(self):
| column = columns.List(columns.Text(min_length=100))
self.assertIsInstance(column.value_col, columns.Text)
|
'Tests that to_python of value column is called'
| def test_to_python(self):
| column = columns.List(JsonTestColumn)
val = [1, 2, 3]
db_val = column.to_database(val)
self.assertEqual(db_val, [json.dumps(v) for v in val])
py_val = column.to_python(db_val)
self.assertEqual(py_val, val)
|
'tests that the default empty container is not saved if it hasn\'t been updated'
| def test_default_empty_container_saving(self):
| pkey = uuid4()
TestListModel.create(partition=pkey, int_list=[1, 2, 3, 4])
TestListModel.create(partition=pkey)
m = TestListModel.get(partition=pkey)
self.assertEqual(m.int_list, [1, 2, 3, 4])
|
'Tests that updates from None work as expected'
| def test_blind_list_updates_from_none(self):
| m = TestListModel.create(int_list=None)
expected = [1, 2]
m.int_list = expected
m.save()
m2 = TestListModel.get(partition=m.partition)
self.assertEqual(m2.int_list, expected)
TestListModel.objects(partition=m.partition).update(int_list=[])
m3 = TestListModel.get(partition=m.partition)
self.assertEqual(m3.int_list, [])
|
'Tests that a basic usage works as expected'
| def test_io_success(self):
| k1 = uuid4()
k2 = uuid4()
now = datetime.now()
then = (now + timedelta(days=1))
m1 = TestMapModel.create(int_map={1: k1, 2: k2}, text_map={'now': now, 'then': then})
m2 = TestMapModel.get(partition=m1.partition)
self.assertTrue(isinstance(m2.int_map, dict))
self.assertTrue(isinstance(m2.text_map, dict))
self.assertTrue((1 in m2.int_map))
self.assertTrue((2 in m2.int_map))
self.assertEqual(m2.int_map[1], k1)
self.assertEqual(m2.int_map[2], k2)
self.assertAlmostEqual(get_total_seconds((now - m2.text_map['now'])), 0, 2)
self.assertAlmostEqual(get_total_seconds((then - m2.text_map['then'])), 0, 2)
|
'Tests that attempting to use the wrong types will raise an exception'
| def test_type_validation(self):
| self.assertRaises(ValidationError, TestMapModel.create, **{'int_map': {'key': 2, uuid4(): 'val'}, 'text_map': {2: 5}})
|
'Tests that big collections are detected and raise an exception.'
| def test_element_count_validation(self):
| while True:
try:
TestMapModel.create(text_map=dict(((str(uuid4()), i) for i in range(65535))))
break
except WriteTimeout:
(ex_type, ex, tb) = sys.exc_info()
log.warn('{0}: {1} Backtrace: {2}'.format(ex_type.__name__, ex, traceback.extract_tb(tb)))
del tb
self.assertRaises(ValidationError, TestMapModel.create, **{'text_map': dict(((str(uuid4()), i) for i in range(65536)))})
|
'Tests that partial udpates work as expected'
| def test_partial_updates(self):
| now = datetime.now()
now = datetime(*now.timetuple()[:(-3)])
early = (now - timedelta(minutes=30))
earlier = (early - timedelta(minutes=30))
later = (now + timedelta(minutes=30))
initial = {'now': now, 'early': earlier}
final = {'later': later, 'early': early}
m1 = TestMapModel.create(text_map=initial)
m1.text_map = final
m1.save()
m2 = TestMapModel.get(partition=m1.partition)
self.assertEqual(m2.text_map, final)
|
'Tests that updates from None work as expected'
| def test_updates_from_none(self):
| m = TestMapModel.create(int_map=None)
expected = {1: uuid4()}
m.int_map = expected
m.save()
m2 = TestMapModel.get(partition=m.partition)
self.assertEqual(m2.int_map, expected)
m2.int_map = None
m2.save()
m3 = TestMapModel.get(partition=m.partition)
self.assertNotEqual(m3.int_map, expected)
|
'Tests that updates from None work as expected'
| def test_blind_updates_from_none(self):
| m = TestMapModel.create(int_map=None)
expected = {1: uuid4()}
m.int_map = expected
m.save()
m2 = TestMapModel.get(partition=m.partition)
self.assertEqual(m2.int_map, expected)
TestMapModel.objects(partition=m.partition).update(int_map={})
m3 = TestMapModel.get(partition=m.partition)
self.assertNotEqual(m3.int_map, expected)
|
'Tests that setting the field to None works as expected'
| def test_updates_to_none(self):
| m = TestMapModel.create(int_map={1: uuid4()})
m.int_map = None
m.save()
m2 = TestMapModel.get(partition=m.partition)
self.assertEqual(m2.int_map, {})
|
'Tests that columns instantiated with a column class work properly
and that the class is instantiated in the constructor'
| def test_instantiation_with_column_class(self):
| column = columns.Map(columns.Text, columns.Integer)
self.assertIsInstance(column.key_col, columns.Text)
self.assertIsInstance(column.value_col, columns.Integer)
|
'Tests that columns instantiated with a column instance work properly'
| def test_instantiation_with_column_instance(self):
| column = columns.Map(columns.Text(min_length=100), columns.Integer())
self.assertIsInstance(column.key_col, columns.Text)
self.assertIsInstance(column.value_col, columns.Integer)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.