-
Notifications
You must be signed in to change notification settings - Fork 23
Description
Hello!
Thank you for providing such comprehensive courses in Go! I have learnt a lot while coding along on Udemy.
Issue
I wanted to raise an issue with testing UploadFiles method on Windows.
In the original test, the successfully uploaded files are intended to be cleaned up, but it is offered to ignore the result of calling os.Remove():
if !e.errorExpected {
if _, err := os.Stat(fmt.Sprintf("./testdata/uploads/%s", uploadedFiles[0].NewFileName)); os.IsNotExist(err) {
t.Errorf("%s: expected file to exist: %s", e.name, err.Error())
}
// clean up
_ = os.Remove(fmt.Sprintf("./testdata/uploads/%s", uploadedFiles[0].NewFileName))
}Error
However, when executing this test on a Windows system, the uploaded files do not get removed. When allowing to populate the result with an err variable, we can get a following error:
tools_test.go:133: failed to remove file img.png, remove ./testdata/uploads/img.png: The process cannot access the file because it is being used by another process.Possible solution
I tried several things, such as adding sleep time hoping that it will allow for the system to release the files, removing uploaded files after the test has run, creating a temp folder and removing the entire folder after the test has run, and a couple of other things. All of those were underwhelming or did not work at all.
After some googling, I was able to come to a solution that looks like this:
if !entry.errorExpected {
if _, err := os.Stat(fmt.Sprintf("./testdata/uploads/%s", uploadedFiles[0].NewFileName)); os.IsNotExist(err) {
t.Errorf("expected file to exist: %s", err.Error())
}
// Forces Go runtime to release unused resources, this solves file lock issue on Windows
runtime.GC()
// Clean up
err = os.Remove(fmt.Sprintf("./testdata/uploads/%s", uploadedFiles[0].NewFileName))
if err != nil {
t.Errorf("failed to remove file %s, %+v", uploadedFiles[0].NewFileName, err)
}
}Here, I am using runtime package and GC() method that forces GO runtime to release unused resources.
Here is a brief description of the method:
runtime.GC(): Runs a garbage collection and blocks the caller until the garbage collection is complete. It may also block the entire program.
The solution works, yet I would like to hear your opinion on both the issue and the solution that worked for me.
Thank you for your time!