I've witten a few functional tests using the StaticLiveServerCase. This works great for local testing, but now I'd like to test my staging server as well. The author of the book I'm reading suggests the following hack:
import sys
[...]
class NewVisitorTest(StaticLiveServerCase):
@classmethod
def setUpClass(cls):
for arg in sys.argv:
if 'liveserver' in arg:
cls.server_url = 'http://' + arg.split('=')[1]
return
super().setUpClass()
cls.server_url = cls.live_server_url
@classmethod
def tearDownClass(cls):
if cls.server_url == cls.live_server_url:
super().tearDownClass()
# Now use self.server_url instead of self.live_server_url
I adjusted it to call super(LiveServerTestCase, cls).setUpClass() (as well as tearDownClass) instead, when not using the "temporary server", because bluntly ignoring the (grand)parent's implementation feels wrong.
Still it's a hack, and I'd like to know if cleaner solutions exist. Django does have a --liveserver argument of its own, but it can only be used to change the bindings of the temporary server.
So far, I've come up with the following ideas:
StaticLiveServerCase to parse the argument, change the live_server_url property accordingly, and let the temporary server just be started/stopped unused. Costs some performance and in theory, makes the tests less reliable.StaticLiveServerCase or some StagingServerTestCase subclassing TransactionTestCase) at runtime. This is not much less of a hack, and my IDE probably isn't going to like it either.StaticLiveServerTestCase or TransactionTestCase (composition instead of inheritance). Looks like a lot of work to achieve this one thing.Although this hack might work, I think it would be better to use a tool made for testing remote servers.
The most known tool is Selenium, which have a good integration with Django. A test with Django + Selenium would look a lot like the tests you did with StaticLiveServerTestCase, eg:
class MyTestCase(SeleniumLiveTestCase):
def test_home(self):
self.driver.open_url(reverse('main'))
self.assertEquals(self.driver.get_title(), 'Sample Test Page')
self.driver.type_in('input#id_query', 'search something')
self.driver.click('.form-search button[type="submit"]')
self.assertEquals(self.driver.get_text('#success'), 'SUCCESS')
Django-Selenium works either with local and remote servers, take a look at its settings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With