github.com/masterhung0112/hk_server/v5@v5.0.0-20220302090640-ec71aef15e1c/utils/testutils/testutils.go (about) 1 // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. 2 // See LICENSE.txt for license information. 3 4 package testutils 5 6 import ( 7 "bytes" 8 "io" 9 "net" 10 "os" 11 "os/exec" 12 "path/filepath" 13 "runtime" 14 "strconv" 15 "time" 16 17 "github.com/masterhung0112/hk_server/v5/utils" 18 19 "github.com/masterhung0112/hk_server/v5/utils/fileutils" 20 ) 21 22 func ReadTestFile(name string) ([]byte, error) { 23 path, _ := fileutils.FindDir("tests") 24 file, err := os.Open(filepath.Join(path, name)) 25 if err != nil { 26 return nil, err 27 } 28 defer file.Close() 29 30 data := &bytes.Buffer{} 31 if _, err := io.Copy(data, file); err != nil { 32 return nil, err 33 } 34 return data.Bytes(), nil 35 } 36 37 // GetInterface returns the best match of an interface that might be listening on a given port. 38 // This is helpful when a test is being run in a CI environment under docker. 39 func GetInterface(port int) string { 40 dial := func(iface string, port int) bool { 41 c, err := net.DialTimeout("tcp", iface+":"+strconv.Itoa(port), time.Second) 42 if err != nil { 43 return false 44 } 45 c.Close() 46 return true 47 } 48 // First, we check dockerhost 49 iface := "dockerhost" 50 if ok := dial(iface, port); ok { 51 return iface 52 } 53 // If not, we check localhost 54 iface = "localhost" 55 if ok := dial(iface, port); ok { 56 return iface 57 } 58 // If nothing works, we just attempt to use a hack and get the interface IP. 59 // https://stackoverflow.com/a/37212665/4962526. 60 cmdStr := "" 61 switch runtime.GOOS { 62 // Using ip address for Linux, ifconfig for Darwin. 63 case "linux": 64 cmdStr = `ip address | grep -E "([0-9]{1,3}\.){3}[0-9]{1,3}" | grep -v 127.0.0.1 | awk '{ print $2 }' | cut -f2 -d: | cut -f1 -d/ | head -n1` 65 case "darwin": 66 cmdStr = `ifconfig | grep -E "([0-9]{1,3}\.){3}[0-9]{1,3}" | grep -v 127.0.0.1 | awk '{ print $2 }' | cut -f2 -d: | head -n1` 67 default: 68 return "" 69 } 70 cmd := exec.Command("bash", "-c", cmdStr) 71 out, err := cmd.CombinedOutput() 72 if err != nil { 73 return "" 74 } 75 return string(out) 76 } 77 78 func ResetLicenseValidator() { 79 utils.LicenseValidator = &utils.LicenseValidatorImpl{} 80 }