Skip to content

Commit

Permalink
Add pytest-mock
Browse files Browse the repository at this point in the history
  • Loading branch information
baniasbaabe committed Dec 30, 2023
1 parent e5ed341 commit 7e37de7
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions book/testing/Chapter.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down

0 comments on commit 7e37de7

Please sign in to comment.