LoginSignup
4
2

More than 5 years have passed since last update.

Test-Driven Development with Python をやってみた -1

Last updated at Posted at 2016-09-23

色々中途半端にしてるのに、新しいことを始めるのもどうかと思おうが、DjangoとTDDが同時に勉強できるお得な本があったので、実際にやってみることにした。

Test-Driven Development with Python

Cloudnに新しいUbuntuのvmを立って。
環境を準備。

$ sudo apt-get update

$ sudo apt-get upgrade

$ sudo apt install python3-venv python3-pip

$ pip install -U selenium
$ vim functional_tests.py
from selenium import webdriver

browser = webdriver.Firefox()
browser.get('http://localhost:8000')

assert 'Django' in browser.title

最初のテスト functional_tests.pyを実行した。
本だと次のようなエラーになるはずだが

$ python3 functional_tests.py
Traceback (most recent call last):
  File "functional_tests.py", line 6, in <module>
    assert 'Django' in browser.title
AssertionError

実際のエラーはこんな感じ、いきなり本の内容と違うエラーが発生。
Xが入っていないから当然か

$ python3 functional_tests.py
Traceback (most recent call last):
  File "functional_tests.py", line 3, in <module>
    browser = webdriver.Firefox()
  File "/home/ubuntu/venv/lib/python3.5/site-packages/selenium/webdriver/firefox/webdriver.py", line 80, in __init__
    self.binary, timeout)
  File "/home/ubuntu/venv/lib/python3.5/site-packages/selenium/webdriver/firefox/extension_connection.py", line 52, in __init__
    self.binary.launch_browser(self.profile, timeout=timeout)
  File "/home/ubuntu/venv/lib/python3.5/site-packages/selenium/webdriver/firefox/firefox_binary.py", line 68, in launch_browser
    self._wait_until_connectable(timeout=timeout)
  File "/home/ubuntu/venv/lib/python3.5/site-packages/selenium/webdriver/firefox/firefox_binary.py", line 99, in _wait_until_connectable
    "The browser appears to have exited "
selenium.common.exceptions.WebDriverException: Message: The browser appears to have exited before we could connect. If you specified a log_file in the FirefoxBinary constructor, check it for details.

解決するためにXvfb と pyvirtualdisplay をインストール

$ sudo apt-get install xvfb
$ sudo pip install pyvirtualdisplay

さらに、今のバージョンのだとエラーになるようなのでFirefoxのバージョンをさげたら

$ sudo apt-get install firefox=45.0.2+build1-0ubuntu1
$ sudo apt-mark hold firefox

これでやっと本と同じ結果が表示された

$ python3 functional_tests.py
Traceback (most recent call last):
  File "functional_tests.py", line 10, in <module>
    assert 'Django' in browser.title
AssertionError

Djangoプロジェクトを作成して、起動すると。

$ django-admin.py startproject superlists

$ python3 manage.py runserver

$ python3 functional_tests.py
$

テストは問題なく終了。

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2