Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

パート 5: テストランナーを導入する

このページにスクリプトエラーがあります。サイト編集者によって解決されるまでの間は、以下の部分的な内容のみが表示可能です。

{{ FirefoxOSSidebar }}

すべては、ここまでうまく進んでいます。しかし、まだ1つのテストのみを扱っています。実世界の大きなWebアプリケーションをテストする時には、数十または数百のテストケースである場合があり、それぞれを手動で実行することは絶対にしたくありません。このようなシナリオでは、我々は私たちのためにテストを見つけて実行するテストランナーを使用する必要があります。この記事ではただそれだけについて見ていきます。

テストランナー

テストランナーは、実際のテストフレームワークのための良好な基礎を提供します。テストランナーがテスト、属性を含むタグのテスト (アノテーション)を実行するように設計されて、レポートおよび他の機能を提供します。利用可能な多くのPythonのテストランナーがあります。しかし、この場合、効果的なシンプルで、PythonでパッケージされているようにPythonの独自の unittest を使います。

一般的には3つの標準のセクションにテストを分割します。テストランナーのセットアップのための典型的なsetUp()、tests、tearDown()
 
setUp()tearDown() メソッドはすべてのテストのために自動的に実行されて、それぞれ下記を含んでいます:

  • 画面ロックを解除し開いているアプリケーションを停止するといった、テストを実行する前に必要なセットアップの手順。
  • Marionetteセッションを閉じるといった、テスト後に実行に必要なクールダウンの手順。

セットアップのテスト部分では、実際のテストのために実行したい任意のコードです。第2-4部分の上に構築されたテストにこれを適用する方法を見てみましょう。

ユニットテストとtest_add_contact.pyの実行

最初のインポートのユニットテストに必要なユニットテストを使用するには、他のインポート行の下に次を追加してください。:

import unittest

次に、テストランナーを作成する必要があります。これを行うために、 unittest.Testcase クラスから TestContacts クラス継承を行います。つまり、class 行を下記に更新してください。:

class TestContacts(unittest.TestCase):

また、次のものを削除する必要があります:

    def __init__(self):
        self.test_add_contacts()

テストを初期化すると、代わりにユニットテストによって処理されますので、自分自身を処理する必要はありません。あなたのコードの下で、次のものを置き換えて:

if __name__ == '__main__':
    TestContacts()

下記を用います。:

if __name__ == '__main__':
    unittest.main()

次に、TestContacts クラス内部に setUp(self): メソッドを生成する必要があります。そして、次の手順を実施します。:

  1. Marionetteをインスタンス化し、Marionetteセッションを開始します
  2. 画面ロックを解除します
  3. 開いているすべてのアプリケーションを強制終了します
  4. 連絡先アプリをロードします

このメソッドは、以下のようになります。test_add_contacts で既にある同一の行を削除する必要があります。

    def setUp(self):
         # Create the client for this session. Assuming you're using the default port on a Marionette instance running locally
        self.marionette = Marionette()
        self.marionette.start_session()

        # Unlock the screen
        self.unlock_screen()

        # kill all open apps
        self.kill_all()

        # Switch context to the homescreen iframe
        time.sleep(2)
        home_frame = self.marionette.find_element('css selector', 'div.homescreen iframe')
        self.marionette.switch_to_frame(home_frame)

今のtearDown(self):メソッドを作成します。ここにMarionetteセッションを閉じるためのコードを追加する必要があります。メソッドは次のようになります。:

    def tearDown(self):
        # Close the Marionette session now that the test is finished
        self.marionette.delete_session()

ここでも、test_add_contacts から同じ行を削除することを忘れないでください。

今、前にしたとおりにテストを実行してみてください。これで、パスと失敗のレポートを取得することを確認できます。これは、ユニットテストやpy.testなどのテストランナーを使用する利点の一つです。

注意: あなたが動けなくなる場合は、インターネットのまわりのユニットテスト使用するガイドがたくさんあります。https://selenium-python.readthedocs.org/en/latest/getting-started.htmlhttps://assertselenium.com/2013/10/07/getting-started-with-python-webdriver/ をお勧めします。Pythonとwebdriverをするためのものであるが、これらはまだ関連しています。

参照コード

参考のため、この段階での私たちの最終的なコードは次のようになります:

import time
from marionette import Marionette
from marionette_driver import Wait
import unittest


class TestContacts(unittest.TestCase):

    def unlock_screen(self):
        self.marionette.execute_script('window.wrappedJSObject.lockScreen.unlock();')

    def kill_all(self):
        self.marionette.switch_to_frame()
        self.marionette.execute_async_script("""
             // Kills all running apps, except the homescreen.
             function killAll() {
               let manager = window.wrappedJSObject.AppWindowManager;

               let apps = manager.getApps();
               for (let id in apps) {
                 let origin = apps[id].origin;
                 if (origin.indexOf('verticalhome') == -1) {
                   manager.kill(origin);
                 }
               }
             };
             killAll();
             // return true so execute_async_script knows the script is complete
             marionetteScriptFinished(true);
            """)

    def setUp(self):
         # Create the client for this session. Assuming you're using the default port on a Marionette instance running locally
        self.marionette = Marionette()
        self.marionette.start_session()

        # Unlock the screen
        self.unlock_screen()

        # kill all open apps
        self.kill_all()

        # Switch context to the homescreen iframe and tap on the contacts icon
        time.sleep(2)
        home_frame = self.marionette.find_element('css selector', 'div.homescreen iframe')
        self.marionette.switch_to_frame(home_frame)


    def test_add_contacts(self):
        contacts_icon = self.marionette.find_element('xpath', "//div[@class='icon']//span[contains(text(),'Contacts')]")
        contacts_icon.tap()

        # Switch context back to the base frame
        self.marionette.switch_to_frame()
        Wait(self.marionette).until(lambda m: m.find_element('css selector', "iframe[data-url*='contacts']").is_displayed())

        # Switch context to the contacts app
        contacts_frame = self.marionette.find_element('css selector', "iframe[data-url*='contacts']")
        self.marionette.switch_to_frame(contacts_frame)

        # Tap [+] to add a new Contact
        self.marionette.find_element('id', 'add-contact-button').tap()
        Wait(self.marionette).until(lambda m: m.find_element('id', 'save-button').location['y']== 0)

        # Type name into the fields
        self.marionette.find_element('id', 'givenName').send_keys('John')
        self.marionette.find_element('id', 'familyName').send_keys('Doe')

        # Tap done
        self.marionette.find_element('id', 'save-button').tap()
        Wait(self.marionette).until(lambda m: not m.find_element('id', 'save-button').is_displayed())

    def tearDown(self):
        # Close the Marionette session now that the test is finished
        self.marionette.delete_session()

if __name__ == '__main__':
    unittest.main()

ドキュメントのタグと貢献者

 このページの貢献者: hamasaki, Uemmra3, shide55
 最終更新者: hamasaki,