Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - how to change FileField upload_to path during testing

I am writing a test case for a Django model with a FileField. I'd like to change the upload path to prevent tests from having side effects on the rest of the system.

I have tried passing a callable to upload_to and patching that in 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 doesn't seem to work, and I believe the reason is that upload_path is dereferenced by FileField before any test code gets run, so it's too late to patch things.

How can I have test code change what upload_to is? Failing that, how can a model check if it's being run by a test?

like image 352
dgirardi Avatar asked Oct 06 '22 02:10

dgirardi


1 Answers

I think you're almost there, but to get the late evaluation you want, you need to put file_path in as a variable you want to patch, and then use the lambda to delay 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):
    ...
like image 83
hwjp Avatar answered Oct 10 '22 02:10

hwjp