我想模擬下面的書面功能。為此,我不確定是否要為此添加單元測驗。在不使用 unittest 庫的情況下撰寫可能的單元測驗有什么建議嗎?非常感謝!
def file_upload(self, upload_file_bucket, file_name, file_path):
if os.path.exists(file_path):
with open(file_path, 'r') as f:
xml = f.read()
else:
logging.error("File '%s' does not exist." % file_path)
tools.exit_gracefully(botocore.log)
try:
conn = boto3.session.Session(profile_name=aws_prof_dev_qa)
s3 = conn.resource('s3')
object = s3.Object(upload_file_bucket, file_name)
result = object.put(Body=xml)
res = result.get('ResponseMetadata')
if res.get('HTTPStatusCode') == 200:
logging.info('File Uploaded Successfully')
else:
logging.info('File Not Uploaded Successfully')
return res
except ClientError as e:
logging.error(e)
uj5u.com熱心網友回復:
您可以使用moto撰寫健壯的端到端測驗。
Moto 是測驗 boto 的最佳實踐。它在您的本地機器上模擬 boto,在本地創建存盤桶,以便您可以進行完整的端到端測驗。
這是您的方法的一些示例代碼(我將您的代碼更改為使用組態檔名稱“aws_prof_dev_qa”)。我使用pytest 固定裝置來組織我的代碼,但這不是強制性的:
@pytest.fixture(scope='session')
def aws_credentials():
"""Mocked AWS Credentials for moto."""
os.environ['AWS_ACCESS_KEY_ID'] = 'testing'
os.environ['AWS_SECRET_ACCESS_KEY'] = 'testing'
os.environ['AWS_SECURITY_TOKEN'] = 'testing'
os.environ['AWS_SESSION_TOKEN'] = 'testing'
os.environ['AWS_DEFAULT_REGION'] = 'us-east-1'
try:
tmp = NamedTemporaryFile(delete=False)
# you many need to change 'aws_prof_dev_qa' to be your profile name
tmp.write(b"""[aws_prof_dev_qa]
aws_access_key_id = testing
aws_secret_access_key = testing""")
tmp.close()
os.environ['AWS_SHARED_CREDENTIALS_FILE'] = str(tmp.name)
yield
finally:
os.unlink(tmp.name)
@pytest.fixture(scope='function')
def empty_bucket(aws_credentials):
moto_fake = moto.mock_s3()
try:
moto_fake.start()
conn = boto3.resource('s3')
conn.create_bucket(Bucket="MY_BUCKET") # or the name of the bucket you use
yield conn
finally:
moto_fake.stop()
def test_file_upload(empty_bucket):
with NamedTemporaryFile() as tmp:
tmp.write(b'Hi')
file_name = pathlib.Path(tmp.name).name
result = file_upload("MY_BUCKET", file_name, tmp.name)
assert result.get('HTTPStatusCode') == 200
有關為什么 moto 比嘲笑更好的更多詳細資訊,請參閱我的講座。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/462187.html
標籤:Python python-2.7 亚马逊-s3 嘲弄 python-unittest
上一篇:根據python中的輸入數字生成唯一的16位字母數字
下一篇:AttributeError:“instancemethod”物件沒有屬性“short_description”
