Мне любопытно, возможно ли что-то в этом духе, когда глобальный модуль может быть инициализирован в __main__
и, тем не менее, доступен для pytest, когда он работает с использованием механизма pytest.main()
.
Моя первоначальная попыткапохоже, отрицательно указывает на передачу глобального состояния в сессию pytest ...
import pytest
globalList = []
def test_globalList() :
global globalList
print( "globalList: {}".format( globalList))
assert globalList
if __name__ == '__main__':
print('Main Start')
globalList.append(1)
globalList.append(2)
globalList.append(3)
pytest_options = [ __file__ ]
print( "globalList: {}".format( globalList))
print('\n\n\n\n')
pytest.main( pytest_options ) # run pytest for just this file
print('Main Complete')
Я получаю следующий вывод консоли
Main Start
globalList: [1, 2, 3]
=================================== test session starts ================
platform darwin -- Python 2.7.10, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: /Users/USER/, inifile:
collected 1 item
test_temp.py F [100%]
=================================== FAILURES ===========================
___________________________________ test_globalList ____________________
def test_globalList() :
print( "globalList: {}".format( globalList))
> assert globalList
E assert []
test_temp.py:39: AssertionError
----------------------------------- Captured stdout call ---------------
globalList: []
=================================== 1 failed in 0.09 seconds ===========
Main Complete
Какую концепцию в pytest я не понимаюэто предупредило бы меня заранее, что такая попытка невозможна.Есть ли способ поделиться глобальным состоянием в вызове pytest.main
?
UPDATE
оказалось, что globalList - это совершенно новый экземпляр, но процесс и потоки совпадают воба случая.Загрузка модуля происходит в контексте pytest, который полностью отделен от контекста main .Цитирование заметки из документации
Note
Вызов pytest.main () приведет к импорту ваших тестов и всех импортируемых ими модулей.
import pytest
import os
import threading
globalList = []
print( "\n__name__ : {}".format( __name__ ))
print("process ID : {}".format(hex(os.getpid())))
cur_thread = threading.current_thread()
print( "thread ID : {}".format( hex(id(cur_thread )) ))
print( "thread Name : {}".format( cur_thread.name ))
print( "globalList ID : {}".format(hex(id(globalList))))
def test_globalList() :
global globalList
print( "globalList: {}".format( globalList)) # TODO this will be empty in the pytest session, somehow this approach fails to bring this variable into scope.
assert globalList
if __name__ == '__main__':
print('Main Start')
globalList.append(1)
globalList.append(2)
globalList.append(3)
pytest_options = [ __file__ , '-s']
print( "globalList: {}".format( globalList))
print('\n\n\n\n')
pytest.main( pytest_options ) # run pytest for just this file
print('Main Complete')
И соответствующий вывод консоли ...
__name__ : __main__
process ID : 0xa43e
thread ID : 0x10ac9b190
thread Name : MainThread
globalList ID : 0x10b476320
Main Start
globalList: [1, 2, 3]
=================================== test session starts ================
platform darwin -- Python 2.7.10, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: /Users/USER, inifile:
plugins: lazy-fixture-0.5.1, html-1.20.0, metadata-1.8.0
collecting ...
__name__ : test_temp
process ID : 0xa43e
thread ID : 0x10ac9b190
thread Name : MainThread
globalList ID : 0x10bb46128
collected 1 item
test_temp.py globalList: []
F
=================================== FAILURES ===========================
___________________________________ test_globalList ____________________
def test_globalList() :
global globalList
print( "globalList: {}".format( globalList))
> assert globalList
E assert []
test_temp.py:50: AssertionError
=================================== 1 failed in 0.10 seconds ===========
Main Complete
И сразу же появляются некоторые различия, имя модуля и адрес в списке разные ...
__name__ : __main__ test_temp <--different
process ID : 0xa43e 0xa43e
thread ID : 0x10ac9b190 0x10ac9b190
thread Name : MainThread MainThread
globalList ID : 0x10b476320 0x10bb46128 <--different