File: test_lwt_conditional.py

package info (click to toggle)
python-cassandra-driver 3.29.2-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 5,144 kB
  • sloc: python: 51,532; ansic: 768; makefile: 136; sh: 13
file content (294 lines) | stat: -rw-r--r-- 11,876 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# Copyright DataStax, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
from unittest import mock
from uuid import uuid4

from cassandra.cqlengine import columns
from cassandra.cqlengine.management import sync_table, drop_table
from cassandra.cqlengine.models import Model
from cassandra.cqlengine.query import BatchQuery, LWTException
from cassandra.cqlengine.statements import ConditionalClause

from tests.integration.cqlengine.base import BaseCassEngTestCase
from tests.integration import greaterthancass20


class TestConditionalModel(Model):
    id = columns.UUID(primary_key=True, default=uuid4)
    count = columns.Integer()
    text = columns.Text(required=False)


class TestUpdateModel(Model):
    partition = columns.Integer(primary_key=True)
    cluster = columns.Integer(primary_key=True)
    value = columns.Integer(required=False)
    text = columns.Text(required=False, index=True)


@greaterthancass20
class TestConditional(BaseCassEngTestCase):

    @classmethod
    def setUpClass(cls):
        super(TestConditional, cls).setUpClass()
        sync_table(TestConditionalModel)

    @classmethod
    def tearDownClass(cls):
        super(TestConditional, cls).tearDownClass()
        drop_table(TestConditionalModel)

    def test_update_using_conditional(self):
        t = TestConditionalModel.if_not_exists().create(text='blah blah')
        t.text = 'new blah'
        with mock.patch.object(self.session, 'execute') as m:
            t.iff(text='blah blah').save()

        args = m.call_args
        self.assertIn('IF "text" = %(0)s', args[0][0].query_string)

    def test_update_conditional_success(self):
        t = TestConditionalModel.if_not_exists().create(text='blah blah', count=5)
        id = t.id
        t.text = 'new blah'
        t.iff(text='blah blah').save()

        updated = TestConditionalModel.objects(id=id).first()
        self.assertEqual(updated.count, 5)
        self.assertEqual(updated.text, 'new blah')

    def test_update_failure(self):
        t = TestConditionalModel.if_not_exists().create(text='blah blah')
        t.text = 'new blah'
        t = t.iff(text='something wrong')

        with self.assertRaises(LWTException) as assertion:
            t.save()

        self.assertEqual(assertion.exception.existing, {
            'text': 'blah blah',
            '[applied]': False,
        })

    def test_blind_update(self):
        t = TestConditionalModel.if_not_exists().create(text='blah blah')
        t.text = 'something else'
        uid = t.id

        with mock.patch.object(self.session, 'execute') as m:
            TestConditionalModel.objects(id=uid).iff(text='blah blah').update(text='oh hey der')

        args = m.call_args
        self.assertIn('IF "text" = %(1)s', args[0][0].query_string)

    def test_blind_update_fail(self):
        t = TestConditionalModel.if_not_exists().create(text='blah blah')
        t.text = 'something else'
        uid = t.id
        qs = TestConditionalModel.objects(id=uid).iff(text='Not dis!')
        with self.assertRaises(LWTException) as assertion:
            qs.update(text='this will never work')

        self.assertEqual(assertion.exception.existing, {
            'text': 'blah blah',
            '[applied]': False,
        })

    def test_conditional_clause(self):
        tc = ConditionalClause('some_value', 23)
        tc.set_context_id(3)

        self.assertEqual('"some_value" = %(3)s', str(tc))
        self.assertEqual('"some_value" = %(3)s', str(tc))

    def test_batch_update_conditional(self):
        t = TestConditionalModel.if_not_exists().create(text='something', count=5)
        id = t.id
        with BatchQuery() as b:
            t.batch(b).iff(count=5).update(text='something else')

        updated = TestConditionalModel.objects(id=id).first()
        self.assertEqual(updated.text, 'something else')

        b = BatchQuery()
        updated.batch(b).iff(count=6).update(text='and another thing')
        with self.assertRaises(LWTException) as assertion:
            b.execute()

        self.assertEqual(assertion.exception.existing, {
            'id': id,
            'count': 5,
            '[applied]': False,
        })

        updated = TestConditionalModel.objects(id=id).first()
        self.assertEqual(updated.text, 'something else')

    @unittest.skip("Skipping until PYTHON-943 is resolved")
    def test_batch_update_conditional_several_rows(self):
        sync_table(TestUpdateModel)
        self.addCleanup(drop_table, TestUpdateModel)

        first_row = TestUpdateModel.create(partition=1, cluster=1, value=5, text="something")
        second_row = TestUpdateModel.create(partition=1, cluster=2, value=5, text="something")

        b = BatchQuery()
        TestUpdateModel.batch(b).if_not_exists().create(partition=1, cluster=1, value=5, text='something else')
        TestUpdateModel.batch(b).if_not_exists().create(partition=1, cluster=2, value=5, text='something else')
        TestUpdateModel.batch(b).if_not_exists().create(partition=1, cluster=3, value=5, text='something else')

        # The response will be more than two rows because two of the inserts will fail
        with self.assertRaises(LWTException):
            b.execute()

        first_row.delete()
        second_row.delete()
        b.execute()


    def test_delete_conditional(self):
        # DML path
        t = TestConditionalModel.if_not_exists().create(text='something', count=5)
        self.assertEqual(TestConditionalModel.objects(id=t.id).count(), 1)
        with self.assertRaises(LWTException):
            t.iff(count=9999).delete()
        self.assertEqual(TestConditionalModel.objects(id=t.id).count(), 1)
        t.iff(count=5).delete()
        self.assertEqual(TestConditionalModel.objects(id=t.id).count(), 0)

        # QuerySet path
        t = TestConditionalModel.if_not_exists().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=9999).delete()
        self.assertEqual(TestConditionalModel.objects(id=t.id).count(), 1)
        TestConditionalModel.objects(id=t.id).iff(count=5).delete()
        self.assertEqual(TestConditionalModel.objects(id=t.id).count(), 0)

    def test_delete_lwt_ne(self):
        """
        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
        """

        # DML path
        t = TestConditionalModel.if_not_exists().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)

        # QuerySet path
        t = TestConditionalModel.if_not_exists().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)

    def test_update_lwt_ne(self):
        """
        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
        """

        # DML path
        t = TestConditionalModel.if_not_exists().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()

        # QuerySet path
        t = TestConditionalModel.if_not_exists().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()

    def test_update_to_none(self):
        # This test is done because updates to none are split into deletes
        # for old versions of cassandra. Can be removed when we drop that code
        # https://github.com/datastax/python-driver/blob/3.1.1/cassandra/cqlengine/query.py#L1197-L1200

        # DML path
        t = TestConditionalModel.if_not_exists().create(text='something', count=5)
        self.assertEqual(TestConditionalModel.objects(id=t.id).count(), 1)
        with self.assertRaises(LWTException):
            t.iff(count=9999).update(text=None)
        self.assertIsNotNone(TestConditionalModel.objects(id=t.id).first().text)
        t.iff(count=5).update(text=None)
        self.assertIsNone(TestConditionalModel.objects(id=t.id).first().text)

        # QuerySet path
        t = TestConditionalModel.if_not_exists().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=9999).update(text=None)
        self.assertIsNotNone(TestConditionalModel.objects(id=t.id).first().text)
        TestConditionalModel.objects(id=t.id).iff(count=5).update(text=None)
        self.assertIsNone(TestConditionalModel.objects(id=t.id).first().text)

    def test_column_delete_after_update(self):
        # DML path
        t = TestConditionalModel.if_not_exists().create(text='something', count=5)
        t.iff(count=5).update(text=None, count=6)

        self.assertIsNone(t.text)
        self.assertEqual(t.count, 6)

        # QuerySet path
        t = TestConditionalModel.if_not_exists().create(text='something', count=5)
        TestConditionalModel.objects(id=t.id).iff(count=5).update(text=None, count=6)

        self.assertIsNone(TestConditionalModel.objects(id=t.id).first().text)
        self.assertEqual(TestConditionalModel.objects(id=t.id).first().count, 6)

    def test_conditional_without_instance(self):
        """
        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
        """
        uuid = uuid4()
        TestConditionalModel.if_not_exists().create(id=uuid, text='test_for_cassandra', count=5)

        # This uses the iff method directly from the model class without
        # an instance having been created
        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)