-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_test.go
446 lines (361 loc) · 11.8 KB
/
main_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"os"
"strings"
"testing"
"github.com/MajotraderLucky/MarketRepository/initlog"
"github.com/MajotraderLucky/MarketRepository/klinesdata"
"github.com/MajotraderLucky/MarketRepository/orderinfolog"
"github.com/MajotraderLucky/MarketRepository/positionlog"
"github.com/MajotraderLucky/MarketRepository/tradinglog"
"github.com/MajotraderLucky/Utils/logger"
"github.com/adshao/go-binance/v2"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
func TestCheckFilesExist(t *testing.T) {
// Perform the CheckFilesExist() function test
result := initlog.CheckFilesExist()
// Check that the function returns true
assert.True(t, result)
}
func TestCreateLogsDir(t *testing.T) {
logger := logger.Logger{}
err := logger.CreateLogsDir()
if err != nil {
t.Errorf("Expected no error, but got: %v", err)
}
// Check that the "logs" directory was created
_, err = os.Stat("logs")
if os.IsNotExist(err) {
t.Error("Expected 'logs' directory to be created, but it doesn't exist")
}
}
func TestOpenLogFile(t *testing.T) {
logger := logger.Logger{}
err := logger.OpenLogFile()
if err != nil {
t.Errorf("Expected no error, but got: %v", err)
}
// Check that the log file was created
_, err = os.Stat("logs/log.txt")
if os.IsNotExist(err) {
t.Error("Expected 'logs/log.txt' file to be created, but it doesn't exist")
}
}
func TestSetLogger(t *testing.T) {
// Create a temporary file for testing
file, err := os.Create("test.log")
if err != nil {
t.Fatalf("Failed to create log file: %v", err)
}
defer file.Close()
logger := logger.Logger{}
logger.SetLogger()
// Redirect log output to the specified file
log.SetOutput(file)
// Check that the log output is indeed redirected to the specified file
log.Println("This is a test log message")
// Reed the contents of the log file
contents, err := os.ReadFile("test.log")
if err != nil {
t.Fatalf("Failed to read log file: %v", err)
}
// Check that the log message is present in the file
if !strings.Contains(string(contents), "This is a test log message") {
t.Errorf("Expected log message not found in log file")
}
}
// Testing WritePositionsToFile with empty data and verifying file creation behavior in case of an error.
func TestWritePositionsToFile(t *testing.T) {
data := positionlog.AutoGeneratedPos{}
err := positionlog.WritePositionsToFile(data)
if err == nil {
t.Fatal("Expected an error when calling WritePositionsToFile with empty data, got no error")
}
data = positionlog.AutoGeneratedPos{
Positions: []struct {
Isolated bool `json:"isolated"`
Leverage string `json:"leverage"`
InitialMargin string `json:"initialMargin"`
MaintMargin string `json:"maintMargin"`
OpenOrderInitialMargin string `json:"openOrderInitialMargin"`
PositionInitialMargin string `json:"positionInitialMargin"`
Symbol string `json:"symbol"`
UnrealizedProfit string `json:"unrealizedProfit"`
EntryPrice string `json:"entryPrice"`
MaxNotional string `json:"maxNotional"`
PositionSide string `json:"positionSide"`
PositionAmt string `json:"positionAmt"`
Notional string `json:"notional"`
IsolatedWallet string `json:"isolatedWallet"`
UpdateTime int64 `json:"updateTime"`
}{
{
Symbol: "ETHUSDT",
},
},
}
err = positionlog.WritePositionsToFile(data)
if err == nil {
t.Fatal("Expected an error when calling WritePositionsToFile with data without BTCUSDT position, got no error")
}
}
// Create a mock for futuresClient with a predictable response
type MockFuturesClient struct {
mock.Mock
}
func (m *MockFuturesClient) NewKlinesService() klinesdata.KlinesService {
args := m.Called()
return args.Get(0).(klinesdata.KlinesService)
}
type MockKlinesService struct {
mock.Mock
}
func (m *MockKlinesService) Symbol(symbol string) klinesdata.KlinesService {
m.Called(symbol)
return m
}
func (m *MockKlinesService) Interval(interval string) klinesdata.KlinesService {
m.Called(interval)
return m
}
func (m *MockKlinesService) Do(ctx context.Context, opts ...klinesdata.RequestOption) ([]*klinesdata.Kline, error) {
args := m.Called(ctx)
return args.Get(0).([]*klinesdata.Kline), args.Error(1)
}
func TestFindMinMaxInfo2(t *testing.T) {
mockClient := new(MockFuturesClient)
expectedKlines := []*klinesdata.Kline{
{
High: "12000",
Low: "9000",
},
}
mockService := new(MockKlinesService)
// Mock function calls
mockClient.On("NewKlinesService").Return(mockService)
mockService.On("Symbol", "BTCUSDT").Return(mockService)
mockService.On("Interval", "15m").Return(mockService)
mockService.On("Do", mock.Anything).Return(expectedKlines, nil)
max, min, err := klinesdata.FindMinMaxInfoTest(mockClient)
// Verification assertions
assert.NoError(t, err)
assert.Equal(t, float64(12000), max)
assert.Equal(t, float64(9000), min)
// Check that the functions were called
mockClient.AssertCalled(t, "NewKlinesService")
mockService.AssertCalled(t, "Symbol", "BTCUSDT")
mockService.AssertCalled(t, "Interval", "15m")
mockService.AssertCalled(t, "Do", mock.Anything)
}
// Define the testLogger type
type testLogger struct {
messages []string
}
func (tl *testLogger) Println(v ...interface{}) {
message := fmt.Sprint(v...)
tl.messages = append(tl.messages, message)
}
func (tl *testLogger) Fatalf(format string, v ...interface{}) {
message := fmt.Sprintf(format, v...)
tl.messages = append(tl.messages, message)
panic(message)
}
func TestFindPriceCorridor_NormalValues(t *testing.T) {
// Arrange
mockFindMinMaxInfo := func() (float64, float64, error) {
return 20, 10, nil
}
mockLogger := &MockLogger{t: t}
// Act
priceCorridor, err := klinesdata.FindPriceCorridorTest(mockLogger, mockFindMinMaxInfo)
// Assert
assert.NoError(t, err)
assert.Equal(t, 50.0, priceCorridor)
}
type MockLogger struct {
t *testing.T
}
func (m *MockLogger) Println(v ...interface{}) {
m.t.Logf("Println called: %v", v)
}
func (m *MockLogger) Fatalf(format string, v ...interface{}) {
m.t.Logf("Fatalf called: format=%s, v=%v", format, v)
}
func TestCleanLogCountLines(t *testing.T) {
l := &logger.Logger{}
_ = l.CreateLogsDir()
_ = l.OpenLogFile()
l.SetLogger()
// Записываем строки в лог с использованием log.Printf
for i := 1; i <= 200; i++ {
log.Printf("Log Line %d", i)
}
n := 100
l.CleanLogCountLines(n)
// Проверьте, что файл журнала содержит n строк
data, err := os.ReadFile("logs/log.txt")
if err != nil {
t.Errorf("Failed to read log file: %s", err.Error())
}
lines := strings.Split(strings.TrimSuffix(string(data), "\n"), "\n")
if len(lines) != n {
t.Errorf("Expected logFile to contain %d lines but got %d lines", n, len(lines))
}
for i, line := range lines {
if line == "" {
continue
}
expectedSubString := fmt.Sprintf("Log Line %d", i+102)
if !strings.Contains(line, expectedSubString) {
t.Errorf("Expected line to contain '%s', got '%s'", expectedSubString, line)
}
}
}
func TestIsCorridorHigher(t *testing.T) {
finder := &klinesdata.MockCorridorFinder{Corridor: 20.0, Err: nil}
checker := &klinesdata.CorridorChecker{Finder: finder}
isHigher, err := checker.IsCorridorHigherTest(8)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if isHigher != true {
t.Errorf("expected true, but got %v", isHigher)
}
}
// Test for the IsAskPriceHigherThanLongFibRetLogTest function
type PriceGetterMock struct {
DataFunc func() (string, string, error)
}
func (pg *PriceGetterMock) GetDebthData() (string, string, error) {
return pg.DataFunc()
}
type FibLevelCalculatorMock struct {
FibFunc func() ([]float64, error)
}
func (flc *FibLevelCalculatorMock) GetFibonacciLevelsReturns() ([]float64, error) {
return flc.FibFunc()
}
func TestIsAskPriceHigherThanLongFibRetLogTest(t *testing.T) {
pc := &klinesdata.PriceChecker{
PGetter: &PriceGetterMock{DataFunc: func() (string, string, error) {
// Return the data you want to use for the test
return "100", "", nil
}},
FLCalculator: &FibLevelCalculatorMock{FibFunc: func() ([]float64, error) {
// Return the data you want to use for the test
return []float64{80, 70, 60, 50, 40}, nil
}},
}
res, ok := pc.IsAskPriceHigherThanLongFibRetLogTest()
if !ok {
t.Fatalf("Expected true, got false")
}
expectedRes := "LongFib236"
if res != expectedRes {
t.Fatalf("Unexpected result. Expected %v, got %v", expectedRes, res)
}
}
// -----------------------------------------------------------
type OpenOrder struct {
OrderID string
Symbol string
}
type OrderInfoLogger interface {
GetOpenOrders() ([]OpenOrder, error)
}
type MockOrderInfoLogger struct {
ShouldFail bool
orders []OpenOrder
}
func (m *MockOrderInfoLogger) GetOpenOrders() ([]OpenOrder, error) {
if m.ShouldFail {
return nil, errors.New("mock error")
}
return []OpenOrder{
{OrderID: "12345", Symbol: "BTCUSDT"},
}, nil
}
func TestSomethingWithOpenOrder(t *testing.T) {
var order OpenOrder
order.OrderID = "12345"
order.Symbol = "BTCUSDT"
mockLogger := &MockOrderInfoLogger{}
orders, err := mockLogger.GetOpenOrders()
if err != nil {
t.Fatalf("Got unexpected error: %s", err.Error())
}
if len(orders) == 0 || orders[0].OrderID != order.OrderID || orders[0].Symbol != order.Symbol {
t.Fatalf("The order is not as expected: %#v", orders)
}
}
// GetOpenOrdersInfoJsonTest gets open order info and write it as JSON to the specified file
func GetOpenOrdersInfoJsonTest(svc OrderInfoLogger, filename string) error {
orders, err := svc.GetOpenOrders()
if err != nil {
return err
}
data, err := json.Marshal(orders)
if err != nil {
return err
}
return os.WriteFile(filename, data, 0644)
}
// ------------------------------------------------------
type MockListOpenOrdersService struct {
mock.Mock
}
func (service *MockListOpenOrdersService) Do(ctx context.Context, opts ...binance.RequestOption) (res []*binance.Order, err error) {
args := service.Called()
return nil, args.Error(0) // assuming we're returning an error
}
type MockBinanceService struct {
mock.Mock
}
func (m *MockBinanceService) NewListOpenOrdersService() orderinfolog.ListOpenOrdersService {
args := m.Called()
return args.Get(0).(orderinfolog.ListOpenOrdersService)
}
func TestCheckIfOpenOrdersExist_Error(t *testing.T) {
expectedError := errors.New("some error")
mockService := new(MockListOpenOrdersService)
mockService.On("Do").Return(nil, expectedError)
mockBinanceService := new(MockBinanceService)
mockBinanceService.On("NewListOpenOrdersService").Return(mockService)
result := orderinfolog.CheckIfOpenOrdersExistTest(mockBinanceService)
if result != false {
t.Errorf("Expected false, but got %v", result)
}
mockBinanceService.AssertExpectations(t)
mockService.AssertExpectations(t)
}
// --------------------------------------------------------------------
func TestInvalidInput(t *testing.T) {
_, err := tradinglog.GetFiboLevelStartTrade()
expectedErr := error(nil)
if err != expectedErr {
t.Errorf("Expected error message '%v', but got '%v'", expectedErr, err)
}
}
func MockGetFiboLevelStartTradeOnce(response string, err error) *tradinglog.TradeLevels {
return &tradinglog.TradeLevels{
Response: response,
Error: err,
}
}
func TestIsStopTradeLevel236MetWithNonStopTrade236Level(t *testing.T) {
// Настраиваем мок так, чтобы вернуть значение, отличное от "stopTrade236"
tradinglog.GetFiboLevelStartTradeOnce = func() *tradinglog.TradeLevels {
return MockGetFiboLevelStartTradeOnce("nonStopTrade236Level", nil)
}
// Проверяем, что IsStopTradeLevel236Met() возвращает false
if tradinglog.IsStopTradeLevel236Met() {
t.Errorf("Expected false for level other than stopTrade236, got true")
}
}