Search code examples
pythongoogle-chromeuser-interfaceselenium-webdriverautomated-tests

Possible to sequentially run multiple python scripts in the same selenium session?


I'm taking a shot at UI automation and I was wondering if it was possible to run tests from multiple python scripts in order in the same session?

So for example:

Script 1: Test to Login

Script 2: Test to click button

Script 3: Test to Logout

versus having a single script do all three tests in a single script.

I tried creating a BAT file that will initiate each script one by one, but it will open a new browser window for each execution.

note: Of course my actual code is much more complex and has many more test cases :) I just want to know if its even possible. Looking it up has been weird. Not sure how to word it out in a way where google would understand lol.


Solution

  • There's a Python Selenium framework called SeleniumBase that can do exactly that.

    After pip install -U seleniumbase, you can run pytest --rs on the following script to reuse the browser session between tests. (There's a special part added at the top to automatically call pytest with those args if calling python directly):

    from seleniumbase import BaseCase
    
    if __name__ == "__main__":
        from pytest import main
        main([__file__, "--rs"])
    
    class MyTestClass(BaseCase):
        def test_1(self):
            self.open("https://google.com")
            self.sleep(1)
    
        def test_2(self):
            self.open("https://facebook.com")
            self.sleep(1)
    
        def test_3(self):
            self.open("https://seleniumbase.io")
            self.sleep(1)
    
        def test_4(self):
            self.open("https://seleniumbase.com")
            self.sleep(1)
    

    The --rs option will make all tests reuse the same browser session. To access the driver that you have via regular selenium, use self.driver.