<p>我不知道你到底想要什么,所以我会给你一些开始。你知道吗</p>
<p>例如,你让<code>unittest.mock</code>为你模拟一切。(有用的阅读:<a href="https://docs.python.org/3/library/unittest.mock.html" rel="nofollow noreferrer">https://docs.python.org/3/library/unittest.mock.html</a>)</p>
<p><code>module.py</code>:</p>
<pre><code>import boto3
def function():
session = boto3.Session(profile_name="foobar")
client = session.resource("sts")
return client.get_caller_identity().get('Account')
</code></pre>
<p><code>test_module.py</code>:</p>
<pre><code>from unittest.mock import patch
import module
@patch("module.boto3") # this creates mock which is passed to test below
def test_function(mocked_boto):
# mocks below are magically created by unittest.mock when they are accessed
mocked_session = mocked_boto.Session()
mocked_client = mocked_session.resource()
mocked_identity = mocked_client.get_caller_identity()
# now mock the return value of .get()
mocked_identity.get.return_value = "foo-bar-baz"
result = module.function()
assert result == "foo-bar-baz"
# we can make sure mocks were called properly, for example
mocked_identity.get.assert_called_once_with("Account")
</code></pre>
<p>试运行结果:</p>
<pre><code>$ pytest
================================ test session starts ================================
platform darwin Python 3.7.6, pytest-5.3.2, py-1.8.1, pluggy-0.13.1
rootdir: /private/tmp/one
collected 1 item
test_module.py . [100%]
================================= 1 passed in 0.09s =================================
</code></pre>
<p>我还建议安装<code>pytest-socket</code>并运行<code>pytest disable-socket</code>,以确保您的测试不会意外地与网络通信。你知道吗</p>