github.com/docker/engine@v22.0.0-20211208180946-d456264580cf+incompatible/daemon/trustkey_test.go (about)

     1  package daemon // import "github.com/docker/docker/daemon"
     2  
     3  import (
     4  	"os"
     5  	"path/filepath"
     6  	"testing"
     7  
     8  	"gotest.tools/v3/assert"
     9  	is "gotest.tools/v3/assert/cmp"
    10  	"gotest.tools/v3/fs"
    11  )
    12  
    13  // LoadOrCreateTrustKey
    14  func TestLoadOrCreateTrustKeyInvalidKeyFile(t *testing.T) {
    15  	tmpKeyFolderPath, err := os.MkdirTemp("", "api-trustkey-test")
    16  	assert.NilError(t, err)
    17  	defer os.RemoveAll(tmpKeyFolderPath)
    18  
    19  	tmpKeyFile, err := os.CreateTemp(tmpKeyFolderPath, "keyfile")
    20  	assert.NilError(t, err)
    21  
    22  	_, err = loadOrCreateTrustKey(tmpKeyFile.Name())
    23  	assert.Check(t, is.ErrorContains(err, "Error loading key file"))
    24  }
    25  
    26  func TestLoadOrCreateTrustKeyCreateKeyWhenFileDoesNotExist(t *testing.T) {
    27  	tmpKeyFolderPath := fs.NewDir(t, "api-trustkey-test")
    28  	defer tmpKeyFolderPath.Remove()
    29  
    30  	// Without the need to create the folder hierarchy
    31  	tmpKeyFile := tmpKeyFolderPath.Join("keyfile")
    32  
    33  	key, err := loadOrCreateTrustKey(tmpKeyFile)
    34  	assert.NilError(t, err)
    35  	assert.Check(t, key != nil)
    36  
    37  	_, err = os.Stat(tmpKeyFile)
    38  	assert.NilError(t, err, "key file doesn't exist")
    39  }
    40  
    41  func TestLoadOrCreateTrustKeyCreateKeyWhenDirectoryDoesNotExist(t *testing.T) {
    42  	tmpKeyFolderPath := fs.NewDir(t, "api-trustkey-test")
    43  	defer tmpKeyFolderPath.Remove()
    44  	tmpKeyFile := tmpKeyFolderPath.Join("folder/hierarchy/keyfile")
    45  
    46  	key, err := loadOrCreateTrustKey(tmpKeyFile)
    47  	assert.NilError(t, err)
    48  	assert.Check(t, key != nil)
    49  
    50  	_, err = os.Stat(tmpKeyFile)
    51  	assert.NilError(t, err, "key file doesn't exist")
    52  }
    53  
    54  func TestLoadOrCreateTrustKeyCreateKeyNoPath(t *testing.T) {
    55  	defer os.Remove("keyfile")
    56  	key, err := loadOrCreateTrustKey("keyfile")
    57  	assert.NilError(t, err)
    58  	assert.Check(t, key != nil)
    59  
    60  	_, err = os.Stat("keyfile")
    61  	assert.NilError(t, err, "key file doesn't exist")
    62  }
    63  
    64  func TestLoadOrCreateTrustKeyLoadValidKey(t *testing.T) {
    65  	tmpKeyFile := filepath.Join("testdata", "keyfile")
    66  	key, err := loadOrCreateTrustKey(tmpKeyFile)
    67  	assert.NilError(t, err)
    68  	expected := "AWX2:I27X:WQFX:IOMK:CNAK:O7PW:VYNB:ZLKC:CVAE:YJP2:SI4A:XXAY"
    69  	assert.Check(t, is.Contains(key.String(), expected))
    70  }