github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/tequilapi/endpoints/sessions_test.go (about)

     1  /*
     2   * Copyright (C) 2018 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 endpoints
    19  
    20  import (
    21  	"encoding/json"
    22  	"errors"
    23  	"net/http"
    24  	"net/http/httptest"
    25  	"testing"
    26  	"time"
    27  
    28  	"github.com/mysteriumnetwork/go-rest/apierror"
    29  	"github.com/mysteriumnetwork/node/tequilapi/contract"
    30  	"github.com/stretchr/testify/assert"
    31  
    32  	"github.com/mysteriumnetwork/node/consumer/session"
    33  	"github.com/mysteriumnetwork/node/identity"
    34  	node_session "github.com/mysteriumnetwork/node/session"
    35  )
    36  
    37  var (
    38  	connectionSessionMock = session.History{
    39  		SessionID:       node_session.ID("ID"),
    40  		ConsumerID:      identity.FromAddress("consumerID"),
    41  		HermesID:        "0x000000000000000000000000000000000000000C",
    42  		ProviderID:      identity.FromAddress("providerID"),
    43  		ServiceType:     "serviceType",
    44  		ConsumerCountry: "ConsumerCountry",
    45  		ProviderCountry: "ProviderCountry",
    46  		IPType:          "residential",
    47  		Started:         time.Date(2010, time.January, 1, 12, 00, 0, 700000000, time.UTC),
    48  		Updated:         time.Date(2010, time.January, 1, 12, 00, 55, 800000000, time.UTC),
    49  		DataSent:        10,
    50  		DataReceived:    10,
    51  	}
    52  	sessionsMock = []session.History{
    53  		connectionSessionMock,
    54  	}
    55  	sessionStatsMock = session.Stats{
    56  		Count: 1,
    57  	}
    58  	sessionStatsByDayMock = map[time.Time]session.Stats{
    59  		connectionSessionMock.Started: sessionStatsMock,
    60  	}
    61  )
    62  
    63  func Test_SessionsEndpoint_SessionToDto(t *testing.T) {
    64  	sessionDTO := contract.NewSessionDTO(connectionSessionMock)
    65  	assert.Equal(t, "2010-01-01T12:00:00Z", sessionDTO.CreatedAt)
    66  	assert.Equal(t, string(connectionSessionMock.SessionID), sessionDTO.ID)
    67  	assert.Equal(t, connectionSessionMock.ConsumerID.Address, sessionDTO.ConsumerID)
    68  	assert.Equal(t, connectionSessionMock.HermesID, sessionDTO.HermesID)
    69  	assert.Equal(t, connectionSessionMock.ProviderID.Address, sessionDTO.ProviderID)
    70  	assert.Equal(t, connectionSessionMock.ServiceType, sessionDTO.ServiceType)
    71  	assert.Equal(t, connectionSessionMock.ConsumerCountry, sessionDTO.ConsumerCountry)
    72  	assert.Equal(t, connectionSessionMock.ProviderCountry, sessionDTO.ProviderCountry)
    73  	assert.Equal(t, connectionSessionMock.DataReceived, sessionDTO.BytesReceived)
    74  	assert.Equal(t, connectionSessionMock.DataSent, sessionDTO.BytesSent)
    75  	assert.Equal(t, 55, int(sessionDTO.Duration))
    76  	assert.Equal(t, connectionSessionMock.Status, sessionDTO.Status)
    77  	assert.Equal(t, connectionSessionMock.IPType, sessionDTO.IPType)
    78  }
    79  
    80  func Test_SessionsEndpoint_List(t *testing.T) {
    81  	url := "/sessions"
    82  	req, err := http.NewRequest(
    83  		http.MethodGet,
    84  		url,
    85  		nil,
    86  	)
    87  	assert.Nil(t, err)
    88  
    89  	ssm := &sessionStorageMock{
    90  		sessionsToReturn: sessionsMock,
    91  	}
    92  
    93  	resp := httptest.NewRecorder()
    94  	handlerFunc := NewSessionsEndpoint(ssm).List
    95  
    96  	g := summonTestGin()
    97  	g.GET(url, handlerFunc)
    98  	g.ServeHTTP(resp, req)
    99  
   100  	parsedResponse := contract.SessionListResponse{}
   101  	err = json.Unmarshal(resp.Body.Bytes(), &parsedResponse)
   102  	assert.Nil(t, err)
   103  	assert.Equal(t, http.StatusOK, resp.Code)
   104  	assert.EqualValues(
   105  		t,
   106  		contract.SessionListResponse{
   107  			Items: []contract.SessionDTO{
   108  				contract.NewSessionDTO(connectionSessionMock),
   109  			},
   110  			PageableDTO: contract.PageableDTO{
   111  				Page:       1,
   112  				PageSize:   50,
   113  				TotalItems: 1,
   114  				TotalPages: 1,
   115  			},
   116  		},
   117  		parsedResponse,
   118  	)
   119  	assert.Equal(t, session.NewFilter(), ssm.calledWithFilter)
   120  }
   121  
   122  func Test_SessionsEndpoint_ListRespectsFilters(t *testing.T) {
   123  	path := "/sessions"
   124  	ssm := &sessionStorageMock{
   125  		sessionsToReturn: sessionsMock,
   126  	}
   127  
   128  	// when
   129  	req, _ := http.NewRequest(
   130  		http.MethodGet,
   131  		path+"?date_from=2020-09-19&date_to=2020-09-20&direction=direction&service_type=service_type&status=status",
   132  		nil,
   133  	)
   134  	resp := httptest.NewRecorder()
   135  	g := summonTestGin()
   136  	g.GET(path, NewSessionsEndpoint(ssm).List)
   137  	g.ServeHTTP(resp, req)
   138  
   139  	// then
   140  	assert.Equal(
   141  		t,
   142  		session.NewFilter().
   143  			SetStartedFrom(time.Date(2020, 9, 19, 0, 0, 0, 0, time.UTC)).
   144  			SetStartedTo(time.Date(2020, 9, 20, 23, 59, 59, 0, time.UTC)).
   145  			SetDirection("direction").
   146  			SetServiceType("service_type").
   147  			SetStatus("status"),
   148  		ssm.calledWithFilter,
   149  	)
   150  	assert.Equal(t, http.StatusOK, resp.Code)
   151  }
   152  
   153  func Test_SessionsEndpoint_ListBubblesError(t *testing.T) {
   154  	path := "/sessions"
   155  	req, err := http.NewRequest(
   156  		http.MethodGet,
   157  		path,
   158  		nil,
   159  	)
   160  	assert.Nil(t, err)
   161  
   162  	mockErr := errors.New("something exploded")
   163  	ssm := &sessionStorageMock{
   164  		errToReturn: mockErr,
   165  	}
   166  
   167  	resp := httptest.NewRecorder()
   168  	handlerFunc := NewSessionsEndpoint(ssm).List
   169  	g := summonTestGin()
   170  	g.GET(path, handlerFunc)
   171  	g.ServeHTTP(resp, req)
   172  
   173  	assert.Equal(t, http.StatusInternalServerError, resp.Code)
   174  	assert.Equal(t, "err_session_list", apierror.Parse(resp.Result()).Err.Code)
   175  }
   176  
   177  func Test_SessionsEndpoint_StatsAggregated(t *testing.T) {
   178  	path := "/sessions/stats-aggregated"
   179  	req, err := http.NewRequest(
   180  		http.MethodGet,
   181  		path,
   182  		nil,
   183  	)
   184  	assert.Nil(t, err)
   185  
   186  	ssm := &sessionStorageMock{
   187  		statsToReturn: sessionStatsMock,
   188  	}
   189  
   190  	resp := httptest.NewRecorder()
   191  	handlerFunc := NewSessionsEndpoint(ssm).StatsAggregated
   192  	g := summonTestGin()
   193  	g.GET(path, handlerFunc)
   194  	g.ServeHTTP(resp, req)
   195  
   196  	parsedResponse := contract.SessionStatsAggregatedResponse{}
   197  	err = json.Unmarshal(resp.Body.Bytes(), &parsedResponse)
   198  	assert.Nil(t, err)
   199  	assert.Equal(t, http.StatusOK, resp.Code)
   200  	assert.EqualValues(
   201  		t,
   202  		contract.SessionStatsAggregatedResponse{
   203  			Stats: contract.NewSessionStatsDTO(sessionStatsMock),
   204  		},
   205  		parsedResponse,
   206  	)
   207  	assert.Equal(t, session.NewFilter(), ssm.calledWithFilter)
   208  }
   209  
   210  func Test_SessionsEndpoint_StatsDaily(t *testing.T) {
   211  	path := "/sessions/stats-daily"
   212  	req, err := http.NewRequest(
   213  		http.MethodGet,
   214  		path,
   215  		nil,
   216  	)
   217  	assert.Nil(t, err)
   218  
   219  	ssm := &sessionStorageMock{
   220  		statsToReturn:      sessionStatsMock,
   221  		statsByDayToReturn: sessionStatsByDayMock,
   222  	}
   223  
   224  	resp := httptest.NewRecorder()
   225  	handlerFunc := NewSessionsEndpoint(ssm).StatsDaily
   226  	g := summonTestGin()
   227  	g.GET(path, handlerFunc)
   228  	g.ServeHTTP(resp, req)
   229  
   230  	parsedResponse := contract.SessionStatsDailyResponse{}
   231  	err = json.Unmarshal(resp.Body.Bytes(), &parsedResponse)
   232  	assert.Nil(t, err)
   233  	assert.Equal(t, http.StatusOK, resp.Code)
   234  	assert.EqualValues(
   235  		t,
   236  		contract.SessionStatsDailyResponse{
   237  			Items: map[string]contract.SessionStatsDTO{
   238  				"2010-01-01": contract.NewSessionStatsDTO(sessionStatsMock),
   239  			},
   240  			Stats: contract.NewSessionStatsDTO(sessionStatsMock),
   241  		},
   242  		parsedResponse,
   243  	)
   244  	assert.NotEqual(t, session.NewFilter(), ssm.calledWithFilter)
   245  	assert.Equal(t, time.Now().UTC().Add(-30*24*time.Hour).Day(), ssm.calledWithFilter.StartedFrom.Day())
   246  	assert.Equal(t, time.Now().UTC().Day(), ssm.calledWithFilter.StartedTo.Day())
   247  }
   248  
   249  type sessionStorageMock struct {
   250  	sessionsToReturn   []session.History
   251  	statsToReturn      session.Stats
   252  	statsByDayToReturn map[time.Time]session.Stats
   253  	errToReturn        error
   254  
   255  	calledWithFilter *session.Filter
   256  }
   257  
   258  func (ssm *sessionStorageMock) List(filter *session.Filter) ([]session.History, error) {
   259  	ssm.calledWithFilter = filter
   260  	return ssm.sessionsToReturn, ssm.errToReturn
   261  }
   262  
   263  func (ssm *sessionStorageMock) Stats(filter *session.Filter) (session.Stats, error) {
   264  	ssm.calledWithFilter = filter
   265  	return ssm.statsToReturn, ssm.errToReturn
   266  }
   267  
   268  func (ssm *sessionStorageMock) StatsByDay(filter *session.Filter) (map[time.Time]session.Stats, error) {
   269  	ssm.calledWithFilter = filter
   270  	return ssm.statsByDayToReturn, ssm.errToReturn
   271  }