2017-01-17 18 views
0

即時通訊工作pytest權利知道。我的問題是我需要使用另一個test_file2.py中的test_file1.py中生成的同一個對象,這些對象位於兩個不同的目錄中,並分別從另一個目錄中調用。從不同的PyTest測試文件中使用相同的對象?

繼承人的代碼:

$ 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(moreoften在未來也許)

這裏是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中的對象不一樣。

我的問題是現在是否有可能使用excatly那一個生成的對象。也許在全球conftest.py或類似的東西。

謝謝你的時間!

回答

0

完全一樣,你的意思是一個類似的對象,對吧?做到這一點的唯一方法是在第一個過程中對其進行編組,並在另一個過程中對其進行解組。一種方法是使用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 
相關問題