Юнит-тестирование в Питоне, часть 1: модуль unittest | Participants
|
- Statistics
- Participants
- Translate into Russian
- Translation result
- Translated in draft, editing and proof-reading required. Completed: 65%.
If you do not want to register an account, you can sign in with OpenID.
Python unit testing part 1: the unittest module | Юнит-тестирование в Питоне, часть 1: модуль unittest | |
Python developers who are serious about testing their code are fortunate to have a choice between at least three unit test frameworks: unittest, doctest and py.test. I'll discuss these frameworks and I'll focus on features such as availability, ease of use, API complexity, test execution customization, test fixture management, test reuse and organization, assertion syntax, dealing with exceptions. This post is the first in a series of three. It discusses the unittest module. | Разработчикам на языке Питон, серьёзно относящимся к тестированию своего кода, повезло. Они могут выбирать как минимум между тремя фреймворками для юнит-тестирования: unittest, doctest и py.test. Я рассмотрю эти фреймворки и обращу особое внимание на такие возможности как доступность, простота использования, сложность API, настройка выполнения тестов, управление тестовой конфигурацией (test fixture), организация и повторное использование тестов, синтаксис утверждений, связь с исключениями. Эта статья о модуле unittest. | |
The SUT (software under test) I'll use in this discussion is a simple Blog management application, based on the Universal Feed Parser Python module written by Mark Pilgrim of Dive Into Python fame. I discussed this application in a previous PyFIT-related post. I implemented the blog management functionality in a module called Blogger (all the source code used in this discussion can be found here.) | В качестве SUT (software under test - тестируемое программное обеспечение ) в этой статье, я буду использовать простое приложение управляющее Блогом, которое базируется на модуле Universal Feed Parser, написанным Mark Pilgrim в известной книге "Dive Into Python". Я обсуждал это приложение также и в прошлой статье "PyFIT". Я реализовал функциональность управления блогом в модуле Blogger (весь исходный код используемый в этой статье может найден здесь.) | — "приложение, управляющее", "код, используемый в этой статье, может быть найден", "базируется на модуле, написаннОм" — Jaeger |
unittest | ||
Availability | ||
The unittest module (called PyUnit by Steve Purcell, its author) has been part of the Python standard library since version 2.1. | Модуль unittest (известный также как PyUnit) является частью стандартной библиотеки Питона начиная с версии 2.1. | — перед "начиная" нужна запятая — Jaeger |
Ease of use | ||
Since unittest is based on jUnit, people familiar with the xUnit framework will have no difficulty picking up the unittest API. Due to the jUnit heritage, some Python pundits consider that unittest is too much "java-esque" and not enough "pythonic". I think the opinions are split though. I tried to initiate a discussion on this topic at comp.lang.python, but I didn't have much success. | Unittest основан на jUnit, и людям знакомым с xUnit-фреймворками , не составит труда начать использовать unittest API. Из-за наследия jUnit, многие Питон разработчики считают что модуль unittest выглядит слишком в java-стиле, а не по-питоновски. Я думаю что тут нет единого мнения. Я пытался начать дискуссию на эту тему в comp.lang.python, но особого успеха это не принесло. | |
API complexity | ||
The canonical way of writing unittest tests is to derive a test class from unittest.TestCase. The test class exists in its own module, separate from the module containing the SUT. Here is a short example of a test class for the Blogger module. I saved the following in a file called unittest_blogger.py: | Канонический путь написания unittest тестов это наследовать тестовый класс от unittest.TestCase. Тестовый класс находится в собственном модуле, отдельно от модуля содержащего SUT. Ниже приведен короткий пример тестового класса для модуля Blogger. Я сохранил следующий код в файле unittest_blogger.py: | — Не хватает тире перед "это" — Jaeger |
import unittest | ||
import Blogger | ||
class testBlogger(unittest.TestCase): | ||
""" | ||
A test class for the Blogger module. | ||
""" | ||
def setUp(self): | ||
""" | ||
set up data used in the tests. | — перед "используемые" нужна запятая — Jaeger | |
setUp is called before each test function execution. | setUp вызывается каждый раз перед исполнением тестовой функции. |
License: CC

— А что делать с поломанным форматированием питоновского кода? — itismow
— Я думаю уже ничего не сделаешь. — k0sh