python使用Mock

背景

aws的lambda function使用python完成,python連接pymsql,涉及到的UT怎麼寫?

問題一:使用mock調用lambda function

conn = boto3.resource('s3', region_name='us-east-1')
conn.create_bucket(Bucket="test")

boto3.client('s3', region_name='us-east-1').put_object(Bucket="test", Key="123456789_20190419_0/0/20200419/20200419.publish", Body="testpublish")

event = s3_object_created_event("test", "123456789_20190419_0/0/20200419/20200419.publish")

參考: http://joshuaballoch.github.io/testing-lambda-functions/
about moto: http://docs.getmoto.org/en/latest/docs/getting_started.html

問題二: 使用mock操作RDS(mysql)

主要使用patch和side_effect

@patch("pymysql.connect")
@patch("lambda_function.check")
@patch("lambda_function.insert")
@patch("lambda_function.connect")
@patch("lambda_function.send_email")
def test_lambda_handler(self, mock_send_email, mock_connect, mock_insert, mock_check, mock_pyconnect):

error情況

with self.assertRaises(SystemExit) as cm:
    lambda_function.lambda_handler(event, None)
self.assertEqual(cm.exception.code, -4)

相關參考

https://blog.csdn.net/lk142500/article/details/79582176
https://realpython.com/python-testing/
https://docs.python.org/3/library/unittest.mock.html
http://note.qidong.name/2018/02/pytest-mock/
http://devopstarter.info/three-years-later-test-mock/
https://www.programcreek.com/python/example/105254/moto.mock_s3
http://doc.codingdict.com/python_352/library/unittest.mock-examples.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章