python pytest testing framework (a)

This link: https: //blog.csdn.net/yxxxiao/article/details/94591174
directory

First, install

Second, the first test example

Three, pytest parameters

1、-K EXPRESSION

3 - a = maxfail

4、-m MARKEXPR

5、 -v, --verbose

6、-q, --quiet

7、--junit-xml=path

8、 --result-log=path

Four, pytest cases rules with

Five, pytest Run

1. Perform one py file with all individual cases

2. Perform all the use cases directory

3. Run a single use case

Six, fixture

1, fixture scope parameter range

2, call the fixture of the three methods

2.1 function or class method which directly transfer function of the parameter name fixture

2.2 decorator @ pytest.mark.usefixtures () needs to run a modified embodiment

2.3 superimposed usefixtures

3.usefixtures and pass fixture difference

4.fixture automatically autouse = True

Scope of 5.conftest.py

5.1conftest scope between the different levels are not the same

5.2conftest is not called cross-module (module calls is not used here)

First, install
pytest python is not the default package, need to be installed manually.

pytest supported versions between python 2.6--3.5, and can be installed on windows, unix system

Installation:

pip install pytest
after the installation is complete, you can view the version:

pytest --version
two, first test example
1. test_sample.py create file, create a method, a use case

# content of test_sample.py
def func(x):
return x + 1

def test_answer():
assert func(3) == 5
2.执行

Pytest $
=========================== the Test Soho starts the session ================== ==========
Platform Linux - Python 3.xy, pytest-4.xy, Py-1.xy, pluggy-0.xy
cacheDir is: $ PYTHON_PREFIX / .pytest_cache
RootDir: $ REGENDOC_TMPDIR
Collected 1 Item

F. test_sample.py [100%]

================================= of FAILURES ======== =========================
_______________________________ test_answer ________________________________

DEF test_answer ():
> Assert FUNC (. 3). 5 ==
E == Assert. 4. 5
E + FUNC. 4 = WHERE (. 3)

test_sample.py:5: AssertionError with
========================= failed. 1 in 0.12 seconds The ====== ===================
this test returns a failure report, because func (3) does not return 5.

Three, pytest parameter
1, -K EXPRESSION
perform a keyword use cases
use cases to match the expression given; the python syntax, matching the range of file names, class names, function named variables, and to distinguish

As described in some test cases

# content of test.py
class TestClass(object):
def test_zne(self):
x = "this"
assert 'h' in x


def test_two(self):
x = "hello"
assert hasattr(x, 'check')

def test_a(self):
assert 1==2
运行pytest时带-k参数

pytest -k "test and TestClass and not test_a" test.py
results are as follows:

 

As can be seen, with this embodiment test_A is deselected, no run

3, - maxfail = num
When the number of errors reaches a predetermined number, exit the test, the examples cited here is not, similar results -x

4, -m MARKEXPR
  only running test cases appropriately labeled, using this parameter, the test case to use the modified @ pytest.mark.marker

  The following examples

# content of test.py
import pytest
class TestClass(object):
def test_one(self):
'''new_etests'''
x = "this"
assert 'h' in x

@pytest.mark.slow
def test_two(self):
'''new_sssetests'''
x = "hello"
assert hasattr(x, 'check')

def test_a(self):
assert 1==2
teste_two使用了@pytest.mark.slow来修饰

In use, the following parameters

pytest -m slow test.py
results were as follows:

 

As can be seen from the figure above, only it runs a use case with our logo.

Note that, not later with -m '' resolution (single quotes), with only "" (double quote), not otherwise identified

If you want to run multiple identities, then use the expression, as follows

pytest -m "slow or faster" running slow identification or faster identified by Example
pytest -m "slow and faster" running with Examples slow and faster identification of
pytest -m "slow and not faster" running slow and use cases no faster identification of
5, -v, --verbose
detailed results

6, -q, --quiet
 minimalist results show simplified console output, and the output information can be seen without prior information is not the same does not add -q, the figure there are two points instead pass the results ..

7, -s
input we use modal information in cases, such as print information print, etc., we use case plus a print (driver.title), we run what we look at use cases, debugging information output

8, -V
can output a more detailed embodiment of the execution information, such as use cases where the file with the Case Name and the like

9, - junit-xml = path
output xml file format, and when used to make integrated jenkins

10, --result-log = path
to save the final result to the local file

Note: Fields marked yellow are often used

Four, cases rules with pytest
pytest can be found in the package in a different embodiment with the rules function, as found in

File names begin with the test_ py file
in order to function at the beginning of test_
start with Test class
at the beginning of the method test_ (and similar 2)
Note that all packages must be init.py file (using a variety of automatically generated when the editor)
five, pytest run
1. run py one file with all individual cases
pytest the test.py
2. Example performed with all the directory
pytest testcase /
performed separately in Example 3. a use
with a functional form of embodiment
pytest test_login.py::test_1

into classes with Example
pytest test_login.py::TestClass::test_1
six, pytest fixtures
pytest supports xUnit test model format type (setup / teardown), but also comes with the python unittest or a little different, as follows

---- modular form using setup_module / teardown_module  
functional form using ---- setup_function / teardown_function
class ---- form using setup_class / teardown_class
of the method using --- setup_method / teardown_method
Note:

1.pytest test cases can be run directly unittest mode

2. If you use in pytest setupClass mode () function does not work, will not be recognized, but if the class inherits embodiment unittest.Testcase used, can identify or

1, the range parameter scope fixtures
using @ pytest.fixture (scope = 'module' ) to define a frame before, the parameters are the following scope

 Each function is executed with the embodiment of
class for each class execution
module execute each module (functional forms of use cases)
session runs only once per session, while automated testing, the login procedure may use the session
2, the three methods call the fixture
2.1 function or class method which directly transfer function of the parameter name fixture
from __future__ Import print_function
Import pytest

@ pytest.fixture (scope = 'Module1')
DEF resource_a_setup (Request):
Print ( '\ nresources_a_setup ()')
DEF resource_a_teardown ():
Print ( '\ nresources_a_teardown ()')
request.addfinalizer (resource_a_teardown)

DEF TEST_1 (resource_a_setup):
Print ( 'TEST_1 ()')

DEF test_2 ():
Print ( '\ ntest_2 ()')

DEF test_3 (resource_a_setup):
Print ( '\ ntest_3 ()')
use -s -v run View details are as follows

 

2.2 decorator @ pytest.mark.usefixtures () needs to run modified with Example
Import pytest
# test_fixture1.py


@ pytest.fixture ()
DEF test1 ():
Print ( '\ n-started function')


@ pytest.mark.usefixtures ( 'test1')
DEF test_A ():
Print ( 'Examples execution --- --- A')


@ pytest.mark.usefixtures ( 'test1')
class TestCase:

DEF Test_B (Self):
Print ( '--- Example performed with b --- ')

DEF test_c (Self):
Print (' --- performed with embodiment c --- ')


IF the __name__ ==' __main__ ':
pytest.main ([' - S ',' test_fixture1.py '])

output:
Platform Win32 - the Python 3.7.0, 4.0.2-pytest, Py-1.7.0, 0.8.0 pluggy-
RootDir: C: \ Program Files \ PycharmProjects \ Exercise, inifile: Collected items. 3

test_fixture1 .py
started function
Example performed with a --- .---

begin function
.--- performed with embodiment b ---

begin function
.--- performed with embodiment c ---
[100%]

============== 3 passed in 0.06 seconds The ================ ===========================
Process Finished Exit code 0 with
2.3 superimposed usefixtures
if a class or a method of using a plurality of calls simultaneously embodiment want fixture, may be used @ pytest.mark.usefixture () superimposed. Note that the order of superposition, the bottom discharge is executed first, the upper layer after performing the discharge

pytest Import
# test_fixture1.py


@ pytest.fixture ()
DEF test1 ():
Print ( '\ begin implementation of the n-function1')


@ pytest.fixture ()
DEF test2 ():
Print ( '\ the n-started function2')


@pytest .mark.usefixtures ( 'test1')
@ pytest.mark.usefixtures ( 'test2')
DEF test_A ():
Print ( '--- a use case execution ---')


@ pytest.mark.usefixtures ( 'test2')
pytest.mark.usefixtures @ ( 'test1')
class TestCase:

DEF Test_B (Self):
Print ( '--- performed with embodiment b ---')

DEF test_c (Self):
Print ( '--- execution Example c - - ')


IF the __name__ ==' __main__ ':
pytest.main ([' - S ',' test_fixture1.py '])


Output:
============================= Test Soho starts the session ============= ================
win32 Platform - Python 3.7.0, pytest-4.0.2, Py-1.7.0, 0.8.0 pluggy-
RootDir: C: \ Program Files \ PycharmProjects \ Exercise, inifile: 3 Collected items

test_fixture1.py
started function2

start performing function1
.--- --- performed with Examples a

begin function1

begin function2
.--- performed with embodiment b ---

begin function1

begin function2
.--- performed with embodiment c ---
[100%]

== ======================== 3 passed in 0.03 seconds ===================== ======
Process Finished with Exit code 0
3.usefixtures and mass fixture difference
 if the fixture has a return value, usefixture can not get the return value, this is a decorator usefixture use cases pass directly fixture parameter difference.

When the fixture out of the need to use the return parameters, parameter names can only speak directly passed as parameters, it is not necessary to use return out of the parameters, it can be in two ways.

4.fixture autouse = True automatically
when a lot of cases, when every pass this parameter, will be very troublesome. fixture which has a parameter autouse, the default is False did not open, can be set to turn on automatically use True fixture features, such use cases do not always go to the mass participation

autouse set to True, the function automatically calls fixture

pytest Import
# test_fixture1.py


@ pytest.fixture (scope = 'Module1', autouse = True)
DEF test1 ():
Print ( '\ n-started Module1')


@ pytest.fixture (scope = 'class', autouse = True )
DEF test2 ():
Print ( '\ n-started class')


@ pytest.fixture (scope = 'function', autouse = True)
DEF Test3 ():
Print ( '\ n-started function')


DEF test_A () :
Print ( '--- a use case execution ---')


DEF test_d ():
Print ( '--- performed with embodiment d ---')


class TestCase:

DEF Test_B (Self):
Print ( 'use cases --- b execution --- ')

DEF test_c (Self):
Print (' execution --- --- Example C ')


IF the __name__ ==' __main__ ':
pytest.main ([' - S ',' test_fixture1.py '])


Output:
============================= test session starts ================== ===========
Platform win32 - Python 3.7.0, pytest-4.0.2, Py-1.7.0, 0.8.0 pluggy-
RootDir: C: \ Program Files \ PycharmProjects \ Exercise, inifile : Collected items. 4

test_fixture1.py
begins execution module

begins execution class

begin function
.--- execution Example A ---

begin class

begin function
.--- performed with embodiment d ---

begin class

begins execution function
.- - --- Example b with execution

begins execution function
.--- performed with embodiment c ---
action 5.conftest.py range
files can be built plurality conftest.py next project, typically disposed under the root directory of the project conftest file to play a global role. In different subdirectories can also put conftest.py file, scope and level of change can only take effect in the following directory.

Project examples:

Directory Structure:

 

5.1conftest scope between different levels of different
# conftest level show /conftest.py

Import pytest


@ pytest.fixture (scope = 'the session', autouse = True)
DEF the Login ():
Print ( '---- preparation Login ---- ')





# conftest level show / sougou_login / conftest
Import pytest


@ pytest.fixture (scope =' the session ', autouse = True)
DEF bai_du ():
Print (' ----- login Baidu page - --- ')







# conftest level show / sougou_login / login_website
Import pytest


class TestCase:
DEF test_login (Self):
Print (' hhh, successfully log on Baidu ')


IF __name__ ==' __main__ ':
pytest.main ([' - S ',' login_website.py '])



output:

============================= Test Soho starts the session ====== =======================
win32 Platform - Python 3.7.0, pytest-4.0.2, Py-1.7.0, 0.8.0 pluggy-
RootDir: C: \ Program Files \ PycharmProjects \ conftest level demo \ sougou_login, inifile: Collected 1 Item

login_website.py ---- ---- is ready to log
----- Login Baidu page -----
.hhh, a successful login Baidu
[100%]

================= 1 passed in 0.03 seconds The ========= ===========================
Process Finished with Exit code 0
5.2conftest is can not be called cross-module (not used here module calls)
# conftest level demo /log/contfest.py
Import pytest


@ pytest.fixture (scope = 'function', autouse = True)
DEF log_web ():
Print ( 'Print page log success')




# conftest level demo /log/log_website.py
Import pytest


DEF test_web ():
Print ( 'hhh, the success of a print log')


DEF test_web1 ():
print ( 'hhh, two successful printing log')


IF the __name__ == '__main__':
pytest.main ([ '- S', 'log_website.py'])


output:
========== =================== test session starts ============================ =
Platform win32 - Python 3.7.0, pytest-4.0.2, Py-1.7.0, 0.8.0 pluggy-
RootDir: C: \ Program Files \ PycharmProjects \ conftest level demo \ log, inifile:
Collected 2 items

log_website. py ---- ---- ready to log on
to print pages in the log successful
hhh, the success of a print journal
. Print page log successful
hhh, twice successfully print log
.

================ 2 passed in 0.02 seconds The ========== ===========================
-------- --------
Disclaimer: this article is the original article CSDN bloggers "Xiaoxiao _yun", and follow CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Original link: https: //blog.csdn.net/yxxxiao/article/details/94591174

Guess you like

Origin www.cnblogs.com/zhanglinfei/p/11496126.html