【Python自動化】pytestシリーズ(中)

ここに画像の説明を挿入します

上記書籍の続き:【Python自動化】pytestシリーズ(前編)

ここが中盤で、あと2つありますが、このパートから知識ポイントが増え、徐々に難易度が上がっていきます。

この章の知識ポイント


1. 前のセクションの知識ポイントの復習

  • Pytestのインストール
  • Pytest 存在コードの意味
  • Pytest コマンドの一般的な使用法
  • Pytest がテストを実行する方法

これらの知識ポイントを頭の中で思い出し、大まかに書き留めることができれば、前のセクションの内容を十分に理解していることになります。

新しい知識ポイントを学びましょう。

2. Pytest の操作前と操作後

ユースケース関数の接頭辞と接尾辞はモジュール内で定義されます: setup、teardown

  • setup_method または setup: は、各ユースケース関数が実行される前に実行されます。
  • Teadown_method または Teardown: 各ユースケース関数が実行された後に実行されます。

ユースケースクラスのプレフィックスとポストフィックスは、テストクラスで定義されます: setup_class、teardown_class

  • setup_class: 各ユースケースクラスが実行される前に実行されます。

  • teardown_class: 各ユースケースクラスの実行後に実行されます。

    ユース ケース モジュールの前部分と後部分は、テスト クラスで定義されます: setup_module、teardown_module (あまり使用されません)

  • setup_module: 各モジュールが実行される前に実行されます。

  • Teardown_module: 各モジュールの実行後に実行されます。

新しいファイルを作成しtest_c.py、次のコードを記述します。

class Test_C():

    def setup_class(self):
        print("我是Test_C下的用例类前置函数setup_class")
        
    def setup(self):
        print("我是Test_C下的用例方法前置函数setup")

    def test_001(self):
        print("我是Test_C下的test_001函数")

    def test_002(self):
        print("我是Test_C下的test_002函数")

    def teardown(self):
        print("我是Test_C下的用例方法后置函数teardown")

    def teardown_class(self):
        print("我是Test_C下的用例类后置函数teardown_class")

実行結果は以下の通り

============================= test session starts =============================
collecting ... collected 2 items

test_c.py::Test_C::test_001 我是Test_C下的用例类前置函数setup_class
我是Test_C下的用例方法前置函数setup
PASSED                                       [ 50%]我是Test_C下的test_001函数
我是Test_C下的用例方法后置函数teardown

test_c.py::Test_C::test_002 我是Test_C下的用例方法前置函数setup
PASSED                                       [100%]我是Test_C下的test_002函数
我是Test_C下的用例方法后置函数teardown
我是Test_C下的用例类后置函数teardown_class


======================== 2 passed, 4 warnings in 0.01s ========================

Process finished with exit code 0

実行結果には4つの警告が表示されており、トラブルシューティングを行った結果、警告情報は以下のとおりであることがわかりました。

============================== warnings summary ===============================
test_c.py::Test_C::test_001
  D:\Z_Enviroment\python\ApiTestProject\lib\site-packages\_pytest\fixtures.py:901: PytestRemovedIn8Warning: Support for nose tests is deprecated and will be removed in a future release.
  test_c.py::Test_C::test_001 is using nose-specific method: `setup(self)`
  To remove this warning, rename it to `setup_method(self)`
  See docs: https://docs.pytest.org/en/stable/deprecations.html#support-for-tests-written-for-nose
    fixture_result = next(generator)

test_c.py::Test_C::test_001
  D:\Z_Enviroment\python\ApiTestProject\lib\site-packages\_pytest\fixtures.py:917: PytestRemovedIn8Warning: Support for nose tests is deprecated and will be removed in a future release.
  test_c.py::Test_C::test_001 is using nose-specific method: `teardown(self)`
  To remove this warning, rename it to `teardown_method(self)`
  See docs: https://docs.pytest.org/en/stable/deprecations.html#support-for-tests-written-for-nose
    next(it)

test_c.py::Test_C::test_002
  D:\Z_Enviroment\python\ApiTestProject\lib\site-packages\_pytest\fixtures.py:901: PytestRemovedIn8Warning: Support for nose tests is deprecated and will be removed in a future release.
  test_c.py::Test_C::test_002 is using nose-specific method: `setup(self)`
  To remove this warning, rename it to `setup_method(self)`
  See docs: https://docs.pytest.org/en/stable/deprecations.html#support-for-tests-written-for-nose
    fixture_result = next(generator)

test_c.py::Test_C::test_002
  D:\Z_Enviroment\python\ApiTestProject\lib\site-packages\_pytest\fixtures.py:917: PytestRemovedIn8Warning: Support for nose tests is deprecated and will be removed in a future release.
  test_c.py::Test_C::test_002 is using nose-specific method: `teardown(self)`
  To remove this warning, rename it to `teardown_method(self)`
  See docs: https://docs.pytest.org/en/stable/deprecations.html#support-for-tests-written-for-nose
    next(it)

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html

公式 Web サイトを読むと、setupと がteardownpytest のネイティブな使用法ではないことがsetup_methodわかります。teardown_method

ここに画像の説明を挿入します

変更して実行した後は、警告は表示されません。

ここに画像の説明を挿入します

何かを学ぶには、それがどのようになっているのか、そしてさらに重要なのは、なぜそうなのかを知る必要があります。

3.アサートアサート

参考ブログ:https://blog.csdn.net/kafu0/article/details/125180417

1. Unittest とは異なり、pytest はPython に付属するAssert
キーワードを使用してアサーションを作成します 2. Assert キーワードの後に​​式を続けることができます 式の最終結果が True である限り、アサーションは合格し、ユースケースは終了しますは正常に実行され、それ以外の場合はユースケースの実行に失敗しました

よく使用されるアサーションのまとめ

pytest のアサーションは、実際には Python のアサーション アサーション メソッドであり、以下が一般的に使用されます
xx をアサート: xx が真であると判断する
xx ではないをアサート: xx が真ではないを判断する
アサート a in b: b に
アサート a == が含まれていると判断するb: a が b に等しいと判断します
a != b をアサートします: a が b に等しくないことを判断します

新しいファイルを作成しtest_d.py、次のコードを記述します。

def test001():
    print("我是test_d下的test001")
    assert 1 == 1

def test002():
    print("我是test_d下的test002")
    assert 1 == 2

実行結果は次のとおりです。

============================= test session starts =============================
collecting ... collected 2 items

test_d.py::test001 PASSED                                                [ 50%]我是test_d下的test001

test_d.py::test002 FAILED                                                [100%]我是test_d下的test002

test_d.py:15 (test002)
1 != 2

Expected :2
Actual   :1
<Click to see difference>

def test002():
        print("我是test_d下的test002")
>       assert 1 == 2
E       assert 1 == 2

test_d.py:18: AssertionError


========================= 1 failed, 1 passed in 0.06s =========================

4. 運用と報告

コマンドライン実行

1. Pytest/test.py(终端,命令⾏,pycharm都⾏,可配置pycharm使⽤pytest⽅式执⾏)
	❖ Pytest –v (最⾼级别信息—verbose)
	❖ pytest -v -s ⽂件名 (s是带控制台输出结果,也是输出详细)

2. pytest将在当前⽬录及其⼦⽬录中运⾏test_*.py或*_test.py形式的所有⽂件。

3. 以test_开头的函数,以Test开头的类,以test_开头的⽅法。所有包package都要有__init__.py⽂件。

4. Pytest可以执⾏unittest框架写的⽤例和⽅法

上記の第 3.3 章で示したように、ルート ディレクトリに main.py ファイルを作成し、pytest をインポートしてユース ケースを収集して実行できます。これはコマンド ラインと同じ効果があります。

パラメータを追加する方法:

import pytest

pytest.main(["-s","-v"])

関連プラグイン

公式プラグイン リスト には、現時点で 1,100 を超えるプラグインが含まれています。

ここに画像の説明を挿入します

Pytest-html : 生成可视化报告

Pytest-rerunfailures : 失败重跑—reruns n, n是重复次数

Pytest-assume :多条断言有失败也都运行

Pytest-allure : 高大上精美报告

Pytest-xdist : 只支持多进程, pytest -n 2 在2个cpu上运行测试  —-looponfail标志,它将自动重新运行你的失败测试(不支持多线程)

Pytest-parallel :   1、同时支持多线程、多进程两种方式执行测试用例-workers=n       
                    2、指定运行的进程数为 n,默认为1,windows系统中只能为1
                    3、--tests-per-worker=m        指定运行的线程数为 m
                    4、若两个参数都指定,则表示启动n个进程,每个进程最多启动m线程执行,总线程数 = 进程数 * 线程数
                    5、windows系统中不支持 --workers 取其他值,即只能为1,mac或linux系统中可取其他值

Pytest-sugar : 改变pytest的默认外观,增加进度条,安装后即可

Pytest-picked : 运行基于你已修改但尚未提交给git的代码的测试。

Pytest-instafail : 修改默认行为,以立即显示失败和错误,而不是等到pytest完成每个测试运行。

Pytest-django : 开发web

Pytest-selenium : pytest提供运行支持selenium为基础

アリュールレポート

ここに表示されるテスト レポートは比較的包括的でよくできており、公式 Web サイトはPython、Java、JavaScript などの言語をサポートしています。

pytest-allure 公式ウェブサイトのチュートリアル

ここに画像の説明を挿入します

pytest-allure をインストールする

pip install allure-pytest

使い方

main.py のルート ディレクトリに新しいallureReportフォルダーを作成し、パスを相対パスとして入力します。

コマンドの実行

pytest --alluredir=allureReport

実行するpyファイル

import pytest

pytest.main(["-s","-v","--alluredir=allureReport"]) # 填如的是相对路径

実行後、allureReport に大量の json ファイルがあることがわかります。

ここに画像の説明を挿入します

allure コマンドを使用してレポートを生成する

テスト終了後に実際のレポートを確認するには、Allure コマンド ライン ユーティリティを使用して結果からレポートを生成する必要があります。

allure serve allureReport

ここでは allure コマンドを使用する必要があり、関連ツールをインストールする必要があります。

公式サイトのインストールリンク

ここに画像の説明を挿入します

下にスクロールして「手動インストール」を見つけます。ダウンロード アドレス中央リポジトリ: io/qameta/allure/allure-commandline (apache.org)

ここに画像の説明を挿入します

インストール後、allure を環境変数に設定する必要があります。

インストールと構成が成功したことを確認します。allure --version

ここに画像の説明を挿入します

cmd ウィンドウでプロジェクト ファイルのルート ディレクトリに移動し、実行します。allure serve allureReport

ここに画像の説明を挿入します

プロンプトに従ってレポートが生成され、Web ページでそのアドレスのレポートが自動的C:\Users\xiaozai\AppData\Local\Temp\5470331366185654759\allure-reportに開きます。http://192.168.12.85:7359

ここに画像の説明を挿入します

左下隅で言語を切り替えることができます。

この時点で、pytest の基本的な使い方をマスターしました。

おすすめ

転載: blog.csdn.net/qq_46158060/article/details/132429903