Randomly generate operations on a given database with multiple clients to ensure consistency and thread safety.
(t *testing.T, openOption *bolt.Options, round, threadCount, parallelism int)
| 31 | |
| 32 | // Randomly generate operations on a given database with multiple clients to ensure consistency and thread safety. |
| 33 | func testSimulate(t *testing.T, openOption *bolt.Options, round, threadCount, parallelism int) { |
| 34 | if testing.Short() { |
| 35 | t.Skip("skipping test in short mode.") |
| 36 | } |
| 37 | |
| 38 | // A list of operations that readers and writers can perform. |
| 39 | var readerHandlers = []simulateHandler{simulateGetHandler} |
| 40 | var writerHandlers = []simulateHandler{simulateGetHandler, simulatePutHandler} |
| 41 | |
| 42 | var versions = make(map[int]*QuickDB) |
| 43 | versions[1] = NewQuickDB() |
| 44 | |
| 45 | db := btesting.MustCreateDBWithOption(t, openOption) |
| 46 | |
| 47 | var mutex sync.Mutex |
| 48 | |
| 49 | for n := 0; n < round; n++ { |
| 50 | // Run n threads in parallel, each with their own operation. |
| 51 | var threads = make(chan bool, parallelism) |
| 52 | var wg sync.WaitGroup |
| 53 | |
| 54 | // counter for how many goroutines were fired |
| 55 | var opCount int64 |
| 56 | |
| 57 | // counter for ignored operations |
| 58 | var igCount int64 |
| 59 | |
| 60 | var errCh = make(chan error, threadCount) |
| 61 | |
| 62 | var i int |
| 63 | for { |
| 64 | // this buffered channel will keep accepting booleans |
| 65 | // until it hits the limit defined by the parallelism |
| 66 | // argument to testSimulate() |
| 67 | threads <- true |
| 68 | |
| 69 | // this wait group can only be marked "done" from inside |
| 70 | // the subsequent goroutine |
| 71 | wg.Add(1) |
| 72 | writable := ((rand.Int() % 100) < 20) // 20% writers |
| 73 | |
| 74 | // Choose an operation to execute. |
| 75 | var handler simulateHandler |
| 76 | if writable { |
| 77 | handler = writerHandlers[rand.Intn(len(writerHandlers))] |
| 78 | } else { |
| 79 | handler = readerHandlers[rand.Intn(len(readerHandlers))] |
| 80 | } |
| 81 | |
| 82 | // Execute a thread for the given operation. |
| 83 | go func(writable bool, handler simulateHandler) { |
| 84 | defer wg.Done() |
| 85 | atomic.AddInt64(&opCount, 1) |
| 86 | // Start transaction. |
| 87 | tx, err := db.Begin(writable) |
| 88 | if err != nil { |
| 89 | errCh <- fmt.Errorf("error tx begin: %v", err) |
| 90 | return |
no test coverage detected