2

I'm trying to run tests in my FastAPI application and I'm using a static file that contains a JSON with colors. Once I'm running the command 'pytest {path of my test file}' I'm getting the error - No such file or directory.

At first I was running the below line in the main page of the backend side -

app.mount("/static", StaticFiles(directory="static"), name="static")

The application works fine, but the test doesn't.

The main reason is this function:

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

After that, I tried to do two more actions in order to solve it -

  1. Deleted the mount line, and added this path in the function instead:
    with open("../../../static/def_Sys/colors.json") as f:

but the application could not run (this is the relative path from the current script)

  1. Deleted the mount line, and changed to this line -

    with open(os.path.abspath("static\def_Sys\colors.json"),'r') as f:

The application run, but the tests can't find the path to this static file.

Moreover I noticed the tests are not using the same path like the application.

For example: When we run in pytest:
"C:\Users\user\PycharmProjects\application\static\def_Sys\colors.json"
When we run the application:
"C:\Users\user\PycharmProjects\application\app\static\def_Sys\colors.json"

I'm trying to find a solution that will let me run the tests and my application without changing the code between each run.

Tomer S
  • 900
  • 1
  • 10
  • 21

1 Answers1

1

You may look at https://github.com/tiangolo/fastapi/issues/3550 and https://github.com/tiangolo/fastapi/discussions/8748 for a temporary hack.

app.mount('/static', StaticFiles(directory=realpath(f'{realpath(__file__)}/../static')), name='static')

Same applies to templates folder if needed.

vpoulailleau
  • 54
  • 1
  • 4