{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Effective Python - 59 Specific Ways to Write Better Python. \n", "# *Chapter 8 - Production*\n", "Book by Brett Slatkin. \n", "Summary notes by Tyler Banks." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Item 56: Test Everything with unittest" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Use `unittest` module to test your utilities" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "# utils.py\n", "def to_str(data):\n", " if isinstance(data, str):\n", " return data\n", " elif isinstance(data, bytes):\n", " return data.decode('utf-8')\n", " else:\n", " raise TypeError('Must supply str or bytes, found: %r' % data)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "# utils_test.py\n", "from unittest import TestCase, main\n", "#from utils import to_str\n", "class UtilsTestCase(TestCase):\n", " def test_to_str_bytes(self):\n", " self.assertEqual('hello', to_str(b'hello'))\n", " def test_to_str_str(self):\n", " self.assertEqual('hello', to_str('hello'))\n", " def test_to_str_bad(self):\n", " self.assertRaises(TypeError, to_str, object())\n", "#if __name__ == '__main__':\n", "# main()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Use `setUp` and `tearDown`" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "class MyTest(TestCase):\n", " def setUp(self):\n", " self.test_dir = TemporaryDirectory()\n", " def tearDown(self):\n", " self.test_dir.cleanup()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.5" } }, "nbformat": 4, "nbformat_minor": 2 }