github.com/containers/podman/v4@v4.9.4/test/utils/common_function_test.go (about)

     1  package utils_test
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"io"
     7  	"os"
     8  	"reflect"
     9  	"strings"
    10  
    11  	. "github.com/containers/podman/v4/test/utils"
    12  	. "github.com/onsi/ginkgo/v2"
    13  	. "github.com/onsi/gomega"
    14  )
    15  
    16  var _ = Describe("Common functions test", func() {
    17  	var defaultOSPath string
    18  	var defaultCgroupPath string
    19  
    20  	BeforeEach(func() {
    21  		defaultOSPath = OSReleasePath
    22  		defaultCgroupPath = ProcessOneCgroupPath
    23  	})
    24  
    25  	AfterEach(func() {
    26  		OSReleasePath = defaultOSPath
    27  		ProcessOneCgroupPath = defaultCgroupPath
    28  	})
    29  
    30  	It("Test CreateTempDirInTempDir", func() {
    31  		tmpDir, _ := CreateTempDirInTempDir()
    32  		_, err := os.Stat(tmpDir)
    33  		Expect(os.IsNotExist(err)).ShouldNot(BeTrue(), "Directory is not created as expect")
    34  	})
    35  
    36  	It("Test SystemExec", func() {
    37  		session := SystemExec(GoechoPath, []string{})
    38  		Expect(session.Command.Process).ShouldNot(BeNil(), "SystemExec cannot start a process")
    39  	})
    40  
    41  	It("Test StringInSlice", func() {
    42  		testSlice := []string{"apple", "peach", "pear"}
    43  		Expect(StringInSlice("apple", testSlice)).To(BeTrue(), "apple should in ['apple', 'peach', 'pear']")
    44  		Expect(StringInSlice("banana", testSlice)).ShouldNot(BeTrue(), "banana should not in ['apple', 'peach', 'pear']")
    45  		Expect(StringInSlice("anything", []string{})).ShouldNot(BeTrue(), "anything should not in empty slice")
    46  	})
    47  
    48  	DescribeTable("Test GetHostDistributionInfo",
    49  		func(path, id, ver string, empty bool) {
    50  			txt := fmt.Sprintf("ID=%s\nVERSION_ID=%s", id, ver)
    51  			if !empty {
    52  				f, _ := os.Create(path)
    53  				_, err := f.WriteString(txt)
    54  				Expect(err).ToNot(HaveOccurred(), "Failed to write data.")
    55  				f.Close()
    56  			}
    57  
    58  			OSReleasePath = path
    59  			host := GetHostDistributionInfo()
    60  			if empty {
    61  				Expect(host).To(Equal(HostOS{}), "HostOs should be empty.")
    62  			} else {
    63  				Expect(host.Distribution).To(Equal(strings.Trim(id, "\"")))
    64  				Expect(host.Version).To(Equal(strings.Trim(ver, "\"")))
    65  			}
    66  		},
    67  		Entry("Configure file is not exist.", "/tmp/nonexistent", "", "", true),
    68  		Entry("Item value with and without \"", "/tmp/os-release.test", "fedora", "\"28\"", false),
    69  		Entry("Item empty with and without \"", "/tmp/os-release.test", "", "\"\"", false),
    70  	)
    71  
    72  	DescribeTable("Test IsKernelNewerThan",
    73  		func(kv string, expect, isNil bool) {
    74  			newer, err := IsKernelNewerThan(kv)
    75  			Expect(newer).To(Equal(expect), "Version compare results is not as expect.")
    76  			Expect(err == nil).To(Equal(isNil), "Error is not as expect.")
    77  		},
    78  		Entry("Invalid kernel version: 0", "0", false, false),
    79  		Entry("Older kernel version:0.0", "0.0", true, true),
    80  		Entry("Newer kernel version: 100.17.14", "100.17.14", false, true),
    81  		Entry("Invalid kernel version: I am not a kernel version", "I am not a kernel version", false, false),
    82  	)
    83  
    84  	DescribeTable("Test TestIsCommandAvailable",
    85  		func(cmd string, expect bool) {
    86  			cmdExist := IsCommandAvailable(cmd)
    87  			Expect(cmdExist).To(Equal(expect))
    88  		},
    89  		Entry("Command exist", GoechoPath, true),
    90  		Entry("Command exist", "Fakecmd", false),
    91  	)
    92  
    93  	It("Test WriteJSONFile", func() {
    94  		type testJSON struct {
    95  			Item1 int
    96  			Item2 []string
    97  		}
    98  		compareData := &testJSON{}
    99  
   100  		testData := &testJSON{
   101  			Item1: 5,
   102  			Item2: []string{"test"},
   103  		}
   104  
   105  		testByte, err := json.Marshal(testData)
   106  		Expect(err).ToNot(HaveOccurred(), "Failed to marshal data.")
   107  
   108  		err = WriteJSONFile(testByte, "/tmp/testJSON")
   109  		Expect(err).ToNot(HaveOccurred(), "Failed to write JSON to file.")
   110  
   111  		read, err := os.Open("/tmp/testJSON")
   112  		Expect(err).ToNot(HaveOccurred(), "Can not find the JSON file after we write it.")
   113  		defer read.Close()
   114  
   115  		bytes, err := io.ReadAll(read)
   116  		Expect(err).ToNot(HaveOccurred())
   117  		err = json.Unmarshal(bytes, compareData)
   118  		Expect(err).ToNot(HaveOccurred())
   119  
   120  		Expect(reflect.DeepEqual(testData, compareData)).To(BeTrue(), "Data changed after we store it to file.")
   121  	})
   122  
   123  	DescribeTable("Test Containerized",
   124  		func(path string, setEnv, createFile, expect bool) {
   125  			if setEnv && (os.Getenv("container") == "") {
   126  				os.Setenv("container", "test")
   127  				defer os.Setenv("container", "")
   128  			}
   129  			if !setEnv && (os.Getenv("container") != "") {
   130  				containerized := os.Getenv("container")
   131  				os.Setenv("container", "")
   132  				defer os.Setenv("container", containerized)
   133  			}
   134  			txt := "1:test:/"
   135  			if expect {
   136  				txt = "2:docker:/"
   137  			}
   138  			if createFile {
   139  				f, _ := os.Create(path)
   140  				_, err := f.WriteString(txt)
   141  				Expect(err).ToNot(HaveOccurred(), "Failed to write data.")
   142  				f.Close()
   143  			}
   144  			ProcessOneCgroupPath = path
   145  			Expect(Containerized()).To(Equal(expect))
   146  		},
   147  		Entry("Set container in env", "", true, false, true),
   148  		Entry("Can not read from file", "/tmp/nonexistent", false, false, false),
   149  		Entry("Docker in cgroup file", "/tmp/cgroup.test", false, true, true),
   150  		Entry("Docker not in cgroup file", "/tmp/cgroup.test", false, true, false),
   151  	)
   152  
   153  	It("Test WriteRSAKeyPair", func() {
   154  		fileName := "/tmp/test_key"
   155  		bitSize := 1024
   156  
   157  		publicKeyFileName, privateKeyFileName, err := WriteRSAKeyPair(fileName, bitSize)
   158  		Expect(err).ToNot(HaveOccurred(), "Failed to write RSA key pair to files.")
   159  
   160  		read, err := os.Open(publicKeyFileName)
   161  		Expect(err).ToNot(HaveOccurred(), "Cannot find the public key file after we write it.")
   162  		defer read.Close()
   163  
   164  		read, err = os.Open(privateKeyFileName)
   165  		Expect(err).ToNot(HaveOccurred(), "Cannot find the private key file after we write it.")
   166  		defer read.Close()
   167  	})
   168  
   169  })