Юнит-тестирование в Питоне, часть 1: модуль unittest

Grig Gheorghiu, “Python unit testing part 1: the unittest module ”, public translation into Russian from English More about this translation.

See also 109 similar translations

Translate into another language.

Participants

k0sh1038 points
itismow727 points
rnd010150 points
And others...
Join Translated.by to translate! If you already have a Translated.by account, please sign in.
If you do not want to register an account, you can sign in with OpenID.
Pages: ← previous Ctrl next next untranslated
1 2 3 4 5 6 7 8

Python unit testing part 1: the unittest module

Юнит-тестирование в Питоне, часть 1: модуль unittest

History of edits (Latest: k0sh 3 years, 9 months ago) §

— А что делать с поломанным форматированием питоновского кода? itismow

— Я думаю уже ничего не сделаешь. k0sh

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.

History of edits (Latest: k0sh 2 years, 7 months ago) §

— -= test fixture management =- ? k0sh

— Перед "как" нужна запятая - "такие возможности, как доступность". Возможно, стоит разбить длинный список союзами "а также", "кроме того". Jaeger

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 (весь исходный код используемый в этой статье может найден здесь.)

History of edits (Latest: k0sh 2 years, 7 months ago) §

— "приложение, управляющее", "код, используемый в этой статье, может быть найден", "базируется на модуле, написаннОм" Jaeger

unittest

unittest

History of edits (Latest: k0sh 3 years, 9 months ago) §

Availability

Доступность

History of edits (Latest: k0sh 3 years, 10 months ago) §

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.

History of edits (Latest: k0sh 3 years, 10 months ago) §

— перед "начиная" нужна запятая Jaeger

Ease of use

Простота использования

History of edits (Latest: k0sh 3 years, 10 months ago) §

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, но особого успеха это не принесло.

Unapproved edits (Latest: itismow 3 years, 9 months ago) §

— Переведен не до конца. k0sh

— done itismow

— запятая перед "знакомым", после "считают", после "думаю" Jaeger

API complexity

Сложность API

History of edits (Latest: k0sh 3 years, 9 months ago) §

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:

Unapproved edits (Latest: k0sh 3 years, 10 months ago) §

— Не хватает тире перед "это" Jaeger

import unittest

import unittest

History of edits (Latest: k0sh 3 years, 10 months ago) §

import Blogger

import Blogger

History of edits (Latest: k0sh 3 years, 10 months ago) §

class testBlogger(unittest.TestCase):

class testBlogger(unittest.TestCase):

History of edits (Latest: k0sh 3 years, 10 months ago) §

"""

""

History of edits (Latest: k0sh 3 years, 10 months ago) §

A test class for the Blogger module.

Тестовый класс для модуля Blogger.

History of edits (Latest: k0sh 3 years, 10 months ago) §

"""

"""

History of edits (Latest: k0sh 3 years, 10 months ago) §

def setUp(self):

def setUp(self):

History of edits (Latest: k0sh 3 years, 10 months ago) §

"""

"""

History of edits (Latest: k0sh 3 years, 10 months ago) §

set up data used in the tests.

подготавливает данные используемые в тесте.

Unapproved edits (Latest: k0sh 3 years, 10 months ago) §

— перед "используемые" нужна запятая Jaeger

setUp is called before each test function execution.

setUp вызывается каждый раз перед исполнением тестовой функции.

History of edits (Latest: k0sh 3 years, 9 months ago) §
Pages: ← previous Ctrl next next untranslated
1 2 3 4 5 6 7 8

License: CC