Improve socket init and close in tests