...

Source file src/github.com/chaos-mesh/chaos-mesh/controllers/podnetworkchaos/types_test.go

Documentation: github.com/chaos-mesh/chaos-mesh/controllers/podnetworkchaos

     1  // Copyright 2021 Chaos Mesh Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  // http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  //
    15  
    16  package podnetworkchaos
    17  
    18  import (
    19  	"context"
    20  	"testing"
    21  
    22  	. "github.com/onsi/gomega"
    23  	v1 "k8s.io/api/core/v1"
    24  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    25  	"k8s.io/apimachinery/pkg/runtime"
    26  	"k8s.io/apimachinery/pkg/types"
    27  	ctrl "sigs.k8s.io/controller-runtime"
    28  	"sigs.k8s.io/controller-runtime/pkg/client/fake"
    29  	"sigs.k8s.io/controller-runtime/pkg/log/zap"
    30  
    31  	"github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
    32  	"github.com/chaos-mesh/chaos-mesh/cmd/chaos-controller-manager/provider"
    33  	. "github.com/chaos-mesh/chaos-mesh/controllers/test"
    34  	"github.com/chaos-mesh/chaos-mesh/controllers/utils/recorder"
    35  	"github.com/chaos-mesh/chaos-mesh/pkg/chaosdaemon/pb"
    36  	"github.com/chaos-mesh/chaos-mesh/pkg/mock"
    37  	. "github.com/chaos-mesh/chaos-mesh/pkg/testutils"
    38  )
    39  
    40  func setHostNetwork(objs []runtime.Object) {
    41  	for _, obj := range objs {
    42  		if pod, ok := obj.(*v1.Pod); ok {
    43  			pod.Spec.HostNetwork = true
    44  		}
    45  	}
    46  }
    47  
    48  func TestHostNetworkOption(t *testing.T) {
    49  	defer mock.With("MockChaosDaemonClient", &MockChaosDaemonClient{})()
    50  	RegisterTestingT(t)
    51  
    52  	testCases := []struct {
    53  		name                     string
    54  		enableHostNetworkTesting bool
    55  		errorEvaluation          func(err string)
    56  	}{
    57  		{
    58  			name:                     "host networking testing disabled (default)",
    59  			enableHostNetworkTesting: false,
    60  			errorEvaluation: func(err string) {
    61  				Expect(err).To(ContainSubstring("It's dangerous to inject network chaos on a pod"))
    62  			},
    63  		},
    64  		{
    65  			name:                     "host networking testing enabled",
    66  			enableHostNetworkTesting: true,
    67  			errorEvaluation: func(err string) {
    68  				Expect(err).To(Equal(""))
    69  			},
    70  		},
    71  	}
    72  
    73  	for _, testCase := range testCases {
    74  
    75  		objs, _ := GenerateNPods("p", 1, PodArg{})
    76  
    77  		setHostNetwork(objs)
    78  
    79  		chaos := &v1alpha1.PodNetworkChaos{
    80  			TypeMeta: metav1.TypeMeta{
    81  				Kind:       "PodNetworkChaos",
    82  				APIVersion: "v1",
    83  			},
    84  			ObjectMeta: metav1.ObjectMeta{
    85  				Namespace:  metav1.NamespaceDefault,
    86  				Name:       "p0",
    87  				Generation: 1,
    88  			},
    89  			Spec: v1alpha1.PodNetworkChaosSpec{},
    90  		}
    91  		objs = append(objs, chaos)
    92  
    93  		fakeClient := fake.NewClientBuilder().
    94  			WithScheme(provider.NewScheme()).
    95  			WithRuntimeObjects(objs...).
    96  			WithStatusSubresource(&v1alpha1.PodNetworkChaos{}).
    97  			Build()
    98  
    99  		recorder := recorder.NewDebugRecorder()
   100  		h := &Reconciler{
   101  			Client:                  fakeClient,
   102  			Recorder:                recorder,
   103  			Log:                     zap.New(zap.UseDevMode(true)),
   104  			AllowHostNetworkTesting: testCase.enableHostNetworkTesting,
   105  		}
   106  
   107  		_, err := h.Reconcile(
   108  			context.TODO(),
   109  			ctrl.Request{
   110  				NamespacedName: types.NamespacedName{
   111  					Namespace: metav1.NamespaceDefault,
   112  					Name:      "p0",
   113  				},
   114  			})
   115  		Expect(err).To(BeNil())
   116  
   117  		fakeClient.Get(context.Background(), types.NamespacedName{
   118  			Namespace: metav1.NamespaceDefault,
   119  			Name:      "p0",
   120  		}, chaos)
   121  
   122  		testCase.errorEvaluation(chaos.Status.FailedMessage)
   123  	}
   124  }
   125  
   126  func TestMergenetem(t *testing.T) {
   127  	t.Run("empty", func(t *testing.T) {
   128  		spec := v1alpha1.TcParameter{}
   129  		_, err := mergeNetem(spec)
   130  		if err == nil {
   131  			t.Errorf("expect invalid spec failed with message %s but got nil", invalidNetemSpecMsg)
   132  		}
   133  		if err != nil && err.Error() != invalidNetemSpecMsg {
   134  			t.Errorf("expect merge failed with message %s but got %v", invalidNetemSpecMsg, err)
   135  		}
   136  	})
   137  
   138  	t.Run("delay loss rate", func(t *testing.T) {
   139  		g := NewGomegaWithT(t)
   140  
   141  		spec := v1alpha1.TcParameter{
   142  			Delay: &v1alpha1.DelaySpec{
   143  				Latency:     "90ms",
   144  				Correlation: "25",
   145  				Jitter:      "90ms",
   146  			},
   147  			Loss: &v1alpha1.LossSpec{
   148  				Loss:        "25",
   149  				Correlation: "25",
   150  			},
   151  			Rate: &v1alpha1.RateSpec{
   152  				Rate: "25mbps",
   153  			},
   154  		}
   155  		m, err := mergeNetem(spec)
   156  		g.Expect(err).ShouldNot(HaveOccurred())
   157  		em := &pb.Netem{
   158  			Time:      90000,
   159  			Jitter:    90000,
   160  			DelayCorr: 25,
   161  			Loss:      25,
   162  			LossCorr:  25,
   163  			Rate:      "25mbps",
   164  		}
   165  		g.Expect(m).Should(Equal(em))
   166  	})
   167  }
   168