This commit is contained in:
Yavuz Sava 2025-01-27 14:54:44 +03:00
parent 6fb26d5d40
commit d64226f44e

View File

@ -272,9 +272,7 @@
"./rearrange_test.py \n",
"\n",
"#!/usr/bin/env python3\n",
"\n",
"import re\n",
"\n",
"def rearrange_name(name):\n",
" result = re.search(r\"^([\\w .-]*), ([\\w .-]*)$\", name)\n",
" if result is None:\n",
@ -283,6 +281,226 @@
"\n",
"./rearrange_test.py"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Additional test cases"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from rearrange import rearrange_name\n",
"import unittest\n",
"\n",
"class TestRearrange(unittest.TestCase):\n",
" \n",
" def test_basic(self):\n",
" testcase = \"Lovelace, Ada\"\n",
" expected = \"Ada Lovelace\"\n",
" self.assertEqual(rearrange_name(testcase), expected)\n",
"\n",
" def test_empty(self):\n",
" testcase = \"\"\n",
" expected = \"\"\n",
" self.assertEqual(rearrange_name(testcase), expected)\n",
"\n",
" def test_double_name(self):\n",
" testcase = \"Hopper, Grace M.\"\n",
" expected = \"Grace M. Hopper\"\n",
" self.assertEqual(rearrange_name(testcase), expected)\n",
"\n",
" def test_one_name(self):\n",
" testcase = \"Voltaire\"\n",
" expected = \"Voltaire\"\n",
" self.assertEqual(rearrange_name(testcase), expected)\n",
"\n",
"# Run the tests\n",
"unittest.main()\n",
"\n",
"import re\n",
"def rearrange_name(name):\n",
" result = re.search(r\"^([\\w .]*), ([\\w .]*)$\", name)\n",
" if result is None:\n",
" return name\n",
" return \"{} {}\".format(result[2], result[1])\n",
"\n",
"./rearrange_test.py "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Assertions**\n",
"\n",
"The TestCase class also employs its own assert methods that work similarly to the assert statement: if a test fails, an exception is raised with an explanatory message, and unittest identifies the test case as a failure. In the above example, there are several assertions used:\n",
"- An assertEqual() to check for an expected result\n",
"- An assertTrue() and an assertFalse() to verify a condition\n",
"- An assertRaises() to verify that a specific exception gets raised\n",
"\n",
"Each of these assert methods is used in place of the standard assert statement so the test runner can gather all the test results and generate a report.\n",
"\n",
"Below is a list of commonly used assert methods in the TestCase class. For more information on each method, select the embedded link in the list provided. \n",
"- The assertEqual(a, b) method checks that a == b\n",
"- The assertNotEqual(a, b) method checks that a != b\n",
"- The assertTrue(x) method checks that bool(x) is True\n",
"- The assertFalse(x) method checks that bool(x) is False\n",
"- The assertIs(a, b) method checks that a is b\n",
"- The assertIsNot(a, b) method checks that a is not b\n",
"- The assertIsNone(x) method checks that x is None\n",
"- The assertIsNotNone(x) method checks that x is not None\n",
"- The assertIn(a, b) method checks that a in b\n",
"- The assertNotIn(a, b) method checks that a not in b\n",
"- The assertIsInstance(a, b) method checks that isinstance(a, b)\n",
"- The assertNotIsInstance(a, b) method checks that not isinstance(a, b)\n",
"\n",
"You can also use assert methods to generate exceptions, warnings, and log messages. For example, another important assert method in unit testing is assertRaises. It allows you to test whether exceptions are raised when they should be, ensuring that your program can handle errors. assertRaises also allows developers to check which specific exception type is raised, ensuring that the correct error handling is in place."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Command-line interface**\n",
"\n",
"The command-line interface allows you to interact with an application or program through your operating system command line, terminal, or console by beginning your code with a text command. When you want to run tests in Python, you can use the unittest module from the command line to run tests from modules, classes, or even individual test methods. This also allows you to run multiple files at one time. \n",
"\n",
"**To call an entire module:**\n",
"python -m unittest test_module1 test_module2 \n",
"\n",
"**To call a test class:**\n",
"python -m unittest test_module.TestClass\n",
"\n",
"**To call a test method:**\n",
"python -m unittest test_module.TestClass.test_method\n",
"\n",
"**Test modules can also be called using a file path, as written below:**\n",
"python -m unittest tests/test_something.py"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import unittest\n",
"class TestStringMethods(unittest.TestCase):\n",
" def test_upper(self):\n",
" self.assertEqual('foo'.upper(), 'FOO')\n",
" def test_isupper(self):\n",
" self.assertTrue('FOO'.isupper())\n",
" self.assertFalse('Foo'.isupper())\n",
" def test_split(self):\n",
" s = 'hello world'\n",
" self.assertEqual(s.split(), ['hello', 'world'])\n",
" # check that s.split fails when the separator is not a string\n",
" with self.assertRaises(TypeError): \n",
" s.split(2)\n",
"if __name__ == '__main__':\n",
" unittest.main()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class Library:\n",
"\tdef __init__(self):\n",
"\t\tself.collection = []\n",
"\tdef add_book(self, book_title):\n",
"\t\tself.collection.append(book_title)\n",
"\tdef has_book(self, book_title):\n",
"\t\treturn book_title in self.collection\n",
"\n",
"# Unit test for the Library system\n",
"class TestLibrary(unittest.TestCase):\n",
"\tdef test_adding_book_to_library(self):\n",
" \t# Arrange\n",
"\t\tlibrary = Library()\n",
"\t\tnew_book = \"Python Design Patterns\"\n",
" \t# Act\n",
" \tlibrary.add_book(new_book)\n",
" \t# Assert\n",
" \tself.assertTrue(library.has_book(new_book))\n",
"\n",
"# Running the test\n",
"library_test_output = unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromTestCase(TestLibrary))\n",
"print(library_test_output)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Test suites\n",
"Testing can be time-intensive, but there are ways that you can optimize the testing process. The following methods and modules allow you to define instructions that execute before and after each test method:\n",
"- setUp() can be called automatically with every test thats run to set up code. \n",
"- tearDown() helps clean up after the test has been run. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import unittest\n",
"import os\n",
"import shutil\n",
"# Function to test\n",
"def simple_addition(a, b):\n",
"\treturn a + b\n",
"# Paths for file operations\n",
"ORIGINAL_FILE_PATH = \"/tmp/original_test_file.txt\"\n",
"COPIED_FILE_PATH = \"/mnt/data/copied_test_file.txt\"\n",
"# Global counter\n",
"COUNTER = 0\n",
"# This method will be run once before any tests or test classes\n",
"def setUpModule():\n",
"\tglobal COUNTER\n",
"\tCOUNTER = 0\n",
"\t# Create a file in /tmp\n",
"\twith open(ORIGINAL_FILE_PATH, 'w') as file:\n",
" \tfile.write(\"Test Results:\\n\")\n",
"# This method will be run once after all tests and test classes\n",
"def tearDownModule():\n",
"\t# Copy the file to another directory\n",
"\tshutil.copy2(ORIGINAL_FILE_PATH, COPIED_FILE_PATH)\n",
"\t# Remove the original file\n",
"\tos.remove(ORIGINAL_FILE_PATH)\n",
"class TestSimpleAddition(unittest.TestCase):\n",
"\t# This method will be run before each individual test\n",
"\tdef setUp(self):\n",
" \tglobal COUNTER\n",
" \tCOUNTER += 1\n",
"\t# This method will be run after each individual test\n",
"\tdef tearDown(self):\n",
" \t# Append the test result to the file\n",
" \twith open(ORIGINAL_FILE_PATH, 'a') as file:\n",
" \tresult = \"PASSED\" if self._outcome.success else \"FAILED\"\n",
" \tfile.write(f\"Test {COUNTER}: {result}\\n\")\n",
"\tdef test_add_positive_numbers(self):\n",
" \tself.assertEqual(simple_addition(3, 4), 7)\n",
"\tdef test_add_negative_numbers(self):\n",
" \tself.assertEqual(simple_addition(-3, -4), -7)\n",
"# Running the tests\n",
"suite = unittest.TestLoader().loadTestsFromTestCase(TestSimpleAddition)\n",
"runner = unittest.TextTestRunner()\n",
"runner.run(suite)\n",
"# Read the copied file to show the results\n",
"with open(COPIED_FILE_PATH, 'r') as result_file:\n",
"\ttest_results = result_file.read()\n",
"print(test_results)"
]
}
],
"metadata": {