Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Django's StaticLiveServerCase with staging server as well

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:

  • Subclassing 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.
  • Exploiting Python's dynamic typing to determine the base class (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.
  • Writing a third class that delegates to either StaticLiveServerTestCase or TransactionTestCase (composition instead of inheritance). Looks like a lot of work to achieve this one thing.
like image 573
Thijs van Dien Avatar asked Aug 21 '14 14:08

Thijs van Dien


1 Answers

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.

like image 153
Renan Ivo Avatar answered Oct 08 '22 10:10

Renan Ivo