github.com/ethersphere/bee/v2@v2.2.0/pkg/storage/migration/steps_chain_test.go (about)

     1  // Copyright 2022 The Swarm Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package migration_test
     6  
     7  import (
     8  	"testing"
     9  
    10  	storage "github.com/ethersphere/bee/v2/pkg/storage"
    11  	"github.com/ethersphere/bee/v2/pkg/storage/inmemstore"
    12  	"github.com/ethersphere/bee/v2/pkg/storage/migration"
    13  )
    14  
    15  func TestNewStepsChain(t *testing.T) {
    16  	t.Parallel()
    17  
    18  	const populateItemsCount = 100
    19  	store := inmemstore.New()
    20  	populateStore(t, store, populateItemsCount)
    21  
    22  	stepsFn := make([]migration.StepFn, 0)
    23  
    24  	// Create 10 step functions where each would remove single element, having value [0-10)
    25  	for i := 0; i < 10; i++ {
    26  		valForRemoval := i
    27  		var stepFn migration.StepFn
    28  
    29  		// We create two types of step functions, each should have equivalent
    30  		// behavior where each should remove only one element from store
    31  		if i%2 == 0 {
    32  			stepFn = migration.NewStepOnIndex(
    33  				store,
    34  				storage.Query{
    35  					Factory:      newObjFactory,
    36  					ItemProperty: storage.QueryItem,
    37  				},
    38  				migration.WithItemDeleteFn(func(i storage.Item) bool {
    39  					o := i.(*obj)
    40  					return o.id == valForRemoval
    41  				}),
    42  			)
    43  		} else {
    44  			stepFn = func() error {
    45  				return store.Delete(&obj{id: valForRemoval})
    46  			}
    47  		}
    48  
    49  		stepsFn = append(stepsFn, stepFn)
    50  	}
    51  
    52  	stepFn := migration.NewStepsChain(stepsFn...)
    53  	if err := stepFn(); err != nil {
    54  		t.Fatalf("step migration should succeed: %v", err)
    55  	}
    56  
    57  	afterStepCount, err := store.Count(&obj{})
    58  	if err != nil {
    59  		t.Fatalf("count should succeed: %v", err)
    60  	}
    61  
    62  	expectedCount := populateItemsCount - 10
    63  	if afterStepCount != expectedCount {
    64  		t.Fatalf("step migration should remove items; expected count: %d, have count %d", expectedCount, afterStepCount)
    65  	}
    66  }