Class 从不同的PyTest文件中使用相同的对象?

Class 从不同的PyTest文件中使用相同的对象?,class,object,pytest,fixture,Class,Object,Pytest,Fixture,我现在和pytest一起工作。我的问题是,我需要在另一个test_file2.py中使用在一个test_file1.py中生成的相同对象,该对象位于两个不同的目录中,并分别从另一个目录调用 代码如下: $ testhandler.py # Starts the first testcases returnValue = pytest.main(["-x", "--alluredir=%s" % test1_path, "--junitxml=%s" % test1_path+"\\JunitO

我现在和pytest一起工作。我的问题是,我需要在另一个test_file2.py中使用在一个test_file1.py中生成的相同对象,该对象位于两个不同的目录中,并分别从另一个目录调用

代码如下:

$ testhandler.py

# Starts the first testcases
returnValue = pytest.main(["-x", "--alluredir=%s" % test1_path, "--junitxml=%s" % test1_path+"\\JunitOut_test1.xml", test_file1]) 

# Starts the second testcases
pytest.main(["--alluredir=%s" % test2_path, "--junitxml=%s" % test2_path+"\\JunitOut_test2.xml", test_file2])
正如您所看到的,第一个是关键的,因此我以-x开始它,以便在出现错误时中断。并且--alluredir在开始新测试之前删除目标目录。这就是为什么我决定在testhandler.py中调用pytest两次(以后可能会更频繁)

以下是测试文件:

$ test1_directory/test_file1.py

@pytest.fixture(scope='session')
def object():
    # Generate reusable object from another file

def test_use_object(object):
    # use the object generated above
请注意,该对象实际上是一个具有参数和函数的类

$ test2_directory/test_file2.py

def test_use_object_from_file1():
    # reuse the object 
我试图在testhandler.py文件中生成该对象,并将其导入两个testfile。问题在于该对象与testhandler.py或test_file1.py中的对象不完全相同

我现在的问题是,是否有可能使用一个生成的对象。可能是用一个global conftest.py或类似的东西


谢谢你抽出时间

完全相同是指类似的物体,对吗?唯一的方法是在第一个进程中封送它,在另一个进程中取消封送。一种方法是使用
json
pickle
作为封送器,并传递用于json/pickle文件的文件名,以便能够读回对象

以下是一些未经测试的示例代码:

# conftest.py

def pytest_addoption(parser):
    parser.addoption("--marshalfile", help="file name to transfer files between processes")

@pytest.fixture(scope='session')
def object(request):
    filename = request.getoption('marshalfile')
    if filename is None:
        raise pytest.UsageError('--marshalfile required')

    # dump object
    if not os.path.isfile(filename):
        obj = create_expensive_object()
        with open(filename, 'wb') as f:
            pickle.dump(f, obj)
    else:
        # load object, hopefully in the other process
        with open(filename, 'rb') as f:
            obj = pickle.load(f)

    return obj