The whole network is hot, the pytest automated testing framework is proficient in actual combat from 0-1, your advanced road...


foreword

1. Operation mode

Command line mode:

pytest -s login.py

Main function mode:

if __name__ == '__main__':
	pytest.main(["-s", "login.py"])

pytest.ini running:
Configure the running parameters of pytest in the pytest.ini file.
Points to note:
location: the configuration file is generally placed in the root directory of the project;
encoding: must be ANSI, you can use text editing tools to modify the encoding format;
rules: no matter what kind of operation mode, the configuration file will be read, which is the highest level ;
the first line at the beginning of the file must be [pytest] except for the comment, which is a fixed format, and the file name pytest.ini is also fixed, and cannot be renamed by itself;

Commonly used parameters:
addopts command line parameters, separated by spaces;
testpaths test case path;
markers marker parameters, the assignment method is key:value;
python_files module naming rules xx.py;
python_classes class name naming rules Xxx;
python_functions method Naming rules**
required_plugins plugin usage;
xfail_strict = true disables xpass;

2, affirmation

The pytest unit testing framework does not provide a special assert method, but directly uses Python's assert to assert.

import pytest

# 功能:用于计算 a 与 b 相加的和
def add(a, b):
    return a + b

# 功能:用于判断素数
def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, n):
        if n % i == 0:
            return False
        return True

# 测试相等
def test_add_1():
    assert add(3, 4) == 7

# 测试不相等
def test_add_2():
    assert add(17, 22) != 50

# 测试大于或等于
def test_add_3():
    assert add(17, 22) <= 50

# 测试小于或等于
def test_add_4():
    assert add(17, 22) >= 38

# 测试包含
def test_in():
    a = "hello"
    b = "he"
    assert b in a

# 测试不包含
def test_not_in():
    a = "hello"
    b = "hi"
    assert b not in a

# 判断是否为 True
def test_true_1():
    assert is_prime(13)

# 判断是否为 True
def test_true_2():
    assert is_prime(7) is True

# 判断是否不为 True
def test_true_3():
    assert not is_prime(4)

# 判断是否不为 True
def test_true_4():
    assert is_prime(6) is not True

# 判断是否为 False
def test_false_1():
    assert is_prime(8) is False


if __name__ == '__main__':
    pytest.main(["-s", "0701.py"])

3、Fixture

Fixture is usually used to initialize or restore the test environment for test methods, test functions, test classes and the entire test file.

setup_module/teardown_module: Executed before and after all test cases in the current file.

setup_function/teardown_function: executed before and after each test function.

setup/teardown: executed before and after each test function. These two methods also work on class methods.

4. Parameterization

# argnames:参数名 
# argvalues:参数对应值,类型必须为可迭代类型,一般使用list 
@pytest.mark.parametrize(argnames, argvalues, indirect=False,ids=None, scope=None)

Example:

import pytest

class TestLogin:
    @pytest.mark.parametrize(("username", "password"), [("zhangsan", "zhangsan123"), (" xiaoming", "xiaoming123")])
    def test_a(self, username, password):
        print(username)
        print(password)
        assert 1

5. Run the test

pytest provides a wealth of parameters to run test cases, and you can view the help through "pytest --help".

Run test cases whose name contains a certain string:
For example: pass "-k" to specify a test case whose name contains "add"

pytest -k add test.py
if __name__ == '__main__':
	pytest.main(["-k", "add", "test.py"])

D1

Reduce the verbosity of the test run:
the run log has a lot less information, "-q" is used to reduce the verbosity of the test run; you can also use "-quiet" instead.

pytest -q test.py
if __name__ == '__main__':
	pytest.main(["-q", "test.py"])

D2

If a test case fails, exit the test:
This is useful in the debugging phase of the test case. When a failed test case occurs, you should first pass the test case through debugging instead of continuing to execute subsequent tests Example.

pytest -x test.py
if __name__ == '__main__':
	pytest.main(["-x", "test.py"])

D3

Run the test directory:
the test directory can specify either a relative path (such as ./test_dir) or an absolute path (such as D:\pytest_sample\test_dir).

pytest ./test_dir

Specify a specific class or method to execute:
here specify to run the test_numbers_5_6() method under the TestMultiply class in the test_fixtures_02.py file, and the file name, class name and method name are separated by the "::" symbol.

pytest test_fixtures_02.py::TestMultiply::test_numbers_5_6

6. Skip the test

How to use: Add the decorator @pytest.mark.skipif(condition, reason="xxx") on top of the test script that needs to be skipped

# condition:跳过的条件,必传参数 
# reason:标注原因,必传参数 
@pytest.mark.skipif(condition, reason=None)

7. Generate test report

Generate the JUnit XML file:

pytest ./test_dir --junit-xml=./report/log.xml

Generate an online test report:

pytest ./test_dir --pastebin=all

The above code can generate a session-log link, copy the link, open it through a browser, and you will get a test report in HTML format.

8. pytest plugin

pytest-html:
pytest-html can generate test reports in HTML format.
First, install the pytest-html extension via the pip command.

pip install pytest-html

Second, run the test case and generate a test report.

pytest ./ --html=./report/result.html

pytest-rerunfailures:
pytest-rerunfailures enables retrying of test cases when they fail.

pip install pytest-rerunfailures

Set the number of retries after the test case fails to run through the "-reruns" parameter.

pytest -v test.py --reruns 3

pytest-parallel:
The pytest-parallel extension enables parallel execution of test cases.

pip install pytest-parallel

The parameter "–tests-per-worker" is used to specify the number of threads, and "auto" means automatic allocation.

pytest -q test.py --tests-per-worker auto

Example:

from time import sleep

def test_01():
    sleep(3)

def test_02():
    sleep(5)

def test_03():
    sleep(6)

Running the test case without using threads took 14.05s, which was shortened to 6.02s after using it.

pytest-ordering:
Control function execution order.

pip3 install pytest-ordering

Use:
mark the function under test, @pytest.mark.run(order=x);
solve the running order according to the parameters passed in order;
when the order values ​​are all positive or all negative, the running order: the smaller the value, The higher the priority;
both positive and negative numbers exist: positive numbers have higher priority;

The following is the most complete software test engineer learning knowledge architecture system diagram in 2023 that I compiled

1. From entry to mastery of Python programming

Please add a picture description

2. Interface automation project actual combat

Please add a picture description

3. Actual Combat of Web Automation Project

Please add a picture description

4. Actual Combat of App Automation Project

Please add a picture description

5. Resume of first-tier manufacturers

Please add a picture description

6. Test and develop DevOps system

Please add a picture description

7. Commonly used automated testing tools

Please add a picture description

Eight, JMeter performance test

Please add a picture description

9. Summary (little surprise at the end)

Only by sweating and working hard can we reap brilliant achievements; only by working hard can we create our own wonderful life. Persevere and chase your dreams, you will become an unmatched strong man!

Only with unremitting efforts can we achieve brilliance; only with the determination to go forward bravely can we succeed in pursuing our dreams; don’t be afraid of difficulties and face challenges bravely, you will definitely be able to write your own magnificent chapter!

Only by doing our best can we bloom brilliantly; only by persevering can we create miracles; only by going forward bravely can we realize our dreams. Believe in yourself, keep your feet on the ground and work hard, the future will surely belong to you!

Guess you like

Origin blog.csdn.net/csdnchengxi/article/details/131810534