stats_test.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. /*
  2. * Copyright (c) 2014, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package psiphon
  20. import (
  21. "encoding/json"
  22. "errors"
  23. "net"
  24. "net/http"
  25. "testing"
  26. "time"
  27. mapset "github.com/deckarep/golang-set"
  28. "github.com/stretchr/testify/suite"
  29. )
  30. var _SERVER_ID = "myserverid"
  31. type StatsTestSuite struct {
  32. suite.Suite
  33. httpClient *http.Client
  34. }
  35. func TestStatsTestSuite(t *testing.T) {
  36. suite.Run(t, new(StatsTestSuite))
  37. }
  38. func (suite *StatsTestSuite) SetupTest() {
  39. Stats_Start()
  40. re := make(Regexps, 0)
  41. suite.httpClient = &http.Client{
  42. Transport: &http.Transport{
  43. Dial: makeStatsDialer(_SERVER_ID, &re),
  44. },
  45. }
  46. }
  47. func (suite *StatsTestSuite) TearDownTest() {
  48. suite.httpClient = nil
  49. Stats_Stop()
  50. }
  51. func makeStatsDialer(serverID string, regexps *Regexps) func(network, addr string) (conn net.Conn, err error) {
  52. return func(network, addr string) (conn net.Conn, err error) {
  53. var subConn net.Conn
  54. switch network {
  55. case "tcp", "tcp4", "tcp6":
  56. tcpAddr, err := net.ResolveTCPAddr(network, addr)
  57. if err != nil {
  58. return nil, err
  59. }
  60. subConn, err = net.DialTCP(network, nil, tcpAddr)
  61. if err != nil {
  62. return nil, err
  63. }
  64. default:
  65. err = errors.New("using an unsupported testing network type")
  66. return
  67. }
  68. conn = NewStatsConn(subConn, serverID, regexps)
  69. err = nil
  70. return
  71. }
  72. }
  73. func (suite *StatsTestSuite) Test_StartStop() {
  74. // Make sure Start and Stop calls don't crash
  75. Stats_Start()
  76. Stats_Start()
  77. Stats_Stop()
  78. Stats_Stop()
  79. Stats_Start()
  80. Stats_Stop()
  81. }
  82. func (suite *StatsTestSuite) Test_NextSendPeriod() {
  83. res1 := NextSendPeriod()
  84. suite.True(res1 > time.Duration(0), "duration should not be zero")
  85. res2 := NextSendPeriod()
  86. suite.NotEqual(res1, res2, "duration should have randomness difference between calls")
  87. }
  88. func (suite *StatsTestSuite) Test_StatsConn() {
  89. resp, err := suite.httpClient.Get("http://example.com/index.html")
  90. suite.Nil(err, "basic HTTP requests should succeed (1)")
  91. resp.Body.Close()
  92. resp, err = suite.httpClient.Get("http://example.org/index.html")
  93. suite.Nil(err, "basic HTTP requests should succeed (1)")
  94. resp.Body.Close()
  95. }
  96. func (suite *StatsTestSuite) Test_GetForServer() {
  97. payload := GetForServer(_SERVER_ID)
  98. suite.Nil(payload, "should get nil stats before any traffic (but not crash)")
  99. resp, err := suite.httpClient.Get("http://example.com/index.html")
  100. suite.Nil(err, "need successful http to proceed with tests")
  101. resp.Body.Close()
  102. // Make sure there aren't stats returned for a bad server ID
  103. payload = GetForServer("INVALID")
  104. suite.Nil(payload, "should get nil stats for invalid server ID")
  105. payload = GetForServer(_SERVER_ID)
  106. suite.NotNil(payload, "should receive valid payload for valid server ID")
  107. payloadJSON, err := json.Marshal(payload)
  108. var parsedJSON interface{}
  109. err = json.Unmarshal(payloadJSON, &parsedJSON)
  110. suite.Nil(err, "payload JSON should parse successfully")
  111. // After we retrieve the stats for a server, they should be cleared out of the tracked stats
  112. payload = GetForServer(_SERVER_ID)
  113. suite.Nil(payload, "after retrieving stats for a server, there should be no more stats (until more data goes through)")
  114. }
  115. func (suite *StatsTestSuite) Test_PutBack() {
  116. resp, err := suite.httpClient.Get("http://example.com/index.html")
  117. suite.Nil(err, "need successful http to proceed with tests")
  118. resp.Body.Close()
  119. payloadToPutBack := GetForServer(_SERVER_ID)
  120. suite.NotNil(payloadToPutBack, "should receive valid payload for valid server ID")
  121. payload := GetForServer(_SERVER_ID)
  122. suite.Nil(payload, "should not be any remaining stats after getting them")
  123. PutBack(_SERVER_ID, payloadToPutBack)
  124. // PutBack is asynchronous, so we'll need to wait a moment for it to do its thing
  125. <-time.After(100 * time.Millisecond)
  126. payload = GetForServer(_SERVER_ID)
  127. suite.NotNil(payload, "stats should be re-added after putting back")
  128. suite.Equal(payload, payloadToPutBack, "stats should be the same as after the first retrieval")
  129. }
  130. func (suite *StatsTestSuite) Test_MakeRegexps() {
  131. pageViewRegexes := []map[string]string{make(map[string]string)}
  132. pageViewRegexes[0]["regex"] = `(^http://[a-z0-9\.]*\.example\.[a-z\.]*)/.*`
  133. pageViewRegexes[0]["replace"] = "$1"
  134. httpsRequestRegexes := []map[string]string{make(map[string]string), make(map[string]string)}
  135. httpsRequestRegexes[0]["regex"] = `^[a-z0-9\.]*\.(example\.com)$`
  136. httpsRequestRegexes[0]["replace"] = "$1"
  137. httpsRequestRegexes[1]["regex"] = `^.*example\.org$`
  138. httpsRequestRegexes[1]["replace"] = "replacement"
  139. regexps := MakeRegexps(pageViewRegexes, httpsRequestRegexes)
  140. suite.NotNil(regexps, "should return a valid object")
  141. suite.Len(*regexps, 2, "should only have processed httpsRequestRegexes")
  142. //
  143. // Test some bad regexps
  144. //
  145. httpsRequestRegexes[0]["regex"] = ""
  146. httpsRequestRegexes[0]["replace"] = "$1"
  147. regexps = MakeRegexps(pageViewRegexes, httpsRequestRegexes)
  148. suite.NotNil(regexps, "should return a valid object")
  149. suite.Len(*regexps, 1, "should have discarded one regexp")
  150. httpsRequestRegexes[0]["regex"] = `^[a-z0-9\.]*\.(example\.com)$`
  151. httpsRequestRegexes[0]["replace"] = ""
  152. regexps = MakeRegexps(pageViewRegexes, httpsRequestRegexes)
  153. suite.NotNil(regexps, "should return a valid object")
  154. suite.Len(*regexps, 1, "should have discarded one regexp")
  155. httpsRequestRegexes[0]["regex"] = `^[a-z0-9\.]*\.(example\.com$` // missing closing paren
  156. httpsRequestRegexes[0]["replace"] = "$1"
  157. regexps = MakeRegexps(pageViewRegexes, httpsRequestRegexes)
  158. suite.NotNil(regexps, "should return a valid object")
  159. suite.Len(*regexps, 1, "should have discarded one regexp")
  160. }
  161. func (suite *StatsTestSuite) Test_Regex() {
  162. // We'll make a new client with actual regexps.
  163. pageViewRegexes := make([]map[string]string, 0)
  164. httpsRequestRegexes := []map[string]string{make(map[string]string), make(map[string]string)}
  165. httpsRequestRegexes[0]["regex"] = `^[a-z0-9\.]*\.(example\.com)$`
  166. httpsRequestRegexes[0]["replace"] = "$1"
  167. httpsRequestRegexes[1]["regex"] = `^.*example\.org$`
  168. httpsRequestRegexes[1]["replace"] = "replacement"
  169. regexps := MakeRegexps(pageViewRegexes, httpsRequestRegexes)
  170. suite.httpClient = &http.Client{
  171. Transport: &http.Transport{
  172. Dial: makeStatsDialer(_SERVER_ID, regexps),
  173. },
  174. }
  175. // No subdomain, so won't match regex
  176. resp, err := suite.httpClient.Get("http://example.com/index.html")
  177. suite.Nil(err)
  178. resp.Body.Close()
  179. // Will match the first regex
  180. resp, err = suite.httpClient.Get("http://www.example.com/index.html")
  181. suite.Nil(err)
  182. resp.Body.Close()
  183. // Will match the second regex
  184. resp, err = suite.httpClient.Get("http://example.org/index.html")
  185. suite.Nil(err)
  186. resp.Body.Close()
  187. payload := GetForServer(_SERVER_ID)
  188. suite.NotNil(payload, "should get stats because we made HTTP reqs")
  189. expectedHostnames := mapset.NewSet()
  190. expectedHostnames.Add("(OTHER)")
  191. expectedHostnames.Add("example.com")
  192. expectedHostnames.Add("replacement")
  193. hostnames := make([]interface{}, 0)
  194. for hostname := range payload.hostnameToStats {
  195. hostnames = append(hostnames, hostname)
  196. }
  197. actualHostnames := mapset.NewSetFromSlice(hostnames)
  198. suite.Equal(expectedHostnames, actualHostnames, "post-regex hostnames should be processed as expecteds")
  199. }
  200. func (suite *StatsTestSuite) Test_recordStat() {
  201. // The normal operation of this function will get exercised during the
  202. // other tests, but there is a code branch that only gets hit when the
  203. // allStats.statsChan is filled. To make sure we fill the channel, we will
  204. // lock the stats access mutex, try to record a bunch of stats, and then
  205. // release it.
  206. allStats.statsMutex.Lock()
  207. stat := statsUpdate{"test", "test", 1, 1}
  208. for i := 0; i < _CHANNEL_CAPACITY*2; i++ {
  209. recordStat(&stat)
  210. }
  211. allStats.statsMutex.Unlock()
  212. }