MCPcopy
hub / github.com/apache/answer / TestTransactions

Function TestTransactions

plugin/plugin_test/kv_storage_test.go:189–247  ·  view source on GitHub ↗

Test transactions including rollback and nested transactions

(t *testing.T)

Source from the content-addressed store, hash-verified

187
188// Test transactions including rollback and nested transactions
189func TestTransactions(t *testing.T) {
190 setupTestEnvironment()
191 kv := testPlugin.operator
192 ctx := context.Background()
193
194 t.Run("SuccessfulTransaction", func(t *testing.T) {
195 err := kv.Tx(ctx, func(ctx context.Context, txKv *plugin.KVOperator) error {
196 if err := txKv.Set(ctx, plugin.KVParams{Group: "tx_group", Key: "tx_key1", Value: "tx_value1"}); err != nil {
197 return err
198 }
199 if err := txKv.Set(ctx, plugin.KVParams{Group: "tx_group", Key: "tx_key2", Value: "tx_value2"}); err != nil {
200 return err
201 }
202 return nil
203 })
204 if err != nil {
205 t.Fatalf("Successful transaction failed: %v", err)
206 }
207
208 mustGet(t, kv, ctx, "tx_group", "tx_key1", "tx_value1")
209 mustGet(t, kv, ctx, "tx_group", "tx_key2", "tx_value2")
210 })
211
212 t.Run("TransactionRollback", func(t *testing.T) {
213 err := kv.Tx(ctx, func(ctx context.Context, txKv *plugin.KVOperator) error {
214 if err := txKv.Set(ctx, plugin.KVParams{Group: "tx_group", Key: "tx_key3", Value: "tx_value3"}); err != nil {
215 return err
216 }
217 return fmt.Errorf("mock error")
218 })
219 if err == nil {
220 t.Error("Expected transaction to fail but it succeeded")
221 }
222
223 assertNotFound(t, kv, ctx, "tx_group", "tx_key3")
224 })
225
226 t.Run("NestedTransactions", func(t *testing.T) {
227 err := kv.Tx(ctx, func(ctx context.Context, txKv *plugin.KVOperator) error {
228 if err := txKv.Set(ctx, plugin.KVParams{Group: "nested", Key: "key1", Value: "value1"}); err != nil {
229 return err
230 }
231
232 return txKv.Tx(ctx, func(ctx context.Context, nestedKv *plugin.KVOperator) error {
233 if err := nestedKv.Set(ctx, plugin.KVParams{Group: "nested", Key: "key2", Value: "value2"}); err != nil {
234 return err
235 }
236 return fmt.Errorf("mock nested error")
237 })
238 })
239 if err == nil {
240 t.Error("Expected nested transaction to fail but it succeeded")
241 }
242
243 // Verify outer transaction also rolled back
244 assertNotFound(t, kv, ctx, "nested", "key1")
245 assertNotFound(t, kv, ctx, "nested", "key2")
246 })

Callers

nothing calls this directly

Calls 6

setupTestEnvironmentFunction · 0.85
mustGetFunction · 0.85
assertNotFoundFunction · 0.85
RunMethod · 0.80
TxMethod · 0.80
SetMethod · 0.80

Tested by

no test coverage detected