Skip to content

Commit 3c50e94

Browse files
author
Julio Sarango
committed
Agregamos doctest
1 parent 2ed348d commit 3c50e94

5 files changed

Lines changed: 132 additions & 66 deletions

File tree

README.md

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,4 +47,15 @@ El “side effect” en Mock nos permite modificar el comportamiento de un méto
4747

4848
```
4949
python -m unittest tests.test_api_client.ApiClientTest.test_get_location_return_side_effect
50-
```
50+
```
51+
52+
# SubTest
53+
Nos ayuda a realizar validaciones con varios valores sin la necesidad de crear varios métodos. SubTest también es útil para identificar errores específicos. Si una prueba falla con un conjunto particular de parámetros, SubTest permitirá identificar fácilmente qué valores causaron el fallo.
54+
55+
```
56+
python -m unittest tests.test_bank_account.BankAccoutTest.test_deposit_multiple_amounts
57+
```
58+
59+
# Doctest
60+
61+
Doctest es una librería que está incluida en Python y que permite crear pruebas en los comentarios del código.

src/api_client.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,22 @@
11
import requests, ipaddress
22

3+
34
def get_location(ip):
5+
46
ipaddress.ip_address(ip)
57
url = f"https://freeipapi.com/api/json/{ip}"
6-
8+
79
response = requests.get(url)
810
response.raise_for_status()
911
data = response.json()
10-
12+
1113
return {
1214
"country": data["countryName"],
1315
"region": data["regionName"],
1416
"city": data["cityName"],
15-
"code": data["countryCode"]
17+
"code": data["countryCode"],
1618
}
1719

1820

19-
if __name__ == '__main__':
21+
if __name__ == "__main__":
2022
get_location("8.8.0")
21-

src/calculator.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,74 @@
11
def suma(a, b):
2+
"""Add two numbers
3+
4+
Args:
5+
a (numeric): First number
6+
b (numeric): Second number
7+
8+
Returns:
9+
numeric: Return the result of addition
10+
11+
>>> suma(4,5)
12+
9
13+
14+
>>> suma(14,20)
15+
34
16+
"""
217
return a + b
318

419

520
def resta(a, b):
21+
"""Diff two numbers
22+
23+
Args:
24+
a (numeric): First number
25+
b (numeric): Second number
26+
27+
Returns:
28+
numeric: Result
29+
30+
>>> resta(3,44)
31+
-41
32+
"""
633
return a - b
734

835

936
def multiplicacion(a, b):
37+
"""Multiply two numbers
38+
39+
Args:
40+
a (numeric): First number
41+
b (numeric): Second number
42+
43+
Returns:
44+
numeric: Result
45+
>>> multiplicacion(4,6)
46+
24
47+
>>> multiplicacion(4,0)
48+
0
49+
"""
1050
return a * b
1151

1252

1353
def division(a, b):
54+
"""_summary_
55+
56+
Args:
57+
a (numeric): First number
58+
b (numeric): Second number
59+
60+
Raises:
61+
ZeroDivisionError: _description_
62+
63+
Returns:
64+
numeric: Result
65+
66+
>>> division(20,5)
67+
4.0
68+
>>> division(20,0)
69+
Traceback (most recent call last):
70+
ZeroDivisionError: Operación no permitida
71+
"""
1472
if b == 0:
1573
raise ZeroDivisionError("Operación no permitida")
1674

tests/test_api_client.py

Lines changed: 38 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -8,88 +8,66 @@ class ApiClientTest(unittest.TestCase):
88
@patch("src.api_client.requests.get")
99
def test_get_location_return_expected_data(self, mock_get):
1010
mock_get.return_value.status_code = 200
11-
11+
1212
# Establecemos los datos que deseamos y la estructura que necesitamos.
1313
# Mockeamos la respuesta del API
14-
mock_get.return_value.json.return_value = {
15-
'countryName': 'USA',
16-
'regionName': 'Florida',
17-
'cityName': 'MIAMI',
18-
'countryCode': "US"
19-
}
20-
14+
mock_get.return_value.json.return_value = {
15+
"countryName": "USA",
16+
"regionName": "Florida",
17+
"cityName": "MIAMI",
18+
"countryCode": "US",
19+
}
20+
2121
result = get_location("8.8.8.8")
2222
self.assertEqual(result.get("country"), "USA")
2323
self.assertEqual(result.get("region"), "Florida")
2424
self.assertEqual(result.get("city"), "MIAMI")
2525
self.assertEqual(result.get("code"), "US")
26-
26+
2727
# Nos aseguramos que la petición sea con la url y el parámetro correcto
28-
28+
2929
mock_get.assert_called_once_with("https://freeipapi.com/api/json/8.8.8.8")
30-
31-
30+
3231
@patch("src.api_client.requests.get")
3332
def test_get_location_return_side_effect(self, mock_get):
3433
# Se realizarán dos llamadas, una con error y otra correctamente
35-
34+
3635
mock_get.side_effect = [
3736
requests.exceptions.RequestException("Service Unavailable"),
3837
unittest.mock.Mock(
39-
status_code = 200,
40-
json = lambda: {
41-
'countryName': 'USA',
42-
'regionName': 'Florida',
43-
'cityName': 'MIAMI',
44-
'countryCode': "US"
45-
}
46-
47-
)
48-
]
49-
50-
with self.assertRaises(
51-
requests.exceptions.RequestException
52-
):
53-
get_location("8.8.8.8")
54-
38+
status_code=200,
39+
json=lambda: {
40+
"countryName": "USA",
41+
"regionName": "Florida",
42+
"cityName": "MIAMI",
43+
"countryCode": "US",
44+
},
45+
),
46+
]
47+
48+
with self.assertRaises(requests.exceptions.RequestException):
49+
get_location("8.8.8.8")
50+
5551
result = get_location("8.8.8.8")
5652
self.assertEqual(result.get("country"), "USA")
5753
self.assertEqual(result.get("region"), "Florida")
5854
self.assertEqual(result.get("city"), "MIAMI")
5955
self.assertEqual(result.get("code"), "US")
6056

61-
6257
@patch("src.api_client.requests.get")
6358
def test_get_location_return_side_effect_with_invalid_ip(self, mock_get):
64-
# Se realizarán dos llamadas, una con error y otra correctamente
65-
6659
mock_get.side_effect = [
67-
requests.exceptions.HTTPError("8.8.0 does not appear to be an IPv4 or IPv6 address"),
60+
ValueError("8.8.0 does not appear to be an IPv4 or IPv6 address"),
6861
unittest.mock.Mock(
69-
status_code = 200,
70-
json = lambda: {
71-
'countryName': 'USA',
72-
'regionName': 'Florida',
73-
'cityName': 'MIAMI',
74-
'countryCode': "US"
75-
}
76-
77-
)
78-
]
79-
80-
with self.assertRaises(requests.exceptions.HTTPError):
81-
get_location("8.8.8.8")
82-
83-
84-
result = get_location("8.8.8.8")
85-
self.assertEqual(result.get("country"), "USA")
86-
self.assertEqual(result.get("region"), "Florida")
87-
self.assertEqual(result.get("city"), "MIAMI")
88-
self.assertEqual(result.get("code"), "US")
89-
90-
91-
92-
93-
94-
95-
62+
status_code=200,
63+
json=lambda: {
64+
"countryName": "USA",
65+
"regionName": "Florida",
66+
"cityName": "MIAMI",
67+
"countryCode": "US",
68+
},
69+
),
70+
]
71+
72+
with self.assertRaises(ValueError):
73+
get_location("8.8.0")

tests/test_bank_account.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,3 +89,21 @@ def test_withdraw_allow_in_week(self, mock_datetime):
8989
mock_datetime.now.return_value.weekday.return_value = 3
9090
self.account.withdraw(100)
9191
self.assertEqual(self.account.balance, 900)
92+
93+
# Subtest
94+
def test_deposit_multiple_amounts(self):
95+
tests_cases = [
96+
{"ammount": 100, "expected": 1100},
97+
{"ammount": 3000, "expected": 4000},
98+
{"ammount": 4500, "expected": 5500},
99+
]
100+
101+
for case in tests_cases:
102+
with self.subTest(case=case):
103+
self.account = BankAccount(
104+
balance=1000,
105+
log_file="transaction_log.txt",
106+
file_log_withdraw="withdraw_log.txt",
107+
)
108+
new_balance = self.account.deposit(case["ammount"])
109+
self.assertEqual(new_balance, case["expected"])

0 commit comments

Comments
 (0)