Refactor a bunch of stuff re: session closing, add test cases