class TestS3Actor(unittest.TestCase): @mock_s3 def setUp(self): self.bucket_name = 'test_bucket_01' self.key_name = 'stats_com/fake_fake/test.Json' self.key_contents = 'This is test data.' s3 = boto3.session.Session().resource('s3') s3.create_bucket(Bucket=self.bucket_name) s3.Object(self.bucket_name,self.key_name).put(Body=self.key_contents)
错误:
...file "/library/Python/2.7/site-packages/botocore/vendored/requests/packages/urllib3/connectionpool.py",line 344,in _make_requestself._raise_timeout(err=e,url=url,timeout_value=conn.timeout)file "/library/Python/2.7/site-packages/botocore/vendored/requests/packages/urllib3/connectionpool.py",line 314,in _raise_timeoutif 'timed out' in str(err) or 'dID not complete (read)' in str(err): # Python 2.6TypeError: __str__ returned non-string (type WantWriteError)botocore.hooks: DEBUG: Event needs-retry.s3.CreateBucket: calling handler <botocore.retryhandler.RetryHandler object at 0x10ce75310>
看起来moto没有正确地模仿boto3调用 – 我该如何工作呢?
解决方法 对我来说有用的是在用boto3运行我的模拟测试之前用boto设置环境.这是一个工作片段:
import unittestimport botofrom boto.s3.key import Keyfrom moto import mock_s3import boto3class TestS3Actor(unittest.TestCase): mock_s3 = mock_s3() def setUp(self): self.mock_s3.start() self.location = "eu-west-1" self.bucket_name = 'test_bucket_01' self.key_name = 'stats_com/fake_fake/test.Json' self.key_contents = 'This is test data.' s3 = boto.connect_s3() bucket = s3.create_bucket(self.bucket_name,location=self.location) k = Key(bucket) k.key = self.key_name k.set_contents_from_string(self.key_contents) def tearDown(self): self.mock_s3.stop() def test_s3_boto3(self): s3 = boto3.resource('s3',region_name=self.location) bucket = s3.Bucket(self.bucket_name) assert bucket.name == self.bucket_name # retrIEve already setup keys keys = List(bucket.objects.filter(Prefix=self.key_name)) assert len(keys) == 1 assert keys[0].key == self.key_name # update key s3.Object(self.bucket_name,self.key_name).put(Body='new') key = s3.Object(self.bucket_name,self.key_name).get() assert 'new' == key['Body'].read()
使用py.test test.py运行时,您将获得以下输出:
collected 1 items test.py .========================================================================================= 1 passed in 2.22 seconds =========================================================================================总结
以上是内存溢出为你收集整理的python – 如何使用带有moto的boto3测试方法全部内容,希望文章能够帮你解决python – 如何使用带有moto的boto3测试方法所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)