5

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?

4

1 に答える 1

4

私はあなたがほとんどそこにいると思いますが、必要な遅い評価を取得するには、パッチを適用する変数として file_path を配置し、ラムダを使用してバインディングを遅延させる必要があります。

#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):
    ...
于 2012-11-04T14:09:33.220 に答える