Fix file descriptor leaks in tests by properly closing resources

Signed-off-by: Raul Gutierrez S <rgs@itevenworks.net>
Reported-by: Santtu Voutilainen <santtu@twitter.com>