Home > Blockchain >  `go test` fails because it cannot read files in root dir
`go test` fails because it cannot read files in root dir

Time:07-07

package model is imports package config which reads config.xml in it's init

When running test; I get an error complaining it cannot read the file.

I've checked the file does exists and I can run my application(read the config file)

Does golang test not run in rootdir ? Is there a way I can run this test without too much refactoring?

server git:(main) ➜ go test -v ./model/...
2022/07/06 15:46:21 config.go:72: Reading config file config.yaml
2022/07/06 15:46:21 config.go:75: open config.yaml: no such file or directory
FAIL    github.com/texbazaar/server/model   0.141s
FAIL
server git:(main) ➜

CodePudding user response:

Assume the following file structure:

workspaces
└── gotests
    └── main.go
        packages
        └── read
            └── file_test.go
        testfile
        └── test.txt

file_test.go contents:

package read_test

import (
    "fmt"
    "os"
    "testing"
)

func TestReadFile(t *testing.T) {
    t.Run("I read a file", func(t *testing.T) {
        currentDir, err := os.Getwd()
        if err != nil {
            panic(err)
        }

        executable, err := os.Executable()
        if err != nil {
            panic(err)
        }

        fmt.Printf("Current dir: %v\n", currentDir)
        fmt.Printf("Executable: %v\n", executable)

        bytes, err := os.ReadFile("../../testfile/test.txt")
        if err != nil {
            panic(err)
        }

        fmt.Println(string(bytes))
    })
}

If you run go test ./packages/read -run=TestReadFile -count=1 -v in the same folder as main.go (in my case, /workspaces/gotests), you can expect a log like:

=== RUN   TestReadFile
=== RUN   TestReadFile/I_read_a_file
Current dir: /workspaces/gotests/packages/read
Executable: /tmp/go-build1080340781/b001/read.test
Im some test text.
--- PASS: TestReadFile (0.00s)
    --- PASS: TestReadFile/I_read_a_file (0.00s)
PASS

CodePudding user response:

You should mock opened files to prevent this error. It's bad idea to test your app with existing configuration files. You can create a separate function for reading the file by name and then mock this in your tests. There are a lot of cases to mock this functionality.

  • Related