summaryrefslogtreecommitdiff
path: root/vendor/github.com/getlantern/ops/ops_test.go
blob: 1c16e73cee84000f6ad0b69338acefefc21bbf92 (plain)
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package ops_test

import (
	"sync"
	"testing"

	"github.com/getlantern/errors"
	"github.com/getlantern/ops"
	"github.com/stretchr/testify/assert"
)

func TestSuccess(t *testing.T) {
	var reportedFailure error
	var reportedCtx map[string]interface{}
	report := func(failure error, ctx map[string]interface{}) {
		reportedFailure = failure
		reportedCtx = ctx
	}

	ops.RegisterReporter(report)
	ops.SetGlobal("g", "g1")
	op := ops.Begin("test_success").Set("a", 1).SetDynamic("b", func() interface{} { return 2 })
	defer op.End()
	innerOp := op.Begin("inside")
	innerOp.FailIf(nil)
	innerOp.End()

	assert.Nil(t, reportedFailure)
	expectedCtx := map[string]interface{}{
		"op":      "inside",
		"root_op": "test_success",
		"g":       "g1",
		"a":       1,
		"b":       2,
	}
	assert.Equal(t, expectedCtx, reportedCtx)
}

func TestFailure(t *testing.T) {
	doTestFailure(t, false)
}

func TestCancel(t *testing.T) {
	doTestFailure(t, true)
}

func doTestFailure(t *testing.T, cancel bool) {
	var reportedFailure error
	var reportedCtx map[string]interface{}
	report := func(failure error, ctx map[string]interface{}) {
		reportedFailure = failure
		reportedCtx = ctx
	}

	ops.RegisterReporter(report)
	op := ops.Begin("test_failure")
	var wg sync.WaitGroup
	wg.Add(1)
	op.Go(func() {
		op.FailIf(errors.New("I failed").With("errorcontext", 5))
		wg.Done()
	})
	wg.Wait()
	if cancel {
		op.Cancel()
	}
	op.End()

	if cancel {
		assert.Nil(t, reportedFailure)
		assert.Nil(t, reportedCtx)
	} else {
		assert.Contains(t, reportedFailure.Error(), "I failed")
		assert.Equal(t, 5, reportedCtx["errorcontext"])
	}
}