擅长:python、mysql、java
<p>正如@schillingt在评论中指出的,<a href="https://docs.python.org/2/library/test.html#test.test_support.EnvironmentVarGuard" rel="noreferrer">EnvironmentVarGuard</a>是正确的方式。</p>
<pre><code>from test.test_support import EnvironmentVarGuard # Python(2.7 < 3)
from test.support import EnvironmentVarGuard # Python >=3
from django.test import TestCase
class MyTestCase(TestCase):
def setUp(self):
self.env = EnvironmentVarGuard()
self.env.set('VAR', 'value')
def test_something(self):
with self.env:
# ... perform tests here ... #
pass
</code></pre>
<p>这将在上下文对象<code>with</code>语句的持续时间内正确设置环境变量。</p>