github.com/mattermosttest/mattermost-server/v5@v5.0.0-20200917143240-9dfa12e121f9/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/mattermost/mattermost-server/v5/utils/fileutils" 18 ) 19 20 func ReadTestFile(name string) ([]byte, error) { 21 path, _ := fileutils.FindDir("tests") 22 file, err := os.Open(filepath.Join(path, name)) 23 if err != nil { 24 return nil, err 25 } 26 defer file.Close() 27 28 data := &bytes.Buffer{} 29 if _, err := io.Copy(data, file); err != nil { 30 return nil, err 31 } else { 32 return data.Bytes(), nil 33 } 34 } 35 36 // GetInterface returns the best match of an interface that might be listening on a given port. 37 // This is helpful when a test is being run in a CI environment under docker. 38 func GetInterface(port int) string { 39 dial := func(iface string, port int) bool { 40 c, err := net.DialTimeout("tcp", iface+":"+strconv.Itoa(port), time.Second) 41 if err != nil { 42 return false 43 } 44 c.Close() 45 return true 46 } 47 // First, we check dockerhost 48 iface := "dockerhost" 49 if ok := dial(iface, port); ok { 50 return iface 51 } 52 // If not, we check localhost 53 iface = "localhost" 54 if ok := dial(iface, port); ok { 55 return iface 56 } 57 // If nothing works, we just attempt to use a hack and get the interface IP. 58 // https://stackoverflow.com/a/37212665/4962526. 59 cmdStr := "" 60 switch runtime.GOOS { 61 // Using ip address for Linux, ifconfig for Darwin. 62 case "linux": 63 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` 64 case "darwin": 65 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` 66 default: 67 return "" 68 } 69 cmd := exec.Command("bash", "-c", cmdStr) 70 out, err := cmd.CombinedOutput() 71 if err != nil { 72 return "" 73 } 74 return string(out) 75 }