Search code examples
pythonpython-3.xseleniummethodspython-class

How to execute methods in a class using Selenium and Python


I recently found the SeleniumIDE extension for Google Chrome, but there is something I don't understand...

from selenium import webdriver
from selenium.webdriver.common.by import By

class TestStealth():
 def setup_method(self, method):
 print("setup_method")
 self.driver = webdriver.Chrome()
 self.vars = {}

def teardown_method(self, method):
 self.driver.quit()

def test_stealth(self):
 print("Testing")
 self.driver.get("https://stealthxio.myshopify.com/products/stealthxio-practice")
 self.driver.set_window_size(968, 1039)

this is the code I get from selenium, when I try to run with:

run = TestStealth()
run.setup_method()
run.test_stealth()

I get an error in run.setup_method() as:

Missing 1 required positional argument: 'method'

Does anyone know what I am doing wrong?


Solution

  • This error message...

    Missing 1 required positional argument: 'method'
    

    ...implies that the setup_method() is missing a required positional argument, i.e. 'method'


    Analysis

    You were pretty close. As per the defination of setup_method(self, method) it expects an argument as method.

    def setup_method(self, method):
    

    But when you invoked setup_method() as in:

    run.setup_method()
    

    You haven't passed any argument. Hence there was a argument mismatch and you see the error.


    Solution

    To execute your tests with in the Class using Selenium you can use the following solution:

    • Code Block:

      class TestStealth():
          def setup_method(self):
              print("setup_method")
              self.driver = webdriver.Chrome(executable_path=r'C:\WebDrivers\chromedriver.exe')
              self.vars = {}
      
          def teardown_method(self):
             self.driver.quit()
      
          def test_stealth(self):
             print("Testing")
             self.driver.get("https://stealthxio.myshopify.com/products/stealthxio-practice")
             self.driver.set_window_size(968, 1039)    
      
      run = TestStealth()
      run.setup_method()
      run.test_stealth()
      
    • Console Output:

      setup_method
      
      DevTools listening on ws://127.0.0.1:51558/devtools/browser/88bf2c58-10da-4b03-9697-eec415197e66
      Testing
      
    • Browser Snapshot:

    stealth