github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/market/mysterium/mysterium_api_test.go (about)

     1  /*
     2   * Copyright (C) 2017 The "MysteriumNetwork/node" Authors.
     3   *
     4   * This program is free software: you can redistribute it and/or modify
     5   * it under the terms of the GNU General Public License as published by
     6   * the Free Software Foundation, either version 3 of the License, or
     7   * (at your option) any later version.
     8   *
     9   * This program is distributed in the hope that it will be useful,
    10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12   * GNU General Public License for more details.
    13   *
    14   * You should have received a copy of the GNU General Public License
    15   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    16   */
    17  
    18  package mysterium
    19  
    20  import (
    21  	"net"
    22  	"net/http"
    23  	"testing"
    24  	"time"
    25  
    26  	"github.com/mysteriumnetwork/node/requests"
    27  	"github.com/stretchr/testify/assert"
    28  )
    29  
    30  const bindAllAddress = "0.0.0.0"
    31  
    32  func TestHttpTransportDoesntBlockForeverIfServerFailsToSendAnyResponse(t *testing.T) {
    33  
    34  	address, err := createHTTPServer(func(writer http.ResponseWriter, request *http.Request) {
    35  		select {} //infinite loop with no response to client
    36  	})
    37  	assert.NoError(t, err)
    38  
    39  	httpClient := requests.NewHTTPClient(bindAllAddress, 50*time.Millisecond)
    40  	req, err := http.NewRequest(http.MethodGet, "http://"+address+"/", nil)
    41  	assert.NoError(t, err)
    42  
    43  	completed := make(chan error)
    44  	go func() {
    45  		_, err := httpClient.Do(req)
    46  		completed <- err
    47  	}()
    48  
    49  	select {
    50  	case err := <-completed:
    51  		netError, ok := err.(net.Error)
    52  		assert.True(t, ok)
    53  		assert.True(t, netError.Timeout())
    54  	case <-time.After(1000 * time.Millisecond):
    55  		assert.Fail(t, "failed request expected")
    56  	}
    57  }
    58  
    59  func createHTTPServer(handlerFunc http.HandlerFunc) (address string, err error) {
    60  	listener, err := net.Listen("tcp", "localhost:0")
    61  	if err != nil {
    62  		return
    63  	}
    64  
    65  	go http.Serve(listener, handlerFunc)
    66  	return listener.Addr().String(), nil
    67  }