File: trylock_test.go

package info (click to toggle)
golang-github-pion-turn.v2 2.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bookworm-backports, forky, sid, trixie
  • size: 716 kB
  • sloc: makefile: 4
file content (61 lines) | stat: -rw-r--r-- 1,092 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
package client

import (
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
)

func TestTryLock(t *testing.T) {
	t.Run("success case", func(t *testing.T) {
		cl := &TryLock{}
		testFunc := func() error {
			if err := cl.Lock(); err != nil {
				return err
			}
			defer cl.Unlock()
			return nil
		}

		err := testFunc()
		assert.NoError(t, err, "should succeed")
		assert.Equal(t, int32(0), cl.n, "should match")
	})

	t.Run("failure case", func(t *testing.T) {
		cl := &TryLock{}
		testFunc := func() error {
			if err := cl.Lock(); err != nil {
				return err
			}
			defer cl.Unlock()
			time.Sleep(50 * time.Millisecond)
			return nil
		}

		var err1, err2 error
		doneCh1 := make(chan struct{})
		doneCh2 := make(chan struct{})

		go func() {
			err1 = testFunc()
			close(doneCh1)
		}()
		go func() {
			err2 = testFunc()
			close(doneCh2)
		}()

		<-doneCh1
		<-doneCh2

		// Either one of them should fail
		if err1 == nil {
			assert.Error(t, err2, "should fail")
		} else {
			assert.Error(t, err1, "should fail")
		}
		assert.Equal(t, int32(0), cl.n, "should match")
	})
}