为每个问题生成一次随机值 Python

Generate random value once for every issue Python

我正在尝试为拍卖生成随机标题,然后在方法之外使用它。

add_consignment.py:

class AddConsignmentPage(BasePage):

    def __init__(self, driver):
        super(AddConsignmentPage, self).__init__(driver, self._title)
        self._title_uuid = get_random_uuid(7)

inst = AddConsignmentPage(AddConsignmentPage)

我想使用相同的 _title_uuid 查看添加的货物(在搜索字段中输入其标题)

view_consignments.py

from pages.add_consignment import inst
class ViewConsignmentsPage(BasePage):
    _title_uuid = inst._title_uuid

    def check_added_consignment(self):
        self.send_keys(self._title_uuid, self._auction_search)

在这种情况下,标题生成了两次,因此添加的寄售中的标题与搜索字段中的标题不同

那么如何将_title_uuid的值从AddConsignmentPage传递给ViewConsignmentsPage呢?我希望它在两种方法中是相同的,但对于每批货物(测试用例)都不同

如何为每批货物生成一次?

那是因为 _title_uuid 是一个 class variable 而不是实例变量:它只被初始化一次。但是如果你在构造函数中初始化它,它应该可以工作。

另见 Static class variables in Python

例如,

import random

class Foo:
    num1 = random.randint(1,10)

    def __init__(self):
        self.num2 = random.randint(1,10)

for n in range(10):
    foo = Foo()
    print(foo.num1, foo.num2)

运行 以上给出:

(7, 2)
(7, 6)
(7, 6)
(7, 5)
(7, 7)
(7, 1)
(7, 2)
(7, 3)
(7, 7)
(7, 7)

您也可以在此处执行 print(Foo.num1),如果这样可以说明任何问题,但不能 print(Foo.num2),因为它仅适用于实例化对象。

如您所见,num1 初始化一次,而 num2 为对象的每个实例化初始化。

在你的情况下,你可以这样做:

class AddConsignmentPage(BasePage):
    def __init__(self):
        super(AddConsignmentPage, self).__init__() # initializes BasePage
        self._title_uuid = get_random_uuid(7)

    # ...

我认为您应该在 __init__ 方法中定义 _title_uuid,因为 class 上的值每次都会更改。

你的情况可能是:

def __init__(self, *args, **kw):
   super(AddConsignmentPage, self).__init__(*args, **kw)
   self._title_uuid = get_random_uuid(7)

我已通过将 ViewConsignmentsPage._title_uuid = self._title_uuid 添加到初始化方法来解决问题

add_consignment.py:

from pages.view_consignments import ViewConsignmentsPage

class AddConsignmentPage(BasePage):

    def __init__(self, driver):
        super(AddConsignmentPage, self).__init__(driver, self._title)
        self._title_uuid = get_random_uuid(7)
        ViewConsignmentsPage._title_uuid = self._title_uuid