Skip to content

Commit 27b2cce

Browse files
authored
Merge pull request #515 from realpython/python-unittest
Sample code for the article on `unittest`
2 parents 2218306 + 3162644 commit 27b2cce

30 files changed

+740
-0
lines changed

python-unittest/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Python's unittest: Writing Unit Tests for Your Code
2+
3+
This folder provides the code examples for the Real Python tutorial [Python's unittest: Writing Unit Tests for Your Code](https://realpython.com/python-unittest/).

python-unittest/age.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
def categorize_by_age(age):
2+
if 0 <= age <= 9:
3+
return "Child"
4+
elif 9 < age <= 18:
5+
return "Adolescent"
6+
elif 18 < age <= 65:
7+
return "Adult"
8+
elif 65 < age <= 150:
9+
return "Golden age"
10+
else:
11+
return f"Invalid age: {age}"

python-unittest/calculations.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
from collections import Counter
2+
3+
4+
def add(x, y):
5+
return x + y
6+
7+
8+
def subtract(x, y):
9+
return x - y
10+
11+
12+
def multiply(x, y):
13+
return x * y
14+
15+
16+
def divide(x, y):
17+
if y == 0:
18+
raise ZeroDivisionError("Cannot divide by zero.")
19+
return x / y
20+
21+
22+
def mean(data):
23+
return sum(data) / len(data)
24+
25+
26+
def median(data):
27+
n = len(data)
28+
index = n // 2
29+
if n % 2:
30+
return sorted(data)[index]
31+
return sum(sorted(data)[index - 1 : index + 1]) / 2
32+
33+
34+
def mode(data):
35+
c = Counter(data)
36+
return [k for k, v in c.items() if v == c.most_common(1)[0][1]]

python-unittest/employee.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import csv
2+
3+
4+
class Employee:
5+
__slots__ = ["name", "age", "job", "salary"]
6+
7+
def __init__(self, name, age, job, salary):
8+
self.name = name
9+
self.age = age
10+
self.job = job
11+
self.salary = salary
12+
13+
def profile(self):
14+
for attr in self.__slots__:
15+
print(f"{attr.capitalize()}: {getattr(self, attr)}")
16+
print()
17+
18+
19+
def from_csv_file(file_path):
20+
with open(file_path) as file:
21+
reader = csv.DictReader(file)
22+
employees = []
23+
for row in reader:
24+
employees.append(
25+
Employee(
26+
name=row["name"],
27+
age=int(row["age"]),
28+
job=row["job"],
29+
salary=float(row["salary"]),
30+
)
31+
)
32+
return employees
33+
34+
35+
if __name__ == "__main__":
36+
employees = from_csv_file("employees.csv")
37+
for employee in employees:
38+
employee.profile()

python-unittest/employees.csv

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
name,age,job,salary
2+
Alice,25,Engineer,50000
3+
Bob,30,Analyst,60000
4+
Jane,35,Manager,80000
5+
John,40,CEO,100000

python-unittest/even.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
def is_even(number):
2+
return number % 2 == 0

python-unittest/fizzbuzz.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# def fizzbuzz(number):
2+
# if number % 3 == 0:
3+
# return "fizz"
4+
# elif number % 5 == 0:
5+
# return "buzz"
6+
# elif number % 15 == 0:
7+
# return "fizz buzz"
8+
# else:
9+
# return number
10+
11+
12+
def fizzbuzz(number):
13+
if number % 15 == 0:
14+
return "fizz buzz"
15+
elif number % 3 == 0:
16+
return "fizz"
17+
elif number % 5 == 0:
18+
return "buzz"
19+
else:
20+
return number

python-unittest/game.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
def rock_paper_scissors(choice):
2+
if choice < 0 or choice > 2:
3+
raise ValueError("number must be 0, 1, or 2")
4+
5+
choices = ["rock", "paper", "scissors"]
6+
return choices[choice]

python-unittest/prime_v1.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import math
2+
3+
4+
def is_prime(number):
5+
if number <= 1:
6+
return False
7+
for i in range(2, int(math.sqrt(number)) + 1):
8+
if number % i == 0:
9+
return False
10+
return True

python-unittest/prime_v2.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
from math import sqrt
2+
3+
4+
def is_prime(number):
5+
if not isinstance(number, int):
6+
raise TypeError(
7+
f"integer number expected, got {type(number).__name__}"
8+
)
9+
if number < 2:
10+
raise ValueError(f"integer above 1 expected, got {number}")
11+
for candidate in range(2, int(sqrt(number)) + 1):
12+
if number % candidate == 0:
13+
return False
14+
return True

0 commit comments

Comments
 (0)