"""tests for server sessions.""" from time import sleep from pytest_bdd import given, scenarios, then, when SESSION_NAME = "morethantext.sid" scenarios("../features/session.feature") def get_session_id(page): """Pulls the session id cookie.""" cookies = page.get_cookies() id_cookie = None for holder in cookies: if holder.name == SESSION_NAME: id_cookie = holder return id_cookie @given("a running server") def start_server(server): """Make a running server.""" server.set_safe_port() server.start() @given("the home page is accessed") def store_session_id(server, page, data_store): """Store the session id.""" page.request_url(f"http://{server.base_url}/") cookie = get_session_id(page) data_store["session"] = cookie.value @when("the home page is accessed") def access_home_page(server, page): """Access the home page.""" url = f"http://{server.base_url}/" page.request_url(url) @when("the server is restarted") def restart_server(server): """Restarts the server""" server.stop() sleep(1) server.start() @then("there is a default session id") def confirm_session(page): """Confirm session id exists.""" assert get_session_id( page ), f"Did not find cookie {SESSION_NAME}, but retrieved {page.get_cookies()}" @then("the session id remains the same") def check_session_id(page, data_store): """Checks the new session with the old.""" cookie = get_session_id(page) session = cookie.value assert ( session == data_store["session"] ), f"Session id became {session} but should have been {data_store['session']}"