使用 pytest 时不会加载图像资产

Image assets won't load when using pytest

我正在使用 PySide 开发 GUI,我从这样的图像创建像素图:

PHONE_IMAGE_PATH = "resources/images/phone.png"
self.phone_null = QtGui.QPixmap(GREY_DOT_PATH)
self.phone_null = self.phone_null.scaledToWidth(20)

这在我 运行 程序时完美运行,但是当我用 py.test 测试它时,会发生这种情况:

QPixmap::scaleWidth: Pixmap is a null pixmap

它说像素图是空的,所以似乎图像没有正确加载。

我真的很想测试我的代码,但我在任何地方都找不到关于这个问题的任何信息。有人能解决我的问题吗?

来自维基百科:

By contrast, a relative path starts from some given working directory, avoiding the need to provide the full absolute path. A filename can be considered as a relative path based at the current working directory. If the working directory is not the file's parent directory, a file not found error will result if the file is addressed by its name.

您似乎正在为您的图像资产使用相对路径,因此当您 运行 您的程序时,相对路径是正确的,但我假设您的测试位于与主程序不同的目录中.

您可以通过以下方式获取当前文件位置:__file__
示例:

main_script_dir = os.path.dirname(__file__)
rel_path = "resources/images/phone.png"
PHONE_IMAGE_PATH = os.path.join(main_script_dir, rel_path)