Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Using the snippet: <|code_start|>
@pytest.mark.django_db
def test_update_pet(client, api_urls):
pet1 = Pet.objects.create(name='henlo')
payload = {'name': 'worl', 'tag': 'bunner'}
resp = client.patch(
f'/api/pets/{pet1.id}',
json.dumps(payload),
content_type='application/json'
)
assert resp.status_code == 200
pet_data = get_data_from_response(client.get('/api/pets'))[0]
assert pet_data['name'] == 'worl'
assert pet_data['tag'] == 'bunner'
@pytest.mark.django_db
def test_invalid_operation(client, api_urls):
assert client.patch('/api/pets').status_code == 405
@pytest.mark.django_db
def test_invalid_body_format(client, api_urls):
with pytest.raises(ErroneousParameters) as ei:
client.post(
'/api/pets',
b'<pet></pet>',
content_type='application/xml'
)
<|code_end|>
, determine the next line of code. You have imports:
import json
import django.conf
import pytest
from django.utils.crypto import get_random_string
from lepo.excs import ErroneousParameters, InvalidBodyContent, InvalidBodyFormat
from lepo_tests.models import Pet
from lepo_tests.tests.utils import get_data_from_response
from lepo_tests.utils import urlconf_map
from django.urls import clear_url_caches, set_urlconf
from django.core.urlresolvers import clear_url_caches, set_urlconf
and context (class names, function names, or code) available:
# Path: lepo/excs.py
# class ErroneousParameters(Exception):
# def __init__(self, error_map, parameters):
# self.errors = error_map
# self.parameters = parameters
#
# class InvalidBodyContent(ValueError):
# pass
#
# class InvalidBodyFormat(ValueError):
# pass
#
# Path: lepo_tests/models.py
# class Pet(models.Model):
# name = models.CharField(max_length=128)
# tag = models.CharField(max_length=128, blank=True)
#
# Path: lepo_tests/tests/utils.py
# def get_data_from_response(response, status=200):
# if status and response.status_code != status:
# raise ValueError(f'failed status check ({response.status_code} != expected {status})') # pragma: no cover
# return json.loads(response.content.decode('utf-8'))
#
# Path: lepo_tests/utils.py
# def get_urlpatterns(handler_module, definition_file='swagger2/petstore-expanded.yaml'):
# def generate_urlconf_module(handler_style, version):
# def generate_urlconf_modules(handler_styles, versions):
# URLCONF_TEMPLATE = '''
# from lepo_tests.handlers import %(module)s
# from lepo_tests.utils import get_urlpatterns
# urlpatterns = get_urlpatterns(%(module)s, %(file)r)
# '''
. Output only the next line. | assert isinstance(ei.value.errors['pet'], InvalidBodyFormat) |
Given the following code snippet before the placeholder: <|code_start|>
@pytest.mark.django_db
@pytest.mark.parametrize('with_tag', (False, True))
def test_post_pet(client, api_urls, with_tag):
payload = {
'name': get_random_string(15),
}
if with_tag:
payload['tag'] = get_random_string(15)
pet = get_data_from_response(
client.post(
'/api/pets',
json.dumps(payload),
content_type='application/json'
)
)
assert pet['name'] == payload['name']
assert pet['id']
if with_tag:
assert pet['tag'] == payload['tag']
# Test we can get the pet from the API now
assert get_data_from_response(client.get('/api/pets')) == [pet]
assert get_data_from_response(client.get(f"/api/pets/{pet['id']}")) == pet
@pytest.mark.django_db
def test_search_by_tag(client, api_urls):
<|code_end|>
, predict the next line using imports from the current file:
import json
import django.conf
import pytest
from django.utils.crypto import get_random_string
from lepo.excs import ErroneousParameters, InvalidBodyContent, InvalidBodyFormat
from lepo_tests.models import Pet
from lepo_tests.tests.utils import get_data_from_response
from lepo_tests.utils import urlconf_map
from django.urls import clear_url_caches, set_urlconf
from django.core.urlresolvers import clear_url_caches, set_urlconf
and context including class names, function names, and sometimes code from other files:
# Path: lepo/excs.py
# class ErroneousParameters(Exception):
# def __init__(self, error_map, parameters):
# self.errors = error_map
# self.parameters = parameters
#
# class InvalidBodyContent(ValueError):
# pass
#
# class InvalidBodyFormat(ValueError):
# pass
#
# Path: lepo_tests/models.py
# class Pet(models.Model):
# name = models.CharField(max_length=128)
# tag = models.CharField(max_length=128, blank=True)
#
# Path: lepo_tests/tests/utils.py
# def get_data_from_response(response, status=200):
# if status and response.status_code != status:
# raise ValueError(f'failed status check ({response.status_code} != expected {status})') # pragma: no cover
# return json.loads(response.content.decode('utf-8'))
#
# Path: lepo_tests/utils.py
# def get_urlpatterns(handler_module, definition_file='swagger2/petstore-expanded.yaml'):
# def generate_urlconf_module(handler_style, version):
# def generate_urlconf_modules(handler_styles, versions):
# URLCONF_TEMPLATE = '''
# from lepo_tests.handlers import %(module)s
# from lepo_tests.utils import get_urlpatterns
# urlpatterns = get_urlpatterns(%(module)s, %(file)r)
# '''
. Output only the next line. | pet1 = Pet.objects.create(name='smolboye', tag='pupper') |
Using the snippet: <|code_start|># `urlconf_map` is a map of dynamically generated URLconf modules
# that don't actually exist on disk, and this fixture ensures all
# tests in this module which request the `api_urls` fixture (defined below)
# actually get parametrized to include all versions in the map.
def pytest_generate_tests(metafunc):
if 'api_urls' in metafunc.fixturenames:
module_names = [m.__name__ for m in urlconf_map.values()]
metafunc.parametrize('api_urls', module_names, indirect=True)
@pytest.fixture
def api_urls(request):
urls = request.param
original_urlconf = django.conf.settings.ROOT_URLCONF
django.conf.settings.ROOT_URLCONF = urls
clear_url_caches()
set_urlconf(None)
def restore():
django.conf.settings.ROOT_URLCONF = original_urlconf
clear_url_caches()
set_urlconf(None)
request.addfinalizer(restore)
@pytest.mark.django_db
def test_get_empty_list(client, api_urls):
<|code_end|>
, determine the next line of code. You have imports:
import json
import django.conf
import pytest
from django.utils.crypto import get_random_string
from lepo.excs import ErroneousParameters, InvalidBodyContent, InvalidBodyFormat
from lepo_tests.models import Pet
from lepo_tests.tests.utils import get_data_from_response
from lepo_tests.utils import urlconf_map
from django.urls import clear_url_caches, set_urlconf
from django.core.urlresolvers import clear_url_caches, set_urlconf
and context (class names, function names, or code) available:
# Path: lepo/excs.py
# class ErroneousParameters(Exception):
# def __init__(self, error_map, parameters):
# self.errors = error_map
# self.parameters = parameters
#
# class InvalidBodyContent(ValueError):
# pass
#
# class InvalidBodyFormat(ValueError):
# pass
#
# Path: lepo_tests/models.py
# class Pet(models.Model):
# name = models.CharField(max_length=128)
# tag = models.CharField(max_length=128, blank=True)
#
# Path: lepo_tests/tests/utils.py
# def get_data_from_response(response, status=200):
# if status and response.status_code != status:
# raise ValueError(f'failed status check ({response.status_code} != expected {status})') # pragma: no cover
# return json.loads(response.content.decode('utf-8'))
#
# Path: lepo_tests/utils.py
# def get_urlpatterns(handler_module, definition_file='swagger2/petstore-expanded.yaml'):
# def generate_urlconf_module(handler_style, version):
# def generate_urlconf_modules(handler_styles, versions):
# URLCONF_TEMPLATE = '''
# from lepo_tests.handlers import %(module)s
# from lepo_tests.utils import get_urlpatterns
# urlpatterns = get_urlpatterns(%(module)s, %(file)r)
# '''
. Output only the next line. | assert get_data_from_response(client.get('/api/pets')) == [] |
Next line prediction: <|code_start|>
try:
# Django 2
except: # pragma: no cover
# Django 1.11
# There's some moderate Py.test and Python magic going on here.
# `urlconf_map` is a map of dynamically generated URLconf modules
# that don't actually exist on disk, and this fixture ensures all
# tests in this module which request the `api_urls` fixture (defined below)
# actually get parametrized to include all versions in the map.
def pytest_generate_tests(metafunc):
if 'api_urls' in metafunc.fixturenames:
<|code_end|>
. Use current file imports:
(import json
import django.conf
import pytest
from django.utils.crypto import get_random_string
from lepo.excs import ErroneousParameters, InvalidBodyContent, InvalidBodyFormat
from lepo_tests.models import Pet
from lepo_tests.tests.utils import get_data_from_response
from lepo_tests.utils import urlconf_map
from django.urls import clear_url_caches, set_urlconf
from django.core.urlresolvers import clear_url_caches, set_urlconf)
and context including class names, function names, or small code snippets from other files:
# Path: lepo/excs.py
# class ErroneousParameters(Exception):
# def __init__(self, error_map, parameters):
# self.errors = error_map
# self.parameters = parameters
#
# class InvalidBodyContent(ValueError):
# pass
#
# class InvalidBodyFormat(ValueError):
# pass
#
# Path: lepo_tests/models.py
# class Pet(models.Model):
# name = models.CharField(max_length=128)
# tag = models.CharField(max_length=128, blank=True)
#
# Path: lepo_tests/tests/utils.py
# def get_data_from_response(response, status=200):
# if status and response.status_code != status:
# raise ValueError(f'failed status check ({response.status_code} != expected {status})') # pragma: no cover
# return json.loads(response.content.decode('utf-8'))
#
# Path: lepo_tests/utils.py
# def get_urlpatterns(handler_module, definition_file='swagger2/petstore-expanded.yaml'):
# def generate_urlconf_module(handler_style, version):
# def generate_urlconf_modules(handler_styles, versions):
# URLCONF_TEMPLATE = '''
# from lepo_tests.handlers import %(module)s
# from lepo_tests.utils import get_urlpatterns
# urlpatterns = get_urlpatterns(%(module)s, %(file)r)
# '''
. Output only the next line. | module_names = [m.__name__ for m in urlconf_map.values()] |
Predict the next line for this snippet: <|code_start|> required:
- lat
- long
properties:
lat:
type: number
long:
type: number
''')
def test_complex_parameter():
coords_obj = {'lat': 8, 'long': 7}
request = make_request_for_operation(
doc.get_path('/complex-parameter').get_operation('get'),
query_string=urlencode({
'coordinates': json.dumps(coords_obj),
}),
)
params = read_parameters(request)
assert params == {'coordinates': coords_obj}
def test_complex_parameter_fails_validation():
request = make_request_for_operation(
doc.get_path('/complex-parameter').get_operation('get'),
query_string=urlencode({
'coordinates': json.dumps({'lat': 8, 'long': 'hoi there'}),
}),
)
<|code_end|>
with the help of current file imports:
import json
import pytest
from django.utils.http import urlencode
from jsonschema import ValidationError
from lepo.apidef.doc import APIDefinition
from lepo.excs import ErroneousParameters, InvalidComplexContent
from lepo.parameter_utils import read_parameters
from lepo_tests.tests.utils import make_request_for_operation
and context from other files:
# Path: lepo/apidef/doc.py
# class APIDefinition:
# version = None
# path_class = Path
# operation_class = None
#
# def __init__(self, doc):
# """
# Instantiate a new Lepo router.
#
# :param doc: The OpenAPI definition document.
# :type doc: dict
# """
# self.doc = doc
# self.resolver = RefResolver('', self.doc)
#
# def resolve_reference(self, ref):
# """
# Resolve a JSON Pointer object reference to the object itself.
#
# :param ref: Reference string (`#/foo/bar`, for instance)
# :return: The object, if found
# :raises jsonschema.exceptions.RefResolutionError: if there is trouble resolving the reference
# """
# url, resolved = self.resolver.resolve(ref)
# return resolved
#
# def get_path_mapping(self, path):
# return maybe_resolve(self.doc['paths'][path], self.resolve_reference)
#
# def get_path_names(self):
# yield from self.doc['paths']
#
# def get_path(self, path):
# """
# Construct a Path object from a path string.
#
# The Path string must be declared in the API.
#
# :type path: str
# :rtype: lepo.path.Path
# """
# mapping = self.get_path_mapping(path)
# return self.path_class(api=self, path=path, mapping=mapping)
#
# def get_paths(self):
# """
# Iterate over all Path objects declared by the API.
#
# :rtype: Iterable[lepo.path.Path]
# """
# for path_name in self.get_path_names():
# yield self.get_path(path_name)
#
# @classmethod
# def from_file(cls, filename):
# """
# Construct an APIDefinition by parsing the given `filename`.
#
# If PyYAML is installed, YAML files are supported.
# JSON files are always supported.
#
# :param filename: The filename to read.
# :rtype: APIDefinition
# """
# with open(filename) as infp:
# if filename.endswith('.yaml') or filename.endswith('.yml'):
# import yaml
# data = yaml.safe_load(infp)
# else:
# import json
# data = json.load(infp)
# return cls.from_data(data)
#
# @classmethod
# def from_data(cls, data):
# version = parse_version(data)
# if version == SWAGGER_2:
# return Swagger2APIDefinition(data)
# if version == OPENAPI_3:
# return OpenAPI3APIDefinition(data)
# raise NotImplementedError('We can never get here.') # pragma: no cover
#
# @classmethod
# def from_yaml(cls, yaml_string):
# from yaml import safe_load
# return cls.from_data(safe_load(yaml_string))
#
# Path: lepo/excs.py
# class ErroneousParameters(Exception):
# def __init__(self, error_map, parameters):
# self.errors = error_map
# self.parameters = parameters
#
# class InvalidComplexContent(ValueError):
# def __init__(self, message, error_map):
# super().__init__(message)
# self.errors = error_map
#
# Path: lepo/parameter_utils.py
# def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901
# """
# :param request: HttpRequest with attached api_info
# :type request: HttpRequest
# :type view_kwargs: dict[str, object]
# :type capture_errors: bool
# :rtype: dict[str, object]
# """
# if view_kwargs is None:
# view_kwargs = {}
# params = {}
# errors = {}
# for param in request.api_info.operation.parameters:
# try:
# value = param.get_value(request, view_kwargs)
# if value is NO_VALUE:
# if param.has_default:
# params[param.name] = param.default
# elif param.required: # Required but missing
# errors[param.name] = MissingParameter(f'parameter {param.name} is required but missing')
# continue # No value, or a default was added, or an error was added.
# params[param.name] = param.cast(request.api_info.api, value)
# except (NotImplementedError, ImproperlyConfigured):
# raise
# except Exception as e:
# if not capture_errors:
# raise
# errors[param.name] = e
# if errors:
# raise ErroneousParameters(errors, params)
# return params
#
# Path: lepo_tests/tests/utils.py
# def make_request_for_operation(operation, method='GET', query_string=''):
# request = RequestFactory().generic(method=method, path=operation.path.path, QUERY_STRING=query_string)
# request.api_info = APIInfo(operation)
# return request
, which may contain function names, class names, or code. Output only the next line. | with pytest.raises(ErroneousParameters) as ei: |
Predict the next line after this snippet: <|code_start|>paths:
/complex-parameter:
get:
parameters:
- in: query
name: coordinates
required: true
content:
application/json:
schema:
type: object
required:
- lat
- long
properties:
lat:
type: number
long:
type: number
''')
def test_complex_parameter():
coords_obj = {'lat': 8, 'long': 7}
request = make_request_for_operation(
doc.get_path('/complex-parameter').get_operation('get'),
query_string=urlencode({
'coordinates': json.dumps(coords_obj),
}),
)
<|code_end|>
using the current file's imports:
import json
import pytest
from django.utils.http import urlencode
from jsonschema import ValidationError
from lepo.apidef.doc import APIDefinition
from lepo.excs import ErroneousParameters, InvalidComplexContent
from lepo.parameter_utils import read_parameters
from lepo_tests.tests.utils import make_request_for_operation
and any relevant context from other files:
# Path: lepo/apidef/doc.py
# class APIDefinition:
# version = None
# path_class = Path
# operation_class = None
#
# def __init__(self, doc):
# """
# Instantiate a new Lepo router.
#
# :param doc: The OpenAPI definition document.
# :type doc: dict
# """
# self.doc = doc
# self.resolver = RefResolver('', self.doc)
#
# def resolve_reference(self, ref):
# """
# Resolve a JSON Pointer object reference to the object itself.
#
# :param ref: Reference string (`#/foo/bar`, for instance)
# :return: The object, if found
# :raises jsonschema.exceptions.RefResolutionError: if there is trouble resolving the reference
# """
# url, resolved = self.resolver.resolve(ref)
# return resolved
#
# def get_path_mapping(self, path):
# return maybe_resolve(self.doc['paths'][path], self.resolve_reference)
#
# def get_path_names(self):
# yield from self.doc['paths']
#
# def get_path(self, path):
# """
# Construct a Path object from a path string.
#
# The Path string must be declared in the API.
#
# :type path: str
# :rtype: lepo.path.Path
# """
# mapping = self.get_path_mapping(path)
# return self.path_class(api=self, path=path, mapping=mapping)
#
# def get_paths(self):
# """
# Iterate over all Path objects declared by the API.
#
# :rtype: Iterable[lepo.path.Path]
# """
# for path_name in self.get_path_names():
# yield self.get_path(path_name)
#
# @classmethod
# def from_file(cls, filename):
# """
# Construct an APIDefinition by parsing the given `filename`.
#
# If PyYAML is installed, YAML files are supported.
# JSON files are always supported.
#
# :param filename: The filename to read.
# :rtype: APIDefinition
# """
# with open(filename) as infp:
# if filename.endswith('.yaml') or filename.endswith('.yml'):
# import yaml
# data = yaml.safe_load(infp)
# else:
# import json
# data = json.load(infp)
# return cls.from_data(data)
#
# @classmethod
# def from_data(cls, data):
# version = parse_version(data)
# if version == SWAGGER_2:
# return Swagger2APIDefinition(data)
# if version == OPENAPI_3:
# return OpenAPI3APIDefinition(data)
# raise NotImplementedError('We can never get here.') # pragma: no cover
#
# @classmethod
# def from_yaml(cls, yaml_string):
# from yaml import safe_load
# return cls.from_data(safe_load(yaml_string))
#
# Path: lepo/excs.py
# class ErroneousParameters(Exception):
# def __init__(self, error_map, parameters):
# self.errors = error_map
# self.parameters = parameters
#
# class InvalidComplexContent(ValueError):
# def __init__(self, message, error_map):
# super().__init__(message)
# self.errors = error_map
#
# Path: lepo/parameter_utils.py
# def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901
# """
# :param request: HttpRequest with attached api_info
# :type request: HttpRequest
# :type view_kwargs: dict[str, object]
# :type capture_errors: bool
# :rtype: dict[str, object]
# """
# if view_kwargs is None:
# view_kwargs = {}
# params = {}
# errors = {}
# for param in request.api_info.operation.parameters:
# try:
# value = param.get_value(request, view_kwargs)
# if value is NO_VALUE:
# if param.has_default:
# params[param.name] = param.default
# elif param.required: # Required but missing
# errors[param.name] = MissingParameter(f'parameter {param.name} is required but missing')
# continue # No value, or a default was added, or an error was added.
# params[param.name] = param.cast(request.api_info.api, value)
# except (NotImplementedError, ImproperlyConfigured):
# raise
# except Exception as e:
# if not capture_errors:
# raise
# errors[param.name] = e
# if errors:
# raise ErroneousParameters(errors, params)
# return params
#
# Path: lepo_tests/tests/utils.py
# def make_request_for_operation(operation, method='GET', query_string=''):
# request = RequestFactory().generic(method=method, path=operation.path.path, QUERY_STRING=query_string)
# request.api_info = APIInfo(operation)
# return request
. Output only the next line. | params = read_parameters(request) |
Given the following code snippet before the placeholder: <|code_start|>
doc = APIDefinition.from_yaml('''
openapi: 3.0.0
paths:
/complex-parameter:
get:
parameters:
- in: query
name: coordinates
required: true
content:
application/json:
schema:
type: object
required:
- lat
- long
properties:
lat:
type: number
long:
type: number
''')
def test_complex_parameter():
coords_obj = {'lat': 8, 'long': 7}
<|code_end|>
, predict the next line using imports from the current file:
import json
import pytest
from django.utils.http import urlencode
from jsonschema import ValidationError
from lepo.apidef.doc import APIDefinition
from lepo.excs import ErroneousParameters, InvalidComplexContent
from lepo.parameter_utils import read_parameters
from lepo_tests.tests.utils import make_request_for_operation
and context including class names, function names, and sometimes code from other files:
# Path: lepo/apidef/doc.py
# class APIDefinition:
# version = None
# path_class = Path
# operation_class = None
#
# def __init__(self, doc):
# """
# Instantiate a new Lepo router.
#
# :param doc: The OpenAPI definition document.
# :type doc: dict
# """
# self.doc = doc
# self.resolver = RefResolver('', self.doc)
#
# def resolve_reference(self, ref):
# """
# Resolve a JSON Pointer object reference to the object itself.
#
# :param ref: Reference string (`#/foo/bar`, for instance)
# :return: The object, if found
# :raises jsonschema.exceptions.RefResolutionError: if there is trouble resolving the reference
# """
# url, resolved = self.resolver.resolve(ref)
# return resolved
#
# def get_path_mapping(self, path):
# return maybe_resolve(self.doc['paths'][path], self.resolve_reference)
#
# def get_path_names(self):
# yield from self.doc['paths']
#
# def get_path(self, path):
# """
# Construct a Path object from a path string.
#
# The Path string must be declared in the API.
#
# :type path: str
# :rtype: lepo.path.Path
# """
# mapping = self.get_path_mapping(path)
# return self.path_class(api=self, path=path, mapping=mapping)
#
# def get_paths(self):
# """
# Iterate over all Path objects declared by the API.
#
# :rtype: Iterable[lepo.path.Path]
# """
# for path_name in self.get_path_names():
# yield self.get_path(path_name)
#
# @classmethod
# def from_file(cls, filename):
# """
# Construct an APIDefinition by parsing the given `filename`.
#
# If PyYAML is installed, YAML files are supported.
# JSON files are always supported.
#
# :param filename: The filename to read.
# :rtype: APIDefinition
# """
# with open(filename) as infp:
# if filename.endswith('.yaml') or filename.endswith('.yml'):
# import yaml
# data = yaml.safe_load(infp)
# else:
# import json
# data = json.load(infp)
# return cls.from_data(data)
#
# @classmethod
# def from_data(cls, data):
# version = parse_version(data)
# if version == SWAGGER_2:
# return Swagger2APIDefinition(data)
# if version == OPENAPI_3:
# return OpenAPI3APIDefinition(data)
# raise NotImplementedError('We can never get here.') # pragma: no cover
#
# @classmethod
# def from_yaml(cls, yaml_string):
# from yaml import safe_load
# return cls.from_data(safe_load(yaml_string))
#
# Path: lepo/excs.py
# class ErroneousParameters(Exception):
# def __init__(self, error_map, parameters):
# self.errors = error_map
# self.parameters = parameters
#
# class InvalidComplexContent(ValueError):
# def __init__(self, message, error_map):
# super().__init__(message)
# self.errors = error_map
#
# Path: lepo/parameter_utils.py
# def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901
# """
# :param request: HttpRequest with attached api_info
# :type request: HttpRequest
# :type view_kwargs: dict[str, object]
# :type capture_errors: bool
# :rtype: dict[str, object]
# """
# if view_kwargs is None:
# view_kwargs = {}
# params = {}
# errors = {}
# for param in request.api_info.operation.parameters:
# try:
# value = param.get_value(request, view_kwargs)
# if value is NO_VALUE:
# if param.has_default:
# params[param.name] = param.default
# elif param.required: # Required but missing
# errors[param.name] = MissingParameter(f'parameter {param.name} is required but missing')
# continue # No value, or a default was added, or an error was added.
# params[param.name] = param.cast(request.api_info.api, value)
# except (NotImplementedError, ImproperlyConfigured):
# raise
# except Exception as e:
# if not capture_errors:
# raise
# errors[param.name] = e
# if errors:
# raise ErroneousParameters(errors, params)
# return params
#
# Path: lepo_tests/tests/utils.py
# def make_request_for_operation(operation, method='GET', query_string=''):
# request = RequestFactory().generic(method=method, path=operation.path.path, QUERY_STRING=query_string)
# request.api_info = APIInfo(operation)
# return request
. Output only the next line. | request = make_request_for_operation( |
Continue the code snippet: <|code_start|>
class PathView(View):
router = None # Filled in by subclasses
path = None # Filled in by subclasses
def dispatch(self, request, **kwargs):
try:
operation = self.path.get_operation(request.method)
except InvalidOperation:
return self.http_method_not_allowed(request, **kwargs)
<|code_end|>
. Use current file imports:
from django.http import HttpResponse, JsonResponse
from django.views import View
from lepo.api_info import APIInfo
from lepo.excs import ExceptionalResponse, InvalidOperation
from lepo.parameter_utils import read_parameters
from lepo.utils import snake_case
and context (classes, functions, or code) from other files:
# Path: lepo/api_info.py
# class APIInfo:
# def __init__(self, operation, router=None):
# """
# :type operation: lepo.operation.Operation
# :type router: lepo.router.Router
# """
# self.api = operation.api
# self.path = operation.path
# self.operation = operation
# self.router = router
#
# Path: lepo/excs.py
# class ExceptionalResponse(Exception):
# """
# Wraps a Response in an exception.
#
# These exceptions are caught in PathView.
# """
# def __init__(self, response):
# self.response = response
#
# class InvalidOperation(ValueError):
# pass
#
# Path: lepo/parameter_utils.py
# def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901
# """
# :param request: HttpRequest with attached api_info
# :type request: HttpRequest
# :type view_kwargs: dict[str, object]
# :type capture_errors: bool
# :rtype: dict[str, object]
# """
# if view_kwargs is None:
# view_kwargs = {}
# params = {}
# errors = {}
# for param in request.api_info.operation.parameters:
# try:
# value = param.get_value(request, view_kwargs)
# if value is NO_VALUE:
# if param.has_default:
# params[param.name] = param.default
# elif param.required: # Required but missing
# errors[param.name] = MissingParameter(f'parameter {param.name} is required but missing')
# continue # No value, or a default was added, or an error was added.
# params[param.name] = param.cast(request.api_info.api, value)
# except (NotImplementedError, ImproperlyConfigured):
# raise
# except Exception as e:
# if not capture_errors:
# raise
# errors[param.name] = e
# if errors:
# raise ErroneousParameters(errors, params)
# return params
#
# Path: lepo/utils.py
# def snake_case(string):
# return camel_case_to_spaces(string).replace('-', '_').replace(' ', '_').replace('__', '_')
. Output only the next line. | request.api_info = APIInfo( |
Using the snippet: <|code_start|>
class PathView(View):
router = None # Filled in by subclasses
path = None # Filled in by subclasses
def dispatch(self, request, **kwargs):
try:
operation = self.path.get_operation(request.method)
except InvalidOperation:
return self.http_method_not_allowed(request, **kwargs)
request.api_info = APIInfo(
operation=operation,
router=self.router,
)
params = {
snake_case(name): value
for (name, value)
in read_parameters(request, kwargs, capture_errors=True).items()
}
handler = request.api_info.router.get_handler(operation.id)
try:
response = handler(request, **params)
<|code_end|>
, determine the next line of code. You have imports:
from django.http import HttpResponse, JsonResponse
from django.views import View
from lepo.api_info import APIInfo
from lepo.excs import ExceptionalResponse, InvalidOperation
from lepo.parameter_utils import read_parameters
from lepo.utils import snake_case
and context (class names, function names, or code) available:
# Path: lepo/api_info.py
# class APIInfo:
# def __init__(self, operation, router=None):
# """
# :type operation: lepo.operation.Operation
# :type router: lepo.router.Router
# """
# self.api = operation.api
# self.path = operation.path
# self.operation = operation
# self.router = router
#
# Path: lepo/excs.py
# class ExceptionalResponse(Exception):
# """
# Wraps a Response in an exception.
#
# These exceptions are caught in PathView.
# """
# def __init__(self, response):
# self.response = response
#
# class InvalidOperation(ValueError):
# pass
#
# Path: lepo/parameter_utils.py
# def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901
# """
# :param request: HttpRequest with attached api_info
# :type request: HttpRequest
# :type view_kwargs: dict[str, object]
# :type capture_errors: bool
# :rtype: dict[str, object]
# """
# if view_kwargs is None:
# view_kwargs = {}
# params = {}
# errors = {}
# for param in request.api_info.operation.parameters:
# try:
# value = param.get_value(request, view_kwargs)
# if value is NO_VALUE:
# if param.has_default:
# params[param.name] = param.default
# elif param.required: # Required but missing
# errors[param.name] = MissingParameter(f'parameter {param.name} is required but missing')
# continue # No value, or a default was added, or an error was added.
# params[param.name] = param.cast(request.api_info.api, value)
# except (NotImplementedError, ImproperlyConfigured):
# raise
# except Exception as e:
# if not capture_errors:
# raise
# errors[param.name] = e
# if errors:
# raise ErroneousParameters(errors, params)
# return params
#
# Path: lepo/utils.py
# def snake_case(string):
# return camel_case_to_spaces(string).replace('-', '_').replace(' ', '_').replace('__', '_')
. Output only the next line. | except ExceptionalResponse as er: |
Here is a snippet: <|code_start|>
class PathView(View):
router = None # Filled in by subclasses
path = None # Filled in by subclasses
def dispatch(self, request, **kwargs):
try:
operation = self.path.get_operation(request.method)
<|code_end|>
. Write the next line using the current file imports:
from django.http import HttpResponse, JsonResponse
from django.views import View
from lepo.api_info import APIInfo
from lepo.excs import ExceptionalResponse, InvalidOperation
from lepo.parameter_utils import read_parameters
from lepo.utils import snake_case
and context from other files:
# Path: lepo/api_info.py
# class APIInfo:
# def __init__(self, operation, router=None):
# """
# :type operation: lepo.operation.Operation
# :type router: lepo.router.Router
# """
# self.api = operation.api
# self.path = operation.path
# self.operation = operation
# self.router = router
#
# Path: lepo/excs.py
# class ExceptionalResponse(Exception):
# """
# Wraps a Response in an exception.
#
# These exceptions are caught in PathView.
# """
# def __init__(self, response):
# self.response = response
#
# class InvalidOperation(ValueError):
# pass
#
# Path: lepo/parameter_utils.py
# def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901
# """
# :param request: HttpRequest with attached api_info
# :type request: HttpRequest
# :type view_kwargs: dict[str, object]
# :type capture_errors: bool
# :rtype: dict[str, object]
# """
# if view_kwargs is None:
# view_kwargs = {}
# params = {}
# errors = {}
# for param in request.api_info.operation.parameters:
# try:
# value = param.get_value(request, view_kwargs)
# if value is NO_VALUE:
# if param.has_default:
# params[param.name] = param.default
# elif param.required: # Required but missing
# errors[param.name] = MissingParameter(f'parameter {param.name} is required but missing')
# continue # No value, or a default was added, or an error was added.
# params[param.name] = param.cast(request.api_info.api, value)
# except (NotImplementedError, ImproperlyConfigured):
# raise
# except Exception as e:
# if not capture_errors:
# raise
# errors[param.name] = e
# if errors:
# raise ErroneousParameters(errors, params)
# return params
#
# Path: lepo/utils.py
# def snake_case(string):
# return camel_case_to_spaces(string).replace('-', '_').replace(' ', '_').replace('__', '_')
, which may include functions, classes, or code. Output only the next line. | except InvalidOperation: |
Here is a snippet: <|code_start|>
class PathView(View):
router = None # Filled in by subclasses
path = None # Filled in by subclasses
def dispatch(self, request, **kwargs):
try:
operation = self.path.get_operation(request.method)
except InvalidOperation:
return self.http_method_not_allowed(request, **kwargs)
request.api_info = APIInfo(
operation=operation,
router=self.router,
)
params = {
snake_case(name): value
for (name, value)
<|code_end|>
. Write the next line using the current file imports:
from django.http import HttpResponse, JsonResponse
from django.views import View
from lepo.api_info import APIInfo
from lepo.excs import ExceptionalResponse, InvalidOperation
from lepo.parameter_utils import read_parameters
from lepo.utils import snake_case
and context from other files:
# Path: lepo/api_info.py
# class APIInfo:
# def __init__(self, operation, router=None):
# """
# :type operation: lepo.operation.Operation
# :type router: lepo.router.Router
# """
# self.api = operation.api
# self.path = operation.path
# self.operation = operation
# self.router = router
#
# Path: lepo/excs.py
# class ExceptionalResponse(Exception):
# """
# Wraps a Response in an exception.
#
# These exceptions are caught in PathView.
# """
# def __init__(self, response):
# self.response = response
#
# class InvalidOperation(ValueError):
# pass
#
# Path: lepo/parameter_utils.py
# def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901
# """
# :param request: HttpRequest with attached api_info
# :type request: HttpRequest
# :type view_kwargs: dict[str, object]
# :type capture_errors: bool
# :rtype: dict[str, object]
# """
# if view_kwargs is None:
# view_kwargs = {}
# params = {}
# errors = {}
# for param in request.api_info.operation.parameters:
# try:
# value = param.get_value(request, view_kwargs)
# if value is NO_VALUE:
# if param.has_default:
# params[param.name] = param.default
# elif param.required: # Required but missing
# errors[param.name] = MissingParameter(f'parameter {param.name} is required but missing')
# continue # No value, or a default was added, or an error was added.
# params[param.name] = param.cast(request.api_info.api, value)
# except (NotImplementedError, ImproperlyConfigured):
# raise
# except Exception as e:
# if not capture_errors:
# raise
# errors[param.name] = e
# if errors:
# raise ErroneousParameters(errors, params)
# return params
#
# Path: lepo/utils.py
# def snake_case(string):
# return camel_case_to_spaces(string).replace('-', '_').replace(' ', '_').replace('__', '_')
, which may include functions, classes, or code. Output only the next line. | in read_parameters(request, kwargs, capture_errors=True).items() |
Given the following code snippet before the placeholder: <|code_start|>
class PathView(View):
router = None # Filled in by subclasses
path = None # Filled in by subclasses
def dispatch(self, request, **kwargs):
try:
operation = self.path.get_operation(request.method)
except InvalidOperation:
return self.http_method_not_allowed(request, **kwargs)
request.api_info = APIInfo(
operation=operation,
router=self.router,
)
params = {
<|code_end|>
, predict the next line using imports from the current file:
from django.http import HttpResponse, JsonResponse
from django.views import View
from lepo.api_info import APIInfo
from lepo.excs import ExceptionalResponse, InvalidOperation
from lepo.parameter_utils import read_parameters
from lepo.utils import snake_case
and context including class names, function names, and sometimes code from other files:
# Path: lepo/api_info.py
# class APIInfo:
# def __init__(self, operation, router=None):
# """
# :type operation: lepo.operation.Operation
# :type router: lepo.router.Router
# """
# self.api = operation.api
# self.path = operation.path
# self.operation = operation
# self.router = router
#
# Path: lepo/excs.py
# class ExceptionalResponse(Exception):
# """
# Wraps a Response in an exception.
#
# These exceptions are caught in PathView.
# """
# def __init__(self, response):
# self.response = response
#
# class InvalidOperation(ValueError):
# pass
#
# Path: lepo/parameter_utils.py
# def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901
# """
# :param request: HttpRequest with attached api_info
# :type request: HttpRequest
# :type view_kwargs: dict[str, object]
# :type capture_errors: bool
# :rtype: dict[str, object]
# """
# if view_kwargs is None:
# view_kwargs = {}
# params = {}
# errors = {}
# for param in request.api_info.operation.parameters:
# try:
# value = param.get_value(request, view_kwargs)
# if value is NO_VALUE:
# if param.has_default:
# params[param.name] = param.default
# elif param.required: # Required but missing
# errors[param.name] = MissingParameter(f'parameter {param.name} is required but missing')
# continue # No value, or a default was added, or an error was added.
# params[param.name] = param.cast(request.api_info.api, value)
# except (NotImplementedError, ImproperlyConfigured):
# raise
# except Exception as e:
# if not capture_errors:
# raise
# errors[param.name] = e
# if errors:
# raise ErroneousParameters(errors, params)
# return params
#
# Path: lepo/utils.py
# def snake_case(string):
# return camel_case_to_spaces(string).replace('-', '_').replace(' ', '_').replace('__', '_')
. Output only the next line. | snake_case(name): value |
Using the snippet: <|code_start|>
def cast(self, api, value): # pragma: no cover
raise NotImplementedError('Subclasses must implement cast')
def get_value(self, request, view_kwargs): # pragma: no cover
"""
:type request: WSGIRequest
:type view_kwargs: dict
"""
raise NotImplementedError('Subclasses must implement get_value')
class BaseTopParameter(BaseParameter):
"""
Top-level Parameter, such as in an operation
"""
def __init__(self, data, api=None, operation=None):
super().__init__(data, api=api)
self.operation = operation
@property
def name(self):
return self.data['name']
@property
def in_body(self):
return self.location in ('formData', 'body')
def get_value(self, request, view_kwargs):
<|code_end|>
, determine the next line of code. You have imports:
from lepo.excs import InvalidParameterDefinition
and context (class names, function names, or code) available:
# Path: lepo/excs.py
# class InvalidParameterDefinition(ImproperlyConfigured):
# pass
. Output only the next line. | raise InvalidParameterDefinition(f'unsupported `in` value {self.location!r} in {self!r}') # pragma: no cover |
Predict the next line for this snippet: <|code_start|>
lil_bub = {'name': 'Lil Bub', 'petType': 'Cat', 'huntingSkill': 'lazy'}
hachiko = {'name': 'Hachiko', 'petType': 'Dog', 'packSize': 83}
@doc_versions
def test_path_refs(doc_version):
router = get_router(f'{doc_version}/path-refs.yaml')
assert router.get_path('/b').mapping == router.get_path('/a').mapping
@doc_versions
def test_schema_refs(rf, doc_version):
router = get_router(f'{doc_version}/schema-refs.yaml')
request = rf.post('/cat', json.dumps(lil_bub), content_type='application/json')
<|code_end|>
with the help of current file imports:
import json
import pytest
from lepo.api_info import APIInfo
from lepo.parameter_utils import read_parameters
from lepo_tests.tests.utils import doc_versions, get_router
and context from other files:
# Path: lepo/api_info.py
# class APIInfo:
# def __init__(self, operation, router=None):
# """
# :type operation: lepo.operation.Operation
# :type router: lepo.router.Router
# """
# self.api = operation.api
# self.path = operation.path
# self.operation = operation
# self.router = router
#
# Path: lepo/parameter_utils.py
# def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901
# """
# :param request: HttpRequest with attached api_info
# :type request: HttpRequest
# :type view_kwargs: dict[str, object]
# :type capture_errors: bool
# :rtype: dict[str, object]
# """
# if view_kwargs is None:
# view_kwargs = {}
# params = {}
# errors = {}
# for param in request.api_info.operation.parameters:
# try:
# value = param.get_value(request, view_kwargs)
# if value is NO_VALUE:
# if param.has_default:
# params[param.name] = param.default
# elif param.required: # Required but missing
# errors[param.name] = MissingParameter(f'parameter {param.name} is required but missing')
# continue # No value, or a default was added, or an error was added.
# params[param.name] = param.cast(request.api_info.api, value)
# except (NotImplementedError, ImproperlyConfigured):
# raise
# except Exception as e:
# if not capture_errors:
# raise
# errors[param.name] = e
# if errors:
# raise ErroneousParameters(errors, params)
# return params
#
# Path: lepo_tests/tests/utils.py
# TESTS_DIR = os.path.dirname(__file__)
# DOC_VERSIONS = ['swagger2', 'openapi3']
# def get_router(fixture_name):
# def get_data_from_response(response, status=200):
# def cast_parameter_value(apidoc, parameter, value):
# def get_apidoc_from_version(version, content={}):
# def make_request_for_operation(operation, method='GET', query_string=''):
, which may contain function names, class names, or code. Output only the next line. | request.api_info = APIInfo(router.get_path('/cat').get_operation('post')) |
Continue the code snippet: <|code_start|>
lil_bub = {'name': 'Lil Bub', 'petType': 'Cat', 'huntingSkill': 'lazy'}
hachiko = {'name': 'Hachiko', 'petType': 'Dog', 'packSize': 83}
@doc_versions
def test_path_refs(doc_version):
router = get_router(f'{doc_version}/path-refs.yaml')
assert router.get_path('/b').mapping == router.get_path('/a').mapping
@doc_versions
def test_schema_refs(rf, doc_version):
router = get_router(f'{doc_version}/schema-refs.yaml')
request = rf.post('/cat', json.dumps(lil_bub), content_type='application/json')
request.api_info = APIInfo(router.get_path('/cat').get_operation('post'))
<|code_end|>
. Use current file imports:
import json
import pytest
from lepo.api_info import APIInfo
from lepo.parameter_utils import read_parameters
from lepo_tests.tests.utils import doc_versions, get_router
and context (classes, functions, or code) from other files:
# Path: lepo/api_info.py
# class APIInfo:
# def __init__(self, operation, router=None):
# """
# :type operation: lepo.operation.Operation
# :type router: lepo.router.Router
# """
# self.api = operation.api
# self.path = operation.path
# self.operation = operation
# self.router = router
#
# Path: lepo/parameter_utils.py
# def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901
# """
# :param request: HttpRequest with attached api_info
# :type request: HttpRequest
# :type view_kwargs: dict[str, object]
# :type capture_errors: bool
# :rtype: dict[str, object]
# """
# if view_kwargs is None:
# view_kwargs = {}
# params = {}
# errors = {}
# for param in request.api_info.operation.parameters:
# try:
# value = param.get_value(request, view_kwargs)
# if value is NO_VALUE:
# if param.has_default:
# params[param.name] = param.default
# elif param.required: # Required but missing
# errors[param.name] = MissingParameter(f'parameter {param.name} is required but missing')
# continue # No value, or a default was added, or an error was added.
# params[param.name] = param.cast(request.api_info.api, value)
# except (NotImplementedError, ImproperlyConfigured):
# raise
# except Exception as e:
# if not capture_errors:
# raise
# errors[param.name] = e
# if errors:
# raise ErroneousParameters(errors, params)
# return params
#
# Path: lepo_tests/tests/utils.py
# TESTS_DIR = os.path.dirname(__file__)
# DOC_VERSIONS = ['swagger2', 'openapi3']
# def get_router(fixture_name):
# def get_data_from_response(response, status=200):
# def cast_parameter_value(apidoc, parameter, value):
# def get_apidoc_from_version(version, content={}):
# def make_request_for_operation(operation, method='GET', query_string=''):
. Output only the next line. | params = read_parameters(request, {}) |
Given snippet: <|code_start|>
lil_bub = {'name': 'Lil Bub', 'petType': 'Cat', 'huntingSkill': 'lazy'}
hachiko = {'name': 'Hachiko', 'petType': 'Dog', 'packSize': 83}
@doc_versions
def test_path_refs(doc_version):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
import pytest
from lepo.api_info import APIInfo
from lepo.parameter_utils import read_parameters
from lepo_tests.tests.utils import doc_versions, get_router
and context:
# Path: lepo/api_info.py
# class APIInfo:
# def __init__(self, operation, router=None):
# """
# :type operation: lepo.operation.Operation
# :type router: lepo.router.Router
# """
# self.api = operation.api
# self.path = operation.path
# self.operation = operation
# self.router = router
#
# Path: lepo/parameter_utils.py
# def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901
# """
# :param request: HttpRequest with attached api_info
# :type request: HttpRequest
# :type view_kwargs: dict[str, object]
# :type capture_errors: bool
# :rtype: dict[str, object]
# """
# if view_kwargs is None:
# view_kwargs = {}
# params = {}
# errors = {}
# for param in request.api_info.operation.parameters:
# try:
# value = param.get_value(request, view_kwargs)
# if value is NO_VALUE:
# if param.has_default:
# params[param.name] = param.default
# elif param.required: # Required but missing
# errors[param.name] = MissingParameter(f'parameter {param.name} is required but missing')
# continue # No value, or a default was added, or an error was added.
# params[param.name] = param.cast(request.api_info.api, value)
# except (NotImplementedError, ImproperlyConfigured):
# raise
# except Exception as e:
# if not capture_errors:
# raise
# errors[param.name] = e
# if errors:
# raise ErroneousParameters(errors, params)
# return params
#
# Path: lepo_tests/tests/utils.py
# TESTS_DIR = os.path.dirname(__file__)
# DOC_VERSIONS = ['swagger2', 'openapi3']
# def get_router(fixture_name):
# def get_data_from_response(response, status=200):
# def cast_parameter_value(apidoc, parameter, value):
# def get_apidoc_from_version(version, content={}):
# def make_request_for_operation(operation, method='GET', query_string=''):
which might include code, classes, or functions. Output only the next line. | router = get_router(f'{doc_version}/path-refs.yaml') |
Predict the next line after this snippet: <|code_start|>"""
Class-based implementation of the pet resource.
"""
class PetHandler(CRUDModelHandler):
model = Pet
queryset = Pet.objects.all()
<|code_end|>
using the current file's imports:
from functools import reduce
from django.db.models import Q
from lepo.handlers import CRUDModelHandler
from lepo_tests.models import Pet
from lepo_tests.schemata import PetSchema
and any relevant context from other files:
# Path: lepo/handlers.py
# class CRUDModelHandler(
# ModelHandlerCreateMixin,
# ModelHandlerReadMixin,
# ModelHandlerUpdateMixin,
# ModelHandlerDeleteMixin,
# ):
# pass
#
# Path: lepo_tests/models.py
# class Pet(models.Model):
# name = models.CharField(max_length=128)
# tag = models.CharField(max_length=128, blank=True)
#
# Path: lepo_tests/schemata.py
# class PetSchema(Schema):
# id = fields.Integer(required=False)
# name = fields.Str(required=True)
# tag = fields.Str(required=False)
. Output only the next line. | schema_class = PetSchema |
Here is a snippet: <|code_start|> :rtype: APIDefinition
"""
with open(filename) as infp:
if filename.endswith('.yaml') or filename.endswith('.yml'):
data = yaml.safe_load(infp)
else:
data = json.load(infp)
return cls.from_data(data)
@classmethod
def from_data(cls, data):
version = parse_version(data)
if version == SWAGGER_2:
return Swagger2APIDefinition(data)
if version == OPENAPI_3:
return OpenAPI3APIDefinition(data)
raise NotImplementedError('We can never get here.') # pragma: no cover
@classmethod
def from_yaml(cls, yaml_string):
return cls.from_data(safe_load(yaml_string))
class Swagger2APIDefinition(APIDefinition):
version = SWAGGER_2
operation_class = Swagger2Operation
class OpenAPI3APIDefinition(APIDefinition):
version = OPENAPI_3
<|code_end|>
. Write the next line using the current file imports:
from jsonschema import RefResolver
from lepo.apidef.operation.openapi import OpenAPI3Operation
from lepo.apidef.operation.swagger import Swagger2Operation
from lepo.apidef.path import Path
from lepo.apidef.version import OPENAPI_3, SWAGGER_2, parse_version
from lepo.utils import maybe_resolve
from yaml import safe_load
import yaml
import json
and context from other files:
# Path: lepo/apidef/operation/openapi.py
# class OpenAPI3Operation(Operation):
# parameter_class = OpenAPI3Parameter
# body_parameter_class = OpenAPI3BodyParameter
#
# def _get_body_parameter(self):
# for source in (
# self.path.mapping.get('requestBody'),
# self.data.get('requestBody'),
# ):
# if source:
# source = maybe_resolve(source, self.api.resolve_reference)
# body_parameter = self.body_parameter_class(data=source, operation=self, api=self.api)
# # TODO: Document x-lepo-body-name
# body_parameter.name = self.data.get('x-lepo-body-name', body_parameter.name)
# return body_parameter
#
# def get_parameter_dict(self):
# parameter_dict = super().get_parameter_dict()
# for parameter in parameter_dict.values():
# if parameter.in_body: # pragma: no cover
# raise ValueError('Regular parameter declared to be in body while parsing OpenAPI 3')
# body_parameter = self._get_body_parameter()
# if body_parameter:
# parameter_dict[body_parameter.name] = body_parameter
# return parameter_dict
#
# Path: lepo/apidef/operation/swagger.py
# class Swagger2Operation(Operation):
# parameter_class = Swagger2Parameter
#
# @cached_property
# def consumes(self):
# value = self._get_overridable('consumes', [])
# if not isinstance(value, (list, tuple)):
# raise TypeError(f'`consumes` must be a list, got {value!r}') # pragma: no cover
# return value
#
# @cached_property
# def produces(self):
# value = self._get_overridable('produces', [])
# if not isinstance(value, (list, tuple)):
# raise TypeError(f'`produces` must be a list, got {value!r}') # pragma: no cover
# return value
#
# Path: lepo/apidef/path.py
# class Path:
# def __init__(self, api, path, mapping):
# """
# :type api: lepo.apidef.APIDefinition
# :type path: str
# :type mapping: dict
# """
# self.api = api
# self.path = path
# self.mapping = mapping
# self.regex = self._build_regex()
# self.name = self._build_view_name()
#
# def get_view_class(self, router):
# return type(f'{self.name.title()}View', (PathView,), {
# 'path': self,
# 'router': router,
# })
#
# def _build_view_name(self):
# path = re.sub(PATH_PLACEHOLDER_REGEX, r'\1', self.path)
# name = re.sub(r'[^a-z0-9]+', '-', path, flags=re.I).strip('-').lower()
# return name
#
# def _build_regex(self):
# return re.sub(
# PATH_PLACEHOLDER_REGEX,
# lambda m: f'(?P<{m.group(1)}>[^/]+?)',
# self.path,
# ).lstrip('/') + '$'
#
# def get_operation(self, method):
# operation_data = self.mapping.get(method.lower())
# if not operation_data:
# raise InvalidOperation(f'Path {self.path} does not support method {method.upper()}')
# return self.api.operation_class(api=self.api, path=self, data=operation_data, method=method)
#
# def get_operations(self):
# for method in METHODS:
# if method in self.mapping:
# yield self.get_operation(method)
#
# Path: lepo/apidef/version.py
# OPENAPI_3 = 'openapi3'
#
# SWAGGER_2 = 'swagger2'
#
# def parse_version(doc_dict):
# if 'swagger' in doc_dict:
# version = split_version(doc_dict['swagger'])
# if version[0] != 2: # pragma: no cover
# raise ValueError('Only Swagger 2.x is supported')
# return SWAGGER_2
# elif 'openapi' in doc_dict:
# version = split_version(doc_dict['openapi'])
# if version[0] != 3: # pragma: no cover
# raise ValueError('Only OpenAPI 3.x is supported')
# return OPENAPI_3
# raise ValueError('API document is missing version specifier')
#
# Path: lepo/utils.py
# def maybe_resolve(object, resolve):
# """
# Call `resolve` on the `object`'s `$ref` value if it has one.
#
# :param object: An object.
# :param resolve: A resolving function.
# :return: An object, or some other object! :sparkles:
# """
# if isinstance(object, dict) and object.get('$ref'):
# return resolve(object['$ref'])
# return object
, which may include functions, classes, or code. Output only the next line. | operation_class = OpenAPI3Operation |
Given the following code snippet before the placeholder: <|code_start|>
If PyYAML is installed, YAML files are supported.
JSON files are always supported.
:param filename: The filename to read.
:rtype: APIDefinition
"""
with open(filename) as infp:
if filename.endswith('.yaml') or filename.endswith('.yml'):
data = yaml.safe_load(infp)
else:
data = json.load(infp)
return cls.from_data(data)
@classmethod
def from_data(cls, data):
version = parse_version(data)
if version == SWAGGER_2:
return Swagger2APIDefinition(data)
if version == OPENAPI_3:
return OpenAPI3APIDefinition(data)
raise NotImplementedError('We can never get here.') # pragma: no cover
@classmethod
def from_yaml(cls, yaml_string):
return cls.from_data(safe_load(yaml_string))
class Swagger2APIDefinition(APIDefinition):
version = SWAGGER_2
<|code_end|>
, predict the next line using imports from the current file:
from jsonschema import RefResolver
from lepo.apidef.operation.openapi import OpenAPI3Operation
from lepo.apidef.operation.swagger import Swagger2Operation
from lepo.apidef.path import Path
from lepo.apidef.version import OPENAPI_3, SWAGGER_2, parse_version
from lepo.utils import maybe_resolve
from yaml import safe_load
import yaml
import json
and context including class names, function names, and sometimes code from other files:
# Path: lepo/apidef/operation/openapi.py
# class OpenAPI3Operation(Operation):
# parameter_class = OpenAPI3Parameter
# body_parameter_class = OpenAPI3BodyParameter
#
# def _get_body_parameter(self):
# for source in (
# self.path.mapping.get('requestBody'),
# self.data.get('requestBody'),
# ):
# if source:
# source = maybe_resolve(source, self.api.resolve_reference)
# body_parameter = self.body_parameter_class(data=source, operation=self, api=self.api)
# # TODO: Document x-lepo-body-name
# body_parameter.name = self.data.get('x-lepo-body-name', body_parameter.name)
# return body_parameter
#
# def get_parameter_dict(self):
# parameter_dict = super().get_parameter_dict()
# for parameter in parameter_dict.values():
# if parameter.in_body: # pragma: no cover
# raise ValueError('Regular parameter declared to be in body while parsing OpenAPI 3')
# body_parameter = self._get_body_parameter()
# if body_parameter:
# parameter_dict[body_parameter.name] = body_parameter
# return parameter_dict
#
# Path: lepo/apidef/operation/swagger.py
# class Swagger2Operation(Operation):
# parameter_class = Swagger2Parameter
#
# @cached_property
# def consumes(self):
# value = self._get_overridable('consumes', [])
# if not isinstance(value, (list, tuple)):
# raise TypeError(f'`consumes` must be a list, got {value!r}') # pragma: no cover
# return value
#
# @cached_property
# def produces(self):
# value = self._get_overridable('produces', [])
# if not isinstance(value, (list, tuple)):
# raise TypeError(f'`produces` must be a list, got {value!r}') # pragma: no cover
# return value
#
# Path: lepo/apidef/path.py
# class Path:
# def __init__(self, api, path, mapping):
# """
# :type api: lepo.apidef.APIDefinition
# :type path: str
# :type mapping: dict
# """
# self.api = api
# self.path = path
# self.mapping = mapping
# self.regex = self._build_regex()
# self.name = self._build_view_name()
#
# def get_view_class(self, router):
# return type(f'{self.name.title()}View', (PathView,), {
# 'path': self,
# 'router': router,
# })
#
# def _build_view_name(self):
# path = re.sub(PATH_PLACEHOLDER_REGEX, r'\1', self.path)
# name = re.sub(r'[^a-z0-9]+', '-', path, flags=re.I).strip('-').lower()
# return name
#
# def _build_regex(self):
# return re.sub(
# PATH_PLACEHOLDER_REGEX,
# lambda m: f'(?P<{m.group(1)}>[^/]+?)',
# self.path,
# ).lstrip('/') + '$'
#
# def get_operation(self, method):
# operation_data = self.mapping.get(method.lower())
# if not operation_data:
# raise InvalidOperation(f'Path {self.path} does not support method {method.upper()}')
# return self.api.operation_class(api=self.api, path=self, data=operation_data, method=method)
#
# def get_operations(self):
# for method in METHODS:
# if method in self.mapping:
# yield self.get_operation(method)
#
# Path: lepo/apidef/version.py
# OPENAPI_3 = 'openapi3'
#
# SWAGGER_2 = 'swagger2'
#
# def parse_version(doc_dict):
# if 'swagger' in doc_dict:
# version = split_version(doc_dict['swagger'])
# if version[0] != 2: # pragma: no cover
# raise ValueError('Only Swagger 2.x is supported')
# return SWAGGER_2
# elif 'openapi' in doc_dict:
# version = split_version(doc_dict['openapi'])
# if version[0] != 3: # pragma: no cover
# raise ValueError('Only OpenAPI 3.x is supported')
# return OPENAPI_3
# raise ValueError('API document is missing version specifier')
#
# Path: lepo/utils.py
# def maybe_resolve(object, resolve):
# """
# Call `resolve` on the `object`'s `$ref` value if it has one.
#
# :param object: An object.
# :param resolve: A resolving function.
# :return: An object, or some other object! :sparkles:
# """
# if isinstance(object, dict) and object.get('$ref'):
# return resolve(object['$ref'])
# return object
. Output only the next line. | operation_class = Swagger2Operation |
Given snippet: <|code_start|> Iterate over all Path objects declared by the API.
:rtype: Iterable[lepo.path.Path]
"""
for path_name in self.get_path_names():
yield self.get_path(path_name)
@classmethod
def from_file(cls, filename):
"""
Construct an APIDefinition by parsing the given `filename`.
If PyYAML is installed, YAML files are supported.
JSON files are always supported.
:param filename: The filename to read.
:rtype: APIDefinition
"""
with open(filename) as infp:
if filename.endswith('.yaml') or filename.endswith('.yml'):
data = yaml.safe_load(infp)
else:
data = json.load(infp)
return cls.from_data(data)
@classmethod
def from_data(cls, data):
version = parse_version(data)
if version == SWAGGER_2:
return Swagger2APIDefinition(data)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from jsonschema import RefResolver
from lepo.apidef.operation.openapi import OpenAPI3Operation
from lepo.apidef.operation.swagger import Swagger2Operation
from lepo.apidef.path import Path
from lepo.apidef.version import OPENAPI_3, SWAGGER_2, parse_version
from lepo.utils import maybe_resolve
from yaml import safe_load
import yaml
import json
and context:
# Path: lepo/apidef/operation/openapi.py
# class OpenAPI3Operation(Operation):
# parameter_class = OpenAPI3Parameter
# body_parameter_class = OpenAPI3BodyParameter
#
# def _get_body_parameter(self):
# for source in (
# self.path.mapping.get('requestBody'),
# self.data.get('requestBody'),
# ):
# if source:
# source = maybe_resolve(source, self.api.resolve_reference)
# body_parameter = self.body_parameter_class(data=source, operation=self, api=self.api)
# # TODO: Document x-lepo-body-name
# body_parameter.name = self.data.get('x-lepo-body-name', body_parameter.name)
# return body_parameter
#
# def get_parameter_dict(self):
# parameter_dict = super().get_parameter_dict()
# for parameter in parameter_dict.values():
# if parameter.in_body: # pragma: no cover
# raise ValueError('Regular parameter declared to be in body while parsing OpenAPI 3')
# body_parameter = self._get_body_parameter()
# if body_parameter:
# parameter_dict[body_parameter.name] = body_parameter
# return parameter_dict
#
# Path: lepo/apidef/operation/swagger.py
# class Swagger2Operation(Operation):
# parameter_class = Swagger2Parameter
#
# @cached_property
# def consumes(self):
# value = self._get_overridable('consumes', [])
# if not isinstance(value, (list, tuple)):
# raise TypeError(f'`consumes` must be a list, got {value!r}') # pragma: no cover
# return value
#
# @cached_property
# def produces(self):
# value = self._get_overridable('produces', [])
# if not isinstance(value, (list, tuple)):
# raise TypeError(f'`produces` must be a list, got {value!r}') # pragma: no cover
# return value
#
# Path: lepo/apidef/path.py
# class Path:
# def __init__(self, api, path, mapping):
# """
# :type api: lepo.apidef.APIDefinition
# :type path: str
# :type mapping: dict
# """
# self.api = api
# self.path = path
# self.mapping = mapping
# self.regex = self._build_regex()
# self.name = self._build_view_name()
#
# def get_view_class(self, router):
# return type(f'{self.name.title()}View', (PathView,), {
# 'path': self,
# 'router': router,
# })
#
# def _build_view_name(self):
# path = re.sub(PATH_PLACEHOLDER_REGEX, r'\1', self.path)
# name = re.sub(r'[^a-z0-9]+', '-', path, flags=re.I).strip('-').lower()
# return name
#
# def _build_regex(self):
# return re.sub(
# PATH_PLACEHOLDER_REGEX,
# lambda m: f'(?P<{m.group(1)}>[^/]+?)',
# self.path,
# ).lstrip('/') + '$'
#
# def get_operation(self, method):
# operation_data = self.mapping.get(method.lower())
# if not operation_data:
# raise InvalidOperation(f'Path {self.path} does not support method {method.upper()}')
# return self.api.operation_class(api=self.api, path=self, data=operation_data, method=method)
#
# def get_operations(self):
# for method in METHODS:
# if method in self.mapping:
# yield self.get_operation(method)
#
# Path: lepo/apidef/version.py
# OPENAPI_3 = 'openapi3'
#
# SWAGGER_2 = 'swagger2'
#
# def parse_version(doc_dict):
# if 'swagger' in doc_dict:
# version = split_version(doc_dict['swagger'])
# if version[0] != 2: # pragma: no cover
# raise ValueError('Only Swagger 2.x is supported')
# return SWAGGER_2
# elif 'openapi' in doc_dict:
# version = split_version(doc_dict['openapi'])
# if version[0] != 3: # pragma: no cover
# raise ValueError('Only OpenAPI 3.x is supported')
# return OPENAPI_3
# raise ValueError('API document is missing version specifier')
#
# Path: lepo/utils.py
# def maybe_resolve(object, resolve):
# """
# Call `resolve` on the `object`'s `$ref` value if it has one.
#
# :param object: An object.
# :param resolve: A resolving function.
# :return: An object, or some other object! :sparkles:
# """
# if isinstance(object, dict) and object.get('$ref'):
# return resolve(object['$ref'])
# return object
which might include code, classes, or functions. Output only the next line. | if version == OPENAPI_3: |
Predict the next line after this snippet: <|code_start|> def get_paths(self):
"""
Iterate over all Path objects declared by the API.
:rtype: Iterable[lepo.path.Path]
"""
for path_name in self.get_path_names():
yield self.get_path(path_name)
@classmethod
def from_file(cls, filename):
"""
Construct an APIDefinition by parsing the given `filename`.
If PyYAML is installed, YAML files are supported.
JSON files are always supported.
:param filename: The filename to read.
:rtype: APIDefinition
"""
with open(filename) as infp:
if filename.endswith('.yaml') or filename.endswith('.yml'):
data = yaml.safe_load(infp)
else:
data = json.load(infp)
return cls.from_data(data)
@classmethod
def from_data(cls, data):
version = parse_version(data)
<|code_end|>
using the current file's imports:
from jsonschema import RefResolver
from lepo.apidef.operation.openapi import OpenAPI3Operation
from lepo.apidef.operation.swagger import Swagger2Operation
from lepo.apidef.path import Path
from lepo.apidef.version import OPENAPI_3, SWAGGER_2, parse_version
from lepo.utils import maybe_resolve
from yaml import safe_load
import yaml
import json
and any relevant context from other files:
# Path: lepo/apidef/operation/openapi.py
# class OpenAPI3Operation(Operation):
# parameter_class = OpenAPI3Parameter
# body_parameter_class = OpenAPI3BodyParameter
#
# def _get_body_parameter(self):
# for source in (
# self.path.mapping.get('requestBody'),
# self.data.get('requestBody'),
# ):
# if source:
# source = maybe_resolve(source, self.api.resolve_reference)
# body_parameter = self.body_parameter_class(data=source, operation=self, api=self.api)
# # TODO: Document x-lepo-body-name
# body_parameter.name = self.data.get('x-lepo-body-name', body_parameter.name)
# return body_parameter
#
# def get_parameter_dict(self):
# parameter_dict = super().get_parameter_dict()
# for parameter in parameter_dict.values():
# if parameter.in_body: # pragma: no cover
# raise ValueError('Regular parameter declared to be in body while parsing OpenAPI 3')
# body_parameter = self._get_body_parameter()
# if body_parameter:
# parameter_dict[body_parameter.name] = body_parameter
# return parameter_dict
#
# Path: lepo/apidef/operation/swagger.py
# class Swagger2Operation(Operation):
# parameter_class = Swagger2Parameter
#
# @cached_property
# def consumes(self):
# value = self._get_overridable('consumes', [])
# if not isinstance(value, (list, tuple)):
# raise TypeError(f'`consumes` must be a list, got {value!r}') # pragma: no cover
# return value
#
# @cached_property
# def produces(self):
# value = self._get_overridable('produces', [])
# if not isinstance(value, (list, tuple)):
# raise TypeError(f'`produces` must be a list, got {value!r}') # pragma: no cover
# return value
#
# Path: lepo/apidef/path.py
# class Path:
# def __init__(self, api, path, mapping):
# """
# :type api: lepo.apidef.APIDefinition
# :type path: str
# :type mapping: dict
# """
# self.api = api
# self.path = path
# self.mapping = mapping
# self.regex = self._build_regex()
# self.name = self._build_view_name()
#
# def get_view_class(self, router):
# return type(f'{self.name.title()}View', (PathView,), {
# 'path': self,
# 'router': router,
# })
#
# def _build_view_name(self):
# path = re.sub(PATH_PLACEHOLDER_REGEX, r'\1', self.path)
# name = re.sub(r'[^a-z0-9]+', '-', path, flags=re.I).strip('-').lower()
# return name
#
# def _build_regex(self):
# return re.sub(
# PATH_PLACEHOLDER_REGEX,
# lambda m: f'(?P<{m.group(1)}>[^/]+?)',
# self.path,
# ).lstrip('/') + '$'
#
# def get_operation(self, method):
# operation_data = self.mapping.get(method.lower())
# if not operation_data:
# raise InvalidOperation(f'Path {self.path} does not support method {method.upper()}')
# return self.api.operation_class(api=self.api, path=self, data=operation_data, method=method)
#
# def get_operations(self):
# for method in METHODS:
# if method in self.mapping:
# yield self.get_operation(method)
#
# Path: lepo/apidef/version.py
# OPENAPI_3 = 'openapi3'
#
# SWAGGER_2 = 'swagger2'
#
# def parse_version(doc_dict):
# if 'swagger' in doc_dict:
# version = split_version(doc_dict['swagger'])
# if version[0] != 2: # pragma: no cover
# raise ValueError('Only Swagger 2.x is supported')
# return SWAGGER_2
# elif 'openapi' in doc_dict:
# version = split_version(doc_dict['openapi'])
# if version[0] != 3: # pragma: no cover
# raise ValueError('Only OpenAPI 3.x is supported')
# return OPENAPI_3
# raise ValueError('API document is missing version specifier')
#
# Path: lepo/utils.py
# def maybe_resolve(object, resolve):
# """
# Call `resolve` on the `object`'s `$ref` value if it has one.
#
# :param object: An object.
# :param resolve: A resolving function.
# :return: An object, or some other object! :sparkles:
# """
# if isinstance(object, dict) and object.get('$ref'):
# return resolve(object['$ref'])
# return object
. Output only the next line. | if version == SWAGGER_2: |
Predict the next line for this snippet: <|code_start|>
def get_paths(self):
"""
Iterate over all Path objects declared by the API.
:rtype: Iterable[lepo.path.Path]
"""
for path_name in self.get_path_names():
yield self.get_path(path_name)
@classmethod
def from_file(cls, filename):
"""
Construct an APIDefinition by parsing the given `filename`.
If PyYAML is installed, YAML files are supported.
JSON files are always supported.
:param filename: The filename to read.
:rtype: APIDefinition
"""
with open(filename) as infp:
if filename.endswith('.yaml') or filename.endswith('.yml'):
data = yaml.safe_load(infp)
else:
data = json.load(infp)
return cls.from_data(data)
@classmethod
def from_data(cls, data):
<|code_end|>
with the help of current file imports:
from jsonschema import RefResolver
from lepo.apidef.operation.openapi import OpenAPI3Operation
from lepo.apidef.operation.swagger import Swagger2Operation
from lepo.apidef.path import Path
from lepo.apidef.version import OPENAPI_3, SWAGGER_2, parse_version
from lepo.utils import maybe_resolve
from yaml import safe_load
import yaml
import json
and context from other files:
# Path: lepo/apidef/operation/openapi.py
# class OpenAPI3Operation(Operation):
# parameter_class = OpenAPI3Parameter
# body_parameter_class = OpenAPI3BodyParameter
#
# def _get_body_parameter(self):
# for source in (
# self.path.mapping.get('requestBody'),
# self.data.get('requestBody'),
# ):
# if source:
# source = maybe_resolve(source, self.api.resolve_reference)
# body_parameter = self.body_parameter_class(data=source, operation=self, api=self.api)
# # TODO: Document x-lepo-body-name
# body_parameter.name = self.data.get('x-lepo-body-name', body_parameter.name)
# return body_parameter
#
# def get_parameter_dict(self):
# parameter_dict = super().get_parameter_dict()
# for parameter in parameter_dict.values():
# if parameter.in_body: # pragma: no cover
# raise ValueError('Regular parameter declared to be in body while parsing OpenAPI 3')
# body_parameter = self._get_body_parameter()
# if body_parameter:
# parameter_dict[body_parameter.name] = body_parameter
# return parameter_dict
#
# Path: lepo/apidef/operation/swagger.py
# class Swagger2Operation(Operation):
# parameter_class = Swagger2Parameter
#
# @cached_property
# def consumes(self):
# value = self._get_overridable('consumes', [])
# if not isinstance(value, (list, tuple)):
# raise TypeError(f'`consumes` must be a list, got {value!r}') # pragma: no cover
# return value
#
# @cached_property
# def produces(self):
# value = self._get_overridable('produces', [])
# if not isinstance(value, (list, tuple)):
# raise TypeError(f'`produces` must be a list, got {value!r}') # pragma: no cover
# return value
#
# Path: lepo/apidef/path.py
# class Path:
# def __init__(self, api, path, mapping):
# """
# :type api: lepo.apidef.APIDefinition
# :type path: str
# :type mapping: dict
# """
# self.api = api
# self.path = path
# self.mapping = mapping
# self.regex = self._build_regex()
# self.name = self._build_view_name()
#
# def get_view_class(self, router):
# return type(f'{self.name.title()}View', (PathView,), {
# 'path': self,
# 'router': router,
# })
#
# def _build_view_name(self):
# path = re.sub(PATH_PLACEHOLDER_REGEX, r'\1', self.path)
# name = re.sub(r'[^a-z0-9]+', '-', path, flags=re.I).strip('-').lower()
# return name
#
# def _build_regex(self):
# return re.sub(
# PATH_PLACEHOLDER_REGEX,
# lambda m: f'(?P<{m.group(1)}>[^/]+?)',
# self.path,
# ).lstrip('/') + '$'
#
# def get_operation(self, method):
# operation_data = self.mapping.get(method.lower())
# if not operation_data:
# raise InvalidOperation(f'Path {self.path} does not support method {method.upper()}')
# return self.api.operation_class(api=self.api, path=self, data=operation_data, method=method)
#
# def get_operations(self):
# for method in METHODS:
# if method in self.mapping:
# yield self.get_operation(method)
#
# Path: lepo/apidef/version.py
# OPENAPI_3 = 'openapi3'
#
# SWAGGER_2 = 'swagger2'
#
# def parse_version(doc_dict):
# if 'swagger' in doc_dict:
# version = split_version(doc_dict['swagger'])
# if version[0] != 2: # pragma: no cover
# raise ValueError('Only Swagger 2.x is supported')
# return SWAGGER_2
# elif 'openapi' in doc_dict:
# version = split_version(doc_dict['openapi'])
# if version[0] != 3: # pragma: no cover
# raise ValueError('Only OpenAPI 3.x is supported')
# return OPENAPI_3
# raise ValueError('API document is missing version specifier')
#
# Path: lepo/utils.py
# def maybe_resolve(object, resolve):
# """
# Call `resolve` on the `object`'s `$ref` value if it has one.
#
# :param object: An object.
# :param resolve: A resolving function.
# :return: An object, or some other object! :sparkles:
# """
# if isinstance(object, dict) and object.get('$ref'):
# return resolve(object['$ref'])
# return object
, which may contain function names, class names, or code. Output only the next line. | version = parse_version(data) |
Given the following code snippet before the placeholder: <|code_start|>
class APIDefinition:
version = None
path_class = Path
operation_class = None
def __init__(self, doc):
"""
Instantiate a new Lepo router.
:param doc: The OpenAPI definition document.
:type doc: dict
"""
self.doc = doc
self.resolver = RefResolver('', self.doc)
def resolve_reference(self, ref):
"""
Resolve a JSON Pointer object reference to the object itself.
:param ref: Reference string (`#/foo/bar`, for instance)
:return: The object, if found
:raises jsonschema.exceptions.RefResolutionError: if there is trouble resolving the reference
"""
url, resolved = self.resolver.resolve(ref)
return resolved
def get_path_mapping(self, path):
<|code_end|>
, predict the next line using imports from the current file:
from jsonschema import RefResolver
from lepo.apidef.operation.openapi import OpenAPI3Operation
from lepo.apidef.operation.swagger import Swagger2Operation
from lepo.apidef.path import Path
from lepo.apidef.version import OPENAPI_3, SWAGGER_2, parse_version
from lepo.utils import maybe_resolve
from yaml import safe_load
import yaml
import json
and context including class names, function names, and sometimes code from other files:
# Path: lepo/apidef/operation/openapi.py
# class OpenAPI3Operation(Operation):
# parameter_class = OpenAPI3Parameter
# body_parameter_class = OpenAPI3BodyParameter
#
# def _get_body_parameter(self):
# for source in (
# self.path.mapping.get('requestBody'),
# self.data.get('requestBody'),
# ):
# if source:
# source = maybe_resolve(source, self.api.resolve_reference)
# body_parameter = self.body_parameter_class(data=source, operation=self, api=self.api)
# # TODO: Document x-lepo-body-name
# body_parameter.name = self.data.get('x-lepo-body-name', body_parameter.name)
# return body_parameter
#
# def get_parameter_dict(self):
# parameter_dict = super().get_parameter_dict()
# for parameter in parameter_dict.values():
# if parameter.in_body: # pragma: no cover
# raise ValueError('Regular parameter declared to be in body while parsing OpenAPI 3')
# body_parameter = self._get_body_parameter()
# if body_parameter:
# parameter_dict[body_parameter.name] = body_parameter
# return parameter_dict
#
# Path: lepo/apidef/operation/swagger.py
# class Swagger2Operation(Operation):
# parameter_class = Swagger2Parameter
#
# @cached_property
# def consumes(self):
# value = self._get_overridable('consumes', [])
# if not isinstance(value, (list, tuple)):
# raise TypeError(f'`consumes` must be a list, got {value!r}') # pragma: no cover
# return value
#
# @cached_property
# def produces(self):
# value = self._get_overridable('produces', [])
# if not isinstance(value, (list, tuple)):
# raise TypeError(f'`produces` must be a list, got {value!r}') # pragma: no cover
# return value
#
# Path: lepo/apidef/path.py
# class Path:
# def __init__(self, api, path, mapping):
# """
# :type api: lepo.apidef.APIDefinition
# :type path: str
# :type mapping: dict
# """
# self.api = api
# self.path = path
# self.mapping = mapping
# self.regex = self._build_regex()
# self.name = self._build_view_name()
#
# def get_view_class(self, router):
# return type(f'{self.name.title()}View', (PathView,), {
# 'path': self,
# 'router': router,
# })
#
# def _build_view_name(self):
# path = re.sub(PATH_PLACEHOLDER_REGEX, r'\1', self.path)
# name = re.sub(r'[^a-z0-9]+', '-', path, flags=re.I).strip('-').lower()
# return name
#
# def _build_regex(self):
# return re.sub(
# PATH_PLACEHOLDER_REGEX,
# lambda m: f'(?P<{m.group(1)}>[^/]+?)',
# self.path,
# ).lstrip('/') + '$'
#
# def get_operation(self, method):
# operation_data = self.mapping.get(method.lower())
# if not operation_data:
# raise InvalidOperation(f'Path {self.path} does not support method {method.upper()}')
# return self.api.operation_class(api=self.api, path=self, data=operation_data, method=method)
#
# def get_operations(self):
# for method in METHODS:
# if method in self.mapping:
# yield self.get_operation(method)
#
# Path: lepo/apidef/version.py
# OPENAPI_3 = 'openapi3'
#
# SWAGGER_2 = 'swagger2'
#
# def parse_version(doc_dict):
# if 'swagger' in doc_dict:
# version = split_version(doc_dict['swagger'])
# if version[0] != 2: # pragma: no cover
# raise ValueError('Only Swagger 2.x is supported')
# return SWAGGER_2
# elif 'openapi' in doc_dict:
# version = split_version(doc_dict['openapi'])
# if version[0] != 3: # pragma: no cover
# raise ValueError('Only OpenAPI 3.x is supported')
# return OPENAPI_3
# raise ValueError('API document is missing version specifier')
#
# Path: lepo/utils.py
# def maybe_resolve(object, resolve):
# """
# Call `resolve` on the `object`'s `$ref` value if it has one.
#
# :param object: An object.
# :param resolve: A resolving function.
# :return: An object, or some other object! :sparkles:
# """
# if isinstance(object, dict) and object.get('$ref'):
# return resolve(object['$ref'])
# return object
. Output only the next line. | return maybe_resolve(self.doc['paths'][path], self.resolve_reference) |
Using the snippet: <|code_start|>
routers = pytest.mark.parametrize('router', [
get_router(f'{doc_version}/parameter-test.yaml')
for doc_version
in DOC_VERSIONS
], ids=DOC_VERSIONS)
def test_parameter_validation():
with pytest.raises(ValidationError) as ei:
cast_parameter_value(
Swagger2APIDefinition({}),
{
'type': 'array',
'collectionFormat': 'ssv',
'items': {
'type': 'string',
'maxLength': 3,
},
},
'what it do',
)
assert "'what' is too long" in str(ei.value)
@routers
def test_files(rf, router):
request = rf.post('/upload', {
'file': ContentFile(b'foo', name='foo.txt'),
})
<|code_end|>
, determine the next line of code. You have imports:
import pytest
from django.core.exceptions import ImproperlyConfigured
from django.core.files.base import ContentFile
from django.core.files.uploadedfile import UploadedFile
from jsonschema import ValidationError
from lepo.api_info import APIInfo
from lepo.apidef.doc import Swagger2APIDefinition
from lepo.apidef.parameter.openapi import OpenAPI3BodyParameter
from lepo.excs import ErroneousParameters, MissingParameter
from lepo.parameter_utils import read_parameters
from lepo_tests.tests.utils import DOC_VERSIONS, cast_parameter_value, get_router
and context (class names, function names, or code) available:
# Path: lepo/api_info.py
# class APIInfo:
# def __init__(self, operation, router=None):
# """
# :type operation: lepo.operation.Operation
# :type router: lepo.router.Router
# """
# self.api = operation.api
# self.path = operation.path
# self.operation = operation
# self.router = router
#
# Path: lepo/apidef/doc.py
# class Swagger2APIDefinition(APIDefinition):
# version = SWAGGER_2
# operation_class = Swagger2Operation
#
# Path: lepo/apidef/parameter/openapi.py
# class OpenAPI3BodyParameter(OpenAPI3Parameter):
# """
# OpenAPI 3 Body Parameter
# """
#
# name = '_body'
#
# @property
# def location(self):
# return 'body'
#
# def get_value(self, request, view_kwargs):
# media_map = self.media_map
# content_type_name = media_map.match(request.content_type)
# if not content_type_name:
# raise InvalidBodyFormat(f'Content-type {request.content_type} is not supported ({media_map.keys()!r} are)')
# parameter = media_map[content_type_name]
# value = read_body(request, parameter=parameter)
# return WrappedValue(parameter=parameter, value=value)
#
# Path: lepo/excs.py
# class ErroneousParameters(Exception):
# def __init__(self, error_map, parameters):
# self.errors = error_map
# self.parameters = parameters
#
# class MissingParameter(ValueError):
# pass
#
# Path: lepo/parameter_utils.py
# def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901
# """
# :param request: HttpRequest with attached api_info
# :type request: HttpRequest
# :type view_kwargs: dict[str, object]
# :type capture_errors: bool
# :rtype: dict[str, object]
# """
# if view_kwargs is None:
# view_kwargs = {}
# params = {}
# errors = {}
# for param in request.api_info.operation.parameters:
# try:
# value = param.get_value(request, view_kwargs)
# if value is NO_VALUE:
# if param.has_default:
# params[param.name] = param.default
# elif param.required: # Required but missing
# errors[param.name] = MissingParameter(f'parameter {param.name} is required but missing')
# continue # No value, or a default was added, or an error was added.
# params[param.name] = param.cast(request.api_info.api, value)
# except (NotImplementedError, ImproperlyConfigured):
# raise
# except Exception as e:
# if not capture_errors:
# raise
# errors[param.name] = e
# if errors:
# raise ErroneousParameters(errors, params)
# return params
#
# Path: lepo_tests/tests/utils.py
# DOC_VERSIONS = ['swagger2', 'openapi3']
#
# def cast_parameter_value(apidoc, parameter, value):
# if isinstance(parameter, dict):
# parameter_class = apidoc.operation_class.parameter_class
# parameter = parameter_class(parameter)
# return parameter.cast(apidoc, value)
#
# def get_router(fixture_name):
# return Router.from_file(os.path.join(TESTS_DIR, fixture_name))
. Output only the next line. | request.api_info = APIInfo(router.get_path('/upload').get_operation('post')) |
Continue the code snippet: <|code_start|>
routers = pytest.mark.parametrize('router', [
get_router(f'{doc_version}/parameter-test.yaml')
for doc_version
in DOC_VERSIONS
], ids=DOC_VERSIONS)
def test_parameter_validation():
with pytest.raises(ValidationError) as ei:
cast_parameter_value(
<|code_end|>
. Use current file imports:
import pytest
from django.core.exceptions import ImproperlyConfigured
from django.core.files.base import ContentFile
from django.core.files.uploadedfile import UploadedFile
from jsonschema import ValidationError
from lepo.api_info import APIInfo
from lepo.apidef.doc import Swagger2APIDefinition
from lepo.apidef.parameter.openapi import OpenAPI3BodyParameter
from lepo.excs import ErroneousParameters, MissingParameter
from lepo.parameter_utils import read_parameters
from lepo_tests.tests.utils import DOC_VERSIONS, cast_parameter_value, get_router
and context (classes, functions, or code) from other files:
# Path: lepo/api_info.py
# class APIInfo:
# def __init__(self, operation, router=None):
# """
# :type operation: lepo.operation.Operation
# :type router: lepo.router.Router
# """
# self.api = operation.api
# self.path = operation.path
# self.operation = operation
# self.router = router
#
# Path: lepo/apidef/doc.py
# class Swagger2APIDefinition(APIDefinition):
# version = SWAGGER_2
# operation_class = Swagger2Operation
#
# Path: lepo/apidef/parameter/openapi.py
# class OpenAPI3BodyParameter(OpenAPI3Parameter):
# """
# OpenAPI 3 Body Parameter
# """
#
# name = '_body'
#
# @property
# def location(self):
# return 'body'
#
# def get_value(self, request, view_kwargs):
# media_map = self.media_map
# content_type_name = media_map.match(request.content_type)
# if not content_type_name:
# raise InvalidBodyFormat(f'Content-type {request.content_type} is not supported ({media_map.keys()!r} are)')
# parameter = media_map[content_type_name]
# value = read_body(request, parameter=parameter)
# return WrappedValue(parameter=parameter, value=value)
#
# Path: lepo/excs.py
# class ErroneousParameters(Exception):
# def __init__(self, error_map, parameters):
# self.errors = error_map
# self.parameters = parameters
#
# class MissingParameter(ValueError):
# pass
#
# Path: lepo/parameter_utils.py
# def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901
# """
# :param request: HttpRequest with attached api_info
# :type request: HttpRequest
# :type view_kwargs: dict[str, object]
# :type capture_errors: bool
# :rtype: dict[str, object]
# """
# if view_kwargs is None:
# view_kwargs = {}
# params = {}
# errors = {}
# for param in request.api_info.operation.parameters:
# try:
# value = param.get_value(request, view_kwargs)
# if value is NO_VALUE:
# if param.has_default:
# params[param.name] = param.default
# elif param.required: # Required but missing
# errors[param.name] = MissingParameter(f'parameter {param.name} is required but missing')
# continue # No value, or a default was added, or an error was added.
# params[param.name] = param.cast(request.api_info.api, value)
# except (NotImplementedError, ImproperlyConfigured):
# raise
# except Exception as e:
# if not capture_errors:
# raise
# errors[param.name] = e
# if errors:
# raise ErroneousParameters(errors, params)
# return params
#
# Path: lepo_tests/tests/utils.py
# DOC_VERSIONS = ['swagger2', 'openapi3']
#
# def cast_parameter_value(apidoc, parameter, value):
# if isinstance(parameter, dict):
# parameter_class = apidoc.operation_class.parameter_class
# parameter = parameter_class(parameter)
# return parameter.cast(apidoc, value)
#
# def get_router(fixture_name):
# return Router.from_file(os.path.join(TESTS_DIR, fixture_name))
. Output only the next line. | Swagger2APIDefinition({}), |
Based on the snippet: <|code_start|> get_router(f'{doc_version}/parameter-test.yaml')
for doc_version
in DOC_VERSIONS
], ids=DOC_VERSIONS)
def test_parameter_validation():
with pytest.raises(ValidationError) as ei:
cast_parameter_value(
Swagger2APIDefinition({}),
{
'type': 'array',
'collectionFormat': 'ssv',
'items': {
'type': 'string',
'maxLength': 3,
},
},
'what it do',
)
assert "'what' is too long" in str(ei.value)
@routers
def test_files(rf, router):
request = rf.post('/upload', {
'file': ContentFile(b'foo', name='foo.txt'),
})
request.api_info = APIInfo(router.get_path('/upload').get_operation('post'))
parameters = read_parameters(request)
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
from django.core.exceptions import ImproperlyConfigured
from django.core.files.base import ContentFile
from django.core.files.uploadedfile import UploadedFile
from jsonschema import ValidationError
from lepo.api_info import APIInfo
from lepo.apidef.doc import Swagger2APIDefinition
from lepo.apidef.parameter.openapi import OpenAPI3BodyParameter
from lepo.excs import ErroneousParameters, MissingParameter
from lepo.parameter_utils import read_parameters
from lepo_tests.tests.utils import DOC_VERSIONS, cast_parameter_value, get_router
and context (classes, functions, sometimes code) from other files:
# Path: lepo/api_info.py
# class APIInfo:
# def __init__(self, operation, router=None):
# """
# :type operation: lepo.operation.Operation
# :type router: lepo.router.Router
# """
# self.api = operation.api
# self.path = operation.path
# self.operation = operation
# self.router = router
#
# Path: lepo/apidef/doc.py
# class Swagger2APIDefinition(APIDefinition):
# version = SWAGGER_2
# operation_class = Swagger2Operation
#
# Path: lepo/apidef/parameter/openapi.py
# class OpenAPI3BodyParameter(OpenAPI3Parameter):
# """
# OpenAPI 3 Body Parameter
# """
#
# name = '_body'
#
# @property
# def location(self):
# return 'body'
#
# def get_value(self, request, view_kwargs):
# media_map = self.media_map
# content_type_name = media_map.match(request.content_type)
# if not content_type_name:
# raise InvalidBodyFormat(f'Content-type {request.content_type} is not supported ({media_map.keys()!r} are)')
# parameter = media_map[content_type_name]
# value = read_body(request, parameter=parameter)
# return WrappedValue(parameter=parameter, value=value)
#
# Path: lepo/excs.py
# class ErroneousParameters(Exception):
# def __init__(self, error_map, parameters):
# self.errors = error_map
# self.parameters = parameters
#
# class MissingParameter(ValueError):
# pass
#
# Path: lepo/parameter_utils.py
# def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901
# """
# :param request: HttpRequest with attached api_info
# :type request: HttpRequest
# :type view_kwargs: dict[str, object]
# :type capture_errors: bool
# :rtype: dict[str, object]
# """
# if view_kwargs is None:
# view_kwargs = {}
# params = {}
# errors = {}
# for param in request.api_info.operation.parameters:
# try:
# value = param.get_value(request, view_kwargs)
# if value is NO_VALUE:
# if param.has_default:
# params[param.name] = param.default
# elif param.required: # Required but missing
# errors[param.name] = MissingParameter(f'parameter {param.name} is required but missing')
# continue # No value, or a default was added, or an error was added.
# params[param.name] = param.cast(request.api_info.api, value)
# except (NotImplementedError, ImproperlyConfigured):
# raise
# except Exception as e:
# if not capture_errors:
# raise
# errors[param.name] = e
# if errors:
# raise ErroneousParameters(errors, params)
# return params
#
# Path: lepo_tests/tests/utils.py
# DOC_VERSIONS = ['swagger2', 'openapi3']
#
# def cast_parameter_value(apidoc, parameter, value):
# if isinstance(parameter, dict):
# parameter_class = apidoc.operation_class.parameter_class
# parameter = parameter_class(parameter)
# return parameter.cast(apidoc, value)
#
# def get_router(fixture_name):
# return Router.from_file(os.path.join(TESTS_DIR, fixture_name))
. Output only the next line. | if OpenAPI3BodyParameter.name in parameters: # Peel into the body parameter |
Given the code snippet: <|code_start|> request = rf.post('/upload', {
'file': ContentFile(b'foo', name='foo.txt'),
})
request.api_info = APIInfo(router.get_path('/upload').get_operation('post'))
parameters = read_parameters(request)
if OpenAPI3BodyParameter.name in parameters: # Peel into the body parameter
parameters = parameters[OpenAPI3BodyParameter.name]
assert isinstance(parameters['file'], UploadedFile)
@routers
def test_multi(rf, router):
request = rf.get('/multiple-tags?tag=a&tag=b&tag=c')
request.api_info = APIInfo(router.get_path('/multiple-tags').get_operation('get'))
parameters = read_parameters(request)
assert parameters['tag'] == ['a', 'b', 'c']
@routers
def test_default(rf, router):
request = rf.get('/greet?greetee=doggo')
request.api_info = APIInfo(router.get_path('/greet').get_operation('get'))
parameters = read_parameters(request)
assert parameters == {'greeting': 'henlo', 'greetee': 'doggo'}
@routers
def test_required(rf, router):
request = rf.get('/greet')
request.api_info = APIInfo(router.get_path('/greet').get_operation('get'))
<|code_end|>
, generate the next line using the imports in this file:
import pytest
from django.core.exceptions import ImproperlyConfigured
from django.core.files.base import ContentFile
from django.core.files.uploadedfile import UploadedFile
from jsonschema import ValidationError
from lepo.api_info import APIInfo
from lepo.apidef.doc import Swagger2APIDefinition
from lepo.apidef.parameter.openapi import OpenAPI3BodyParameter
from lepo.excs import ErroneousParameters, MissingParameter
from lepo.parameter_utils import read_parameters
from lepo_tests.tests.utils import DOC_VERSIONS, cast_parameter_value, get_router
and context (functions, classes, or occasionally code) from other files:
# Path: lepo/api_info.py
# class APIInfo:
# def __init__(self, operation, router=None):
# """
# :type operation: lepo.operation.Operation
# :type router: lepo.router.Router
# """
# self.api = operation.api
# self.path = operation.path
# self.operation = operation
# self.router = router
#
# Path: lepo/apidef/doc.py
# class Swagger2APIDefinition(APIDefinition):
# version = SWAGGER_2
# operation_class = Swagger2Operation
#
# Path: lepo/apidef/parameter/openapi.py
# class OpenAPI3BodyParameter(OpenAPI3Parameter):
# """
# OpenAPI 3 Body Parameter
# """
#
# name = '_body'
#
# @property
# def location(self):
# return 'body'
#
# def get_value(self, request, view_kwargs):
# media_map = self.media_map
# content_type_name = media_map.match(request.content_type)
# if not content_type_name:
# raise InvalidBodyFormat(f'Content-type {request.content_type} is not supported ({media_map.keys()!r} are)')
# parameter = media_map[content_type_name]
# value = read_body(request, parameter=parameter)
# return WrappedValue(parameter=parameter, value=value)
#
# Path: lepo/excs.py
# class ErroneousParameters(Exception):
# def __init__(self, error_map, parameters):
# self.errors = error_map
# self.parameters = parameters
#
# class MissingParameter(ValueError):
# pass
#
# Path: lepo/parameter_utils.py
# def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901
# """
# :param request: HttpRequest with attached api_info
# :type request: HttpRequest
# :type view_kwargs: dict[str, object]
# :type capture_errors: bool
# :rtype: dict[str, object]
# """
# if view_kwargs is None:
# view_kwargs = {}
# params = {}
# errors = {}
# for param in request.api_info.operation.parameters:
# try:
# value = param.get_value(request, view_kwargs)
# if value is NO_VALUE:
# if param.has_default:
# params[param.name] = param.default
# elif param.required: # Required but missing
# errors[param.name] = MissingParameter(f'parameter {param.name} is required but missing')
# continue # No value, or a default was added, or an error was added.
# params[param.name] = param.cast(request.api_info.api, value)
# except (NotImplementedError, ImproperlyConfigured):
# raise
# except Exception as e:
# if not capture_errors:
# raise
# errors[param.name] = e
# if errors:
# raise ErroneousParameters(errors, params)
# return params
#
# Path: lepo_tests/tests/utils.py
# DOC_VERSIONS = ['swagger2', 'openapi3']
#
# def cast_parameter_value(apidoc, parameter, value):
# if isinstance(parameter, dict):
# parameter_class = apidoc.operation_class.parameter_class
# parameter = parameter_class(parameter)
# return parameter.cast(apidoc, value)
#
# def get_router(fixture_name):
# return Router.from_file(os.path.join(TESTS_DIR, fixture_name))
. Output only the next line. | with pytest.raises(ErroneousParameters) as ei: |
Predict the next line after this snippet: <|code_start|> })
request.api_info = APIInfo(router.get_path('/upload').get_operation('post'))
parameters = read_parameters(request)
if OpenAPI3BodyParameter.name in parameters: # Peel into the body parameter
parameters = parameters[OpenAPI3BodyParameter.name]
assert isinstance(parameters['file'], UploadedFile)
@routers
def test_multi(rf, router):
request = rf.get('/multiple-tags?tag=a&tag=b&tag=c')
request.api_info = APIInfo(router.get_path('/multiple-tags').get_operation('get'))
parameters = read_parameters(request)
assert parameters['tag'] == ['a', 'b', 'c']
@routers
def test_default(rf, router):
request = rf.get('/greet?greetee=doggo')
request.api_info = APIInfo(router.get_path('/greet').get_operation('get'))
parameters = read_parameters(request)
assert parameters == {'greeting': 'henlo', 'greetee': 'doggo'}
@routers
def test_required(rf, router):
request = rf.get('/greet')
request.api_info = APIInfo(router.get_path('/greet').get_operation('get'))
with pytest.raises(ErroneousParameters) as ei:
read_parameters(request)
<|code_end|>
using the current file's imports:
import pytest
from django.core.exceptions import ImproperlyConfigured
from django.core.files.base import ContentFile
from django.core.files.uploadedfile import UploadedFile
from jsonschema import ValidationError
from lepo.api_info import APIInfo
from lepo.apidef.doc import Swagger2APIDefinition
from lepo.apidef.parameter.openapi import OpenAPI3BodyParameter
from lepo.excs import ErroneousParameters, MissingParameter
from lepo.parameter_utils import read_parameters
from lepo_tests.tests.utils import DOC_VERSIONS, cast_parameter_value, get_router
and any relevant context from other files:
# Path: lepo/api_info.py
# class APIInfo:
# def __init__(self, operation, router=None):
# """
# :type operation: lepo.operation.Operation
# :type router: lepo.router.Router
# """
# self.api = operation.api
# self.path = operation.path
# self.operation = operation
# self.router = router
#
# Path: lepo/apidef/doc.py
# class Swagger2APIDefinition(APIDefinition):
# version = SWAGGER_2
# operation_class = Swagger2Operation
#
# Path: lepo/apidef/parameter/openapi.py
# class OpenAPI3BodyParameter(OpenAPI3Parameter):
# """
# OpenAPI 3 Body Parameter
# """
#
# name = '_body'
#
# @property
# def location(self):
# return 'body'
#
# def get_value(self, request, view_kwargs):
# media_map = self.media_map
# content_type_name = media_map.match(request.content_type)
# if not content_type_name:
# raise InvalidBodyFormat(f'Content-type {request.content_type} is not supported ({media_map.keys()!r} are)')
# parameter = media_map[content_type_name]
# value = read_body(request, parameter=parameter)
# return WrappedValue(parameter=parameter, value=value)
#
# Path: lepo/excs.py
# class ErroneousParameters(Exception):
# def __init__(self, error_map, parameters):
# self.errors = error_map
# self.parameters = parameters
#
# class MissingParameter(ValueError):
# pass
#
# Path: lepo/parameter_utils.py
# def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901
# """
# :param request: HttpRequest with attached api_info
# :type request: HttpRequest
# :type view_kwargs: dict[str, object]
# :type capture_errors: bool
# :rtype: dict[str, object]
# """
# if view_kwargs is None:
# view_kwargs = {}
# params = {}
# errors = {}
# for param in request.api_info.operation.parameters:
# try:
# value = param.get_value(request, view_kwargs)
# if value is NO_VALUE:
# if param.has_default:
# params[param.name] = param.default
# elif param.required: # Required but missing
# errors[param.name] = MissingParameter(f'parameter {param.name} is required but missing')
# continue # No value, or a default was added, or an error was added.
# params[param.name] = param.cast(request.api_info.api, value)
# except (NotImplementedError, ImproperlyConfigured):
# raise
# except Exception as e:
# if not capture_errors:
# raise
# errors[param.name] = e
# if errors:
# raise ErroneousParameters(errors, params)
# return params
#
# Path: lepo_tests/tests/utils.py
# DOC_VERSIONS = ['swagger2', 'openapi3']
#
# def cast_parameter_value(apidoc, parameter, value):
# if isinstance(parameter, dict):
# parameter_class = apidoc.operation_class.parameter_class
# parameter = parameter_class(parameter)
# return parameter.cast(apidoc, value)
#
# def get_router(fixture_name):
# return Router.from_file(os.path.join(TESTS_DIR, fixture_name))
. Output only the next line. | assert isinstance(ei.value.errors['greetee'], MissingParameter) |
Continue the code snippet: <|code_start|>routers = pytest.mark.parametrize('router', [
get_router(f'{doc_version}/parameter-test.yaml')
for doc_version
in DOC_VERSIONS
], ids=DOC_VERSIONS)
def test_parameter_validation():
with pytest.raises(ValidationError) as ei:
cast_parameter_value(
Swagger2APIDefinition({}),
{
'type': 'array',
'collectionFormat': 'ssv',
'items': {
'type': 'string',
'maxLength': 3,
},
},
'what it do',
)
assert "'what' is too long" in str(ei.value)
@routers
def test_files(rf, router):
request = rf.post('/upload', {
'file': ContentFile(b'foo', name='foo.txt'),
})
request.api_info = APIInfo(router.get_path('/upload').get_operation('post'))
<|code_end|>
. Use current file imports:
import pytest
from django.core.exceptions import ImproperlyConfigured
from django.core.files.base import ContentFile
from django.core.files.uploadedfile import UploadedFile
from jsonschema import ValidationError
from lepo.api_info import APIInfo
from lepo.apidef.doc import Swagger2APIDefinition
from lepo.apidef.parameter.openapi import OpenAPI3BodyParameter
from lepo.excs import ErroneousParameters, MissingParameter
from lepo.parameter_utils import read_parameters
from lepo_tests.tests.utils import DOC_VERSIONS, cast_parameter_value, get_router
and context (classes, functions, or code) from other files:
# Path: lepo/api_info.py
# class APIInfo:
# def __init__(self, operation, router=None):
# """
# :type operation: lepo.operation.Operation
# :type router: lepo.router.Router
# """
# self.api = operation.api
# self.path = operation.path
# self.operation = operation
# self.router = router
#
# Path: lepo/apidef/doc.py
# class Swagger2APIDefinition(APIDefinition):
# version = SWAGGER_2
# operation_class = Swagger2Operation
#
# Path: lepo/apidef/parameter/openapi.py
# class OpenAPI3BodyParameter(OpenAPI3Parameter):
# """
# OpenAPI 3 Body Parameter
# """
#
# name = '_body'
#
# @property
# def location(self):
# return 'body'
#
# def get_value(self, request, view_kwargs):
# media_map = self.media_map
# content_type_name = media_map.match(request.content_type)
# if not content_type_name:
# raise InvalidBodyFormat(f'Content-type {request.content_type} is not supported ({media_map.keys()!r} are)')
# parameter = media_map[content_type_name]
# value = read_body(request, parameter=parameter)
# return WrappedValue(parameter=parameter, value=value)
#
# Path: lepo/excs.py
# class ErroneousParameters(Exception):
# def __init__(self, error_map, parameters):
# self.errors = error_map
# self.parameters = parameters
#
# class MissingParameter(ValueError):
# pass
#
# Path: lepo/parameter_utils.py
# def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901
# """
# :param request: HttpRequest with attached api_info
# :type request: HttpRequest
# :type view_kwargs: dict[str, object]
# :type capture_errors: bool
# :rtype: dict[str, object]
# """
# if view_kwargs is None:
# view_kwargs = {}
# params = {}
# errors = {}
# for param in request.api_info.operation.parameters:
# try:
# value = param.get_value(request, view_kwargs)
# if value is NO_VALUE:
# if param.has_default:
# params[param.name] = param.default
# elif param.required: # Required but missing
# errors[param.name] = MissingParameter(f'parameter {param.name} is required but missing')
# continue # No value, or a default was added, or an error was added.
# params[param.name] = param.cast(request.api_info.api, value)
# except (NotImplementedError, ImproperlyConfigured):
# raise
# except Exception as e:
# if not capture_errors:
# raise
# errors[param.name] = e
# if errors:
# raise ErroneousParameters(errors, params)
# return params
#
# Path: lepo_tests/tests/utils.py
# DOC_VERSIONS = ['swagger2', 'openapi3']
#
# def cast_parameter_value(apidoc, parameter, value):
# if isinstance(parameter, dict):
# parameter_class = apidoc.operation_class.parameter_class
# parameter = parameter_class(parameter)
# return parameter.cast(apidoc, value)
#
# def get_router(fixture_name):
# return Router.from_file(os.path.join(TESTS_DIR, fixture_name))
. Output only the next line. | parameters = read_parameters(request) |
Given the code snippet: <|code_start|>
routers = pytest.mark.parametrize('router', [
get_router(f'{doc_version}/parameter-test.yaml')
for doc_version
<|code_end|>
, generate the next line using the imports in this file:
import pytest
from django.core.exceptions import ImproperlyConfigured
from django.core.files.base import ContentFile
from django.core.files.uploadedfile import UploadedFile
from jsonschema import ValidationError
from lepo.api_info import APIInfo
from lepo.apidef.doc import Swagger2APIDefinition
from lepo.apidef.parameter.openapi import OpenAPI3BodyParameter
from lepo.excs import ErroneousParameters, MissingParameter
from lepo.parameter_utils import read_parameters
from lepo_tests.tests.utils import DOC_VERSIONS, cast_parameter_value, get_router
and context (functions, classes, or occasionally code) from other files:
# Path: lepo/api_info.py
# class APIInfo:
# def __init__(self, operation, router=None):
# """
# :type operation: lepo.operation.Operation
# :type router: lepo.router.Router
# """
# self.api = operation.api
# self.path = operation.path
# self.operation = operation
# self.router = router
#
# Path: lepo/apidef/doc.py
# class Swagger2APIDefinition(APIDefinition):
# version = SWAGGER_2
# operation_class = Swagger2Operation
#
# Path: lepo/apidef/parameter/openapi.py
# class OpenAPI3BodyParameter(OpenAPI3Parameter):
# """
# OpenAPI 3 Body Parameter
# """
#
# name = '_body'
#
# @property
# def location(self):
# return 'body'
#
# def get_value(self, request, view_kwargs):
# media_map = self.media_map
# content_type_name = media_map.match(request.content_type)
# if not content_type_name:
# raise InvalidBodyFormat(f'Content-type {request.content_type} is not supported ({media_map.keys()!r} are)')
# parameter = media_map[content_type_name]
# value = read_body(request, parameter=parameter)
# return WrappedValue(parameter=parameter, value=value)
#
# Path: lepo/excs.py
# class ErroneousParameters(Exception):
# def __init__(self, error_map, parameters):
# self.errors = error_map
# self.parameters = parameters
#
# class MissingParameter(ValueError):
# pass
#
# Path: lepo/parameter_utils.py
# def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901
# """
# :param request: HttpRequest with attached api_info
# :type request: HttpRequest
# :type view_kwargs: dict[str, object]
# :type capture_errors: bool
# :rtype: dict[str, object]
# """
# if view_kwargs is None:
# view_kwargs = {}
# params = {}
# errors = {}
# for param in request.api_info.operation.parameters:
# try:
# value = param.get_value(request, view_kwargs)
# if value is NO_VALUE:
# if param.has_default:
# params[param.name] = param.default
# elif param.required: # Required but missing
# errors[param.name] = MissingParameter(f'parameter {param.name} is required but missing')
# continue # No value, or a default was added, or an error was added.
# params[param.name] = param.cast(request.api_info.api, value)
# except (NotImplementedError, ImproperlyConfigured):
# raise
# except Exception as e:
# if not capture_errors:
# raise
# errors[param.name] = e
# if errors:
# raise ErroneousParameters(errors, params)
# return params
#
# Path: lepo_tests/tests/utils.py
# DOC_VERSIONS = ['swagger2', 'openapi3']
#
# def cast_parameter_value(apidoc, parameter, value):
# if isinstance(parameter, dict):
# parameter_class = apidoc.operation_class.parameter_class
# parameter = parameter_class(parameter)
# return parameter.cast(apidoc, value)
#
# def get_router(fixture_name):
# return Router.from_file(os.path.join(TESTS_DIR, fixture_name))
. Output only the next line. | in DOC_VERSIONS |
Given snippet: <|code_start|>
routers = pytest.mark.parametrize('router', [
get_router(f'{doc_version}/parameter-test.yaml')
for doc_version
in DOC_VERSIONS
], ids=DOC_VERSIONS)
def test_parameter_validation():
with pytest.raises(ValidationError) as ei:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from django.core.exceptions import ImproperlyConfigured
from django.core.files.base import ContentFile
from django.core.files.uploadedfile import UploadedFile
from jsonschema import ValidationError
from lepo.api_info import APIInfo
from lepo.apidef.doc import Swagger2APIDefinition
from lepo.apidef.parameter.openapi import OpenAPI3BodyParameter
from lepo.excs import ErroneousParameters, MissingParameter
from lepo.parameter_utils import read_parameters
from lepo_tests.tests.utils import DOC_VERSIONS, cast_parameter_value, get_router
and context:
# Path: lepo/api_info.py
# class APIInfo:
# def __init__(self, operation, router=None):
# """
# :type operation: lepo.operation.Operation
# :type router: lepo.router.Router
# """
# self.api = operation.api
# self.path = operation.path
# self.operation = operation
# self.router = router
#
# Path: lepo/apidef/doc.py
# class Swagger2APIDefinition(APIDefinition):
# version = SWAGGER_2
# operation_class = Swagger2Operation
#
# Path: lepo/apidef/parameter/openapi.py
# class OpenAPI3BodyParameter(OpenAPI3Parameter):
# """
# OpenAPI 3 Body Parameter
# """
#
# name = '_body'
#
# @property
# def location(self):
# return 'body'
#
# def get_value(self, request, view_kwargs):
# media_map = self.media_map
# content_type_name = media_map.match(request.content_type)
# if not content_type_name:
# raise InvalidBodyFormat(f'Content-type {request.content_type} is not supported ({media_map.keys()!r} are)')
# parameter = media_map[content_type_name]
# value = read_body(request, parameter=parameter)
# return WrappedValue(parameter=parameter, value=value)
#
# Path: lepo/excs.py
# class ErroneousParameters(Exception):
# def __init__(self, error_map, parameters):
# self.errors = error_map
# self.parameters = parameters
#
# class MissingParameter(ValueError):
# pass
#
# Path: lepo/parameter_utils.py
# def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901
# """
# :param request: HttpRequest with attached api_info
# :type request: HttpRequest
# :type view_kwargs: dict[str, object]
# :type capture_errors: bool
# :rtype: dict[str, object]
# """
# if view_kwargs is None:
# view_kwargs = {}
# params = {}
# errors = {}
# for param in request.api_info.operation.parameters:
# try:
# value = param.get_value(request, view_kwargs)
# if value is NO_VALUE:
# if param.has_default:
# params[param.name] = param.default
# elif param.required: # Required but missing
# errors[param.name] = MissingParameter(f'parameter {param.name} is required but missing')
# continue # No value, or a default was added, or an error was added.
# params[param.name] = param.cast(request.api_info.api, value)
# except (NotImplementedError, ImproperlyConfigured):
# raise
# except Exception as e:
# if not capture_errors:
# raise
# errors[param.name] = e
# if errors:
# raise ErroneousParameters(errors, params)
# return params
#
# Path: lepo_tests/tests/utils.py
# DOC_VERSIONS = ['swagger2', 'openapi3']
#
# def cast_parameter_value(apidoc, parameter, value):
# if isinstance(parameter, dict):
# parameter_class = apidoc.operation_class.parameter_class
# parameter = parameter_class(parameter)
# return parameter.cast(apidoc, value)
#
# def get_router(fixture_name):
# return Router.from_file(os.path.join(TESTS_DIR, fixture_name))
which might include code, classes, or functions. Output only the next line. | cast_parameter_value( |
Given snippet: <|code_start|> style: label
explode: true
schema:
type: array
items:
type: string
- name: thing
in: path
schema:
type: string
/object/{thing}/data{format}:
get:
parameters:
- name: format
in: path
style: label
explode: false
schema:
type: object
items:
type: string
- name: thing
in: path
schema:
type: string
''')
def test_label_parameter():
request = make_request_for_operation(doc.get_path('/single/{thing}/data{format}').get_operation('get'))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from lepo.apidef.doc import APIDefinition
from lepo.parameter_utils import read_parameters
from lepo_tests.tests.utils import make_request_for_operation
and context:
# Path: lepo/apidef/doc.py
# class APIDefinition:
# version = None
# path_class = Path
# operation_class = None
#
# def __init__(self, doc):
# """
# Instantiate a new Lepo router.
#
# :param doc: The OpenAPI definition document.
# :type doc: dict
# """
# self.doc = doc
# self.resolver = RefResolver('', self.doc)
#
# def resolve_reference(self, ref):
# """
# Resolve a JSON Pointer object reference to the object itself.
#
# :param ref: Reference string (`#/foo/bar`, for instance)
# :return: The object, if found
# :raises jsonschema.exceptions.RefResolutionError: if there is trouble resolving the reference
# """
# url, resolved = self.resolver.resolve(ref)
# return resolved
#
# def get_path_mapping(self, path):
# return maybe_resolve(self.doc['paths'][path], self.resolve_reference)
#
# def get_path_names(self):
# yield from self.doc['paths']
#
# def get_path(self, path):
# """
# Construct a Path object from a path string.
#
# The Path string must be declared in the API.
#
# :type path: str
# :rtype: lepo.path.Path
# """
# mapping = self.get_path_mapping(path)
# return self.path_class(api=self, path=path, mapping=mapping)
#
# def get_paths(self):
# """
# Iterate over all Path objects declared by the API.
#
# :rtype: Iterable[lepo.path.Path]
# """
# for path_name in self.get_path_names():
# yield self.get_path(path_name)
#
# @classmethod
# def from_file(cls, filename):
# """
# Construct an APIDefinition by parsing the given `filename`.
#
# If PyYAML is installed, YAML files are supported.
# JSON files are always supported.
#
# :param filename: The filename to read.
# :rtype: APIDefinition
# """
# with open(filename) as infp:
# if filename.endswith('.yaml') or filename.endswith('.yml'):
# import yaml
# data = yaml.safe_load(infp)
# else:
# import json
# data = json.load(infp)
# return cls.from_data(data)
#
# @classmethod
# def from_data(cls, data):
# version = parse_version(data)
# if version == SWAGGER_2:
# return Swagger2APIDefinition(data)
# if version == OPENAPI_3:
# return OpenAPI3APIDefinition(data)
# raise NotImplementedError('We can never get here.') # pragma: no cover
#
# @classmethod
# def from_yaml(cls, yaml_string):
# from yaml import safe_load
# return cls.from_data(safe_load(yaml_string))
#
# Path: lepo/parameter_utils.py
# def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901
# """
# :param request: HttpRequest with attached api_info
# :type request: HttpRequest
# :type view_kwargs: dict[str, object]
# :type capture_errors: bool
# :rtype: dict[str, object]
# """
# if view_kwargs is None:
# view_kwargs = {}
# params = {}
# errors = {}
# for param in request.api_info.operation.parameters:
# try:
# value = param.get_value(request, view_kwargs)
# if value is NO_VALUE:
# if param.has_default:
# params[param.name] = param.default
# elif param.required: # Required but missing
# errors[param.name] = MissingParameter(f'parameter {param.name} is required but missing')
# continue # No value, or a default was added, or an error was added.
# params[param.name] = param.cast(request.api_info.api, value)
# except (NotImplementedError, ImproperlyConfigured):
# raise
# except Exception as e:
# if not capture_errors:
# raise
# errors[param.name] = e
# if errors:
# raise ErroneousParameters(errors, params)
# return params
#
# Path: lepo_tests/tests/utils.py
# def make_request_for_operation(operation, method='GET', query_string=''):
# request = RequestFactory().generic(method=method, path=operation.path.path, QUERY_STRING=query_string)
# request.api_info = APIInfo(operation)
# return request
which might include code, classes, or functions. Output only the next line. | params = read_parameters(request, { |
Given snippet: <|code_start|> in: path
style: label
explode: true
schema:
type: array
items:
type: string
- name: thing
in: path
schema:
type: string
/object/{thing}/data{format}:
get:
parameters:
- name: format
in: path
style: label
explode: false
schema:
type: object
items:
type: string
- name: thing
in: path
schema:
type: string
''')
def test_label_parameter():
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from lepo.apidef.doc import APIDefinition
from lepo.parameter_utils import read_parameters
from lepo_tests.tests.utils import make_request_for_operation
and context:
# Path: lepo/apidef/doc.py
# class APIDefinition:
# version = None
# path_class = Path
# operation_class = None
#
# def __init__(self, doc):
# """
# Instantiate a new Lepo router.
#
# :param doc: The OpenAPI definition document.
# :type doc: dict
# """
# self.doc = doc
# self.resolver = RefResolver('', self.doc)
#
# def resolve_reference(self, ref):
# """
# Resolve a JSON Pointer object reference to the object itself.
#
# :param ref: Reference string (`#/foo/bar`, for instance)
# :return: The object, if found
# :raises jsonschema.exceptions.RefResolutionError: if there is trouble resolving the reference
# """
# url, resolved = self.resolver.resolve(ref)
# return resolved
#
# def get_path_mapping(self, path):
# return maybe_resolve(self.doc['paths'][path], self.resolve_reference)
#
# def get_path_names(self):
# yield from self.doc['paths']
#
# def get_path(self, path):
# """
# Construct a Path object from a path string.
#
# The Path string must be declared in the API.
#
# :type path: str
# :rtype: lepo.path.Path
# """
# mapping = self.get_path_mapping(path)
# return self.path_class(api=self, path=path, mapping=mapping)
#
# def get_paths(self):
# """
# Iterate over all Path objects declared by the API.
#
# :rtype: Iterable[lepo.path.Path]
# """
# for path_name in self.get_path_names():
# yield self.get_path(path_name)
#
# @classmethod
# def from_file(cls, filename):
# """
# Construct an APIDefinition by parsing the given `filename`.
#
# If PyYAML is installed, YAML files are supported.
# JSON files are always supported.
#
# :param filename: The filename to read.
# :rtype: APIDefinition
# """
# with open(filename) as infp:
# if filename.endswith('.yaml') or filename.endswith('.yml'):
# import yaml
# data = yaml.safe_load(infp)
# else:
# import json
# data = json.load(infp)
# return cls.from_data(data)
#
# @classmethod
# def from_data(cls, data):
# version = parse_version(data)
# if version == SWAGGER_2:
# return Swagger2APIDefinition(data)
# if version == OPENAPI_3:
# return OpenAPI3APIDefinition(data)
# raise NotImplementedError('We can never get here.') # pragma: no cover
#
# @classmethod
# def from_yaml(cls, yaml_string):
# from yaml import safe_load
# return cls.from_data(safe_load(yaml_string))
#
# Path: lepo/parameter_utils.py
# def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901
# """
# :param request: HttpRequest with attached api_info
# :type request: HttpRequest
# :type view_kwargs: dict[str, object]
# :type capture_errors: bool
# :rtype: dict[str, object]
# """
# if view_kwargs is None:
# view_kwargs = {}
# params = {}
# errors = {}
# for param in request.api_info.operation.parameters:
# try:
# value = param.get_value(request, view_kwargs)
# if value is NO_VALUE:
# if param.has_default:
# params[param.name] = param.default
# elif param.required: # Required but missing
# errors[param.name] = MissingParameter(f'parameter {param.name} is required but missing')
# continue # No value, or a default was added, or an error was added.
# params[param.name] = param.cast(request.api_info.api, value)
# except (NotImplementedError, ImproperlyConfigured):
# raise
# except Exception as e:
# if not capture_errors:
# raise
# errors[param.name] = e
# if errors:
# raise ErroneousParameters(errors, params)
# return params
#
# Path: lepo_tests/tests/utils.py
# def make_request_for_operation(operation, method='GET', query_string=''):
# request = RequestFactory().generic(method=method, path=operation.path.path, QUERY_STRING=query_string)
# request.api_info = APIInfo(operation)
# return request
which might include code, classes, or functions. Output only the next line. | request = make_request_for_operation(doc.get_path('/single/{thing}/data{format}').get_operation('get')) |
Given the code snippet: <|code_start|>
@doc_versions
def test_validator(doc_version):
router = get_router(f'{doc_version}/schema-refs.yaml')
with pytest.raises(RouterValidationError) as ei:
validate_router(router)
assert len(ei.value.errors) == 2
@doc_versions
def test_header_underscore(doc_version):
router = get_router(f'{doc_version}/header-underscore.yaml')
with pytest.raises(RouterValidationError) as ei:
validate_router(router)
errors = list(ei.value.flat_errors)
<|code_end|>
, generate the next line using the imports in this file:
import pytest
from lepo.excs import InvalidParameterDefinition, RouterValidationError
from lepo.validate import validate_router
from lepo_tests.tests.utils import doc_versions, get_router
and context (functions, classes, or occasionally code) from other files:
# Path: lepo/excs.py
# class InvalidParameterDefinition(ImproperlyConfigured):
# pass
#
# class RouterValidationError(Exception):
# def __init__(self, error_map):
# self.errors = error_map
# self.description = '\n'.join(f'{operation.id}: {error}' for (operation, error) in self.flat_errors)
# super().__init__(f'Router validation failed:\n{self.description}')
#
# @property
# def flat_errors(self):
# for operation, errors in sorted(self.errors.items(), key=str):
# for error in errors:
# yield (operation, error)
#
# Path: lepo/validate.py
# def validate_router(router):
# errors = defaultdict(list)
# for path in router.get_paths():
# for operation in path.get_operations():
# # Check the handler exists.
# try:
# router.get_handler(operation.id)
# except MissingHandler as e:
# errors[operation].append(e)
#
# for param in operation.parameters:
# if param.location == 'header' and '_' in param.name: # See https://github.com/akx/lepo/issues/23
# ipd = InvalidParameterDefinition(
# f'{param.name}: Header parameter names may not contain underscores (Django bug 25048)'
# )
# errors[operation].append(ipd)
#
# if errors:
# raise RouterValidationError(errors)
#
# Path: lepo_tests/tests/utils.py
# TESTS_DIR = os.path.dirname(__file__)
# DOC_VERSIONS = ['swagger2', 'openapi3']
# def get_router(fixture_name):
# def get_data_from_response(response, status=200):
# def cast_parameter_value(apidoc, parameter, value):
# def get_apidoc_from_version(version, content={}):
# def make_request_for_operation(operation, method='GET', query_string=''):
. Output only the next line. | assert any(isinstance(e[1], InvalidParameterDefinition) for e in errors) |
Given the following code snippet before the placeholder: <|code_start|>
@doc_versions
def test_validator(doc_version):
router = get_router(f'{doc_version}/schema-refs.yaml')
<|code_end|>
, predict the next line using imports from the current file:
import pytest
from lepo.excs import InvalidParameterDefinition, RouterValidationError
from lepo.validate import validate_router
from lepo_tests.tests.utils import doc_versions, get_router
and context including class names, function names, and sometimes code from other files:
# Path: lepo/excs.py
# class InvalidParameterDefinition(ImproperlyConfigured):
# pass
#
# class RouterValidationError(Exception):
# def __init__(self, error_map):
# self.errors = error_map
# self.description = '\n'.join(f'{operation.id}: {error}' for (operation, error) in self.flat_errors)
# super().__init__(f'Router validation failed:\n{self.description}')
#
# @property
# def flat_errors(self):
# for operation, errors in sorted(self.errors.items(), key=str):
# for error in errors:
# yield (operation, error)
#
# Path: lepo/validate.py
# def validate_router(router):
# errors = defaultdict(list)
# for path in router.get_paths():
# for operation in path.get_operations():
# # Check the handler exists.
# try:
# router.get_handler(operation.id)
# except MissingHandler as e:
# errors[operation].append(e)
#
# for param in operation.parameters:
# if param.location == 'header' and '_' in param.name: # See https://github.com/akx/lepo/issues/23
# ipd = InvalidParameterDefinition(
# f'{param.name}: Header parameter names may not contain underscores (Django bug 25048)'
# )
# errors[operation].append(ipd)
#
# if errors:
# raise RouterValidationError(errors)
#
# Path: lepo_tests/tests/utils.py
# TESTS_DIR = os.path.dirname(__file__)
# DOC_VERSIONS = ['swagger2', 'openapi3']
# def get_router(fixture_name):
# def get_data_from_response(response, status=200):
# def cast_parameter_value(apidoc, parameter, value):
# def get_apidoc_from_version(version, content={}):
# def make_request_for_operation(operation, method='GET', query_string=''):
. Output only the next line. | with pytest.raises(RouterValidationError) as ei: |
Continue the code snippet: <|code_start|>
@doc_versions
def test_validator(doc_version):
router = get_router(f'{doc_version}/schema-refs.yaml')
with pytest.raises(RouterValidationError) as ei:
<|code_end|>
. Use current file imports:
import pytest
from lepo.excs import InvalidParameterDefinition, RouterValidationError
from lepo.validate import validate_router
from lepo_tests.tests.utils import doc_versions, get_router
and context (classes, functions, or code) from other files:
# Path: lepo/excs.py
# class InvalidParameterDefinition(ImproperlyConfigured):
# pass
#
# class RouterValidationError(Exception):
# def __init__(self, error_map):
# self.errors = error_map
# self.description = '\n'.join(f'{operation.id}: {error}' for (operation, error) in self.flat_errors)
# super().__init__(f'Router validation failed:\n{self.description}')
#
# @property
# def flat_errors(self):
# for operation, errors in sorted(self.errors.items(), key=str):
# for error in errors:
# yield (operation, error)
#
# Path: lepo/validate.py
# def validate_router(router):
# errors = defaultdict(list)
# for path in router.get_paths():
# for operation in path.get_operations():
# # Check the handler exists.
# try:
# router.get_handler(operation.id)
# except MissingHandler as e:
# errors[operation].append(e)
#
# for param in operation.parameters:
# if param.location == 'header' and '_' in param.name: # See https://github.com/akx/lepo/issues/23
# ipd = InvalidParameterDefinition(
# f'{param.name}: Header parameter names may not contain underscores (Django bug 25048)'
# )
# errors[operation].append(ipd)
#
# if errors:
# raise RouterValidationError(errors)
#
# Path: lepo_tests/tests/utils.py
# TESTS_DIR = os.path.dirname(__file__)
# DOC_VERSIONS = ['swagger2', 'openapi3']
# def get_router(fixture_name):
# def get_data_from_response(response, status=200):
# def cast_parameter_value(apidoc, parameter, value):
# def get_apidoc_from_version(version, content={}):
# def make_request_for_operation(operation, method='GET', query_string=''):
. Output only the next line. | validate_router(router) |
Based on the snippet: <|code_start|>
DATA_EXAMPLES = [
{'spec': {'type': 'integer'}, 'input': '5041211', 'output': 5041211},
{'spec': {'format': 'long'}, 'input': '88888888888888888888888', 'output': 88888888888888888888888},
{'spec': {'format': 'float'}, 'input': '-6.3', 'output': -6.3},
{'spec': {'format': 'double'}, 'input': '-6.7', 'output': -6.7},
{'spec': {'type': 'string'}, 'input': '', 'output': ''},
{'spec': {'type': 'string'}, 'input': 'hee', 'output': 'hee'},
{'spec': {'format': 'byte'}, 'input': 'c3VyZS4=', 'output': b'sure.'},
{'spec': {'format': 'binary'}, 'input': 'v', 'output': b'v'},
{'spec': {'type': 'boolean'}, 'input': 'true', 'output': True},
{'spec': {'type': 'boolean'}, 'input': 'false', 'output': False},
{'spec': {'format': 'date'}, 'input': '2016-03-06 15:33:33', 'output': date(2016, 3, 6)},
{'spec': {'format': 'date'}, 'input': '2016-03-06', 'output': date(2016, 3, 6)},
{
'spec': {'format': 'dateTime'}, 'input': '2016-03-06 15:33:33',
'output': datetime(2016, 3, 6, 15, 33, 33, tzinfo=UTC)
},
{'spec': {'format': 'password'}, 'input': 'ffffffffffff', 'output': 'ffffffffffff'},
]
@pytest.mark.parametrize('case', DATA_EXAMPLES)
def test_data(case):
spec = case['spec']
type = spec.get('type')
format = spec.get('format')
<|code_end|>
, predict the immediate next line with the help of imports:
from collections import namedtuple
from datetime import date, datetime
from iso8601 import UTC
from lepo.apidef.doc import Swagger2APIDefinition
from lepo.parameter_utils import cast_primitive_value
from lepo_tests.tests.utils import (
cast_parameter_value,
doc_versions,
get_apidoc_from_version,
)
import pytest
and context (classes, functions, sometimes code) from other files:
# Path: lepo/apidef/doc.py
# class Swagger2APIDefinition(APIDefinition):
# version = SWAGGER_2
# operation_class = Swagger2Operation
#
# Path: lepo/parameter_utils.py
# def cast_primitive_value(type, format, value):
# if type == 'boolean':
# return (force_str(value).lower() in ('1', 'yes', 'true'))
# if type == 'integer' or format in ('integer', 'long'):
# return int(value)
# if type == 'number' or format in ('float', 'double'):
# return float(value)
# if format == 'byte': # base64 encoded characters
# return base64.b64decode(value)
# if format == 'binary': # any sequence of octets
# return force_bytes(value)
# if format == 'date': # ISO8601 date
# return iso8601.parse_date(value).date()
# if format == 'dateTime': # ISO8601 datetime
# return iso8601.parse_date(value)
# if type == 'string':
# return force_str(value)
# return value
#
# Path: lepo_tests/tests/utils.py
# TESTS_DIR = os.path.dirname(__file__)
# DOC_VERSIONS = ['swagger2', 'openapi3']
# def get_router(fixture_name):
# def get_data_from_response(response, status=200):
# def cast_parameter_value(apidoc, parameter, value):
# def get_apidoc_from_version(version, content={}):
# def make_request_for_operation(operation, method='GET', query_string=''):
. Output only the next line. | parsed = cast_primitive_value(type, format, case['input']) |
Here is a snippet: <|code_start|> {'type': 'array', 'collectionFormat': 'ssv', 'items': {'type': 'string'}},
None,
'what it do',
['what', 'it', 'do'],
),
Case(
{
'type': 'array',
'collectionFormat': 'pipes',
'items': {
'type': 'array',
'items': {
'type': 'integer',
},
}
},
None,
'1,2,3|4,5,6|7,8,9',
[[1, 2, 3], [4, 5, 6], [7, 8, 9]],
),
]
@doc_versions
@pytest.mark.parametrize('case', collection_format_cases)
def test_collection_formats(doc_version, case):
schema = (case.swagger2_schema if doc_version == 'swagger2' else case.openapi3_schema)
if schema is None:
pytest.xfail(f'{case}: no schema for {doc_version}')
apidoc = get_apidoc_from_version(doc_version)
<|code_end|>
. Write the next line using the current file imports:
from collections import namedtuple
from datetime import date, datetime
from iso8601 import UTC
from lepo.apidef.doc import Swagger2APIDefinition
from lepo.parameter_utils import cast_primitive_value
from lepo_tests.tests.utils import (
cast_parameter_value,
doc_versions,
get_apidoc_from_version,
)
import pytest
and context from other files:
# Path: lepo/apidef/doc.py
# class Swagger2APIDefinition(APIDefinition):
# version = SWAGGER_2
# operation_class = Swagger2Operation
#
# Path: lepo/parameter_utils.py
# def cast_primitive_value(type, format, value):
# if type == 'boolean':
# return (force_str(value).lower() in ('1', 'yes', 'true'))
# if type == 'integer' or format in ('integer', 'long'):
# return int(value)
# if type == 'number' or format in ('float', 'double'):
# return float(value)
# if format == 'byte': # base64 encoded characters
# return base64.b64decode(value)
# if format == 'binary': # any sequence of octets
# return force_bytes(value)
# if format == 'date': # ISO8601 date
# return iso8601.parse_date(value).date()
# if format == 'dateTime': # ISO8601 datetime
# return iso8601.parse_date(value)
# if type == 'string':
# return force_str(value)
# return value
#
# Path: lepo_tests/tests/utils.py
# TESTS_DIR = os.path.dirname(__file__)
# DOC_VERSIONS = ['swagger2', 'openapi3']
# def get_router(fixture_name):
# def get_data_from_response(response, status=200):
# def cast_parameter_value(apidoc, parameter, value):
# def get_apidoc_from_version(version, content={}):
# def make_request_for_operation(operation, method='GET', query_string=''):
, which may include functions, classes, or code. Output only the next line. | assert cast_parameter_value(apidoc, schema, case.input) == case.expected |
Here is a snippet: <|code_start|> Case(
{'type': 'array', 'collectionFormat': 'tsv', 'items': {'type': 'boolean'}},
None, # TSV does not exist in OpenAPI 3
'true\ttrue\tfalse',
[True, True, False],
),
Case(
{'type': 'array', 'collectionFormat': 'ssv', 'items': {'type': 'string'}},
None,
'what it do',
['what', 'it', 'do'],
),
Case(
{
'type': 'array',
'collectionFormat': 'pipes',
'items': {
'type': 'array',
'items': {
'type': 'integer',
},
}
},
None,
'1,2,3|4,5,6|7,8,9',
[[1, 2, 3], [4, 5, 6], [7, 8, 9]],
),
]
<|code_end|>
. Write the next line using the current file imports:
from collections import namedtuple
from datetime import date, datetime
from iso8601 import UTC
from lepo.apidef.doc import Swagger2APIDefinition
from lepo.parameter_utils import cast_primitive_value
from lepo_tests.tests.utils import (
cast_parameter_value,
doc_versions,
get_apidoc_from_version,
)
import pytest
and context from other files:
# Path: lepo/apidef/doc.py
# class Swagger2APIDefinition(APIDefinition):
# version = SWAGGER_2
# operation_class = Swagger2Operation
#
# Path: lepo/parameter_utils.py
# def cast_primitive_value(type, format, value):
# if type == 'boolean':
# return (force_str(value).lower() in ('1', 'yes', 'true'))
# if type == 'integer' or format in ('integer', 'long'):
# return int(value)
# if type == 'number' or format in ('float', 'double'):
# return float(value)
# if format == 'byte': # base64 encoded characters
# return base64.b64decode(value)
# if format == 'binary': # any sequence of octets
# return force_bytes(value)
# if format == 'date': # ISO8601 date
# return iso8601.parse_date(value).date()
# if format == 'dateTime': # ISO8601 datetime
# return iso8601.parse_date(value)
# if type == 'string':
# return force_str(value)
# return value
#
# Path: lepo_tests/tests/utils.py
# TESTS_DIR = os.path.dirname(__file__)
# DOC_VERSIONS = ['swagger2', 'openapi3']
# def get_router(fixture_name):
# def get_data_from_response(response, status=200):
# def cast_parameter_value(apidoc, parameter, value):
# def get_apidoc_from_version(version, content={}):
# def make_request_for_operation(operation, method='GET', query_string=''):
, which may include functions, classes, or code. Output only the next line. | @doc_versions |
Predict the next line for this snippet: <|code_start|> Case(
{'type': 'array', 'collectionFormat': 'ssv', 'items': {'type': 'string'}},
None,
'what it do',
['what', 'it', 'do'],
),
Case(
{
'type': 'array',
'collectionFormat': 'pipes',
'items': {
'type': 'array',
'items': {
'type': 'integer',
},
}
},
None,
'1,2,3|4,5,6|7,8,9',
[[1, 2, 3], [4, 5, 6], [7, 8, 9]],
),
]
@doc_versions
@pytest.mark.parametrize('case', collection_format_cases)
def test_collection_formats(doc_version, case):
schema = (case.swagger2_schema if doc_version == 'swagger2' else case.openapi3_schema)
if schema is None:
pytest.xfail(f'{case}: no schema for {doc_version}')
<|code_end|>
with the help of current file imports:
from collections import namedtuple
from datetime import date, datetime
from iso8601 import UTC
from lepo.apidef.doc import Swagger2APIDefinition
from lepo.parameter_utils import cast_primitive_value
from lepo_tests.tests.utils import (
cast_parameter_value,
doc_versions,
get_apidoc_from_version,
)
import pytest
and context from other files:
# Path: lepo/apidef/doc.py
# class Swagger2APIDefinition(APIDefinition):
# version = SWAGGER_2
# operation_class = Swagger2Operation
#
# Path: lepo/parameter_utils.py
# def cast_primitive_value(type, format, value):
# if type == 'boolean':
# return (force_str(value).lower() in ('1', 'yes', 'true'))
# if type == 'integer' or format in ('integer', 'long'):
# return int(value)
# if type == 'number' or format in ('float', 'double'):
# return float(value)
# if format == 'byte': # base64 encoded characters
# return base64.b64decode(value)
# if format == 'binary': # any sequence of octets
# return force_bytes(value)
# if format == 'date': # ISO8601 date
# return iso8601.parse_date(value).date()
# if format == 'dateTime': # ISO8601 datetime
# return iso8601.parse_date(value)
# if type == 'string':
# return force_str(value)
# return value
#
# Path: lepo_tests/tests/utils.py
# TESTS_DIR = os.path.dirname(__file__)
# DOC_VERSIONS = ['swagger2', 'openapi3']
# def get_router(fixture_name):
# def get_data_from_response(response, status=200):
# def cast_parameter_value(apidoc, parameter, value):
# def get_apidoc_from_version(version, content={}):
# def make_request_for_operation(operation, method='GET', query_string=''):
, which may contain function names, class names, or code. Output only the next line. | apidoc = get_apidoc_from_version(doc_version) |
Using the snippet: <|code_start|>
COLLECTION_FORMAT_SPLITTERS = {
'csv': comma_split,
'ssv': space_split,
'tsv': tab_split,
'pipes': pipe_split,
}
OPENAPI_JSONSCHEMA_VALIDATION_KEYS = (
'maximum', 'exclusiveMaximum',
'minimum', 'exclusiveMinimum',
'maxLength', 'minLength',
'pattern',
'maxItems', 'minItems',
'uniqueItems',
'enum', 'multipleOf',
)
<|code_end|>
, determine the next line of code. You have imports:
import jsonschema
from lepo.apidef.parameter.base import NO_VALUE, BaseParameter, BaseTopParameter
from lepo.apidef.parameter.utils import (
comma_split,
pipe_split,
read_body,
space_split,
tab_split,
validate_schema,
)
from lepo.excs import InvalidBodyFormat
from lepo.parameter_utils import cast_primitive_value
from lepo.utils import maybe_resolve
and context (class names, function names, or code) available:
# Path: lepo/apidef/parameter/base.py
# NO_VALUE = object()
#
# class BaseParameter:
# def __init__(self, data, api=None):
# self.data = data
# self.api = api
#
# def __repr__(self):
# return f'<{self.__class__.__name__} ({self.data!r})>'
#
# @property
# def location(self):
# return self.data['in']
#
# @property
# def required(self):
# return bool(self.data.get('required'))
#
# @property
# def items(self):
# return self.data.get('items')
#
# def cast(self, api, value): # pragma: no cover
# raise NotImplementedError('Subclasses must implement cast')
#
# def get_value(self, request, view_kwargs): # pragma: no cover
# """
# :type request: WSGIRequest
# :type view_kwargs: dict
# """
# raise NotImplementedError('Subclasses must implement get_value')
#
# class BaseTopParameter(BaseParameter):
# """
# Top-level Parameter, such as in an operation
# """
#
# def __init__(self, data, api=None, operation=None):
# super().__init__(data, api=api)
# self.operation = operation
#
# @property
# def name(self):
# return self.data['name']
#
# @property
# def in_body(self):
# return self.location in ('formData', 'body')
#
# def get_value(self, request, view_kwargs):
# raise InvalidParameterDefinition(f'unsupported `in` value {self.location!r} in {self!r}') # pragma: no cover
#
# Path: lepo/apidef/parameter/utils.py
# def comma_split(value):
# return force_str(value).split(',')
#
# def pipe_split(value):
# return force_str(value).split('|')
#
# def read_body(request, parameter=None):
# if parameter:
# if parameter.type == 'binary':
# return request.body.read()
# try:
# if request.content_type == 'multipart/form-data':
# # TODO: this definitely doesn't handle multiple values for the same key correctly
# data = dict()
# data.update(request.POST.items())
# data.update(request.FILES.items())
# return data
# decoder = get_decoder(request.content_type)
# if decoder:
# return decoder(request.body, encoding=request.content_params.get('charset', 'UTF-8'))
# except Exception as exc:
# raise InvalidBodyContent(f'Unable to parse this body as {request.content_type}') from exc
# raise NotImplementedError(f'No idea how to parse content-type {request.content_type}') # pragma: no cover
#
# def space_split(value):
# return force_str(value).split(' ')
#
# def tab_split(value):
# return force_str(value).split('\t')
#
# def validate_schema(schema, api, value):
# schema = maybe_resolve(schema, resolve=api.resolve_reference)
# jsonschema.validate(
# value,
# schema,
# cls=LepoDraft4Validator,
# resolver=api.resolver,
# )
# if 'discriminator' in schema: # Swagger/OpenAPI 3 Polymorphism support
# discriminator = schema['discriminator']
# if isinstance(discriminator, dict): # OpenAPI 3
# type = value[discriminator['propertyName']]
# if 'mapping' in discriminator:
# actual_type = discriminator['mapping'][type]
# else:
# actual_type = f'#/components/schemas/{type}'
# else:
# type = value[discriminator]
# actual_type = f'#/definitions/{type}'
# schema = api.resolve_reference(actual_type)
# jsonschema.validate(
# value,
# schema,
# cls=LepoDraft4Validator,
# resolver=api.resolver,
# )
# return value
#
# Path: lepo/excs.py
# class InvalidBodyFormat(ValueError):
# pass
#
# Path: lepo/parameter_utils.py
# def cast_primitive_value(type, format, value):
# if type == 'boolean':
# return (force_str(value).lower() in ('1', 'yes', 'true'))
# if type == 'integer' or format in ('integer', 'long'):
# return int(value)
# if type == 'number' or format in ('float', 'double'):
# return float(value)
# if format == 'byte': # base64 encoded characters
# return base64.b64decode(value)
# if format == 'binary': # any sequence of octets
# return force_bytes(value)
# if format == 'date': # ISO8601 date
# return iso8601.parse_date(value).date()
# if format == 'dateTime': # ISO8601 datetime
# return iso8601.parse_date(value)
# if type == 'string':
# return force_str(value)
# return value
#
# Path: lepo/utils.py
# def maybe_resolve(object, resolve):
# """
# Call `resolve` on the `object`'s `$ref` value if it has one.
#
# :param object: An object.
# :param resolve: A resolving function.
# :return: An object, or some other object! :sparkles:
# """
# if isinstance(object, dict) and object.get('$ref'):
# return resolve(object['$ref'])
# return object
. Output only the next line. | class Swagger2BaseParameter(BaseParameter): |
Continue the code snippet: <|code_start|>
COLLECTION_FORMAT_SPLITTERS = {
'csv': comma_split,
'ssv': space_split,
'tsv': tab_split,
<|code_end|>
. Use current file imports:
import jsonschema
from lepo.apidef.parameter.base import NO_VALUE, BaseParameter, BaseTopParameter
from lepo.apidef.parameter.utils import (
comma_split,
pipe_split,
read_body,
space_split,
tab_split,
validate_schema,
)
from lepo.excs import InvalidBodyFormat
from lepo.parameter_utils import cast_primitive_value
from lepo.utils import maybe_resolve
and context (classes, functions, or code) from other files:
# Path: lepo/apidef/parameter/base.py
# NO_VALUE = object()
#
# class BaseParameter:
# def __init__(self, data, api=None):
# self.data = data
# self.api = api
#
# def __repr__(self):
# return f'<{self.__class__.__name__} ({self.data!r})>'
#
# @property
# def location(self):
# return self.data['in']
#
# @property
# def required(self):
# return bool(self.data.get('required'))
#
# @property
# def items(self):
# return self.data.get('items')
#
# def cast(self, api, value): # pragma: no cover
# raise NotImplementedError('Subclasses must implement cast')
#
# def get_value(self, request, view_kwargs): # pragma: no cover
# """
# :type request: WSGIRequest
# :type view_kwargs: dict
# """
# raise NotImplementedError('Subclasses must implement get_value')
#
# class BaseTopParameter(BaseParameter):
# """
# Top-level Parameter, such as in an operation
# """
#
# def __init__(self, data, api=None, operation=None):
# super().__init__(data, api=api)
# self.operation = operation
#
# @property
# def name(self):
# return self.data['name']
#
# @property
# def in_body(self):
# return self.location in ('formData', 'body')
#
# def get_value(self, request, view_kwargs):
# raise InvalidParameterDefinition(f'unsupported `in` value {self.location!r} in {self!r}') # pragma: no cover
#
# Path: lepo/apidef/parameter/utils.py
# def comma_split(value):
# return force_str(value).split(',')
#
# def pipe_split(value):
# return force_str(value).split('|')
#
# def read_body(request, parameter=None):
# if parameter:
# if parameter.type == 'binary':
# return request.body.read()
# try:
# if request.content_type == 'multipart/form-data':
# # TODO: this definitely doesn't handle multiple values for the same key correctly
# data = dict()
# data.update(request.POST.items())
# data.update(request.FILES.items())
# return data
# decoder = get_decoder(request.content_type)
# if decoder:
# return decoder(request.body, encoding=request.content_params.get('charset', 'UTF-8'))
# except Exception as exc:
# raise InvalidBodyContent(f'Unable to parse this body as {request.content_type}') from exc
# raise NotImplementedError(f'No idea how to parse content-type {request.content_type}') # pragma: no cover
#
# def space_split(value):
# return force_str(value).split(' ')
#
# def tab_split(value):
# return force_str(value).split('\t')
#
# def validate_schema(schema, api, value):
# schema = maybe_resolve(schema, resolve=api.resolve_reference)
# jsonschema.validate(
# value,
# schema,
# cls=LepoDraft4Validator,
# resolver=api.resolver,
# )
# if 'discriminator' in schema: # Swagger/OpenAPI 3 Polymorphism support
# discriminator = schema['discriminator']
# if isinstance(discriminator, dict): # OpenAPI 3
# type = value[discriminator['propertyName']]
# if 'mapping' in discriminator:
# actual_type = discriminator['mapping'][type]
# else:
# actual_type = f'#/components/schemas/{type}'
# else:
# type = value[discriminator]
# actual_type = f'#/definitions/{type}'
# schema = api.resolve_reference(actual_type)
# jsonschema.validate(
# value,
# schema,
# cls=LepoDraft4Validator,
# resolver=api.resolver,
# )
# return value
#
# Path: lepo/excs.py
# class InvalidBodyFormat(ValueError):
# pass
#
# Path: lepo/parameter_utils.py
# def cast_primitive_value(type, format, value):
# if type == 'boolean':
# return (force_str(value).lower() in ('1', 'yes', 'true'))
# if type == 'integer' or format in ('integer', 'long'):
# return int(value)
# if type == 'number' or format in ('float', 'double'):
# return float(value)
# if format == 'byte': # base64 encoded characters
# return base64.b64decode(value)
# if format == 'binary': # any sequence of octets
# return force_bytes(value)
# if format == 'date': # ISO8601 date
# return iso8601.parse_date(value).date()
# if format == 'dateTime': # ISO8601 datetime
# return iso8601.parse_date(value)
# if type == 'string':
# return force_str(value)
# return value
#
# Path: lepo/utils.py
# def maybe_resolve(object, resolve):
# """
# Call `resolve` on the `object`'s `$ref` value if it has one.
#
# :param object: An object.
# :param resolve: A resolving function.
# :return: An object, or some other object! :sparkles:
# """
# if isinstance(object, dict) and object.get('$ref'):
# return resolve(object['$ref'])
# return object
. Output only the next line. | 'pipes': pipe_split, |
Given the code snippet: <|code_start|>
COLLECTION_FORMAT_SPLITTERS = {
'csv': comma_split,
'ssv': space_split,
<|code_end|>
, generate the next line using the imports in this file:
import jsonschema
from lepo.apidef.parameter.base import NO_VALUE, BaseParameter, BaseTopParameter
from lepo.apidef.parameter.utils import (
comma_split,
pipe_split,
read_body,
space_split,
tab_split,
validate_schema,
)
from lepo.excs import InvalidBodyFormat
from lepo.parameter_utils import cast_primitive_value
from lepo.utils import maybe_resolve
and context (functions, classes, or occasionally code) from other files:
# Path: lepo/apidef/parameter/base.py
# NO_VALUE = object()
#
# class BaseParameter:
# def __init__(self, data, api=None):
# self.data = data
# self.api = api
#
# def __repr__(self):
# return f'<{self.__class__.__name__} ({self.data!r})>'
#
# @property
# def location(self):
# return self.data['in']
#
# @property
# def required(self):
# return bool(self.data.get('required'))
#
# @property
# def items(self):
# return self.data.get('items')
#
# def cast(self, api, value): # pragma: no cover
# raise NotImplementedError('Subclasses must implement cast')
#
# def get_value(self, request, view_kwargs): # pragma: no cover
# """
# :type request: WSGIRequest
# :type view_kwargs: dict
# """
# raise NotImplementedError('Subclasses must implement get_value')
#
# class BaseTopParameter(BaseParameter):
# """
# Top-level Parameter, such as in an operation
# """
#
# def __init__(self, data, api=None, operation=None):
# super().__init__(data, api=api)
# self.operation = operation
#
# @property
# def name(self):
# return self.data['name']
#
# @property
# def in_body(self):
# return self.location in ('formData', 'body')
#
# def get_value(self, request, view_kwargs):
# raise InvalidParameterDefinition(f'unsupported `in` value {self.location!r} in {self!r}') # pragma: no cover
#
# Path: lepo/apidef/parameter/utils.py
# def comma_split(value):
# return force_str(value).split(',')
#
# def pipe_split(value):
# return force_str(value).split('|')
#
# def read_body(request, parameter=None):
# if parameter:
# if parameter.type == 'binary':
# return request.body.read()
# try:
# if request.content_type == 'multipart/form-data':
# # TODO: this definitely doesn't handle multiple values for the same key correctly
# data = dict()
# data.update(request.POST.items())
# data.update(request.FILES.items())
# return data
# decoder = get_decoder(request.content_type)
# if decoder:
# return decoder(request.body, encoding=request.content_params.get('charset', 'UTF-8'))
# except Exception as exc:
# raise InvalidBodyContent(f'Unable to parse this body as {request.content_type}') from exc
# raise NotImplementedError(f'No idea how to parse content-type {request.content_type}') # pragma: no cover
#
# def space_split(value):
# return force_str(value).split(' ')
#
# def tab_split(value):
# return force_str(value).split('\t')
#
# def validate_schema(schema, api, value):
# schema = maybe_resolve(schema, resolve=api.resolve_reference)
# jsonschema.validate(
# value,
# schema,
# cls=LepoDraft4Validator,
# resolver=api.resolver,
# )
# if 'discriminator' in schema: # Swagger/OpenAPI 3 Polymorphism support
# discriminator = schema['discriminator']
# if isinstance(discriminator, dict): # OpenAPI 3
# type = value[discriminator['propertyName']]
# if 'mapping' in discriminator:
# actual_type = discriminator['mapping'][type]
# else:
# actual_type = f'#/components/schemas/{type}'
# else:
# type = value[discriminator]
# actual_type = f'#/definitions/{type}'
# schema = api.resolve_reference(actual_type)
# jsonschema.validate(
# value,
# schema,
# cls=LepoDraft4Validator,
# resolver=api.resolver,
# )
# return value
#
# Path: lepo/excs.py
# class InvalidBodyFormat(ValueError):
# pass
#
# Path: lepo/parameter_utils.py
# def cast_primitive_value(type, format, value):
# if type == 'boolean':
# return (force_str(value).lower() in ('1', 'yes', 'true'))
# if type == 'integer' or format in ('integer', 'long'):
# return int(value)
# if type == 'number' or format in ('float', 'double'):
# return float(value)
# if format == 'byte': # base64 encoded characters
# return base64.b64decode(value)
# if format == 'binary': # any sequence of octets
# return force_bytes(value)
# if format == 'date': # ISO8601 date
# return iso8601.parse_date(value).date()
# if format == 'dateTime': # ISO8601 datetime
# return iso8601.parse_date(value)
# if type == 'string':
# return force_str(value)
# return value
#
# Path: lepo/utils.py
# def maybe_resolve(object, resolve):
# """
# Call `resolve` on the `object`'s `$ref` value if it has one.
#
# :param object: An object.
# :param resolve: A resolving function.
# :return: An object, or some other object! :sparkles:
# """
# if isinstance(object, dict) and object.get('$ref'):
# return resolve(object['$ref'])
# return object
. Output only the next line. | 'tsv': tab_split, |
Continue the code snippet: <|code_start|>
CASCADE_DOC = """
swagger: "2.0"
consumes:
- application/json
produces:
- application/x-happiness
paths:
/cows:
consumes:
- application/x-grass
produces:
- application/x-moo
post:
operationId: tip
delete:
operationId: remoove
produces:
- application/x-no-more-moo
/hello:
get:
operationId: greet
"""
def test_cascade():
<|code_end|>
. Use current file imports:
import yaml
from lepo.apidef.doc import APIDefinition
and context (classes, functions, or code) from other files:
# Path: lepo/apidef/doc.py
# class APIDefinition:
# version = None
# path_class = Path
# operation_class = None
#
# def __init__(self, doc):
# """
# Instantiate a new Lepo router.
#
# :param doc: The OpenAPI definition document.
# :type doc: dict
# """
# self.doc = doc
# self.resolver = RefResolver('', self.doc)
#
# def resolve_reference(self, ref):
# """
# Resolve a JSON Pointer object reference to the object itself.
#
# :param ref: Reference string (`#/foo/bar`, for instance)
# :return: The object, if found
# :raises jsonschema.exceptions.RefResolutionError: if there is trouble resolving the reference
# """
# url, resolved = self.resolver.resolve(ref)
# return resolved
#
# def get_path_mapping(self, path):
# return maybe_resolve(self.doc['paths'][path], self.resolve_reference)
#
# def get_path_names(self):
# yield from self.doc['paths']
#
# def get_path(self, path):
# """
# Construct a Path object from a path string.
#
# The Path string must be declared in the API.
#
# :type path: str
# :rtype: lepo.path.Path
# """
# mapping = self.get_path_mapping(path)
# return self.path_class(api=self, path=path, mapping=mapping)
#
# def get_paths(self):
# """
# Iterate over all Path objects declared by the API.
#
# :rtype: Iterable[lepo.path.Path]
# """
# for path_name in self.get_path_names():
# yield self.get_path(path_name)
#
# @classmethod
# def from_file(cls, filename):
# """
# Construct an APIDefinition by parsing the given `filename`.
#
# If PyYAML is installed, YAML files are supported.
# JSON files are always supported.
#
# :param filename: The filename to read.
# :rtype: APIDefinition
# """
# with open(filename) as infp:
# if filename.endswith('.yaml') or filename.endswith('.yml'):
# import yaml
# data = yaml.safe_load(infp)
# else:
# import json
# data = json.load(infp)
# return cls.from_data(data)
#
# @classmethod
# def from_data(cls, data):
# version = parse_version(data)
# if version == SWAGGER_2:
# return Swagger2APIDefinition(data)
# if version == OPENAPI_3:
# return OpenAPI3APIDefinition(data)
# raise NotImplementedError('We can never get here.') # pragma: no cover
#
# @classmethod
# def from_yaml(cls, yaml_string):
# from yaml import safe_load
# return cls.from_data(safe_load(yaml_string))
. Output only the next line. | router = APIDefinition.from_data(yaml.safe_load(CASCADE_DOC)) |
Here is a snippet: <|code_start|>
def validate_router(router):
errors = defaultdict(list)
for path in router.get_paths():
for operation in path.get_operations():
# Check the handler exists.
try:
router.get_handler(operation.id)
except MissingHandler as e:
errors[operation].append(e)
for param in operation.parameters:
if param.location == 'header' and '_' in param.name: # See https://github.com/akx/lepo/issues/23
<|code_end|>
. Write the next line using the current file imports:
from collections import defaultdict
from lepo.excs import InvalidParameterDefinition, MissingHandler, RouterValidationError
and context from other files:
# Path: lepo/excs.py
# class InvalidParameterDefinition(ImproperlyConfigured):
# pass
#
# class MissingHandler(ValueError):
# pass
#
# class RouterValidationError(Exception):
# def __init__(self, error_map):
# self.errors = error_map
# self.description = '\n'.join(f'{operation.id}: {error}' for (operation, error) in self.flat_errors)
# super().__init__(f'Router validation failed:\n{self.description}')
#
# @property
# def flat_errors(self):
# for operation, errors in sorted(self.errors.items(), key=str):
# for error in errors:
# yield (operation, error)
, which may include functions, classes, or code. Output only the next line. | ipd = InvalidParameterDefinition( |
Given snippet: <|code_start|>
def validate_router(router):
errors = defaultdict(list)
for path in router.get_paths():
for operation in path.get_operations():
# Check the handler exists.
try:
router.get_handler(operation.id)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from collections import defaultdict
from lepo.excs import InvalidParameterDefinition, MissingHandler, RouterValidationError
and context:
# Path: lepo/excs.py
# class InvalidParameterDefinition(ImproperlyConfigured):
# pass
#
# class MissingHandler(ValueError):
# pass
#
# class RouterValidationError(Exception):
# def __init__(self, error_map):
# self.errors = error_map
# self.description = '\n'.join(f'{operation.id}: {error}' for (operation, error) in self.flat_errors)
# super().__init__(f'Router validation failed:\n{self.description}')
#
# @property
# def flat_errors(self):
# for operation, errors in sorted(self.errors.items(), key=str):
# for error in errors:
# yield (operation, error)
which might include code, classes, or functions. Output only the next line. | except MissingHandler as e: |
Given the following code snippet before the placeholder: <|code_start|>
def validate_router(router):
errors = defaultdict(list)
for path in router.get_paths():
for operation in path.get_operations():
# Check the handler exists.
try:
router.get_handler(operation.id)
except MissingHandler as e:
errors[operation].append(e)
for param in operation.parameters:
if param.location == 'header' and '_' in param.name: # See https://github.com/akx/lepo/issues/23
ipd = InvalidParameterDefinition(
f'{param.name}: Header parameter names may not contain underscores (Django bug 25048)'
)
errors[operation].append(ipd)
if errors:
<|code_end|>
, predict the next line using imports from the current file:
from collections import defaultdict
from lepo.excs import InvalidParameterDefinition, MissingHandler, RouterValidationError
and context including class names, function names, and sometimes code from other files:
# Path: lepo/excs.py
# class InvalidParameterDefinition(ImproperlyConfigured):
# pass
#
# class MissingHandler(ValueError):
# pass
#
# class RouterValidationError(Exception):
# def __init__(self, error_map):
# self.errors = error_map
# self.description = '\n'.join(f'{operation.id}: {error}' for (operation, error) in self.flat_errors)
# super().__init__(f'Router validation failed:\n{self.description}')
#
# @property
# def flat_errors(self):
# for operation, errors in sorted(self.errors.items(), key=str):
# for error in errors:
# yield (operation, error)
. Output only the next line. | raise RouterValidationError(errors) |
Predict the next line for this snippet: <|code_start|>
JSONIFY_DOC = """
swagger: "2.0"
consumes:
- text/plain
produces:
- application/json
paths:
/jsonify:
post:
parameters:
- name: text
in: body
"""
# TODO: add OpenAPI 3 version of this test
def test_text_body_type(rf):
apidoc = APIDefinition.from_data(yaml.safe_load(JSONIFY_DOC))
operation = apidoc.get_path('/jsonify').get_operation('post')
request = rf.post('/jsonify', 'henlo worl', content_type='text/plain')
<|code_end|>
with the help of current file imports:
import yaml
from lepo.api_info import APIInfo
from lepo.apidef.doc import APIDefinition
from lepo.parameter_utils import read_parameters
and context from other files:
# Path: lepo/api_info.py
# class APIInfo:
# def __init__(self, operation, router=None):
# """
# :type operation: lepo.operation.Operation
# :type router: lepo.router.Router
# """
# self.api = operation.api
# self.path = operation.path
# self.operation = operation
# self.router = router
#
# Path: lepo/apidef/doc.py
# class APIDefinition:
# version = None
# path_class = Path
# operation_class = None
#
# def __init__(self, doc):
# """
# Instantiate a new Lepo router.
#
# :param doc: The OpenAPI definition document.
# :type doc: dict
# """
# self.doc = doc
# self.resolver = RefResolver('', self.doc)
#
# def resolve_reference(self, ref):
# """
# Resolve a JSON Pointer object reference to the object itself.
#
# :param ref: Reference string (`#/foo/bar`, for instance)
# :return: The object, if found
# :raises jsonschema.exceptions.RefResolutionError: if there is trouble resolving the reference
# """
# url, resolved = self.resolver.resolve(ref)
# return resolved
#
# def get_path_mapping(self, path):
# return maybe_resolve(self.doc['paths'][path], self.resolve_reference)
#
# def get_path_names(self):
# yield from self.doc['paths']
#
# def get_path(self, path):
# """
# Construct a Path object from a path string.
#
# The Path string must be declared in the API.
#
# :type path: str
# :rtype: lepo.path.Path
# """
# mapping = self.get_path_mapping(path)
# return self.path_class(api=self, path=path, mapping=mapping)
#
# def get_paths(self):
# """
# Iterate over all Path objects declared by the API.
#
# :rtype: Iterable[lepo.path.Path]
# """
# for path_name in self.get_path_names():
# yield self.get_path(path_name)
#
# @classmethod
# def from_file(cls, filename):
# """
# Construct an APIDefinition by parsing the given `filename`.
#
# If PyYAML is installed, YAML files are supported.
# JSON files are always supported.
#
# :param filename: The filename to read.
# :rtype: APIDefinition
# """
# with open(filename) as infp:
# if filename.endswith('.yaml') or filename.endswith('.yml'):
# import yaml
# data = yaml.safe_load(infp)
# else:
# import json
# data = json.load(infp)
# return cls.from_data(data)
#
# @classmethod
# def from_data(cls, data):
# version = parse_version(data)
# if version == SWAGGER_2:
# return Swagger2APIDefinition(data)
# if version == OPENAPI_3:
# return OpenAPI3APIDefinition(data)
# raise NotImplementedError('We can never get here.') # pragma: no cover
#
# @classmethod
# def from_yaml(cls, yaml_string):
# from yaml import safe_load
# return cls.from_data(safe_load(yaml_string))
#
# Path: lepo/parameter_utils.py
# def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901
# """
# :param request: HttpRequest with attached api_info
# :type request: HttpRequest
# :type view_kwargs: dict[str, object]
# :type capture_errors: bool
# :rtype: dict[str, object]
# """
# if view_kwargs is None:
# view_kwargs = {}
# params = {}
# errors = {}
# for param in request.api_info.operation.parameters:
# try:
# value = param.get_value(request, view_kwargs)
# if value is NO_VALUE:
# if param.has_default:
# params[param.name] = param.default
# elif param.required: # Required but missing
# errors[param.name] = MissingParameter(f'parameter {param.name} is required but missing')
# continue # No value, or a default was added, or an error was added.
# params[param.name] = param.cast(request.api_info.api, value)
# except (NotImplementedError, ImproperlyConfigured):
# raise
# except Exception as e:
# if not capture_errors:
# raise
# errors[param.name] = e
# if errors:
# raise ErroneousParameters(errors, params)
# return params
, which may contain function names, class names, or code. Output only the next line. | request.api_info = APIInfo(operation=operation) |
Based on the snippet: <|code_start|>
JSONIFY_DOC = """
swagger: "2.0"
consumes:
- text/plain
produces:
- application/json
paths:
/jsonify:
post:
parameters:
- name: text
in: body
"""
# TODO: add OpenAPI 3 version of this test
def test_text_body_type(rf):
<|code_end|>
, predict the immediate next line with the help of imports:
import yaml
from lepo.api_info import APIInfo
from lepo.apidef.doc import APIDefinition
from lepo.parameter_utils import read_parameters
and context (classes, functions, sometimes code) from other files:
# Path: lepo/api_info.py
# class APIInfo:
# def __init__(self, operation, router=None):
# """
# :type operation: lepo.operation.Operation
# :type router: lepo.router.Router
# """
# self.api = operation.api
# self.path = operation.path
# self.operation = operation
# self.router = router
#
# Path: lepo/apidef/doc.py
# class APIDefinition:
# version = None
# path_class = Path
# operation_class = None
#
# def __init__(self, doc):
# """
# Instantiate a new Lepo router.
#
# :param doc: The OpenAPI definition document.
# :type doc: dict
# """
# self.doc = doc
# self.resolver = RefResolver('', self.doc)
#
# def resolve_reference(self, ref):
# """
# Resolve a JSON Pointer object reference to the object itself.
#
# :param ref: Reference string (`#/foo/bar`, for instance)
# :return: The object, if found
# :raises jsonschema.exceptions.RefResolutionError: if there is trouble resolving the reference
# """
# url, resolved = self.resolver.resolve(ref)
# return resolved
#
# def get_path_mapping(self, path):
# return maybe_resolve(self.doc['paths'][path], self.resolve_reference)
#
# def get_path_names(self):
# yield from self.doc['paths']
#
# def get_path(self, path):
# """
# Construct a Path object from a path string.
#
# The Path string must be declared in the API.
#
# :type path: str
# :rtype: lepo.path.Path
# """
# mapping = self.get_path_mapping(path)
# return self.path_class(api=self, path=path, mapping=mapping)
#
# def get_paths(self):
# """
# Iterate over all Path objects declared by the API.
#
# :rtype: Iterable[lepo.path.Path]
# """
# for path_name in self.get_path_names():
# yield self.get_path(path_name)
#
# @classmethod
# def from_file(cls, filename):
# """
# Construct an APIDefinition by parsing the given `filename`.
#
# If PyYAML is installed, YAML files are supported.
# JSON files are always supported.
#
# :param filename: The filename to read.
# :rtype: APIDefinition
# """
# with open(filename) as infp:
# if filename.endswith('.yaml') or filename.endswith('.yml'):
# import yaml
# data = yaml.safe_load(infp)
# else:
# import json
# data = json.load(infp)
# return cls.from_data(data)
#
# @classmethod
# def from_data(cls, data):
# version = parse_version(data)
# if version == SWAGGER_2:
# return Swagger2APIDefinition(data)
# if version == OPENAPI_3:
# return OpenAPI3APIDefinition(data)
# raise NotImplementedError('We can never get here.') # pragma: no cover
#
# @classmethod
# def from_yaml(cls, yaml_string):
# from yaml import safe_load
# return cls.from_data(safe_load(yaml_string))
#
# Path: lepo/parameter_utils.py
# def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901
# """
# :param request: HttpRequest with attached api_info
# :type request: HttpRequest
# :type view_kwargs: dict[str, object]
# :type capture_errors: bool
# :rtype: dict[str, object]
# """
# if view_kwargs is None:
# view_kwargs = {}
# params = {}
# errors = {}
# for param in request.api_info.operation.parameters:
# try:
# value = param.get_value(request, view_kwargs)
# if value is NO_VALUE:
# if param.has_default:
# params[param.name] = param.default
# elif param.required: # Required but missing
# errors[param.name] = MissingParameter(f'parameter {param.name} is required but missing')
# continue # No value, or a default was added, or an error was added.
# params[param.name] = param.cast(request.api_info.api, value)
# except (NotImplementedError, ImproperlyConfigured):
# raise
# except Exception as e:
# if not capture_errors:
# raise
# errors[param.name] = e
# if errors:
# raise ErroneousParameters(errors, params)
# return params
. Output only the next line. | apidoc = APIDefinition.from_data(yaml.safe_load(JSONIFY_DOC)) |
Next line prediction: <|code_start|>
JSONIFY_DOC = """
swagger: "2.0"
consumes:
- text/plain
produces:
- application/json
paths:
/jsonify:
post:
parameters:
- name: text
in: body
"""
# TODO: add OpenAPI 3 version of this test
def test_text_body_type(rf):
apidoc = APIDefinition.from_data(yaml.safe_load(JSONIFY_DOC))
operation = apidoc.get_path('/jsonify').get_operation('post')
request = rf.post('/jsonify', 'henlo worl', content_type='text/plain')
request.api_info = APIInfo(operation=operation)
<|code_end|>
. Use current file imports:
(import yaml
from lepo.api_info import APIInfo
from lepo.apidef.doc import APIDefinition
from lepo.parameter_utils import read_parameters)
and context including class names, function names, or small code snippets from other files:
# Path: lepo/api_info.py
# class APIInfo:
# def __init__(self, operation, router=None):
# """
# :type operation: lepo.operation.Operation
# :type router: lepo.router.Router
# """
# self.api = operation.api
# self.path = operation.path
# self.operation = operation
# self.router = router
#
# Path: lepo/apidef/doc.py
# class APIDefinition:
# version = None
# path_class = Path
# operation_class = None
#
# def __init__(self, doc):
# """
# Instantiate a new Lepo router.
#
# :param doc: The OpenAPI definition document.
# :type doc: dict
# """
# self.doc = doc
# self.resolver = RefResolver('', self.doc)
#
# def resolve_reference(self, ref):
# """
# Resolve a JSON Pointer object reference to the object itself.
#
# :param ref: Reference string (`#/foo/bar`, for instance)
# :return: The object, if found
# :raises jsonschema.exceptions.RefResolutionError: if there is trouble resolving the reference
# """
# url, resolved = self.resolver.resolve(ref)
# return resolved
#
# def get_path_mapping(self, path):
# return maybe_resolve(self.doc['paths'][path], self.resolve_reference)
#
# def get_path_names(self):
# yield from self.doc['paths']
#
# def get_path(self, path):
# """
# Construct a Path object from a path string.
#
# The Path string must be declared in the API.
#
# :type path: str
# :rtype: lepo.path.Path
# """
# mapping = self.get_path_mapping(path)
# return self.path_class(api=self, path=path, mapping=mapping)
#
# def get_paths(self):
# """
# Iterate over all Path objects declared by the API.
#
# :rtype: Iterable[lepo.path.Path]
# """
# for path_name in self.get_path_names():
# yield self.get_path(path_name)
#
# @classmethod
# def from_file(cls, filename):
# """
# Construct an APIDefinition by parsing the given `filename`.
#
# If PyYAML is installed, YAML files are supported.
# JSON files are always supported.
#
# :param filename: The filename to read.
# :rtype: APIDefinition
# """
# with open(filename) as infp:
# if filename.endswith('.yaml') or filename.endswith('.yml'):
# import yaml
# data = yaml.safe_load(infp)
# else:
# import json
# data = json.load(infp)
# return cls.from_data(data)
#
# @classmethod
# def from_data(cls, data):
# version = parse_version(data)
# if version == SWAGGER_2:
# return Swagger2APIDefinition(data)
# if version == OPENAPI_3:
# return OpenAPI3APIDefinition(data)
# raise NotImplementedError('We can never get here.') # pragma: no cover
#
# @classmethod
# def from_yaml(cls, yaml_string):
# from yaml import safe_load
# return cls.from_data(safe_load(yaml_string))
#
# Path: lepo/parameter_utils.py
# def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901
# """
# :param request: HttpRequest with attached api_info
# :type request: HttpRequest
# :type view_kwargs: dict[str, object]
# :type capture_errors: bool
# :rtype: dict[str, object]
# """
# if view_kwargs is None:
# view_kwargs = {}
# params = {}
# errors = {}
# for param in request.api_info.operation.parameters:
# try:
# value = param.get_value(request, view_kwargs)
# if value is NO_VALUE:
# if param.has_default:
# params[param.name] = param.default
# elif param.required: # Required but missing
# errors[param.name] = MissingParameter(f'parameter {param.name} is required but missing')
# continue # No value, or a default was added, or an error was added.
# params[param.name] = param.cast(request.api_info.api, value)
# except (NotImplementedError, ImproperlyConfigured):
# raise
# except Exception as e:
# if not capture_errors:
# raise
# errors[param.name] = e
# if errors:
# raise ErroneousParameters(errors, params)
# return params
. Output only the next line. | params = read_parameters(request, {}) |
Given snippet: <|code_start|>
def greet(request, greeting, greetee):
raise ExceptionalResponse(HttpResponse('oh no', status=400))
@doc_versions
def test_exceptional_response(rf, doc_version):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.http.response import HttpResponse
from lepo.excs import ExceptionalResponse
from lepo_tests.tests.utils import doc_versions, get_router
and context:
# Path: lepo/excs.py
# class ExceptionalResponse(Exception):
# """
# Wraps a Response in an exception.
#
# These exceptions are caught in PathView.
# """
# def __init__(self, response):
# self.response = response
#
# Path: lepo_tests/tests/utils.py
# TESTS_DIR = os.path.dirname(__file__)
# DOC_VERSIONS = ['swagger2', 'openapi3']
# def get_router(fixture_name):
# def get_data_from_response(response, status=200):
# def cast_parameter_value(apidoc, parameter, value):
# def get_apidoc_from_version(version, content={}):
# def make_request_for_operation(operation, method='GET', query_string=''):
which might include code, classes, or functions. Output only the next line. | router = get_router(f'{doc_version}/parameter-test.yaml') |
Given the following code snippet before the placeholder: <|code_start|> :type path: str
:type mapping: dict
"""
self.api = api
self.path = path
self.mapping = mapping
self.regex = self._build_regex()
self.name = self._build_view_name()
def get_view_class(self, router):
return type(f'{self.name.title()}View', (PathView,), {
'path': self,
'router': router,
})
def _build_view_name(self):
path = re.sub(PATH_PLACEHOLDER_REGEX, r'\1', self.path)
name = re.sub(r'[^a-z0-9]+', '-', path, flags=re.I).strip('-').lower()
return name
def _build_regex(self):
return re.sub(
PATH_PLACEHOLDER_REGEX,
lambda m: f'(?P<{m.group(1)}>[^/]+?)',
self.path,
).lstrip('/') + '$'
def get_operation(self, method):
operation_data = self.mapping.get(method.lower())
if not operation_data:
<|code_end|>
, predict the next line using imports from the current file:
import re
from lepo.excs import InvalidOperation
from lepo.path_view import PathView
and context including class names, function names, and sometimes code from other files:
# Path: lepo/excs.py
# class InvalidOperation(ValueError):
# pass
#
# Path: lepo/path_view.py
# class PathView(View):
# router = None # Filled in by subclasses
# path = None # Filled in by subclasses
#
# def dispatch(self, request, **kwargs):
# try:
# operation = self.path.get_operation(request.method)
# except InvalidOperation:
# return self.http_method_not_allowed(request, **kwargs)
# request.api_info = APIInfo(
# operation=operation,
# router=self.router,
# )
# params = {
# snake_case(name): value
# for (name, value)
# in read_parameters(request, kwargs, capture_errors=True).items()
# }
# handler = request.api_info.router.get_handler(operation.id)
# try:
# response = handler(request, **params)
# except ExceptionalResponse as er:
# response = er.response
#
# return self.transform_response(response)
#
# def transform_response(self, response):
# if isinstance(response, HttpResponse):
# # TODO: validate against responses
# return response
# return JsonResponse(response, safe=False) # TODO: maybe less TIMTOWDI here?
. Output only the next line. | raise InvalidOperation(f'Path {self.path} does not support method {method.upper()}') |
Here is a snippet: <|code_start|>
PATH_PLACEHOLDER_REGEX = r'\{(.+?)\}'
# As defined in the documentation for Path Items:
METHODS = {'get', 'put', 'post', 'delete', 'options', 'head', 'patch'}
class Path:
def __init__(self, api, path, mapping):
"""
:type api: lepo.apidef.APIDefinition
:type path: str
:type mapping: dict
"""
self.api = api
self.path = path
self.mapping = mapping
self.regex = self._build_regex()
self.name = self._build_view_name()
def get_view_class(self, router):
<|code_end|>
. Write the next line using the current file imports:
import re
from lepo.excs import InvalidOperation
from lepo.path_view import PathView
and context from other files:
# Path: lepo/excs.py
# class InvalidOperation(ValueError):
# pass
#
# Path: lepo/path_view.py
# class PathView(View):
# router = None # Filled in by subclasses
# path = None # Filled in by subclasses
#
# def dispatch(self, request, **kwargs):
# try:
# operation = self.path.get_operation(request.method)
# except InvalidOperation:
# return self.http_method_not_allowed(request, **kwargs)
# request.api_info = APIInfo(
# operation=operation,
# router=self.router,
# )
# params = {
# snake_case(name): value
# for (name, value)
# in read_parameters(request, kwargs, capture_errors=True).items()
# }
# handler = request.api_info.router.get_handler(operation.id)
# try:
# response = handler(request, **params)
# except ExceptionalResponse as er:
# response = er.response
#
# return self.transform_response(response)
#
# def transform_response(self, response):
# if isinstance(response, HttpResponse):
# # TODO: validate against responses
# return response
# return JsonResponse(response, safe=False) # TODO: maybe less TIMTOWDI here?
, which may include functions, classes, or code. Output only the next line. | return type(f'{self.name.title()}View', (PathView,), { |
Here is a snippet: <|code_start|>try:
except ImportError:
def root_view(request):
return HttpResponse('API root')
class Router:
def __init__(self, api):
"""
Instantiate a new Lepo router.
:param api: An APIDefinition object
:type api: APIDefinition
"""
<|code_end|>
. Write the next line using the current file imports:
from collections.abc import Iterable
from collections import Iterable
from functools import reduce
from importlib import import_module
from inspect import isfunction, ismethod
from django.http import HttpResponse
from django.urls import re_path
from lepo.apidef.doc import APIDefinition
from lepo.excs import MissingHandler
from lepo.utils import snake_case
and context from other files:
# Path: lepo/apidef/doc.py
# class APIDefinition:
# version = None
# path_class = Path
# operation_class = None
#
# def __init__(self, doc):
# """
# Instantiate a new Lepo router.
#
# :param doc: The OpenAPI definition document.
# :type doc: dict
# """
# self.doc = doc
# self.resolver = RefResolver('', self.doc)
#
# def resolve_reference(self, ref):
# """
# Resolve a JSON Pointer object reference to the object itself.
#
# :param ref: Reference string (`#/foo/bar`, for instance)
# :return: The object, if found
# :raises jsonschema.exceptions.RefResolutionError: if there is trouble resolving the reference
# """
# url, resolved = self.resolver.resolve(ref)
# return resolved
#
# def get_path_mapping(self, path):
# return maybe_resolve(self.doc['paths'][path], self.resolve_reference)
#
# def get_path_names(self):
# yield from self.doc['paths']
#
# def get_path(self, path):
# """
# Construct a Path object from a path string.
#
# The Path string must be declared in the API.
#
# :type path: str
# :rtype: lepo.path.Path
# """
# mapping = self.get_path_mapping(path)
# return self.path_class(api=self, path=path, mapping=mapping)
#
# def get_paths(self):
# """
# Iterate over all Path objects declared by the API.
#
# :rtype: Iterable[lepo.path.Path]
# """
# for path_name in self.get_path_names():
# yield self.get_path(path_name)
#
# @classmethod
# def from_file(cls, filename):
# """
# Construct an APIDefinition by parsing the given `filename`.
#
# If PyYAML is installed, YAML files are supported.
# JSON files are always supported.
#
# :param filename: The filename to read.
# :rtype: APIDefinition
# """
# with open(filename) as infp:
# if filename.endswith('.yaml') or filename.endswith('.yml'):
# import yaml
# data = yaml.safe_load(infp)
# else:
# import json
# data = json.load(infp)
# return cls.from_data(data)
#
# @classmethod
# def from_data(cls, data):
# version = parse_version(data)
# if version == SWAGGER_2:
# return Swagger2APIDefinition(data)
# if version == OPENAPI_3:
# return OpenAPI3APIDefinition(data)
# raise NotImplementedError('We can never get here.') # pragma: no cover
#
# @classmethod
# def from_yaml(cls, yaml_string):
# from yaml import safe_load
# return cls.from_data(safe_load(yaml_string))
#
# Path: lepo/excs.py
# class MissingHandler(ValueError):
# pass
#
# Path: lepo/utils.py
# def snake_case(string):
# return camel_case_to_spaces(string).replace('-', '_').replace(' ', '_').replace('__', '_')
, which may include functions, classes, or code. Output only the next line. | assert isinstance(api, APIDefinition) |
Based on the snippet: <|code_start|> regex = regex.rstrip('$')
if not regex.endswith('/'):
regex += '/'
regex += '?$'
view = decorate(path.get_view_class(router=self).as_view())
urls.append(re_path(regex, view, name=name_template.format(name=path.name)))
if root_view_name:
urls.append(re_path(r'^$', root_view, name=name_template.format(name=root_view_name)))
return urls
def get_handler(self, operation_id):
"""
Get the handler function for a given operation.
To remain Pythonic, both the original and the snake_cased version of the operation ID are
supported.
This could be overridden in a subclass.
:param operation_id: Operation ID.
:return: Handler function
:rtype: function
"""
handler = (
self.handlers.get(operation_id)
or self.handlers.get(snake_case(operation_id))
)
if handler:
return handler
<|code_end|>
, predict the immediate next line with the help of imports:
from collections.abc import Iterable
from collections import Iterable
from functools import reduce
from importlib import import_module
from inspect import isfunction, ismethod
from django.http import HttpResponse
from django.urls import re_path
from lepo.apidef.doc import APIDefinition
from lepo.excs import MissingHandler
from lepo.utils import snake_case
and context (classes, functions, sometimes code) from other files:
# Path: lepo/apidef/doc.py
# class APIDefinition:
# version = None
# path_class = Path
# operation_class = None
#
# def __init__(self, doc):
# """
# Instantiate a new Lepo router.
#
# :param doc: The OpenAPI definition document.
# :type doc: dict
# """
# self.doc = doc
# self.resolver = RefResolver('', self.doc)
#
# def resolve_reference(self, ref):
# """
# Resolve a JSON Pointer object reference to the object itself.
#
# :param ref: Reference string (`#/foo/bar`, for instance)
# :return: The object, if found
# :raises jsonschema.exceptions.RefResolutionError: if there is trouble resolving the reference
# """
# url, resolved = self.resolver.resolve(ref)
# return resolved
#
# def get_path_mapping(self, path):
# return maybe_resolve(self.doc['paths'][path], self.resolve_reference)
#
# def get_path_names(self):
# yield from self.doc['paths']
#
# def get_path(self, path):
# """
# Construct a Path object from a path string.
#
# The Path string must be declared in the API.
#
# :type path: str
# :rtype: lepo.path.Path
# """
# mapping = self.get_path_mapping(path)
# return self.path_class(api=self, path=path, mapping=mapping)
#
# def get_paths(self):
# """
# Iterate over all Path objects declared by the API.
#
# :rtype: Iterable[lepo.path.Path]
# """
# for path_name in self.get_path_names():
# yield self.get_path(path_name)
#
# @classmethod
# def from_file(cls, filename):
# """
# Construct an APIDefinition by parsing the given `filename`.
#
# If PyYAML is installed, YAML files are supported.
# JSON files are always supported.
#
# :param filename: The filename to read.
# :rtype: APIDefinition
# """
# with open(filename) as infp:
# if filename.endswith('.yaml') or filename.endswith('.yml'):
# import yaml
# data = yaml.safe_load(infp)
# else:
# import json
# data = json.load(infp)
# return cls.from_data(data)
#
# @classmethod
# def from_data(cls, data):
# version = parse_version(data)
# if version == SWAGGER_2:
# return Swagger2APIDefinition(data)
# if version == OPENAPI_3:
# return OpenAPI3APIDefinition(data)
# raise NotImplementedError('We can never get here.') # pragma: no cover
#
# @classmethod
# def from_yaml(cls, yaml_string):
# from yaml import safe_load
# return cls.from_data(safe_load(yaml_string))
#
# Path: lepo/excs.py
# class MissingHandler(ValueError):
# pass
#
# Path: lepo/utils.py
# def snake_case(string):
# return camel_case_to_spaces(string).replace('-', '_').replace(' ', '_').replace('__', '_')
. Output only the next line. | raise MissingHandler( |
Here is a snippet: <|code_start|> urls = []
for path in self.api.get_paths():
regex = path.regex
if optional_trailing_slash:
regex = regex.rstrip('$')
if not regex.endswith('/'):
regex += '/'
regex += '?$'
view = decorate(path.get_view_class(router=self).as_view())
urls.append(re_path(regex, view, name=name_template.format(name=path.name)))
if root_view_name:
urls.append(re_path(r'^$', root_view, name=name_template.format(name=root_view_name)))
return urls
def get_handler(self, operation_id):
"""
Get the handler function for a given operation.
To remain Pythonic, both the original and the snake_cased version of the operation ID are
supported.
This could be overridden in a subclass.
:param operation_id: Operation ID.
:return: Handler function
:rtype: function
"""
handler = (
self.handlers.get(operation_id)
<|code_end|>
. Write the next line using the current file imports:
from collections.abc import Iterable
from collections import Iterable
from functools import reduce
from importlib import import_module
from inspect import isfunction, ismethod
from django.http import HttpResponse
from django.urls import re_path
from lepo.apidef.doc import APIDefinition
from lepo.excs import MissingHandler
from lepo.utils import snake_case
and context from other files:
# Path: lepo/apidef/doc.py
# class APIDefinition:
# version = None
# path_class = Path
# operation_class = None
#
# def __init__(self, doc):
# """
# Instantiate a new Lepo router.
#
# :param doc: The OpenAPI definition document.
# :type doc: dict
# """
# self.doc = doc
# self.resolver = RefResolver('', self.doc)
#
# def resolve_reference(self, ref):
# """
# Resolve a JSON Pointer object reference to the object itself.
#
# :param ref: Reference string (`#/foo/bar`, for instance)
# :return: The object, if found
# :raises jsonschema.exceptions.RefResolutionError: if there is trouble resolving the reference
# """
# url, resolved = self.resolver.resolve(ref)
# return resolved
#
# def get_path_mapping(self, path):
# return maybe_resolve(self.doc['paths'][path], self.resolve_reference)
#
# def get_path_names(self):
# yield from self.doc['paths']
#
# def get_path(self, path):
# """
# Construct a Path object from a path string.
#
# The Path string must be declared in the API.
#
# :type path: str
# :rtype: lepo.path.Path
# """
# mapping = self.get_path_mapping(path)
# return self.path_class(api=self, path=path, mapping=mapping)
#
# def get_paths(self):
# """
# Iterate over all Path objects declared by the API.
#
# :rtype: Iterable[lepo.path.Path]
# """
# for path_name in self.get_path_names():
# yield self.get_path(path_name)
#
# @classmethod
# def from_file(cls, filename):
# """
# Construct an APIDefinition by parsing the given `filename`.
#
# If PyYAML is installed, YAML files are supported.
# JSON files are always supported.
#
# :param filename: The filename to read.
# :rtype: APIDefinition
# """
# with open(filename) as infp:
# if filename.endswith('.yaml') or filename.endswith('.yml'):
# import yaml
# data = yaml.safe_load(infp)
# else:
# import json
# data = json.load(infp)
# return cls.from_data(data)
#
# @classmethod
# def from_data(cls, data):
# version = parse_version(data)
# if version == SWAGGER_2:
# return Swagger2APIDefinition(data)
# if version == OPENAPI_3:
# return OpenAPI3APIDefinition(data)
# raise NotImplementedError('We can never get here.') # pragma: no cover
#
# @classmethod
# def from_yaml(cls, yaml_string):
# from yaml import safe_load
# return cls.from_data(safe_load(yaml_string))
#
# Path: lepo/excs.py
# class MissingHandler(ValueError):
# pass
#
# Path: lepo/utils.py
# def snake_case(string):
# return camel_case_to_spaces(string).replace('-', '_').replace(' ', '_').replace('__', '_')
, which may include functions, classes, or code. Output only the next line. | or self.handlers.get(snake_case(operation_id)) |
Next line prediction: <|code_start|>
DEFAULT_TEMPLATE = 'fedora'
DEFAULT_PYTHON_VERSIONS = {
'fedora': ['3'],
'epel7': ['2', '3'],
'epel6': ['2'],
'mageia': ['3'],
'pld': ['2', '3']
}
DEFAULT_PYTHON_VERSION = DEFAULT_PYTHON_VERSIONS[DEFAULT_TEMPLATE][0]
DEFAULT_PKG_SOURCE = 'pypi'
DEFAULT_METADATA_SOURCE = 'pypi'
DEFAULT_DISTRO = 'fedora'
<|code_end|>
. Use current file imports:
(from pyp2rpm import utils)
and context including class names, function names, or small code snippets from other files:
# Path: pyp2rpm/utils.py
# PY3 = sys.version > '3'
# class ChangeDir(object):
# def __init__(self, new_path):
# def __enter__(self):
# def __exit__(self, type, value, traceback): # TODO handle exception
# def memoize_by_args(func):
# def memoized(*args):
# def build_srpm(specfile, save_dir):
# def remove_major_minor_suffix(scripts):
# def runtime_to_build(runtime_deps):
# def unique_deps(deps):
# def console_to_str(s):
# def console_to_str(s):
# def c_time_locale():
# def rpm_eval(macro):
# def get_default_save_path():
. Output only the next line. | DEFAULT_PKG_SAVE_PATH = utils.get_default_save_path() |
Next line prediction: <|code_start|>
def __sub__(self, other):
'''
Makes differance of DirsContents objects attributes
'''
if any([self.bindir is None, self.lib_sitepackages is None,
other.bindir is None, other.lib_sitepackages is None]):
raise ValueError("Some of the attributes is uninicialized")
result = DirsContent(
self.bindir - other.bindir,
self.lib_sitepackages - other.lib_sitepackages)
return result
class VirtualEnv(object):
def __init__(self, name, temp_dir, name_convertor,
base_python_version):
self.name = name
self.temp_dir = temp_dir
self.name_convertor = name_convertor
if not base_python_version:
base_python_version = DEFAULT_PYTHON_VERSION
python_version = 'python' + base_python_version
self.env = VirtualEnvironment(temp_dir + '/venv',
python=python_version)
try:
self.env.open_or_create()
except (ve.VirtualenvCreationException,
ve.VirtualenvReadonlyException):
<|code_end|>
. Use current file imports:
(import os
import glob
import logging
import pprint
import virtualenvapi.exceptions as ve
from virtualenvapi.manage import VirtualEnvironment
from pyp2rpm.exceptions import VirtualenvFailException
from pyp2rpm.settings import DEFAULT_PYTHON_VERSION, MODULE_SUFFIXES)
and context including class names, function names, or small code snippets from other files:
# Path: pyp2rpm/exceptions.py
# class VirtualenvFailException(BaseException):
# pass
#
# Path: pyp2rpm/settings.py
# DEFAULT_PYTHON_VERSION = DEFAULT_PYTHON_VERSIONS[DEFAULT_TEMPLATE][0]
#
# MODULE_SUFFIXES = ('.py', '.pyc')
. Output only the next line. | raise VirtualenvFailException('Failed to create virtualenv') |
Given snippet: <|code_start|>
def fill(self, path):
'''
Scans content of directories
'''
self.bindir = set(os.listdir(path + 'bin/'))
self.lib_sitepackages = set(os.listdir(glob.glob(
path + 'lib/python*.*/site-packages/')[0]))
def __sub__(self, other):
'''
Makes differance of DirsContents objects attributes
'''
if any([self.bindir is None, self.lib_sitepackages is None,
other.bindir is None, other.lib_sitepackages is None]):
raise ValueError("Some of the attributes is uninicialized")
result = DirsContent(
self.bindir - other.bindir,
self.lib_sitepackages - other.lib_sitepackages)
return result
class VirtualEnv(object):
def __init__(self, name, temp_dir, name_convertor,
base_python_version):
self.name = name
self.temp_dir = temp_dir
self.name_convertor = name_convertor
if not base_python_version:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import glob
import logging
import pprint
import virtualenvapi.exceptions as ve
from virtualenvapi.manage import VirtualEnvironment
from pyp2rpm.exceptions import VirtualenvFailException
from pyp2rpm.settings import DEFAULT_PYTHON_VERSION, MODULE_SUFFIXES
and context:
# Path: pyp2rpm/exceptions.py
# class VirtualenvFailException(BaseException):
# pass
#
# Path: pyp2rpm/settings.py
# DEFAULT_PYTHON_VERSION = DEFAULT_PYTHON_VERSIONS[DEFAULT_TEMPLATE][0]
#
# MODULE_SUFFIXES = ('.py', '.pyc')
which might include code, classes, or functions. Output only the next line. | base_python_version = DEFAULT_PYTHON_VERSION |
Given the code snippet: <|code_start|>
def install_package_to_venv(self):
'''
Installs package given as first argument to virtualenv without
dependencies
'''
try:
self.env.install((self.name,), force=True,
options=["--no-deps"])
except (ve.PackageInstallationException,
ve.VirtualenvReadonlyException):
raise VirtualenvFailException(
'Failed to install package to virtualenv')
self.dirs_after_install.fill(self.temp_dir + '/venv/')
def get_dirs_differance(self):
'''
Makes final versions of site_packages and scripts using DirsContent
sub method and filters
'''
try:
diff = self.dirs_after_install - self.dirs_before_install
except ValueError:
raise VirtualenvFailException(
"Some of the DirsContent attributes is uninicialized")
self.data['has_pth'] = \
any([x for x in diff.lib_sitepackages if x.endswith('.pth')])
site_packages = site_packages_filter(diff.lib_sitepackages)
self.data['packages'] = sorted(
<|code_end|>
, generate the next line using the imports in this file:
import os
import glob
import logging
import pprint
import virtualenvapi.exceptions as ve
from virtualenvapi.manage import VirtualEnvironment
from pyp2rpm.exceptions import VirtualenvFailException
from pyp2rpm.settings import DEFAULT_PYTHON_VERSION, MODULE_SUFFIXES
and context (functions, classes, or occasionally code) from other files:
# Path: pyp2rpm/exceptions.py
# class VirtualenvFailException(BaseException):
# pass
#
# Path: pyp2rpm/settings.py
# DEFAULT_PYTHON_VERSION = DEFAULT_PYTHON_VERSIONS[DEFAULT_TEMPLATE][0]
#
# MODULE_SUFFIXES = ('.py', '.pyc')
. Output only the next line. | [p for p in site_packages if not p.endswith(MODULE_SUFFIXES)]) |
Predict the next line after this snippet: <|code_start|>
def close(self):
if self.handle:
self.handle.close()
def __enter__(self):
return self.open()
def __exit__(self, type, value, traceback): # TODO: handle exceptions here
self.close()
@property
def extractor_cls(self):
"""Returns the class that can read this archive based on archive suffix.
Returns:
Class that can read this archive or None if no such exists.
"""
file_cls = None
# only catches ".gz", even from ".tar.gz"
if self.is_tar:
file_cls = TarFile
elif self.is_zip:
file_cls = ZipFile
else:
logger.info("Couldn't recognize archive suffix: {0}.".format(
self.suffix))
return file_cls
<|code_end|>
using the current file's imports:
import json
import locale
import logging
import os
import re
import sre_constants
import sys
from zipfile import ZipFile, ZipInfo
from tarfile import TarFile, TarInfo
from pyp2rpm import utils
and any relevant context from other files:
# Path: pyp2rpm/utils.py
# PY3 = sys.version > '3'
# class ChangeDir(object):
# def __init__(self, new_path):
# def __enter__(self):
# def __exit__(self, type, value, traceback): # TODO handle exception
# def memoize_by_args(func):
# def memoized(*args):
# def build_srpm(specfile, save_dir):
# def remove_major_minor_suffix(scripts):
# def runtime_to_build(runtime_deps):
# def unique_deps(deps):
# def console_to_str(s):
# def console_to_str(s):
# def c_time_locale():
# def rpm_eval(macro):
# def get_default_save_path():
. Output only the next line. | @utils.memoize_by_args |
Based on the snippet: <|code_start|>
tests_dir = os.path.split(os.path.abspath(__file__))[0]
class TestMetadataExtractor(object):
td_dir = '{0}/test_data/'.format(tests_dir)
def setup_method(self, method):
# create fresh extractors for every test
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import setuptools
import pytest
import pyp2rpm.metadata_extractors as me
from flexmock import flexmock
from pyp2rpm.name_convertor import NameConvertor
from pyp2rpm import utils
and context (classes, functions, sometimes code) from other files:
# Path: pyp2rpm/name_convertor.py
# class NameConvertor(object):
# distro = settings.DEFAULT_TEMPLATE
#
# def __init__(self, distro):
# self.distro = distro
# self.reg_start = re.compile(r'^[Pp]ython(\d*|)-(.*)')
# self.reg_end = re.compile(r'(.*)-(python)(\d*|)$')
#
# @classmethod
# def get_default_py_version(cls):
# try:
# return settings.DEFAULT_PYTHON_VERSIONS[cls.distro][0]
# except KeyError:
# logger.error('Default python versions for template {0} are '
# 'missing in settings, using versions of template '
# '{1}.'.format(cls.distro,
# settings.DEFAULT_TEMPLATE))
# return settings.DEFAULT_PYTHON_VERSIONS[
# settings.DEFAULT_TEMPLATE][0]
#
# @classmethod
# def rpm_versioned_name(cls, name, version, default_number=False,
# use_macros=False):
# """Properly versions the name.
# For example:
# rpm_versioned_name('python-foo', '26') will return python26-foo
# rpm_versioned_name('pyfoo, '3') will return python3-pyfoo
#
# If version is same as settings.DEFAULT_PYTHON_VERSION, no change
# is done.
#
# Args:
# name: name to version
# version: version or None
# Returns:
# Versioned name or the original name if given version is None.
# """
# regexp = re.compile(r'^python(\d*|)-(.*)')
# auto_provides_regexp = re.compile(r'^python(\d*|)dist(.*)')
#
# if (not version or version == cls.get_default_py_version() and
# not default_number):
# found = regexp.search(name)
# # second check is to avoid renaming of python2-devel to
# # python-devel
# if found and found.group(2) != 'devel':
# if 'epel' not in cls.distro:
# return 'python-{0}'.format(regexp.search(name).group(2))
# return name
#
# versioned_name = name
# if version:
#
# if regexp.search(name):
# versioned_name = re.sub(r'^python(\d*|)-', 'python{0}-'.format(
# version), name)
# elif auto_provides_regexp.search(name):
# versioned_name = re.sub(
# r'^python(\d*|)dist', 'python{0}dist'.format(
# version), name)
#
# else:
# versioned_name = 'python{0}-{1}'.format(version, name)
# if (use_macros and 'epel' in cls.distro and version !=
# cls.get_default_py_version()):
# versioned_name = versioned_name.replace('python{0}-'.format(
# version), 'python%{{python{0}_pkgversion}}-'.format(version))
# return versioned_name
#
# def rpm_name(self, name, python_version=None, pkg_name=False):
# """Returns name of the package converted to (possibly) correct package
# name according to Packaging Guidelines.
# Args:
# name: name to convert
# python_version: python version for which to retrieve the name of
# the package
# pkg_name: flag to perform conversion of rpm package name,
# present in this class just for API compatibility reason
# Returns:
# Converted name of the package, that should be in line with
# Fedora Packaging Guidelines. If for_python is not None,
# the returned name is in form python%(version)s-%(name)s
# """
# logger.debug("Converting name: {0} to rpm name, version: {1}.".format(
# name, python_version))
# rpmized_name = self.base_name(name)
#
# rpmized_name = 'python-{0}'.format(rpmized_name)
#
# if self.distro == 'mageia':
# rpmized_name = rpmized_name.lower()
# logger.debug('Rpmized name of {0}: {1}.'.format(name, rpmized_name))
# return NameConvertor.rpm_versioned_name(rpmized_name, python_version)
#
# def base_name(self, name):
# """Removes any python prefixes of suffixes from name if present."""
# base_name = name.replace('.', "-")
# # remove python prefix if present
# found_prefix = self.reg_start.search(name)
# if found_prefix:
# base_name = found_prefix.group(2)
#
# # remove -pythonXY like suffix if present
# found_end = self.reg_end.search(name.lower())
# if found_end:
# base_name = found_end.group(1)
#
# return base_name
#
# Path: pyp2rpm/utils.py
# PY3 = sys.version > '3'
# class ChangeDir(object):
# def __init__(self, new_path):
# def __enter__(self):
# def __exit__(self, type, value, traceback): # TODO handle exception
# def memoize_by_args(func):
# def memoized(*args):
# def build_srpm(specfile, save_dir):
# def remove_major_minor_suffix(scripts):
# def runtime_to_build(runtime_deps):
# def unique_deps(deps):
# def console_to_str(s):
# def console_to_str(s):
# def c_time_locale():
# def rpm_eval(macro):
# def get_default_save_path():
. Output only the next line. | self.nc = NameConvertor('fedora') |
Next line prediction: <|code_start|>
logger = logging.getLogger(__name__)
def dependency_to_rpm(dep, runtime, use_rich_deps=True):
"""Converts a dependency got by pkg_resources.Requirement.parse()
to RPM format.
Args:
dep - a dependency retrieved by pkg_resources.Requirement.parse()
runtime - whether the returned dependency should be runtime (True)
or build time (False)
Returns:
List of semi-SPECFILE dependencies (package names are not properly
converted yet).
For example: [['Requires', 'jinja2', '{name}'],
['Conflicts', 'jinja2', '{name} = 2.0.1']]
"""
logger.debug('Dependencies provided: {0} runtime: {1}.'.format(
dep, runtime))
<|code_end|>
. Use current file imports:
(import logging
import re
from pkg_resources import Requirement
from pyp2rpm.dependency_convert import convert_requirement)
and context including class names, function names, or small code snippets from other files:
# Path: pyp2rpm/dependency_convert.py
# def convert_requirement(parsed_req, use_rich_deps=True):
# if not use_rich_deps:
# return legacy_convert_requirement(parsed_req)
# reqs = []
# for spec in parsed_req.specs:
# reqs.append(convert(parsed_req.project_name, spec[0], spec[1]))
# if len(reqs) == 0:
# return [['Requires', parsed_req.project_name, '{name}']]
# if len(reqs) == 1:
# return [['Requires', parsed_req.project_name, reqs[0]]]
# reqs.sort(reverse=True)
# return [['Requires', parsed_req.project_name,
# '({})'.format(' with '.join(reqs))]]
. Output only the next line. | converted = convert_requirement(dep, use_rich_deps) |
Predict the next line after this snippet: <|code_start|> [['Requires', 'pyp2rpm', '{name} >= 0.9.3.1'],
['Requires', 'pyp2rpm', '{name} < 0.9.4']
]
),
('docutils>=0.3,<1,!=0.5', True, True,
[['Requires', 'docutils',
'({name} >= 0.3 with {name} < 1~~ with ({name} < 0.5 or {name} > 0.5))']
]
),
('pytest>=0.3a5,<1.1.1.1,!=1', False, True,
[['BuildRequires', 'pytest',
'({name} >= 0.3~a5 with {name} < 1.1.1.1~~ with ({name} < 1 or {name} > 1))']
]
),
('pyp2rpm~=3.3.0rc2', True, True,
[['Requires', 'pyp2rpm', '({name} >= 3.3~rc2 with {name} < 3.4)']]
),
('pyp2rpm~=0.9.3', True, True,
[['Requires', 'pyp2rpm', '({name} >= 0.9.3 with {name} < 0.10)']]
),
('pyp2rpm~=0.9.3.1', True, True,
[['Requires', 'pyp2rpm', '({name} >= 0.9.3.1 with {name} < 0.9.4)']]
),
('nb2plots>0+unknown', True, True,
[['Requires', 'nb2plots', '{name} > 0.0']]
),
])
def test_dependency_to_rpm(self, d, r, rich, expected):
# we can't convert lists of lists into sets => compare len and contents
<|code_end|>
using the current file's imports:
import pytest
from pkg_resources import Requirement as R
from pyp2rpm.dependency_parser import dependency_to_rpm
and any relevant context from other files:
# Path: pyp2rpm/dependency_parser.py
# def dependency_to_rpm(dep, runtime, use_rich_deps=True):
# """Converts a dependency got by pkg_resources.Requirement.parse()
# to RPM format.
# Args:
# dep - a dependency retrieved by pkg_resources.Requirement.parse()
# runtime - whether the returned dependency should be runtime (True)
# or build time (False)
# Returns:
# List of semi-SPECFILE dependencies (package names are not properly
# converted yet).
# For example: [['Requires', 'jinja2', '{name}'],
# ['Conflicts', 'jinja2', '{name} = 2.0.1']]
# """
# logger.debug('Dependencies provided: {0} runtime: {1}.'.format(
# dep, runtime))
# converted = convert_requirement(dep, use_rich_deps)
#
# if not runtime:
# for conv in converted:
# conv[0] = "Build" + conv[0]
# logger.debug('Converted dependencies: {0}.'.format(converted))
#
# return converted
. Output only the next line. | rpm_deps = dependency_to_rpm(R.parse(d), r, rich) |
Given the following code snippet before the placeholder: <|code_start|>
description = """Convert Python packages to RPM SPECFILES. The packages can be downloaded from
PyPI and the produced SPEC is in line with Fedora Packaging Guidelines or Mageia Python Policy.
Users can provide their own templates for rendering the package metadata. Both the package
source and metadata can be extracted from PyPI or from local filesystem (local file doesn't
provide that much information though)."""
class build_py(_build_py):
def run(self):
# Run the normal build process
_build_py.run(self)
# Build test data
call([sys.executable, 'setup.py', 'sdist'],
cwd='tests/test_data/isholiday-0.1')
copy('tests/test_data/isholiday-0.1/dist/isholiday-0.1.tar.gz',
'tests/test_data/')
call([sys.executable, 'setup.py', 'sdist'],
cwd='tests/test_data/utest')
copy('tests/test_data/utest/dist/utest-0.1.0.tar.gz',
'tests/test_data/')
setup(
cmdclass={
'build_py': build_py,
},
name='pyp2rpm',
<|code_end|>
, predict the next line using imports from the current file:
import sys
from pyp2rpm.version import version
from setuptools import setup
from setuptools.command.build_py import build_py as _build_py
from subprocess import call
from shutil import copy
and context including class names, function names, and sometimes code from other files:
# Path: pyp2rpm/version.py
. Output only the next line. | version=version, |
Based on the snippet: <|code_start|> def teardown_method(self, method):
shutil.rmtree(self.temp_dir)
@pytest.mark.webtest
def test_srpm(self):
res = self.env.run('{0} Jinja2 -v2.8 --srpm'.format(self.exe),
expect_stderr=True)
assert res.returncode == 0
@pytest.mark.skipif(SclConvertor is None, reason="spec2scl not installed")
class TestSclIntegration(object):
"""
"""
sphinx_spec = '{0}/test_data/python-sphinx_autonc.spec'.format(tests_dir)
@classmethod
def setup_class(cls):
with open(cls.sphinx_spec, 'r') as spec:
cls.test_spec = spec.read()
def setup_method(self, method):
self.default_options = {
'no_meta_runtime_dep': False,
'no_meta_buildtime_dep': False,
'skip_functions': [''],
'no_deps_convert': False,
'list_file': None,
'meta_spec': None
}
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
import os
import tempfile
import shutil
import dnf
from flexmock import flexmock
from scripttest import TestFileEnvironment
from pyp2rpm.bin import Convertor, SclConvertor, main, convert_to_scl
and context (classes, functions, sometimes code) from other files:
# Path: pyp2rpm/bin.py
# CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
# class Pyp2rpmCommand(click.Command):
# class SclizeOption(click.Option):
# def format_options(self, ctx, formatter):
# def handle_parse_result(self, ctx, opts, args):
# def get_help_record(self, ctx):
# def get_scl_help_record(self, ctx):
# def main(package, v, prerelease, d, s, r, proxy, srpm, p, b, o, t, venv, autonc,
# sclize, **scl_kwargs):
# def convert_to_scl(spec, scl_options):
. Output only the next line. | flexmock(Convertor).should_receive('__init__').and_return(None) |
Next line prediction: <|code_start|> nc = '_dnfnc' if dnf is not None else '_nc'
variant = expected.format(nc)
with open(self.td_dir + variant) as fi:
self.spec_content = fi.read()
res = self.env.run('{0} {1} {2}'.format(self.exe, package, options),
expect_stderr=True)
# changelog have to be cut from spec files
assert res.stdout.split('\n')[1:-4] == self.spec_content.split(
'\n')[1:-4]
class TestSrpm(object):
td_dir = '{0}/test_data/'.format(tests_dir)
bin_dir = os.path.split(tests_dir)[0] + '/'
exe = 'python {0}mybin.py'.format(bin_dir)
def setup_method(self, method):
self.temp_dir = tempfile.mkdtemp()
self.env = TestFileEnvironment(self.temp_dir, start_clear=False)
def teardown_method(self, method):
shutil.rmtree(self.temp_dir)
@pytest.mark.webtest
def test_srpm(self):
res = self.env.run('{0} Jinja2 -v2.8 --srpm'.format(self.exe),
expect_stderr=True)
assert res.returncode == 0
<|code_end|>
. Use current file imports:
(import pytest
import os
import tempfile
import shutil
import dnf
from flexmock import flexmock
from scripttest import TestFileEnvironment
from pyp2rpm.bin import Convertor, SclConvertor, main, convert_to_scl)
and context including class names, function names, or small code snippets from other files:
# Path: pyp2rpm/bin.py
# CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
# class Pyp2rpmCommand(click.Command):
# class SclizeOption(click.Option):
# def format_options(self, ctx, formatter):
# def handle_parse_result(self, ctx, opts, args):
# def get_help_record(self, ctx):
# def get_scl_help_record(self, ctx):
# def main(package, v, prerelease, d, s, r, proxy, srpm, p, b, o, t, venv, autonc,
# sclize, **scl_kwargs):
# def convert_to_scl(spec, scl_options):
. Output only the next line. | @pytest.mark.skipif(SclConvertor is None, reason="spec2scl not installed") |
Predict the next line for this snippet: <|code_start|> 'skip_functions': [''],
'no_deps_convert': False,
'list_file': None,
'meta_spec': None
}
flexmock(Convertor).should_receive('__init__').and_return(None)
flexmock(Convertor).should_receive('convert').and_return(
self.test_spec)
@pytest.mark.parametrize(('options', 'expected_options'), [
(['--no-meta-runtime-dep'], {'no_meta_runtime_dep': True}),
(['--no-meta-buildtime-dep'], {'no_meta_buildtime_dep': True}),
(['--skip-functions=func1,func2'], {'skip_functions':
['func1', 'func2']}),
(['--no-deps-convert'], {'no_deps_convert': True}),
(['--list-file=file_name'], {'list_file': 'file_name'}),
])
def test_scl_convertor_args_correctly_passed(self, options,
expected_options, capsys):
"""Test that pyp2rpm command passes correct options to
SCL convertor.
"""
self.default_options.update(expected_options)
flexmock(SclConvertor).should_receive('convert').and_return(
self.test_spec)
flexmock(SclConvertor).should_receive('__init__').with_args(
options=self.default_options,
).once()
with pytest.raises(SystemExit):
<|code_end|>
with the help of current file imports:
import pytest
import os
import tempfile
import shutil
import dnf
from flexmock import flexmock
from scripttest import TestFileEnvironment
from pyp2rpm.bin import Convertor, SclConvertor, main, convert_to_scl
and context from other files:
# Path: pyp2rpm/bin.py
# CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
# class Pyp2rpmCommand(click.Command):
# class SclizeOption(click.Option):
# def format_options(self, ctx, formatter):
# def handle_parse_result(self, ctx, opts, args):
# def get_help_record(self, ctx):
# def get_scl_help_record(self, ctx):
# def main(package, v, prerelease, d, s, r, proxy, srpm, p, b, o, t, venv, autonc,
# sclize, **scl_kwargs):
# def convert_to_scl(spec, scl_options):
, which may contain function names, class names, or code. Output only the next line. | main(args=['foo_package', '--sclize'] + options) |
Given snippet: <|code_start|> (['--list-file=file_name'], {'list_file': 'file_name'}),
])
def test_scl_convertor_args_correctly_passed(self, options,
expected_options, capsys):
"""Test that pyp2rpm command passes correct options to
SCL convertor.
"""
self.default_options.update(expected_options)
flexmock(SclConvertor).should_receive('convert').and_return(
self.test_spec)
flexmock(SclConvertor).should_receive('__init__').with_args(
options=self.default_options,
).once()
with pytest.raises(SystemExit):
main(args=['foo_package', '--sclize'] + options)
out, err = capsys.readouterr()
assert out == self.test_spec + '\n'
@pytest.mark.parametrize(('options', 'omit_from_spec'), [
({'no_meta_runtime_dep': True}, '%{?scl:Requires: %{scl}-runtime}'),
({'no_meta_buildtime_dep': True},
'{?scl:BuildRequires: %{scl}-runtime}'),
({'skip_functions': 'handle_python_specific_commands'},
'%{?scl:scl enable %{scl} - << \\EOF}\nset -e\nsphinx-build doc html\n%{?scl:EOF}'),
])
def test_convert_to_scl_options(self, options, omit_from_spec):
"""Test integration with SCL options."""
self.default_options.update({'skip_functions': ''})
self.default_options.update(options)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
import os
import tempfile
import shutil
import dnf
from flexmock import flexmock
from scripttest import TestFileEnvironment
from pyp2rpm.bin import Convertor, SclConvertor, main, convert_to_scl
and context:
# Path: pyp2rpm/bin.py
# CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
# class Pyp2rpmCommand(click.Command):
# class SclizeOption(click.Option):
# def format_options(self, ctx, formatter):
# def handle_parse_result(self, ctx, opts, args):
# def get_help_record(self, ctx):
# def get_scl_help_record(self, ctx):
# def main(package, v, prerelease, d, s, r, proxy, srpm, p, b, o, t, venv, autonc,
# sclize, **scl_kwargs):
# def convert_to_scl(spec, scl_options):
which might include code, classes, or functions. Output only the next line. | converted = convert_to_scl(self.test_spec, self.default_options) |
Predict the next line for this snippet: <|code_start|>
logger = logging.getLogger(__name__)
def get_deps_names(runtime_deps_list):
'''
data['runtime_deps'] has format:
[['Requires', 'name', '{name} >= version'], ...]
this function creates list of lowercase deps names
'''
return [x[1].lower() for x in runtime_deps_list]
class PackageData(object):
<|code_end|>
with the help of current file imports:
import subprocess
import time
import locale
import logging
from pyp2rpm import version
from pyp2rpm import utils
and context from other files:
# Path: pyp2rpm/version.py
#
# Path: pyp2rpm/utils.py
# PY3 = sys.version > '3'
# class ChangeDir(object):
# def __init__(self, new_path):
# def __enter__(self):
# def __exit__(self, type, value, traceback): # TODO handle exception
# def memoize_by_args(func):
# def memoized(*args):
# def build_srpm(specfile, save_dir):
# def remove_major_minor_suffix(scripts):
# def runtime_to_build(runtime_deps):
# def unique_deps(deps):
# def console_to_str(s):
# def console_to_str(s):
# def c_time_locale():
# def rpm_eval(macro):
# def get_default_save_path():
, which may contain function names, class names, or code. Output only the next line. | credit_line = '# Created by pyp2rpm-{0}'.format(version.version) |
Given snippet: <|code_start|> object.__setattr__(self, 'data', {})
self.data['local_file'] = local_file
self.data['name'] = name
self.data['srcname'] = srcname
self.data['pkg_name'] = pkg_name
self.data['version'] = version
self.data['python_versions'] = []
self.data['md5'] = md5
self.data['source0'] = source0
self.data['sphinx_dir'] = None
def __getattr__(self, name):
if name == 'underscored_name':
return self.data['name'].replace('-', '_')
elif name == 'changelog_date_packager':
return self.get_changelog_date_packager()
elif name in ['runtime_deps', 'build_deps', 'classifiers',
'doc_files', 'doc_license']:
return self.data.get(name, [])
elif name in ['packages', 'py_modules', 'scripts']:
return self.data.get(name, [])
elif name in ['has_egg_info', 'has_test_suite',
'has_pth', 'has_extension']:
return self.data.get(name, False)
elif name == 'sorted_python_versions':
return sorted([self.data.get('base_python_version')] +
self.data.get('python_versions', []))
return self.data.get(name, 'TODO:')
def __setattr__(self, name, value):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import subprocess
import time
import locale
import logging
from pyp2rpm import version
from pyp2rpm import utils
and context:
# Path: pyp2rpm/version.py
#
# Path: pyp2rpm/utils.py
# PY3 = sys.version > '3'
# class ChangeDir(object):
# def __init__(self, new_path):
# def __enter__(self):
# def __exit__(self, type, value, traceback): # TODO handle exception
# def memoize_by_args(func):
# def memoized(*args):
# def build_srpm(specfile, save_dir):
# def remove_major_minor_suffix(scripts):
# def runtime_to_build(runtime_deps):
# def unique_deps(deps):
# def console_to_str(s):
# def console_to_str(s):
# def c_time_locale():
# def rpm_eval(macro):
# def get_default_save_path():
which might include code, classes, or functions. Output only the next line. | if name == 'summary' and isinstance(value, utils.str_classes): |
Based on the snippet: <|code_start|>
class TestPackageData(object):
@pytest.mark.parametrize(('s', 'expected'), [
('Spam.', 'Spam'),
('Spam', 'Spam'),
])
def test_summary_with_dot(self, s, expected):
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
from pyp2rpm.package_data import PackageData
and context (classes, functions, sometimes code) from other files:
# Path: pyp2rpm/package_data.py
# class PackageData(object):
# credit_line = '# Created by pyp2rpm-{0}'.format(version.version)
#
# """A simple object that carries data about a package."""
#
# def __init__(self, local_file, name, pkg_name, version,
# md5='', source0='', srcname=None):
# object.__setattr__(self, 'data', {})
# self.data['local_file'] = local_file
# self.data['name'] = name
# self.data['srcname'] = srcname
# self.data['pkg_name'] = pkg_name
# self.data['version'] = version
# self.data['python_versions'] = []
# self.data['md5'] = md5
# self.data['source0'] = source0
# self.data['sphinx_dir'] = None
#
# def __getattr__(self, name):
# if name == 'underscored_name':
# return self.data['name'].replace('-', '_')
# elif name == 'changelog_date_packager':
# return self.get_changelog_date_packager()
# elif name in ['runtime_deps', 'build_deps', 'classifiers',
# 'doc_files', 'doc_license']:
# return self.data.get(name, [])
# elif name in ['packages', 'py_modules', 'scripts']:
# return self.data.get(name, [])
# elif name in ['has_egg_info', 'has_test_suite',
# 'has_pth', 'has_extension']:
# return self.data.get(name, False)
# elif name == 'sorted_python_versions':
# return sorted([self.data.get('base_python_version')] +
# self.data.get('python_versions', []))
# return self.data.get(name, 'TODO:')
#
# def __setattr__(self, name, value):
# if name == 'summary' and isinstance(value, utils.str_classes):
# value = value.rstrip('.').replace('\n', ' ')
# if value is not None:
# self.data[name] = value
#
# def update_attr(self, name, value):
# if name in self.data and value:
# if name in ['runtime_deps', 'build_deps']:
# for item in value:
# if not item[1].lower() in get_deps_names(self.data[name]):
# self.data[name].append(item)
# elif isinstance(self.data[name], list):
# for item in value:
# if item not in self.data[name]:
# self.data[name].append(item)
# elif isinstance(self.data[name], set):
# if not isinstance(value, set):
# value = set(value)
# self.data[name] |= value
# elif not self.data[name] and self.data[name] is not False:
# self.data[name] = value
# elif name not in self.data and value is not None:
# self.data[name] = value
#
# def set_from(self, data_dict, update=False):
# for k, v in data_dict.items():
# if update:
# self.update_attr(k, v)
# else:
# setattr(self, k, v)
#
# def get_changelog_date_packager(self):
# """Returns part of the changelog entry, containing date and packager.
# """
# try:
# packager = subprocess.Popen(
# 'rpmdev-packager', stdout=subprocess.PIPE).communicate(
# )[0].strip()
# except OSError:
# # Hi John Doe, you should install rpmdevtools
# packager = "John Doe <john@doe.com>"
# logger.warn("Package rpmdevtools is missing, using default "
# "name: {0}.".format(packager))
# with utils.c_time_locale():
# date_str = time.strftime('%a %b %d %Y', time.gmtime())
# encoding = locale.getpreferredencoding()
# return u'{0} {1}'.format(date_str, packager.decode(encoding))
. Output only the next line. | pd = PackageData('spam', 'spam', 'python-spam', 'spam') |
Continue the code snippet: <|code_start|># -*- encoding: utf-8 -*-
class TestRerun(object):
def setup_method(self, test_method):
self.patcher = patch('thefuck.output_readers.rerun.Process')
process_mock = self.patcher.start()
self.proc_mock = process_mock.return_value = Mock()
def teardown_method(self, test_method):
self.patcher.stop()
@patch('thefuck.output_readers.rerun._wait_output', return_value=False)
@patch('thefuck.output_readers.rerun.Popen')
def test_get_output(self, popen_mock, wait_output_mock):
popen_mock.return_value.stdout.read.return_value = b'output'
<|code_end|>
. Use current file imports:
from mock import Mock, patch
from psutil import AccessDenied, TimeoutExpired
from thefuck.output_readers import rerun
and context (classes, functions, or code) from other files:
# Path: thefuck/output_readers/rerun.py
# def _kill_process(proc):
# def _wait_output(popen, is_slow):
# def get_output(script, expanded):
. Output only the next line. | assert rerun.get_output('', '') is None |
Given the following code snippet before the placeholder: <|code_start|>
@pytest.mark.parametrize('called, command, output', [
('git co', 'git checkout', "19:22:36.299340 git.c:282 trace: alias expansion: co => 'checkout'"),
('git com file', 'git commit --verbose file',
"19:23:25.470911 git.c:282 trace: alias expansion: com => 'commit' '--verbose'"),
('git com -m "Initial commit"', 'git commit -m "Initial commit"',
"19:22:36.299340 git.c:282 trace: alias expansion: com => 'commit'"),
('git br -d some_branch', 'git branch -d some_branch',
"19:22:36.299340 git.c:282 trace: alias expansion: br => 'branch'")])
def test_git_support(called, command, output):
<|code_end|>
, predict the next line using imports from the current file:
import pytest
from thefuck.specific.git import git_support
from thefuck.types import Command
and context including class names, function names, and sometimes code from other files:
# Path: thefuck/specific/git.py
# @decorator
# def git_support(fn, command):
# """Resolves git aliases and supports testing for both git and hub."""
# # supports GitHub's `hub` command
# # which is recommended to be used with `alias git=hub`
# # but at this point, shell aliases have already been resolved
# if not is_app(command, 'git', 'hub'):
# return False
#
# # perform git aliases expansion
# if command.output and 'trace: alias expansion:' in command.output:
# search = re.search("trace: alias expansion: ([^ ]*) => ([^\n]*)",
# command.output)
# alias = search.group(1)
#
# # by default git quotes everything, for example:
# # 'commit' '--amend'
# # which is surprising and does not allow to easily test for
# # eg. 'git commit'
# expansion = ' '.join(shell.quote(part)
# for part in shell.split_command(search.group(2)))
# new_script = re.sub(r"\b{}\b".format(alias), expansion, command.script)
#
# command = command.update(script=new_script)
#
# return fn(command)
#
# Path: thefuck/types.py
# class Command(object):
# """Command that should be fixed."""
#
# def __init__(self, script, output):
# """Initializes command with given values.
#
# :type script: basestring
# :type output: basestring
#
# """
# self.script = script
# self.output = output
#
# @property
# def stdout(self):
# logs.warn('`stdout` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def stderr(self):
# logs.warn('`stderr` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def script_parts(self):
# if not hasattr(self, '_script_parts'):
# try:
# self._script_parts = shell.split_command(self.script)
# except Exception:
# logs.debug(u"Can't split command script {} because:\n {}".format(
# self, sys.exc_info()))
# self._script_parts = []
#
# return self._script_parts
#
# def __eq__(self, other):
# if isinstance(other, Command):
# return (self.script, self.output) == (other.script, other.output)
# else:
# return False
#
# def __repr__(self):
# return u'Command(script={}, output={})'.format(
# self.script, self.output)
#
# def update(self, **kwargs):
# """Returns new command with replaced fields.
#
# :rtype: Command
#
# """
# kwargs.setdefault('script', self.script)
# kwargs.setdefault('output', self.output)
# return Command(**kwargs)
#
# @classmethod
# def from_raw_script(cls, raw_script):
# """Creates instance of `Command` from a list of script parts.
#
# :type raw_script: [basestring]
# :rtype: Command
# :raises: EmptyCommand
#
# """
# script = format_raw_script(raw_script)
# if not script:
# raise EmptyCommand
#
# expanded = shell.from_shell(script)
# output = get_output(script, expanded)
# return cls(expanded, output)
. Output only the next line. | @git_support |
Using the snippet: <|code_start|>
@pytest.mark.parametrize('called, command, output', [
('git co', 'git checkout', "19:22:36.299340 git.c:282 trace: alias expansion: co => 'checkout'"),
('git com file', 'git commit --verbose file',
"19:23:25.470911 git.c:282 trace: alias expansion: com => 'commit' '--verbose'"),
('git com -m "Initial commit"', 'git commit -m "Initial commit"',
"19:22:36.299340 git.c:282 trace: alias expansion: com => 'commit'"),
('git br -d some_branch', 'git branch -d some_branch',
"19:22:36.299340 git.c:282 trace: alias expansion: br => 'branch'")])
def test_git_support(called, command, output):
@git_support
def fn(command):
return command.script
<|code_end|>
, determine the next line of code. You have imports:
import pytest
from thefuck.specific.git import git_support
from thefuck.types import Command
and context (class names, function names, or code) available:
# Path: thefuck/specific/git.py
# @decorator
# def git_support(fn, command):
# """Resolves git aliases and supports testing for both git and hub."""
# # supports GitHub's `hub` command
# # which is recommended to be used with `alias git=hub`
# # but at this point, shell aliases have already been resolved
# if not is_app(command, 'git', 'hub'):
# return False
#
# # perform git aliases expansion
# if command.output and 'trace: alias expansion:' in command.output:
# search = re.search("trace: alias expansion: ([^ ]*) => ([^\n]*)",
# command.output)
# alias = search.group(1)
#
# # by default git quotes everything, for example:
# # 'commit' '--amend'
# # which is surprising and does not allow to easily test for
# # eg. 'git commit'
# expansion = ' '.join(shell.quote(part)
# for part in shell.split_command(search.group(2)))
# new_script = re.sub(r"\b{}\b".format(alias), expansion, command.script)
#
# command = command.update(script=new_script)
#
# return fn(command)
#
# Path: thefuck/types.py
# class Command(object):
# """Command that should be fixed."""
#
# def __init__(self, script, output):
# """Initializes command with given values.
#
# :type script: basestring
# :type output: basestring
#
# """
# self.script = script
# self.output = output
#
# @property
# def stdout(self):
# logs.warn('`stdout` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def stderr(self):
# logs.warn('`stderr` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def script_parts(self):
# if not hasattr(self, '_script_parts'):
# try:
# self._script_parts = shell.split_command(self.script)
# except Exception:
# logs.debug(u"Can't split command script {} because:\n {}".format(
# self, sys.exc_info()))
# self._script_parts = []
#
# return self._script_parts
#
# def __eq__(self, other):
# if isinstance(other, Command):
# return (self.script, self.output) == (other.script, other.output)
# else:
# return False
#
# def __repr__(self):
# return u'Command(script={}, output={})'.format(
# self.script, self.output)
#
# def update(self, **kwargs):
# """Returns new command with replaced fields.
#
# :rtype: Command
#
# """
# kwargs.setdefault('script', self.script)
# kwargs.setdefault('output', self.output)
# return Command(**kwargs)
#
# @classmethod
# def from_raw_script(cls, raw_script):
# """Creates instance of `Command` from a list of script parts.
#
# :type raw_script: [basestring]
# :rtype: Command
# :raises: EmptyCommand
#
# """
# script = format_raw_script(raw_script)
# if not script:
# raise EmptyCommand
#
# expanded = shell.from_shell(script)
# output = get_output(script, expanded)
# return cls(expanded, output)
. Output only the next line. | assert fn(Command(called, output)) == command |
Given snippet: <|code_start|>
@pytest.fixture
def output(branch_name):
if not branch_name:
return ''
return '''fatal: The current branch {} has no upstream branch.
To push the current branch and set the remote as upstream, use
git push --set-upstream origin {}
'''.format(branch_name, branch_name)
@pytest.fixture
def output_bitbucket():
return '''Total 0 (delta 0), reused 0 (delta 0)
remote:
remote: Create pull request for feature/set-upstream:
remote: https://bitbucket.org/set-upstream
remote:
To git@bitbucket.org:test.git
e5e7fbb..700d998 feature/set-upstream -> feature/set-upstream
Branch feature/set-upstream set up to track remote branch feature/set-upstream from origin.
'''
@pytest.mark.parametrize('script, branch_name', [
('git push', 'master'),
('git push origin', 'master')])
def test_match(output, script, branch_name):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from thefuck.rules.git_push import match, get_new_command
from thefuck.types import Command
and context:
# Path: thefuck/types.py
# class Command(object):
# """Command that should be fixed."""
#
# def __init__(self, script, output):
# """Initializes command with given values.
#
# :type script: basestring
# :type output: basestring
#
# """
# self.script = script
# self.output = output
#
# @property
# def stdout(self):
# logs.warn('`stdout` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def stderr(self):
# logs.warn('`stderr` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def script_parts(self):
# if not hasattr(self, '_script_parts'):
# try:
# self._script_parts = shell.split_command(self.script)
# except Exception:
# logs.debug(u"Can't split command script {} because:\n {}".format(
# self, sys.exc_info()))
# self._script_parts = []
#
# return self._script_parts
#
# def __eq__(self, other):
# if isinstance(other, Command):
# return (self.script, self.output) == (other.script, other.output)
# else:
# return False
#
# def __repr__(self):
# return u'Command(script={}, output={})'.format(
# self.script, self.output)
#
# def update(self, **kwargs):
# """Returns new command with replaced fields.
#
# :rtype: Command
#
# """
# kwargs.setdefault('script', self.script)
# kwargs.setdefault('output', self.output)
# return Command(**kwargs)
#
# @classmethod
# def from_raw_script(cls, raw_script):
# """Creates instance of `Command` from a list of script parts.
#
# :type raw_script: [basestring]
# :rtype: Command
# :raises: EmptyCommand
#
# """
# script = format_raw_script(raw_script)
# if not script:
# raise EmptyCommand
#
# expanded = shell.from_shell(script)
# output = get_output(script, expanded)
# return cls(expanded, output)
which might include code, classes, or functions. Output only the next line. | assert match(Command(script, output)) |
Predict the next line after this snippet: <|code_start|>
@pytest.fixture
def module_error_output(filename, module_name):
return """Traceback (most recent call last):
File "{0}", line 1, in <module>
import {1}
ModuleNotFoundError: No module named '{1}'""".format(
filename, module_name
)
@pytest.mark.parametrize(
"test",
[
<|code_end|>
using the current file's imports:
import pytest
from thefuck.rules.python_module_error import get_new_command, match
from thefuck.types import Command
and any relevant context from other files:
# Path: thefuck/types.py
# class Command(object):
# """Command that should be fixed."""
#
# def __init__(self, script, output):
# """Initializes command with given values.
#
# :type script: basestring
# :type output: basestring
#
# """
# self.script = script
# self.output = output
#
# @property
# def stdout(self):
# logs.warn('`stdout` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def stderr(self):
# logs.warn('`stderr` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def script_parts(self):
# if not hasattr(self, '_script_parts'):
# try:
# self._script_parts = shell.split_command(self.script)
# except Exception:
# logs.debug(u"Can't split command script {} because:\n {}".format(
# self, sys.exc_info()))
# self._script_parts = []
#
# return self._script_parts
#
# def __eq__(self, other):
# if isinstance(other, Command):
# return (self.script, self.output) == (other.script, other.output)
# else:
# return False
#
# def __repr__(self):
# return u'Command(script={}, output={})'.format(
# self.script, self.output)
#
# def update(self, **kwargs):
# """Returns new command with replaced fields.
#
# :rtype: Command
#
# """
# kwargs.setdefault('script', self.script)
# kwargs.setdefault('output', self.output)
# return Command(**kwargs)
#
# @classmethod
# def from_raw_script(cls, raw_script):
# """Creates instance of `Command` from a list of script parts.
#
# :type raw_script: [basestring]
# :rtype: Command
# :raises: EmptyCommand
#
# """
# script = format_raw_script(raw_script)
# if not script:
# raise EmptyCommand
#
# expanded = shell.from_shell(script)
# output = get_output(script, expanded)
# return cls(expanded, output)
. Output only the next line. | Command("python hello_world.py", "Hello World"), |
Given the following code snippet before the placeholder: <|code_start|>Additional help topics:
\tbuildconstraint build constraints
\tbuildmode build modes
\tc calling between Go and C
\tcache build and test caching
\tenvironment environment variables
\tfiletype file types
\tgo.mod the go.mod file
\tgopath GOPATH environment variable
\tgopath-get legacy GOPATH go get
\tgoproxy module proxy protocol
\timportpath import path syntax
\tmodules modules, module versions, and more
\tmodule-get module-aware go get
\tmodule-auth module authentication using go.sum
\tmodule-private module configuration for non-public modules
\tpackages package lists and patterns
\ttestflag testing flags
\ttestfunc testing functions
Use "go help <topic>" for more information about that topic.
'''
mock = mocker.patch('subprocess.Popen')
mock.return_value.stderr = BytesIO(stderr)
return mock
def test_match(build_misspelled_output):
<|code_end|>
, predict the next line using imports from the current file:
import pytest
from io import BytesIO
from thefuck.rules.go_unknown_command import match, get_new_command
from thefuck.types import Command
and context including class names, function names, and sometimes code from other files:
# Path: thefuck/rules/go_unknown_command.py
# @for_app('go')
# def match(command):
# return 'unknown command' in command.output
#
# def get_new_command(command):
# closest_subcommand = get_closest(command.script_parts[1], get_golang_commands())
# return replace_argument(command.script, command.script_parts[1],
# closest_subcommand)
#
# Path: thefuck/types.py
# class Command(object):
# """Command that should be fixed."""
#
# def __init__(self, script, output):
# """Initializes command with given values.
#
# :type script: basestring
# :type output: basestring
#
# """
# self.script = script
# self.output = output
#
# @property
# def stdout(self):
# logs.warn('`stdout` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def stderr(self):
# logs.warn('`stderr` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def script_parts(self):
# if not hasattr(self, '_script_parts'):
# try:
# self._script_parts = shell.split_command(self.script)
# except Exception:
# logs.debug(u"Can't split command script {} because:\n {}".format(
# self, sys.exc_info()))
# self._script_parts = []
#
# return self._script_parts
#
# def __eq__(self, other):
# if isinstance(other, Command):
# return (self.script, self.output) == (other.script, other.output)
# else:
# return False
#
# def __repr__(self):
# return u'Command(script={}, output={})'.format(
# self.script, self.output)
#
# def update(self, **kwargs):
# """Returns new command with replaced fields.
#
# :rtype: Command
#
# """
# kwargs.setdefault('script', self.script)
# kwargs.setdefault('output', self.output)
# return Command(**kwargs)
#
# @classmethod
# def from_raw_script(cls, raw_script):
# """Creates instance of `Command` from a list of script parts.
#
# :type raw_script: [basestring]
# :rtype: Command
# :raises: EmptyCommand
#
# """
# script = format_raw_script(raw_script)
# if not script:
# raise EmptyCommand
#
# expanded = shell.from_shell(script)
# output = get_output(script, expanded)
# return cls(expanded, output)
. Output only the next line. | assert match(Command('go bulid', build_misspelled_output)) |
Predict the next line for this snippet: <|code_start|>\tgopath GOPATH environment variable
\tgopath-get legacy GOPATH go get
\tgoproxy module proxy protocol
\timportpath import path syntax
\tmodules modules, module versions, and more
\tmodule-get module-aware go get
\tmodule-auth module authentication using go.sum
\tmodule-private module configuration for non-public modules
\tpackages package lists and patterns
\ttestflag testing flags
\ttestfunc testing functions
Use "go help <topic>" for more information about that topic.
'''
mock = mocker.patch('subprocess.Popen')
mock.return_value.stderr = BytesIO(stderr)
return mock
def test_match(build_misspelled_output):
assert match(Command('go bulid', build_misspelled_output))
def test_not_match():
assert not match(Command('go run', 'go run: no go files listed'))
@pytest.mark.usefixtures('no_memoize', 'go_stderr')
def test_get_new_command(build_misspelled_output):
<|code_end|>
with the help of current file imports:
import pytest
from io import BytesIO
from thefuck.rules.go_unknown_command import match, get_new_command
from thefuck.types import Command
and context from other files:
# Path: thefuck/rules/go_unknown_command.py
# @for_app('go')
# def match(command):
# return 'unknown command' in command.output
#
# def get_new_command(command):
# closest_subcommand = get_closest(command.script_parts[1], get_golang_commands())
# return replace_argument(command.script, command.script_parts[1],
# closest_subcommand)
#
# Path: thefuck/types.py
# class Command(object):
# """Command that should be fixed."""
#
# def __init__(self, script, output):
# """Initializes command with given values.
#
# :type script: basestring
# :type output: basestring
#
# """
# self.script = script
# self.output = output
#
# @property
# def stdout(self):
# logs.warn('`stdout` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def stderr(self):
# logs.warn('`stderr` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def script_parts(self):
# if not hasattr(self, '_script_parts'):
# try:
# self._script_parts = shell.split_command(self.script)
# except Exception:
# logs.debug(u"Can't split command script {} because:\n {}".format(
# self, sys.exc_info()))
# self._script_parts = []
#
# return self._script_parts
#
# def __eq__(self, other):
# if isinstance(other, Command):
# return (self.script, self.output) == (other.script, other.output)
# else:
# return False
#
# def __repr__(self):
# return u'Command(script={}, output={})'.format(
# self.script, self.output)
#
# def update(self, **kwargs):
# """Returns new command with replaced fields.
#
# :rtype: Command
#
# """
# kwargs.setdefault('script', self.script)
# kwargs.setdefault('output', self.output)
# return Command(**kwargs)
#
# @classmethod
# def from_raw_script(cls, raw_script):
# """Creates instance of `Command` from a list of script parts.
#
# :type raw_script: [basestring]
# :rtype: Command
# :raises: EmptyCommand
#
# """
# script = format_raw_script(raw_script)
# if not script:
# raise EmptyCommand
#
# expanded = shell.from_shell(script)
# output = get_output(script, expanded)
# return cls(expanded, output)
, which may contain function names, class names, or code. Output only the next line. | assert get_new_command(Command('go bulid', build_misspelled_output)) == 'go build' |
Next line prediction: <|code_start|>Additional help topics:
\tbuildconstraint build constraints
\tbuildmode build modes
\tc calling between Go and C
\tcache build and test caching
\tenvironment environment variables
\tfiletype file types
\tgo.mod the go.mod file
\tgopath GOPATH environment variable
\tgopath-get legacy GOPATH go get
\tgoproxy module proxy protocol
\timportpath import path syntax
\tmodules modules, module versions, and more
\tmodule-get module-aware go get
\tmodule-auth module authentication using go.sum
\tmodule-private module configuration for non-public modules
\tpackages package lists and patterns
\ttestflag testing flags
\ttestfunc testing functions
Use "go help <topic>" for more information about that topic.
'''
mock = mocker.patch('subprocess.Popen')
mock.return_value.stderr = BytesIO(stderr)
return mock
def test_match(build_misspelled_output):
<|code_end|>
. Use current file imports:
(import pytest
from io import BytesIO
from thefuck.rules.go_unknown_command import match, get_new_command
from thefuck.types import Command)
and context including class names, function names, or small code snippets from other files:
# Path: thefuck/rules/go_unknown_command.py
# @for_app('go')
# def match(command):
# return 'unknown command' in command.output
#
# def get_new_command(command):
# closest_subcommand = get_closest(command.script_parts[1], get_golang_commands())
# return replace_argument(command.script, command.script_parts[1],
# closest_subcommand)
#
# Path: thefuck/types.py
# class Command(object):
# """Command that should be fixed."""
#
# def __init__(self, script, output):
# """Initializes command with given values.
#
# :type script: basestring
# :type output: basestring
#
# """
# self.script = script
# self.output = output
#
# @property
# def stdout(self):
# logs.warn('`stdout` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def stderr(self):
# logs.warn('`stderr` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def script_parts(self):
# if not hasattr(self, '_script_parts'):
# try:
# self._script_parts = shell.split_command(self.script)
# except Exception:
# logs.debug(u"Can't split command script {} because:\n {}".format(
# self, sys.exc_info()))
# self._script_parts = []
#
# return self._script_parts
#
# def __eq__(self, other):
# if isinstance(other, Command):
# return (self.script, self.output) == (other.script, other.output)
# else:
# return False
#
# def __repr__(self):
# return u'Command(script={}, output={})'.format(
# self.script, self.output)
#
# def update(self, **kwargs):
# """Returns new command with replaced fields.
#
# :rtype: Command
#
# """
# kwargs.setdefault('script', self.script)
# kwargs.setdefault('output', self.output)
# return Command(**kwargs)
#
# @classmethod
# def from_raw_script(cls, raw_script):
# """Creates instance of `Command` from a list of script parts.
#
# :type raw_script: [basestring]
# :rtype: Command
# :raises: EmptyCommand
#
# """
# script = format_raw_script(raw_script)
# if not script:
# raise EmptyCommand
#
# expanded = shell.from_shell(script)
# output = get_output(script, expanded)
# return cls(expanded, output)
. Output only the next line. | assert match(Command('go bulid', build_misspelled_output)) |
Given the code snippet: <|code_start|> '\n'
'\n'
)
@pytest.fixture
def composer_not_command_one_of_this():
# that weird spacing is part of the actual command output
return (
'\n'
'\n'
' \n'
' [InvalidArgumentException] \n'
' Command "pdate" is not defined. \n'
' Did you mean one of these? \n'
' selfupdate \n'
' self-update \n'
' update \n'
' \n'
'\n'
'\n'
)
@pytest.fixture
def composer_require_instead_of_install():
return 'Invalid argument package. Use "composer require package" instead to add packages to your composer.json.'
def test_match(composer_not_command, composer_not_command_one_of_this, composer_require_instead_of_install):
<|code_end|>
, generate the next line using the imports in this file:
import pytest
from thefuck.rules.composer_not_command import match, get_new_command
from thefuck.types import Command
and context (functions, classes, or occasionally code) from other files:
# Path: thefuck/types.py
# class Command(object):
# """Command that should be fixed."""
#
# def __init__(self, script, output):
# """Initializes command with given values.
#
# :type script: basestring
# :type output: basestring
#
# """
# self.script = script
# self.output = output
#
# @property
# def stdout(self):
# logs.warn('`stdout` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def stderr(self):
# logs.warn('`stderr` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def script_parts(self):
# if not hasattr(self, '_script_parts'):
# try:
# self._script_parts = shell.split_command(self.script)
# except Exception:
# logs.debug(u"Can't split command script {} because:\n {}".format(
# self, sys.exc_info()))
# self._script_parts = []
#
# return self._script_parts
#
# def __eq__(self, other):
# if isinstance(other, Command):
# return (self.script, self.output) == (other.script, other.output)
# else:
# return False
#
# def __repr__(self):
# return u'Command(script={}, output={})'.format(
# self.script, self.output)
#
# def update(self, **kwargs):
# """Returns new command with replaced fields.
#
# :rtype: Command
#
# """
# kwargs.setdefault('script', self.script)
# kwargs.setdefault('output', self.output)
# return Command(**kwargs)
#
# @classmethod
# def from_raw_script(cls, raw_script):
# """Creates instance of `Command` from a list of script parts.
#
# :type raw_script: [basestring]
# :rtype: Command
# :raises: EmptyCommand
#
# """
# script = format_raw_script(raw_script)
# if not script:
# raise EmptyCommand
#
# expanded = shell.from_shell(script)
# output = get_output(script, expanded)
# return cls(expanded, output)
. Output only the next line. | assert match(Command('composer udpate', |
Predict the next line for this snippet: <|code_start|>
@pytest.fixture
def output():
return "error: Cannot delete branch 'foo' checked out at '/bar/foo'"
@pytest.mark.parametrize("script", ["git branch -d foo", "git branch -D foo"])
def test_match(script, output):
<|code_end|>
with the help of current file imports:
import pytest
from thefuck.rules.git_branch_delete_checked_out import match, get_new_command
from thefuck.types import Command
and context from other files:
# Path: thefuck/rules/git_branch_delete_checked_out.py
# @git_support
# def match(command):
# return (
# ("branch -d" in command.script or "branch -D" in command.script)
# and "error: Cannot delete branch '" in command.output
# and "' checked out at '" in command.output
# )
#
# @git_support
# def get_new_command(command):
# return shell.and_("git checkout master", "{}").format(
# replace_argument(command.script, "-d", "-D")
# )
#
# Path: thefuck/types.py
# class Command(object):
# """Command that should be fixed."""
#
# def __init__(self, script, output):
# """Initializes command with given values.
#
# :type script: basestring
# :type output: basestring
#
# """
# self.script = script
# self.output = output
#
# @property
# def stdout(self):
# logs.warn('`stdout` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def stderr(self):
# logs.warn('`stderr` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def script_parts(self):
# if not hasattr(self, '_script_parts'):
# try:
# self._script_parts = shell.split_command(self.script)
# except Exception:
# logs.debug(u"Can't split command script {} because:\n {}".format(
# self, sys.exc_info()))
# self._script_parts = []
#
# return self._script_parts
#
# def __eq__(self, other):
# if isinstance(other, Command):
# return (self.script, self.output) == (other.script, other.output)
# else:
# return False
#
# def __repr__(self):
# return u'Command(script={}, output={})'.format(
# self.script, self.output)
#
# def update(self, **kwargs):
# """Returns new command with replaced fields.
#
# :rtype: Command
#
# """
# kwargs.setdefault('script', self.script)
# kwargs.setdefault('output', self.output)
# return Command(**kwargs)
#
# @classmethod
# def from_raw_script(cls, raw_script):
# """Creates instance of `Command` from a list of script parts.
#
# :type raw_script: [basestring]
# :rtype: Command
# :raises: EmptyCommand
#
# """
# script = format_raw_script(raw_script)
# if not script:
# raise EmptyCommand
#
# expanded = shell.from_shell(script)
# output = get_output(script, expanded)
# return cls(expanded, output)
, which may contain function names, class names, or code. Output only the next line. | assert match(Command(script, output)) |
Given snippet: <|code_start|>
@pytest.fixture
def output():
return "error: Cannot delete branch 'foo' checked out at '/bar/foo'"
@pytest.mark.parametrize("script", ["git branch -d foo", "git branch -D foo"])
def test_match(script, output):
assert match(Command(script, output))
@pytest.mark.parametrize("script", ["git branch -d foo", "git branch -D foo"])
def test_not_match(script):
assert not match(Command(script, "Deleted branch foo (was a1b2c3d)."))
@pytest.mark.parametrize(
"script, new_command",
[
("git branch -d foo", "git checkout master && git branch -D foo"),
("git branch -D foo", "git checkout master && git branch -D foo"),
],
)
def test_get_new_command(script, new_command, output):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from thefuck.rules.git_branch_delete_checked_out import match, get_new_command
from thefuck.types import Command
and context:
# Path: thefuck/rules/git_branch_delete_checked_out.py
# @git_support
# def match(command):
# return (
# ("branch -d" in command.script or "branch -D" in command.script)
# and "error: Cannot delete branch '" in command.output
# and "' checked out at '" in command.output
# )
#
# @git_support
# def get_new_command(command):
# return shell.and_("git checkout master", "{}").format(
# replace_argument(command.script, "-d", "-D")
# )
#
# Path: thefuck/types.py
# class Command(object):
# """Command that should be fixed."""
#
# def __init__(self, script, output):
# """Initializes command with given values.
#
# :type script: basestring
# :type output: basestring
#
# """
# self.script = script
# self.output = output
#
# @property
# def stdout(self):
# logs.warn('`stdout` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def stderr(self):
# logs.warn('`stderr` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def script_parts(self):
# if not hasattr(self, '_script_parts'):
# try:
# self._script_parts = shell.split_command(self.script)
# except Exception:
# logs.debug(u"Can't split command script {} because:\n {}".format(
# self, sys.exc_info()))
# self._script_parts = []
#
# return self._script_parts
#
# def __eq__(self, other):
# if isinstance(other, Command):
# return (self.script, self.output) == (other.script, other.output)
# else:
# return False
#
# def __repr__(self):
# return u'Command(script={}, output={})'.format(
# self.script, self.output)
#
# def update(self, **kwargs):
# """Returns new command with replaced fields.
#
# :rtype: Command
#
# """
# kwargs.setdefault('script', self.script)
# kwargs.setdefault('output', self.output)
# return Command(**kwargs)
#
# @classmethod
# def from_raw_script(cls, raw_script):
# """Creates instance of `Command` from a list of script parts.
#
# :type raw_script: [basestring]
# :rtype: Command
# :raises: EmptyCommand
#
# """
# script = format_raw_script(raw_script)
# if not script:
# raise EmptyCommand
#
# expanded = shell.from_shell(script)
# output = get_output(script, expanded)
# return cls(expanded, output)
which might include code, classes, or functions. Output only the next line. | assert get_new_command(Command(script, output)) == new_command |
Based on the snippet: <|code_start|>
@pytest.fixture
def output():
return "error: Cannot delete branch 'foo' checked out at '/bar/foo'"
@pytest.mark.parametrize("script", ["git branch -d foo", "git branch -D foo"])
def test_match(script, output):
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
from thefuck.rules.git_branch_delete_checked_out import match, get_new_command
from thefuck.types import Command
and context (classes, functions, sometimes code) from other files:
# Path: thefuck/rules/git_branch_delete_checked_out.py
# @git_support
# def match(command):
# return (
# ("branch -d" in command.script or "branch -D" in command.script)
# and "error: Cannot delete branch '" in command.output
# and "' checked out at '" in command.output
# )
#
# @git_support
# def get_new_command(command):
# return shell.and_("git checkout master", "{}").format(
# replace_argument(command.script, "-d", "-D")
# )
#
# Path: thefuck/types.py
# class Command(object):
# """Command that should be fixed."""
#
# def __init__(self, script, output):
# """Initializes command with given values.
#
# :type script: basestring
# :type output: basestring
#
# """
# self.script = script
# self.output = output
#
# @property
# def stdout(self):
# logs.warn('`stdout` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def stderr(self):
# logs.warn('`stderr` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def script_parts(self):
# if not hasattr(self, '_script_parts'):
# try:
# self._script_parts = shell.split_command(self.script)
# except Exception:
# logs.debug(u"Can't split command script {} because:\n {}".format(
# self, sys.exc_info()))
# self._script_parts = []
#
# return self._script_parts
#
# def __eq__(self, other):
# if isinstance(other, Command):
# return (self.script, self.output) == (other.script, other.output)
# else:
# return False
#
# def __repr__(self):
# return u'Command(script={}, output={})'.format(
# self.script, self.output)
#
# def update(self, **kwargs):
# """Returns new command with replaced fields.
#
# :rtype: Command
#
# """
# kwargs.setdefault('script', self.script)
# kwargs.setdefault('output', self.output)
# return Command(**kwargs)
#
# @classmethod
# def from_raw_script(cls, raw_script):
# """Creates instance of `Command` from a list of script parts.
#
# :type raw_script: [basestring]
# :rtype: Command
# :raises: EmptyCommand
#
# """
# script = format_raw_script(raw_script)
# if not script:
# raise EmptyCommand
#
# expanded = shell.from_shell(script)
# output = get_output(script, expanded)
# return cls(expanded, output)
. Output only the next line. | assert match(Command(script, output)) |
Next line prediction: <|code_start|>
@pytest.fixture
def load_source(mocker):
return mocker.patch('thefuck.conf.load_source')
def test_settings_defaults(load_source, settings):
load_source.return_value = object()
settings.init()
<|code_end|>
. Use current file imports:
(import pytest
import six
import os
from mock import Mock
from thefuck import const)
and context including class names, function names, or small code snippets from other files:
# Path: thefuck/const.py
# class _GenConst(object):
# def __init__(self, name):
# def __repr__(self):
# KEY_UP = _GenConst('↑')
# KEY_DOWN = _GenConst('↓')
# KEY_CTRL_C = _GenConst('Ctrl+C')
# KEY_CTRL_N = _GenConst('Ctrl+N')
# KEY_CTRL_P = _GenConst('Ctrl+P')
# KEY_MAPPING = {'\x0e': KEY_CTRL_N,
# '\x03': KEY_CTRL_C,
# '\x10': KEY_CTRL_P}
# ACTION_SELECT = _GenConst('select')
# ACTION_ABORT = _GenConst('abort')
# ACTION_PREVIOUS = _GenConst('previous')
# ACTION_NEXT = _GenConst('next')
# ALL_ENABLED = _GenConst('All rules enabled')
# DEFAULT_RULES = [ALL_ENABLED]
# DEFAULT_PRIORITY = 1000
# DEFAULT_SETTINGS = {'rules': DEFAULT_RULES,
# 'exclude_rules': [],
# 'wait_command': 3,
# 'require_confirmation': True,
# 'no_colors': False,
# 'debug': False,
# 'priority': {},
# 'history_limit': None,
# 'alter_history': True,
# 'wait_slow_command': 15,
# 'slow_commands': ['lein', 'react-native', 'gradle',
# './gradlew', 'vagrant'],
# 'repeat': False,
# 'instant_mode': False,
# 'num_close_matches': 3,
# 'env': {'LC_ALL': 'C', 'LANG': 'C', 'GIT_TRACE': '1'},
# 'excluded_search_path_prefixes': []}
# ENV_TO_ATTR = {'THEFUCK_RULES': 'rules',
# 'THEFUCK_EXCLUDE_RULES': 'exclude_rules',
# 'THEFUCK_WAIT_COMMAND': 'wait_command',
# 'THEFUCK_REQUIRE_CONFIRMATION': 'require_confirmation',
# 'THEFUCK_NO_COLORS': 'no_colors',
# 'THEFUCK_DEBUG': 'debug',
# 'THEFUCK_PRIORITY': 'priority',
# 'THEFUCK_HISTORY_LIMIT': 'history_limit',
# 'THEFUCK_ALTER_HISTORY': 'alter_history',
# 'THEFUCK_WAIT_SLOW_COMMAND': 'wait_slow_command',
# 'THEFUCK_SLOW_COMMANDS': 'slow_commands',
# 'THEFUCK_REPEAT': 'repeat',
# 'THEFUCK_INSTANT_MODE': 'instant_mode',
# 'THEFUCK_NUM_CLOSE_MATCHES': 'num_close_matches',
# 'THEFUCK_EXCLUDED_SEARCH_PATH_PREFIXES': 'excluded_search_path_prefixes'}
# SETTINGS_HEADER = u"""# The Fuck settings file
# #
# # The rules are defined as in the example bellow:
# #
# # rules = ['cd_parent', 'git_push', 'python_command', 'sudo']
# #
# # The default values are as follows. Uncomment and change to fit your needs.
# # See https://github.com/nvbn/thefuck#settings for more information.
# #
#
# """
# ARGUMENT_PLACEHOLDER = 'THEFUCK_ARGUMENT_PLACEHOLDER'
# CONFIGURATION_TIMEOUT = 60
# USER_COMMAND_MARK = u'\u200B' * 10
# LOG_SIZE_IN_BYTES = 1024 * 1024
# LOG_SIZE_TO_CLEAN = 10 * 1024
# DIFF_WITH_ALIAS = 0.5
# SHELL_LOGGER_SOCKET_ENV = 'SHELL_LOGGER_SOCKET'
# SHELL_LOGGER_LIMIT = 5
. Output only the next line. | for key, val in const.DEFAULT_SETTINGS.items(): |
Given the following code snippet before the placeholder: <|code_start|>
def get_loaded_rules(rules_paths):
"""Yields all available rules.
:type rules_paths: [Path]
:rtype: Iterable[Rule]
"""
for path in rules_paths:
if path.name != '__init__.py':
rule = Rule.from_path(path)
if rule and rule.is_enabled:
yield rule
def get_rules_import_paths():
"""Yields all rules import paths.
:rtype: Iterable[Path]
"""
# Bundled rules:
yield Path(__file__).parent.joinpath('rules')
# Rules defined by user:
<|code_end|>
, predict the next line using imports from the current file:
import sys
from .conf import settings
from .types import Rule
from .system import Path
from . import logs
and context including class names, function names, and sometimes code from other files:
# Path: thefuck/conf.py
# class Settings(dict):
# def __getattr__(self, item):
# def __setattr__(self, key, value):
# def init(self, args=None):
# def _init_settings_file(self):
# def _get_user_dir_path(self):
# def _setup_user_dir(self):
# def _settings_from_file(self):
# def _rules_from_env(self, val):
# def _priority_from_env(self, val):
# def _val_from_env(self, env, attr):
# def _settings_from_env(self):
# def _settings_from_args(self, args):
#
# Path: thefuck/types.py
# class Rule(object):
# """Rule for fixing commands."""
#
# def __init__(self, name, match, get_new_command,
# enabled_by_default, side_effect,
# priority, requires_output):
# """Initializes rule with given fields.
#
# :type name: basestring
# :type match: (Command) -> bool
# :type get_new_command: (Command) -> (basestring | [basestring])
# :type enabled_by_default: boolean
# :type side_effect: (Command, basestring) -> None
# :type priority: int
# :type requires_output: bool
#
# """
# self.name = name
# self.match = match
# self.get_new_command = get_new_command
# self.enabled_by_default = enabled_by_default
# self.side_effect = side_effect
# self.priority = priority
# self.requires_output = requires_output
#
# def __eq__(self, other):
# if isinstance(other, Rule):
# return ((self.name, self.match, self.get_new_command,
# self.enabled_by_default, self.side_effect,
# self.priority, self.requires_output)
# == (other.name, other.match, other.get_new_command,
# other.enabled_by_default, other.side_effect,
# other.priority, other.requires_output))
# else:
# return False
#
# def __repr__(self):
# return 'Rule(name={}, match={}, get_new_command={}, ' \
# 'enabled_by_default={}, side_effect={}, ' \
# 'priority={}, requires_output={})'.format(
# self.name, self.match, self.get_new_command,
# self.enabled_by_default, self.side_effect,
# self.priority, self.requires_output)
#
# @classmethod
# def from_path(cls, path):
# """Creates rule instance from path.
#
# :type path: pathlib.Path
# :rtype: Rule
#
# """
# name = path.name[:-3]
# if name in settings.exclude_rules:
# logs.debug(u'Ignoring excluded rule: {}'.format(name))
# return
# with logs.debug_time(u'Importing rule: {};'.format(name)):
# try:
# rule_module = load_source(name, str(path))
# except Exception:
# logs.exception(u"Rule {} failed to load".format(name), sys.exc_info())
# return
# priority = getattr(rule_module, 'priority', DEFAULT_PRIORITY)
# return cls(name, rule_module.match,
# rule_module.get_new_command,
# getattr(rule_module, 'enabled_by_default', True),
# getattr(rule_module, 'side_effect', None),
# settings.priority.get(name, priority),
# getattr(rule_module, 'requires_output', True))
#
# @property
# def is_enabled(self):
# """Returns `True` when rule enabled.
#
# :rtype: bool
#
# """
# return (
# self.name in settings.rules
# or self.enabled_by_default
# and ALL_ENABLED in settings.rules
# )
#
# def is_match(self, command):
# """Returns `True` if rule matches the command.
#
# :type command: Command
# :rtype: bool
#
# """
# if command.output is None and self.requires_output:
# return False
#
# try:
# with logs.debug_time(u'Trying rule: {};'.format(self.name)):
# if self.match(command):
# return True
# except Exception:
# logs.rule_failed(self, sys.exc_info())
#
# def get_corrected_commands(self, command):
# """Returns generator with corrected commands.
#
# :type command: Command
# :rtype: Iterable[CorrectedCommand]
#
# """
# new_commands = self.get_new_command(command)
# if not isinstance(new_commands, list):
# new_commands = (new_commands,)
# for n, new_command in enumerate(new_commands):
# yield CorrectedCommand(script=new_command,
# side_effect=self.side_effect,
# priority=(n + 1) * self.priority)
. Output only the next line. | yield settings.user_dir.joinpath('rules') |
Given the code snippet: <|code_start|>
def get_loaded_rules(rules_paths):
"""Yields all available rules.
:type rules_paths: [Path]
:rtype: Iterable[Rule]
"""
for path in rules_paths:
if path.name != '__init__.py':
<|code_end|>
, generate the next line using the imports in this file:
import sys
from .conf import settings
from .types import Rule
from .system import Path
from . import logs
and context (functions, classes, or occasionally code) from other files:
# Path: thefuck/conf.py
# class Settings(dict):
# def __getattr__(self, item):
# def __setattr__(self, key, value):
# def init(self, args=None):
# def _init_settings_file(self):
# def _get_user_dir_path(self):
# def _setup_user_dir(self):
# def _settings_from_file(self):
# def _rules_from_env(self, val):
# def _priority_from_env(self, val):
# def _val_from_env(self, env, attr):
# def _settings_from_env(self):
# def _settings_from_args(self, args):
#
# Path: thefuck/types.py
# class Rule(object):
# """Rule for fixing commands."""
#
# def __init__(self, name, match, get_new_command,
# enabled_by_default, side_effect,
# priority, requires_output):
# """Initializes rule with given fields.
#
# :type name: basestring
# :type match: (Command) -> bool
# :type get_new_command: (Command) -> (basestring | [basestring])
# :type enabled_by_default: boolean
# :type side_effect: (Command, basestring) -> None
# :type priority: int
# :type requires_output: bool
#
# """
# self.name = name
# self.match = match
# self.get_new_command = get_new_command
# self.enabled_by_default = enabled_by_default
# self.side_effect = side_effect
# self.priority = priority
# self.requires_output = requires_output
#
# def __eq__(self, other):
# if isinstance(other, Rule):
# return ((self.name, self.match, self.get_new_command,
# self.enabled_by_default, self.side_effect,
# self.priority, self.requires_output)
# == (other.name, other.match, other.get_new_command,
# other.enabled_by_default, other.side_effect,
# other.priority, other.requires_output))
# else:
# return False
#
# def __repr__(self):
# return 'Rule(name={}, match={}, get_new_command={}, ' \
# 'enabled_by_default={}, side_effect={}, ' \
# 'priority={}, requires_output={})'.format(
# self.name, self.match, self.get_new_command,
# self.enabled_by_default, self.side_effect,
# self.priority, self.requires_output)
#
# @classmethod
# def from_path(cls, path):
# """Creates rule instance from path.
#
# :type path: pathlib.Path
# :rtype: Rule
#
# """
# name = path.name[:-3]
# if name in settings.exclude_rules:
# logs.debug(u'Ignoring excluded rule: {}'.format(name))
# return
# with logs.debug_time(u'Importing rule: {};'.format(name)):
# try:
# rule_module = load_source(name, str(path))
# except Exception:
# logs.exception(u"Rule {} failed to load".format(name), sys.exc_info())
# return
# priority = getattr(rule_module, 'priority', DEFAULT_PRIORITY)
# return cls(name, rule_module.match,
# rule_module.get_new_command,
# getattr(rule_module, 'enabled_by_default', True),
# getattr(rule_module, 'side_effect', None),
# settings.priority.get(name, priority),
# getattr(rule_module, 'requires_output', True))
#
# @property
# def is_enabled(self):
# """Returns `True` when rule enabled.
#
# :rtype: bool
#
# """
# return (
# self.name in settings.rules
# or self.enabled_by_default
# and ALL_ENABLED in settings.rules
# )
#
# def is_match(self, command):
# """Returns `True` if rule matches the command.
#
# :type command: Command
# :rtype: bool
#
# """
# if command.output is None and self.requires_output:
# return False
#
# try:
# with logs.debug_time(u'Trying rule: {};'.format(self.name)):
# if self.match(command):
# return True
# except Exception:
# logs.rule_failed(self, sys.exc_info())
#
# def get_corrected_commands(self, command):
# """Returns generator with corrected commands.
#
# :type command: Command
# :rtype: Iterable[CorrectedCommand]
#
# """
# new_commands = self.get_new_command(command)
# if not isinstance(new_commands, list):
# new_commands = (new_commands,)
# for n, new_command in enumerate(new_commands):
# yield CorrectedCommand(script=new_command,
# side_effect=self.side_effect,
# priority=(n + 1) * self.priority)
. Output only the next line. | rule = Rule.from_path(path) |
Given snippet: <|code_start|>
def test_match():
assert match(Command('cs', 'cs: command not found'))
assert match(Command('cs /etc/', 'cs: command not found'))
def test_get_new_command():
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from thefuck.rules.cd_cs import match, get_new_command
from thefuck.types import Command
and context:
# Path: thefuck/rules/cd_cs.py
# def match(command):
# if command.script_parts[0] == 'cs':
# return True
#
# def get_new_command(command):
# return 'cd' + ''.join(command.script[2:])
#
# Path: thefuck/types.py
# class Command(object):
# """Command that should be fixed."""
#
# def __init__(self, script, output):
# """Initializes command with given values.
#
# :type script: basestring
# :type output: basestring
#
# """
# self.script = script
# self.output = output
#
# @property
# def stdout(self):
# logs.warn('`stdout` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def stderr(self):
# logs.warn('`stderr` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def script_parts(self):
# if not hasattr(self, '_script_parts'):
# try:
# self._script_parts = shell.split_command(self.script)
# except Exception:
# logs.debug(u"Can't split command script {} because:\n {}".format(
# self, sys.exc_info()))
# self._script_parts = []
#
# return self._script_parts
#
# def __eq__(self, other):
# if isinstance(other, Command):
# return (self.script, self.output) == (other.script, other.output)
# else:
# return False
#
# def __repr__(self):
# return u'Command(script={}, output={})'.format(
# self.script, self.output)
#
# def update(self, **kwargs):
# """Returns new command with replaced fields.
#
# :rtype: Command
#
# """
# kwargs.setdefault('script', self.script)
# kwargs.setdefault('output', self.output)
# return Command(**kwargs)
#
# @classmethod
# def from_raw_script(cls, raw_script):
# """Creates instance of `Command` from a list of script parts.
#
# :type raw_script: [basestring]
# :rtype: Command
# :raises: EmptyCommand
#
# """
# script = format_raw_script(raw_script)
# if not script:
# raise EmptyCommand
#
# expanded = shell.from_shell(script)
# output = get_output(script, expanded)
# return cls(expanded, output)
which might include code, classes, or functions. Output only the next line. | assert get_new_command(Command('cs /etc/', 'cs: command not found')) == 'cd /etc/' |
Based on the snippet: <|code_start|> aliases = {}
proc = Popen(['fish', '-ic', 'alias'], stdout=PIPE, stderr=DEVNULL)
alias_out = proc.stdout.read().decode('utf-8').strip()
if not alias_out:
return aliases
for alias in alias_out.split('\n'):
for separator in (' ', '='):
split_alias = alias.replace('alias ', '', 1).split(separator, 1)
if len(split_alias) == 2:
name, value = split_alias
break
else:
continue
if name not in overridden:
aliases[name] = value
return aliases
class Fish(Generic):
friendly_name = 'Fish Shell'
def _get_overridden_aliases(self):
overridden = os.environ.get('THEFUCK_OVERRIDDEN_ALIASES',
os.environ.get('TF_OVERRIDDEN_ALIASES', ''))
default = {'cd', 'grep', 'ls', 'man', 'open'}
for alias in overridden.split(','):
default.add(alias.strip())
return sorted(default)
def app_alias(self, alias_name):
<|code_end|>
, predict the immediate next line with the help of imports:
from subprocess import Popen, PIPE
from time import time
from .. import logs
from ..conf import settings
from ..const import ARGUMENT_PLACEHOLDER
from ..utils import DEVNULL, cache
from .generic import Generic
import os
import sys
import six
and context (classes, functions, sometimes code) from other files:
# Path: thefuck/conf.py
# class Settings(dict):
# def __getattr__(self, item):
# def __setattr__(self, key, value):
# def init(self, args=None):
# def _init_settings_file(self):
# def _get_user_dir_path(self):
# def _setup_user_dir(self):
# def _settings_from_file(self):
# def _rules_from_env(self, val):
# def _priority_from_env(self, val):
# def _val_from_env(self, env, attr):
# def _settings_from_env(self):
# def _settings_from_args(self, args):
#
# Path: thefuck/const.py
# ARGUMENT_PLACEHOLDER = 'THEFUCK_ARGUMENT_PLACEHOLDER'
. Output only the next line. | if settings.alter_history: |
Based on the snippet: <|code_start|> aliases[name] = value
return aliases
class Fish(Generic):
friendly_name = 'Fish Shell'
def _get_overridden_aliases(self):
overridden = os.environ.get('THEFUCK_OVERRIDDEN_ALIASES',
os.environ.get('TF_OVERRIDDEN_ALIASES', ''))
default = {'cd', 'grep', 'ls', 'man', 'open'}
for alias in overridden.split(','):
default.add(alias.strip())
return sorted(default)
def app_alias(self, alias_name):
if settings.alter_history:
alter_history = (' builtin history delete --exact'
' --case-sensitive -- $fucked_up_command\n'
' builtin history merge\n')
else:
alter_history = ''
# It is VERY important to have the variables declared WITHIN the alias
return ('function {0} -d "Correct your previous console command"\n'
' set -l fucked_up_command $history[1]\n'
' env TF_SHELL=fish TF_ALIAS={0} PYTHONIOENCODING=utf-8'
' thefuck $fucked_up_command {2} $argv | read -l unfucked_command\n'
' if [ "$unfucked_command" != "" ]\n'
' eval $unfucked_command\n{1}'
' end\n'
<|code_end|>
, predict the immediate next line with the help of imports:
from subprocess import Popen, PIPE
from time import time
from .. import logs
from ..conf import settings
from ..const import ARGUMENT_PLACEHOLDER
from ..utils import DEVNULL, cache
from .generic import Generic
import os
import sys
import six
and context (classes, functions, sometimes code) from other files:
# Path: thefuck/conf.py
# class Settings(dict):
# def __getattr__(self, item):
# def __setattr__(self, key, value):
# def init(self, args=None):
# def _init_settings_file(self):
# def _get_user_dir_path(self):
# def _setup_user_dir(self):
# def _settings_from_file(self):
# def _rules_from_env(self, val):
# def _priority_from_env(self, val):
# def _val_from_env(self, env, attr):
# def _settings_from_env(self):
# def _settings_from_args(self, args):
#
# Path: thefuck/const.py
# ARGUMENT_PLACEHOLDER = 'THEFUCK_ARGUMENT_PLACEHOLDER'
. Output only the next line. | 'end').format(alias_name, alter_history, ARGUMENT_PLACEHOLDER) |
Predict the next line for this snippet: <|code_start|> self.requires_output = requires_output
def __eq__(self, other):
if isinstance(other, Rule):
return ((self.name, self.match, self.get_new_command,
self.enabled_by_default, self.side_effect,
self.priority, self.requires_output)
== (other.name, other.match, other.get_new_command,
other.enabled_by_default, other.side_effect,
other.priority, other.requires_output))
else:
return False
def __repr__(self):
return 'Rule(name={}, match={}, get_new_command={}, ' \
'enabled_by_default={}, side_effect={}, ' \
'priority={}, requires_output={})'.format(
self.name, self.match, self.get_new_command,
self.enabled_by_default, self.side_effect,
self.priority, self.requires_output)
@classmethod
def from_path(cls, path):
"""Creates rule instance from path.
:type path: pathlib.Path
:rtype: Rule
"""
name = path.name[:-3]
<|code_end|>
with the help of current file imports:
from imp import load_source
from . import logs
from .shells import shell
from .conf import settings
from .const import DEFAULT_PRIORITY, ALL_ENABLED
from .exceptions import EmptyCommand
from .utils import get_alias, format_raw_script
from .output_readers import get_output
import os
import sys
and context from other files:
# Path: thefuck/conf.py
# class Settings(dict):
# def __getattr__(self, item):
# def __setattr__(self, key, value):
# def init(self, args=None):
# def _init_settings_file(self):
# def _get_user_dir_path(self):
# def _setup_user_dir(self):
# def _settings_from_file(self):
# def _rules_from_env(self, val):
# def _priority_from_env(self, val):
# def _val_from_env(self, env, attr):
# def _settings_from_env(self):
# def _settings_from_args(self, args):
#
# Path: thefuck/const.py
# DEFAULT_PRIORITY = 1000
#
# ALL_ENABLED = _GenConst('All rules enabled')
, which may contain function names, class names, or code. Output only the next line. | if name in settings.exclude_rules: |
Given the following code snippet before the placeholder: <|code_start|> other.priority, other.requires_output))
else:
return False
def __repr__(self):
return 'Rule(name={}, match={}, get_new_command={}, ' \
'enabled_by_default={}, side_effect={}, ' \
'priority={}, requires_output={})'.format(
self.name, self.match, self.get_new_command,
self.enabled_by_default, self.side_effect,
self.priority, self.requires_output)
@classmethod
def from_path(cls, path):
"""Creates rule instance from path.
:type path: pathlib.Path
:rtype: Rule
"""
name = path.name[:-3]
if name in settings.exclude_rules:
logs.debug(u'Ignoring excluded rule: {}'.format(name))
return
with logs.debug_time(u'Importing rule: {};'.format(name)):
try:
rule_module = load_source(name, str(path))
except Exception:
logs.exception(u"Rule {} failed to load".format(name), sys.exc_info())
return
<|code_end|>
, predict the next line using imports from the current file:
from imp import load_source
from . import logs
from .shells import shell
from .conf import settings
from .const import DEFAULT_PRIORITY, ALL_ENABLED
from .exceptions import EmptyCommand
from .utils import get_alias, format_raw_script
from .output_readers import get_output
import os
import sys
and context including class names, function names, and sometimes code from other files:
# Path: thefuck/conf.py
# class Settings(dict):
# def __getattr__(self, item):
# def __setattr__(self, key, value):
# def init(self, args=None):
# def _init_settings_file(self):
# def _get_user_dir_path(self):
# def _setup_user_dir(self):
# def _settings_from_file(self):
# def _rules_from_env(self, val):
# def _priority_from_env(self, val):
# def _val_from_env(self, env, attr):
# def _settings_from_env(self):
# def _settings_from_args(self, args):
#
# Path: thefuck/const.py
# DEFAULT_PRIORITY = 1000
#
# ALL_ENABLED = _GenConst('All rules enabled')
. Output only the next line. | priority = getattr(rule_module, 'priority', DEFAULT_PRIORITY) |
Predict the next line after this snippet: <|code_start|>
"""
name = path.name[:-3]
if name in settings.exclude_rules:
logs.debug(u'Ignoring excluded rule: {}'.format(name))
return
with logs.debug_time(u'Importing rule: {};'.format(name)):
try:
rule_module = load_source(name, str(path))
except Exception:
logs.exception(u"Rule {} failed to load".format(name), sys.exc_info())
return
priority = getattr(rule_module, 'priority', DEFAULT_PRIORITY)
return cls(name, rule_module.match,
rule_module.get_new_command,
getattr(rule_module, 'enabled_by_default', True),
getattr(rule_module, 'side_effect', None),
settings.priority.get(name, priority),
getattr(rule_module, 'requires_output', True))
@property
def is_enabled(self):
"""Returns `True` when rule enabled.
:rtype: bool
"""
return (
self.name in settings.rules
or self.enabled_by_default
<|code_end|>
using the current file's imports:
from imp import load_source
from . import logs
from .shells import shell
from .conf import settings
from .const import DEFAULT_PRIORITY, ALL_ENABLED
from .exceptions import EmptyCommand
from .utils import get_alias, format_raw_script
from .output_readers import get_output
import os
import sys
and any relevant context from other files:
# Path: thefuck/conf.py
# class Settings(dict):
# def __getattr__(self, item):
# def __setattr__(self, key, value):
# def init(self, args=None):
# def _init_settings_file(self):
# def _get_user_dir_path(self):
# def _setup_user_dir(self):
# def _settings_from_file(self):
# def _rules_from_env(self, val):
# def _priority_from_env(self, val):
# def _val_from_env(self, env, attr):
# def _settings_from_env(self):
# def _settings_from_args(self, args):
#
# Path: thefuck/const.py
# DEFAULT_PRIORITY = 1000
#
# ALL_ENABLED = _GenConst('All rules enabled')
. Output only the next line. | and ALL_ENABLED in settings.rules |
Given snippet: <|code_start|>
@pytest.fixture
def mistype_response():
return """
CommandNotFoundError: No command 'conda lst'.
Did you mean 'conda list'?
"""
def test_match(mistype_response):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from thefuck.rules.conda_mistype import match, get_new_command
from thefuck.types import Command
and context:
# Path: thefuck/types.py
# class Command(object):
# """Command that should be fixed."""
#
# def __init__(self, script, output):
# """Initializes command with given values.
#
# :type script: basestring
# :type output: basestring
#
# """
# self.script = script
# self.output = output
#
# @property
# def stdout(self):
# logs.warn('`stdout` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def stderr(self):
# logs.warn('`stderr` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def script_parts(self):
# if not hasattr(self, '_script_parts'):
# try:
# self._script_parts = shell.split_command(self.script)
# except Exception:
# logs.debug(u"Can't split command script {} because:\n {}".format(
# self, sys.exc_info()))
# self._script_parts = []
#
# return self._script_parts
#
# def __eq__(self, other):
# if isinstance(other, Command):
# return (self.script, self.output) == (other.script, other.output)
# else:
# return False
#
# def __repr__(self):
# return u'Command(script={}, output={})'.format(
# self.script, self.output)
#
# def update(self, **kwargs):
# """Returns new command with replaced fields.
#
# :rtype: Command
#
# """
# kwargs.setdefault('script', self.script)
# kwargs.setdefault('output', self.output)
# return Command(**kwargs)
#
# @classmethod
# def from_raw_script(cls, raw_script):
# """Creates instance of `Command` from a list of script parts.
#
# :type raw_script: [basestring]
# :rtype: Command
# :raises: EmptyCommand
#
# """
# script = format_raw_script(raw_script)
# if not script:
# raise EmptyCommand
#
# expanded = shell.from_shell(script)
# output = get_output(script, expanded)
# return cls(expanded, output)
which might include code, classes, or functions. Output only the next line. | assert match(Command('conda lst', mistype_response)) |
Given the code snippet: <|code_start|>
@pytest.mark.parametrize(
"script, output",
[
('git commit -m "test"', "no changes added to commit"),
("git commit", "no changes added to commit"),
],
)
def test_match(output, script):
<|code_end|>
, generate the next line using the imports in this file:
import pytest
from thefuck.rules.git_commit_add import match, get_new_command
from thefuck.types import Command
and context (functions, classes, or occasionally code) from other files:
# Path: thefuck/rules/git_commit_add.py
# @git_support
# def match(command):
# return (
# "commit" in command.script_parts
# and "no changes added to commit" in command.output
# )
#
# @eager
# @git_support
# def get_new_command(command):
# for opt in ("-a", "-p"):
# yield replace_argument(command.script, "commit", "commit {}".format(opt))
#
# Path: thefuck/types.py
# class Command(object):
# """Command that should be fixed."""
#
# def __init__(self, script, output):
# """Initializes command with given values.
#
# :type script: basestring
# :type output: basestring
#
# """
# self.script = script
# self.output = output
#
# @property
# def stdout(self):
# logs.warn('`stdout` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def stderr(self):
# logs.warn('`stderr` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def script_parts(self):
# if not hasattr(self, '_script_parts'):
# try:
# self._script_parts = shell.split_command(self.script)
# except Exception:
# logs.debug(u"Can't split command script {} because:\n {}".format(
# self, sys.exc_info()))
# self._script_parts = []
#
# return self._script_parts
#
# def __eq__(self, other):
# if isinstance(other, Command):
# return (self.script, self.output) == (other.script, other.output)
# else:
# return False
#
# def __repr__(self):
# return u'Command(script={}, output={})'.format(
# self.script, self.output)
#
# def update(self, **kwargs):
# """Returns new command with replaced fields.
#
# :rtype: Command
#
# """
# kwargs.setdefault('script', self.script)
# kwargs.setdefault('output', self.output)
# return Command(**kwargs)
#
# @classmethod
# def from_raw_script(cls, raw_script):
# """Creates instance of `Command` from a list of script parts.
#
# :type raw_script: [basestring]
# :rtype: Command
# :raises: EmptyCommand
#
# """
# script = format_raw_script(raw_script)
# if not script:
# raise EmptyCommand
#
# expanded = shell.from_shell(script)
# output = get_output(script, expanded)
# return cls(expanded, output)
. Output only the next line. | assert match(Command(script, output)) |
Next line prediction: <|code_start|> [
('git commit -m "test"', "no changes added to commit"),
("git commit", "no changes added to commit"),
],
)
def test_match(output, script):
assert match(Command(script, output))
@pytest.mark.parametrize(
"script, output",
[
('git commit -m "test"', " 1 file changed, 15 insertions(+), 14 deletions(-)"),
("git branch foo", ""),
("git checkout feature/test_commit", ""),
("git push", ""),
],
)
def test_not_match(output, script):
assert not match(Command(script, output))
@pytest.mark.parametrize(
"script, new_command",
[
("git commit", ["git commit -a", "git commit -p"]),
('git commit -m "foo"', ['git commit -a -m "foo"', 'git commit -p -m "foo"']),
],
)
def test_get_new_command(script, new_command):
<|code_end|>
. Use current file imports:
(import pytest
from thefuck.rules.git_commit_add import match, get_new_command
from thefuck.types import Command)
and context including class names, function names, or small code snippets from other files:
# Path: thefuck/rules/git_commit_add.py
# @git_support
# def match(command):
# return (
# "commit" in command.script_parts
# and "no changes added to commit" in command.output
# )
#
# @eager
# @git_support
# def get_new_command(command):
# for opt in ("-a", "-p"):
# yield replace_argument(command.script, "commit", "commit {}".format(opt))
#
# Path: thefuck/types.py
# class Command(object):
# """Command that should be fixed."""
#
# def __init__(self, script, output):
# """Initializes command with given values.
#
# :type script: basestring
# :type output: basestring
#
# """
# self.script = script
# self.output = output
#
# @property
# def stdout(self):
# logs.warn('`stdout` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def stderr(self):
# logs.warn('`stderr` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def script_parts(self):
# if not hasattr(self, '_script_parts'):
# try:
# self._script_parts = shell.split_command(self.script)
# except Exception:
# logs.debug(u"Can't split command script {} because:\n {}".format(
# self, sys.exc_info()))
# self._script_parts = []
#
# return self._script_parts
#
# def __eq__(self, other):
# if isinstance(other, Command):
# return (self.script, self.output) == (other.script, other.output)
# else:
# return False
#
# def __repr__(self):
# return u'Command(script={}, output={})'.format(
# self.script, self.output)
#
# def update(self, **kwargs):
# """Returns new command with replaced fields.
#
# :rtype: Command
#
# """
# kwargs.setdefault('script', self.script)
# kwargs.setdefault('output', self.output)
# return Command(**kwargs)
#
# @classmethod
# def from_raw_script(cls, raw_script):
# """Creates instance of `Command` from a list of script parts.
#
# :type raw_script: [basestring]
# :rtype: Command
# :raises: EmptyCommand
#
# """
# script = format_raw_script(raw_script)
# if not script:
# raise EmptyCommand
#
# expanded = shell.from_shell(script)
# output = get_output(script, expanded)
# return cls(expanded, output)
. Output only the next line. | assert get_new_command(Command(script, "")) == new_command |
Given the code snippet: <|code_start|>
@pytest.mark.parametrize(
"script, output",
[
('git commit -m "test"', "no changes added to commit"),
("git commit", "no changes added to commit"),
],
)
def test_match(output, script):
<|code_end|>
, generate the next line using the imports in this file:
import pytest
from thefuck.rules.git_commit_add import match, get_new_command
from thefuck.types import Command
and context (functions, classes, or occasionally code) from other files:
# Path: thefuck/rules/git_commit_add.py
# @git_support
# def match(command):
# return (
# "commit" in command.script_parts
# and "no changes added to commit" in command.output
# )
#
# @eager
# @git_support
# def get_new_command(command):
# for opt in ("-a", "-p"):
# yield replace_argument(command.script, "commit", "commit {}".format(opt))
#
# Path: thefuck/types.py
# class Command(object):
# """Command that should be fixed."""
#
# def __init__(self, script, output):
# """Initializes command with given values.
#
# :type script: basestring
# :type output: basestring
#
# """
# self.script = script
# self.output = output
#
# @property
# def stdout(self):
# logs.warn('`stdout` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def stderr(self):
# logs.warn('`stderr` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def script_parts(self):
# if not hasattr(self, '_script_parts'):
# try:
# self._script_parts = shell.split_command(self.script)
# except Exception:
# logs.debug(u"Can't split command script {} because:\n {}".format(
# self, sys.exc_info()))
# self._script_parts = []
#
# return self._script_parts
#
# def __eq__(self, other):
# if isinstance(other, Command):
# return (self.script, self.output) == (other.script, other.output)
# else:
# return False
#
# def __repr__(self):
# return u'Command(script={}, output={})'.format(
# self.script, self.output)
#
# def update(self, **kwargs):
# """Returns new command with replaced fields.
#
# :rtype: Command
#
# """
# kwargs.setdefault('script', self.script)
# kwargs.setdefault('output', self.output)
# return Command(**kwargs)
#
# @classmethod
# def from_raw_script(cls, raw_script):
# """Creates instance of `Command` from a list of script parts.
#
# :type raw_script: [basestring]
# :rtype: Command
# :raises: EmptyCommand
#
# """
# script = format_raw_script(raw_script)
# if not script:
# raise EmptyCommand
#
# expanded = shell.from_shell(script)
# output = get_output(script, expanded)
# return cls(expanded, output)
. Output only the next line. | assert match(Command(script, output)) |
Next line prediction: <|code_start|>
output = 'merge: local - not something we can merge\n\n' \
'Did you mean this?\n\tremote/local'
def test_match():
<|code_end|>
. Use current file imports:
(import pytest
from thefuck.rules.git_merge import match, get_new_command
from thefuck.types import Command)
and context including class names, function names, or small code snippets from other files:
# Path: thefuck/types.py
# class Command(object):
# """Command that should be fixed."""
#
# def __init__(self, script, output):
# """Initializes command with given values.
#
# :type script: basestring
# :type output: basestring
#
# """
# self.script = script
# self.output = output
#
# @property
# def stdout(self):
# logs.warn('`stdout` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def stderr(self):
# logs.warn('`stderr` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def script_parts(self):
# if not hasattr(self, '_script_parts'):
# try:
# self._script_parts = shell.split_command(self.script)
# except Exception:
# logs.debug(u"Can't split command script {} because:\n {}".format(
# self, sys.exc_info()))
# self._script_parts = []
#
# return self._script_parts
#
# def __eq__(self, other):
# if isinstance(other, Command):
# return (self.script, self.output) == (other.script, other.output)
# else:
# return False
#
# def __repr__(self):
# return u'Command(script={}, output={})'.format(
# self.script, self.output)
#
# def update(self, **kwargs):
# """Returns new command with replaced fields.
#
# :rtype: Command
#
# """
# kwargs.setdefault('script', self.script)
# kwargs.setdefault('output', self.output)
# return Command(**kwargs)
#
# @classmethod
# def from_raw_script(cls, raw_script):
# """Creates instance of `Command` from a list of script parts.
#
# :type raw_script: [basestring]
# :rtype: Command
# :raises: EmptyCommand
#
# """
# script = format_raw_script(raw_script)
# if not script:
# raise EmptyCommand
#
# expanded = shell.from_shell(script)
# output = get_output(script, expanded)
# return cls(expanded, output)
. Output only the next line. | assert match(Command('git merge test', output)) |
Given the following code snippet before the placeholder: <|code_start|>
def test_and_(self, shell):
assert shell.and_('foo', 'bar') == 'foo; and bar'
def test_or_(self, shell):
assert shell.or_('foo', 'bar') == 'foo; or bar'
def test_get_aliases(self, shell):
assert shell.get_aliases() == {'fish_config': 'fish_config',
'fuck': 'fuck',
'funced': 'funced',
'funcsave': 'funcsave',
'history': 'history',
'll': 'll',
'math': 'math',
'popd': 'popd',
'pushd': 'pushd',
'ruby': 'ruby',
'g': 'git',
'fish_key_reader': '/usr/bin/fish_key_reader',
'alias_with_equal_sign': 'echo'}
assert shell.get_aliases() == {'func1': 'func1', 'func2': 'func2'}
def test_app_alias(self, shell):
assert 'function fuck' in shell.app_alias('fuck')
assert 'function FUCK' in shell.app_alias('FUCK')
assert 'thefuck' in shell.app_alias('fuck')
assert 'TF_SHELL=fish' in shell.app_alias('fuck')
assert 'TF_ALIAS=fuck PYTHONIOENCODING' in shell.app_alias('fuck')
assert 'PYTHONIOENCODING=utf-8 thefuck' in shell.app_alias('fuck')
<|code_end|>
, predict the next line using imports from the current file:
import pytest
from thefuck.const import ARGUMENT_PLACEHOLDER
from thefuck.shells import Fish
and context including class names, function names, and sometimes code from other files:
# Path: thefuck/const.py
# ARGUMENT_PLACEHOLDER = 'THEFUCK_ARGUMENT_PLACEHOLDER'
. Output only the next line. | assert ARGUMENT_PLACEHOLDER in shell.app_alias('fuck') |
Given the following code snippet before the placeholder: <|code_start|>
@pytest.fixture
def output(branch_name):
if not branch_name:
return ""
output_str = u"error: pathspec '{}' did not match any file(s) known to git"
return output_str.format(branch_name)
@pytest.mark.parametrize(
"script, branch_name",
[
("git checkout main", "main"),
("git checkout master", "master"),
("git show main", "main"),
],
)
def test_match(script, branch_name, output):
<|code_end|>
, predict the next line using imports from the current file:
import pytest
from thefuck.rules.git_main_master import match, get_new_command
from thefuck.types import Command
and context including class names, function names, and sometimes code from other files:
# Path: thefuck/rules/git_main_master.py
# @git_support
# def match(command):
# return "'master'" in command.output or "'main'" in command.output
#
# @git_support
# def get_new_command(command):
# if "'master'" in command.output:
# return command.script.replace("master", "main")
# return command.script.replace("main", "master")
#
# Path: thefuck/types.py
# class Command(object):
# """Command that should be fixed."""
#
# def __init__(self, script, output):
# """Initializes command with given values.
#
# :type script: basestring
# :type output: basestring
#
# """
# self.script = script
# self.output = output
#
# @property
# def stdout(self):
# logs.warn('`stdout` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def stderr(self):
# logs.warn('`stderr` is deprecated, please use `output` instead')
# return self.output
#
# @property
# def script_parts(self):
# if not hasattr(self, '_script_parts'):
# try:
# self._script_parts = shell.split_command(self.script)
# except Exception:
# logs.debug(u"Can't split command script {} because:\n {}".format(
# self, sys.exc_info()))
# self._script_parts = []
#
# return self._script_parts
#
# def __eq__(self, other):
# if isinstance(other, Command):
# return (self.script, self.output) == (other.script, other.output)
# else:
# return False
#
# def __repr__(self):
# return u'Command(script={}, output={})'.format(
# self.script, self.output)
#
# def update(self, **kwargs):
# """Returns new command with replaced fields.
#
# :rtype: Command
#
# """
# kwargs.setdefault('script', self.script)
# kwargs.setdefault('output', self.output)
# return Command(**kwargs)
#
# @classmethod
# def from_raw_script(cls, raw_script):
# """Creates instance of `Command` from a list of script parts.
#
# :type raw_script: [basestring]
# :rtype: Command
# :raises: EmptyCommand
#
# """
# script = format_raw_script(raw_script)
# if not script:
# raise EmptyCommand
#
# expanded = shell.from_shell(script)
# output = get_output(script, expanded)
# return cls(expanded, output)
. Output only the next line. | assert match(Command(script, output)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.