|
| 1 | +/* |
| 2 | +* SPDX-FileCopyrightText: Copyright (c) <2024> NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 3 | +* SPDX-License-Identifier: Apache-2.0 |
| 4 | +* |
| 5 | +* Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +* you may not use this file except in compliance with the License. |
| 7 | +* You may obtain a copy of the License at |
| 8 | +* |
| 9 | +* http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +* |
| 11 | +* Unless required by applicable law or agreed to in writing, software |
| 12 | +* distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +* See the License for the specific language governing permissions and |
| 15 | +* limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +package validator |
| 19 | + |
| 20 | +import ( |
| 21 | + "net" |
| 22 | + "sync" |
| 23 | + "testing" |
| 24 | + |
| 25 | + canaryv1 "github.com/nvidia/container-canary/internal/apis/v1" |
| 26 | + "github.com/stretchr/testify/require" |
| 27 | +) |
| 28 | + |
| 29 | +func TestTCPSocketSuccess(t *testing.T) { |
| 30 | + require := require.New(t) |
| 31 | + |
| 32 | + c := &dummyContainer{} |
| 33 | + probe := &canaryv1.Probe{ |
| 34 | + TCPSocket: &canaryv1.TCPSocketAction{ |
| 35 | + Port: 54321, |
| 36 | + }, |
| 37 | + } |
| 38 | + |
| 39 | + var wg sync.WaitGroup |
| 40 | + wg.Add(1) |
| 41 | + listener, err := net.Listen("tcp", "localhost:54321") |
| 42 | + require.NoError(err) |
| 43 | + success := false |
| 44 | + go func() { |
| 45 | + conn, err := listener.Accept() |
| 46 | + require.NoError(err) |
| 47 | + conn.Close() |
| 48 | + success = true |
| 49 | + wg.Done() |
| 50 | + }() |
| 51 | + |
| 52 | + logger, buf := logger() |
| 53 | + e := logger.Info() |
| 54 | + result, err := TCPSocketCheck(c, probe, e) |
| 55 | + e.Send() |
| 56 | + |
| 57 | + require.True(result) |
| 58 | + require.NoError(err) |
| 59 | + require.Equal("{\"level\":\"info\"}\n", buf.String()) |
| 60 | + wg.Wait() |
| 61 | + require.True(success) |
| 62 | +} |
| 63 | + |
| 64 | +func TestTCPSocketFailure(t *testing.T) { |
| 65 | + require := require.New(t) |
| 66 | + |
| 67 | + c := &dummyContainer{} |
| 68 | + probe := &canaryv1.Probe{ |
| 69 | + TCPSocket: &canaryv1.TCPSocketAction{ |
| 70 | + Port: 54321, |
| 71 | + }, |
| 72 | + } |
| 73 | + |
| 74 | + logger, buf := logger() |
| 75 | + e := logger.Info() |
| 76 | + result, err := TCPSocketCheck(c, probe, e) |
| 77 | + e.Send() |
| 78 | + |
| 79 | + require.False(result) |
| 80 | + require.NoError(err) |
| 81 | + require.Equal("{\"level\":\"info\"}\n", buf.String()) |
| 82 | +} |
0 commit comments