api_test.go 2.49 KB
Newer Older
1
package api
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
)

type MockDB struct {
	mock.Mock
}

18
func (db *MockDB) GetDeposits(limit int, cursor string, sortDirection string) ([]Deposit, string, bool, error) {
19
	args := db.Called(limit, cursor, sortDirection)
20
	return args.Get(0).([]Deposit), args.String(1), args.Bool(2), args.Error(3)
21 22
}

23
func (db *MockDB) GetWithdrawals(limit int, cursor string, sortDirection string, sortBy string) ([]Withdrawal, string, bool, error) {
24
	args := db.Called(limit, cursor, sortDirection, sortBy)
25
	return args.Get(0).([]Withdrawal), args.String(1), args.Bool(2), args.Error(3)
26 27 28 29 30
}

func TestApi(t *testing.T) {
	mockDB := new(MockDB)

31
	mockDeposits := []Deposit{
32 33 34 35 36 37 38 39 40 41 42
		{
			Guid:            "test-guid",
			Amount:          "1000",
			BlockNumber:     123,
			BlockTimestamp:  time.Unix(123456, 0),
			From:            "0x1",
			To:              "0x2",
			TransactionHash: "0x3",
		},
	}

43
	mockWithdrawals := []Withdrawal{
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
		{
			Guid:            "test-guid",
			Amount:          "1000",
			BlockNumber:     123,
			BlockTimestamp:  time.Unix(123456, 0),
			From:            "0x1",
			To:              "0x2",
			TransactionHash: "0x3",
		},
	}

	mockDB.On("GetDeposits", 10, "", "").Return(mockDeposits, "nextCursor", false, nil)

	mockDB.On("GetWithdrawals", 10, "", "", "").Return(mockWithdrawals, "nextCursor", false, nil)

59
	testApi := NewApi(mockDB, mockDB)
60 61 62 63 64 65 66 67

	req, _ := http.NewRequest("GET", "/api/v0/deposits", nil)
	rr := httptest.NewRecorder()
	testApi.Router.ServeHTTP(rr, req)

	assert.Equal(t, http.StatusOK, rr.Code, "status code should be 200")

	// TODO make this type exist
68
	var depositsResponse DepositsResponse
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
	err := json.Unmarshal(rr.Body.Bytes(), &depositsResponse)
	assert.NoError(t, err)

	assert.Equal(t, mockDeposits, depositsResponse.Data)

	req, _ = http.NewRequest("GET", "/api/v0/withdrawals", nil)
	rr = httptest.NewRecorder()
	testApi.Router.ServeHTTP(rr, req)

	assert.Equal(t, http.StatusOK, rr.Code, "status code should be 200")

	// TODO make this type exist
	var withdrawalsResponse WithdrawalsResponse
	err = json
	err = json.Unmarshal(rr.Body.Bytes(), &withdrawalsResponse)
	assert.NoError(t, err)

	// Assert response data
	assert.Equal(t, mockWithdrawals, withdrawalsResponse.Data)

	// Finally, assert that the methods were called with the expected parameters
	mockDB.AssertCalled(t, "GetDeposits", 10, "", "")
	mockDB.AssertCalled(t, "GetWithdrawals", 10, "", "", "")
}