如何在使用Flask测试框架测试Flask REST API时让静态文件工作



我正在用Flask- restx库制作一个Flask REST API。API的一部分也是生成PDF文档的调用。为了生成文档,我使用了static/目录中的一些字体文件和图像。当我运行API时,一切都在工作,但是当我试图从测试中调用相同的调用时,我得到一个错误,在PDF生成中使用的文件无法找到。

OSError: Cannot open resource "static/logo.png"

我猜这是因为运行测试时static文件夹的路径不同。是否有一个很好的方法在测试中使用相同的路径到静态文件,或者需要一些自定义的路径切换逻辑,这取决于运行类型(开发,生产,测试)。

文件夹结构:

/src
/application
/main
app.py
/test
test.py
/static
logo.png

我像这样访问我的应用程序中的资源:

static/logo.png

所以我通过更改测试中的当前工作目录来解决这个问题。跟随这篇文章。所以我实现了这个方法:

from contextlib import contextmanager
@contextmanager
def cwd(path):
old_pwd = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(old_pwd)

然后在测试期间,我在测试期间更改路径:

def simple_test():
# default CWD
with cwd('../../'):
# code inside this block, and only inside this block, is in the new directory
perform_call()
# default CWD

最新更新