微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用装饰器进行重构以减少代码量

我最近切换到一个新项目,并且我们所有的硒测试都是用Python编写的.我想知道我是否可以通过使用装饰器来减少代码

我们现在得到的是:

class BasePage(object):
    view_button = ".//a[text()='View']"
    create_button = ".//a[text()='Create']"
    #some code here

class BaseTestCase(unittest.TestCase):
    setUpclass(cls):
    #code here

    def find(cls,xpath):
        return cls.driver.find_element_by_xpath(xpath)


class SomeTest(BaseTestCase):
    def test_00_something(self):
        self.find(self.view_button).click()

我在想有一种方法可以将Wholeself.find(self.view_button).click()最小化为click.view_button

我听说可以使用装饰器完成此操作,但是作为Java语言的人,我在此方面获得的成功很少.

解决方法:

您还可以检查以下解决方案;使用创建新模块-navigation.py:

class Button():

    def __init__(self,driver, locator):
        self.driver = driver
        self.locator = locator

    @property
    def click(self):
        return self.driver.find_element_by_xpath(self.locator).click()

class Navigation():

    """NAVIGATION COMMANDS """
    def goTo(self):
        #somethign

    def prevIoUsPage(self):
        #something

    """ BUTTONS """
    @property
    def view_button(self):
        xpath = ".//a[text()='View']"
        view = Button(self.driver,xpath)
        return view

   @property
   def create_button(self):
       xpath = ".//a[text()='Create']"
       create = Button(self.driver,xpath)
       return create

在basetestcase.py中:

class BaseTestCase(unittest.TestCase, Navigation)

      setUpClass(cls):
      #somethign here

并且您的测试用例将如下所示:

class TestSomething(BaseTestCase):

     def test_99_somethign(self):
         #finds .//a[text()='View'] and clicks
         self.view.click

         #create button
         self.create_button.click

这样,您将可以在测试中使用导航类.另外,您可以将所有导航元素放在一个位置

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐