improve context ux, prevent duplicate setup & teardown

This commit is contained in:
Elijah Duffy
2025-06-04 17:26:12 -07:00
parent 6e7acc758e
commit 1cb207964c
2 changed files with 55 additions and 10 deletions

View File

@@ -54,7 +54,7 @@ func TestLifecycleToFromContext(t *testing.T) {
lc := NewLifecycle()
// Add the Lifecycle to the context
ctx := LifecycleToContext(context.Background(), lc)
ctx := lc.Context(context.Background())
// Retrieve the Lifecycle from the context
retrievedLC := LifecycleFromContext(ctx)
@@ -63,7 +63,8 @@ func TestLifecycleToFromContext(t *testing.T) {
assert.Equal(lc, retrievedLC, "expected retrieved Lifecycle to match original")
// Test with nil Lifecycle
nilCtx := LifecycleToContext(context.Background(), nil)
var nilLifecycle *Lifecycle
nilCtx := nilLifecycle.Context(context.Background())
retrievedNilLC := LifecycleFromContext(nilCtx)
assert.Nil(retrievedNilLC, "expected nil Lifecycle to return nil from context")
}
@@ -171,6 +172,22 @@ func TestLifecycle_Setup(t *testing.T) {
}
})
}
// Test double setup
t.Run("double setup", func(t *testing.T) {
assert := assert.New(t)
lc := NewLifecycle(
NewModule("module1", ModuleOpts{}),
)
err := lc.Setup()
assert.NoError(err, "expected first Setup to succeed")
err = lc.Setup()
assert.Error(err, "expected second Setup to fail")
assert.Contains(err.Error(), "already set up", "expected error message to indicate already set up")
})
}
func TestLifecycle_Teardown(t *testing.T) {
@@ -254,6 +271,26 @@ func TestLifecycle_Teardown(t *testing.T) {
}
})
}
// Test double teardown
t.Run("double teardown", func(t *testing.T) {
assert := assert.New(t)
lc := NewLifecycle(
NewModule("module1", ModuleOpts{}),
)
// Fake setup for the module
lc.modules[0].loaded = true
lc.setupTracker[lc.modules[0].name] = 0
err := lc.Teardown()
assert.NoError(err, "expected first Teardown to succeed")
err = lc.Teardown()
assert.Error(err, "expected second Teardown to fail")
assert.Contains(err.Error(), "already torn down", "expected error message to indicate already torn down")
})
}
func TestLifecycle_Require(t *testing.T) {