如何从代码和测试中引用相关文件 [英] how to reference a relative file from code and tests

查看:114
本文介绍了如何从代码和测试中引用相关文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从 patients.go 中引用 patients.json ,这里是文件夹结构:





如果我这样做:

filepath.Abs​​(../../ conf / patients.json)



它适用于 go test ./... ,但是<$ c失败$ c> revel run



如果我这样做:

filepath.Abs​​(conf / patients.json)



恰恰相反(狂欢很好,但测试失败) / p>

有没有一种方法可以正确地引用该文件,以便它可以用于测试和正常程序运行?

解决方案

相对路径总是被解释/解析为基本路径: current 工作目录 - 因此它会一直有它的限制。



如果你总是照顾正确的工作目录,你可以继续使用相对路径。

我建议不要依赖工作目录,而要显式指定基本路径。这可能有一个硬编码在你的应用程序(也可能是工作目录)的默认值,你应该提供几种方法来覆盖它的值。



推荐方法来覆盖您的相对路径所解决的基本路径:


  1. 命令行标志(请参阅

  2. 环境变量(参见 os.Getenv()

  3. (修复命名)用户主目录中的配置文件(请参阅 os / user / User

拥有基本路径后,您可以通过加入基本路径和相对路径来获得完整路径。您可以使用 path.Join() filepath.Join() ,例如:

  //从上述解决方案的组合中获取基本路径
base:=/ var / myapp

//相对路径,资源可读写:
relf:=conf / patients.json

//标识资源的完整路径:
full:= filepath.Join(base,relf)// full将为/var/myapp/conf/patients.json


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

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?

解决方案

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"

这篇关于如何从代码和测试中引用相关文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆