Setup and teardown python

Классический «setup» в стиле xunit ¶

Этот раздел описывает популярный классический способ реализации фикстур («setup/teardown» методов) на уровнях модулей/классов/функций.

Поскольку эти методы просты и хорошо знакомы тем, кто уже использовал unittest or nose background , вы также можете рассмотреть применение более мощного механизма фикстур , который использует концепцию внедрения зависимостей, позволяя создавать более модальные и масштабируемые тесты, что особенно важно в больших проектах или при функциональном тестировании. В одном и том же файле можно использовать оба механизма, однако нужно иметь в виду, что подклассы unittest.TestCase не способны принимать аргументы-фикстуры.

«setup/teardown» для модуля¶

Если у вас есть несколько тестовых функций и классов в отдельном модуле, вы можете реализовать следующие методы-фикстуры, которые будут вызываться только один раз для всех функций модуля:

def setup_module(module): """настройка любых состояний, специфичных для выполнения этого модуля """ def teardown_module(module): """ очистка любых состояний, настроенных ранее с помощью метода setup_module """ 

Начиная с pytest-3.0 , параметр module можно не указывать

«setup/teardown» для класса¶

Аналогичные методы существуют и на уровне класса — они будут вызваны до и после всех тестовых методов класса:

@classmethod def setup_class(cls): """ настройка любых состояний, специфичных для выполнения этого класса (который обычно содержит тесты). """ @classmethod def teardown_class(cls): """ очистка любых состояний, настроенных ранее с помощью метода setup_class. """ 

«setup/teardown» для функций и методов¶

Аналогично, следующими методами можно «обернуть» каждый вызов метода класса:

def setup_method(self, method): """ настройка любого состояния, связанного с выполнением этого метода класса. setup_method вызывается для каждого метода класса. """ def teardown_method(self, method): """ очистка любого состояния, настроенного ранее с помощью вызова setup_method """ 

Начиная с pytest-3.0 , параметр method указывать не обязательно.

Читайте также:  Стандарты и технологии css

Если же вы предпрочитаете определять тестовые функции на уровне модуля (без разнесения по классам), для них тоже можно реализовать фикстуры:

def setup_function(function): """ настройка любого состояния, связанного с выполнением данной функции. Вызывается для каждой тестовой функции модуля. """ def teardown_function(function): """ очистка любого состояния, настроенного ранее с помощью вызова setup_function """ 

Начиная с pytest-3.0 , параметр function указывать не обязательно.

  • Пары «setup/teardown» во время тестирования могут вызываться многократно.
  • Функция «teardown» не будет вызвана, если соответствующая «setup» функция существует, но была пропущена или выдала ошибку.
  • Вплоть до pytest-4.2 , для функций в стиле xunit не соблюдались правила задания области действия фикстур, поэтому, к примеру, могло случаться так, что setup_method вызывался до autouse фикстуры уровня сессии. Сейчас функции xunit интегрированы с механизмом фикстур, и для них применяются те же правила области действия, что и для вызова фикстур.

pytest

Источник

How to implement xunit-style set-up¶

This section describes a classic and popular way how you can implement fixtures (setup and teardown test state) on a per-module/class/function basis.

While these setup/teardown methods are simple and familiar to those coming from a unittest or nose background, you may also consider using pytest’s more powerful fixture mechanism which leverages the concept of dependency injection, allowing for a more modular and more scalable approach for managing test state, especially for larger projects and for functional testing. You can mix both fixture mechanisms in the same file but test methods of unittest.TestCase subclasses cannot receive fixture arguments.

Module level setup/teardown¶

If you have multiple test functions and test classes in a single module you can optionally implement the following fixture methods which will usually be called once for all the functions:

def setup_module(module): """setup any state specific to the execution of the given module.""" def teardown_module(module): """teardown any state that was previously setup with a setup_module method. """ 

As of pytest-3.0, the module parameter is optional.

Читайте также:  Sorting numbers in java an array

Class level setup/teardown¶

Similarly, the following methods are called at class level before and after all test methods of the class are called:

@classmethod def setup_class(cls): """setup any state specific to the execution of the given class (which usually contains tests). """ @classmethod def teardown_class(cls): """teardown any state that was previously setup with a call to setup_class. """ 

Method and function level setup/teardown¶

Similarly, the following methods are called around each method invocation:

def setup_method(self, method): """setup any state tied to the execution of the given method in a class. setup_method is invoked for every test method of a class. """ def teardown_method(self, method): """teardown any state that was previously setup with a setup_method call. """ 

As of pytest-3.0, the method parameter is optional.

If you would rather define test functions directly at module level you can also use the following functions to implement fixtures:

def setup_function(function): """setup any state tied to the execution of the given function. Invoked for every test function in the module. """ def teardown_function(function): """teardown any state that was previously setup with a setup_function call. """ 

As of pytest-3.0, the function parameter is optional.

  • It is possible for setup/teardown pairs to be invoked multiple times per testing process.
  • teardown functions are not called if the corresponding setup function existed and failed/was skipped.
  • Prior to pytest-4.2, xunit-style functions did not obey the scope rules of fixtures, so it was possible, for example, for a setup_method to be called before a session-scoped autouse fixture. Now the xunit-style functions are integrated with the fixture mechanism and obey the proper scope rules of fixtures involved in the call.
Читайте также:  Can android use javascript

Источник

Оцените статью