github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/requests/request_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 requests
    19  
    20  import (
    21  	"bytes"
    22  	"io"
    23  	"net/url"
    24  	"testing"
    25  
    26  	"github.com/mysteriumnetwork/node/identity"
    27  	"github.com/stretchr/testify/assert"
    28  )
    29  
    30  type testPayload struct {
    31  	Value string `json:"value"`
    32  }
    33  
    34  type mockedSigner struct {
    35  	signatureToReturn identity.Signature
    36  }
    37  
    38  var testRequestApiUrl = "http://testUrl"
    39  
    40  func (signer *mockedSigner) Sign(message []byte) (identity.Signature, error) {
    41  	return signer.signatureToReturn, nil
    42  }
    43  
    44  func TestSignatureIsInsertedForSignedPost(t *testing.T) {
    45  
    46  	signer := mockedSigner{identity.SignatureBase64("deadbeef")}
    47  
    48  	req, err := NewSignedPostRequest(testRequestApiUrl, "/post-path", testPayload{"abc"}, &signer)
    49  	assert.NoError(t, err)
    50  	assert.Equal(t, req.Header.Get("Authorization"), "Signature deadbeef")
    51  }
    52  
    53  func TestDoGetContactsPassedValuesForUrl(t *testing.T) {
    54  
    55  	params := url.Values{}
    56  	params["param1"] = []string{"value1"}
    57  	params["param2"] = []string{"value2"}
    58  
    59  	req, err := NewGetRequest(testRequestApiUrl, "get-path", params)
    60  
    61  	assert.NoError(t, err)
    62  	assert.Equal(t, "http://testUrl/get-path?param1=value1&param2=value2", req.URL.String())
    63  
    64  }
    65  
    66  func TestPayloadIsSerializedSuccessfullyForPostMethod(t *testing.T) {
    67  
    68  	req, err := NewPostRequest(testRequestApiUrl, "post-path", testPayload{"abc"})
    69  
    70  	assert.NoError(t, err)
    71  
    72  	encodedBody := bytes.NewBuffer(nil)
    73  	_, err = io.Copy(encodedBody, req.Body)
    74  	assert.NoError(t, err)
    75  
    76  	assert.JSONEq(
    77  		t,
    78  		`{
    79  			"value" : "abc"
    80  		}`,
    81  		encodedBody.String(),
    82  	)
    83  }