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

标签 python selenium nose

我最近切换到了一个新项目,我们所有的 selenium 测试都是用 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()

我在想有没有办法将整个self.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

这样,您将能够在测试中使用导航类。另外,您可以将所有导航元素保留在一个地方

关于python - 使用装饰器进行重构以减少代码量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37878872/

相关文章:

python - xpath:元素中的元素

java - 等待模式在 Selenium 2.0 中消失

Django-nose 不会运行单独的 TestCase 类

python - 如何在 shell 中跳过用 nose.plugins.attrib.attr 修饰的类的 nosetests

python - 如何删除没有扩展名的文件?

python - 如何打印文本文件中的某些行和行的某些部分

python - 伪造对象是否是 Python 中类的实例

python - 对无响应的 Flask 路由的调用设置超时(更新)

python - 在 Nose 测试中打印不同的长描述以及测试名称 python

java - Selenium 驱动程序中的随机警报,我该如何处理?