unittest
module.Let's consider a simple function that calculates the factorial of a number:
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
To test this function, you could write unit tests using Python's unittest
module:
import unittest
from factorial import factorial
class TestFactorial(unittest.TestCase):
def test_factorial_of_zero(self):
self.assertEqual(factorial(0), 1)
def test_factorial_of_one(self):
self.assertEqual(factorial(1), 1)
def test_factorial_of_five(self):
self.assertEqual(factorial(5), 120)
if __name__ == '__main__':
unittest.main()
This test case covers the base cases of zero and one, as well as a more complex case with the number five.
What causes it: Incorrect syntax in your code.
# Bad code example that triggers the error
def print "hello"
Error message:
File "example.py", line 1
def print "hello"
^
SyntaxError: invalid syntax
Solution: Correct the syntax of your function definition:
# Corrected code
def print_hello():
print("hello")
Why it happens: Python requires proper indentation and correct syntax for all statements.
How to prevent it: Always double-check your syntax and follow the PEP8 style guide.
What causes it: Trying to use an undefined variable or function in your code.
# Bad code example that triggers the error
print(uninitialized_var)
Error message:
Traceback (most recent call last):
File "example.py", line 1, in <module>
print(uninitialized_var)
NameError: name 'uninitialized_var' is not defined
Solution: Define the variable or function before using it in your code:
# Corrected code
uninitialized_var = "I have been initialized"
print(uninitialized_var)
Why it happens: You are trying to access a variable or function that has not yet been defined.
How to prevent it: Always declare and initialize your variables at the beginning of a scope, and import any necessary functions before using them.
pylint
or flake8
to catch common coding errors and enforce best practices.