github.com/haalcala/mattermost-server-change-repo/v5@v5.33.2/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  	}
    32  	return data.Bytes(), nil
    33  }
    34  
    35  // GetInterface returns the best match of an interface that might be listening on a given port.
    36  // This is helpful when a test is being run in a CI environment under docker.
    37  func GetInterface(port int) string {
    38  	dial := func(iface string, port int) bool {
    39  		c, err := net.DialTimeout("tcp", iface+":"+strconv.Itoa(port), time.Second)
    40  		if err != nil {
    41  			return false
    42  		}
    43  		c.Close()
    44  		return true
    45  	}
    46  	// First, we check dockerhost
    47  	iface := "dockerhost"
    48  	if ok := dial(iface, port); ok {
    49  		return iface
    50  	}
    51  	// If not, we check localhost
    52  	iface = "localhost"
    53  	if ok := dial(iface, port); ok {
    54  		return iface
    55  	}
    56  	// If nothing works, we just attempt to use a hack and get the interface IP.
    57  	// https://stackoverflow.com/a/37212665/4962526.
    58  	cmdStr := ""
    59  	switch runtime.GOOS {
    60  	// Using ip address for Linux, ifconfig for Darwin.
    61  	case "linux":
    62  		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`
    63  	case "darwin":
    64  		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`
    65  	default:
    66  		return ""
    67  	}
    68  	cmd := exec.Command("bash", "-c", cmdStr)
    69  	out, err := cmd.CombinedOutput()
    70  	if err != nil {
    71  		return ""
    72  	}
    73  	return string(out)
    74  }