Exemplo n.º 1
0
Think of how you might test the lights on a car. You would turn on the lights (known as the test step) and go outside the car or ask a friend to check that the lights are on (known as the test assertion). Testing multiple components is known as integration testing.

Think of all the things that need to work correctly in order for a simple task to give the right result. These components are like the parts to your application, all of those classes, functions, and modules you’ve written.

A major challenge with integration testing is when an integration test doesn’t give the right result. It’s very hard to diagnose the issue without being able to isolate which part of the system is failing. If the lights didn’t turn on, then maybe the bulbs are broken. Is the battery dead? What about the alternator? Is the car’s computer failing?

If you have a fancy modern car, it will tell you when your light bulbs have gone. It does this using a form of unit test.

A unit test is a smaller test, one that checks that a single component operates in the right way. A unit test helps you to isolate what is broken in your application and fix it faster.

You have just seen two types of tests:

An integration test checks that components in your application operate with each other.
A unit test checks a small component in your application.
You can write both integration tests and unit tests in Python. To write a unit test for the built-in function sum(), you would check the output of sum() against a known output.

For example, here’s how you check that the sum() of the numbers (1, 2, 3) equals 6:

>>> assert sum([1, 2, 3]) == 6, "Should be 6"
This will not output anything on the REPL because the values are correct.

If the result from sum() is incorrect, this will fail with an AssertionError and the message "Should be 6". Try an assertion statement again with the wrong values to see an AssertionError:

>>> assert sum([1, 1, 1]) == 6, "Should be 6"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: Should be 6
In the REPL, you are seeing the raised AssertionError because the result of sum() does not match 6.

Instead of testing on the REPL, you’ll want to put this into a new Python file called test_sum.py and execute it again:
 def test_list_negative(self):
     data = [-2]
     result = sum(data)
     self.assertEqual(result, -2)
 def test_list_large(self):
     data = [2**32, 2**32]
     result = sum(data)
     self.assertEqual(result, 2**33)
Exemplo n.º 4
0
 def test_bad_type(self):
     data = "banana"
     with self.assertRaises(TypeError):
         result = sum(data)
Exemplo n.º 5
0
 def test_list_init(self):
     """ Test that it can sum a list of integers """
     data = [1, 2, 3]
     result = sum(data)
     self.assertEqual(result, 6)
Exemplo n.º 6
0
def test_sum():
    assert sum([1, 2, 3]) == 6, "Should be 6"
Exemplo n.º 7
0
 def test_list_fraction(self):
     #Test that it can sum a list of fractions
     data = [Fraction(1, 4), Fraction(1, 4), Fraction(2, 5)]
     result = sum(data)
     self.assertEqual(result, 1)
Exemplo n.º 8
0
 def test_my_sum(self):
     self.assertEqual(my_sum.sum([1, 2, 3]), 6)
 def test_tuple_int(self):
     data = (1, 2, 3)
     result = sum(data)
     self.assertEqual(result, 6)
Exemplo n.º 10
0
 def test_sum(self):
     result = sum(self.data)
     self.assertEqual(result, 6)
Exemplo n.º 11
0
Очень сложно диагностировать проблему, не имея возможности определить, какая часть системы дает сбой.
Если свет не включился, возможно, лампочки сломаны. Батарея разряжена? А как насчет генератора?

Если у вас шикарный современный автомобиль, он сообщит вам, когда у вас погаснут лампочки.
Это делается с помощью модульного теста.

Модульный тест - это небольшой тест, который проверяет правильность работы отдельного компонента.
Модульный тест помогает выявить неисправности в вашем приложении и быстрее исправить.

Вы только что видели два типа тестов:

* Интеграционный тест проверяет, взаимодействуют ли компоненты вашего приложения друг с другом.
* Модульный тест проверяет небольшой компонент в вашем приложении.

Вы можете писать как интеграционные тесты, так и модульные тесты на Python.
Чтобы написать модульный тест для встроенной функции `sum()`, вы должны сравнить вывод `sum()` с известным выводом.

Например, вот как вы проверяете, что `sum()` чисел (1, 2, 3) равна 6:

assert sum([1, 2, 3]) == 6, "Should be 6"

Это ничего не выведет, потому что значения верны.

Если результат `sum()` неверен, это приведет к ошибке `AssertionError` и сообщению «Should be 6».
Повторите попытку с неправильными значениями, чтобы увидеть AssertionError:

assert sum([1, 1, 1]) == 6, "Should be 6"

Вы видите ошибку AssertionError, потому что результат `sum()` не соответствует 6.

Давайте поместим тест в новый файл с именем `test_sum.py` и выполним его снова:
Exemplo n.º 12
0
 def test_sum_tuple(self):
     data = tuple(self.data)
     result = sum(data)
     self.assertEqual(result, 6)
Exemplo n.º 13
0
 def test_bad_type(self):
     data = 'banana'
     with self.assertRaises(TypeError):
         sum(data)
Exemplo n.º 14
0
from my_sum import sum

if __name__ == '__main__':
    data = [1, 2, 3]
    result = sum(data)
    print(result)
Exemplo n.º 15
0
 def test_sum(self):
     self.assertEqual(sum([1, 2, 3]), 6, "Should be 6")
 def test_set_int(self):
     data = set([1, 2, 3, 1])
     result = sum(data)
     self.assertEqual(result, 6)
Exemplo n.º 17
0
 def test_sum_tuple(self):
     self.assertEqual(sum((1, 2, 2)), 6, "Should be 6")
 def test_list_floats(self):
     data = [1.5, 2.5, 3]
     result = sum(data)
     self.assertEqual(result, 7)
Exemplo n.º 19
0
def test_sum_tuple():
    assert sum((1, 2, 2)) == 6, "Should be 6"
 def test_list_single(self):
     data = [6]
     result = sum(data)
     self.assertEqual(result, 6)
Exemplo n.º 21
0
 def test_list_fraction(self):
     data = [Fraction(1, 4), Fraction(1, 4), Fraction(2, 5)]
     result = sum(data)
     self.assertEqual(result, 1)
 def test_list_empty(self):
     data = []
     result = sum(data)
     self.assertEqual(result, 0)
Exemplo n.º 23
0
 def test_list_int(self):
     data = [1, 2, 3]
     result = sum(data)
     self.assertEqual(result, 6)
Exemplo n.º 24
0
 def test_list_fraction(self):
     """ Test that it can sum a list of fractions """
     data = [Fraction(1, 4), Fraction(1, 4), Fraction(2, 5)]
     result = sum(data)
     self.assertEqual(0.9, 9 / 10)