Skip to content

Commit 06de17c

Browse files
authored
test: add several test cases for the transaction feature (#351)
1 parent 0cf2b55 commit 06de17c

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

README.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,29 @@ end
211211
# either of the values
212212
```
213213

214+
You can early return out of your block with a `next` statement if you want to cancel your transaction.
215+
In this context, don't use `break` and `return` statements.
216+
217+
```ruby
218+
# The transaction isn't executed.
219+
cli.multi do |tx|
220+
next if some_conditions?
221+
222+
tx.call('SET', '{key}1', '1')
223+
tx.call('SET', '{key}2', '2')
224+
end
225+
```
226+
227+
```ruby
228+
# The watching state is automatically cleared with an execution of an empty transaction.
229+
cli.multi(watch: %w[{key}1 {key}2]) do |tx|
230+
next if some_conditions?
231+
232+
tx.call('SET', '{key}1', '1')
233+
tx.call('SET', '{key}2', '2')
234+
end
235+
```
236+
214237
`RedisClient::Cluster#multi` is aware of redirections and node failures like ordinary calls to `RedisClient::Cluster`,
215238
but because you may have written non-idempotent code inside your block, the block is called once if e.g. the slot
216239
it is operating on moves to a different node.

test/redis_client/test_cluster.rb

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,34 @@ def test_transaction_with_empty_block_and_watch
240240
assert_equal(%w[WATCH MULTI EXEC], @captured_commands.to_a.map(&:command).map(&:first))
241241
end
242242

243+
def test_transaction_with_early_return_block
244+
@captured_commands.clear
245+
condition = true
246+
got = @client.multi do |tx|
247+
next if condition
248+
249+
tx.call('SET', 'key', 'value')
250+
end
251+
252+
assert_empty(got)
253+
assert_empty(@captured_commands.to_a.map(&:command).map(&:first))
254+
assert_nil(@client.call('GET', 'key'))
255+
end
256+
257+
def test_transaction_with_early_return_block_in_watching
258+
@captured_commands.clear
259+
condition = true
260+
got = @client.multi(watch: %w[key]) do |tx|
261+
next if condition
262+
263+
tx.call('SET', 'key', 'value')
264+
end
265+
266+
assert_empty(got)
267+
assert_equal(%w[WATCH MULTI EXEC], @captured_commands.to_a.map(&:command).map(&:first))
268+
assert_nil(@client.call('GET', 'key'))
269+
end
270+
243271
def test_transaction_with_only_keyless_commands
244272
assert_raises(::RedisClient::Cluster::Transaction::ConsistencyError) do
245273
@client.multi do |t|

0 commit comments

Comments
 (0)