github.com/turgay/mattermost-server@v5.3.2-0.20181002173352-2945e8a2b0ce+incompatible/utils/utils_test.go (about)

     1  // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
     2  // See License.txt for license information.
     3  
     4  package utils
     5  
     6  import (
     7  	"net/http"
     8  	"testing"
     9  
    10  	"github.com/stretchr/testify/assert"
    11  )
    12  
    13  func TestStringArrayIntersection(t *testing.T) {
    14  	a := []string{
    15  		"abc",
    16  		"def",
    17  		"ghi",
    18  	}
    19  	b := []string{
    20  		"jkl",
    21  	}
    22  	c := []string{
    23  		"def",
    24  	}
    25  
    26  	if len(StringArrayIntersection(a, b)) != 0 {
    27  		t.Fatal("should be 0")
    28  	}
    29  
    30  	if len(StringArrayIntersection(a, c)) != 1 {
    31  		t.Fatal("should be 1")
    32  	}
    33  }
    34  
    35  func TestRemoveDuplicatesFromStringArray(t *testing.T) {
    36  	a := []string{
    37  		"a",
    38  		"b",
    39  		"a",
    40  		"a",
    41  		"b",
    42  		"c",
    43  		"a",
    44  	}
    45  
    46  	if len(RemoveDuplicatesFromStringArray(a)) != 3 {
    47  		t.Fatal("should be 3")
    48  	}
    49  }
    50  
    51  func TestGetIpAddress(t *testing.T) {
    52  	// Test with a single IP in the X-Forwarded-For
    53  	httpRequest1 := http.Request{
    54  		Header: http.Header{
    55  			"X-Forwarded-For": []string{"10.0.0.1"},
    56  			"X-Real-Ip":       []string{"10.1.0.1"},
    57  		},
    58  		RemoteAddr: "10.2.0.1:12345",
    59  	}
    60  
    61  	assert.Equal(t, "10.0.0.1", GetIpAddress(&httpRequest1))
    62  
    63  	// Test with multiple IPs in the X-Forwarded-For
    64  	httpRequest2 := http.Request{
    65  		Header: http.Header{
    66  			"X-Forwarded-For": []string{"10.0.0.1,  10.0.0.2, 10.0.0.3"},
    67  			"X-Real-Ip":       []string{"10.1.0.1"},
    68  		},
    69  		RemoteAddr: "10.2.0.1:12345",
    70  	}
    71  
    72  	assert.Equal(t, "10.0.0.1", GetIpAddress(&httpRequest2))
    73  
    74  	// Test with an empty X-Forwarded-For
    75  	httpRequest3 := http.Request{
    76  		Header: http.Header{
    77  			"X-Forwarded-For": []string{""},
    78  			"X-Real-Ip":       []string{"10.1.0.1"},
    79  		},
    80  		RemoteAddr: "10.2.0.1:12345",
    81  	}
    82  
    83  	assert.Equal(t, "10.1.0.1", GetIpAddress(&httpRequest3))
    84  
    85  	// Test without an X-Fowarded-For
    86  	httpRequest4 := http.Request{
    87  		Header: http.Header{
    88  			"X-Real-Ip": []string{"10.1.0.1"},
    89  		},
    90  		RemoteAddr: "10.2.0.1:12345",
    91  	}
    92  
    93  	assert.Equal(t, "10.1.0.1", GetIpAddress(&httpRequest4))
    94  
    95  	// Test without any headers
    96  	httpRequest5 := http.Request{
    97  		RemoteAddr: "10.2.0.1:12345",
    98  	}
    99  
   100  	assert.Equal(t, "10.2.0.1", GetIpAddress(&httpRequest5))
   101  }