sigs.k8s.io/release-sdk@v0.11.1-0.20240417074027-8061fb5e4952/test/integration/container_registry.go (about)

     1  /*
     2  Copyright 2022 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package integration
    18  
    19  import (
    20  	"os"
    21  	"path/filepath"
    22  	"testing"
    23  
    24  	"github.com/stretchr/testify/require"
    25  
    26  	"sigs.k8s.io/release-utils/command"
    27  )
    28  
    29  const (
    30  	dockerfile = `
    31  FROM scratch
    32  CMD [""]
    33  `
    34  
    35  	dockerCommand  = "docker"
    36  	dockerfileName = "Dockerfile"
    37  
    38  	registryImage         = "registry:2"
    39  	registryContainerName = "k8s-registry"
    40  )
    41  
    42  type dockerRegistry struct {
    43  	ImageName      string
    44  	DockerfilePath string
    45  }
    46  
    47  func runDockerRegistryWithDummyImage(t *testing.T, imageName string) *dockerRegistry {
    48  	// Setup the Docker Registry
    49  	cmd := command.New(dockerCommand, "run", "--detach", "--network", "host",
    50  		"--name", registryContainerName, registryImage)
    51  	err := cmd.RunSuccess()
    52  	require.Nil(t, err)
    53  
    54  	// Setup the temp dir
    55  	tempDir, err := os.MkdirTemp("", "k8s-test-img-")
    56  	require.Nil(t, err)
    57  
    58  	// Add the image
    59  	require.Nil(t, os.WriteFile(
    60  		filepath.Join(tempDir, dockerfileName),
    61  		[]byte(dockerfile),
    62  		os.FileMode(0o644),
    63  	))
    64  
    65  	// Build the image
    66  	cmd = command.New(dockerCommand, "build", "--tag", imageName, tempDir)
    67  	err = cmd.RunSuccess()
    68  	require.Nil(t, err)
    69  
    70  	// Push the image
    71  	cmd = command.New(dockerCommand, "push", imageName)
    72  	err = cmd.RunSuccess()
    73  	require.Nil(t, err)
    74  
    75  	// After the image is pushed, we don't need the Dockerfile any longer
    76  	require.Nil(t, os.RemoveAll(tempDir))
    77  
    78  	return &dockerRegistry{
    79  		ImageName:      imageName,
    80  		DockerfilePath: tempDir,
    81  	}
    82  }
    83  
    84  func deleteRegistryContainer(t *testing.T) {
    85  	cmd := command.New(dockerCommand, "rm", "-f", registryContainerName)
    86  	err := cmd.RunSuccess()
    87  	require.Nil(t, err)
    88  }