Python Tema7 Parte6 Test-Unittest BR v1-1
Python Tema7 Parte6 Test-Unittest BR v1-1
1
IBM SkillsBuild | Introducción a Python
Índice
Introdução 3
Exemplo 3. Reciclagem 12
2
IBM SkillsBuild | Introducción a Python
Introdução
3
IBM SkillsBuild | Introducción a Python
Exemplo 1. Binário a
decimal
Arquivo bin_to_dec.py:
def decimal(binary_str):
place = 1; # Posición
dec = 0 # El valor decimal
return dec
Arquivo test_bin_to_dec.py:
import unittest
import bin_to_dec
class TestBinaryToDecimal(unittest.TestCase):
def test_binario_decimal_con_entradas_validas(self):
dec_output = bin_to_dec.decimal(binary)
self.assertEqual(d, dec_output)
for d in test_vals:
binary = bin(d) # En formato '0b10101'
binary = binary[2:] # Quitar la inicial '0b'
dec_output = bin_to_dec.decimal(binary)
self.assertEqual(d, dec_output)
def test_binario_decimal_con_entradas_invalidas(self):
# Testeamos que se genere un error con cadenas que no estén compuestas por 0 y 1.
valid = '010101'
valid2 = '1111111'
if __name__ == '__main__':
unittest.main()
5
IBM SkillsBuild | Introducción a Python
Resultado do teste:
6
IBM SkillsBuild | Introducción a Python
Arquivo camel.py:
import re
def capitalize(word):
""" Convierta la palabra para que tenga la primera letra en mayúscula, el resto en
minúsculas"""
return word[0:1].upper() + word[1:].lower()
# Los segmentos no producen errores de tipo "index out of bounds".
# Así que esto todavía funciona en cadenas vacías y cadenas de longitud 1
def lowercase(word):
"""convierte una palabra a minúsculas"""
return word.lower()
def camel_case(sentence):
# Escribe con mayúscula la segunda palabra y las siguientes y las pone en una nueva
lista.
capitalized_words = [ capitalize(word) for word in words[ 1: ] ]
camel_cased_sentance = ''.join(camel_cased_words)
return camel_cased_sentance
def main():
sentence = input('Introduzca la frase: ')
camelcased = camel_case(sentence)
print(camelcased)
if __name__ == '__main__':
main()
Arquivo test_camel.py:
import unittest
from unittest.mock import patch
import camel
class TestCamelCase(unittest.TestCase):
def test_capitalize(self):
def test_lower(self):
# this isn't really needed, since we can assume that Python's library functions
work correctly :)
input_words = ['abc', 'ABC', 'aBC', 'ABc']
lower = 'abc'
def test_camel_case_single_words(self):
input_and_expected_outputs = {
'hello' : 'hello',
'Hello' : 'hello',
'Thisisaverylongwordlalalalalalalalalalala':
'thisisaverylongwordlalalalalalalalalalala',
8
IBM SkillsBuild | Introducción a Python
'a': 'a'
}
def test_camel_case_uppercase(self):
input_and_expected_outputs = {
'HELLO': 'hello',
'Hello': 'hello',
'HeLLo wORlD': 'helloWorld'
def test_camel_case_lowercase(self):
input_and_expected_outputs = {
'hello': 'hello',
'hELLO': 'hello',
'heLLo WORlD': 'helloWorld'
}
def test_camel_case_empty_strings(self):
input_and_expected_outputs = {
'': '',
' ': '',
}
def test_camel_case_many_words(self):
input_and_expected_outputs = {
'two words': 'twoWords',
'this is a sentence': 'thisIsASentence',
9
IBM SkillsBuild | Introducción a Python
def test_camel_case_extra_spaces(self):
input_and_expected_outputs = {
' Spaces Before': 'spacesBefore',
'Spaces after ': 'spacesAfter',
' Spaces Every where ': 'spacesEveryWhere',
'\tThere is a \t tab here': 'thereIsATabHere',
'\nThere is a \n newline here': 'thereIsANewlineHere',
'There is a newline here\n': 'thereIsANewlineHere',
'\nThere is a newline here\n': 'thereIsANewlineHere',
def test_camel_case_emojis(self):
input_and_expected_outputs = {
'👽🌎🌺': '👽🌎🌺',
'👽 🌎🌺🐑🌳 🌵🐬': '👽🌎🌺🐑🌳🌵🐬',
}
def test_camel_case_international(self):
input_and_expected_outputs = {
'你叫 什么 名字': '你叫什么名字',
'Write a résumé': 'writeARésumé',
'Über die Brücke': 'überDieBrücke',
'Fahre über die Brücke': 'fahreÜberDieBrücke',
}
10
IBM SkillsBuild | Introducción a Python
def test_input_and_output(self):
# Patch the input. Using with context manager automatically takes care of
unpatching.
with patch('builtins.input', return_value='This IS another SENTenCE'):
camel.main()
mock_print.assert_called_with('thisIsAnotherSentence')
if __name__ == '__main__':
unittest.main()
11
IBM SkillsBuild | Introducción a Python
Exemplo 3. Reciclagem
Calcule o número da casa com mais reciclagem e o
número de caixas que a casa recicla. O mesmo para a
casa com o menor número e o número de caixas para
aquela casa.
Você é um motorista de caminhão de reciclagem.
Você gostaria de coletar algumas estatísticas sobre o Arquivo recycling.py:
quanto cada casa recicla. Suponha que o número de
lares seja 0, 1, 2, 3....
def max_recycling(crates):
"""Returns the index with the largest value in the list and the number of crates for
that house.
Raises ValueError if list is empty."""
max_houses = []
max_crates = crates[0]
def min_recycling(crates):
"""Returns the smallest value in the list
and a list of house number (list indexes) with that value.
Raises ValueError if list is None or empty."""
min_houses = []
min_crates = crates[0]
12
IBM SkillsBuild | Introducción a Python
def total_crates(crates):
""" Return the total of all the values in the crates list"""
total = 0
for crate in crates:
total += crate
return total
def get_crate_quantities(houses):
""" Ask user for number of crates for each house"""
crates = []
for house in range(houses):
crates.append(positive_int_input('Enter crates for house {}'.format(house)))
return crates
def positive_int_input(question):
""" Valdiate user enters a positive integer """
while True:
try:
integer = int(input(question + ' '))
if integer >= 0:
return integer
else:
print('Please enter a positive integer.')
except ValueError:
print('Please enter a positive integer.')
def main():
crates = get_crate_quantities(houses)
13
IBM SkillsBuild | Introducción a Python
maximums = max_recycling(crates)
minimums = min_recycling(crates)
total = total_crates(crates)
if __name__ == '__main__':
main()
Arquivo test_recycling.py:
import unittest
from unittest.mock import Mock, patch
import recycling
class TestRecycling(unittest.TestCase):
def test_max_values(self):
def test_min_values(self):
self.assertEqual(min_data.crates, 0)
self.assertEqual(min_data.houses, [1, 4])
def test_total(self):
example_data = [1, 3, 5, 0, 2, 6]
self.assertEqual(recycling.total_crates(example_data), 17)
def test_get_crate_quantities(self):
"""
Create a patch to replace the built in input function with a mock.
The mock is called mock_input, and we can change the way it behaves, e.g. provide
our desired return values. So when the code calls input(), instead of
calling the built-in input function, it will call the mock_input mock function,
which doesn't do anything except for returning the values provided in the
list of side_effect values - the first time it is called, it returns the first
side_effect value (1), second time it will return the second value, (3) etc...
"""
example_data = [1, 3, 5, 0, 2, 6]
with patch('builtins.input', side_effect=example_data) as mock_input:
self.assertEqual(recycling.get_crate_quantities(6), example_data)
def test_int_input(self):
15
IBM SkillsBuild | Introducción a Python
def test_main(self):
if __name__ == '__main__':
unittest.main()
Resultado do teste:
16