import time def pytest_funcarg__echoserver(request)def setup() subprocess popen['python ''echo_server py']time sleep( return def cleanup( ) terminate(return request cached_setupsetup=setupteardown=cleanupscope="session"def pytest_funcarg__clientsocket(request) socket socket(socket af_inetsocket sock_streams connect(('localhost' )request addfinalizer(lambdas close()return def test_echo(echoserverclientsocket)clientsocket send( "abc"assert clientsocket recv( = 'abcdef test_echo (echoserverclientsocket)clientsocket send( "def"assert clientsocket recv( = 'defwe've created two funcargs here the first runs the echo server in separate processand returns the process object the second instantiates new socket object for each testand closes it when the test has completedusing addfinalizer the first funcarg is the one we're currently interested in it looks much like traditional unit test setup and teardown we create setup function that accepts no parameters and returns the correct argumentin this casea process object that is actually ignored by the testssince they only care that the server is running thenwe create cleanup function (the name of the function is arbitrary since it' just an object we pass into another function)which accepts single argumentthe argument returned by setup this cleanup code terminates the process