github.com/1aal/kubeblocks@v0.0.0-20231107070852-e1c03e598921/test/e2e/util/client.go (about)

     1  /*
     2  Copyright (C) 2022-2023 ApeCloud Co., Ltd
     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 util
    18  
    19  import (
    20  	"os"
    21  
    22  	"github.com/vmware-tanzu/velero/pkg/client"
    23  	"k8s.io/client-go/kubernetes"
    24  	"k8s.io/client-go/rest"
    25  	"k8s.io/client-go/tools/clientcmd"
    26  	kbclient "sigs.k8s.io/controller-runtime/pkg/client"
    27  )
    28  
    29  // TestClient defines the desired type of Client
    30  type TestClient struct {
    31  	Kubebuilder    kbclient.Client
    32  	ClientGo       kubernetes.Interface
    33  	dynamicFactory client.DynamicFactory
    34  }
    35  
    36  // NewTestClient returns a set of ready-to-use API clients.
    37  func NewTestClient(kubecontext string) (TestClient, error) {
    38  	return InitTestClient(kubecontext)
    39  }
    40  
    41  // InitTestClient inits different type clients
    42  func InitTestClient(kubecontext string) (TestClient, error) {
    43  	config, err := client.LoadConfig()
    44  	if err != nil {
    45  		return TestClient{}, err
    46  	}
    47  	f := client.NewFactory("e2e", kubecontext, config)
    48  	clientGo, err := f.KubeClient()
    49  	if err != nil {
    50  		return TestClient{}, err
    51  	}
    52  	kb, err := f.KubebuilderClient()
    53  	if err != nil {
    54  		return TestClient{}, err
    55  	}
    56  	dynamicClient, err := f.DynamicClient()
    57  	if err != nil {
    58  		return TestClient{}, err
    59  	}
    60  	factory := client.NewDynamicFactory(dynamicClient)
    61  	return TestClient{
    62  		Kubebuilder:    kb,
    63  		ClientGo:       clientGo,
    64  		dynamicFactory: factory,
    65  	}, nil
    66  }
    67  
    68  func GetConfig() (*rest.Config, error) {
    69  	kubeConfigPath, exists := os.LookupEnv("KUBECONFIG")
    70  	if !exists {
    71  		kubeConfigPath = os.ExpandEnv("$HOME/.kube/config")
    72  	}
    73  	config, err := clientcmd.BuildConfigFromFlags("", kubeConfigPath)
    74  	if err != nil {
    75  		return nil, err
    76  	}
    77  	return config, nil
    78  }