how to reference a relative file from code and tests

有些话、适合烂在心里 提交于 2019-11-26 02:25:29

问题


I need to reference patients.json from patients.go, here\'s the folder structure:

\"enter

If I do:

filepath.Abs(\"../../conf/patients.json\")

it works for go test ./... but fails for revel run

If I do:

filepath.Abs(\"conf/patients.json\")

the exact opposite happens (revel is fine but tests fail).

Is there a way to correctly reference the file so that it works both for tests and normal program run?


回答1:


Relative paths are always interpreted / resolved to a base path: the current or working directory - therefore it will always have its limitations.

If you can live with always taking care of the proper working directory, you may keep using relative paths.

What I would suggest is to not rely on the working directory, but an explicitly specified base path. This may have a default value hard-coded in your application (which may be the working directory as well), and you should provide several ways to override its value.

Recommended ways to override the base path to which your "relative" paths are resolved against:

  1. Command line flag (see flag package)
  2. Environment variable (see os.Getenv())
  3. (Fix named) Config file in user's home directory (see os/user/User and os/user/Current())

Once you have the base path, you can get the full path by joining the base path and the relative path. You may use path.Join() or filepath.Join(), e.g.:

// Get base path, from any or from the combination of the above mentioned solutions
base := "/var/myapp"

// Relative path, resource to read/write from:
relf := "conf/patients.json"

// Full path that identifies the resource:
full := filepath.Join(base, relf) // full will be "/var/myapp/conf/patients.json"



回答2:


I've never used Revel myself but the following looks helpful to me:

http://revel.github.io/docs/godoc/revel.html

  • revel.BasePath
  • revel.AppPath



回答3:


This is not the problem with path, but the problem with your design.

You should design your code more careful.

As far as I can tell, you share same path in your test file and reveal run. I guess that maybe you hard code your json path in your model package which is not suggested.

Better way is

  • model package get json path from global config, or init model with json path like model := NewModel(config_path). so reveal run can init model with any json you want.
  • hard code "../../conf/patients.json" in your xxxx_testing.go


来源:https://stackoverflow.com/questions/31059023/how-to-reference-a-relative-file-from-code-and-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!