github.com/tommi2day/gomodules/pwlib@v0.0.0-20230217211148-82cdbcf0a79d/testinit.go (about)

     1  package pwlib
     2  
     3  // https://intellij-support.jetbrains.com/hc/en-us/community/posts/360009685279-Go-test-working-directory-keeps-changing-to-dir-of-the-test-file-instead-of-value-in-template
     4  import (
     5  	"os"
     6  	"path"
     7  	"runtime"
     8  )
     9  
    10  // TestDir working dir for tests
    11  var TestDir string
    12  
    13  // TestData directory for working files
    14  var TestData string
    15  
    16  func init() {
    17  	_, filename, _, _ := runtime.Caller(0)
    18  	dir := path.Dir(filename)
    19  	err := os.Chdir(dir)
    20  	if err != nil {
    21  		panic(err)
    22  	}
    23  	TestDir = dir
    24  	TestData = path.Join(TestDir, "testdata")
    25  	// create data directory and ignore errors
    26  	err = os.Mkdir(TestData, 0750)
    27  	if err != nil && !os.IsExist(err) {
    28  		panic(err)
    29  	}
    30  	println("Work in " + dir)
    31  }