擅长:python、mysql、java
<p>使用<code>EnvironmentVarGuard</code>不是一个好的解决方案,因为它在某些环境中失败,在另一些环境中工作。请参见下面的示例。</p>
<p><a href="https://i.stack.imgur.com/EhyX8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EhyX8.png" alt="Python3.6 environment on gitlab ci"/></a></p>
<p>一个更好的解决方案是<a href="https://stackoverflow.com/users/1748754/erewok">erewok</a>所建议的,它需要利用python3中的<code>unittest.mock</code>。</p>
<p>假设使用unittest</p>
<pre><code>from unittest.mock import patch
class TestCase(unittest.TestCase):
def setUp(self):
self.env = patch.dict('os.environ', {'hello':'world'})
def test_scenario_1(self):
with self.env:
self.assertEqual(os.environ.get('hello'), 'world')
</code></pre>
<p>```</p>