|
| 1 | +/* |
| 2 | + Copyright The containerd Authors. |
| 3 | +
|
| 4 | + Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + you may not use this file except in compliance with the License. |
| 6 | + You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | + Unless required by applicable law or agreed to in writing, software |
| 11 | + distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + See the License for the specific language governing permissions and |
| 14 | + limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package types |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "sync" |
| 22 | + "testing" |
| 23 | + "time" |
| 24 | + |
| 25 | + "github.com/stretchr/testify/assert" |
| 26 | + |
| 27 | + "github.com/containerd/containerd/v2/internal/cri/store/sandbox" |
| 28 | +) |
| 29 | + |
| 30 | +func Test_PodSandbox(t *testing.T) { |
| 31 | + p := NewPodSandbox("test", sandbox.Status{State: sandbox.StateUnknown}) |
| 32 | + assert.Equal(t, p.Status.Get().State, sandbox.StateUnknown) |
| 33 | + assert.Equal(t, p.ID, "test") |
| 34 | + p.Metadata = sandbox.Metadata{ID: "test", NetNSPath: "/test"} |
| 35 | + createAt := time.Now() |
| 36 | + assert.NoError(t, p.Status.Update(func(status sandbox.Status) (sandbox.Status, error) { |
| 37 | + status.State = sandbox.StateReady |
| 38 | + status.Pid = uint32(100) |
| 39 | + status.CreatedAt = createAt |
| 40 | + return status, nil |
| 41 | + })) |
| 42 | + status := p.Status.Get() |
| 43 | + assert.Equal(t, status.State, sandbox.StateReady) |
| 44 | + assert.Equal(t, status.Pid, uint32(100)) |
| 45 | + assert.Equal(t, status.CreatedAt, createAt) |
| 46 | + |
| 47 | + exitAt := time.Now().Add(time.Second) |
| 48 | + wg := sync.WaitGroup{} |
| 49 | + wg.Add(1) |
| 50 | + go func() { |
| 51 | + defer wg.Done() |
| 52 | + ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*500) |
| 53 | + defer cancel() |
| 54 | + _, err := p.Wait(ctx) |
| 55 | + assert.Equal(t, err, ctx.Err()) |
| 56 | + }() |
| 57 | + |
| 58 | + wg.Add(1) |
| 59 | + go func() { |
| 60 | + defer wg.Done() |
| 61 | + exitStatus, err := p.Wait(context.Background()) |
| 62 | + assert.Equal(t, err, nil) |
| 63 | + code, exitTime, err := exitStatus.Result() |
| 64 | + assert.Equal(t, err, nil) |
| 65 | + assert.Equal(t, code, uint32(128)) |
| 66 | + assert.Equal(t, exitTime, exitAt) |
| 67 | + }() |
| 68 | + time.Sleep(time.Second) |
| 69 | + if err := p.Exit(uint32(128), exitAt); err != nil { |
| 70 | + t.Fatalf("failed to set exit of pod sandbox %v", err) |
| 71 | + } |
| 72 | + wg.Wait() |
| 73 | +} |
0 commit comments