【问题标题】:Using the same object from different PyTest testfiles?使用来自不同 PyTest 测试文件的相同对象?
【发布时间】:2017-01-17 15:41:30
【问题描述】:

我正在使用 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 两次(可能在将来更频繁)

这里是 test_files:

$ 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 文件中生成对象并将其导入到两个测试文件中。问题是该对象与 testhandler.py 或 test_file1.py 中的对象并不完全相同。

我现在的问题是是否有可能完全使用该生成的对象。也许使用全局 conftest.py 或类似的东西。

感谢您的宝贵时间!

【问题讨论】:

    标签: class object pytest fixture


    【解决方案1】:

    完全相同是指相似的对象,对吗?做到这一点的唯一方法是在第一个进程中编组它并在另一个进程中解组它。一种方法是使用 jsonpickle 作为编组器,并传递文件名以用于 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      • 2012-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多