| | 1 | import httplib |
| | 2 | import socket |
| | 3 | |
| | 4 | from django.conf import settings |
| | 5 | from django.test.testcases import LiveServerTestCase |
| | 6 | from django.utils.unittest import skipUnless, SkipTest |
| | 7 | |
| | 8 | try: |
| | 9 | from selenium import selenium |
| | 10 | except ImportError: |
| | 11 | selenium_installed = False |
| | 12 | else: |
| | 13 | selenium_installed = True |
| | 14 | |
| | 15 | _NOT_INSTALLED_MSG = "The 'selenium' package isn't installed" |
| | 16 | _CANT_CONNECT_MSG = ("Can't connect to the Selenium server using address" |
| | 17 | " %s and port %s") |
| | 18 | |
| | 19 | |
| | 20 | class SeleniumRCTestCase(LiveServerTestCase): |
| | 21 | """ |
| | 22 | Does basically the same as TestServerTestCase but also connects to the |
| | 23 | Selenium RC server. The selenium client is then available with |
| | 24 | 'self.selenium'. The requirements are to have the 'selenium' installed in |
| | 25 | the python path and to have the Selenium RC server running. If those |
| | 26 | requirements are not filled then the tests will be skipped. |
| | 27 | """ |
| | 28 | _selenium_server_running = None |
| | 29 | |
| | 30 | @property |
| | 31 | def selenium_server_running(self): |
| | 32 | """ |
| | 33 | Determine if we can connect to the Selenium RC server. |
| | 34 | Only evaluated once for performance reasons. |
| | 35 | """ |
| | 36 | if SeleniumRCTestCase._selenium_server_running is not None: |
| | 37 | return SeleniumRCTestCase._selenium_server_running |
| | 38 | |
| | 39 | try: |
| | 40 | conn = httplib.HTTPConnection(settings.SELENIUM_RC_HOST, |
| | 41 | settings.SELENIUM_RC_PORT) |
| | 42 | try: |
| | 43 | conn.request("GET", "/selenium-server/driver/", '', {}) |
| | 44 | finally: |
| | 45 | conn.close() |
| | 46 | SeleniumRCTestCase._selenium_server_running = True |
| | 47 | except socket.error: |
| | 48 | SeleniumRCTestCase._selenium_server_running = False |
| | 49 | |
| | 50 | return SeleniumRCTestCase._selenium_server_running |
| | 51 | |
| | 52 | def setUp(self): |
| | 53 | if not self.selenium_server_running: |
| | 54 | message = (_CANT_CONNECT_MSG % (settings.SELENIUM_RC_HOST, |
| | 55 | settings.SELENIUM_RC_PORT)) |
| | 56 | raise SkipTest(message) |
| | 57 | |
| | 58 | super(SeleniumRCTestCase, self).setUp() |
| | 59 | |
| | 60 | # Launch the Selenium server |
| | 61 | self.selenium = selenium( |
| | 62 | settings.SELENIUM_RC_HOST, |
| | 63 | int(settings.SELENIUM_RC_PORT), |
| | 64 | settings.SELENIUM_RC_BROWSER, |
| | 65 | self.live_test_server_url) |
| | 66 | self.selenium.start() |
| | 67 | |
| | 68 | def tearDown(self): |
| | 69 | super(SeleniumRCTestCase, self).tearDown() |
| | 70 | self.selenium.stop() |
| | 71 | |
| | 72 | SeleniumRCTestCase = skipUnless(selenium_installed, |
| | 73 | _NOT_INSTALLED_MSG)(SeleniumRCTestCase) |