Django - how to change FileField upload_to path during testing

I am writing a test case for a Django model with FileField. I would like to change the boot path so that the tests do not have side effects for the rest of the system.

I tried passing the called ones for upload_to and the fixes that are in the tests:

#models.py upload_path = lambda x, y: 'files' class Model(models.Model): file = models.FileField(upload_to=upload_path) #tests.py test_path = mock.Mock() test_path.return_value = 'files/test' @mock.patch('models.upload_path', new=test_path) class ModelTest(object): ... 

However, this does not work, and I believe the reason is that upload_path is dereferenced by FileField before any test code is run, so it's too late to fix things.

How can I change the test code, what is upload_to? Otherwise, how can the model check if this test is running?

+4
source share
1 answer

I think you're almost there, but in order to get a later estimate that you want, you need to specify file_path as the variable you want to copy, and then use lambda to delay the binding:

 #models.py upload_path = 'files' class Model(models.Model): file = models.FileField(upload_to=lambda x,y: upload_path) #tests.py @mock.patch('models.upload_path', 'files/test') class ModelTest(object): ... 
+4
source

Source: https://habr.com/ru/post/1443930/


All Articles