class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
    @property
    def body(self):
        """get request body."""
        data = copy.copy(self.rfile)

        if self.headers.getheader('Content-Length') is None:
            body = None
        else:
            content_length = int(self.headers.getheader('Content-Length'))
            body = data.read(content_length)

        return body

    def send_reply(self, code, headers, body):
        """ Send reply to client. """
        # reply code
        self.send_response(code)

        # reply headers
        for keyword, value in headers.iteritems():
            self.send_header(keyword, value)
        self.end_headers()

        # reply body
        self.wfile.write(body)

    def do_POST(self):
        reply = self.headers.getheader("reply")
        code = int(reply)
        self.send_reply(code, self.headers.dict, body=self.body)

    def do_GET(self):
        body = "ok"
        self.send_reply(200, {"Content-Length": len(body)}, body)

    def log_error(self, format, *args):
        pass

    def log_message(self, format, *args):
        pass

    def log_request(self, code='-', size='-'):
        pass class BaseTestCase(unittest.TestCase):
    def shortDescription(self):
        return None class ServerMock(object):
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self._server = BaseHTTPServer.HTTPServer((host, port), Handler)
        self._server.timeout = 1
        self._server.allow_reuse_address = True
        self._thread = threading.Thread(target=self._server.serve_forever)

    def start(self):
        self._thread.start()

    def stop(self):
        self._server.shutdown()
        self._server.server_close()
        self._thread.join() def get_free_port():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(('', 0))
    port = s.getsockname()[1]
    s.close()
    return port class DatabaseMock(Mock):
    active_sessions = {}
    endpoints = {}

    def __init__(self, *args, **kwargs):
        super(DatabaseMock, self).__init__(*args, **kwargs)
        self.add = Mock(side_effect=set_primary_key)

    def get_active_sessions(self, provider_id=None):
        return self.active_sessions.values()

    def get_session(self, session_id):
        return self.active_sessions.get(str(session_id))

    def get_endpoint(self, endpoint):
        pass

    def get_endpoints(self, *args, **kwargs):
        return self.endpoints.values()

    @staticmethod
    def get_last_session_step(session_id):
        return Mock()

    def register_provider(self, name, url, platforms):
        from core.db.models import Provider
        return Provider(name, url, platforms) class CreationException(Exception):
    pass class ConnectionError(Exception):
    pass class SessionException(Exception):
    pass class TimeoutException(Exception):
    pass def full_path(path_to_config):
def _import(filename):
def create_if_not_exist(directory):
    def update(self, new_values):
def setup_config(path_to_config):
class Config(object):
import copy
import json
from mock import Mock, PropertyMock, patch
from tests.helpers import Handler, BaseTestCase, ServerMock, get_free_port, DatabaseMock
from core.exceptions import CreationException, ConnectionError, \
    SessionException, TimeoutException
from core.config import setup_config, config
from flask import Flask
            from core.db.models import Session, Provider, Endpoint
            from vmmaster.webdriver import commands
        from vmmaster.webdriver import commands

@patch(
    'vmmaster.webdriver.commands.start_selenium_session', new=Mock(
        __name__="start_selenium_session",
        side_effect=selenium_status_mock
    )
)
@patch(
    'vmmaster.webdriver.commands.ping_endpoint_before_start_session',
    new=Mock(__name__="ping_endpoint_before_start_session", side_effect=ping_vm_mock)
)
@patch(
    'vmmaster.webdriver.helpers.is_request_closed',
    Mock(return_value=False)
)
@patch('flask.current_app.database', Mock())
class TestStartSessionCommands(CommonCommandsTestCase):
    def setUp(self):
        super(TestStartSessionCommands, self).setUp()
        self.session.dc = Mock(__name__="dc")

    def test_start_session_when_selenium_status_failed(self):
        request = copy.copy(self.request)

        def make_request_mock(arg1, arg2):
            yield 200, {}, json.dumps({'status': 1})

        with patch(
            'core.db.models.Session.make_request', Mock(
                __name__="make_request",
                side_effect=make_request_mock
            )
        ):
            self.assertRaises(
                CreationException, self.commands.start_session,
                request, self.session
            )

    @patch(
        'vmmaster.webdriver.helpers.is_session_timeouted',
        Mock(return_value=True)
    )
    @patch(
        'requests.request', Mock(side_effect=Mock(
            __name__="request",
            return_value=(200, {}, json.dumps({'status': 0}))))
    )
    def test_start_session_when_session_was_timeouted(self):
        request = copy.copy(self.request)
        self.assertRaises(TimeoutException, self.commands.start_session,
                          request, self.session)

    @patch(
        'vmmaster.webdriver.helpers.is_session_closed',
        Mock(return_value=True)
    )
    @patch(
        'requests.request', Mock(side_effect=Mock(
            __name__="request",
            return_value=(200, {}, json.dumps({'status': 0}))))
    )
    def test_start_session_when_session_was_closed(self):
        request = copy.copy(self.request)
        self.assertRaises(SessionException, self.commands.start_session,
                          request, self.session)


@patch('flask.current_app.database', Mock())
class TestStartSeleniumSessionCommands(CommonCommandsTestCase):
    @patch(
        'vmmaster.webdriver.helpers.is_request_closed',
        Mock(return_value=False)
    )
    @patch("vmmaster.webdriver.commands.ping_endpoint_before_start_session", Mock())
    def test_session_response_success(self):
        request = copy.deepcopy(self.request)
        request.headers.update({"reply": "200"})

        status, headers, body = self.commands.start_selenium_session(
            request, self.session
        )

        self.assertEqual(status, 200)

        request_headers = dict((key.lower(), value) for key, value in
                               request.headers.iteritems())
        for key, value in headers.iteritems():
            if key == 'server' or key == 'date':
                continue
            self.assertDictContainsSubset({key: value}, request_headers)
        self.assertEqual(body, request.data)

    @patch(
        'vmmaster.webdriver.helpers.is_request_closed',
        Mock(return_value=False)
    )
    @patch("vmmaster.webdriver.commands.ping_endpoint_before_start_session", Mock())
    def test_session_response_fail(self):
        request = copy.deepcopy(self.request)
        request.headers.update({"reply": "500"})

        def start_selenium_session(req):
            for result in self.commands.start_selenium_session(
                req, self.session
            ):
                pass

        self.assertRaises(CreationException, start_selenium_session, request)

    @patch(
        'vmmaster.webdriver.helpers.is_request_closed',
        Mock(return_value=True)
    )
    def test_start_selenium_session_when_connection_closed(self):
        self.session.closed = True

        request = copy.deepcopy(self.request)
        request.headers.update({"reply": "200"})

        self.assertRaises(

            ConnectionError, self.commands.start_selenium_session,