このページにスクリプトエラーがあります。サイト編集者によって解決されるまでの間は、以下の部分的な内容のみが表示可能です。
この記事は編集レビューを必要としています。ぜひご協力ください。
{{ FirefoxOSSidebar }}
今、おそらく、進捗状況についてのかなり良く感じている複数のテストを持っています。しかし、さらなるコード効率を向上させる他の方法があります — これまでに、各テストファイルにおいて setUp()
と tearDown()
メソッドが含まれるように持っていたことがあります。 このシリーズで見てきた現在のコンストラクトで行きます。数十のテストを持っている場合、それはコードの重複がたくさんです! この記事では、TestBase
クラスのすべてのテストに共通なsetUp()
/tearDown()
コードを配置する方法を見てみましょう。これは、各個々のテストファイルにインポートすることができます。
test_base.py
開始するには、既存のテストケースと同じディレクトリに test_base.py
と呼ばれる新しいファイルを作成します。
次に、setUp()
と tearDown()
メソッドを含むTestBase
クラスに加えて、ファイルに共通の設定(unittest
, Marionette
and time
)に関連するあなたの大切な書類を移動します。そして、共通ヘルパー関数(unlock_screen()
のような)と関連付けられています。 ファイルには、次のようになります:
import time import unittest from marionette import Marionette class TestBase(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 tearDown(self): # Close the Marionette session now that the test is finished self.marionette.delete_session()
テストファイルの更新
作成された test_base.py
ファイルを使用して、TestBase
をテストファイルにインポートする必要があります。そして、テストクラスは、TestBase
クラスを拡張するために変更される必要があります。:
import unittest from marionette import Wait from marionette import By from test_base import TestBase class TestContacts(TestBase): def test(self): # Tests in here if __name__ == '__main__': unittest.main()
もう一度テストファイルを実行してみてください。
今は多くのように見えないかもしれないが、あなたは数十または数百のテストがある場合、これは実際に重複したコードの多くを保存します。