Sophie

Sophie

distrib > Fedora > 18 > i386 > by-pkgid > 7f671eb35339cf812de52087b0d93519 > files > 389

python3-pytest-2.3.5-3.fc18.noarch.rpm



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>カスタムマーカーを使う</title>
    
    <link rel="stylesheet" href="../_static/sphinxdoc.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '2.2.4.0',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/translations.js"></script>
    <link rel="top" title="None" href="../index.html" />
    <link rel="up" title="使用方法と例" href="index.html" />
    <link rel="next" title="標準的な (Python) テスト探索の変更" href="pythoncollection.html" />
    <link rel="prev" title="パラメーターテスト" href="parametrize.html" /> 
  </head>
  <body>
    <div class="related">
      <h3>ナビゲーション</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../py-modindex.html" title="Pythonモジュール索引"
             >モジュール</a></li>
        <li class="right" >
          <a href="pythoncollection.html" title="標準的な (Python) テスト探索の変更"
             accesskey="N">次へ</a> |</li>
        <li class="right" >
          <a href="parametrize.html" title="パラメーターテスト"
             accesskey="P">前へ</a> |</li>
        <li><a href="../contents.html">pytest-2.2.4.0</a> &raquo;</li>
          <li><a href="index.html" accesskey="U">使用方法と例</a> &raquo;</li> 
      </ul>
    </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">目次</a></h3>
  <ul>
<li><a class="reference internal" href="#">カスタムマーカーを使う</a><ul>
<li><a class="reference internal" href="#id2">テスト関数をマークして実行時に選択</a></li>
<li><a class="reference internal" href="#id3">マーカーの登録</a></li>
<li><a class="reference internal" href="#scoped-marking">クラスまたはモジュール全体をマーキング</a></li>
<li><a class="reference internal" href="#k-text"><tt class="docutils literal"><span class="pre">-k</span> <span class="pre">TEXT</span></tt> を使ったテストの選択</a></li>
<li><a class="reference internal" href="#adding-a-custom-marker-from-a-plugin">カスタムマーカーとコマンドラインオプションによるテストの実行制御</a></li>
<li><a class="reference internal" href="#id6">複数の場所から設定されたマーカーを読み込む</a></li>
</ul>
</li>
</ul>

  <h4>前のトピックへ</h4>
  <p class="topless"><a href="parametrize.html"
                        title="前の章へ">パラメーターテスト</a></p>
  <h4>次のトピックへ</h4>
  <p class="topless"><a href="pythoncollection.html"
                        title="次の章へ">標準的な (Python) テスト探索の変更</a></p>
<div id="searchbox" style="display: none">
  <h3>クイック検索</h3>
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="検索" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    モジュール、クラス、または関数名を入力してください
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="mark-examples">
<span id="id1"></span><h1>カスタムマーカーを使う<a class="headerlink" href="#mark-examples" title="このヘッドラインへのパーマリンク">¶</a></h1>
<p>ここでは <a class="reference internal" href="../mark.html#mark"><em>属性をもつテスト関数のマーク</em></a> の仕組みを使ったサンプルを紹介します。</p>
<div class="section" id="id2">
<h2>テスト関数をマークして実行時に選択<a class="headerlink" href="#id2" title="このヘッドラインへのパーマリンク">¶</a></h2>
<p>次のようにカスタムメタデータでテスト関数を &#8220;マーク&#8221; できます:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># test_server.py の内容</span>

<span class="kn">import</span> <span class="nn">pytest</span>
<span class="nd">@pytest.mark.webtest</span>
<span class="k">def</span> <span class="nf">test_send_http</span><span class="p">():</span>
    <span class="k">pass</span> <span class="c"># アプリの webtest テストを実行</span>
<span class="k">def</span> <span class="nf">test_something_quick</span><span class="p">():</span>
    <span class="k">pass</span>
</pre></div>
</div>
<p class="versionadded">
<span class="versionmodified">バージョン 2.2 で追加.</span></p>
<p><tt class="docutils literal"><span class="pre">webtest</span></tt> でマークされたテストのみを実行するように制限できます:</p>
<div class="highlight-python"><pre>$ py.test -v -m webtest
=========================== test session starts ============================
platform linux2 -- Python 2.7.1 -- pytest-2.2.4 -- /home/hpk/venv/0/bin/python
collecting ... collected 2 items

test_server.py:3: test_send_http PASSED

=================== 1 tests deselected by "-m 'webtest'" ===================
================== 1 passed, 1 deselected in 0.00 seconds ==================</pre>
</div>
<p>もしくは逆に webtest を除く全てのテストを実行します:</p>
<div class="highlight-python"><pre>$ py.test -v -m "not webtest"
=========================== test session starts ============================
platform linux2 -- Python 2.7.1 -- pytest-2.2.4 -- /home/hpk/venv/0/bin/python
collecting ... collected 2 items

test_server.py:6: test_something_quick PASSED

================= 1 tests deselected by "-m 'not webtest'" =================
================== 1 passed, 1 deselected in 0.00 seconds ==================</pre>
</div>
</div>
<div class="section" id="id3">
<h2>マーカーの登録<a class="headerlink" href="#id3" title="このヘッドラインへのパーマリンク">¶</a></h2>
<p class="versionadded">
<span class="versionmodified">バージョン 2.2 で追加.</span></p>
<p>テストスイートにマーカーを登録するのは登録です:</p>
<div class="highlight-python"><pre># pytest.ini の内容
[pytest]
markers =
    webtest: mark a test as a webtest.</pre>
</div>
<p>テストスイートに存在するマーカーが調べます。次の一覧では、先ほど定義した <tt class="docutils literal"><span class="pre">webtest</span></tt> マーカーがあります:</p>
<div class="highlight-python"><pre>$ py.test --markers
@pytest.mark.webtest: mark a test as a webtest.

@pytest.mark.skipif(*conditions): skip the given test function if evaluation of all conditions has a True value.  Evaluation happens within the module global context. Example: skipif('sys.platform == "win32"') skips the test if we are on the win32 platform.

@pytest.mark.xfail(*conditions, reason=None, run=True): mark the the test function as an expected failure. Optionally specify a reason and run=False if you don't even want to execute the test function. Any positional condition strings will be evaluated (like with skipif) and if one is False the marker will not be applied.

@pytest.mark.parametrize(argnames, argvalues): call a test function multiple times passing in multiple different argument value sets. Example: @parametrize('arg1', [1,2]) would lead to two calls of the decorated test function, one with arg1=1 and another with arg1=2.

@pytest.mark.tryfirst: mark a hook implementation function such that the plugin machinery will try to call it first/as early as possible.

@pytest.mark.trylast: mark a hook implementation function such that the plugin machinery will try to call it last/as late as possible.</pre>
</div>
<p>プラグインからマーカーを追加して処理するサンプルについては <a class="reference internal" href="#adding-a-custom-marker-from-a-plugin"><em>カスタムマーカーとコマンドラインオプションによるテストの実行制御</em></a> を参照してください。</p>
<div class="admonition note">
<p class="first admonition-title">ノート</p>
<p>次のように明示的にマーカーを登録することを推奨します:</p>
<ul class="last simple">
<li>テストスイートの一箇所でマーカーを定義する</li>
<li><tt class="docutils literal"><span class="pre">py.test</span> <span class="pre">--markers</span></tt> で既存のマーカーに関する分かりやすい説明を表示する</li>
<li><tt class="docutils literal"><span class="pre">--strict</span></tt> オプションを使うと、関数マーカー内の誤字をエラーにします、最近の py.test バージョンでは、未登録マーカーをエラーとして扱うようにしています</li>
</ul>
</div>
</div>
<div class="section" id="scoped-marking">
<span id="id4"></span><h2>クラスまたはモジュール全体をマーキング<a class="headerlink" href="#scoped-marking" title="このヘッドラインへのパーマリンク">¶</a></h2>
<p>Python 2.6 か、それ以上のバージョンでコーディングしているなら、クラスのテストメソッド全てにマーカーを適用するために <tt class="docutils literal"><span class="pre">pytest.mark</span></tt> をクラスデコレーターとして使えます:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># test_mark_classlevel.py の内容</span>
<span class="kn">import</span> <span class="nn">pytest</span>
<span class="nd">@pytest.mark.webtest</span>
<span class="k">class</span> <span class="nc">TestClass</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">test_startup</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">pass</span>
    <span class="k">def</span> <span class="nf">test_startup_and_more</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">pass</span>
</pre></div>
</div>
<p>これは2つのテスト関数に直接デコレーターを適用するのと同じです。</p>
<p>Pythn 2.4 との後方互換性を維持するには、次のように TestClass に <tt class="docutils literal"><span class="pre">pytestmark</span></tt> 属性も設定できます:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">pytest</span>

<span class="k">class</span> <span class="nc">TestClass</span><span class="p">:</span>
    <span class="n">pytestmark</span> <span class="o">=</span> <span class="n">pytest</span><span class="o">.</span><span class="n">mark</span><span class="o">.</span><span class="n">webtest</span>
</pre></div>
</div>
<p>もしくは、複数のマーカーを使う必要がある場合はリストも使えます:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">pytest</span>

<span class="k">class</span> <span class="nc">TestClass</span><span class="p">:</span>
    <span class="n">pytestmark</span> <span class="o">=</span> <span class="p">[</span><span class="n">pytest</span><span class="o">.</span><span class="n">mark</span><span class="o">.</span><span class="n">webtest</span><span class="p">,</span> <span class="n">pytest</span><span class="o">.</span><span class="n">mark</span><span class="o">.</span><span class="n">slowtest</span><span class="p">]</span>
</pre></div>
</div>
<p>モジュールレベルのマーカーも設定できます:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">pytest</span>
<span class="n">pytestmark</span> <span class="o">=</span> <span class="n">pytest</span><span class="o">.</span><span class="n">mark</span><span class="o">.</span><span class="n">webtest</span>
</pre></div>
</div>
<p>この場合、そのモジュール内で定義されている全ての関数とメソッドに適用されます。</p>
</div>
<div class="section" id="k-text">
<h2><tt class="docutils literal"><span class="pre">-k</span> <span class="pre">TEXT</span></tt> を使ったテストの選択<a class="headerlink" href="#k-text" title="このヘッドラインへのパーマリンク">¶</a></h2>
<p>指定した引数に一致する名前のテストを実行するには <tt class="docutils literal"><span class="pre">-k</span></tt> コマンドラインオプションを使います:</p>
<div class="highlight-python"><pre>$ py.test -k send_http  # 前節で定義したサンプルを実行
=========================== test session starts ============================
platform linux2 -- Python 2.7.1 -- pytest-2.2.4
collecting ... collected 4 items

test_server.py .

=================== 3 tests deselected by '-ksend_http' ====================
================== 1 passed, 3 deselected in 0.01 seconds ==================</pre>
</div>
<p>また、そのキーワードに一致するものを除く全てのテストを実行することもできます:</p>
<div class="highlight-python"><pre>$ py.test -k-send_http
=========================== test session starts ============================
platform linux2 -- Python 2.7.1 -- pytest-2.2.4
collecting ... collected 4 items

test_mark_classlevel.py ..
test_server.py .

=================== 1 tests deselected by '-k-send_http' ===================
================== 3 passed, 1 deselected in 0.01 seconds ==================</pre>
</div>
<p>もしくは、クラスのみを選択するには次のようにします:</p>
<div class="highlight-python"><pre>$ py.test -kTestClass
=========================== test session starts ============================
platform linux2 -- Python 2.7.1 -- pytest-2.2.4
collecting ... collected 4 items

test_mark_classlevel.py ..

=================== 2 tests deselected by '-kTestClass' ====================
================== 2 passed, 2 deselected in 0.01 seconds ==================</pre>
</div>
</div>
<div class="section" id="adding-a-custom-marker-from-a-plugin">
<span id="id5"></span><h2>カスタムマーカーとコマンドラインオプションによるテストの実行制御<a class="headerlink" href="#adding-a-custom-marker-from-a-plugin" title="このヘッドラインへのパーマリンク">¶</a></h2>
<p>プラグインは、カスタムマーカーを提供して、そのマーカーに基づく特別な振る舞いを実装します。これは、コマンドラインオプションと、名前付きの環境の値に特化したテストを実行するためのパラメーター化されたテスト関数マーカーを追加する自己完結型のサンプルです:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># conftest.py の内容</span>

<span class="kn">import</span> <span class="nn">pytest</span>
<span class="k">def</span> <span class="nf">pytest_addoption</span><span class="p">(</span><span class="n">parser</span><span class="p">):</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">addoption</span><span class="p">(</span><span class="s">&quot;-E&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;env&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&quot;store&quot;</span><span class="p">,</span> <span class="n">metavar</span><span class="o">=</span><span class="s">&quot;NAME&quot;</span><span class="p">,</span>
        <span class="n">help</span><span class="o">=</span><span class="s">&quot;only run tests matching the environment NAME.&quot;</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">pytest_configure</span><span class="p">(</span><span class="n">config</span><span class="p">):</span>
    <span class="c"># 追加のマーカーを登録</span>
    <span class="n">config</span><span class="o">.</span><span class="n">addinivalue_line</span><span class="p">(</span><span class="s">&quot;markers&quot;</span><span class="p">,</span>
        <span class="s">&quot;env(name): mark test to run only on named environment&quot;</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">pytest_runtest_setup</span><span class="p">(</span><span class="n">item</span><span class="p">):</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">item</span><span class="p">,</span> <span class="n">item</span><span class="o">.</span><span class="n">Function</span><span class="p">):</span>
        <span class="k">return</span>
    <span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">item</span><span class="o">.</span><span class="n">obj</span><span class="p">,</span> <span class="s">&#39;env&#39;</span><span class="p">):</span>
        <span class="n">envmarker</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">item</span><span class="o">.</span><span class="n">obj</span><span class="p">,</span> <span class="s">&#39;env&#39;</span><span class="p">)</span>
        <span class="n">envname</span> <span class="o">=</span> <span class="n">envmarker</span><span class="o">.</span><span class="n">args</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
        <span class="k">if</span> <span class="n">envname</span> <span class="o">!=</span> <span class="n">item</span><span class="o">.</span><span class="n">config</span><span class="o">.</span><span class="n">option</span><span class="o">.</span><span class="n">env</span><span class="p">:</span>
            <span class="n">pytest</span><span class="o">.</span><span class="n">skip</span><span class="p">(</span><span class="s">&quot;test requires env </span><span class="si">%r</span><span class="s">&quot;</span> <span class="o">%</span> <span class="n">envname</span><span class="p">)</span>
</pre></div>
</div>
<p>この local プラグインを使うテストファイルです:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># test_someenv.py の内容</span>

<span class="kn">import</span> <span class="nn">pytest</span>
<span class="nd">@pytest.mark.env</span><span class="p">(</span><span class="s">&quot;stage1&quot;</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">test_basic_db_operation</span><span class="p">():</span>
    <span class="k">pass</span>
</pre></div>
</div>
<p>そのテストが必要とするものではない別の環境を指定して実行する例です:</p>
<div class="highlight-python"><pre>$ py.test -E stage2
=========================== test session starts ============================
platform linux2 -- Python 2.7.1 -- pytest-2.2.4
collecting ... collected 1 items

test_someenv.py s

======================== 1 skipped in 0.00 seconds =========================</pre>
</div>
<p>今度は正しく必要とする環境を指定して実行します:</p>
<div class="highlight-python"><pre>$ py.test -E stage1
=========================== test session starts ============================
platform linux2 -- Python 2.7.1 -- pytest-2.2.4
collecting ... collected 1 items

test_someenv.py .

========================= 1 passed in 0.00 seconds =========================</pre>
</div>
<p><tt class="docutils literal"><span class="pre">--markers</span></tt> オプションは利用できるマーカーの一覧を表示します:</p>
<div class="highlight-python"><pre>$ py.test --markers
@pytest.mark.env(name): mark test to run only on named environment

@pytest.mark.skipif(*conditions): skip the given test function if evaluation of all conditions has a True value.  Evaluation happens within the module global context. Example: skipif('sys.platform == "win32"') skips the test if we are on the win32 platform.

@pytest.mark.xfail(*conditions, reason=None, run=True): mark the the test function as an expected failure. Optionally specify a reason and run=False if you don't even want to execute the test function. Any positional condition strings will be evaluated (like with skipif) and if one is False the marker will not be applied.

@pytest.mark.parametrize(argnames, argvalues): call a test function multiple times passing in multiple different argument value sets. Example: @parametrize('arg1', [1,2]) would lead to two calls of the decorated test function, one with arg1=1 and another with arg1=2.

@pytest.mark.tryfirst: mark a hook implementation function such that the plugin machinery will try to call it first/as early as possible.

@pytest.mark.trylast: mark a hook implementation function such that the plugin machinery will try to call it last/as late as possible.</pre>
</div>
</div>
<div class="section" id="id6">
<h2>複数の場所から設定されたマーカーを読み込む<a class="headerlink" href="#id6" title="このヘッドラインへのパーマリンク">¶</a></h2>
<p>テストスイート内でマーカーをたくさん使うと、テスト関数に対して数回マーカーが適用される場合があります。プラグインコードから、そういった全ての設定を読み込めます。サンプルを紹介します:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># test_mark_three_times.py の内容</span>
<span class="kn">import</span> <span class="nn">pytest</span>
<span class="n">pytestmark</span> <span class="o">=</span> <span class="n">pytest</span><span class="o">.</span><span class="n">mark</span><span class="o">.</span><span class="n">glob</span><span class="p">(</span><span class="s">&quot;module&quot;</span><span class="p">,</span> <span class="n">x</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>

<span class="nd">@pytest.mark.glob</span><span class="p">(</span><span class="s">&quot;class&quot;</span><span class="p">,</span> <span class="n">x</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">TestClass</span><span class="p">:</span>
    <span class="nd">@pytest.mark.glob</span><span class="p">(</span><span class="s">&quot;function&quot;</span><span class="p">,</span> <span class="n">x</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>
    <span class="k">def</span> <span class="nf">test_something</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">pass</span>
</pre></div>
</div>
<p>ここでは、同じテスト関数に対して3回適用される &#8220;glob&#8221; マーカーがあります。conftest ファイルから次のようにしてそれを調べます:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># conftest.py の内容</span>

<span class="k">def</span> <span class="nf">pytest_runtest_setup</span><span class="p">(</span><span class="n">item</span><span class="p">):</span>
    <span class="n">g</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">item</span><span class="o">.</span><span class="n">obj</span><span class="p">,</span> <span class="s">&#39;glob&#39;</span><span class="p">,</span> <span class="bp">None</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">g</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
        <span class="k">for</span> <span class="n">info</span> <span class="ow">in</span> <span class="n">g</span><span class="p">:</span>
            <span class="k">print</span> <span class="p">(</span><span class="s">&quot;glob args=</span><span class="si">%s</span><span class="s"> kwargs=</span><span class="si">%s</span><span class="s">&quot;</span> <span class="o">%</span><span class="p">(</span><span class="n">info</span><span class="o">.</span><span class="n">args</span><span class="p">,</span> <span class="n">info</span><span class="o">.</span><span class="n">kwargs</span><span class="p">))</span>
</pre></div>
</div>
<p>標準出力を取得せずにこのテストを実行して、何が表示されるかを見てみましょう:</p>
<div class="highlight-python"><pre>$ py.test -q -s
collecting ... collected 2 items
..
2 passed in 0.01 seconds
glob args=('function',) kwargs={'x': 3}
glob args=('class',) kwargs={'x': 2}
glob args=('module',) kwargs={'x': 1}</pre>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>ナビゲーション</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../py-modindex.html" title="Pythonモジュール索引"
             >モジュール</a></li>
        <li class="right" >
          <a href="pythoncollection.html" title="標準的な (Python) テスト探索の変更"
             >次へ</a> |</li>
        <li class="right" >
          <a href="parametrize.html" title="パラメーターテスト"
             >前へ</a> |</li>
        <li><a href="../contents.html">pytest-2.2.4.0</a> &raquo;</li>
          <li><a href="index.html" >使用方法と例</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer">
        &copy; Copyright 2011, holger krekel et alii.
      このドキュメントは <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.1.3 で生成しました。
    </div>
  </body>
</html>