3

I'm a newbie on selenium and I wrote a little python script using selenium to test some functionalities on our website.

But I notice something strange in my code. I have several functions for example :

  1. Login to website
  2. List item
  3. Click on a link etc.

But, each time selenium hits the bottom of a function it closes the browser and I lose my session. This forces me to put all the test in just one function.

Is there a way to prevent this behavior? I'm using selenium RC not a Webdriver.

3
  • In case you are using junit4, you can put the opening of browser in setUp() method having annotation @Beforeclass and closing of browser in tearDown() method having annotation @AfterClass. In between, you can have multiple test methods for Login, Click on link, etc. as testLogin(), testClickOnLink(), etc. under annotation @Test
    – Subh
    Nov 12, 2014 at 15:24
  • jUnit is for Java. The OP is using python.
    – ddavison
    Nov 12, 2014 at 16:03
  • Have you tried to pass the Browser instance as a parameter for each function?
    – Pablo
    Nov 12, 2014 at 16:10

2 Answers 2

2

That is actually by design.

In order to keep a maintainable, independent test suite, you'll need your tests to close your browser.

Picture this:

class MyTestClass:
  def test_method1():
    test_something()

  def test_method2():
    test_something_else()

Once test_method1() has started running, it should have it's own browser instance, and should close it afterwards.

Once test_method2() has started running, it should have it's own browser, and close it afterwards. This is a good design to have. I'd recommend not changing it.

4
  • The fact is here I need a function for login to log into the website and another to click on links. Nov 12, 2014 at 16:56
  • 1
    Your test class shouldn't have helper methods like that.. You should create a "helper class" with those types of functions, then you could do something like: login_page.login() in your test method
    – ddavison
    Nov 12, 2014 at 19:17
  • OK will do :) Thx for the tip anyway Nov 14, 2014 at 7:57
  • sircapsalot is it possible to have the same session for the 2 test method you put in you comment ? Nov 14, 2014 at 7:58
1

I figure it out :) It seems that wen you remove the test_ from the beginning of the function I can setup function wihtout the browser to be closed

2
  • How is this a relevant answer? Apr 16, 2018 at 11:53
  • lol it worked XD (not really is a joke)
    – The Weird
    Jun 18, 2022 at 11:59

Not the answer you're looking for? Browse other questions tagged or ask your own question.