diff --git a/book/testing/Chapter.ipynb b/book/testing/Chapter.ipynb index 00e02a4..08767e6 100644 --- a/book/testing/Chapter.ipynb +++ b/book/testing/Chapter.ipynb @@ -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": {