Merge pull request #106015 from ahrtr/replace_ioutil_with_io_os_test

Replace ioutil with os and io for the test
This commit is contained in:
Kubernetes Prow Robot 2022-02-03 04:31:44 -08:00 committed by GitHub
commit adbda068c1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
96 changed files with 250 additions and 297 deletions

View File

@ -19,7 +19,6 @@ package main
import (
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/signal"
@ -123,7 +122,7 @@ func saveResults(resultsDir string) error {
return fmt.Errorf("failed to find absolute path for %v: %w", resultsTarball, err)
}
err = ioutil.WriteFile(doneFile, []byte(resultsTarball), os.FileMode(0777))
err = os.WriteFile(doneFile, []byte(resultsTarball), os.FileMode(0777))
if err != nil {
return fmt.Errorf("writing donefile: %w", err)
}

View File

@ -21,7 +21,6 @@ import (
"compress/gzip"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"reflect"
@ -30,7 +29,7 @@ import (
)
func TestTar(t *testing.T) {
tmp, err := ioutil.TempDir("", "testtar")
tmp, err := os.MkdirTemp("", "testtar")
if err != nil {
t.Fatal(err)
}
@ -39,13 +38,13 @@ func TestTar(t *testing.T) {
if err := os.Mkdir(filepath.Join(tmp, "subdir"), os.FileMode(0755)); err != nil {
t.Fatal(err)
}
if err := ioutil.WriteFile(filepath.Join(tmp, "file1"), []byte(`file1 data`), os.FileMode(0644)); err != nil {
if err := os.WriteFile(filepath.Join(tmp, "file1"), []byte(`file1 data`), os.FileMode(0644)); err != nil {
t.Fatal(err)
}
if err := ioutil.WriteFile(filepath.Join(tmp, "file2"), []byte(`file2 data`), os.FileMode(0644)); err != nil {
if err := os.WriteFile(filepath.Join(tmp, "file2"), []byte(`file2 data`), os.FileMode(0644)); err != nil {
t.Fatal(err)
}
if err := ioutil.WriteFile(filepath.Join(tmp, "subdir", "file4"), []byte(`file4 data`), os.FileMode(0644)); err != nil {
if err := os.WriteFile(filepath.Join(tmp, "subdir", "file4"), []byte(`file4 data`), os.FileMode(0644)); err != nil {
t.Fatal(err)
}
@ -138,7 +137,7 @@ func readAllTar(tarPath string) (map[string]string, error) {
return nil, err
}
b, err := ioutil.ReadAll(tr)
b, err := io.ReadAll(tr)
if err != nil {
return nil, err
}

View File

@ -18,7 +18,6 @@ package apimachinery
import (
"crypto/x509"
"io/ioutil"
"os"
"k8s.io/client-go/util/cert"
@ -36,7 +35,7 @@ type certContext struct {
// Setup the server cert. For example, user apiservers and admission webhooks
// can use the cert to prove their identify to the kube-apiserver
func setupServerCert(namespaceName, serviceName string) *certContext {
certDir, err := ioutil.TempDir("", "test-e2e-server-cert")
certDir, err := os.MkdirTemp("", "test-e2e-server-cert")
if err != nil {
framework.Failf("Failed to create a temp dir for cert generation %v", err)
}
@ -49,11 +48,11 @@ func setupServerCert(namespaceName, serviceName string) *certContext {
if err != nil {
framework.Failf("Failed to create CA cert for apiserver %v", err)
}
caCertFile, err := ioutil.TempFile(certDir, "ca.crt")
caCertFile, err := os.CreateTemp(certDir, "ca.crt")
if err != nil {
framework.Failf("Failed to create a temp file for ca cert generation %v", err)
}
if err := ioutil.WriteFile(caCertFile.Name(), utils.EncodeCertPEM(signingCert), 0644); err != nil {
if err := os.WriteFile(caCertFile.Name(), utils.EncodeCertPEM(signingCert), 0644); err != nil {
framework.Failf("Failed to write CA cert %v", err)
}
key, err := utils.NewPrivateKey()
@ -71,22 +70,22 @@ func setupServerCert(namespaceName, serviceName string) *certContext {
if err != nil {
framework.Failf("Failed to create cert%v", err)
}
certFile, err := ioutil.TempFile(certDir, "server.crt")
certFile, err := os.CreateTemp(certDir, "server.crt")
if err != nil {
framework.Failf("Failed to create a temp file for cert generation %v", err)
}
keyFile, err := ioutil.TempFile(certDir, "server.key")
keyFile, err := os.CreateTemp(certDir, "server.key")
if err != nil {
framework.Failf("Failed to create a temp file for key generation %v", err)
}
if err = ioutil.WriteFile(certFile.Name(), utils.EncodeCertPEM(signedCert), 0600); err != nil {
if err = os.WriteFile(certFile.Name(), utils.EncodeCertPEM(signedCert), 0600); err != nil {
framework.Failf("Failed to write cert file %v", err)
}
privateKeyPEM, err := keyutil.MarshalPrivateKeyToPEM(key)
if err != nil {
framework.Failf("Failed to marshal key %v", err)
}
if err = ioutil.WriteFile(keyFile.Name(), privateKeyPEM, 0644); err != nil {
if err = os.WriteFile(keyFile.Name(), privateKeyPEM, 0644); err != nil {
framework.Failf("Failed to write key file %v", err)
}
return &certContext{

View File

@ -20,7 +20,7 @@ import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"regexp"
"strings"
@ -662,7 +662,7 @@ func waitForOpenAPISchema(c k8sclientset.Interface, pred func(*spec.Swagger) (bo
spec = etagSpec
} else if resp.StatusCode != http.StatusOK {
return false, fmt.Errorf("unexpected response: %d", resp.StatusCode)
} else if bs, err := ioutil.ReadAll(resp.Body); err != nil {
} else if bs, err := io.ReadAll(resp.Body); err != nil {
return false, err
} else if err := json.Unmarshal(bs, spec); err != nil {
return false, err

View File

@ -17,7 +17,7 @@ limitations under the License.
package apimachinery
import (
"io/ioutil"
"io"
"net/http"
"strings"
@ -100,7 +100,7 @@ func newRequest(f *framework.Framework, timeout string) *http.Request {
}
func readBody(response *http.Response) string {
raw, err := ioutil.ReadAll(response.Body)
raw, err := io.ReadAll(response.Body)
framework.ExpectNoError(err)
return string(raw)

View File

@ -19,7 +19,7 @@ package autoscaling
import (
"context"
"fmt"
"io/ioutil"
"io"
"math"
"net/http"
"os"
@ -1101,7 +1101,7 @@ func getCluster(apiVersion string) (string, error) {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}

View File

@ -19,7 +19,7 @@ package node
import (
"context"
"fmt"
"io/ioutil"
"os"
"path"
"time"
@ -291,7 +291,7 @@ while true; do sleep 1; done
}`
// we might be told to use a different docker config JSON.
if framework.TestContext.DockerConfigFile != "" {
contents, err := ioutil.ReadFile(framework.TestContext.DockerConfigFile)
contents, err := os.ReadFile(framework.TestContext.DockerConfigFile)
framework.ExpectNoError(err)
auth = string(contents)
}

View File

@ -20,7 +20,6 @@ import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path"
@ -298,7 +297,7 @@ func logClusterImageSources() {
outputBytes, _ := json.MarshalIndent(images, "", " ")
filePath := filepath.Join(framework.TestContext.ReportDir, "images.json")
if err := ioutil.WriteFile(filePath, outputBytes, 0644); err != nil {
if err := os.WriteFile(filePath, outputBytes, 0644); err != nil {
framework.Logf("cluster images sources, could not write to %q: %v", filePath, err)
}
}

View File

@ -24,8 +24,8 @@ package framework
import (
"context"
"fmt"
"io/ioutil"
"math/rand"
"os"
"path"
"strings"
"sync"
@ -328,7 +328,7 @@ func printSummaries(summaries []TestDataSummary, testBaseName string) {
} else {
// TODO: learn to extract test name and append it to the kind instead of timestamp.
filePath := path.Join(TestContext.ReportDir, summaries[i].SummaryKind()+"_"+testBaseName+"_"+now.Format(time.RFC3339)+".txt")
if err := ioutil.WriteFile(filePath, []byte(summaries[i].PrintHumanReadable()), 0644); err != nil {
if err := os.WriteFile(filePath, []byte(summaries[i].PrintHumanReadable()), 0644); err != nil {
Logf("Failed to write file %v with test performance data: %v", filePath, err)
}
}
@ -345,7 +345,7 @@ func printSummaries(summaries []TestDataSummary, testBaseName string) {
// TODO: learn to extract test name and append it to the kind instead of timestamp.
filePath := path.Join(TestContext.ReportDir, summaries[i].SummaryKind()+"_"+testBaseName+"_"+now.Format(time.RFC3339)+".json")
Logf("Writing to %s", filePath)
if err := ioutil.WriteFile(filePath, []byte(summaries[i].PrintJSON()), 0644); err != nil {
if err := os.WriteFile(filePath, []byte(summaries[i].PrintJSON()), 0644); err != nil {
Logf("Failed to write file %v with test performance data: %v", filePath, err)
}
}

View File

@ -26,10 +26,11 @@ import (
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"io/ioutil"
"io"
"math/big"
"net"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
@ -178,7 +179,7 @@ func SimpleGET(c *http.Client, url, host string) (string, error) {
return "", err
}
defer res.Body.Close()
rawBody, err := ioutil.ReadAll(res.Body)
rawBody, err := io.ReadAll(res.Body)
if err != nil {
return "", err
}
@ -533,7 +534,7 @@ func ingressToManifest(ing *networkingv1.Ingress, path string) error {
return fmt.Errorf("failed to marshal ingress %v to YAML: %v", ing, err)
}
if err := ioutil.WriteFile(path, serialized, 0600); err != nil {
if err := os.WriteFile(path, serialized, 0600); err != nil {
return fmt.Errorf("error in writing ingress to file: %s", err)
}
return nil

View File

@ -17,7 +17,6 @@ limitations under the License.
package ingress
import (
"io/ioutil"
"os"
"path/filepath"
"testing"
@ -28,7 +27,7 @@ import (
func TestIngressToManifest(t *testing.T) {
ing := &networkingv1.Ingress{}
// Create a temp dir.
tmpDir, err := ioutil.TempDir("", "kubemci")
tmpDir, err := os.MkdirTemp("", "kubemci")
if err != nil {
t.Fatalf("unexpected error in creating temp dir: %s", err)
}

View File

@ -20,7 +20,7 @@ import (
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"regexp"
"strconv"
@ -117,7 +117,7 @@ func decodeConfigz(resp *http.Response) (*kubeletconfig.KubeletConfiguration, er
configz := configzWrapper{}
kubeCfg := kubeletconfig.KubeletConfiguration{}
contentsBytes, err := ioutil.ReadAll(resp.Body)
contentsBytes, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}

View File

@ -18,7 +18,7 @@ package manifest
import (
"fmt"
"io/ioutil"
"io"
"net/http"
"time"
@ -115,7 +115,7 @@ func DaemonSetFromURL(url string) (*appsv1.DaemonSet, error) {
}
defer response.Body.Close()
data, err := ioutil.ReadAll(response.Body)
data, err := io.ReadAll(response.Body)
if err != nil {
return nil, fmt.Errorf("Failed to read html response body: %v", err)
}

View File

@ -19,7 +19,7 @@ package metrics
import (
"context"
"fmt"
"io/ioutil"
"io"
"net/http"
"sort"
"strconv"
@ -73,7 +73,7 @@ func GrabKubeletMetricsWithoutProxy(nodeName, path string) (KubeletMetrics, erro
return KubeletMetrics{}, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return KubeletMetrics{}, err
}

View File

@ -21,7 +21,7 @@ import (
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net"
"net/http"
"strconv"
@ -1005,7 +1005,7 @@ func PokeHTTP(host string, port int, path string, params *HTTPPokeParams) HTTPPo
ret.Code = resp.StatusCode
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
ret.Status = HTTPError
ret.Error = fmt.Errorf("error reading HTTP body: %v", err)

View File

@ -20,7 +20,7 @@ import (
"context"
"errors"
"fmt"
"io/ioutil"
"io"
"net"
"net/http"
"regexp"
@ -116,7 +116,7 @@ func (d *Dialer) DialContainerPort(ctx context.Context, addr Addr) (conn net.Con
}
errorStream.Close()
go func() {
message, err := ioutil.ReadAll(errorStream)
message, err := io.ReadAll(errorStream)
switch {
case err != nil:
klog.ErrorS(err, "error reading from error stream")

View File

@ -20,7 +20,6 @@ import (
"bytes"
"context"
"fmt"
"io/ioutil"
"net"
"os"
"path/filepath"
@ -102,7 +101,7 @@ func GetSigner(provider string) (ssh.Signer, error) {
}
func makePrivateKeySignerFromFile(key string) (ssh.Signer, error) {
buffer, err := ioutil.ReadFile(key)
buffer, err := os.ReadFile(key)
if err != nil {
return nil, fmt.Errorf("error reading SSH key %s: '%v'", key, err)
}

View File

@ -22,7 +22,6 @@ import (
"errors"
"flag"
"fmt"
"io/ioutil"
"math"
"os"
"sort"
@ -449,7 +448,7 @@ func AfterReadingAllFlags(t *TestContextType) {
if len(t.Host) == 0 && len(t.KubeConfig) == 0 {
// Check if we can use the in-cluster config
if clusterConfig, err := restclient.InClusterConfig(); err == nil {
if tempFile, err := ioutil.TempFile(os.TempDir(), "kubeconfig-"); err == nil {
if tempFile, err := os.CreateTemp(os.TempDir(), "kubeconfig-"); err == nil {
kubeConfig := createKubeConfig(clusterConfig)
clientcmd.WriteToFile(*kubeConfig, tempFile.Name())
t.KubeConfig = tempFile.Name()

View File

@ -29,7 +29,6 @@ import (
"errors"
"fmt"
"io/fs"
"io/ioutil"
"os"
"path"
"path/filepath"
@ -122,7 +121,7 @@ func (r RootFileSource) ReadTestFile(filePath string) ([]byte, error) {
} else {
fullPath = filepath.Join(r.Root, filePath)
}
data, err := ioutil.ReadFile(fullPath)
data, err := os.ReadFile(fullPath)
if os.IsNotExist(err) {
// Not an error (yet), some other provider may have the file.
return nil, nil

View File

@ -20,7 +20,7 @@ import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"reflect"
"time"
@ -89,7 +89,7 @@ func testAgent(f *framework.Framework, kubeClient clientset.Interface) {
if resp.StatusCode != 200 {
framework.Failf("Stackdriver Metadata API returned error status: %s", resp.Status)
}
metadataAPIResponse, err := ioutil.ReadAll(resp.Body)
metadataAPIResponse, err := io.ReadAll(resp.Body)
if err != nil {
framework.Failf("Failed to read response from Stackdriver Metadata API: %s", err)
}

View File

@ -24,7 +24,6 @@ import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
@ -280,7 +279,7 @@ var _ = SIGDescribe("Kubectl client", func() {
}
framework.Logf("%s modified at %s (current time: %s)", path, info.ModTime(), time.Now())
data, readError := ioutil.ReadFile(path)
data, readError := os.ReadFile(path)
if readError != nil {
framework.Logf("%s error: %v", path, readError)
} else {
@ -691,11 +690,11 @@ var _ = SIGDescribe("Kubectl client", func() {
// Build a kubeconfig file that will make use of the injected ca and token,
// but point at the DNS host and the default namespace
tmpDir, err := ioutil.TempDir("", "icc-override")
tmpDir, err := os.MkdirTemp("", "icc-override")
overrideKubeconfigName := "icc-override.kubeconfig"
framework.ExpectNoError(err)
defer func() { os.Remove(tmpDir) }()
framework.ExpectNoError(ioutil.WriteFile(filepath.Join(tmpDir, overrideKubeconfigName), []byte(`
framework.ExpectNoError(os.WriteFile(filepath.Join(tmpDir, overrideKubeconfigName), []byte(`
kind: Config
apiVersion: v1
clusters:
@ -719,14 +718,14 @@ users:
framework.Logf("copying override kubeconfig to the %s pod", simplePodName)
framework.RunKubectlOrDie(ns, "cp", filepath.Join(tmpDir, overrideKubeconfigName), ns+"/"+simplePodName+":/tmp/")
framework.ExpectNoError(ioutil.WriteFile(filepath.Join(tmpDir, "invalid-configmap-with-namespace.yaml"), []byte(`
framework.ExpectNoError(os.WriteFile(filepath.Join(tmpDir, "invalid-configmap-with-namespace.yaml"), []byte(`
kind: ConfigMap
apiVersion: v1
metadata:
name: "configmap with namespace and invalid name"
namespace: configmap-namespace
`), os.FileMode(0755)))
framework.ExpectNoError(ioutil.WriteFile(filepath.Join(tmpDir, "invalid-configmap-without-namespace.yaml"), []byte(`
framework.ExpectNoError(os.WriteFile(filepath.Join(tmpDir, "invalid-configmap-without-namespace.yaml"), []byte(`
kind: ConfigMap
apiVersion: v1
metadata:
@ -1385,7 +1384,7 @@ metadata:
ginkgo.It("should copy a file from a running Pod", func() {
remoteContents := "foobar\n"
podSource := fmt.Sprintf("%s:/root/foo/bar/foo.bar", busyboxPodName)
tempDestination, err := ioutil.TempFile(os.TempDir(), "copy-foobar")
tempDestination, err := os.CreateTemp(os.TempDir(), "copy-foobar")
if err != nil {
framework.Failf("Failed creating temporary destination file: %v", err)
}
@ -1393,7 +1392,7 @@ metadata:
ginkgo.By("specifying a remote filepath " + podSource + " on the pod")
framework.RunKubectlOrDie(ns, "cp", podSource, tempDestination.Name())
ginkgo.By("verifying that the contents of the remote file " + podSource + " have been copied to a local file " + tempDestination.Name())
localData, err := ioutil.ReadAll(tempDestination)
localData, err := io.ReadAll(tempDestination)
if err != nil {
framework.Failf("Failed reading temporary local file: %v", err)
}
@ -1648,7 +1647,7 @@ metadata:
*/
framework.ConformanceIt("should support --unix-socket=/path ", func() {
ginkgo.By("Starting the proxy")
tmpdir, err := ioutil.TempDir("", "kubectl-proxy-unix")
tmpdir, err := os.MkdirTemp("", "kubectl-proxy-unix")
if err != nil {
framework.Failf("Failed to create temporary directory: %v", err)
}
@ -1958,7 +1957,7 @@ func curlTransport(url string, transport *http.Transport) (string, error) {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}

View File

@ -23,7 +23,7 @@ import (
"context"
"encoding/binary"
"fmt"
"io/ioutil"
"io"
"net"
"os/exec"
"regexp"
@ -231,7 +231,7 @@ func doTestConnectSendDisconnect(bindAddress string, f *framework.Framework) {
}()
ginkgo.By("Reading data from the local port")
fromServer, err := ioutil.ReadAll(conn)
fromServer, err := io.ReadAll(conn)
if err != nil {
framework.Failf("Unexpected error reading data from the server: %v", err)
}
@ -323,7 +323,7 @@ func doTestMustConnectSendDisconnect(bindAddress string, f *framework.Framework)
fmt.Fprint(conn, "abc")
ginkgo.By("Reading data from the local port")
fromServer, err := ioutil.ReadAll(conn)
fromServer, err := io.ReadAll(conn)
if err != nil {
framework.Failf("Unexpected error reading data from the server: %v", err)
}

View File

@ -19,7 +19,7 @@ package network
import (
"context"
"fmt"
"io/ioutil"
"io"
"os"
"path/filepath"
"strings"
@ -175,7 +175,7 @@ func prepareResourceWithReplacedString(inputFile, old, new string) string {
f, err := os.Open(inputFile)
framework.ExpectNoError(err, "failed to open file: %s", inputFile)
defer f.Close()
data, err := ioutil.ReadAll(f)
data, err := io.ReadAll(f)
framework.ExpectNoError(err, "failed to read from file: %s", inputFile)
podYaml := strings.Replace(string(data), old, new, 1)
return podYaml

View File

@ -19,7 +19,7 @@ package scale
import (
"context"
"fmt"
"io/ioutil"
"os"
"sync"
"time"
@ -316,7 +316,7 @@ func (f *IngressScaleFramework) dumpLatencies() {
formattedData := f.GetFormattedLatencies()
if f.OutputFile != "" {
f.Logger.Infof("Dumping scale test latencies to file %s...", f.OutputFile)
ioutil.WriteFile(f.OutputFile, []byte(formattedData), 0644)
os.WriteFile(f.OutputFile, []byte(formattedData), 0644)
return
}
f.Logger.Infof("\n%v", formattedData)

View File

@ -20,7 +20,7 @@ import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"strings"
"time"
@ -123,7 +123,7 @@ func (reporter *ProgressReporter) postProgressToURL(b []byte) {
klog.Errorf("Unexpected response when posting progress update to %v: %v", reporter.progressURL, resp.StatusCode)
if resp.Body != nil {
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
respBody, err := io.ReadAll(resp.Body)
if err != nil {
klog.Errorf("Failed to read response body from posting progress: %v", err)
return

View File

@ -22,7 +22,6 @@ package drivers
import (
"context"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
@ -79,7 +78,7 @@ func createGCESecrets(client clientset.Interface, ns string) {
framework.ExpectNoError(err, "error copying service account key: %s\nstdout: %s\nstderr: %s", err, stdout, stderr)
defer shredFile(saFile)
// Create Secret with this Service Account
fileBytes, err := ioutil.ReadFile(saFile)
fileBytes, err := os.ReadFile(saFile)
framework.ExpectNoError(err, "Failed to read file %v", saFile)
s := &v1.Secret{

View File

@ -21,7 +21,6 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"sync"
@ -220,7 +219,7 @@ func dial(ctx context.Context, prefix string, dialer httpstream.Dialer, port int
}
errorStream.Close()
go func() {
message, err := ioutil.ReadAll(errorStream)
message, err := io.ReadAll(errorStream)
switch {
case err != nil:
klog.Errorf("%s: error reading from error stream: %v", prefix, err)

View File

@ -21,7 +21,7 @@ import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"os"
"time"
storagev1 "k8s.io/api/storage/v1"
@ -182,7 +182,7 @@ func loadDriverDefinition(filename string) (*driverDefinition, error) {
if filename == "" {
return nil, fmt.Errorf("missing file name")
}
data, err := ioutil.ReadFile(filename)
data, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
@ -339,7 +339,7 @@ func (d *driverDefinition) GetTimeouts() *framework.TimeoutContext {
}
func loadSnapshotClass(filename string) (*unstructured.Unstructured, error) {
data, err := ioutil.ReadFile(filename)
data, err := os.ReadFile(filename)
if err != nil {
return nil, err
}

View File

@ -18,7 +18,7 @@ package e2e
import (
"fmt"
"io/ioutil"
"os"
"path"
"time"
@ -80,7 +80,7 @@ func gatherTestSuiteMetrics() error {
metricsJSON := metricsForE2E.PrintJSON()
if framework.TestContext.ReportDir != "" {
filePath := path.Join(framework.TestContext.ReportDir, "MetricsForE2ESuite_"+time.Now().Format(time.RFC3339)+".json")
if err := ioutil.WriteFile(filePath, []byte(metricsJSON), 0644); err != nil {
if err := os.WriteFile(filePath, []byte(metricsJSON), 0644); err != nil {
return fmt.Errorf("error writing to %q: %v", filePath, err)
}
} else {

View File

@ -20,7 +20,7 @@ import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"path/filepath"
"sync"
@ -124,7 +124,7 @@ func (t *CassandraUpgradeTest) listUsers() ([]string, error) {
}
defer r.Body.Close()
if r.StatusCode != http.StatusOK {
b, err := ioutil.ReadAll(r.Body)
b, err := io.ReadAll(r.Body)
if err != nil {
return nil, err
}
@ -146,7 +146,7 @@ func (t *CassandraUpgradeTest) addUser(name string) error {
}
defer r.Body.Close()
if r.StatusCode != http.StatusOK {
b, err := ioutil.ReadAll(r.Body)
b, err := io.ReadAll(r.Body)
if err != nil {
return err
}

View File

@ -20,7 +20,7 @@ import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"path/filepath"
"sync"
@ -118,7 +118,7 @@ func (t *EtcdUpgradeTest) listUsers() ([]string, error) {
}
defer r.Body.Close()
if r.StatusCode != http.StatusOK {
b, err := ioutil.ReadAll(r.Body)
b, err := io.ReadAll(r.Body)
if err != nil {
return nil, err
}
@ -139,7 +139,7 @@ func (t *EtcdUpgradeTest) addUser(name string) error {
}
defer r.Body.Close()
if r.StatusCode != http.StatusOK {
b, err := ioutil.ReadAll(r.Body)
b, err := io.ReadAll(r.Body)
if err != nil {
return err
}

View File

@ -20,7 +20,7 @@ import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"path/filepath"
"strconv"
@ -187,7 +187,7 @@ func (t *MySQLUpgradeTest) addName(name string) error {
}
defer r.Body.Close()
if r.StatusCode != http.StatusOK {
b, err := ioutil.ReadAll(r.Body)
b, err := io.ReadAll(r.Body)
if err != nil {
return err
}
@ -205,7 +205,7 @@ func (t *MySQLUpgradeTest) countNames() (int, error) {
}
defer r.Body.Close()
if r.StatusCode != http.StatusOK {
b, err := ioutil.ReadAll(r.Body)
b, err := io.ReadAll(r.Body)
if err != nil {
return 0, err
}

View File

@ -41,7 +41,6 @@ package windows
import (
"context"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path"
@ -245,7 +244,7 @@ func retrieveCRDManifestFileContents(f *framework.Framework, node v1.Node) strin
func deployGmsaWebhook(f *framework.Framework, deployScriptPath string) (func(), error) {
cleanUpFunc := func() {}
tempDir, err := ioutil.TempDir("", "")
tempDir, err := os.MkdirTemp("", "")
if err != nil {
return cleanUpFunc, fmt.Errorf("unable to create temp dir: %w", err)
}
@ -287,7 +286,7 @@ func deployGmsaWebhook(f *framework.Framework, deployScriptPath string) (func(),
func createGmsaCustomResource(ns string, crdManifestContents string) (func(), error) {
cleanUpFunc := func() {}
tempFile, err := ioutil.TempFile("", "")
tempFile, err := os.CreateTemp("", "")
if err != nil {
return cleanUpFunc, fmt.Errorf("unable to create temp file: %w", err)
}

View File

@ -19,8 +19,8 @@ package windows
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
)
// downloadFile saves a remote URL to a local temp file, and returns its path.
@ -32,7 +32,7 @@ func downloadFile(url string) (string, error) {
}
defer response.Body.Close()
tempFile, err := ioutil.TempFile("", "")
tempFile, err := os.CreateTemp("", "")
if err != nil {
return "", fmt.Errorf("unable to create temp file: %w", err)
}

View File

@ -20,7 +20,6 @@ import (
"bytes"
"context"
"fmt"
"io/ioutil"
"os"
"os/exec"
"regexp"
@ -118,7 +117,7 @@ profile e2e-node-apparmor-test-audit-write flags=(attach_disconnected) {
`
func loadTestProfiles() error {
f, err := ioutil.TempFile("/tmp", "apparmor")
f, err := os.CreateTemp("/tmp", "apparmor")
if err != nil {
return fmt.Errorf("failed to open temp file: %v", err)
}

View File

@ -22,7 +22,7 @@ package e2enode
import (
"context"
"fmt"
"io/ioutil"
"os"
"path"
"sort"
"strconv"
@ -51,7 +51,7 @@ func dumpDataToFile(data interface{}, labels map[string]string, prefix string) {
fileName := path.Join(framework.TestContext.ReportDir, fmt.Sprintf("%s-%s-%s.json", prefix, framework.TestContext.ReportPrefix, testName))
labels["timestamp"] = strconv.FormatInt(time.Now().UTC().Unix(), 10)
framework.Logf("Dumping perf data for test %q to %q.", testName, fileName)
if err := ioutil.WriteFile(fileName, []byte(framework.PrettyPrintJSON(data)), 0644); err != nil {
if err := os.WriteFile(fileName, []byte(framework.PrettyPrintJSON(data)), 0644); err != nil {
framework.Logf("Failed to write perf data for test %q to %q: %v", testName, fileName, err)
}
}

View File

@ -19,7 +19,6 @@ package e2enode
import (
"context"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
@ -306,8 +305,8 @@ func rewriteCheckpointAsV1(dir, name string) error {
// TODO: why `checkpointManager.CreateCheckpoint(name, cpV1)` doesn't seem to work?
ckPath := filepath.Join(dir, name)
ioutil.WriteFile(filepath.Join("/tmp", name), blob, 0600)
return ioutil.WriteFile(ckPath, blob, 0600)
os.WriteFile(filepath.Join("/tmp", name), blob, 0600)
return os.WriteFile(ckPath, blob, 0600)
}
func convertPodDeviceEntriesToV1(entries []checkpoint.PodDevicesEntry) []checkpoint.PodDevicesEntryV1 {

View File

@ -27,7 +27,6 @@ import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"math/rand"
"os"
@ -260,7 +259,7 @@ func validateSystem() error {
}
func maskLocksmithdOnCoreos() {
data, err := ioutil.ReadFile("/etc/os-release")
data, err := os.ReadFile("/etc/os-release")
if err != nil {
// Not all distros contain this file.
klog.Infof("Could not read /etc/os-release: %v", err)
@ -350,7 +349,7 @@ func getAPIServerClient() (*clientset.Clientset, error) {
// loadSystemSpecFromFile returns the system spec from the file with the
// filename.
func loadSystemSpecFromFile(filename string) (*system.SysSpec, error) {
b, err := ioutil.ReadFile(filename)
b, err := os.ReadFile(filename)
if err != nil {
return nil, err
}

View File

@ -21,7 +21,6 @@ package main
import (
"flag"
"fmt"
"io/ioutil"
"net"
"os/exec"
"regexp"
@ -146,7 +145,7 @@ const cmdlineCGroupMemory = `cgroup_enable=memory`
// kernel checks that the kernel has been configured correctly to support the required cgroup features
func kernel() error {
cmdline, err := ioutil.ReadFile("/proc/cmdline")
cmdline, err := os.ReadFile("/proc/cmdline")
if err != nil {
return printError("Kernel Command Line Check %s: Could not check /proc/cmdline", failed)
}

View File

@ -19,7 +19,6 @@ package gcp
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"os/exec"
"strconv"
@ -137,7 +136,7 @@ var _ = SIGDescribe("GKE system requirements [NodeConformance][Feature:GKEEnv][N
// getPPID returns the PPID for the pid.
func getPPID(pid int) (int, error) {
statusFile := "/proc/" + strconv.Itoa(pid) + "/status"
content, err := ioutil.ReadFile(statusFile)
content, err := os.ReadFile(statusFile)
if err != nil {
return 0, err
}
@ -183,7 +182,7 @@ func getCmdToProcessMap() (map[string][]process, error) {
if err != nil {
continue
}
content, err := ioutil.ReadFile("/proc/" + dir + "/cmdline")
content, err := os.ReadFile("/proc/" + dir + "/cmdline")
if err != nil || len(content) == 0 {
continue
}

View File

@ -18,7 +18,6 @@ package kubeletconfig
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
@ -49,7 +48,7 @@ func GetCurrentKubeletConfigFromFile() (*kubeletconfig.KubeletConfiguration, err
return nil, err
}
data, err := ioutil.ReadFile(kubeletConfigFilePath)
data, err := os.ReadFile(kubeletConfigFilePath)
if err != nil {
return nil, fmt.Errorf("failed to get the kubelet config from the file %q: %w", kubeletConfigFilePath, err)
}
@ -87,7 +86,7 @@ func WriteKubeletConfigFile(kubeletConfig *kubeletconfig.KubeletConfiguration) e
return err
}
if err := ioutil.WriteFile(kubeletConfigFilePath, data, 0644); err != nil {
if err := os.WriteFile(kubeletConfigFilePath, data, 0644); err != nil {
return fmt.Errorf("failed to write the kubelet file to %q: %w", kubeletConfigFilePath, err)
}

View File

@ -22,7 +22,7 @@ package e2enode
import (
"context"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
@ -73,7 +73,7 @@ var _ = SIGDescribe("Node Container Manager [Serial]", func() {
})
func expectFileValToEqual(filePath string, expectedValue, delta int64) error {
out, err := ioutil.ReadFile(filePath)
out, err := os.ReadFile(filePath)
if err != nil {
return fmt.Errorf("failed to read file %q", filePath)
}

View File

@ -18,7 +18,6 @@ package e2enode
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
@ -78,7 +77,7 @@ func (R *numaPodResources) String() string {
}
func getCPUsPerNUMANode(nodeNum int) ([]int, error) {
nodeCPUList, err := ioutil.ReadFile(fmt.Sprintf("/sys/devices/system/node/node%d/cpulist", nodeNum))
nodeCPUList, err := os.ReadFile(fmt.Sprintf("/sys/devices/system/node/node%d/cpulist", nodeNum))
if err != nil {
return nil, err
}
@ -230,7 +229,7 @@ type pciDeviceInfo struct {
func getPCIDeviceInfo(sysPCIDir string) ([]pciDeviceInfo, error) {
var pciDevs []pciDeviceInfo
entries, err := ioutil.ReadDir(sysPCIDir)
entries, err := os.ReadDir(sysPCIDir)
if err != nil {
return nil, err
}
@ -251,7 +250,7 @@ func getPCIDeviceInfo(sysPCIDir string) ([]pciDeviceInfo, error) {
return nil, err
}
content, err := ioutil.ReadFile(filepath.Join(sysPCIDir, entry.Name(), "numa_node"))
content, err := os.ReadFile(filepath.Join(sysPCIDir, entry.Name(), "numa_node"))
if err != nil {
return nil, err
}

View File

@ -20,7 +20,6 @@ import (
"context"
"errors"
"fmt"
"io/ioutil"
"os"
"strings"
"time"
@ -829,7 +828,7 @@ func requireLackOfSRIOVDevices() {
}
func getOnlineCPUs() (cpuset.CPUSet, error) {
onlineCPUList, err := ioutil.ReadFile("/sys/devices/system/cpu/online")
onlineCPUList, err := os.ReadFile("/sys/devices/system/cpu/online")
if err != nil {
return cpuset.CPUSet{}, err
}

View File

@ -20,7 +20,6 @@ import (
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
@ -71,7 +70,7 @@ func copyKubeletConfigIfExists(kubeletConfigFile, dstDir string) error {
// CreateTestArchive creates the archive package for the node e2e test.
func CreateTestArchive(suite TestSuite, systemSpecName, kubeletConfigFile string) (string, error) {
klog.V(2).Infof("Building archive...")
tardir, err := ioutil.TempDir("", "node-e2e-archive")
tardir, err := os.MkdirTemp("", "node-e2e-archive")
if err != nil {
return "", fmt.Errorf("failed to create temporary directory %v", err)
}

View File

@ -23,7 +23,7 @@ import (
"bytes"
"context"
"fmt"
"io/ioutil"
"io"
"log"
"os"
"sort"
@ -486,7 +486,7 @@ func getPidFromPidFile(pidFile string) (int, error) {
}
defer file.Close()
data, err := ioutil.ReadAll(file)
data, err := io.ReadAll(file)
if err != nil {
return 0, fmt.Errorf("error reading pid file %s: %v", pidFile, err)
}

View File

@ -24,7 +24,6 @@ import (
"context"
"flag"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"os"
@ -323,7 +322,7 @@ func prepareGceImages() (*internalImageConfig, error) {
configPath = filepath.Join(*imageConfigDir, *imageConfigFile)
}
imageConfigData, err := ioutil.ReadFile(configPath)
imageConfigData, err := os.ReadFile(configPath)
if err != nil {
return nil, fmt.Errorf("Could not read image config file provided: %v", err)
}
@ -895,7 +894,7 @@ func parseInstanceMetadata(str string) map[string]string {
if *imageConfigDir != "" {
metaPath = filepath.Join(*imageConfigDir, metaPath)
}
v, err := ioutil.ReadFile(metaPath)
v, err := os.ReadFile(metaPath)
if err != nil {
klog.Fatalf("Failed to read metadata file %q: %v", metaPath, err)
continue

View File

@ -18,7 +18,6 @@ package e2enode
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"time"
@ -81,7 +80,7 @@ var _ = SIGDescribe("Container Runtime Conformance Test", func() {
}
configFile := filepath.Join(services.KubeletRootDirectory, "config.json")
err := ioutil.WriteFile(configFile, []byte(auth), 0644)
err := os.WriteFile(configFile, []byte(auth), 0644)
framework.ExpectNoError(err)
defer os.Remove(configFile)

View File

@ -18,7 +18,6 @@ package services
import (
"fmt"
"io/ioutil"
"os"
"k8s.io/apiserver/pkg/storage/storagebackend"
@ -76,12 +75,12 @@ func (a *APIServer) Start() error {
o.Authentication.TokenFile.TokenFile = tokenFilePath
o.Admission.GenericAdmission.DisablePlugins = []string{"ServiceAccount", "TaintNodesByCondition"}
saSigningKeyFile, err := ioutil.TempFile("/tmp", "insecure_test_key")
saSigningKeyFile, err := os.CreateTemp("/tmp", "insecure_test_key")
if err != nil {
return fmt.Errorf("create temp file failed: %v", err)
}
defer os.RemoveAll(saSigningKeyFile.Name())
if err = ioutil.WriteFile(saSigningKeyFile.Name(), []byte(ecdsaPrivateKey), 0666); err != nil {
if err = os.WriteFile(saSigningKeyFile.Name(), []byte(ecdsaPrivateKey), 0666); err != nil {
return fmt.Errorf("write file %s failed: %v", saSigningKeyFile.Name(), err)
}
o.ServiceAccountSigningKeyFile = saSigningKeyFile.Name()
@ -143,5 +142,5 @@ func getAPIServerHealthCheckURL() string {
func generateTokenFile(tokenFilePath string) error {
tokenFile := fmt.Sprintf("%s,kubelet,uid,system:masters\n", framework.TestContext.BearerToken)
return ioutil.WriteFile(tokenFilePath, []byte(tokenFile), 0644)
return os.WriteFile(tokenFilePath, []byte(tokenFile), 0644)
}

View File

@ -19,7 +19,6 @@ package services
import (
"flag"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
@ -327,7 +326,7 @@ func writeKubeletConfigFile(internal *kubeletconfig.KubeletConfiguration, path s
return err
}
// write the file
if err := ioutil.WriteFile(path, data, 0755); err != nil {
if err := os.WriteFile(path, data, 0755); err != nil {
return err
}
return nil
@ -339,7 +338,7 @@ func createPodDirectory() (string, error) {
if err != nil {
return "", fmt.Errorf("failed to get current working directory: %v", err)
}
path, err := ioutil.TempDir(cwd, "static-pods")
path, err := os.MkdirTemp(cwd, "static-pods")
if err != nil {
return "", fmt.Errorf("failed to create static pod directory: %v", err)
}
@ -366,7 +365,7 @@ contexts:
name: local-context
current-context: local-context`, framework.TestContext.BearerToken, getAPIServerClientURL()))
if err := ioutil.WriteFile(path, kubeconfig, 0666); err != nil {
if err := os.WriteFile(path, kubeconfig, 0666); err != nil {
return err
}
return nil

View File

@ -18,7 +18,6 @@ package services
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"path"
@ -167,7 +166,7 @@ func (e *E2EServices) collectLogFiles() {
if err != nil {
klog.Errorf("failed to get %q from journald: %v, %v", targetFileName, string(out), err)
} else {
if err = ioutil.WriteFile(targetLink, out, 0644); err != nil {
if err = os.WriteFile(targetLink, out, 0644); err != nil {
klog.Errorf("failed to write logs to %q: %v", targetLink, err)
}
}

View File

@ -18,7 +18,7 @@ package e2enode
import (
"fmt"
"io/ioutil"
"os"
"strings"
"time"
@ -434,7 +434,7 @@ func recordSystemCgroupProcesses() {
if IsCgroup2UnifiedMode() {
filePattern = "/sys/fs/cgroup/%s/cgroup.procs"
}
pids, err := ioutil.ReadFile(fmt.Sprintf(filePattern, cgroup))
pids, err := os.ReadFile(fmt.Sprintf(filePattern, cgroup))
if err != nil {
framework.Logf("Failed to read processes in cgroup %s: %v", name, err)
continue
@ -443,7 +443,7 @@ func recordSystemCgroupProcesses() {
framework.Logf("Processes in %s cgroup (%s):", name, cgroup)
for _, pid := range strings.Fields(string(pids)) {
path := fmt.Sprintf("/proc/%s/cmdline", pid)
cmd, err := ioutil.ReadFile(path)
cmd, err := os.ReadFile(path)
if err != nil {
framework.Logf(" ginkgo.Failed to read %s: %v", path, err)
} else {

View File

@ -19,7 +19,7 @@ package e2enode
import (
"context"
"fmt"
"io/ioutil"
"os"
"os/exec"
"regexp"
"strconv"
@ -478,7 +478,7 @@ func getSRIOVDevicePluginConfigMap(cmFile string) *v1.ConfigMap {
// the SRIOVDP configuration is hw-dependent, so we allow per-test-host customization.
framework.Logf("host-local SRIOV Device Plugin Config Map %q", cmFile)
if cmFile != "" {
data, err = ioutil.ReadFile(cmFile)
data, err = os.ReadFile(cmFile)
if err != nil {
framework.Failf("unable to load the SRIOV Device Plugin ConfigMap: %v", err)
}

View File

@ -22,7 +22,7 @@ import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"io"
"net/http"
"os/exec"
"regexp"
@ -95,7 +95,7 @@ func getNodeSummary() (*stats.Summary, error) {
}
defer resp.Body.Close()
contentsBytes, err := ioutil.ReadAll(resp.Body)
contentsBytes, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read /stats/summary: %+v", resp)
}

View File

@ -23,7 +23,6 @@ import (
"go/ast"
"go/parser"
"go/token"
"io/ioutil"
"os"
"path/filepath"
"sort"
@ -237,7 +236,7 @@ func importedGlobalVariableDeclaration(localVariables map[string]ast.Expr, impor
continue
}
files, err := ioutil.ReadDir(importDirectory)
files, err := os.ReadDir(importDirectory)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to read import path directory %s with error %s, skipping\n", importDirectory, err)
continue

View File

@ -22,7 +22,7 @@ import (
"crypto/x509"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"path"
@ -1262,7 +1262,7 @@ func testNoPruningCustomFancy(c *testContext) {
func newV1beta1WebhookHandler(t *testing.T, holder *holder, phase string, converted bool) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
data, err := ioutil.ReadAll(r.Body)
data, err := io.ReadAll(r.Body)
if err != nil {
t.Error(err)
return
@ -1360,7 +1360,7 @@ func newV1beta1WebhookHandler(t *testing.T, holder *holder, phase string, conver
func newV1WebhookHandler(t *testing.T, holder *holder, phase string, converted bool) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
data, err := ioutil.ReadAll(r.Body)
data, err := io.ReadAll(r.Body)
if err != nil {
t.Error(err)
return

View File

@ -22,7 +22,7 @@ import (
"crypto/x509"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"net/url"
@ -84,13 +84,13 @@ func testWebhookClientAuth(t *testing.T, enableAggregatorRouting bool) {
t.Fatal(err)
}
kubeConfigFile, err := ioutil.TempFile("", "admission-config.yaml")
kubeConfigFile, err := os.CreateTemp("", "admission-config.yaml")
if err != nil {
t.Fatal(err)
}
defer os.Remove(kubeConfigFile.Name())
if err := ioutil.WriteFile(kubeConfigFile.Name(), []byte(`
if err := os.WriteFile(kubeConfigFile.Name(), []byte(`
apiVersion: v1
kind: Config
users:
@ -110,13 +110,13 @@ users:
t.Fatal(err)
}
admissionConfigFile, err := ioutil.TempFile("", "admission-config.yaml")
admissionConfigFile, err := os.CreateTemp("", "admission-config.yaml")
if err != nil {
t.Fatal(err)
}
defer os.Remove(admissionConfigFile.Name())
if err := ioutil.WriteFile(admissionConfigFile.Name(), []byte(`
if err := os.WriteFile(admissionConfigFile.Name(), []byte(`
apiVersion: apiserver.k8s.io/v1alpha1
kind: AdmissionConfiguration
plugins:
@ -247,7 +247,7 @@ func newClientAuthWebhookHandler(t *testing.T, recorder *clientAuthRecorder) htt
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
data, err := ioutil.ReadAll(r.Body)
data, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}

View File

@ -23,7 +23,7 @@ import (
"crypto/x509"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"strings"
@ -176,7 +176,7 @@ func TestMutatingWebhookDuplicateOwnerReferences(t *testing.T) {
func newDuplicateOwnerReferencesWebhookHandler(t *testing.T) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
data, err := ioutil.ReadAll(r.Body)
data, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}

View File

@ -23,7 +23,7 @@ import (
"crypto/x509"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"strings"
@ -179,7 +179,7 @@ func validateManagedFieldsAndDecode(managedFields []metav1.ManagedFieldsEntry) e
func newInvalidManagedFieldsWebhookHandler(t *testing.T) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
data, err := ioutil.ReadAll(r.Body)
data, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}

View File

@ -22,7 +22,7 @@ import (
"crypto/x509"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net"
"net/http"
"sync"
@ -245,7 +245,7 @@ func newLoadBalanceWebhookHandler(recorder *connectionRecorder) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.Proto)
defer r.Body.Close()
data, err := ioutil.ReadAll(r.Body)
data, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), 400)
}

View File

@ -22,7 +22,7 @@ import (
"crypto/x509"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"os"
@ -265,7 +265,7 @@ func testWebhookReinvocationPolicy(t *testing.T, watchCache bool) {
defer webhookServer.Close()
// prepare audit policy file
policyFile, err := ioutil.TempFile("", "audit-policy.yaml")
policyFile, err := os.CreateTemp("", "audit-policy.yaml")
if err != nil {
t.Fatalf("Failed to create audit policy file: %v", err)
}
@ -278,7 +278,7 @@ func testWebhookReinvocationPolicy(t *testing.T, watchCache bool) {
}
// prepare audit log file
logFile, err := ioutil.TempFile("", "audit.log")
logFile, err := os.CreateTemp("", "audit.log")
if err != nil {
t.Fatalf("Failed to create audit log file: %v", err)
}
@ -536,7 +536,7 @@ func newReinvokeWebhookHandler(recorder *invocationRecorder) http.Handler {
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
data, err := ioutil.ReadAll(r.Body)
data, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), 400)
}

View File

@ -22,7 +22,7 @@ import (
"crypto/x509"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"sort"
@ -413,7 +413,7 @@ func newTimeoutWebhookHandler(recorder *timeoutRecorder) http.Handler {
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
data, err := ioutil.ReadAll(r.Body)
data, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), 400)
}

View File

@ -22,7 +22,6 @@ import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/http/httptest"
@ -117,7 +116,7 @@ func verifyStatusCode(t *testing.T, verb, URL, body string, expectedStatusCode i
t.Fatalf("unexpected error: %v in req: %v", err, req)
}
defer resp.Body.Close()
b, _ := ioutil.ReadAll(resp.Body)
b, _ := io.ReadAll(resp.Body)
if resp.StatusCode != expectedStatusCode {
t.Errorf("Expected status %v, but got %v", expectedStatusCode, resp.StatusCode)
t.Errorf("Body: %v", string(b))
@ -2070,7 +2069,7 @@ func expectPartialObjectMetaEventsProtobuf(t *testing.T, r io.Reader, values ...
metav1.AddToGroupVersion(scheme, schema.GroupVersion{Version: "v1"})
rs := protobuf.NewRawSerializer(scheme, scheme)
d := streaming.NewDecoder(
protobuf.LengthDelimitedFramer.NewFrameReader(ioutil.NopCloser(r)),
protobuf.LengthDelimitedFramer.NewFrameReader(io.NopCloser(r)),
rs,
)
ds := metainternalversionscheme.Codecs.UniversalDeserializer()
@ -2179,7 +2178,7 @@ func expectPartialObjectMetaV1EventsProtobuf(t *testing.T, r io.Reader, values .
metav1.AddToGroupVersion(scheme, schema.GroupVersion{Version: "v1"})
rs := protobuf.NewRawSerializer(scheme, scheme)
d := streaming.NewDecoder(
protobuf.LengthDelimitedFramer.NewFrameReader(ioutil.NopCloser(r)),
protobuf.LengthDelimitedFramer.NewFrameReader(io.NopCloser(r)),
rs,
)
ds := metainternalversionscheme.Codecs.UniversalDeserializer()

View File

@ -25,7 +25,6 @@ import (
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"io/ioutil"
"math/big"
"os"
"path"
@ -204,10 +203,10 @@ func testClientCA(t *testing.T, recreate bool) {
}
// when we run this the second time, we know which one we are expecting
if err := ioutil.WriteFile(clientCAFilename, clientCA.CACert, 0644); err != nil {
if err := os.WriteFile(clientCAFilename, clientCA.CACert, 0644); err != nil {
t.Fatal(err)
}
if err := ioutil.WriteFile(frontProxyCAFilename, frontProxyCA.CACert, 0644); err != nil {
if err := os.WriteFile(frontProxyCAFilename, frontProxyCA.CACert, 0644); err != nil {
t.Fatal(err)
}
@ -492,10 +491,10 @@ func testServingCert(t *testing.T, recreate bool) {
}
}
if err := ioutil.WriteFile(path.Join(servingCertPath, "apiserver.key"), serverKey, 0644); err != nil {
if err := os.WriteFile(path.Join(servingCertPath, "apiserver.key"), serverKey, 0644); err != nil {
t.Fatal(err)
}
if err := ioutil.WriteFile(path.Join(servingCertPath, "apiserver.crt"), serverCert, 0644); err != nil {
if err := os.WriteFile(path.Join(servingCertPath, "apiserver.crt"), serverCert, 0644); err != nil {
t.Fatal(err)
}
@ -522,10 +521,10 @@ func TestSNICert(t *testing.T) {
opts.GenericServerRunOptions.MaxRequestBodyBytes = 1024 * 1024
servingCertPath = opts.SecureServing.ServerCert.CertDirectory
if err := ioutil.WriteFile(path.Join(servingCertPath, "foo.key"), anotherServerKey, 0644); err != nil {
if err := os.WriteFile(path.Join(servingCertPath, "foo.key"), anotherServerKey, 0644); err != nil {
t.Fatal(err)
}
if err := ioutil.WriteFile(path.Join(servingCertPath, "foo.crt"), anotherServerCert, 0644); err != nil {
if err := os.WriteFile(path.Join(servingCertPath, "foo.crt"), anotherServerCert, 0644); err != nil {
t.Fatal(err)
}
@ -546,10 +545,10 @@ func TestSNICert(t *testing.T) {
t.Fatal(err)
}
if err := ioutil.WriteFile(path.Join(servingCertPath, "foo.key"), serverKey, 0644); err != nil {
if err := os.WriteFile(path.Join(servingCertPath, "foo.key"), serverKey, 0644); err != nil {
t.Fatal(err)
}
if err := ioutil.WriteFile(path.Join(servingCertPath, "foo.crt"), serverCert, 0644); err != nil {
if err := os.WriteFile(path.Join(servingCertPath, "foo.crt"), serverCert, 0644); err != nil {
t.Fatal(err)
}

View File

@ -19,7 +19,7 @@ package apiserver
import (
"context"
"encoding/json"
"io/ioutil"
"io"
"net/http"
"reflect"
"strings"
@ -73,7 +73,7 @@ func TestOpenAPIV3SpecRoundTrip(t *testing.T) {
t.Fatal(err)
}
defer resp.Body.Close()
bs, err := ioutil.ReadAll(resp.Body)
bs, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
@ -217,7 +217,7 @@ func TestOpenAPIV3ProtoRoundtrip(t *testing.T) {
t.Fatal(err)
}
defer resp.Body.Close()
bs, err := ioutil.ReadAll(resp.Body)
bs, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
@ -237,7 +237,7 @@ func TestOpenAPIV3ProtoRoundtrip(t *testing.T) {
t.Fatal(err)
}
defer protoResp.Body.Close()
bs, err = ioutil.ReadAll(protoResp.Body)
bs, err = io.ReadAll(protoResp.Body)
if err != nil {
t.Fatal(err)
}

View File

@ -20,7 +20,6 @@ import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"reflect"
"strings"
@ -162,7 +161,7 @@ func TestServerSidePrint(t *testing.T) {
t.Errorf("unexpected error: %v", err)
}
cacheDir, err := ioutil.TempDir(os.TempDir(), "test-integration-apiserver-print")
cacheDir, err := os.MkdirTemp(os.TempDir(), "test-integration-apiserver-print")
if err != nil {
t.Errorf("unexpected error: %v", err)
}

View File

@ -19,7 +19,6 @@ package tracing
import (
"context"
"fmt"
"io/ioutil"
"net"
"os"
"testing"
@ -61,13 +60,13 @@ func TestAPIServerTracing(t *testing.T) {
defer srv.Stop()
// Write the configuration for tracing to a file
tracingConfigFile, err := ioutil.TempFile("", "tracing-config.yaml")
tracingConfigFile, err := os.CreateTemp("", "tracing-config.yaml")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tracingConfigFile.Name())
if err := ioutil.WriteFile(tracingConfigFile.Name(), []byte(fmt.Sprintf(`
if err := os.WriteFile(tracingConfigFile.Name(), []byte(fmt.Sprintf(`
apiVersion: apiserver.config.k8s.io/v1alpha1
kind: TracingConfiguration
endpoint: %s`, listener.Addr().String())), os.FileMode(0755)); err != nil {

View File

@ -30,7 +30,7 @@ import (
"encoding/json"
"encoding/pem"
"fmt"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"net/url"
@ -87,7 +87,7 @@ func getTestTokenAuth() authenticator.Request {
}
func getTestWebhookTokenAuth(serverURL string, customDial utilnet.DialFunc) (authenticator.Request, error) {
kubecfgFile, err := ioutil.TempFile("", "webhook-kubecfg")
kubecfgFile, err := os.CreateTemp("", "webhook-kubecfg")
if err != nil {
return nil, err
}
@ -495,7 +495,7 @@ func TestAuthModeAlwaysAllow(t *testing.T) {
t.Fatalf("unexpected error: %v", err)
}
defer resp.Body.Close()
b, _ := ioutil.ReadAll(resp.Body)
b, _ := io.ReadAll(resp.Body)
if _, ok := r.statusCodes[resp.StatusCode]; !ok {
t.Logf("case %v", r)
t.Errorf("Expected status one of %v, but got %v", r.statusCodes, resp.StatusCode)
@ -643,7 +643,7 @@ func TestAliceNotForbiddenOrUnauthorized(t *testing.T) {
t.Fatalf("unexpected error: %v", err)
}
defer resp.Body.Close()
b, _ := ioutil.ReadAll(resp.Body)
b, _ := io.ReadAll(resp.Body)
if _, ok := r.statusCodes[resp.StatusCode]; !ok {
t.Logf("case %v", r)
t.Errorf("Expected status one of %v, but got %v", r.statusCodes, resp.StatusCode)
@ -742,7 +742,7 @@ func TestUnknownUserIsUnauthorized(t *testing.T) {
if resp.StatusCode != http.StatusUnauthorized {
t.Logf("case %v", r)
t.Errorf("Expected status %v, but got %v", http.StatusUnauthorized, resp.StatusCode)
b, _ := ioutil.ReadAll(resp.Body)
b, _ := io.ReadAll(resp.Body)
t.Errorf("Body: %v", string(b))
}
}()
@ -1047,14 +1047,14 @@ func csrPEM(t *testing.T) []byte {
}
func newAuthorizerWithContents(t *testing.T, contents string) authorizer.Authorizer {
f, err := ioutil.TempFile("", "auth_test")
f, err := os.CreateTemp("", "auth_test")
if err != nil {
t.Fatalf("unexpected error creating policyfile: %v", err)
}
f.Close()
defer os.Remove(f.Name())
if err := ioutil.WriteFile(f.Name(), []byte(contents), 0700); err != nil {
if err := os.WriteFile(f.Name(), []byte(contents), 0700); err != nil {
t.Fatalf("unexpected error writing policyfile: %v", err)
}
@ -1215,7 +1215,7 @@ func TestNamespaceAuthorization(t *testing.T) {
t.Fatalf("unexpected error: %v", err)
}
defer resp.Body.Close()
b, _ := ioutil.ReadAll(resp.Body)
b, _ := io.ReadAll(resp.Body)
if _, ok := r.statusCodes[resp.StatusCode]; !ok {
t.Logf("case %v", r)
t.Errorf("Expected status one of %v, but got %v", r.statusCodes, resp.StatusCode)
@ -1300,7 +1300,7 @@ func TestKindAuthorization(t *testing.T) {
t.Fatalf("unexpected error: %v", err)
}
defer resp.Body.Close()
b, _ := ioutil.ReadAll(resp.Body)
b, _ := io.ReadAll(resp.Body)
if _, ok := r.statusCodes[resp.StatusCode]; !ok {
t.Logf("case %v", r)
t.Errorf("Expected status one of %v, but got %v", r.statusCodes, resp.StatusCode)
@ -1367,7 +1367,7 @@ func TestReadOnlyAuthorization(t *testing.T) {
if _, ok := r.statusCodes[resp.StatusCode]; !ok {
t.Logf("case %v", r)
t.Errorf("Expected status one of %v, but got %v", r.statusCodes, resp.StatusCode)
b, _ := ioutil.ReadAll(resp.Body)
b, _ := io.ReadAll(resp.Body)
t.Errorf("Body: %v", string(b))
}
}()

View File

@ -19,7 +19,7 @@ package auth
import (
"bytes"
"fmt"
"io/ioutil"
"io"
"net/http"
"testing"
"time"
@ -160,7 +160,7 @@ func TestBootstrapTokenAuth(t *testing.T) {
t.Fatalf("unexpected error: %v", err)
}
defer resp.Body.Close()
b, _ := ioutil.ReadAll(resp.Body)
b, _ := io.ReadAll(resp.Body)
if _, ok := test.request.statusCodes[resp.StatusCode]; !ok {
t.Logf("case %v", test.name)
t.Errorf("Expected status one of %v, but got %v", test.request.statusCodes, resp.StatusCode)

View File

@ -18,7 +18,6 @@ package auth
import (
"context"
"io/ioutil"
"os"
"testing"
"time"
@ -36,13 +35,13 @@ import (
)
func TestDynamicClientBuilder(t *testing.T) {
tmpfile, err := ioutil.TempFile("/tmp", "key")
tmpfile, err := os.CreateTemp("/tmp", "key")
if err != nil {
t.Fatalf("create temp file failed: %v", err)
}
defer os.RemoveAll(tmpfile.Name())
if err = ioutil.WriteFile(tmpfile.Name(), []byte(ecdsaPrivateKey), 0666); err != nil {
if err = os.WriteFile(tmpfile.Name(), []byte(ecdsaPrivateKey), 0666); err != nil {
t.Fatalf("write file %s failed: %v", tmpfile.Name(), err)
}

View File

@ -19,7 +19,7 @@ package auth
import (
"context"
"fmt"
"io/ioutil"
"os"
"strings"
"testing"
"time"
@ -55,7 +55,7 @@ func TestNodeAuthorizer(t *testing.T) {
// Enable DynamicKubeletConfig feature so that Node.Spec.ConfigSource can be set
defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.DynamicKubeletConfig, true)()
tokenFile, err := ioutil.TempFile("", "kubeconfig")
tokenFile, err := os.CreateTemp("", "kubeconfig")
if err != nil {
t.Fatal(err)
}

View File

@ -20,7 +20,7 @@ import (
"context"
"crypto/tls"
"fmt"
"io/ioutil"
"io"
"net"
"net/http"
"net/url"
@ -325,7 +325,7 @@ func ValidateWebhookMetrics(t *testing.T, webhookAddr string) {
if resp.StatusCode != http.StatusOK {
t.Fatalf("Non-200 response trying to scrape metrics from %s: %v", endpoint.String(), resp)
}
data, err := ioutil.ReadAll(resp.Body)
data, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Unable to read metrics response: %v", err)
}

View File

@ -20,7 +20,6 @@ import (
"context"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httputil"
gopath "path"
@ -623,7 +622,7 @@ func TestRBAC(t *testing.T) {
t.Errorf("case %d, req %d: %s expected %q got %q", i, j, r, statusCode(r.expectedStatus), statusCode(resp.StatusCode))
}
b, _ := ioutil.ReadAll(resp.Body)
b, _ := io.ReadAll(resp.Body)
if r.verb == "POST" && (resp.StatusCode/100) == 2 {
// For successful create operations, extract resourceVersion

View File

@ -23,7 +23,7 @@ import (
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"net/url"
"reflect"
@ -740,7 +740,7 @@ func TestServiceAccountTokenCreate(t *testing.T) {
t.Errorf("got Cache-Control: %v, want: %v", got, want)
}
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
@ -793,7 +793,7 @@ func TestServiceAccountTokenCreate(t *testing.T) {
t.Errorf("got Cache-Control: %v, want: %v", got, want)
}
b, err = ioutil.ReadAll(resp.Body)
b, err = io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}

View File

@ -20,7 +20,6 @@ import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"os"
benchparse "golang.org/x/tools/benchmark/parse"
@ -87,7 +86,7 @@ func run() error {
if err := json.Indent(formatted, output.Bytes(), "", " "); err != nil {
return err
}
return ioutil.WriteFile(os.Args[1], formatted.Bytes(), 0664)
return os.WriteFile(os.Args[1], formatted.Bytes(), 0664)
}
func appendIfMeasured(items []DataItem, benchmark *benchparse.Benchmark, metricType int, metricName string, unit string, value float64) []DataItem {

View File

@ -23,7 +23,6 @@ import (
"crypto/rand"
"crypto/x509/pkix"
"encoding/pem"
"io/ioutil"
"os"
"path"
"strings"
@ -99,7 +98,7 @@ func TestCSRDuration(t *testing.T) {
t.Fatal(err)
}
caPublicKeyFile := path.Join(s.TmpDir, "test-ca-public-key")
if err := ioutil.WriteFile(caPublicKeyFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caCert.Raw}), os.FileMode(0600)); err != nil {
if err := os.WriteFile(caPublicKeyFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caCert.Raw}), os.FileMode(0600)); err != nil {
t.Fatal(err)
}
caPrivateKeyBytes, err := keyutil.MarshalPrivateKeyToPEM(caPrivateKey)
@ -107,7 +106,7 @@ func TestCSRDuration(t *testing.T) {
t.Fatal(err)
}
caPrivateKeyFile := path.Join(s.TmpDir, "test-ca-private-key")
if err := ioutil.WriteFile(caPrivateKeyFile, caPrivateKeyBytes, os.FileMode(0600)); err != nil {
if err := os.WriteFile(caPrivateKeyFile, caPrivateKeyBytes, os.FileMode(0600)); err != nil {
t.Fatal(err)
}

View File

@ -23,7 +23,6 @@ import (
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"io/ioutil"
"math"
"math/big"
"os"
@ -157,7 +156,7 @@ func writeCACertFiles(t *testing.T, certDir string) (string, *x509.Certificate,
clientCAFilename := path.Join(certDir, "ca.crt")
if err := ioutil.WriteFile(clientCAFilename, utils.EncodeCertPEM(clientSigningCert), 0644); err != nil {
if err := os.WriteFile(clientCAFilename, utils.EncodeCertPEM(clientSigningCert), 0644); err != nil {
t.Fatal(err)
}
@ -175,7 +174,7 @@ func writeCerts(t *testing.T, clientSigningCert *x509.Certificate, clientSigning
t.Fatal(err)
}
if err := ioutil.WriteFile(path.Join(certDir, "client.key"), pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}), 0666); err != nil {
if err := os.WriteFile(path.Join(certDir, "client.key"), pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}), 0666); err != nil {
t.Fatal(err)
}
@ -201,7 +200,7 @@ func writeCerts(t *testing.T, clientSigningCert *x509.Certificate, clientSigning
t.Fatal(err)
}
if err := ioutil.WriteFile(path.Join(certDir, "client.crt"), pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDERBytes}), 0666); err != nil {
if err := os.WriteFile(path.Join(certDir, "client.crt"), pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDERBytes}), 0666); err != nil {
t.Fatal(err)
}

View File

@ -23,7 +23,6 @@ import (
"encoding/base64"
"errors"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
@ -700,7 +699,7 @@ type execPlugin struct {
func newExecPlugin(t *testing.T) *execPlugin {
t.Helper()
outputFile, err := ioutil.TempFile("", "kubernetes-client-exec-test-plugin-output-file-*")
outputFile, err := os.CreateTemp("", "kubernetes-client-exec-test-plugin-output-file-*")
if err != nil {
t.Fatal(err)
}
@ -806,7 +805,7 @@ func TestExecPluginRotationViaInformer(t *testing.T) {
}
func startTestServer(t *testing.T) (result *kubeapiservertesting.TestServer, clientAuthorizedToken string, clientCertFileName string, clientKeyFileName string) {
certDir, err := ioutil.TempDir("", "kubernetes-client-exec-test-cert-dir-*")
certDir, err := os.MkdirTemp("", "kubernetes-client-exec-test-cert-dir-*")
if err != nil {
t.Fatal(err)
}
@ -837,7 +836,7 @@ func startTestServer(t *testing.T) (result *kubeapiservertesting.TestServer, cli
func writeTokenFile(t *testing.T, goodToken string) string {
t.Helper()
tokenFile, err := ioutil.TempFile("", "kubernetes-client-exec-test-token-file-*")
tokenFile, err := os.CreateTemp("", "kubernetes-client-exec-test-token-file-*")
if err != nil {
t.Fatal(err)
}
@ -855,7 +854,7 @@ func writeTokenFile(t *testing.T, goodToken string) string {
func read(t *testing.T, fileName string) string {
t.Helper()
data, err := ioutil.ReadFile(fileName)
data, err := os.ReadFile(fileName)
if err != nil {
t.Fatal(err)
}

View File

@ -20,7 +20,6 @@ import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
@ -232,7 +231,7 @@ func runTestWithVersion(t *testing.T, version string) {
// prepare audit policy file
auditPolicy := strings.Replace(auditPolicyPattern, "{version}", version, 1)
policyFile, err := ioutil.TempFile("", "audit-policy.yaml")
policyFile, err := os.CreateTemp("", "audit-policy.yaml")
if err != nil {
t.Fatalf("Failed to create audit policy file: %v", err)
}
@ -245,7 +244,7 @@ func runTestWithVersion(t *testing.T, version string) {
}
// prepare audit log file
logFile, err := ioutil.TempFile("", "audit.log")
logFile, err := os.CreateTemp("", "audit.log")
if err != nil {
t.Fatalf("Failed to create audit log file: %v", err)
}

View File

@ -18,7 +18,6 @@ package controlplane
import (
"io"
"io/ioutil"
"net/http"
"sync"
"testing"
@ -55,7 +54,7 @@ func TestGracefulShutdown(t *testing.T) {
if respErr.err != nil {
t.Fatalf("unexpected error: %v", err)
}
bs, err := ioutil.ReadAll(respErr.resp.Body)
bs, err := io.ReadAll(respErr.resp.Body)
if err != nil {
t.Fatal(err)
}
@ -96,7 +95,7 @@ func TestGracefulShutdown(t *testing.T) {
t.Fatal(respErr.err)
}
defer respErr.resp.Body.Close()
bs, err := ioutil.ReadAll(respErr.resp.Body)
bs, err := io.ReadAll(respErr.resp.Body)
if err != nil {
t.Fatal(err)
}

View File

@ -21,7 +21,7 @@ import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"os"
"path"
@ -126,7 +126,7 @@ func TestEmptyList(t *testing.T) {
t.Fatalf("got status %v instead of 200 OK", resp.StatusCode)
}
defer resp.Body.Close()
data, _ := ioutil.ReadAll(resp.Body)
data, _ := io.ReadAll(resp.Body)
decodedData := map[string]interface{}{}
if err := json.Unmarshal(data, &decodedData); err != nil {
t.Logf("body: %s", string(data))
@ -214,7 +214,7 @@ func TestStatus(t *testing.T) {
t.Fatalf("got status %v instead of %s", resp.StatusCode, tc.name)
}
defer resp.Body.Close()
data, _ := ioutil.ReadAll(resp.Body)
data, _ := io.ReadAll(resp.Body)
decodedData := map[string]interface{}{}
if err := json.Unmarshal(data, &decodedData); err != nil {
t.Logf("body: %s", string(data))
@ -470,7 +470,7 @@ func TestAutoscalingGroupBackwardCompatibility(t *testing.T) {
t.Fatalf("unexpected error: %v", err)
}
defer resp.Body.Close()
b, _ := ioutil.ReadAll(resp.Body)
b, _ := io.ReadAll(resp.Body)
body := string(b)
if _, ok := r.expectedStatusCodes[resp.StatusCode]; !ok {
t.Logf("case %v", r)
@ -518,7 +518,7 @@ func TestAppsGroupBackwardCompatibility(t *testing.T) {
t.Fatalf("unexpected error: %v", err)
}
defer resp.Body.Close()
b, _ := ioutil.ReadAll(resp.Body)
b, _ := io.ReadAll(resp.Body)
body := string(b)
if _, ok := r.expectedStatusCodes[resp.StatusCode]; !ok {
t.Logf("case %v", r)
@ -545,7 +545,7 @@ func TestAccept(t *testing.T) {
t.Fatalf("got status %v instead of 200 OK", resp.StatusCode)
}
body, _ := ioutil.ReadAll(resp.Body)
body, _ := io.ReadAll(resp.Body)
if resp.Header.Get("Content-Type") != "application/json" {
t.Errorf("unexpected content: %s", body)
}
@ -562,7 +562,7 @@ func TestAccept(t *testing.T) {
if err != nil {
t.Fatal(err)
}
body, _ = ioutil.ReadAll(resp.Body)
body, _ = io.ReadAll(resp.Body)
if resp.Header.Get("Content-Type") != "application/yaml" {
t.Errorf("unexpected content: %s", body)
}
@ -580,7 +580,7 @@ func TestAccept(t *testing.T) {
if err != nil {
t.Fatal(err)
}
body, _ = ioutil.ReadAll(resp.Body)
body, _ = io.ReadAll(resp.Body)
if resp.Header.Get("Content-Type") != "application/json" {
t.Errorf("unexpected content: %s", body)
}

View File

@ -20,7 +20,6 @@ import (
"bytes"
"context"
"fmt"
"io/ioutil"
"os"
"path"
"strconv"
@ -173,14 +172,14 @@ func (e *transformTest) getEncryptionOptions() []string {
}
func (e *transformTest) createEncryptionConfig() (string, error) {
tempDir, err := ioutil.TempDir("", "secrets-encryption-test")
tempDir, err := os.MkdirTemp("", "secrets-encryption-test")
if err != nil {
return "", fmt.Errorf("failed to create temp directory: %v", err)
}
encryptionConfig := path.Join(tempDir, encryptionConfigFileName)
if err := ioutil.WriteFile(encryptionConfig, []byte(e.transformerConfig), 0644); err != nil {
if err := os.WriteFile(encryptionConfig, []byte(e.transformerConfig), 0644); err != nil {
os.RemoveAll(tempDir)
return "", fmt.Errorf("error while writing encryption config: %v", err)
}

View File

@ -19,7 +19,6 @@ package etcd
import (
"context"
"encoding/json"
"io/ioutil"
"net"
"net/http"
"os"
@ -64,7 +63,7 @@ AwEHoUQDQgAEH6cuzP8XuD5wal6wf9M6xDljTOPLX2i8uIp/C/ASqiIGUeeKQtX0
// StartRealAPIServerOrDie starts an API server that is appropriate for use in tests that require one of every resource
func StartRealAPIServerOrDie(t *testing.T, configFuncs ...func(*options.ServerRunOptions)) *APIServer {
certDir, err := ioutil.TempDir("", t.Name())
certDir, err := os.MkdirTemp("", t.Name())
if err != nil {
t.Fatal(err)
}
@ -79,12 +78,12 @@ func StartRealAPIServerOrDie(t *testing.T, configFuncs ...func(*options.ServerRu
t.Fatal(err)
}
saSigningKeyFile, err := ioutil.TempFile("/tmp", "insecure_test_key")
saSigningKeyFile, err := os.CreateTemp("/tmp", "insecure_test_key")
if err != nil {
t.Fatalf("create temp file failed: %v", err)
}
defer os.RemoveAll(saSigningKeyFile.Name())
if err = ioutil.WriteFile(saSigningKeyFile.Name(), []byte(ecdsaPrivateKey), 0666); err != nil {
if err = os.WriteFile(saSigningKeyFile.Name(), []byte(ecdsaPrivateKey), 0666); err != nil {
t.Fatalf("write file %s failed: %v", saSigningKeyFile.Name(), err)
}

View File

@ -20,7 +20,6 @@ import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
@ -72,7 +71,7 @@ func TestAggregatedAPIServer(t *testing.T) {
// start the wardle server to prove we can aggregate it
wardleToKASKubeConfigFile := writeKubeConfigForWardleServerToKASConnection(t, rest.CopyConfig(kubeClientConfig))
defer os.Remove(wardleToKASKubeConfigFile)
wardleCertDir, _ := ioutil.TempDir("", "test-integration-wardle-server")
wardleCertDir, _ := os.MkdirTemp("", "test-integration-wardle-server")
defer os.RemoveAll(wardleCertDir)
listener, wardlePort, err := genericapiserveroptions.CreateListener("tcp", "127.0.0.1:0", net.ListenConfig{})
if err != nil {
@ -108,7 +107,7 @@ func TestAggregatedAPIServer(t *testing.T) {
testAPIGroup(t, wardleClient.Discovery().RESTClient())
testAPIResourceList(t, wardleClient.Discovery().RESTClient())
wardleCA, err := ioutil.ReadFile(directWardleClientConfig.CAFile)
wardleCA, err := os.ReadFile(directWardleClientConfig.CAFile)
if err != nil {
t.Fatal(err)
}
@ -158,10 +157,10 @@ func TestAggregatedAPIServer(t *testing.T) {
// now we update the client-ca nd request-header-client-ca-file and the kas will consume it, update the configmap
// and then the wardle server will detect and update too.
if err := ioutil.WriteFile(path.Join(testServer.TmpDir, "client-ca.crt"), differentClientCA, 0644); err != nil {
if err := os.WriteFile(path.Join(testServer.TmpDir, "client-ca.crt"), differentClientCA, 0644); err != nil {
t.Fatal(err)
}
if err := ioutil.WriteFile(path.Join(testServer.TmpDir, "proxy-ca.crt"), differentFrontProxyCA, 0644); err != nil {
if err := os.WriteFile(path.Join(testServer.TmpDir, "proxy-ca.crt"), differentFrontProxyCA, 0644); err != nil {
t.Fatal(err)
}
// wait for it to be picked up. there's a test in certreload_test.go that ensure this works
@ -274,7 +273,7 @@ func writeKubeConfigForWardleServerToKASConnection(t *testing.T, kubeClientConfi
}
adminKubeConfig := createKubeConfig(wardleToKASKubeClientConfig)
wardleToKASKubeConfigFile, _ := ioutil.TempFile("", "")
wardleToKASKubeConfigFile, _ := os.CreateTemp("", "")
if err := clientcmd.WriteToFile(*adminKubeConfig, wardleToKASKubeConfigFile.Name()); err != nil {
t.Fatal(err)
}

View File

@ -20,7 +20,7 @@ import (
"context"
"flag"
"fmt"
"io/ioutil"
"io"
"net"
"os"
"os/exec"
@ -104,7 +104,7 @@ func RunCustomEtcd(dataDir string, customFlags []string) (url string, stopFn fun
klog.Infof("starting etcd on %s", customURL)
etcdDataDir, err := ioutil.TempDir(os.TempDir(), dataDir)
etcdDataDir, err := os.MkdirTemp(os.TempDir(), dataDir)
if err != nil {
return "", nil, fmt.Errorf("unable to make temp etcd data dir %s: %v", dataDir, err)
}
@ -139,7 +139,7 @@ func RunCustomEtcd(dataDir string, customFlags []string) (url string, stopFn fun
// Quiet etcd logs for integration tests
// Comment out to get verbose logs if desired
grpclog.SetLoggerV2(grpclog.NewLoggerV2(ioutil.Discard, ioutil.Discard, os.Stderr))
grpclog.SetLoggerV2(grpclog.NewLoggerV2(io.Discard, io.Discard, os.Stderr))
if err := cmd.Start(); err != nil {
return "", nil, fmt.Errorf("failed to run etcd: %v", err)

View File

@ -18,7 +18,6 @@ package framework
import (
"context"
"io/ioutil"
"net"
"net/http"
"os"
@ -58,7 +57,7 @@ type TestServerSetup struct {
// StartTestServer runs a kube-apiserver, optionally calling out to the setup.ModifyServerRunOptions and setup.ModifyServerConfig functions
func StartTestServer(t *testing.T, stopCh <-chan struct{}, setup TestServerSetup) (client.Interface, *rest.Config) {
certDir, _ := ioutil.TempDir("", "test-integration-"+t.Name())
certDir, _ := os.MkdirTemp("", "test-integration-"+t.Name())
go func() {
<-stopCh
os.RemoveAll(certDir)
@ -73,8 +72,8 @@ func StartTestServer(t *testing.T, stopCh <-chan struct{}, setup TestServerSetup
if err != nil {
t.Fatal(err)
}
proxyCACertFile, _ := ioutil.TempFile(certDir, "proxy-ca.crt")
if err := ioutil.WriteFile(proxyCACertFile.Name(), utils.EncodeCertPEM(proxySigningCert), 0644); err != nil {
proxyCACertFile, _ := os.CreateTemp(certDir, "proxy-ca.crt")
if err := os.WriteFile(proxyCACertFile.Name(), utils.EncodeCertPEM(proxySigningCert), 0644); err != nil {
t.Fatal(err)
}
clientSigningKey, err := utils.NewPrivateKey()
@ -85,8 +84,8 @@ func StartTestServer(t *testing.T, stopCh <-chan struct{}, setup TestServerSetup
if err != nil {
t.Fatal(err)
}
clientCACertFile, _ := ioutil.TempFile(certDir, "client-ca.crt")
if err := ioutil.WriteFile(clientCACertFile.Name(), utils.EncodeCertPEM(clientSigningCert), 0644); err != nil {
clientCACertFile, _ := os.CreateTemp(certDir, "client-ca.crt")
if err := os.WriteFile(clientCACertFile.Name(), utils.EncodeCertPEM(clientSigningCert), 0644); err != nil {
t.Fatal(err)
}
@ -95,12 +94,12 @@ func StartTestServer(t *testing.T, stopCh <-chan struct{}, setup TestServerSetup
t.Fatal(err)
}
saSigningKeyFile, err := ioutil.TempFile("/tmp", "insecure_test_key")
saSigningKeyFile, err := os.CreateTemp("/tmp", "insecure_test_key")
if err != nil {
t.Fatalf("create temp file failed: %v", err)
}
defer os.RemoveAll(saSigningKeyFile.Name())
if err = ioutil.WriteFile(saSigningKeyFile.Name(), []byte(ecdsaPrivateKey), 0666); err != nil {
if err = os.WriteFile(saSigningKeyFile.Name(), []byte(ecdsaPrivateKey), 0666); err != nil {
t.Fatalf("write file %s failed: %v", saSigningKeyFile.Name(), err)
}

View File

@ -19,7 +19,6 @@ package ipamperf
import (
"encoding/json"
"fmt"
"io/ioutil"
"net"
"os"
"testing"
@ -101,7 +100,7 @@ func logResults(allResults []*Results) {
}
if resultsLogFile != "" {
klog.Infof("Logging results to %s", resultsLogFile)
if err := ioutil.WriteFile(resultsLogFile, jStr, os.FileMode(0644)); err != nil {
if err := os.WriteFile(resultsLogFile, jStr, os.FileMode(0644)); err != nil {
klog.Errorf("Error logging results to %s: %v", resultsLogFile, err)
}
}

View File

@ -20,7 +20,7 @@ import (
"context"
"errors"
"fmt"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"runtime"
@ -51,7 +51,7 @@ func scrapeMetrics(s *httptest.Server) (testutil.Metrics, error) {
return nil, fmt.Errorf("Non-200 response trying to scrape metrics from API Server: %v", resp)
}
metrics := testutil.NewMetrics()
data, err := ioutil.ReadAll(resp.Body)
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("Unable to read response: %v", resp)
}

View File

@ -19,7 +19,7 @@ package scale
import (
"context"
"encoding/json"
"io/ioutil"
"io"
"path"
"strings"
"testing"
@ -203,7 +203,7 @@ var (
)
func setupWithOptions(t *testing.T, instanceOptions *apitesting.TestServerInstanceOptions, flags []string) (client kubernetes.Interface, tearDown func()) {
grpclog.SetLoggerV2(grpclog.NewLoggerV2(ioutil.Discard, ioutil.Discard, ioutil.Discard))
grpclog.SetLoggerV2(grpclog.NewLoggerV2(io.Discard, io.Discard, io.Discard))
result := apitesting.StartTestServerOrDie(t, instanceOptions, flags, framework.SharedEtcd())
result.ClientConfig.AcceptContentTypes = ""

View File

@ -20,8 +20,8 @@ import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"math"
"os"
"strings"
"sync"
"testing"
@ -542,7 +542,7 @@ func BenchmarkPerfScheduling(b *testing.B) {
}
func loadSchedulerConfig(file string) (*config.KubeSchedulerConfiguration, error) {
data, err := ioutil.ReadFile(file)
data, err := os.ReadFile(file)
if err != nil {
return nil, err
}
@ -940,7 +940,7 @@ func waitUntilPodsScheduled(ctx context.Context, podInformer coreinformers.PodIn
}
func getSpecFromFile(path *string, spec interface{}) error {
bytes, err := ioutil.ReadFile(*path)
bytes, err := os.ReadFile(*path)
if err != nil {
return err
}
@ -948,7 +948,7 @@ func getSpecFromFile(path *string, spec interface{}) error {
}
func getUnstructuredFromFile(path string) (*unstructured.Unstructured, *schema.GroupVersionKind, error) {
bytes, err := ioutil.ReadFile(path)
bytes, err := os.ReadFile(path)
if err != nil {
return nil, nil, err
}

View File

@ -22,7 +22,6 @@ import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"math"
"os"
"path"
@ -178,7 +177,7 @@ func dataItems2JSONFile(dataItems DataItems, namePrefix string) error {
if err := json.Indent(formatted, b, "", " "); err != nil {
return fmt.Errorf("indenting error: %v", err)
}
return ioutil.WriteFile(destFile, formatted.Bytes(), 0644)
return os.WriteFile(destFile, formatted.Bytes(), 0644)
}
type labelValues struct {

View File

@ -21,7 +21,6 @@ import (
"crypto/x509"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path"
@ -90,7 +89,7 @@ func TestComponentSecureServingAndAuth(t *testing.T) {
// authenticate to apiserver via bearer token
token := "flwqkenfjasasdfmwerasd" // Fake token for testing.
tokenFile, err := ioutil.TempFile("", "kubeconfig")
tokenFile, err := os.CreateTemp("", "kubeconfig")
if err != nil {
t.Fatal(err)
}
@ -107,7 +106,7 @@ func TestComponentSecureServingAndAuth(t *testing.T) {
defer server.TearDownFn()
// create kubeconfig for the apiserver
apiserverConfig, err := ioutil.TempFile("", "kubeconfig")
apiserverConfig, err := os.CreateTemp("", "kubeconfig")
if err != nil {
t.Fatal(err)
}
@ -133,7 +132,7 @@ users:
apiserverConfig.Close()
// create BROKEN kubeconfig for the apiserver
brokenApiserverConfig, err := ioutil.TempFile("", "kubeconfig")
brokenApiserverConfig, err := os.CreateTemp("", "kubeconfig")
if err != nil {
t.Fatal(err)
}
@ -273,7 +272,7 @@ func testComponent(t *testing.T, tester componentTester, kubeconfig, brokenKubec
// read self-signed server cert disk
pool := x509.NewCertPool()
serverCertPath := path.Join(secureOptions.ServerCert.CertDirectory, secureOptions.ServerCert.PairName+".crt")
serverCert, err := ioutil.ReadFile(serverCertPath)
serverCert, err := os.ReadFile(serverCertPath)
if err != nil {
t.Fatalf("Failed to read component server cert %q: %v", serverCertPath, err)
}
@ -297,7 +296,7 @@ func testComponent(t *testing.T, tester componentTester, kubeconfig, brokenKubec
t.Fatalf("failed to GET %s from component: %v", tt.path, err)
}
body, err := ioutil.ReadAll(r.Body)
body, err := io.ReadAll(r.Body)
if err != nil {
t.Fatalf("failed to read response body: %v", err)
}
@ -315,7 +314,7 @@ func testComponent(t *testing.T, tester componentTester, kubeconfig, brokenKubec
if err != nil {
t.Fatalf("failed to GET %s from component: %v", tt.path, err)
}
body, err := ioutil.ReadAll(r.Body)
body, err := io.ReadAll(r.Body)
if err != nil {
t.Fatalf("failed to read response body: %v", err)
}
@ -396,7 +395,7 @@ func testComponentWithSecureServing(t *testing.T, tester componentTester, kubeco
// read self-signed server cert disk
pool := x509.NewCertPool()
serverCertPath := path.Join(secureOptions.ServerCert.CertDirectory, secureOptions.ServerCert.PairName+".crt")
serverCert, err := ioutil.ReadFile(serverCertPath)
serverCert, err := os.ReadFile(serverCertPath)
if err != nil {
t.Fatalf("Failed to read component server cert %q: %v", serverCertPath, err)
}
@ -420,7 +419,7 @@ func testComponentWithSecureServing(t *testing.T, tester componentTester, kubeco
t.Fatalf("failed to GET %s from component: %v", tt.path, err)
}
body, err := ioutil.ReadAll(r.Body)
body, err := io.ReadAll(r.Body)
if err != nil {
t.Fatalf("failed to read response body: %v", err)
}

View File

@ -21,7 +21,7 @@ import (
"crypto/x509"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"testing"
@ -55,7 +55,7 @@ func NewAdmissionWebhookServer(handler http.Handler) (string, func(), error) {
func AdmissionWebhookHandler(t *testing.T, admit func(*v1beta1.AdmissionReview) error) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
data, err := ioutil.ReadAll(r.Body)
data, err := io.ReadAll(r.Body)
if err != nil {
t.Error(err)
return

View File

@ -17,7 +17,6 @@ limitations under the License.
package harness
import (
"io/ioutil"
"os"
"testing"
@ -56,11 +55,11 @@ func (h *Harness) Close() {
}
}
// TempDir is a wrapper around ioutil.TempDir for tests.
// TempDir is a wrapper around os.MkdirTemp for tests.
// It automatically fails the test if we can't create a temp file,
// and deletes the temp directory when Close is called on the Harness
func (h *Harness) TempDir(baseDir string, prefix string) string {
tempDir, err := ioutil.TempDir(baseDir, prefix)
tempDir, err := os.MkdirTemp(baseDir, prefix)
if err != nil {
h.Fatalf("unable to create tempdir: %v", err)
}

View File

@ -20,7 +20,6 @@ import (
"crypto/sha256"
"encoding/base64"
"fmt"
"io/ioutil"
"os"
"regexp"
"strings"
@ -73,7 +72,7 @@ func initReg() RegistryList {
return registry
}
fileContent, err := ioutil.ReadFile(repoList)
fileContent, err := os.ReadFile(repoList)
if err != nil {
panic(fmt.Errorf("Error reading '%v' file contents: %v", repoList, err))
}

View File

@ -17,7 +17,7 @@ limitations under the License.
package utils
import (
"io/ioutil"
"os"
"k8s.io/klog/v2"
)
@ -26,7 +26,7 @@ func MakeTempDirOrDie(prefix string, baseDir string) string {
if baseDir == "" {
baseDir = "/tmp"
}
tempDir, err := ioutil.TempDir(baseDir, prefix)
tempDir, err := os.MkdirTemp(baseDir, prefix)
if err != nil {
klog.Fatalf("Can't make a temp rootdir: %v", err)
}