Python unittest passing arguments to parent test class

蹲街弑〆低调 提交于 2019-12-02 05:18:40

I also struggled to run the same test cases on multiple browsers. After a lot of iterations, trial and error and input from friends I implemented the following solutions to my projects:

Here TestCase is the class that has all the tests and the browser driver is None. SafariTestCase inherits the TestCase and overrides setUpClass and sets the browser driver to be safari driver and same with the ChromeTestCase and you can add more class for other browsers. Command Line input can be taken in the TestSuite file and conditionally load tests based on the arguments:

class TestCase(unittest.TestCase):
  @classmethod
  def setUpClass(cls):
    cls.browser = None

  def test_1(self):
    self.assert(self.browser.find_element_by_id('test1')

  def test_2(self):
    self.assert(self.browser.find_element_by_id('test2')

  def test_3(self):
    self.assert(self.browser.find_element_by_id('test3')

  @classmethod
  def tearDownClass(cls):
    cls.browser.quit()


class SafariTestCase(TestCase):
  @classmethod:
  def setUpClass(cls):
    cls.browser = webdriver.Safari(executable_path='/usr/bin/safaridriver')

class ChromeTestCase(TestCase):
  @classmethod:
  def setUpClass(cls):
    cls.browser = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver')  

In the runner file TestSuite.py:

import TestCase as tc

if len(sys.argv) == 1:
  print("Missing arguments, tell a couple of browsers to test against.")
  sys.exit(1)

if sys.argv[1] == 'safari':
  test = unittest.TestLoader().loadTestsFromTestCase(tc.SafariTestCase)

if sys.argv[1] == 'chrome':
  test = unittest.TestLoader().loadTestsFromTestCase(lt.ChromeTestCase)

unittest.TextTestRunner().run(test)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!