desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Tests that to_python of value column is called'
def test_to_python(self):
column = columns.Map(JsonTestColumn, JsonTestColumn) val = {1: 2, 3: 4, 5: 6} db_val = column.to_database(val) self.assertEqual(db_val, dict(((json.dumps(k), json.dumps(v)) for (k, v) in val.items()))) 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() tmap = {1: uuid4(), 2: uuid4()} TestMapModel.create(partition=pkey, int_map=tmap) TestMapModel.create(partition=pkey) m = TestMapModel.get(partition=pkey) self.assertEqual(m.int_map, tmap)
'Tests creation and insertion of tuple types with models @since 3.1 @jira_ticket PYTHON-306 @expected_result Model is successfully crated @test_category object_mapper'
def test_initial(self):
tmp = TestTupleModel.create() tmp.int_tuple = (1, 2, 3)
'Tests creation and insertion of tuple types with models, and their retrieval. @since 3.1 @jira_ticket PYTHON-306 @expected_result Model is successfully crated @test_category object_mapper'
def test_initial_retrieve(self):
tmp = TestTupleModel.create() tmp2 = tmp.get(partition=tmp.partition) tmp2.int_tuple = (1, 2, 3)
'Tests creation and insertion of various types with models, and their retrieval. @since 3.1 @jira_ticket PYTHON-306 @expected_result Model is successfully created and fetched correctly @test_category object_mapper'
def test_io_success(self):
m1 = TestTupleModel.create(int_tuple=(1, 2, 3, 5, 6), text_tuple=('kai', 'andreas'), mixed_tuple=('first', 2, 'Third')) m2 = TestTupleModel.get(partition=m1.partition) self.assertIsInstance(m2.int_tuple, tuple) self.assertIsInstance(m2.text_tuple, tuple) self.assertIsInstance(m2.mixed_tuple, tuple) self.assertEqual((1, 2, 3), m2.int_tuple) self.assertEqual(('kai', 'andreas'), m2.text_tuple) self.assertEqual(('first', 2, 'Third'), m2.mixed_tuple)
'Tests to make sure tuple type validation occurs @since 3.1 @jira_ticket PYTHON-306 @expected_result validation errors are raised @test_category object_mapper'
def test_type_validation(self):
self.assertRaises(ValidationError, TestTupleModel.create, **{'int_tuple': ('string', True), 'text_tuple': ('test', 'test'), 'mixed_tuple': ('one', 2, 'three')}) self.assertRaises(ValidationError, TestTupleModel.create, **{'int_tuple': ('string', 'string'), 'text_tuple': (1, 3.0), 'mixed_tuple': ('one', 2, 'three')}) self.assertRaises(ValidationError, TestTupleModel.create, **{'int_tuple': ('string', 'string'), 'text_tuple': ('test', 'test'), 'mixed_tuple': (1, 'two', 3)})
'Tests that columns instantiated with a column class work properly and that the class is instantiated in the constructor @since 3.1 @jira_ticket PYTHON-306 @expected_result types are instantiated correctly @test_category object_mapper'
def test_instantiation_with_column_class(self):
mixed_tuple = columns.Tuple(columns.Text, columns.Integer, columns.Text, required=False) self.assertIsInstance(mixed_tuple.types[0], columns.Text) self.assertIsInstance(mixed_tuple.types[1], columns.Integer) self.assertIsInstance(mixed_tuple.types[2], columns.Text) self.assertEqual(len(mixed_tuple.types), 3)
'Tests that the default empty container is not saved if it hasn\'t been updated @since 3.1 @jira_ticket PYTHON-306 @expected_result empty tuple is not upserted @test_category object_mapper'
def test_default_empty_container_saving(self):
pkey = uuid4() TestTupleModel.create(partition=pkey, int_tuple=(1, 2, 3)) TestTupleModel.create(partition=pkey) m = TestTupleModel.get(partition=pkey) self.assertEqual(m.int_tuple, (1, 2, 3))
'Tests that updates can be preformed on tuple containers @since 3.1 @jira_ticket PYTHON-306 @expected_result tuple is replaced @test_category object_mapper'
def test_updates(self):
initial = (1, 2) replacement = (1, 2, 3) m1 = TestTupleModel.create(int_tuple=initial) m1.int_tuple = replacement m1.save() m2 = TestTupleModel.get(partition=m1.partition) self.assertEqual(tuple(m2.int_tuple), replacement)
'Tests that explcit none updates are processed correctly on tuples @since 3.1 @jira_ticket PYTHON-306 @expected_result tuple is replaced with none @test_category object_mapper'
def test_update_from_non_empty_to_empty(self):
pkey = uuid4() tmp = TestTupleModel.create(partition=pkey, int_tuple=(1, 2, 3)) tmp.int_tuple = None tmp.update() tmp = TestTupleModel.get(partition=pkey) self.assertEqual(tmp.int_tuple, None)
'Tests that Tuples can be created as none @since 3.1 @jira_ticket PYTHON-306 @expected_result tuple is created as none @test_category object_mapper'
def test_insert_none(self):
pkey = uuid4() tmp = TestTupleModel.create(partition=pkey, int_tuple=None) self.assertEqual(None, tmp.int_tuple)
'Tests that Tuples can be updated from none @since 3.1 @jira_ticket PYTHON-306 @expected_result tuple is created as none, but upserted to contain values @test_category object_mapper'
def test_blind_tuple_updates_from_none(self):
m = TestTupleModel.create(int_tuple=None) expected = (1, 2, 3) m.int_tuple = expected m.save() m2 = TestTupleModel.get(partition=m.partition) self.assertEqual(m2.int_tuple, expected) TestTupleModel.objects(partition=m.partition).update(int_tuple=None) m3 = TestTupleModel.get(partition=m.partition) self.assertEqual(m3.int_tuple, None)
'Tests creation and insertion of nested collection types with models @since 3.1 @jira_ticket PYTHON-478 @expected_result Model is successfully created @test_category object_mapper'
def test_initial(self):
tmp = TestNestedModel.create() tmp.list_list = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
'Tests creation and insertion of nested collection types with models, and their retrieval. @since 3.1 @jira_ticket PYTHON-478 @expected_result Model is successfully crated @test_category object_mapper'
def test_initial_retrieve(self):
tmp = TestNestedModel.create() tmp2 = tmp.get(partition=tmp.partition) tmp2.list_list = [[1, 2, 3], [2, 3, 4], [3, 4, 5]] tmp2.map_list = {'key1': ['text1', 'text2', 'text3'], 'key2': ['text1', 'text2', 'text3'], 'key3': ['text1', 'text2', 'text3']} tmp2.set_tuple = set(((1, 2), (3, 5), (4, 5)))
'Tests creation and insertion of various nested collection types with models, and their retrieval. @since 3.1 @jira_ticket PYTHON-378 @expected_result Model is successfully created and fetched correctly @test_category object_mapper'
def test_io_success(self):
list_list_master = [[1, 2, 3], [2, 3, 4], [3, 4, 5]] map_list_master = {'key1': ['text1', 'text2', 'text3'], 'key2': ['text1', 'text2', 'text3'], 'key3': ['text1', 'text2', 'text3']} set_tuple_master = set(((1, 2), (3, 5), (4, 5))) m1 = TestNestedModel.create(list_list=list_list_master, map_list=map_list_master, set_tuple=set_tuple_master) m2 = TestNestedModel.get(partition=m1.partition) self.assertIsInstance(m2.list_list, list) self.assertIsInstance(m2.list_list[0], list) self.assertIsInstance(m2.map_list, dict) self.assertIsInstance(m2.map_list.get('key2'), list) self.assertEqual(list_list_master, m2.list_list) self.assertEqual(map_list_master, m2.map_list) self.assertEqual(set_tuple_master, m2.set_tuple) self.assertIsInstance(m2.set_tuple.pop(), tuple)
'Tests to make sure nested collection type validation occurs @since 3.1 @jira_ticket PYTHON-478 @expected_result validation errors are raised @test_category object_mapper'
def test_type_validation(self):
list_list_bad_list_context = [['text', 'text', 'text'], ['text', 'text', 'text'], ['text', 'text', 'text']] list_list_no_list = ['text', 'text', 'text'] map_list_bad_value = {'key1': [1, 2, 3], 'key2': [1, 2, 3], 'key3': [1, 2, 3]} map_list_bad_key = {1: ['text1', 'text2', 'text3'], 2: ['text1', 'text2', 'text3'], 3: ['text1', 'text2', 'text3']} set_tuple_bad_tuple_value = set((('text', 'text'), ('text', 'text'), ('text', 'text'))) set_tuple_not_set = ['This', 'is', 'not', 'a', 'set'] self.assertRaises(ValidationError, TestNestedModel.create, **{'list_list': list_list_bad_list_context}) self.assertRaises(ValidationError, TestNestedModel.create, **{'list_list': list_list_no_list}) self.assertRaises(ValidationError, TestNestedModel.create, **{'map_list': map_list_bad_value}) self.assertRaises(ValidationError, TestNestedModel.create, **{'map_list': map_list_bad_key}) self.assertRaises(ValidationError, TestNestedModel.create, **{'set_tuple': set_tuple_bad_tuple_value}) self.assertRaises(ValidationError, TestNestedModel.create, **{'set_tuple': set_tuple_not_set})
'Tests that columns instantiated with a column class work properly and that the class is instantiated in the constructor @since 3.1 @jira_ticket PYTHON-478 @expected_result types are instantiated correctly @test_category object_mapper'
def test_instantiation_with_column_class(self):
list_list = columns.List(columns.List(columns.Integer), required=False) map_list = columns.Map(columns.Text, columns.List(columns.Text), required=False) set_tuple = columns.Set(columns.Tuple(columns.Integer, columns.Integer), required=False) self.assertIsInstance(list_list, columns.List) self.assertIsInstance(list_list.types[0], columns.List) self.assertIsInstance(map_list.types[0], columns.Text) self.assertIsInstance(map_list.types[1], columns.List) self.assertIsInstance(set_tuple.types[0], columns.Tuple)
'Tests that the default empty nested collection container is not saved if it hasn\'t been updated @since 3.1 @jira_ticket PYTHON-478 @expected_result empty nested collection is not upserted @test_category object_mapper'
def test_default_empty_container_saving(self):
pkey = uuid4() list_list_master = [[1, 2, 3], [2, 3, 4], [3, 4, 5]] map_list_master = {'key1': ['text1', 'text2', 'text3'], 'key2': ['text1', 'text2', 'text3'], 'key3': ['text1', 'text2', 'text3']} set_tuple_master = set(((1, 2), (3, 5), (4, 5))) TestNestedModel.create(partition=pkey, list_list=list_list_master, map_list=map_list_master, set_tuple=set_tuple_master) TestNestedModel.create(partition=pkey) m = TestNestedModel.get(partition=pkey) self.assertEqual(m.list_list, list_list_master) self.assertEqual(m.map_list, map_list_master) self.assertEqual(m.set_tuple, set_tuple_master)
'Tests that updates can be preformed on nested collections @since 3.1 @jira_ticket PYTHON-478 @expected_result nested collection is replaced @test_category object_mapper'
def test_updates(self):
list_list_initial = [[1, 2, 3], [2, 3, 4], [3, 4, 5]] list_list_replacement = [[1, 2, 3], [3, 4, 5]] set_tuple_initial = set(((1, 2), (3, 5), (4, 5))) map_list_initial = {'key1': ['text1', 'text2', 'text3'], 'key2': ['text1', 'text2', 'text3'], 'key3': ['text1', 'text2', 'text3']} map_list_replacement = {'key1': ['text1', 'text2', 'text3'], 'key3': ['text1', 'text2', 'text3']} set_tuple_replacement = set(((7, 7), (7, 7), (4, 5))) m1 = TestNestedModel.create(list_list=list_list_initial, map_list=map_list_initial, set_tuple=set_tuple_initial) m1.list_list = list_list_replacement m1.map_list = map_list_replacement m1.set_tuple = set_tuple_replacement m1.save() m2 = TestNestedModel.get(partition=m1.partition) self.assertEqual(m2.list_list, list_list_replacement) self.assertEqual(m2.map_list, map_list_replacement) self.assertEqual(m2.set_tuple, set_tuple_replacement)
'Tests that explcit none updates are processed correctly on tuples @since 3.1 @jira_ticket PYTHON-478 @expected_result nested collection is replaced with none @test_category object_mapper'
def test_update_from_non_empty_to_empty(self):
list_list_initial = [[1, 2, 3], [2, 3, 4], [3, 4, 5]] map_list_initial = {'key1': ['text1', 'text2', 'text3'], 'key2': ['text1', 'text2', 'text3'], 'key3': ['text1', 'text2', 'text3']} set_tuple_initial = set(((1, 2), (3, 5), (4, 5))) tmp = TestNestedModel.create(list_list=list_list_initial, map_list=map_list_initial, set_tuple=set_tuple_initial) tmp.list_list = [] tmp.map_list = {} tmp.set_tuple = set() tmp.update() tmp = TestNestedModel.get(partition=tmp.partition) self.assertEqual(tmp.list_list, []) self.assertEqual(tmp.map_list, {}) self.assertEqual(tmp.set_tuple, set())
'Tests that Tuples can be created as none @since 3.1 @jira_ticket PYTHON-478 @expected_result nested collection is created as none @test_category object_mapper'
def test_insert_none(self):
pkey = uuid4() tmp = TestNestedModel.create(partition=pkey, list_list=None, map_list=None, set_tuple=None) self.assertEqual([], tmp.list_list) self.assertEqual({}, tmp.map_list) self.assertEqual(set(), tmp.set_tuple)
'Test to ensure that truncate microseconds works as expected. This will be default behavior in the future and we will need to modify the tests to comply with new behavior @since 3.2 @jira_ticket PYTHON-273 @expected_result microseconds should be to the nearest thousand when truncate is set. @test_category object_mapper'
def test_datetime_truncate_microseconds(self):
DateTime.truncate_microseconds = True try: dt_value = datetime(2024, 12, 31, 10, 10, 10, 923567) dt_truncated = datetime(2024, 12, 31, 10, 10, 10, 923000) self.DatetimeTest.objects.create(test_id=6, created_at=dt_value) dt2 = self.DatetimeTest.objects(test_id=6).first() self.assertEqual(dt2.created_at, dt_truncated) finally: DateTime.truncate_microseconds = False
'Check that different ways of reading the value from the model class give the same expected result'
def _check_value_is_correct_in_db(self, value):
if (value is None): result = self.model_class.objects.all().allow_filtering().filter(test_id=0).first() self.assertIsNone(result.class_param) result = self.model_class.objects(test_id=0).first() self.assertIsNone(result.class_param) else: if (not isinstance(value, self.python_klass)): value_to_compare = self.python_klass(value) else: value_to_compare = value result = self.model_class.objects(test_id=0).first() self.assertIsInstance(result.class_param, self.python_klass) self.assertEqual(result.class_param, value_to_compare) result = self.model_class.objects.all().allow_filtering().filter(test_id=0).first() self.assertIsInstance(result.class_param, self.python_klass) self.assertEqual(result.class_param, value_to_compare) result = self.model_class.objects.all().allow_filtering().filter(test_id=0, class_param=value).first() self.assertIsInstance(result.class_param, self.python_klass) self.assertEqual(result.class_param, value_to_compare) return result
'Test that None value is correctly written to the db and then is correctly read'
def test_param_none(self):
self.model_class.objects.create(test_id=1, class_param=None) dt2 = self.model_class.objects(test_id=1).first() self.assertIsNone(dt2.class_param) dts = self.model_class.objects(test_id=1).values_list('class_param') self.assertIsNone(dts[0][0])
'ensures that :return:'
def test_timeuuid_io(self):
t0 = self.TimeUUIDTest.create(test_id=0) t1 = self.TimeUUIDTest.get(test_id=0) assert (t1.timeuuid.time == t1.timeuuid.time)
'Tests that integer columns with a default value of 0 validate'
def test_default_zero_fields_validate(self):
it = self.IntegerTest() it.validate()
'Tests that bigint columns with a default value of 0 validate'
def test_default_zero_fields_validate(self):
it = self.BigIntTest() it.validate()
'Test arbitrary minimal lengths requirements.'
def test_min_length(self):
Ascii(min_length=0).validate('') Ascii(min_length=0).validate(None) Ascii(min_length=0).validate('kevin') Ascii(min_length=1).validate('k') Ascii(min_length=5).validate('kevin') Ascii(min_length=5).validate('kevintastic') with self.assertRaises(ValidationError): Ascii(min_length=1).validate('') with self.assertRaises(ValidationError): Ascii(min_length=1).validate(None) with self.assertRaises(ValidationError): Ascii(min_length=6).validate('') with self.assertRaises(ValidationError): Ascii(min_length=6).validate(None) with self.assertRaises(ValidationError): Ascii(min_length=6).validate('kevin') with self.assertRaises(ValueError): Ascii(min_length=(-1))
'Test arbitrary maximal lengths requirements.'
def test_max_length(self):
Ascii(max_length=0).validate('') Ascii(max_length=0).validate(None) Ascii(max_length=1).validate('') Ascii(max_length=1).validate(None) Ascii(max_length=1).validate('b') Ascii(max_length=5).validate('') Ascii(max_length=5).validate(None) Ascii(max_length=5).validate('b') Ascii(max_length=5).validate('blake') with self.assertRaises(ValidationError): Ascii(max_length=0).validate('b') with self.assertRaises(ValidationError): Ascii(max_length=5).validate('blaketastic') with self.assertRaises(ValueError): Ascii(max_length=(-1))
'Test the validation step doesn\'t re-interpret values.'
def test_unaltering_validation(self):
self.assertEqual(Ascii().validate(''), '') self.assertEqual(Ascii().validate(None), None) self.assertEqual(Ascii().validate('yo'), 'yo')
'Tests that validation is ok on none and blank values if required is False.'
def test_non_required_validation(self):
Ascii().validate('') Ascii().validate(None)
'Tests that validation raise on none and blank values if value required.'
def test_required_validation(self):
Ascii(required=True).validate('k') with self.assertRaises(ValidationError): Ascii(required=True).validate('') with self.assertRaises(ValidationError): Ascii(required=True).validate(None) Ascii(required=True, min_length=0).validate('k') Ascii(required=True, min_length=1).validate('k') with self.assertRaises(ValidationError): Ascii(required=True, min_length=2).validate('k') Ascii(required=True, max_length=1).validate('k') with self.assertRaises(ValidationError): Ascii(required=True, max_length=2).validate('kevin') with self.assertRaises(ValueError): Ascii(required=True, max_length=0)
'Test arbitrary minimal lengths requirements.'
def test_min_length(self):
Text(min_length=0).validate('') Text(min_length=0).validate(None) Text(min_length=0).validate('blake') Text(min_length=1).validate('b') Text(min_length=5).validate('blake') Text(min_length=5).validate('blaketastic') with self.assertRaises(ValidationError): Text(min_length=1).validate('') with self.assertRaises(ValidationError): Text(min_length=1).validate(None) with self.assertRaises(ValidationError): Text(min_length=6).validate('') with self.assertRaises(ValidationError): Text(min_length=6).validate(None) with self.assertRaises(ValidationError): Text(min_length=6).validate('blake') with self.assertRaises(ValueError): Text(min_length=(-1))
'Test arbitrary maximal lengths requirements.'
def test_max_length(self):
Text(max_length=0).validate('') Text(max_length=0).validate(None) Text(max_length=1).validate('') Text(max_length=1).validate(None) Text(max_length=1).validate('b') Text(max_length=5).validate('') Text(max_length=5).validate(None) Text(max_length=5).validate('b') Text(max_length=5).validate('blake') with self.assertRaises(ValidationError): Text(max_length=0).validate('b') with self.assertRaises(ValidationError): Text(max_length=5).validate('blaketastic') with self.assertRaises(ValueError): Text(max_length=(-1))
'Test the validation step doesn\'t re-interpret values.'
def test_unaltering_validation(self):
self.assertEqual(Text().validate(''), '') self.assertEqual(Text().validate(None), None) self.assertEqual(Text().validate('yo'), 'yo')
'Tests that validation is ok on none and blank values if required is False'
def test_non_required_validation(self):
Text().validate('') Text().validate(None)
'Tests that validation raise on none and blank values if value required.'
def test_required_validation(self):
Text(required=True).validate('b') with self.assertRaises(ValidationError): Text(required=True).validate('') with self.assertRaises(ValidationError): Text(required=True).validate(None) Text(required=True, min_length=0).validate('b') Text(required=True, min_length=1).validate('b') with self.assertRaises(ValidationError): Text(required=True, min_length=2).validate('b') Text(required=True, max_length=1).validate('b') with self.assertRaises(ValidationError): Text(required=True, max_length=2).validate('blake') with self.assertRaises(ValueError): Text(required=True, max_length=0)
'If you want to convert the original value used to compare the model vales'
def comparator_converter(self, val):
return val
'Tests the given models class creates and retrieves values as expected'
def test_column_io(self):
if (not self.column): return for (pkey, data) in zip(self.pkey_val, self.data_val): m1 = self._generated_model.create(pkey=pkey, data=data) m2 = self._generated_model.get(pkey=pkey) assert (m1.pkey == m2.pkey == self.comparator_converter(pkey)), self.column assert (m1.data == m2.data == self.comparator_converter(data)), self.column self._generated_model.filter(pkey=pkey).delete()
'Tests that defining a non counter column field in a model with a counter column fails'
def test_defining_a_non_counter_column_fails(self):
try: class model(Model, ): partition = columns.UUID(primary_key=True, default=uuid4) counter = columns.Counter() text = columns.Text() self.fail('did not raise expected ModelDefinitionException') except ModelDefinitionException: pass
'Tests that defining primary keys on counter columns fails'
def test_defining_a_primary_key_counter_column_fails(self):
try: class model(Model, ): partition = columns.UUID(primary_key=True, default=uuid4) cluster = columns.Counter(primary_ley=True) counter = columns.Counter() self.fail('did not raise expected TypeError') except TypeError: pass try: class model(Model, ): partition = columns.UUID(primary_key=True, default=uuid4) cluster = columns.Counter() cluster.primary_key = True counter = columns.Counter() self.fail('did not raise expected ModelDefinitionException') except ModelDefinitionException: pass
'Tests that counter updates work as intended'
def test_updates(self):
instance = TestCounterModel.create() instance.counter += 5 instance.save() actual = TestCounterModel.get(partition=instance.partition) assert (actual.counter == 5)
'Tests updates from multiple queries reaches the correct value'
def test_concurrent_updates(self):
instance = TestCounterModel.create() new1 = TestCounterModel.get(partition=instance.partition) new2 = TestCounterModel.get(partition=instance.partition) new1.counter += 5 new1.save() new2.counter += 5 new2.save() actual = TestCounterModel.get(partition=instance.partition) assert (actual.counter == 10)
'Tests that updating from None uses a create statement'
def test_update_from_none(self):
instance = TestCounterModel() instance.counter += 1 instance.save() new = TestCounterModel.get(partition=instance.partition) assert (new.counter == 1)
'Tests that instantiating a new model instance will set the counter column to zero'
def test_new_instance_defaults_to_zero(self):
instance = TestCounterModel() assert (instance.counter == 0)
'Tests that updates on both static and non-static columns work as intended'
def test_mixed_updates(self):
instance = TestStaticModel.create() instance.static = "it's shared" instance.text = 'some text' instance.save() u = TestStaticModel.get(partition=instance.partition) u.static = "it's still shared" u.text = 'another text' u.update() actual = TestStaticModel.get(partition=u.partition) assert (actual.static == "it's still shared")
'Tests that updates on static only column work as intended'
def test_static_only_updates(self):
instance = TestStaticModel.create() instance.static = "it's shared" instance.text = 'some text' instance.save() u = TestStaticModel.get(partition=instance.partition) u.static = "it's still shared" u.update() actual = TestStaticModel.get(partition=u.partition) assert (actual.static == "it's still shared")
'Tests that save/update/delete works for static column works when clustering key is null'
def test_static_with_null_cluster_key(self):
instance = TestStaticModel.create(cluster=None, static="it's shared") instance.save() u = TestStaticModel.get(partition=instance.partition) u.static = "it's still shared" u.update() actual = TestStaticModel.get(partition=u.partition) assert (actual.static == "it's still shared")
'Test to ensure that deletes using IF and not equals are honored correctly @since 3.2 @jira_ticket PYTHON-328 @expected_result Delete conditional with NE should be honored @test_category object_mapper'
@greaterthancass20 def test_delete_lwt_ne(self):
t = TestConditionalModel.create(text='something', count=5) self.assertEqual(TestConditionalModel.objects(id=t.id).count(), 1) with self.assertRaises(LWTException): t.iff(count__ne=5).delete() t.iff(count__ne=2).delete() self.assertEqual(TestConditionalModel.objects(id=t.id).count(), 0) t = TestConditionalModel.create(text='something', count=5) self.assertEqual(TestConditionalModel.objects(id=t.id).count(), 1) with self.assertRaises(LWTException): TestConditionalModel.objects(id=t.id).iff(count__ne=5).delete() TestConditionalModel.objects(id=t.id).iff(count__ne=2).delete() self.assertEqual(TestConditionalModel.objects(id=t.id).count(), 0)
'Test to ensure that update using IF and not equals are honored correctly @since 3.2 @jira_ticket PYTHON-328 @expected_result update conditional with NE should be honored @test_category object_mapper'
@greaterthancass20 def test_update_lwt_ne(self):
t = TestConditionalModel.create(text='something', count=5) self.assertEqual(TestConditionalModel.objects(id=t.id).count(), 1) with self.assertRaises(LWTException): t.iff(count__ne=5).update(text='nothing') t.iff(count__ne=2).update(text='nothing') self.assertEqual(TestConditionalModel.objects(id=t.id).first().text, 'nothing') t.delete() t = TestConditionalModel.create(text='something', count=5) self.assertEqual(TestConditionalModel.objects(id=t.id).count(), 1) with self.assertRaises(LWTException): TestConditionalModel.objects(id=t.id).iff(count__ne=5).update(text='nothing') TestConditionalModel.objects(id=t.id).iff(count__ne=2).update(text='nothing') self.assertEqual(TestConditionalModel.objects(id=t.id).first().text, 'nothing') t.delete()
'Test to ensure that the iff method is honored if it\'s called directly from the Model class @jira_ticket PYTHON-505 @expected_result the value is updated @test_category object_mapper'
def test_conditional_without_instance(self):
uuid = uuid4() TestConditionalModel.create(id=uuid, text='test_for_cassandra', count=5) TestConditionalModel.iff(count=5).filter(id=uuid).update(text=None, count=6) t = TestConditionalModel.filter(id=uuid).first() self.assertIsNone(t.text) self.assertEqual(t.count, 6)
'tests that ttls on models work as expected'
def test_ttl_included_on_create(self):
session = get_session() with mock.patch.object(session, 'execute') as m: TestTTLModel.ttl(60).create(text='hello blake') query = m.call_args[0][0].query_string self.assertIn('USING TTL', query)
'ensures we get a queryset descriptor back'
def test_queryset_is_returned_on_class(self):
qs = TestTTLModel.ttl(60) self.assertTrue(isinstance(qs, TestTTLModel.__queryset__), type(qs))
'ensures that we properly handle the instance.ttl(60).save() scenario :return:'
def test_instance_is_returned(self):
o = TestTTLModel.create(text='whatever') o.text = 'new stuff' o = o.ttl(60) self.assertEqual(60, o._ttl)
'Tests that queries with helper functions are generated properly'
def test_maxtimeuuid_function(self):
now = datetime.now() where = WhereClause('time', EqualsOperator(), functions.MaxTimeUUID(now)) where.set_context_id(5) self.assertEqual(str(where), '"time" = MaxTimeUUID(%(5)s)') ctx = {} where.update_context(ctx) self.assertEqual(ctx, {'5': columns.DateTime().to_database(now)})
'Tests that queries with helper functions are generated properly'
def test_mintimeuuid_function(self):
now = datetime.now() where = WhereClause('time', EqualsOperator(), functions.MinTimeUUID(now)) where.set_context_id(5) self.assertEqual(str(where), '"time" = MinTimeUUID(%(5)s)') ctx = {} where.update_context(ctx) self.assertEqual(ctx, {'5': columns.DateTime().to_database(now)})
'Tests that token functions work properly'
@execute_count(15) def test_token_function(self):
assert (TokenTestModel.objects.count() == 0) for i in range(10): TokenTestModel.create(key=i, val=i) assert (TokenTestModel.objects.count() == 10) seen_keys = set() last_token = None for instance in TokenTestModel.objects().limit(5): last_token = instance.key seen_keys.add(last_token) assert (len(seen_keys) == 5) for instance in TokenTestModel.objects(pk__token__gt=functions.Token(last_token)): seen_keys.add(instance.key) assert (len(seen_keys) == 10) assert all([(i in seen_keys) for i in range(10)]) r = TokenTestModel.objects(pk__token=functions.Token(last_token)) self.assertEqual(len(r), 1)
'Test to ensure that token function work with named tables. @since 3.2 @jira_ticket PYTHON-272 @expected_result partition key token functions should all for pagination. Prior to Python-272 this would fail with an AttributeError @test_category object_mapper'
@execute_count(7) def test_named_table_pk_token_function(self):
for i in range(5): TokenTestModel.create(key=i, val=i) named = NamedTable(DEFAULT_KEYSPACE, TokenTestModel.__table_name__) query = named.all().limit(1) first_page = list(query) last = first_page[(-1)] self.assertTrue((len(first_page) is 1)) next_page = list(query.filter(pk__token__gt=functions.Token(last.key))) self.assertTrue((len(next_page) is 1))
'Tests the queryset filter method parses it\'s kwargs properly'
def test_query_filter_parsing(self):
query1 = TestModel.objects(test_id=5) assert (len(query1._where) == 1) op = query1._where[0] assert isinstance(op, statements.WhereClause) assert isinstance(op.operator, operators.EqualsOperator) assert (op.value == 5) query2 = query1.filter(expected_result__gte=1) assert (len(query2._where) == 2) op = query2._where[1] self.assertIsInstance(op, statements.WhereClause) self.assertIsInstance(op.operator, operators.GreaterThanOrEqualOperator) assert (op.value == 1)
'Tests that query experessions are evaluated properly'
def test_query_expression_parsing(self):
query1 = TestModel.filter((TestModel.test_id == 5)) assert (len(query1._where) == 1) op = query1._where[0] assert isinstance(op, statements.WhereClause) assert isinstance(op.operator, operators.EqualsOperator) assert (op.value == 5) query2 = query1.filter((TestModel.expected_result >= 1)) assert (len(query2._where) == 2) op = query2._where[1] self.assertIsInstance(op, statements.WhereClause) self.assertIsInstance(op.operator, operators.GreaterThanOrEqualOperator) assert (op.value == 1)
'Tests that using invalid or nonexistant column names for filter args raises an error'
def test_using_invalid_column_names_in_filter_kwargs_raises_error(self):
with self.assertRaises(query.QueryException): TestModel.objects(nonsense=5)
'Tests that using invalid or nonexistant columns for query args raises an error'
def test_using_nonexistant_column_names_in_query_args_raises_error(self):
with self.assertRaises(AttributeError): TestModel.objects((TestModel.nonsense == 5))
'Tests that providing query args that are not query operator instances raises an error'
def test_using_non_query_operators_in_query_args_raises_error(self):
with self.assertRaises(query.QueryException): TestModel.objects(5)
'Tests that calling a queryset function that changes it\'s state returns a new queryset'
def test_queryset_is_immutable(self):
query1 = TestModel.objects(test_id=5) assert (len(query1._where) == 1) query2 = query1.filter(expected_result__gte=1) assert (len(query2._where) == 2) assert (len(query1._where) == 1)
'Tests that calling a queryset function that changes it\'s state returns a new queryset with same limit'
def test_queryset_limit_immutability(self):
query1 = TestModel.objects(test_id=5).limit(1) assert (query1._limit == 1) query2 = query1.filter(expected_result__gte=1) assert (query2._limit == 1) query3 = query1.filter(expected_result__gte=1).limit(2) assert (query1._limit == 1) assert (query3._limit == 2)
'Tests that calling all on a queryset with previously defined filters duplicates queryset'
def test_the_all_method_duplicates_queryset(self):
query1 = TestModel.objects(test_id=5) assert (len(query1._where) == 1) query2 = query1.filter(expected_result__gte=1) assert (len(query2._where) == 2) query3 = query2.all() assert (query3 == query2)
'Tests that calling distinct on a queryset w/without parameter are evaluated properly.'
def test_queryset_with_distinct(self):
query1 = TestModel.objects.distinct() self.assertEqual(len(query1._distinct_fields), 1) query2 = TestModel.objects.distinct(['test_id']) self.assertEqual(len(query2._distinct_fields), 1) query3 = TestModel.objects.distinct(['test_id', 'attempt_id']) self.assertEqual(len(query3._distinct_fields), 2)
'Tests defining only fields @since 3.5 @jira_ticket PYTHON-560 @expected_result deferred fields should not be returned @test_category object_mapper'
def test_defining_only_fields(self):
q = TestModel.objects.only(['attempt_id', 'description']) self.assertEqual(q._select_fields(), ['attempt_id', 'description']) with self.assertRaises(query.QueryException): TestModel.objects.only(['nonexistent_field']) with self.assertRaises(query.QueryException): TestModel.objects.only(['description']).only(['attempt_id']) q = TestModel.objects.only(['attempt_id', 'description']) q = q.defer(['description']) self.assertEqual(q._select_fields(), ['attempt_id']) q = TestModel.objects.only(['description']) q = q.defer(['description']) with self.assertRaises(query.QueryException): q._select_fields() q = TestModel.objects.filter(test_id=0).only(['test_id', 'attempt_id', 'description']) self.assertEqual(q._select_fields(), ['attempt_id', 'description']) with self.assertRaises(query.QueryException): q = TestModel.objects.only(['test_id']).defer(['test_id']) q._select_fields() with self.assertRaises(query.QueryException): q = TestModel.objects.filter(test_id=0).only(['test_id']) q._select_fields()
'Tests defining defer fields @since 3.5 @jira_ticket PYTHON-560 @jira_ticket PYTHON-599 @expected_result deferred fields should not be returned @test_category object_mapper'
def test_defining_defer_fields(self):
q = TestModel.objects.defer(['attempt_id', 'description']) self.assertEqual(q._select_fields(), ['test_id', 'expected_result', 'test_result']) with self.assertRaises(query.QueryException): TestModel.objects.defer(['nonexistent_field']) q = TestModel.objects.defer(['attempt_id', 'description']) q = q.defer(['expected_result']) self.assertEqual(q._select_fields(), ['test_id', 'test_result']) q = TestModel.objects.defer(['description', 'attempt_id']) q = q.only(['description', 'test_id']) self.assertEqual(q._select_fields(), ['test_id']) q = TestModel.objects.defer(['description', 'attempt_id']) q = q.only(['description']) with self.assertRaises(query.QueryException): q._select_fields() q = TestModel.objects.filter(test_id=0) self.assertEqual(q._select_fields(), ['attempt_id', 'description', 'expected_result', 'test_result']) q = TestModel.objects.defer(['test_id', 'attempt_id', 'description', 'expected_result', 'test_result']) self.assertEqual(q._select_fields(), ['test_id'])
'Tests that adding filtering statements affects the count query as expected'
@execute_count(2) def test_count(self):
assert (TestModel.objects.count() == 12) q = TestModel.objects(test_id=0) assert (q.count() == 4)
'Tests that adding query statements affects the count query as expected'
@execute_count(2) def test_query_expression_count(self):
assert (TestModel.objects.count() == 12) q = TestModel.objects((TestModel.test_id == 0)) assert (q.count() == 4)
'Tests that iterating over a query set pulls back all of the expected results'
@execute_count(3) def test_iteration(self):
q = TestModel.objects(test_id=0) compare_set = set([(0, 5), (1, 10), (2, 15), (3, 20)]) for t in q: val = (t.attempt_id, t.expected_result) assert (val in compare_set) compare_set.remove(val) assert (len(compare_set) == 0) q = TestModel.objects(attempt_id=3).allow_filtering() assert (len(q) == 3) compare_set = set([(0, 20), (1, 20), (2, 75)]) for t in q: val = (t.test_id, t.expected_result) assert (val in compare_set) compare_set.remove(val) assert (len(compare_set) == 0) q = TestModel.objects((TestModel.attempt_id == 3)).allow_filtering() assert (len(q) == 3) compare_set = set([(0, 20), (1, 20), (2, 75)]) for t in q: val = (t.test_id, t.expected_result) assert (val in compare_set) compare_set.remove(val) assert (len(compare_set) == 0)
'Tests that iterating over a query set more than once works'
@execute_count(2) def test_multiple_iterations_work_properly(self):
for q in (TestModel.objects(test_id=0), TestModel.objects((TestModel.test_id == 0))): compare_set = set([(0, 5), (1, 10), (2, 15), (3, 20)]) for t in q: val = (t.attempt_id, t.expected_result) assert (val in compare_set) compare_set.remove(val) assert (len(compare_set) == 0) compare_set = set([(0, 5), (1, 10), (2, 15), (3, 20)]) for t in q: val = (t.attempt_id, t.expected_result) assert (val in compare_set) compare_set.remove(val) assert (len(compare_set) == 0)
'tests that the use of one iterator does not affect the behavior of another'
@execute_count(2) def test_multiple_iterators_are_isolated(self):
for q in (TestModel.objects(test_id=0), TestModel.objects((TestModel.test_id == 0))): q = q.order_by('attempt_id') expected_order = [0, 1, 2, 3] iter1 = iter(q) iter2 = iter(q) for attempt_id in expected_order: assert (next(iter1).attempt_id == attempt_id) assert (next(iter2).attempt_id == attempt_id)
'Tests that the .get() method works on new and existing querysets'
@execute_count(3) def test_get_success_case(self):
m = TestModel.objects.get(test_id=0, attempt_id=0) assert isinstance(m, TestModel) assert (m.test_id == 0) assert (m.attempt_id == 0) q = TestModel.objects(test_id=0, attempt_id=0) m = q.get() assert isinstance(m, TestModel) assert (m.test_id == 0) assert (m.attempt_id == 0) q = TestModel.objects(test_id=0) m = q.get(attempt_id=0) assert isinstance(m, TestModel) assert (m.test_id == 0) assert (m.attempt_id == 0)
'Tests that the .get() method works on new and existing querysets'
@execute_count(3) def test_query_expression_get_success_case(self):
m = TestModel.get((TestModel.test_id == 0), (TestModel.attempt_id == 0)) assert isinstance(m, TestModel) assert (m.test_id == 0) assert (m.attempt_id == 0) q = TestModel.objects((TestModel.test_id == 0), (TestModel.attempt_id == 0)) m = q.get() assert isinstance(m, TestModel) assert (m.test_id == 0) assert (m.attempt_id == 0) q = TestModel.objects((TestModel.test_id == 0)) m = q.get((TestModel.attempt_id == 0)) assert isinstance(m, TestModel) assert (m.test_id == 0) assert (m.attempt_id == 0)
'Tests that get calls that don\'t return a result raises a DoesNotExist error'
@execute_count(1) def test_get_doesnotexist_exception(self):
with self.assertRaises(TestModel.DoesNotExist): TestModel.objects.get(test_id=100)
'Tests that get calls that return multiple results raise a MultipleObjectsReturned error'
@execute_count(1) def test_get_multipleobjects_exception(self):
with self.assertRaises(TestModel.MultipleObjectsReturned): TestModel.objects.get(test_id=1)
'Tests that queries that don\'t have an equals relation to a primary key or indexed field fail'
def test_primary_key_or_index_must_be_specified(self):
with self.assertRaises(query.QueryException): q = TestModel.objects(test_result=25) list([i for i in q])
'Tests that queries that don\'t have non equal (>,<, etc) relation to a primary key or indexed field fail'
def test_primary_key_or_index_must_have_equal_relation_filter(self):
with self.assertRaises(query.QueryException): q = TestModel.objects(test_id__gt=0) list([i for i in q])
'Tests that queries on an indexed field will work without any primary key relations specified'
@greaterthancass20 @execute_count(7) def test_indexed_field_can_be_queried(self):
q = IndexedTestModel.objects(test_result=25) self.assertEqual(q.count(), 4) q = IndexedCollectionsTestModel.objects.filter(test_list__contains=42) self.assertEqual(q.count(), 1) q = IndexedCollectionsTestModel.objects.filter(test_list__contains=13) self.assertEqual(q.count(), 0) q = IndexedCollectionsTestModel.objects.filter(test_set__contains=42) self.assertEqual(q.count(), 1) q = IndexedCollectionsTestModel.objects.filter(test_set__contains=13) self.assertEqual(q.count(), 0) q = IndexedCollectionsTestModel.objects.filter(test_map__contains=42) self.assertEqual(q.count(), 1) q = IndexedCollectionsTestModel.objects.filter(test_map__contains=13) self.assertEqual(q.count(), 0)
'Tests that attempting to delete a model without defining a partition key fails'
def test_delete_without_partition_key(self):
with self.assertRaises(query.QueryException): TestModel.objects(attempt_id=0).delete()
'Tests that attempting to delete a whole table without any arguments will fail'
def test_delete_without_any_where_args(self):
with self.assertRaises(query.QueryException): TestModel.objects(attempt_id=0).delete()
'Tests that range deletion work as expected'
@unittest.skipIf((CASSANDRA_VERSION < '3.0'), 'range deletion was introduce in C* 3.0, currently running {0}'.format(CASSANDRA_VERSION)) @execute_count(18) def test_range_deletion(self):
for i in range(10): TestMultiClusteringModel.objects().create(one=1, two=i, three=i) TestMultiClusteringModel.objects(one=1, two__gte=0, two__lte=3).delete() self.assertEqual(6, len(TestMultiClusteringModel.objects.all())) TestMultiClusteringModel.objects(one=1, two__gt=3, two__lt=5).delete() self.assertEqual(5, len(TestMultiClusteringModel.objects.all())) TestMultiClusteringModel.objects(one=1, two__in=[8, 9]).delete() self.assertEqual(3, len(TestMultiClusteringModel.objects.all())) TestMultiClusteringModel.objects(one__in=[1], two__gte=0).delete() self.assertEqual(0, len(TestMultiClusteringModel.objects.all()))
'Test that using timezone aware datetime instances works with the MinTimeUUID/MaxTimeUUID functions.'
@execute_count(7) def test_tzaware_datetime_support(self):
pk = uuid4() midpoint_utc = datetime.utcnow().replace(tzinfo=TzOffset(0)) midpoint_helsinki = midpoint_utc.astimezone(TzOffset(3)) assert (midpoint_utc.utctimetuple() == midpoint_helsinki.utctimetuple()) assert (midpoint_utc.timetuple() != midpoint_helsinki.timetuple()) TimeUUIDQueryModel.create(partition=pk, time=uuid_from_time((midpoint_utc - timedelta(minutes=1))), data='1') TimeUUIDQueryModel.create(partition=pk, time=uuid_from_time(midpoint_utc), data='2') TimeUUIDQueryModel.create(partition=pk, time=uuid_from_time((midpoint_utc + timedelta(minutes=1))), data='3') assert (['1', '2'] == [o.data for o in TimeUUIDQueryModel.filter((TimeUUIDQueryModel.partition == pk), (TimeUUIDQueryModel.time <= functions.MaxTimeUUID(midpoint_utc)))]) assert (['1', '2'] == [o.data for o in TimeUUIDQueryModel.filter((TimeUUIDQueryModel.partition == pk), (TimeUUIDQueryModel.time <= functions.MaxTimeUUID(midpoint_helsinki)))]) assert (['2', '3'] == [o.data for o in TimeUUIDQueryModel.filter((TimeUUIDQueryModel.partition == pk), (TimeUUIDQueryModel.time >= functions.MinTimeUUID(midpoint_utc)))]) assert (['2', '3'] == [o.data for o in TimeUUIDQueryModel.filter((TimeUUIDQueryModel.partition == pk), (TimeUUIDQueryModel.time >= functions.MinTimeUUID(midpoint_helsinki)))])
'Test that the min and max time uuid functions work as expected'
@execute_count(8) def test_success_case(self):
pk = uuid4() startpoint = datetime.utcnow() TimeUUIDQueryModel.create(partition=pk, time=uuid_from_time((startpoint + timedelta(seconds=1))), data='1') TimeUUIDQueryModel.create(partition=pk, time=uuid_from_time((startpoint + timedelta(seconds=2))), data='2') midpoint = (startpoint + timedelta(seconds=3)) TimeUUIDQueryModel.create(partition=pk, time=uuid_from_time((startpoint + timedelta(seconds=4))), data='3') TimeUUIDQueryModel.create(partition=pk, time=uuid_from_time((startpoint + timedelta(seconds=5))), data='4') q = TimeUUIDQueryModel.filter(partition=pk, time__lte=functions.MaxTimeUUID(midpoint)) q = [d for d in q] self.assertEqual(len(q), 2, msg=('Got: %s' % q)) datas = [d.data for d in q] assert ('1' in datas) assert ('2' in datas) q = TimeUUIDQueryModel.filter(partition=pk, time__gte=functions.MinTimeUUID(midpoint)) assert (len(q) == 2) datas = [d.data for d in q] assert ('3' in datas) assert ('4' in datas) q = TimeUUIDQueryModel.filter((TimeUUIDQueryModel.partition == pk), (TimeUUIDQueryModel.time <= functions.MaxTimeUUID(midpoint))) q = [d for d in q] assert (len(q) == 2) datas = [d.data for d in q] assert ('1' in datas) assert ('2' in datas) q = TimeUUIDQueryModel.filter((TimeUUIDQueryModel.partition == pk), (TimeUUIDQueryModel.time >= functions.MinTimeUUID(midpoint))) assert (len(q) == 2) datas = [d.data for d in q] assert ('3' in datas) assert ('4' in datas)
'Tests the in operator works with the kwarg query method'
@execute_count(1) def test_kwarg_success_case(self):
q = TestModel.filter(test_id__in=[0, 1]) assert (q.count() == 8)
'Tests the in operator works with the query expression query method'
@execute_count(1) def test_query_expression_success_case(self):
q = TestModel.filter(TestModel.test_id.in_([0, 1])) assert (q.count() == 8)
'Adding coverage to cqlengine for bool types. @since 3.6 @jira_ticket PYTHON-596 @expected_result bool results should be filtered appropriately @test_category object_mapper'
@execute_count(5) def test_bool(self):
class bool_model(Model, ): k = columns.Integer(primary_key=True) b = columns.Boolean(primary_key=True) v = columns.Integer(default=3) sync_table(bool_model) bool_model.create(k=0, b=True) bool_model.create(k=0, b=False) self.assertEqual(len(bool_model.objects.all()), 2) self.assertEqual(len(bool_model.objects.filter(k=0, b=True)), 1) self.assertEqual(len(bool_model.objects.filter(k=0, b=False)), 1)
'Test to ensure that we don\'t translate boolean objects to String unnecessarily in filter clauses @since 3.6 @jira_ticket PYTHON-596 @expected_result We should not receive a server error @test_category object_mapper'
@execute_count(3) def test_bool_filter(self):
class bool_model2(Model, ): k = columns.Boolean(primary_key=True) b = columns.Integer(primary_key=True) v = columns.Text() drop_table(bool_model2) sync_table(bool_model2) bool_model2.create(k=True, b=1, v='a') bool_model2.create(k=False, b=1, v='b') self.assertEqual(len(list(bool_model2.objects(k__in=(True, False)))), 2)
'Tests the CONTAINS operator works with the kwarg query method'
@execute_count(6) def test_kwarg_success_case(self):
q = IndexedCollectionsTestModel.filter(test_list__contains=1) self.assertEqual(q.count(), 2) q = IndexedCollectionsTestModel.filter(test_list__contains=13) self.assertEqual(q.count(), 0) q = IndexedCollectionsTestModel.filter(test_set__contains=3) self.assertEqual(q.count(), 2) q = IndexedCollectionsTestModel.filter(test_set__contains=13) self.assertEqual(q.count(), 0) q = IndexedCollectionsTestModel.filter(test_map__contains=42) self.assertEqual(q.count(), 1) q = IndexedCollectionsTestModel.filter(test_map__contains=13) self.assertEqual(q.count(), 0) with self.assertRaises(QueryException): q = IndexedCollectionsTestModel.filter(test_list_no_index__contains=1) self.assertEqual(q.count(), 0) with self.assertRaises(QueryException): q = IndexedCollectionsTestModel.filter(test_set_no_index__contains=1) self.assertEqual(q.count(), 0) with self.assertRaises(QueryException): q = IndexedCollectionsTestModel.filter(test_map_no_index__contains=1) self.assertEqual(q.count(), 0)
'Tests the CONTAINS operator works with the query expression query method'
@execute_count(6) def test_query_expression_success_case(self):
q = IndexedCollectionsTestModel.filter(IndexedCollectionsTestModel.test_list.contains_(1)) self.assertEqual(q.count(), 2) q = IndexedCollectionsTestModel.filter(IndexedCollectionsTestModel.test_list.contains_(13)) self.assertEqual(q.count(), 0) q = IndexedCollectionsTestModel.filter(IndexedCollectionsTestModel.test_set.contains_(3)) self.assertEqual(q.count(), 2) q = IndexedCollectionsTestModel.filter(IndexedCollectionsTestModel.test_set.contains_(13)) self.assertEqual(q.count(), 0) q = IndexedCollectionsTestModel.filter(IndexedCollectionsTestModel.test_map.contains_(42)) self.assertEqual(q.count(), 1) q = IndexedCollectionsTestModel.filter(IndexedCollectionsTestModel.test_map.contains_(13)) self.assertEqual(q.count(), 0) with self.assertRaises(QueryException): q = IndexedCollectionsTestModel.filter(IndexedCollectionsTestModel.test_map_no_index.contains_(1)) self.assertEqual(q.count(), 0) with self.assertRaises(QueryException): q = IndexedCollectionsTestModel.filter(IndexedCollectionsTestModel.test_map_no_index.contains_(1)) self.assertEqual(q.count(), 0) with self.assertRaises(QueryException): q = IndexedCollectionsTestModel.filter(IndexedCollectionsTestModel.test_map_no_index.contains_(1)) self.assertEqual(q.count(), 0)
'Tests creation update and delete of object model queries that are using db_field mappings. @since 3.1 @jira_ticket PYTHON-351 @expected_result results are properly retrieved without errors @test_category object_mapper'
@execute_count(33) def test_basic_crud(self):
for model in self.model_list: values = {'k0': 1, 'k1': 2, 'c0': 3, 'v0': 4, 'v1': 5} i = model.create(**values) i = model.objects(k0=i.k0, k1=i.k1).first() self.assertEqual(i, model(**values)) values['v0'] = 101 i.update(v0=values['v0']) i = model.objects(k0=i.k0, k1=i.k1).first() self.assertEqual(i, model(**values)) model.objects(k0=i.k0, k1=i.k1).delete() i = model.objects(k0=i.k0, k1=i.k1).first() self.assertIsNone(i) i = model.create(**values) i = model.objects(k0=i.k0, k1=i.k1).first() self.assertEqual(i, model(**values)) i.delete() model.objects(k0=i.k0, k1=i.k1).delete() i = model.objects(k0=i.k0, k1=i.k1).first() self.assertIsNone(i)
'Tests slice queries for object models that are using db_field mapping @since 3.1 @jira_ticket PYTHON-351 @expected_result results are properly retrieved without errors @test_category object_mapper'
@execute_count(21) def test_slice(self):
for model in self.model_list: values = {'k0': 1, 'k1': 3, 'c0': 3, 'v0': 4, 'v1': 5} clustering_values = range(3) for c in clustering_values: values['c0'] = c i = model.create(**values) self.assertEqual(model.objects(k0=i.k0, k1=i.k1).count(), len(clustering_values)) self.assertEqual(model.objects(k0=i.k0, k1=i.k1, c0=i.c0).count(), 1) self.assertEqual(model.objects(k0=i.k0, k1=i.k1, c0__lt=i.c0).count(), len(clustering_values[:(-1)])) self.assertEqual(model.objects(k0=i.k0, k1=i.k1, c0__gt=0).count(), len(clustering_values[1:]))
'Tests order by queries for object models that are using db_field mapping @since 3.1 @jira_ticket PYTHON-351 @expected_result results are properly retrieved without errors @test_category object_mapper'
@execute_count(15) def test_order(self):
for model in self.model_list: values = {'k0': 1, 'k1': 4, 'c0': 3, 'v0': 4, 'v1': 5} clustering_values = range(3) for c in clustering_values: values['c0'] = c i = model.create(**values) self.assertEqual(model.objects(k0=i.k0, k1=i.k1).order_by('c0').first().c0, clustering_values[0]) self.assertEqual(model.objects(k0=i.k0, k1=i.k1).order_by('-c0').first().c0, clustering_values[(-1)])
'Tests queries using index fields for object models using db_field mapping @since 3.1 @jira_ticket PYTHON-351 @expected_result results are properly retrieved without errors @test_category object_mapper'
@execute_count(15) def test_index(self):
for model in self.model_list: values = {'k0': 1, 'k1': 5, 'c0': 3, 'v0': 4, 'v1': 5} clustering_values = range(3) for c in clustering_values: values['c0'] = c values['v1'] = c i = model.create(**values) self.assertEqual(model.objects(k0=i.k0, k1=i.k1).count(), len(clustering_values)) self.assertEqual(model.objects(k0=i.k0, k1=i.k1, v1=0).count(), 1)
'Tests to ensure that with generated cql update statements correctly utilize the db_field values. @since 3.2 @jira_ticket PYTHON-530 @expected_result resulting cql_statements will use the db_field values @test_category object_mapper'
@execute_count(1) def test_db_field_names_used(self):
values = ('k0', 'k1', 'c0', 'v0', 'v1') b = BatchQuery() DBFieldModel.objects(k0=1).batch(b).update(v0=0, v1=9) for value in values: self.assertTrue((value not in str(b.queries[0]))) b2 = BatchQuery() dml_field_model = DBFieldModel.create(k0=1, k1=5, c0=3, v0=4, v1=5) dml_field_model.batch(b2).update(v0=0, v1=9) for value in values: self.assertTrue((value not in str(b2.queries[0])))
'Tests that loading from a range of dates works properly'
@execute_count(1) def test_range_query(self):
start = datetime(*self.base_date.timetuple()[:3]) end = (start + timedelta(days=3)) results = DateTimeQueryTestModel.filter(user=0, day__gte=start, day__lt=end) assert (len(results) == 3)
'Tests that millisecond resolution is preserved when saving datetime objects'
@execute_count(3) def test_datetime_precision(self):
now = datetime.now() pk = 1000 obj = DateTimeQueryTestModel.create(user=pk, day=now, data='energy cheese') load = DateTimeQueryTestModel.get(user=pk) self.assertAlmostEqual(get_total_seconds((now - load.day)), 0, 2) obj.delete()
'Tests the queryset filter method parses it\'s kwargs properly'
def test_query_filter_parsing(self):
query1 = self.table.objects(test_id=5) assert (len(query1._where) == 1) op = query1._where[0] assert isinstance(op.operator, operators.EqualsOperator) assert (op.value == 5) query2 = query1.filter(expected_result__gte=1) assert (len(query2._where) == 2) op = query2._where[1] assert isinstance(op.operator, operators.GreaterThanOrEqualOperator) assert (op.value == 1)