0

1.env

  • python : 3.8.14
  • django version : '4.2.4'

2.Purpose

  • Make sure that the static file is saved
  • Make sure that the static file can be accessed from the web browser

3.Issue

The problem is that after running django server, the static file can be accessed through url, but not in the unitest environment.

For example, suppose a file is stored in the following path

'MAPPER  #<- project dir  
 |-datasets #<-app name
    |-static
       |-datasets
          |-images
             |-Recursion Cellular Image Classification.jpeg

3.1 Access the browser after running the server

  • enter the following path into the browser to confirm that it works well. http://localhost:8000/static/datasets/static/datasets/images/Recursion Cellular Image Classification.jpeg

3.2 unittest

  • get a 404 status code. and cannot get the image file
from django.test import Client
client = Client()
res_redirect = self.client.get(res.url)

4. try

I tried using requests.get , but i didn't work requests.get(http://localhost:8000/static/datasets/static/datasets/images/Recursion Cellular Image Classification.jpeg)

5. Question

SO this is my question, how can i access file through url in unittest env

Soulduck
  • 569
  • 1
  • 6
  • 17

1 Answers1

0

You will need to URL encode to properly handle the spaces in the URL. a [space] character is %20, eg,

requests.get(
    'http://localhost:8000/static/datasets/static/datasets/images/Recursion%20Cellular%20Image%20Classification.jpeg'
)

(Don't forget the quotes)

However, seeing as you are working with a property or field, res.url you'll need to pass it to a function to urlEncode it. As you are already using requests you can use:

#safe argument allows the / and : in http://localhost:80000 to be unencoded
encoded_url = requests.utils.quote(res.url, safe="/:")

requests.get(encoded_url) 
SamSparx
  • 4,629
  • 1
  • 4
  • 16