Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Continue the code snippet: <|code_start|>
class SftpRecurseTest(TestCase):
def __sftp_cb(self, ssh, sftp):
def dir_cb(path, full_path, entry):
# print("DIR: %s" % (full_path))
<|code_end|>
. Use current file imports:
from unittest import TestCase
from pysecure.test.test_base import connect_sftp_test
and context (classes, functions, or code) from other files:
# Path: pysecure/test/test_base.py
# def connect_sftp_test(sftp_cb):
# print("Connecting SFTP with key: %s" % (key_filepath))
# auth_cb = get_key_auth_cb(key_filepath)
# connect_sftp_with_cb(sftp_cb, user, host, auth_cb, verbosity=verbosity)
. Output only the next line. | pass |
Next line prediction: <|code_start|> )
@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,
request, self.session
)
@patch(
<|code_end|>
. Use current file imports:
(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)
and context including class names, function names, or small code snippets from other files:
# Path: tests/helpers.py
# 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)
#
# Path: core/exceptions.py
# class CreationException(Exception):
# pass
#
# class ConnectionError(Exception):
# pass
#
# class SessionException(Exception):
# pass
#
# class TimeoutException(Exception):
# pass
#
# Path: core/config.py
# 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):
. Output only the next line. | 'vmmaster.webdriver.helpers.is_request_closed', |
Next line prediction: <|code_start|>
def test_take_screenshot_some_string(self):
self.body['desiredCapabilities'].update({
"takeScreenshot": "asdf"
})
self.session_request_headers = {
'content-length': '%s' % len(self.body),
}
self.request.headers.update(self.session_request_headers)
self.request.data = json.dumps(self.body)
dc = self.commands.get_desired_capabilities(self.request)
self.assertTrue(dc["takeScreenshot"])
def test_take_screenshot_empty_string(self):
self.body['desiredCapabilities'].update({
"takeScreenshot": ""
})
self.session_request_headers = {
'content-length': '%s' % len(self.body),
}
self.request.headers.update(self.session_request_headers)
self.request.data = json.dumps(self.body)
dc = self.commands.get_desired_capabilities(self.request)
self.assertFalse(dc["takeScreenshot"])
class TestRunScript(CommonCommandsTestCase):
def setUp(self):
super(TestRunScript, self).setUp()
config.DEFAULT_AGENT_PORT = self.vmmaster_agent.port
<|code_end|>
. Use current file imports:
(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)
and context including class names, function names, or small code snippets from other files:
# Path: tests/helpers.py
# 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)
#
# Path: core/exceptions.py
# class CreationException(Exception):
# pass
#
# class ConnectionError(Exception):
# pass
#
# class SessionException(Exception):
# pass
#
# class TimeoutException(Exception):
# pass
#
# Path: core/config.py
# 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):
. Output only the next line. | self.response_body = "some_body" |
Continue the code snippet: <|code_start|> 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}))))
<|code_end|>
. Use current file imports:
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
and context (classes, functions, or code) from other files:
# Path: tests/helpers.py
# 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)
#
# Path: core/exceptions.py
# class CreationException(Exception):
# pass
#
# class ConnectionError(Exception):
# pass
#
# class SessionException(Exception):
# pass
#
# class TimeoutException(Exception):
# pass
#
# Path: core/config.py
# 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):
. Output only the next line. | ) |
Given the code snippet: <|code_start|># coding: utf-8
class CommonCommandsTestCase(BaseTestCase):
webdriver_server = None
vmmaster_agent = None
vnc_server = None
host = 'localhost'
@classmethod
def setUpClass(cls):
setup_config("data/config_openstack.py")
body = {
"sessionId": None,
"desiredCapabilities": {
"platform": "some_platform",
"browserName": "firefox",
<|code_end|>
, generate the next line using the imports in this file:
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
and context (functions, classes, or occasionally code) from other files:
# Path: tests/helpers.py
# 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)
#
# Path: core/exceptions.py
# class CreationException(Exception):
# pass
#
# class ConnectionError(Exception):
# pass
#
# class SessionException(Exception):
# pass
#
# class TimeoutException(Exception):
# pass
#
# Path: core/config.py
# 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):
. Output only the next line. | "version": "", |
Based on the snippet: <|code_start|> @classmethod
def tearDownClass(cls):
cls.webdriver_server.stop()
cls.vmmaster_agent.stop()
cls.vnc_server.stop()
del cls.app
def ping_vm_mock(arg, ports=None):
yield None
def selenium_status_mock(arg1, arg2, arg3):
yield None
@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)
)
<|code_end|>
, predict the immediate next line with the help of imports:
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
and context (classes, functions, sometimes code) from other files:
# Path: tests/helpers.py
# 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)
#
# Path: core/exceptions.py
# class CreationException(Exception):
# pass
#
# class ConnectionError(Exception):
# pass
#
# class SessionException(Exception):
# pass
#
# class TimeoutException(Exception):
# pass
#
# Path: core/config.py
# 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):
. Output only the next line. | @patch('flask.current_app.database', Mock()) |
Using the snippet: <|code_start|> def test_name(self):
self.body['desiredCapabilities'].update({
"name": "some_name"
})
self.session_request_headers = {
'content-length': '%s' % len(self.body),
}
self.request.headers.update(self.session_request_headers)
self.request.data = json.dumps(self.body)
dc = self.commands.get_desired_capabilities(self.request)
self.assertIsInstance(dc["name"], unicode)
self.assertEqual(self.body["desiredCapabilities"]["name"], dc["name"])
def test_no_name(self):
self.session_request_headers = {
'content-length': '%s' % len(self.body),
}
self.request.headers.update(self.session_request_headers)
self.request.data = json.dumps(self.body)
dc = self.commands.get_desired_capabilities(self.request)
self.assertEqual(dc.get("name", None), None)
def test_take_screenshot_bool(self):
self.body['desiredCapabilities'].update({
"takeScreenshot": True
})
self.session_request_headers = {
'content-length': '%s' % len(self.body),
}
<|code_end|>
, determine the next line of code. You have imports:
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
and context (class names, function names, or code) available:
# Path: tests/helpers.py
# 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)
#
# Path: core/exceptions.py
# class CreationException(Exception):
# pass
#
# class ConnectionError(Exception):
# pass
#
# class SessionException(Exception):
# pass
#
# class TimeoutException(Exception):
# pass
#
# Path: core/config.py
# 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):
. Output only the next line. | self.request.headers.update(self.session_request_headers) |
Predict the next line for this snippet: <|code_start|>
class TestRunScript(CommonCommandsTestCase):
def setUp(self):
super(TestRunScript, self).setUp()
config.DEFAULT_AGENT_PORT = self.vmmaster_agent.port
self.response_body = "some_body"
def tearDown(self):
super(TestRunScript, self).tearDown()
@patch('flask.current_app.database', Mock())
def test_run_script(self):
def run_script_through_websocket_mock(*args, **kwargs):
return 200, {}, 'some_body'
with patch('vmmaster.webdriver.commands.run_script_through_websocket',
run_script_through_websocket_mock):
response = self.commands.run_script(self.request, self.session)
self.assertEqual(200, response[0])
self.assertEqual(self.response_body, response[2])
class TestLabelCommands(CommonCommandsTestCase):
def test_label(self):
request = copy.deepcopy(self.request)
label = "step-label"
label_id = 1
request.data = json.dumps({"label": label})
<|code_end|>
with the help of current file imports:
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
and context from other files:
# Path: tests/helpers.py
# 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)
#
# Path: core/exceptions.py
# class CreationException(Exception):
# pass
#
# class ConnectionError(Exception):
# pass
#
# class SessionException(Exception):
# pass
#
# class TimeoutException(Exception):
# pass
#
# Path: core/config.py
# 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):
, which may contain function names, class names, or code. Output only the next line. | with patch('core.db.models.Session.current_log_step', |
Using the snippet: <|code_start|>
@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(
<|code_end|>
, determine the next line of code. You have imports:
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
and context (class names, function names, or code) available:
# Path: tests/helpers.py
# 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)
#
# Path: core/exceptions.py
# class CreationException(Exception):
# pass
#
# class ConnectionError(Exception):
# pass
#
# class SessionException(Exception):
# pass
#
# class TimeoutException(Exception):
# pass
#
# Path: core/config.py
# 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):
. Output only the next line. | __name__="make_request", |
Using the snippet: <|code_start|> 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)
<|code_end|>
, determine the next line of code. You have imports:
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
and context (class names, function names, or code) available:
# Path: tests/helpers.py
# 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)
#
# Path: core/exceptions.py
# class CreationException(Exception):
# pass
#
# class ConnectionError(Exception):
# pass
#
# class SessionException(Exception):
# pass
#
# class TimeoutException(Exception):
# pass
#
# Path: core/config.py
# 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):
. Output only the next line. | request.headers.update({"reply": "200"}) |
Given the code snippet: <|code_start|> 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',
<|code_end|>
, generate the next line using the imports in this file:
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
and context (functions, classes, or occasionally code) from other files:
# Path: tests/helpers.py
# 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)
#
# Path: core/exceptions.py
# class CreationException(Exception):
# pass
#
# class ConnectionError(Exception):
# pass
#
# class SessionException(Exception):
# pass
#
# class TimeoutException(Exception):
# pass
#
# Path: core/config.py
# 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):
. Output only the next line. | Mock(return_value=False) |
Next line prediction: <|code_start|> self.session_request_headers = {
'content-length': '%s' % len(self.body),
}
self.request.headers.update(self.session_request_headers)
self.request.data = json.dumps(self.body)
dc = self.commands.get_desired_capabilities(self.request)
self.assertTrue(dc["takeScreenshot"])
def test_take_screenshot_empty_string(self):
self.body['desiredCapabilities'].update({
"takeScreenshot": ""
})
self.session_request_headers = {
'content-length': '%s' % len(self.body),
}
self.request.headers.update(self.session_request_headers)
self.request.data = json.dumps(self.body)
dc = self.commands.get_desired_capabilities(self.request)
self.assertFalse(dc["takeScreenshot"])
class TestRunScript(CommonCommandsTestCase):
def setUp(self):
super(TestRunScript, self).setUp()
config.DEFAULT_AGENT_PORT = self.vmmaster_agent.port
self.response_body = "some_body"
def tearDown(self):
super(TestRunScript, self).tearDown()
<|code_end|>
. Use current file imports:
(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)
and context including class names, function names, or small code snippets from other files:
# Path: tests/helpers.py
# 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)
#
# Path: core/exceptions.py
# class CreationException(Exception):
# pass
#
# class ConnectionError(Exception):
# pass
#
# class SessionException(Exception):
# pass
#
# class TimeoutException(Exception):
# pass
#
# Path: core/config.py
# 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):
. Output only the next line. | @patch('flask.current_app.database', Mock()) |
Here is a snippet: <|code_start|> self.assertTrue(self.pool.endpoint_preparer.stop.called)
self.assertTrue(self.pool.endpoint_remover.stop.called)
self.assertTrue(self.pool.artifact_collector.stop.called)
self.assertTrue(self.pool.preloader.stop.called)
def test_pool_count(self):
self.assertEqual(0, len(self.pool.active_endpoints))
self.pool.add(self.platform_name)
self.assertEqual(1, len(self.pool.active_endpoints))
def test_get_parallel_two_vm(self):
threads = ThreadPool(processes=1)
self.pool.preload(self.platform_name)
self.pool.preload(self.platform_name)
self.assertEqual(2, len(self.pool.active_endpoints))
deffered1 = threads.apply_async(
self.pool.get_by_platform, args=(self.platform_name,))
deffered2 = threads.apply_async(
self.pool.get_by_platform, args=(self.platform_name,))
deffered1.wait()
deffered2.wait()
self.assertEqual(2, len(self.pool.active_endpoints))
def test_vm_preloading(self):
self.assertEqual(0, len(self.pool.active_endpoints))
self.pool.preload(self.platform_name)
<|code_end|>
. Write the next line using the current file imports:
import json
from mock import Mock, patch, PropertyMock
from core.config import setup_config, config
from tests.helpers import BaseTestCase, custom_wait
from flask import Flask
from core.db import Database
from vmpool.virtual_machines_pool import VirtualMachinesPool
from multiprocessing.pool import ThreadPool
from core.db.models import OpenstackClone
from core.db.models import OpenstackClone
and context from other files:
# Path: core/config.py
# 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):
#
# Path: tests/helpers.py
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# def custom_wait(self):
# self.ready = True
# self.checking = False
# yield self.ready
, which may include functions, classes, or code. Output only the next line. | self.assertIsInstance(self.pool.active_endpoints[0], OpenstackClone) |
Predict the next line for this snippet: <|code_start|> self.assertTrue(self.pool.endpoint_preparer.stop.called)
self.assertTrue(self.pool.endpoint_remover.stop.called)
self.assertTrue(self.pool.artifact_collector.stop.called)
self.assertTrue(self.pool.preloader.stop.called)
def test_pool_count(self):
self.assertEqual(0, len(self.pool.active_endpoints))
self.pool.add(self.platform_name)
self.assertEqual(1, len(self.pool.active_endpoints))
def test_get_parallel_two_vm(self):
threads = ThreadPool(processes=1)
self.pool.preload(self.platform_name)
self.pool.preload(self.platform_name)
self.assertEqual(2, len(self.pool.active_endpoints))
deffered1 = threads.apply_async(
self.pool.get_by_platform, args=(self.platform_name,))
deffered2 = threads.apply_async(
self.pool.get_by_platform, args=(self.platform_name,))
deffered1.wait()
deffered2.wait()
self.assertEqual(2, len(self.pool.active_endpoints))
def test_vm_preloading(self):
self.assertEqual(0, len(self.pool.active_endpoints))
self.pool.preload(self.platform_name)
<|code_end|>
with the help of current file imports:
import json
from mock import Mock, patch, PropertyMock
from core.config import setup_config, config
from tests.helpers import BaseTestCase, custom_wait
from flask import Flask
from core.db import Database
from vmpool.virtual_machines_pool import VirtualMachinesPool
from multiprocessing.pool import ThreadPool
from core.db.models import OpenstackClone
from core.db.models import OpenstackClone
and context from other files:
# Path: core/config.py
# 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):
#
# Path: tests/helpers.py
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# def custom_wait(self):
# self.ready = True
# self.checking = False
# yield self.ready
, which may contain function names, class names, or code. Output only the next line. | self.assertIsInstance(self.pool.active_endpoints[0], OpenstackClone) |
Here is a snippet: <|code_start|> def test_stop_workers(self):
self.pool.endpoint_remover.stop = Mock()
self.pool.stop_workers()
self.assertTrue(self.pool.endpoint_preparer.stop.called)
self.assertTrue(self.pool.endpoint_remover.stop.called)
self.assertTrue(self.pool.artifact_collector.stop.called)
self.assertTrue(self.pool.preloader.stop.called)
def test_pool_count(self):
self.assertEqual(0, len(self.pool.active_endpoints))
self.pool.add(self.platform_name)
self.assertEqual(1, len(self.pool.active_endpoints))
def test_get_parallel_two_vm(self):
threads = ThreadPool(processes=1)
self.pool.preload(self.platform_name)
self.pool.preload(self.platform_name)
self.assertEqual(2, len(self.pool.active_endpoints))
deffered1 = threads.apply_async(
self.pool.get_by_platform, args=(self.platform_name,))
deffered2 = threads.apply_async(
self.pool.get_by_platform, args=(self.platform_name,))
deffered1.wait()
deffered2.wait()
self.assertEqual(2, len(self.pool.active_endpoints))
<|code_end|>
. Write the next line using the current file imports:
import json
from mock import Mock, patch, PropertyMock
from core.config import setup_config, config
from tests.helpers import BaseTestCase, custom_wait
from flask import Flask
from core.db import Database
from vmpool.virtual_machines_pool import VirtualMachinesPool
from multiprocessing.pool import ThreadPool
from core.db.models import OpenstackClone
from core.db.models import OpenstackClone
and context from other files:
# Path: core/config.py
# 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):
#
# Path: tests/helpers.py
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# def custom_wait(self):
# self.ready = True
# self.checking = False
# yield self.ready
, which may include functions, classes, or code. Output only the next line. | def test_vm_preloading(self): |
Given the following code snippet before the placeholder: <|code_start|> self.mocked_image = Mock(
id=1, status='active',
get=Mock(return_value='snapshot'),
min_disk=20,
min_ram=2,
instance_type_flavorid=1,
)
type(self.mocked_image).name = PropertyMock(
return_value='test_origin_1')
with patch.multiple(
'vmpool.platforms.OpenstackPlatforms',
images=Mock(return_value=[self.mocked_image]),
flavor_params=Mock(return_value={'vcpus': 1, 'ram': 2}),
limits=Mock(return_value={
'maxTotalCores': 10, 'maxTotalInstances': 10,
'maxTotalRAMSize': 100, 'totalCoresUsed': 0,
'totalInstancesUsed': 0, 'totalRAMUsed': 0}),
):
self.pool = VirtualMachinesPool(
self.app, preloader_class=Mock(), artifact_collector_class=Mock(), endpoint_preparer_class=Mock()
)
self.ctx = self.app.app_context()
self.ctx.push()
self.pool.register()
def tearDown(self):
self.pool.endpoint_remover.remove_all()
self.pool.unregister()
self.pool.platforms.cleanup()
<|code_end|>
, predict the next line using imports from the current file:
import json
from mock import Mock, patch, PropertyMock
from core.config import setup_config, config
from tests.helpers import BaseTestCase, custom_wait
from flask import Flask
from core.db import Database
from vmpool.virtual_machines_pool import VirtualMachinesPool
from multiprocessing.pool import ThreadPool
from core.db.models import OpenstackClone
from core.db.models import OpenstackClone
and context including class names, function names, and sometimes code from other files:
# Path: core/config.py
# 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):
#
# Path: tests/helpers.py
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# def custom_wait(self):
# self.ready = True
# self.checking = False
# yield self.ready
. Output only the next line. | self.ctx.pop() |
Using the snippet: <|code_start|>
class Config(object):
BASEDIR = os.path.dirname(os.path.realpath(__file__))
PORT = get_free_port()
# PostgreSQL dbname
DATABASE = "postgresql://vmmaster:vmmaster@localhost/vmmaster_db"
ENDPOINT_THREADPOOL_PROCESSES = 1
# screenshots
SCREENSHOTS_DIR = os.sep.join([BASEDIR, "screenshots"])
SCREENSHOTS_DAYS = 7
# logging
LOG_TYPE = "plain"
LOG_LEVEL = "DEBUG"
PROVIDER_NAME = "noname"
# openstack
USE_OPENSTACK = True
OPENSTACK_MAX_VM_COUNT = 2
OPENSTACK_PRELOADED = {
'origin_1': 1
}
# selenium
DEFAULT_PORTS = {
<|code_end|>
, determine the next line of code. You have imports:
import os
from tests.helpers import get_free_port
and context (class names, function names, or code) available:
# Path: tests/helpers.py
# 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
. Output only the next line. | "selenium": "4455", |
Given the following code snippet before the placeholder: <|code_start|># coding: utf-8
class TestDockerClient(BaseTestCase):
def setUp(self):
with patch("docker.DockerClient", Mock(
containers=Mock(
create=Mock(),
get=Mock()
)
)):
setup_config('data/config_openstack.py')
self._docker_client = DockerManageClient()
def test_create_container(self):
container = self._docker_client.create_container("image")
self.assertTrue(self._docker_client.client.containers.create.called)
self.assertTrue(self._docker_client.client.containers.get.called)
self.assertTrue(isinstance(container, DockerContainer))
def test_get_containers_list(self):
self._docker_client.client.containers.list = Mock(return_value=[Mock()])
containers_list = self._docker_client.containers()
<|code_end|>
, predict the next line using imports from the current file:
from mock import patch, Mock
from tests.helpers import BaseTestCase
from core.config import setup_config
from core.clients.docker_client import DockerManageClient
from core.clients.docker_client import DockerContainer
from core.clients.docker_client import DockerContainer
from vmpool.platforms import DockerImage
and context including class names, function names, and sometimes code from other files:
# Path: tests/helpers.py
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
. Output only the next line. | self.assertTrue(len(containers_list), 1) |
Here is a snippet: <|code_start|>
class TestOpenstackCloneUnit(BaseTestCase):
def setUp(self):
setup_config('data/config_openstack.py')
self.app = Flask(__name__)
self.app.database = DatabaseMock()
self.pool = Mock(id=1, provider=Provider(name='fake', url='no//url'))
self.mocked_origin = Mock(
short_name="platform_1",
id=1, status="active",
get=Mock(return_value="snapshot"),
min_disk=20,
min_ram=2,
instance_type_flavorid=1
)
self.ctx = self.app.app_context()
self.ctx.push()
with patch(
"core.utils.openstack_utils.nova_client", Mock(return_value=Mock())
), patch(
"flask.current_app", self.app
):
self.clone = OpenstackClone(self.mocked_origin, "preloaded", self.pool)
<|code_end|>
. Write the next line using the current file imports:
import os
from core.exceptions import CreationException
from mock import Mock, patch, PropertyMock
from tests.helpers import BaseTestCase, custom_wait, wait_for, DatabaseMock
from core.db.models import Provider
from flask import Flask
from core.config import setup_config
from core.db.models import OpenstackClone
and context from other files:
# Path: core/exceptions.py
# class CreationException(Exception):
# pass
#
# Path: tests/helpers.py
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# def custom_wait(self):
# self.ready = True
# self.checking = False
# yield self.ready
#
# def wait_for(condition, timeout=10):
# start = time.time()
# while not condition() and time.time() - start < timeout:
# time.sleep(0.1)
#
# return condition()
#
# 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)
#
# Path: core/db/models.py
# class Provider(Base, FeaturesMixin):
# __tablename__ = 'providers'
#
# id = Column(Integer, primary_key=True)
# name = Column(String(length=200), nullable=True)
# url = Column(String, nullable=True)
# active = Column(Boolean, default=False)
# config = Column(JSON, default={})
# max_limit = Column(Integer, default=0)
#
# def __init__(self, name, url, config=None, active=True, max_limit=0):
# self.name = name
# self.url = url
# self.active = active
# self.max_limit = max_limit
#
# if config:
# self.config = config
#
# @property
# def info(self):
# return {
# "id": self.id,
# "name": self.name,
# "url": self.url
# }
, which may include functions, classes, or code. Output only the next line. | def tearDown(self): |
Here is a snippet: <|code_start|># coding: utf-8
class TestOpenstackCloneUnit(BaseTestCase):
def setUp(self):
setup_config('data/config_openstack.py')
self.app = Flask(__name__)
self.app.database = DatabaseMock()
self.pool = Mock(id=1, provider=Provider(name='fake', url='no//url'))
self.mocked_origin = Mock(
<|code_end|>
. Write the next line using the current file imports:
import os
from core.exceptions import CreationException
from mock import Mock, patch, PropertyMock
from tests.helpers import BaseTestCase, custom_wait, wait_for, DatabaseMock
from core.db.models import Provider
from flask import Flask
from core.config import setup_config
from core.db.models import OpenstackClone
and context from other files:
# Path: core/exceptions.py
# class CreationException(Exception):
# pass
#
# Path: tests/helpers.py
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# def custom_wait(self):
# self.ready = True
# self.checking = False
# yield self.ready
#
# def wait_for(condition, timeout=10):
# start = time.time()
# while not condition() and time.time() - start < timeout:
# time.sleep(0.1)
#
# return condition()
#
# 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)
#
# Path: core/db/models.py
# class Provider(Base, FeaturesMixin):
# __tablename__ = 'providers'
#
# id = Column(Integer, primary_key=True)
# name = Column(String(length=200), nullable=True)
# url = Column(String, nullable=True)
# active = Column(Boolean, default=False)
# config = Column(JSON, default={})
# max_limit = Column(Integer, default=0)
#
# def __init__(self, name, url, config=None, active=True, max_limit=0):
# self.name = name
# self.url = url
# self.active = active
# self.max_limit = max_limit
#
# if config:
# self.config = config
#
# @property
# def info(self):
# return {
# "id": self.id,
# "name": self.name,
# "url": self.url
# }
, which may include functions, classes, or code. Output only the next line. | short_name="platform_1", |
Based on the snippet: <|code_start|># coding: utf-8
class TestOpenstackCloneUnit(BaseTestCase):
def setUp(self):
setup_config('data/config_openstack.py')
self.app = Flask(__name__)
self.app.database = DatabaseMock()
self.pool = Mock(id=1, provider=Provider(name='fake', url='no//url'))
self.mocked_origin = Mock(
short_name="platform_1",
id=1, status="active",
get=Mock(return_value="snapshot"),
min_disk=20,
min_ram=2,
<|code_end|>
, predict the immediate next line with the help of imports:
import os
from core.exceptions import CreationException
from mock import Mock, patch, PropertyMock
from tests.helpers import BaseTestCase, custom_wait, wait_for, DatabaseMock
from core.db.models import Provider
from flask import Flask
from core.config import setup_config
from core.db.models import OpenstackClone
and context (classes, functions, sometimes code) from other files:
# Path: core/exceptions.py
# class CreationException(Exception):
# pass
#
# Path: tests/helpers.py
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# def custom_wait(self):
# self.ready = True
# self.checking = False
# yield self.ready
#
# def wait_for(condition, timeout=10):
# start = time.time()
# while not condition() and time.time() - start < timeout:
# time.sleep(0.1)
#
# return condition()
#
# 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)
#
# Path: core/db/models.py
# class Provider(Base, FeaturesMixin):
# __tablename__ = 'providers'
#
# id = Column(Integer, primary_key=True)
# name = Column(String(length=200), nullable=True)
# url = Column(String, nullable=True)
# active = Column(Boolean, default=False)
# config = Column(JSON, default={})
# max_limit = Column(Integer, default=0)
#
# def __init__(self, name, url, config=None, active=True, max_limit=0):
# self.name = name
# self.url = url
# self.active = active
# self.max_limit = max_limit
#
# if config:
# self.config = config
#
# @property
# def info(self):
# return {
# "id": self.id,
# "name": self.name,
# "url": self.url
# }
. Output only the next line. | instance_type_flavorid=1 |
Next line prediction: <|code_start|>
self.pool = Mock(id=1, provider=Provider(name='fake', url='no//url'))
self.mocked_origin = Mock(
short_name="platform_1",
id=1, status="active",
get=Mock(return_value="snapshot"),
min_disk=20,
min_ram=2,
instance_type_flavorid=1
)
self.ctx = self.app.app_context()
self.ctx.push()
with patch(
"core.utils.openstack_utils.nova_client", Mock(return_value=Mock())
), patch(
"flask.current_app", self.app
):
self.clone = OpenstackClone(self.mocked_origin, "preloaded", self.pool)
def tearDown(self):
self.ctx.pop()
del self.app
def test_success_openstack_set_userdata(self):
file_object = self.clone.set_userdata("%s/data/userdata" % os.path.dirname(__file__))
self.assertTrue(hasattr(file_object, "read"))
@patch.multiple(
<|code_end|>
. Use current file imports:
(import os
from core.exceptions import CreationException
from mock import Mock, patch, PropertyMock
from tests.helpers import BaseTestCase, custom_wait, wait_for, DatabaseMock
from core.db.models import Provider
from flask import Flask
from core.config import setup_config
from core.db.models import OpenstackClone)
and context including class names, function names, or small code snippets from other files:
# Path: core/exceptions.py
# class CreationException(Exception):
# pass
#
# Path: tests/helpers.py
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# def custom_wait(self):
# self.ready = True
# self.checking = False
# yield self.ready
#
# def wait_for(condition, timeout=10):
# start = time.time()
# while not condition() and time.time() - start < timeout:
# time.sleep(0.1)
#
# return condition()
#
# 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)
#
# Path: core/db/models.py
# class Provider(Base, FeaturesMixin):
# __tablename__ = 'providers'
#
# id = Column(Integer, primary_key=True)
# name = Column(String(length=200), nullable=True)
# url = Column(String, nullable=True)
# active = Column(Boolean, default=False)
# config = Column(JSON, default={})
# max_limit = Column(Integer, default=0)
#
# def __init__(self, name, url, config=None, active=True, max_limit=0):
# self.name = name
# self.url = url
# self.active = active
# self.max_limit = max_limit
#
# if config:
# self.config = config
#
# @property
# def info(self):
# return {
# "id": self.id,
# "name": self.name,
# "url": self.url
# }
. Output only the next line. | "core.db.models.OpenstackClone", |
Based on the snippet: <|code_start|># coding: utf-8
class TestOpenstackCloneUnit(BaseTestCase):
def setUp(self):
setup_config('data/config_openstack.py')
self.app = Flask(__name__)
self.app.database = DatabaseMock()
self.pool = Mock(id=1, provider=Provider(name='fake', url='no//url'))
self.mocked_origin = Mock(
short_name="platform_1",
id=1, status="active",
get=Mock(return_value="snapshot"),
min_disk=20,
min_ram=2,
<|code_end|>
, predict the immediate next line with the help of imports:
import os
from core.exceptions import CreationException
from mock import Mock, patch, PropertyMock
from tests.helpers import BaseTestCase, custom_wait, wait_for, DatabaseMock
from core.db.models import Provider
from flask import Flask
from core.config import setup_config
from core.db.models import OpenstackClone
and context (classes, functions, sometimes code) from other files:
# Path: core/exceptions.py
# class CreationException(Exception):
# pass
#
# Path: tests/helpers.py
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# def custom_wait(self):
# self.ready = True
# self.checking = False
# yield self.ready
#
# def wait_for(condition, timeout=10):
# start = time.time()
# while not condition() and time.time() - start < timeout:
# time.sleep(0.1)
#
# return condition()
#
# 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)
#
# Path: core/db/models.py
# class Provider(Base, FeaturesMixin):
# __tablename__ = 'providers'
#
# id = Column(Integer, primary_key=True)
# name = Column(String(length=200), nullable=True)
# url = Column(String, nullable=True)
# active = Column(Boolean, default=False)
# config = Column(JSON, default={})
# max_limit = Column(Integer, default=0)
#
# def __init__(self, name, url, config=None, active=True, max_limit=0):
# self.name = name
# self.url = url
# self.active = active
# self.max_limit = max_limit
#
# if config:
# self.config = config
#
# @property
# def info(self):
# return {
# "id": self.id,
# "name": self.name,
# "url": self.url
# }
. Output only the next line. | instance_type_flavorid=1 |
Given snippet: <|code_start|> def setUp(self):
setup_config('data/config_openstack.py')
self.app = Flask(__name__)
self.app.database = DatabaseMock()
self.pool = Mock(id=1, provider=Provider(name='fake', url='no//url'))
self.mocked_origin = Mock(
short_name="platform_1",
id=1, status="active",
get=Mock(return_value="snapshot"),
min_disk=20,
min_ram=2,
instance_type_flavorid=1
)
self.ctx = self.app.app_context()
self.ctx.push()
with patch(
"core.utils.openstack_utils.nova_client", Mock(return_value=Mock())
), patch(
"flask.current_app", self.app
):
self.clone = OpenstackClone(self.mocked_origin, "preloaded", self.pool)
def tearDown(self):
self.ctx.pop()
del self.app
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
from core.exceptions import CreationException
from mock import Mock, patch, PropertyMock
from tests.helpers import BaseTestCase, custom_wait, wait_for, DatabaseMock
from core.db.models import Provider
from flask import Flask
from core.config import setup_config
from core.db.models import OpenstackClone
and context:
# Path: core/exceptions.py
# class CreationException(Exception):
# pass
#
# Path: tests/helpers.py
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# def custom_wait(self):
# self.ready = True
# self.checking = False
# yield self.ready
#
# def wait_for(condition, timeout=10):
# start = time.time()
# while not condition() and time.time() - start < timeout:
# time.sleep(0.1)
#
# return condition()
#
# 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)
#
# Path: core/db/models.py
# class Provider(Base, FeaturesMixin):
# __tablename__ = 'providers'
#
# id = Column(Integer, primary_key=True)
# name = Column(String(length=200), nullable=True)
# url = Column(String, nullable=True)
# active = Column(Boolean, default=False)
# config = Column(JSON, default={})
# max_limit = Column(Integer, default=0)
#
# def __init__(self, name, url, config=None, active=True, max_limit=0):
# self.name = name
# self.url = url
# self.active = active
# self.max_limit = max_limit
#
# if config:
# self.config = config
#
# @property
# def info(self):
# return {
# "id": self.id,
# "name": self.name,
# "url": self.url
# }
which might include code, classes, or functions. Output only the next line. | def test_success_openstack_set_userdata(self): |
Next line prediction: <|code_start|># coding: utf-8
patch('core.utils.call_in_thread', lambda x: x).start()
app_context = Mock(return_value=Mock(__enter__=Mock(), __exit__=Mock()))
class TestEndpointRemover(BaseTestCase):
def setUp(self):
setup_config('data/config_openstack.py')
def test_remove_endpoint(self):
endpoint = Mock()
endpoint_remover = EndpointRemover(
platforms=Mock(), artifact_collector=Mock(),
database=Mock(), app_context=app_context
)
endpoint_remover.save_endpoint_artifacts = Mock()
endpoint_remover.remove_endpoint(endpoint)
self.assertTrue(endpoint.service_mode_on.called)
self.assertTrue(endpoint_remover.database.get_session_by_endpoint_id.called)
self.assertTrue(endpoint_remover.save_endpoint_artifacts.called)
self.assertTrue(endpoint.delete.called)
self.assertTrue(endpoint.service_mode_off.called)
def test_stop(self):
<|code_end|>
. Use current file imports:
(from mock import Mock, patch
from tests.helpers import BaseTestCase
from core.config import setup_config
from vmpool.virtual_machines_pool import EndpointRemover
from vmpool.virtual_machines_pool import EndpointRemover)
and context including class names, function names, or small code snippets from other files:
# Path: tests/helpers.py
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
. Output only the next line. | endpoint_remover = EndpointRemover( |
Based on the snippet: <|code_start|># coding: utf-8
patch('core.utils.call_in_thread', lambda x: x).start()
class TestEndpointPreparer(BaseTestCase):
def setUp(self):
setup_config('data/config_openstack.py')
@dataprovider([
(True, False, True, False, False, True),
(False, False, True, True, True, False),
])
def test_run_preparer(self, is_running, screencast_started, take_screencast, is_waiting, pec, ssc):
sessions = Mock(active=Mock(return_value=[
Mock(
is_running=is_running, screencast_started=screencast_started,
take_screencast=take_screencast, is_waiting=is_waiting
)
]))
endpoint_preparer = EndpointPreparer(
pool=Mock(), sessions=sessions, artifact_collector=Mock(), app_context=app_context_mock
)
<|code_end|>
, predict the immediate next line with the help of imports:
from lode_runner import dataprovider
from mock import Mock, patch, PropertyMock, MagicMock
from tests.helpers import BaseTestCase, app_context_mock
from core.exceptions import CreationException
from core.config import setup_config
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer
and context (classes, functions, sometimes code) from other files:
# Path: tests/helpers.py
# class TimeoutException(Exception):
# class Response(object):
# class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
# class ServerMock(object):
# class BaseTestCase(unittest.TestCase):
# class DatabaseMock(Mock):
# def call_in_thread_mock(f):
# def wrapper(*args, **kwargs):
# def wait_for(condition, timeout=10):
# def request(host, method, url, headers=None, body=None):
# def request_with_drop(address, desired_caps, method=None):
# def new_session_request(client, desired_caps):
# def open_url_request(client, session, data):
# def delete_session_request(client, session):
# def get_session_request(client, session):
# def run_script(client, session, script):
# def vmmaster_label(client, session, label=None):
# def server_is_up(address, wait=5):
# def server_is_down(address, wait=5):
# def fake_home_dir():
# def get_free_port():
# def body(self):
# def send_reply(self, code, headers, body):
# def do_POST(self):
# def do_GET(self):
# def log_error(self, format, *args):
# def log_message(self, format, *args):
# def log_request(self, code='-', size='-'):
# def __init__(self, host, port):
# def start(self):
# def stop(self):
# def shortDescription(self):
# def set_primary_key(_self):
# def __init__(self, *args, **kwargs):
# def get_active_sessions(self, provider_id=None):
# def get_session(self, session_id):
# def get_endpoint(self, endpoint):
# def get_endpoints(self, *args, **kwargs):
# def get_last_session_step(session_id):
# def register_provider(self, name, url, platforms):
# def custom_wait(self):
# def vmmaster_server_mock(port):
# def request_mock(**kwargs):
# def wait_deferred(d, timeout=5):
#
# Path: core/exceptions.py
# class CreationException(Exception):
# pass
. Output only the next line. | endpoint_preparer.start_screencast = Mock() |
Predict the next line after this snippet: <|code_start|># coding: utf-8
patch('core.utils.call_in_thread', lambda x: x).start()
class TestEndpointPreparer(BaseTestCase):
def setUp(self):
setup_config('data/config_openstack.py')
@dataprovider([
(True, False, True, False, False, True),
(False, False, True, True, True, False),
])
def test_run_preparer(self, is_running, screencast_started, take_screencast, is_waiting, pec, ssc):
sessions = Mock(active=Mock(return_value=[
Mock(
is_running=is_running, screencast_started=screencast_started,
take_screencast=take_screencast, is_waiting=is_waiting
)
<|code_end|>
using the current file's imports:
from lode_runner import dataprovider
from mock import Mock, patch, PropertyMock, MagicMock
from tests.helpers import BaseTestCase, app_context_mock
from core.exceptions import CreationException
from core.config import setup_config
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer
and any relevant context from other files:
# Path: tests/helpers.py
# class TimeoutException(Exception):
# class Response(object):
# class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
# class ServerMock(object):
# class BaseTestCase(unittest.TestCase):
# class DatabaseMock(Mock):
# def call_in_thread_mock(f):
# def wrapper(*args, **kwargs):
# def wait_for(condition, timeout=10):
# def request(host, method, url, headers=None, body=None):
# def request_with_drop(address, desired_caps, method=None):
# def new_session_request(client, desired_caps):
# def open_url_request(client, session, data):
# def delete_session_request(client, session):
# def get_session_request(client, session):
# def run_script(client, session, script):
# def vmmaster_label(client, session, label=None):
# def server_is_up(address, wait=5):
# def server_is_down(address, wait=5):
# def fake_home_dir():
# def get_free_port():
# def body(self):
# def send_reply(self, code, headers, body):
# def do_POST(self):
# def do_GET(self):
# def log_error(self, format, *args):
# def log_message(self, format, *args):
# def log_request(self, code='-', size='-'):
# def __init__(self, host, port):
# def start(self):
# def stop(self):
# def shortDescription(self):
# def set_primary_key(_self):
# def __init__(self, *args, **kwargs):
# def get_active_sessions(self, provider_id=None):
# def get_session(self, session_id):
# def get_endpoint(self, endpoint):
# def get_endpoints(self, *args, **kwargs):
# def get_last_session_step(session_id):
# def register_provider(self, name, url, platforms):
# def custom_wait(self):
# def vmmaster_server_mock(port):
# def request_mock(**kwargs):
# def wait_deferred(d, timeout=5):
#
# Path: core/exceptions.py
# class CreationException(Exception):
# pass
. Output only the next line. | ])) |
Next line prediction: <|code_start|># coding: utf-8
patch('core.utils.call_in_thread', lambda x: x).start()
class TestEndpointPreparer(BaseTestCase):
def setUp(self):
setup_config('data/config_openstack.py')
@dataprovider([
<|code_end|>
. Use current file imports:
(from lode_runner import dataprovider
from mock import Mock, patch, PropertyMock, MagicMock
from tests.helpers import BaseTestCase, app_context_mock
from core.exceptions import CreationException
from core.config import setup_config
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer
from vmpool.endpoint import EndpointPreparer)
and context including class names, function names, or small code snippets from other files:
# Path: tests/helpers.py
# class TimeoutException(Exception):
# class Response(object):
# class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
# class ServerMock(object):
# class BaseTestCase(unittest.TestCase):
# class DatabaseMock(Mock):
# def call_in_thread_mock(f):
# def wrapper(*args, **kwargs):
# def wait_for(condition, timeout=10):
# def request(host, method, url, headers=None, body=None):
# def request_with_drop(address, desired_caps, method=None):
# def new_session_request(client, desired_caps):
# def open_url_request(client, session, data):
# def delete_session_request(client, session):
# def get_session_request(client, session):
# def run_script(client, session, script):
# def vmmaster_label(client, session, label=None):
# def server_is_up(address, wait=5):
# def server_is_down(address, wait=5):
# def fake_home_dir():
# def get_free_port():
# def body(self):
# def send_reply(self, code, headers, body):
# def do_POST(self):
# def do_GET(self):
# def log_error(self, format, *args):
# def log_message(self, format, *args):
# def log_request(self, code='-', size='-'):
# def __init__(self, host, port):
# def start(self):
# def stop(self):
# def shortDescription(self):
# def set_primary_key(_self):
# def __init__(self, *args, **kwargs):
# def get_active_sessions(self, provider_id=None):
# def get_session(self, session_id):
# def get_endpoint(self, endpoint):
# def get_endpoints(self, *args, **kwargs):
# def get_last_session_step(session_id):
# def register_provider(self, name, url, platforms):
# def custom_wait(self):
# def vmmaster_server_mock(port):
# def request_mock(**kwargs):
# def wait_deferred(d, timeout=5):
#
# Path: core/exceptions.py
# class CreationException(Exception):
# pass
. Output only the next line. | (True, False, True, False, False, True), |
Continue the code snippet: <|code_start|> self.app.cleanup()
self.ctx.pop()
@patch(
"vmmaster.webdriver.helpers.transparent",
Mock(return_value=transparent_mock(200, {}, json.dumps({'status': 0})))
)
def test_successful_open_url_request(self):
with patch(
"core.db.models.Session", Mock()
):
session = Session("origin_1")
session.id = 1
self.app.sessions.get_session = Mock(return_value=session)
data = {
"sessionId": session.id,
"url": "http://host.domain"
}
response = open_url_request(self.vmmaster_client, session.id, data)
self.assertEqual(200, response.status_code)
@patch(
"vmmaster.webdriver.helpers.transparent",
Mock(side_effect=Exception("request error"))
)
def test_exception_on_open_url_request(self):
with patch(
"core.db.models.Session", Mock()
):
<|code_end|>
. Use current file imports:
import json
import time
from uuid import uuid4
from flask import Flask
from mock import Mock, patch
from multiprocessing.pool import ThreadPool
from nose.twistedtools import reactor
from core.config import setup_config, config
from core.exceptions import SessionException
from tests.helpers import server_is_up, server_is_down, \
new_session_request, get_session_request, delete_session_request, \
vmmaster_label, run_script, BaseTestCase, \
DatabaseMock, custom_wait, request_mock, wait_for, open_url_request, app_context_mock
from vmmaster.app import create_app
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from flask import Flask
from core.sessions import SessionWorker
from vmmaster.server import VMMasterServer
from vmmaster.webdriver.helpers import get_session
and context (classes, functions, or code) from other files:
# Path: core/config.py
# 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):
#
# Path: core/exceptions.py
# class SessionException(Exception):
# pass
#
# Path: tests/helpers.py
# class TimeoutException(Exception):
# class Response(object):
# class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
# class ServerMock(object):
# class BaseTestCase(unittest.TestCase):
# class DatabaseMock(Mock):
# def call_in_thread_mock(f):
# def wrapper(*args, **kwargs):
# def wait_for(condition, timeout=10):
# def request(host, method, url, headers=None, body=None):
# def request_with_drop(address, desired_caps, method=None):
# def new_session_request(client, desired_caps):
# def open_url_request(client, session, data):
# def delete_session_request(client, session):
# def get_session_request(client, session):
# def run_script(client, session, script):
# def vmmaster_label(client, session, label=None):
# def server_is_up(address, wait=5):
# def server_is_down(address, wait=5):
# def fake_home_dir():
# def get_free_port():
# def body(self):
# def send_reply(self, code, headers, body):
# def do_POST(self):
# def do_GET(self):
# def log_error(self, format, *args):
# def log_message(self, format, *args):
# def log_request(self, code='-', size='-'):
# def __init__(self, host, port):
# def start(self):
# def stop(self):
# def shortDescription(self):
# def set_primary_key(_self):
# def __init__(self, *args, **kwargs):
# def get_active_sessions(self, provider_id=None):
# def get_session(self, session_id):
# def get_endpoint(self, endpoint):
# def get_endpoints(self, *args, **kwargs):
# def get_last_session_step(session_id):
# def register_provider(self, name, url, platforms):
# def custom_wait(self):
# def vmmaster_server_mock(port):
# def request_mock(**kwargs):
# def wait_deferred(d, timeout=5):
. Output only the next line. | session = Session("origin_1") |
Predict the next line after this snippet: <|code_start|>
@patch(
"vmmaster.webdriver.helpers.transparent",
Mock(side_effect=Exception("request error"))
)
def test_exception_on_open_url_request(self):
with patch(
"core.db.models.Session", Mock()
):
session = Session("origin_1")
session.id = 1
self.app.sessions.get_session = Mock(return_value=session)
data = {
"sessionId": session.id,
"url": "http://host.domain"
}
response = open_url_request(self.vmmaster_client, session.id, data)
response_data = json.loads(response.data)
self.assertEqual(500, response.status_code)
self.assertEqual(13, response_data.get("status", 0))
self.assertIn("request error", response_data.get("value", {}).get("message", None))
@patch(
"vmmaster.webdriver.helpers.transparent",
Mock(return_value=transparent_mock(500, None, None))
)
def test_open_url_request_with_empty_response_from_endpoint(self):
with patch(
"core.db.models.Session", Mock()
<|code_end|>
using the current file's imports:
import json
import time
from uuid import uuid4
from flask import Flask
from mock import Mock, patch
from multiprocessing.pool import ThreadPool
from nose.twistedtools import reactor
from core.config import setup_config, config
from core.exceptions import SessionException
from tests.helpers import server_is_up, server_is_down, \
new_session_request, get_session_request, delete_session_request, \
vmmaster_label, run_script, BaseTestCase, \
DatabaseMock, custom_wait, request_mock, wait_for, open_url_request, app_context_mock
from vmmaster.app import create_app
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from flask import Flask
from core.sessions import SessionWorker
from vmmaster.server import VMMasterServer
from vmmaster.webdriver.helpers import get_session
and any relevant context from other files:
# Path: core/config.py
# 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):
#
# Path: core/exceptions.py
# class SessionException(Exception):
# pass
#
# Path: tests/helpers.py
# class TimeoutException(Exception):
# class Response(object):
# class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
# class ServerMock(object):
# class BaseTestCase(unittest.TestCase):
# class DatabaseMock(Mock):
# def call_in_thread_mock(f):
# def wrapper(*args, **kwargs):
# def wait_for(condition, timeout=10):
# def request(host, method, url, headers=None, body=None):
# def request_with_drop(address, desired_caps, method=None):
# def new_session_request(client, desired_caps):
# def open_url_request(client, session, data):
# def delete_session_request(client, session):
# def get_session_request(client, session):
# def run_script(client, session, script):
# def vmmaster_label(client, session, label=None):
# def server_is_up(address, wait=5):
# def server_is_down(address, wait=5):
# def fake_home_dir():
# def get_free_port():
# def body(self):
# def send_reply(self, code, headers, body):
# def do_POST(self):
# def do_GET(self):
# def log_error(self, format, *args):
# def log_message(self, format, *args):
# def log_request(self, code='-', size='-'):
# def __init__(self, host, port):
# def start(self):
# def stop(self):
# def shortDescription(self):
# def set_primary_key(_self):
# def __init__(self, *args, **kwargs):
# def get_active_sessions(self, provider_id=None):
# def get_session(self, session_id):
# def get_endpoint(self, endpoint):
# def get_endpoints(self, *args, **kwargs):
# def get_last_session_step(session_id):
# def register_provider(self, name, url, platforms):
# def custom_wait(self):
# def vmmaster_server_mock(port):
# def request_mock(**kwargs):
# def wait_deferred(d, timeout=5):
. Output only the next line. | ): |
Based on the snippet: <|code_start|> _get_nova_client=Mock(return_value=Mock()),
_wait_for_activated_service=custom_wait,
ping_endpoint_before_start_session=Mock(return_value=True),
is_broken=Mock(return_value=False)
)
)
class TestServer(BaseTestFlaskApp):
def setUp(self):
setup_config('data/config_openstack.py')
super(TestServer, self).setUp()
self.desired_caps = {
'desiredCapabilities': {
'platform': 'origin_1'
}
}
self.vmmaster_client = self.app.test_client()
self.ctx = self.app.app_context()
self.ctx.push()
def tearDown(self):
self.app.sessions.kill_all()
self.app.cleanup()
self.ctx.pop()
def test_server_create_new_session(self):
response = new_session_request(self.vmmaster_client, self.desired_caps)
self.assertEqual(200, response.status_code)
def test_server_creating_a_few_parallel_sessions(self):
<|code_end|>
, predict the immediate next line with the help of imports:
import json
import time
from uuid import uuid4
from flask import Flask
from mock import Mock, patch
from multiprocessing.pool import ThreadPool
from nose.twistedtools import reactor
from core.config import setup_config, config
from core.exceptions import SessionException
from tests.helpers import server_is_up, server_is_down, \
new_session_request, get_session_request, delete_session_request, \
vmmaster_label, run_script, BaseTestCase, \
DatabaseMock, custom_wait, request_mock, wait_for, open_url_request, app_context_mock
from vmmaster.app import create_app
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from flask import Flask
from core.sessions import SessionWorker
from vmmaster.server import VMMasterServer
from vmmaster.webdriver.helpers import get_session
and context (classes, functions, sometimes code) from other files:
# Path: core/config.py
# 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):
#
# Path: core/exceptions.py
# class SessionException(Exception):
# pass
#
# Path: tests/helpers.py
# class TimeoutException(Exception):
# class Response(object):
# class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
# class ServerMock(object):
# class BaseTestCase(unittest.TestCase):
# class DatabaseMock(Mock):
# def call_in_thread_mock(f):
# def wrapper(*args, **kwargs):
# def wait_for(condition, timeout=10):
# def request(host, method, url, headers=None, body=None):
# def request_with_drop(address, desired_caps, method=None):
# def new_session_request(client, desired_caps):
# def open_url_request(client, session, data):
# def delete_session_request(client, session):
# def get_session_request(client, session):
# def run_script(client, session, script):
# def vmmaster_label(client, session, label=None):
# def server_is_up(address, wait=5):
# def server_is_down(address, wait=5):
# def fake_home_dir():
# def get_free_port():
# def body(self):
# def send_reply(self, code, headers, body):
# def do_POST(self):
# def do_GET(self):
# def log_error(self, format, *args):
# def log_message(self, format, *args):
# def log_request(self, code='-', size='-'):
# def __init__(self, host, port):
# def start(self):
# def stop(self):
# def shortDescription(self):
# def set_primary_key(_self):
# def __init__(self, *args, **kwargs):
# def get_active_sessions(self, provider_id=None):
# def get_session(self, session_id):
# def get_endpoint(self, endpoint):
# def get_endpoints(self, *args, **kwargs):
# def get_last_session_step(session_id):
# def register_provider(self, name, url, platforms):
# def custom_wait(self):
# def vmmaster_server_mock(port):
# def request_mock(**kwargs):
# def wait_deferred(d, timeout=5):
. Output only the next line. | tpool = ThreadPool(2) |
Based on the snippet: <|code_start|>
@patch.multiple(
'vmmaster.webdriver.commands',
ping_endpoint_before_start_session=Mock(side_effect=ping_vm_true_mock),
selenium_status=Mock(return_value=(200, {}, json.dumps({'status': 0}))),
start_selenium_session=Mock(return_value=(200, {}, json.dumps({'sessionId': "1"})))
)
@patch.multiple(
"core.db.models.Session",
endpoint_id=Mock(return_value=1),
endpoint=Mock(
vnc_port=5900,
agent_port=9000,
selenium_port=4455,
_get_nova_client=Mock(return_value=Mock()),
_wait_for_activated_service=custom_wait,
ping_endpoint_before_start_session=Mock(return_value=True),
is_broken=Mock(return_value=False)
)
)
class TestServer(BaseTestFlaskApp):
def setUp(self):
setup_config('data/config_openstack.py')
super(TestServer, self).setUp()
self.desired_caps = {
'desiredCapabilities': {
'platform': 'origin_1'
}
<|code_end|>
, predict the immediate next line with the help of imports:
import json
import time
from uuid import uuid4
from flask import Flask
from mock import Mock, patch
from multiprocessing.pool import ThreadPool
from nose.twistedtools import reactor
from core.config import setup_config, config
from core.exceptions import SessionException
from tests.helpers import server_is_up, server_is_down, \
new_session_request, get_session_request, delete_session_request, \
vmmaster_label, run_script, BaseTestCase, \
DatabaseMock, custom_wait, request_mock, wait_for, open_url_request, app_context_mock
from vmmaster.app import create_app
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from flask import Flask
from core.sessions import SessionWorker
from vmmaster.server import VMMasterServer
from vmmaster.webdriver.helpers import get_session
and context (classes, functions, sometimes code) from other files:
# Path: core/config.py
# 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):
#
# Path: core/exceptions.py
# class SessionException(Exception):
# pass
#
# Path: tests/helpers.py
# class TimeoutException(Exception):
# class Response(object):
# class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
# class ServerMock(object):
# class BaseTestCase(unittest.TestCase):
# class DatabaseMock(Mock):
# def call_in_thread_mock(f):
# def wrapper(*args, **kwargs):
# def wait_for(condition, timeout=10):
# def request(host, method, url, headers=None, body=None):
# def request_with_drop(address, desired_caps, method=None):
# def new_session_request(client, desired_caps):
# def open_url_request(client, session, data):
# def delete_session_request(client, session):
# def get_session_request(client, session):
# def run_script(client, session, script):
# def vmmaster_label(client, session, label=None):
# def server_is_up(address, wait=5):
# def server_is_down(address, wait=5):
# def fake_home_dir():
# def get_free_port():
# def body(self):
# def send_reply(self, code, headers, body):
# def do_POST(self):
# def do_GET(self):
# def log_error(self, format, *args):
# def log_message(self, format, *args):
# def log_request(self, code='-', size='-'):
# def __init__(self, host, port):
# def start(self):
# def stop(self):
# def shortDescription(self):
# def set_primary_key(_self):
# def __init__(self, *args, **kwargs):
# def get_active_sessions(self, provider_id=None):
# def get_session(self, session_id):
# def get_endpoint(self, endpoint):
# def get_endpoints(self, *args, **kwargs):
# def get_last_session_step(session_id):
# def register_provider(self, name, url, platforms):
# def custom_wait(self):
# def vmmaster_server_mock(port):
# def request_mock(**kwargs):
# def wait_deferred(d, timeout=5):
. Output only the next line. | } |
Given the code snippet: <|code_start|> self.assertIn("request error", response_data.get("value", {}).get("message", None))
@patch(
"vmmaster.webdriver.helpers.transparent",
Mock(return_value=transparent_mock(500, None, None))
)
def test_open_url_request_with_empty_response_from_endpoint(self):
with patch(
"core.db.models.Session", Mock()
):
session = Session("origin_1")
session.id = 1
self.app.sessions.get_session = Mock(return_value=session)
data = {
"sessionId": session.id,
"url": "http://host.domain"
}
response = open_url_request(self.vmmaster_client, session.id, data)
response_data = json.loads(response.data)
self.assertEqual(500, response.status_code)
self.assertEqual(13, response_data.get("status", 0))
self.assertIn(
"Something ugly happened. No real reply formed",
response_data.get("value", {}).get("message", None)
)
@patch(
"vmmaster.webdriver.helpers.transparent",
Mock(return_value=transparent_mock(500, None, "No response"))
<|code_end|>
, generate the next line using the imports in this file:
import json
import time
from uuid import uuid4
from flask import Flask
from mock import Mock, patch
from multiprocessing.pool import ThreadPool
from nose.twistedtools import reactor
from core.config import setup_config, config
from core.exceptions import SessionException
from tests.helpers import server_is_up, server_is_down, \
new_session_request, get_session_request, delete_session_request, \
vmmaster_label, run_script, BaseTestCase, \
DatabaseMock, custom_wait, request_mock, wait_for, open_url_request, app_context_mock
from vmmaster.app import create_app
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from flask import Flask
from core.sessions import SessionWorker
from vmmaster.server import VMMasterServer
from vmmaster.webdriver.helpers import get_session
and context (functions, classes, or occasionally code) from other files:
# Path: core/config.py
# 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):
#
# Path: core/exceptions.py
# class SessionException(Exception):
# pass
#
# Path: tests/helpers.py
# class TimeoutException(Exception):
# class Response(object):
# class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
# class ServerMock(object):
# class BaseTestCase(unittest.TestCase):
# class DatabaseMock(Mock):
# def call_in_thread_mock(f):
# def wrapper(*args, **kwargs):
# def wait_for(condition, timeout=10):
# def request(host, method, url, headers=None, body=None):
# def request_with_drop(address, desired_caps, method=None):
# def new_session_request(client, desired_caps):
# def open_url_request(client, session, data):
# def delete_session_request(client, session):
# def get_session_request(client, session):
# def run_script(client, session, script):
# def vmmaster_label(client, session, label=None):
# def server_is_up(address, wait=5):
# def server_is_down(address, wait=5):
# def fake_home_dir():
# def get_free_port():
# def body(self):
# def send_reply(self, code, headers, body):
# def do_POST(self):
# def do_GET(self):
# def log_error(self, format, *args):
# def log_message(self, format, *args):
# def log_request(self, code='-', size='-'):
# def __init__(self, host, port):
# def start(self):
# def stop(self):
# def shortDescription(self):
# def set_primary_key(_self):
# def __init__(self, *args, **kwargs):
# def get_active_sessions(self, provider_id=None):
# def get_session(self, session_id):
# def get_endpoint(self, endpoint):
# def get_endpoints(self, *args, **kwargs):
# def get_last_session_step(session_id):
# def register_provider(self, name, url, platforms):
# def custom_wait(self):
# def vmmaster_server_mock(port):
# def request_mock(**kwargs):
# def wait_deferred(d, timeout=5):
. Output only the next line. | ) |
Continue the code snippet: <|code_start|> setup_config('data/config_openstack.py')
super(TestServer, self).setUp()
self.desired_caps = {
'desiredCapabilities': {
'platform': 'origin_1'
}
}
self.vmmaster_client = self.app.test_client()
self.ctx = self.app.app_context()
self.ctx.push()
def tearDown(self):
self.app.sessions.kill_all()
self.app.cleanup()
self.ctx.pop()
def test_server_create_new_session(self):
response = new_session_request(self.vmmaster_client, self.desired_caps)
self.assertEqual(200, response.status_code)
def test_server_creating_a_few_parallel_sessions(self):
tpool = ThreadPool(2)
deffered1 = tpool.apply_async(new_session_request, args=(
self.vmmaster_client, self.desired_caps))
deffered2 = tpool.apply_async(new_session_request, args=(
self.vmmaster_client, self.desired_caps))
deffered1.wait()
deffered2.wait()
<|code_end|>
. Use current file imports:
import json
import time
from uuid import uuid4
from flask import Flask
from mock import Mock, patch
from multiprocessing.pool import ThreadPool
from nose.twistedtools import reactor
from core.config import setup_config, config
from core.exceptions import SessionException
from tests.helpers import server_is_up, server_is_down, \
new_session_request, get_session_request, delete_session_request, \
vmmaster_label, run_script, BaseTestCase, \
DatabaseMock, custom_wait, request_mock, wait_for, open_url_request, app_context_mock
from vmmaster.app import create_app
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from flask import Flask
from core.sessions import SessionWorker
from vmmaster.server import VMMasterServer
from vmmaster.webdriver.helpers import get_session
and context (classes, functions, or code) from other files:
# Path: core/config.py
# 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):
#
# Path: core/exceptions.py
# class SessionException(Exception):
# pass
#
# Path: tests/helpers.py
# class TimeoutException(Exception):
# class Response(object):
# class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
# class ServerMock(object):
# class BaseTestCase(unittest.TestCase):
# class DatabaseMock(Mock):
# def call_in_thread_mock(f):
# def wrapper(*args, **kwargs):
# def wait_for(condition, timeout=10):
# def request(host, method, url, headers=None, body=None):
# def request_with_drop(address, desired_caps, method=None):
# def new_session_request(client, desired_caps):
# def open_url_request(client, session, data):
# def delete_session_request(client, session):
# def get_session_request(client, session):
# def run_script(client, session, script):
# def vmmaster_label(client, session, label=None):
# def server_is_up(address, wait=5):
# def server_is_down(address, wait=5):
# def fake_home_dir():
# def get_free_port():
# def body(self):
# def send_reply(self, code, headers, body):
# def do_POST(self):
# def do_GET(self):
# def log_error(self, format, *args):
# def log_message(self, format, *args):
# def log_request(self, code='-', size='-'):
# def __init__(self, host, port):
# def start(self):
# def stop(self):
# def shortDescription(self):
# def set_primary_key(_self):
# def __init__(self, *args, **kwargs):
# def get_active_sessions(self, provider_id=None):
# def get_session(self, session_id):
# def get_endpoint(self, endpoint):
# def get_endpoints(self, *args, **kwargs):
# def get_last_session_step(session_id):
# def register_provider(self, name, url, platforms):
# def custom_wait(self):
# def vmmaster_server_mock(port):
# def request_mock(**kwargs):
# def wait_deferred(d, timeout=5):
. Output only the next line. | result1 = deffered1.get() |
Next line prediction: <|code_start|> }
}
self.vmmaster_client = self.app.test_client()
self.ctx = self.app.app_context()
self.ctx.push()
def tearDown(self):
self.app.sessions.kill_all()
self.app.cleanup()
self.ctx.pop()
@patch(
"vmmaster.webdriver.helpers.transparent",
Mock(return_value=transparent_mock(200, {}, json.dumps({'status': 0})))
)
def test_successful_open_url_request(self):
with patch(
"core.db.models.Session", Mock()
):
session = Session("origin_1")
session.id = 1
self.app.sessions.get_session = Mock(return_value=session)
data = {
"sessionId": session.id,
"url": "http://host.domain"
}
response = open_url_request(self.vmmaster_client, session.id, data)
self.assertEqual(200, response.status_code)
<|code_end|>
. Use current file imports:
(import json
import time
from uuid import uuid4
from flask import Flask
from mock import Mock, patch
from multiprocessing.pool import ThreadPool
from nose.twistedtools import reactor
from core.config import setup_config, config
from core.exceptions import SessionException
from tests.helpers import server_is_up, server_is_down, \
new_session_request, get_session_request, delete_session_request, \
vmmaster_label, run_script, BaseTestCase, \
DatabaseMock, custom_wait, request_mock, wait_for, open_url_request, app_context_mock
from vmmaster.app import create_app
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from flask import Flask
from core.sessions import SessionWorker
from vmmaster.server import VMMasterServer
from vmmaster.webdriver.helpers import get_session)
and context including class names, function names, or small code snippets from other files:
# Path: core/config.py
# 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):
#
# Path: core/exceptions.py
# class SessionException(Exception):
# pass
#
# Path: tests/helpers.py
# class TimeoutException(Exception):
# class Response(object):
# class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
# class ServerMock(object):
# class BaseTestCase(unittest.TestCase):
# class DatabaseMock(Mock):
# def call_in_thread_mock(f):
# def wrapper(*args, **kwargs):
# def wait_for(condition, timeout=10):
# def request(host, method, url, headers=None, body=None):
# def request_with_drop(address, desired_caps, method=None):
# def new_session_request(client, desired_caps):
# def open_url_request(client, session, data):
# def delete_session_request(client, session):
# def get_session_request(client, session):
# def run_script(client, session, script):
# def vmmaster_label(client, session, label=None):
# def server_is_up(address, wait=5):
# def server_is_down(address, wait=5):
# def fake_home_dir():
# def get_free_port():
# def body(self):
# def send_reply(self, code, headers, body):
# def do_POST(self):
# def do_GET(self):
# def log_error(self, format, *args):
# def log_message(self, format, *args):
# def log_request(self, code='-', size='-'):
# def __init__(self, host, port):
# def start(self):
# def stop(self):
# def shortDescription(self):
# def set_primary_key(_self):
# def __init__(self, *args, **kwargs):
# def get_active_sessions(self, provider_id=None):
# def get_session(self, session_id):
# def get_endpoint(self, endpoint):
# def get_endpoints(self, *args, **kwargs):
# def get_last_session_step(session_id):
# def register_provider(self, name, url, platforms):
# def custom_wait(self):
# def vmmaster_server_mock(port):
# def request_mock(**kwargs):
# def wait_deferred(d, timeout=5):
. Output only the next line. | @patch( |
Given the code snippet: <|code_start|> setup_config('data/config_openstack.py')
super(TestProxyRequests, self).setUp()
self.desired_caps = {
'desiredCapabilities': {
'platform': 'origin_1'
}
}
self.vmmaster_client = self.app.test_client()
self.ctx = self.app.app_context()
self.ctx.push()
def tearDown(self):
self.app.sessions.kill_all()
self.app.cleanup()
self.ctx.pop()
@patch(
"vmmaster.webdriver.helpers.transparent",
Mock(return_value=transparent_mock(200, {}, json.dumps({'status': 0})))
)
def test_successful_open_url_request(self):
with patch(
"core.db.models.Session", Mock()
):
session = Session("origin_1")
session.id = 1
self.app.sessions.get_session = Mock(return_value=session)
data = {
<|code_end|>
, generate the next line using the imports in this file:
import json
import time
from uuid import uuid4
from flask import Flask
from mock import Mock, patch
from multiprocessing.pool import ThreadPool
from nose.twistedtools import reactor
from core.config import setup_config, config
from core.exceptions import SessionException
from tests.helpers import server_is_up, server_is_down, \
new_session_request, get_session_request, delete_session_request, \
vmmaster_label, run_script, BaseTestCase, \
DatabaseMock, custom_wait, request_mock, wait_for, open_url_request, app_context_mock
from vmmaster.app import create_app
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from flask import Flask
from core.sessions import SessionWorker
from vmmaster.server import VMMasterServer
from vmmaster.webdriver.helpers import get_session
and context (functions, classes, or occasionally code) from other files:
# Path: core/config.py
# 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):
#
# Path: core/exceptions.py
# class SessionException(Exception):
# pass
#
# Path: tests/helpers.py
# class TimeoutException(Exception):
# class Response(object):
# class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
# class ServerMock(object):
# class BaseTestCase(unittest.TestCase):
# class DatabaseMock(Mock):
# def call_in_thread_mock(f):
# def wrapper(*args, **kwargs):
# def wait_for(condition, timeout=10):
# def request(host, method, url, headers=None, body=None):
# def request_with_drop(address, desired_caps, method=None):
# def new_session_request(client, desired_caps):
# def open_url_request(client, session, data):
# def delete_session_request(client, session):
# def get_session_request(client, session):
# def run_script(client, session, script):
# def vmmaster_label(client, session, label=None):
# def server_is_up(address, wait=5):
# def server_is_down(address, wait=5):
# def fake_home_dir():
# def get_free_port():
# def body(self):
# def send_reply(self, code, headers, body):
# def do_POST(self):
# def do_GET(self):
# def log_error(self, format, *args):
# def log_message(self, format, *args):
# def log_request(self, code='-', size='-'):
# def __init__(self, host, port):
# def start(self):
# def stop(self):
# def shortDescription(self):
# def set_primary_key(_self):
# def __init__(self, *args, **kwargs):
# def get_active_sessions(self, provider_id=None):
# def get_session(self, session_id):
# def get_endpoint(self, endpoint):
# def get_endpoints(self, *args, **kwargs):
# def get_last_session_step(session_id):
# def register_provider(self, name, url, platforms):
# def custom_wait(self):
# def vmmaster_server_mock(port):
# def request_mock(**kwargs):
# def wait_deferred(d, timeout=5):
. Output only the next line. | "sessionId": session.id, |
Here is a snippet: <|code_start|> self.app.sessions.kill_all()
self.app.cleanup()
self.ctx.pop()
@patch(
"vmmaster.webdriver.helpers.transparent",
Mock(return_value=transparent_mock(200, {}, json.dumps({'status': 0})))
)
def test_successful_open_url_request(self):
with patch(
"core.db.models.Session", Mock()
):
session = Session("origin_1")
session.id = 1
self.app.sessions.get_session = Mock(return_value=session)
data = {
"sessionId": session.id,
"url": "http://host.domain"
}
response = open_url_request(self.vmmaster_client, session.id, data)
self.assertEqual(200, response.status_code)
@patch(
"vmmaster.webdriver.helpers.transparent",
Mock(side_effect=Exception("request error"))
)
def test_exception_on_open_url_request(self):
with patch(
"core.db.models.Session", Mock()
<|code_end|>
. Write the next line using the current file imports:
import json
import time
from uuid import uuid4
from flask import Flask
from mock import Mock, patch
from multiprocessing.pool import ThreadPool
from nose.twistedtools import reactor
from core.config import setup_config, config
from core.exceptions import SessionException
from tests.helpers import server_is_up, server_is_down, \
new_session_request, get_session_request, delete_session_request, \
vmmaster_label, run_script, BaseTestCase, \
DatabaseMock, custom_wait, request_mock, wait_for, open_url_request, app_context_mock
from vmmaster.app import create_app
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from flask import Flask
from core.sessions import SessionWorker
from vmmaster.server import VMMasterServer
from vmmaster.webdriver.helpers import get_session
and context from other files:
# Path: core/config.py
# 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):
#
# Path: core/exceptions.py
# class SessionException(Exception):
# pass
#
# Path: tests/helpers.py
# class TimeoutException(Exception):
# class Response(object):
# class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
# class ServerMock(object):
# class BaseTestCase(unittest.TestCase):
# class DatabaseMock(Mock):
# def call_in_thread_mock(f):
# def wrapper(*args, **kwargs):
# def wait_for(condition, timeout=10):
# def request(host, method, url, headers=None, body=None):
# def request_with_drop(address, desired_caps, method=None):
# def new_session_request(client, desired_caps):
# def open_url_request(client, session, data):
# def delete_session_request(client, session):
# def get_session_request(client, session):
# def run_script(client, session, script):
# def vmmaster_label(client, session, label=None):
# def server_is_up(address, wait=5):
# def server_is_down(address, wait=5):
# def fake_home_dir():
# def get_free_port():
# def body(self):
# def send_reply(self, code, headers, body):
# def do_POST(self):
# def do_GET(self):
# def log_error(self, format, *args):
# def log_message(self, format, *args):
# def log_request(self, code='-', size='-'):
# def __init__(self, host, port):
# def start(self):
# def stop(self):
# def shortDescription(self):
# def set_primary_key(_self):
# def __init__(self, *args, **kwargs):
# def get_active_sessions(self, provider_id=None):
# def get_session(self, session_id):
# def get_endpoint(self, endpoint):
# def get_endpoints(self, *args, **kwargs):
# def get_last_session_step(session_id):
# def register_provider(self, name, url, platforms):
# def custom_wait(self):
# def vmmaster_server_mock(port):
# def request_mock(**kwargs):
# def wait_deferred(d, timeout=5):
, which may include functions, classes, or code. Output only the next line. | ): |
Based on the snippet: <|code_start|> ), patch(
'vmpool.virtual_machines_pool.VirtualMachinesPool', Mock()
):
self.app = create_app()
self.app.get_matched_platforms = Mock(return_value=('origin_1', 1))
self.desired_caps = {
'desiredCapabilities': {
'platform': 'origin_1'
}
}
@patch("vmmaster.webdriver.take_screenshot", Mock())
class TestProxyRequests(BaseTestFlaskApp):
def setUp(self):
setup_config('data/config_openstack.py')
super(TestProxyRequests, self).setUp()
self.desired_caps = {
'desiredCapabilities': {
'platform': 'origin_1'
}
}
self.vmmaster_client = self.app.test_client()
self.ctx = self.app.app_context()
self.ctx.push()
def tearDown(self):
self.app.sessions.kill_all()
<|code_end|>
, predict the immediate next line with the help of imports:
import json
import time
from uuid import uuid4
from flask import Flask
from mock import Mock, patch
from multiprocessing.pool import ThreadPool
from nose.twistedtools import reactor
from core.config import setup_config, config
from core.exceptions import SessionException
from tests.helpers import server_is_up, server_is_down, \
new_session_request, get_session_request, delete_session_request, \
vmmaster_label, run_script, BaseTestCase, \
DatabaseMock, custom_wait, request_mock, wait_for, open_url_request, app_context_mock
from vmmaster.app import create_app
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from flask import Flask
from core.sessions import SessionWorker
from vmmaster.server import VMMasterServer
from vmmaster.webdriver.helpers import get_session
and context (classes, functions, sometimes code) from other files:
# Path: core/config.py
# 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):
#
# Path: core/exceptions.py
# class SessionException(Exception):
# pass
#
# Path: tests/helpers.py
# class TimeoutException(Exception):
# class Response(object):
# class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
# class ServerMock(object):
# class BaseTestCase(unittest.TestCase):
# class DatabaseMock(Mock):
# def call_in_thread_mock(f):
# def wrapper(*args, **kwargs):
# def wait_for(condition, timeout=10):
# def request(host, method, url, headers=None, body=None):
# def request_with_drop(address, desired_caps, method=None):
# def new_session_request(client, desired_caps):
# def open_url_request(client, session, data):
# def delete_session_request(client, session):
# def get_session_request(client, session):
# def run_script(client, session, script):
# def vmmaster_label(client, session, label=None):
# def server_is_up(address, wait=5):
# def server_is_down(address, wait=5):
# def fake_home_dir():
# def get_free_port():
# def body(self):
# def send_reply(self, code, headers, body):
# def do_POST(self):
# def do_GET(self):
# def log_error(self, format, *args):
# def log_message(self, format, *args):
# def log_request(self, code='-', size='-'):
# def __init__(self, host, port):
# def start(self):
# def stop(self):
# def shortDescription(self):
# def set_primary_key(_self):
# def __init__(self, *args, **kwargs):
# def get_active_sessions(self, provider_id=None):
# def get_session(self, session_id):
# def get_endpoint(self, endpoint):
# def get_endpoints(self, *args, **kwargs):
# def get_last_session_step(session_id):
# def register_provider(self, name, url, platforms):
# def custom_wait(self):
# def vmmaster_server_mock(port):
# def request_mock(**kwargs):
# def wait_deferred(d, timeout=5):
. Output only the next line. | self.app.cleanup() |
Here is a snippet: <|code_start|> def test_open_url_request_if_no_response_from_endpoint(self):
with patch(
"core.db.models.Session", Mock()
):
session = Session("origin_1")
session.id = 1
self.app.sessions.get_session = Mock(return_value=session)
data = {
"sessionId": session.id,
"url": "http://host.domain"
}
response = open_url_request(self.vmmaster_client, session.id, data)
response_data = json.loads(response.data)
self.assertEqual(500, response.status_code)
self.assertEqual(13, response_data.get("status", 0))
self.assertIn(
"No response",
response_data.get("value", {}).get("message", None)
)
@patch.multiple(
'vmmaster.webdriver.commands',
ping_endpoint_before_start_session=Mock(side_effect=ping_vm_true_mock),
selenium_status=Mock(return_value=(200, {}, json.dumps({'status': 0}))),
start_selenium_session=Mock(return_value=(200, {}, json.dumps({'sessionId': "1"})))
)
@patch.multiple(
"core.db.models.Session",
<|code_end|>
. Write the next line using the current file imports:
import json
import time
from uuid import uuid4
from flask import Flask
from mock import Mock, patch
from multiprocessing.pool import ThreadPool
from nose.twistedtools import reactor
from core.config import setup_config, config
from core.exceptions import SessionException
from tests.helpers import server_is_up, server_is_down, \
new_session_request, get_session_request, delete_session_request, \
vmmaster_label, run_script, BaseTestCase, \
DatabaseMock, custom_wait, request_mock, wait_for, open_url_request, app_context_mock
from vmmaster.app import create_app
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from flask import Flask
from core.sessions import SessionWorker
from vmmaster.server import VMMasterServer
from vmmaster.webdriver.helpers import get_session
and context from other files:
# Path: core/config.py
# 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):
#
# Path: core/exceptions.py
# class SessionException(Exception):
# pass
#
# Path: tests/helpers.py
# class TimeoutException(Exception):
# class Response(object):
# class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
# class ServerMock(object):
# class BaseTestCase(unittest.TestCase):
# class DatabaseMock(Mock):
# def call_in_thread_mock(f):
# def wrapper(*args, **kwargs):
# def wait_for(condition, timeout=10):
# def request(host, method, url, headers=None, body=None):
# def request_with_drop(address, desired_caps, method=None):
# def new_session_request(client, desired_caps):
# def open_url_request(client, session, data):
# def delete_session_request(client, session):
# def get_session_request(client, session):
# def run_script(client, session, script):
# def vmmaster_label(client, session, label=None):
# def server_is_up(address, wait=5):
# def server_is_down(address, wait=5):
# def fake_home_dir():
# def get_free_port():
# def body(self):
# def send_reply(self, code, headers, body):
# def do_POST(self):
# def do_GET(self):
# def log_error(self, format, *args):
# def log_message(self, format, *args):
# def log_request(self, code='-', size='-'):
# def __init__(self, host, port):
# def start(self):
# def stop(self):
# def shortDescription(self):
# def set_primary_key(_self):
# def __init__(self, *args, **kwargs):
# def get_active_sessions(self, provider_id=None):
# def get_session(self, session_id):
# def get_endpoint(self, endpoint):
# def get_endpoints(self, *args, **kwargs):
# def get_last_session_step(session_id):
# def register_provider(self, name, url, platforms):
# def custom_wait(self):
# def vmmaster_server_mock(port):
# def request_mock(**kwargs):
# def wait_deferred(d, timeout=5):
, which may include functions, classes, or code. Output only the next line. | endpoint_id=Mock(return_value=1), |
Given the following code snippet before the placeholder: <|code_start|> endpoint_id=Mock(return_value=1),
endpoint=Mock(
vnc_port=5900,
agent_port=9000,
selenium_port=4455,
_get_nova_client=Mock(return_value=Mock()),
_wait_for_activated_service=custom_wait,
ping_endpoint_before_start_session=Mock(return_value=True),
is_broken=Mock(return_value=False)
)
)
class TestServer(BaseTestFlaskApp):
def setUp(self):
setup_config('data/config_openstack.py')
super(TestServer, self).setUp()
self.desired_caps = {
'desiredCapabilities': {
'platform': 'origin_1'
}
}
self.vmmaster_client = self.app.test_client()
self.ctx = self.app.app_context()
self.ctx.push()
def tearDown(self):
self.app.sessions.kill_all()
self.app.cleanup()
self.ctx.pop()
<|code_end|>
, predict the next line using imports from the current file:
import json
import time
from uuid import uuid4
from flask import Flask
from mock import Mock, patch
from multiprocessing.pool import ThreadPool
from nose.twistedtools import reactor
from core.config import setup_config, config
from core.exceptions import SessionException
from tests.helpers import server_is_up, server_is_down, \
new_session_request, get_session_request, delete_session_request, \
vmmaster_label, run_script, BaseTestCase, \
DatabaseMock, custom_wait, request_mock, wait_for, open_url_request, app_context_mock
from vmmaster.app import create_app
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from flask import Flask
from core.sessions import SessionWorker
from vmmaster.server import VMMasterServer
from vmmaster.webdriver.helpers import get_session
and context including class names, function names, and sometimes code from other files:
# Path: core/config.py
# 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):
#
# Path: core/exceptions.py
# class SessionException(Exception):
# pass
#
# Path: tests/helpers.py
# class TimeoutException(Exception):
# class Response(object):
# class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
# class ServerMock(object):
# class BaseTestCase(unittest.TestCase):
# class DatabaseMock(Mock):
# def call_in_thread_mock(f):
# def wrapper(*args, **kwargs):
# def wait_for(condition, timeout=10):
# def request(host, method, url, headers=None, body=None):
# def request_with_drop(address, desired_caps, method=None):
# def new_session_request(client, desired_caps):
# def open_url_request(client, session, data):
# def delete_session_request(client, session):
# def get_session_request(client, session):
# def run_script(client, session, script):
# def vmmaster_label(client, session, label=None):
# def server_is_up(address, wait=5):
# def server_is_down(address, wait=5):
# def fake_home_dir():
# def get_free_port():
# def body(self):
# def send_reply(self, code, headers, body):
# def do_POST(self):
# def do_GET(self):
# def log_error(self, format, *args):
# def log_message(self, format, *args):
# def log_request(self, code='-', size='-'):
# def __init__(self, host, port):
# def start(self):
# def stop(self):
# def shortDescription(self):
# def set_primary_key(_self):
# def __init__(self, *args, **kwargs):
# def get_active_sessions(self, provider_id=None):
# def get_session(self, session_id):
# def get_endpoint(self, endpoint):
# def get_endpoints(self, *args, **kwargs):
# def get_last_session_step(session_id):
# def register_provider(self, name, url, platforms):
# def custom_wait(self):
# def vmmaster_server_mock(port):
# def request_mock(**kwargs):
# def wait_deferred(d, timeout=5):
. Output only the next line. | def test_server_create_new_session(self): |
Given the code snippet: <|code_start|> session = Session("origin_1")
session.id = 1
self.app.sessions.get_session = Mock(return_value=session)
data = {
"sessionId": session.id,
"url": "http://host.domain"
}
response = open_url_request(self.vmmaster_client, session.id, data)
response_data = json.loads(response.data)
self.assertEqual(500, response.status_code)
self.assertEqual(13, response_data.get("status", 0))
self.assertIn(
"Something ugly happened. No real reply formed",
response_data.get("value", {}).get("message", None)
)
@patch(
"vmmaster.webdriver.helpers.transparent",
Mock(return_value=transparent_mock(500, None, "No response"))
)
def test_open_url_request_if_no_response_from_endpoint(self):
with patch(
"core.db.models.Session", Mock()
):
session = Session("origin_1")
session.id = 1
self.app.sessions.get_session = Mock(return_value=session)
data = {
<|code_end|>
, generate the next line using the imports in this file:
import json
import time
from uuid import uuid4
from flask import Flask
from mock import Mock, patch
from multiprocessing.pool import ThreadPool
from nose.twistedtools import reactor
from core.config import setup_config, config
from core.exceptions import SessionException
from tests.helpers import server_is_up, server_is_down, \
new_session_request, get_session_request, delete_session_request, \
vmmaster_label, run_script, BaseTestCase, \
DatabaseMock, custom_wait, request_mock, wait_for, open_url_request, app_context_mock
from vmmaster.app import create_app
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from flask import Flask
from core.sessions import SessionWorker
from vmmaster.server import VMMasterServer
from vmmaster.webdriver.helpers import get_session
and context (functions, classes, or occasionally code) from other files:
# Path: core/config.py
# 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):
#
# Path: core/exceptions.py
# class SessionException(Exception):
# pass
#
# Path: tests/helpers.py
# class TimeoutException(Exception):
# class Response(object):
# class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
# class ServerMock(object):
# class BaseTestCase(unittest.TestCase):
# class DatabaseMock(Mock):
# def call_in_thread_mock(f):
# def wrapper(*args, **kwargs):
# def wait_for(condition, timeout=10):
# def request(host, method, url, headers=None, body=None):
# def request_with_drop(address, desired_caps, method=None):
# def new_session_request(client, desired_caps):
# def open_url_request(client, session, data):
# def delete_session_request(client, session):
# def get_session_request(client, session):
# def run_script(client, session, script):
# def vmmaster_label(client, session, label=None):
# def server_is_up(address, wait=5):
# def server_is_down(address, wait=5):
# def fake_home_dir():
# def get_free_port():
# def body(self):
# def send_reply(self, code, headers, body):
# def do_POST(self):
# def do_GET(self):
# def log_error(self, format, *args):
# def log_message(self, format, *args):
# def log_request(self, code='-', size='-'):
# def __init__(self, host, port):
# def start(self):
# def stop(self):
# def shortDescription(self):
# def set_primary_key(_self):
# def __init__(self, *args, **kwargs):
# def get_active_sessions(self, provider_id=None):
# def get_session(self, session_id):
# def get_endpoint(self, endpoint):
# def get_endpoints(self, *args, **kwargs):
# def get_last_session_step(session_id):
# def register_provider(self, name, url, platforms):
# def custom_wait(self):
# def vmmaster_server_mock(port):
# def request_mock(**kwargs):
# def wait_deferred(d, timeout=5):
. Output only the next line. | "sessionId": session.id, |
Continue the code snippet: <|code_start|>
def ping_vm_false_mock(arg=None, ports=None):
yield False
def transparent_mock(code=200, headers=None, body=None):
if not headers:
headers = {}
return code, headers, body
class BaseTestFlaskApp(BaseTestCase):
def setUp(self):
with patch(
'core.db.Database', DatabaseMock()
), patch(
'core.sessions.SessionWorker', Mock()
), patch(
'vmpool.virtual_machines_pool.VirtualMachinesPool', Mock()
):
self.app = create_app()
self.app.get_matched_platforms = Mock(return_value=('origin_1', 1))
self.desired_caps = {
'desiredCapabilities': {
'platform': 'origin_1'
}
}
<|code_end|>
. Use current file imports:
import json
import time
from uuid import uuid4
from flask import Flask
from mock import Mock, patch
from multiprocessing.pool import ThreadPool
from nose.twistedtools import reactor
from core.config import setup_config, config
from core.exceptions import SessionException
from tests.helpers import server_is_up, server_is_down, \
new_session_request, get_session_request, delete_session_request, \
vmmaster_label, run_script, BaseTestCase, \
DatabaseMock, custom_wait, request_mock, wait_for, open_url_request, app_context_mock
from vmmaster.app import create_app
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from flask import Flask
from core.sessions import SessionWorker
from vmmaster.server import VMMasterServer
from vmmaster.webdriver.helpers import get_session
and context (classes, functions, or code) from other files:
# Path: core/config.py
# 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):
#
# Path: core/exceptions.py
# class SessionException(Exception):
# pass
#
# Path: tests/helpers.py
# class TimeoutException(Exception):
# class Response(object):
# class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
# class ServerMock(object):
# class BaseTestCase(unittest.TestCase):
# class DatabaseMock(Mock):
# def call_in_thread_mock(f):
# def wrapper(*args, **kwargs):
# def wait_for(condition, timeout=10):
# def request(host, method, url, headers=None, body=None):
# def request_with_drop(address, desired_caps, method=None):
# def new_session_request(client, desired_caps):
# def open_url_request(client, session, data):
# def delete_session_request(client, session):
# def get_session_request(client, session):
# def run_script(client, session, script):
# def vmmaster_label(client, session, label=None):
# def server_is_up(address, wait=5):
# def server_is_down(address, wait=5):
# def fake_home_dir():
# def get_free_port():
# def body(self):
# def send_reply(self, code, headers, body):
# def do_POST(self):
# def do_GET(self):
# def log_error(self, format, *args):
# def log_message(self, format, *args):
# def log_request(self, code='-', size='-'):
# def __init__(self, host, port):
# def start(self):
# def stop(self):
# def shortDescription(self):
# def set_primary_key(_self):
# def __init__(self, *args, **kwargs):
# def get_active_sessions(self, provider_id=None):
# def get_session(self, session_id):
# def get_endpoint(self, endpoint):
# def get_endpoints(self, *args, **kwargs):
# def get_last_session_step(session_id):
# def register_provider(self, name, url, platforms):
# def custom_wait(self):
# def vmmaster_server_mock(port):
# def request_mock(**kwargs):
# def wait_deferred(d, timeout=5):
. Output only the next line. | @patch("vmmaster.webdriver.take_screenshot", Mock()) |
Continue the code snippet: <|code_start|># coding: utf-8
def ping_vm_true_mock(arg=None, ports=None):
yield True
def selenium_status_true_mock(arg=None, arg2=None, arg3=None):
yield 200, {}, ""
def ping_vm_false_mock(arg=None, ports=None):
yield False
def transparent_mock(code=200, headers=None, body=None):
if not headers:
headers = {}
return code, headers, body
class BaseTestFlaskApp(BaseTestCase):
def setUp(self):
with patch(
'core.db.Database', DatabaseMock()
), patch(
'core.sessions.SessionWorker', Mock()
), patch(
<|code_end|>
. Use current file imports:
import json
import time
from uuid import uuid4
from flask import Flask
from mock import Mock, patch
from multiprocessing.pool import ThreadPool
from nose.twistedtools import reactor
from core.config import setup_config, config
from core.exceptions import SessionException
from tests.helpers import server_is_up, server_is_down, \
new_session_request, get_session_request, delete_session_request, \
vmmaster_label, run_script, BaseTestCase, \
DatabaseMock, custom_wait, request_mock, wait_for, open_url_request, app_context_mock
from vmmaster.app import create_app
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from flask import Flask
from core.sessions import SessionWorker
from vmmaster.server import VMMasterServer
from vmmaster.webdriver.helpers import get_session
and context (classes, functions, or code) from other files:
# Path: core/config.py
# 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):
#
# Path: core/exceptions.py
# class SessionException(Exception):
# pass
#
# Path: tests/helpers.py
# class TimeoutException(Exception):
# class Response(object):
# class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
# class ServerMock(object):
# class BaseTestCase(unittest.TestCase):
# class DatabaseMock(Mock):
# def call_in_thread_mock(f):
# def wrapper(*args, **kwargs):
# def wait_for(condition, timeout=10):
# def request(host, method, url, headers=None, body=None):
# def request_with_drop(address, desired_caps, method=None):
# def new_session_request(client, desired_caps):
# def open_url_request(client, session, data):
# def delete_session_request(client, session):
# def get_session_request(client, session):
# def run_script(client, session, script):
# def vmmaster_label(client, session, label=None):
# def server_is_up(address, wait=5):
# def server_is_down(address, wait=5):
# def fake_home_dir():
# def get_free_port():
# def body(self):
# def send_reply(self, code, headers, body):
# def do_POST(self):
# def do_GET(self):
# def log_error(self, format, *args):
# def log_message(self, format, *args):
# def log_request(self, code='-', size='-'):
# def __init__(self, host, port):
# def start(self):
# def stop(self):
# def shortDescription(self):
# def set_primary_key(_self):
# def __init__(self, *args, **kwargs):
# def get_active_sessions(self, provider_id=None):
# def get_session(self, session_id):
# def get_endpoint(self, endpoint):
# def get_endpoints(self, *args, **kwargs):
# def get_last_session_step(session_id):
# def register_provider(self, name, url, platforms):
# def custom_wait(self):
# def vmmaster_server_mock(port):
# def request_mock(**kwargs):
# def wait_deferred(d, timeout=5):
. Output only the next line. | 'vmpool.virtual_machines_pool.VirtualMachinesPool', Mock() |
Given snippet: <|code_start|>)
@patch.multiple(
"core.db.models.Session",
endpoint_id=Mock(return_value=1),
endpoint=Mock(
vnc_port=5900,
agent_port=9000,
selenium_port=4455,
_get_nova_client=Mock(return_value=Mock()),
_wait_for_activated_service=custom_wait,
ping_endpoint_before_start_session=Mock(return_value=True),
is_broken=Mock(return_value=False)
)
)
class TestServer(BaseTestFlaskApp):
def setUp(self):
setup_config('data/config_openstack.py')
super(TestServer, self).setUp()
self.desired_caps = {
'desiredCapabilities': {
'platform': 'origin_1'
}
}
self.vmmaster_client = self.app.test_client()
self.ctx = self.app.app_context()
self.ctx.push()
def tearDown(self):
self.app.sessions.kill_all()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
import time
from uuid import uuid4
from flask import Flask
from mock import Mock, patch
from multiprocessing.pool import ThreadPool
from nose.twistedtools import reactor
from core.config import setup_config, config
from core.exceptions import SessionException
from tests.helpers import server_is_up, server_is_down, \
new_session_request, get_session_request, delete_session_request, \
vmmaster_label, run_script, BaseTestCase, \
DatabaseMock, custom_wait, request_mock, wait_for, open_url_request, app_context_mock
from vmmaster.app import create_app
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from flask import Flask
from core.sessions import SessionWorker
from vmmaster.server import VMMasterServer
from vmmaster.webdriver.helpers import get_session
and context:
# Path: core/config.py
# 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):
#
# Path: core/exceptions.py
# class SessionException(Exception):
# pass
#
# Path: tests/helpers.py
# class TimeoutException(Exception):
# class Response(object):
# class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
# class ServerMock(object):
# class BaseTestCase(unittest.TestCase):
# class DatabaseMock(Mock):
# def call_in_thread_mock(f):
# def wrapper(*args, **kwargs):
# def wait_for(condition, timeout=10):
# def request(host, method, url, headers=None, body=None):
# def request_with_drop(address, desired_caps, method=None):
# def new_session_request(client, desired_caps):
# def open_url_request(client, session, data):
# def delete_session_request(client, session):
# def get_session_request(client, session):
# def run_script(client, session, script):
# def vmmaster_label(client, session, label=None):
# def server_is_up(address, wait=5):
# def server_is_down(address, wait=5):
# def fake_home_dir():
# def get_free_port():
# def body(self):
# def send_reply(self, code, headers, body):
# def do_POST(self):
# def do_GET(self):
# def log_error(self, format, *args):
# def log_message(self, format, *args):
# def log_request(self, code='-', size='-'):
# def __init__(self, host, port):
# def start(self):
# def stop(self):
# def shortDescription(self):
# def set_primary_key(_self):
# def __init__(self, *args, **kwargs):
# def get_active_sessions(self, provider_id=None):
# def get_session(self, session_id):
# def get_endpoint(self, endpoint):
# def get_endpoints(self, *args, **kwargs):
# def get_last_session_step(session_id):
# def register_provider(self, name, url, platforms):
# def custom_wait(self):
# def vmmaster_server_mock(port):
# def request_mock(**kwargs):
# def wait_deferred(d, timeout=5):
which might include code, classes, or functions. Output only the next line. | self.app.cleanup() |
Using the snippet: <|code_start|> def test_error(self):
raise Exception('some client exception')
class TestLongRequest(DesktopTestCase):
def test_1_long_micro_app_request(self):
self.driver.get(self.micro_app_address)
def test_2_long_micro_app_request(self):
self.driver.get("{}/long".format(self.micro_app_address))
def test_3_long_micro_app_request(self):
self.driver.get(self.micro_app_address)
class TestEnvironmentVariables(DesktopTestCase):
desired_capabilities = {"environmentVars": {
"TEST_ENV": "TEST_VALUE",
}}
def test_environment_variables(self):
output = self.vmmaster.run_script("echo $TEST_ENV").get("output")
self.assertIn(u"TEST_VALUE", output, msg="Not set environment variables in endpoint")
class TestRunScriptOnSessionCreation(DesktopTestCase):
@classmethod
def setUpClass(cls):
cls.desired_capabilities["runScript"] = \
{"script": 'echo "hello" > ~/hello_file'}
<|code_end|>
, determine the next line of code. You have imports:
import os
from tests.functional.tests.helpers import DesktopTestCase, AndroidTestCase
and context (class names, function names, or code) available:
# Path: tests/functional/tests/helpers.py
# class DesktopTestCase(BaseTestCase):
# def __new__(cls, *args, **kwargs):
# if not cls.desired_capabilities or getattr(Config, 'browser', '') == 'chrome':
# cls.desired_capabilities = DesiredCapabilities.CHROME.copy()
#
# if getattr(Config, 'browser', '') == 'firefox':
# cls.desired_capabilities.update(DesiredCapabilities.FIREFOX.copy())
#
# if getattr(Config, 'browser', '') == 'chrome':
# cls.desired_capabilities["chromeOptions"] = {
# "args": [
# "--use-gl",
# "--ignore-gpu-blacklist"
# ],
# "extensions": []
# }
#
# if hasattr(Config, 'version'):
# cls.desired_capabilities["version"] = getattr(Config, 'version', 'ANY')
#
# cls.desired_capabilities["takeScreenshot"] = getattr(Config, "take_screenshot", True)
# cls.desired_capabilities["takeScreencast"] = getattr(Config, "take_screencast", False)
#
# return super(DesktopTestCase, cls).__new__(cls)
#
# class AndroidTestCase(BaseTestCase):
# def __new__(cls, *args, **kwargs):
# if not cls.desired_capabilities:
# cls.desired_capabilities = DesiredCapabilities.ANDROID.copy()
#
# return super(AndroidTestCase, cls).__new__(cls)
. Output only the next line. | super(TestRunScriptOnSessionCreation, cls).setUpClass() |
Predict the next line after this snippet: <|code_start|>
def test_open_mobile_application(self):
raise Exception('application was opened')
class TestPositiveCase(DesktopTestCase):
def test_micro_app(self):
self.driver.get(self.micro_app_address)
go_button = self.driver.find_element_by_xpath("//input[2]")
go_button.click()
def test_error(self):
raise Exception('some client exception')
class TestLongRequest(DesktopTestCase):
def test_1_long_micro_app_request(self):
self.driver.get(self.micro_app_address)
def test_2_long_micro_app_request(self):
self.driver.get("{}/long".format(self.micro_app_address))
def test_3_long_micro_app_request(self):
self.driver.get(self.micro_app_address)
class TestEnvironmentVariables(DesktopTestCase):
desired_capabilities = {"environmentVars": {
"TEST_ENV": "TEST_VALUE",
<|code_end|>
using the current file's imports:
import os
from tests.functional.tests.helpers import DesktopTestCase, AndroidTestCase
and any relevant context from other files:
# Path: tests/functional/tests/helpers.py
# class DesktopTestCase(BaseTestCase):
# def __new__(cls, *args, **kwargs):
# if not cls.desired_capabilities or getattr(Config, 'browser', '') == 'chrome':
# cls.desired_capabilities = DesiredCapabilities.CHROME.copy()
#
# if getattr(Config, 'browser', '') == 'firefox':
# cls.desired_capabilities.update(DesiredCapabilities.FIREFOX.copy())
#
# if getattr(Config, 'browser', '') == 'chrome':
# cls.desired_capabilities["chromeOptions"] = {
# "args": [
# "--use-gl",
# "--ignore-gpu-blacklist"
# ],
# "extensions": []
# }
#
# if hasattr(Config, 'version'):
# cls.desired_capabilities["version"] = getattr(Config, 'version', 'ANY')
#
# cls.desired_capabilities["takeScreenshot"] = getattr(Config, "take_screenshot", True)
# cls.desired_capabilities["takeScreencast"] = getattr(Config, "take_screencast", False)
#
# return super(DesktopTestCase, cls).__new__(cls)
#
# class AndroidTestCase(BaseTestCase):
# def __new__(cls, *args, **kwargs):
# if not cls.desired_capabilities:
# cls.desired_capabilities = DesiredCapabilities.ANDROID.copy()
#
# return super(AndroidTestCase, cls).__new__(cls)
. Output only the next line. | }} |
Based on the snippet: <|code_start|> endpoint = Endpoint(Mock(), '', provider)
endpoint.ip = 'localhost'
self.session.endpoint = endpoint
def tearDown(self):
self.session._close()
self.ctx.pop()
self.vmmaster.app.sessions.kill_all()
self.vmmaster.app.cleanup()
self.vmmaster.stop_services()
self.assertTrue(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)
<|code_end|>
, predict the immediate next line with the help of imports:
import requests
from mock import Mock, patch
from core.config import setup_config, config
from tests.helpers import (vmmaster_server_mock, server_is_up, server_is_down,
BaseTestCase, get_free_port, ServerMock)
from core.db.models import Session, Provider, Endpoint
and context (classes, functions, sometimes code) from other files:
# Path: core/config.py
# 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):
#
# Path: tests/helpers.py
# def vmmaster_server_mock(port):
# mocked_image = Mock(
# id=1, status='active',
# get=Mock(return_value='snapshot'),
# min_disk=20,
# min_ram=2,
# instance_type_flavorid=1,
# )
# type(mocked_image).name = PropertyMock(
# return_value='test_origin_1')
#
# with patch(
# 'core.db.Database', DatabaseMock()
# ), patch(
# 'core.utils.init.home_dir', Mock(return_value=fake_home_dir())
# ), patch(
# 'core.logger.setup_logging', Mock(return_value=Mock())
# ), patch(
# 'core.sessions.SessionWorker', Mock()
# ), patch.multiple(
# 'vmpool.platforms.OpenstackPlatforms',
# images=Mock(return_value=[mocked_image]),
# flavor_params=Mock(return_value={'vcpus': 1, 'ram': 2}),
# limits=Mock(return_value={
# 'maxTotalCores': 10, 'maxTotalInstances': 10,
# 'maxTotalRAMSize': 100, 'totalCoresUsed': 0,
# 'totalInstancesUsed': 0, 'totalRAMUsed': 0}),
# ), patch.multiple(
# 'core.utils.openstack_utils',
# nova_client=Mock(return_value=Mock())
# ), patch.multiple(
# 'core.db.models.OpenstackClone',
# _wait_for_activated_service=custom_wait,
# ping_vm=Mock(return_value=True)
# ):
# from vmmaster.server import VMMasterServer
# return VMMasterServer(reactor, port)
#
# def server_is_up(address, wait=5):
# time_start = time.time()
# while time.time() - time_start < wait:
# time.sleep(0.1)
# if get_socket(address[0], address[1]):
# return True
#
# return False
#
# def server_is_down(address, wait=5):
# time_start = time.time()
# while time.time() - time_start < wait:
# time.sleep(0.1)
# if not get_socket(address[0], address[1]):
# return True
#
# return False
#
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# 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 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()
. Output only the next line. | ): |
Using the snippet: <|code_start|> 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_was_closed(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(
"Session {}(Success) already closed earlier".format(self.session.id),
response.content
<|code_end|>
, determine the next line of code. You have imports:
import requests
from mock import Mock, patch
from core.config import setup_config, config
from tests.helpers import (vmmaster_server_mock, server_is_up, server_is_down,
BaseTestCase, get_free_port, ServerMock)
from core.db.models import Session, Provider, Endpoint
and context (class names, function names, or code) available:
# Path: core/config.py
# 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):
#
# Path: tests/helpers.py
# def vmmaster_server_mock(port):
# mocked_image = Mock(
# id=1, status='active',
# get=Mock(return_value='snapshot'),
# min_disk=20,
# min_ram=2,
# instance_type_flavorid=1,
# )
# type(mocked_image).name = PropertyMock(
# return_value='test_origin_1')
#
# with patch(
# 'core.db.Database', DatabaseMock()
# ), patch(
# 'core.utils.init.home_dir', Mock(return_value=fake_home_dir())
# ), patch(
# 'core.logger.setup_logging', Mock(return_value=Mock())
# ), patch(
# 'core.sessions.SessionWorker', Mock()
# ), patch.multiple(
# 'vmpool.platforms.OpenstackPlatforms',
# images=Mock(return_value=[mocked_image]),
# flavor_params=Mock(return_value={'vcpus': 1, 'ram': 2}),
# limits=Mock(return_value={
# 'maxTotalCores': 10, 'maxTotalInstances': 10,
# 'maxTotalRAMSize': 100, 'totalCoresUsed': 0,
# 'totalInstancesUsed': 0, 'totalRAMUsed': 0}),
# ), patch.multiple(
# 'core.utils.openstack_utils',
# nova_client=Mock(return_value=Mock())
# ), patch.multiple(
# 'core.db.models.OpenstackClone',
# _wait_for_activated_service=custom_wait,
# ping_vm=Mock(return_value=True)
# ):
# from vmmaster.server import VMMasterServer
# return VMMasterServer(reactor, port)
#
# def server_is_up(address, wait=5):
# time_start = time.time()
# while time.time() - time_start < wait:
# time.sleep(0.1)
# if get_socket(address[0], address[1]):
# return True
#
# return False
#
# def server_is_down(address, wait=5):
# time_start = time.time()
# while time.time() - time_start < wait:
# time.sleep(0.1)
# if not get_socket(address[0], address[1]):
# return True
#
# return False
#
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# 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 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()
. Output only the next line. | ) |
Given the code snippet: <|code_start|># coding: utf-8
class TestHttpProxy(BaseTestCase):
def setUp(self):
setup_config('data/config_openstack.py')
<|code_end|>
, generate the next line using the imports in this file:
import requests
from mock import Mock, patch
from core.config import setup_config, config
from tests.helpers import (vmmaster_server_mock, server_is_up, server_is_down,
BaseTestCase, get_free_port, ServerMock)
from core.db.models import Session, Provider, Endpoint
and context (functions, classes, or occasionally code) from other files:
# Path: core/config.py
# 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):
#
# Path: tests/helpers.py
# def vmmaster_server_mock(port):
# mocked_image = Mock(
# id=1, status='active',
# get=Mock(return_value='snapshot'),
# min_disk=20,
# min_ram=2,
# instance_type_flavorid=1,
# )
# type(mocked_image).name = PropertyMock(
# return_value='test_origin_1')
#
# with patch(
# 'core.db.Database', DatabaseMock()
# ), patch(
# 'core.utils.init.home_dir', Mock(return_value=fake_home_dir())
# ), patch(
# 'core.logger.setup_logging', Mock(return_value=Mock())
# ), patch(
# 'core.sessions.SessionWorker', Mock()
# ), patch.multiple(
# 'vmpool.platforms.OpenstackPlatforms',
# images=Mock(return_value=[mocked_image]),
# flavor_params=Mock(return_value={'vcpus': 1, 'ram': 2}),
# limits=Mock(return_value={
# 'maxTotalCores': 10, 'maxTotalInstances': 10,
# 'maxTotalRAMSize': 100, 'totalCoresUsed': 0,
# 'totalInstancesUsed': 0, 'totalRAMUsed': 0}),
# ), patch.multiple(
# 'core.utils.openstack_utils',
# nova_client=Mock(return_value=Mock())
# ), patch.multiple(
# 'core.db.models.OpenstackClone',
# _wait_for_activated_service=custom_wait,
# ping_vm=Mock(return_value=True)
# ):
# from vmmaster.server import VMMasterServer
# return VMMasterServer(reactor, port)
#
# def server_is_up(address, wait=5):
# time_start = time.time()
# while time.time() - time_start < wait:
# time.sleep(0.1)
# if get_socket(address[0], address[1]):
# return True
#
# return False
#
# def server_is_down(address, wait=5):
# time_start = time.time()
# while time.time() - time_start < wait:
# time.sleep(0.1)
# if not get_socket(address[0], address[1]):
# return True
#
# return False
#
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# 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 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()
. Output only the next line. | self.host = "localhost" |
Next line prediction: <|code_start|> 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_was_closed(self):
self.session.succeed()
with patch(
<|code_end|>
. Use current file imports:
(import requests
from mock import Mock, patch
from core.config import setup_config, config
from tests.helpers import (vmmaster_server_mock, server_is_up, server_is_down,
BaseTestCase, get_free_port, ServerMock)
from core.db.models import Session, Provider, Endpoint)
and context including class names, function names, or small code snippets from other files:
# Path: core/config.py
# 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):
#
# Path: tests/helpers.py
# def vmmaster_server_mock(port):
# mocked_image = Mock(
# id=1, status='active',
# get=Mock(return_value='snapshot'),
# min_disk=20,
# min_ram=2,
# instance_type_flavorid=1,
# )
# type(mocked_image).name = PropertyMock(
# return_value='test_origin_1')
#
# with patch(
# 'core.db.Database', DatabaseMock()
# ), patch(
# 'core.utils.init.home_dir', Mock(return_value=fake_home_dir())
# ), patch(
# 'core.logger.setup_logging', Mock(return_value=Mock())
# ), patch(
# 'core.sessions.SessionWorker', Mock()
# ), patch.multiple(
# 'vmpool.platforms.OpenstackPlatforms',
# images=Mock(return_value=[mocked_image]),
# flavor_params=Mock(return_value={'vcpus': 1, 'ram': 2}),
# limits=Mock(return_value={
# 'maxTotalCores': 10, 'maxTotalInstances': 10,
# 'maxTotalRAMSize': 100, 'totalCoresUsed': 0,
# 'totalInstancesUsed': 0, 'totalRAMUsed': 0}),
# ), patch.multiple(
# 'core.utils.openstack_utils',
# nova_client=Mock(return_value=Mock())
# ), patch.multiple(
# 'core.db.models.OpenstackClone',
# _wait_for_activated_service=custom_wait,
# ping_vm=Mock(return_value=True)
# ):
# from vmmaster.server import VMMasterServer
# return VMMasterServer(reactor, port)
#
# def server_is_up(address, wait=5):
# time_start = time.time()
# while time.time() - time_start < wait:
# time.sleep(0.1)
# if get_socket(address[0], address[1]):
# return True
#
# return False
#
# def server_is_down(address, wait=5):
# time_start = time.time()
# while time.time() - time_start < wait:
# time.sleep(0.1)
# if not get_socket(address[0], address[1]):
# return True
#
# return False
#
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# 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 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()
. Output only the next line. | 'flask.current_app.database.get_session', |
Next line prediction: <|code_start|># coding: utf-8
class TestHttpProxy(BaseTestCase):
def setUp(self):
setup_config('data/config_openstack.py')
self.host = "localhost"
self.port = config.PORT
self.address = (self.host, self.port)
self.vmmaster = vmmaster_server_mock(self.port)
self.assertTrue(server_is_up(self.address))
self.free_port = get_free_port()
self.ctx = self.vmmaster.app.app_context()
self.ctx.push()
self.session = Session('some_platform')
provider = Provider(name='noname', url='nourl')
endpoint = Endpoint(Mock(), '', provider)
endpoint.ip = 'localhost'
self.session.endpoint = endpoint
def tearDown(self):
self.session._close()
self.ctx.pop()
<|code_end|>
. Use current file imports:
(import requests
from mock import Mock, patch
from core.config import setup_config, config
from tests.helpers import (vmmaster_server_mock, server_is_up, server_is_down,
BaseTestCase, get_free_port, ServerMock)
from core.db.models import Session, Provider, Endpoint)
and context including class names, function names, or small code snippets from other files:
# Path: core/config.py
# 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):
#
# Path: tests/helpers.py
# def vmmaster_server_mock(port):
# mocked_image = Mock(
# id=1, status='active',
# get=Mock(return_value='snapshot'),
# min_disk=20,
# min_ram=2,
# instance_type_flavorid=1,
# )
# type(mocked_image).name = PropertyMock(
# return_value='test_origin_1')
#
# with patch(
# 'core.db.Database', DatabaseMock()
# ), patch(
# 'core.utils.init.home_dir', Mock(return_value=fake_home_dir())
# ), patch(
# 'core.logger.setup_logging', Mock(return_value=Mock())
# ), patch(
# 'core.sessions.SessionWorker', Mock()
# ), patch.multiple(
# 'vmpool.platforms.OpenstackPlatforms',
# images=Mock(return_value=[mocked_image]),
# flavor_params=Mock(return_value={'vcpus': 1, 'ram': 2}),
# limits=Mock(return_value={
# 'maxTotalCores': 10, 'maxTotalInstances': 10,
# 'maxTotalRAMSize': 100, 'totalCoresUsed': 0,
# 'totalInstancesUsed': 0, 'totalRAMUsed': 0}),
# ), patch.multiple(
# 'core.utils.openstack_utils',
# nova_client=Mock(return_value=Mock())
# ), patch.multiple(
# 'core.db.models.OpenstackClone',
# _wait_for_activated_service=custom_wait,
# ping_vm=Mock(return_value=True)
# ):
# from vmmaster.server import VMMasterServer
# return VMMasterServer(reactor, port)
#
# def server_is_up(address, wait=5):
# time_start = time.time()
# while time.time() - time_start < wait:
# time.sleep(0.1)
# if get_socket(address[0], address[1]):
# return True
#
# return False
#
# def server_is_down(address, wait=5):
# time_start = time.time()
# while time.time() - time_start < wait:
# time.sleep(0.1)
# if not get_socket(address[0], address[1]):
# return True
#
# return False
#
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# 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 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()
. Output only the next line. | self.vmmaster.app.sessions.kill_all() |
Here is a snippet: <|code_start|> 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_was_closed(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(
"Session {}(Success) already closed earlier".format(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)
<|code_end|>
. Write the next line using the current file imports:
import requests
from mock import Mock, patch
from core.config import setup_config, config
from tests.helpers import (vmmaster_server_mock, server_is_up, server_is_down,
BaseTestCase, get_free_port, ServerMock)
from core.db.models import Session, Provider, Endpoint
and context from other files:
# Path: core/config.py
# 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):
#
# Path: tests/helpers.py
# def vmmaster_server_mock(port):
# mocked_image = Mock(
# id=1, status='active',
# get=Mock(return_value='snapshot'),
# min_disk=20,
# min_ram=2,
# instance_type_flavorid=1,
# )
# type(mocked_image).name = PropertyMock(
# return_value='test_origin_1')
#
# with patch(
# 'core.db.Database', DatabaseMock()
# ), patch(
# 'core.utils.init.home_dir', Mock(return_value=fake_home_dir())
# ), patch(
# 'core.logger.setup_logging', Mock(return_value=Mock())
# ), patch(
# 'core.sessions.SessionWorker', Mock()
# ), patch.multiple(
# 'vmpool.platforms.OpenstackPlatforms',
# images=Mock(return_value=[mocked_image]),
# flavor_params=Mock(return_value={'vcpus': 1, 'ram': 2}),
# limits=Mock(return_value={
# 'maxTotalCores': 10, 'maxTotalInstances': 10,
# 'maxTotalRAMSize': 100, 'totalCoresUsed': 0,
# 'totalInstancesUsed': 0, 'totalRAMUsed': 0}),
# ), patch.multiple(
# 'core.utils.openstack_utils',
# nova_client=Mock(return_value=Mock())
# ), patch.multiple(
# 'core.db.models.OpenstackClone',
# _wait_for_activated_service=custom_wait,
# ping_vm=Mock(return_value=True)
# ):
# from vmmaster.server import VMMasterServer
# return VMMasterServer(reactor, port)
#
# def server_is_up(address, wait=5):
# time_start = time.time()
# while time.time() - time_start < wait:
# time.sleep(0.1)
# if get_socket(address[0], address[1]):
# return True
#
# return False
#
# def server_is_down(address, wait=5):
# time_start = time.time()
# while time.time() - time_start < wait:
# time.sleep(0.1)
# if not get_socket(address[0], address[1]):
# return True
#
# return False
#
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# 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 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()
, which may include functions, classes, or code. Output only the next line. | ) |
Continue the code snippet: <|code_start|> (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_was_closed(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(
"Session {}(Success) already closed earlier".format(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 "
<|code_end|>
. Use current file imports:
import requests
from mock import Mock, patch
from core.config import setup_config, config
from tests.helpers import (vmmaster_server_mock, server_is_up, server_is_down,
BaseTestCase, get_free_port, ServerMock)
from core.db.models import Session, Provider, Endpoint
and context (classes, functions, or code) from other files:
# Path: core/config.py
# 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):
#
# Path: tests/helpers.py
# def vmmaster_server_mock(port):
# mocked_image = Mock(
# id=1, status='active',
# get=Mock(return_value='snapshot'),
# min_disk=20,
# min_ram=2,
# instance_type_flavorid=1,
# )
# type(mocked_image).name = PropertyMock(
# return_value='test_origin_1')
#
# with patch(
# 'core.db.Database', DatabaseMock()
# ), patch(
# 'core.utils.init.home_dir', Mock(return_value=fake_home_dir())
# ), patch(
# 'core.logger.setup_logging', Mock(return_value=Mock())
# ), patch(
# 'core.sessions.SessionWorker', Mock()
# ), patch.multiple(
# 'vmpool.platforms.OpenstackPlatforms',
# images=Mock(return_value=[mocked_image]),
# flavor_params=Mock(return_value={'vcpus': 1, 'ram': 2}),
# limits=Mock(return_value={
# 'maxTotalCores': 10, 'maxTotalInstances': 10,
# 'maxTotalRAMSize': 100, 'totalCoresUsed': 0,
# 'totalInstancesUsed': 0, 'totalRAMUsed': 0}),
# ), patch.multiple(
# 'core.utils.openstack_utils',
# nova_client=Mock(return_value=Mock())
# ), patch.multiple(
# 'core.db.models.OpenstackClone',
# _wait_for_activated_service=custom_wait,
# ping_vm=Mock(return_value=True)
# ):
# from vmmaster.server import VMMasterServer
# return VMMasterServer(reactor, port)
#
# def server_is_up(address, wait=5):
# time_start = time.time()
# while time.time() - time_start < wait:
# time.sleep(0.1)
# if get_socket(address[0], address[1]):
# return True
#
# return False
#
# def server_is_down(address, wait=5):
# time_start = time.time()
# while time.time() - time_start < wait:
# time.sleep(0.1)
# if not get_socket(address[0], address[1]):
# return True
#
# return False
#
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# 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 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()
. Output only the next line. | "/proxy/session/<session_id>/port/<port_number>/<destination>", |
Predict the next line after this snippet: <|code_start|> endpoint = Endpoint(Mock(), '', provider)
endpoint.ip = 'localhost'
self.session.endpoint = endpoint
def tearDown(self):
self.session._close()
self.ctx.pop()
self.vmmaster.app.sessions.kill_all()
self.vmmaster.app.cleanup()
self.vmmaster.stop_services()
self.assertTrue(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)
<|code_end|>
using the current file's imports:
import requests
from mock import Mock, patch
from core.config import setup_config, config
from tests.helpers import (vmmaster_server_mock, server_is_up, server_is_down,
BaseTestCase, get_free_port, ServerMock)
from core.db.models import Session, Provider, Endpoint
and any relevant context from other files:
# Path: core/config.py
# 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):
#
# Path: tests/helpers.py
# def vmmaster_server_mock(port):
# mocked_image = Mock(
# id=1, status='active',
# get=Mock(return_value='snapshot'),
# min_disk=20,
# min_ram=2,
# instance_type_flavorid=1,
# )
# type(mocked_image).name = PropertyMock(
# return_value='test_origin_1')
#
# with patch(
# 'core.db.Database', DatabaseMock()
# ), patch(
# 'core.utils.init.home_dir', Mock(return_value=fake_home_dir())
# ), patch(
# 'core.logger.setup_logging', Mock(return_value=Mock())
# ), patch(
# 'core.sessions.SessionWorker', Mock()
# ), patch.multiple(
# 'vmpool.platforms.OpenstackPlatforms',
# images=Mock(return_value=[mocked_image]),
# flavor_params=Mock(return_value={'vcpus': 1, 'ram': 2}),
# limits=Mock(return_value={
# 'maxTotalCores': 10, 'maxTotalInstances': 10,
# 'maxTotalRAMSize': 100, 'totalCoresUsed': 0,
# 'totalInstancesUsed': 0, 'totalRAMUsed': 0}),
# ), patch.multiple(
# 'core.utils.openstack_utils',
# nova_client=Mock(return_value=Mock())
# ), patch.multiple(
# 'core.db.models.OpenstackClone',
# _wait_for_activated_service=custom_wait,
# ping_vm=Mock(return_value=True)
# ):
# from vmmaster.server import VMMasterServer
# return VMMasterServer(reactor, port)
#
# def server_is_up(address, wait=5):
# time_start = time.time()
# while time.time() - time_start < wait:
# time.sleep(0.1)
# if get_socket(address[0], address[1]):
# return True
#
# return False
#
# def server_is_down(address, wait=5):
# time_start = time.time()
# while time.time() - time_start < wait:
# time.sleep(0.1)
# if not get_socket(address[0], address[1]):
# return True
#
# return False
#
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# 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 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()
. Output only the next line. | ): |
Given the following code snippet before the placeholder: <|code_start|>from __future__ import with_statement
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
# fileConfig(config.config_file_name)
log = logging.getLogger(__name__)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = Base.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
<|code_end|>
, predict the next line using imports from the current file:
import logging
from alembic import context
from sqlalchemy import engine_from_config, pool
from core.db.models import Base
and context including class names, function names, and sometimes code from other files:
# Path: core/db/models.py
# class FeaturesMixin(object):
# class SessionLogSubStep(Base, FeaturesMixin):
# class SessionLogStep(Base, FeaturesMixin):
# class Session(Base, FeaturesMixin):
# class Endpoint(Base, FeaturesMixin):
# class OpenstackClone(Endpoint):
# class DockerClone(Endpoint):
# class User(Base, FeaturesMixin):
# class UserGroup(Base):
# class Platform(Base):
# class Provider(Base, FeaturesMixin):
# def add(self):
# def save(self):
# def refresh(self):
# def delete(self):
# def __init__(self, control_line, body=None, parent_id=None):
# def __init__(self, control_line, body=None, session_id=None, created=None):
# def add_sub_step_to_step(self, control_line, body):
# def __init__(self, platform, name=None, dc=None, provider_id=None):
# def __str__(self):
# def inactivity(self):
# def duration(self):
# def is_waiting(self):
# def is_running(self):
# def is_done(self):
# def is_succeed(self):
# def is_preparing(self):
# def current_log_step(self):
# def add_session_step(self, control_line, body=None, created=None):
# def info(self):
# def start_timer(self):
# def stop_timer(self):
# def stop_vnc_proxy(self):
# def _close(self, reason=None):
# def succeed(self):
# def failed(self, tb=None, reason=None):
# def set_status(self, status):
# def set_endpoint(self, endpoint):
# def set_screencast_started(self, value):
# def run(self):
# def timeout(self):
# def set_user(self, username):
# def _add_sub_step(self, control_line, body, context):
# def add_sub_step(self, control_line, body=None):
# def make_request(self, port, request,
# timeout=getattr(config, "REQUEST_TIMEOUT", constants.REQUEST_TIMEOUT)):
# def __str__(self):
# def __init__(self, origin, prefix, provider):
# def delete(self, try_to_rebuild=False):
# def create(self):
# def rebuild(self):
# def bind_ports(self):
# def __get_prop_from_config(self, prop, default_prop):
# def artifacts(self):
# def defined_ports_from_config(self):
# def vnc_port(self):
# def selenium_port(self):
# def agent_port(self):
# def agent_ws_url(self):
# def service_mode_on(self):
# def service_mode_off(self):
# def send_to_service(self):
# def set_mode(self, mode):
# def set_ready(self, value):
# def set_in_use(self, value):
# def set_env_vars(self, env_vars):
# def in_pool(self):
# def in_service(self):
# def wait_for_service(self):
# def info(self):
# def is_preloaded(self):
# def is_ondemand(self):
# def ping_vm(self):
# def clone_refresher(func):
# def wrapper(self, *args, **kwargs):
# def __init__(self, origin, prefix, pool):
# def _get_nova_client():
# def network_id(self):
# def refresh_endpoint(self):
# def set_userdata(file_path):
# def create(self):
# def _parse_ip_from_networks(self):
# def get_ip(self):
# def _wait_for_activated_service(self):
# def image(self):
# def flavor(self):
# def is_created(server):
# def is_spawning(server):
# def is_broken(server):
# def get_vm(self, server_name):
# def delete(self, try_to_rebuild=False):
# def rebuild(self):
# def __init__(self, origin, prefix, pool):
# def _get_client():
# def __str__(self):
# def refresh_endpoint(self):
# def get_container(self):
# def connect_network(self):
# def disconnect_network(self):
# def status(self):
# def is_spawning(self):
# def is_created(self):
# def is_broken(self):
# def image(self):
# def __make_binded_ports(self):
# def create(self):
# def selenium_is_ready(self):
# def _wait_for_activated_service(self):
# def delete(self, try_to_rebuild=False):
# def rebuild(self):
# def generate_token():
# def regenerate_token(self):
# def info(self):
# def __init__(self, name):
# def __init__(self, name, url, config=None, active=True, max_limit=0):
# def info(self):
. Output only the next line. | def run_migrations_offline(): |
Given snippet: <|code_start|>
def run_script_mock(script, host):
yield 200, {}, '{"output": "test text"}'
def failed_run_script_mock(script, host):
yield 500, {}, ''
class TestArtifactCollector(BaseTestCase):
@classmethod
def setUpClass(cls):
setup_config('data/config_openstack.py')
cls.app = Flask(__name__)
cls.app.database = DatabaseMock()
cls.app.sessions = Mock()
cls.session_id = 1
cls.artifact_dir = os.sep.join([config.SCREENSHOTS_DIR, str(cls.session_id)])
if not os.path.exists(cls.artifact_dir):
os.mkdir(cls.artifact_dir)
def setUp(self):
self.ctx = self.app.test_request_context()
self.ctx.push()
def tearDown(self):
self.ctx.pop()
@patch('vmpool.artifact_collector.run_script', run_script_mock)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
from flask import Flask
from mock import patch, Mock
from tests.helpers import BaseTestCase, DatabaseMock, wait_for
from core.config import config, setup_config
from vmpool.artifact_collector import ArtifactCollector
from core.db.models import Session, Endpoint, Provider
from vmpool.artifact_collector import ArtifactCollector
from core.db.models import Session, Endpoint, Provider
from vmpool.artifact_collector import ArtifactCollector
from core.db.models import Session, Endpoint, Provider
from vmpool.artifact_collector import ArtifactCollector, Task
from multiprocessing.pool import AsyncResult
and context:
# Path: tests/helpers.py
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# 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)
#
# def wait_for(condition, timeout=10):
# start = time.time()
# while not condition() and time.time() - start < timeout:
# time.sleep(0.1)
#
# return condition()
#
# Path: core/config.py
# 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):
which might include code, classes, or functions. Output only the next line. | def test_add_tasks(self): |
Based on the snippet: <|code_start|># coding: utf-8
def run_script_mock(script, host):
yield 200, {}, '{"output": "test text"}'
def failed_run_script_mock(script, host):
yield 500, {}, ''
class TestArtifactCollector(BaseTestCase):
@classmethod
<|code_end|>
, predict the immediate next line with the help of imports:
import os
from flask import Flask
from mock import patch, Mock
from tests.helpers import BaseTestCase, DatabaseMock, wait_for
from core.config import config, setup_config
from vmpool.artifact_collector import ArtifactCollector
from core.db.models import Session, Endpoint, Provider
from vmpool.artifact_collector import ArtifactCollector
from core.db.models import Session, Endpoint, Provider
from vmpool.artifact_collector import ArtifactCollector
from core.db.models import Session, Endpoint, Provider
from vmpool.artifact_collector import ArtifactCollector, Task
from multiprocessing.pool import AsyncResult
and context (classes, functions, sometimes code) from other files:
# Path: tests/helpers.py
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# 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)
#
# def wait_for(condition, timeout=10):
# start = time.time()
# while not condition() and time.time() - start < timeout:
# time.sleep(0.1)
#
# return condition()
#
# Path: core/config.py
# 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):
. Output only the next line. | def setUpClass(cls): |
Given snippet: <|code_start|># coding: utf-8
def run_script_mock(script, host):
yield 200, {}, '{"output": "test text"}'
def failed_run_script_mock(script, host):
yield 500, {}, ''
class TestArtifactCollector(BaseTestCase):
@classmethod
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
from flask import Flask
from mock import patch, Mock
from tests.helpers import BaseTestCase, DatabaseMock, wait_for
from core.config import config, setup_config
from vmpool.artifact_collector import ArtifactCollector
from core.db.models import Session, Endpoint, Provider
from vmpool.artifact_collector import ArtifactCollector
from core.db.models import Session, Endpoint, Provider
from vmpool.artifact_collector import ArtifactCollector
from core.db.models import Session, Endpoint, Provider
from vmpool.artifact_collector import ArtifactCollector, Task
from multiprocessing.pool import AsyncResult
and context:
# Path: tests/helpers.py
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# 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)
#
# def wait_for(condition, timeout=10):
# start = time.time()
# while not condition() and time.time() - start < timeout:
# time.sleep(0.1)
#
# return condition()
#
# Path: core/config.py
# 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):
which might include code, classes, or functions. Output only the next line. | def setUpClass(cls): |
Given the code snippet: <|code_start|>
def run_script_mock(script, host):
yield 200, {}, '{"output": "test text"}'
def failed_run_script_mock(script, host):
yield 500, {}, ''
class TestArtifactCollector(BaseTestCase):
@classmethod
def setUpClass(cls):
setup_config('data/config_openstack.py')
cls.app = Flask(__name__)
cls.app.database = DatabaseMock()
cls.app.sessions = Mock()
cls.session_id = 1
cls.artifact_dir = os.sep.join([config.SCREENSHOTS_DIR, str(cls.session_id)])
if not os.path.exists(cls.artifact_dir):
os.mkdir(cls.artifact_dir)
def setUp(self):
self.ctx = self.app.test_request_context()
self.ctx.push()
def tearDown(self):
self.ctx.pop()
<|code_end|>
, generate the next line using the imports in this file:
import os
from flask import Flask
from mock import patch, Mock
from tests.helpers import BaseTestCase, DatabaseMock, wait_for
from core.config import config, setup_config
from vmpool.artifact_collector import ArtifactCollector
from core.db.models import Session, Endpoint, Provider
from vmpool.artifact_collector import ArtifactCollector
from core.db.models import Session, Endpoint, Provider
from vmpool.artifact_collector import ArtifactCollector
from core.db.models import Session, Endpoint, Provider
from vmpool.artifact_collector import ArtifactCollector, Task
from multiprocessing.pool import AsyncResult
and context (functions, classes, or occasionally code) from other files:
# Path: tests/helpers.py
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# 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)
#
# def wait_for(condition, timeout=10):
# start = time.time()
# while not condition() and time.time() - start < timeout:
# time.sleep(0.1)
#
# return condition()
#
# Path: core/config.py
# 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):
. Output only the next line. | @patch('vmpool.artifact_collector.run_script', run_script_mock) |
Based on the snippet: <|code_start|>
def run_script_mock(script, host):
yield 200, {}, '{"output": "test text"}'
def failed_run_script_mock(script, host):
yield 500, {}, ''
class TestArtifactCollector(BaseTestCase):
@classmethod
def setUpClass(cls):
setup_config('data/config_openstack.py')
cls.app = Flask(__name__)
cls.app.database = DatabaseMock()
cls.app.sessions = Mock()
cls.session_id = 1
cls.artifact_dir = os.sep.join([config.SCREENSHOTS_DIR, str(cls.session_id)])
if not os.path.exists(cls.artifact_dir):
os.mkdir(cls.artifact_dir)
def setUp(self):
self.ctx = self.app.test_request_context()
self.ctx.push()
def tearDown(self):
self.ctx.pop()
@patch('vmpool.artifact_collector.run_script', run_script_mock)
<|code_end|>
, predict the immediate next line with the help of imports:
import os
from flask import Flask
from mock import patch, Mock
from tests.helpers import BaseTestCase, DatabaseMock, wait_for
from core.config import config, setup_config
from vmpool.artifact_collector import ArtifactCollector
from core.db.models import Session, Endpoint, Provider
from vmpool.artifact_collector import ArtifactCollector
from core.db.models import Session, Endpoint, Provider
from vmpool.artifact_collector import ArtifactCollector
from core.db.models import Session, Endpoint, Provider
from vmpool.artifact_collector import ArtifactCollector, Task
from multiprocessing.pool import AsyncResult
and context (classes, functions, sometimes code) from other files:
# Path: tests/helpers.py
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# 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)
#
# def wait_for(condition, timeout=10):
# start = time.time()
# while not condition() and time.time() - start < timeout:
# time.sleep(0.1)
#
# return condition()
#
# Path: core/config.py
# 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):
. Output only the next line. | def test_add_tasks(self): |
Given snippet: <|code_start|> DOCKER_BASE_URL = 'unix://var/run/docker.sock'
DOCKER_TIMEOUT = 120
DOCKER_NUM_POOLS = 100
DOCKER_NETWORK_NAME = "vmmaster_network"
DOCKER_SUBNET = "192.168.1.0/24"
DOCKER_GATEWAY = "192.168.1.254"
DOCKER_CONTAINER_MEMORY_LIMIT = "1g"
DOCKER_CONTAINER_CPU_PERIOD = 100000
DOCKER_CONTAINER_CPU_QUOTA = 50000
DOCKER_CONTAINER_VOLUMES = {}
DOCKER_CONTAINER_ENVIRONMENT = {}
DNS_LIST = []
DNS_SEARCH_LIST = [
"test"
]
PUBLIC_IP = "127.0.0.1"
VM_PING_RETRY_COUNT = 3
VM_CREATE_CHECK_PAUSE = 3
VM_CREATE_CHECK_ATTEMPTS = 5
PRELOADER_FREQUENCY = 3
SESSION_TIMEOUT = 5
PING_TIMEOUT = 5
# vm pool
GET_VM_TIMEOUT = 5
SCREENCAST_RESOLUTION = (1600, 1200)
MAKE_REQUEST_ATTEMPTS_AMOUNT = 5
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
from tests.helpers import get_free_port
and context:
# Path: tests/helpers.py
# 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
which might include code, classes, or functions. Output only the next line. | FLASK_THREAD_POOL_MAX = 10 |
Predict the next line after this snippet: <|code_start|># coding: utf-8
class TestSeleniumMatcherNegative(BaseTestCase):
def test_empty_platforms_config(self):
matcher = SeleniumMatcher(platforms={})
dc = {
'browserName': 'ANY',
'version': 'ANY',
<|code_end|>
using the current file's imports:
from mock import Mock, patch
from lode_runner import dataprovider
from tests.helpers import BaseTestCase
from vmmaster.matcher import SeleniumMatcher
from vmmaster.matcher import SeleniumMatcher
from vmmaster.matcher import SeleniumMatcher
from vmmaster.matcher import SeleniumMatcher
from vmmaster.matcher import SeleniumMatcher, PlatformsBasedMatcher
from vmmaster.app import Vmmaster
from vmmaster.app import Vmmaster
from vmmaster.app import Vmmaster
from vmmaster.app import Vmmaster
and any relevant context from other files:
# Path: tests/helpers.py
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
. Output only the next line. | 'platform': 'ANY', |
Given the code snippet: <|code_start|># # inside of a "create the database" script, first create
# # tables:
# my_metadata.create_all(engine)
# then, load the Alembic configuration and generate the
# version table, "stamping" it with the most recent rev:
alembic_cfg = Config("%s/migrations/alembic.ini" % home_dir())
script = ScriptDirectory.from_config(alembic_cfg)
def run(connection_string):
revision = "1f77126c0528"
alembic_cfg.set_main_option("sqlalchemy.url", connection_string)
<|code_end|>
, generate the next line using the imports in this file:
from alembic.config import Config
from alembic import command
from alembic.script import ScriptDirectory
from core.utils.init import home_dir
and context (functions, classes, or occasionally code) from other files:
# Path: core/utils/init.py
# def home_dir():
# return os.path.abspath(os.curdir)
. Output only the next line. | command.upgrade(alembic_cfg, revision) |
Given the following code snippet before the placeholder: <|code_start|>app_context_mock = Mock(return_value=Mock(__enter__=Mock(), __exit__=Mock()))
def call_in_thread_mock(f):
def wrapper(*args, **kwargs):
return f(*args, **kwargs)
return wrapper
def wait_for(condition, timeout=10):
start = time.time()
while not condition() and time.time() - start < timeout:
time.sleep(0.1)
return condition()
def request(host, method, url, headers=None, body=None):
if headers is None:
headers = dict()
conn = httplib.HTTPConnection(host, timeout=20)
conn.request(method=method, url=url, headers=headers, body=body)
response = conn.getresponse()
class Response(object):
pass
r = Response()
r.status = response.status
r.headers = response.getheaders()
r.content = response.read()
<|code_end|>
, predict the next line using imports from the current file:
import BaseHTTPServer
import copy
import json
import os
import threading
import time
import socket
import unittest
import httplib
from Queue import Queue, Empty
from mock import Mock, patch, PropertyMock
from nose.twistedtools import reactor
from core.utils.network_utils import get_socket
from twisted.internet.defer import Deferred, TimeoutError
from twisted.python.failure import Failure
from core.db.models import Provider
from vmmaster.server import VMMasterServer
and context including class names, function names, and sometimes code from other files:
# Path: core/utils/network_utils.py
# def get_socket(host, port):
# s = None
#
# addr_info = socket.getaddrinfo(
# host, port, socket.AF_UNSPEC, socket.SOCK_STREAM
# )
# for af, socktype, proto, canonname, sa in addr_info:
# try:
# s = socket.socket(af, socktype, proto)
# except socket.error:
# s = None
# continue
# try:
# s = socket.create_connection((host, port), timeout=0.1)
# except socket.error:
# s.close()
# s = None
# continue
# break
#
# return s
. Output only the next line. | conn.close() |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
OPENSTACK_UTILS_LOG_LEVEL = logging.WARNING
OPENSTACK_AUTH_URL = '{}:{}/{}'.format(
config.OPENSTACK_AUTH_URL,
config.OPENSTACK_PORT,
config.OPENSTACK_CLIENT_VERSION
)
logging.getLogger("requests").setLevel(OPENSTACK_UTILS_LOG_LEVEL)
logging.getLogger("keystoneauth").setLevel(OPENSTACK_UTILS_LOG_LEVEL)
logging.getLogger("novaclient").setLevel(OPENSTACK_UTILS_LOG_LEVEL)
def get_session():
<|code_end|>
. Write the next line using the current file imports:
import logging
from keystoneauth1 import session
from keystoneauth1.identity import v3
from keystoneclient.v3 import client as ksclient
from novaclient import client as novaclient
from core.config import config
and context from other files:
# Path: core/config.py
# 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):
, which may include functions, classes, or code. Output only the next line. | auth = v3.Password( |
Given the code snippet: <|code_start|> self._cache.popitem(last=False)
def values(self):
return self._cache.values()
def clear(self):
with self._cache_lock:
self._cache.clear()
class Sessions(object):
_worker = None
_cache = None
def __init__(self, database, context, session_worker_class=SessionWorker, cache_class=SessionCache):
self.db = database
self.context = context
if session_worker_class:
self._worker = session_worker_class(self, self.context)
if cache_class:
self._cache = cache_class()
def start_workers(self):
if self._worker:
self._worker.start()
def stop_workers(self):
if self._worker:
<|code_end|>
, generate the next line using the imports in this file:
import time
import logging
from collections import OrderedDict
from threading import Thread, Lock
from core.config import config
from core.exceptions import SessionException
and context (functions, classes, or occasionally code) from other files:
# Path: core/config.py
# 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):
#
# Path: core/exceptions.py
# class SessionException(Exception):
# pass
. Output only the next line. | self._worker.stop() |
Next line prediction: <|code_start|> while self.running:
with self.context():
for session in self.sessions.running(cached=True):
if not session.is_active and session.inactivity > config.SESSION_TIMEOUT:
session.timeout()
time.sleep(1)
def stop(self):
self.running = False
self.join(1)
log.info("SessionWorker stopped")
class SessionCache:
def __init__(self, max_size=100):
self._max_size = max_size
self._cache = OrderedDict()
self._cache_lock = Lock()
def to_json(self):
return self._cache.keys()
def __getitem__(self, item):
return self._cache[item]
def __setitem__(self, key, value):
with self._cache_lock:
self._check_limit()
self._cache[key] = value
<|code_end|>
. Use current file imports:
(import time
import logging
from collections import OrderedDict
from threading import Thread, Lock
from core.config import config
from core.exceptions import SessionException)
and context including class names, function names, or small code snippets from other files:
# Path: core/config.py
# 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):
#
# Path: core/exceptions.py
# class SessionException(Exception):
# pass
. Output only the next line. | def _check_limit(self): |
Given the following code snippet before the placeholder: <|code_start|># coding: utf-8
class TestVNCVideoHelper(BaseTestCase):
def setUp(self):
setup_config('data/config_openstack.py')
<|code_end|>
, predict the next line using imports from the current file:
from mock import patch, Mock
from tests.helpers import BaseTestCase, DatabaseMock, wait_for
from core.config import setup_config
from vmpool.artifact_collector import ArtifactCollector
and context including class names, function names, and sometimes code from other files:
# Path: tests/helpers.py
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# 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)
#
# def wait_for(condition, timeout=10):
# start = time.time()
# while not condition() and time.time() - start < timeout:
# time.sleep(0.1)
#
# return condition()
. Output only the next line. | def test_run_recorder(self): |
Given snippet: <|code_start|> session = Session('some_platform')
session.status = 'unknown'
session.name = '__test_file_deletion'
session.save()
session_dir = os.path.join(
config.SCREENSHOTS_DIR, str(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([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)
session = Session('some_platform')
session.status = 'unknown'
session.closed = True
session.name = '__test_outdated_sessions'
session.save()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import unittest
from mock import Mock, patch
from core.utils import system_utils
from core.config import setup_config, config
from flask import Flask
from core import db
from vmmaster import cleanup
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session, Endpoint, Provider
and context:
# Path: core/utils/system_utils.py
# def run_command(command, silent=False):
#
# Path: core/config.py
# 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):
which might include code, classes, or functions. Output only the next line. | session_ids_to_delete = [p.id for p in self.cleanup.sessions_overflow(user)] |
Given snippet: <|code_start|>
def test_file_deletion(self):
session = Session('some_platform')
session.status = 'unknown'
session.name = '__test_file_deletion'
session.save()
session_dir = os.path.join(
config.SCREENSHOTS_DIR, str(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([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)
session = Session('some_platform')
session.status = 'unknown'
session.closed = True
session.name = '__test_outdated_sessions'
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import unittest
from mock import Mock, patch
from core.utils import system_utils
from core.config import setup_config, config
from flask import Flask
from core import db
from vmmaster import cleanup
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session, Endpoint, Provider
and context:
# Path: core/utils/system_utils.py
# def run_command(command, silent=False):
#
# Path: core/config.py
# 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):
which might include code, classes, or functions. Output only the next line. | session.save() |
Next line prediction: <|code_start|> cls.app = Flask(__name__)
cls.app.sessions = None
cls.app.database = db.Database(config.DATABASE)
with patch(
'core.utils.init.home_dir', Mock(return_value=config.BASEDIR)
):
cls.cleanup = cleanup
def setUp(self):
self.ctx = self.app.app_context()
self.ctx.push()
def tearDown(self):
self.ctx.pop()
def test_file_deletion(self):
session = Session('some_platform')
session.status = 'unknown'
session.name = '__test_file_deletion'
session.save()
session_dir = os.path.join(
config.SCREENSHOTS_DIR, str(session.id)
)
system_utils.run_command(
["mkdir", config.SCREENSHOTS_DIR],
silent=True)
system_utils.run_command(
<|code_end|>
. Use current file imports:
(import os
import unittest
from mock import Mock, patch
from core.utils import system_utils
from core.config import setup_config, config
from flask import Flask
from core import db
from vmmaster import cleanup
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session
from core.db.models import Session, Endpoint, Provider)
and context including class names, function names, or small code snippets from other files:
# Path: core/utils/system_utils.py
# def run_command(command, silent=False):
#
# Path: core/config.py
# 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):
. Output only the next line. | ["mkdir", session_dir], |
Based on the snippet: <|code_start|> deffered1 = pool.apply_async(self.runner.run, args=(suite1,))
deffered2 = pool.apply_async(self.runner.run, args=(suite2,))
deffered1.wait()
deffered2.wait()
result1 = deffered1.get()
result2 = deffered2.get()
self.assertEqual(1, result1.testsRun, result1.errors)
self.assertEqual(1, result2.testsRun, result2.errors)
self.assertEqual(0, len(result1.errors), result1.errors)
self.assertEqual(0, len(result2.errors), result2.errors)
self.assertEqual(0, len(result1.failures), result1.failures)
self.assertEqual(0, len(result2.failures), result2.failures)
@dataprovider(Config.android_platforms)
class TestAndroidWeb(TestCaseApp):
def test_mobile_web(self, platform):
TestAndroidWebTestCase.platform = platform
TestAndroidWebTestCase.micro_app_address = self.micro_app_address
suite = self.loader.loadTestsFromTestCase(TestAndroidWebTestCase)
result = self.runner.run(suite)
self.assertEqual(1, result.testsRun, result.errors)
self.assertEqual(0, len(result.errors), result.errors)
self.assertEqual(0, len(result.failures), result.failures)
@dataprovider(Config.android_platforms)
class TestAndroidNative(unittest.TestCase):
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
import subprocess
from StringIO import StringIO
from multiprocessing.pool import ThreadPool
from os import setsid, killpg
from signal import SIGTERM
from lode_runner import dataprovider
from core.utils.network_utils import get_free_port
from tests.helpers import get_microapp_address
from tests.config import Config
from tests.test_normal import TestPositiveCase
from tests.test_normal import TestLongRequest
from tests.test_normal import TestParallelSessions1, TestParallelSessions2
from tests.test_normal import TestRunScriptOnSessionCreation
from tests.test_normal import TestEnvironmentVariables
from tests.test_normal import TestRunScriptWithInstallPackageOnSessionCreation
from tests.test_normal import TestParallelSlowRunScriptOnSession1, TestParallelSlowRunScriptOnSession2
from tests.test_normal import TestAndroidWebTestCase
from tests.test_normal import TestAndroidNativeTestCase
and context (classes, functions, sometimes code) from other files:
# Path: core/utils/network_utils.py
# 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
#
# Path: tests/helpers.py
# class TimeoutException(Exception):
# class Response(object):
# class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
# class ServerMock(object):
# class BaseTestCase(unittest.TestCase):
# class DatabaseMock(Mock):
# def call_in_thread_mock(f):
# def wrapper(*args, **kwargs):
# def wait_for(condition, timeout=10):
# def request(host, method, url, headers=None, body=None):
# def request_with_drop(address, desired_caps, method=None):
# def new_session_request(client, desired_caps):
# def open_url_request(client, session, data):
# def delete_session_request(client, session):
# def get_session_request(client, session):
# def run_script(client, session, script):
# def vmmaster_label(client, session, label=None):
# def server_is_up(address, wait=5):
# def server_is_down(address, wait=5):
# def fake_home_dir():
# def get_free_port():
# def body(self):
# def send_reply(self, code, headers, body):
# def do_POST(self):
# def do_GET(self):
# def log_error(self, format, *args):
# def log_message(self, format, *args):
# def log_request(self, code='-', size='-'):
# def __init__(self, host, port):
# def start(self):
# def stop(self):
# def shortDescription(self):
# def set_primary_key(_self):
# def __init__(self, *args, **kwargs):
# def get_active_sessions(self, provider_id=None):
# def get_session(self, session_id):
# def get_endpoint(self, endpoint):
# def get_endpoints(self, *args, **kwargs):
# def get_last_session_step(session_id):
# def register_provider(self, name, url, platforms):
# def custom_wait(self):
# def vmmaster_server_mock(port):
# def request_mock(**kwargs):
# def wait_deferred(d, timeout=5):
. Output only the next line. | def setUp(self): |
Given snippet: <|code_start|> self.assertEqual(0, len(result.errors), result.errors)
self.assertEqual(0, len(result.failures), result.failures)
@unittest.skip("Error \"Connection reset by peer\" in apt-get-scripts on random openstack endpoints")
def test_run_script_tests_parallel_run(self, platform):
TestParallelSlowRunScriptOnSession1.platform = platform
TestParallelSlowRunScriptOnSession2.platform = platform
suite1 = unittest.TestSuite()
suite1.addTest(TestParallelSlowRunScriptOnSession1("test"))
suite2 = unittest.TestSuite()
suite2.addTest(TestParallelSlowRunScriptOnSession2("test"))
pool = ThreadPool(2)
deffered1 = pool.apply_async(self.runner.run, args=(suite1,))
deffered2 = pool.apply_async(self.runner.run, args=(suite2,))
deffered1.wait()
deffered2.wait()
result1 = deffered1.get()
result2 = deffered2.get()
self.assertEqual(1, result1.testsRun, result1.errors)
self.assertEqual(1, result2.testsRun, result2.errors)
self.assertEqual(0, len(result1.errors), result1.errors)
self.assertEqual(0, len(result2.errors), result2.errors)
self.assertEqual(0, len(result1.failures), result1.failures)
self.assertEqual(0, len(result2.failures), result2.failures)
@dataprovider(Config.android_platforms)
class TestAndroidWeb(TestCaseApp):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
import subprocess
from StringIO import StringIO
from multiprocessing.pool import ThreadPool
from os import setsid, killpg
from signal import SIGTERM
from lode_runner import dataprovider
from core.utils.network_utils import get_free_port
from tests.helpers import get_microapp_address
from tests.config import Config
from tests.test_normal import TestPositiveCase
from tests.test_normal import TestLongRequest
from tests.test_normal import TestParallelSessions1, TestParallelSessions2
from tests.test_normal import TestRunScriptOnSessionCreation
from tests.test_normal import TestEnvironmentVariables
from tests.test_normal import TestRunScriptWithInstallPackageOnSessionCreation
from tests.test_normal import TestParallelSlowRunScriptOnSession1, TestParallelSlowRunScriptOnSession2
from tests.test_normal import TestAndroidWebTestCase
from tests.test_normal import TestAndroidNativeTestCase
and context:
# Path: core/utils/network_utils.py
# 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
#
# Path: tests/helpers.py
# class TimeoutException(Exception):
# class Response(object):
# class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
# class ServerMock(object):
# class BaseTestCase(unittest.TestCase):
# class DatabaseMock(Mock):
# def call_in_thread_mock(f):
# def wrapper(*args, **kwargs):
# def wait_for(condition, timeout=10):
# def request(host, method, url, headers=None, body=None):
# def request_with_drop(address, desired_caps, method=None):
# def new_session_request(client, desired_caps):
# def open_url_request(client, session, data):
# def delete_session_request(client, session):
# def get_session_request(client, session):
# def run_script(client, session, script):
# def vmmaster_label(client, session, label=None):
# def server_is_up(address, wait=5):
# def server_is_down(address, wait=5):
# def fake_home_dir():
# def get_free_port():
# def body(self):
# def send_reply(self, code, headers, body):
# def do_POST(self):
# def do_GET(self):
# def log_error(self, format, *args):
# def log_message(self, format, *args):
# def log_request(self, code='-', size='-'):
# def __init__(self, host, port):
# def start(self):
# def stop(self):
# def shortDescription(self):
# def set_primary_key(_self):
# def __init__(self, *args, **kwargs):
# def get_active_sessions(self, provider_id=None):
# def get_session(self, session_id):
# def get_endpoint(self, endpoint):
# def get_endpoints(self, *args, **kwargs):
# def get_last_session_step(session_id):
# def register_provider(self, name, url, platforms):
# def custom_wait(self):
# def vmmaster_server_mock(port):
# def request_mock(**kwargs):
# def wait_deferred(d, timeout=5):
which might include code, classes, or functions. Output only the next line. | def test_mobile_web(self, platform): |
Using the snippet: <|code_start|> def __init__(self, host, port=5900, filename_prefix='vnc'):
self.filename_prefix = filename_prefix
self.dir_path = os.sep.join([config.SCREENSHOTS_DIR,
str(self.filename_prefix)])
if not os.path.isdir(self.dir_path):
os.mkdir(self.dir_path)
self.host = host
self.port = port
self.SCREENCAST_FRAMERATE = 5
self.SCREENCAST_WIDTH, self.SCREENCAST_HEIGHT = config.SCREENCAST_RESOLUTION
@staticmethod
def _flvrec(filename, host='localhost', port=5900,
framerate=12, keyframe=120,
preferred_encoding=(0,),
blocksize=32, clipping=None,
debug=0):
fp = file(filename, 'wb')
pwdcache = rfb.PWDCache('%s:%d' % (host, port))
writer = flv.FLVWriter(fp, framerate=framerate, debug=debug)
sink = video.FLVVideoSink(
writer,
blocksize=blocksize, framerate=framerate, keyframe=keyframe,
clipping=clipping, debug=debug)
client = rfb.RFBNetworkClient(
host, port, sink, timeout=500/framerate,
pwdcache=pwdcache, preferred_encoding=preferred_encoding,
debug=debug)
log.debug('Start vnc recording to %s' % filename)
return_code = 0
<|code_end|>
, determine the next line of code. You have imports:
import os
import sys
import time
import signal
import logging
import os.path
import websockify
import multiprocessing
from core.config import config
from vnc2flv import flv, rfb, video
from core.utils.network_utils import get_free_port
from core.exceptions import VNCProxyException
and context (class names, function names, or code) available:
# Path: core/config.py
# 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):
#
# Path: core/utils/network_utils.py
# 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
#
# Path: core/exceptions.py
# class VNCProxyException(Exception):
# pass
. Output only the next line. | try: |
Continue the code snippet: <|code_start|>
log = logging.getLogger(__name__)
class VNCVideoHelper:
recorder = None
__filepath = None
def __init__(self, host, port=5900, filename_prefix='vnc'):
self.filename_prefix = filename_prefix
self.dir_path = os.sep.join([config.SCREENSHOTS_DIR,
str(self.filename_prefix)])
if not os.path.isdir(self.dir_path):
os.mkdir(self.dir_path)
self.host = host
self.port = port
self.SCREENCAST_FRAMERATE = 5
self.SCREENCAST_WIDTH, self.SCREENCAST_HEIGHT = config.SCREENCAST_RESOLUTION
@staticmethod
def _flvrec(filename, host='localhost', port=5900,
framerate=12, keyframe=120,
preferred_encoding=(0,),
blocksize=32, clipping=None,
debug=0):
fp = file(filename, 'wb')
pwdcache = rfb.PWDCache('%s:%d' % (host, port))
writer = flv.FLVWriter(fp, framerate=framerate, debug=debug)
sink = video.FLVVideoSink(
writer,
<|code_end|>
. Use current file imports:
import os
import sys
import time
import signal
import logging
import os.path
import websockify
import multiprocessing
from core.config import config
from vnc2flv import flv, rfb, video
from core.utils.network_utils import get_free_port
from core.exceptions import VNCProxyException
and context (classes, functions, or code) from other files:
# Path: core/config.py
# 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):
#
# Path: core/utils/network_utils.py
# 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
#
# Path: core/exceptions.py
# class VNCProxyException(Exception):
# pass
. Output only the next line. | blocksize=blocksize, framerate=framerate, keyframe=keyframe, |
Given snippet: <|code_start|> log.debug('File %s was deleted' % vnc_log)
def start_recording(self):
log.info("Screencast recorder starting for session {}".format(self.filename_prefix))
sys.stderr = sys.stdout = open(os.sep.join([
self.dir_path, 'vnc_video.log'
]), 'w')
self.__filepath = os.sep.join([self.dir_path,
str(self.filename_prefix) + '.flv'])
kwargs = {
'framerate': self.SCREENCAST_FRAMERATE,
'clipping': video.str2clip("{}x{}+0-0".format(self.SCREENCAST_WIDTH, self.SCREENCAST_HEIGHT)),
'debug': 1
}
self.recorder = multiprocessing.Process(
target=self._flvrec,
args=(self.__filepath, self.host, self.port),
kwargs=kwargs,
name="{}.recorder".format(__name__)
)
self.recorder.daemon = True
self.recorder.start()
log.info(
"Started screencast recording(pid:{}) for {}:{} to {}".format(
self.recorder.pid, self.host, self.port, self.dir_path
)
)
def stop_recording(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import sys
import time
import signal
import logging
import os.path
import websockify
import multiprocessing
from core.config import config
from vnc2flv import flv, rfb, video
from core.utils.network_utils import get_free_port
from core.exceptions import VNCProxyException
and context:
# Path: core/config.py
# 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):
#
# Path: core/utils/network_utils.py
# 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
#
# Path: core/exceptions.py
# class VNCProxyException(Exception):
# pass
which might include code, classes, or functions. Output only the next line. | if self.recorder and self.recorder.is_alive(): |
Predict the next line after this snippet: <|code_start|>
class LogStreamHandlerTest(BaseTestCase):
def setUp(self):
self.logger = logging.getLogger('logging-test')
self.logger.setLevel(logging.DEBUG)
self.buffer = BytesIO()
self.logHandler = logging.StreamHandler(self.buffer)
self.logger.addHandler(self.logHandler)
@dataprovider([
"test message",
"{0}"
])
def test_properties(self, msg):
props = {
"message": msg,
"@version": "1",
"level": "INFO"
}
self.logHandler.setFormatter(LogstashFormatter())
self.logger.info(msg)
log_json = json.loads(self.buffer.getvalue())
self.assertEqual(log_json.get("@version"), props["@version"])
self.assertEqual(log_json.get("tags"), list())
self.assertTrue(isinstance(log_json.get("@timestamp"), unicode))
self.assertEqual(log_json["message"], msg)
@dataprovider([
{"custom_field": 1},
{"@1": "1"}
<|code_end|>
using the current file's imports:
import json
import logging
from io import BytesIO
from tests.helpers import BaseTestCase
from lode_runner import dataprovider
from core.logger import LogstashFormatter
and any relevant context from other files:
# Path: tests/helpers.py
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# Path: core/logger.py
# class LogstashFormatter(logging.Formatter):
#
# def __init__(self, fmt=None, datefmt=None, message_type=None, tags=None, fqdn=False):
# super(LogstashFormatter, self).__init__(fmt=fmt, datefmt=datefmt)
# self.message_type = message_type if message_type else "vmmaster"
# self.tags = tags if tags is not None else []
# self.team = "vmmaster"
# self.project = "vmmaster"
#
# if fqdn:
# self.host = socket.getfqdn()
# else:
# self.host = socket.gethostname()
#
# def get_extra_fields(self, record):
# # The list contains all the attributes listed in
# # http://docs.python.org/library/logging.html#logrecord-attributes
# skip_list = (
# 'args', 'asctime', 'created', 'exc_info', 'exc_text', 'filename',
# 'funcName', 'id', 'levelname', 'levelno', 'lineno', 'module',
# 'msecs', 'msecs', 'message', 'msg', 'name', 'pathname', 'process',
# 'processName', 'relativeCreated', 'thread', 'threadName', 'extra')
#
# if sys.version_info < (3, 0):
# easy_types = (basestring, bool, dict, float, int, long, list, type(None))
# else:
# easy_types = (str, bool, dict, float, int, list, type(None))
#
# fields = {}
#
# for key, value in record.__dict__.items():
# if key not in skip_list:
# if isinstance(value, easy_types):
# fields[key] = value
# else:
# fields[key] = repr(value)
#
# return fields
#
# def get_debug_fields(self, record):
# fields = {
# 'stack_trace': self.format_exception(record.exc_info),
# 'lineno': record.lineno,
# 'process': record.process,
# 'thread_name': record.threadName,
# }
#
# if not getattr(record, 'funcName', None):
# fields['funcName'] = record.funcName
#
# if not getattr(record, 'processName', None):
# fields['processName'] = record.processName
#
# return fields
#
# @classmethod
# def format_source(cls, message_type, host, path):
# return "%s://%s/%s" % (message_type, host, path)
#
# @classmethod
# def format_timestamp(cls, time):
# tstamp = datetime.utcfromtimestamp(time)
# return tstamp.strftime("%Y-%m-%dT%H:%M:%S") + ".%03d" % (tstamp.microsecond / 1000) + "Z"
#
# @classmethod
# def format_exception(cls, exc_info):
# return ''.join(traceback.format_exception(*exc_info)) if exc_info else ''
#
# @classmethod
# def serialize(cls, message):
# if sys.version_info < (3, 0):
# return json.dumps(message)
# else:
# return bytes(json.dumps(message), 'utf-8')
#
# def format(self, record):
# message = {
# '@timestamp': self.format_timestamp(record.created),
# '@version': '1',
# 'message': record.getMessage(),
# 'host': self.host,
# 'path': record.pathname,
# 'tags': self.tags,
# 'type': self.message_type,
# 'team': self.team,
# 'project': self.project,
#
# # Extra Fields
# 'level': record.levelname,
# 'logger_name': record.name,
# }
#
# message.update(self.get_extra_fields(record))
#
# # If exception, add debug info
# if record.exc_info:
# message.update(self.get_debug_fields(record))
#
# return self.serialize(message)
. Output only the next line. | ]) |
Based on the snippet: <|code_start|># coding: utf-8
class LogStreamHandlerTest(BaseTestCase):
def setUp(self):
self.logger = logging.getLogger('logging-test')
self.logger.setLevel(logging.DEBUG)
self.buffer = BytesIO()
self.logHandler = logging.StreamHandler(self.buffer)
self.logger.addHandler(self.logHandler)
@dataprovider([
"test message",
<|code_end|>
, predict the immediate next line with the help of imports:
import json
import logging
from io import BytesIO
from tests.helpers import BaseTestCase
from lode_runner import dataprovider
from core.logger import LogstashFormatter
and context (classes, functions, sometimes code) from other files:
# Path: tests/helpers.py
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# Path: core/logger.py
# class LogstashFormatter(logging.Formatter):
#
# def __init__(self, fmt=None, datefmt=None, message_type=None, tags=None, fqdn=False):
# super(LogstashFormatter, self).__init__(fmt=fmt, datefmt=datefmt)
# self.message_type = message_type if message_type else "vmmaster"
# self.tags = tags if tags is not None else []
# self.team = "vmmaster"
# self.project = "vmmaster"
#
# if fqdn:
# self.host = socket.getfqdn()
# else:
# self.host = socket.gethostname()
#
# def get_extra_fields(self, record):
# # The list contains all the attributes listed in
# # http://docs.python.org/library/logging.html#logrecord-attributes
# skip_list = (
# 'args', 'asctime', 'created', 'exc_info', 'exc_text', 'filename',
# 'funcName', 'id', 'levelname', 'levelno', 'lineno', 'module',
# 'msecs', 'msecs', 'message', 'msg', 'name', 'pathname', 'process',
# 'processName', 'relativeCreated', 'thread', 'threadName', 'extra')
#
# if sys.version_info < (3, 0):
# easy_types = (basestring, bool, dict, float, int, long, list, type(None))
# else:
# easy_types = (str, bool, dict, float, int, list, type(None))
#
# fields = {}
#
# for key, value in record.__dict__.items():
# if key not in skip_list:
# if isinstance(value, easy_types):
# fields[key] = value
# else:
# fields[key] = repr(value)
#
# return fields
#
# def get_debug_fields(self, record):
# fields = {
# 'stack_trace': self.format_exception(record.exc_info),
# 'lineno': record.lineno,
# 'process': record.process,
# 'thread_name': record.threadName,
# }
#
# if not getattr(record, 'funcName', None):
# fields['funcName'] = record.funcName
#
# if not getattr(record, 'processName', None):
# fields['processName'] = record.processName
#
# return fields
#
# @classmethod
# def format_source(cls, message_type, host, path):
# return "%s://%s/%s" % (message_type, host, path)
#
# @classmethod
# def format_timestamp(cls, time):
# tstamp = datetime.utcfromtimestamp(time)
# return tstamp.strftime("%Y-%m-%dT%H:%M:%S") + ".%03d" % (tstamp.microsecond / 1000) + "Z"
#
# @classmethod
# def format_exception(cls, exc_info):
# return ''.join(traceback.format_exception(*exc_info)) if exc_info else ''
#
# @classmethod
# def serialize(cls, message):
# if sys.version_info < (3, 0):
# return json.dumps(message)
# else:
# return bytes(json.dumps(message), 'utf-8')
#
# def format(self, record):
# message = {
# '@timestamp': self.format_timestamp(record.created),
# '@version': '1',
# 'message': record.getMessage(),
# 'host': self.host,
# 'path': record.pathname,
# 'tags': self.tags,
# 'type': self.message_type,
# 'team': self.team,
# 'project': self.project,
#
# # Extra Fields
# 'level': record.levelname,
# 'logger_name': record.name,
# }
#
# message.update(self.get_extra_fields(record))
#
# # If exception, add debug info
# if record.exc_info:
# message.update(self.get_debug_fields(record))
#
# return self.serialize(message)
. Output only the next line. | "{0}" |
Next line prediction: <|code_start|>
return sorted(screenshots)
def get_screenshots_for_label(session_id, label_id):
steps_groups = {}
current_label = 0
log_steps = current_app.database.get_log_steps_for_session(session_id)
for step in reversed(log_steps):
if label_step(step.control_line) == 'label':
current_label = step.id
if not steps_groups.get(current_label, None):
steps_groups[current_label] = []
if step.screenshot:
steps_groups[current_label].append(step.screenshot)
try:
return steps_groups[label_id]
except KeyError:
return []
def label_step(string):
try:
request = string.split(" ")
if request[0] == "POST" and request[1].endswith("/vmmasterLabel"):
return 'label'
<|code_end|>
. Use current file imports:
(from flask import current_app
from core.exceptions import SessionException)
and context including class names, function names, or small code snippets from other files:
# Path: core/exceptions.py
# class SessionException(Exception):
# pass
. Output only the next line. | except: |
Using the snippet: <|code_start|>
log = logging.getLogger(__name__)
class RequestHelper(object):
method = None
url = None
headers = None
data = None
def __init__(self, method, url="/", headers=None, data=""):
_headers = {}
<|code_end|>
, determine the next line of code. You have imports:
import time
import logging
import netifaces
import requests
import socket
from Queue import Queue
from threading import Thread
from core import constants, config
from core.exceptions import RequestException, RequestTimeoutException
from . import system_utils
and context (class names, function names, or code) available:
# Path: core/constants.py
# SESSION_CLOSE_REASON_API_CALL = "Session closed via API stop_session call"
# GET_ENDPOINT_ATTEMPTS = 10
# ENDPOINT_REBUILD_ATTEMPTS = 3
# CREATE_SESSION_REQUEST_TIMEOUT = 60
# REQUEST_TIMEOUT = 60
# MAKE_REQUEST_ATTEMPTS_AMOUNT = 3
# REQUEST_SLEEP_BASE_TIME = 5
# REQUEST_TIMEOUT_ON_CREATE_ENDPOINT = 60
# ANY = u'ANY'
# GET_SESSION_SLEEP_TIME = 2
# ER_SLEEP_TIME = 2
# EP_SLEEP_TIME = 2
#
# Path: core/config.py
# 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):
#
# Path: core/exceptions.py
# class RequestException(Exception):
# pass
#
# class RequestTimeoutException(Exception):
# pass
#
# Path: core/utils/system_utils.py
# def run_command(command, silent=False):
. Output only the next line. | if headers: |
Based on the snippet: <|code_start|> continue
try:
s = socket.create_connection((host, port), timeout=0.1)
except socket.error:
s.close()
s = None
continue
break
return s
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
def ping(ip, port):
try:
s = get_socket(ip, int(port))
except Exception:
return False
if s:
s.close()
return True
<|code_end|>
, predict the immediate next line with the help of imports:
import time
import logging
import netifaces
import requests
import socket
from Queue import Queue
from threading import Thread
from core import constants, config
from core.exceptions import RequestException, RequestTimeoutException
from . import system_utils
and context (classes, functions, sometimes code) from other files:
# Path: core/constants.py
# SESSION_CLOSE_REASON_API_CALL = "Session closed via API stop_session call"
# GET_ENDPOINT_ATTEMPTS = 10
# ENDPOINT_REBUILD_ATTEMPTS = 3
# CREATE_SESSION_REQUEST_TIMEOUT = 60
# REQUEST_TIMEOUT = 60
# MAKE_REQUEST_ATTEMPTS_AMOUNT = 3
# REQUEST_SLEEP_BASE_TIME = 5
# REQUEST_TIMEOUT_ON_CREATE_ENDPOINT = 60
# ANY = u'ANY'
# GET_SESSION_SLEEP_TIME = 2
# ER_SLEEP_TIME = 2
# EP_SLEEP_TIME = 2
#
# Path: core/config.py
# 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):
#
# Path: core/exceptions.py
# class RequestException(Exception):
# pass
#
# class RequestTimeoutException(Exception):
# pass
#
# Path: core/utils/system_utils.py
# def run_command(command, silent=False):
. Output only the next line. | return False |
Here is a snippet: <|code_start|>
log = logging.getLogger(__name__)
class RequestHelper(object):
method = None
url = None
headers = None
data = None
def __init__(self, method, url="/", headers=None, data=""):
_headers = {}
if headers:
for key, value in headers.items():
if value:
_headers[key] = value
_headers["Content-Length"] = str(len(data))
self.headers = _headers
self.method = method
self.url = url
self.data = data
def __repr__(self):
return "<RequestHelper method:%s url:%s headers:%s body:%s>" % (
self.method, self.url, self.headers, self.data)
<|code_end|>
. Write the next line using the current file imports:
import time
import logging
import netifaces
import requests
import socket
from Queue import Queue
from threading import Thread
from core import constants, config
from core.exceptions import RequestException, RequestTimeoutException
from . import system_utils
and context from other files:
# Path: core/constants.py
# SESSION_CLOSE_REASON_API_CALL = "Session closed via API stop_session call"
# GET_ENDPOINT_ATTEMPTS = 10
# ENDPOINT_REBUILD_ATTEMPTS = 3
# CREATE_SESSION_REQUEST_TIMEOUT = 60
# REQUEST_TIMEOUT = 60
# MAKE_REQUEST_ATTEMPTS_AMOUNT = 3
# REQUEST_SLEEP_BASE_TIME = 5
# REQUEST_TIMEOUT_ON_CREATE_ENDPOINT = 60
# ANY = u'ANY'
# GET_SESSION_SLEEP_TIME = 2
# ER_SLEEP_TIME = 2
# EP_SLEEP_TIME = 2
#
# Path: core/config.py
# 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):
#
# Path: core/exceptions.py
# class RequestException(Exception):
# pass
#
# class RequestTimeoutException(Exception):
# pass
#
# Path: core/utils/system_utils.py
# def run_command(command, silent=False):
, which may include functions, classes, or code. Output only the next line. | def get_interface_subnet(inteface): |
Next line prediction: <|code_start|>
def get_socket(host, port):
s = None
addr_info = socket.getaddrinfo(
host, port, socket.AF_UNSPEC, socket.SOCK_STREAM
)
for af, socktype, proto, canonname, sa in addr_info:
try:
s = socket.socket(af, socktype, proto)
except socket.error:
s = None
continue
try:
s = socket.create_connection((host, port), timeout=0.1)
except socket.error:
s.close()
s = None
continue
break
return s
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]
<|code_end|>
. Use current file imports:
(import time
import logging
import netifaces
import requests
import socket
from Queue import Queue
from threading import Thread
from core import constants, config
from core.exceptions import RequestException, RequestTimeoutException
from . import system_utils)
and context including class names, function names, or small code snippets from other files:
# Path: core/constants.py
# SESSION_CLOSE_REASON_API_CALL = "Session closed via API stop_session call"
# GET_ENDPOINT_ATTEMPTS = 10
# ENDPOINT_REBUILD_ATTEMPTS = 3
# CREATE_SESSION_REQUEST_TIMEOUT = 60
# REQUEST_TIMEOUT = 60
# MAKE_REQUEST_ATTEMPTS_AMOUNT = 3
# REQUEST_SLEEP_BASE_TIME = 5
# REQUEST_TIMEOUT_ON_CREATE_ENDPOINT = 60
# ANY = u'ANY'
# GET_SESSION_SLEEP_TIME = 2
# ER_SLEEP_TIME = 2
# EP_SLEEP_TIME = 2
#
# Path: core/config.py
# 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):
#
# Path: core/exceptions.py
# class RequestException(Exception):
# pass
#
# class RequestTimeoutException(Exception):
# pass
#
# Path: core/utils/system_utils.py
# def run_command(command, silent=False):
. Output only the next line. | s.close() |
Given the following code snippet before the placeholder: <|code_start|>
def get_ip_by_mac(mac):
subnet = get_interface_subnet("br0")
nmap_ping_scan(subnet)
code, output = arp_numeric()
split_output = output.split("\n")
for line in split_output:
if mac in line:
break
if line == "":
return None
return line.split(" ")[0]
def get_socket(host, port):
s = None
addr_info = socket.getaddrinfo(
host, port, socket.AF_UNSPEC, socket.SOCK_STREAM
)
for af, socktype, proto, canonname, sa in addr_info:
try:
s = socket.socket(af, socktype, proto)
except socket.error:
s = None
continue
<|code_end|>
, predict the next line using imports from the current file:
import time
import logging
import netifaces
import requests
import socket
from Queue import Queue
from threading import Thread
from core import constants, config
from core.exceptions import RequestException, RequestTimeoutException
from . import system_utils
and context including class names, function names, and sometimes code from other files:
# Path: core/constants.py
# SESSION_CLOSE_REASON_API_CALL = "Session closed via API stop_session call"
# GET_ENDPOINT_ATTEMPTS = 10
# ENDPOINT_REBUILD_ATTEMPTS = 3
# CREATE_SESSION_REQUEST_TIMEOUT = 60
# REQUEST_TIMEOUT = 60
# MAKE_REQUEST_ATTEMPTS_AMOUNT = 3
# REQUEST_SLEEP_BASE_TIME = 5
# REQUEST_TIMEOUT_ON_CREATE_ENDPOINT = 60
# ANY = u'ANY'
# GET_SESSION_SLEEP_TIME = 2
# ER_SLEEP_TIME = 2
# EP_SLEEP_TIME = 2
#
# Path: core/config.py
# 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):
#
# Path: core/exceptions.py
# class RequestException(Exception):
# pass
#
# class RequestTimeoutException(Exception):
# pass
#
# Path: core/utils/system_utils.py
# def run_command(command, silent=False):
. Output only the next line. | try: |
Based on the snippet: <|code_start|> with patch(
'core.utils.init.home_dir', Mock(return_value=fake_home_dir())
), patch(
'core.db.Database', DatabaseMock()
), patch(
'vmpool.virtual_machines_pool.VirtualMachinesPool', Mock()
):
self.app = create_app()
self.app.pool = VirtualMachinesPool(
self.app, 'unnamed', platforms_class=Mock(), preloader_class=Mock(),
artifact_collector_class=Mock(), endpoint_preparer_class=Mock(), endpoint_remover_class=Mock()
)
self.vmmaster_client = self.app.test_client()
self.platform = 'origin_1'
self.ctx = self.app.app_context()
self.ctx.push()
@patch('vmpool.api.helpers.get_platforms', Mock(return_value=['origin_1']))
def test_api_platforms(self):
response = self.vmmaster_client.get('/api/platforms')
body = json.loads(response.data)
platforms = body['result']['platforms']
self.assertEqual(200, response.status_code)
self.assertEqual(1, len(platforms))
names = [platform for platform in platforms]
<|code_end|>
, predict the immediate next line with the help of imports:
import json
from datetime import datetime
from mock import Mock, patch, PropertyMock
from lode_runner import dataprovider
from tests.helpers import BaseTestCase, fake_home_dir, DatabaseMock
from core import constants
from core.config import setup_config
from vmmaster.server import create_app
from core.db.models import Session, Endpoint, Provider
from core.db.models import Session, Endpoint, Provider
from core.db.models import Session, Endpoint, Provider
from core.db.models import Session, Endpoint, Provider
from core.db.models import Session, Endpoint, Provider
from core.db.models import Session
from core.db.models import Session
from core.config import setup_config
from vmpool.server import create_app
from vmpool.virtual_machines_pool import VirtualMachinesPool
and context (classes, functions, sometimes code) from other files:
# Path: tests/helpers.py
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# def fake_home_dir():
# return '%s/data' % os.path.dirname(__file__)
#
# 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)
#
# Path: core/constants.py
# SESSION_CLOSE_REASON_API_CALL = "Session closed via API stop_session call"
# GET_ENDPOINT_ATTEMPTS = 10
# ENDPOINT_REBUILD_ATTEMPTS = 3
# CREATE_SESSION_REQUEST_TIMEOUT = 60
# REQUEST_TIMEOUT = 60
# MAKE_REQUEST_ATTEMPTS_AMOUNT = 3
# REQUEST_SLEEP_BASE_TIME = 5
# REQUEST_TIMEOUT_ON_CREATE_ENDPOINT = 60
# ANY = u'ANY'
# GET_SESSION_SLEEP_TIME = 2
# ER_SLEEP_TIME = 2
# EP_SLEEP_TIME = 2
. Output only the next line. | self.assertEqual(names[0], self.platform) |
Here is a snippet: <|code_start|> provider = Provider(name='noname', url='nourl')
endpoint = Endpoint(Mock(), '', provider)
endpoint.ip = '127.0.0.1'
endpoint.name = 'test_endpoint'
endpoint.ports = {'4455': 4455, '9000': 9000, '5900': 5900}
session = Session("some_platform")
session.name = "session1"
session.id = 1
session.status = "waiting"
session.vnc_proxy_port = None
session.vnc_proxy_pid = None
session.created = session.modified = datetime.now()
session.endpoint = endpoint
with patch(
'flask.current_app.sessions.get_session', Mock(return_value=session)
):
response = self.vmmaster_client.get('/api/session/{}/vnc_info'.format(session.id))
body = json.loads(response.data)
self.assertEqual(200, response.status_code)
self.assertDictEqual({}, body['result'])
self.assertEqual(500, body['metacode'])
def test_start_new_proxy(self):
provider = Provider(name='noname', url='nourl')
endpoint = Endpoint(Mock(), '', provider)
endpoint.ip = '127.0.0.1'
endpoint.name = 'test_endpoint'
endpoint.ports = {'4455': 4455, '9000': 9000, '5900': 5900}
<|code_end|>
. Write the next line using the current file imports:
import json
from datetime import datetime
from mock import Mock, patch, PropertyMock
from lode_runner import dataprovider
from tests.helpers import BaseTestCase, fake_home_dir, DatabaseMock
from core import constants
from core.config import setup_config
from vmmaster.server import create_app
from core.db.models import Session, Endpoint, Provider
from core.db.models import Session, Endpoint, Provider
from core.db.models import Session, Endpoint, Provider
from core.db.models import Session, Endpoint, Provider
from core.db.models import Session, Endpoint, Provider
from core.db.models import Session
from core.db.models import Session
from core.config import setup_config
from vmpool.server import create_app
from vmpool.virtual_machines_pool import VirtualMachinesPool
and context from other files:
# Path: tests/helpers.py
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# def fake_home_dir():
# return '%s/data' % os.path.dirname(__file__)
#
# 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)
#
# Path: core/constants.py
# SESSION_CLOSE_REASON_API_CALL = "Session closed via API stop_session call"
# GET_ENDPOINT_ATTEMPTS = 10
# ENDPOINT_REBUILD_ATTEMPTS = 3
# CREATE_SESSION_REQUEST_TIMEOUT = 60
# REQUEST_TIMEOUT = 60
# MAKE_REQUEST_ATTEMPTS_AMOUNT = 3
# REQUEST_SLEEP_BASE_TIME = 5
# REQUEST_TIMEOUT_ON_CREATE_ENDPOINT = 60
# ANY = u'ANY'
# GET_SESSION_SLEEP_TIME = 2
# ER_SLEEP_TIME = 2
# EP_SLEEP_TIME = 2
, which may include functions, classes, or code. Output only the next line. | session = Session("some_platform") |
Using the snippet: <|code_start|> ), patch(
'core.utils.kill_process', Mock()
), patch(
'core.db.Database', DatabaseMock()
):
self.app = create_app()
self.vmmaster_client = self.app.test_client()
self.platform = 'origin_1'
self.desired_caps = {
'desiredCapabilities': {
'platform': self.platform
}
}
self.ctx = self.app.app_context()
self.ctx.push()
def tearDown(self):
self.app.sessions.kill_all()
self.ctx.pop()
self.app.cleanup()
del self.app
def test_get_vnc_proxy_port_if_session_is_waiting(self):
provider = Provider(name='noname', url='nourl')
endpoint = Endpoint(Mock(), '', provider)
endpoint.ip = '127.0.0.1'
endpoint.name = 'test_endpoint'
<|code_end|>
, determine the next line of code. You have imports:
import json
from datetime import datetime
from mock import Mock, patch, PropertyMock
from lode_runner import dataprovider
from tests.helpers import BaseTestCase, fake_home_dir, DatabaseMock
from core import constants
from core.config import setup_config
from vmmaster.server import create_app
from core.db.models import Session, Endpoint, Provider
from core.db.models import Session, Endpoint, Provider
from core.db.models import Session, Endpoint, Provider
from core.db.models import Session, Endpoint, Provider
from core.db.models import Session, Endpoint, Provider
from core.db.models import Session
from core.db.models import Session
from core.config import setup_config
from vmpool.server import create_app
from vmpool.virtual_machines_pool import VirtualMachinesPool
and context (class names, function names, or code) available:
# Path: tests/helpers.py
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# def fake_home_dir():
# return '%s/data' % os.path.dirname(__file__)
#
# 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)
#
# Path: core/constants.py
# SESSION_CLOSE_REASON_API_CALL = "Session closed via API stop_session call"
# GET_ENDPOINT_ATTEMPTS = 10
# ENDPOINT_REBUILD_ATTEMPTS = 3
# CREATE_SESSION_REQUEST_TIMEOUT = 60
# REQUEST_TIMEOUT = 60
# MAKE_REQUEST_ATTEMPTS_AMOUNT = 3
# REQUEST_SLEEP_BASE_TIME = 5
# REQUEST_TIMEOUT_ON_CREATE_ENDPOINT = 60
# ANY = u'ANY'
# GET_SESSION_SLEEP_TIME = 2
# ER_SLEEP_TIME = 2
# EP_SLEEP_TIME = 2
. Output only the next line. | endpoint.ports = {'4455': 4455, '9000': 9000, '5900': 5900} |
Continue the code snippet: <|code_start|>
def test_when_during_proxy_starting_session_was_closed(self):
provider = Provider(name='noname', url='nourl')
endpoint = Endpoint(Mock(), '', provider)
endpoint.ip = '127.0.0.1'
endpoint.name = 'test_endpoint'
endpoint.ports = {'4455': 4455, '9000': 9000, '5900': 5900}
session = Session("some_platform")
session.id = 1
session.name = "session1"
session.status = "running"
session.closed = True
type(session).vnc_proxy_port = PropertyMock(side_effect=[None, 55555, 55555])
session.vnc_proxy_pid = 55555
session.created = session.modified = datetime.now()
session.endpoint = endpoint
session.stop_vnc_proxy = Mock()
with patch(
'flask.current_app.sessions.get_session', Mock(return_value=session)
):
response = self.vmmaster_client.get('/api/session/%s/vnc_info' % session.id)
body = json.loads(response.data)
self.assertEqual(200, response.status_code)
self.assertDictEqual({}, body['result'])
self.assertEqual(500, body['metacode'])
def test_get_vnc_port_if_running_proxy(self):
provider = Provider(name='noname', url='nourl')
<|code_end|>
. Use current file imports:
import json
from datetime import datetime
from mock import Mock, patch, PropertyMock
from lode_runner import dataprovider
from tests.helpers import BaseTestCase, fake_home_dir, DatabaseMock
from core import constants
from core.config import setup_config
from vmmaster.server import create_app
from core.db.models import Session, Endpoint, Provider
from core.db.models import Session, Endpoint, Provider
from core.db.models import Session, Endpoint, Provider
from core.db.models import Session, Endpoint, Provider
from core.db.models import Session, Endpoint, Provider
from core.db.models import Session
from core.db.models import Session
from core.config import setup_config
from vmpool.server import create_app
from vmpool.virtual_machines_pool import VirtualMachinesPool
and context (classes, functions, or code) from other files:
# Path: tests/helpers.py
# class BaseTestCase(unittest.TestCase):
# def shortDescription(self):
# return None
#
# def fake_home_dir():
# return '%s/data' % os.path.dirname(__file__)
#
# 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)
#
# Path: core/constants.py
# SESSION_CLOSE_REASON_API_CALL = "Session closed via API stop_session call"
# GET_ENDPOINT_ATTEMPTS = 10
# ENDPOINT_REBUILD_ATTEMPTS = 3
# CREATE_SESSION_REQUEST_TIMEOUT = 60
# REQUEST_TIMEOUT = 60
# MAKE_REQUEST_ATTEMPTS_AMOUNT = 3
# REQUEST_SLEEP_BASE_TIME = 5
# REQUEST_TIMEOUT_ON_CREATE_ENDPOINT = 60
# ANY = u'ANY'
# GET_SESSION_SLEEP_TIME = 2
# ER_SLEEP_TIME = 2
# EP_SLEEP_TIME = 2
. Output only the next line. | endpoint = Endpoint(Mock(), '', provider) |
Given the following code snippet before the placeholder: <|code_start|> PLATFORMS = {}
OPENSTACK_AUTH_URL = "localhost"
OPENSTACK_PORT = 5000
OPENSTACK_CLIENT_VERSION = "v3"
OPENSTACK_USERNAME = "user"
OPENSTACK_PASSWORD = "password"
OPENSTACK_TENANT_NAME = "name"
OPENSTACK_TENANT_ID = "id"
OPENSTACK_NETWORK_ID = "id"
OPENSTACK_NETWORK_NAME = "network"
OPENSTACK_ZONE_FOR_VM_CREATE = ""
OPENSTACK_PLATFORM_NAME_PREFIX = "test_"
OPENSTACK_DEFAULT_FLAVOR = 'flavor'
OPENSTACK_DOMAIN_NAME = "test"
OPENASTACK_VM_META_DATA = {
'admin_pass': 'password'
}
OPENSTACK_VM_USERDATA_FILE_PATH = "%s/userdata" % os.path.abspath(os.curdir)
USE_DOCKER = False
BIND_LOCALHOST_PORTS = False
DOCKER_MAX_COUNT = 3
DOCKER_PRELOADED = {}
DOCKER_BASE_URL = 'unix://var/run/docker.sock'
DOCKER_TIMEOUT = 120
DOCKER_NUM_POOLS = 100
DOCKER_NETWORK_NAME = "vmmaster_network"
DOCKER_SUBNET = "192.168.1.0/24"
DOCKER_GATEWAY = "192.168.1.254"
<|code_end|>
, predict the next line using imports from the current file:
import os
from tests.helpers import get_free_port
and context including class names, function names, and sometimes code from other files:
# Path: tests/helpers.py
# 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
. Output only the next line. | DOCKER_CONTAINER_MEMORY_LIMIT = "1g" |
Predict the next line after this snippet: <|code_start|>
testdata_dir = os.path.realpath(
os.path.join(
os.path.dirname(__file__), '..', '..', 'testdata', 'source',
'waveapps'))
examples = [
'test_basic',
'test_matching',
]
<|code_end|>
using the current file's imports:
import os
import pytest
from .source_test import check_source_example
and any relevant context from other files:
# Path: beancount_import/source/source_test.py
# def check_source_example(example_dir: str,
# source_spec: SourceSpec,
# replacements: List[Tuple[str, str]],
# write: Optional[bool] = None):
# journal_path = os.path.join(example_dir, 'journal.beancount')
# editor = JournalEditor(journal_path)
# assert editor.errors == []
# source = load_source(source_spec)
# results = SourceResults()
# source.prepare(editor, results)
# results.pending.sort(key=lambda x: x.date)
# account_source_map = {account: source for account in results.accounts}
# sources = [source]
# extractor = training.FeatureExtractor(
# sources=sources, account_source_map=account_source_map,
# skip_accounts=results.skip_training_accounts)
# assert(not [m for m in results.messages if m[0] == 'error'])
# for filename, new_contents in _add_invalid_reference_and_cleared_metadata(
# editor, source,
# sorted(
# results.invalid_references,
# key=invalid_source_reference_sort_key)).items():
# test_util.check_golden_contents(
# filename,
# new_contents,
# replacements=[],
# write=write,
# )
# test_util.check_golden_contents(
# os.path.join(example_dir, 'import_results.beancount'),
# _format_import_results(
# results.pending, extractor=extractor, source=source),
# replacements=replacements,
# write=write,
# )
# test_util.check_golden_contents(
# os.path.join(example_dir, 'accounts.txt'),
# ''.join(account + '\n' for account in sorted(results.accounts)),
# replacements=replacements,
# write=write,
# )
#
# training_examples = training.MockTrainingExamples()
# extractor.extract_examples(editor.entries, training_examples)
#
# test_util.check_golden_contents(
# os.path.join(example_dir, 'training_examples.json'),
# json.dumps(
# [[_json_encode_prediction_input(prediction_input), target]
# for prediction_input, target in training_examples.examples],
# indent=' ',
# sort_keys=True),
# replacements=replacements,
# write=write,
# )
. Output only the next line. | @pytest.mark.parametrize('name', examples) |
Continue the code snippet: <|code_start|>
testdata_dir = os.path.realpath(
os.path.join(
os.path.dirname(__file__), '..', '..', 'testdata', 'source',
'google_purchases'))
examples = [
'test_basic',
'test_matching',
'test_invalid',
<|code_end|>
. Use current file imports:
import os
import pytest
from .source_test import check_source_example
and context (classes, functions, or code) from other files:
# Path: beancount_import/source/source_test.py
# def check_source_example(example_dir: str,
# source_spec: SourceSpec,
# replacements: List[Tuple[str, str]],
# write: Optional[bool] = None):
# journal_path = os.path.join(example_dir, 'journal.beancount')
# editor = JournalEditor(journal_path)
# assert editor.errors == []
# source = load_source(source_spec)
# results = SourceResults()
# source.prepare(editor, results)
# results.pending.sort(key=lambda x: x.date)
# account_source_map = {account: source for account in results.accounts}
# sources = [source]
# extractor = training.FeatureExtractor(
# sources=sources, account_source_map=account_source_map,
# skip_accounts=results.skip_training_accounts)
# assert(not [m for m in results.messages if m[0] == 'error'])
# for filename, new_contents in _add_invalid_reference_and_cleared_metadata(
# editor, source,
# sorted(
# results.invalid_references,
# key=invalid_source_reference_sort_key)).items():
# test_util.check_golden_contents(
# filename,
# new_contents,
# replacements=[],
# write=write,
# )
# test_util.check_golden_contents(
# os.path.join(example_dir, 'import_results.beancount'),
# _format_import_results(
# results.pending, extractor=extractor, source=source),
# replacements=replacements,
# write=write,
# )
# test_util.check_golden_contents(
# os.path.join(example_dir, 'accounts.txt'),
# ''.join(account + '\n' for account in sorted(results.accounts)),
# replacements=replacements,
# write=write,
# )
#
# training_examples = training.MockTrainingExamples()
# extractor.extract_examples(editor.entries, training_examples)
#
# test_util.check_golden_contents(
# os.path.join(example_dir, 'training_examples.json'),
# json.dumps(
# [[_json_encode_prediction_input(prediction_input), target]
# for prediction_input, target in training_examples.examples],
# indent=' ',
# sort_keys=True),
# replacements=replacements,
# write=write,
# )
. Output only the next line. | ] |
Predict the next line after this snippet: <|code_start|>
testdata_dir = os.path.realpath(
os.path.join(
os.path.dirname(__file__), '..', '..', 'testdata', 'source', 'mint'))
examples = [
'test_basic',
'test_training_examples',
'test_invalid',
]
@pytest.mark.parametrize('name', examples)
def test_source(name: str):
check_source_example(
<|code_end|>
using the current file's imports:
import os
import pytest
from .source_test import check_source_example
and any relevant context from other files:
# Path: beancount_import/source/source_test.py
# def check_source_example(example_dir: str,
# source_spec: SourceSpec,
# replacements: List[Tuple[str, str]],
# write: Optional[bool] = None):
# journal_path = os.path.join(example_dir, 'journal.beancount')
# editor = JournalEditor(journal_path)
# assert editor.errors == []
# source = load_source(source_spec)
# results = SourceResults()
# source.prepare(editor, results)
# results.pending.sort(key=lambda x: x.date)
# account_source_map = {account: source for account in results.accounts}
# sources = [source]
# extractor = training.FeatureExtractor(
# sources=sources, account_source_map=account_source_map,
# skip_accounts=results.skip_training_accounts)
# assert(not [m for m in results.messages if m[0] == 'error'])
# for filename, new_contents in _add_invalid_reference_and_cleared_metadata(
# editor, source,
# sorted(
# results.invalid_references,
# key=invalid_source_reference_sort_key)).items():
# test_util.check_golden_contents(
# filename,
# new_contents,
# replacements=[],
# write=write,
# )
# test_util.check_golden_contents(
# os.path.join(example_dir, 'import_results.beancount'),
# _format_import_results(
# results.pending, extractor=extractor, source=source),
# replacements=replacements,
# write=write,
# )
# test_util.check_golden_contents(
# os.path.join(example_dir, 'accounts.txt'),
# ''.join(account + '\n' for account in sorted(results.accounts)),
# replacements=replacements,
# write=write,
# )
#
# training_examples = training.MockTrainingExamples()
# extractor.extract_examples(editor.entries, training_examples)
#
# test_util.check_golden_contents(
# os.path.join(example_dir, 'training_examples.json'),
# json.dumps(
# [[_json_encode_prediction_input(prediction_input), target]
# for prediction_input, target in training_examples.examples],
# indent=' ',
# sort_keys=True),
# replacements=replacements,
# write=write,
# )
. Output only the next line. | example_dir=os.path.join(testdata_dir, name), |
Predict the next line after this snippet: <|code_start|>
testdata_dir = os.path.realpath(
os.path.join(
os.path.dirname(__file__), '..', '..', 'testdata', 'source',
'paypal'))
examples = [
'test_basic',
<|code_end|>
using the current file's imports:
import os
import pytest
from .source_test import check_source_example
and any relevant context from other files:
# Path: beancount_import/source/source_test.py
# def check_source_example(example_dir: str,
# source_spec: SourceSpec,
# replacements: List[Tuple[str, str]],
# write: Optional[bool] = None):
# journal_path = os.path.join(example_dir, 'journal.beancount')
# editor = JournalEditor(journal_path)
# assert editor.errors == []
# source = load_source(source_spec)
# results = SourceResults()
# source.prepare(editor, results)
# results.pending.sort(key=lambda x: x.date)
# account_source_map = {account: source for account in results.accounts}
# sources = [source]
# extractor = training.FeatureExtractor(
# sources=sources, account_source_map=account_source_map,
# skip_accounts=results.skip_training_accounts)
# assert(not [m for m in results.messages if m[0] == 'error'])
# for filename, new_contents in _add_invalid_reference_and_cleared_metadata(
# editor, source,
# sorted(
# results.invalid_references,
# key=invalid_source_reference_sort_key)).items():
# test_util.check_golden_contents(
# filename,
# new_contents,
# replacements=[],
# write=write,
# )
# test_util.check_golden_contents(
# os.path.join(example_dir, 'import_results.beancount'),
# _format_import_results(
# results.pending, extractor=extractor, source=source),
# replacements=replacements,
# write=write,
# )
# test_util.check_golden_contents(
# os.path.join(example_dir, 'accounts.txt'),
# ''.join(account + '\n' for account in sorted(results.accounts)),
# replacements=replacements,
# write=write,
# )
#
# training_examples = training.MockTrainingExamples()
# extractor.extract_examples(editor.entries, training_examples)
#
# test_util.check_golden_contents(
# os.path.join(example_dir, 'training_examples.json'),
# json.dumps(
# [[_json_encode_prediction_input(prediction_input), target]
# for prediction_input, target in training_examples.examples],
# indent=' ',
# sort_keys=True),
# replacements=replacements,
# write=write,
# )
. Output only the next line. | 'test_matching', |
Given the following code snippet before the placeholder: <|code_start|> words.append(w)
for start_i in range(len(words)):
for end_i in range(start_i + 1, len(words) + 1):
features['%s:%s' % (key, ' '.join(
words[start_i:end_i]))] = True
return features
class TrainingExamples(object):
def __init__(self):
self.training_examples = []
def add(self, example: PredictionInput, target_account: str):
self.training_examples.append((get_features(example), target_account))
class MockTrainingExamples(object):
def __init__(self):
self.examples = [] # type: List[Tuple[PredictionInput, str]]
def add(self, prediction_input: PredictionInput,
target_account: str) -> None:
self.examples.append((prediction_input, target_account))
TrainingExamplesInterface = Union[TrainingExamples, MockTrainingExamples]
def get_unknown_account_postings(transaction: Transaction) -> List[Posting]:
return [
<|code_end|>
, predict the next line using imports from the current file:
import collections
import datetime
import functools
import itertools
import re
from typing import Callable, Any, Dict, Iterable, List, NamedTuple, Sequence, Union, Optional, Tuple, Set
from beancount.core.data import Directive, Entries, Transaction, Posting
from beancount.core.amount import Amount
from .matching import is_unknown_account, FIXME_ACCOUNT
from .posting_date import get_posting_date
from .source import Source # For typing only.
and context including class names, function names, and sometimes code from other files:
# Path: beancount_import/matching.py
# def is_unknown_account(account: str):
# return account == FIXME_ACCOUNT or account.startswith(
# MERGEABLE_FIXME_ACCOUNT_PREFIX)
#
# FIXME_ACCOUNT = 'Expenses:FIXME'
#
# Path: beancount_import/posting_date.py
# def get_posting_date(entry, posting):
# """Returns the date associated with a posting."""
# return ((posting.meta and (posting.meta.get(POSTING_DATE_KEY) or
# posting.meta.get(POSTING_TRANSACTION_DATE_KEY))) or entry.date)
. Output only the next line. | posting for posting in transaction.postings |
Predict the next line for this snippet: <|code_start|> if entry.meta:
for k in entry.meta:
extractor = example_transaction_key_extractors.get(k, None)
if extractor is None: continue
extractor(entry.meta[k], transaction_key_value_pairs)
# First attempt to extract direct training examples using
# the key extractors that convert metadata key-value pairs
# to sets of features. This is for the alternative prediction
# method described in source/__init__.py with an Amazon example.
got_example = False
for posting in entry.postings:
meta = posting.meta
if not meta: continue
if is_unknown_account(posting.account): continue
key_value_pairs = dict() # type: ExampleKeyValuePairs
for k in meta:
extractor = example_posting_key_extractors.get(k, None)
if extractor is None: continue
extractor(meta[k], key_value_pairs)
if key_value_pairs:
got_example = True
key_value_pairs = dict(transaction_key_value_pairs,
**key_value_pairs)
training_examples.add(
PredictionInput(
source_account='',
amount=posting.units,
date=entry.date,
key_value_pairs=key_value_pairs),
<|code_end|>
with the help of current file imports:
import collections
import datetime
import functools
import itertools
import re
from typing import Callable, Any, Dict, Iterable, List, NamedTuple, Sequence, Union, Optional, Tuple, Set
from beancount.core.data import Directive, Entries, Transaction, Posting
from beancount.core.amount import Amount
from .matching import is_unknown_account, FIXME_ACCOUNT
from .posting_date import get_posting_date
from .source import Source # For typing only.
and context from other files:
# Path: beancount_import/matching.py
# def is_unknown_account(account: str):
# return account == FIXME_ACCOUNT or account.startswith(
# MERGEABLE_FIXME_ACCOUNT_PREFIX)
#
# FIXME_ACCOUNT = 'Expenses:FIXME'
#
# Path: beancount_import/posting_date.py
# def get_posting_date(entry, posting):
# """Returns the date associated with a posting."""
# return ((posting.meta and (posting.meta.get(POSTING_DATE_KEY) or
# posting.meta.get(POSTING_TRANSACTION_DATE_KEY))) or entry.date)
, which may contain function names, class names, or code. Output only the next line. | target_account=posting.account, |
Continue the code snippet: <|code_start|> self, transaction: Transaction) -> List[Optional[PredictionInput]]:
group_numbers = get_unknown_account_group_numbers(transaction)
example_posting_key_extractors = self.example_posting_key_extractors
example_transaction_key_extractors = self.example_transaction_key_extractors
transaction_key_value_pairs = dict() # type: ExampleKeyValuePairs
if transaction.meta:
for k in transaction.meta:
extractor = example_transaction_key_extractors.get(k, None)
if extractor is None: continue
extractor(transaction.meta[k], transaction_key_value_pairs)
def get_direct_posting_prediction(postings: List[Posting]):
key_value_pairs = {} # type: ExampleKeyValuePairs
for posting in postings:
meta = posting.meta
if not meta: continue
for key, value in meta.items():
extractor = example_posting_key_extractors.get(key)
if extractor is None: continue
extractor(value, key_value_pairs)
if not key_value_pairs: return None
return PredictionInput(
source_account='',
amount=posting.units,
date=transaction.date,
key_value_pairs=key_value_pairs)
def get_indirect_posting_prediction() -> Optional[PredictionInput]:
non_ignored_postings = self.get_postings_for_automatic_classification(
<|code_end|>
. Use current file imports:
import collections
import datetime
import functools
import itertools
import re
from typing import Callable, Any, Dict, Iterable, List, NamedTuple, Sequence, Union, Optional, Tuple, Set
from beancount.core.data import Directive, Entries, Transaction, Posting
from beancount.core.amount import Amount
from .matching import is_unknown_account, FIXME_ACCOUNT
from .posting_date import get_posting_date
from .source import Source # For typing only.
and context (classes, functions, or code) from other files:
# Path: beancount_import/matching.py
# def is_unknown_account(account: str):
# return account == FIXME_ACCOUNT or account.startswith(
# MERGEABLE_FIXME_ACCOUNT_PREFIX)
#
# FIXME_ACCOUNT = 'Expenses:FIXME'
#
# Path: beancount_import/posting_date.py
# def get_posting_date(entry, posting):
# """Returns the date associated with a posting."""
# return ((posting.meta and (posting.meta.get(POSTING_DATE_KEY) or
# posting.meta.get(POSTING_TRANSACTION_DATE_KEY))) or entry.date)
. Output only the next line. | transaction.postings) |
Next line prediction: <|code_start|>
testdata_dir = os.path.realpath(
os.path.join(
os.path.dirname(__file__), '..', '..', 'testdata', 'source', 'generic_importer'))
testdata_csv = os.path.join(testdata_dir, "csv")
examples = [
'test_basic',
'test_invalid',
'test_training_examples'
]
importer = CSVImporter({Col.DATE: 'Date',
Col.NARRATION1: 'Description',
Col.AMOUNT: 'Amount',
},
'Assets:Bank',
<|code_end|>
. Use current file imports:
(import os
import pytest
from .source_test import check_source_example
from beancount.ingest.importers.csv import Importer as CSVImporter, Col
from beancount.ingest.importer import ImporterProtocol
from beancount.parser.parser import parse_file)
and context including class names, function names, or small code snippets from other files:
# Path: beancount_import/source/source_test.py
# def check_source_example(example_dir: str,
# source_spec: SourceSpec,
# replacements: List[Tuple[str, str]],
# write: Optional[bool] = None):
# journal_path = os.path.join(example_dir, 'journal.beancount')
# editor = JournalEditor(journal_path)
# assert editor.errors == []
# source = load_source(source_spec)
# results = SourceResults()
# source.prepare(editor, results)
# results.pending.sort(key=lambda x: x.date)
# account_source_map = {account: source for account in results.accounts}
# sources = [source]
# extractor = training.FeatureExtractor(
# sources=sources, account_source_map=account_source_map,
# skip_accounts=results.skip_training_accounts)
# assert(not [m for m in results.messages if m[0] == 'error'])
# for filename, new_contents in _add_invalid_reference_and_cleared_metadata(
# editor, source,
# sorted(
# results.invalid_references,
# key=invalid_source_reference_sort_key)).items():
# test_util.check_golden_contents(
# filename,
# new_contents,
# replacements=[],
# write=write,
# )
# test_util.check_golden_contents(
# os.path.join(example_dir, 'import_results.beancount'),
# _format_import_results(
# results.pending, extractor=extractor, source=source),
# replacements=replacements,
# write=write,
# )
# test_util.check_golden_contents(
# os.path.join(example_dir, 'accounts.txt'),
# ''.join(account + '\n' for account in sorted(results.accounts)),
# replacements=replacements,
# write=write,
# )
#
# training_examples = training.MockTrainingExamples()
# extractor.extract_examples(editor.entries, training_examples)
#
# test_util.check_golden_contents(
# os.path.join(example_dir, 'training_examples.json'),
# json.dumps(
# [[_json_encode_prediction_input(prediction_input), target]
# for prediction_input, target in training_examples.examples],
# indent=' ',
# sort_keys=True),
# replacements=replacements,
# write=write,
# )
. Output only the next line. | 'USD', |
Continue the code snippet: <|code_start|>
class DescriptionBasedSourceTest(unittest.TestCase):
def test_merged_posting_is_cleared(self):
postings = [
Posting(account="a", units=Amount(D(10), "USD"), cost=None,
price=None, flag=None, meta=None),
Posting(account="a", units=Amount(D(10), "USD"), cost=None,
price=None, flag=None, meta={"merge": True}),
]
source = DescriptionBasedSource(lambda s: None)
<|code_end|>
. Use current file imports:
import unittest
from beancount.core.amount import Amount
from beancount.core.data import Posting
from beancount.core.number import D
from .description_based_source import DescriptionBasedSource
and context (classes, functions, or code) from other files:
# Path: beancount_import/source/description_based_source.py
# class DescriptionBasedSource(Source):
# def get_example_key_value_pairs(self, transaction: Transaction,
# posting: Posting):
# result = {}
# if posting.meta is not None:
# meta = posting.meta
# key = SOURCE_DESC_KEYS[0]
# value = meta.get(key)
# if value is not None:
# result['desc'] = value
# return result
#
# def is_posting_cleared(self, posting: Posting):
# if posting.meta is None:
# return False
# if posting.meta.get("merge"):
# return True
# return not MATCHED_METADATA_KEYS.isdisjoint(posting.meta)
. Output only the next line. | self.assertEqual(source.is_posting_cleared(postings[0]), False) |
Given the code snippet: <|code_start|> '€0.00': Amount(D('0.00'), 'EUR'),
'-€.12': Amount(D('-0.12'), 'EUR'),
'-€123.45': Amount(D('-123.45'), 'EUR'),
'£12345.67': Amount(D('12345.67'), 'GBP'),
'£12,345.67': Amount(D('12345.67'), 'GBP'),
'+£123': Amount(D('123'), 'GBP'),
'£12.34': Amount(D('12.34'), 'GBP'),
'£1.23': Amount(D('1.23'), 'GBP'),
'£0.12': Amount(D('0.12'), 'GBP'),
'£0': Amount(D('0'), 'GBP'),
'£0.00': Amount(D('0.00'), 'GBP'),
'£.12': Amount(D('0.12'), 'GBP'),
'-£.12': Amount(D('-0.12'), 'GBP'),
'-£123.45': Amount(D('-123.45'), 'GBP'),
'$': None,
'$.': None,
'€0.': None,
'£,': None,
'$123,.00': None,
'€,123.00': None,
'£,47.1': None,
'$€!@#$': None,
' INS': None,
"I'm a parrot, cluck cluck": None,
'1,234,567.89': None,
}
for input, expected in cases.items():
try:
actual = parse_amount(input)
<|code_end|>
, generate the next line using the imports in this file:
from beancount.core.number import D
from beancount.core.amount import Amount
from .amount_parsing import parse_amount
and context (functions, classes, or occasionally code) from other files:
# Path: beancount_import/amount_parsing.py
# def parse_amount(x, assumed_currency=None):
# """Parses a number and currency."""
# if not x:
# return None
# sign, amount_str = parse_possible_negative(x)
# m = re.fullmatch(r'(?:[(][^)]+[)])?\s*([\$€£])?((?:[0-9](?:,?[0-9])*|(?=\.))(?:\.[0-9]+)?)(?:\s+([A-Z]{3}))?', amount_str)
# if m is None:
# raise ValueError('Failed to parse amount from %r' % amount_str)
# if m.group(1):
# currency = {'$': 'USD', '€': 'EUR', '£': 'GBP'}[m.group(1)]
# elif m.group(3):
# currency = m.group(3)
# elif assumed_currency is not None:
# currency = assumed_currency
# else:
# raise ValueError('Failed to determine currency from %r' % amount_str)
# number = D(m.group(2))
# return Amount(number * sign, currency)
. Output only the next line. | except ValueError: |
Predict the next line for this snippet: <|code_start|>
def test_two_parents_for_one_goal_is_forbidden():
with pytest.raises(AssertionError):
build_goaltree(
open_(1, "First parent of 3", [2, 3]),
open_(2, "Second parent of 3", [3]),
open_(3, "Fellow child"),
<|code_end|>
with the help of current file imports:
import pytest
from siebenapp.tests.dsl import build_goaltree, open_
and context from other files:
# Path: siebenapp/tests/dsl.py
# def build_goaltree(*goal_prototypes, message_fn=None):
# goals = [(g.goal_id, g.name, g.open) for g in goal_prototypes]
# edges = [
# (g.goal_id, e, EdgeType.PARENT) for g in goal_prototypes for e in g.children
# ] + [(g.goal_id, e, EdgeType.BLOCKER) for g in goal_prototypes for e in g.blockers]
# selection = {g.goal_id for g in goal_prototypes if g.select == selected}
# prev_selection = {g.goal_id for g in goal_prototypes if g.select == previous}
# assert len(selection) == 1
# assert len(prev_selection) <= 1
# selection_id = selection.pop()
# return Goals.build(
# goals,
# edges,
# [
# ("selection", selection_id),
# (
# "previous_selection",
# prev_selection.pop() if prev_selection else selection_id,
# ),
# ],
# message_fn,
# )
#
# def open_(goal_id, name, children=None, blockers=None, select=None):
# return _build_goal_prototype(goal_id, name, True, children, blockers, select)
, which may contain function names, class names, or code. Output only the next line. | ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.