Skip to content

Commit

Permalink
test: use T.TempDir to create temporary test directory (thrasher-co…
Browse files Browse the repository at this point in the history
…rp#934)

* test: use `T.TempDir` to create temporary test directory

This commit replaces `ioutil.TempDir` with `t.TempDir` in tests. The
directory created by `t.TempDir` is automatically removed when the test
and all its subtests complete.

Prior to this commit, temporary directory created using `ioutil.TempDir`
needs to be removed manually by calling `os.RemoveAll`, which is omitted
in some tests. The error handling boilerplate e.g.
	defer func() {
		if err := os.RemoveAll(dir); err != nil {
			t.Fatal(err)
		}
	}
is also tedious, but `t.TempDir` handles this for us nicely.

Reference: https://pkg.go.dev/testing#T.TempDir
Signed-off-by: Eng Zer Jun <[email protected]>

* test: fix TestEncryptTwiceReusesSaltButNewCipher on Windows

Signed-off-by: Eng Zer Jun <[email protected]>

* test: fix TestCheckConnection on Windows

Signed-off-by: Eng Zer Jun <[email protected]>

* test: fix TestRPCServer_GetTicker_LastUpdatedNanos on Windows

Signed-off-by: Eng Zer Jun <[email protected]>

* test: cleanup TestGenerateReport

Signed-off-by: Eng Zer Jun <[email protected]>
  • Loading branch information
Juneezee authored Apr 28, 2022
1 parent b87a079 commit 21b3d6a
Show file tree
Hide file tree
Showing 9 changed files with 62 additions and 157 deletions.
13 changes: 2 additions & 11 deletions backtester/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,18 +62,9 @@ func TestLoadConfig(t *testing.T) {
}

func TestReadConfigFromFile(t *testing.T) {
tempDir, err := ioutil.TempDir("", "")
if err != nil {
t.Fatalf("Problem creating temp dir at %s: %s\n", tempDir, err)
}
defer func() {
err = os.RemoveAll(tempDir)
if err != nil {
t.Error(err)
}
}()
tempDir := t.TempDir()
var passFile *os.File
passFile, err = ioutil.TempFile(tempDir, "*.start")
passFile, err := ioutil.TempFile(tempDir, "*.start")
if err != nil {
t.Fatalf("Problem creating temp file at %v: %s\n", passFile, err)
}
Expand Down
37 changes: 12 additions & 25 deletions backtester/report/report_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@ package report

import (
"errors"
"io/ioutil"
"os"
"path/filepath"
"testing"
"time"

Expand All @@ -27,19 +24,13 @@ func TestGenerateReport(t *testing.T) {
e := testExchange
a := asset.Spot
p := currency.NewPair(currency.BTC, currency.USDT)
tempDir, err := ioutil.TempDir("", "")
if err != nil {
t.Fatalf("Problem creating temp dir at %s: %s\n", tempDir, err)
}
defer func(path string) {
err = os.RemoveAll(path)
if err != nil {
t.Error(err)
}
}(tempDir)
d := Data{
Config: &config.Config{},
OutputPath: filepath.Join("..", "results"),
Config: &config.Config{
StrategySettings: config.StrategySettings{
DisableUSDTracking: true,
},
},
OutputPath: t.TempDir(),
TemplatePath: "tpl.gohtml",
OriginalCandles: []*gctkline.Item{
{
Expand Down Expand Up @@ -312,18 +303,14 @@ func TestGenerateReport(t *testing.T) {
},
CurrencyPairStatistics: nil,
WasAnyDataMissing: false,
FundingStatistics: nil,
},
}
d.OutputPath = tempDir
d.Config.StrategySettings.DisableUSDTracking = true
d.Statistics.FundingStatistics = &statistics.FundingStatistics{
Report: &funding.Report{
DisableUSDTracking: true,
FundingStatistics: &statistics.FundingStatistics{
Report: &funding.Report{
DisableUSDTracking: true,
},
},
},
}
err = d.GenerateReport()
if err != nil {
if err := d.GenerateReport(); err != nil {
t.Error(err)
}
}
Expand Down
24 changes: 2 additions & 22 deletions common/file/archive/zip_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,12 @@ package archive
import (
"archive/zip"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"testing"
)

var (
tempDir string
)

func TestMain(m *testing.M) {
var err error
tempDir, err = ioutil.TempDir("", "gct-temp")
if err != nil {
fmt.Printf("failed to create tempDir: %v", err)
os.Exit(1)
}
t := m.Run()
err = os.RemoveAll(tempDir)
if err != nil {
fmt.Printf("Failed to remove tempDir %v", err)
}
os.Exit(t)
}

func TestUnZip(t *testing.T) {
tempDir := t.TempDir()
zipFile := filepath.Join("..", "..", "..", "testdata", "testdata.zip")
files, err := UnZip(zipFile, tempDir)
if err != nil {
Expand All @@ -53,6 +32,7 @@ func TestUnZip(t *testing.T) {
}

func TestZip(t *testing.T) {
tempDir := t.TempDir()
singleFile := filepath.Join("..", "..", "..", "testdata", "configtest.json")
outFile := filepath.Join(tempDir, "out.zip")
err := Zip(singleFile, outFile)
Expand Down
14 changes: 3 additions & 11 deletions common/file/file_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,11 +199,7 @@ func TestWriter(t *testing.T) {
type args struct {
file string
}
tmp, err := ioutil.TempDir("", "")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmp)
tmp := t.TempDir()

testData := `data`

Expand Down Expand Up @@ -269,12 +265,8 @@ func TestWriterNoPermissionFails(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Skip file permissions")
}
temp, err := ioutil.TempDir("", "")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(temp)
err = os.Chmod(temp, 0o555)
temp := t.TempDir()
err := os.Chmod(temp, 0o555)
if err != nil {
t.Fatal(err)
}
Expand Down
30 changes: 12 additions & 18 deletions config/config_encryption_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,11 +139,7 @@ func TestEncryptTwiceReusesSaltButNewCipher(t *testing.T) {
c := &Config{
EncryptConfig: 1,
}
tempDir, err := ioutil.TempDir("", "")
if err != nil {
t.Fatalf("Problem creating temp dir at %s: %s\n", tempDir, err)
}
defer os.RemoveAll(tempDir)
tempDir := t.TempDir()

// Prepare input
passFile, err := ioutil.TempFile(tempDir, "*.pw")
Expand All @@ -161,11 +157,17 @@ func TestEncryptTwiceReusesSaltButNewCipher(t *testing.T) {

// Temporarily replace Stdin with a custom input
oldIn := os.Stdin
defer func() { os.Stdin = oldIn }()
t.Cleanup(func() { os.Stdin = oldIn })
os.Stdin, err = os.Open(passFile.Name())
if err != nil {
t.Fatalf("Problem opening temp file at %s: %s\n", passFile.Name(), err)
}
t.Cleanup(func() {
err = os.Stdin.Close()
if err != nil {
t.Error(err)
}
})

// Save encrypted config
enc1 := filepath.Join(tempDir, "encrypted.dat")
Expand Down Expand Up @@ -203,15 +205,11 @@ func TestSaveAndReopenEncryptedConfig(t *testing.T) {
c := &Config{}
c.Name = "myCustomName"
c.EncryptConfig = 1
tempDir, err := ioutil.TempDir("", "")
if err != nil {
t.Fatalf("Problem creating temp dir at %s: %s\n", tempDir, err)
}
defer os.RemoveAll(tempDir)
tempDir := t.TempDir()

// Save encrypted config
enc := filepath.Join(tempDir, "encrypted.dat")
err = withInteractiveResponse(t, "pass\npass\n", func() error {
err := withInteractiveResponse(t, "pass\npass\n", func() error {
return c.SaveConfigToFile(enc)
})
if err != nil {
Expand Down Expand Up @@ -253,11 +251,7 @@ func setAnswersFile(t *testing.T, answerFile string) func() {

func TestReadConfigWithPrompt(t *testing.T) {
// Prepare temp dir
tempDir, err := ioutil.TempDir("", "")
if err != nil {
t.Fatalf("Problem creating temp dir at %s: %s\n", tempDir, err)
}
defer os.RemoveAll(tempDir)
tempDir := t.TempDir()

// Ensure we'll get the prompt when loading
c := &Config{
Expand All @@ -266,7 +260,7 @@ func TestReadConfigWithPrompt(t *testing.T) {

// Save config
testConfigFile := filepath.Join(tempDir, "config.json")
err = c.SaveConfigToFile(testConfigFile)
err := c.SaveConfigToFile(testConfigFile)
if err != nil {
t.Fatalf("Problem saving config file in %s: %s\n", tempDir, err)
}
Expand Down
6 changes: 1 addition & 5 deletions config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2176,11 +2176,7 @@ func TestMigrateConfig(t *testing.T) {
targetDir string
}

dir, err := ioutil.TempDir("", "")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
dir := t.TempDir()

tests := []struct {
name string
Expand Down
49 changes: 19 additions & 30 deletions engine/database_connection_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,38 +2,27 @@ package engine

import (
"errors"
"io/ioutil"
"log"
"os"
"sync"
"testing"

"github.com/thrasher-corp/gocryptotrader/database"
"github.com/thrasher-corp/gocryptotrader/database/drivers"
)

func CreateDatabase(t *testing.T) string {
func CreateDatabase(t *testing.T) {
t.Helper()
// fun workarounds to globals ruining testing
tmpDir, err := ioutil.TempDir("", "")
if err != nil {
log.Fatal(err)
}
database.DB.DataPath = tmpDir
return tmpDir
}
database.DB.DataPath = t.TempDir()

func Cleanup(tmpDir string) {
if database.DB.IsConnected() {
err := database.DB.CloseConnection()
if err != nil {
log.Fatal(err)
}
err = os.RemoveAll(tmpDir)
if err != nil {
log.Fatal(err)
t.Cleanup(func() {
if database.DB.IsConnected() {
err := database.DB.CloseConnection()
if err != nil {
log.Fatal(err)
}
}
}
})
}

func TestSetupDatabaseConnectionManager(t *testing.T) {
Expand All @@ -52,8 +41,7 @@ func TestSetupDatabaseConnectionManager(t *testing.T) {
}

func TestStartSQLite(t *testing.T) {
tmpDir := CreateDatabase(t)
defer Cleanup(tmpDir)
CreateDatabase(t)
m, err := SetupDatabaseConnectionManager(&database.Config{})
if !errors.Is(err, nil) {
t.Errorf("error '%v', expected '%v'", err, nil)
Expand Down Expand Up @@ -113,8 +101,7 @@ func TestStartPostgres(t *testing.T) {
}

func TestDatabaseConnectionManagerIsRunning(t *testing.T) {
tmpDir := CreateDatabase(t)
defer Cleanup(tmpDir)
CreateDatabase(t)
m, err := SetupDatabaseConnectionManager(&database.Config{
Enabled: true,
Driver: database.DBSQLite,
Expand Down Expand Up @@ -144,8 +131,7 @@ func TestDatabaseConnectionManagerIsRunning(t *testing.T) {
}

func TestDatabaseConnectionManagerStop(t *testing.T) {
tmpDir := CreateDatabase(t)
defer Cleanup(tmpDir)
CreateDatabase(t)
m, err := SetupDatabaseConnectionManager(&database.Config{
Enabled: true,
Driver: database.DBSQLite,
Expand Down Expand Up @@ -181,8 +167,7 @@ func TestDatabaseConnectionManagerStop(t *testing.T) {
}

func TestCheckConnection(t *testing.T) {
tmpDir := CreateDatabase(t)
defer Cleanup(tmpDir)
CreateDatabase(t)
var m *DatabaseConnectionManager
err := m.checkConnection()
if !errors.Is(err, ErrNilSubsystem) {
Expand Down Expand Up @@ -236,11 +221,15 @@ func TestCheckConnection(t *testing.T) {
if !errors.Is(err, database.ErrDatabaseNotConnected) {
t.Errorf("error '%v', expected '%v'", err, database.ErrDatabaseNotConnected)
}

err = m.Stop()
if !errors.Is(err, nil) {
t.Errorf("error '%v', expected '%v'", err, nil)
}
}

func TestGetInstance(t *testing.T) {
tmpDir := CreateDatabase(t)
defer Cleanup(tmpDir)
CreateDatabase(t)
m, err := SetupDatabaseConnectionManager(&database.Config{
Enabled: true,
Driver: database.DBSQLite,
Expand Down
32 changes: 3 additions & 29 deletions engine/engine_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package engine

import (
"errors"
"io/ioutil"
"os"
"testing"
"time"
Expand Down Expand Up @@ -77,16 +76,7 @@ func TestLoadConfigWithSettings(t *testing.T) {

func TestStartStopDoesNotCausePanic(t *testing.T) {
t.Parallel()
tempDir, err := ioutil.TempDir("", "")
if err != nil {
t.Fatalf("Problem creating temp dir at %s: %s\n", tempDir, err)
}
defer func() {
err = os.RemoveAll(tempDir)
if err != nil {
t.Error(err)
}
}()
tempDir := t.TempDir()
botOne, err := NewFromSettings(&Settings{
ConfigFile: config.TestFile,
EnableDryRun: true,
Expand Down Expand Up @@ -116,24 +106,8 @@ func TestStartStopTwoDoesNotCausePanic(t *testing.T) {
if !enableExperimentalTest {
t.Skip("test is functional, however does not need to be included in go test runs")
}
tempDir, err := ioutil.TempDir("", "")
if err != nil {
t.Fatalf("Problem creating temp dir at %s: %s\n", tempDir, err)
}
tempDir2, err := ioutil.TempDir("", "")
if err != nil {
t.Fatalf("Problem creating temp dir at %s: %s\n", tempDir, err)
}
defer func() {
err = os.RemoveAll(tempDir)
if err != nil {
t.Error(err)
}
err = os.RemoveAll(tempDir2)
if err != nil {
t.Error(err)
}
}()
tempDir := t.TempDir()
tempDir2 := t.TempDir()
botOne, err := NewFromSettings(&Settings{
ConfigFile: config.TestFile,
EnableDryRun: true,
Expand Down
Loading

0 comments on commit 21b3d6a

Please sign in to comment.