github.com/kata-containers/runtime@v0.0.0-20210505125100-04f29832a923/virtcontainers/device/config/config_test.go (about)

     1  // Copyright (c) 2020 Intel Corporation
     2  //
     3  // SPDX-License-Identifier: Apache-2.0
     4  //
     5  
     6  package config
     7  
     8  import (
     9  	"fmt"
    10  	"io/ioutil"
    11  	"os"
    12  	"path/filepath"
    13  	"testing"
    14  
    15  	"github.com/stretchr/testify/assert"
    16  )
    17  
    18  func TestGetBackingFile(t *testing.T) {
    19  	assert := assert.New(t)
    20  
    21  	dir, err := ioutil.TempDir("", "backing")
    22  	assert.NoError(err)
    23  	defer os.RemoveAll(dir)
    24  
    25  	orgGetSysDevPath := getSysDevPath
    26  	getSysDevPath = func(info DeviceInfo) string {
    27  		return dir
    28  	}
    29  	defer func() { getSysDevPath = orgGetSysDevPath }()
    30  
    31  	info := DeviceInfo{}
    32  	path, err := getBackingFile(info)
    33  	assert.Error(err)
    34  	assert.Empty(path)
    35  
    36  	loopDir := filepath.Join(dir, "loop")
    37  	err = os.Mkdir(loopDir, os.FileMode(0755))
    38  	assert.NoError(err)
    39  
    40  	backingFile := "/fake-img"
    41  
    42  	err = ioutil.WriteFile(filepath.Join(loopDir, "backing_file"), []byte(backingFile), os.FileMode(0755))
    43  	assert.NoError(err)
    44  
    45  	path, err = getBackingFile(info)
    46  	assert.NoError(err)
    47  	assert.Equal(backingFile, path)
    48  }
    49  
    50  func TestGetSysDevPathImpl(t *testing.T) {
    51  	assert := assert.New(t)
    52  
    53  	info := DeviceInfo{
    54  		DevType: "",
    55  		Major:   127,
    56  		Minor:   0,
    57  	}
    58  
    59  	path := getSysDevPathImpl(info)
    60  	assert.Empty(path)
    61  
    62  	expectedFormat := fmt.Sprintf("%d:%d", info.Major, info.Minor)
    63  
    64  	info.DevType = "c"
    65  	path = getSysDevPathImpl(info)
    66  	assert.Contains(path, expectedFormat)
    67  	assert.Contains(path, "char")
    68  
    69  	info.DevType = "b"
    70  	path = getSysDevPathImpl(info)
    71  	assert.Contains(path, expectedFormat)
    72  	assert.Contains(path, "block")
    73  }