Python FastAPI中的测试不';不能使用相对静态路径文件

Python FastAPI中的测试不';不能使用相对静态路径文件,python,json,path,pytest,fastapi,Python,Json,Path,Pytest,Fastapi,我试图在我的FastAPI应用程序中运行测试,我使用的是一个静态文件,其中包含带颜色的JSON。 一旦我运行命令'pytest{path of my test file}'我就得到了错误——没有这样的文件或目录 起初,我在后台主页上运行下面的一行- app.mount("/static", StaticFiles(directory="static"), name="static") 应用程序运行良好,但测试不起作用 主要原因是此功能

我试图在我的FastAPI应用程序中运行测试,我使用的是一个静态文件,其中包含带颜色的JSON。 一旦我运行命令'pytest{path of my test file}'我就得到了错误——没有这样的文件或目录

起初,我在后台主页上运行下面的一行-

app.mount("/static", StaticFiles(directory="static"), name="static")
应用程序运行良好,但测试不起作用

主要原因是此功能:

with open("static/def_Sys/colors.json") as f:
    li = json.load(f)
    colors = [x['color'] for x in li]
    names = [x['label'] for x in li]
for (x, col) in zip(names, colors):
    colors_dict[x.upper()] = col  # save systems (key) and color(value) in dictionary and return it

return colors_dict
在那之后,我试图再做两件事来解决它-

  • 删除了挂载行,并在函数中添加了此路径:
    将open(“../../../static/def_Sys/colors.json”)作为f:
  • 但应用程序无法运行(这是当前脚本的相对路径)

  • 删除了装载行,并更改为此行-

    将open(os.path.abspath(“static\def_Sys\colors.json”),'r')作为f:

  • 应用程序正在运行,但测试找不到此静态文件的路径。

    此外,我注意到测试使用的路径与应用程序不同

    例如: 在pytest中运行时:
    “C:\Users\user\PycharmProjects\application\static\def\u Sys\colors.json”
    运行应用程序时:
    “C:\Users\user\PycharmProjects\application\app\static\def\u Sys\colors.json”

    我试图找到一个解决方案,让我运行测试和应用程序,而不必在每次运行之间更改代码