diff --git a/book/testing/Chapter.ipynb b/book/testing/Chapter.ipynb index 4674171..7c6470a 100644 --- a/book/testing/Chapter.ipynb +++ b/book/testing/Chapter.ipynb @@ -358,6 +358,70 @@ "def test_addition_commutative(a, b):\n", " assert a + b == b + a" ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Mocking Dependencies with `pytest-mock`" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Testing is an essential part of Software projects.\n", + "\n", + "\n", + "\n", + "Especially unit testing, where you test the smallest piece of code that can be isolated.\n", + "\n", + "\n", + "\n", + "They should be independent, and fast & cheap to execute.\n", + "\n", + "\n", + "\n", + "But, what if you have some dependencies like API calls or interactions with databases and systems?\n", + "\n", + "\n", + "\n", + "Here's where mocking comes into play.\n", + "\n", + "\n", + "\n", + "Mocking allows you to replace dependencies and real objects with fake ones which mimic the real behavior.\n", + "\n", + "\n", + "\n", + "So, you don't have to rely on the availability of your API, or ask for permission to interact with a database, but you can test your functions isolated and independently.\n", + "\n", + "\n", + "\n", + "In Python, you can perform mocking with `pytest-mock`, a wrapper around the built-in mock functionality of Python.\n", + "\n", + "\n", + "\n", + "See the example below, where we mock the file removal functionality. We can test it without deleting a file from the disk." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "\n", + "class UnixFS:\n", + " @staticmethod\n", + " def rm(filename):\n", + " os.remove(filename)\n", + "def test_unix_fs(mocker):\n", + " mocker.patch('os.remove')\n", + " UnixFS.rm('file')\n", + " os.remove.assert_called_once_with('file')\n" + ] } ], "metadata": {