github.com/docker/app@v0.9.1-beta3.0.20210611140623-a48f773ab002/internal/packager/packing_test.go (about)

     1  package packager
     2  
     3  import (
     4  	"archive/tar"
     5  	"bytes"
     6  	"fmt"
     7  	"io"
     8  	"strings"
     9  	"testing"
    10  
    11  	"github.com/docker/app/types"
    12  	"github.com/docker/cli/cli/command"
    13  	"gotest.tools/assert"
    14  )
    15  
    16  func TestPackInvocationImageContext(t *testing.T) {
    17  	app, err := types.NewAppFromDefaultFiles("testdata/packages/packing.dockerapp")
    18  	assert.NilError(t, err)
    19  	buf := bytes.NewBuffer(nil)
    20  	dockerCli, err := command.NewDockerCli()
    21  	assert.NilError(t, err)
    22  	assert.NilError(t, PackInvocationImageContext(dockerCli, app, buf))
    23  	assert.NilError(t, hasExpectedFiles(buf, map[string]bool{
    24  		"Dockerfile":                                              true,
    25  		".dockerignore":                                           true,
    26  		"packing.dockerapp/metadata.yml":                          true,
    27  		"packing.dockerapp/docker-compose.yml":                    true,
    28  		"packing.dockerapp/parameters.yml":                        true,
    29  		"packing.dockerapp/config.cfg":                            true,
    30  		"packing.dockerapp/nesteddir/config2.cfg":                 true,
    31  		"packing.dockerapp/nesteddir/nested2/nested3/config3.cfg": true,
    32  	}))
    33  }
    34  
    35  func hasExpectedFiles(r io.Reader, expectedFiles map[string]bool) error {
    36  	tr := tar.NewReader(r)
    37  	var errors []string
    38  	originalExpectedFilesCount := len(expectedFiles)
    39  	for {
    40  		hdr, err := tr.Next()
    41  		if err == io.EOF {
    42  			break // End of archive
    43  		}
    44  		if err != nil {
    45  			return err
    46  		}
    47  		if hdr.Size == 0 {
    48  			errors = append(errors, fmt.Sprintf("content of '%s' is empty", hdr.Name))
    49  		}
    50  		if _, ok := expectedFiles[hdr.Name]; !ok {
    51  			errors = append(errors, fmt.Sprintf("couldn't find file '%s' in the tar archive", hdr.Name))
    52  			continue
    53  		}
    54  		delete(expectedFiles, hdr.Name)
    55  	}
    56  	if len(expectedFiles) != 0 {
    57  		errors = append(errors, fmt.Sprintf("number of expected files is in archive is '%d', but just '%d' were found",
    58  			originalExpectedFilesCount, originalExpectedFilesCount-len(expectedFiles)))
    59  		for k := range expectedFiles {
    60  			errors = append(errors, fmt.Sprintf("expected file '%s' not found", k))
    61  		}
    62  	}
    63  	if len(errors) != 0 {
    64  		return fmt.Errorf("%s", strings.Join(errors, "\n"))
    65  	}
    66  	return nil
    67  }