Search code examples
djangoseleniumfunctional-testing

Django tests: Don't close selenium driver after each test


I have a test suite that includes a lot of tests for selenium. Now, I have a lot of tests, and they take quite a while, so I am trying to speed up the process.

Part of the issue is that it takes quite some time for selenium to close and reopen firefox between each test. I don't see why it should either. I realise that we don't want things like login sessions to carry over between tests, but say we had a way of clearing it.

So, before any tests run, I want a driver to open firefox. All tests use this driver, and sessions are cleared between each test. After all tests have finished, the driver should close.

I am not sure how to accomplish this. I have initialized the driver in a file that all tests import, which will successfully keep the window open, but I don't know how to close it when tests have finished.

Are the some way to capture test_start and test_end events or something? I havn't been able to find documentation.


Solution

  • Keeping a single Selenium driver across multiple tests is a kind of global state. The entity responsible for setting up and tearing down the global state is the test runner. You could do it this way:

    1. Have your utility library export a function like get_driver() which starts a driver if no driver was started or returns the already existing driver.

    2. I presume that you have some tests (e.g. model tests) that don't need Selenium. Have the tests that do need a driver call get_driver(). (This does not need to be test by test. If all the tests in a test class need a driver then setUp could make one call.) This way a driver is not started for tests that don't need it.

    3. Have a custom test runner tell the utility library to close any driver that it may have running.

    Here is the documentation about defining a new test runner.