Merge pull request #131676 from karlkfi/karl-ioutil

refactor: Stop using ioutil in apiserver

Kubernetes-commit: 7ce0e1ca2b176bc11855944f721a9f6cf73cae54
This commit is contained in:
Kubernetes Publisher 2025-05-09 00:31:21 -07:00
commit f2b80d742a
28 changed files with 105 additions and 119 deletions

View File

@ -18,7 +18,7 @@ package policy
import (
"fmt"
"io/ioutil"
"os"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
@ -47,7 +47,7 @@ func LoadPolicyFromFile(filePath string) (*auditinternal.Policy, error) {
if filePath == "" {
return nil, fmt.Errorf("file path not specified")
}
policyDef, err := ioutil.ReadFile(filePath)
policyDef, err := os.ReadFile(filePath)
if err != nil {
return nil, fmt.Errorf("failed to read file path %q: %+v", filePath, err)
}

View File

@ -17,7 +17,6 @@ limitations under the License.
package policy
import (
"io/ioutil"
"os"
"reflect"
"strings"
@ -158,7 +157,7 @@ kind: Policy`,
}
func writePolicy(t *testing.T, policy string) (string, error) {
f, err := ioutil.TempFile("", "policy.yaml")
f, err := os.CreateTemp("", "policy.yaml")
require.NoError(t, err)
_, err = f.WriteString(policy)

View File

@ -18,7 +18,6 @@ package tokenfile
import (
"context"
"io/ioutil"
"os"
"reflect"
"testing"
@ -137,14 +136,14 @@ func TestEmptyTokenTokenFile(t *testing.T) {
}
func newWithContents(t *testing.T, contents string) (auth *TokenAuthenticator, err error) {
f, err := ioutil.TempFile("", "tokenfile_test")
f, err := os.CreateTemp("", "tokenfile_test")
if err != nil {
t.Fatalf("unexpected error creating tokenfile: %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 tokenfile: %v", err)
}

View File

@ -24,7 +24,6 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net/http"
"net/http/httptest"
@ -703,7 +702,7 @@ func (storage *SimpleTypedStorage) GetSingularName() string {
func bodyOrDie(response *http.Response) string {
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
body, err := io.ReadAll(response.Body)
if err != nil {
panic(err)
}
@ -716,7 +715,7 @@ func extractBody(response *http.Response, object runtime.Object) (string, error)
func extractBodyDecoder(response *http.Response, object runtime.Object, decoder runtime.Decoder) (string, error) {
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
body, err := io.ReadAll(response.Body)
if err != nil {
return string(body), err
}
@ -725,7 +724,7 @@ func extractBodyDecoder(response *http.Response, object runtime.Object, decoder
func extractBodyObject(response *http.Response, decoder runtime.Decoder) (runtime.Object, string, error) {
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
body, err := io.ReadAll(response.Body)
if err != nil {
return nil, string(body), err
}
@ -888,7 +887,7 @@ func TestUnimplementedRESTStorage(t *testing.T) {
t.Fatalf("unexpected error: %v", err)
}
defer response.Body.Close()
data, err := ioutil.ReadAll(response.Body)
data, err := io.ReadAll(response.Body)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@ -957,7 +956,7 @@ func TestSomeUnimplementedRESTStorage(t *testing.T) {
t.Fatalf("unexpected error: %v", err)
}
defer response.Body.Close()
data, err := ioutil.ReadAll(response.Body)
data, err := io.ReadAll(response.Body)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@ -1122,7 +1121,7 @@ func TestList(t *testing.T) {
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("%d: unexpected status: %d from url %s, Expected: %d, %#v", i, resp.StatusCode, testCase.url, http.StatusOK, resp)
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Errorf("%d: unexpected error: %v", i, err)
continue
@ -1180,7 +1179,7 @@ func TestRequestsWithInvalidQuery(t *testing.T) {
defer resp.Body.Close()
if resp.StatusCode != http.StatusBadRequest {
t.Errorf("%d: unexpected status: %d from url %s, Expected: %d, %#v", i, resp.StatusCode, url, http.StatusBadRequest, resp)
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Errorf("%d: unexpected error: %v", i, err)
continue
@ -1245,7 +1244,7 @@ func TestListCompression(t *testing.T) {
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("%d: unexpected status: %d from url %s, Expected: %d, %#v", i, resp.StatusCode, testCase.url, http.StatusOK, resp)
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Errorf("%d: unexpected error: %v", i, err)
continue
@ -1299,7 +1298,7 @@ func TestLogs(t *testing.T) {
t.Errorf("unexpected error: %v", err)
}
body, err := ioutil.ReadAll(response.Body)
body, err := io.ReadAll(response.Body)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@ -1348,7 +1347,7 @@ func TestNonEmptyList(t *testing.T) {
if resp.StatusCode != http.StatusOK {
t.Errorf("Unexpected status: %d, Expected: %d, %#v", resp.StatusCode, http.StatusOK, resp)
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@ -1461,7 +1460,7 @@ func BenchmarkGet(b *testing.B) {
if resp.StatusCode != http.StatusOK {
b.Fatalf("unexpected response: %#v", resp)
}
if _, err := io.Copy(ioutil.Discard, resp.Body); err != nil {
if _, err := io.Copy(io.Discard, resp.Body); err != nil {
b.Fatalf("unable to read body")
}
}
@ -1497,7 +1496,7 @@ func BenchmarkGetNoCompression(b *testing.B) {
if resp.StatusCode != http.StatusOK {
b.Fatalf("unexpected response: %#v", resp)
}
if _, err := io.Copy(ioutil.Discard, resp.Body); err != nil {
if _, err := io.Copy(io.Discard, resp.Body); err != nil {
b.Fatalf("unable to read body")
}
}
@ -1556,7 +1555,7 @@ func TestGetCompression(t *testing.T) {
if err != nil {
t.Errorf("unexpected error: %v", err)
}
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Errorf("unexpected error reading body: %v", err)
}
@ -2043,12 +2042,12 @@ func TestWatchTable(t *testing.T) {
test.send(simpleStorage.fakeWatch)
}()
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
t.Logf("Body:\n%s", string(body))
d := watcher(resp.Header.Get("Content-Type"), ioutil.NopCloser(bytes.NewReader(body)))
d := watcher(resp.Header.Get("Content-Type"), io.NopCloser(bytes.NewReader(body)))
var actual []*metav1.WatchEvent
for {
var event metav1.WatchEvent
@ -2244,7 +2243,7 @@ func TestGetPartialObjectMetadata(t *testing.T) {
}
body = d
} else {
d, err := ioutil.ReadAll(resp.Body)
d, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
@ -2283,7 +2282,7 @@ func TestGetBinary(t *testing.T) {
if resp.StatusCode != http.StatusOK {
t.Fatalf("unexpected response: %#v", resp)
}
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
@ -2538,7 +2537,7 @@ func TestConnect(t *testing.T) {
t.Errorf("unexpected response: %#v", resp)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
@ -2576,7 +2575,7 @@ func TestConnectResponderObject(t *testing.T) {
t.Errorf("unexpected response: %#v", resp)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
@ -2617,7 +2616,7 @@ func TestConnectResponderError(t *testing.T) {
t.Errorf("unexpected response: %#v", resp)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
@ -2686,7 +2685,7 @@ func TestConnectWithOptions(t *testing.T) {
t.Errorf("unexpected response: %#v", resp)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
@ -2736,7 +2735,7 @@ func TestConnectWithOptionsAndPath(t *testing.T) {
t.Errorf("unexpected response: %#v", resp)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
@ -2813,7 +2812,7 @@ func TestDeleteWithOptions(t *testing.T) {
}
if res.StatusCode != http.StatusOK {
t.Errorf("unexpected response: %s %#v", request.URL, res)
s, err := ioutil.ReadAll(res.Body)
s, err := io.ReadAll(res.Body)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@ -2853,7 +2852,7 @@ func TestDeleteWithOptionsQuery(t *testing.T) {
}
if res.StatusCode != http.StatusOK {
t.Errorf("unexpected response: %s %#v", request.URL, res)
s, err := ioutil.ReadAll(res.Body)
s, err := io.ReadAll(res.Body)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@ -2896,7 +2895,7 @@ func TestDeleteWithOptionsQueryAndBody(t *testing.T) {
}
if res.StatusCode != http.StatusOK {
t.Errorf("unexpected response: %s %#v", request.URL, res)
s, err := ioutil.ReadAll(res.Body)
s, err := io.ReadAll(res.Body)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@ -3286,7 +3285,7 @@ func TestCreateChecksDecode(t *testing.T) {
if response.StatusCode != http.StatusBadRequest {
t.Errorf("Unexpected response %#v", response)
}
b, err := ioutil.ReadAll(response.Body)
b, err := io.ReadAll(response.Body)
if err != nil {
t.Errorf("unexpected error: %v", err)
} else if !strings.Contains(string(b), "cannot be handled as a Simple") {
@ -3565,7 +3564,7 @@ func TestUpdateChecksDecode(t *testing.T) {
if response.StatusCode != http.StatusBadRequest {
t.Errorf("Unexpected response %#v\n%s", response, readBodyOrDie(response.Body))
}
b, err := ioutil.ReadAll(response.Body)
b, err := io.ReadAll(response.Body)
if err != nil {
t.Errorf("unexpected error: %v", err)
} else if !strings.Contains(string(b), "cannot be handled as a Simple") {
@ -3932,7 +3931,7 @@ func TestCreateChecksAPIVersion(t *testing.T) {
if response.StatusCode != http.StatusBadRequest {
t.Errorf("Unexpected response %#v", response)
}
b, err := ioutil.ReadAll(response.Body)
b, err := io.ReadAll(response.Body)
if err != nil {
t.Errorf("unexpected error: %v", err)
} else if !strings.Contains(string(b), "does not match the expected API version") {
@ -3997,7 +3996,7 @@ func TestUpdateChecksAPIVersion(t *testing.T) {
if response.StatusCode != http.StatusBadRequest {
t.Errorf("Unexpected response %#v", response)
}
b, err := ioutil.ReadAll(response.Body)
b, err := io.ReadAll(response.Body)
if err != nil {
t.Errorf("unexpected error: %v", err)
} else if !strings.Contains(string(b), "does not match the expected API version") {
@ -4391,7 +4390,7 @@ func TestXGSubresource(t *testing.T) {
}
func readBodyOrDie(r io.Reader) []byte {
body, err := ioutil.ReadAll(r)
body, err := io.ReadAll(r)
if err != nil {
panic(err)
}
@ -4432,10 +4431,10 @@ func BenchmarkUpdateProtobuf(b *testing.B) {
b.Fatalf("unexpected error: %v", err)
}
if response.StatusCode != http.StatusBadRequest {
body, _ := ioutil.ReadAll(response.Body)
body, _ := io.ReadAll(response.Body)
b.Fatalf("Unexpected response %#v\n%s", response, body)
}
_, _ = ioutil.ReadAll(response.Body)
_, _ = io.ReadAll(response.Body)
response.Body.Close()
}
b.StopTimer()

View File

@ -20,7 +20,7 @@ import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"testing"
@ -55,7 +55,7 @@ func init() {
func decodeResponse(t *testing.T, resp *http.Response, obj interface{}) error {
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
data, err := io.ReadAll(resp.Body)
t.Log(string(data))
if err != nil {
return err

View File

@ -19,7 +19,7 @@ package fieldmanager_test
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"
@ -38,7 +38,7 @@ import (
)
var fakeTypeConverter = func() managedfields.TypeConverter {
data, err := ioutil.ReadFile(filepath.Join(strings.Repeat(".."+string(filepath.Separator), 8),
data, err := os.ReadFile(filepath.Join(strings.Repeat(".."+string(filepath.Separator), 8),
"api", "openapi-spec", "swagger.json"))
if err != nil {
panic(err)
@ -60,7 +60,7 @@ var fakeTypeConverter = func() managedfields.TypeConverter {
}()
func getObjectBytes(file string) []byte {
s, err := ioutil.ReadFile(file)
s, err := os.ReadFile(file)
if err != nil {
panic(err)
}

View File

@ -25,7 +25,6 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net/http"
"net/http/httptest"
@ -369,7 +368,7 @@ func TestSerializeObject(t *testing.T) {
if !reflect.DeepEqual(result.Header, tt.wantHeaders) {
t.Fatal(cmp.Diff(tt.wantHeaders, result.Header))
}
body, _ := ioutil.ReadAll(result.Body)
body, _ := io.ReadAll(result.Body)
if !bytes.Equal(tt.wantBody, body) {
t.Fatalf("wanted:\n%s\ngot:\n%s", hex.Dump(tt.wantBody), hex.Dump(body))
}

View File

@ -21,7 +21,6 @@ import (
"encoding/hex"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
@ -373,13 +372,13 @@ func summarizeData(data []byte, maxLength int) string {
func limitedReadBody(req *http.Request, limit int64) ([]byte, error) {
defer req.Body.Close()
if limit <= 0 {
return ioutil.ReadAll(req.Body)
return io.ReadAll(req.Body)
}
lr := &io.LimitedReader{
R: req.Body,
N: limit + 1,
}
data, err := ioutil.ReadAll(lr)
data, err := io.ReadAll(lr)
if err != nil {
return nil, err
}

View File

@ -21,7 +21,6 @@ import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
@ -232,7 +231,7 @@ func TestWatchClientClose(t *testing.T) {
}
if response.StatusCode != http.StatusOK {
b, _ := ioutil.ReadAll(response.Body)
b, _ := io.ReadAll(response.Body)
t.Fatalf("Unexpected response: %#v\n%s", response, string(b))
}
@ -276,7 +275,7 @@ func TestWatchRead(t *testing.T) {
}
if response.StatusCode != http.StatusOK {
b, _ := ioutil.ReadAll(response.Body)
b, _ := io.ReadAll(response.Body)
t.Fatalf("Unexpected response for accept: %q: %#v\n%s", accept, response, string(b))
}
return response.Body, response.Header.Get("Content-Type")
@ -656,7 +655,7 @@ func runWatchHTTPBenchmark(b *testing.B, items []runtime.Object, contentType str
wg.Add(1)
go func() {
defer response.Body.Close()
if _, err := io.Copy(ioutil.Discard, response.Body); err != nil {
if _, err := io.Copy(io.Discard, response.Body); err != nil {
b.Error(err)
}
wg.Done()
@ -696,7 +695,7 @@ func BenchmarkWatchWebsocket(b *testing.B) {
wg.Add(1)
go func() {
defer ws.Close()
if _, err := io.Copy(ioutil.Discard, ws); err != nil {
if _, err := io.Copy(io.Discard, ws); err != nil {
b.Error(err)
}
wg.Done()

View File

@ -19,7 +19,6 @@ package rest
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"k8s.io/apimachinery/pkg/api/errors"
@ -47,7 +46,7 @@ type GenericHttpResponseChecker struct {
func (checker GenericHttpResponseChecker) Check(resp *http.Response) error {
if resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusPartialContent {
defer resp.Body.Close()
bodyBytes, err := ioutil.ReadAll(io.LimitReader(resp.Body, maxReadLength))
bodyBytes, err := io.ReadAll(io.LimitReader(resp.Body, maxReadLength))
if err != nil {
return errors.NewInternalError(err)
}

View File

@ -19,7 +19,7 @@ package rest
import (
"bytes"
"fmt"
"io/ioutil"
"io"
"net/http"
"reflect"
"strings"
@ -39,7 +39,7 @@ func TestGenericHttpResponseChecker(t *testing.T) {
}{
{
resp: &http.Response{
Body: ioutil.NopCloser(bytes.NewBufferString("Success")),
Body: io.NopCloser(bytes.NewBufferString("Success")),
StatusCode: http.StatusOK,
},
expectError: false,
@ -47,7 +47,7 @@ func TestGenericHttpResponseChecker(t *testing.T) {
},
{
resp: &http.Response{
Body: ioutil.NopCloser(bytes.NewBufferString("Invalid request.")),
Body: io.NopCloser(bytes.NewBufferString("Invalid request.")),
StatusCode: http.StatusBadRequest,
},
expectError: true,
@ -56,7 +56,7 @@ func TestGenericHttpResponseChecker(t *testing.T) {
},
{
resp: &http.Response{
Body: ioutil.NopCloser(bytes.NewBufferString("Pod does not exist.")),
Body: io.NopCloser(bytes.NewBufferString("Pod does not exist.")),
StatusCode: http.StatusInternalServerError,
},
expectError: true,
@ -82,7 +82,7 @@ func TestGenericHttpResponseCheckerLimitReader(t *testing.T) {
responseChecker := NewGenericHttpResponseChecker(v1.Resource("pods"), "foo")
excessedString := strings.Repeat("a", (maxReadLength + 10000))
resp := &http.Response{
Body: ioutil.NopCloser(bytes.NewBufferString(excessedString)),
Body: io.NopCloser(bytes.NewBufferString(excessedString)),
StatusCode: http.StatusBadRequest,
}
err := responseChecker.Check(resp)

View File

@ -21,7 +21,7 @@ import (
"bytes"
"context"
"fmt"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"net/url"
@ -54,7 +54,7 @@ func TestInputStreamReader(t *testing.T) {
return
}
defer readCloser.Close()
result, _ := ioutil.ReadAll(readCloser)
result, _ := io.ReadAll(readCloser)
if string(result) != resultString {
t.Errorf("Stream content does not match. Got: %s. Expected: %s.", string(result), resultString)
}
@ -117,7 +117,7 @@ func TestInputStreamTransport(t *testing.T) {
return
}
defer readCloser.Close()
result, _ := ioutil.ReadAll(readCloser)
result, _ := io.ReadAll(readCloser)
if string(result) != message {
t.Errorf("Stream content does not match. Got: %s. Expected: %s.", string(result), message)
}

View File

@ -22,7 +22,6 @@ import (
"crypto/tls"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net"
"net/http"
@ -142,7 +141,7 @@ func newTestGOAWAYServer() (*httptest.Server, error) {
return
})
postHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reqBody, err := ioutil.ReadAll(r.Body)
reqBody, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
@ -208,7 +207,7 @@ func requestGOAWAYServer(client *http.Client, serverBaseURL, url string) (<-chan
if resp.StatusCode != http.StatusOK {
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body and status code is %d, error: %v", resp.StatusCode, err)
}
@ -248,7 +247,7 @@ func requestGOAWAYServer(client *http.Client, serverBaseURL, url string) (<-chan
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body, error: %v", err)
}

View File

@ -23,7 +23,7 @@ import (
"crypto/x509"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net"
"net/http"
"net/http/httptest"
@ -121,7 +121,7 @@ func TestTimeout(t *testing.T) {
if res.StatusCode != http.StatusOK {
t.Errorf("got res.StatusCode %d; expected %d", res.StatusCode, http.StatusOK)
}
body, _ := ioutil.ReadAll(res.Body)
body, _ := io.ReadAll(res.Body)
if string(body) != resp {
t.Errorf("got body %q; expected %q", string(body), resp)
}
@ -143,7 +143,7 @@ func TestTimeout(t *testing.T) {
if res.StatusCode != http.StatusGatewayTimeout {
t.Errorf("got res.StatusCode %d; expected %d", res.StatusCode, http.StatusGatewayTimeout)
}
body, _ = ioutil.ReadAll(res.Body)
body, _ = io.ReadAll(res.Body)
status := &metav1.Status{}
if err := json.Unmarshal(body, status); err != nil {
t.Fatal(err)

View File

@ -19,7 +19,6 @@ package options
import (
stdjson "encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"testing"
@ -271,7 +270,7 @@ func makeTmpWebhookConfig(t *testing.T) string {
{Cluster: v1.Cluster{Server: "localhost", InsecureSkipTLSVerify: true}},
},
}
f, err := ioutil.TempFile("", "k8s_audit_webhook_test_")
f, err := os.CreateTemp("", "k8s_audit_webhook_test_")
require.NoError(t, err, "creating temp file")
require.NoError(t, stdjson.NewEncoder(f).Encode(config), "writing webhook kubeconfig")
require.NoError(t, f.Close())
@ -289,7 +288,7 @@ func makeTmpPolicy(t *testing.T) string {
},
},
}
f, err := ioutil.TempFile("", "k8s_audit_policy_test_")
f, err := os.CreateTemp("", "k8s_audit_policy_test_")
require.NoError(t, err, "creating temp file")
require.NoError(t, stdjson.NewEncoder(f).Encode(pol), "writing policy file")
require.NoError(t, f.Close())

View File

@ -17,7 +17,6 @@ limitations under the License.
package options
import (
"io/ioutil"
"net/http"
"os"
"reflect"
@ -88,13 +87,13 @@ func TestToAuthenticationRequestHeaderConfig(t *testing.T) {
func TestApplyToFallback(t *testing.T) {
f, err := ioutil.TempFile("", "authkubeconfig")
f, err := os.CreateTemp("", "authkubeconfig")
if err != nil {
t.Fatal(err)
}
defer os.Remove(f.Name())
if err := ioutil.WriteFile(f.Name(), []byte(`
if err := os.WriteFile(f.Name(), []byte(`
apiVersion: v1
kind: Config
clusters:

View File

@ -28,7 +28,6 @@ import (
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
"math/big"
"net"
"os"
@ -405,13 +404,13 @@ func getOrCreateTestCertFiles(certFileName, keyFileName string, spec TestCertSpe
}
os.MkdirAll(filepath.Dir(certFileName), os.FileMode(0755))
err = ioutil.WriteFile(certFileName, certPem, os.FileMode(0755))
err = os.WriteFile(certFileName, certPem, os.FileMode(0755))
if err != nil {
return err
}
os.MkdirAll(filepath.Dir(keyFileName), os.FileMode(0755))
err = ioutil.WriteFile(keyFileName, keyPem, os.FileMode(0755))
err = os.WriteFile(keyFileName, keyPem, os.FileMode(0755))
if err != nil {
return err
}
@ -420,7 +419,7 @@ func getOrCreateTestCertFiles(certFileName, keyFileName string, spec TestCertSpe
}
func caCertFromBundle(bundlePath string) (*x509.Certificate, error) {
pemData, err := ioutil.ReadFile(bundlePath)
pemData, err := os.ReadFile(bundlePath)
if err != nil {
return nil, err
}

View File

@ -19,8 +19,8 @@ package options
import (
"context"
"fmt"
"io/ioutil"
"net"
"os"
"github.com/spf13/pflag"
"go.opentelemetry.io/otel"
@ -153,7 +153,7 @@ func ReadTracingConfiguration(configFilePath string) (*tracingapi.TracingConfigu
if configFilePath == "" {
return nil, fmt.Errorf("tracing config file was empty")
}
data, err := ioutil.ReadFile(configFilePath)
data, err := os.ReadFile(configFilePath)
if err != nil {
return nil, fmt.Errorf("unable to read tracing configuration from %q: %v", configFilePath, err)
}

View File

@ -18,7 +18,6 @@ package options
import (
"fmt"
"io/ioutil"
"os"
"reflect"
"strings"
@ -182,12 +181,12 @@ spec:
t.Run(tc.name, func(t *testing.T) {
proxyConfig := fmt.Sprintf("test-tracing-config-%s", tc.name)
if tc.createFile {
f, err := ioutil.TempFile("", proxyConfig)
f, err := os.CreateTemp("", proxyConfig)
if err != nil {
t.Fatal(err)
}
defer os.Remove(f.Name())
if err := ioutil.WriteFile(f.Name(), []byte(tc.contents), os.FileMode(0755)); err != nil {
if err := os.WriteFile(f.Name(), []byte(tc.contents), os.FileMode(0755)); err != nil {
t.Fatal(err)
}
proxyConfig = f.Name()

View File

@ -19,7 +19,7 @@ package routes
import (
"fmt"
"html/template"
"io/ioutil"
"io"
"net/http"
"path"
"sync"
@ -98,7 +98,7 @@ func StringFlagPutHandler(setter StringFlagSetterFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
switch {
case req.Method == "PUT":
body, err := ioutil.ReadAll(req.Body)
body, err := io.ReadAll(req.Body)
if err != nil {
writePlainText(http.StatusBadRequest, "error reading request body: "+err.Error(), w)
return

View File

@ -20,7 +20,7 @@ import (
"context"
"crypto/rand"
"fmt"
"io/ioutil"
"io"
"os"
"reflect"
"strings"
@ -61,7 +61,7 @@ func init() {
utilruntime.Must(example.AddToScheme(scheme))
utilruntime.Must(examplev1.AddToScheme(scheme))
grpclog.SetLoggerV2(grpclog.NewLoggerV2(ioutil.Discard, ioutil.Discard, os.Stderr))
grpclog.SetLoggerV2(grpclog.NewLoggerV2(io.Discard, io.Discard, os.Stderr))
}
func newPod() runtime.Object {

View File

@ -18,7 +18,6 @@ package factory
import (
"context"
"io/ioutil"
"os"
"path"
"path/filepath"
@ -94,20 +93,20 @@ func TestTLSConnection(t *testing.T) {
func configureTLSCerts(t *testing.T) (certFile, keyFile, caFile string) {
baseDir := os.TempDir()
tempDir, err := ioutil.TempDir(baseDir, "etcd_certificates")
tempDir, err := os.MkdirTemp(baseDir, "etcd_certificates")
if err != nil {
t.Fatal(err)
}
certFile = path.Join(tempDir, "etcdcert.pem")
if err := ioutil.WriteFile(certFile, []byte(testingcert.CertFileContent), 0644); err != nil {
if err := os.WriteFile(certFile, []byte(testingcert.CertFileContent), 0644); err != nil {
t.Fatal(err)
}
keyFile = path.Join(tempDir, "etcdkey.pem")
if err := ioutil.WriteFile(keyFile, []byte(testingcert.KeyFileContent), 0644); err != nil {
if err := os.WriteFile(keyFile, []byte(testingcert.KeyFileContent), 0644); err != nil {
t.Fatal(err)
}
caFile = path.Join(tempDir, "ca.pem")
if err := ioutil.WriteFile(caFile, []byte(testingcert.CAFileContent), 0644); err != nil {
if err := os.WriteFile(caFile, []byte(testingcert.CAFileContent), 0644); err != nil {
t.Fatal(err)
}
return certFile, keyFile, caFile

View File

@ -20,7 +20,6 @@ import (
stdjson "encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
@ -65,7 +64,7 @@ type testWebhookHandler struct {
func (t *testWebhookHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
err := func() error {
body, err := ioutil.ReadAll(r.Body)
body, err := io.ReadAll(r.Body)
if err != nil {
return fmt.Errorf("read webhook request body: %v", err)
}
@ -96,7 +95,7 @@ func newWebhook(t *testing.T, endpoint string, groupVersion schema.GroupVersion)
{Cluster: v1.Cluster{Server: endpoint, InsecureSkipTLSVerify: true}},
},
}
f, err := ioutil.TempFile("", "k8s_audit_webhook_test_")
f, err := os.CreateTemp("", "k8s_audit_webhook_test_")
require.NoError(t, err, "creating temp file")
defer func() {

View File

@ -33,7 +33,7 @@ import (
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"net/url"
"strings"
@ -986,7 +986,7 @@ func getClaimJWT(ctx context.Context, client *http.Client, url, accessToken stri
if response.StatusCode < http.StatusOK || response.StatusCode > http.StatusIMUsed {
return "", fmt.Errorf("error while getting distributed claim JWT: %v", response.Status)
}
responseBytes, err := ioutil.ReadAll(response.Body)
responseBytes, err := io.ReadAll(response.Body)
if err != nil {
return "", fmt.Errorf("could not decode distributed claim response")
}

View File

@ -22,7 +22,7 @@ import (
"crypto/x509"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"net/url"
@ -89,7 +89,7 @@ func NewV1TestServer(s V1Service, cert, key, caCert []byte) (*httptest.Server, e
}
var review authenticationv1.TokenReview
bodyData, _ := ioutil.ReadAll(r.Body)
bodyData, _ := io.ReadAll(r.Body)
if err := json.Unmarshal(bodyData, &review); err != nil {
http.Error(w, fmt.Sprintf("failed to decode body: %v", err), http.StatusBadRequest)
return
@ -180,7 +180,7 @@ func (m *mockV1Service) HTTPStatusCode() int { return m.statusCode }
// newV1TokenAuthenticator creates a temporary kubeconfig file from the provided
// arguments and attempts to load a new WebhookTokenAuthenticator from it.
func newV1TokenAuthenticator(serverURL string, clientCert, clientKey, ca []byte, cacheTime time.Duration, implicitAuds authenticator.Audiences, metrics AuthenticatorMetrics) (authenticator.Token, error) {
tempfile, err := ioutil.TempFile("", "")
tempfile, err := os.CreateTemp("", "")
if err != nil {
return nil, err
}

View File

@ -22,7 +22,7 @@ import (
"crypto/x509"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"net/url"
@ -83,7 +83,7 @@ func NewV1beta1TestServer(s V1beta1Service, cert, key, caCert []byte) (*httptest
}
var review authenticationv1beta1.TokenReview
bodyData, _ := ioutil.ReadAll(r.Body)
bodyData, _ := io.ReadAll(r.Body)
if err := json.Unmarshal(bodyData, &review); err != nil {
http.Error(w, fmt.Sprintf("failed to decode body: %v", err), http.StatusBadRequest)
return
@ -174,7 +174,7 @@ func (m *mockV1beta1Service) HTTPStatusCode() int { return m.statusCode }
// newV1beta1TokenAuthenticator creates a temporary kubeconfig file from the provided
// arguments and attempts to load a new WebhookTokenAuthenticator from it.
func newV1beta1TokenAuthenticator(serverURL string, clientCert, clientKey, ca []byte, cacheTime time.Duration, implicitAuds authenticator.Audiences) (authenticator.Token, error) {
tempfile, err := ioutil.TempFile("", "")
tempfile, err := os.CreateTemp("", "")
if err != nil {
return nil, err
}

View File

@ -22,7 +22,7 @@ import (
"crypto/x509"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"net/url"
@ -65,7 +65,7 @@ var testRetryBackoff = wait.Backoff{
}
func TestV1NewFromConfig(t *testing.T) {
dir, err := ioutil.TempDir("", "")
dir, err := os.MkdirTemp("", "")
if err != nil {
t.Fatal(err)
}
@ -90,7 +90,7 @@ func TestV1NewFromConfig(t *testing.T) {
{data.Key, clientKey},
}
for _, file := range files {
if err := ioutil.WriteFile(file.name, file.data, 0400); err != nil {
if err := os.WriteFile(file.name, file.data, 0400); err != nil {
t.Fatal(err)
}
}
@ -193,7 +193,7 @@ current-context: default
for _, tt := range tests {
// Use a closure so defer statements trigger between loop iterations.
err := func() error {
tempfile, err := ioutil.TempFile("", "")
tempfile, err := os.CreateTemp("", "")
if err != nil {
return err
}
@ -267,7 +267,7 @@ func NewV1TestServer(s V1Service, cert, key, caCert []byte) (*httptest.Server, e
}
var review authorizationv1.SubjectAccessReview
bodyData, _ := ioutil.ReadAll(r.Body)
bodyData, _ := io.ReadAll(r.Body)
if err := json.Unmarshal(bodyData, &review); err != nil {
http.Error(w, fmt.Sprintf("failed to decode body: %v", err), http.StatusBadRequest)
return
@ -337,7 +337,7 @@ func (m *mockV1Service) HTTPStatusCode() int { return m.statusCode }
// newV1Authorizer creates a temporary kubeconfig file from the provided arguments and attempts to load
// a new WebhookAuthorizer from it.
func newV1Authorizer(callbackURL string, clientCert, clientKey, ca []byte, cacheTime time.Duration, metrics metrics.AuthorizerMetrics, compiler authorizationcel.Compiler, expressions []apiserver.WebhookMatchCondition, authzName string) (*WebhookAuthorizer, error) {
tempfile, err := ioutil.TempFile("", "")
tempfile, err := os.CreateTemp("", "")
if err != nil {
return nil, err
}

View File

@ -22,7 +22,7 @@ import (
"crypto/x509"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"net/url"
@ -47,7 +47,7 @@ import (
)
func TestV1beta1NewFromConfig(t *testing.T) {
dir, err := ioutil.TempDir("", "")
dir, err := os.MkdirTemp("", "")
if err != nil {
t.Fatal(err)
}
@ -72,7 +72,7 @@ func TestV1beta1NewFromConfig(t *testing.T) {
{data.Key, clientKey},
}
for _, file := range files {
if err := ioutil.WriteFile(file.name, file.data, 0400); err != nil {
if err := os.WriteFile(file.name, file.data, 0400); err != nil {
t.Fatal(err)
}
}
@ -175,7 +175,7 @@ current-context: default
for _, tt := range tests {
// Use a closure so defer statements trigger between loop iterations.
err := func() error {
tempfile, err := ioutil.TempFile("", "")
tempfile, err := os.CreateTemp("", "")
if err != nil {
return err
}
@ -249,7 +249,7 @@ func NewV1beta1TestServer(s V1beta1Service, cert, key, caCert []byte) (*httptest
}
var review authorizationv1beta1.SubjectAccessReview
bodyData, _ := ioutil.ReadAll(r.Body)
bodyData, _ := io.ReadAll(r.Body)
if err := json.Unmarshal(bodyData, &review); err != nil {
http.Error(w, fmt.Sprintf("failed to decode body: %v", err), http.StatusBadRequest)
return
@ -312,7 +312,7 @@ func (m *mockV1beta1Service) HTTPStatusCode() int { return m.statusCode }
// newV1beta1Authorizer creates a temporary kubeconfig file from the provided arguments and attempts to load
// a new WebhookAuthorizer from it.
func newV1beta1Authorizer(callbackURL string, clientCert, clientKey, ca []byte, cacheTime time.Duration) (*WebhookAuthorizer, error) {
tempfile, err := ioutil.TempFile("", "")
tempfile, err := os.CreateTemp("", "")
if err != nil {
return nil, err
}