0

im working with pytest right know. My Problem is that I need to use the same object generated in one test_file1.py in another test_file2.py which are in two different directories and invoked separately from another.

Heres the code:

$ 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])

As you can see the first one is critical, therefore I start it with -x to interrupt if there is an error. And --alluredir deletes the target directory before starting the new tests. Thats why I decided to invoke pytest twice in my testhandler.py (moreoften in the future maybe)

Here is are the 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

Note that the object is actually a class with parameters and functions.

$ test2_directory/test_file2.py

def test_use_object_from_file1():
    # reuse the object 

I tried to generate the object in the testhandler.py file and importing it to both testfiles. The problem was that the object was not excatly the same as in the testhandler.py or test_file1.py.

My question is now if there is a possibility to use excatly that one generated object. Maybe with a global conftest.py or something like that.

Thank you for your time!

shujin
  • 3
  • 1

1 Answers1

0

By exactly the same you mean a similar object, right? The only way to do this is to marshal it in the first process and unmarshal it in the other process. One way to do it is by using json or pickle as marshaller, and pass the filename to use for the json/pickle file to be able to read the object back.

Here's some sample code, untested:

# 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
Bruno Oliveira
  • 13,694
  • 5
  • 43
  • 41