Question

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?

Was it helpful?

Solution

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):
    ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top