WIP
This commit is contained in:
28
src/cleanup/cleanup.go
Normal file
28
src/cleanup/cleanup.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package cleanup
|
||||
|
||||
import "context"
|
||||
|
||||
const ctxKey = "__cleanup"
|
||||
|
||||
func Inject(ctx context.Context, foo func()) context.Context {
|
||||
before := Extract(ctx)
|
||||
after := func() {
|
||||
foo()
|
||||
before()
|
||||
}
|
||||
return context.WithValue(ctx, ctxKey, after)
|
||||
}
|
||||
|
||||
func Extract(ctx context.Context) func() {
|
||||
v := ctx.Value(ctxKey)
|
||||
if v == nil {
|
||||
return func() {}
|
||||
}
|
||||
|
||||
v2, _ := v.(func())
|
||||
if v2 == nil {
|
||||
return func() {}
|
||||
}
|
||||
|
||||
return v2
|
||||
}
|
||||
33
src/cleanup/cleanup_test.go
Normal file
33
src/cleanup/cleanup_test.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package cleanup_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"show-rss/src/cleanup"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCleanup(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
called := make([]bool, 100)
|
||||
for i := range called {
|
||||
i := i
|
||||
ctx = cleanup.Inject(ctx, func() {
|
||||
t.Logf("cleaning %d", i)
|
||||
if i < len(called)-1 && !called[i+1] {
|
||||
t.Errorf("cleaning %d before %d", i, i+1)
|
||||
}
|
||||
called[i] = true
|
||||
})
|
||||
}
|
||||
|
||||
t.Logf("cleaning")
|
||||
cleanup.Extract(ctx)()
|
||||
t.Logf("cleaned")
|
||||
|
||||
for i := range called {
|
||||
if !called[i] {
|
||||
t.Fatalf("missing called[%d]", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user