func NewBaseClientSet() (*BaseClientSet, error) {
config, err := clientcmd.BuildConfigFromFlags("", types.KUBE_CONF_FILE)
if err != nil {
return nil, err
}
clientSet, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, err
}
baseClient := &BaseClientSet{
ClientSet: clientSet,
}
return baseClient, err
}
该方式读取配置文件内的ca.crt、kubectl.crt、kubectl.key等认证文件不支持相对路径,写测试用例时需注意。
func NewBaseClientSet() (*BaseClientSet, error) {
data, err := AppFs.ReadFile(types.KUBE_CONF_FILE)
if err != nil {
return nil, err
}
config, err := clientcmd.RESTConfigFromKubeConfig(data)
if err != nil {
return nil, err
}
clientSet, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, err
}
baseClient := &BaseClientSet{
ClientSet: clientSet,
}
return baseClient, err
}
测试用例,动态获取绝对路径:
func TestNewBaseClientSet(t *testing.T) {
Convey("Subject: Test pkg.restful.kube.client_set.NewBaseClientSet\n", t, func() {
patches := NewPatches()
defer patches.Reset()
kubeConfigByte, _ := ioutil.ReadFile("../../../testdata/conf/kubectl.kubeconfig")
_, filename, _, _ := runtime.Caller(0)
absPath := path.Dir(filename)
certificateAuthority := filepath.Join(absPath, "../../../testdata/ca.crt")
clientCertificate := filepath.Join(absPath, "../../../testdata/kubectl.crt")
clientKey := filepath.Join(absPath, "../../../testdata/kubectl.key")
kubeConfig := fmt.Sprintf(string(kubeConfigByte), certificateAuthority, clientCertificate, clientKey)
fmt.Println(kubeConfig)
AppFs.WriteFile(types.KUBE_CONF_FILE, []byte(kubeConfig), 0640)
Convey("BuildConfigFromFlags fail", func() {
patches.ApplyFunc(clientcmd.BuildConfigFromFlags, func(string, string) (*rest.Config, error) {
return &rest.Config{}, fmt.Errorf("BuildConfigFromFlags fail")
})
clientSet, err := NewBaseClientSet()
So(err.Error(), ShouldContainSubstring, "fail")
So(clientSet, ShouldEqual, nil)
})
})