def test_500_code_run_script_during_add_tasks(self): """ - add tasks Expected: selenium log was saved and endpoint was deleted """ from vmpool.artifact_collector import ArtifactCollector with patch("core.network.Network", Mock()), patch("core.connection.Virsh", Mock()), patch('core.db.Database', DatabaseMock()): from core.sessions import Session session = Session(dc={'platform': 'test_origin_1'}) session.id = 1 endpoint = Mock(ip='127.0.0.1', name='test_endpoint', delete=Mock()) session.endpoint = endpoint self.app.database.get_session = Mock(return_value=session) vmpool = Mock(get_by_name=Mock(return_value=endpoint)) vmpool.app = self.app self.app.pool = vmpool art_collector = ArtifactCollector(vmpool) in_queue = art_collector.add_tasks( session.id, {'selenium_server': '/var/log/selenium_server.log'}) self.assertTrue(in_queue) self.assertTrue(wait_for(lambda: not session.selenium_log)) self.assertTrue(wait_for(lambda: len(art_collector.get_queue()) == 0)) self.assertTrue(wait_for(lambda: session.endpoint.delete.called)) art_collector.stop()
def test_run_recorder(self): """ - call session.run() - call session.delete() Expected: vnc_recorder was started and stopped """ endpoint = Mock(ip='127.0.0.1', name='test_endpoint') dc = {'takeScreencast': True, 'platform': 'test_origin_1'} with patch('core.db.models.Session', Mock()), patch("core.network.Network", Mock()), patch( "core.connection.Virsh", Mock()), patch('core.db.Database', DatabaseMock()): from core.sessions import Session self.session = Session(dc=dc) self.session.name = "session1" with patch('core.video.VNCVideoHelper._flvrec', Mock()), patch('core.video.VNCVideoHelper._flv2webm', Mock()): self.session.run(endpoint=endpoint) self.assertTrue( isinstance(self.session.vnc_helper.recorder, Process)) self.session.close() self.assertTrue( wait_for(lambda: not self.session.vnc_helper.recorder. is_alive()))
def test_vmmaster_label(self): from core.sessions import Session session = Session() with patch('core.sessions.Sessions.get_session', Mock(return_value=session)): response = vmmaster_label(self.address, session.id, "step-label") self.assertEqual(200, response.status) self.assertEqual(json.dumps({"value": "step-label"}), response.content) session.close()
class TestVNCVideoHelper(BaseTestCase): @classmethod def setUpClass(cls): from core.config import setup_config setup_config('data/config.py') cls.app = Flask(__name__) cls.app.database = DatabaseMock() cls.app.sessions = Mock() @classmethod def tearDownClass(cls): del cls.app def setUp(self): self.ctx = self.app.test_request_context() self.ctx.push() def tearDown(self): self.ctx.pop() @patch('flask.current_app', Mock()) @patch('flask.current_app.database', Mock()) def test_run_recorder(self): """ - call session.run() - call session.delete() Expected: vnc_recorder was started and stopped """ endpoint = Mock(ip='127.0.0.1', name='test_endpoint') dc = {'takeScreencast': True, 'platform': 'test_origin_1'} with patch('core.db.models.Session', Mock()), patch("core.network.Network", Mock()), patch( "core.connection.Virsh", Mock()), patch('core.db.Database', DatabaseMock()): from core.sessions import Session self.session = Session(dc=dc) self.session.name = "session1" with patch('core.video.VNCVideoHelper._flvrec', Mock()), patch('core.video.VNCVideoHelper._flv2webm', Mock()): self.session.run(endpoint=endpoint) self.assertTrue( isinstance(self.session.vnc_helper.recorder, Process)) self.session.close() self.assertTrue( wait_for(lambda: not self.session.vnc_helper.recorder. is_alive()))
def test_api_stop_session(self): from core.sessions import Session session = Session() session.failed = Mock() with patch('flask.current_app.sessions.get_session', Mock(return_value=session)): response = self.vmmaster_client.post("/api/session/%s/stop" % session.id) body = json.loads(response.data) self.assertEqual(200, body['metacode']) session.failed.assert_any_call( reason=constants.SESSION_CLOSE_REASON_API_CALL)
def get_session(): dc = commands.get_desired_capabilities(request) session = Session(dc=dc) request.session = session log.info("New session %s (%s) for %s" % (str(session.id), session.name, str(dc))) yield session for vm in endpoint.get_vm(dc): session.endpoint = vm yield session session.run(session.endpoint) yield session
def setUp(self): setup_config('data/config.py') self.host = "localhost" self.port = 9001 self.address = (self.host, self.port) self.vmmaster = vmmaster_server_mock(self.port) server_is_up(self.address) self.free_port = get_free_port() self.ctx = self.vmmaster.app.app_context() self.ctx.push() from core.sessions import Session self.session = Session() self.session.endpoint_ip = "localhost"
def get_session(): dc = commands.get_desired_capabilities(request) session = Session(dc=dc) request.session = session log.info("New session %s (%s) for %s" % (str(session.id), session.name, str(dc))) yield session for _endpoint in get_endpoint(session.id, dc): if _endpoint: session.endpoint = _endpoint yield session session.run(session.endpoint) yield session
def test_server_deleting_session_on_client_connection_drop(self): """ - create vmmaster session - close the connection - try to get vmmaster session Expected: vmmaster session deleted """ from core.sessions import Session session = Session() with patch('core.sessions.Sessions.get_session', Mock(return_value=session)), patch.object(Session, 'close') as mock: get_session_request(self.address, session.id) self.assertTrue(mock.called) session.close()
def test_session_is_not_deleted_after_server_shutdown(self): """ - delete server with active session Expected: session not deleted """ from core.sessions import Session session = Session() session.closed = False with patch('core.sessions.Sessions.get_session', Mock(return_value=session)): del self.vmmaster self.assertFalse(session.closed) session.failed() server_is_down(self.address)
def test_api_sessions(self): from core.sessions import Session session = Session("session1", self.desired_caps["desiredCapabilities"]) session.created = session.modified = datetime.now() with patch('flask.current_app.sessions.active', Mock(return_value=[session])): response = self.vmmaster_client.get('/api/sessions') body = json.loads(response.data) self.assertEqual(200, response.status_code) sessions = body['result']['sessions'] self.assertEqual(1, len(sessions)) self.assertEqual(self.platform, session.platform) self.assertEqual(200, body['metacode']) session.failed()
def test_failed_get_vnc_info_with_create_proxy(self): from core.sessions import Session endpoint = Mock(ip='127.0.0.1') session = Session() session.name = "session1" session.created = session.modified = datetime.now() expected = 5901 with patch('flask.current_app.sessions.active', Mock(return_value=[session])), patch( 'websockify.websocketproxy.websockify_init', Mock()): session.run(endpoint) response = self.vmmaster_client.get('/api/session/%s/vnc_info' % session.id) body = json.loads(response.data) self.assertEqual(200, response.status_code) vnc_proxy_port = body['result']['vnc_proxy_port'] self.assertEqual(type(expected), type(vnc_proxy_port)) self.assertEqual(200, body['metacode']) self.assertTrue(isinstance(session.vnc_helper.proxy, Process)) session.close() self.assertTrue( wait_for(lambda: not session.vnc_helper.proxy.is_alive()))
def test_add_tasks(self): """ - add tasks Expected: selenium log was saved and endpoint was deleted """ from vmpool.artifact_collector import ArtifactCollector with patch("core.network.Network", Mock()), patch("core.connection.Virsh", Mock()), patch('core.db.Database', DatabaseMock()): from core.sessions import Session session = Session(dc={'platform': 'test_origin_1'}) session.id = 1 log_path = os.sep.join([ config.SCREENSHOTS_DIR, str(session.id), 'selenium_server.log' ]) endpoint = Mock(ip='127.0.0.1', name='test_endpoint', delete=Mock(), selenium_port=4455, agent_port=9000, vnc_port=5900) session.endpoint = endpoint self.app.database.get_session = Mock(return_value=session) vmpool = Mock(get_by_name=Mock(return_value=endpoint)) vmpool.app = self.app self.app.pool = vmpool art_collector = ArtifactCollector(vmpool) in_queue = art_collector.add_tasks( session, {'selenium_server': '/var/log/selenium_server.log'}) self.assertTrue(in_queue) self.assertTrue(wait_for(lambda: session.selenium_log == log_path)) with open(session.selenium_log, 'r') as f: text = f.read() self.assertEqual(text, 'test text') self.assertTrue(wait_for(lambda: len(art_collector.get_queue()) == 0)) self.assertTrue(wait_for(lambda: session.endpoint.delete.called)) art_collector.stop()
def test_run_script(self): """ - create vmmaster session - send run_script request Expected: script executed, output contains echo message """ from core.sessions import Session session = Session() session.selenium_session = '1' output = json.dumps({"output": "hello world\n"}) with patch('core.sessions.Sessions.get_session', Mock(return_value=session)): response = run_script(self.address, session.id, "echo 'hello world'") self.assertEqual(200, response.status) self.assertEqual(output, response.content) session.close()
def setUp(self): self.ctx = self.app.test_request_context() self.ctx.push() with patch('flask.current_app.database', DatabaseMock()), patch( 'flask.current_app.sessions', Mock()), patch("core.network.Network", Mock()), patch("core.connection.Virsh", Mock()): from core.sessions import Session self.session = Session() self.session.name = "session1" vm = Mock() vm.name = 'vm1' vm.ip = self.host self.session.run(vm) from vmmaster.webdriver import commands self.commands = commands
def setUp(self): self.ctx = self.app.app_context() self.ctx.push() with patch( 'core.utils.init.home_dir', Mock(return_value=config.BASE_DIR) ), patch( 'core.logger.setup_logging', Mock(return_value=Mock()) ), patch( 'flask.current_app.sessions', Mock() ), patch( 'core.network.Network', Mock() ), patch( 'core.connection.Virsh', Mock() ): from vmmaster import cleanup self.cleanup = cleanup from core.sessions import Session self.session = Session() self.session.status = 'unknown'
def test_get_closed_session(self): """ - succeed existing session - try to get this session Expected: session exception without any reason """ from core.sessions import Session session = Session() session.selenium_session = '1' session.succeed() with patch('flask.current_app.database.get_session', Mock(return_value=session)): response = get_session_request(self.address, session.id) self.assertIn( "SessionException: There is no active session %s" % session.id, response.content) session.close()
def test_get_vnc_info_for_running_proxy(self): from core.sessions import Session endpoint = Mock(ip='127.0.0.1') session = Session() session.name = "session1" session.created = session.modified = datetime.now() session.run(endpoint) session.vnc_helper = Mock(proxy=Mock(), get_proxy_port=Mock(return_value=5900)) expected = {'vnc_proxy_port': 5900} response = self.vmmaster_client.get('/api/session/%s/vnc_info' % session.id) body = json.loads(response.data) self.assertEqual(200, response.status_code) vnc_proxy_port = body['result'] self.assertDictEqual(expected, vnc_proxy_port) self.assertEqual(200, body['metacode']) session.close()
def test_delete_session(self): """ - create new session - try to get id from response - delete session by id Expected: session deleted """ from core.sessions import Session session = Session() session.succeed = Mock() session.add_session_step = Mock() with patch('flask.current_app.sessions.get_session', Mock(return_value=session)): response = delete_session_request(self.address, session.id) session.succeed.assert_called_once_with() self.assertEqual(200, response.status) session.close()
def test_delete_session_if_got_session_but_session_not_exist(self): """ - create new session - try to get id from response - delete session by id - mocking get_session - repeat deleting session Expected: session deleted """ from core.sessions import Session session = Session() session.succeed = Mock() session.add_session_step = Mock() with patch('core.sessions.Sessions.get_session', Mock(return_value=session)): response = delete_session_request(self.address, session.id) self.assertEqual(200, response.status) response2 = delete_session_request(self.address, session.id) self.assertEqual(200, response2.status) session.close()
from app.menus import ActivityChoiceMenu from core.authenthication import User from core.menus import ChoiceMenu from core.sessions import Session if __name__ == '__main__': # ============================================================================================= # CREATE SESSION # ============================================================================================= while True: with Session(user=User('tom', 'tom')) as new_session: # ========================================================================================= # ACTIVITIES MENU # ========================================================================================= actual_menu = ActivityChoiceMenu() # ========================================================================================= # CATEGORIES PRODUCTS OR FAVORITES MENU # ========================================================================================= while isinstance(actual_menu, ChoiceMenu): actual_menu = actual_menu() # ========================================================================================= # PRODUCT AND SUBSTITUTE # ========================================================================================= product = actual_menu()
class TestCleanup(unittest.TestCase): @classmethod def setUpClass(cls): setup_config('data/config.py') from flask import Flask cls.app = Flask(__name__) cls.app.sessions = None from core import db cls.app.database = db.Database(config.DATABASE) def setUp(self): self.ctx = self.app.app_context() self.ctx.push() with patch( 'core.utils.init.home_dir', Mock(return_value=config.BASE_DIR) ), patch( 'core.logger.setup_logging', Mock(return_value=Mock()) ), patch( 'flask.current_app.sessions', Mock() ), patch( 'core.network.Network', Mock() ), patch( 'core.connection.Virsh', Mock() ): from vmmaster import cleanup self.cleanup = cleanup from core.sessions import Session self.session = Session() self.session.status = 'unknown' def tearDown(self): self.ctx.pop() def test_file_deletion(self): self.session.name = '__test_file_deletion' self.session.save() session_dir = os.path.join( config.SCREENSHOTS_DIR, str(self.session.id) ) system_utils.run_command( ["mkdir", config.SCREENSHOTS_DIR], silent=True) system_utils.run_command( ["mkdir", session_dir], silent=True) system_utils.run_command( ["touch", os.path.join(session_dir, "file_for_deletion")], silent=True) self.cleanup.delete_session_data([self.session]) self.assertEqual(os.path.isdir(session_dir), 0) system_utils.run_command( ["rm", "-rf", config.SCREENSHOTS_DIR], silent=True) def test_sessions_overflow(self): user = Mock(id=1, max_stored_sessions=0) self.session.closed = True self.session.name = '__test_outdated_sessions' self.session.save() sessions_to_delete = self.cleanup.sessions_overflow(user) session_ids = [s.id for s in sessions_to_delete] self.assertIn(self.session.id, session_ids) self.cleanup.delete_session_data([self.session])
class CommonCommandsTestCase(BaseTestCase): webdriver_server = None vmmaster_agent = None host = 'localhost' @classmethod def setUpClass(cls): setup_config("data/config.py") body = { "sessionId": None, "desiredCapabilities": { "platform": "some_platform", "browserName": "firefox", "version": "", "javascriptEnabled": True } } session_request_body = json.dumps(body) session_request_headers = { 'content-length': '%s' % len(session_request_body), 'accept-encoding': 'identity', 'Connection': 'close', 'accept': 'application/json', 'user-agent': 'Python-urllib/2.7', 'host': '127.0.0.1:9000', 'content-type': 'application/json;charset=UTF-8', } cls.request = Mock() cls.request.method = "POST" cls.request.path = "/wd/hub/session" cls.request.headers = dict() cls.request.headers.update(session_request_headers) cls.request.data = session_request_body cls.webdriver_server = ServerMock(cls.host, get_free_port()) cls.webdriver_server.start() cls.vmmaster_agent = ServerMock(cls.host, get_free_port()) cls.vmmaster_agent.start() cls.app = Flask(__name__) cls.app.database = None cls.app.sessions = None def setUp(self): self.ctx = self.app.test_request_context() self.ctx.push() with patch('flask.current_app.database', DatabaseMock()), patch( 'flask.current_app.sessions', Mock()), patch("core.network.Network", Mock()), patch("core.connection.Virsh", Mock()): from core.sessions import Session self.session = Session() self.session.name = "session1" vm = Mock() vm.name = 'vm1' vm.ip = self.host self.session.run(vm) from vmmaster.webdriver import commands self.commands = commands def tearDown(self): with patch('flask.current_app.sessions', Mock()), patch('flask.current_app.database', Mock()): self.session.close() self.ctx.pop() @classmethod def tearDownClass(cls): cls.webdriver_server.stop() cls.vmmaster_agent.stop() del cls.app
class TestHttpProxy(BaseTestCase): def setUp(self): setup_config('data/config.py') self.host = "localhost" self.port = 9001 self.address = (self.host, self.port) self.vmmaster = vmmaster_server_mock(self.port) server_is_up(self.address) self.free_port = get_free_port() self.ctx = self.vmmaster.app.app_context() self.ctx.push() from core.sessions import Session self.session = Session() self.session.endpoint_ip = "localhost" def tearDown(self): self.session.close() self.ctx.pop() self.vmmaster.app.sessions.kill_all() self.vmmaster.app.cleanup() del self.vmmaster server_is_down(self.address) def test_proxy_successful(self): server = ServerMock(self.host, self.free_port) server.start() with patch('core.sessions.Sessions.get_session', Mock(return_value=self.session)): response = requests.get( "http://%s:%s/proxy/session/%s/port/%s/" % (self.host, self.port, self.session.id, self.free_port)) server.stop() self.assertEqual("ok", response.content) def test_proxy_responses_when_trying_to_connect_failed(self): with patch('core.sessions.Sessions.get_session', Mock(return_value=self.session)): response = requests.get( "http://%s:%s/proxy/session/%s/port/%s/" % (self.host, self.port, self.session.id, self.free_port)) self.assertEqual( "Request forwarding failed:\n" "Connection was refused by other side: 111: Connection refused.", response.content) def test_proxy_to_session_that_doesnt_exist(self): self.session.succeed() with patch('flask.current_app.database.get_session', Mock(return_value=self.session)): response = requests.get( "http://%s:%s/proxy/session/%s/port/%s/" % (self.host, self.port, self.session.id, self.free_port)) self.assertIn("There is no active session %s" % self.session.id, response.content) def test_proxy_with_wrong_path(self): response = requests.get("http://%s:%s/proxy/asdf/%s/" % (self.host, self.port, self.free_port)) self.assertEqual( "Couldn't parse request uri, " "make sure you request uri has " "/proxy/session/<session_id>/port/<port_number>/<destination>", response.content)