Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Next line prediction: <|code_start|>
CURRENT_DIR = os.path.abspath(os.path.dirname(__file__))
BUILD_DIR = os.path.join(CURRENT_DIR, 'sample', '_build')
@pytest.fixture(scope='session', autouse=True)
def remove_build():
"""Ensure that build directory does not exists before each test."""
if os.path.exists(BUILD_DIR):
shutil.rmtree(BUILD_DIR)
@pytest.fixture
def settings():
"""Read the sample config file."""
<|code_end|>
. Use current file imports:
(import os
import shutil
import blinker
import PIL
import pytest
from sigal import signals
from sigal.settings import read_settings)
and context including class names, function names, or small code snippets from other files:
# Path: sigal/signals.py
#
# Path: sigal/settings.py
# def read_settings(filename=None):
# """Read settings from a config file in the source_dir root."""
#
# logger = logging.getLogger(__name__)
# logger.info("Reading settings ...")
# settings = _DEFAULT_CONFIG.copy()
#
# if filename:
# logger.debug("Settings file: %s", filename)
# settings_path = os.path.dirname(filename)
# tempdict = {}
#
# with open(filename) as f:
# code = compile(f.read(), filename, 'exec')
# exec(code, tempdict)
#
# settings.update(
# (k, v) for k, v in tempdict.items() if k not in ['__builtins__']
# )
#
# # Make the paths relative to the settings file
# paths = ['source', 'destination', 'watermark']
#
# if os.path.isdir(join(settings_path, settings['theme'])) and os.path.isdir(
# join(settings_path, settings['theme'], 'templates')
# ):
# paths.append('theme')
#
# for p in paths:
# path = settings[p]
# if path and not isabs(path):
# settings[p] = abspath(normpath(join(settings_path, path)))
# logger.debug("Rewrite %s : %s -> %s", p, path, settings[p])
#
# for key in ('img_size', 'thumb_size', 'video_size'):
# if settings[key]:
# w, h = settings[key]
# if h > w:
# settings[key] = (h, w)
# logger.warning(
# "The %s setting should be specified with the largest value first.",
# key,
# )
#
# if not settings['img_processor']:
# logger.info('No Processor, images will not be resized')
#
# logger.debug('Settings:\n%s', pformat(settings, width=120))
# return settings
. Output only the next line. | return read_settings(os.path.join(CURRENT_DIR, 'sample', 'sigal.conf.py')) |
Predict the next line for this snippet: <|code_start|> "url": url_from_path(os.path.relpath(self.theme_path, album.dst_path)),
},
}
page = self.template.render(ctx)
file_path = os.path.join(album.dst_path, media_group[0].dst_filename)
output_file = f"{file_path}.html"
with open(output_file, "w", encoding="utf-8") as f:
f.write(page)
def generate_media_pages(gallery):
"""Generates and writes the media pages for all media in the gallery"""
writer = PageWriter(gallery.settings, index_title=gallery.title)
for album in gallery.albums.values():
medias = album.medias
next_medias = medias[1:] + [None]
previous_medias = [None] + medias[:-1]
# The media group allows us to easily get next and previous links
media_groups = zip(medias, next_medias, previous_medias)
for media_group in media_groups:
writer.write(album, media_group)
def register(settings):
<|code_end|>
with the help of current file imports:
import os
from sigal import signals
from sigal.utils import url_from_path
from sigal.writer import AbstractWriter
from sigal import __url__ as sigal_link
and context from other files:
# Path: sigal/signals.py
#
# Path: sigal/utils.py
# def url_from_path(path):
# """Transform path to url, converting backslashes to slashes if needed."""
#
# if os.sep != '/':
# path = '/'.join(path.split(os.sep))
# return quote(path)
#
# Path: sigal/writer.py
# class AbstractWriter:
# template_file = None
#
# def __init__(self, settings, index_title=""):
# self.settings = settings
# self.output_dir = settings["destination"]
# self.theme = settings["theme"]
# self.index_title = index_title
# self.logger = logging.getLogger(__name__)
#
# # search the theme in sigal/theme if the given one does not exists
# if not os.path.exists(self.theme) or not os.path.exists(
# os.path.join(self.theme, "templates")
# ):
# self.theme = os.path.join(THEMES_PATH, self.theme)
# if not os.path.exists(self.theme):
# raise Exception("Impossible to find the theme %s" % self.theme)
#
# self.logger.info("Theme : %s", self.theme)
# theme_relpath = os.path.join(self.theme, "templates")
# default_loader = FileSystemLoader(
# os.path.join(THEMES_PATH, "default", "templates")
# )
#
# # setup jinja env
# env_options = {"trim_blocks": True, "autoescape": True, "lstrip_blocks": True}
#
# loaders = [
# FileSystemLoader(theme_relpath),
# default_loader, # implicit inheritance
# PrefixLoader({"!default": default_loader}), # explicit one
# ]
# env = Environment(loader=ChoiceLoader(loaders), **env_options)
#
# # handle optional filters.py
# filters_py = os.path.join(self.theme, "filters.py")
# if os.path.exists(filters_py):
# self.logger.info('Loading filters file: %s', filters_py)
# module_spec = importlib.util.spec_from_file_location('filters', filters_py)
# mod = importlib.util.module_from_spec(module_spec)
# sys.modules['filters'] = mod
# module_spec.loader.exec_module(mod)
# for name in dir(mod):
# if isinstance(getattr(mod, name), types.FunctionType):
# env.filters[name] = getattr(mod, name)
#
# try:
# self.template = env.get_template(self.template_file)
# except TemplateNotFound:
# self.logger.error(
# "The template %s was not found in template folder %s.",
# self.template_file,
# theme_relpath,
# )
# sys.exit(1)
#
# # Copy the theme files in the output dir
# self.theme_path = os.path.join(self.output_dir, "static")
# if os.path.isdir(self.theme_path):
# shutil.rmtree(self.theme_path)
#
# for static_path in (
# os.path.join(THEMES_PATH, 'default', 'static'),
# os.path.join(self.theme, 'static'),
# ):
# shutil.copytree(static_path, self.theme_path, dirs_exist_ok=True)
#
# if self.settings["user_css"]:
# if not os.path.exists(self.settings["user_css"]):
# self.logger.error(
# "CSS file %s could not be found", self.settings["user_css"]
# )
# else:
# shutil.copy(self.settings["user_css"], self.theme_path)
#
# def generate_context(self, album):
# """Generate the context dict for the given path."""
#
# from . import __url__ as sigal_link
#
# self.logger.info("Output album : %r", album)
# ctx = {
# "album": album,
# "index_title": self.index_title,
# "settings": self.settings,
# "sigal_link": sigal_link,
# "theme": {
# "name": os.path.basename(self.theme),
# "url": url_from_path(os.path.relpath(self.theme_path, album.dst_path)),
# },
# }
# if self.settings["user_css"]:
# ctx["user_css"] = os.path.basename(self.settings["user_css"])
# return ctx
#
# def write(self, album):
# """Generate the HTML page and save it."""
# context = self.generate_context(album)
# signals.before_render.send(context)
# page = self.template.render(**context)
# output_file = os.path.join(album.dst_path, album.output_file)
#
# with open(output_file, "w", encoding="utf-8") as f:
# f.write(page)
, which may contain function names, class names, or code. Output only the next line. | signals.gallery_build.connect(generate_media_pages) |
Continue the code snippet: <|code_start|>Currently this plugin can be used only with the colorbox theme, the other
themes have to be adapted.
For themes, the ``previous_media`` and ``next_media`` variables contain the
previous/next :class:`~sigal.gallery.Media` objects.
"""
class PageWriter(AbstractWriter):
"""A writer for writing media pages, based on writer"""
template_file = "media.html"
def write(self, album, media_group):
"""Generate the media page and save it"""
ctx = {
"album": album,
"media": media_group[0],
"previous_media": media_group[-1],
"next_media": media_group[1],
"index_title": self.index_title,
"settings": self.settings,
"sigal_link": sigal_link,
"theme": {
"name": os.path.basename(self.theme),
<|code_end|>
. Use current file imports:
import os
from sigal import signals
from sigal.utils import url_from_path
from sigal.writer import AbstractWriter
from sigal import __url__ as sigal_link
and context (classes, functions, or code) from other files:
# Path: sigal/signals.py
#
# Path: sigal/utils.py
# def url_from_path(path):
# """Transform path to url, converting backslashes to slashes if needed."""
#
# if os.sep != '/':
# path = '/'.join(path.split(os.sep))
# return quote(path)
#
# Path: sigal/writer.py
# class AbstractWriter:
# template_file = None
#
# def __init__(self, settings, index_title=""):
# self.settings = settings
# self.output_dir = settings["destination"]
# self.theme = settings["theme"]
# self.index_title = index_title
# self.logger = logging.getLogger(__name__)
#
# # search the theme in sigal/theme if the given one does not exists
# if not os.path.exists(self.theme) or not os.path.exists(
# os.path.join(self.theme, "templates")
# ):
# self.theme = os.path.join(THEMES_PATH, self.theme)
# if not os.path.exists(self.theme):
# raise Exception("Impossible to find the theme %s" % self.theme)
#
# self.logger.info("Theme : %s", self.theme)
# theme_relpath = os.path.join(self.theme, "templates")
# default_loader = FileSystemLoader(
# os.path.join(THEMES_PATH, "default", "templates")
# )
#
# # setup jinja env
# env_options = {"trim_blocks": True, "autoescape": True, "lstrip_blocks": True}
#
# loaders = [
# FileSystemLoader(theme_relpath),
# default_loader, # implicit inheritance
# PrefixLoader({"!default": default_loader}), # explicit one
# ]
# env = Environment(loader=ChoiceLoader(loaders), **env_options)
#
# # handle optional filters.py
# filters_py = os.path.join(self.theme, "filters.py")
# if os.path.exists(filters_py):
# self.logger.info('Loading filters file: %s', filters_py)
# module_spec = importlib.util.spec_from_file_location('filters', filters_py)
# mod = importlib.util.module_from_spec(module_spec)
# sys.modules['filters'] = mod
# module_spec.loader.exec_module(mod)
# for name in dir(mod):
# if isinstance(getattr(mod, name), types.FunctionType):
# env.filters[name] = getattr(mod, name)
#
# try:
# self.template = env.get_template(self.template_file)
# except TemplateNotFound:
# self.logger.error(
# "The template %s was not found in template folder %s.",
# self.template_file,
# theme_relpath,
# )
# sys.exit(1)
#
# # Copy the theme files in the output dir
# self.theme_path = os.path.join(self.output_dir, "static")
# if os.path.isdir(self.theme_path):
# shutil.rmtree(self.theme_path)
#
# for static_path in (
# os.path.join(THEMES_PATH, 'default', 'static'),
# os.path.join(self.theme, 'static'),
# ):
# shutil.copytree(static_path, self.theme_path, dirs_exist_ok=True)
#
# if self.settings["user_css"]:
# if not os.path.exists(self.settings["user_css"]):
# self.logger.error(
# "CSS file %s could not be found", self.settings["user_css"]
# )
# else:
# shutil.copy(self.settings["user_css"], self.theme_path)
#
# def generate_context(self, album):
# """Generate the context dict for the given path."""
#
# from . import __url__ as sigal_link
#
# self.logger.info("Output album : %r", album)
# ctx = {
# "album": album,
# "index_title": self.index_title,
# "settings": self.settings,
# "sigal_link": sigal_link,
# "theme": {
# "name": os.path.basename(self.theme),
# "url": url_from_path(os.path.relpath(self.theme_path, album.dst_path)),
# },
# }
# if self.settings["user_css"]:
# ctx["user_css"] = os.path.basename(self.settings["user_css"])
# return ctx
#
# def write(self, album):
# """Generate the HTML page and save it."""
# context = self.generate_context(album)
# signals.before_render.send(context)
# page = self.template.render(**context)
# output_file = os.path.join(album.dst_path, album.output_file)
#
# with open(output_file, "w", encoding="utf-8") as f:
# f.write(page)
. Output only the next line. | "url": url_from_path(os.path.relpath(self.theme_path, album.dst_path)), |
Given the code snippet: <|code_start|># of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""Plugin which generates HTML pages for each image.
Currently this plugin can be used only with the colorbox theme, the other
themes have to be adapted.
For themes, the ``previous_media`` and ``next_media`` variables contain the
previous/next :class:`~sigal.gallery.Media` objects.
"""
<|code_end|>
, generate the next line using the imports in this file:
import os
from sigal import signals
from sigal.utils import url_from_path
from sigal.writer import AbstractWriter
from sigal import __url__ as sigal_link
and context (functions, classes, or occasionally code) from other files:
# Path: sigal/signals.py
#
# Path: sigal/utils.py
# def url_from_path(path):
# """Transform path to url, converting backslashes to slashes if needed."""
#
# if os.sep != '/':
# path = '/'.join(path.split(os.sep))
# return quote(path)
#
# Path: sigal/writer.py
# class AbstractWriter:
# template_file = None
#
# def __init__(self, settings, index_title=""):
# self.settings = settings
# self.output_dir = settings["destination"]
# self.theme = settings["theme"]
# self.index_title = index_title
# self.logger = logging.getLogger(__name__)
#
# # search the theme in sigal/theme if the given one does not exists
# if not os.path.exists(self.theme) or not os.path.exists(
# os.path.join(self.theme, "templates")
# ):
# self.theme = os.path.join(THEMES_PATH, self.theme)
# if not os.path.exists(self.theme):
# raise Exception("Impossible to find the theme %s" % self.theme)
#
# self.logger.info("Theme : %s", self.theme)
# theme_relpath = os.path.join(self.theme, "templates")
# default_loader = FileSystemLoader(
# os.path.join(THEMES_PATH, "default", "templates")
# )
#
# # setup jinja env
# env_options = {"trim_blocks": True, "autoescape": True, "lstrip_blocks": True}
#
# loaders = [
# FileSystemLoader(theme_relpath),
# default_loader, # implicit inheritance
# PrefixLoader({"!default": default_loader}), # explicit one
# ]
# env = Environment(loader=ChoiceLoader(loaders), **env_options)
#
# # handle optional filters.py
# filters_py = os.path.join(self.theme, "filters.py")
# if os.path.exists(filters_py):
# self.logger.info('Loading filters file: %s', filters_py)
# module_spec = importlib.util.spec_from_file_location('filters', filters_py)
# mod = importlib.util.module_from_spec(module_spec)
# sys.modules['filters'] = mod
# module_spec.loader.exec_module(mod)
# for name in dir(mod):
# if isinstance(getattr(mod, name), types.FunctionType):
# env.filters[name] = getattr(mod, name)
#
# try:
# self.template = env.get_template(self.template_file)
# except TemplateNotFound:
# self.logger.error(
# "The template %s was not found in template folder %s.",
# self.template_file,
# theme_relpath,
# )
# sys.exit(1)
#
# # Copy the theme files in the output dir
# self.theme_path = os.path.join(self.output_dir, "static")
# if os.path.isdir(self.theme_path):
# shutil.rmtree(self.theme_path)
#
# for static_path in (
# os.path.join(THEMES_PATH, 'default', 'static'),
# os.path.join(self.theme, 'static'),
# ):
# shutil.copytree(static_path, self.theme_path, dirs_exist_ok=True)
#
# if self.settings["user_css"]:
# if not os.path.exists(self.settings["user_css"]):
# self.logger.error(
# "CSS file %s could not be found", self.settings["user_css"]
# )
# else:
# shutil.copy(self.settings["user_css"], self.theme_path)
#
# def generate_context(self, album):
# """Generate the context dict for the given path."""
#
# from . import __url__ as sigal_link
#
# self.logger.info("Output album : %r", album)
# ctx = {
# "album": album,
# "index_title": self.index_title,
# "settings": self.settings,
# "sigal_link": sigal_link,
# "theme": {
# "name": os.path.basename(self.theme),
# "url": url_from_path(os.path.relpath(self.theme_path, album.dst_path)),
# },
# }
# if self.settings["user_css"]:
# ctx["user_css"] = os.path.basename(self.settings["user_css"])
# return ctx
#
# def write(self, album):
# """Generate the HTML page and save it."""
# context = self.generate_context(album)
# signals.before_render.send(context)
# page = self.template.render(**context)
# output_file = os.path.join(album.dst_path, album.output_file)
#
# with open(output_file, "w", encoding="utf-8") as f:
# f.write(page)
. Output only the next line. | class PageWriter(AbstractWriter): |
Here is a snippet: <|code_start|>
logger = logging.getLogger(__name__)
def add_copyright(img, settings=None):
logger.debug('Adding copyright to %r', img)
draw = ImageDraw.Draw(img)
text = settings['copyright']
font = settings.get('copyright_text_font', None)
font_size = settings.get('copyright_text_font_size', 10)
assert font_size >= 0
color = settings.get('copyright_text_color', (0, 0, 0))
bottom_margin = 3 # bottom margin for text
text_height = bottom_margin + 12 # default text height (of 15)
if font:
try:
font = ImageFont.truetype(font, font_size)
text_height = font.getsize(text)[1] + bottom_margin
except Exception: # load default font in case of any exception
logger.debug("Exception: Couldn't locate font %s, using default font", font)
font = ImageFont.load_default()
else:
font = ImageFont.load_default()
left, top = settings.get('copyright_text_position', (5, img.size[1] - text_height))
draw.text((left, top), text, fill=color, font=font)
return img
def register(settings):
if settings.get('copyright'):
<|code_end|>
. Write the next line using the current file imports:
import logging
from PIL import ImageDraw, ImageFont
from sigal import signals
and context from other files:
# Path: sigal/signals.py
, which may include functions, classes, or code. Output only the next line. | signals.img_resized.connect(add_copyright) |
Given snippet: <|code_start|> layer = Image.new('RGBA', im.size, (0, 0, 0, 0))
if position == 'tile':
for y in range(0, im.size[1], mark.size[1]):
for x in range(0, im.size[0], mark.size[0]):
layer.paste(mark, (x, y))
elif position == 'scale':
# scale, but preserve the aspect ratio
ratio = min(float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1])
w = int(mark.size[0] * ratio)
h = int(mark.size[1] * ratio)
mark = mark.resize((w, h))
layer.paste(mark, (int((im.size[0] - w) / 2), int((im.size[1] - h) / 2)))
else:
layer.paste(mark, position)
# composite the watermark with the layer
return Image.composite(layer, im, layer)
def add_watermark(img, settings=None):
logger = logging.getLogger(__name__)
logger.debug('Adding watermark to %r', img)
mark = Image.open(settings['watermark'])
position = settings.get('watermark_position', 'scale')
opacity = settings.get("watermark_opacity", 1)
return watermark(img, mark, position, opacity)
def register(settings):
logger = logging.getLogger(__name__)
if settings.get('watermark'):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
from PIL import Image, ImageEnhance
from sigal import signals
and context:
# Path: sigal/signals.py
which might include code, classes, or functions. Output only the next line. | signals.img_resized.connect(add_watermark) |
Given the following code snippet before the placeholder: <|code_start|> job: 'top_quick1'
serial flow: [
job: 'top_x_quick2-1'
]
serial flow: [
job: 'top_x_quick2-2'
]
serial flow: [
job: 'top_x_quick2-3'
]
job: 'top_quick3'
parallel flow: (
serial flow: [
job: 'top_y_z_quick4a'
]
serial flow: [
job: 'quick4b'
]
job: 'top_y_quick5'
)
]
"""
def test_prefix(api_type, capsys):
<|code_end|>
, predict the next line using imports from the current file:
from jenkinsflow.flow import serial
from .framework import api_select
and context including class names, function names, and sometimes code from other files:
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
. Output only the next line. | with api_select.api(__file__, api_type) as api: |
Predict the next line for this snippet: <|code_start|> script=None,
securitytoken='abc',
print_env=False,
create_job=None,
num_builds_to_keep=4,
final_result_use_cli=False,
set_build_descriptions=()
)
def _random_job_name(api, short_name=None):
# If short_name is not specified, use a random name to make sure the job doesn't exist
short_name = short_name or str(random.random()).replace('.', '')
return api.job_name_prefix + short_name, short_name
def _assert_job(api, job_name, cleanup=False):
job = api.get_job(job_name)
assert job is not None
assert job.name == job_name
assert job.public_uri is not None and job_name in job.public_uri
if cleanup:
api.delete_job(job_name)
return None
return job
def test_job_load_new_no_pre_delete(api_type):
<|code_end|>
with the help of current file imports:
import os, random
from jenkinsflow import jobload
from .framework import api_select
and context from other files:
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
, which may contain function names, class names, or code. Output only the next line. | api = api_select.api(__file__, api_type, login=True) |
Here is a snippet: <|code_start|> ctrl1.invoke('j1', password='a', s1='b')
ctrl1.invoke('j1', password='a', s1='b')
def test_multiple_invocations_new_flow(api_type):
with api_select.api(__file__, api_type) as api:
api.flow_job()
_params = (('password', '', 'Some password'), ('s1', '', 'Some string argument'))
api.job('j1', max_fails=0, expect_invocations=2, expect_order=1, params=_params)
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix, report_interval=1) as ctrl1:
ctrl1.invoke('j1', password='a', s1='b')
with serial(api, timeout=15, job_name_prefix=api.job_name_prefix, report_interval=1) as ctrl1:
ctrl1.invoke('j1', password='something else', s1='asdasdasdasdad')
def test_multiple_invocations_new_flow_same_args(api_type):
with api_select.api(__file__, api_type) as api:
api.flow_job()
_params = (('password', '', 'Some password'), ('s1', '', 'Some string argument'))
api.job('j1', max_fails=0, expect_invocations=2, expect_order=1, params=_params)
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix, report_interval=1) as ctrl1:
ctrl1.invoke('j1', password='a', s1='b')
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix, report_interval=1) as ctrl1:
ctrl1.invoke('j1', password='a', s1='b')
<|code_end|>
. Write the next line using the current file imports:
import os, re
import pytest
from pytest import xfail
from jenkinsflow.flow import serial, parallel
from .cfg import ApiType
from .framework import api_select
from .framework.utils import lines_in, build_started_msg
and context from other files:
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
#
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
# """Assert that `*expected_lines` occur in order in the lines of `text`.
#
# Args:
# *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
# If `expected_line` has a match method it is called and must return True for a line in `text`.
# Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
# Otherwise `expected line` must simply occur in a line in `text`
# """
#
# assert isinstance(api_type, test_cfg.ApiType)
# assert text
# assert expected_lines
#
# return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
#
# def build_started_msg(api, job_name, num, invocation_number=0):
# return "Build started: " + repr(job_name) + ((' Invocation-' + repr(invocation_number)) if invocation_number else '') + " - " + console_url(api, job_name, num)
, which may include functions, classes, or code. Output only the next line. | @pytest.mark.not_apis(ApiType.MOCK, ApiType.SCRIPT) |
Given the following code snippet before the placeholder: <|code_start|> with api_select.api(__file__, api_type) as api:
api.flow_job()
_params = (('password', '', 'Some password'), ('s1', '', 'Some string argument'))
api.job('j1', max_fails=0, expect_invocations=2, expect_order=1, params=_params)
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix, report_interval=1) as ctrl1:
ctrl1.invoke('j1', password='a', s1='b')
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix, report_interval=1) as ctrl1:
ctrl1.invoke('j1', password='a', s1='b')
@pytest.mark.not_apis(ApiType.MOCK, ApiType.SCRIPT)
def test_multiple_invocations_parallel_same_flow_queued(api_type, capsys):
with api_select.api(__file__, api_type) as api:
is_hudson = os.environ.get('HUDSON_URL')
if is_hudson: # TODO investigate why this test fails in Hudson
xfail("Doesn't pass when using Hudson")
return
api.flow_job()
_params = (('password', '', 'Some password'), ('s1', '', 'Some string argument'))
api.job('j1', max_fails=0, expect_invocations=3, expect_order=1, exec_time=3, params=_params)
with parallel(api, timeout=70, job_name_prefix=api.job_name_prefix, report_interval=1) as ctrl1:
ctrl1.invoke('j1', password='a', s1='invocation1')
ctrl1.invoke('j1', password='b', s1='invocation2')
ctrl1.invoke('j1', password='b', s1='invocation3')
sout, _ = capsys.readouterr()
<|code_end|>
, predict the next line using imports from the current file:
import os, re
import pytest
from pytest import xfail
from jenkinsflow.flow import serial, parallel
from .cfg import ApiType
from .framework import api_select
from .framework.utils import lines_in, build_started_msg
and context including class names, function names, and sometimes code from other files:
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
#
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
# """Assert that `*expected_lines` occur in order in the lines of `text`.
#
# Args:
# *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
# If `expected_line` has a match method it is called and must return True for a line in `text`.
# Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
# Otherwise `expected line` must simply occur in a line in `text`
# """
#
# assert isinstance(api_type, test_cfg.ApiType)
# assert text
# assert expected_lines
#
# return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
#
# def build_started_msg(api, job_name, num, invocation_number=0):
# return "Build started: " + repr(job_name) + ((' Invocation-' + repr(invocation_number)) if invocation_number else '') + " - " + console_url(api, job_name, num)
. Output only the next line. | assert lines_in( |
Given the following code snippet before the placeholder: <|code_start|> ctrl1.invoke('j1', password='a', s1='b')
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix, report_interval=1) as ctrl1:
ctrl1.invoke('j1', password='a', s1='b')
@pytest.mark.not_apis(ApiType.MOCK, ApiType.SCRIPT)
def test_multiple_invocations_parallel_same_flow_queued(api_type, capsys):
with api_select.api(__file__, api_type) as api:
is_hudson = os.environ.get('HUDSON_URL')
if is_hudson: # TODO investigate why this test fails in Hudson
xfail("Doesn't pass when using Hudson")
return
api.flow_job()
_params = (('password', '', 'Some password'), ('s1', '', 'Some string argument'))
api.job('j1', max_fails=0, expect_invocations=3, expect_order=1, exec_time=3, params=_params)
with parallel(api, timeout=70, job_name_prefix=api.job_name_prefix, report_interval=1) as ctrl1:
ctrl1.invoke('j1', password='a', s1='invocation1')
ctrl1.invoke('j1', password='b', s1='invocation2')
ctrl1.invoke('j1', password='b', s1='invocation3')
sout, _ = capsys.readouterr()
assert lines_in(
api_type, sout,
"^Job Invocation-1 (1/1,1/1): http://x.x/job/jenkinsflow_test__multiple_invocations_parallel_same_flow_queued__j1",
"^Job Invocation-2 (1/1,1/1): http://x.x/job/jenkinsflow_test__multiple_invocations_parallel_same_flow_queued__j1",
"^Job Invocation-3 (1/1,1/1): http://x.x/job/jenkinsflow_test__multiple_invocations_parallel_same_flow_queued__j1",
(
<|code_end|>
, predict the next line using imports from the current file:
import os, re
import pytest
from pytest import xfail
from jenkinsflow.flow import serial, parallel
from .cfg import ApiType
from .framework import api_select
from .framework.utils import lines_in, build_started_msg
and context including class names, function names, and sometimes code from other files:
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
#
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
# """Assert that `*expected_lines` occur in order in the lines of `text`.
#
# Args:
# *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
# If `expected_line` has a match method it is called and must return True for a line in `text`.
# Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
# Otherwise `expected line` must simply occur in a line in `text`
# """
#
# assert isinstance(api_type, test_cfg.ApiType)
# assert text
# assert expected_lines
#
# return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
#
# def build_started_msg(api, job_name, num, invocation_number=0):
# return "Build started: " + repr(job_name) + ((' Invocation-' + repr(invocation_number)) if invocation_number else '') + " - " + console_url(api, job_name, num)
. Output only the next line. | build_started_msg(api, "jenkinsflow_test__multiple_invocations_parallel_same_flow_queued__j1", 1, invocation_number=1), |
Predict the next line after this snippet: <|code_start|># Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
@pytest.mark.apis(ApiType.SCRIPT)
def test_script_api_env_unchanged(api_type):
"""Ensure that os.environ is unchanged after run of slow using script_api"""
env_before = os.environ.copy()
<|code_end|>
using the current file's imports:
import os
import pytest
from jenkinsflow.flow import serial
from .framework import api_select
from .cfg import ApiType
and any relevant context from other files:
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
. Output only the next line. | with api_select.api(__file__, api_type, login=True) as api: |
Here is a snippet: <|code_start|># Copyright (c) 2012 - 2017 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
def set_build_description(
description: str, replace: bool = False, separator: str = '\n',
username: str = None, password: str = None,
build_url: str = None, job_name: str = None, build_number: int = None,
direct_url: str = None):
"""Utility method to set/append build description on a job build.
If this is used from inside the hudson job you do not have to specify 'build_url' or 'job_name', 'build_number'. You do not have to specify 'direct_url' either
but may still want to do so if JENKINS_URL points to a proxy, so that rest calls can go directly to Jenkins.
The 'build_url' is preferred over 'job_name' and 'build_number'.
Args:
description: The description to set on the build.
replace: Replace existing description, if any, instead of appending.
separator: A separator to insert between any existing description and the new 'description' if 'replace' is not specified.
username: User Name for Jenkin authentication with secured Jenkins.
password: Password of Jenkins User.
build_url: The URL of the jenkins build - preferably non-proxied. Default is os.environ['BUILD_URL'].
job_name: Name of the job to modify a build on. Default is os.environ['JOB_NAME'].
build_number: Build Number to modify. . Default is os.environ['BUILD_NUMBER'].
direct_url: Jenkins URL - preferably non-proxied. If not specified, the value of JENKINS_URL or HUDSON_URL environment variables will be used.
"""
<|code_end|>
. Write the next line using the current file imports:
from .utils import base_url_and_api
and context from other files:
# Path: utils/utils.py
# def base_url_and_api(direct_url):
# try:
# base_url = direct_url.rstrip('/') if direct_url else env_base_url()
# except Exception:
# print("*** ERROR: You must specify 'direct-url' if not running from Jenkins job", file=sys.stderr)
# raise
#
# if base_url.startswith('http:') or base_url.startswith('https:'):
# # Using jenkins_api
# from .. import jenkins_api as api
# else:
# # Using script_api
# from .. import script_api as api
#
# return base_url, api
, which may include functions, classes, or code. Output only the next line. | base_url, api = base_url_and_api(direct_url) |
Predict the next line for this snippet: <|code_start|># Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
here = os.path.abspath(os.path.dirname(__file__))
@pytest.mark.not_apis(ApiType.SCRIPT) # TODO
def test_kill_all_unchecked(api_type, capsys):
<|code_end|>
with the help of current file imports:
import os, re
import pytest
from pytest import raises, xfail
from jenkinsflow.flow import serial, FailedChildJobException, FinalResultException, BuildResult
from .cfg import ApiType
from .framework import api_select
from .framework.utils import lines_in, kill_current_msg
from .framework.killer import kill
and context from other files:
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
#
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
# """Assert that `*expected_lines` occur in order in the lines of `text`.
#
# Args:
# *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
# If `expected_line` has a match method it is called and must return True for a line in `text`.
# Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
# Otherwise `expected line` must simply occur in a line in `text`
# """
#
# assert isinstance(api_type, test_cfg.ApiType)
# assert text
# assert expected_lines
#
# return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
#
# def kill_current_msg(api, job_name, num):
# return "Killing build: " + repr(job_name) + " - " + console_url(api, job_name, num)
#
# Path: test/framework/killer.py
# def kill(api, sleep_time, num_kills):
# """Kill this process"""
# pid = os.getpid()
# ff = __file__.replace('.pyc', '.py')
# log_file_name = api.func_name.replace('test_', '')
# args = [sys.executable, ff, repr(pid), repr(sleep_time), repr(num_kills), log_file_name]
# with open(log_file_name, 'w') as log_file:
# logt(log_file, "Invoking kill subprocess.", args)
#
# subprocess.Popen(args)
, which may contain function names, class names, or code. Output only the next line. | with api_select.api(__file__, api_type, login=True) as api: |
Given the following code snippet before the placeholder: <|code_start|>@pytest.mark.not_apis(ApiType.SCRIPT) # TODO
def test_kill_all_unchecked(api_type, capsys):
with api_select.api(__file__, api_type, login=True) as api:
api.flow_job()
api.job('j1', max_fails=0, expect_invocations=1, expect_order=None, exec_time=50, invocation_delay=0, unknown_result=False, kill=True)
api.job('j2', max_fails=0, expect_invocations=1, expect_order=1, invocation_delay=0, unknown_result=False, kill=True)
api.job('j3', max_fails=0, expect_invocations=3, expect_order=None, exec_time=50, invocation_delay=0, unknown_result=False, kill=True, allow_running=True)
api.job('j4', max_fails=0, expect_invocations=1, expect_order=None, invocation_delay=0, unknown_result=False, kill=True)
api.job('j5', max_fails=1, expect_invocations=1, expect_order=2, invocation_delay=0, unknown_result=False, kill=True)
def flow(api, kill_all):
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix, kill_all=kill_all) as ctrl1:
with ctrl1.parallel() as ctrl2:
ctrl2.invoke_unchecked('j1')
ctrl2.invoke_unchecked('j2')
with ctrl1.parallel() as ctrl3:
ctrl3.invoke_unchecked('j3')
ctrl3.invoke_unchecked('j3') # Queue
ctrl3.invoke_unchecked('j3') # Queue
ctrl3.invoke_unchecked('j4')
ctrl3.invoke_unchecked('j5')
# Invoke the flow
flow(api, False)
# Make sure job has actually started before entering new flow
api.sleep(5)
if capsys:
sout, _ = capsys.readouterr()
<|code_end|>
, predict the next line using imports from the current file:
import os, re
import pytest
from pytest import raises, xfail
from jenkinsflow.flow import serial, FailedChildJobException, FinalResultException, BuildResult
from .cfg import ApiType
from .framework import api_select
from .framework.utils import lines_in, kill_current_msg
from .framework.killer import kill
and context including class names, function names, and sometimes code from other files:
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
#
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
# """Assert that `*expected_lines` occur in order in the lines of `text`.
#
# Args:
# *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
# If `expected_line` has a match method it is called and must return True for a line in `text`.
# Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
# Otherwise `expected line` must simply occur in a line in `text`
# """
#
# assert isinstance(api_type, test_cfg.ApiType)
# assert text
# assert expected_lines
#
# return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
#
# def kill_current_msg(api, job_name, num):
# return "Killing build: " + repr(job_name) + " - " + console_url(api, job_name, num)
#
# Path: test/framework/killer.py
# def kill(api, sleep_time, num_kills):
# """Kill this process"""
# pid = os.getpid()
# ff = __file__.replace('.pyc', '.py')
# log_file_name = api.func_name.replace('test_', '')
# args = [sys.executable, ff, repr(pid), repr(sleep_time), repr(num_kills), log_file_name]
# with open(log_file_name, 'w') as log_file:
# logt(log_file, "Invoking kill subprocess.", args)
#
# subprocess.Popen(args)
. Output only the next line. | assert lines_in(api_type, sout, "unchecked job: 'jenkinsflow_test__kill_all_unchecked__j1' UNKNOWN - RUNNING") |
Given snippet: <|code_start|> api.job('j7', max_fails=0, expect_invocations=0, expect_order=None, exec_time=50)
# Set a long sleep here, when heaviliy loaded it can take time for the flow to get started
kill(api, 35, 1)
# TODO: shouldn't we expect a FailedChildJobsException here?
with raises(FinalResultException) as exinfo:
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix, report_interval=0.05) as ctrl1:
with ctrl1.parallel() as ctrl2:
ctrl2.invoke('j1')
with ctrl2.serial() as ctrl3:
ctrl3.invoke('j2')
ctrl3.invoke('j3')
ctrl2.invoke('j4')
ctrl2.invoke_unchecked('j5')
for ii in range(0, num_j6_invocations):
# Queue a lot of jobs
ctrl2.invoke('j6', a=ii)
with ctrl1.parallel() as ctrl4:
ctrl4.invoke('j7')
assert exinfo.value.result == BuildResult.FAILURE # TODO? Note that ABORTED on child job propagates as FAILURE to the flow
if not capsys:
return
sout, _ = capsys.readouterr()
assert lines_in(
api_type, sout,
"^Got SIGTERM: Killing all builds belonging to current flow",
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os, re
import pytest
from pytest import raises, xfail
from jenkinsflow.flow import serial, FailedChildJobException, FinalResultException, BuildResult
from .cfg import ApiType
from .framework import api_select
from .framework.utils import lines_in, kill_current_msg
from .framework.killer import kill
and context:
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
#
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
# """Assert that `*expected_lines` occur in order in the lines of `text`.
#
# Args:
# *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
# If `expected_line` has a match method it is called and must return True for a line in `text`.
# Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
# Otherwise `expected line` must simply occur in a line in `text`
# """
#
# assert isinstance(api_type, test_cfg.ApiType)
# assert text
# assert expected_lines
#
# return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
#
# def kill_current_msg(api, job_name, num):
# return "Killing build: " + repr(job_name) + " - " + console_url(api, job_name, num)
#
# Path: test/framework/killer.py
# def kill(api, sleep_time, num_kills):
# """Kill this process"""
# pid = os.getpid()
# ff = __file__.replace('.pyc', '.py')
# log_file_name = api.func_name.replace('test_', '')
# args = [sys.executable, ff, repr(pid), repr(sleep_time), repr(num_kills), log_file_name]
# with open(log_file_name, 'w') as log_file:
# logt(log_file, "Invoking kill subprocess.", args)
#
# subprocess.Popen(args)
which might include code, classes, or functions. Output only the next line. | kill_current_msg(api, 'jenkinsflow_test__kill_current__j1', 1), |
Given the code snippet: <|code_start|># Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
here = os.path.abspath(os.path.dirname(__file__))
@pytest.mark.not_apis(ApiType.SCRIPT) # TODO
def test_kill_all_unchecked(api_type, capsys):
with api_select.api(__file__, api_type, login=True) as api:
api.flow_job()
<|code_end|>
, generate the next line using the imports in this file:
import os, re
import pytest
from pytest import raises, xfail
from jenkinsflow.flow import serial, FailedChildJobException, FinalResultException, BuildResult
from .cfg import ApiType
from .framework import api_select
from .framework.utils import lines_in, kill_current_msg
from .framework.killer import kill
and context (functions, classes, or occasionally code) from other files:
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
#
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
# """Assert that `*expected_lines` occur in order in the lines of `text`.
#
# Args:
# *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
# If `expected_line` has a match method it is called and must return True for a line in `text`.
# Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
# Otherwise `expected line` must simply occur in a line in `text`
# """
#
# assert isinstance(api_type, test_cfg.ApiType)
# assert text
# assert expected_lines
#
# return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
#
# def kill_current_msg(api, job_name, num):
# return "Killing build: " + repr(job_name) + " - " + console_url(api, job_name, num)
#
# Path: test/framework/killer.py
# def kill(api, sleep_time, num_kills):
# """Kill this process"""
# pid = os.getpid()
# ff = __file__.replace('.pyc', '.py')
# log_file_name = api.func_name.replace('test_', '')
# args = [sys.executable, ff, repr(pid), repr(sleep_time), repr(num_kills), log_file_name]
# with open(log_file_name, 'w') as log_file:
# logt(log_file, "Invoking kill subprocess.", args)
#
# subprocess.Popen(args)
. Output only the next line. | api.job('j1', max_fails=0, expect_invocations=1, expect_order=None, exec_time=50, invocation_delay=0, unknown_result=False, kill=True) |
Based on the snippet: <|code_start|># Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
here = os.path.abspath(os.path.dirname(__file__))
@pytest.mark.not_apis(ApiType.SCRIPT)
def test_abort(api_type, capsys):
<|code_end|>
, predict the immediate next line with the help of imports:
import os, re
import pytest
from pytest import raises
from jenkinsflow.flow import parallel, FailedChildJobsException
from .framework import api_select
from .framework.utils import lines_in
from .framework.abort_job import abort
from .cfg import ApiType
and context (classes, functions, sometimes code) from other files:
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
# """Assert that `*expected_lines` occur in order in the lines of `text`.
#
# Args:
# *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
# If `expected_line` has a match method it is called and must return True for a line in `text`.
# Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
# Otherwise `expected line` must simply occur in a line in `text`
# """
#
# assert isinstance(api_type, test_cfg.ApiType)
# assert text
# assert expected_lines
#
# return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
#
# Path: test/framework/abort_job.py
# def abort(api, job_name, sleep_time):
# """Call this script as a subprocess"""
# if api.api_type == ApiType.MOCK:
# return
#
# ff = __file__.replace('.pyc', '.py')
# args = [sys.executable, ff, api.file_name, api.api_type.name, api.func_name.replace('test_', ''), job_name, str(sleep_time)]
# with open(job_name, 'w') as log_file:
# logt(log_file, "Invoking abort subprocess.", args)
# subprocess.Popen(args)
#
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
. Output only the next line. | with api_select.api(__file__, api_type, login=True) as api: |
Predict the next line after this snippet: <|code_start|># All rights reserved. This work is under a BSD license, see LICENSE.TXT.
here = os.path.abspath(os.path.dirname(__file__))
@pytest.mark.not_apis(ApiType.SCRIPT)
def test_abort(api_type, capsys):
with api_select.api(__file__, api_type, login=True) as api:
api.flow_job()
api.job('quick', max_fails=0, expect_invocations=1, expect_order=1)
api.job('wait10_abort', max_fails=0, expect_invocations=1, expect_order=1, exec_time=20, final_result='ABORTED')
api.job('wait1_fail', max_fails=1, expect_invocations=1, expect_order=1, exec_time=1)
abort(api, 'wait10_abort', 10)
with raises(FailedChildJobsException) as exinfo:
with parallel(api, timeout=40, job_name_prefix=api.job_name_prefix, report_interval=3) as ctrl:
ctrl.invoke('quick')
ctrl.invoke('wait10_abort')
ctrl.invoke('wait1_fail')
assert "wait10_abort" in str(exinfo.value)
assert "wait1_fail" in str(exinfo.value)
sout, _ = capsys.readouterr()
<|code_end|>
using the current file's imports:
import os, re
import pytest
from pytest import raises
from jenkinsflow.flow import parallel, FailedChildJobsException
from .framework import api_select
from .framework.utils import lines_in
from .framework.abort_job import abort
from .cfg import ApiType
and any relevant context from other files:
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
# """Assert that `*expected_lines` occur in order in the lines of `text`.
#
# Args:
# *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
# If `expected_line` has a match method it is called and must return True for a line in `text`.
# Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
# Otherwise `expected line` must simply occur in a line in `text`
# """
#
# assert isinstance(api_type, test_cfg.ApiType)
# assert text
# assert expected_lines
#
# return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
#
# Path: test/framework/abort_job.py
# def abort(api, job_name, sleep_time):
# """Call this script as a subprocess"""
# if api.api_type == ApiType.MOCK:
# return
#
# ff = __file__.replace('.pyc', '.py')
# args = [sys.executable, ff, api.file_name, api.api_type.name, api.func_name.replace('test_', ''), job_name, str(sleep_time)]
# with open(job_name, 'w') as log_file:
# logt(log_file, "Invoking abort subprocess.", args)
# subprocess.Popen(args)
#
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
. Output only the next line. | assert lines_in( |
Continue the code snippet: <|code_start|># Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
here = os.path.abspath(os.path.dirname(__file__))
@pytest.mark.not_apis(ApiType.SCRIPT)
def test_abort(api_type, capsys):
with api_select.api(__file__, api_type, login=True) as api:
api.flow_job()
api.job('quick', max_fails=0, expect_invocations=1, expect_order=1)
api.job('wait10_abort', max_fails=0, expect_invocations=1, expect_order=1, exec_time=20, final_result='ABORTED')
api.job('wait1_fail', max_fails=1, expect_invocations=1, expect_order=1, exec_time=1)
<|code_end|>
. Use current file imports:
import os, re
import pytest
from pytest import raises
from jenkinsflow.flow import parallel, FailedChildJobsException
from .framework import api_select
from .framework.utils import lines_in
from .framework.abort_job import abort
from .cfg import ApiType
and context (classes, functions, or code) from other files:
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
# """Assert that `*expected_lines` occur in order in the lines of `text`.
#
# Args:
# *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
# If `expected_line` has a match method it is called and must return True for a line in `text`.
# Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
# Otherwise `expected line` must simply occur in a line in `text`
# """
#
# assert isinstance(api_type, test_cfg.ApiType)
# assert text
# assert expected_lines
#
# return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
#
# Path: test/framework/abort_job.py
# def abort(api, job_name, sleep_time):
# """Call this script as a subprocess"""
# if api.api_type == ApiType.MOCK:
# return
#
# ff = __file__.replace('.pyc', '.py')
# args = [sys.executable, ff, api.file_name, api.api_type.name, api.func_name.replace('test_', ''), job_name, str(sleep_time)]
# with open(job_name, 'w') as log_file:
# logt(log_file, "Invoking abort subprocess.", args)
# subprocess.Popen(args)
#
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
. Output only the next line. | abort(api, 'wait10_abort', 10) |
Here is a snippet: <|code_start|># Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
here = os.path.abspath(os.path.dirname(__file__))
extra_sys_path = [os.path.normpath(path) for path in [here, jp(here, '../..'), jp(here, '../demo'), jp(here, '../demo/jobs')]]
sys.path = extra_sys_path + sys.path
def load_demo_jobs(demo, api_type):
print("\nLoad jobs for demo:", demo.__name__)
job_load_module_name = demo.__name__ + '_jobs'
job_load = imp.load_source(job_load_module_name, jp(here, '../demo/jobs', job_load_module_name + '.py'))
api = job_load.create_jobs(api_type)
return api
def _test_demo(demo, api_type):
load_demo_jobs(demo, api_type)
<|code_end|>
. Write the next line using the current file imports:
import sys, os, imp
import pytest
import basic, calculated_flow, prefix, hide_password, errors
from os.path import join as jp
from pytest import raises
from jenkinsflow.flow import parallel, JobControlFailException
from .framework import api_select
from .cfg import ApiType
and context from other files:
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
, which may include functions, classes, or code. Output only the next line. | with api_select.api(__file__, api_type, fixed_prefix="jenkinsflow_demo__") as api: |
Continue the code snippet: <|code_start|># Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
here = os.path.abspath(os.path.dirname(__file__))
extra_sys_path = [os.path.normpath(path) for path in [here, jp(here, '../..'), jp(here, '../demo'), jp(here, '../demo/jobs')]]
sys.path = extra_sys_path + sys.path
def load_demo_jobs(demo, api_type):
print("\nLoad jobs for demo:", demo.__name__)
job_load_module_name = demo.__name__ + '_jobs'
job_load = imp.load_source(job_load_module_name, jp(here, '../demo/jobs', job_load_module_name + '.py'))
api = job_load.create_jobs(api_type)
return api
def _test_demo(demo, api_type):
load_demo_jobs(demo, api_type)
with api_select.api(__file__, api_type, fixed_prefix="jenkinsflow_demo__") as api:
api.job(demo.__name__ + "__0flow", max_fails=0, expect_invocations=1, expect_order=1)
with parallel(api, timeout=70, job_name_prefix=api.job_name_prefix) as ctrl1:
ctrl1.invoke(demo.__name__ + "__0flow")
<|code_end|>
. Use current file imports:
import sys, os, imp
import pytest
import basic, calculated_flow, prefix, hide_password, errors
from os.path import join as jp
from pytest import raises
from jenkinsflow.flow import parallel, JobControlFailException
from .framework import api_select
from .cfg import ApiType
and context (classes, functions, or code) from other files:
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
. Output only the next line. | @pytest.mark.not_apis(ApiType.SCRIPT) # TODO: script api is not configured to run demos |
Given the following code snippet before the placeholder: <|code_start|># Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
def test_single_level_errors_parallel(api_type, capsys):
with api_select.api(__file__, api_type) as api:
api.flow_job()
api.job('quick', max_fails=0, expect_invocations=1, expect_order=1, params=(('s1', '', 'desc'), ('c1', 'false', 'desc')))
api.job('quick_fail', max_fails=1, expect_invocations=1, expect_order=1)
api.job('wait10', max_fails=0, expect_invocations=1, expect_order=1, exec_time=10)
api.job('wait10_fail', max_fails=1, expect_invocations=1, expect_order=1, exec_time=10)
api.job('wait5', max_fails=0, expect_invocations=1, expect_order=1, exec_time=5)
api.job('wait5_fail', max_fails=1, expect_invocations=1, expect_order=1, exec_time=5)
with raises(FailedChildJobsException) as exinfo:
with parallel(api, timeout=40, job_name_prefix=api.job_name_prefix, report_interval=3) as ctrl:
ctrl.invoke('quick', s1='', c1=False)
ctrl.invoke('quick_fail')
ctrl.invoke('wait10')
ctrl.invoke('wait10_fail')
ctrl.invoke('wait5')
ctrl.invoke('wait5_fail')
assert "quick_fail" in str(exinfo.value)
assert "wait10_fail" in str(exinfo.value)
assert "wait5_fail" in str(exinfo.value)
sout, _ = capsys.readouterr()
<|code_end|>
, predict the next line using imports from the current file:
import re
from pytest import raises
from jenkinsflow.flow import parallel, serial, FailedChildJobException, FailedChildJobsException
from .framework import api_select
from .framework.utils import lines_in
and context including class names, function names, and sometimes code from other files:
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
# """Assert that `*expected_lines` occur in order in the lines of `text`.
#
# Args:
# *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
# If `expected_line` has a match method it is called and must return True for a line in `text`.
# Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
# Otherwise `expected line` must simply occur in a line in `text`
# """
#
# assert isinstance(api_type, test_cfg.ApiType)
# assert text
# assert expected_lines
#
# return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
. Output only the next line. | assert lines_in( |
Using the snippet: <|code_start|>
def public_cli_url(api_type):
if api_type != ApiType.SCRIPT:
purl = os.environ.get('JENKINS_URL')
if purl:
return purl.rstrip('/') + '/jnlpJars/jenkins-cli.jar'
purl = os.environ.get('HUDSON_URL')
if purl:
return purl.rstrip('/') + '/jnlpJars/hudson-cli.jar'
# If neither JENKINS nor HUDSON URL is set, assume jenkins for testing
return "http://" + socket.getfqdn() + ':' + repr(8080) + '/jnlpJars/jenkins-cli.jar'
else:
return script_dir()
proxied_public_url = "http://myproxy.mydom/jenkins"
def proxied_public_cli_url(api_type):
# Not required to be a real url
if api_type != ApiType.SCRIPT:
# If neither JENKINS nor HUDSON URL is set, assume jenkins for testing
cli = '/jnlpJars/hudson-cli.jar' if os.environ.get('HUDSON_URL') else '/jnlpJars/jenkins-cli.jar'
return proxied_public_url + cli
else:
return script_dir()
def script_dir():
sdir = os.environ.get(SCRIPT_DIR_NAME)
<|code_end|>
, determine the next line of code. You have imports:
import os, socket
from enum import Enum
from .framework import config
and context (class names, function names, or code) available:
# Path: test/framework/config.py
. Output only the next line. | return config.job_script_dir if sdir is None else sdir.rstrip('/') |
Given snippet: <|code_start|>
_here = os.path.dirname(os.path.abspath(__file__))
def _clear_description(api, job):
if api.api_type == ApiType.SCRIPT:
# TODO: There is no build number concept for script api, so we need to ensure a clean start
description_file = jp(job.workspace, 'description.txt')
if os.path.exists(description_file):
os.remove(description_file)
def _get_description(api, job, build_number):
# Read back description and verify
if api.api_type == ApiType.JENKINS:
build_url = "/job/" + job.name + '/' + str(build_number)
dct = api.get_json(build_url, tree="description")
return dct['description']
if api.api_type == ApiType.SCRIPT:
with open(jp(job.workspace, 'description.txt')) as ff:
return ff.read()
if api.api_type == ApiType.MOCK:
raise Exception(repr(ApiType.MOCK) + " 'description' not supported by test framework")
@pytest.mark.not_apis(ApiType.MOCK)
def test_set_build_description_flow_set(api_type):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys, os
import subprocess
import pytest
from os.path import join as jp
from pytest import raises
from jenkinsflow.flow import serial
from jenkinsflow.utils.set_build_description import set_build_description
from jenkinsflow.cli.cli import cli
from .framework import api_select
from .framework.cfg import jenkins_security
from . import cfg as test_cfg
from .cfg import ApiType
and context:
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
which might include code, classes, or functions. Output only the next line. | with api_select.api(__file__, api_type, login=True) as api: |
Predict the next line for this snippet: <|code_start|> return _http_re.sub(r'http://x.x/job/\1\2', contains_url)
else:
return _http_re.sub(r'/tmp/jenkinsflow-test/job/\1.py', contains_url)
def lines_in(api_type, text, *expected_lines):
"""Assert that `*expected_lines` occur in order in the lines of `text`.
Args:
*expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
If `expected_line` has a match method it is called and must return True for a line in `text`.
Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
Otherwise `expected line` must simply occur in a line in `text`
"""
assert isinstance(api_type, test_cfg.ApiType)
assert text
assert expected_lines
return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
def flow_graph_dir(flow_name):
"""Control which directory to put flow graph in.
Put the generated graph in the workspace root if running from Jenkins.
If running from commandline put it under config.flow_graph_root_dir/flow_name
Return: dir-name
"""
<|code_end|>
with the help of current file imports:
import os, re, tempfile
from os.path import join as jp
from functools import partial
from jenkinsflow.test import cfg as test_cfg
from jenkinsflow.test.cfg import ApiType
from .config import flow_graph_root_dir
from .lines_in import lines_in as generic_lines_in
and context from other files:
# Path: test/framework/config.py
, which may contain function names, class names, or code. Output only the next line. | return '.' if os.environ.get('JOB_NAME') else jp(flow_graph_root_dir, flow_name) |
Using the snippet: <|code_start|>
here = os.path.abspath(os.path.dirname(__file__))
with open(jp(here, "just_dump_test_compact.json")) as _jf:
_compact_json = _jf.read().strip()
def _flow(api, json_dir):
if json_dir and not os.path.exists(json_dir):
os.makedirs(json_dir)
with serial(api, timeout=1, job_name_prefix=api.job_name_prefix, json_dir=json_dir, json_strip_top_level_prefix=True, just_dump=True) as ctrl1:
ctrl1.invoke('j1')
with ctrl1.parallel(timeout=40, report_interval=3) as ctrl2:
with ctrl2.serial(timeout=40, report_interval=3) as ctrl3a:
ctrl3a.invoke('j2')
ctrl3a.invoke_unchecked('j3_unchecked')
with ctrl2.parallel(timeout=40, report_interval=3) as ctrl3b:
ctrl3b.invoke('j4')
ctrl1.invoke('j5')
return ctrl1
def test_just_dump_no_json(api_type):
<|code_end|>
, determine the next line of code. You have imports:
import os
from os.path import join as jp
from jenkinsflow.flow import serial
from .framework import api_select
from .framework.utils import flow_graph_dir
from .json_test import _assert_json
and context (class names, function names, or code) available:
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def flow_graph_dir(flow_name):
# """Control which directory to put flow graph in.
#
# Put the generated graph in the workspace root if running from Jenkins.
# If running from commandline put it under config.flow_graph_root_dir/flow_name
#
# Return: dir-name
# """
# return '.' if os.environ.get('JOB_NAME') else jp(flow_graph_root_dir, flow_name)
#
# Path: test/json_test.py
# def _assert_json(got_json, expected_json, api_type):
# got_json = utils.replace_host_port(api_type, got_json)
# got_json = _timestamp_re.sub(r't": 12345.123', got_json)
#
# if api_type == ApiType.SCRIPT:
# expected_json = utils.replace_host_port(api_type, expected_json)
#
# if got_json.strip() != expected_json:
# if not os.environ.get('JOB_NAME'):
# print("--- expected json ---")
# print(expected_json)
# print("--- got json ---")
# print(got_json)
# assert got_json.strip() == expected_json
. Output only the next line. | with api_select.api(__file__, api_type, login=True) as api: |
Continue the code snippet: <|code_start|>
with ctrl2.parallel(timeout=40, report_interval=3) as ctrl3b:
ctrl3b.invoke('j4')
ctrl1.invoke('j5')
return ctrl1
def test_just_dump_no_json(api_type):
with api_select.api(__file__, api_type, login=True) as api:
api.flow_job()
api.job('j1', max_fails=0, expect_invocations=0, expect_order=None)
api.job('j2', max_fails=0, expect_invocations=0, expect_order=None)
api.job('j3_unchecked', max_fails=0, expect_invocations=0, expect_order=None, exec_time=40)
api.job('j4', max_fails=0, expect_invocations=0, expect_order=None, exec_time=5)
api.job('j5', max_fails=0, expect_invocations=0, expect_order=None, exec_time=5)
_flow(api, None)
def test_just_dump_with_json(api_type):
with api_select.api(__file__, api_type, login=True) as api:
flow_name = api.flow_job()
api.job('j1', max_fails=0, expect_invocations=0, expect_order=None)
api.job('j2', max_fails=0, expect_invocations=0, expect_order=None)
api.job('j3_unchecked', max_fails=0, expect_invocations=0, expect_order=None, exec_time=40)
api.job('j4', max_fails=0, expect_invocations=0, expect_order=None, exec_time=5)
api.job('j5', max_fails=0, expect_invocations=0, expect_order=None, exec_time=5)
<|code_end|>
. Use current file imports:
import os
from os.path import join as jp
from jenkinsflow.flow import serial
from .framework import api_select
from .framework.utils import flow_graph_dir
from .json_test import _assert_json
and context (classes, functions, or code) from other files:
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def flow_graph_dir(flow_name):
# """Control which directory to put flow graph in.
#
# Put the generated graph in the workspace root if running from Jenkins.
# If running from commandline put it under config.flow_graph_root_dir/flow_name
#
# Return: dir-name
# """
# return '.' if os.environ.get('JOB_NAME') else jp(flow_graph_root_dir, flow_name)
#
# Path: test/json_test.py
# def _assert_json(got_json, expected_json, api_type):
# got_json = utils.replace_host_port(api_type, got_json)
# got_json = _timestamp_re.sub(r't": 12345.123', got_json)
#
# if api_type == ApiType.SCRIPT:
# expected_json = utils.replace_host_port(api_type, expected_json)
#
# if got_json.strip() != expected_json:
# if not os.environ.get('JOB_NAME'):
# print("--- expected json ---")
# print(expected_json)
# print("--- got json ---")
# print(got_json)
# assert got_json.strip() == expected_json
. Output only the next line. | fgd = flow_graph_dir(flow_name) |
Given the code snippet: <|code_start|>
return ctrl1
def test_just_dump_no_json(api_type):
with api_select.api(__file__, api_type, login=True) as api:
api.flow_job()
api.job('j1', max_fails=0, expect_invocations=0, expect_order=None)
api.job('j2', max_fails=0, expect_invocations=0, expect_order=None)
api.job('j3_unchecked', max_fails=0, expect_invocations=0, expect_order=None, exec_time=40)
api.job('j4', max_fails=0, expect_invocations=0, expect_order=None, exec_time=5)
api.job('j5', max_fails=0, expect_invocations=0, expect_order=None, exec_time=5)
_flow(api, None)
def test_just_dump_with_json(api_type):
with api_select.api(__file__, api_type, login=True) as api:
flow_name = api.flow_job()
api.job('j1', max_fails=0, expect_invocations=0, expect_order=None)
api.job('j2', max_fails=0, expect_invocations=0, expect_order=None)
api.job('j3_unchecked', max_fails=0, expect_invocations=0, expect_order=None, exec_time=40)
api.job('j4', max_fails=0, expect_invocations=0, expect_order=None, exec_time=5)
api.job('j5', max_fails=0, expect_invocations=0, expect_order=None, exec_time=5)
fgd = flow_graph_dir(flow_name)
ctrl1 = _flow(api, fgd)
# Test json
json = ctrl1.json(None)
<|code_end|>
, generate the next line using the imports in this file:
import os
from os.path import join as jp
from jenkinsflow.flow import serial
from .framework import api_select
from .framework.utils import flow_graph_dir
from .json_test import _assert_json
and context (functions, classes, or occasionally code) from other files:
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def flow_graph_dir(flow_name):
# """Control which directory to put flow graph in.
#
# Put the generated graph in the workspace root if running from Jenkins.
# If running from commandline put it under config.flow_graph_root_dir/flow_name
#
# Return: dir-name
# """
# return '.' if os.environ.get('JOB_NAME') else jp(flow_graph_root_dir, flow_name)
#
# Path: test/json_test.py
# def _assert_json(got_json, expected_json, api_type):
# got_json = utils.replace_host_port(api_type, got_json)
# got_json = _timestamp_re.sub(r't": 12345.123', got_json)
#
# if api_type == ApiType.SCRIPT:
# expected_json = utils.replace_host_port(api_type, expected_json)
#
# if got_json.strip() != expected_json:
# if not os.environ.get('JOB_NAME'):
# print("--- expected json ---")
# print(expected_json)
# print("--- got json ---")
# print(got_json)
# assert got_json.strip() == expected_json
. Output only the next line. | _assert_json(json, _compact_json, api.api_type) |
Predict the next line after this snippet: <|code_start|># Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
def test_reporting_queued(api_type, capsys):
# TODO
skip_apis = (ApiType.SCRIPT, ApiType.MOCK)
with api_select.api(__file__, api_type, login=True) as api:
api.flow_job()
exp_invocations = 2 if api.api_type not in skip_apis else 1
unknown_result = False if api.api_type not in skip_apis else True
api.job('j1', max_fails=0, expect_invocations=exp_invocations, expect_order=None, exec_time=10, unknown_result=unknown_result)
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix) as ctrl1:
ctrl1.invoke_unchecked('j1')
print(api.api_type, type(api.api_type))
if api.api_type in skip_apis:
return
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix, require_idle=False) as ctrl1:
ctrl1.invoke('j1')
sout, _ = capsys.readouterr()
<|code_end|>
using the current file's imports:
from jenkinsflow.flow import serial
from .cfg import ApiType
from .framework import api_select
from .framework.utils import lines_in, build_started_msg, build_queued_msg
and any relevant context from other files:
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
#
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
# """Assert that `*expected_lines` occur in order in the lines of `text`.
#
# Args:
# *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
# If `expected_line` has a match method it is called and must return True for a line in `text`.
# Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
# Otherwise `expected line` must simply occur in a line in `text`
# """
#
# assert isinstance(api_type, test_cfg.ApiType)
# assert text
# assert expected_lines
#
# return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
#
# def build_started_msg(api, job_name, num, invocation_number=0):
# return "Build started: " + repr(job_name) + ((' Invocation-' + repr(invocation_number)) if invocation_number else '') + " - " + console_url(api, job_name, num)
#
# def build_queued_msg(api, job_name, num):
# if api.api_type == ApiType.MOCK:
# queued_why = r"Why am I queued\?"
# else:
# queued_why = r"Build #[0-9]+ is already in progress \(ETA: ?([0-9.]+ sec|N/A)\)"
# return re.compile("^job: '" + job_name + "' Status QUEUED - " + queued_why)
. Output only the next line. | assert lines_in( |
Using the snippet: <|code_start|># Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
def test_reporting_queued(api_type, capsys):
# TODO
skip_apis = (ApiType.SCRIPT, ApiType.MOCK)
with api_select.api(__file__, api_type, login=True) as api:
api.flow_job()
exp_invocations = 2 if api.api_type not in skip_apis else 1
unknown_result = False if api.api_type not in skip_apis else True
api.job('j1', max_fails=0, expect_invocations=exp_invocations, expect_order=None, exec_time=10, unknown_result=unknown_result)
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix) as ctrl1:
ctrl1.invoke_unchecked('j1')
print(api.api_type, type(api.api_type))
if api.api_type in skip_apis:
return
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix, require_idle=False) as ctrl1:
ctrl1.invoke('j1')
sout, _ = capsys.readouterr()
assert lines_in(
api_type, sout,
"^Job Invocation (1/1,1/1): http://x.x/job/jenkinsflow_test__reporting_queued__j1",
build_queued_msg(api, "jenkinsflow_test__reporting_queued__j1", 1),
<|code_end|>
, determine the next line of code. You have imports:
from jenkinsflow.flow import serial
from .cfg import ApiType
from .framework import api_select
from .framework.utils import lines_in, build_started_msg, build_queued_msg
and context (class names, function names, or code) available:
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
#
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
# """Assert that `*expected_lines` occur in order in the lines of `text`.
#
# Args:
# *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
# If `expected_line` has a match method it is called and must return True for a line in `text`.
# Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
# Otherwise `expected line` must simply occur in a line in `text`
# """
#
# assert isinstance(api_type, test_cfg.ApiType)
# assert text
# assert expected_lines
#
# return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
#
# def build_started_msg(api, job_name, num, invocation_number=0):
# return "Build started: " + repr(job_name) + ((' Invocation-' + repr(invocation_number)) if invocation_number else '') + " - " + console_url(api, job_name, num)
#
# def build_queued_msg(api, job_name, num):
# if api.api_type == ApiType.MOCK:
# queued_why = r"Why am I queued\?"
# else:
# queued_why = r"Build #[0-9]+ is already in progress \(ETA: ?([0-9.]+ sec|N/A)\)"
# return re.compile("^job: '" + job_name + "' Status QUEUED - " + queued_why)
. Output only the next line. | build_started_msg(api, "jenkinsflow_test__reporting_queued__j1", 2), |
Predict the next line for this snippet: <|code_start|># Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
def test_reporting_queued(api_type, capsys):
# TODO
skip_apis = (ApiType.SCRIPT, ApiType.MOCK)
with api_select.api(__file__, api_type, login=True) as api:
api.flow_job()
exp_invocations = 2 if api.api_type not in skip_apis else 1
unknown_result = False if api.api_type not in skip_apis else True
api.job('j1', max_fails=0, expect_invocations=exp_invocations, expect_order=None, exec_time=10, unknown_result=unknown_result)
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix) as ctrl1:
ctrl1.invoke_unchecked('j1')
print(api.api_type, type(api.api_type))
if api.api_type in skip_apis:
return
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix, require_idle=False) as ctrl1:
ctrl1.invoke('j1')
sout, _ = capsys.readouterr()
assert lines_in(
api_type, sout,
"^Job Invocation (1/1,1/1): http://x.x/job/jenkinsflow_test__reporting_queued__j1",
<|code_end|>
with the help of current file imports:
from jenkinsflow.flow import serial
from .cfg import ApiType
from .framework import api_select
from .framework.utils import lines_in, build_started_msg, build_queued_msg
and context from other files:
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
#
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
# """Assert that `*expected_lines` occur in order in the lines of `text`.
#
# Args:
# *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
# If `expected_line` has a match method it is called and must return True for a line in `text`.
# Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
# Otherwise `expected line` must simply occur in a line in `text`
# """
#
# assert isinstance(api_type, test_cfg.ApiType)
# assert text
# assert expected_lines
#
# return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
#
# def build_started_msg(api, job_name, num, invocation_number=0):
# return "Build started: " + repr(job_name) + ((' Invocation-' + repr(invocation_number)) if invocation_number else '') + " - " + console_url(api, job_name, num)
#
# def build_queued_msg(api, job_name, num):
# if api.api_type == ApiType.MOCK:
# queued_why = r"Why am I queued\?"
# else:
# queued_why = r"Build #[0-9]+ is already in progress \(ETA: ?([0-9.]+ sec|N/A)\)"
# return re.compile("^job: '" + job_name + "' Status QUEUED - " + queued_why)
, which may contain function names, class names, or code. Output only the next line. | build_queued_msg(api, "jenkinsflow_test__reporting_queued__j1", 1), |
Here is a snippet: <|code_start|>#!/usr/bin/env python3
# Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
# Allow relative imports while running as script. Necessary for testing without installing
if __package__ is None:
_here = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(1, os.path.dirname(os.path.dirname(_here)))
__package__ = "jenkinsflow.cli"
@click.group()
def cli():
"""Commandline utilities for jenkinsflow"""
pass
<|code_end|>
. Write the next line using the current file imports:
import sys, os
import click
import jenkinsflow.cli
from .set_build_description import set_build_description
and context from other files:
# Path: cli/set_build_description.py
# @click.command()
# @click.option('--description', help="The description to set on the build")
# @click.option('--replace/--no-replace', default=False, help="Replace existing description, if any, instead of appending.")
# @click.option('--separator', default='\n', help="A separator to insert between any existing description and the new 'description' if 'replace' is not specified.")
# @click.option('--username', help="User Name for Jenkin authentication with secured Jenkins")
# @click.option('--password', help="Password of Jenkins User")
# @click.option('--build-url', help='Build URL', envvar='BUILD_URL')
# @click.option('--job-name', help='Job Name', envvar='JOB_NAME')
# @click.option('--build-number', help="Build Number", type=click.INT, envvar='BUILD_NUMBER')
# @click.option(
# '--direct-url',
# default=None,
# help="Jenkins URL - preferably non-proxied. If not specified, the value of JENKINS_URL or HUDSON_URL environment variables will be used.")
# def set_build_description(description, replace, separator, username, password, build_url, job_name, build_number, direct_url):
# """Utility to set/append build description on a job build.
#
# When called from a Jenkins job you can leave out the '--build-url', '--job-name' and '--build-number' arguments, the BUILD_URL env variable will be used.
# """
#
# # %(file)s --job-name <job_name> --build-number <build_number> --description <description> [--direct-url <direct_url>] [--replace | --separator <separator>] [(--username <user_name> --password <password>)]
#
# usbd.set_build_description(description, replace, separator, username, password, build_url, job_name, build_number, direct_url)
, which may include functions, classes, or code. Output only the next line. | cli.add_command(set_build_description, name="set_build_description") |
Given the code snippet: <|code_start|> with raises(JobNotIdleException) as exinfo:
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix) as ctrl1:
ctrl1.invoke('j1')
assert "job: 'jenkinsflow_test__no_running_jobs__j1' is in state RUNNING. It must be IDLE." in str(exinfo.value)
def test_no_running_jobs_unchecked(api_type, capsys):
with api_select.api(__file__, api_type, login=True) as api:
api.flow_job()
api.job('j1', max_fails=0, expect_invocations=1, expect_order=None, exec_time=50, invocation_delay=0, unknown_result=True)
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix) as ctrl1:
ctrl1.invoke_unchecked('j1')
sout, _ = capsys.readouterr()
assert lines_in(api_type, sout, "unchecked job: 'jenkinsflow_test__no_running_jobs_unchecked__j1' UNKNOWN - RUNNING")
api.sleep(1)
with raises(JobNotIdleException) as exinfo:
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix) as ctrl1:
ctrl1.invoke_unchecked('j1')
assert "unchecked job: 'jenkinsflow_test__no_running_jobs_unchecked__j1' is in state RUNNING. It must be IDLE." in str(exinfo.value)
def test_no_running_jobs_jobs_allowed(api_type):
with api_select.api(__file__, api_type, login=True) as api:
api.flow_job()
<|code_end|>
, generate the next line using the imports in this file:
from pytest import raises
from jenkinsflow.flow import serial, JobNotIdleException
from .cfg import ApiType
from .framework import api_select
from .framework.utils import lines_in
and context (functions, classes, or occasionally code) from other files:
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
#
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
# """Assert that `*expected_lines` occur in order in the lines of `text`.
#
# Args:
# *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
# If `expected_line` has a match method it is called and must return True for a line in `text`.
# Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
# Otherwise `expected line` must simply occur in a line in `text`
# """
#
# assert isinstance(api_type, test_cfg.ApiType)
# assert text
# assert expected_lines
#
# return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
. Output only the next line. | exp_invocations = 2 if api.api_type != ApiType.MOCK else 1 |
Given snippet: <|code_start|># Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
def test_no_running_jobs(api_type, capsys):
with api_select.api(__file__, api_type, login=True) as api:
api.flow_job()
api.job('j1', max_fails=0, expect_invocations=1, expect_order=None, exec_time=50, invocation_delay=0, unknown_result=True)
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix) as ctrl1:
ctrl1.invoke_unchecked('j1')
sout, _ = capsys.readouterr()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pytest import raises
from jenkinsflow.flow import serial, JobNotIdleException
from .cfg import ApiType
from .framework import api_select
from .framework.utils import lines_in
and context:
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
#
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
# """Assert that `*expected_lines` occur in order in the lines of `text`.
#
# Args:
# *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
# If `expected_line` has a match method it is called and must return True for a line in `text`.
# Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
# Otherwise `expected line` must simply occur in a line in `text`
# """
#
# assert isinstance(api_type, test_cfg.ApiType)
# assert text
# assert expected_lines
#
# return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
which might include code, classes, or functions. Output only the next line. | assert lines_in(api_type, sout, "unchecked job: 'jenkinsflow_test__no_running_jobs__j1' UNKNOWN - RUNNING") |
Next line prediction: <|code_start|># Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
def test_messages(api_type, capsys):
with api_select.api(__file__, api_type) as api:
api.flow_job()
api.job('j11', max_fails=0, expect_invocations=1, invocation_delay=1.0, expect_order=1, serial=True)
api.job('j21', max_fails=0, expect_invocations=1, invocation_delay=1.0, expect_order=2, serial=True)
api.job('j12', max_fails=0, expect_invocations=1, invocation_delay=1.0, expect_order=3, serial=True)
api.job('j22', max_fails=0, expect_invocations=1, invocation_delay=1.0, expect_order=4)
api.job('j23', max_fails=0, expect_invocations=1, invocation_delay=1.0, exec_time=2.00, expect_order=4)
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix) as ctrl1:
ctrl1.invoke('j11')
with ctrl1.serial() as sctrl2:
sctrl2.message("**** Message 1 ****")
sctrl2.invoke('j21')
ctrl1.invoke('j12')
with ctrl1.parallel() as pctrl:
pctrl.message("==== Message 2 ====")
pctrl.invoke('j22')
pctrl.invoke('j23')
sout, _ = capsys.readouterr()
print(sout)
<|code_end|>
. Use current file imports:
(from pytest import raises
from jenkinsflow.flow import serial, MessageRedefinedException
from .framework import api_select
from .framework.utils import lines_in, result_msg)
and context including class names, function names, or small code snippets from other files:
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
# """Assert that `*expected_lines` occur in order in the lines of `text`.
#
# Args:
# *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
# If `expected_line` has a match method it is called and must return True for a line in `text`.
# Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
# Otherwise `expected line` must simply occur in a line in `text`
# """
#
# assert isinstance(api_type, test_cfg.ApiType)
# assert text
# assert expected_lines
#
# return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
#
# def result_msg(api, job_name, num=None):
# if api.api_type == ApiType.SCRIPT:
# return repr(job_name) + " - build: " + _script_api_log_file(job_name)
# return repr(job_name) + " - build: http://x.x/job/" + job_name + "/" + (str(num) + "/console" if api.api_type == ApiType.MOCK and num else "")
. Output only the next line. | assert lines_in( |
Predict the next line after this snippet: <|code_start|>
def test_messages(api_type, capsys):
with api_select.api(__file__, api_type) as api:
api.flow_job()
api.job('j11', max_fails=0, expect_invocations=1, invocation_delay=1.0, expect_order=1, serial=True)
api.job('j21', max_fails=0, expect_invocations=1, invocation_delay=1.0, expect_order=2, serial=True)
api.job('j12', max_fails=0, expect_invocations=1, invocation_delay=1.0, expect_order=3, serial=True)
api.job('j22', max_fails=0, expect_invocations=1, invocation_delay=1.0, expect_order=4)
api.job('j23', max_fails=0, expect_invocations=1, invocation_delay=1.0, exec_time=2.00, expect_order=4)
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix) as ctrl1:
ctrl1.invoke('j11')
with ctrl1.serial() as sctrl2:
sctrl2.message("**** Message 1 ****")
sctrl2.invoke('j21')
ctrl1.invoke('j12')
with ctrl1.parallel() as pctrl:
pctrl.message("==== Message 2 ====")
pctrl.invoke('j22')
pctrl.invoke('j23')
sout, _ = capsys.readouterr()
print(sout)
assert lines_in(
api_type, sout,
"^--- Starting flow ---",
"^Flow Invocation (1/1,1/1): ['jenkinsflow_test__messages__j11', ['jenkinsflow_test__messages__j21'], 'jenkinsflow_test__messages__j12', (",
"^Job Invocation (1/1,1/1): http://x.x/job/jenkinsflow_test__messages__j11",
<|code_end|>
using the current file's imports:
from pytest import raises
from jenkinsflow.flow import serial, MessageRedefinedException
from .framework import api_select
from .framework.utils import lines_in, result_msg
and any relevant context from other files:
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
# """Assert that `*expected_lines` occur in order in the lines of `text`.
#
# Args:
# *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
# If `expected_line` has a match method it is called and must return True for a line in `text`.
# Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
# Otherwise `expected line` must simply occur in a line in `text`
# """
#
# assert isinstance(api_type, test_cfg.ApiType)
# assert text
# assert expected_lines
#
# return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
#
# def result_msg(api, job_name, num=None):
# if api.api_type == ApiType.SCRIPT:
# return repr(job_name) + " - build: " + _script_api_log_file(job_name)
# return repr(job_name) + " - build: http://x.x/job/" + job_name + "/" + (str(num) + "/console" if api.api_type == ApiType.MOCK and num else "")
. Output only the next line. | "^SUCCESS: " + result_msg(api, "jenkinsflow_test__messages__j11"), |
Continue the code snippet: <|code_start|># Copyright (c) 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
here = os.path.abspath(os.path.dirname(__file__))
@bottle.route('/')
def _index():
return bottle.static_file('which_ci_server.html', root=here)
@bottle.route('/api/json')
def _api():
return bottle.static_file('which_ci_server.html', root=here)
_host = 'localhost'
_port = 8082
def _server():
bottle.run(host=_host, port=_port, debug=True)
<|code_end|>
. Use current file imports:
import os, multiprocessing
import time
import bottle
import requests
import pytest
from pytest import raises
from jenkinsflow import jenkins_api
from .cfg import ApiType
from .framework import api_select
from .framework.utils import lines_in
and context (classes, functions, or code) from other files:
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
#
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
# """Assert that `*expected_lines` occur in order in the lines of `text`.
#
# Args:
# *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
# If `expected_line` has a match method it is called and must return True for a line in `text`.
# Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
# Otherwise `expected line` must simply occur in a line in `text`
# """
#
# assert isinstance(api_type, test_cfg.ApiType)
# assert text
# assert expected_lines
#
# return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
. Output only the next line. | @pytest.mark.apis(ApiType.JENKINS) |
Predict the next line after this snippet: <|code_start|>
here = os.path.abspath(os.path.dirname(__file__))
@bottle.route('/')
def _index():
return bottle.static_file('which_ci_server.html', root=here)
@bottle.route('/api/json')
def _api():
return bottle.static_file('which_ci_server.html', root=here)
_host = 'localhost'
_port = 8082
def _server():
bottle.run(host=_host, port=_port, debug=True)
@pytest.mark.apis(ApiType.JENKINS)
def test_which_ci_server_not_ci(api_type):
proc = None
try:
<|code_end|>
using the current file's imports:
import os, multiprocessing
import time
import bottle
import requests
import pytest
from pytest import raises
from jenkinsflow import jenkins_api
from .cfg import ApiType
from .framework import api_select
from .framework.utils import lines_in
and any relevant context from other files:
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
#
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
# """Assert that `*expected_lines` occur in order in the lines of `text`.
#
# Args:
# *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
# If `expected_line` has a match method it is called and must return True for a line in `text`.
# Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
# Otherwise `expected line` must simply occur in a line in `text`
# """
#
# assert isinstance(api_type, test_cfg.ApiType)
# assert text
# assert expected_lines
#
# return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
. Output only the next line. | with api_select.api(__file__, api_type): |
Given snippet: <|code_start|>def _api():
return bottle.static_file('which_ci_server.html', root=here)
_host = 'localhost'
_port = 8082
def _server():
bottle.run(host=_host, port=_port, debug=True)
@pytest.mark.apis(ApiType.JENKINS)
def test_which_ci_server_not_ci(api_type):
proc = None
try:
with api_select.api(__file__, api_type):
proc = multiprocessing.Process(target=_server)
proc.start()
with raises(Exception) as exinfo:
for _ in range(0, 10):
ex = None
try:
jenkins_api.Jenkins("http://" + _host + ':' + repr(_port), "dummy").poll()
except requests.exceptions.ConnectionError as ex:
# Wait for bottle to start
print(ex)
time.sleep(0.1)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os, multiprocessing
import time
import bottle
import requests
import pytest
from pytest import raises
from jenkinsflow import jenkins_api
from .cfg import ApiType
from .framework import api_select
from .framework.utils import lines_in
and context:
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
#
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
# """Assert that `*expected_lines` occur in order in the lines of `text`.
#
# Args:
# *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
# If `expected_line` has a match method it is called and must return True for a line in `text`.
# Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
# Otherwise `expected line` must simply occur in a line in `text`
# """
#
# assert isinstance(api_type, test_cfg.ApiType)
# assert text
# assert expected_lines
#
# return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
which might include code, classes, or functions. Output only the next line. | assert lines_in( |
Based on the snippet: <|code_start|> print("--- got json ---")
print(got_json)
assert got_json.strip() == expected_json
def _flow(api, strip_prefix, json_dir):
if not os.path.exists(json_dir):
os.makedirs(json_dir)
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix, report_interval=1, json_dir=json_dir, json_strip_top_level_prefix=strip_prefix) as ctrl1:
ctrl1.invoke('j1')
ctrl1.invoke('j2')
with ctrl1.parallel(timeout=40, report_interval=3) as ctrl2:
with ctrl2.serial(timeout=40, report_interval=3) as ctrl3a:
ctrl3a.invoke('j3')
ctrl3a.invoke('j6')
ctrl3a.invoke_unchecked('j7_unchecked')
with ctrl2.parallel(timeout=40, report_interval=3) as ctrl3b:
ctrl3b.invoke('j4')
ctrl3b.invoke('j5')
ctrl3b.invoke_unchecked('j8_unchecked')
ctrl1.invoke('j9')
return ctrl1
def test_json_strip_prefix(api_type):
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import re
from os.path import join as jp
from jenkinsflow.flow import serial
from .framework import api_select, utils
from .framework.utils import flow_graph_dir
from .cfg import ApiType
and context (classes, functions, sometimes code) from other files:
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def _script_api_log_file(job_name):
# def console_url(api, job_name, num):
# def result_msg(api, job_name, num=None):
# def build_started_msg(api, job_name, num, invocation_number=0):
# def kill_current_msg(api, job_name, num):
# def build_queued_msg(api, job_name, num):
# def replace_host_port(api_type, contains_url):
# def lines_in(api_type, text, *expected_lines):
# def flow_graph_dir(flow_name):
#
# Path: test/framework/utils.py
# def flow_graph_dir(flow_name):
# """Control which directory to put flow graph in.
#
# Put the generated graph in the workspace root if running from Jenkins.
# If running from commandline put it under config.flow_graph_root_dir/flow_name
#
# Return: dir-name
# """
# return '.' if os.environ.get('JOB_NAME') else jp(flow_graph_root_dir, flow_name)
#
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
. Output only the next line. | with api_select.api(__file__, api_type, login=True) as api: |
Given snippet: <|code_start|># Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
here = os.path.abspath(os.path.dirname(__file__))
_timestamp_re = re.compile(r't": [0-9]+.[0-9]+')
with open(jp(here, "json_test_compact.json")) as _jf:
_compact_json = _jf.read().strip()
with open(jp(here, "json_test_pretty.json")) as _jf:
_pretty_json = _jf.read().strip()
def _assert_json(got_json, expected_json, api_type):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import re
from os.path import join as jp
from jenkinsflow.flow import serial
from .framework import api_select, utils
from .framework.utils import flow_graph_dir
from .cfg import ApiType
and context:
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def _script_api_log_file(job_name):
# def console_url(api, job_name, num):
# def result_msg(api, job_name, num=None):
# def build_started_msg(api, job_name, num, invocation_number=0):
# def kill_current_msg(api, job_name, num):
# def build_queued_msg(api, job_name, num):
# def replace_host_port(api_type, contains_url):
# def lines_in(api_type, text, *expected_lines):
# def flow_graph_dir(flow_name):
#
# Path: test/framework/utils.py
# def flow_graph_dir(flow_name):
# """Control which directory to put flow graph in.
#
# Put the generated graph in the workspace root if running from Jenkins.
# If running from commandline put it under config.flow_graph_root_dir/flow_name
#
# Return: dir-name
# """
# return '.' if os.environ.get('JOB_NAME') else jp(flow_graph_root_dir, flow_name)
#
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
which might include code, classes, or functions. Output only the next line. | got_json = utils.replace_host_port(api_type, got_json) |
Given the code snippet: <|code_start|>
with ctrl1.parallel(timeout=40, report_interval=3) as ctrl2:
with ctrl2.serial(timeout=40, report_interval=3) as ctrl3a:
ctrl3a.invoke('j3')
ctrl3a.invoke('j6')
ctrl3a.invoke_unchecked('j7_unchecked')
with ctrl2.parallel(timeout=40, report_interval=3) as ctrl3b:
ctrl3b.invoke('j4')
ctrl3b.invoke('j5')
ctrl3b.invoke_unchecked('j8_unchecked')
ctrl1.invoke('j9')
return ctrl1
def test_json_strip_prefix(api_type):
with api_select.api(__file__, api_type, login=True) as api:
flow_name = api.flow_job()
api.job('j1', max_fails=0, expect_invocations=1, expect_order=1)
api.job('j2', max_fails=0, expect_invocations=1, expect_order=2)
api.job('j3', max_fails=0, expect_invocations=1, expect_order=3)
api.job('j4', max_fails=0, expect_invocations=1, expect_order=3)
api.job('j5', max_fails=0, expect_invocations=1, expect_order=3)
api.job('j6', max_fails=0, expect_invocations=1, expect_order=3)
api.job('j7_unchecked', max_fails=0, expect_invocations=1, invocation_delay=0, exec_time=40, expect_order=None, unknown_result=True)
api.job('j8_unchecked', max_fails=0, expect_invocations=1, invocation_delay=0, exec_time=40, expect_order=None, unknown_result=True)
api.job('j9', max_fails=0, expect_invocations=1, expect_order=4, exec_time=5)
<|code_end|>
, generate the next line using the imports in this file:
import os
import re
from os.path import join as jp
from jenkinsflow.flow import serial
from .framework import api_select, utils
from .framework.utils import flow_graph_dir
from .cfg import ApiType
and context (functions, classes, or occasionally code) from other files:
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def _script_api_log_file(job_name):
# def console_url(api, job_name, num):
# def result_msg(api, job_name, num=None):
# def build_started_msg(api, job_name, num, invocation_number=0):
# def kill_current_msg(api, job_name, num):
# def build_queued_msg(api, job_name, num):
# def replace_host_port(api_type, contains_url):
# def lines_in(api_type, text, *expected_lines):
# def flow_graph_dir(flow_name):
#
# Path: test/framework/utils.py
# def flow_graph_dir(flow_name):
# """Control which directory to put flow graph in.
#
# Put the generated graph in the workspace root if running from Jenkins.
# If running from commandline put it under config.flow_graph_root_dir/flow_name
#
# Return: dir-name
# """
# return '.' if os.environ.get('JOB_NAME') else jp(flow_graph_root_dir, flow_name)
#
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
. Output only the next line. | ctrl1 = _flow(api, True, flow_graph_dir(flow_name)) |
Using the snippet: <|code_start|># Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
here = os.path.abspath(os.path.dirname(__file__))
_timestamp_re = re.compile(r't": [0-9]+.[0-9]+')
with open(jp(here, "json_test_compact.json")) as _jf:
_compact_json = _jf.read().strip()
with open(jp(here, "json_test_pretty.json")) as _jf:
_pretty_json = _jf.read().strip()
def _assert_json(got_json, expected_json, api_type):
got_json = utils.replace_host_port(api_type, got_json)
got_json = _timestamp_re.sub(r't": 12345.123', got_json)
<|code_end|>
, determine the next line of code. You have imports:
import os
import re
from os.path import join as jp
from jenkinsflow.flow import serial
from .framework import api_select, utils
from .framework.utils import flow_graph_dir
from .cfg import ApiType
and context (class names, function names, or code) available:
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def _script_api_log_file(job_name):
# def console_url(api, job_name, num):
# def result_msg(api, job_name, num=None):
# def build_started_msg(api, job_name, num, invocation_number=0):
# def kill_current_msg(api, job_name, num):
# def build_queued_msg(api, job_name, num):
# def replace_host_port(api_type, contains_url):
# def lines_in(api_type, text, *expected_lines):
# def flow_graph_dir(flow_name):
#
# Path: test/framework/utils.py
# def flow_graph_dir(flow_name):
# """Control which directory to put flow graph in.
#
# Put the generated graph in the workspace root if running from Jenkins.
# If running from commandline put it under config.flow_graph_root_dir/flow_name
#
# Return: dir-name
# """
# return '.' if os.environ.get('JOB_NAME') else jp(flow_graph_root_dir, flow_name)
#
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
. Output only the next line. | if api_type == ApiType.SCRIPT: |
Here is a snippet: <|code_start|># Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
def test_missing_jobs_not_allowed(api_type):
with api_select.api(__file__, api_type) as api:
api.flow_job()
api.job('j1', max_fails=0, expect_invocations=0, expect_order=None)
api.job('j2', max_fails=0, expect_invocations=0, expect_order=None)
with raises(MissingJobsException) as exinfo:
with serial(api, 20, job_name_prefix=api.job_name_prefix) as ctrl1:
ctrl1.invoke('j1')
ctrl1.invoke('missingA')
ctrl1.invoke('j2')
<|code_end|>
. Write the next line using the current file imports:
import re
import pytest
from pytest import raises
from jenkinsflow.flow import parallel, serial, MissingJobsException, FailedChildJobsException, FailedChildJobException, UnknownJobException
from .framework import api_select
from .framework.utils import lines_in
from .cfg import ApiType
and context from other files:
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
# """Assert that `*expected_lines` occur in order in the lines of `text`.
#
# Args:
# *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
# If `expected_line` has a match method it is called and must return True for a line in `text`.
# Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
# Otherwise `expected line` must simply occur in a line in `text`
# """
#
# assert isinstance(api_type, test_cfg.ApiType)
# assert text
# assert expected_lines
#
# return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
#
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
, which may include functions, classes, or code. Output only the next line. | assert lines_in( |
Here is a snippet: <|code_start|>
def test_missing_jobs_allowed_still_missing_serial(api_type):
with api_select.api(__file__, api_type) as api:
api.flow_job()
api.job('j1', max_fails=0, expect_invocations=1, expect_order=1)
api.job('j2', max_fails=0, expect_invocations=0, expect_order=None)
with raises(FailedChildJobException):
with serial(api, 20, job_name_prefix=api.job_name_prefix, allow_missing_jobs=True) as ctrl1:
ctrl1.invoke('j1')
ctrl1.invoke('missingA')
ctrl1.invoke('j2')
def test_missing_jobs_allowed_still_missing_parallel_serial(api_type):
with api_select.api(__file__, api_type) as api:
api.flow_job()
api.job('j1', max_fails=0, expect_invocations=1, expect_order=1)
api.job('j2', max_fails=0, expect_invocations=0, expect_order=None)
with raises(FailedChildJobsException):
with parallel(api, 20, job_name_prefix=api.job_name_prefix, allow_missing_jobs=True) as ctrl1:
ctrl1.invoke('j1')
ctrl1.invoke('missingA')
with ctrl1.serial() as ctrl2:
ctrl2.invoke('missingB')
ctrl2.invoke('j2')
ctrl1.invoke('missingC')
<|code_end|>
. Write the next line using the current file imports:
import re
import pytest
from pytest import raises
from jenkinsflow.flow import parallel, serial, MissingJobsException, FailedChildJobsException, FailedChildJobException, UnknownJobException
from .framework import api_select
from .framework.utils import lines_in
from .cfg import ApiType
and context from other files:
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
# """Assert that `*expected_lines` occur in order in the lines of `text`.
#
# Args:
# *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
# If `expected_line` has a match method it is called and must return True for a line in `text`.
# Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
# Otherwise `expected line` must simply occur in a line in `text`
# """
#
# assert isinstance(api_type, test_cfg.ApiType)
# assert text
# assert expected_lines
#
# return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
#
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
, which may include functions, classes, or code. Output only the next line. | @pytest.mark.not_apis(ApiType.SCRIPT) # TODO: Handle ApiType.SCRIPT |
Based on the snippet: <|code_start|># Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
_here = os.path.dirname(os.path.abspath(__file__))
def _verify_description(api, job, build_number, expected):
if api.api_type == ApiType.MOCK:
return
# Read back description and verify
if api.api_type == ApiType.JENKINS:
build_url = "/job/" + job.name + '/' + str(build_number)
dct = api.get_json(build_url, tree="description")
description = dct['description']
if api.api_type == ApiType.SCRIPT:
with codecs.open(jp(job.workspace, 'description.txt'), encoding='utf-8') as ff:
description = ff.read()
assert description == expected
def test_set_build_description_unicode_set_build_description_util(api_type):
<|code_end|>
, predict the immediate next line with the help of imports:
import codecs, os
from os.path import join as jp
from jenkinsflow.flow import serial
from .framework import api_select
from .cfg import ApiType
from .set_build_description_test import _clear_description
and context (classes, functions, sometimes code) from other files:
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
#
# Path: test/set_build_description_test.py
# def _clear_description(api, job):
# if api.api_type == ApiType.SCRIPT:
# # TODO: There is no build number concept for script api, so we need to ensure a clean start
# description_file = jp(job.workspace, 'description.txt')
# if os.path.exists(description_file):
# os.remove(description_file)
. Output only the next line. | with api_select.api(__file__, api_type, login=True) as api: |
Given the code snippet: <|code_start|>
def _verify_description(api, job, build_number, expected):
if api.api_type == ApiType.MOCK:
return
# Read back description and verify
if api.api_type == ApiType.JENKINS:
build_url = "/job/" + job.name + '/' + str(build_number)
dct = api.get_json(build_url, tree="description")
description = dct['description']
if api.api_type == ApiType.SCRIPT:
with codecs.open(jp(job.workspace, 'description.txt'), encoding='utf-8') as ff:
description = ff.read()
assert description == expected
def test_set_build_description_unicode_set_build_description_util(api_type):
with api_select.api(__file__, api_type, login=True) as api:
api.flow_job()
job_name = 'job-1'
api.job(job_name, max_fails=0, expect_invocations=1, expect_order=1)
# Need to read the build number
if api.api_type == ApiType.SCRIPT:
# TODO: This can't be called here for Jenkins API. Why?
job = api.get_job(api.job_name_prefix + job_name)
<|code_end|>
, generate the next line using the imports in this file:
import codecs, os
from os.path import join as jp
from jenkinsflow.flow import serial
from .framework import api_select
from .cfg import ApiType
from .set_build_description_test import _clear_description
and context (functions, classes, or occasionally code) from other files:
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
#
# Path: test/set_build_description_test.py
# def _clear_description(api, job):
# if api.api_type == ApiType.SCRIPT:
# # TODO: There is no build number concept for script api, so we need to ensure a clean start
# description_file = jp(job.workspace, 'description.txt')
# if os.path.exists(description_file):
# os.remove(description_file)
. Output only the next line. | _clear_description(api, job) |
Given snippet: <|code_start|># Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
@pytest.mark.not_apis(ApiType.MOCK)
def test_replace_invocation_class_log_override(api_type, capsys):
if api_type == ApiType.JENKINS:
class LogInvocation(Invocation):
def console_url(self):
return "HELLO LOG"
elif api_type == ApiType.SCRIPT:
class LogInvocation(Invocation):
def console_url(self):
return "HELLO LOG"
else:
raise Exception("Invalid ApiType: " + repr(api_type))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from jenkinsflow.flow import parallel
from .framework import api_select
from .cfg import ApiType
from jenkinsflow.jenkins_api import Invocation
from jenkinsflow.script_api import Invocation
and context:
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
which might include code, classes, or functions. Output only the next line. | with api_select.api(__file__, api_type, invocation_class=LogInvocation) as api: |
Predict the next line for this snippet: <|code_start|># Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
def _mkdir(path):
try:
os.mkdir(path)
except OSError:
if not os.path.exists(path):
raise
<|code_end|>
with the help of current file imports:
import abc
import os
from collections import OrderedDict
from os.path import join as jp
from jenkinsflow.api_base import UnknownJobException, BuildResult, Progress
from .abstract_api import AbstractApiJob, AbstractApiJenkins
from .config import test_tmp_dir
and context from other files:
# Path: test/framework/abstract_api.py
# class AbstractApiJob(metaclass=abc.ABCMeta):
# @abc.abstractmethod
# def invoke(self, securitytoken, build_params, cause, description):
# raise Exception("AbstractNotImplemented")
#
# # The following should be declare abstract, but since they are 'implemented' by proxy we can't do that (conveniently)
# # def is_running(self):
# # def is_queued(self):
# # def get_last_build_or_none(self):
# # def get_build_triggerurl(self):
# # def update_config(self, config_xml):
# # def poll(self):
#
# class AbstractApiJenkins(metaclass=abc.ABCMeta):
# @abc.abstractmethod
# def create_job(self, job_name, config_xml):
# raise Exception("AbstractNotImplemented")
#
# @abc.abstractmethod
# def delete_job(self, job_name):
# raise Exception("AbstractNotImplemented")
#
# @abc.abstractmethod
# def get_job(self, name):
# raise Exception("AbstractNotImplemented")
#
# @abc.abstractmethod
# def poll(self):
# raise Exception("AbstractNotImplemented")
#
# Path: test/framework/config.py
, which may contain function names, class names, or code. Output only the next line. | class TestJob(AbstractApiJob, metaclass=abc.ABCMeta): |
Continue the code snippet: <|code_start|>
class Jobs():
def __init__(self, api):
self.api = api
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type:
return None
test_jobs = self.api.test_jobs
for job_name, job in test_jobs.items():
if job.flow_created:
# Patch up another job that is supposed to be created by this job - replace job_name with job reference
for other_job in test_jobs.values():
if isinstance(other_job.create_job, str):
other_job_name = self.api.job_name_prefix + other_job.create_job
if other_job_name == job_name:
other_job.create_job = job
break
else:
raise Exception("Job: " + repr(job_name) + " is supposed to be created by another job, but that job was not found")
for job_name, job in test_jobs.items():
if job.create_job and isinstance(job.create_job, str):
raise Exception("Job: " + repr(job_name) + " is supposed to create job: " + repr(job.create_job) + " but definition for that job was not found")
<|code_end|>
. Use current file imports:
import abc
import os
from collections import OrderedDict
from os.path import join as jp
from jenkinsflow.api_base import UnknownJobException, BuildResult, Progress
from .abstract_api import AbstractApiJob, AbstractApiJenkins
from .config import test_tmp_dir
and context (classes, functions, or code) from other files:
# Path: test/framework/abstract_api.py
# class AbstractApiJob(metaclass=abc.ABCMeta):
# @abc.abstractmethod
# def invoke(self, securitytoken, build_params, cause, description):
# raise Exception("AbstractNotImplemented")
#
# # The following should be declare abstract, but since they are 'implemented' by proxy we can't do that (conveniently)
# # def is_running(self):
# # def is_queued(self):
# # def get_last_build_or_none(self):
# # def get_build_triggerurl(self):
# # def update_config(self, config_xml):
# # def poll(self):
#
# class AbstractApiJenkins(metaclass=abc.ABCMeta):
# @abc.abstractmethod
# def create_job(self, job_name, config_xml):
# raise Exception("AbstractNotImplemented")
#
# @abc.abstractmethod
# def delete_job(self, job_name):
# raise Exception("AbstractNotImplemented")
#
# @abc.abstractmethod
# def get_job(self, name):
# raise Exception("AbstractNotImplemented")
#
# @abc.abstractmethod
# def poll(self):
# raise Exception("AbstractNotImplemented")
#
# Path: test/framework/config.py
. Output only the next line. | class TestJenkins(AbstractApiJenkins, metaclass=abc.ABCMeta): |
Predict the next line after this snippet: <|code_start|> try:
job = self.test_jobs[job_name]
if job.non_existing:
raise UnknownJobException(job_name)
job.non_existing = True
except KeyError as ex:
raise Exception("Test job setup error, missing test job definition:", job_name) from ex
def create_job(self, job_name, config_xml):
try:
job = self.test_jobs[job_name]
job.non_existing = False
except KeyError as ex:
raise Exception("Test job setup error, missing test job definition:", job_name) from ex
def job_creator(self):
return Jobs(self)
@abc.abstractmethod
def flow_job(self, name=None, params=None):
pass
def flow_job_name(self, name):
# Don't create flow jobs when mocked
name = '0flow_' + name if name else '0flow'
return (self.job_name_prefix or '') + name
def __enter__(self):
# pylint: disable=attribute-defined-outside-init
self._pre_work_dir = os.getcwd()
<|code_end|>
using the current file's imports:
import abc
import os
from collections import OrderedDict
from os.path import join as jp
from jenkinsflow.api_base import UnknownJobException, BuildResult, Progress
from .abstract_api import AbstractApiJob, AbstractApiJenkins
from .config import test_tmp_dir
and any relevant context from other files:
# Path: test/framework/abstract_api.py
# class AbstractApiJob(metaclass=abc.ABCMeta):
# @abc.abstractmethod
# def invoke(self, securitytoken, build_params, cause, description):
# raise Exception("AbstractNotImplemented")
#
# # The following should be declare abstract, but since they are 'implemented' by proxy we can't do that (conveniently)
# # def is_running(self):
# # def is_queued(self):
# # def get_last_build_or_none(self):
# # def get_build_triggerurl(self):
# # def update_config(self, config_xml):
# # def poll(self):
#
# class AbstractApiJenkins(metaclass=abc.ABCMeta):
# @abc.abstractmethod
# def create_job(self, job_name, config_xml):
# raise Exception("AbstractNotImplemented")
#
# @abc.abstractmethod
# def delete_job(self, job_name):
# raise Exception("AbstractNotImplemented")
#
# @abc.abstractmethod
# def get_job(self, name):
# raise Exception("AbstractNotImplemented")
#
# @abc.abstractmethod
# def poll(self):
# raise Exception("AbstractNotImplemented")
#
# Path: test/framework/config.py
. Output only the next line. | self._work_dir = jp(test_tmp_dir,self.job_name_prefix) |
Predict the next line for this snippet: <|code_start|># Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
def test_reporting_job_status(api_type, capsys):
with api_select.api(__file__, api_type) as api:
api.flow_job()
api.job('j11', max_fails=0, expect_invocations=1, expect_order=1)
api.job('j12', max_fails=0, expect_invocations=1, invocation_delay=1.0, exec_time=1.5, initial_buildno=7, expect_order=2, serial=True)
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix, report_interval=0.5/api.speedup) as ctrl1:
ctrl1.invoke('j11')
ctrl1.invoke('j12')
sout, _ = capsys.readouterr()
<|code_end|>
with the help of current file imports:
import re
from pytest import raises
from jenkinsflow.flow import serial, parallel, FailedChildJobException
from .cfg import ApiType
from .framework import api_select
from .framework.utils import lines_in, replace_host_port, result_msg, build_started_msg
and context from other files:
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
#
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
# """Assert that `*expected_lines` occur in order in the lines of `text`.
#
# Args:
# *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
# If `expected_line` has a match method it is called and must return True for a line in `text`.
# Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
# Otherwise `expected line` must simply occur in a line in `text`
# """
#
# assert isinstance(api_type, test_cfg.ApiType)
# assert text
# assert expected_lines
#
# return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
#
# def replace_host_port(api_type, contains_url):
# if api_type != ApiType.SCRIPT:
# return _http_re.sub(r'http://x.x/job/\1\2', contains_url)
# else:
# return _http_re.sub(r'/tmp/jenkinsflow-test/job/\1.py', contains_url)
#
# def result_msg(api, job_name, num=None):
# if api.api_type == ApiType.SCRIPT:
# return repr(job_name) + " - build: " + _script_api_log_file(job_name)
# return repr(job_name) + " - build: http://x.x/job/" + job_name + "/" + (str(num) + "/console" if api.api_type == ApiType.MOCK and num else "")
#
# def build_started_msg(api, job_name, num, invocation_number=0):
# return "Build started: " + repr(job_name) + ((' Invocation-' + repr(invocation_number)) if invocation_number else '') + " - " + console_url(api, job_name, num)
, which may contain function names, class names, or code. Output only the next line. | if api.api_type == ApiType.MOCK: |
Here is a snippet: <|code_start|># Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
def test_reporting_job_status(api_type, capsys):
with api_select.api(__file__, api_type) as api:
api.flow_job()
api.job('j11', max_fails=0, expect_invocations=1, expect_order=1)
api.job('j12', max_fails=0, expect_invocations=1, invocation_delay=1.0, exec_time=1.5, initial_buildno=7, expect_order=2, serial=True)
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix, report_interval=0.5/api.speedup) as ctrl1:
ctrl1.invoke('j11')
ctrl1.invoke('j12')
sout, _ = capsys.readouterr()
if api.api_type == ApiType.MOCK:
repr_not_invoked = "job: 'jenkinsflow_test__reporting_job_status__j11' Status IDLE - latest build: "
assert repr_not_invoked in sout, repr_not_invoked + "\n - NOT FOUND IN:\n" + sout
<|code_end|>
. Write the next line using the current file imports:
import re
from pytest import raises
from jenkinsflow.flow import serial, parallel, FailedChildJobException
from .cfg import ApiType
from .framework import api_select
from .framework.utils import lines_in, replace_host_port, result_msg, build_started_msg
and context from other files:
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
#
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
# """Assert that `*expected_lines` occur in order in the lines of `text`.
#
# Args:
# *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
# If `expected_line` has a match method it is called and must return True for a line in `text`.
# Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
# Otherwise `expected line` must simply occur in a line in `text`
# """
#
# assert isinstance(api_type, test_cfg.ApiType)
# assert text
# assert expected_lines
#
# return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
#
# def replace_host_port(api_type, contains_url):
# if api_type != ApiType.SCRIPT:
# return _http_re.sub(r'http://x.x/job/\1\2', contains_url)
# else:
# return _http_re.sub(r'/tmp/jenkinsflow-test/job/\1.py', contains_url)
#
# def result_msg(api, job_name, num=None):
# if api.api_type == ApiType.SCRIPT:
# return repr(job_name) + " - build: " + _script_api_log_file(job_name)
# return repr(job_name) + " - build: http://x.x/job/" + job_name + "/" + (str(num) + "/console" if api.api_type == ApiType.MOCK and num else "")
#
# def build_started_msg(api, job_name, num, invocation_number=0):
# return "Build started: " + repr(job_name) + ((' Invocation-' + repr(invocation_number)) if invocation_number else '') + " - " + console_url(api, job_name, num)
, which may include functions, classes, or code. Output only the next line. | assert lines_in(api_type, sout, "job: 'jenkinsflow_test__reporting_job_status__j12' Status IDLE - latest build: #7") |
Here is a snippet: <|code_start|> assert " c1 = 'why?'" in sout
assert " b1 = 'true'" in sout
ordered_params_output = """
Defined Invocation http://x.x/job/jenkinsflow_test__reporting_ordered_job_parameters__j1 - parameters:
s1 = 'hi'
s2 = 'not-last'
c1 = 'why?'
i1 = '2'
b1 = 'true'
s4 = 'was last'
aaa = '3'
unknown1 = 'Hello'
unknown2 = 'true'
s3 = 'last'
"""
def test_reporting_ordered_job_parameters(api_type, capsys):
with api_select.api(__file__, api_type) as api:
api.flow_job()
api.job('j1', max_fails=0, expect_invocations=1, invocation_delay=1.0, exec_time=1.5, initial_buildno=7, expect_order=1, serial=True,
params=(('s1', '', 'desc'), ('c1', 'what', 'desc'), ('i1', 1, 'integer'), ('b1', False, 'boolean'), ('s2', 't', 'd'), ('s3', 't2', 'd2'),
('unknown1', 'Hello', 'd'), ('aaa', 17, 'd'), ('unknown2', False, 'd')))
order = ['s1', 's2', 'c1', 'i1', 'b1', 's4', '*', 's3']
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix, report_interval=0.5/api.speedup, params_display_order=order) as ctrl1:
ctrl1.invoke('j1', s1="hi", c1='why?', i1=2, b1=True, s2='not-last', s3='last', unknown1='Hello', aaa=3, unknown2=True, s4='was last')
sout, _ = capsys.readouterr()
<|code_end|>
. Write the next line using the current file imports:
import re
from pytest import raises
from jenkinsflow.flow import serial, parallel, FailedChildJobException
from .cfg import ApiType
from .framework import api_select
from .framework.utils import lines_in, replace_host_port, result_msg, build_started_msg
and context from other files:
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
#
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
# """Assert that `*expected_lines` occur in order in the lines of `text`.
#
# Args:
# *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
# If `expected_line` has a match method it is called and must return True for a line in `text`.
# Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
# Otherwise `expected line` must simply occur in a line in `text`
# """
#
# assert isinstance(api_type, test_cfg.ApiType)
# assert text
# assert expected_lines
#
# return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
#
# def replace_host_port(api_type, contains_url):
# if api_type != ApiType.SCRIPT:
# return _http_re.sub(r'http://x.x/job/\1\2', contains_url)
# else:
# return _http_re.sub(r'/tmp/jenkinsflow-test/job/\1.py', contains_url)
#
# def result_msg(api, job_name, num=None):
# if api.api_type == ApiType.SCRIPT:
# return repr(job_name) + " - build: " + _script_api_log_file(job_name)
# return repr(job_name) + " - build: http://x.x/job/" + job_name + "/" + (str(num) + "/console" if api.api_type == ApiType.MOCK and num else "")
#
# def build_started_msg(api, job_name, num, invocation_number=0):
# return "Build started: " + repr(job_name) + ((' Invocation-' + repr(invocation_number)) if invocation_number else '') + " - " + console_url(api, job_name, num)
, which may include functions, classes, or code. Output only the next line. | assert replace_host_port(api_type, ordered_params_output.strip()) in replace_host_port(api_type, sout) |
Predict the next line for this snippet: <|code_start|> with api_select.api(__file__, api_type, login=True) as api:
api.flow_job()
api.job('j11', max_fails=0, expect_invocations=1, expect_order=1)
api.job('j21_unchecked', max_fails=0, expect_invocations=1, invocation_delay=0, exec_time=50, initial_buildno=7, expect_order=None, unknown_result=True, serial=True)
api.job('j22', max_fails=0, expect_invocations=1, invocation_delay=0, exec_time=1.5, initial_buildno=7, expect_order=2)
api.job('j31', max_fails=0, expect_invocations=1, invocation_delay=0, exec_time=1.5, initial_buildno=7, expect_order=3)
api.job('j32_unchecked_fail', max_fails=1, expect_invocations=1, invocation_delay=0, exec_time=1.5, initial_buildno=7, expect_order=3)
api.job('j41', max_fails=0, expect_invocations=1, invocation_delay=0, exec_time=1.5, initial_buildno=7, expect_order=3)
api.job('j42_unchecked', max_fails=0, expect_invocations=1, invocation_delay=0, exec_time=1.5, initial_buildno=7, expect_order=3, serial=True)
api.job('j23', max_fails=0, expect_invocations=1, invocation_delay=0, exec_time=1.5, initial_buildno=7, expect_order=4)
api.job('j12', max_fails=0, expect_invocations=1, invocation_delay=0, exec_time=5, initial_buildno=7, expect_order=5)
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix, report_interval=0.5/api.speedup) as ctrl1:
ctrl1.invoke('j11')
with ctrl1.serial() as ctrl2:
ctrl2.invoke_unchecked('j21_unchecked')
ctrl2.invoke('j22')
with ctrl2.parallel() as ctrl3:
ctrl3.invoke('j31')
ctrl3.invoke_unchecked('j32_unchecked_fail')
with ctrl3.serial() as ctrl4:
ctrl4.invoke('j41')
ctrl4.invoke_unchecked('j42_unchecked')
ctrl2.invoke('j23')
ctrl1.invoke('j12')
sout, _ = capsys.readouterr()
assert lines_in(
api_type, sout,
<|code_end|>
with the help of current file imports:
import re
from pytest import raises
from jenkinsflow.flow import serial, parallel, FailedChildJobException
from .cfg import ApiType
from .framework import api_select
from .framework.utils import lines_in, replace_host_port, result_msg, build_started_msg
and context from other files:
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
#
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
# """Assert that `*expected_lines` occur in order in the lines of `text`.
#
# Args:
# *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
# If `expected_line` has a match method it is called and must return True for a line in `text`.
# Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
# Otherwise `expected line` must simply occur in a line in `text`
# """
#
# assert isinstance(api_type, test_cfg.ApiType)
# assert text
# assert expected_lines
#
# return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
#
# def replace_host_port(api_type, contains_url):
# if api_type != ApiType.SCRIPT:
# return _http_re.sub(r'http://x.x/job/\1\2', contains_url)
# else:
# return _http_re.sub(r'/tmp/jenkinsflow-test/job/\1.py', contains_url)
#
# def result_msg(api, job_name, num=None):
# if api.api_type == ApiType.SCRIPT:
# return repr(job_name) + " - build: " + _script_api_log_file(job_name)
# return repr(job_name) + " - build: http://x.x/job/" + job_name + "/" + (str(num) + "/console" if api.api_type == ApiType.MOCK and num else "")
#
# def build_started_msg(api, job_name, num, invocation_number=0):
# return "Build started: " + repr(job_name) + ((' Invocation-' + repr(invocation_number)) if invocation_number else '') + " - " + console_url(api, job_name, num)
, which may contain function names, class names, or code. Output only the next line. | "^UNCHECKED FAILURE: " + result_msg(api, "jenkinsflow_test__reporting_result_unchecked__j32_unchecked_fail"), |
Next line prediction: <|code_start|> assert lines_in(api_type, sout, "'jenkinsflow_test__reporting_job_status__j12' Status QUEUED - Why am I queued?")
assert lines_in(api_type, sout, "'jenkinsflow_test__reporting_job_status__j12' Status RUNNING - build: #8")
assert lines_in(api_type, sout, "'jenkinsflow_test__reporting_job_status__j12' Status IDLE - build: #8")
else:
# TODO: know if we cleaned jobs and check the 'repr_not_invoked' above
assert "'jenkinsflow_test__reporting_job_status__j12' Status RUNNING - build: " in sout
# assert "'jenkinsflow_test__reporting_job_status__j12' Status IDLE - build: " in sout
def test_reporting_invocation_serial(api_type, capsys):
with api_select.api(__file__, api_type) as api:
api.flow_job()
api.job('j11', max_fails=0, expect_invocations=1, expect_order=1)
api.job('j12', max_fails=0, expect_invocations=1, invocation_delay=1.0, exec_time=1.5, initial_buildno=7, expect_order=2, serial=True)
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix, report_interval=0.5/api.speedup) as ctrl1:
ctrl1.invoke('j11')
ctrl1.invoke('j12')
sout, _ = capsys.readouterr()
empty_re = re.compile("^$")
assert lines_in(
api_type, sout,
"^Defined Invocation http://x.x/job/jenkinsflow_test__reporting_invocation_serial__j11",
"^Defined Invocation http://x.x/job/jenkinsflow_test__reporting_invocation_serial__j12",
empty_re,
"--- Starting flow ---",
empty_re,
"^Flow Invocation (1/1,1/1): ['jenkinsflow_test__reporting_invocation_serial__j11', 'jenkinsflow_test__reporting_invocation_serial__j12']",
"^Job Invocation (1/1,1/1): http://x.x/job/jenkinsflow_test__reporting_invocation_serial__j11",
<|code_end|>
. Use current file imports:
(import re
from pytest import raises
from jenkinsflow.flow import serial, parallel, FailedChildJobException
from .cfg import ApiType
from .framework import api_select
from .framework.utils import lines_in, replace_host_port, result_msg, build_started_msg)
and context including class names, function names, or small code snippets from other files:
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
#
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
# """Assert that `*expected_lines` occur in order in the lines of `text`.
#
# Args:
# *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
# If `expected_line` has a match method it is called and must return True for a line in `text`.
# Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
# Otherwise `expected line` must simply occur in a line in `text`
# """
#
# assert isinstance(api_type, test_cfg.ApiType)
# assert text
# assert expected_lines
#
# return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
#
# def replace_host_port(api_type, contains_url):
# if api_type != ApiType.SCRIPT:
# return _http_re.sub(r'http://x.x/job/\1\2', contains_url)
# else:
# return _http_re.sub(r'/tmp/jenkinsflow-test/job/\1.py', contains_url)
#
# def result_msg(api, job_name, num=None):
# if api.api_type == ApiType.SCRIPT:
# return repr(job_name) + " - build: " + _script_api_log_file(job_name)
# return repr(job_name) + " - build: http://x.x/job/" + job_name + "/" + (str(num) + "/console" if api.api_type == ApiType.MOCK and num else "")
#
# def build_started_msg(api, job_name, num, invocation_number=0):
# return "Build started: " + repr(job_name) + ((' Invocation-' + repr(invocation_number)) if invocation_number else '') + " - " + console_url(api, job_name, num)
. Output only the next line. | build_started_msg(api, "jenkinsflow_test__reporting_invocation_serial__j11", 1), |
Given snippet: <|code_start|> api.job('j22_fail', max_fails=1, expect_invocations=2, expect_order=2)
api.job('j31_fail', max_fails=2, expect_invocations=3, expect_order=2)
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix) as ctrl1:
ctrl1.invoke('j11')
with ctrl1.parallel(timeout=70, max_tries=2) as ctrl2:
ctrl2.invoke('j21')
ctrl2.invoke('j22_fail')
with ctrl2.parallel(timeout=70, max_tries=2) as ctrl3:
ctrl3.invoke('j31_fail')
def test_retry_parallel_through_outer_level(api_type, capsys):
with api_select.api(__file__, api_type) as api:
api.flow_job()
api.job('j11', max_fails=0, expect_invocations=1, expect_order=1)
api.job('j21', max_fails=0, expect_invocations=1, expect_order=2, serial=True)
api.job('j31', max_fails=0, expect_invocations=1, expect_order=3, serial=True)
api.job('j41_fail', max_fails=2, expect_invocations=3, expect_order=3)
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix) as ctrl1:
ctrl1.invoke('j11')
with ctrl1.serial(timeout=70, max_tries=2) as ctrl2:
ctrl2.invoke('j21')
with ctrl2.parallel(timeout=70) as ctrl3:
ctrl3.invoke('j31')
with ctrl3.parallel(timeout=70, max_tries=2) as ctrl4:
ctrl4.invoke('j41_fail')
sout, _ = capsys.readouterr()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pytest import raises
from jenkinsflow.flow import parallel, serial, FailedChildJobException, FailedChildJobsException
from .framework import api_select, utils
and context:
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/utils.py
# def _script_api_log_file(job_name):
# def console_url(api, job_name, num):
# def result_msg(api, job_name, num=None):
# def build_started_msg(api, job_name, num, invocation_number=0):
# def kill_current_msg(api, job_name, num):
# def build_queued_msg(api, job_name, num):
# def replace_host_port(api_type, contains_url):
# def lines_in(api_type, text, *expected_lines):
# def flow_graph_dir(flow_name):
which might include code, classes, or functions. Output only the next line. | sout = utils.replace_host_port(api_type, sout) |
Given the following code snippet before the placeholder: <|code_start|># Copyright (c) 2017 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
def _job_name(api, short_name):
return api.job_name_prefix + short_name, short_name
@pytest.mark.not_apis(ApiType.MOCK, ApiType.SCRIPT)
def test_enable_disable_disable_enable(api_type):
<|code_end|>
, predict the next line using imports from the current file:
import pytest
from jenkinsflow.flow import serial
from .framework import api_select
from .cfg import ApiType
and context including class names, function names, and sometimes code from other files:
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
. Output only the next line. | with api_select.api(__file__, api_type, login=True) as api: |
Predict the next line after this snippet: <|code_start|># Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
here = os.path.abspath(os.path.dirname(__file__))
@pytest.mark.not_apis(ApiType.SCRIPT)
def test_abort_retry_serial_toplevel(api_type):
<|code_end|>
using the current file's imports:
import os
import pytest
from pytest import raises
from jenkinsflow.flow import parallel, serial, FailedChildJobException, FailedChildJobsException
from .framework import api_select
from .framework.abort_job import abort
from .cfg import ApiType
and any relevant context from other files:
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/abort_job.py
# def abort(api, job_name, sleep_time):
# """Call this script as a subprocess"""
# if api.api_type == ApiType.MOCK:
# return
#
# ff = __file__.replace('.pyc', '.py')
# args = [sys.executable, ff, api.file_name, api.api_type.name, api.func_name.replace('test_', ''), job_name, str(sleep_time)]
# with open(job_name, 'w') as log_file:
# logt(log_file, "Invoking abort subprocess.", args)
# subprocess.Popen(args)
#
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
. Output only the next line. | with api_select.api(__file__, api_type) as api: |
Next line prediction: <|code_start|># Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
here = os.path.abspath(os.path.dirname(__file__))
@pytest.mark.not_apis(ApiType.SCRIPT)
def test_abort_retry_serial_toplevel(api_type):
with api_select.api(__file__, api_type) as api:
api.flow_job()
api.job('j11', max_fails=0, expect_invocations=1, expect_order=1)
api.job('j12_abort', max_fails=0, expect_invocations=1, expect_order=2, exec_time=20, serial=True, final_result='ABORTED')
api.job('j13', max_fails=0, expect_invocations=0, expect_order=None, serial=True)
<|code_end|>
. Use current file imports:
(import os
import pytest
from pytest import raises
from jenkinsflow.flow import parallel, serial, FailedChildJobException, FailedChildJobsException
from .framework import api_select
from .framework.abort_job import abort
from .cfg import ApiType)
and context including class names, function names, or small code snippets from other files:
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
# username=None, password=None):
#
# Path: test/framework/abort_job.py
# def abort(api, job_name, sleep_time):
# """Call this script as a subprocess"""
# if api.api_type == ApiType.MOCK:
# return
#
# ff = __file__.replace('.pyc', '.py')
# args = [sys.executable, ff, api.file_name, api.api_type.name, api.func_name.replace('test_', ''), job_name, str(sleep_time)]
# with open(job_name, 'w') as log_file:
# logt(log_file, "Invoking abort subprocess.", args)
# subprocess.Popen(args)
#
# Path: test/cfg.py
# class ApiType(Enum):
# JENKINS = 0
# SCRIPT = 1
# MOCK = 2
. Output only the next line. | abort(api, 'j12_abort', 10) |
Next line prediction: <|code_start|>
class InstComparator:
'''
Can be used to compare the passed in CommonInstFormat object with any other
CommonInstFormat object. This class must be subclassed before it can be used
and the child must implement the equals method for finding which fields to compare
on.
'''
def __init__(self, inst):
<|code_end|>
. Use current file imports:
(from disassembler.formats.common.inst import CommonInstFormat
from disassembler.formats.helpers.exceptions import ImproperObjectType
from disassembler.formats.helpers.label import Label)
and context including class names, function names, or small code snippets from other files:
# Path: disassembler/formats/common/inst.py
# class CommonInstFormat:
# def __init__(self, address, mnemonic, op_str, bytes, comment=None):
# self.address = address
# self.mnemonic = mnemonic
# self.op_str = op_str
# self.bytes = bytes
# self.function = None
# self.comment = comment
#
# def getByteString(self, num_bytes):
# string_size = num_bytes*3
# unpadded = str(self.bytes).encode("hex")[0:num_bytes*2]
# return ' '.join([unpadded[x:x+2] for x in xrange(0, len(unpadded), 2)]).ljust(string_size)
#
# @staticmethod
# def length(inst):
# return 1
#
# @staticmethod
# def toString(inst):
# pass
#
# Path: disassembler/formats/helpers/exceptions.py
# class ImproperObjectType(Exception):
# def __init__(self, message):
# Exception.__init__(self, message)
#
# Path: disassembler/formats/helpers/label.py
# class Label:
# def __init__(self, address, name, item, xrefs=None):
# self.address = address
# self.name = name
# self.item = item
# self.xrefs = [] if xrefs is None else xrefs
#
# def __str__(self):
# return self.name
. Output only the next line. | if not isinstance(inst, CommonInstFormat): |
Based on the snippet: <|code_start|>
class InstComparator:
'''
Can be used to compare the passed in CommonInstFormat object with any other
CommonInstFormat object. This class must be subclassed before it can be used
and the child must implement the equals method for finding which fields to compare
on.
'''
def __init__(self, inst):
if not isinstance(inst, CommonInstFormat):
<|code_end|>
, predict the immediate next line with the help of imports:
from disassembler.formats.common.inst import CommonInstFormat
from disassembler.formats.helpers.exceptions import ImproperObjectType
from disassembler.formats.helpers.label import Label
and context (classes, functions, sometimes code) from other files:
# Path: disassembler/formats/common/inst.py
# class CommonInstFormat:
# def __init__(self, address, mnemonic, op_str, bytes, comment=None):
# self.address = address
# self.mnemonic = mnemonic
# self.op_str = op_str
# self.bytes = bytes
# self.function = None
# self.comment = comment
#
# def getByteString(self, num_bytes):
# string_size = num_bytes*3
# unpadded = str(self.bytes).encode("hex")[0:num_bytes*2]
# return ' '.join([unpadded[x:x+2] for x in xrange(0, len(unpadded), 2)]).ljust(string_size)
#
# @staticmethod
# def length(inst):
# return 1
#
# @staticmethod
# def toString(inst):
# pass
#
# Path: disassembler/formats/helpers/exceptions.py
# class ImproperObjectType(Exception):
# def __init__(self, message):
# Exception.__init__(self, message)
#
# Path: disassembler/formats/helpers/label.py
# class Label:
# def __init__(self, address, name, item, xrefs=None):
# self.address = address
# self.name = name
# self.item = item
# self.xrefs = [] if xrefs is None else xrefs
#
# def __str__(self):
# return self.name
. Output only the next line. | raise ImproperObjectType('InstComparator must be constructed with a CommonInstFormat object') |
Continue the code snippet: <|code_start|>
class AddressComparator(InstComparator):
def equals(self, other):
return self.inst.address == other.address
class MnemonicComparator(InstComparator):
def equals(self, other):
return self.inst.mnemonic == other.mnemonic
class OpStrComparator(InstComparator):
def equals(self, other):
return self.inst.op_str == other.op_str
class BytesComparator(InstComparator):
def equals(self, other):
return self.inst.bytes == other.bytes
class CommentComparator(InstComparator):
def equals(self, other):
return self.inst.comment == other.comment
class LabelComparator:
'''
Can be used to compare the passed in Label object with any other
Label object. This class must be subclassed before it can be used
and the child must implement the equals method for finding which fields to compare
on.
'''
def __init__(self, label):
<|code_end|>
. Use current file imports:
from disassembler.formats.common.inst import CommonInstFormat
from disassembler.formats.helpers.exceptions import ImproperObjectType
from disassembler.formats.helpers.label import Label
and context (classes, functions, or code) from other files:
# Path: disassembler/formats/common/inst.py
# class CommonInstFormat:
# def __init__(self, address, mnemonic, op_str, bytes, comment=None):
# self.address = address
# self.mnemonic = mnemonic
# self.op_str = op_str
# self.bytes = bytes
# self.function = None
# self.comment = comment
#
# def getByteString(self, num_bytes):
# string_size = num_bytes*3
# unpadded = str(self.bytes).encode("hex")[0:num_bytes*2]
# return ' '.join([unpadded[x:x+2] for x in xrange(0, len(unpadded), 2)]).ljust(string_size)
#
# @staticmethod
# def length(inst):
# return 1
#
# @staticmethod
# def toString(inst):
# pass
#
# Path: disassembler/formats/helpers/exceptions.py
# class ImproperObjectType(Exception):
# def __init__(self, message):
# Exception.__init__(self, message)
#
# Path: disassembler/formats/helpers/label.py
# class Label:
# def __init__(self, address, name, item, xrefs=None):
# self.address = address
# self.name = name
# self.item = item
# self.xrefs = [] if xrefs is None else xrefs
#
# def __str__(self):
# return self.name
. Output only the next line. | if not isinstance(label, Label): |
Given the code snippet: <|code_start|>
prologues = {}
epilogues = {}
prologues[CS_ARCH_X86] = {
CS_MODE_16 : [
<|code_end|>
, generate the next line using the imports in this file:
from capstone import *
from disassembler.formats.common.inst import CommonInstFormat
and context (functions, classes, or occasionally code) from other files:
# Path: disassembler/formats/common/inst.py
# class CommonInstFormat:
# def __init__(self, address, mnemonic, op_str, bytes, comment=None):
# self.address = address
# self.mnemonic = mnemonic
# self.op_str = op_str
# self.bytes = bytes
# self.function = None
# self.comment = comment
#
# def getByteString(self, num_bytes):
# string_size = num_bytes*3
# unpadded = str(self.bytes).encode("hex")[0:num_bytes*2]
# return ' '.join([unpadded[x:x+2] for x in xrange(0, len(unpadded), 2)]).ljust(string_size)
#
# @staticmethod
# def length(inst):
# return 1
#
# @staticmethod
# def toString(inst):
# pass
. Output only the next line. | [CommonInstFormat(None, 'push', 'bp', ''), CommonInstFormat(None, 'mov', 'bp, sp', '')], # CDECL/STDCALL/FASTCALL
|
Next line prediction: <|code_start|># Register your models here.
admin.site.register(Skill)
admin.site.register(Interest)
admin.site.register(Goal)
admin.site.register(UserProfile)
<|code_end|>
. Use current file imports:
(from django.contrib import admin
from .models import Skill, Interest, Goal, Project, UserProfile)
and context including class names, function names, or small code snippets from other files:
# Path: components/admin/api/models.py
# class Skill(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Skill, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Interest(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Interest, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Goal(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def __str__(self):
# return self.name
#
# def save(self, *args, **kwargs):
# super(Goal, self).save(*args, **kwargs)
#
# class Project(models.Model):
# id = models.AutoField(primary_key=True)
# project_lead = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True)
# preview = models.BooleanField(default=True) # project will only appear in Project List when set to False
#
# # UI properties
# title = models.CharField(max_length=454, null=True)
# summary = models.CharField(max_length=254)
# skills_needed = models.ManyToManyField(Skill)
# learning_opportunities = models.ManyToManyField(Goal)
# civic_interests = models.ManyToManyField(Interest)
# pending_tasks = models.CharField(max_length=454, null=True)
# progress_made = models.CharField(max_length=454, null=True)
# additional_info = models.CharField(max_length=454, null=True)
# slack_channel = models.CharField(max_length=200)
#
# # Admin properties
# github_repository = models.CharField(max_length=454, null=True)
# website = models.CharField(max_length=454, null=True)
# twitter = models.CharField(max_length=454, null=True)
#
# def save(self, *args, **kwargs):
# super(Project, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.title
#
# class UserProfile(models.Model):
# user = models.OneToOneField(User, on_delete=models.CASCADE)
# github_user_name = models.CharField(max_length=254)
# name = models.CharField(max_length=254)
# email_address = models.EmailField(max_length=254)
# slack_name = models.CharField(max_length=254)
# slack_id = models.CharField(max_length=20)
#
# def __str__(self):
# return self.github_user_name
. Output only the next line. | admin.site.register(Project) |
Predict the next line for this snippet: <|code_start|># Register your models here.
admin.site.register(Skill)
admin.site.register(Interest)
admin.site.register(Goal)
<|code_end|>
with the help of current file imports:
from django.contrib import admin
from .models import Skill, Interest, Goal, Project, UserProfile
and context from other files:
# Path: components/admin/api/models.py
# class Skill(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Skill, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Interest(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Interest, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Goal(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def __str__(self):
# return self.name
#
# def save(self, *args, **kwargs):
# super(Goal, self).save(*args, **kwargs)
#
# class Project(models.Model):
# id = models.AutoField(primary_key=True)
# project_lead = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True)
# preview = models.BooleanField(default=True) # project will only appear in Project List when set to False
#
# # UI properties
# title = models.CharField(max_length=454, null=True)
# summary = models.CharField(max_length=254)
# skills_needed = models.ManyToManyField(Skill)
# learning_opportunities = models.ManyToManyField(Goal)
# civic_interests = models.ManyToManyField(Interest)
# pending_tasks = models.CharField(max_length=454, null=True)
# progress_made = models.CharField(max_length=454, null=True)
# additional_info = models.CharField(max_length=454, null=True)
# slack_channel = models.CharField(max_length=200)
#
# # Admin properties
# github_repository = models.CharField(max_length=454, null=True)
# website = models.CharField(max_length=454, null=True)
# twitter = models.CharField(max_length=454, null=True)
#
# def save(self, *args, **kwargs):
# super(Project, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.title
#
# class UserProfile(models.Model):
# user = models.OneToOneField(User, on_delete=models.CASCADE)
# github_user_name = models.CharField(max_length=254)
# name = models.CharField(max_length=254)
# email_address = models.EmailField(max_length=254)
# slack_name = models.CharField(max_length=254)
# slack_id = models.CharField(max_length=20)
#
# def __str__(self):
# return self.github_user_name
, which may contain function names, class names, or code. Output only the next line. | admin.site.register(UserProfile) |
Given the following code snippet before the placeholder: <|code_start|>
class SkillSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
<|code_end|>
, predict the next line using imports from the current file:
from rest_framework import serializers
from .models import Skill, Interest, Goal, Project
and context including class names, function names, and sometimes code from other files:
# Path: components/admin/api/models.py
# class Skill(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Skill, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Interest(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Interest, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Goal(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def __str__(self):
# return self.name
#
# def save(self, *args, **kwargs):
# super(Goal, self).save(*args, **kwargs)
#
# class Project(models.Model):
# id = models.AutoField(primary_key=True)
# project_lead = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True)
# preview = models.BooleanField(default=True) # project will only appear in Project List when set to False
#
# # UI properties
# title = models.CharField(max_length=454, null=True)
# summary = models.CharField(max_length=254)
# skills_needed = models.ManyToManyField(Skill)
# learning_opportunities = models.ManyToManyField(Goal)
# civic_interests = models.ManyToManyField(Interest)
# pending_tasks = models.CharField(max_length=454, null=True)
# progress_made = models.CharField(max_length=454, null=True)
# additional_info = models.CharField(max_length=454, null=True)
# slack_channel = models.CharField(max_length=200)
#
# # Admin properties
# github_repository = models.CharField(max_length=454, null=True)
# website = models.CharField(max_length=454, null=True)
# twitter = models.CharField(max_length=454, null=True)
#
# def save(self, *args, **kwargs):
# super(Project, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.title
. Output only the next line. | model = Skill |
Here is a snippet: <|code_start|>
class SkillSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Skill
fields = ('_id', 'name', 'title', 'parent')
class InterestSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
<|code_end|>
. Write the next line using the current file imports:
from rest_framework import serializers
from .models import Skill, Interest, Goal, Project
and context from other files:
# Path: components/admin/api/models.py
# class Skill(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Skill, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Interest(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Interest, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Goal(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def __str__(self):
# return self.name
#
# def save(self, *args, **kwargs):
# super(Goal, self).save(*args, **kwargs)
#
# class Project(models.Model):
# id = models.AutoField(primary_key=True)
# project_lead = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True)
# preview = models.BooleanField(default=True) # project will only appear in Project List when set to False
#
# # UI properties
# title = models.CharField(max_length=454, null=True)
# summary = models.CharField(max_length=254)
# skills_needed = models.ManyToManyField(Skill)
# learning_opportunities = models.ManyToManyField(Goal)
# civic_interests = models.ManyToManyField(Interest)
# pending_tasks = models.CharField(max_length=454, null=True)
# progress_made = models.CharField(max_length=454, null=True)
# additional_info = models.CharField(max_length=454, null=True)
# slack_channel = models.CharField(max_length=200)
#
# # Admin properties
# github_repository = models.CharField(max_length=454, null=True)
# website = models.CharField(max_length=454, null=True)
# twitter = models.CharField(max_length=454, null=True)
#
# def save(self, *args, **kwargs):
# super(Project, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.title
, which may include functions, classes, or code. Output only the next line. | model = Interest |
Based on the snippet: <|code_start|>
class SkillSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Skill
fields = ('_id', 'name', 'title', 'parent')
class InterestSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Interest
fields = ('_id', 'name', 'title', 'parent')
class GoalSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
<|code_end|>
, predict the immediate next line with the help of imports:
from rest_framework import serializers
from .models import Skill, Interest, Goal, Project
and context (classes, functions, sometimes code) from other files:
# Path: components/admin/api/models.py
# class Skill(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Skill, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Interest(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Interest, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Goal(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def __str__(self):
# return self.name
#
# def save(self, *args, **kwargs):
# super(Goal, self).save(*args, **kwargs)
#
# class Project(models.Model):
# id = models.AutoField(primary_key=True)
# project_lead = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True)
# preview = models.BooleanField(default=True) # project will only appear in Project List when set to False
#
# # UI properties
# title = models.CharField(max_length=454, null=True)
# summary = models.CharField(max_length=254)
# skills_needed = models.ManyToManyField(Skill)
# learning_opportunities = models.ManyToManyField(Goal)
# civic_interests = models.ManyToManyField(Interest)
# pending_tasks = models.CharField(max_length=454, null=True)
# progress_made = models.CharField(max_length=454, null=True)
# additional_info = models.CharField(max_length=454, null=True)
# slack_channel = models.CharField(max_length=200)
#
# # Admin properties
# github_repository = models.CharField(max_length=454, null=True)
# website = models.CharField(max_length=454, null=True)
# twitter = models.CharField(max_length=454, null=True)
#
# def save(self, *args, **kwargs):
# super(Project, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.title
. Output only the next line. | model = Goal |
Next line prediction: <|code_start|>
class SkillSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Skill
fields = ('_id', 'name', 'title', 'parent')
class InterestSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Interest
fields = ('_id', 'name', 'title', 'parent')
class GoalSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Goal
fields = ('_id', 'name', 'title', 'parent')
class ProjectSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
<|code_end|>
. Use current file imports:
(from rest_framework import serializers
from .models import Skill, Interest, Goal, Project)
and context including class names, function names, or small code snippets from other files:
# Path: components/admin/api/models.py
# class Skill(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Skill, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Interest(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Interest, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Goal(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def __str__(self):
# return self.name
#
# def save(self, *args, **kwargs):
# super(Goal, self).save(*args, **kwargs)
#
# class Project(models.Model):
# id = models.AutoField(primary_key=True)
# project_lead = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True)
# preview = models.BooleanField(default=True) # project will only appear in Project List when set to False
#
# # UI properties
# title = models.CharField(max_length=454, null=True)
# summary = models.CharField(max_length=254)
# skills_needed = models.ManyToManyField(Skill)
# learning_opportunities = models.ManyToManyField(Goal)
# civic_interests = models.ManyToManyField(Interest)
# pending_tasks = models.CharField(max_length=454, null=True)
# progress_made = models.CharField(max_length=454, null=True)
# additional_info = models.CharField(max_length=454, null=True)
# slack_channel = models.CharField(max_length=200)
#
# # Admin properties
# github_repository = models.CharField(max_length=454, null=True)
# website = models.CharField(max_length=454, null=True)
# twitter = models.CharField(max_length=454, null=True)
#
# def save(self, *args, **kwargs):
# super(Project, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.title
. Output only the next line. | model = Project |
Based on the snippet: <|code_start|>
def index(request):
return render(request, 'index.html',)
def create_project(request):
return render(request, 'create_project/index.html',)
class SkillList(generics.ListCreateAPIView):
<|code_end|>
, predict the immediate next line with the help of imports:
from django.http import HttpResponse, Http404
from django.shortcuts import render
from rest_framework import generics, permissions, status, mixins
from .models import Skill, Interest, Goal, Project
from .serializers import SkillSerializer, InterestSerializer, GoalSerializer, ProjectSerializer
from .permissions import IsOwnerOrReadOnly
from django.contrib.auth.models import User
from django.views.generic import TemplateView
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.views import APIView
and context (classes, functions, sometimes code) from other files:
# Path: components/admin/api/models.py
# class Skill(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Skill, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Interest(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Interest, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Goal(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def __str__(self):
# return self.name
#
# def save(self, *args, **kwargs):
# super(Goal, self).save(*args, **kwargs)
#
# class Project(models.Model):
# id = models.AutoField(primary_key=True)
# project_lead = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True)
# preview = models.BooleanField(default=True) # project will only appear in Project List when set to False
#
# # UI properties
# title = models.CharField(max_length=454, null=True)
# summary = models.CharField(max_length=254)
# skills_needed = models.ManyToManyField(Skill)
# learning_opportunities = models.ManyToManyField(Goal)
# civic_interests = models.ManyToManyField(Interest)
# pending_tasks = models.CharField(max_length=454, null=True)
# progress_made = models.CharField(max_length=454, null=True)
# additional_info = models.CharField(max_length=454, null=True)
# slack_channel = models.CharField(max_length=200)
#
# # Admin properties
# github_repository = models.CharField(max_length=454, null=True)
# website = models.CharField(max_length=454, null=True)
# twitter = models.CharField(max_length=454, null=True)
#
# def save(self, *args, **kwargs):
# super(Project, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.title
#
# Path: components/admin/api/serializers.py
# class SkillSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Skill
# fields = ('_id', 'name', 'title', 'parent')
#
# class InterestSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Interest
# fields = ('_id', 'name', 'title', 'parent')
#
# class GoalSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Goal
# fields = ('_id', 'name', 'title', 'parent')
#
# class ProjectSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Project
# fields = ('_id', 'preview', 'title', 'summary', 'skills_needed', 'learning_opportunity', 'civic_interests', 'pending_tasks', 'progress_made', 'additional_info', 'slack_channel', 'github_repository')
#
# Path: components/admin/api/permissions.py
# class IsOwnerOrReadOnly(permissions.BasePermission):
# def has_object_permission(self, request, view, obj):
# if request.method in permissions.SAFE_METHODS:
# return True
# return obj.owner == request.user
. Output only the next line. | queryset = Skill.objects.all() |
Given snippet: <|code_start|>
def index(request):
return render(request, 'index.html',)
def create_project(request):
return render(request, 'create_project/index.html',)
class SkillList(generics.ListCreateAPIView):
queryset = Skill.objects.all()
serializer_class = SkillSerializer
permissions_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
class SkillDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Skill.objects.all()
serializer_class = SkillSerializer
permissions_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
class InterestList(generics.ListCreateAPIView):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.http import HttpResponse, Http404
from django.shortcuts import render
from rest_framework import generics, permissions, status, mixins
from .models import Skill, Interest, Goal, Project
from .serializers import SkillSerializer, InterestSerializer, GoalSerializer, ProjectSerializer
from .permissions import IsOwnerOrReadOnly
from django.contrib.auth.models import User
from django.views.generic import TemplateView
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.views import APIView
and context:
# Path: components/admin/api/models.py
# class Skill(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Skill, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Interest(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Interest, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Goal(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def __str__(self):
# return self.name
#
# def save(self, *args, **kwargs):
# super(Goal, self).save(*args, **kwargs)
#
# class Project(models.Model):
# id = models.AutoField(primary_key=True)
# project_lead = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True)
# preview = models.BooleanField(default=True) # project will only appear in Project List when set to False
#
# # UI properties
# title = models.CharField(max_length=454, null=True)
# summary = models.CharField(max_length=254)
# skills_needed = models.ManyToManyField(Skill)
# learning_opportunities = models.ManyToManyField(Goal)
# civic_interests = models.ManyToManyField(Interest)
# pending_tasks = models.CharField(max_length=454, null=True)
# progress_made = models.CharField(max_length=454, null=True)
# additional_info = models.CharField(max_length=454, null=True)
# slack_channel = models.CharField(max_length=200)
#
# # Admin properties
# github_repository = models.CharField(max_length=454, null=True)
# website = models.CharField(max_length=454, null=True)
# twitter = models.CharField(max_length=454, null=True)
#
# def save(self, *args, **kwargs):
# super(Project, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.title
#
# Path: components/admin/api/serializers.py
# class SkillSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Skill
# fields = ('_id', 'name', 'title', 'parent')
#
# class InterestSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Interest
# fields = ('_id', 'name', 'title', 'parent')
#
# class GoalSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Goal
# fields = ('_id', 'name', 'title', 'parent')
#
# class ProjectSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Project
# fields = ('_id', 'preview', 'title', 'summary', 'skills_needed', 'learning_opportunity', 'civic_interests', 'pending_tasks', 'progress_made', 'additional_info', 'slack_channel', 'github_repository')
#
# Path: components/admin/api/permissions.py
# class IsOwnerOrReadOnly(permissions.BasePermission):
# def has_object_permission(self, request, view, obj):
# if request.method in permissions.SAFE_METHODS:
# return True
# return obj.owner == request.user
which might include code, classes, or functions. Output only the next line. | queryset = Interest.objects.all() |
Here is a snippet: <|code_start|>
def index(request):
return render(request, 'index.html',)
def create_project(request):
return render(request, 'create_project/index.html',)
class SkillList(generics.ListCreateAPIView):
queryset = Skill.objects.all()
serializer_class = SkillSerializer
permissions_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
class SkillDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Skill.objects.all()
serializer_class = SkillSerializer
permissions_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
class InterestList(generics.ListCreateAPIView):
queryset = Interest.objects.all()
serializer_class = InterestSerializer
permissions_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
class InterestDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Interest.objects.all()
serializer_class = InterestSerializer
permissions_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
class GoalList(generics.ListCreateAPIView):
<|code_end|>
. Write the next line using the current file imports:
from django.http import HttpResponse, Http404
from django.shortcuts import render
from rest_framework import generics, permissions, status, mixins
from .models import Skill, Interest, Goal, Project
from .serializers import SkillSerializer, InterestSerializer, GoalSerializer, ProjectSerializer
from .permissions import IsOwnerOrReadOnly
from django.contrib.auth.models import User
from django.views.generic import TemplateView
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.views import APIView
and context from other files:
# Path: components/admin/api/models.py
# class Skill(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Skill, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Interest(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Interest, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Goal(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def __str__(self):
# return self.name
#
# def save(self, *args, **kwargs):
# super(Goal, self).save(*args, **kwargs)
#
# class Project(models.Model):
# id = models.AutoField(primary_key=True)
# project_lead = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True)
# preview = models.BooleanField(default=True) # project will only appear in Project List when set to False
#
# # UI properties
# title = models.CharField(max_length=454, null=True)
# summary = models.CharField(max_length=254)
# skills_needed = models.ManyToManyField(Skill)
# learning_opportunities = models.ManyToManyField(Goal)
# civic_interests = models.ManyToManyField(Interest)
# pending_tasks = models.CharField(max_length=454, null=True)
# progress_made = models.CharField(max_length=454, null=True)
# additional_info = models.CharField(max_length=454, null=True)
# slack_channel = models.CharField(max_length=200)
#
# # Admin properties
# github_repository = models.CharField(max_length=454, null=True)
# website = models.CharField(max_length=454, null=True)
# twitter = models.CharField(max_length=454, null=True)
#
# def save(self, *args, **kwargs):
# super(Project, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.title
#
# Path: components/admin/api/serializers.py
# class SkillSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Skill
# fields = ('_id', 'name', 'title', 'parent')
#
# class InterestSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Interest
# fields = ('_id', 'name', 'title', 'parent')
#
# class GoalSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Goal
# fields = ('_id', 'name', 'title', 'parent')
#
# class ProjectSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Project
# fields = ('_id', 'preview', 'title', 'summary', 'skills_needed', 'learning_opportunity', 'civic_interests', 'pending_tasks', 'progress_made', 'additional_info', 'slack_channel', 'github_repository')
#
# Path: components/admin/api/permissions.py
# class IsOwnerOrReadOnly(permissions.BasePermission):
# def has_object_permission(self, request, view, obj):
# if request.method in permissions.SAFE_METHODS:
# return True
# return obj.owner == request.user
, which may include functions, classes, or code. Output only the next line. | queryset = Goal.objects.all() |
Given snippet: <|code_start|> queryset = Skill.objects.all()
serializer_class = SkillSerializer
permissions_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
class SkillDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Skill.objects.all()
serializer_class = SkillSerializer
permissions_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
class InterestList(generics.ListCreateAPIView):
queryset = Interest.objects.all()
serializer_class = InterestSerializer
permissions_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
class InterestDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Interest.objects.all()
serializer_class = InterestSerializer
permissions_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
class GoalList(generics.ListCreateAPIView):
queryset = Goal.objects.all()
serializer_class = GoalSerializer
permissions_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
class GoalDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Goal.objects.all()
serializer_class = GoalSerializer
permissions_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
class ProjectList(generics.ListCreateAPIView):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.http import HttpResponse, Http404
from django.shortcuts import render
from rest_framework import generics, permissions, status, mixins
from .models import Skill, Interest, Goal, Project
from .serializers import SkillSerializer, InterestSerializer, GoalSerializer, ProjectSerializer
from .permissions import IsOwnerOrReadOnly
from django.contrib.auth.models import User
from django.views.generic import TemplateView
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.views import APIView
and context:
# Path: components/admin/api/models.py
# class Skill(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Skill, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Interest(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Interest, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Goal(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def __str__(self):
# return self.name
#
# def save(self, *args, **kwargs):
# super(Goal, self).save(*args, **kwargs)
#
# class Project(models.Model):
# id = models.AutoField(primary_key=True)
# project_lead = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True)
# preview = models.BooleanField(default=True) # project will only appear in Project List when set to False
#
# # UI properties
# title = models.CharField(max_length=454, null=True)
# summary = models.CharField(max_length=254)
# skills_needed = models.ManyToManyField(Skill)
# learning_opportunities = models.ManyToManyField(Goal)
# civic_interests = models.ManyToManyField(Interest)
# pending_tasks = models.CharField(max_length=454, null=True)
# progress_made = models.CharField(max_length=454, null=True)
# additional_info = models.CharField(max_length=454, null=True)
# slack_channel = models.CharField(max_length=200)
#
# # Admin properties
# github_repository = models.CharField(max_length=454, null=True)
# website = models.CharField(max_length=454, null=True)
# twitter = models.CharField(max_length=454, null=True)
#
# def save(self, *args, **kwargs):
# super(Project, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.title
#
# Path: components/admin/api/serializers.py
# class SkillSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Skill
# fields = ('_id', 'name', 'title', 'parent')
#
# class InterestSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Interest
# fields = ('_id', 'name', 'title', 'parent')
#
# class GoalSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Goal
# fields = ('_id', 'name', 'title', 'parent')
#
# class ProjectSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Project
# fields = ('_id', 'preview', 'title', 'summary', 'skills_needed', 'learning_opportunity', 'civic_interests', 'pending_tasks', 'progress_made', 'additional_info', 'slack_channel', 'github_repository')
#
# Path: components/admin/api/permissions.py
# class IsOwnerOrReadOnly(permissions.BasePermission):
# def has_object_permission(self, request, view, obj):
# if request.method in permissions.SAFE_METHODS:
# return True
# return obj.owner == request.user
which might include code, classes, or functions. Output only the next line. | queryset = Project.objects.all() |
Continue the code snippet: <|code_start|>
def index(request):
return render(request, 'index.html',)
def create_project(request):
return render(request, 'create_project/index.html',)
class SkillList(generics.ListCreateAPIView):
queryset = Skill.objects.all()
<|code_end|>
. Use current file imports:
from django.http import HttpResponse, Http404
from django.shortcuts import render
from rest_framework import generics, permissions, status, mixins
from .models import Skill, Interest, Goal, Project
from .serializers import SkillSerializer, InterestSerializer, GoalSerializer, ProjectSerializer
from .permissions import IsOwnerOrReadOnly
from django.contrib.auth.models import User
from django.views.generic import TemplateView
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.views import APIView
and context (classes, functions, or code) from other files:
# Path: components/admin/api/models.py
# class Skill(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Skill, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Interest(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Interest, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Goal(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def __str__(self):
# return self.name
#
# def save(self, *args, **kwargs):
# super(Goal, self).save(*args, **kwargs)
#
# class Project(models.Model):
# id = models.AutoField(primary_key=True)
# project_lead = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True)
# preview = models.BooleanField(default=True) # project will only appear in Project List when set to False
#
# # UI properties
# title = models.CharField(max_length=454, null=True)
# summary = models.CharField(max_length=254)
# skills_needed = models.ManyToManyField(Skill)
# learning_opportunities = models.ManyToManyField(Goal)
# civic_interests = models.ManyToManyField(Interest)
# pending_tasks = models.CharField(max_length=454, null=True)
# progress_made = models.CharField(max_length=454, null=True)
# additional_info = models.CharField(max_length=454, null=True)
# slack_channel = models.CharField(max_length=200)
#
# # Admin properties
# github_repository = models.CharField(max_length=454, null=True)
# website = models.CharField(max_length=454, null=True)
# twitter = models.CharField(max_length=454, null=True)
#
# def save(self, *args, **kwargs):
# super(Project, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.title
#
# Path: components/admin/api/serializers.py
# class SkillSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Skill
# fields = ('_id', 'name', 'title', 'parent')
#
# class InterestSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Interest
# fields = ('_id', 'name', 'title', 'parent')
#
# class GoalSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Goal
# fields = ('_id', 'name', 'title', 'parent')
#
# class ProjectSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Project
# fields = ('_id', 'preview', 'title', 'summary', 'skills_needed', 'learning_opportunity', 'civic_interests', 'pending_tasks', 'progress_made', 'additional_info', 'slack_channel', 'github_repository')
#
# Path: components/admin/api/permissions.py
# class IsOwnerOrReadOnly(permissions.BasePermission):
# def has_object_permission(self, request, view, obj):
# if request.method in permissions.SAFE_METHODS:
# return True
# return obj.owner == request.user
. Output only the next line. | serializer_class = SkillSerializer |
Based on the snippet: <|code_start|>
def index(request):
return render(request, 'index.html',)
def create_project(request):
return render(request, 'create_project/index.html',)
class SkillList(generics.ListCreateAPIView):
queryset = Skill.objects.all()
serializer_class = SkillSerializer
permissions_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
class SkillDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Skill.objects.all()
serializer_class = SkillSerializer
permissions_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
class InterestList(generics.ListCreateAPIView):
queryset = Interest.objects.all()
<|code_end|>
, predict the immediate next line with the help of imports:
from django.http import HttpResponse, Http404
from django.shortcuts import render
from rest_framework import generics, permissions, status, mixins
from .models import Skill, Interest, Goal, Project
from .serializers import SkillSerializer, InterestSerializer, GoalSerializer, ProjectSerializer
from .permissions import IsOwnerOrReadOnly
from django.contrib.auth.models import User
from django.views.generic import TemplateView
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.views import APIView
and context (classes, functions, sometimes code) from other files:
# Path: components/admin/api/models.py
# class Skill(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Skill, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Interest(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Interest, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Goal(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def __str__(self):
# return self.name
#
# def save(self, *args, **kwargs):
# super(Goal, self).save(*args, **kwargs)
#
# class Project(models.Model):
# id = models.AutoField(primary_key=True)
# project_lead = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True)
# preview = models.BooleanField(default=True) # project will only appear in Project List when set to False
#
# # UI properties
# title = models.CharField(max_length=454, null=True)
# summary = models.CharField(max_length=254)
# skills_needed = models.ManyToManyField(Skill)
# learning_opportunities = models.ManyToManyField(Goal)
# civic_interests = models.ManyToManyField(Interest)
# pending_tasks = models.CharField(max_length=454, null=True)
# progress_made = models.CharField(max_length=454, null=True)
# additional_info = models.CharField(max_length=454, null=True)
# slack_channel = models.CharField(max_length=200)
#
# # Admin properties
# github_repository = models.CharField(max_length=454, null=True)
# website = models.CharField(max_length=454, null=True)
# twitter = models.CharField(max_length=454, null=True)
#
# def save(self, *args, **kwargs):
# super(Project, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.title
#
# Path: components/admin/api/serializers.py
# class SkillSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Skill
# fields = ('_id', 'name', 'title', 'parent')
#
# class InterestSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Interest
# fields = ('_id', 'name', 'title', 'parent')
#
# class GoalSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Goal
# fields = ('_id', 'name', 'title', 'parent')
#
# class ProjectSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Project
# fields = ('_id', 'preview', 'title', 'summary', 'skills_needed', 'learning_opportunity', 'civic_interests', 'pending_tasks', 'progress_made', 'additional_info', 'slack_channel', 'github_repository')
#
# Path: components/admin/api/permissions.py
# class IsOwnerOrReadOnly(permissions.BasePermission):
# def has_object_permission(self, request, view, obj):
# if request.method in permissions.SAFE_METHODS:
# return True
# return obj.owner == request.user
. Output only the next line. | serializer_class = InterestSerializer |
Based on the snippet: <|code_start|>
def index(request):
return render(request, 'index.html',)
def create_project(request):
return render(request, 'create_project/index.html',)
class SkillList(generics.ListCreateAPIView):
queryset = Skill.objects.all()
serializer_class = SkillSerializer
permissions_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
class SkillDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Skill.objects.all()
serializer_class = SkillSerializer
permissions_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
class InterestList(generics.ListCreateAPIView):
queryset = Interest.objects.all()
serializer_class = InterestSerializer
permissions_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
class InterestDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Interest.objects.all()
serializer_class = InterestSerializer
permissions_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
class GoalList(generics.ListCreateAPIView):
queryset = Goal.objects.all()
<|code_end|>
, predict the immediate next line with the help of imports:
from django.http import HttpResponse, Http404
from django.shortcuts import render
from rest_framework import generics, permissions, status, mixins
from .models import Skill, Interest, Goal, Project
from .serializers import SkillSerializer, InterestSerializer, GoalSerializer, ProjectSerializer
from .permissions import IsOwnerOrReadOnly
from django.contrib.auth.models import User
from django.views.generic import TemplateView
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.views import APIView
and context (classes, functions, sometimes code) from other files:
# Path: components/admin/api/models.py
# class Skill(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Skill, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Interest(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Interest, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Goal(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def __str__(self):
# return self.name
#
# def save(self, *args, **kwargs):
# super(Goal, self).save(*args, **kwargs)
#
# class Project(models.Model):
# id = models.AutoField(primary_key=True)
# project_lead = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True)
# preview = models.BooleanField(default=True) # project will only appear in Project List when set to False
#
# # UI properties
# title = models.CharField(max_length=454, null=True)
# summary = models.CharField(max_length=254)
# skills_needed = models.ManyToManyField(Skill)
# learning_opportunities = models.ManyToManyField(Goal)
# civic_interests = models.ManyToManyField(Interest)
# pending_tasks = models.CharField(max_length=454, null=True)
# progress_made = models.CharField(max_length=454, null=True)
# additional_info = models.CharField(max_length=454, null=True)
# slack_channel = models.CharField(max_length=200)
#
# # Admin properties
# github_repository = models.CharField(max_length=454, null=True)
# website = models.CharField(max_length=454, null=True)
# twitter = models.CharField(max_length=454, null=True)
#
# def save(self, *args, **kwargs):
# super(Project, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.title
#
# Path: components/admin/api/serializers.py
# class SkillSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Skill
# fields = ('_id', 'name', 'title', 'parent')
#
# class InterestSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Interest
# fields = ('_id', 'name', 'title', 'parent')
#
# class GoalSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Goal
# fields = ('_id', 'name', 'title', 'parent')
#
# class ProjectSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Project
# fields = ('_id', 'preview', 'title', 'summary', 'skills_needed', 'learning_opportunity', 'civic_interests', 'pending_tasks', 'progress_made', 'additional_info', 'slack_channel', 'github_repository')
#
# Path: components/admin/api/permissions.py
# class IsOwnerOrReadOnly(permissions.BasePermission):
# def has_object_permission(self, request, view, obj):
# if request.method in permissions.SAFE_METHODS:
# return True
# return obj.owner == request.user
. Output only the next line. | serializer_class = GoalSerializer |
Given the code snippet: <|code_start|> serializer_class = SkillSerializer
permissions_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
class SkillDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Skill.objects.all()
serializer_class = SkillSerializer
permissions_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
class InterestList(generics.ListCreateAPIView):
queryset = Interest.objects.all()
serializer_class = InterestSerializer
permissions_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
class InterestDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Interest.objects.all()
serializer_class = InterestSerializer
permissions_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
class GoalList(generics.ListCreateAPIView):
queryset = Goal.objects.all()
serializer_class = GoalSerializer
permissions_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
class GoalDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Goal.objects.all()
serializer_class = GoalSerializer
permissions_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
class ProjectList(generics.ListCreateAPIView):
queryset = Project.objects.all()
<|code_end|>
, generate the next line using the imports in this file:
from django.http import HttpResponse, Http404
from django.shortcuts import render
from rest_framework import generics, permissions, status, mixins
from .models import Skill, Interest, Goal, Project
from .serializers import SkillSerializer, InterestSerializer, GoalSerializer, ProjectSerializer
from .permissions import IsOwnerOrReadOnly
from django.contrib.auth.models import User
from django.views.generic import TemplateView
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.views import APIView
and context (functions, classes, or occasionally code) from other files:
# Path: components/admin/api/models.py
# class Skill(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Skill, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Interest(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Interest, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Goal(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def __str__(self):
# return self.name
#
# def save(self, *args, **kwargs):
# super(Goal, self).save(*args, **kwargs)
#
# class Project(models.Model):
# id = models.AutoField(primary_key=True)
# project_lead = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True)
# preview = models.BooleanField(default=True) # project will only appear in Project List when set to False
#
# # UI properties
# title = models.CharField(max_length=454, null=True)
# summary = models.CharField(max_length=254)
# skills_needed = models.ManyToManyField(Skill)
# learning_opportunities = models.ManyToManyField(Goal)
# civic_interests = models.ManyToManyField(Interest)
# pending_tasks = models.CharField(max_length=454, null=True)
# progress_made = models.CharField(max_length=454, null=True)
# additional_info = models.CharField(max_length=454, null=True)
# slack_channel = models.CharField(max_length=200)
#
# # Admin properties
# github_repository = models.CharField(max_length=454, null=True)
# website = models.CharField(max_length=454, null=True)
# twitter = models.CharField(max_length=454, null=True)
#
# def save(self, *args, **kwargs):
# super(Project, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.title
#
# Path: components/admin/api/serializers.py
# class SkillSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Skill
# fields = ('_id', 'name', 'title', 'parent')
#
# class InterestSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Interest
# fields = ('_id', 'name', 'title', 'parent')
#
# class GoalSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Goal
# fields = ('_id', 'name', 'title', 'parent')
#
# class ProjectSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Project
# fields = ('_id', 'preview', 'title', 'summary', 'skills_needed', 'learning_opportunity', 'civic_interests', 'pending_tasks', 'progress_made', 'additional_info', 'slack_channel', 'github_repository')
#
# Path: components/admin/api/permissions.py
# class IsOwnerOrReadOnly(permissions.BasePermission):
# def has_object_permission(self, request, view, obj):
# if request.method in permissions.SAFE_METHODS:
# return True
# return obj.owner == request.user
. Output only the next line. | serializer_class = ProjectSerializer |
Here is a snippet: <|code_start|>
def index(request):
return render(request, 'index.html',)
def create_project(request):
return render(request, 'create_project/index.html',)
class SkillList(generics.ListCreateAPIView):
queryset = Skill.objects.all()
serializer_class = SkillSerializer
<|code_end|>
. Write the next line using the current file imports:
from django.http import HttpResponse, Http404
from django.shortcuts import render
from rest_framework import generics, permissions, status, mixins
from .models import Skill, Interest, Goal, Project
from .serializers import SkillSerializer, InterestSerializer, GoalSerializer, ProjectSerializer
from .permissions import IsOwnerOrReadOnly
from django.contrib.auth.models import User
from django.views.generic import TemplateView
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.views import APIView
and context from other files:
# Path: components/admin/api/models.py
# class Skill(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Skill, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Interest(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Interest, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Goal(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def __str__(self):
# return self.name
#
# def save(self, *args, **kwargs):
# super(Goal, self).save(*args, **kwargs)
#
# class Project(models.Model):
# id = models.AutoField(primary_key=True)
# project_lead = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True)
# preview = models.BooleanField(default=True) # project will only appear in Project List when set to False
#
# # UI properties
# title = models.CharField(max_length=454, null=True)
# summary = models.CharField(max_length=254)
# skills_needed = models.ManyToManyField(Skill)
# learning_opportunities = models.ManyToManyField(Goal)
# civic_interests = models.ManyToManyField(Interest)
# pending_tasks = models.CharField(max_length=454, null=True)
# progress_made = models.CharField(max_length=454, null=True)
# additional_info = models.CharField(max_length=454, null=True)
# slack_channel = models.CharField(max_length=200)
#
# # Admin properties
# github_repository = models.CharField(max_length=454, null=True)
# website = models.CharField(max_length=454, null=True)
# twitter = models.CharField(max_length=454, null=True)
#
# def save(self, *args, **kwargs):
# super(Project, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.title
#
# Path: components/admin/api/serializers.py
# class SkillSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Skill
# fields = ('_id', 'name', 'title', 'parent')
#
# class InterestSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Interest
# fields = ('_id', 'name', 'title', 'parent')
#
# class GoalSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Goal
# fields = ('_id', 'name', 'title', 'parent')
#
# class ProjectSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
# class Meta:
# model = Project
# fields = ('_id', 'preview', 'title', 'summary', 'skills_needed', 'learning_opportunity', 'civic_interests', 'pending_tasks', 'progress_made', 'additional_info', 'slack_channel', 'github_repository')
#
# Path: components/admin/api/permissions.py
# class IsOwnerOrReadOnly(permissions.BasePermission):
# def has_object_permission(self, request, view, obj):
# if request.method in permissions.SAFE_METHODS:
# return True
# return obj.owner == request.user
, which may include functions, classes, or code. Output only the next line. | permissions_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) |
Next line prediction: <|code_start|>
class ProjectTest(TestCase):
@classmethod
def set_up_test_data(cls):
<|code_end|>
. Use current file imports:
(from django.test import TestCase
from .models import Skill, Interest, Goal, Project)
and context including class names, function names, or small code snippets from other files:
# Path: components/admin/api/models.py
# class Skill(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Skill, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Interest(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def save(self, *args, **kwargs):
# super(Interest, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.name
#
# class Goal(models.Model):
# id = models.AutoField(primary_key=True)
# name = models.CharField(max_length=254)
# title = models.CharField(max_length=254)
# parent = models.CharField(max_length=254)
#
# def __str__(self):
# return self.name
#
# def save(self, *args, **kwargs):
# super(Goal, self).save(*args, **kwargs)
#
# class Project(models.Model):
# id = models.AutoField(primary_key=True)
# project_lead = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True)
# preview = models.BooleanField(default=True) # project will only appear in Project List when set to False
#
# # UI properties
# title = models.CharField(max_length=454, null=True)
# summary = models.CharField(max_length=254)
# skills_needed = models.ManyToManyField(Skill)
# learning_opportunities = models.ManyToManyField(Goal)
# civic_interests = models.ManyToManyField(Interest)
# pending_tasks = models.CharField(max_length=454, null=True)
# progress_made = models.CharField(max_length=454, null=True)
# additional_info = models.CharField(max_length=454, null=True)
# slack_channel = models.CharField(max_length=200)
#
# # Admin properties
# github_repository = models.CharField(max_length=454, null=True)
# website = models.CharField(max_length=454, null=True)
# twitter = models.CharField(max_length=454, null=True)
#
# def save(self, *args, **kwargs):
# super(Project, self).save(*args, **kwargs)
#
# def __str__(self):
# return self.title
. Output only the next line. | Project.objects.create(title="first project title") |
Based on the snippet: <|code_start|>#!/usr/bin/env python
sys.path.append(".")
sys.path.append("./chromabot")
def main():
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
from collections import defaultdict
from chromabot.config import Config
from chromabot.db import *
and context (classes, functions, sometimes code) from other files:
# Path: chromabot/config.py
# class Config(object):
#
# def __init__(self, conffile=None):
# # Try to locate our configuration directory
#
# proposals = [conffile, os.environ.get("CHROMABOT_CONFIG"),
# "../config/config.json", "./config/config.json",
# "/etc/chromabot/config.json"]
#
# if not self.check_exist(proposals):
# logging.error("Could not locate config file!")
# raise SystemExit
#
# self.refresh()
#
# def __getitem__(self, key):
# return self.data[key]
#
# def __getattr__(self, key):
# return self.data[key]
#
# def check_exist(self, proposed_paths):
# for fullpath in proposed_paths:
# if fullpath and os.path.exists(fullpath):
# self.conffile = fullpath
# return True
# return False
#
# def praw(self):
# """Return a praw.Reddit object configured according to this config"""
# ua = self.data["bot"]["useragent"]
# site = self.data["bot"].get('site')
#
# result = praw.Reddit(user_agent=ua, site_name=site)
# return result
#
# def refresh(self):
# with open(self.conffile) as data_file:
# self.data = json.loads(data_file.read())
#
# # Useful properties follow
# @property
# def dbstring(self):
# return self.data["db"]["connection"]
#
# @property
# def game(self):
# return self.data["game"]
#
# @property
# def headquarters(self):
# return self.data["bot"]["hq_sub"]
#
# @property
# def password(self):
# return self.data["bot"]["password"]
#
# @property
# def username(self):
# return self.data["bot"]["username"]
. Output only the next line. | config = Config() |
Using the snippet: <|code_start|>#!/usr/bin/env python
sys.path.append(".")
sys.path.append("./chromabot")
def main():
<|code_end|>
, determine the next line of code. You have imports:
import sys
from collections import defaultdict
from chromabot.config import Config
from chromabot.db import *
and context (class names, function names, or code) available:
# Path: chromabot/config.py
# class Config(object):
#
# def __init__(self, conffile=None):
# # Try to locate our configuration directory
#
# proposals = [conffile, os.environ.get("CHROMABOT_CONFIG"),
# "../config/config.json", "./config/config.json",
# "/etc/chromabot/config.json"]
#
# if not self.check_exist(proposals):
# logging.error("Could not locate config file!")
# raise SystemExit
#
# self.refresh()
#
# def __getitem__(self, key):
# return self.data[key]
#
# def __getattr__(self, key):
# return self.data[key]
#
# def check_exist(self, proposed_paths):
# for fullpath in proposed_paths:
# if fullpath and os.path.exists(fullpath):
# self.conffile = fullpath
# return True
# return False
#
# def praw(self):
# """Return a praw.Reddit object configured according to this config"""
# ua = self.data["bot"]["useragent"]
# site = self.data["bot"].get('site')
#
# result = praw.Reddit(user_agent=ua, site_name=site)
# return result
#
# def refresh(self):
# with open(self.conffile) as data_file:
# self.data = json.loads(data_file.read())
#
# # Useful properties follow
# @property
# def dbstring(self):
# return self.data["db"]["connection"]
#
# @property
# def game(self):
# return self.data["game"]
#
# @property
# def headquarters(self):
# return self.data["bot"]["hq_sub"]
#
# @property
# def password(self):
# return self.data["bot"]["password"]
#
# @property
# def username(self):
# return self.data["bot"]["username"]
. Output only the next line. | config = Config() |
Predict the next line after this snippet: <|code_start|># coding=utf-8
def extract_single_command(text):
cmd = utils.extract_command(text)
assert(len(cmd) > 0)
return cmd[0].strip()
class TestMovement(unittest.TestCase):
def testMoveCommand(self):
src = 'lead 10 to "hurfendurf"'
<|code_end|>
using the current file's imports:
import unittest
from chromabot import utils
from chromabot.commands import *
from chromabot.parser import parse
and any relevant context from other files:
# Path: chromabot/utils.py
# def base36decode(number):
# def extract_command(text):
# def forcelist(item):
# def name_to_id(name):
# def now():
# def num_to_team(number, config=None):
# def pairwise(iterable):
# def team_to_num(team):
# def timestr(secs=None):
# def version(config):
#
# Path: chromabot/parser.py
# def parse(s):
# result = root.parseString(s)
# return result[0]
. Output only the next line. | parsed = parse(src) |
Predict the next line for this snippet: <|code_start|> return query(cls, **kw).all()
def all_as_dict(cls):
result = {}
for item in all(cls):
result[item.name] = item
return result
def battle_adopt(battle, postid):
battle.ends = battle.begins + 10800
battle.display_ends = battle.ends
battle.submission_id="t3_%s" % postid
sess.commit()
def cancel_battle(battle):
global reddit
post = reddit.get_submission(
submission_id=name_to_id(battle.submission_id))
post.edit("*This battle has been canceled*")
sess.delete(battle)
sess.commit()
def context(player=None, comment=None):
if not player:
player = by_id(User, 1)
<|code_end|>
with the help of current file imports:
import code
import logging
import readline
import sys
from config import Config
from db import *
from utils import *
from chromabot.commands import Context, InvadeCommand
and context from other files:
# Path: chromabot/commands.py
# class Context(object):
# def __init__(self, player, config, session, comment, reddit):
# self.player = player # a DB object
# self.config = config
# self.session = session
# self.comment = comment # a praw object
# self.reddit = reddit # root praw object
#
# @failable
# def reply(self, reply, pm=True):
# verbose = self.config.bot.get("verbose_logging")
# was_comment = getattr(self.comment, 'was_comment', True)
# header = ""
# if was_comment and pm:
# header = ("(In response to [this comment](%s))" %
# self.comment.permalink)
# else: # It wasn't a comment, or pm = False
# if verbose:
# logging.info("Replying: %s" % reply)
# return self.comment.reply(reply)
#
# full_reply = "%s\n\n%s" % (header, reply)
# if verbose:
# logging.info("PMing: %s" % full_reply)
# self.reddit.send_message(self.player.name, "Chromabot reply",
# full_reply)
#
# @failable
# def submit(self, srname, title, text):
# return self.reddit.submit(srname, title=title, text=text)
#
# def team_name(self):
# return num_to_team(self.player.team, self.config)
#
# class InvadeCommand(Command):
# def __init__(self, tokens):
# self.where = tokens["where"].lower()
#
# @staticmethod
# @failable
# def post_invasion(title, battle, reddit):
# text = ("Negotiations have broken down, and the trumpets of "
# "war have sounded. Even now, civilians are being "
# "evacuated and the able-bodied drafted. The conflict "
# "will soon be upon you.\n\n"
# "Gather your forces while you can, for your enemy "
# "shall arrive at %s") % battle.begins_str()
# submitted = reddit.submit(battle.region.srname,
# title=title,
# text=text)
# return submitted
#
# def execute(self, context):
# dest = Region.get_region(self.where, context)
# if dest:
# now = time.mktime(time.localtime())
# begins = now + context.config["game"]["battle_delay"]
# battle = None
#
# if dest.capital is not None:
# invade = context.config['game']['capital_invasion']
# if invade == 'none':
# context.reply("You cannot invade the enemy capital")
# return
#
# try:
# battle = dest.invade(context.player, begins)
# if "battle_lockout" in context.config["game"]:
# battle.lockout = context.config["game"]["battle_lockout"]
# context.session.commit()
# except db.RankException:
# context.reply("You don't have the authority "
# "to invade a region!")
# except db.TeamException:
# context.reply("You can't invade %s, you already own it!" %
# dest.markdown())
# except db.NonAdjacentException:
# context.reply("%s is not next to any territory you control" %
# dest.markdown())
# except db.InProgressException as ipe:
# context.reply("%s is %s being invaded!" % (dest.markdown(),
# ipe.other.markdown("already")))
# except db.TimingException as te:
# context.reply(("%s is too fortified to be attacked. "
# "These fortifications will break down by %s") %
# (dest.markdown(), timestr(te.expected)))
#
# if battle:
# context.reply("**Confirmed** Battle will begin at %s" %
# battle.begins_str())
# title = ("[Invasion] The %s armies march on %s!" %
# (context.team_name(), dest.name))
# submitted = InvadeCommand.post_invasion(title, battle,
# context.reddit)
# if submitted:
# battle.submission_id = submitted.name
# context.session.commit()
# else:
# logging.warn("Couldn't submit invasion thread")
# context.session.rollback()
, which may contain function names, class names, or code. Output only the next line. | return Context(player, config, sess, comment, reddit) |
Given the following code snippet before the placeholder: <|code_start|> battle.ends = battle.begins + 10800
battle.display_ends = battle.ends
battle.submission_id="t3_%s" % postid
sess.commit()
def cancel_battle(battle):
global reddit
post = reddit.get_submission(
submission_id=name_to_id(battle.submission_id))
post.edit("*This battle has been canceled*")
sess.delete(battle)
sess.commit()
def context(player=None, comment=None):
if not player:
player = by_id(User, 1)
return Context(player, config, sess, comment, reddit)
def end_battle(battle):
battle.ends = battle.begins + 1
sess.commit()
def fast_battle(named='snooland'):
where = by_name(Region, named)
battle = where.new_battle_here(now() + 60)
<|code_end|>
, predict the next line using imports from the current file:
import code
import logging
import readline
import sys
from config import Config
from db import *
from utils import *
from chromabot.commands import Context, InvadeCommand
and context including class names, function names, and sometimes code from other files:
# Path: chromabot/commands.py
# class Context(object):
# def __init__(self, player, config, session, comment, reddit):
# self.player = player # a DB object
# self.config = config
# self.session = session
# self.comment = comment # a praw object
# self.reddit = reddit # root praw object
#
# @failable
# def reply(self, reply, pm=True):
# verbose = self.config.bot.get("verbose_logging")
# was_comment = getattr(self.comment, 'was_comment', True)
# header = ""
# if was_comment and pm:
# header = ("(In response to [this comment](%s))" %
# self.comment.permalink)
# else: # It wasn't a comment, or pm = False
# if verbose:
# logging.info("Replying: %s" % reply)
# return self.comment.reply(reply)
#
# full_reply = "%s\n\n%s" % (header, reply)
# if verbose:
# logging.info("PMing: %s" % full_reply)
# self.reddit.send_message(self.player.name, "Chromabot reply",
# full_reply)
#
# @failable
# def submit(self, srname, title, text):
# return self.reddit.submit(srname, title=title, text=text)
#
# def team_name(self):
# return num_to_team(self.player.team, self.config)
#
# class InvadeCommand(Command):
# def __init__(self, tokens):
# self.where = tokens["where"].lower()
#
# @staticmethod
# @failable
# def post_invasion(title, battle, reddit):
# text = ("Negotiations have broken down, and the trumpets of "
# "war have sounded. Even now, civilians are being "
# "evacuated and the able-bodied drafted. The conflict "
# "will soon be upon you.\n\n"
# "Gather your forces while you can, for your enemy "
# "shall arrive at %s") % battle.begins_str()
# submitted = reddit.submit(battle.region.srname,
# title=title,
# text=text)
# return submitted
#
# def execute(self, context):
# dest = Region.get_region(self.where, context)
# if dest:
# now = time.mktime(time.localtime())
# begins = now + context.config["game"]["battle_delay"]
# battle = None
#
# if dest.capital is not None:
# invade = context.config['game']['capital_invasion']
# if invade == 'none':
# context.reply("You cannot invade the enemy capital")
# return
#
# try:
# battle = dest.invade(context.player, begins)
# if "battle_lockout" in context.config["game"]:
# battle.lockout = context.config["game"]["battle_lockout"]
# context.session.commit()
# except db.RankException:
# context.reply("You don't have the authority "
# "to invade a region!")
# except db.TeamException:
# context.reply("You can't invade %s, you already own it!" %
# dest.markdown())
# except db.NonAdjacentException:
# context.reply("%s is not next to any territory you control" %
# dest.markdown())
# except db.InProgressException as ipe:
# context.reply("%s is %s being invaded!" % (dest.markdown(),
# ipe.other.markdown("already")))
# except db.TimingException as te:
# context.reply(("%s is too fortified to be attacked. "
# "These fortifications will break down by %s") %
# (dest.markdown(), timestr(te.expected)))
#
# if battle:
# context.reply("**Confirmed** Battle will begin at %s" %
# battle.begins_str())
# title = ("[Invasion] The %s armies march on %s!" %
# (context.team_name(), dest.name))
# submitted = InvadeCommand.post_invasion(title, battle,
# context.reddit)
# if submitted:
# battle.submission_id = submitted.name
# context.session.commit()
# else:
# logging.warn("Couldn't submit invasion thread")
# context.session.rollback()
. Output only the next line. | post = InvadeCommand.post_invasion("Fast battle go!", battle, |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
class FiveCProject(unittest.TestCase):
def setUp(self):
self.data_fname = 'test/data/test.fcd'
self.project_fname = 'test/data/test.fcp'
self.probability_fname = 'test/data/test_probability.fcp'
self.express_fname = 'test/data/test_express.fcp'
self.binning_fname = 'test/data/test_binning.fcp'
self.raw = h5py.File(self.project_fname, 'r')
<|code_end|>
using the current file's imports:
import os
import sys
import subprocess
import unittest
import numpy
import h5py
from operator import mul
from hifive import fivec
and any relevant context from other files:
# Path: hifive/fivec.py
# class FiveC(object):
# def __init__(self, filename, mode='r', silent=False):
# def __getitem__(self, key):
# def __setitem__(self, key, value):
# def load_data(self, filename):
# def save(self, out_fname=None):
# def load(self):
# def filter_fragments(self, mininteractions=20, mindistance=0, maxdistance=0):
# def find_distance_parameters(self):
# def find_probability_fragment_corrections(self, mindistance=0, maxdistance=0, max_iterations=1000,
# minchange=0.0005, learningstep=0.1, precalculate=True, regions=[],
# precorrect=False):
# def find_express_fragment_corrections(self, mindistance=0, maxdistance=0, iterations=1000, remove_distance=False,
# usereads='cis', regions=[], precorrect=False, logged=True, kr=False):
# def _find_kr_corrections(self, mindistance=0, maxdistance=0, remove_distance=True,
# usereads='cis', regions=[], precorrect=False, logged=False):
# def find_binning_fragment_corrections(self, mindistance=0, maxdistance=0, model=['gc', 'len'], num_bins=[10, 10],
# parameters=['even', 'even'], learning_threshold=1.0, max_iterations=100,
# usereads='cis', regions=[], precorrect=False):
# def find_cor_sums(index, indices, corrections, correction_indices, cor_sums):
# def find_sigma2(counts, sums, cor_sums, n):
# def find_ll(counts, sums, cor_sums, n, sigma, sigma2):
# def temp_ll(x, *args):
# def temp_ll_grad(x, *args):
# def find_trans_mean(self):
# def cis_heatmap(self, region, binsize=0, binbounds=None, start=None, stop=None, startfrag=None, stopfrag=None,
# datatype='enrichment', arraytype='full', skipfiltered=False, returnmapping=False,
# dynamically_binned=False, minobservations=0, searchdistance=0, expansion_binsize=0,
# removefailed=False, image_file=None, **kwargs):
# def trans_heatmap(self, region1, region2, binsize=1000000, binbounds1=None, start1=None, stop1=None,
# startfrag1=None, stopfrag1=None, binbounds2=None, start2=None, stop2=None, startfrag2=None,
# stopfrag2=None, datatype='enrichment', arraytype='full', returnmapping=False,
# dynamically_binned=False, minobservations=0, searchdistance=0, expansion_binsize=0,
# removefailed=False, skipfiltered=False, image_file=None, **kwargs):
# def write_heatmap(self, filename, binsize, includetrans=True, datatype='enrichment', arraytype='full',
# regions=[], dynamically_binned=False, minobservations=0, searchdistance=0, expansion_binsize=0,
# removefailed=False, format='hdf5'):
# Z = rk / v
# Z = rk / v
# M = numpy.sum(counts * cor_sums2 + sums[:, 1] - 2.0 * cor_sums1 * sums[:, 0])
# N = 1.0 / (n - 1.0) * numpy.sum(2.0 * counts * cor_sums1 - 2.0 * sums[:, 0])
# O = N / (2.0 * sigma)
. Output only the next line. | self.probability = fivec.FiveC(self.probability_fname, 'r') |
Given snippet: <|code_start|> self.compare_hdf5_dicts(self.bam_data, data, 'data')
def test_hic_bin_raw_data_creation(self):
subprocess.call("./bin/hifive hic-data -q -R %s -i 500 %s test/data/test_temp.hcd" %
(self.raw_fname, self.binned_fend_fname), shell=True)
data = h5py.File('test/data/test_temp.hcd', 'r')
self.compare_hdf5_dicts(self.bin_raw_data, data, 'data')
def test_hic_bin_mat_data_creation(self):
subprocess.call("./bin/hifive hic-data -q -M %s -i 500 %s test/data/test_temp.hcd" %
(self.mat_fname, self.binned_fend_fname), shell=True)
data = h5py.File('test/data/test_temp.hcd', 'r')
self.compare_hdf5_dicts(self.bin_mat_data, data, 'data')
def test_hic_bin_bam_data_creation(self):
if 'pysam' not in sys.modules.keys():
print >> sys.stderr, "pysam required for bam import"
return None
subprocess.call("./bin/hifive hic-data -q -S %s %s -i 500 %s test/data/test_temp.hcd" %
(self.bam_fname1, self.bam_fname2, self.binned_fend_fname), shell=True)
data = h5py.File('test/data/test_temp.hcd', 'r')
self.compare_hdf5_dicts(self.bin_bam_data, data, 'data')
def test_hic_matrix_data_creation(self):
subprocess.call("./bin/hifive hic-data -q -X '%s' -i 500 %s test/data/test_temp.hcd" %
(self.matrix_fname, self.binned_fend_fname), shell=True)
data = h5py.File('test/data/test_temp.hcd', 'r')
self.compare_hdf5_dicts(self.matrix_data, data, 'data')
def test_hic_mat_export(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import sys
import subprocess
import unittest
import numpy
import pysam
import h5py
from operator import mul
from hifive import hic_data
and context:
# Path: hifive/hic_data.py
# class HiCData(object):
# def __init__(self, filename, mode='r', silent=False):
# def __getitem__(self, key):
# def __setitem__(self, key, value):
# def save(self):
# def load(self):
# def _find_cut_sites(self):
# def load_data_from_raw(self, fendfilename, filelist, maxinsert, skip_duplicate_filtering=False):
# def load_data_from_bam(self, fendfilename, filelist, maxinsert, skip_duplicate_filtering=False):
# def load_data_from_mat(self, fendfilename, filename, basefend=0):
# def _load_binned_data_from_mat(self, filename):
# def load_binned_data_from_matrices(self, fendfilename, filename, format=None):
# def _load_txt_matrices(self, data, filename, chroms, bins, bin_indices):
# def _load_hdf5_npz_matrices(self, data, filename, chroms, bins, bin_indices, format):
# def _find_fend_pairs(self, data, fend_pairs, skip_duplicate_filtering=False):
# def _find_bin_pairs(self, data, bin_pairs, skip_duplicate_filtering=False):
# def _clean_fend_pairs(self, fend_pairs):
# def _parse_fend_pairs(self, fend_pairs):
# def _parse_binned_fend_pairs(self, fend_pairs):
# def export_to_mat(self, outfilename):
# N = pos1.shape[0]
# N = (-0.5 + (0.25 + 2 * tempdata.shape[0]))
# N = (0.5 + (0.25 + 2 * tempdata.shape[0]))
# N, M = tempdata.shape
which might include code, classes, or functions. Output only the next line. | data = hic_data.HiCData('test/data/test_import_raw.hcd', 'r', silent=True) |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
class FiveCBinning(unittest.TestCase):
def setUp(self):
self.project_fname = 'test/data/test_probability.fcp'
self.binned_fname = 'test/data/test_binned.hdf5'
self.heatmap_fname = 'test/data/test.fch'
self.data = h5py.File(self.binned_fname, 'r')
self.heatmap = h5py.File(self.heatmap_fname, 'r')
<|code_end|>
using the current file's imports:
import os
import sys
import subprocess
import unittest
import numpy
import h5py
from operator import mul
from hifive import fivec
and any relevant context from other files:
# Path: hifive/fivec.py
# class FiveC(object):
# def __init__(self, filename, mode='r', silent=False):
# def __getitem__(self, key):
# def __setitem__(self, key, value):
# def load_data(self, filename):
# def save(self, out_fname=None):
# def load(self):
# def filter_fragments(self, mininteractions=20, mindistance=0, maxdistance=0):
# def find_distance_parameters(self):
# def find_probability_fragment_corrections(self, mindistance=0, maxdistance=0, max_iterations=1000,
# minchange=0.0005, learningstep=0.1, precalculate=True, regions=[],
# precorrect=False):
# def find_express_fragment_corrections(self, mindistance=0, maxdistance=0, iterations=1000, remove_distance=False,
# usereads='cis', regions=[], precorrect=False, logged=True, kr=False):
# def _find_kr_corrections(self, mindistance=0, maxdistance=0, remove_distance=True,
# usereads='cis', regions=[], precorrect=False, logged=False):
# def find_binning_fragment_corrections(self, mindistance=0, maxdistance=0, model=['gc', 'len'], num_bins=[10, 10],
# parameters=['even', 'even'], learning_threshold=1.0, max_iterations=100,
# usereads='cis', regions=[], precorrect=False):
# def find_cor_sums(index, indices, corrections, correction_indices, cor_sums):
# def find_sigma2(counts, sums, cor_sums, n):
# def find_ll(counts, sums, cor_sums, n, sigma, sigma2):
# def temp_ll(x, *args):
# def temp_ll_grad(x, *args):
# def find_trans_mean(self):
# def cis_heatmap(self, region, binsize=0, binbounds=None, start=None, stop=None, startfrag=None, stopfrag=None,
# datatype='enrichment', arraytype='full', skipfiltered=False, returnmapping=False,
# dynamically_binned=False, minobservations=0, searchdistance=0, expansion_binsize=0,
# removefailed=False, image_file=None, **kwargs):
# def trans_heatmap(self, region1, region2, binsize=1000000, binbounds1=None, start1=None, stop1=None,
# startfrag1=None, stopfrag1=None, binbounds2=None, start2=None, stop2=None, startfrag2=None,
# stopfrag2=None, datatype='enrichment', arraytype='full', returnmapping=False,
# dynamically_binned=False, minobservations=0, searchdistance=0, expansion_binsize=0,
# removefailed=False, skipfiltered=False, image_file=None, **kwargs):
# def write_heatmap(self, filename, binsize, includetrans=True, datatype='enrichment', arraytype='full',
# regions=[], dynamically_binned=False, minobservations=0, searchdistance=0, expansion_binsize=0,
# removefailed=False, format='hdf5'):
# Z = rk / v
# Z = rk / v
# M = numpy.sum(counts * cor_sums2 + sums[:, 1] - 2.0 * cor_sums1 * sums[:, 0])
# N = 1.0 / (n - 1.0) * numpy.sum(2.0 * counts * cor_sums1 - 2.0 * sums[:, 0])
# O = N / (2.0 * sigma)
. Output only the next line. | self.project = fivec.FiveC(self.project_fname, 'r', silent=True) |
Predict the next line after this snippet: <|code_start|>
class DRFDocsViewTests(TestCase):
SETTINGS_HIDE_DOCS = {
'HIDE_DOCS': True # Default: False
}
def setUp(self):
super(DRFDocsViewTests, self).setUp()
def test_settings_module(self):
<|code_end|>
using the current file's imports:
from django.core.urlresolvers import reverse
from django.test import TestCase, override_settings
from rest_framework_docs.settings import DRFSettings
and any relevant context from other files:
# Path: rest_framework_docs/settings.py
# class DRFSettings(object):
#
# def __init__(self):
# self.drf_settings = {
# "HIDE_DOCS": self.get_setting("HIDE_DOCS") or False
# }
#
# def get_setting(self, name):
# try:
# return settings.REST_FRAMEWORK_DOCS[name]
# except:
# return None
#
# @property
# def settings(self):
# return self.drf_settings
. Output only the next line. | settings = DRFSettings() |
Given snippet: <|code_start|>
class DRFDocsView(TemplateView):
template_name = "rest_framework_docs/home.html"
drf_router = None
def get_context_data(self, **kwargs):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.http import Http404
from django.views.generic.base import TemplateView
from rest_framework_docs.api_docs import ApiDocumentation
from rest_framework_docs.settings import DRFSettings
and context:
# Path: rest_framework_docs/settings.py
# class DRFSettings(object):
#
# def __init__(self):
# self.drf_settings = {
# "HIDE_DOCS": self.get_setting("HIDE_DOCS") or False
# }
#
# def get_setting(self, name):
# try:
# return settings.REST_FRAMEWORK_DOCS[name]
# except:
# return None
#
# @property
# def settings(self):
# return self.drf_settings
which might include code, classes, or functions. Output only the next line. | settings = DRFSettings().settings |
Given the code snippet: <|code_start|> Lazy-loading of the S3 boto connection. Refer to this instead of
referencing self._aws_s3_connection directly.
:param str access_key: The AWS_ Access Key needed to get to the
file in question.
:param str secret_access_key: The AWS_ Secret Access Key needed to get
to the file in question.
:rtype: :py:class:`boto.s3.connection.Connection`
:returns: A boto connection to Amazon's S3 interface.
"""
return boto.connect_s3(access_key, secret_access_key)
@classmethod
def download_file(cls, uri, fobj):
"""
Given a URI, download the file to the ``fobj`` file-like object.
:param str uri: The URI of a file to download.
:param file fobj: A file-like object to download the file to.
:rtype: file
:returns: A file handle to the downloaded file.
"""
# Breaks the URI into usable componenents.
values = get_values_from_media_uri(uri)
conn = cls._get_aws_s3_connection(values['username'],
values['password'])
bucket = conn.get_bucket(values['host'])
key = bucket.get_key(values['path'])
<|code_end|>
, generate the next line using the imports in this file:
import boto
from media_nommer.utils import logger
from media_nommer.utils.uri_parsing import get_values_from_media_uri
from media_nommer.core.storage_backends.exceptions import InfileNotFoundException
from media_nommer.core.storage_backends.base_backend import BaseStorageBackend
and context (functions, classes, or occasionally code) from other files:
# Path: media_nommer/utils/logger.py
# def debug(message):
# def info(message):
# def warning(message):
# def error(message_or_obj=None):
#
# Path: media_nommer/utils/uri_parsing.py
# def get_values_from_media_uri(uri_str):
# """
# Given a valid URI string, break it up into its component pieces like
# protocol, hostname, and path, along with some optional elements like
# username, password, and port. All of these values are returned in a dict.
#
# The following keys should always be in the dict:
# * protocol
# * host
# * path
#
# The following are set when present, but absent when not:
# * port
# * username
# * password
#
# :param str uri_str: A valid URI string.
# :returns: A dict of strings.
# """
# # The dict that will be later returned.
# values = {}
#
# dslash_split = uri_str.split('://', 1)
# values['protocol'] = dslash_split[0]
# try:
# url_str = dslash_split[1]
# except IndexError:
# # If this split fails, we've definitely forgotten the protocol.
# msg = 'No protocol specified. Pre-pend "proto://" to your current ' \
# 'value of "%s", where "proto" is your choice of protocol.' % uri_str
# raise InvalidUri(msg)
#
# # An '@' symbol indicates the presence of a username and/or username+pass.
# has_auth_details = '@' in url_str
# if has_auth_details:
# auth_host_split = url_str.split('@', 1)
# # Should be just the username or username@pass.
# auth_details = auth_host_split[0]
#
# # A colon is used to separate username from passwords.
# has_password = ':' in auth_details
# if has_password:
# user_pass_split = auth_details.split(':', 1)
# values['username'] = user_pass_split[0]
# values['password'] = user_pass_split[1]
# else:
# values['username'] = auth_details
#
# # Seperated the host/path from auth details.
# host_and_path = auth_host_split[1]
# else:
# host_and_path = url_str
#
# # Split the host and path up.
# host_path_split = host_and_path.split('/', 1)
# values['host'] = host_path_split[0]
#
# try:
# values['path'] = host_path_split[1]
# except IndexError:
# # This means that no trailing slash was present in the URI str after
# # the host was specified. Assume they mean the root path.
# values['path'] = '/'
#
# if ':' in values['host']:
# # Looks like they specified a port.
# host_port_split = values['host'].split(':')
# values['host'] = host_port_split[0]
# values['port'] = host_port_split[1]
#
# return values
#
# Path: media_nommer/core/storage_backends/exceptions.py
# class InfileNotFoundException(StorageException):
# """
# Raised by storage backends when the given source_path (the media to encode)
# cannot be found.
# """
# pass
#
# Path: media_nommer/core/storage_backends/base_backend.py
# class BaseStorageBackend(object):
# """
# This class serves as a protocol for storage backends. Each storage backend
# should override the following methods, if supported by whatever protocols
# they interact with.
# """
# @classmethod
# def download_file(cls, uri, fobj):
# """
# Given a URI, download the file to the ``fobj`` file-like object.
#
# :param str uri: The URI of a file to download.
# :param file fobj: A file-like object to download the file to.
# :rtype: file
# :returns: A file handle to the downloaded file.
# """
# msg = "Backend doesn't implement download_file()"
# raise NotImplementedError(msg)
#
# @classmethod
# def upload_file(cls, uri, fobj):
# """
# Given a file-like object, upload it to the specified URI.
#
# :param str uri: The URI to upload the file to.
# :param file fobj: The file-like object to upload.
# :returns: Return value and type depends on backend.
# """
# msg = "Backend doesn't implement upload_file()"
# raise NotImplementedError(msg)
. Output only the next line. | logger.debug("S3Backend.download_file(): " \ |
Next line prediction: <|code_start|>class S3Backend(BaseStorageBackend):
"""
Abstracts access to S3 via the common set of file storage backend methods.
"""
@classmethod
def _get_aws_s3_connection(cls, access_key, secret_access_key):
"""
Lazy-loading of the S3 boto connection. Refer to this instead of
referencing self._aws_s3_connection directly.
:param str access_key: The AWS_ Access Key needed to get to the
file in question.
:param str secret_access_key: The AWS_ Secret Access Key needed to get
to the file in question.
:rtype: :py:class:`boto.s3.connection.Connection`
:returns: A boto connection to Amazon's S3 interface.
"""
return boto.connect_s3(access_key, secret_access_key)
@classmethod
def download_file(cls, uri, fobj):
"""
Given a URI, download the file to the ``fobj`` file-like object.
:param str uri: The URI of a file to download.
:param file fobj: A file-like object to download the file to.
:rtype: file
:returns: A file handle to the downloaded file.
"""
# Breaks the URI into usable componenents.
<|code_end|>
. Use current file imports:
(import boto
from media_nommer.utils import logger
from media_nommer.utils.uri_parsing import get_values_from_media_uri
from media_nommer.core.storage_backends.exceptions import InfileNotFoundException
from media_nommer.core.storage_backends.base_backend import BaseStorageBackend)
and context including class names, function names, or small code snippets from other files:
# Path: media_nommer/utils/logger.py
# def debug(message):
# def info(message):
# def warning(message):
# def error(message_or_obj=None):
#
# Path: media_nommer/utils/uri_parsing.py
# def get_values_from_media_uri(uri_str):
# """
# Given a valid URI string, break it up into its component pieces like
# protocol, hostname, and path, along with some optional elements like
# username, password, and port. All of these values are returned in a dict.
#
# The following keys should always be in the dict:
# * protocol
# * host
# * path
#
# The following are set when present, but absent when not:
# * port
# * username
# * password
#
# :param str uri_str: A valid URI string.
# :returns: A dict of strings.
# """
# # The dict that will be later returned.
# values = {}
#
# dslash_split = uri_str.split('://', 1)
# values['protocol'] = dslash_split[0]
# try:
# url_str = dslash_split[1]
# except IndexError:
# # If this split fails, we've definitely forgotten the protocol.
# msg = 'No protocol specified. Pre-pend "proto://" to your current ' \
# 'value of "%s", where "proto" is your choice of protocol.' % uri_str
# raise InvalidUri(msg)
#
# # An '@' symbol indicates the presence of a username and/or username+pass.
# has_auth_details = '@' in url_str
# if has_auth_details:
# auth_host_split = url_str.split('@', 1)
# # Should be just the username or username@pass.
# auth_details = auth_host_split[0]
#
# # A colon is used to separate username from passwords.
# has_password = ':' in auth_details
# if has_password:
# user_pass_split = auth_details.split(':', 1)
# values['username'] = user_pass_split[0]
# values['password'] = user_pass_split[1]
# else:
# values['username'] = auth_details
#
# # Seperated the host/path from auth details.
# host_and_path = auth_host_split[1]
# else:
# host_and_path = url_str
#
# # Split the host and path up.
# host_path_split = host_and_path.split('/', 1)
# values['host'] = host_path_split[0]
#
# try:
# values['path'] = host_path_split[1]
# except IndexError:
# # This means that no trailing slash was present in the URI str after
# # the host was specified. Assume they mean the root path.
# values['path'] = '/'
#
# if ':' in values['host']:
# # Looks like they specified a port.
# host_port_split = values['host'].split(':')
# values['host'] = host_port_split[0]
# values['port'] = host_port_split[1]
#
# return values
#
# Path: media_nommer/core/storage_backends/exceptions.py
# class InfileNotFoundException(StorageException):
# """
# Raised by storage backends when the given source_path (the media to encode)
# cannot be found.
# """
# pass
#
# Path: media_nommer/core/storage_backends/base_backend.py
# class BaseStorageBackend(object):
# """
# This class serves as a protocol for storage backends. Each storage backend
# should override the following methods, if supported by whatever protocols
# they interact with.
# """
# @classmethod
# def download_file(cls, uri, fobj):
# """
# Given a URI, download the file to the ``fobj`` file-like object.
#
# :param str uri: The URI of a file to download.
# :param file fobj: A file-like object to download the file to.
# :rtype: file
# :returns: A file handle to the downloaded file.
# """
# msg = "Backend doesn't implement download_file()"
# raise NotImplementedError(msg)
#
# @classmethod
# def upload_file(cls, uri, fobj):
# """
# Given a file-like object, upload it to the specified URI.
#
# :param str uri: The URI to upload the file to.
# :param file fobj: The file-like object to upload.
# :returns: Return value and type depends on backend.
# """
# msg = "Backend doesn't implement upload_file()"
# raise NotImplementedError(msg)
. Output only the next line. | values = get_values_from_media_uri(uri) |
Based on the snippet: <|code_start|> """
return boto.connect_s3(access_key, secret_access_key)
@classmethod
def download_file(cls, uri, fobj):
"""
Given a URI, download the file to the ``fobj`` file-like object.
:param str uri: The URI of a file to download.
:param file fobj: A file-like object to download the file to.
:rtype: file
:returns: A file handle to the downloaded file.
"""
# Breaks the URI into usable componenents.
values = get_values_from_media_uri(uri)
conn = cls._get_aws_s3_connection(values['username'],
values['password'])
bucket = conn.get_bucket(values['host'])
key = bucket.get_key(values['path'])
logger.debug("S3Backend.download_file(): " \
"Downloading: %s" % uri)
try:
key.get_contents_to_file(fobj)
except AttributeError:
# Raised by ResumableDownloadHandler in boto when the given S3
# key can't be found.
message = "The specified input file cannot be found."
<|code_end|>
, predict the immediate next line with the help of imports:
import boto
from media_nommer.utils import logger
from media_nommer.utils.uri_parsing import get_values_from_media_uri
from media_nommer.core.storage_backends.exceptions import InfileNotFoundException
from media_nommer.core.storage_backends.base_backend import BaseStorageBackend
and context (classes, functions, sometimes code) from other files:
# Path: media_nommer/utils/logger.py
# def debug(message):
# def info(message):
# def warning(message):
# def error(message_or_obj=None):
#
# Path: media_nommer/utils/uri_parsing.py
# def get_values_from_media_uri(uri_str):
# """
# Given a valid URI string, break it up into its component pieces like
# protocol, hostname, and path, along with some optional elements like
# username, password, and port. All of these values are returned in a dict.
#
# The following keys should always be in the dict:
# * protocol
# * host
# * path
#
# The following are set when present, but absent when not:
# * port
# * username
# * password
#
# :param str uri_str: A valid URI string.
# :returns: A dict of strings.
# """
# # The dict that will be later returned.
# values = {}
#
# dslash_split = uri_str.split('://', 1)
# values['protocol'] = dslash_split[0]
# try:
# url_str = dslash_split[1]
# except IndexError:
# # If this split fails, we've definitely forgotten the protocol.
# msg = 'No protocol specified. Pre-pend "proto://" to your current ' \
# 'value of "%s", where "proto" is your choice of protocol.' % uri_str
# raise InvalidUri(msg)
#
# # An '@' symbol indicates the presence of a username and/or username+pass.
# has_auth_details = '@' in url_str
# if has_auth_details:
# auth_host_split = url_str.split('@', 1)
# # Should be just the username or username@pass.
# auth_details = auth_host_split[0]
#
# # A colon is used to separate username from passwords.
# has_password = ':' in auth_details
# if has_password:
# user_pass_split = auth_details.split(':', 1)
# values['username'] = user_pass_split[0]
# values['password'] = user_pass_split[1]
# else:
# values['username'] = auth_details
#
# # Seperated the host/path from auth details.
# host_and_path = auth_host_split[1]
# else:
# host_and_path = url_str
#
# # Split the host and path up.
# host_path_split = host_and_path.split('/', 1)
# values['host'] = host_path_split[0]
#
# try:
# values['path'] = host_path_split[1]
# except IndexError:
# # This means that no trailing slash was present in the URI str after
# # the host was specified. Assume they mean the root path.
# values['path'] = '/'
#
# if ':' in values['host']:
# # Looks like they specified a port.
# host_port_split = values['host'].split(':')
# values['host'] = host_port_split[0]
# values['port'] = host_port_split[1]
#
# return values
#
# Path: media_nommer/core/storage_backends/exceptions.py
# class InfileNotFoundException(StorageException):
# """
# Raised by storage backends when the given source_path (the media to encode)
# cannot be found.
# """
# pass
#
# Path: media_nommer/core/storage_backends/base_backend.py
# class BaseStorageBackend(object):
# """
# This class serves as a protocol for storage backends. Each storage backend
# should override the following methods, if supported by whatever protocols
# they interact with.
# """
# @classmethod
# def download_file(cls, uri, fobj):
# """
# Given a URI, download the file to the ``fobj`` file-like object.
#
# :param str uri: The URI of a file to download.
# :param file fobj: A file-like object to download the file to.
# :rtype: file
# :returns: A file handle to the downloaded file.
# """
# msg = "Backend doesn't implement download_file()"
# raise NotImplementedError(msg)
#
# @classmethod
# def upload_file(cls, uri, fobj):
# """
# Given a file-like object, upload it to the specified URI.
#
# :param str uri: The URI to upload the file to.
# :param file fobj: The file-like object to upload.
# :returns: Return value and type depends on backend.
# """
# msg = "Backend doesn't implement upload_file()"
# raise NotImplementedError(msg)
. Output only the next line. | raise InfileNotFoundException(message) |
Given the code snippet: <|code_start|>"""
This module contains an FileBackend class for working with URIs that have
an file:// URI specified. This is for local files (from ec2nommerd's perspective),
more specifically.
"""
class FileBackend(BaseStorageBackend):
"""
Abstracts access to local files via the common set of file storage backend
methods.
"""
@classmethod
def download_file(cls, uri, fobj):
"""
Given a URI, open said file from the local file system.
:param str uri: The URI of a file to open.
:param file fobj: This is unused in this backend, but here for
the sake of consistency.
:rtype: file
:returns: A file handle to the given file.
"""
infile_path = cls._get_path_from_uri(uri)
if not os.path.exists(infile_path):
message = "The specified input file cannot be found: %s" % infile_path
raise InfileNotFoundException(message)
<|code_end|>
, generate the next line using the imports in this file:
import os
import urlparse
import shutil
from media_nommer.utils import logger
from media_nommer.core.storage_backends.exceptions import InfileNotFoundException
from media_nommer.core.storage_backends.base_backend import BaseStorageBackend
and context (functions, classes, or occasionally code) from other files:
# Path: media_nommer/utils/logger.py
# def debug(message):
# def info(message):
# def warning(message):
# def error(message_or_obj=None):
#
# Path: media_nommer/core/storage_backends/exceptions.py
# class InfileNotFoundException(StorageException):
# """
# Raised by storage backends when the given source_path (the media to encode)
# cannot be found.
# """
# pass
#
# Path: media_nommer/core/storage_backends/base_backend.py
# class BaseStorageBackend(object):
# """
# This class serves as a protocol for storage backends. Each storage backend
# should override the following methods, if supported by whatever protocols
# they interact with.
# """
# @classmethod
# def download_file(cls, uri, fobj):
# """
# Given a URI, download the file to the ``fobj`` file-like object.
#
# :param str uri: The URI of a file to download.
# :param file fobj: A file-like object to download the file to.
# :rtype: file
# :returns: A file handle to the downloaded file.
# """
# msg = "Backend doesn't implement download_file()"
# raise NotImplementedError(msg)
#
# @classmethod
# def upload_file(cls, uri, fobj):
# """
# Given a file-like object, upload it to the specified URI.
#
# :param str uri: The URI to upload the file to.
# :param file fobj: The file-like object to upload.
# :returns: Return value and type depends on backend.
# """
# msg = "Backend doesn't implement upload_file()"
# raise NotImplementedError(msg)
. Output only the next line. | logger.debug("FileBackend.download_file(): " \ |
Given the code snippet: <|code_start|>"""
This module contains an FileBackend class for working with URIs that have
an file:// URI specified. This is for local files (from ec2nommerd's perspective),
more specifically.
"""
class FileBackend(BaseStorageBackend):
"""
Abstracts access to local files via the common set of file storage backend
methods.
"""
@classmethod
def download_file(cls, uri, fobj):
"""
Given a URI, open said file from the local file system.
:param str uri: The URI of a file to open.
:param file fobj: This is unused in this backend, but here for
the sake of consistency.
:rtype: file
:returns: A file handle to the given file.
"""
infile_path = cls._get_path_from_uri(uri)
if not os.path.exists(infile_path):
message = "The specified input file cannot be found: %s" % infile_path
<|code_end|>
, generate the next line using the imports in this file:
import os
import urlparse
import shutil
from media_nommer.utils import logger
from media_nommer.core.storage_backends.exceptions import InfileNotFoundException
from media_nommer.core.storage_backends.base_backend import BaseStorageBackend
and context (functions, classes, or occasionally code) from other files:
# Path: media_nommer/utils/logger.py
# def debug(message):
# def info(message):
# def warning(message):
# def error(message_or_obj=None):
#
# Path: media_nommer/core/storage_backends/exceptions.py
# class InfileNotFoundException(StorageException):
# """
# Raised by storage backends when the given source_path (the media to encode)
# cannot be found.
# """
# pass
#
# Path: media_nommer/core/storage_backends/base_backend.py
# class BaseStorageBackend(object):
# """
# This class serves as a protocol for storage backends. Each storage backend
# should override the following methods, if supported by whatever protocols
# they interact with.
# """
# @classmethod
# def download_file(cls, uri, fobj):
# """
# Given a URI, download the file to the ``fobj`` file-like object.
#
# :param str uri: The URI of a file to download.
# :param file fobj: A file-like object to download the file to.
# :rtype: file
# :returns: A file handle to the downloaded file.
# """
# msg = "Backend doesn't implement download_file()"
# raise NotImplementedError(msg)
#
# @classmethod
# def upload_file(cls, uri, fobj):
# """
# Given a file-like object, upload it to the specified URI.
#
# :param str uri: The URI to upload the file to.
# :param file fobj: The file-like object to upload.
# :returns: Return value and type depends on backend.
# """
# msg = "Backend doesn't implement upload_file()"
# raise NotImplementedError(msg)
. Output only the next line. | raise InfileNotFoundException(message) |
Using the snippet: <|code_start|>"""
This module contains an FileBackend class for working with URIs that have
an file:// URI specified. This is for local files (from ec2nommerd's perspective),
more specifically.
"""
<|code_end|>
, determine the next line of code. You have imports:
import os
import urlparse
import shutil
from media_nommer.utils import logger
from media_nommer.core.storage_backends.exceptions import InfileNotFoundException
from media_nommer.core.storage_backends.base_backend import BaseStorageBackend
and context (class names, function names, or code) available:
# Path: media_nommer/utils/logger.py
# def debug(message):
# def info(message):
# def warning(message):
# def error(message_or_obj=None):
#
# Path: media_nommer/core/storage_backends/exceptions.py
# class InfileNotFoundException(StorageException):
# """
# Raised by storage backends when the given source_path (the media to encode)
# cannot be found.
# """
# pass
#
# Path: media_nommer/core/storage_backends/base_backend.py
# class BaseStorageBackend(object):
# """
# This class serves as a protocol for storage backends. Each storage backend
# should override the following methods, if supported by whatever protocols
# they interact with.
# """
# @classmethod
# def download_file(cls, uri, fobj):
# """
# Given a URI, download the file to the ``fobj`` file-like object.
#
# :param str uri: The URI of a file to download.
# :param file fobj: A file-like object to download the file to.
# :rtype: file
# :returns: A file handle to the downloaded file.
# """
# msg = "Backend doesn't implement download_file()"
# raise NotImplementedError(msg)
#
# @classmethod
# def upload_file(cls, uri, fobj):
# """
# Given a file-like object, upload it to the specified URI.
#
# :param str uri: The URI to upload the file to.
# :param file fobj: The file-like object to upload.
# :returns: Return value and type depends on backend.
# """
# msg = "Backend doesn't implement upload_file()"
# raise NotImplementedError(msg)
. Output only the next line. | class FileBackend(BaseStorageBackend): |
Predict the next line for this snippet: <|code_start|>
class SettingsTests(unittest.TestCase):
def setUp(self):
"""
Create some settings objects with default settings in them.
"""
self.fake_defaults = FakeSettingsObj()
self.settings = SettingsStore(self.fake_defaults)
def test_overriding(self):
"""
Tests overriding default settings with the user-specified settings.
"""
# Pretend that this is the global default for some arbitrary setting.
self.settings.SOME_SETTING = 1
# Pretend like this is the user's settings module.
user_vals = FakeSettingsObj()
# The user has changed some setting to a non-default value.
user_vals.SOME_SETTING = 2
user_settings = SettingsStore(user_vals)
# Now load the user's settings over the defaults, like the daemon does.
self.settings.update_settings_from_module(user_settings)
# Make sure the new setting matches the user's values.
self.assert_(self.settings.SOME_SETTING == user_settings.SOME_SETTING)
class ModImportingTests(unittest.TestCase):
def test_valid_import(self):
"""
Test an import that should be valid.
"""
<|code_end|>
with the help of current file imports:
import unittest
from media_nommer.utils.conf import SettingsStore
from media_nommer.utils.mod_importing import import_class_from_module_string
from media_nommer.utils.uri_parsing import get_values_from_media_uri, InvalidUri
and context from other files:
# Path: media_nommer/utils/mod_importing.py
# def import_class_from_module_string(fqpn_str):
# """
# Given a FQPN for a class, import and return the class.
#
# :param str fqpn_str: The FQPN to the class to import.
# :returns: The class given in the FQPN.
# """
# components = fqpn_str.split('.')
# # Generate a FQPN with everything but the class name.
# nom_module_str = '.'.join(components[:-1])
# # Just the target module to import.
# class_name = components[-1]
# # Import the class's module and the class itself.
# nommer = __import__(nom_module_str, globals(), locals(), [class_name])
#
# try:
# return getattr(nommer, class_name)
# except AttributeError:
# raise ImportError('No class named %s' % class_name)
#
# Path: media_nommer/utils/uri_parsing.py
# def get_values_from_media_uri(uri_str):
# """
# Given a valid URI string, break it up into its component pieces like
# protocol, hostname, and path, along with some optional elements like
# username, password, and port. All of these values are returned in a dict.
#
# The following keys should always be in the dict:
# * protocol
# * host
# * path
#
# The following are set when present, but absent when not:
# * port
# * username
# * password
#
# :param str uri_str: A valid URI string.
# :returns: A dict of strings.
# """
# # The dict that will be later returned.
# values = {}
#
# dslash_split = uri_str.split('://', 1)
# values['protocol'] = dslash_split[0]
# try:
# url_str = dslash_split[1]
# except IndexError:
# # If this split fails, we've definitely forgotten the protocol.
# msg = 'No protocol specified. Pre-pend "proto://" to your current ' \
# 'value of "%s", where "proto" is your choice of protocol.' % uri_str
# raise InvalidUri(msg)
#
# # An '@' symbol indicates the presence of a username and/or username+pass.
# has_auth_details = '@' in url_str
# if has_auth_details:
# auth_host_split = url_str.split('@', 1)
# # Should be just the username or username@pass.
# auth_details = auth_host_split[0]
#
# # A colon is used to separate username from passwords.
# has_password = ':' in auth_details
# if has_password:
# user_pass_split = auth_details.split(':', 1)
# values['username'] = user_pass_split[0]
# values['password'] = user_pass_split[1]
# else:
# values['username'] = auth_details
#
# # Seperated the host/path from auth details.
# host_and_path = auth_host_split[1]
# else:
# host_and_path = url_str
#
# # Split the host and path up.
# host_path_split = host_and_path.split('/', 1)
# values['host'] = host_path_split[0]
#
# try:
# values['path'] = host_path_split[1]
# except IndexError:
# # This means that no trailing slash was present in the URI str after
# # the host was specified. Assume they mean the root path.
# values['path'] = '/'
#
# if ':' in values['host']:
# # Looks like they specified a port.
# host_port_split = values['host'].split(':')
# values['host'] = host_port_split[0]
# values['port'] = host_port_split[1]
#
# return values
#
# class InvalidUri(BaseException):
# """
# Raised when an invalid URI is passed to a function that consumes URIs.
# Make sure to instantiate with a helpful error message.
# """
# pass
, which may contain function names, class names, or code. Output only the next line. | import_class_from_module_string('media_nommer.client.api.APIConnection') |
Next line prediction: <|code_start|> # Now load the user's settings over the defaults, like the daemon does.
self.settings.update_settings_from_module(user_settings)
# Make sure the new setting matches the user's values.
self.assert_(self.settings.SOME_SETTING == user_settings.SOME_SETTING)
class ModImportingTests(unittest.TestCase):
def test_valid_import(self):
"""
Test an import that should be valid.
"""
import_class_from_module_string('media_nommer.client.api.APIConnection')
def test_invalid_import(self):
"""
Test some invalid imports to make sure exception raising is good.
"""
self.assertRaises(ImportError, import_class_from_module_string,
'media_nommer.client.api.NonExist')
self.assertRaises(ImportError, import_class_from_module_string,
'media_nommer.client.invalid_mod.APIConnection')
class MediaUriParsingTests(unittest.TestCase):
"""
Tests for media_nommer.utils.uri_parsing.get_values_from_media_uri()
"""
def test_valid_uri_parsing(self):
"""
Test a valid URI with most options specified (aside from port).
"""
valid_uri = 's3://SOMEUSER:SOME/PASS@some_bucket/some_dir/some_file.mpg'
<|code_end|>
. Use current file imports:
(import unittest
from media_nommer.utils.conf import SettingsStore
from media_nommer.utils.mod_importing import import_class_from_module_string
from media_nommer.utils.uri_parsing import get_values_from_media_uri, InvalidUri)
and context including class names, function names, or small code snippets from other files:
# Path: media_nommer/utils/mod_importing.py
# def import_class_from_module_string(fqpn_str):
# """
# Given a FQPN for a class, import and return the class.
#
# :param str fqpn_str: The FQPN to the class to import.
# :returns: The class given in the FQPN.
# """
# components = fqpn_str.split('.')
# # Generate a FQPN with everything but the class name.
# nom_module_str = '.'.join(components[:-1])
# # Just the target module to import.
# class_name = components[-1]
# # Import the class's module and the class itself.
# nommer = __import__(nom_module_str, globals(), locals(), [class_name])
#
# try:
# return getattr(nommer, class_name)
# except AttributeError:
# raise ImportError('No class named %s' % class_name)
#
# Path: media_nommer/utils/uri_parsing.py
# def get_values_from_media_uri(uri_str):
# """
# Given a valid URI string, break it up into its component pieces like
# protocol, hostname, and path, along with some optional elements like
# username, password, and port. All of these values are returned in a dict.
#
# The following keys should always be in the dict:
# * protocol
# * host
# * path
#
# The following are set when present, but absent when not:
# * port
# * username
# * password
#
# :param str uri_str: A valid URI string.
# :returns: A dict of strings.
# """
# # The dict that will be later returned.
# values = {}
#
# dslash_split = uri_str.split('://', 1)
# values['protocol'] = dslash_split[0]
# try:
# url_str = dslash_split[1]
# except IndexError:
# # If this split fails, we've definitely forgotten the protocol.
# msg = 'No protocol specified. Pre-pend "proto://" to your current ' \
# 'value of "%s", where "proto" is your choice of protocol.' % uri_str
# raise InvalidUri(msg)
#
# # An '@' symbol indicates the presence of a username and/or username+pass.
# has_auth_details = '@' in url_str
# if has_auth_details:
# auth_host_split = url_str.split('@', 1)
# # Should be just the username or username@pass.
# auth_details = auth_host_split[0]
#
# # A colon is used to separate username from passwords.
# has_password = ':' in auth_details
# if has_password:
# user_pass_split = auth_details.split(':', 1)
# values['username'] = user_pass_split[0]
# values['password'] = user_pass_split[1]
# else:
# values['username'] = auth_details
#
# # Seperated the host/path from auth details.
# host_and_path = auth_host_split[1]
# else:
# host_and_path = url_str
#
# # Split the host and path up.
# host_path_split = host_and_path.split('/', 1)
# values['host'] = host_path_split[0]
#
# try:
# values['path'] = host_path_split[1]
# except IndexError:
# # This means that no trailing slash was present in the URI str after
# # the host was specified. Assume they mean the root path.
# values['path'] = '/'
#
# if ':' in values['host']:
# # Looks like they specified a port.
# host_port_split = values['host'].split(':')
# values['host'] = host_port_split[0]
# values['port'] = host_port_split[1]
#
# return values
#
# class InvalidUri(BaseException):
# """
# Raised when an invalid URI is passed to a function that consumes URIs.
# Make sure to instantiate with a helpful error message.
# """
# pass
. Output only the next line. | values = get_values_from_media_uri(valid_uri) |
Predict the next line after this snippet: <|code_start|> self.assertEqual(values['path'], 'some_dir/some_file.mpg')
self.assertEqual(values.has_key('port'), False)
def test_valid_uri_minimal_parsing(self):
"""
Test a valid URI with a more minimal value.
"""
valid_uri = 'http://some-hostname.org:80/some_dir/some_file.mpg'
values = get_values_from_media_uri(valid_uri)
self.assertEqual(values['protocol'], 'http')
self.assertEqual(values.has_key('username'), False)
self.assertEqual(values.has_key('password'), False)
self.assertEqual(values['host'], 'some-hostname.org')
self.assertEqual(values['path'], 'some_dir/some_file.mpg')
self.assertEqual(values['port'], '80')
def test_valid_uri_no_path_parsing(self):
"""
If a path is omitted, assume that they're talking about the root path.
"""
valid_uri = 'http://some-hostname.org:80'
values = get_values_from_media_uri(valid_uri)
self.assertEqual(values['path'], '/')
def test_invalid_uri_no_protocol_parsing(self):
"""
Test an invalid URI that lacks a protocol.
"""
invalid_uri = 'some-hostname.org:80/some_dir/some_file.mpg'
<|code_end|>
using the current file's imports:
import unittest
from media_nommer.utils.conf import SettingsStore
from media_nommer.utils.mod_importing import import_class_from_module_string
from media_nommer.utils.uri_parsing import get_values_from_media_uri, InvalidUri
and any relevant context from other files:
# Path: media_nommer/utils/mod_importing.py
# def import_class_from_module_string(fqpn_str):
# """
# Given a FQPN for a class, import and return the class.
#
# :param str fqpn_str: The FQPN to the class to import.
# :returns: The class given in the FQPN.
# """
# components = fqpn_str.split('.')
# # Generate a FQPN with everything but the class name.
# nom_module_str = '.'.join(components[:-1])
# # Just the target module to import.
# class_name = components[-1]
# # Import the class's module and the class itself.
# nommer = __import__(nom_module_str, globals(), locals(), [class_name])
#
# try:
# return getattr(nommer, class_name)
# except AttributeError:
# raise ImportError('No class named %s' % class_name)
#
# Path: media_nommer/utils/uri_parsing.py
# def get_values_from_media_uri(uri_str):
# """
# Given a valid URI string, break it up into its component pieces like
# protocol, hostname, and path, along with some optional elements like
# username, password, and port. All of these values are returned in a dict.
#
# The following keys should always be in the dict:
# * protocol
# * host
# * path
#
# The following are set when present, but absent when not:
# * port
# * username
# * password
#
# :param str uri_str: A valid URI string.
# :returns: A dict of strings.
# """
# # The dict that will be later returned.
# values = {}
#
# dslash_split = uri_str.split('://', 1)
# values['protocol'] = dslash_split[0]
# try:
# url_str = dslash_split[1]
# except IndexError:
# # If this split fails, we've definitely forgotten the protocol.
# msg = 'No protocol specified. Pre-pend "proto://" to your current ' \
# 'value of "%s", where "proto" is your choice of protocol.' % uri_str
# raise InvalidUri(msg)
#
# # An '@' symbol indicates the presence of a username and/or username+pass.
# has_auth_details = '@' in url_str
# if has_auth_details:
# auth_host_split = url_str.split('@', 1)
# # Should be just the username or username@pass.
# auth_details = auth_host_split[0]
#
# # A colon is used to separate username from passwords.
# has_password = ':' in auth_details
# if has_password:
# user_pass_split = auth_details.split(':', 1)
# values['username'] = user_pass_split[0]
# values['password'] = user_pass_split[1]
# else:
# values['username'] = auth_details
#
# # Seperated the host/path from auth details.
# host_and_path = auth_host_split[1]
# else:
# host_and_path = url_str
#
# # Split the host and path up.
# host_path_split = host_and_path.split('/', 1)
# values['host'] = host_path_split[0]
#
# try:
# values['path'] = host_path_split[1]
# except IndexError:
# # This means that no trailing slash was present in the URI str after
# # the host was specified. Assume they mean the root path.
# values['path'] = '/'
#
# if ':' in values['host']:
# # Looks like they specified a port.
# host_port_split = values['host'].split(':')
# values['host'] = host_port_split[0]
# values['port'] = host_port_split[1]
#
# return values
#
# class InvalidUri(BaseException):
# """
# Raised when an invalid URI is passed to a function that consumes URIs.
# Make sure to instantiate with a helpful error message.
# """
# pass
. Output only the next line. | self.assertRaises(InvalidUri, get_values_from_media_uri, invalid_uri) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.