Skip to content

Commit

Permalink
Add moto
Browse files Browse the repository at this point in the history
  • Loading branch information
baniasbaabe committed Apr 21, 2024
1 parent 00175c8 commit dba2fc3
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions book/testing/Chapter.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,55 @@
"def test():\n",
" assert datetime.datetime.now() == datetime.datetime(2015, 2, 20)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Mock AWS Services with `moto`"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you have worked with AWS Services and Python,\n",
"\n",
"you know how difficult testing your code can be.\n",
"\n",
"With `moto`, you can easily mock out AWS Services and write your tests without headaches.t\n",
"\n",
"Note: Not all services are covered, so check out the implementation coverage in their repository. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import boto3\n",
"from moto import mock_aws\n",
"from mymodule import MyModel\n",
"\n",
"class MyModel:\n",
" def __init__(self, name, value):\n",
" self.name = name\n",
" self.value = value\n",
"\n",
" def save(self):\n",
" s3 = boto3.client(\"s3\", region_name=\"us-east-1\")\n",
" s3.put_object(Bucket=\"mybucket\", Key=self.name, Body=self.value)\n",
"\n",
"@mock_aws\n",
"def test_my_model_save():\n",
" conn = boto3.resource(\"s3\", region_name=\"us-east-1\")\n",
" conn.create_bucket(Bucket=\"mybucket\")\n",
" model_instance = MyModel(\"test\", \"testtest\")\n",
" model_instance.save()\n",
" body = conn.Object(\"mybucket\", \"test\").get()[\"Body\"].read().decode(\"utf-8\")\n",
" assert body == \"testtest\""
]
}
],
"metadata": {
Expand Down

0 comments on commit dba2fc3

Please sign in to comment.