Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Based on the snippet: <|code_start|>from __future__ import annotations
# Input, expected return value, expected output
TESTS = (
(b'foo\n', 0, b'foo\n'),
(b'', 0, b''),
(b'\n\n', 1, b''),
(b'\n\n\n\n', 1, b''),
(b'foo', 1, b'foo\n'),
(b'foo\n\n\n', 1, b'foo\n'),
(b'\xe2\x98\x83', 1, b'\xe2\x98\x83\n'),
(b'foo\r\n', 0, b'foo\r\n'),
(b'foo\r\n\r\n\r\n', 1, b'foo\r\n'),
(b'foo\r', 0, b'foo\r'),
<|code_end|>
, predict the immediate next line with the help of imports:
import io
import pytest
from pre_commit_hooks.end_of_file_fixer import fix_file
from pre_commit_hooks.end_of_file_fixer import main
and context (classes, functions, sometimes code) from other files:
# Path: pre_commit_hooks/end_of_file_fixer.py
# def fix_file(file_obj: IO[bytes]) -> int:
# # Test for newline at end of file
# # Empty files will throw IOError here
# try:
# file_obj.seek(-1, os.SEEK_END)
# except OSError:
# return 0
# last_character = file_obj.read(1)
# # last_character will be '' for an empty file
# if last_character not in {b'\n', b'\r'} and last_character != b'':
# # Needs this seek for windows, otherwise IOError
# file_obj.seek(0, os.SEEK_END)
# file_obj.write(b'\n')
# return 1
#
# while last_character in {b'\n', b'\r'}:
# # Deal with the beginning of the file
# if file_obj.tell() == 1:
# # If we've reached the beginning of the file and it is all
# # linebreaks then we can make this file empty
# file_obj.seek(0)
# file_obj.truncate()
# return 1
#
# # Go back two bytes and read a character
# file_obj.seek(-2, os.SEEK_CUR)
# last_character = file_obj.read(1)
#
# # Our current position is at the end of the file just before any amount of
# # newlines. If we find extraneous newlines, then backtrack and trim them.
# position = file_obj.tell()
# remaining = file_obj.read()
# for sequence in (b'\n', b'\r\n', b'\r'):
# if remaining == sequence:
# return 0
# elif remaining.startswith(sequence):
# file_obj.seek(position + len(sequence))
# file_obj.truncate()
# return 1
#
# return 0
#
# Path: pre_commit_hooks/end_of_file_fixer.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='*', help='Filenames to fix')
# args = parser.parse_args(argv)
#
# retv = 0
#
# for filename in args.filenames:
# # Read as binary so we can read byte-by-byte
# with open(filename, 'rb+') as file_obj:
# ret_for_file = fix_file(file_obj)
# if ret_for_file:
# print(f'Fixing {filename}')
# retv |= ret_for_file
#
# return retv
. Output only the next line. | (b'foo\r\r\r\r', 1, b'foo\r'), |
Based on the snippet: <|code_start|>from __future__ import annotations
# Input, expected return value, expected output
TESTS = (
(b'foo\n', 0, b'foo\n'),
<|code_end|>
, predict the immediate next line with the help of imports:
import io
import pytest
from pre_commit_hooks.end_of_file_fixer import fix_file
from pre_commit_hooks.end_of_file_fixer import main
and context (classes, functions, sometimes code) from other files:
# Path: pre_commit_hooks/end_of_file_fixer.py
# def fix_file(file_obj: IO[bytes]) -> int:
# # Test for newline at end of file
# # Empty files will throw IOError here
# try:
# file_obj.seek(-1, os.SEEK_END)
# except OSError:
# return 0
# last_character = file_obj.read(1)
# # last_character will be '' for an empty file
# if last_character not in {b'\n', b'\r'} and last_character != b'':
# # Needs this seek for windows, otherwise IOError
# file_obj.seek(0, os.SEEK_END)
# file_obj.write(b'\n')
# return 1
#
# while last_character in {b'\n', b'\r'}:
# # Deal with the beginning of the file
# if file_obj.tell() == 1:
# # If we've reached the beginning of the file and it is all
# # linebreaks then we can make this file empty
# file_obj.seek(0)
# file_obj.truncate()
# return 1
#
# # Go back two bytes and read a character
# file_obj.seek(-2, os.SEEK_CUR)
# last_character = file_obj.read(1)
#
# # Our current position is at the end of the file just before any amount of
# # newlines. If we find extraneous newlines, then backtrack and trim them.
# position = file_obj.tell()
# remaining = file_obj.read()
# for sequence in (b'\n', b'\r\n', b'\r'):
# if remaining == sequence:
# return 0
# elif remaining.startswith(sequence):
# file_obj.seek(position + len(sequence))
# file_obj.truncate()
# return 1
#
# return 0
#
# Path: pre_commit_hooks/end_of_file_fixer.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='*', help='Filenames to fix')
# args = parser.parse_args(argv)
#
# retv = 0
#
# for filename in args.filenames:
# # Read as binary so we can read byte-by-byte
# with open(filename, 'rb+') as file_obj:
# ret_for_file = fix_file(file_obj)
# if ret_for_file:
# print(f'Fixing {filename}')
# retv |= ret_for_file
#
# return retv
. Output only the next line. | (b'', 0, b''), |
Given snippet: <|code_start|>from __future__ import annotations
@pytest.mark.parametrize(
('filename', 'expected_retval'), (
('bad_yaml.notyaml', 1),
('ok_yaml.yaml', 0),
),
)
def test_main(filename, expected_retval):
ret = main([get_resource_path(filename)])
assert ret == expected_retval
def test_main_allow_multiple_documents(tmpdir):
f = tmpdir.join('test.yaml')
f.write('---\nfoo\n---\nbar\n')
# should fail without the setting
assert main((str(f),))
# should pass when we allow multiple documents
assert not main(('--allow-multiple-documents', str(f)))
def test_fails_even_with_allow_multiple_documents(tmpdir):
f = tmpdir.join('test.yaml')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from pre_commit_hooks.check_yaml import main
from testing.util import get_resource_path
and context:
# Path: pre_commit_hooks/check_yaml.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument(
# '-m', '--multi', '--allow-multiple-documents', action='store_true',
# )
# parser.add_argument(
# '--unsafe', action='store_true',
# help=(
# 'Instead of loading the files, simply parse them for syntax. '
# 'A syntax-only check enables extensions and unsafe contstructs '
# 'which would otherwise be forbidden. Using this option removes '
# 'all guarantees of portability to other yaml implementations. '
# 'Implies --allow-multiple-documents'
# ),
# )
# parser.add_argument('filenames', nargs='*', help='Filenames to check.')
# args = parser.parse_args(argv)
#
# load_fn = LOAD_FNS[Key(multi=args.multi, unsafe=args.unsafe)]
#
# retval = 0
# for filename in args.filenames:
# try:
# with open(filename, encoding='UTF-8') as f:
# load_fn(f)
# except ruamel.yaml.YAMLError as exc:
# print(exc)
# retval = 1
# return retval
#
# Path: testing/util.py
# def get_resource_path(path):
# return os.path.join(TESTING_DIR, 'resources', path)
which might include code, classes, or functions. Output only the next line. | f.write('[') |
Based on the snippet: <|code_start|>from __future__ import annotations
def test_raises_on_error():
with pytest.raises(CalledProcessError):
cmd_output('sh', '-c', 'exit 1')
def test_output():
ret = cmd_output('sh', '-c', 'echo hi')
assert ret == 'hi\n'
@pytest.mark.parametrize('out', ('\0f1\0f2\0', '\0f1\0f2', 'f1\0f2\0'))
def test_check_zsplits_str_correctly(out):
assert zsplit(out) == ['f1', 'f2']
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
from pre_commit_hooks.util import CalledProcessError
from pre_commit_hooks.util import cmd_output
from pre_commit_hooks.util import zsplit
and context (classes, functions, sometimes code) from other files:
# Path: pre_commit_hooks/util.py
# class CalledProcessError(RuntimeError):
# pass
#
# Path: pre_commit_hooks/util.py
# def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str:
# kwargs.setdefault('stdout', subprocess.PIPE)
# kwargs.setdefault('stderr', subprocess.PIPE)
# proc = subprocess.Popen(cmd, **kwargs)
# stdout, stderr = proc.communicate()
# stdout = stdout.decode()
# if retcode is not None and proc.returncode != retcode:
# raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr)
# return stdout
#
# Path: pre_commit_hooks/util.py
# def zsplit(s: str) -> list[str]:
# s = s.strip('\0')
# if s:
# return s.split('\0')
# else:
# return []
. Output only the next line. | @pytest.mark.parametrize('out', ('\0\0', '\0', '')) |
Given the code snippet: <|code_start|>from __future__ import annotations
def test_raises_on_error():
with pytest.raises(CalledProcessError):
cmd_output('sh', '-c', 'exit 1')
def test_output():
ret = cmd_output('sh', '-c', 'echo hi')
assert ret == 'hi\n'
<|code_end|>
, generate the next line using the imports in this file:
import pytest
from pre_commit_hooks.util import CalledProcessError
from pre_commit_hooks.util import cmd_output
from pre_commit_hooks.util import zsplit
and context (functions, classes, or occasionally code) from other files:
# Path: pre_commit_hooks/util.py
# class CalledProcessError(RuntimeError):
# pass
#
# Path: pre_commit_hooks/util.py
# def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str:
# kwargs.setdefault('stdout', subprocess.PIPE)
# kwargs.setdefault('stderr', subprocess.PIPE)
# proc = subprocess.Popen(cmd, **kwargs)
# stdout, stderr = proc.communicate()
# stdout = stdout.decode()
# if retcode is not None and proc.returncode != retcode:
# raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr)
# return stdout
#
# Path: pre_commit_hooks/util.py
# def zsplit(s: str) -> list[str]:
# s = s.strip('\0')
# if s:
# return s.split('\0')
# else:
# return []
. Output only the next line. | @pytest.mark.parametrize('out', ('\0f1\0f2\0', '\0f1\0f2', 'f1\0f2\0')) |
Here is a snippet: <|code_start|>from __future__ import annotations
def test_raises_on_error():
with pytest.raises(CalledProcessError):
cmd_output('sh', '-c', 'exit 1')
def test_output():
ret = cmd_output('sh', '-c', 'echo hi')
assert ret == 'hi\n'
@pytest.mark.parametrize('out', ('\0f1\0f2\0', '\0f1\0f2', 'f1\0f2\0'))
<|code_end|>
. Write the next line using the current file imports:
import pytest
from pre_commit_hooks.util import CalledProcessError
from pre_commit_hooks.util import cmd_output
from pre_commit_hooks.util import zsplit
and context from other files:
# Path: pre_commit_hooks/util.py
# class CalledProcessError(RuntimeError):
# pass
#
# Path: pre_commit_hooks/util.py
# def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str:
# kwargs.setdefault('stdout', subprocess.PIPE)
# kwargs.setdefault('stderr', subprocess.PIPE)
# proc = subprocess.Popen(cmd, **kwargs)
# stdout, stderr = proc.communicate()
# stdout = stdout.decode()
# if retcode is not None and proc.returncode != retcode:
# raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr)
# return stdout
#
# Path: pre_commit_hooks/util.py
# def zsplit(s: str) -> list[str]:
# s = s.strip('\0')
# if s:
# return s.split('\0')
# else:
# return []
, which may include functions, classes, or code. Output only the next line. | def test_check_zsplits_str_correctly(out): |
Predict the next line for this snippet: <|code_start|> assert ret == expected_retval
@pytest.mark.parametrize(
('filename', 'expected_retval'), (
('not_pretty_formatted_json.json', 1),
('unsorted_pretty_formatted_json.json', 0),
('non_ascii_pretty_formatted_json.json', 1),
('pretty_formatted_json.json', 0),
),
)
def test_unsorted_main(filename, expected_retval):
ret = main(['--no-sort-keys', get_resource_path(filename)])
assert ret == expected_retval
@pytest.mark.parametrize(
('filename', 'expected_retval'), (
('not_pretty_formatted_json.json', 1),
('unsorted_pretty_formatted_json.json', 1),
('non_ascii_pretty_formatted_json.json', 1),
('pretty_formatted_json.json', 1),
('tab_pretty_formatted_json.json', 0),
),
)
def test_tab_main(filename, expected_retval):
ret = main(['--indent', '\t', get_resource_path(filename)])
assert ret == expected_retval
<|code_end|>
with the help of current file imports:
import os
import shutil
import pytest
from pre_commit_hooks.pretty_format_json import main
from pre_commit_hooks.pretty_format_json import parse_num_to_int
from testing.util import get_resource_path
and context from other files:
# Path: pre_commit_hooks/pretty_format_json.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument(
# '--autofix',
# action='store_true',
# dest='autofix',
# help='Automatically fixes encountered not-pretty-formatted files',
# )
# parser.add_argument(
# '--indent',
# type=parse_num_to_int,
# default='2',
# help=(
# 'The number of indent spaces or a string to be used as delimiter'
# ' for indentation level e.g. 4 or "\t" (Default: 2)'
# ),
# )
# parser.add_argument(
# '--no-ensure-ascii',
# action='store_true',
# dest='no_ensure_ascii',
# default=False,
# help=(
# 'Do NOT convert non-ASCII characters to Unicode escape sequences '
# '(\\uXXXX)'
# ),
# )
# parser.add_argument(
# '--no-sort-keys',
# action='store_true',
# dest='no_sort_keys',
# default=False,
# help='Keep JSON nodes in the same order',
# )
# parser.add_argument(
# '--top-keys',
# type=parse_topkeys,
# dest='top_keys',
# default=[],
# help='Ordered list of keys to keep at the top of JSON hashes',
# )
# parser.add_argument('filenames', nargs='*', help='Filenames to fix')
# args = parser.parse_args(argv)
#
# status = 0
#
# for json_file in args.filenames:
# with open(json_file, encoding='UTF-8') as f:
# contents = f.read()
#
# try:
# pretty_contents = _get_pretty_format(
# contents, args.indent, ensure_ascii=not args.no_ensure_ascii,
# sort_keys=not args.no_sort_keys, top_keys=args.top_keys,
# )
# except ValueError:
# print(
# f'Input File {json_file} is not a valid JSON, consider using '
# f'check-json',
# )
# return 1
#
# if contents != pretty_contents:
# if args.autofix:
# _autofix(json_file, pretty_contents)
# else:
# diff_output = get_diff(contents, pretty_contents, json_file)
# sys.stdout.buffer.write(diff_output.encode())
#
# status = 1
#
# return status
#
# Path: pre_commit_hooks/pretty_format_json.py
# def parse_num_to_int(s: str) -> int | str:
# """Convert string numbers to int, leaving strings as is."""
# try:
# return int(s)
# except ValueError:
# return s
#
# Path: testing/util.py
# def get_resource_path(path):
# return os.path.join(TESTING_DIR, 'resources', path)
, which may contain function names, class names, or code. Output only the next line. | def test_non_ascii_main(): |
Given the following code snippet before the placeholder: <|code_start|>
def test_top_sorted_get_pretty_format():
ret = main((
'--top-keys=01-alist,alist', get_resource_path('top_sorted_json.json'),
))
assert ret == 0
def test_badfile_main():
ret = main([get_resource_path('ok_yaml.yaml')])
assert ret == 1
def test_diffing_output(capsys):
resource_path = get_resource_path('not_pretty_formatted_json.json')
expected_retval = 1
a = os.path.join('a', resource_path)
b = os.path.join('b', resource_path)
expected_out = f'''\
--- {a}
+++ {b}
@@ -1,6 +1,9 @@
{{
- "foo":
- "bar",
- "alist": [2, 34, 234],
- "blah": null
+ "alist": [
+ 2,
<|code_end|>
, predict the next line using imports from the current file:
import os
import shutil
import pytest
from pre_commit_hooks.pretty_format_json import main
from pre_commit_hooks.pretty_format_json import parse_num_to_int
from testing.util import get_resource_path
and context including class names, function names, and sometimes code from other files:
# Path: pre_commit_hooks/pretty_format_json.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument(
# '--autofix',
# action='store_true',
# dest='autofix',
# help='Automatically fixes encountered not-pretty-formatted files',
# )
# parser.add_argument(
# '--indent',
# type=parse_num_to_int,
# default='2',
# help=(
# 'The number of indent spaces or a string to be used as delimiter'
# ' for indentation level e.g. 4 or "\t" (Default: 2)'
# ),
# )
# parser.add_argument(
# '--no-ensure-ascii',
# action='store_true',
# dest='no_ensure_ascii',
# default=False,
# help=(
# 'Do NOT convert non-ASCII characters to Unicode escape sequences '
# '(\\uXXXX)'
# ),
# )
# parser.add_argument(
# '--no-sort-keys',
# action='store_true',
# dest='no_sort_keys',
# default=False,
# help='Keep JSON nodes in the same order',
# )
# parser.add_argument(
# '--top-keys',
# type=parse_topkeys,
# dest='top_keys',
# default=[],
# help='Ordered list of keys to keep at the top of JSON hashes',
# )
# parser.add_argument('filenames', nargs='*', help='Filenames to fix')
# args = parser.parse_args(argv)
#
# status = 0
#
# for json_file in args.filenames:
# with open(json_file, encoding='UTF-8') as f:
# contents = f.read()
#
# try:
# pretty_contents = _get_pretty_format(
# contents, args.indent, ensure_ascii=not args.no_ensure_ascii,
# sort_keys=not args.no_sort_keys, top_keys=args.top_keys,
# )
# except ValueError:
# print(
# f'Input File {json_file} is not a valid JSON, consider using '
# f'check-json',
# )
# return 1
#
# if contents != pretty_contents:
# if args.autofix:
# _autofix(json_file, pretty_contents)
# else:
# diff_output = get_diff(contents, pretty_contents, json_file)
# sys.stdout.buffer.write(diff_output.encode())
#
# status = 1
#
# return status
#
# Path: pre_commit_hooks/pretty_format_json.py
# def parse_num_to_int(s: str) -> int | str:
# """Convert string numbers to int, leaving strings as is."""
# try:
# return int(s)
# except ValueError:
# return s
#
# Path: testing/util.py
# def get_resource_path(path):
# return os.path.join(TESTING_DIR, 'resources', path)
. Output only the next line. | + 34, |
Predict the next line for this snippet: <|code_start|> ret = main([str(srcfile)])
assert ret == 0
def test_orderfile_get_pretty_format():
ret = main((
'--top-keys=alist', get_resource_path('pretty_formatted_json.json'),
))
assert ret == 0
def test_not_orderfile_get_pretty_format():
ret = main((
'--top-keys=blah', get_resource_path('pretty_formatted_json.json'),
))
assert ret == 1
def test_top_sorted_get_pretty_format():
ret = main((
'--top-keys=01-alist,alist', get_resource_path('top_sorted_json.json'),
))
assert ret == 0
def test_badfile_main():
ret = main([get_resource_path('ok_yaml.yaml')])
assert ret == 1
<|code_end|>
with the help of current file imports:
import os
import shutil
import pytest
from pre_commit_hooks.pretty_format_json import main
from pre_commit_hooks.pretty_format_json import parse_num_to_int
from testing.util import get_resource_path
and context from other files:
# Path: pre_commit_hooks/pretty_format_json.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument(
# '--autofix',
# action='store_true',
# dest='autofix',
# help='Automatically fixes encountered not-pretty-formatted files',
# )
# parser.add_argument(
# '--indent',
# type=parse_num_to_int,
# default='2',
# help=(
# 'The number of indent spaces or a string to be used as delimiter'
# ' for indentation level e.g. 4 or "\t" (Default: 2)'
# ),
# )
# parser.add_argument(
# '--no-ensure-ascii',
# action='store_true',
# dest='no_ensure_ascii',
# default=False,
# help=(
# 'Do NOT convert non-ASCII characters to Unicode escape sequences '
# '(\\uXXXX)'
# ),
# )
# parser.add_argument(
# '--no-sort-keys',
# action='store_true',
# dest='no_sort_keys',
# default=False,
# help='Keep JSON nodes in the same order',
# )
# parser.add_argument(
# '--top-keys',
# type=parse_topkeys,
# dest='top_keys',
# default=[],
# help='Ordered list of keys to keep at the top of JSON hashes',
# )
# parser.add_argument('filenames', nargs='*', help='Filenames to fix')
# args = parser.parse_args(argv)
#
# status = 0
#
# for json_file in args.filenames:
# with open(json_file, encoding='UTF-8') as f:
# contents = f.read()
#
# try:
# pretty_contents = _get_pretty_format(
# contents, args.indent, ensure_ascii=not args.no_ensure_ascii,
# sort_keys=not args.no_sort_keys, top_keys=args.top_keys,
# )
# except ValueError:
# print(
# f'Input File {json_file} is not a valid JSON, consider using '
# f'check-json',
# )
# return 1
#
# if contents != pretty_contents:
# if args.autofix:
# _autofix(json_file, pretty_contents)
# else:
# diff_output = get_diff(contents, pretty_contents, json_file)
# sys.stdout.buffer.write(diff_output.encode())
#
# status = 1
#
# return status
#
# Path: pre_commit_hooks/pretty_format_json.py
# def parse_num_to_int(s: str) -> int | str:
# """Convert string numbers to int, leaving strings as is."""
# try:
# return int(s)
# except ValueError:
# return s
#
# Path: testing/util.py
# def get_resource_path(path):
# return os.path.join(TESTING_DIR, 'resources', path)
, which may contain function names, class names, or code. Output only the next line. | def test_diffing_output(capsys): |
Based on the snippet: <|code_start|>from __future__ import annotations
# Input, expected return value
TESTS = (
(b'-----BEGIN RSA PRIVATE KEY-----', 1),
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
from pre_commit_hooks.detect_private_key import main
and context (classes, functions, sometimes code) from other files:
# Path: pre_commit_hooks/detect_private_key.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='*', help='Filenames to check')
# args = parser.parse_args(argv)
#
# private_key_files = []
#
# for filename in args.filenames:
# with open(filename, 'rb') as f:
# content = f.read()
# if any(line in content for line in BLACKLIST):
# private_key_files.append(filename)
#
# if private_key_files:
# for private_key_file in private_key_files:
# print(f'Private key found: {private_key_file}')
# return 1
# else:
# return 0
. Output only the next line. | (b'-----BEGIN DSA PRIVATE KEY-----', 1), |
Using the snippet: <|code_start|>RETVAL_BAD = 1
TEST_SORTS = [
(
['c: true', '', 'b: 42', 'a: 19'],
['b: 42', 'a: 19', '', 'c: true'],
RETVAL_BAD,
),
(
['# i am', '# a header', '', 'c: true', '', 'b: 42', 'a: 19'],
['# i am', '# a header', '', 'b: 42', 'a: 19', '', 'c: true'],
RETVAL_BAD,
),
(
['# i am', '# a header', '', 'already: sorted', '', 'yup: i am'],
['# i am', '# a header', '', 'already: sorted', '', 'yup: i am'],
RETVAL_GOOD,
),
(
['# i am', '# a header'],
['# i am', '# a header'],
RETVAL_GOOD,
),
]
@pytest.mark.parametrize('bad_lines,good_lines,retval', TEST_SORTS)
def test_integration_good_bad_lines(tmpdir, bad_lines, good_lines, retval):
<|code_end|>
, determine the next line of code. You have imports:
import os
import pytest
from pre_commit_hooks.sort_simple_yaml import first_key
from pre_commit_hooks.sort_simple_yaml import main
from pre_commit_hooks.sort_simple_yaml import parse_block
from pre_commit_hooks.sort_simple_yaml import parse_blocks
from pre_commit_hooks.sort_simple_yaml import sort
and context (class names, function names, or code) available:
# Path: pre_commit_hooks/sort_simple_yaml.py
# def first_key(lines: list[str]) -> str:
# """Returns a string representing the sort key of a block.
#
# The sort key is the first YAML key we encounter, ignoring comments, and
# stripping leading quotes.
#
# >>> print(test)
# # some comment
# 'foo': true
# >>> first_key(test)
# 'foo'
# """
# for line in lines:
# if line.startswith('#'):
# continue
# if any(line.startswith(quote) for quote in QUOTES):
# return line[1:]
# return line
# else:
# return '' # not actually reached in reality
#
# Path: pre_commit_hooks/sort_simple_yaml.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='*', help='Filenames to fix')
# args = parser.parse_args(argv)
#
# retval = 0
#
# for filename in args.filenames:
# with open(filename, 'r+') as f:
# lines = [line.rstrip() for line in f.readlines()]
# new_lines = sort(lines)
#
# if lines != new_lines:
# print(f'Fixing file `{filename}`')
# f.seek(0)
# f.write('\n'.join(new_lines) + '\n')
# f.truncate()
# retval = 1
#
# return retval
#
# Path: pre_commit_hooks/sort_simple_yaml.py
# def parse_block(lines: list[str], header: bool = False) -> list[str]:
# """Parse and return a single block, popping off the start of `lines`.
#
# If parsing a header block, we stop after we reach a line that is not a
# comment. Otherwise, we stop after reaching an empty line.
#
# :param lines: list of lines
# :param header: whether we are parsing a header block
# :return: list of lines that form the single block
# """
# block_lines = []
# while lines and lines[0] and (not header or lines[0].startswith('#')):
# block_lines.append(lines.pop(0))
# return block_lines
#
# Path: pre_commit_hooks/sort_simple_yaml.py
# def parse_blocks(lines: list[str]) -> list[list[str]]:
# """Parse and return all possible blocks, popping off the start of `lines`.
#
# :param lines: list of lines
# :return: list of blocks, where each block is a list of lines
# """
# blocks = []
#
# while lines:
# if lines[0] == '':
# lines.pop(0)
# else:
# blocks.append(parse_block(lines))
#
# return blocks
#
# Path: pre_commit_hooks/sort_simple_yaml.py
# def sort(lines: list[str]) -> list[str]:
# """Sort a YAML file in alphabetical order, keeping blocks together.
#
# :param lines: array of strings (without newlines)
# :return: sorted array of strings
# """
# # make a copy of lines since we will clobber it
# lines = list(lines)
# new_lines = parse_block(lines, header=True)
#
# for block in sorted(parse_blocks(lines), key=first_key):
# if new_lines:
# new_lines.append('')
# new_lines.extend(block)
#
# return new_lines
. Output only the next line. | file_path = os.path.join(str(tmpdir), 'foo.yaml') |
Based on the snippet: <|code_start|> assert [line.rstrip() for line in f.readlines()] == good_lines
def test_parse_header():
lines = ['# some header', '# is here', '', 'this is not a header']
assert parse_block(lines, header=True) == ['# some header', '# is here']
assert lines == ['', 'this is not a header']
lines = ['this is not a header']
assert parse_block(lines, header=True) == []
assert lines == ['this is not a header']
def test_parse_block():
# a normal block
lines = ['a: 42', 'b: 17', '', 'c: 19']
assert parse_block(lines) == ['a: 42', 'b: 17']
assert lines == ['', 'c: 19']
# a block at the end
lines = ['c: 19']
assert parse_block(lines) == ['c: 19']
assert lines == []
# no block
lines = []
assert parse_block(lines) == []
assert lines == []
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import pytest
from pre_commit_hooks.sort_simple_yaml import first_key
from pre_commit_hooks.sort_simple_yaml import main
from pre_commit_hooks.sort_simple_yaml import parse_block
from pre_commit_hooks.sort_simple_yaml import parse_blocks
from pre_commit_hooks.sort_simple_yaml import sort
and context (classes, functions, sometimes code) from other files:
# Path: pre_commit_hooks/sort_simple_yaml.py
# def first_key(lines: list[str]) -> str:
# """Returns a string representing the sort key of a block.
#
# The sort key is the first YAML key we encounter, ignoring comments, and
# stripping leading quotes.
#
# >>> print(test)
# # some comment
# 'foo': true
# >>> first_key(test)
# 'foo'
# """
# for line in lines:
# if line.startswith('#'):
# continue
# if any(line.startswith(quote) for quote in QUOTES):
# return line[1:]
# return line
# else:
# return '' # not actually reached in reality
#
# Path: pre_commit_hooks/sort_simple_yaml.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='*', help='Filenames to fix')
# args = parser.parse_args(argv)
#
# retval = 0
#
# for filename in args.filenames:
# with open(filename, 'r+') as f:
# lines = [line.rstrip() for line in f.readlines()]
# new_lines = sort(lines)
#
# if lines != new_lines:
# print(f'Fixing file `{filename}`')
# f.seek(0)
# f.write('\n'.join(new_lines) + '\n')
# f.truncate()
# retval = 1
#
# return retval
#
# Path: pre_commit_hooks/sort_simple_yaml.py
# def parse_block(lines: list[str], header: bool = False) -> list[str]:
# """Parse and return a single block, popping off the start of `lines`.
#
# If parsing a header block, we stop after we reach a line that is not a
# comment. Otherwise, we stop after reaching an empty line.
#
# :param lines: list of lines
# :param header: whether we are parsing a header block
# :return: list of lines that form the single block
# """
# block_lines = []
# while lines and lines[0] and (not header or lines[0].startswith('#')):
# block_lines.append(lines.pop(0))
# return block_lines
#
# Path: pre_commit_hooks/sort_simple_yaml.py
# def parse_blocks(lines: list[str]) -> list[list[str]]:
# """Parse and return all possible blocks, popping off the start of `lines`.
#
# :param lines: list of lines
# :return: list of blocks, where each block is a list of lines
# """
# blocks = []
#
# while lines:
# if lines[0] == '':
# lines.pop(0)
# else:
# blocks.append(parse_block(lines))
#
# return blocks
#
# Path: pre_commit_hooks/sort_simple_yaml.py
# def sort(lines: list[str]) -> list[str]:
# """Sort a YAML file in alphabetical order, keeping blocks together.
#
# :param lines: array of strings (without newlines)
# :return: sorted array of strings
# """
# # make a copy of lines since we will clobber it
# lines = list(lines)
# new_lines = parse_block(lines, header=True)
#
# for block in sorted(parse_blocks(lines), key=first_key):
# if new_lines:
# new_lines.append('')
# new_lines.extend(block)
#
# return new_lines
. Output only the next line. | def test_parse_blocks(): |
Given the following code snippet before the placeholder: <|code_start|>from __future__ import annotations
RETVAL_GOOD = 0
RETVAL_BAD = 1
TEST_SORTS = [
(
['c: true', '', 'b: 42', 'a: 19'],
['b: 42', 'a: 19', '', 'c: true'],
RETVAL_BAD,
),
(
['# i am', '# a header', '', 'c: true', '', 'b: 42', 'a: 19'],
['# i am', '# a header', '', 'b: 42', 'a: 19', '', 'c: true'],
RETVAL_BAD,
),
(
['# i am', '# a header', '', 'already: sorted', '', 'yup: i am'],
['# i am', '# a header', '', 'already: sorted', '', 'yup: i am'],
RETVAL_GOOD,
<|code_end|>
, predict the next line using imports from the current file:
import os
import pytest
from pre_commit_hooks.sort_simple_yaml import first_key
from pre_commit_hooks.sort_simple_yaml import main
from pre_commit_hooks.sort_simple_yaml import parse_block
from pre_commit_hooks.sort_simple_yaml import parse_blocks
from pre_commit_hooks.sort_simple_yaml import sort
and context including class names, function names, and sometimes code from other files:
# Path: pre_commit_hooks/sort_simple_yaml.py
# def first_key(lines: list[str]) -> str:
# """Returns a string representing the sort key of a block.
#
# The sort key is the first YAML key we encounter, ignoring comments, and
# stripping leading quotes.
#
# >>> print(test)
# # some comment
# 'foo': true
# >>> first_key(test)
# 'foo'
# """
# for line in lines:
# if line.startswith('#'):
# continue
# if any(line.startswith(quote) for quote in QUOTES):
# return line[1:]
# return line
# else:
# return '' # not actually reached in reality
#
# Path: pre_commit_hooks/sort_simple_yaml.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='*', help='Filenames to fix')
# args = parser.parse_args(argv)
#
# retval = 0
#
# for filename in args.filenames:
# with open(filename, 'r+') as f:
# lines = [line.rstrip() for line in f.readlines()]
# new_lines = sort(lines)
#
# if lines != new_lines:
# print(f'Fixing file `{filename}`')
# f.seek(0)
# f.write('\n'.join(new_lines) + '\n')
# f.truncate()
# retval = 1
#
# return retval
#
# Path: pre_commit_hooks/sort_simple_yaml.py
# def parse_block(lines: list[str], header: bool = False) -> list[str]:
# """Parse and return a single block, popping off the start of `lines`.
#
# If parsing a header block, we stop after we reach a line that is not a
# comment. Otherwise, we stop after reaching an empty line.
#
# :param lines: list of lines
# :param header: whether we are parsing a header block
# :return: list of lines that form the single block
# """
# block_lines = []
# while lines and lines[0] and (not header or lines[0].startswith('#')):
# block_lines.append(lines.pop(0))
# return block_lines
#
# Path: pre_commit_hooks/sort_simple_yaml.py
# def parse_blocks(lines: list[str]) -> list[list[str]]:
# """Parse and return all possible blocks, popping off the start of `lines`.
#
# :param lines: list of lines
# :return: list of blocks, where each block is a list of lines
# """
# blocks = []
#
# while lines:
# if lines[0] == '':
# lines.pop(0)
# else:
# blocks.append(parse_block(lines))
#
# return blocks
#
# Path: pre_commit_hooks/sort_simple_yaml.py
# def sort(lines: list[str]) -> list[str]:
# """Sort a YAML file in alphabetical order, keeping blocks together.
#
# :param lines: array of strings (without newlines)
# :return: sorted array of strings
# """
# # make a copy of lines since we will clobber it
# lines = list(lines)
# new_lines = parse_block(lines, header=True)
#
# for block in sorted(parse_blocks(lines), key=first_key):
# if new_lines:
# new_lines.append('')
# new_lines.extend(block)
#
# return new_lines
. Output only the next line. | ), |
Given the following code snippet before the placeholder: <|code_start|> ['# i am', '# a header', '', 'already: sorted', '', 'yup: i am'],
RETVAL_GOOD,
),
(
['# i am', '# a header'],
['# i am', '# a header'],
RETVAL_GOOD,
),
]
@pytest.mark.parametrize('bad_lines,good_lines,retval', TEST_SORTS)
def test_integration_good_bad_lines(tmpdir, bad_lines, good_lines, retval):
file_path = os.path.join(str(tmpdir), 'foo.yaml')
with open(file_path, 'w') as f:
f.write('\n'.join(bad_lines) + '\n')
assert main([file_path]) == retval
with open(file_path) as f:
assert [line.rstrip() for line in f.readlines()] == good_lines
def test_parse_header():
lines = ['# some header', '# is here', '', 'this is not a header']
assert parse_block(lines, header=True) == ['# some header', '# is here']
assert lines == ['', 'this is not a header']
<|code_end|>
, predict the next line using imports from the current file:
import os
import pytest
from pre_commit_hooks.sort_simple_yaml import first_key
from pre_commit_hooks.sort_simple_yaml import main
from pre_commit_hooks.sort_simple_yaml import parse_block
from pre_commit_hooks.sort_simple_yaml import parse_blocks
from pre_commit_hooks.sort_simple_yaml import sort
and context including class names, function names, and sometimes code from other files:
# Path: pre_commit_hooks/sort_simple_yaml.py
# def first_key(lines: list[str]) -> str:
# """Returns a string representing the sort key of a block.
#
# The sort key is the first YAML key we encounter, ignoring comments, and
# stripping leading quotes.
#
# >>> print(test)
# # some comment
# 'foo': true
# >>> first_key(test)
# 'foo'
# """
# for line in lines:
# if line.startswith('#'):
# continue
# if any(line.startswith(quote) for quote in QUOTES):
# return line[1:]
# return line
# else:
# return '' # not actually reached in reality
#
# Path: pre_commit_hooks/sort_simple_yaml.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='*', help='Filenames to fix')
# args = parser.parse_args(argv)
#
# retval = 0
#
# for filename in args.filenames:
# with open(filename, 'r+') as f:
# lines = [line.rstrip() for line in f.readlines()]
# new_lines = sort(lines)
#
# if lines != new_lines:
# print(f'Fixing file `{filename}`')
# f.seek(0)
# f.write('\n'.join(new_lines) + '\n')
# f.truncate()
# retval = 1
#
# return retval
#
# Path: pre_commit_hooks/sort_simple_yaml.py
# def parse_block(lines: list[str], header: bool = False) -> list[str]:
# """Parse and return a single block, popping off the start of `lines`.
#
# If parsing a header block, we stop after we reach a line that is not a
# comment. Otherwise, we stop after reaching an empty line.
#
# :param lines: list of lines
# :param header: whether we are parsing a header block
# :return: list of lines that form the single block
# """
# block_lines = []
# while lines and lines[0] and (not header or lines[0].startswith('#')):
# block_lines.append(lines.pop(0))
# return block_lines
#
# Path: pre_commit_hooks/sort_simple_yaml.py
# def parse_blocks(lines: list[str]) -> list[list[str]]:
# """Parse and return all possible blocks, popping off the start of `lines`.
#
# :param lines: list of lines
# :return: list of blocks, where each block is a list of lines
# """
# blocks = []
#
# while lines:
# if lines[0] == '':
# lines.pop(0)
# else:
# blocks.append(parse_block(lines))
#
# return blocks
#
# Path: pre_commit_hooks/sort_simple_yaml.py
# def sort(lines: list[str]) -> list[str]:
# """Sort a YAML file in alphabetical order, keeping blocks together.
#
# :param lines: array of strings (without newlines)
# :return: sorted array of strings
# """
# # make a copy of lines since we will clobber it
# lines = list(lines)
# new_lines = parse_block(lines, header=True)
#
# for block in sorted(parse_blocks(lines), key=first_key):
# if new_lines:
# new_lines.append('')
# new_lines.extend(block)
#
# return new_lines
. Output only the next line. | lines = ['this is not a header'] |
Here is a snippet: <|code_start|>from __future__ import annotations
BUILTIN_CONSTRUCTORS = '''\
import builtins
c1 = complex()
<|code_end|>
. Write the next line using the current file imports:
import ast
import pytest
from pre_commit_hooks.check_builtin_literals import Call
from pre_commit_hooks.check_builtin_literals import main
from pre_commit_hooks.check_builtin_literals import Visitor
and context from other files:
# Path: pre_commit_hooks/check_builtin_literals.py
# class Call(NamedTuple):
# name: str
# line: int
# column: int
#
# Path: pre_commit_hooks/check_builtin_literals.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='*')
# parser.add_argument('--ignore', type=parse_ignore, default=set())
#
# mutex = parser.add_mutually_exclusive_group(required=False)
# mutex.add_argument('--allow-dict-kwargs', action='store_true')
# mutex.add_argument(
# '--no-allow-dict-kwargs',
# dest='allow_dict_kwargs', action='store_false',
# )
# mutex.set_defaults(allow_dict_kwargs=True)
#
# args = parser.parse_args(argv)
#
# rc = 0
# for filename in args.filenames:
# calls = check_file(
# filename,
# ignore=args.ignore,
# allow_dict_kwargs=args.allow_dict_kwargs,
# )
# if calls:
# rc = rc or 1
# for call in calls:
# print(
# f'{filename}:{call.line}:{call.column}: '
# f'replace {call.name}() with {BUILTIN_TYPES[call.name]}',
# )
# return rc
#
# Path: pre_commit_hooks/check_builtin_literals.py
# class Visitor(ast.NodeVisitor):
# def __init__(
# self,
# ignore: Sequence[str] | None = None,
# allow_dict_kwargs: bool = True,
# ) -> None:
# self.builtin_type_calls: list[Call] = []
# self.ignore = set(ignore) if ignore else set()
# self.allow_dict_kwargs = allow_dict_kwargs
#
# def _check_dict_call(self, node: ast.Call) -> bool:
# return self.allow_dict_kwargs and bool(node.keywords)
#
# def visit_Call(self, node: ast.Call) -> None:
# if not isinstance(node.func, ast.Name):
# # Ignore functions that are object attributes (`foo.bar()`).
# # Assume that if the user calls `builtins.list()`, they know what
# # they're doing.
# return
# if node.func.id not in set(BUILTIN_TYPES).difference(self.ignore):
# return
# if node.func.id == 'dict' and self._check_dict_call(node):
# return
# elif node.args:
# return
# self.builtin_type_calls.append(
# Call(node.func.id, node.lineno, node.col_offset),
# )
, which may include functions, classes, or code. Output only the next line. | d1 = dict() |
Using the snippet: <|code_start|>from __future__ import annotations
BUILTIN_CONSTRUCTORS = '''\
import builtins
c1 = complex()
d1 = dict()
f1 = float()
i1 = int()
<|code_end|>
, determine the next line of code. You have imports:
import ast
import pytest
from pre_commit_hooks.check_builtin_literals import Call
from pre_commit_hooks.check_builtin_literals import main
from pre_commit_hooks.check_builtin_literals import Visitor
and context (class names, function names, or code) available:
# Path: pre_commit_hooks/check_builtin_literals.py
# class Call(NamedTuple):
# name: str
# line: int
# column: int
#
# Path: pre_commit_hooks/check_builtin_literals.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='*')
# parser.add_argument('--ignore', type=parse_ignore, default=set())
#
# mutex = parser.add_mutually_exclusive_group(required=False)
# mutex.add_argument('--allow-dict-kwargs', action='store_true')
# mutex.add_argument(
# '--no-allow-dict-kwargs',
# dest='allow_dict_kwargs', action='store_false',
# )
# mutex.set_defaults(allow_dict_kwargs=True)
#
# args = parser.parse_args(argv)
#
# rc = 0
# for filename in args.filenames:
# calls = check_file(
# filename,
# ignore=args.ignore,
# allow_dict_kwargs=args.allow_dict_kwargs,
# )
# if calls:
# rc = rc or 1
# for call in calls:
# print(
# f'{filename}:{call.line}:{call.column}: '
# f'replace {call.name}() with {BUILTIN_TYPES[call.name]}',
# )
# return rc
#
# Path: pre_commit_hooks/check_builtin_literals.py
# class Visitor(ast.NodeVisitor):
# def __init__(
# self,
# ignore: Sequence[str] | None = None,
# allow_dict_kwargs: bool = True,
# ) -> None:
# self.builtin_type_calls: list[Call] = []
# self.ignore = set(ignore) if ignore else set()
# self.allow_dict_kwargs = allow_dict_kwargs
#
# def _check_dict_call(self, node: ast.Call) -> bool:
# return self.allow_dict_kwargs and bool(node.keywords)
#
# def visit_Call(self, node: ast.Call) -> None:
# if not isinstance(node.func, ast.Name):
# # Ignore functions that are object attributes (`foo.bar()`).
# # Assume that if the user calls `builtins.list()`, they know what
# # they're doing.
# return
# if node.func.id not in set(BUILTIN_TYPES).difference(self.ignore):
# return
# if node.func.id == 'dict' and self._check_dict_call(node):
# return
# elif node.args:
# return
# self.builtin_type_calls.append(
# Call(node.func.id, node.lineno, node.col_offset),
# )
. Output only the next line. | l1 = list() |
Given the following code snippet before the placeholder: <|code_start|> ('input_str', 'output'),
(
(
b'import httplib\n',
b'# -*- coding: utf-8 -*-\n'
b'import httplib\n',
),
(
b'#!/usr/bin/env python\n'
b'x = 1\n',
b'#!/usr/bin/env python\n'
b'# -*- coding: utf-8 -*-\n'
b'x = 1\n',
),
(
b'#coding=utf-8\n'
b'x = 1\n',
b'# -*- coding: utf-8 -*-\n'
b'x = 1\n',
),
(
b'#!/usr/bin/env python\n'
b'#coding=utf8\n'
b'x = 1\n',
b'#!/usr/bin/env python\n'
b'# -*- coding: utf-8 -*-\n'
b'x = 1\n',
),
# These should each get truncated
(b'#coding: utf-8\n', b''),
<|code_end|>
, predict the next line using imports from the current file:
import io
import pytest
from pre_commit_hooks.fix_encoding_pragma import _normalize_pragma
from pre_commit_hooks.fix_encoding_pragma import fix_encoding_pragma
from pre_commit_hooks.fix_encoding_pragma import main
and context including class names, function names, and sometimes code from other files:
# Path: pre_commit_hooks/fix_encoding_pragma.py
# def _normalize_pragma(pragma: str) -> bytes:
# return pragma.encode().rstrip()
#
# Path: pre_commit_hooks/fix_encoding_pragma.py
# def fix_encoding_pragma(
# f: IO[bytes],
# remove: bool = False,
# expected_pragma: bytes = DEFAULT_PRAGMA,
# ) -> int:
# expected = _get_expected_contents(
# f.readline(), f.readline(), f.read(), expected_pragma,
# )
#
# # Special cases for empty files
# if not expected.rest.strip():
# # If a file only has a shebang or a coding pragma, remove it
# if expected.has_any_pragma or expected.shebang:
# f.seek(0)
# f.truncate()
# f.write(b'')
# return 1
# else:
# return 0
#
# if expected.is_expected_pragma(remove):
# return 0
#
# # Otherwise, write out the new file
# f.seek(0)
# f.truncate()
# f.write(expected.shebang)
# if not remove:
# f.write(expected_pragma + expected.ending)
# f.write(expected.rest)
#
# return 1
#
# Path: pre_commit_hooks/fix_encoding_pragma.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser(
# 'Fixes the encoding pragma of python files',
# )
# parser.add_argument('filenames', nargs='*', help='Filenames to fix')
# parser.add_argument(
# '--pragma', default=DEFAULT_PRAGMA, type=_normalize_pragma,
# help=(
# f'The encoding pragma to use. '
# f'Default: {DEFAULT_PRAGMA.decode()}'
# ),
# )
# parser.add_argument(
# '--remove', action='store_true',
# help='Remove the encoding pragma (Useful in a python3-only codebase)',
# )
# args = parser.parse_args(argv)
#
# retv = 0
#
# if args.remove:
# fmt = 'Removed encoding pragma from {filename}'
# else:
# fmt = 'Added `{pragma}` to {filename}'
#
# for filename in args.filenames:
# with open(filename, 'r+b') as f:
# file_ret = fix_encoding_pragma(
# f, remove=args.remove, expected_pragma=args.pragma,
# )
# retv |= file_ret
# if file_ret:
# print(
# fmt.format(pragma=args.pragma.decode(), filename=filename),
# )
#
# return retv
. Output only the next line. | (b'# -*- coding: utf-8 -*-\n', b''), |
Continue the code snippet: <|code_start|>@pytest.mark.parametrize(
('input_str', 'output'),
(
(
b'import httplib\n',
b'# -*- coding: utf-8 -*-\n'
b'import httplib\n',
),
(
b'#!/usr/bin/env python\n'
b'x = 1\n',
b'#!/usr/bin/env python\n'
b'# -*- coding: utf-8 -*-\n'
b'x = 1\n',
),
(
b'#coding=utf-8\n'
b'x = 1\n',
b'# -*- coding: utf-8 -*-\n'
b'x = 1\n',
),
(
b'#!/usr/bin/env python\n'
b'#coding=utf8\n'
b'x = 1\n',
b'#!/usr/bin/env python\n'
b'# -*- coding: utf-8 -*-\n'
b'x = 1\n',
),
# These should each get truncated
<|code_end|>
. Use current file imports:
import io
import pytest
from pre_commit_hooks.fix_encoding_pragma import _normalize_pragma
from pre_commit_hooks.fix_encoding_pragma import fix_encoding_pragma
from pre_commit_hooks.fix_encoding_pragma import main
and context (classes, functions, or code) from other files:
# Path: pre_commit_hooks/fix_encoding_pragma.py
# def _normalize_pragma(pragma: str) -> bytes:
# return pragma.encode().rstrip()
#
# Path: pre_commit_hooks/fix_encoding_pragma.py
# def fix_encoding_pragma(
# f: IO[bytes],
# remove: bool = False,
# expected_pragma: bytes = DEFAULT_PRAGMA,
# ) -> int:
# expected = _get_expected_contents(
# f.readline(), f.readline(), f.read(), expected_pragma,
# )
#
# # Special cases for empty files
# if not expected.rest.strip():
# # If a file only has a shebang or a coding pragma, remove it
# if expected.has_any_pragma or expected.shebang:
# f.seek(0)
# f.truncate()
# f.write(b'')
# return 1
# else:
# return 0
#
# if expected.is_expected_pragma(remove):
# return 0
#
# # Otherwise, write out the new file
# f.seek(0)
# f.truncate()
# f.write(expected.shebang)
# if not remove:
# f.write(expected_pragma + expected.ending)
# f.write(expected.rest)
#
# return 1
#
# Path: pre_commit_hooks/fix_encoding_pragma.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser(
# 'Fixes the encoding pragma of python files',
# )
# parser.add_argument('filenames', nargs='*', help='Filenames to fix')
# parser.add_argument(
# '--pragma', default=DEFAULT_PRAGMA, type=_normalize_pragma,
# help=(
# f'The encoding pragma to use. '
# f'Default: {DEFAULT_PRAGMA.decode()}'
# ),
# )
# parser.add_argument(
# '--remove', action='store_true',
# help='Remove the encoding pragma (Useful in a python3-only codebase)',
# )
# args = parser.parse_args(argv)
#
# retv = 0
#
# if args.remove:
# fmt = 'Removed encoding pragma from {filename}'
# else:
# fmt = 'Added `{pragma}` to {filename}'
#
# for filename in args.filenames:
# with open(filename, 'r+b') as f:
# file_ret = fix_encoding_pragma(
# f, remove=args.remove, expected_pragma=args.pragma,
# )
# retv |= file_ret
# if file_ret:
# print(
# fmt.format(pragma=args.pragma.decode(), filename=filename),
# )
#
# return retv
. Output only the next line. | (b'#coding: utf-8\n', b''), |
Here is a snippet: <|code_start|>)
def test_not_ok_inputs(input_str, output):
bytesio = io.BytesIO(input_str)
assert fix_encoding_pragma(bytesio) == 1
bytesio.seek(0)
assert bytesio.read() == output
def test_ok_input_alternate_pragma():
input_s = b'# coding: utf-8\nx = 1\n'
bytesio = io.BytesIO(input_s)
ret = fix_encoding_pragma(bytesio, expected_pragma=b'# coding: utf-8')
assert ret == 0
bytesio.seek(0)
assert bytesio.read() == input_s
def test_not_ok_input_alternate_pragma():
bytesio = io.BytesIO(b'x = 1\n')
ret = fix_encoding_pragma(bytesio, expected_pragma=b'# coding: utf-8')
assert ret == 1
bytesio.seek(0)
assert bytesio.read() == b'# coding: utf-8\nx = 1\n'
@pytest.mark.parametrize(
('input_s', 'expected'),
(
('# coding: utf-8', b'# coding: utf-8'),
# trailing whitespace
<|code_end|>
. Write the next line using the current file imports:
import io
import pytest
from pre_commit_hooks.fix_encoding_pragma import _normalize_pragma
from pre_commit_hooks.fix_encoding_pragma import fix_encoding_pragma
from pre_commit_hooks.fix_encoding_pragma import main
and context from other files:
# Path: pre_commit_hooks/fix_encoding_pragma.py
# def _normalize_pragma(pragma: str) -> bytes:
# return pragma.encode().rstrip()
#
# Path: pre_commit_hooks/fix_encoding_pragma.py
# def fix_encoding_pragma(
# f: IO[bytes],
# remove: bool = False,
# expected_pragma: bytes = DEFAULT_PRAGMA,
# ) -> int:
# expected = _get_expected_contents(
# f.readline(), f.readline(), f.read(), expected_pragma,
# )
#
# # Special cases for empty files
# if not expected.rest.strip():
# # If a file only has a shebang or a coding pragma, remove it
# if expected.has_any_pragma or expected.shebang:
# f.seek(0)
# f.truncate()
# f.write(b'')
# return 1
# else:
# return 0
#
# if expected.is_expected_pragma(remove):
# return 0
#
# # Otherwise, write out the new file
# f.seek(0)
# f.truncate()
# f.write(expected.shebang)
# if not remove:
# f.write(expected_pragma + expected.ending)
# f.write(expected.rest)
#
# return 1
#
# Path: pre_commit_hooks/fix_encoding_pragma.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser(
# 'Fixes the encoding pragma of python files',
# )
# parser.add_argument('filenames', nargs='*', help='Filenames to fix')
# parser.add_argument(
# '--pragma', default=DEFAULT_PRAGMA, type=_normalize_pragma,
# help=(
# f'The encoding pragma to use. '
# f'Default: {DEFAULT_PRAGMA.decode()}'
# ),
# )
# parser.add_argument(
# '--remove', action='store_true',
# help='Remove the encoding pragma (Useful in a python3-only codebase)',
# )
# args = parser.parse_args(argv)
#
# retv = 0
#
# if args.remove:
# fmt = 'Removed encoding pragma from {filename}'
# else:
# fmt = 'Added `{pragma}` to {filename}'
#
# for filename in args.filenames:
# with open(filename, 'r+b') as f:
# file_ret = fix_encoding_pragma(
# f, remove=args.remove, expected_pragma=args.pragma,
# )
# retv |= file_ret
# if file_ret:
# print(
# fmt.format(pragma=args.pragma.decode(), filename=filename),
# )
#
# return retv
, which may include functions, classes, or code. Output only the next line. | ('# coding: utf-8\n', b'# coding: utf-8'), |
Predict the next line for this snippet: <|code_start|>from __future__ import annotations
@pytest.fixture
def git_dir_with_git_dir(tmpdir):
with tmpdir.as_cwd():
subprocess.check_call(('git', 'init', '.'))
git_commit('--allow-empty', '-m', 'init')
subprocess.check_call(('git', 'init', 'foo'))
git_commit('--allow-empty', '-m', 'init', cwd=str(tmpdir.join('foo')))
yield
@pytest.mark.parametrize(
'cmd',
(
# Actually add the submodule
('git', 'submodule', 'add', './foo'),
# Sneaky submodule add (that doesn't show up in .gitmodules)
('git', 'add', 'foo'),
),
)
def test_main_new_submodule(git_dir_with_git_dir, capsys, cmd):
subprocess.check_call(cmd)
assert main(('random_non-related_file',)) == 0
assert main(('foo',)) == 1
<|code_end|>
with the help of current file imports:
import os
import subprocess
import pytest
from unittest import mock
from pre_commit_hooks.forbid_new_submodules import main
from testing.util import git_commit
and context from other files:
# Path: pre_commit_hooks/forbid_new_submodules.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='*')
# args = parser.parse_args(argv)
#
# if (
# 'PRE_COMMIT_FROM_REF' in os.environ and
# 'PRE_COMMIT_TO_REF' in os.environ
# ):
# diff_arg = '...'.join((
# os.environ['PRE_COMMIT_FROM_REF'],
# os.environ['PRE_COMMIT_TO_REF'],
# ))
# else:
# diff_arg = '--staged'
# added_diff = cmd_output(
# 'git', 'diff', '--diff-filter=A', '--raw', diff_arg, '--',
# *args.filenames,
# )
# retv = 0
# for line in added_diff.splitlines():
# metadata, filename = line.split('\t', 1)
# new_mode = metadata.split(' ')[1]
# if new_mode == '160000':
# print(f'{filename}: new submodule introduced')
# retv = 1
#
# if retv:
# print()
# print('This commit introduces new submodules.')
# print('Did you unintentionally `git add .`?')
# print('To fix: git rm {thesubmodule} # no trailing slash')
# print('Also check .gitmodules')
#
# return retv
#
# Path: testing/util.py
# def git_commit(*args, **kwargs):
# cmd = ('git', 'commit', '--no-gpg-sign', '--no-verify', '--no-edit', *args)
# subprocess.check_call(cmd, **kwargs)
, which may contain function names, class names, or code. Output only the next line. | out, _ = capsys.readouterr() |
Predict the next line for this snippet: <|code_start|> # Sneaky submodule add (that doesn't show up in .gitmodules)
('git', 'add', 'foo'),
),
)
def test_main_new_submodule(git_dir_with_git_dir, capsys, cmd):
subprocess.check_call(cmd)
assert main(('random_non-related_file',)) == 0
assert main(('foo',)) == 1
out, _ = capsys.readouterr()
assert out.startswith('foo: new submodule introduced\n')
def test_main_new_submodule_committed(git_dir_with_git_dir, capsys):
rev_parse_cmd = ('git', 'rev-parse', 'HEAD')
from_ref = subprocess.check_output(rev_parse_cmd).decode().strip()
subprocess.check_call(('git', 'submodule', 'add', './foo'))
git_commit('-m', 'new submodule')
to_ref = subprocess.check_output(rev_parse_cmd).decode().strip()
with mock.patch.dict(
os.environ,
{'PRE_COMMIT_FROM_REF': from_ref, 'PRE_COMMIT_TO_REF': to_ref},
):
assert main(('random_non-related_file',)) == 0
assert main(('foo',)) == 1
out, _ = capsys.readouterr()
assert out.startswith('foo: new submodule introduced\n')
def test_main_no_new_submodule(git_dir_with_git_dir):
open('test.py', 'a+').close()
<|code_end|>
with the help of current file imports:
import os
import subprocess
import pytest
from unittest import mock
from pre_commit_hooks.forbid_new_submodules import main
from testing.util import git_commit
and context from other files:
# Path: pre_commit_hooks/forbid_new_submodules.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='*')
# args = parser.parse_args(argv)
#
# if (
# 'PRE_COMMIT_FROM_REF' in os.environ and
# 'PRE_COMMIT_TO_REF' in os.environ
# ):
# diff_arg = '...'.join((
# os.environ['PRE_COMMIT_FROM_REF'],
# os.environ['PRE_COMMIT_TO_REF'],
# ))
# else:
# diff_arg = '--staged'
# added_diff = cmd_output(
# 'git', 'diff', '--diff-filter=A', '--raw', diff_arg, '--',
# *args.filenames,
# )
# retv = 0
# for line in added_diff.splitlines():
# metadata, filename = line.split('\t', 1)
# new_mode = metadata.split(' ')[1]
# if new_mode == '160000':
# print(f'{filename}: new submodule introduced')
# retv = 1
#
# if retv:
# print()
# print('This commit introduces new submodules.')
# print('Did you unintentionally `git add .`?')
# print('To fix: git rm {thesubmodule} # no trailing slash')
# print('Also check .gitmodules')
#
# return retv
#
# Path: testing/util.py
# def git_commit(*args, **kwargs):
# cmd = ('git', 'commit', '--no-gpg-sign', '--no-verify', '--no-edit', *args)
# subprocess.check_call(cmd, **kwargs)
, which may contain function names, class names, or code. Output only the next line. | subprocess.check_call(('git', 'add', 'test.py')) |
Given snippet: <|code_start|>from __future__ import annotations
def test_failure(tmpdir):
f = tmpdir.join('f.txt')
f.write_text('ohai', encoding='utf-8-sig')
assert check_byte_order_marker.main((str(f),)) == 1
def test_success(tmpdir):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pre_commit_hooks import check_byte_order_marker
and context:
# Path: pre_commit_hooks/check_byte_order_marker.py
# def main(argv: Sequence[str] | None = None) -> int:
which might include code, classes, or functions. Output only the next line. | f = tmpdir.join('f.txt') |
Given snippet: <|code_start|>
CONFLICT_PATTERNS = [
b'<<<<<<< ',
b'======= ',
b'=======\n',
b'>>>>>>> ',
]
def is_in_merge() -> bool:
git_dir = cmd_output('git', 'rev-parse', '--git-dir').rstrip()
return (
os.path.exists(os.path.join(git_dir, 'MERGE_MSG')) and
(
os.path.exists(os.path.join(git_dir, 'MERGE_HEAD')) or
os.path.exists(os.path.join(git_dir, 'rebase-apply')) or
os.path.exists(os.path.join(git_dir, 'rebase-merge'))
)
)
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='*')
parser.add_argument('--assume-in-merge', action='store_true')
args = parser.parse_args(argv)
if not is_in_merge() and not args.assume_in_merge:
return 0
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import argparse
import os.path
from typing import Sequence
from pre_commit_hooks.util import cmd_output
and context:
# Path: pre_commit_hooks/util.py
# def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str:
# kwargs.setdefault('stdout', subprocess.PIPE)
# kwargs.setdefault('stderr', subprocess.PIPE)
# proc = subprocess.Popen(cmd, **kwargs)
# stdout, stderr = proc.communicate()
# stdout = stdout.decode()
# if retcode is not None and proc.returncode != retcode:
# raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr)
# return stdout
which might include code, classes, or functions. Output only the next line. | retcode = 0 |
Given the code snippet: <|code_start|>from __future__ import annotations
def test_no_breakpoints():
visitor = DebugStatementParser()
visitor.visit(ast.parse('import os\nfrom foo import bar\n'))
assert visitor.breakpoints == []
def test_finds_debug_import_attribute_access():
visitor = DebugStatementParser()
visitor.visit(ast.parse('import ipdb; ipdb.set_trace()'))
assert visitor.breakpoints == [Debug(1, 0, 'ipdb', 'imported')]
def test_finds_debug_import_from_import():
visitor = DebugStatementParser()
visitor.visit(ast.parse('from pudb import set_trace; set_trace()'))
assert visitor.breakpoints == [Debug(1, 0, 'pudb', 'imported')]
def test_finds_breakpoint():
visitor = DebugStatementParser()
<|code_end|>
, generate the next line using the imports in this file:
import ast
from pre_commit_hooks.debug_statement_hook import Debug
from pre_commit_hooks.debug_statement_hook import DebugStatementParser
from pre_commit_hooks.debug_statement_hook import main
from testing.util import get_resource_path
and context (functions, classes, or occasionally code) from other files:
# Path: pre_commit_hooks/debug_statement_hook.py
# class Debug(NamedTuple):
# line: int
# col: int
# name: str
# reason: str
#
# Path: pre_commit_hooks/debug_statement_hook.py
# class DebugStatementParser(ast.NodeVisitor):
# def __init__(self) -> None:
# self.breakpoints: list[Debug] = []
#
# def visit_Import(self, node: ast.Import) -> None:
# for name in node.names:
# if name.name in DEBUG_STATEMENTS:
# st = Debug(node.lineno, node.col_offset, name.name, 'imported')
# self.breakpoints.append(st)
#
# def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
# if node.module in DEBUG_STATEMENTS:
# st = Debug(node.lineno, node.col_offset, node.module, 'imported')
# self.breakpoints.append(st)
#
# def visit_Call(self, node: ast.Call) -> None:
# """python3.7+ breakpoint()"""
# if isinstance(node.func, ast.Name) and node.func.id == 'breakpoint':
# st = Debug(node.lineno, node.col_offset, node.func.id, 'called')
# self.breakpoints.append(st)
# self.generic_visit(node)
#
# Path: pre_commit_hooks/debug_statement_hook.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='*', help='Filenames to run')
# args = parser.parse_args(argv)
#
# retv = 0
# for filename in args.filenames:
# retv |= check_file(filename)
# return retv
#
# Path: testing/util.py
# def get_resource_path(path):
# return os.path.join(TESTING_DIR, 'resources', path)
. Output only the next line. | visitor.visit(ast.parse('breakpoint()')) |
Based on the snippet: <|code_start|>
def test_finds_debug_import_from_import():
visitor = DebugStatementParser()
visitor.visit(ast.parse('from pudb import set_trace; set_trace()'))
assert visitor.breakpoints == [Debug(1, 0, 'pudb', 'imported')]
def test_finds_breakpoint():
visitor = DebugStatementParser()
visitor.visit(ast.parse('breakpoint()'))
assert visitor.breakpoints == [Debug(1, 0, 'breakpoint', 'called')]
def test_returns_one_for_failing_file(tmpdir):
f_py = tmpdir.join('f.py')
f_py.write('def f():\n import pdb; pdb.set_trace()')
ret = main([str(f_py)])
assert ret == 1
def test_returns_zero_for_passing_file():
ret = main([__file__])
assert ret == 0
def test_syntaxerror_file():
ret = main([get_resource_path('cannot_parse_ast.notpy')])
assert ret == 1
<|code_end|>
, predict the immediate next line with the help of imports:
import ast
from pre_commit_hooks.debug_statement_hook import Debug
from pre_commit_hooks.debug_statement_hook import DebugStatementParser
from pre_commit_hooks.debug_statement_hook import main
from testing.util import get_resource_path
and context (classes, functions, sometimes code) from other files:
# Path: pre_commit_hooks/debug_statement_hook.py
# class Debug(NamedTuple):
# line: int
# col: int
# name: str
# reason: str
#
# Path: pre_commit_hooks/debug_statement_hook.py
# class DebugStatementParser(ast.NodeVisitor):
# def __init__(self) -> None:
# self.breakpoints: list[Debug] = []
#
# def visit_Import(self, node: ast.Import) -> None:
# for name in node.names:
# if name.name in DEBUG_STATEMENTS:
# st = Debug(node.lineno, node.col_offset, name.name, 'imported')
# self.breakpoints.append(st)
#
# def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
# if node.module in DEBUG_STATEMENTS:
# st = Debug(node.lineno, node.col_offset, node.module, 'imported')
# self.breakpoints.append(st)
#
# def visit_Call(self, node: ast.Call) -> None:
# """python3.7+ breakpoint()"""
# if isinstance(node.func, ast.Name) and node.func.id == 'breakpoint':
# st = Debug(node.lineno, node.col_offset, node.func.id, 'called')
# self.breakpoints.append(st)
# self.generic_visit(node)
#
# Path: pre_commit_hooks/debug_statement_hook.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='*', help='Filenames to run')
# args = parser.parse_args(argv)
#
# retv = 0
# for filename in args.filenames:
# retv |= check_file(filename)
# return retv
#
# Path: testing/util.py
# def get_resource_path(path):
# return os.path.join(TESTING_DIR, 'resources', path)
. Output only the next line. | def test_non_utf8_file(tmpdir): |
Given the code snippet: <|code_start|>from __future__ import annotations
def test_no_breakpoints():
visitor = DebugStatementParser()
visitor.visit(ast.parse('import os\nfrom foo import bar\n'))
assert visitor.breakpoints == []
def test_finds_debug_import_attribute_access():
visitor = DebugStatementParser()
visitor.visit(ast.parse('import ipdb; ipdb.set_trace()'))
assert visitor.breakpoints == [Debug(1, 0, 'ipdb', 'imported')]
def test_finds_debug_import_from_import():
visitor = DebugStatementParser()
visitor.visit(ast.parse('from pudb import set_trace; set_trace()'))
assert visitor.breakpoints == [Debug(1, 0, 'pudb', 'imported')]
<|code_end|>
, generate the next line using the imports in this file:
import ast
from pre_commit_hooks.debug_statement_hook import Debug
from pre_commit_hooks.debug_statement_hook import DebugStatementParser
from pre_commit_hooks.debug_statement_hook import main
from testing.util import get_resource_path
and context (functions, classes, or occasionally code) from other files:
# Path: pre_commit_hooks/debug_statement_hook.py
# class Debug(NamedTuple):
# line: int
# col: int
# name: str
# reason: str
#
# Path: pre_commit_hooks/debug_statement_hook.py
# class DebugStatementParser(ast.NodeVisitor):
# def __init__(self) -> None:
# self.breakpoints: list[Debug] = []
#
# def visit_Import(self, node: ast.Import) -> None:
# for name in node.names:
# if name.name in DEBUG_STATEMENTS:
# st = Debug(node.lineno, node.col_offset, name.name, 'imported')
# self.breakpoints.append(st)
#
# def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
# if node.module in DEBUG_STATEMENTS:
# st = Debug(node.lineno, node.col_offset, node.module, 'imported')
# self.breakpoints.append(st)
#
# def visit_Call(self, node: ast.Call) -> None:
# """python3.7+ breakpoint()"""
# if isinstance(node.func, ast.Name) and node.func.id == 'breakpoint':
# st = Debug(node.lineno, node.col_offset, node.func.id, 'called')
# self.breakpoints.append(st)
# self.generic_visit(node)
#
# Path: pre_commit_hooks/debug_statement_hook.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='*', help='Filenames to run')
# args = parser.parse_args(argv)
#
# retv = 0
# for filename in args.filenames:
# retv |= check_file(filename)
# return retv
#
# Path: testing/util.py
# def get_resource_path(path):
# return os.path.join(TESTING_DIR, 'resources', path)
. Output only the next line. | def test_finds_breakpoint(): |
Given snippet: <|code_start|>def test_finds_debug_import_attribute_access():
visitor = DebugStatementParser()
visitor.visit(ast.parse('import ipdb; ipdb.set_trace()'))
assert visitor.breakpoints == [Debug(1, 0, 'ipdb', 'imported')]
def test_finds_debug_import_from_import():
visitor = DebugStatementParser()
visitor.visit(ast.parse('from pudb import set_trace; set_trace()'))
assert visitor.breakpoints == [Debug(1, 0, 'pudb', 'imported')]
def test_finds_breakpoint():
visitor = DebugStatementParser()
visitor.visit(ast.parse('breakpoint()'))
assert visitor.breakpoints == [Debug(1, 0, 'breakpoint', 'called')]
def test_returns_one_for_failing_file(tmpdir):
f_py = tmpdir.join('f.py')
f_py.write('def f():\n import pdb; pdb.set_trace()')
ret = main([str(f_py)])
assert ret == 1
def test_returns_zero_for_passing_file():
ret = main([__file__])
assert ret == 0
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import ast
from pre_commit_hooks.debug_statement_hook import Debug
from pre_commit_hooks.debug_statement_hook import DebugStatementParser
from pre_commit_hooks.debug_statement_hook import main
from testing.util import get_resource_path
and context:
# Path: pre_commit_hooks/debug_statement_hook.py
# class Debug(NamedTuple):
# line: int
# col: int
# name: str
# reason: str
#
# Path: pre_commit_hooks/debug_statement_hook.py
# class DebugStatementParser(ast.NodeVisitor):
# def __init__(self) -> None:
# self.breakpoints: list[Debug] = []
#
# def visit_Import(self, node: ast.Import) -> None:
# for name in node.names:
# if name.name in DEBUG_STATEMENTS:
# st = Debug(node.lineno, node.col_offset, name.name, 'imported')
# self.breakpoints.append(st)
#
# def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
# if node.module in DEBUG_STATEMENTS:
# st = Debug(node.lineno, node.col_offset, node.module, 'imported')
# self.breakpoints.append(st)
#
# def visit_Call(self, node: ast.Call) -> None:
# """python3.7+ breakpoint()"""
# if isinstance(node.func, ast.Name) and node.func.id == 'breakpoint':
# st = Debug(node.lineno, node.col_offset, node.func.id, 'called')
# self.breakpoints.append(st)
# self.generic_visit(node)
#
# Path: pre_commit_hooks/debug_statement_hook.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='*', help='Filenames to run')
# args = parser.parse_args(argv)
#
# retv = 0
# for filename in args.filenames:
# retv |= check_file(filename)
# return retv
#
# Path: testing/util.py
# def get_resource_path(path):
# return os.path.join(TESTING_DIR, 'resources', path)
which might include code, classes, or functions. Output only the next line. | def test_syntaxerror_file(): |
Predict the next line after this snippet: <|code_start|>from __future__ import annotations
def test_failing_file():
ret = main([get_resource_path('cannot_parse_ast.notpy')])
assert ret == 1
<|code_end|>
using the current file's imports:
from pre_commit_hooks.check_ast import main
from testing.util import get_resource_path
and any relevant context from other files:
# Path: pre_commit_hooks/check_ast.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='*')
# args = parser.parse_args(argv)
#
# retval = 0
# for filename in args.filenames:
#
# try:
# with open(filename, 'rb') as f:
# ast.parse(f.read(), filename=filename)
# except SyntaxError:
# impl = platform.python_implementation()
# version = sys.version.split()[0]
# print(f'{filename}: failed parsing with {impl} {version}:')
# tb = ' ' + traceback.format_exc().replace('\n', '\n ')
# print(f'\n{tb}')
# retval = 1
# return retval
#
# Path: testing/util.py
# def get_resource_path(path):
# return os.path.join(TESTING_DIR, 'resources', path)
. Output only the next line. | def test_passing_file(): |
Using the snippet: <|code_start|>from __future__ import annotations
def is_on_branch(
protected: AbstractSet[str],
patterns: AbstractSet[str] = frozenset(),
) -> bool:
try:
ref_name = cmd_output('git', 'symbolic-ref', 'HEAD')
except CalledProcessError:
return False
chunks = ref_name.strip().split('/')
branch_name = '/'.join(chunks[2:])
return branch_name in protected or any(
re.match(p, branch_name) for p in patterns
)
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument(
'-b', '--branch', action='append',
help='branch to disallow commits to, may be specified multiple times',
)
parser.add_argument(
<|code_end|>
, determine the next line of code. You have imports:
import argparse
import re
from typing import AbstractSet
from typing import Sequence
from pre_commit_hooks.util import CalledProcessError
from pre_commit_hooks.util import cmd_output
and context (class names, function names, or code) available:
# Path: pre_commit_hooks/util.py
# class CalledProcessError(RuntimeError):
# pass
#
# Path: pre_commit_hooks/util.py
# def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str:
# kwargs.setdefault('stdout', subprocess.PIPE)
# kwargs.setdefault('stderr', subprocess.PIPE)
# proc = subprocess.Popen(cmd, **kwargs)
# stdout, stderr = proc.communicate()
# stdout = stdout.decode()
# if retcode is not None and proc.returncode != retcode:
# raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr)
# return stdout
. Output only the next line. | '-p', '--pattern', action='append', |
Based on the snippet: <|code_start|>from __future__ import annotations
def is_on_branch(
protected: AbstractSet[str],
patterns: AbstractSet[str] = frozenset(),
) -> bool:
try:
ref_name = cmd_output('git', 'symbolic-ref', 'HEAD')
except CalledProcessError:
return False
chunks = ref_name.strip().split('/')
branch_name = '/'.join(chunks[2:])
return branch_name in protected or any(
re.match(p, branch_name) for p in patterns
)
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument(
'-b', '--branch', action='append',
help='branch to disallow commits to, may be specified multiple times',
)
parser.add_argument(
'-p', '--pattern', action='append',
help=(
<|code_end|>
, predict the immediate next line with the help of imports:
import argparse
import re
from typing import AbstractSet
from typing import Sequence
from pre_commit_hooks.util import CalledProcessError
from pre_commit_hooks.util import cmd_output
and context (classes, functions, sometimes code) from other files:
# Path: pre_commit_hooks/util.py
# class CalledProcessError(RuntimeError):
# pass
#
# Path: pre_commit_hooks/util.py
# def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str:
# kwargs.setdefault('stdout', subprocess.PIPE)
# kwargs.setdefault('stderr', subprocess.PIPE)
# proc = subprocess.Popen(cmd, **kwargs)
# stdout, stderr = proc.communicate()
# stdout = stdout.decode()
# if retcode is not None and proc.returncode != retcode:
# raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr)
# return stdout
. Output only the next line. | 'regex pattern for branch name to disallow commits to, ' |
Predict the next line for this snippet: <|code_start|>from __future__ import annotations
def test_nothing_added(temp_git_dir):
with temp_git_dir.as_cwd():
assert find_large_added_files(['f.py'], 0) == 0
def test_adding_something(temp_git_dir):
with temp_git_dir.as_cwd():
<|code_end|>
with the help of current file imports:
import shutil
import pytest
from pre_commit_hooks.check_added_large_files import find_large_added_files
from pre_commit_hooks.check_added_large_files import main
from pre_commit_hooks.util import cmd_output
from testing.util import git_commit
and context from other files:
# Path: pre_commit_hooks/check_added_large_files.py
# def find_large_added_files(
# filenames: Sequence[str],
# maxkb: int,
# *,
# enforce_all: bool = False,
# ) -> int:
# # Find all added files that are also in the list of files pre-commit tells
# # us about
# retv = 0
# filenames_filtered = set(filenames)
# filter_lfs_files(filenames_filtered)
#
# if not enforce_all:
# filenames_filtered &= added_files()
#
# for filename in filenames_filtered:
# kb = int(math.ceil(os.stat(filename).st_size / 1024))
# if kb > maxkb:
# print(f'{filename} ({kb} KB) exceeds {maxkb} KB.')
# retv = 1
#
# return retv
#
# Path: pre_commit_hooks/check_added_large_files.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument(
# 'filenames', nargs='*',
# help='Filenames pre-commit believes are changed.',
# )
# parser.add_argument(
# '--enforce-all', action='store_true',
# help='Enforce all files are checked, not just staged files.',
# )
# parser.add_argument(
# '--maxkb', type=int, default=500,
# help='Maximum allowable KB for added files',
# )
# args = parser.parse_args(argv)
#
# return find_large_added_files(
# args.filenames,
# args.maxkb,
# enforce_all=args.enforce_all,
# )
#
# Path: pre_commit_hooks/util.py
# def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str:
# kwargs.setdefault('stdout', subprocess.PIPE)
# kwargs.setdefault('stderr', subprocess.PIPE)
# proc = subprocess.Popen(cmd, **kwargs)
# stdout, stderr = proc.communicate()
# stdout = stdout.decode()
# if retcode is not None and proc.returncode != retcode:
# raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr)
# return stdout
#
# Path: testing/util.py
# def git_commit(*args, **kwargs):
# cmd = ('git', 'commit', '--no-gpg-sign', '--no-verify', '--no-edit', *args)
# subprocess.check_call(cmd, **kwargs)
, which may contain function names, class names, or code. Output only the next line. | temp_git_dir.join('f.py').write("print('hello world')") |
Based on the snippet: <|code_start|> assert main(('--maxkb', '9', 'f.py')) == 0
@xfailif_no_gitlfs
def test_moves_with_gitlfs(temp_git_dir): # pragma: no cover
with temp_git_dir.as_cwd():
cmd_output('git', 'lfs', 'install', '--local')
cmd_output('git', 'lfs', 'track', 'a.bin', 'b.bin')
# First add the file we're going to move
temp_git_dir.join('a.bin').write('a' * 10000)
cmd_output('git', 'add', '--', '.')
git_commit('-am', 'foo')
# Now move it and make sure the hook still succeeds
cmd_output('git', 'mv', 'a.bin', 'b.bin')
assert main(('--maxkb', '9', 'b.bin')) == 0
@xfailif_no_gitlfs
def test_enforce_allows_gitlfs(temp_git_dir): # pragma: no cover
with temp_git_dir.as_cwd():
cmd_output('git', 'lfs', 'install', '--local')
temp_git_dir.join('f.py').write('a' * 10000)
cmd_output('git', 'lfs', 'track', 'f.py')
cmd_output('git', 'add', '--', '.')
# With --enforce-all large files on git lfs should succeed
assert main(('--enforce-all', '--maxkb', '9', 'f.py')) == 0
@xfailif_no_gitlfs
def test_enforce_allows_gitlfs_after_commit(temp_git_dir): # pragma: no cover
<|code_end|>
, predict the immediate next line with the help of imports:
import shutil
import pytest
from pre_commit_hooks.check_added_large_files import find_large_added_files
from pre_commit_hooks.check_added_large_files import main
from pre_commit_hooks.util import cmd_output
from testing.util import git_commit
and context (classes, functions, sometimes code) from other files:
# Path: pre_commit_hooks/check_added_large_files.py
# def find_large_added_files(
# filenames: Sequence[str],
# maxkb: int,
# *,
# enforce_all: bool = False,
# ) -> int:
# # Find all added files that are also in the list of files pre-commit tells
# # us about
# retv = 0
# filenames_filtered = set(filenames)
# filter_lfs_files(filenames_filtered)
#
# if not enforce_all:
# filenames_filtered &= added_files()
#
# for filename in filenames_filtered:
# kb = int(math.ceil(os.stat(filename).st_size / 1024))
# if kb > maxkb:
# print(f'{filename} ({kb} KB) exceeds {maxkb} KB.')
# retv = 1
#
# return retv
#
# Path: pre_commit_hooks/check_added_large_files.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument(
# 'filenames', nargs='*',
# help='Filenames pre-commit believes are changed.',
# )
# parser.add_argument(
# '--enforce-all', action='store_true',
# help='Enforce all files are checked, not just staged files.',
# )
# parser.add_argument(
# '--maxkb', type=int, default=500,
# help='Maximum allowable KB for added files',
# )
# args = parser.parse_args(argv)
#
# return find_large_added_files(
# args.filenames,
# args.maxkb,
# enforce_all=args.enforce_all,
# )
#
# Path: pre_commit_hooks/util.py
# def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str:
# kwargs.setdefault('stdout', subprocess.PIPE)
# kwargs.setdefault('stderr', subprocess.PIPE)
# proc = subprocess.Popen(cmd, **kwargs)
# stdout, stderr = proc.communicate()
# stdout = stdout.decode()
# if retcode is not None and proc.returncode != retcode:
# raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr)
# return stdout
#
# Path: testing/util.py
# def git_commit(*args, **kwargs):
# cmd = ('git', 'commit', '--no-gpg-sign', '--no-verify', '--no-edit', *args)
# subprocess.check_call(cmd, **kwargs)
. Output only the next line. | with temp_git_dir.as_cwd(): |
Given snippet: <|code_start|>
def test_added_file_not_in_pre_commits_list(temp_git_dir):
with temp_git_dir.as_cwd():
temp_git_dir.join('f.py').write("print('hello world')")
cmd_output('git', 'add', 'f.py')
# Should pass even with a size of 0
assert find_large_added_files(['g.py'], 0) == 0
def test_integration(temp_git_dir):
with temp_git_dir.as_cwd():
assert main(argv=[]) == 0
temp_git_dir.join('f.py').write('a' * 10000)
cmd_output('git', 'add', 'f.py')
# Should not fail with default
assert main(argv=['f.py']) == 0
# Should fail with --maxkb
assert main(argv=['--maxkb', '9', 'f.py']) == 1
def has_gitlfs():
return shutil.which('git-lfs') is not None
xfailif_no_gitlfs = pytest.mark.xfail(
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import shutil
import pytest
from pre_commit_hooks.check_added_large_files import find_large_added_files
from pre_commit_hooks.check_added_large_files import main
from pre_commit_hooks.util import cmd_output
from testing.util import git_commit
and context:
# Path: pre_commit_hooks/check_added_large_files.py
# def find_large_added_files(
# filenames: Sequence[str],
# maxkb: int,
# *,
# enforce_all: bool = False,
# ) -> int:
# # Find all added files that are also in the list of files pre-commit tells
# # us about
# retv = 0
# filenames_filtered = set(filenames)
# filter_lfs_files(filenames_filtered)
#
# if not enforce_all:
# filenames_filtered &= added_files()
#
# for filename in filenames_filtered:
# kb = int(math.ceil(os.stat(filename).st_size / 1024))
# if kb > maxkb:
# print(f'{filename} ({kb} KB) exceeds {maxkb} KB.')
# retv = 1
#
# return retv
#
# Path: pre_commit_hooks/check_added_large_files.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument(
# 'filenames', nargs='*',
# help='Filenames pre-commit believes are changed.',
# )
# parser.add_argument(
# '--enforce-all', action='store_true',
# help='Enforce all files are checked, not just staged files.',
# )
# parser.add_argument(
# '--maxkb', type=int, default=500,
# help='Maximum allowable KB for added files',
# )
# args = parser.parse_args(argv)
#
# return find_large_added_files(
# args.filenames,
# args.maxkb,
# enforce_all=args.enforce_all,
# )
#
# Path: pre_commit_hooks/util.py
# def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str:
# kwargs.setdefault('stdout', subprocess.PIPE)
# kwargs.setdefault('stderr', subprocess.PIPE)
# proc = subprocess.Popen(cmd, **kwargs)
# stdout, stderr = proc.communicate()
# stdout = stdout.decode()
# if retcode is not None and proc.returncode != retcode:
# raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr)
# return stdout
#
# Path: testing/util.py
# def git_commit(*args, **kwargs):
# cmd = ('git', 'commit', '--no-gpg-sign', '--no-verify', '--no-edit', *args)
# subprocess.check_call(cmd, **kwargs)
which might include code, classes, or functions. Output only the next line. | not has_gitlfs(), reason='This test requires git-lfs', |
Predict the next line after this snippet: <|code_start|>from __future__ import annotations
def test_nothing_added(temp_git_dir):
with temp_git_dir.as_cwd():
assert find_large_added_files(['f.py'], 0) == 0
def test_adding_something(temp_git_dir):
<|code_end|>
using the current file's imports:
import shutil
import pytest
from pre_commit_hooks.check_added_large_files import find_large_added_files
from pre_commit_hooks.check_added_large_files import main
from pre_commit_hooks.util import cmd_output
from testing.util import git_commit
and any relevant context from other files:
# Path: pre_commit_hooks/check_added_large_files.py
# def find_large_added_files(
# filenames: Sequence[str],
# maxkb: int,
# *,
# enforce_all: bool = False,
# ) -> int:
# # Find all added files that are also in the list of files pre-commit tells
# # us about
# retv = 0
# filenames_filtered = set(filenames)
# filter_lfs_files(filenames_filtered)
#
# if not enforce_all:
# filenames_filtered &= added_files()
#
# for filename in filenames_filtered:
# kb = int(math.ceil(os.stat(filename).st_size / 1024))
# if kb > maxkb:
# print(f'{filename} ({kb} KB) exceeds {maxkb} KB.')
# retv = 1
#
# return retv
#
# Path: pre_commit_hooks/check_added_large_files.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument(
# 'filenames', nargs='*',
# help='Filenames pre-commit believes are changed.',
# )
# parser.add_argument(
# '--enforce-all', action='store_true',
# help='Enforce all files are checked, not just staged files.',
# )
# parser.add_argument(
# '--maxkb', type=int, default=500,
# help='Maximum allowable KB for added files',
# )
# args = parser.parse_args(argv)
#
# return find_large_added_files(
# args.filenames,
# args.maxkb,
# enforce_all=args.enforce_all,
# )
#
# Path: pre_commit_hooks/util.py
# def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str:
# kwargs.setdefault('stdout', subprocess.PIPE)
# kwargs.setdefault('stderr', subprocess.PIPE)
# proc = subprocess.Popen(cmd, **kwargs)
# stdout, stderr = proc.communicate()
# stdout = stdout.decode()
# if retcode is not None and proc.returncode != retcode:
# raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr)
# return stdout
#
# Path: testing/util.py
# def git_commit(*args, **kwargs):
# cmd = ('git', 'commit', '--no-gpg-sign', '--no-verify', '--no-edit', *args)
# subprocess.check_call(cmd, **kwargs)
. Output only the next line. | with temp_git_dir.as_cwd(): |
Based on the snippet: <|code_start|>from __future__ import annotations
def test_always_fails():
with pytest.raises(SystemExit) as excinfo:
main((
'autopep8-wrapper', 'autopep8',
'https://github.com/pre-commit/mirrors-autopep8',
'--foo', 'bar',
))
msg, = excinfo.value.args
assert msg == (
'`autopep8-wrapper` has been removed -- '
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
from pre_commit_hooks.removed import main
and context (classes, functions, sometimes code) from other files:
# Path: pre_commit_hooks/removed.py
# def main(argv: Sequence[str] | None = None) -> int:
# argv = argv if argv is not None else sys.argv[1:]
# hookid, new_hookid, url = argv[:3]
# raise SystemExit(
# f'`{hookid}` has been removed -- use `{new_hookid}` from {url}',
# )
. Output only the next line. | 'use `autopep8` from https://github.com/pre-commit/mirrors-autopep8' |
Predict the next line after this snippet: <|code_start|>
skip_win32 = pytest.mark.skipif(
sys.platform == 'win32',
reason="non-git checks aren't relevant on windows",
)
@skip_win32 # pragma: win32 no cover
@pytest.mark.parametrize(
'content', (
b'#!/bin/bash\nhello world\n',
b'#!/usr/bin/env python3.6',
b'#!python',
'#!☃'.encode(),
),
)
def test_has_shebang(content, tmpdir):
path = tmpdir.join('path')
path.write(content, 'wb')
assert main((str(path),)) == 0
@skip_win32 # pragma: win32 no cover
@pytest.mark.parametrize(
'content', (
b'',
b' #!python\n',
b'\n#!python\n',
b'python\n',
'☃'.encode(),
<|code_end|>
using the current file's imports:
import os
import sys
import pytest
from pre_commit_hooks import check_executables_have_shebangs
from pre_commit_hooks.check_executables_have_shebangs import main
from pre_commit_hooks.util import cmd_output
and any relevant context from other files:
# Path: pre_commit_hooks/check_executables_have_shebangs.py
# EXECUTABLE_VALUES = frozenset(('1', '3', '5', '7'))
# def check_executables(paths: list[str]) -> int:
# def git_ls_files(paths: Sequence[str]) -> Generator[GitLsFile, None, None]:
# def _check_git_filemode(paths: Sequence[str]) -> int:
# def has_shebang(path: str) -> int:
# def _message(path: str) -> None:
# def main(argv: Sequence[str] | None = None) -> int:
# class GitLsFile(NamedTuple):
#
# Path: pre_commit_hooks/check_executables_have_shebangs.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser(description=__doc__)
# parser.add_argument('filenames', nargs='*')
# args = parser.parse_args(argv)
#
# return check_executables(args.filenames)
#
# Path: pre_commit_hooks/util.py
# def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str:
# kwargs.setdefault('stdout', subprocess.PIPE)
# kwargs.setdefault('stderr', subprocess.PIPE)
# proc = subprocess.Popen(cmd, **kwargs)
# stdout, stderr = proc.communicate()
# stdout = stdout.decode()
# if retcode is not None and proc.returncode != retcode:
# raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr)
# return stdout
. Output only the next line. | ), |
Predict the next line for this snippet: <|code_start|>
def test_check_git_filemode_passing(tmpdir):
with tmpdir.as_cwd():
cmd_output('git', 'init', '.')
f = tmpdir.join('f')
f.write('#!/usr/bin/env bash')
f_path = str(f)
cmd_output('chmod', '+x', f_path)
cmd_output('git', 'add', f_path)
cmd_output('git', 'update-index', '--chmod=+x', f_path)
g = tmpdir.join('g').ensure()
g_path = str(g)
cmd_output('git', 'add', g_path)
# this is potentially a problem, but not something the script intends
# to check for -- we're only making sure that things that are
# executable have shebangs
h = tmpdir.join('h')
h.write('#!/usr/bin/env bash')
h_path = str(h)
cmd_output('git', 'add', h_path)
files = (f_path, g_path, h_path)
assert check_executables_have_shebangs._check_git_filemode(files) == 0
def test_check_git_filemode_passing_unusual_characters(tmpdir):
<|code_end|>
with the help of current file imports:
import os
import sys
import pytest
from pre_commit_hooks import check_executables_have_shebangs
from pre_commit_hooks.check_executables_have_shebangs import main
from pre_commit_hooks.util import cmd_output
and context from other files:
# Path: pre_commit_hooks/check_executables_have_shebangs.py
# EXECUTABLE_VALUES = frozenset(('1', '3', '5', '7'))
# def check_executables(paths: list[str]) -> int:
# def git_ls_files(paths: Sequence[str]) -> Generator[GitLsFile, None, None]:
# def _check_git_filemode(paths: Sequence[str]) -> int:
# def has_shebang(path: str) -> int:
# def _message(path: str) -> None:
# def main(argv: Sequence[str] | None = None) -> int:
# class GitLsFile(NamedTuple):
#
# Path: pre_commit_hooks/check_executables_have_shebangs.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser(description=__doc__)
# parser.add_argument('filenames', nargs='*')
# args = parser.parse_args(argv)
#
# return check_executables(args.filenames)
#
# Path: pre_commit_hooks/util.py
# def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str:
# kwargs.setdefault('stdout', subprocess.PIPE)
# kwargs.setdefault('stderr', subprocess.PIPE)
# proc = subprocess.Popen(cmd, **kwargs)
# stdout, stderr = proc.communicate()
# stdout = stdout.decode()
# if retcode is not None and proc.returncode != retcode:
# raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr)
# return stdout
, which may contain function names, class names, or code. Output only the next line. | with tmpdir.as_cwd(): |
Continue the code snippet: <|code_start|> b'#!/usr/bin/env python3.6',
b'#!python',
'#!☃'.encode(),
),
)
def test_has_shebang(content, tmpdir):
path = tmpdir.join('path')
path.write(content, 'wb')
assert main((str(path),)) == 0
@skip_win32 # pragma: win32 no cover
@pytest.mark.parametrize(
'content', (
b'',
b' #!python\n',
b'\n#!python\n',
b'python\n',
'☃'.encode(),
),
)
def test_bad_shebang(content, tmpdir, capsys):
path = tmpdir.join('path')
path.write(content, 'wb')
assert main((str(path),)) == 1
_, stderr = capsys.readouterr()
assert stderr.startswith(f'{path}: marked executable but')
def test_check_git_filemode_passing(tmpdir):
<|code_end|>
. Use current file imports:
import os
import sys
import pytest
from pre_commit_hooks import check_executables_have_shebangs
from pre_commit_hooks.check_executables_have_shebangs import main
from pre_commit_hooks.util import cmd_output
and context (classes, functions, or code) from other files:
# Path: pre_commit_hooks/check_executables_have_shebangs.py
# EXECUTABLE_VALUES = frozenset(('1', '3', '5', '7'))
# def check_executables(paths: list[str]) -> int:
# def git_ls_files(paths: Sequence[str]) -> Generator[GitLsFile, None, None]:
# def _check_git_filemode(paths: Sequence[str]) -> int:
# def has_shebang(path: str) -> int:
# def _message(path: str) -> None:
# def main(argv: Sequence[str] | None = None) -> int:
# class GitLsFile(NamedTuple):
#
# Path: pre_commit_hooks/check_executables_have_shebangs.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser(description=__doc__)
# parser.add_argument('filenames', nargs='*')
# args = parser.parse_args(argv)
#
# return check_executables(args.filenames)
#
# Path: pre_commit_hooks/util.py
# def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str:
# kwargs.setdefault('stdout', subprocess.PIPE)
# kwargs.setdefault('stderr', subprocess.PIPE)
# proc = subprocess.Popen(cmd, **kwargs)
# stdout, stderr = proc.communicate()
# stdout = stdout.decode()
# if retcode is not None and proc.returncode != retcode:
# raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr)
# return stdout
. Output only the next line. | with tmpdir.as_cwd(): |
Predict the next line after this snippet: <|code_start|> for line in zsplit(
cmd_output('git', 'status', '--porcelain=v2', '-z', '--', *files),
):
splitted = line.split(' ')
if splitted and splitted[0] == ORDINARY_CHANGED_ENTRIES_MARKER:
# https://git-scm.com/docs/git-status#_changed_tracked_entries
(
_, _, _,
mode_HEAD,
mode_index,
_,
hash_HEAD,
hash_index,
*path_splitted,
) = splitted
path = ' '.join(path_splitted)
if (
mode_HEAD == PERMS_LINK and
mode_index != PERMS_LINK and
mode_index != PERMS_NONEXIST
):
if hash_HEAD == hash_index:
# if old and new hashes are equal, it's not needed to check
# anything more, we've found a destroyed symlink for sure
destroyed_links.append(path)
else:
# if old and new hashes are *not* equal, it doesn't mean
# that everything is OK - new file may be altered
# by something like trailing-whitespace and/or
# mixed-line-ending hooks so we need to go deeper
<|code_end|>
using the current file's imports:
import argparse
import shlex
import subprocess
from typing import Sequence
from pre_commit_hooks.util import cmd_output
from pre_commit_hooks.util import zsplit
and any relevant context from other files:
# Path: pre_commit_hooks/util.py
# def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str:
# kwargs.setdefault('stdout', subprocess.PIPE)
# kwargs.setdefault('stderr', subprocess.PIPE)
# proc = subprocess.Popen(cmd, **kwargs)
# stdout, stderr = proc.communicate()
# stdout = stdout.decode()
# if retcode is not None and proc.returncode != retcode:
# raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr)
# return stdout
#
# Path: pre_commit_hooks/util.py
# def zsplit(s: str) -> list[str]:
# s = s.strip('\0')
# if s:
# return s.split('\0')
# else:
# return []
. Output only the next line. | SIZE_CMD = ('git', 'cat-file', '-s') |
Given snippet: <|code_start|>from __future__ import annotations
@pytest.mark.parametrize(
('input_s', 'argv', 'expected_retval', 'output'),
(
(b'', [], FAIL, b'\n'),
(b'lonesome\n', [], PASS, b'lonesome\n'),
(b'missing_newline', [], FAIL, b'missing_newline\n'),
(b'newline\nmissing', [], FAIL, b'missing\nnewline\n'),
(b'missing\nnewline', [], FAIL, b'missing\nnewline\n'),
(b'alpha\nbeta\n', [], PASS, b'alpha\nbeta\n'),
(b'beta\nalpha\n', [], FAIL, b'alpha\nbeta\n'),
(b'C\nc\n', [], PASS, b'C\nc\n'),
(b'c\nC\n', [], FAIL, b'C\nc\n'),
(b'mag ical \n tre vor\n', [], FAIL, b' tre vor\nmag ical \n'),
(b'@\n-\n_\n#\n', [], FAIL, b'#\n-\n@\n_\n'),
(b'extra\n\n\nwhitespace\n', [], FAIL, b'extra\nwhitespace\n'),
(b'whitespace\n\n\nextra\n', [], FAIL, b'extra\nwhitespace\n'),
(
b'fee\nFie\nFoe\nfum\n',
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from pre_commit_hooks.file_contents_sorter import FAIL
from pre_commit_hooks.file_contents_sorter import main
from pre_commit_hooks.file_contents_sorter import PASS
and context:
# Path: pre_commit_hooks/file_contents_sorter.py
# FAIL = 1
#
# Path: pre_commit_hooks/file_contents_sorter.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='+', help='Files to sort')
# parser.add_argument(
# '--ignore-case',
# action='store_const',
# const=bytes.lower,
# default=None,
# help='fold lower case to upper case characters',
# )
# parser.add_argument(
# '--unique',
# action='store_true',
# help='ensure each line is unique',
# )
# args = parser.parse_args(argv)
#
# retv = PASS
#
# for arg in args.filenames:
# with open(arg, 'rb+') as file_obj:
# ret_for_file = sort_file_contents(
# file_obj, key=args.ignore_case, unique=args.unique,
# )
#
# if ret_for_file:
# print(f'Sorting {arg}')
#
# retv |= ret_for_file
#
# return retv
#
# Path: pre_commit_hooks/file_contents_sorter.py
# PASS = 0
which might include code, classes, or functions. Output only the next line. | [], |
Predict the next line for this snippet: <|code_start|> ['--unique'],
PASS,
b'Fie\nFoe\nfee\nfum\n',
),
(
b'Fie\nFie\nFoe\nfee\nfum\n',
['--unique'],
FAIL,
b'Fie\nFoe\nfee\nfum\n',
),
(
b'fee\nFie\nFoe\nfum\n',
['--unique', '--ignore-case'],
PASS,
b'fee\nFie\nFoe\nfum\n',
),
(
b'fee\nfee\nFie\nFoe\nfum\n',
['--unique', '--ignore-case'],
FAIL,
b'fee\nFie\nFoe\nfum\n',
),
),
)
def test_integration(input_s, argv, expected_retval, output, tmpdir):
path = tmpdir.join('file.txt')
path.write_binary(input_s)
output_retval = main([str(path)] + argv)
<|code_end|>
with the help of current file imports:
import pytest
from pre_commit_hooks.file_contents_sorter import FAIL
from pre_commit_hooks.file_contents_sorter import main
from pre_commit_hooks.file_contents_sorter import PASS
and context from other files:
# Path: pre_commit_hooks/file_contents_sorter.py
# FAIL = 1
#
# Path: pre_commit_hooks/file_contents_sorter.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='+', help='Files to sort')
# parser.add_argument(
# '--ignore-case',
# action='store_const',
# const=bytes.lower,
# default=None,
# help='fold lower case to upper case characters',
# )
# parser.add_argument(
# '--unique',
# action='store_true',
# help='ensure each line is unique',
# )
# args = parser.parse_args(argv)
#
# retv = PASS
#
# for arg in args.filenames:
# with open(arg, 'rb+') as file_obj:
# ret_for_file = sort_file_contents(
# file_obj, key=args.ignore_case, unique=args.unique,
# )
#
# if ret_for_file:
# print(f'Sorting {arg}')
#
# retv |= ret_for_file
#
# return retv
#
# Path: pre_commit_hooks/file_contents_sorter.py
# PASS = 0
, which may contain function names, class names, or code. Output only the next line. | assert path.read_binary() == output |
Here is a snippet: <|code_start|> (
(b'', [], FAIL, b'\n'),
(b'lonesome\n', [], PASS, b'lonesome\n'),
(b'missing_newline', [], FAIL, b'missing_newline\n'),
(b'newline\nmissing', [], FAIL, b'missing\nnewline\n'),
(b'missing\nnewline', [], FAIL, b'missing\nnewline\n'),
(b'alpha\nbeta\n', [], PASS, b'alpha\nbeta\n'),
(b'beta\nalpha\n', [], FAIL, b'alpha\nbeta\n'),
(b'C\nc\n', [], PASS, b'C\nc\n'),
(b'c\nC\n', [], FAIL, b'C\nc\n'),
(b'mag ical \n tre vor\n', [], FAIL, b' tre vor\nmag ical \n'),
(b'@\n-\n_\n#\n', [], FAIL, b'#\n-\n@\n_\n'),
(b'extra\n\n\nwhitespace\n', [], FAIL, b'extra\nwhitespace\n'),
(b'whitespace\n\n\nextra\n', [], FAIL, b'extra\nwhitespace\n'),
(
b'fee\nFie\nFoe\nfum\n',
[],
FAIL,
b'Fie\nFoe\nfee\nfum\n',
),
(
b'Fie\nFoe\nfee\nfum\n',
[],
PASS,
b'Fie\nFoe\nfee\nfum\n',
),
(
b'fee\nFie\nFoe\nfum\n',
['--ignore-case'],
PASS,
<|code_end|>
. Write the next line using the current file imports:
import pytest
from pre_commit_hooks.file_contents_sorter import FAIL
from pre_commit_hooks.file_contents_sorter import main
from pre_commit_hooks.file_contents_sorter import PASS
and context from other files:
# Path: pre_commit_hooks/file_contents_sorter.py
# FAIL = 1
#
# Path: pre_commit_hooks/file_contents_sorter.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='+', help='Files to sort')
# parser.add_argument(
# '--ignore-case',
# action='store_const',
# const=bytes.lower,
# default=None,
# help='fold lower case to upper case characters',
# )
# parser.add_argument(
# '--unique',
# action='store_true',
# help='ensure each line is unique',
# )
# args = parser.parse_args(argv)
#
# retv = PASS
#
# for arg in args.filenames:
# with open(arg, 'rb+') as file_obj:
# ret_for_file = sort_file_contents(
# file_obj, key=args.ignore_case, unique=args.unique,
# )
#
# if ret_for_file:
# print(f'Sorting {arg}')
#
# retv |= ret_for_file
#
# return retv
#
# Path: pre_commit_hooks/file_contents_sorter.py
# PASS = 0
, which may include functions, classes, or code. Output only the next line. | b'fee\nFie\nFoe\nfum\n', |
Here is a snippet: <|code_start|>from __future__ import annotations
@pytest.mark.parametrize(
('filename', 'expected_retval'), (
('bad_xml.notxml', 1),
('ok_xml.xml', 0),
),
<|code_end|>
. Write the next line using the current file imports:
import pytest
from pre_commit_hooks.check_xml import main
from testing.util import get_resource_path
and context from other files:
# Path: pre_commit_hooks/check_xml.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='*', help='XML filenames to check.')
# args = parser.parse_args(argv)
#
# retval = 0
# handler = xml.sax.handler.ContentHandler()
# for filename in args.filenames:
# try:
# with open(filename, 'rb') as xml_file:
# xml.sax.parse(xml_file, handler)
# except xml.sax.SAXException as exc:
# print(f'{filename}: Failed to xml parse ({exc})')
# retval = 1
# return retval
#
# Path: testing/util.py
# def get_resource_path(path):
# return os.path.join(TESTING_DIR, 'resources', path)
, which may include functions, classes, or code. Output only the next line. | ) |
Continue the code snippet: <|code_start|>from __future__ import annotations
@pytest.mark.parametrize(
('filename', 'expected_retval'), (
<|code_end|>
. Use current file imports:
import pytest
from pre_commit_hooks.check_xml import main
from testing.util import get_resource_path
and context (classes, functions, or code) from other files:
# Path: pre_commit_hooks/check_xml.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='*', help='XML filenames to check.')
# args = parser.parse_args(argv)
#
# retval = 0
# handler = xml.sax.handler.ContentHandler()
# for filename in args.filenames:
# try:
# with open(filename, 'rb') as xml_file:
# xml.sax.parse(xml_file, handler)
# except xml.sax.SAXException as exc:
# print(f'{filename}: Failed to xml parse ({exc})')
# retval = 1
# return retval
#
# Path: testing/util.py
# def get_resource_path(path):
# return os.path.join(TESTING_DIR, 'resources', path)
. Output only the next line. | ('bad_xml.notxml', 1), |
Using the snippet: <|code_start|>from __future__ import annotations
def test_other_branch(temp_git_dir):
with temp_git_dir.as_cwd():
cmd_output('git', 'checkout', '-b', 'anotherbranch')
assert is_on_branch({'master'}) is False
def test_multi_branch(temp_git_dir):
with temp_git_dir.as_cwd():
cmd_output('git', 'checkout', '-b', 'another/branch')
assert is_on_branch({'master'}) is False
<|code_end|>
, determine the next line of code. You have imports:
import pytest
from pre_commit_hooks.no_commit_to_branch import is_on_branch
from pre_commit_hooks.no_commit_to_branch import main
from pre_commit_hooks.util import cmd_output
from testing.util import git_commit
and context (class names, function names, or code) available:
# Path: pre_commit_hooks/no_commit_to_branch.py
# def is_on_branch(
# protected: AbstractSet[str],
# patterns: AbstractSet[str] = frozenset(),
# ) -> bool:
# try:
# ref_name = cmd_output('git', 'symbolic-ref', 'HEAD')
# except CalledProcessError:
# return False
# chunks = ref_name.strip().split('/')
# branch_name = '/'.join(chunks[2:])
# return branch_name in protected or any(
# re.match(p, branch_name) for p in patterns
# )
#
# Path: pre_commit_hooks/no_commit_to_branch.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument(
# '-b', '--branch', action='append',
# help='branch to disallow commits to, may be specified multiple times',
# )
# parser.add_argument(
# '-p', '--pattern', action='append',
# help=(
# 'regex pattern for branch name to disallow commits to, '
# 'may be specified multiple times'
# ),
# )
# args = parser.parse_args(argv)
#
# protected = frozenset(args.branch or ('master', 'main'))
# patterns = frozenset(args.pattern or ())
# return int(is_on_branch(protected, patterns))
#
# Path: pre_commit_hooks/util.py
# def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str:
# kwargs.setdefault('stdout', subprocess.PIPE)
# kwargs.setdefault('stderr', subprocess.PIPE)
# proc = subprocess.Popen(cmd, **kwargs)
# stdout, stderr = proc.communicate()
# stdout = stdout.decode()
# if retcode is not None and proc.returncode != retcode:
# raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr)
# return stdout
#
# Path: testing/util.py
# def git_commit(*args, **kwargs):
# cmd = ('git', 'commit', '--no-gpg-sign', '--no-verify', '--no-edit', *args)
# subprocess.check_call(cmd, **kwargs)
. Output only the next line. | def test_multi_branch_fail(temp_git_dir): |
Continue the code snippet: <|code_start|>from __future__ import annotations
def test_other_branch(temp_git_dir):
with temp_git_dir.as_cwd():
cmd_output('git', 'checkout', '-b', 'anotherbranch')
assert is_on_branch({'master'}) is False
def test_multi_branch(temp_git_dir):
with temp_git_dir.as_cwd():
cmd_output('git', 'checkout', '-b', 'another/branch')
assert is_on_branch({'master'}) is False
def test_multi_branch_fail(temp_git_dir):
with temp_git_dir.as_cwd():
cmd_output('git', 'checkout', '-b', 'another/branch')
assert is_on_branch({'another/branch'}) is True
def test_master_branch(temp_git_dir):
with temp_git_dir.as_cwd():
assert is_on_branch({'master'}) is True
def test_main_branch_call(temp_git_dir):
<|code_end|>
. Use current file imports:
import pytest
from pre_commit_hooks.no_commit_to_branch import is_on_branch
from pre_commit_hooks.no_commit_to_branch import main
from pre_commit_hooks.util import cmd_output
from testing.util import git_commit
and context (classes, functions, or code) from other files:
# Path: pre_commit_hooks/no_commit_to_branch.py
# def is_on_branch(
# protected: AbstractSet[str],
# patterns: AbstractSet[str] = frozenset(),
# ) -> bool:
# try:
# ref_name = cmd_output('git', 'symbolic-ref', 'HEAD')
# except CalledProcessError:
# return False
# chunks = ref_name.strip().split('/')
# branch_name = '/'.join(chunks[2:])
# return branch_name in protected or any(
# re.match(p, branch_name) for p in patterns
# )
#
# Path: pre_commit_hooks/no_commit_to_branch.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument(
# '-b', '--branch', action='append',
# help='branch to disallow commits to, may be specified multiple times',
# )
# parser.add_argument(
# '-p', '--pattern', action='append',
# help=(
# 'regex pattern for branch name to disallow commits to, '
# 'may be specified multiple times'
# ),
# )
# args = parser.parse_args(argv)
#
# protected = frozenset(args.branch or ('master', 'main'))
# patterns = frozenset(args.pattern or ())
# return int(is_on_branch(protected, patterns))
#
# Path: pre_commit_hooks/util.py
# def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str:
# kwargs.setdefault('stdout', subprocess.PIPE)
# kwargs.setdefault('stderr', subprocess.PIPE)
# proc = subprocess.Popen(cmd, **kwargs)
# stdout, stderr = proc.communicate()
# stdout = stdout.decode()
# if retcode is not None and proc.returncode != retcode:
# raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr)
# return stdout
#
# Path: testing/util.py
# def git_commit(*args, **kwargs):
# cmd = ('git', 'commit', '--no-gpg-sign', '--no-verify', '--no-edit', *args)
# subprocess.check_call(cmd, **kwargs)
. Output only the next line. | with temp_git_dir.as_cwd(): |
Given snippet: <|code_start|>from __future__ import annotations
@pytest.mark.parametrize(
('env_vars', 'values'),
(
({}, set()),
({'AWS_PLACEHOLDER_KEY': '/foo'}, set()),
({'AWS_CONFIG_FILE': '/foo'}, {'/foo'}),
({'AWS_CREDENTIAL_FILE': '/foo'}, {'/foo'}),
({'AWS_SHARED_CREDENTIALS_FILE': '/foo'}, {'/foo'}),
({'BOTO_CONFIG': '/foo'}, {'/foo'}),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from unittest.mock import patch
from pre_commit_hooks.detect_aws_credentials import get_aws_cred_files_from_env
from pre_commit_hooks.detect_aws_credentials import get_aws_secrets_from_env
from pre_commit_hooks.detect_aws_credentials import get_aws_secrets_from_file
from pre_commit_hooks.detect_aws_credentials import main
from testing.util import get_resource_path
import pytest
and context:
# Path: pre_commit_hooks/detect_aws_credentials.py
# def get_aws_cred_files_from_env() -> set[str]:
# """Extract credential file paths from environment variables."""
# return {
# os.environ[env_var]
# for env_var in (
# 'AWS_CONFIG_FILE', 'AWS_CREDENTIAL_FILE',
# 'AWS_SHARED_CREDENTIALS_FILE', 'BOTO_CONFIG',
# )
# if env_var in os.environ
# }
#
# Path: pre_commit_hooks/detect_aws_credentials.py
# def get_aws_secrets_from_env() -> set[str]:
# """Extract AWS secrets from environment variables."""
# keys = set()
# for env_var in (
# 'AWS_SECRET_ACCESS_KEY', 'AWS_SECURITY_TOKEN', 'AWS_SESSION_TOKEN',
# ):
# if os.environ.get(env_var):
# keys.add(os.environ[env_var])
# return keys
#
# Path: pre_commit_hooks/detect_aws_credentials.py
# def get_aws_secrets_from_file(credentials_file: str) -> set[str]:
# """Extract AWS secrets from configuration files.
#
# Read an ini-style configuration file and return a set with all found AWS
# secret access keys.
# """
# aws_credentials_file_path = os.path.expanduser(credentials_file)
# if not os.path.exists(aws_credentials_file_path):
# return set()
#
# parser = configparser.ConfigParser()
# try:
# parser.read(aws_credentials_file_path)
# except configparser.MissingSectionHeaderError:
# return set()
#
# keys = set()
# for section in parser.sections():
# for var in (
# 'aws_secret_access_key', 'aws_security_token',
# 'aws_session_token',
# ):
# try:
# key = parser.get(section, var).strip()
# if key:
# keys.add(key)
# except configparser.NoOptionError:
# pass
# return keys
#
# Path: pre_commit_hooks/detect_aws_credentials.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='+', help='Filenames to run')
# parser.add_argument(
# '--credentials-file',
# dest='credentials_file',
# action='append',
# default=[
# '~/.aws/config', '~/.aws/credentials', '/etc/boto.cfg', '~/.boto',
# ],
# help=(
# 'Location of additional AWS credential file from which to get '
# 'secret keys. Can be passed multiple times.'
# ),
# )
# parser.add_argument(
# '--allow-missing-credentials',
# dest='allow_missing_credentials',
# action='store_true',
# help='Allow hook to pass when no credentials are detected.',
# )
# args = parser.parse_args(argv)
#
# credential_files = set(args.credentials_file)
#
# # Add the credentials files configured via environment variables to the set
# # of files to to gather AWS secrets from.
# credential_files |= get_aws_cred_files_from_env()
#
# keys: set[str] = set()
# for credential_file in credential_files:
# keys |= get_aws_secrets_from_file(credential_file)
#
# # Secrets might be part of environment variables, so add such secrets to
# # the set of keys.
# keys |= get_aws_secrets_from_env()
#
# if not keys and args.allow_missing_credentials:
# return 0
#
# if not keys:
# print(
# 'No AWS keys were found in the configured credential files and '
# 'environment variables.\nPlease ensure you have the correct '
# 'setting for --credentials-file',
# )
# return 2
#
# keys_b = {key.encode() for key in keys}
# bad_filenames = check_file_for_aws_keys(args.filenames, keys_b)
# if bad_filenames:
# for bad_file in bad_filenames:
# print(f'AWS secret found in {bad_file.filename}: {bad_file.key}')
# return 1
# else:
# return 0
#
# Path: testing/util.py
# def get_resource_path(path):
# return os.path.join(TESTING_DIR, 'resources', path)
which might include code, classes, or functions. Output only the next line. | ({'AWS_PLACEHOLDER_KEY': '/foo', 'AWS_CONFIG_FILE': '/bar'}, {'/bar'}), |
Predict the next line for this snippet: <|code_start|> {
'AWS_PLACEHOLDER_KEY': '/foo', 'AWS_CONFIG_FILE': '/bar',
'AWS_CREDENTIAL_FILE': '/baz',
},
{'/bar', '/baz'},
),
(
{
'AWS_CONFIG_FILE': '/foo', 'AWS_CREDENTIAL_FILE': '/bar',
'AWS_SHARED_CREDENTIALS_FILE': '/baz',
},
{'/foo', '/bar', '/baz'},
),
),
)
def test_get_aws_credentials_file_from_env(env_vars, values):
with patch.dict('os.environ', env_vars, clear=True):
assert get_aws_cred_files_from_env() == values
@pytest.mark.parametrize(
('env_vars', 'values'),
(
({}, set()),
({'AWS_PLACEHOLDER_KEY': 'foo'}, set()),
({'AWS_SECRET_ACCESS_KEY': 'foo'}, {'foo'}),
({'AWS_SECURITY_TOKEN': 'foo'}, {'foo'}),
({'AWS_SESSION_TOKEN': 'foo'}, {'foo'}),
({'AWS_SESSION_TOKEN': ''}, set()),
({'AWS_SESSION_TOKEN': 'foo', 'AWS_SECURITY_TOKEN': ''}, {'foo'}),
<|code_end|>
with the help of current file imports:
from unittest.mock import patch
from pre_commit_hooks.detect_aws_credentials import get_aws_cred_files_from_env
from pre_commit_hooks.detect_aws_credentials import get_aws_secrets_from_env
from pre_commit_hooks.detect_aws_credentials import get_aws_secrets_from_file
from pre_commit_hooks.detect_aws_credentials import main
from testing.util import get_resource_path
import pytest
and context from other files:
# Path: pre_commit_hooks/detect_aws_credentials.py
# def get_aws_cred_files_from_env() -> set[str]:
# """Extract credential file paths from environment variables."""
# return {
# os.environ[env_var]
# for env_var in (
# 'AWS_CONFIG_FILE', 'AWS_CREDENTIAL_FILE',
# 'AWS_SHARED_CREDENTIALS_FILE', 'BOTO_CONFIG',
# )
# if env_var in os.environ
# }
#
# Path: pre_commit_hooks/detect_aws_credentials.py
# def get_aws_secrets_from_env() -> set[str]:
# """Extract AWS secrets from environment variables."""
# keys = set()
# for env_var in (
# 'AWS_SECRET_ACCESS_KEY', 'AWS_SECURITY_TOKEN', 'AWS_SESSION_TOKEN',
# ):
# if os.environ.get(env_var):
# keys.add(os.environ[env_var])
# return keys
#
# Path: pre_commit_hooks/detect_aws_credentials.py
# def get_aws_secrets_from_file(credentials_file: str) -> set[str]:
# """Extract AWS secrets from configuration files.
#
# Read an ini-style configuration file and return a set with all found AWS
# secret access keys.
# """
# aws_credentials_file_path = os.path.expanduser(credentials_file)
# if not os.path.exists(aws_credentials_file_path):
# return set()
#
# parser = configparser.ConfigParser()
# try:
# parser.read(aws_credentials_file_path)
# except configparser.MissingSectionHeaderError:
# return set()
#
# keys = set()
# for section in parser.sections():
# for var in (
# 'aws_secret_access_key', 'aws_security_token',
# 'aws_session_token',
# ):
# try:
# key = parser.get(section, var).strip()
# if key:
# keys.add(key)
# except configparser.NoOptionError:
# pass
# return keys
#
# Path: pre_commit_hooks/detect_aws_credentials.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='+', help='Filenames to run')
# parser.add_argument(
# '--credentials-file',
# dest='credentials_file',
# action='append',
# default=[
# '~/.aws/config', '~/.aws/credentials', '/etc/boto.cfg', '~/.boto',
# ],
# help=(
# 'Location of additional AWS credential file from which to get '
# 'secret keys. Can be passed multiple times.'
# ),
# )
# parser.add_argument(
# '--allow-missing-credentials',
# dest='allow_missing_credentials',
# action='store_true',
# help='Allow hook to pass when no credentials are detected.',
# )
# args = parser.parse_args(argv)
#
# credential_files = set(args.credentials_file)
#
# # Add the credentials files configured via environment variables to the set
# # of files to to gather AWS secrets from.
# credential_files |= get_aws_cred_files_from_env()
#
# keys: set[str] = set()
# for credential_file in credential_files:
# keys |= get_aws_secrets_from_file(credential_file)
#
# # Secrets might be part of environment variables, so add such secrets to
# # the set of keys.
# keys |= get_aws_secrets_from_env()
#
# if not keys and args.allow_missing_credentials:
# return 0
#
# if not keys:
# print(
# 'No AWS keys were found in the configured credential files and '
# 'environment variables.\nPlease ensure you have the correct '
# 'setting for --credentials-file',
# )
# return 2
#
# keys_b = {key.encode() for key in keys}
# bad_filenames = check_file_for_aws_keys(args.filenames, keys_b)
# if bad_filenames:
# for bad_file in bad_filenames:
# print(f'AWS secret found in {bad_file.filename}: {bad_file.key}')
# return 1
# else:
# return 0
#
# Path: testing/util.py
# def get_resource_path(path):
# return os.path.join(TESTING_DIR, 'resources', path)
, which may contain function names, class names, or code. Output only the next line. | ( |
Continue the code snippet: <|code_start|>from __future__ import annotations
@pytest.mark.parametrize(
('env_vars', 'values'),
(
({}, set()),
({'AWS_PLACEHOLDER_KEY': '/foo'}, set()),
({'AWS_CONFIG_FILE': '/foo'}, {'/foo'}),
({'AWS_CREDENTIAL_FILE': '/foo'}, {'/foo'}),
({'AWS_SHARED_CREDENTIALS_FILE': '/foo'}, {'/foo'}),
<|code_end|>
. Use current file imports:
from unittest.mock import patch
from pre_commit_hooks.detect_aws_credentials import get_aws_cred_files_from_env
from pre_commit_hooks.detect_aws_credentials import get_aws_secrets_from_env
from pre_commit_hooks.detect_aws_credentials import get_aws_secrets_from_file
from pre_commit_hooks.detect_aws_credentials import main
from testing.util import get_resource_path
import pytest
and context (classes, functions, or code) from other files:
# Path: pre_commit_hooks/detect_aws_credentials.py
# def get_aws_cred_files_from_env() -> set[str]:
# """Extract credential file paths from environment variables."""
# return {
# os.environ[env_var]
# for env_var in (
# 'AWS_CONFIG_FILE', 'AWS_CREDENTIAL_FILE',
# 'AWS_SHARED_CREDENTIALS_FILE', 'BOTO_CONFIG',
# )
# if env_var in os.environ
# }
#
# Path: pre_commit_hooks/detect_aws_credentials.py
# def get_aws_secrets_from_env() -> set[str]:
# """Extract AWS secrets from environment variables."""
# keys = set()
# for env_var in (
# 'AWS_SECRET_ACCESS_KEY', 'AWS_SECURITY_TOKEN', 'AWS_SESSION_TOKEN',
# ):
# if os.environ.get(env_var):
# keys.add(os.environ[env_var])
# return keys
#
# Path: pre_commit_hooks/detect_aws_credentials.py
# def get_aws_secrets_from_file(credentials_file: str) -> set[str]:
# """Extract AWS secrets from configuration files.
#
# Read an ini-style configuration file and return a set with all found AWS
# secret access keys.
# """
# aws_credentials_file_path = os.path.expanduser(credentials_file)
# if not os.path.exists(aws_credentials_file_path):
# return set()
#
# parser = configparser.ConfigParser()
# try:
# parser.read(aws_credentials_file_path)
# except configparser.MissingSectionHeaderError:
# return set()
#
# keys = set()
# for section in parser.sections():
# for var in (
# 'aws_secret_access_key', 'aws_security_token',
# 'aws_session_token',
# ):
# try:
# key = parser.get(section, var).strip()
# if key:
# keys.add(key)
# except configparser.NoOptionError:
# pass
# return keys
#
# Path: pre_commit_hooks/detect_aws_credentials.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='+', help='Filenames to run')
# parser.add_argument(
# '--credentials-file',
# dest='credentials_file',
# action='append',
# default=[
# '~/.aws/config', '~/.aws/credentials', '/etc/boto.cfg', '~/.boto',
# ],
# help=(
# 'Location of additional AWS credential file from which to get '
# 'secret keys. Can be passed multiple times.'
# ),
# )
# parser.add_argument(
# '--allow-missing-credentials',
# dest='allow_missing_credentials',
# action='store_true',
# help='Allow hook to pass when no credentials are detected.',
# )
# args = parser.parse_args(argv)
#
# credential_files = set(args.credentials_file)
#
# # Add the credentials files configured via environment variables to the set
# # of files to to gather AWS secrets from.
# credential_files |= get_aws_cred_files_from_env()
#
# keys: set[str] = set()
# for credential_file in credential_files:
# keys |= get_aws_secrets_from_file(credential_file)
#
# # Secrets might be part of environment variables, so add such secrets to
# # the set of keys.
# keys |= get_aws_secrets_from_env()
#
# if not keys and args.allow_missing_credentials:
# return 0
#
# if not keys:
# print(
# 'No AWS keys were found in the configured credential files and '
# 'environment variables.\nPlease ensure you have the correct '
# 'setting for --credentials-file',
# )
# return 2
#
# keys_b = {key.encode() for key in keys}
# bad_filenames = check_file_for_aws_keys(args.filenames, keys_b)
# if bad_filenames:
# for bad_file in bad_filenames:
# print(f'AWS secret found in {bad_file.filename}: {bad_file.key}')
# return 1
# else:
# return 0
#
# Path: testing/util.py
# def get_resource_path(path):
# return os.path.join(TESTING_DIR, 'resources', path)
. Output only the next line. | ({'BOTO_CONFIG': '/foo'}, {'/foo'}), |
Given the following code snippet before the placeholder: <|code_start|> ({}, set()),
({'AWS_PLACEHOLDER_KEY': '/foo'}, set()),
({'AWS_CONFIG_FILE': '/foo'}, {'/foo'}),
({'AWS_CREDENTIAL_FILE': '/foo'}, {'/foo'}),
({'AWS_SHARED_CREDENTIALS_FILE': '/foo'}, {'/foo'}),
({'BOTO_CONFIG': '/foo'}, {'/foo'}),
({'AWS_PLACEHOLDER_KEY': '/foo', 'AWS_CONFIG_FILE': '/bar'}, {'/bar'}),
(
{
'AWS_PLACEHOLDER_KEY': '/foo', 'AWS_CONFIG_FILE': '/bar',
'AWS_CREDENTIAL_FILE': '/baz',
},
{'/bar', '/baz'},
),
(
{
'AWS_CONFIG_FILE': '/foo', 'AWS_CREDENTIAL_FILE': '/bar',
'AWS_SHARED_CREDENTIALS_FILE': '/baz',
},
{'/foo', '/bar', '/baz'},
),
),
)
def test_get_aws_credentials_file_from_env(env_vars, values):
with patch.dict('os.environ', env_vars, clear=True):
assert get_aws_cred_files_from_env() == values
@pytest.mark.parametrize(
('env_vars', 'values'),
<|code_end|>
, predict the next line using imports from the current file:
from unittest.mock import patch
from pre_commit_hooks.detect_aws_credentials import get_aws_cred_files_from_env
from pre_commit_hooks.detect_aws_credentials import get_aws_secrets_from_env
from pre_commit_hooks.detect_aws_credentials import get_aws_secrets_from_file
from pre_commit_hooks.detect_aws_credentials import main
from testing.util import get_resource_path
import pytest
and context including class names, function names, and sometimes code from other files:
# Path: pre_commit_hooks/detect_aws_credentials.py
# def get_aws_cred_files_from_env() -> set[str]:
# """Extract credential file paths from environment variables."""
# return {
# os.environ[env_var]
# for env_var in (
# 'AWS_CONFIG_FILE', 'AWS_CREDENTIAL_FILE',
# 'AWS_SHARED_CREDENTIALS_FILE', 'BOTO_CONFIG',
# )
# if env_var in os.environ
# }
#
# Path: pre_commit_hooks/detect_aws_credentials.py
# def get_aws_secrets_from_env() -> set[str]:
# """Extract AWS secrets from environment variables."""
# keys = set()
# for env_var in (
# 'AWS_SECRET_ACCESS_KEY', 'AWS_SECURITY_TOKEN', 'AWS_SESSION_TOKEN',
# ):
# if os.environ.get(env_var):
# keys.add(os.environ[env_var])
# return keys
#
# Path: pre_commit_hooks/detect_aws_credentials.py
# def get_aws_secrets_from_file(credentials_file: str) -> set[str]:
# """Extract AWS secrets from configuration files.
#
# Read an ini-style configuration file and return a set with all found AWS
# secret access keys.
# """
# aws_credentials_file_path = os.path.expanduser(credentials_file)
# if not os.path.exists(aws_credentials_file_path):
# return set()
#
# parser = configparser.ConfigParser()
# try:
# parser.read(aws_credentials_file_path)
# except configparser.MissingSectionHeaderError:
# return set()
#
# keys = set()
# for section in parser.sections():
# for var in (
# 'aws_secret_access_key', 'aws_security_token',
# 'aws_session_token',
# ):
# try:
# key = parser.get(section, var).strip()
# if key:
# keys.add(key)
# except configparser.NoOptionError:
# pass
# return keys
#
# Path: pre_commit_hooks/detect_aws_credentials.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='+', help='Filenames to run')
# parser.add_argument(
# '--credentials-file',
# dest='credentials_file',
# action='append',
# default=[
# '~/.aws/config', '~/.aws/credentials', '/etc/boto.cfg', '~/.boto',
# ],
# help=(
# 'Location of additional AWS credential file from which to get '
# 'secret keys. Can be passed multiple times.'
# ),
# )
# parser.add_argument(
# '--allow-missing-credentials',
# dest='allow_missing_credentials',
# action='store_true',
# help='Allow hook to pass when no credentials are detected.',
# )
# args = parser.parse_args(argv)
#
# credential_files = set(args.credentials_file)
#
# # Add the credentials files configured via environment variables to the set
# # of files to to gather AWS secrets from.
# credential_files |= get_aws_cred_files_from_env()
#
# keys: set[str] = set()
# for credential_file in credential_files:
# keys |= get_aws_secrets_from_file(credential_file)
#
# # Secrets might be part of environment variables, so add such secrets to
# # the set of keys.
# keys |= get_aws_secrets_from_env()
#
# if not keys and args.allow_missing_credentials:
# return 0
#
# if not keys:
# print(
# 'No AWS keys were found in the configured credential files and '
# 'environment variables.\nPlease ensure you have the correct '
# 'setting for --credentials-file',
# )
# return 2
#
# keys_b = {key.encode() for key in keys}
# bad_filenames = check_file_for_aws_keys(args.filenames, keys_b)
# if bad_filenames:
# for bad_file in bad_filenames:
# print(f'AWS secret found in {bad_file.filename}: {bad_file.key}')
# return 1
# else:
# return 0
#
# Path: testing/util.py
# def get_resource_path(path):
# return os.path.join(TESTING_DIR, 'resources', path)
. Output only the next line. | ( |
Given snippet: <|code_start|>from __future__ import annotations
@pytest.mark.parametrize(
('env_vars', 'values'),
(
({}, set()),
({'AWS_PLACEHOLDER_KEY': '/foo'}, set()),
({'AWS_CONFIG_FILE': '/foo'}, {'/foo'}),
({'AWS_CREDENTIAL_FILE': '/foo'}, {'/foo'}),
({'AWS_SHARED_CREDENTIALS_FILE': '/foo'}, {'/foo'}),
({'BOTO_CONFIG': '/foo'}, {'/foo'}),
({'AWS_PLACEHOLDER_KEY': '/foo', 'AWS_CONFIG_FILE': '/bar'}, {'/bar'}),
(
{
'AWS_PLACEHOLDER_KEY': '/foo', 'AWS_CONFIG_FILE': '/bar',
'AWS_CREDENTIAL_FILE': '/baz',
},
{'/bar', '/baz'},
),
(
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from unittest.mock import patch
from pre_commit_hooks.detect_aws_credentials import get_aws_cred_files_from_env
from pre_commit_hooks.detect_aws_credentials import get_aws_secrets_from_env
from pre_commit_hooks.detect_aws_credentials import get_aws_secrets_from_file
from pre_commit_hooks.detect_aws_credentials import main
from testing.util import get_resource_path
import pytest
and context:
# Path: pre_commit_hooks/detect_aws_credentials.py
# def get_aws_cred_files_from_env() -> set[str]:
# """Extract credential file paths from environment variables."""
# return {
# os.environ[env_var]
# for env_var in (
# 'AWS_CONFIG_FILE', 'AWS_CREDENTIAL_FILE',
# 'AWS_SHARED_CREDENTIALS_FILE', 'BOTO_CONFIG',
# )
# if env_var in os.environ
# }
#
# Path: pre_commit_hooks/detect_aws_credentials.py
# def get_aws_secrets_from_env() -> set[str]:
# """Extract AWS secrets from environment variables."""
# keys = set()
# for env_var in (
# 'AWS_SECRET_ACCESS_KEY', 'AWS_SECURITY_TOKEN', 'AWS_SESSION_TOKEN',
# ):
# if os.environ.get(env_var):
# keys.add(os.environ[env_var])
# return keys
#
# Path: pre_commit_hooks/detect_aws_credentials.py
# def get_aws_secrets_from_file(credentials_file: str) -> set[str]:
# """Extract AWS secrets from configuration files.
#
# Read an ini-style configuration file and return a set with all found AWS
# secret access keys.
# """
# aws_credentials_file_path = os.path.expanduser(credentials_file)
# if not os.path.exists(aws_credentials_file_path):
# return set()
#
# parser = configparser.ConfigParser()
# try:
# parser.read(aws_credentials_file_path)
# except configparser.MissingSectionHeaderError:
# return set()
#
# keys = set()
# for section in parser.sections():
# for var in (
# 'aws_secret_access_key', 'aws_security_token',
# 'aws_session_token',
# ):
# try:
# key = parser.get(section, var).strip()
# if key:
# keys.add(key)
# except configparser.NoOptionError:
# pass
# return keys
#
# Path: pre_commit_hooks/detect_aws_credentials.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='+', help='Filenames to run')
# parser.add_argument(
# '--credentials-file',
# dest='credentials_file',
# action='append',
# default=[
# '~/.aws/config', '~/.aws/credentials', '/etc/boto.cfg', '~/.boto',
# ],
# help=(
# 'Location of additional AWS credential file from which to get '
# 'secret keys. Can be passed multiple times.'
# ),
# )
# parser.add_argument(
# '--allow-missing-credentials',
# dest='allow_missing_credentials',
# action='store_true',
# help='Allow hook to pass when no credentials are detected.',
# )
# args = parser.parse_args(argv)
#
# credential_files = set(args.credentials_file)
#
# # Add the credentials files configured via environment variables to the set
# # of files to to gather AWS secrets from.
# credential_files |= get_aws_cred_files_from_env()
#
# keys: set[str] = set()
# for credential_file in credential_files:
# keys |= get_aws_secrets_from_file(credential_file)
#
# # Secrets might be part of environment variables, so add such secrets to
# # the set of keys.
# keys |= get_aws_secrets_from_env()
#
# if not keys and args.allow_missing_credentials:
# return 0
#
# if not keys:
# print(
# 'No AWS keys were found in the configured credential files and '
# 'environment variables.\nPlease ensure you have the correct '
# 'setting for --credentials-file',
# )
# return 2
#
# keys_b = {key.encode() for key in keys}
# bad_filenames = check_file_for_aws_keys(args.filenames, keys_b)
# if bad_filenames:
# for bad_file in bad_filenames:
# print(f'AWS secret found in {bad_file.filename}: {bad_file.key}')
# return 1
# else:
# return 0
#
# Path: testing/util.py
# def get_resource_path(path):
# return os.path.join(TESTING_DIR, 'resources', path)
which might include code, classes, or functions. Output only the next line. | { |
Predict the next line for this snippet: <|code_start|>def test_ok_no_newline_end_of_file(tmpdir):
filename = tmpdir.join('f')
filename.write_binary(b'foo\nbar')
ret = main((str(filename),))
assert filename.read_binary() == b'foo\nbar'
assert ret == 0
def test_ok_with_dos_line_endings(tmpdir):
filename = tmpdir.join('f')
filename.write_binary(b'foo\r\nbar\r\nbaz\r\n')
ret = main((str(filename),))
assert filename.read_binary() == b'foo\r\nbar\r\nbaz\r\n'
assert ret == 0
@pytest.mark.parametrize('ext', ('md', 'Md', '.md', '*'))
def test_fixes_markdown_files(tmpdir, ext):
path = tmpdir.join('test.md')
path.write(
'foo \n' # leaves alone
'bar \n' # less than two so it is removed
'baz \n' # more than two so it becomes two spaces
'\t\n' # trailing tabs are stripped anyway
'\n ', # whitespace at the end of the file is removed
)
ret = main((str(path), f'--markdown-linebreak-ext={ext}'))
assert ret == 1
assert path.read() == (
'foo \n'
<|code_end|>
with the help of current file imports:
import pytest
from pre_commit_hooks.trailing_whitespace_fixer import main
and context from other files:
# Path: pre_commit_hooks/trailing_whitespace_fixer.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument(
# '--no-markdown-linebreak-ext',
# action='store_true',
# help=argparse.SUPPRESS,
# )
# parser.add_argument(
# '--markdown-linebreak-ext',
# action='append',
# default=[],
# metavar='*|EXT[,EXT,...]',
# help=(
# 'Markdown extensions (or *) to not strip linebreak spaces. '
# 'default: %(default)s'
# ),
# )
# parser.add_argument(
# '--chars',
# help=(
# 'The set of characters to strip from the end of lines. '
# 'Defaults to all whitespace characters.'
# ),
# )
# parser.add_argument('filenames', nargs='*', help='Filenames to fix')
# args = parser.parse_args(argv)
#
# if args.no_markdown_linebreak_ext:
# print('--no-markdown-linebreak-ext now does nothing!')
#
# md_args = args.markdown_linebreak_ext
# if '' in md_args:
# parser.error('--markdown-linebreak-ext requires a non-empty argument')
# all_markdown = '*' in md_args
# # normalize extensions; split at ',', lowercase, and force 1 leading '.'
# md_exts = [
# '.' + x.lower().lstrip('.') for x in ','.join(md_args).split(',')
# ]
#
# # reject probable "eaten" filename as extension: skip leading '.' with [1:]
# for ext in md_exts:
# if any(c in ext[1:] for c in r'./\:'):
# parser.error(
# f'bad --markdown-linebreak-ext extension '
# f'{ext!r} (has . / \\ :)\n'
# f" (probably filename; use '--markdown-linebreak-ext=EXT')",
# )
# chars = None if args.chars is None else args.chars.encode()
# return_code = 0
# for filename in args.filenames:
# _, extension = os.path.splitext(filename.lower())
# md = all_markdown or extension in md_exts
# if _fix_file(filename, md, chars):
# print(f'Fixing {filename}')
# return_code = 1
# return return_code
, which may contain function names, class names, or code. Output only the next line. | 'bar\n' |
Given the following code snippet before the placeholder: <|code_start|> for filename in set(relevant_files):
if filename.lower() in lowercase_relevant_files:
lowercase_relevant_files.remove(filename.lower())
else:
conflicts.add(filename.lower())
if conflicts:
conflicting_files = [
x for x in repo_files | relevant_files
if x.lower() in conflicts
]
for filename in sorted(conflicting_files):
print(f'Case-insensitivity conflict found: {filename}')
retv = 1
return retv
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument(
'filenames', nargs='*',
help='Filenames pre-commit believes are changed.',
)
args = parser.parse_args(argv)
return find_conflicting_filenames(args.filenames)
<|code_end|>
, predict the next line using imports from the current file:
import argparse
from typing import Iterable
from typing import Iterator
from typing import Sequence
from pre_commit_hooks.util import added_files
from pre_commit_hooks.util import cmd_output
and context including class names, function names, and sometimes code from other files:
# Path: pre_commit_hooks/util.py
# def added_files() -> set[str]:
# cmd = ('git', 'diff', '--staged', '--name-only', '--diff-filter=A')
# return set(cmd_output(*cmd).splitlines())
#
# Path: pre_commit_hooks/util.py
# def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str:
# kwargs.setdefault('stdout', subprocess.PIPE)
# kwargs.setdefault('stderr', subprocess.PIPE)
# proc = subprocess.Popen(cmd, **kwargs)
# stdout, stderr = proc.communicate()
# stdout = stdout.decode()
# if retcode is not None and proc.returncode != retcode:
# raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr)
# return stdout
. Output only the next line. | if __name__ == '__main__': |
Next line prediction: <|code_start|>from __future__ import annotations
def test_trivial(tmpdir):
f = tmpdir.join('f.txt').ensure()
assert not main((str(f),))
def test_passing(tmpdir):
f = tmpdir.join('f.txt')
f.write_binary(
# permalinks are ok
b'https://github.com/asottile/test/blob/649e6/foo%20bar#L1\n'
# tags are ok
b'https://github.com/asottile/test/blob/1.0.0/foo%20bar#L1\n'
# links to files but not line numbers are ok
b'https://github.com/asottile/test/blob/master/foo%20bar\n'
# regression test for overly-greedy regex
b'https://github.com/ yes / no ? /blob/master/foo#L1\n',
)
assert not main((str(f),))
def test_failing(tmpdir, capsys):
with tmpdir.as_cwd():
tmpdir.join('f.txt').write_binary(
b'https://github.com/asottile/test/blob/master/foo#L1\n'
<|code_end|>
. Use current file imports:
(from pre_commit_hooks.check_vcs_permalinks import main)
and context including class names, function names, or small code snippets from other files:
# Path: pre_commit_hooks/check_vcs_permalinks.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='*')
# parser.add_argument(
# '--additional-github-domain',
# dest='additional_github_domains',
# action='append',
# default=['github.com'],
# )
# args = parser.parse_args(argv)
#
# patterns = [
# _get_pattern(domain)
# for domain in args.additional_github_domains
# ]
#
# retv = 0
#
# for filename in args.filenames:
# retv |= _check_filename(filename, patterns)
#
# if retv:
# print()
# print('Non-permanent github link detected.')
# print('On any page on github press [y] to load a permalink.')
# return retv
. Output only the next line. | b'https://example.com/asottile/test/blob/master/foo#L1\n' |
Given the code snippet: <|code_start|> b'c-a>=1;python_version>="3.6"\n'
b'd>2\n'
b'e>=2\n'
b'f<=2\n'
b'g<2\n',
),
(b'ocflib\nDjango\nPyMySQL\n', FAIL, b'Django\nocflib\nPyMySQL\n'),
(
b'-e git+ssh://git_url@tag#egg=ocflib\nDjango\nPyMySQL\n',
FAIL,
b'Django\n-e git+ssh://git_url@tag#egg=ocflib\nPyMySQL\n',
),
(b'bar\npkg-resources==0.0.0\nfoo\n', FAIL, b'bar\nfoo\n'),
(b'foo\npkg-resources==0.0.0\nbar\n', FAIL, b'bar\nfoo\n'),
(
b'git+ssh://git_url@tag#egg=ocflib\nDjango\nijk\n',
FAIL,
b'Django\nijk\ngit+ssh://git_url@tag#egg=ocflib\n',
),
(
b'b==1.0.0\n'
b'c=2.0.0 \\\n'
b' --hash=sha256:abcd\n'
b'a=3.0.0 \\\n'
b' --hash=sha256:a1b1c1d1',
FAIL,
b'a=3.0.0 \\\n'
b' --hash=sha256:a1b1c1d1\n'
b'b==1.0.0\n'
b'c=2.0.0 \\\n'
<|code_end|>
, generate the next line using the imports in this file:
import pytest
from pre_commit_hooks.requirements_txt_fixer import FAIL
from pre_commit_hooks.requirements_txt_fixer import main
from pre_commit_hooks.requirements_txt_fixer import PASS
from pre_commit_hooks.requirements_txt_fixer import Requirement
and context (functions, classes, or occasionally code) from other files:
# Path: pre_commit_hooks/requirements_txt_fixer.py
# FAIL = 1
#
# Path: pre_commit_hooks/requirements_txt_fixer.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='*', help='Filenames to fix')
# args = parser.parse_args(argv)
#
# retv = PASS
#
# for arg in args.filenames:
# with open(arg, 'rb+') as file_obj:
# ret_for_file = fix_requirements(file_obj)
#
# if ret_for_file:
# print(f'Sorting {arg}')
#
# retv |= ret_for_file
#
# return retv
#
# Path: pre_commit_hooks/requirements_txt_fixer.py
# PASS = 0
#
# Path: pre_commit_hooks/requirements_txt_fixer.py
# class Requirement:
# UNTIL_COMPARISON = re.compile(b'={2,3}|!=|~=|>=?|<=?')
# UNTIL_SEP = re.compile(rb'[^;\s]+')
#
# def __init__(self) -> None:
# self.value: bytes | None = None
# self.comments: list[bytes] = []
#
# @property
# def name(self) -> bytes:
# assert self.value is not None, self.value
# name = self.value.lower()
# for egg in (b'#egg=', b'&egg='):
# if egg in self.value:
# return name.partition(egg)[-1]
#
# m = self.UNTIL_SEP.match(name)
# assert m is not None
#
# name = m.group()
# m = self.UNTIL_COMPARISON.search(name)
# if not m:
# return name
#
# return name[:m.start()]
#
# def __lt__(self, requirement: Requirement) -> bool:
# # \n means top of file comment, so always return True,
# # otherwise just do a string comparison with value.
# assert self.value is not None, self.value
# if self.value == b'\n':
# return True
# elif requirement.value == b'\n':
# return False
# else:
# return self.name < requirement.name
#
# def is_complete(self) -> bool:
# return (
# self.value is not None and
# not self.value.rstrip(b'\r\n').endswith(b'\\')
# )
#
# def append_value(self, value: bytes) -> None:
# if self.value is not None:
# self.value += value
# else:
# self.value = value
. Output only the next line. | b' --hash=sha256:abcd\n', |
Using the snippet: <|code_start|> (
b'#comment1\nbar\n#comment2\nfoo\n',
PASS,
b'#comment1\nbar\n#comment2\nfoo\n',
),
(b'#comment\n\nfoo\nbar\n', FAIL, b'#comment\n\nbar\nfoo\n'),
(b'#comment\n\nbar\nfoo\n', PASS, b'#comment\n\nbar\nfoo\n'),
(
b'foo\n\t#comment with indent\nbar\n',
FAIL,
b'\t#comment with indent\nbar\nfoo\n',
),
(
b'bar\n\t#comment with indent\nfoo\n',
PASS,
b'bar\n\t#comment with indent\nfoo\n',
),
(b'\nfoo\nbar\n', FAIL, b'bar\n\nfoo\n'),
(b'\nbar\nfoo\n', PASS, b'\nbar\nfoo\n'),
(
b'pyramid-foo==1\npyramid>=2\n',
FAIL,
b'pyramid>=2\npyramid-foo==1\n',
),
(
b'a==1\n'
b'c>=1\n'
b'bbbb!=1\n'
b'c-a>=1;python_version>="3.6"\n'
b'e>=2\n'
<|code_end|>
, determine the next line of code. You have imports:
import pytest
from pre_commit_hooks.requirements_txt_fixer import FAIL
from pre_commit_hooks.requirements_txt_fixer import main
from pre_commit_hooks.requirements_txt_fixer import PASS
from pre_commit_hooks.requirements_txt_fixer import Requirement
and context (class names, function names, or code) available:
# Path: pre_commit_hooks/requirements_txt_fixer.py
# FAIL = 1
#
# Path: pre_commit_hooks/requirements_txt_fixer.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='*', help='Filenames to fix')
# args = parser.parse_args(argv)
#
# retv = PASS
#
# for arg in args.filenames:
# with open(arg, 'rb+') as file_obj:
# ret_for_file = fix_requirements(file_obj)
#
# if ret_for_file:
# print(f'Sorting {arg}')
#
# retv |= ret_for_file
#
# return retv
#
# Path: pre_commit_hooks/requirements_txt_fixer.py
# PASS = 0
#
# Path: pre_commit_hooks/requirements_txt_fixer.py
# class Requirement:
# UNTIL_COMPARISON = re.compile(b'={2,3}|!=|~=|>=?|<=?')
# UNTIL_SEP = re.compile(rb'[^;\s]+')
#
# def __init__(self) -> None:
# self.value: bytes | None = None
# self.comments: list[bytes] = []
#
# @property
# def name(self) -> bytes:
# assert self.value is not None, self.value
# name = self.value.lower()
# for egg in (b'#egg=', b'&egg='):
# if egg in self.value:
# return name.partition(egg)[-1]
#
# m = self.UNTIL_SEP.match(name)
# assert m is not None
#
# name = m.group()
# m = self.UNTIL_COMPARISON.search(name)
# if not m:
# return name
#
# return name[:m.start()]
#
# def __lt__(self, requirement: Requirement) -> bool:
# # \n means top of file comment, so always return True,
# # otherwise just do a string comparison with value.
# assert self.value is not None, self.value
# if self.value == b'\n':
# return True
# elif requirement.value == b'\n':
# return False
# else:
# return self.name < requirement.name
#
# def is_complete(self) -> bool:
# return (
# self.value is not None and
# not self.value.rstrip(b'\r\n').endswith(b'\\')
# )
#
# def append_value(self, value: bytes) -> None:
# if self.value is not None:
# self.value += value
# else:
# self.value = value
. Output only the next line. | b'd>2\n' |
Predict the next line for this snippet: <|code_start|> (b'foo\n# comment at end\n', PASS, b'foo\n# comment at end\n'),
(b'foo\nbar\n', FAIL, b'bar\nfoo\n'),
(b'bar\nfoo\n', PASS, b'bar\nfoo\n'),
(b'a\nc\nb\n', FAIL, b'a\nb\nc\n'),
(b'a\nc\nb', FAIL, b'a\nb\nc\n'),
(b'a\nb\nc', FAIL, b'a\nb\nc\n'),
(
b'#comment1\nfoo\n#comment2\nbar\n',
FAIL,
b'#comment2\nbar\n#comment1\nfoo\n',
),
(
b'#comment1\nbar\n#comment2\nfoo\n',
PASS,
b'#comment1\nbar\n#comment2\nfoo\n',
),
(b'#comment\n\nfoo\nbar\n', FAIL, b'#comment\n\nbar\nfoo\n'),
(b'#comment\n\nbar\nfoo\n', PASS, b'#comment\n\nbar\nfoo\n'),
(
b'foo\n\t#comment with indent\nbar\n',
FAIL,
b'\t#comment with indent\nbar\nfoo\n',
),
(
b'bar\n\t#comment with indent\nfoo\n',
PASS,
b'bar\n\t#comment with indent\nfoo\n',
),
(b'\nfoo\nbar\n', FAIL, b'bar\n\nfoo\n'),
(b'\nbar\nfoo\n', PASS, b'\nbar\nfoo\n'),
<|code_end|>
with the help of current file imports:
import pytest
from pre_commit_hooks.requirements_txt_fixer import FAIL
from pre_commit_hooks.requirements_txt_fixer import main
from pre_commit_hooks.requirements_txt_fixer import PASS
from pre_commit_hooks.requirements_txt_fixer import Requirement
and context from other files:
# Path: pre_commit_hooks/requirements_txt_fixer.py
# FAIL = 1
#
# Path: pre_commit_hooks/requirements_txt_fixer.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='*', help='Filenames to fix')
# args = parser.parse_args(argv)
#
# retv = PASS
#
# for arg in args.filenames:
# with open(arg, 'rb+') as file_obj:
# ret_for_file = fix_requirements(file_obj)
#
# if ret_for_file:
# print(f'Sorting {arg}')
#
# retv |= ret_for_file
#
# return retv
#
# Path: pre_commit_hooks/requirements_txt_fixer.py
# PASS = 0
#
# Path: pre_commit_hooks/requirements_txt_fixer.py
# class Requirement:
# UNTIL_COMPARISON = re.compile(b'={2,3}|!=|~=|>=?|<=?')
# UNTIL_SEP = re.compile(rb'[^;\s]+')
#
# def __init__(self) -> None:
# self.value: bytes | None = None
# self.comments: list[bytes] = []
#
# @property
# def name(self) -> bytes:
# assert self.value is not None, self.value
# name = self.value.lower()
# for egg in (b'#egg=', b'&egg='):
# if egg in self.value:
# return name.partition(egg)[-1]
#
# m = self.UNTIL_SEP.match(name)
# assert m is not None
#
# name = m.group()
# m = self.UNTIL_COMPARISON.search(name)
# if not m:
# return name
#
# return name[:m.start()]
#
# def __lt__(self, requirement: Requirement) -> bool:
# # \n means top of file comment, so always return True,
# # otherwise just do a string comparison with value.
# assert self.value is not None, self.value
# if self.value == b'\n':
# return True
# elif requirement.value == b'\n':
# return False
# else:
# return self.name < requirement.name
#
# def is_complete(self) -> bool:
# return (
# self.value is not None and
# not self.value.rstrip(b'\r\n').endswith(b'\\')
# )
#
# def append_value(self, value: bytes) -> None:
# if self.value is not None:
# self.value += value
# else:
# self.value = value
, which may contain function names, class names, or code. Output only the next line. | ( |
Here is a snippet: <|code_start|> (b'a\nc\nb', FAIL, b'a\nb\nc\n'),
(b'a\nb\nc', FAIL, b'a\nb\nc\n'),
(
b'#comment1\nfoo\n#comment2\nbar\n',
FAIL,
b'#comment2\nbar\n#comment1\nfoo\n',
),
(
b'#comment1\nbar\n#comment2\nfoo\n',
PASS,
b'#comment1\nbar\n#comment2\nfoo\n',
),
(b'#comment\n\nfoo\nbar\n', FAIL, b'#comment\n\nbar\nfoo\n'),
(b'#comment\n\nbar\nfoo\n', PASS, b'#comment\n\nbar\nfoo\n'),
(
b'foo\n\t#comment with indent\nbar\n',
FAIL,
b'\t#comment with indent\nbar\nfoo\n',
),
(
b'bar\n\t#comment with indent\nfoo\n',
PASS,
b'bar\n\t#comment with indent\nfoo\n',
),
(b'\nfoo\nbar\n', FAIL, b'bar\n\nfoo\n'),
(b'\nbar\nfoo\n', PASS, b'\nbar\nfoo\n'),
(
b'pyramid-foo==1\npyramid>=2\n',
FAIL,
b'pyramid>=2\npyramid-foo==1\n',
<|code_end|>
. Write the next line using the current file imports:
import pytest
from pre_commit_hooks.requirements_txt_fixer import FAIL
from pre_commit_hooks.requirements_txt_fixer import main
from pre_commit_hooks.requirements_txt_fixer import PASS
from pre_commit_hooks.requirements_txt_fixer import Requirement
and context from other files:
# Path: pre_commit_hooks/requirements_txt_fixer.py
# FAIL = 1
#
# Path: pre_commit_hooks/requirements_txt_fixer.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='*', help='Filenames to fix')
# args = parser.parse_args(argv)
#
# retv = PASS
#
# for arg in args.filenames:
# with open(arg, 'rb+') as file_obj:
# ret_for_file = fix_requirements(file_obj)
#
# if ret_for_file:
# print(f'Sorting {arg}')
#
# retv |= ret_for_file
#
# return retv
#
# Path: pre_commit_hooks/requirements_txt_fixer.py
# PASS = 0
#
# Path: pre_commit_hooks/requirements_txt_fixer.py
# class Requirement:
# UNTIL_COMPARISON = re.compile(b'={2,3}|!=|~=|>=?|<=?')
# UNTIL_SEP = re.compile(rb'[^;\s]+')
#
# def __init__(self) -> None:
# self.value: bytes | None = None
# self.comments: list[bytes] = []
#
# @property
# def name(self) -> bytes:
# assert self.value is not None, self.value
# name = self.value.lower()
# for egg in (b'#egg=', b'&egg='):
# if egg in self.value:
# return name.partition(egg)[-1]
#
# m = self.UNTIL_SEP.match(name)
# assert m is not None
#
# name = m.group()
# m = self.UNTIL_COMPARISON.search(name)
# if not m:
# return name
#
# return name[:m.start()]
#
# def __lt__(self, requirement: Requirement) -> bool:
# # \n means top of file comment, so always return True,
# # otherwise just do a string comparison with value.
# assert self.value is not None, self.value
# if self.value == b'\n':
# return True
# elif requirement.value == b'\n':
# return False
# else:
# return self.name < requirement.name
#
# def is_complete(self) -> bool:
# return (
# self.value is not None and
# not self.value.rstrip(b'\r\n').endswith(b'\\')
# )
#
# def append_value(self, value: bytes) -> None:
# if self.value is not None:
# self.value += value
# else:
# self.value = value
, which may include functions, classes, or code. Output only the next line. | ), |
Using the snippet: <|code_start|>from __future__ import annotations
def test_readme_contains_all_hooks():
with open('README.md', encoding='UTF-8') as f:
readme_contents = f.read()
with open('.pre-commit-hooks.yaml', encoding='UTF-8') as f:
hooks = yaml.load(f)
<|code_end|>
, determine the next line of code. You have imports:
from pre_commit_hooks.check_yaml import yaml
and context (class names, function names, or code) available:
# Path: pre_commit_hooks/check_yaml.py
# def _exhaust(gen: Generator[str, None, None]) -> None:
# def _parse_unsafe(*args: Any, **kwargs: Any) -> None:
# def _load_all(*args: Any, **kwargs: Any) -> None:
# def main(argv: Sequence[str] | None = None) -> int:
# class Key(NamedTuple):
# LOAD_FNS = {
# Key(multi=False, unsafe=False): yaml.load,
# Key(multi=False, unsafe=True): _parse_unsafe,
# Key(multi=True, unsafe=False): _load_all,
# Key(multi=True, unsafe=True): _parse_unsafe,
# }
. Output only the next line. | for hook in hooks: |
Here is a snippet: <|code_start|>from __future__ import annotations
def test_main_all_pass():
ret = main(['foo_test.py', 'bar_test.py'])
assert ret == 0
def test_main_one_fails():
ret = main(['not_test_ending.py', 'foo_test.py'])
assert ret == 1
def test_regex():
assert main(('foo_test_py',)) == 1
<|code_end|>
. Write the next line using the current file imports:
from pre_commit_hooks.tests_should_end_in_test import main
and context from other files:
# Path: pre_commit_hooks/tests_should_end_in_test.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='*')
# parser.add_argument(
# '--django', default=False, action='store_true',
# help='Use Django-style test naming pattern (test*.py)',
# )
# args = parser.parse_args(argv)
#
# retcode = 0
# test_name_pattern = r'test.*\.py' if args.django else r'.*_test\.py'
# for filename in args.filenames:
# base = os.path.basename(filename)
# if (
# not re.match(test_name_pattern, base) and
# not base == '__init__.py' and
# not base == 'conftest.py'
# ):
# retcode = 1
# print(f'{filename} does not match pattern "{test_name_pattern}"')
#
# return retcode
, which may include functions, classes, or code. Output only the next line. | def test_main_django_all_pass(): |
Given snippet: <|code_start|> ('--fix=crlf', b'foo\r\nbar\r\nbaz\r\n'),
# --fix=lf with lf endings
('--fix=lf', b'foo\nbar\nbaz\n'),
),
)
def test_line_endings_ok(fix_option, input_s, tmpdir, capsys):
path = tmpdir.join('input.txt')
path.write_binary(input_s)
ret = main((fix_option, str(path)))
assert ret == 0
assert path.read_binary() == input_s
out, _ = capsys.readouterr()
assert out == ''
def test_no_fix_does_not_modify(tmpdir, capsys):
path = tmpdir.join('input.txt')
contents = b'foo\r\nbar\rbaz\nwomp\n'
path.write_binary(contents)
ret = main(('--fix=no', str(path)))
assert ret == 1
assert path.read_binary() == contents
out, _ = capsys.readouterr()
assert out == f'{path}: mixed line endings\n'
def test_fix_lf(tmpdir, capsys):
path = tmpdir.join('input.txt')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from pre_commit_hooks.mixed_line_ending import main
and context:
# Path: pre_commit_hooks/mixed_line_ending.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument(
# '-f', '--fix',
# choices=('auto', 'no') + tuple(FIX_TO_LINE_ENDING),
# default='auto',
# help='Replace line ending with the specified. Default is "auto"',
# )
# parser.add_argument('filenames', nargs='*', help='Filenames to fix')
# args = parser.parse_args(argv)
#
# retv = 0
# for filename in args.filenames:
# if fix_filename(filename, args.fix):
# if args.fix == 'no':
# print(f'{filename}: mixed line endings')
# else:
# print(f'{filename}: fixed mixed line endings')
# retv = 1
# return retv
which might include code, classes, or functions. Output only the next line. | path.write_binary(b'foo\r\nbar\rbaz\n') |
Predict the next line after this snippet: <|code_start|> # Commit in clone and pull without committing
with repo2.as_cwd():
repo2_f2.write('child\n')
cmd_output('git', 'add', '.')
git_commit('-m', 'clone commit2')
cmd_output('git', 'pull', '--no-commit', '--no-rebase')
# We should end up in a pending merge
assert repo2_f1.read() == 'parent\n'
assert repo2_f2.read() == 'child\n'
assert os.path.exists(os.path.join('.git', 'MERGE_HEAD'))
yield repo2
@pytest.mark.usefixtures('f1_is_a_conflict_file')
def test_merge_conflicts_git():
assert main(['f1']) == 1
@pytest.mark.parametrize(
'contents', (b'<<<<<<< HEAD\n', b'=======\n', b'>>>>>>> master\n'),
)
def test_merge_conflicts_failing(contents, repository_pending_merge):
repository_pending_merge.join('f2').write_binary(contents)
assert main(['f2']) == 1
@pytest.mark.parametrize(
'contents', (b'# <<<<<<< HEAD\n', b'# =======\n', b'import mod', b''),
)
def test_merge_conflicts_ok(contents, f1_is_a_conflict_file):
<|code_end|>
using the current file's imports:
import os
import shutil
import pytest
from pre_commit_hooks.check_merge_conflict import main
from pre_commit_hooks.util import cmd_output
from testing.util import get_resource_path
from testing.util import git_commit
and any relevant context from other files:
# Path: pre_commit_hooks/check_merge_conflict.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='*')
# parser.add_argument('--assume-in-merge', action='store_true')
# args = parser.parse_args(argv)
#
# if not is_in_merge() and not args.assume_in_merge:
# return 0
#
# retcode = 0
# for filename in args.filenames:
# with open(filename, 'rb') as inputfile:
# for i, line in enumerate(inputfile):
# for pattern in CONFLICT_PATTERNS:
# if line.startswith(pattern):
# print(
# f'Merge conflict string "{pattern.decode()}" '
# f'found in {filename}:{i + 1}',
# )
# retcode = 1
#
# return retcode
#
# Path: pre_commit_hooks/util.py
# def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str:
# kwargs.setdefault('stdout', subprocess.PIPE)
# kwargs.setdefault('stderr', subprocess.PIPE)
# proc = subprocess.Popen(cmd, **kwargs)
# stdout, stderr = proc.communicate()
# stdout = stdout.decode()
# if retcode is not None and proc.returncode != retcode:
# raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr)
# return stdout
#
# Path: testing/util.py
# def get_resource_path(path):
# return os.path.join(TESTING_DIR, 'resources', path)
#
# Path: testing/util.py
# def git_commit(*args, **kwargs):
# cmd = ('git', 'commit', '--no-gpg-sign', '--no-verify', '--no-edit', *args)
# subprocess.check_call(cmd, **kwargs)
. Output only the next line. | f1_is_a_conflict_file.join('f1').write_binary(contents) |
Given the code snippet: <|code_start|>@pytest.fixture
def repository_pending_merge(tmpdir):
# Make a (non-conflicting) merge
repo1 = tmpdir.join('repo1')
repo1_f1 = repo1.join('f1')
repo2 = tmpdir.join('repo2')
repo2_f1 = repo2.join('f1')
repo2_f2 = repo2.join('f2')
cmd_output('git', 'init', str(repo1))
with repo1.as_cwd():
repo1_f1.ensure()
cmd_output('git', 'add', '.')
git_commit('-m', 'commit1')
cmd_output('git', 'clone', str(repo1), str(repo2))
# Commit in master
with repo1.as_cwd():
repo1_f1.write('parent\n')
git_commit('-am', 'master commit2')
# Commit in clone and pull without committing
with repo2.as_cwd():
repo2_f2.write('child\n')
cmd_output('git', 'add', '.')
git_commit('-m', 'clone commit2')
cmd_output('git', 'pull', '--no-commit', '--no-rebase')
# We should end up in a pending merge
assert repo2_f1.read() == 'parent\n'
assert repo2_f2.read() == 'child\n'
<|code_end|>
, generate the next line using the imports in this file:
import os
import shutil
import pytest
from pre_commit_hooks.check_merge_conflict import main
from pre_commit_hooks.util import cmd_output
from testing.util import get_resource_path
from testing.util import git_commit
and context (functions, classes, or occasionally code) from other files:
# Path: pre_commit_hooks/check_merge_conflict.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='*')
# parser.add_argument('--assume-in-merge', action='store_true')
# args = parser.parse_args(argv)
#
# if not is_in_merge() and not args.assume_in_merge:
# return 0
#
# retcode = 0
# for filename in args.filenames:
# with open(filename, 'rb') as inputfile:
# for i, line in enumerate(inputfile):
# for pattern in CONFLICT_PATTERNS:
# if line.startswith(pattern):
# print(
# f'Merge conflict string "{pattern.decode()}" '
# f'found in {filename}:{i + 1}',
# )
# retcode = 1
#
# return retcode
#
# Path: pre_commit_hooks/util.py
# def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str:
# kwargs.setdefault('stdout', subprocess.PIPE)
# kwargs.setdefault('stderr', subprocess.PIPE)
# proc = subprocess.Popen(cmd, **kwargs)
# stdout, stderr = proc.communicate()
# stdout = stdout.decode()
# if retcode is not None and proc.returncode != retcode:
# raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr)
# return stdout
#
# Path: testing/util.py
# def get_resource_path(path):
# return os.path.join(TESTING_DIR, 'resources', path)
#
# Path: testing/util.py
# def git_commit(*args, **kwargs):
# cmd = ('git', 'commit', '--no-gpg-sign', '--no-verify', '--no-edit', *args)
# subprocess.check_call(cmd, **kwargs)
. Output only the next line. | assert os.path.exists(os.path.join('.git', 'MERGE_HEAD')) |
Using the snippet: <|code_start|> repo1_f1 = repo1.join('f1')
repo2 = tmpdir.join('repo2')
repo2_f1 = repo2.join('f1')
repo2_f2 = repo2.join('f2')
cmd_output('git', 'init', str(repo1))
with repo1.as_cwd():
repo1_f1.ensure()
cmd_output('git', 'add', '.')
git_commit('-m', 'commit1')
cmd_output('git', 'clone', str(repo1), str(repo2))
# Commit in master
with repo1.as_cwd():
repo1_f1.write('parent\n')
git_commit('-am', 'master commit2')
# Commit in clone and pull without committing
with repo2.as_cwd():
repo2_f2.write('child\n')
cmd_output('git', 'add', '.')
git_commit('-m', 'clone commit2')
cmd_output('git', 'pull', '--no-commit', '--no-rebase')
# We should end up in a pending merge
assert repo2_f1.read() == 'parent\n'
assert repo2_f2.read() == 'child\n'
assert os.path.exists(os.path.join('.git', 'MERGE_HEAD'))
yield repo2
<|code_end|>
, determine the next line of code. You have imports:
import os
import shutil
import pytest
from pre_commit_hooks.check_merge_conflict import main
from pre_commit_hooks.util import cmd_output
from testing.util import get_resource_path
from testing.util import git_commit
and context (class names, function names, or code) available:
# Path: pre_commit_hooks/check_merge_conflict.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='*')
# parser.add_argument('--assume-in-merge', action='store_true')
# args = parser.parse_args(argv)
#
# if not is_in_merge() and not args.assume_in_merge:
# return 0
#
# retcode = 0
# for filename in args.filenames:
# with open(filename, 'rb') as inputfile:
# for i, line in enumerate(inputfile):
# for pattern in CONFLICT_PATTERNS:
# if line.startswith(pattern):
# print(
# f'Merge conflict string "{pattern.decode()}" '
# f'found in {filename}:{i + 1}',
# )
# retcode = 1
#
# return retcode
#
# Path: pre_commit_hooks/util.py
# def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str:
# kwargs.setdefault('stdout', subprocess.PIPE)
# kwargs.setdefault('stderr', subprocess.PIPE)
# proc = subprocess.Popen(cmd, **kwargs)
# stdout, stderr = proc.communicate()
# stdout = stdout.decode()
# if retcode is not None and proc.returncode != retcode:
# raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr)
# return stdout
#
# Path: testing/util.py
# def get_resource_path(path):
# return os.path.join(TESTING_DIR, 'resources', path)
#
# Path: testing/util.py
# def git_commit(*args, **kwargs):
# cmd = ('git', 'commit', '--no-gpg-sign', '--no-verify', '--no-edit', *args)
# subprocess.check_call(cmd, **kwargs)
. Output only the next line. | @pytest.mark.usefixtures('f1_is_a_conflict_file') |
Next line prediction: <|code_start|> # Commit in master
with repo1.as_cwd():
repo1_f1.write('parent\n')
git_commit('-am', 'master commit2')
# Commit in clone and pull
with repo2.as_cwd():
repo2_f1.write('child\n')
git_commit('-am', 'clone commit2')
cmd_output('git', 'pull', '--no-rebase', retcode=None)
# We should end up in a merge conflict!
f1 = repo2_f1.read()
assert f1.startswith(
'<<<<<<< HEAD\n'
'child\n'
'=======\n'
'parent\n'
'>>>>>>>',
) or f1.startswith(
'<<<<<<< HEAD\n'
'child\n'
# diff3 conflict style git merges add this line:
'||||||| merged common ancestors\n'
'=======\n'
'parent\n'
'>>>>>>>',
) or f1.startswith(
# .gitconfig with [pull] rebase = preserve causes a rebase which
# flips parent / child
'<<<<<<< HEAD\n'
<|code_end|>
. Use current file imports:
(import os
import shutil
import pytest
from pre_commit_hooks.check_merge_conflict import main
from pre_commit_hooks.util import cmd_output
from testing.util import get_resource_path
from testing.util import git_commit)
and context including class names, function names, or small code snippets from other files:
# Path: pre_commit_hooks/check_merge_conflict.py
# def main(argv: Sequence[str] | None = None) -> int:
# parser = argparse.ArgumentParser()
# parser.add_argument('filenames', nargs='*')
# parser.add_argument('--assume-in-merge', action='store_true')
# args = parser.parse_args(argv)
#
# if not is_in_merge() and not args.assume_in_merge:
# return 0
#
# retcode = 0
# for filename in args.filenames:
# with open(filename, 'rb') as inputfile:
# for i, line in enumerate(inputfile):
# for pattern in CONFLICT_PATTERNS:
# if line.startswith(pattern):
# print(
# f'Merge conflict string "{pattern.decode()}" '
# f'found in {filename}:{i + 1}',
# )
# retcode = 1
#
# return retcode
#
# Path: pre_commit_hooks/util.py
# def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str:
# kwargs.setdefault('stdout', subprocess.PIPE)
# kwargs.setdefault('stderr', subprocess.PIPE)
# proc = subprocess.Popen(cmd, **kwargs)
# stdout, stderr = proc.communicate()
# stdout = stdout.decode()
# if retcode is not None and proc.returncode != retcode:
# raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr)
# return stdout
#
# Path: testing/util.py
# def get_resource_path(path):
# return os.path.join(TESTING_DIR, 'resources', path)
#
# Path: testing/util.py
# def git_commit(*args, **kwargs):
# cmd = ('git', 'commit', '--no-gpg-sign', '--no-verify', '--no-edit', *args)
# subprocess.check_call(cmd, **kwargs)
. Output only the next line. | 'parent\n' |
Predict the next line for this snippet: <|code_start|> fname = test_images / "test_000_.SPE"
fr1 = np.zeros((32, 32), np.uint16)
fr2 = np.ones_like(fr1)
# Test imread
im = imageio.imread(fname)
ims = imageio.mimread(fname)
np.testing.assert_equal(im, fr1)
np.testing.assert_equal(ims, [fr1, fr2])
# Test volread
vol = imageio.volread(fname)
vols = imageio.mvolread(fname)
np.testing.assert_equal(vol, [fr1, fr2])
np.testing.assert_equal(vols, [[fr1, fr2]])
# Test get_reader
r = imageio.get_reader(fname, sdt_meta=False)
np.testing.assert_equal(r.get_data(1), fr2)
np.testing.assert_equal(list(r), [fr1, fr2])
pytest.raises(IndexError, r.get_data, -1)
pytest.raises(IndexError, r.get_data, 2)
# check metadata
md = r.get_meta_data()
assert md["ROIs"] == [
<|code_end|>
with the help of current file imports:
from datetime import datetime
from imageio.plugins import spe
import numpy as np
import pytest
import imageio
and context from other files:
# Path: imageio/plugins/spe.py
# class Spec:
# class SDTControlSpec:
# class CommentDesc:
# class SpeFormat(Format):
# class Reader(Format.Reader):
# def __init__(
# self,
# n: int,
# slice: slice,
# cvt: Callable[[str], Any] = str,
# scale: Optional[float] = None,
# ):
# def parse_comments(comments: Sequence[str]) -> Union[Dict, None]:
# def get_datetime(date: str, time: str) -> Union[datetime, None]:
# def extract_metadata(meta: Mapping, char_encoding: str = "latin1"):
# def _can_read(self, request):
# def _can_write(self, request):
# def _open(self, char_encoding="latin1", check_filesize=True, sdt_meta=True):
# def _get_meta_data(self, index):
# def _close(self):
# def _init_meta_data_pre_v3(self):
# def _parse_header(self, spec):
# def _init_meta_data_post_v3(self):
# def _get_length(self):
# def _get_data(self, index):
# def roi_array_to_dict(a):
, which may contain function names, class names, or code. Output only the next line. | {"top_left": [238, 187], "bottom_right": [269, 218], "bin": [1, 1]} |
Given the code snippet: <|code_start|>
User = get_user_model()
@override_settings(AUTH_USER_MODEL='tests.VerifyEmailUser')
class TestVerifyAccountView(APIRequestTestCase):
view_class = views.VerifyAccountViewMixin
<|code_end|>
, generate the next line using the imports in this file:
import mock
from django.contrib.auth import get_user_model
from django.test import override_settings
from user_management.models.tests.factories import VerifyEmailUserFactory
from user_management.models.tests.utils import APIRequestTestCase
from .. import views
and context (functions, classes, or occasionally code) from other files:
# Path: user_management/models/tests/factories.py
# class VerifyEmailUserFactory(UserFactory):
# email_verified = False
#
# class Meta:
# model = VerifyEmailUser
#
# Path: user_management/models/tests/utils.py
# class APIRequestTestCase(Python2AssertMixin, BaseAPIRequestTestCase):
# user_factory = UserFactory
. Output only the next line. | @classmethod |
Based on the snippet: <|code_start|>
User = get_user_model()
@override_settings(AUTH_USER_MODEL='tests.VerifyEmailUser')
class TestVerifyAccountView(APIRequestTestCase):
view_class = views.VerifyAccountViewMixin
@classmethod
def setUpTestData(cls):
cls.request = mock.MagicMock
cls.view_instance = cls.view_class()
cls.user = VerifyEmailUserFactory.create(email_verified=False)
cls.token = cls.user.generate_validation_token()
<|code_end|>
, predict the immediate next line with the help of imports:
import mock
from django.contrib.auth import get_user_model
from django.test import override_settings
from user_management.models.tests.factories import VerifyEmailUserFactory
from user_management.models.tests.utils import APIRequestTestCase
from .. import views
and context (classes, functions, sometimes code) from other files:
# Path: user_management/models/tests/factories.py
# class VerifyEmailUserFactory(UserFactory):
# email_verified = False
#
# class Meta:
# model = VerifyEmailUser
#
# Path: user_management/models/tests/utils.py
# class APIRequestTestCase(Python2AssertMixin, BaseAPIRequestTestCase):
# user_factory = UserFactory
. Output only the next line. | def test_verify_token_allowed(self): |
Continue the code snippet: <|code_start|>
class UserFactory(factory.DjangoModelFactory):
name = factory.Sequence('Test User {}'.format)
email = factory.Sequence('email{}@example.com'.format)
is_active = True
class Meta:
model = get_user_model()
@factory.post_generation
def password(self, create, extracted='default password', **kwargs):
self.raw_password = extracted
self.set_password(self.raw_password)
if create:
self.save()
class VerifyEmailUserFactory(UserFactory):
<|code_end|>
. Use current file imports:
import factory
from django.contrib.auth import get_user_model
from user_management.api.models import AuthToken
from user_management.models.tests.models import VerifyEmailUser
and context (classes, functions, or code) from other files:
# Path: user_management/api/models.py
# class AuthToken(models.Model):
# """
# Model for auth tokens with added functionality of controlling
# expiration time of tokens.
#
# Similar to DRF's model but with extra `expires` field.
#
# It also has FK (not OneToOne relation) to user as the user can have
# many tokens (multiple devices) in order to token expiration to work.
# """
# key = models.CharField(max_length=40, primary_key=True)
# user = models.ForeignKey(
# settings.AUTH_USER_MODEL,
# related_name='authtoken',
# on_delete=models.CASCADE,
# )
# created = models.DateTimeField(default=timezone.now, editable=False)
# expires = models.DateTimeField(default=update_expiry, editable=False)
#
# def __str__(self):
# return self.key
#
# def save(self, *args, **kwargs):
# if not self.key:
# self.key = self.generate_key()
# return super(AuthToken, self).save(*args, **kwargs)
#
# def generate_key(self):
# return binascii.hexlify(os.urandom(20)).decode()
#
# def update_expiry(self, commit=True):
# """Update token's expiration datetime on every auth action."""
# self.expires = update_expiry(self.created)
# if commit:
# self.save()
#
# Path: user_management/models/tests/models.py
# class VerifyEmailUser(VerifyEmailMixin, AbstractBaseUser):
# pass
. Output only the next line. | email_verified = False |
Next line prediction: <|code_start|>
class UserFactory(factory.DjangoModelFactory):
name = factory.Sequence('Test User {}'.format)
email = factory.Sequence('email{}@example.com'.format)
is_active = True
class Meta:
model = get_user_model()
@factory.post_generation
def password(self, create, extracted='default password', **kwargs):
self.raw_password = extracted
self.set_password(self.raw_password)
if create:
self.save()
class VerifyEmailUserFactory(UserFactory):
<|code_end|>
. Use current file imports:
(import factory
from django.contrib.auth import get_user_model
from user_management.api.models import AuthToken
from user_management.models.tests.models import VerifyEmailUser)
and context including class names, function names, or small code snippets from other files:
# Path: user_management/api/models.py
# class AuthToken(models.Model):
# """
# Model for auth tokens with added functionality of controlling
# expiration time of tokens.
#
# Similar to DRF's model but with extra `expires` field.
#
# It also has FK (not OneToOne relation) to user as the user can have
# many tokens (multiple devices) in order to token expiration to work.
# """
# key = models.CharField(max_length=40, primary_key=True)
# user = models.ForeignKey(
# settings.AUTH_USER_MODEL,
# related_name='authtoken',
# on_delete=models.CASCADE,
# )
# created = models.DateTimeField(default=timezone.now, editable=False)
# expires = models.DateTimeField(default=update_expiry, editable=False)
#
# def __str__(self):
# return self.key
#
# def save(self, *args, **kwargs):
# if not self.key:
# self.key = self.generate_key()
# return super(AuthToken, self).save(*args, **kwargs)
#
# def generate_key(self):
# return binascii.hexlify(os.urandom(20)).decode()
#
# def update_expiry(self, commit=True):
# """Update token's expiration datetime on every auth action."""
# self.expires = update_expiry(self.created)
# if commit:
# self.save()
#
# Path: user_management/models/tests/models.py
# class VerifyEmailUser(VerifyEmailMixin, AbstractBaseUser):
# pass
. Output only the next line. | email_verified = False |
Here is a snippet: <|code_start|> def test_invalid_token(self):
data = QueryDict('', mutable=True)
data.update({'token': 'WOOT'})
request = mock.Mock(data=data)
response = FormTokenAuthentication().authenticate(request)
self.assertIsNone(response)
def test_valid_token(self):
token = AuthTokenFactory.create()
data = QueryDict('', mutable=True)
data.update({'token': token.key})
request = mock.Mock(data=data)
response = FormTokenAuthentication().authenticate(request)
expected = (token.user, token)
self.assertEqual(response, expected)
class TestTokenAuthentication(TestCase):
def setUp(self):
self.now = timezone.now()
self.days = 1
self.key = 'k$y'
self.user = UserFactory.create()
self.auth = TokenAuthentication()
def _create_token(self, when):
token = AuthTokenFactory.create(
key=self.key,
user=self.user,
expires=when,
<|code_end|>
. Write the next line using the current file imports:
import datetime
import mock
from django.http import QueryDict
from django.test import TestCase
from django.utils import timezone
from rest_framework import exceptions
from user_management.models.tests.factories import AuthTokenFactory, UserFactory
from ..authentication import FormTokenAuthentication, TokenAuthentication
and context from other files:
# Path: user_management/models/tests/factories.py
# class AuthTokenFactory(factory.DjangoModelFactory):
# key = factory.Sequence('key{}'.format)
# user = factory.SubFactory(UserFactory)
#
# class Meta:
# model = AuthToken
#
# class UserFactory(factory.DjangoModelFactory):
# name = factory.Sequence('Test User {}'.format)
# email = factory.Sequence('email{}@example.com'.format)
# is_active = True
#
# class Meta:
# model = get_user_model()
#
# @factory.post_generation
# def password(self, create, extracted='default password', **kwargs):
# self.raw_password = extracted
# self.set_password(self.raw_password)
# if create:
# self.save()
#
# Path: user_management/api/authentication.py
# class FormTokenAuthentication(authentication.BaseAuthentication):
# def authenticate(self, request):
# """
# Authenticate a user from a token form field
#
# Errors thrown here will be swallowed by django-rest-framework, and it
# expects us to return None if authentication fails.
# """
# try:
# key = request.data['token']
# except KeyError:
# return
#
# try:
# token = AuthToken.objects.get(key=key)
# except AuthToken.DoesNotExist:
# return
#
# return (token.user, token)
#
# class TokenAuthentication(DRFTokenAuthentication):
# model = AuthToken
#
# def authenticate_credentials(self, key):
# """Custom authentication to check if auth token has expired."""
# user, token = super(TokenAuthentication, self).authenticate_credentials(key)
#
# if token.expires < timezone.now():
# msg = _('Token has expired.')
# raise exceptions.AuthenticationFailed(msg)
#
# # Update the token's expiration date
# token.update_expiry()
#
# return (user, token)
, which may include functions, classes, or code. Output only the next line. | ) |
Based on the snippet: <|code_start|>
class TestFormTokenAuthentication(TestCase):
def test_no_token(self):
request = mock.Mock(data=QueryDict(''))
response = FormTokenAuthentication().authenticate(request)
self.assertIsNone(response)
<|code_end|>
, predict the immediate next line with the help of imports:
import datetime
import mock
from django.http import QueryDict
from django.test import TestCase
from django.utils import timezone
from rest_framework import exceptions
from user_management.models.tests.factories import AuthTokenFactory, UserFactory
from ..authentication import FormTokenAuthentication, TokenAuthentication
and context (classes, functions, sometimes code) from other files:
# Path: user_management/models/tests/factories.py
# class AuthTokenFactory(factory.DjangoModelFactory):
# key = factory.Sequence('key{}'.format)
# user = factory.SubFactory(UserFactory)
#
# class Meta:
# model = AuthToken
#
# class UserFactory(factory.DjangoModelFactory):
# name = factory.Sequence('Test User {}'.format)
# email = factory.Sequence('email{}@example.com'.format)
# is_active = True
#
# class Meta:
# model = get_user_model()
#
# @factory.post_generation
# def password(self, create, extracted='default password', **kwargs):
# self.raw_password = extracted
# self.set_password(self.raw_password)
# if create:
# self.save()
#
# Path: user_management/api/authentication.py
# class FormTokenAuthentication(authentication.BaseAuthentication):
# def authenticate(self, request):
# """
# Authenticate a user from a token form field
#
# Errors thrown here will be swallowed by django-rest-framework, and it
# expects us to return None if authentication fails.
# """
# try:
# key = request.data['token']
# except KeyError:
# return
#
# try:
# token = AuthToken.objects.get(key=key)
# except AuthToken.DoesNotExist:
# return
#
# return (token.user, token)
#
# class TokenAuthentication(DRFTokenAuthentication):
# model = AuthToken
#
# def authenticate_credentials(self, key):
# """Custom authentication to check if auth token has expired."""
# user, token = super(TokenAuthentication, self).authenticate_credentials(key)
#
# if token.expires < timezone.now():
# msg = _('Token has expired.')
# raise exceptions.AuthenticationFailed(msg)
#
# # Update the token's expiration date
# token.update_expiry()
#
# return (user, token)
. Output only the next line. | def test_invalid_token(self): |
Predict the next line after this snippet: <|code_start|> response = FormTokenAuthentication().authenticate(request)
self.assertIsNone(response)
def test_invalid_token(self):
data = QueryDict('', mutable=True)
data.update({'token': 'WOOT'})
request = mock.Mock(data=data)
response = FormTokenAuthentication().authenticate(request)
self.assertIsNone(response)
def test_valid_token(self):
token = AuthTokenFactory.create()
data = QueryDict('', mutable=True)
data.update({'token': token.key})
request = mock.Mock(data=data)
response = FormTokenAuthentication().authenticate(request)
expected = (token.user, token)
self.assertEqual(response, expected)
class TestTokenAuthentication(TestCase):
def setUp(self):
self.now = timezone.now()
self.days = 1
self.key = 'k$y'
self.user = UserFactory.create()
self.auth = TokenAuthentication()
def _create_token(self, when):
token = AuthTokenFactory.create(
<|code_end|>
using the current file's imports:
import datetime
import mock
from django.http import QueryDict
from django.test import TestCase
from django.utils import timezone
from rest_framework import exceptions
from user_management.models.tests.factories import AuthTokenFactory, UserFactory
from ..authentication import FormTokenAuthentication, TokenAuthentication
and any relevant context from other files:
# Path: user_management/models/tests/factories.py
# class AuthTokenFactory(factory.DjangoModelFactory):
# key = factory.Sequence('key{}'.format)
# user = factory.SubFactory(UserFactory)
#
# class Meta:
# model = AuthToken
#
# class UserFactory(factory.DjangoModelFactory):
# name = factory.Sequence('Test User {}'.format)
# email = factory.Sequence('email{}@example.com'.format)
# is_active = True
#
# class Meta:
# model = get_user_model()
#
# @factory.post_generation
# def password(self, create, extracted='default password', **kwargs):
# self.raw_password = extracted
# self.set_password(self.raw_password)
# if create:
# self.save()
#
# Path: user_management/api/authentication.py
# class FormTokenAuthentication(authentication.BaseAuthentication):
# def authenticate(self, request):
# """
# Authenticate a user from a token form field
#
# Errors thrown here will be swallowed by django-rest-framework, and it
# expects us to return None if authentication fails.
# """
# try:
# key = request.data['token']
# except KeyError:
# return
#
# try:
# token = AuthToken.objects.get(key=key)
# except AuthToken.DoesNotExist:
# return
#
# return (token.user, token)
#
# class TokenAuthentication(DRFTokenAuthentication):
# model = AuthToken
#
# def authenticate_credentials(self, key):
# """Custom authentication to check if auth token has expired."""
# user, token = super(TokenAuthentication, self).authenticate_credentials(key)
#
# if token.expires < timezone.now():
# msg = _('Token has expired.')
# raise exceptions.AuthenticationFailed(msg)
#
# # Update the token's expiration date
# token.update_expiry()
#
# return (user, token)
. Output only the next line. | key=self.key, |
Using the snippet: <|code_start|>
class TestFormTokenAuthentication(TestCase):
def test_no_token(self):
request = mock.Mock(data=QueryDict(''))
response = FormTokenAuthentication().authenticate(request)
self.assertIsNone(response)
def test_invalid_token(self):
data = QueryDict('', mutable=True)
data.update({'token': 'WOOT'})
request = mock.Mock(data=data)
response = FormTokenAuthentication().authenticate(request)
self.assertIsNone(response)
<|code_end|>
, determine the next line of code. You have imports:
import datetime
import mock
from django.http import QueryDict
from django.test import TestCase
from django.utils import timezone
from rest_framework import exceptions
from user_management.models.tests.factories import AuthTokenFactory, UserFactory
from ..authentication import FormTokenAuthentication, TokenAuthentication
and context (class names, function names, or code) available:
# Path: user_management/models/tests/factories.py
# class AuthTokenFactory(factory.DjangoModelFactory):
# key = factory.Sequence('key{}'.format)
# user = factory.SubFactory(UserFactory)
#
# class Meta:
# model = AuthToken
#
# class UserFactory(factory.DjangoModelFactory):
# name = factory.Sequence('Test User {}'.format)
# email = factory.Sequence('email{}@example.com'.format)
# is_active = True
#
# class Meta:
# model = get_user_model()
#
# @factory.post_generation
# def password(self, create, extracted='default password', **kwargs):
# self.raw_password = extracted
# self.set_password(self.raw_password)
# if create:
# self.save()
#
# Path: user_management/api/authentication.py
# class FormTokenAuthentication(authentication.BaseAuthentication):
# def authenticate(self, request):
# """
# Authenticate a user from a token form field
#
# Errors thrown here will be swallowed by django-rest-framework, and it
# expects us to return None if authentication fails.
# """
# try:
# key = request.data['token']
# except KeyError:
# return
#
# try:
# token = AuthToken.objects.get(key=key)
# except AuthToken.DoesNotExist:
# return
#
# return (token.user, token)
#
# class TokenAuthentication(DRFTokenAuthentication):
# model = AuthToken
#
# def authenticate_credentials(self, key):
# """Custom authentication to check if auth token has expired."""
# user, token = super(TokenAuthentication, self).authenticate_credentials(key)
#
# if token.expires < timezone.now():
# msg = _('Token has expired.')
# raise exceptions.AuthenticationFailed(msg)
#
# # Update the token's expiration date
# token.update_expiry()
#
# return (user, token)
. Output only the next line. | def test_valid_token(self): |
Given snippet: <|code_start|>
class TestAuthToken(utils.APIRequestTestCase):
model = AuthToken
def test_fields(self):
fields = {field.name for field in self.model._meta.get_fields()}
expected = (
# Inherited from subclassed model
'key',
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from user_management.models.tests import factories, utils
from ..models import AuthToken
and context:
# Path: user_management/models/tests/factories.py
# class UserFactory(factory.DjangoModelFactory):
# class Meta:
# class VerifyEmailUserFactory(UserFactory):
# class Meta:
# class AuthTokenFactory(factory.DjangoModelFactory):
# class Meta:
# def password(self, create, extracted='default password', **kwargs):
#
# Path: user_management/models/tests/utils.py
# class APIRequestTestCase(Python2AssertMixin, BaseAPIRequestTestCase):
# class RequestTestCase(Python2AssertMixin, BaseRequestTestCase):
#
# Path: user_management/api/models.py
# class AuthToken(models.Model):
# """
# Model for auth tokens with added functionality of controlling
# expiration time of tokens.
#
# Similar to DRF's model but with extra `expires` field.
#
# It also has FK (not OneToOne relation) to user as the user can have
# many tokens (multiple devices) in order to token expiration to work.
# """
# key = models.CharField(max_length=40, primary_key=True)
# user = models.ForeignKey(
# settings.AUTH_USER_MODEL,
# related_name='authtoken',
# on_delete=models.CASCADE,
# )
# created = models.DateTimeField(default=timezone.now, editable=False)
# expires = models.DateTimeField(default=update_expiry, editable=False)
#
# def __str__(self):
# return self.key
#
# def save(self, *args, **kwargs):
# if not self.key:
# self.key = self.generate_key()
# return super(AuthToken, self).save(*args, **kwargs)
#
# def generate_key(self):
# return binascii.hexlify(os.urandom(20)).decode()
#
# def update_expiry(self, commit=True):
# """Update token's expiration datetime on every auth action."""
# self.expires = update_expiry(self.created)
# if commit:
# self.save()
which might include code, classes, or functions. Output only the next line. | 'user', |
Next line prediction: <|code_start|>
class TestAuthToken(utils.APIRequestTestCase):
model = AuthToken
def test_fields(self):
fields = {field.name for field in self.model._meta.get_fields()}
expected = (
# Inherited from subclassed model
'key',
<|code_end|>
. Use current file imports:
(from user_management.models.tests import factories, utils
from ..models import AuthToken)
and context including class names, function names, or small code snippets from other files:
# Path: user_management/models/tests/factories.py
# class UserFactory(factory.DjangoModelFactory):
# class Meta:
# class VerifyEmailUserFactory(UserFactory):
# class Meta:
# class AuthTokenFactory(factory.DjangoModelFactory):
# class Meta:
# def password(self, create, extracted='default password', **kwargs):
#
# Path: user_management/models/tests/utils.py
# class APIRequestTestCase(Python2AssertMixin, BaseAPIRequestTestCase):
# class RequestTestCase(Python2AssertMixin, BaseRequestTestCase):
#
# Path: user_management/api/models.py
# class AuthToken(models.Model):
# """
# Model for auth tokens with added functionality of controlling
# expiration time of tokens.
#
# Similar to DRF's model but with extra `expires` field.
#
# It also has FK (not OneToOne relation) to user as the user can have
# many tokens (multiple devices) in order to token expiration to work.
# """
# key = models.CharField(max_length=40, primary_key=True)
# user = models.ForeignKey(
# settings.AUTH_USER_MODEL,
# related_name='authtoken',
# on_delete=models.CASCADE,
# )
# created = models.DateTimeField(default=timezone.now, editable=False)
# expires = models.DateTimeField(default=update_expiry, editable=False)
#
# def __str__(self):
# return self.key
#
# def save(self, *args, **kwargs):
# if not self.key:
# self.key = self.generate_key()
# return super(AuthToken, self).save(*args, **kwargs)
#
# def generate_key(self):
# return binascii.hexlify(os.urandom(20)).decode()
#
# def update_expiry(self, commit=True):
# """Update token's expiration datetime on every auth action."""
# self.expires = update_expiry(self.created)
# if commit:
# self.save()
. Output only the next line. | 'user', |
Predict the next line for this snippet: <|code_start|>
class TestAuthToken(utils.APIRequestTestCase):
model = AuthToken
def test_fields(self):
fields = {field.name for field in self.model._meta.get_fields()}
expected = (
# Inherited from subclassed model
'key',
'user',
<|code_end|>
with the help of current file imports:
from user_management.models.tests import factories, utils
from ..models import AuthToken
and context from other files:
# Path: user_management/models/tests/factories.py
# class UserFactory(factory.DjangoModelFactory):
# class Meta:
# class VerifyEmailUserFactory(UserFactory):
# class Meta:
# class AuthTokenFactory(factory.DjangoModelFactory):
# class Meta:
# def password(self, create, extracted='default password', **kwargs):
#
# Path: user_management/models/tests/utils.py
# class APIRequestTestCase(Python2AssertMixin, BaseAPIRequestTestCase):
# class RequestTestCase(Python2AssertMixin, BaseRequestTestCase):
#
# Path: user_management/api/models.py
# class AuthToken(models.Model):
# """
# Model for auth tokens with added functionality of controlling
# expiration time of tokens.
#
# Similar to DRF's model but with extra `expires` field.
#
# It also has FK (not OneToOne relation) to user as the user can have
# many tokens (multiple devices) in order to token expiration to work.
# """
# key = models.CharField(max_length=40, primary_key=True)
# user = models.ForeignKey(
# settings.AUTH_USER_MODEL,
# related_name='authtoken',
# on_delete=models.CASCADE,
# )
# created = models.DateTimeField(default=timezone.now, editable=False)
# expires = models.DateTimeField(default=update_expiry, editable=False)
#
# def __str__(self):
# return self.key
#
# def save(self, *args, **kwargs):
# if not self.key:
# self.key = self.generate_key()
# return super(AuthToken, self).save(*args, **kwargs)
#
# def generate_key(self):
# return binascii.hexlify(os.urandom(20)).decode()
#
# def update_expiry(self, commit=True):
# """Update token's expiration datetime on every auth action."""
# self.expires = update_expiry(self.created)
# if commit:
# self.save()
, which may contain function names, class names, or code. Output only the next line. | 'created', |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
class PasswordsTest(TestCase):
too_simple = (
'Password must have at least ' +
'one upper case letter, one lower case letter, and one number.'
)
too_fancy = (
'Password only accepts the following symbols ' + string.punctuation
)
def test_no_upper(self):
password = 'aaaa1111'
<|code_end|>
using the current file's imports:
import string
from django.core.exceptions import ValidationError
from django.test import TestCase
from ..validators import validate_password_strength
and any relevant context from other files:
# Path: user_management/utils/validators.py
# def validate_password_strength(value):
# """
# Passwords should be tough.
#
# That means they should use:
# - mixed case letters,
# - numbers,
# - (optionally) ascii symbols and spaces.
#
# The (contrversial?) decision to limit the passwords to ASCII only
# is for the sake of:
# - simplicity (no need to normalise UTF-8 input)
# - security (some character sets are visible as typed into password fields)
#
# TODO: In future, it may be worth considering:
# - rejecting common passwords. (Where can we get a list?)
# - rejecting passwords with too many repeated characters.
#
# It should be noted that no restriction has been placed on the length of the
# password here, as that can easily be achieved with use of the min_length
# attribute of a form/serializer field.
# """
# used_chars = set(value)
# good_chars = set(ascii_letters + digits + punctuation + ' ')
# required_sets = (ascii_uppercase, ascii_lowercase, digits)
#
# if not used_chars.issubset(good_chars):
# raise ValidationError(too_fancy)
#
# for required in required_sets:
# if not used_chars.intersection(required):
# raise ValidationError(too_simple)
. Output only the next line. | with self.assertRaises(ValidationError) as error: |
Based on the snippet: <|code_start|>
class VerifyUserAdminTest(TestCase):
def setUp(self):
self.site = AdminSite()
def test_create_fieldsets(self):
expected_fieldsets = (
(None, {
<|code_end|>
, predict the immediate next line with the help of imports:
from django.contrib.admin.sites import AdminSite
from django.test import TestCase
from .factories import UserFactory
from .models import User
from ..admin import VerifyUserAdmin
and context (classes, functions, sometimes code) from other files:
# Path: user_management/models/tests/factories.py
# class UserFactory(factory.DjangoModelFactory):
# name = factory.Sequence('Test User {}'.format)
# email = factory.Sequence('email{}@example.com'.format)
# is_active = True
#
# class Meta:
# model = get_user_model()
#
# @factory.post_generation
# def password(self, create, extracted='default password', **kwargs):
# self.raw_password = extracted
# self.set_password(self.raw_password)
# if create:
# self.save()
#
# Path: user_management/models/tests/models.py
# class User(AvatarMixin, VerifyEmailMixin, PermissionsMixin, AbstractBaseUser):
# pass
#
# Path: user_management/models/admin.py
# class VerifyUserAdmin(UserAdmin):
# readonly_fields = ('date_joined', 'email_verified')
#
# def get_fieldsets(self, request, obj=None):
# fieldsets = super(VerifyUserAdmin, self).get_fieldsets(request, obj)
# fieldsets_dict = OrderedDict(fieldsets)
#
# try:
# fields = list(fieldsets_dict['Permissions']['fields'])
# except KeyError:
# return fieldsets
#
# try:
# index = fields.index('is_active')
# except ValueError:
# # If get_fieldsets is called twice, 'is_active' will already be
# # removed and fieldsets will be correct so return it
# return fieldsets
#
# fields[index] = ('is_active', 'email_verified')
# fieldsets_dict['Permissions']['fields'] = tuple(fields)
# return tuple(fieldsets_dict.items())
. Output only the next line. | 'classes': ('wide',), |
Given the following code snippet before the placeholder: <|code_start|>
class VerifyUserAdminTest(TestCase):
def setUp(self):
self.site = AdminSite()
def test_create_fieldsets(self):
expected_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2'),
}),
)
verify_user_admin = VerifyUserAdmin(User, self.site)
self.assertEqual(
verify_user_admin.get_fieldsets(request=None),
expected_fieldsets,
)
def test_fieldsets(self):
expected_fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal info', {'fields': ('name',)}),
('Permissions', {
'fields': (
('is_active', 'email_verified'),
'is_staff',
'is_superuser',
'groups',
<|code_end|>
, predict the next line using imports from the current file:
from django.contrib.admin.sites import AdminSite
from django.test import TestCase
from .factories import UserFactory
from .models import User
from ..admin import VerifyUserAdmin
and context including class names, function names, and sometimes code from other files:
# Path: user_management/models/tests/factories.py
# class UserFactory(factory.DjangoModelFactory):
# name = factory.Sequence('Test User {}'.format)
# email = factory.Sequence('email{}@example.com'.format)
# is_active = True
#
# class Meta:
# model = get_user_model()
#
# @factory.post_generation
# def password(self, create, extracted='default password', **kwargs):
# self.raw_password = extracted
# self.set_password(self.raw_password)
# if create:
# self.save()
#
# Path: user_management/models/tests/models.py
# class User(AvatarMixin, VerifyEmailMixin, PermissionsMixin, AbstractBaseUser):
# pass
#
# Path: user_management/models/admin.py
# class VerifyUserAdmin(UserAdmin):
# readonly_fields = ('date_joined', 'email_verified')
#
# def get_fieldsets(self, request, obj=None):
# fieldsets = super(VerifyUserAdmin, self).get_fieldsets(request, obj)
# fieldsets_dict = OrderedDict(fieldsets)
#
# try:
# fields = list(fieldsets_dict['Permissions']['fields'])
# except KeyError:
# return fieldsets
#
# try:
# index = fields.index('is_active')
# except ValueError:
# # If get_fieldsets is called twice, 'is_active' will already be
# # removed and fieldsets will be correct so return it
# return fieldsets
#
# fields[index] = ('is_active', 'email_verified')
# fieldsets_dict['Permissions']['fields'] = tuple(fields)
# return tuple(fieldsets_dict.items())
. Output only the next line. | 'user_permissions', |
Here is a snippet: <|code_start|>
def test_create_fieldsets(self):
expected_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2'),
}),
)
verify_user_admin = VerifyUserAdmin(User, self.site)
self.assertEqual(
verify_user_admin.get_fieldsets(request=None),
expected_fieldsets,
)
def test_fieldsets(self):
expected_fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal info', {'fields': ('name',)}),
('Permissions', {
'fields': (
('is_active', 'email_verified'),
'is_staff',
'is_superuser',
'groups',
'user_permissions',
)
}),
('Important dates', {
'fields': ('last_login', 'date_joined'),
<|code_end|>
. Write the next line using the current file imports:
from django.contrib.admin.sites import AdminSite
from django.test import TestCase
from .factories import UserFactory
from .models import User
from ..admin import VerifyUserAdmin
and context from other files:
# Path: user_management/models/tests/factories.py
# class UserFactory(factory.DjangoModelFactory):
# name = factory.Sequence('Test User {}'.format)
# email = factory.Sequence('email{}@example.com'.format)
# is_active = True
#
# class Meta:
# model = get_user_model()
#
# @factory.post_generation
# def password(self, create, extracted='default password', **kwargs):
# self.raw_password = extracted
# self.set_password(self.raw_password)
# if create:
# self.save()
#
# Path: user_management/models/tests/models.py
# class User(AvatarMixin, VerifyEmailMixin, PermissionsMixin, AbstractBaseUser):
# pass
#
# Path: user_management/models/admin.py
# class VerifyUserAdmin(UserAdmin):
# readonly_fields = ('date_joined', 'email_verified')
#
# def get_fieldsets(self, request, obj=None):
# fieldsets = super(VerifyUserAdmin, self).get_fieldsets(request, obj)
# fieldsets_dict = OrderedDict(fieldsets)
#
# try:
# fields = list(fieldsets_dict['Permissions']['fields'])
# except KeyError:
# return fieldsets
#
# try:
# index = fields.index('is_active')
# except ValueError:
# # If get_fieldsets is called twice, 'is_active' will already be
# # removed and fieldsets will be correct so return it
# return fieldsets
#
# fields[index] = ('is_active', 'email_verified')
# fieldsets_dict['Permissions']['fields'] = tuple(fields)
# return tuple(fieldsets_dict.items())
, which may include functions, classes, or code. Output only the next line. | }), |
Given snippet: <|code_start|>
class TestRemoveExpiredTokensManagementCommand(utils.APIRequestTestCase):
def setUp(self):
self.command = remove_expired_tokens.Command()
self.command.stdout = mock.MagicMock()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import datetime
import mock
from django.test.utils import override_settings
from django.utils import timezone
from user_management.api.models import AuthToken
from user_management.models.tests import utils
from user_management.models.tests.factories import AuthTokenFactory
from ..management.commands import remove_expired_tokens
and context:
# Path: user_management/api/models.py
# class AuthToken(models.Model):
# """
# Model for auth tokens with added functionality of controlling
# expiration time of tokens.
#
# Similar to DRF's model but with extra `expires` field.
#
# It also has FK (not OneToOne relation) to user as the user can have
# many tokens (multiple devices) in order to token expiration to work.
# """
# key = models.CharField(max_length=40, primary_key=True)
# user = models.ForeignKey(
# settings.AUTH_USER_MODEL,
# related_name='authtoken',
# on_delete=models.CASCADE,
# )
# created = models.DateTimeField(default=timezone.now, editable=False)
# expires = models.DateTimeField(default=update_expiry, editable=False)
#
# def __str__(self):
# return self.key
#
# def save(self, *args, **kwargs):
# if not self.key:
# self.key = self.generate_key()
# return super(AuthToken, self).save(*args, **kwargs)
#
# def generate_key(self):
# return binascii.hexlify(os.urandom(20)).decode()
#
# def update_expiry(self, commit=True):
# """Update token's expiration datetime on every auth action."""
# self.expires = update_expiry(self.created)
# if commit:
# self.save()
#
# Path: user_management/models/tests/utils.py
# class APIRequestTestCase(Python2AssertMixin, BaseAPIRequestTestCase):
# class RequestTestCase(Python2AssertMixin, BaseRequestTestCase):
#
# Path: user_management/models/tests/factories.py
# class AuthTokenFactory(factory.DjangoModelFactory):
# key = factory.Sequence('key{}'.format)
# user = factory.SubFactory(UserFactory)
#
# class Meta:
# model = AuthToken
#
# Path: user_management/api/management/commands/remove_expired_tokens.py
# class Command(BaseCommand):
# def handle(self, *args, **options):
which might include code, classes, or functions. Output only the next line. | def test_no_tokens_removed(self): |
Given snippet: <|code_start|>
class TestRemoveExpiredTokensManagementCommand(utils.APIRequestTestCase):
def setUp(self):
self.command = remove_expired_tokens.Command()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import datetime
import mock
from django.test.utils import override_settings
from django.utils import timezone
from user_management.api.models import AuthToken
from user_management.models.tests import utils
from user_management.models.tests.factories import AuthTokenFactory
from ..management.commands import remove_expired_tokens
and context:
# Path: user_management/api/models.py
# class AuthToken(models.Model):
# """
# Model for auth tokens with added functionality of controlling
# expiration time of tokens.
#
# Similar to DRF's model but with extra `expires` field.
#
# It also has FK (not OneToOne relation) to user as the user can have
# many tokens (multiple devices) in order to token expiration to work.
# """
# key = models.CharField(max_length=40, primary_key=True)
# user = models.ForeignKey(
# settings.AUTH_USER_MODEL,
# related_name='authtoken',
# on_delete=models.CASCADE,
# )
# created = models.DateTimeField(default=timezone.now, editable=False)
# expires = models.DateTimeField(default=update_expiry, editable=False)
#
# def __str__(self):
# return self.key
#
# def save(self, *args, **kwargs):
# if not self.key:
# self.key = self.generate_key()
# return super(AuthToken, self).save(*args, **kwargs)
#
# def generate_key(self):
# return binascii.hexlify(os.urandom(20)).decode()
#
# def update_expiry(self, commit=True):
# """Update token's expiration datetime on every auth action."""
# self.expires = update_expiry(self.created)
# if commit:
# self.save()
#
# Path: user_management/models/tests/utils.py
# class APIRequestTestCase(Python2AssertMixin, BaseAPIRequestTestCase):
# class RequestTestCase(Python2AssertMixin, BaseRequestTestCase):
#
# Path: user_management/models/tests/factories.py
# class AuthTokenFactory(factory.DjangoModelFactory):
# key = factory.Sequence('key{}'.format)
# user = factory.SubFactory(UserFactory)
#
# class Meta:
# model = AuthToken
#
# Path: user_management/api/management/commands/remove_expired_tokens.py
# class Command(BaseCommand):
# def handle(self, *args, **options):
which might include code, classes, or functions. Output only the next line. | self.command.stdout = mock.MagicMock() |
Given the code snippet: <|code_start|>
class TestRemoveExpiredTokensManagementCommand(utils.APIRequestTestCase):
def setUp(self):
self.command = remove_expired_tokens.Command()
self.command.stdout = mock.MagicMock()
<|code_end|>
, generate the next line using the imports in this file:
import datetime
import mock
from django.test.utils import override_settings
from django.utils import timezone
from user_management.api.models import AuthToken
from user_management.models.tests import utils
from user_management.models.tests.factories import AuthTokenFactory
from ..management.commands import remove_expired_tokens
and context (functions, classes, or occasionally code) from other files:
# Path: user_management/api/models.py
# class AuthToken(models.Model):
# """
# Model for auth tokens with added functionality of controlling
# expiration time of tokens.
#
# Similar to DRF's model but with extra `expires` field.
#
# It also has FK (not OneToOne relation) to user as the user can have
# many tokens (multiple devices) in order to token expiration to work.
# """
# key = models.CharField(max_length=40, primary_key=True)
# user = models.ForeignKey(
# settings.AUTH_USER_MODEL,
# related_name='authtoken',
# on_delete=models.CASCADE,
# )
# created = models.DateTimeField(default=timezone.now, editable=False)
# expires = models.DateTimeField(default=update_expiry, editable=False)
#
# def __str__(self):
# return self.key
#
# def save(self, *args, **kwargs):
# if not self.key:
# self.key = self.generate_key()
# return super(AuthToken, self).save(*args, **kwargs)
#
# def generate_key(self):
# return binascii.hexlify(os.urandom(20)).decode()
#
# def update_expiry(self, commit=True):
# """Update token's expiration datetime on every auth action."""
# self.expires = update_expiry(self.created)
# if commit:
# self.save()
#
# Path: user_management/models/tests/utils.py
# class APIRequestTestCase(Python2AssertMixin, BaseAPIRequestTestCase):
# class RequestTestCase(Python2AssertMixin, BaseRequestTestCase):
#
# Path: user_management/models/tests/factories.py
# class AuthTokenFactory(factory.DjangoModelFactory):
# key = factory.Sequence('key{}'.format)
# user = factory.SubFactory(UserFactory)
#
# class Meta:
# model = AuthToken
#
# Path: user_management/api/management/commands/remove_expired_tokens.py
# class Command(BaseCommand):
# def handle(self, *args, **options):
. Output only the next line. | def test_no_tokens_removed(self): |
Next line prediction: <|code_start|>
class TestRemoveExpiredTokensManagementCommand(utils.APIRequestTestCase):
def setUp(self):
self.command = remove_expired_tokens.Command()
self.command.stdout = mock.MagicMock()
<|code_end|>
. Use current file imports:
(import datetime
import mock
from django.test.utils import override_settings
from django.utils import timezone
from user_management.api.models import AuthToken
from user_management.models.tests import utils
from user_management.models.tests.factories import AuthTokenFactory
from ..management.commands import remove_expired_tokens)
and context including class names, function names, or small code snippets from other files:
# Path: user_management/api/models.py
# class AuthToken(models.Model):
# """
# Model for auth tokens with added functionality of controlling
# expiration time of tokens.
#
# Similar to DRF's model but with extra `expires` field.
#
# It also has FK (not OneToOne relation) to user as the user can have
# many tokens (multiple devices) in order to token expiration to work.
# """
# key = models.CharField(max_length=40, primary_key=True)
# user = models.ForeignKey(
# settings.AUTH_USER_MODEL,
# related_name='authtoken',
# on_delete=models.CASCADE,
# )
# created = models.DateTimeField(default=timezone.now, editable=False)
# expires = models.DateTimeField(default=update_expiry, editable=False)
#
# def __str__(self):
# return self.key
#
# def save(self, *args, **kwargs):
# if not self.key:
# self.key = self.generate_key()
# return super(AuthToken, self).save(*args, **kwargs)
#
# def generate_key(self):
# return binascii.hexlify(os.urandom(20)).decode()
#
# def update_expiry(self, commit=True):
# """Update token's expiration datetime on every auth action."""
# self.expires = update_expiry(self.created)
# if commit:
# self.save()
#
# Path: user_management/models/tests/utils.py
# class APIRequestTestCase(Python2AssertMixin, BaseAPIRequestTestCase):
# class RequestTestCase(Python2AssertMixin, BaseRequestTestCase):
#
# Path: user_management/models/tests/factories.py
# class AuthTokenFactory(factory.DjangoModelFactory):
# key = factory.Sequence('key{}'.format)
# user = factory.SubFactory(UserFactory)
#
# class Meta:
# model = AuthToken
#
# Path: user_management/api/management/commands/remove_expired_tokens.py
# class Command(BaseCommand):
# def handle(self, *args, **options):
. Output only the next line. | def test_no_tokens_removed(self): |
Given the code snippet: <|code_start|>
class User(AvatarMixin, VerifyEmailMixin, PermissionsMixin, AbstractBaseUser):
pass
class BasicUser(BasicUserFieldsMixin, AbstractBaseUser):
pass
class VerifyEmailUser(VerifyEmailMixin, AbstractBaseUser):
<|code_end|>
, generate the next line using the imports in this file:
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.db import models
from .notifications import CustomPasswordResetNotification
from ..mixins import (
AvatarMixin,
BasicUserFieldsMixin,
DateJoinedUserMixin,
EmailUserMixin,
EmailVerifyUserMixin,
IsStaffUserMixin,
NameUserMethodsMixin,
VerifyEmailMixin,
)
and context (functions, classes, or occasionally code) from other files:
# Path: user_management/models/tests/notifications.py
# class CustomPasswordResetNotification(PasswordResetNotification):
# """Test setting a custom notification to alter how we send the password reset."""
# text_email_template = 'my_custom_email.txt'
# html_email_template = None
# headers = {'test-header': 'Test'}
#
# Path: user_management/models/mixins.py
# class AvatarMixin(models.Model):
# avatar = models.ImageField(upload_to='user_avatar', null=True, blank=True)
#
# class Meta:
# abstract = True
#
# class BasicUserFieldsMixin(
# DateJoinedUserMixin, EmailUserMixin, IsStaffUserMixin, NameUserMixin):
# class Meta:
# abstract = True
#
# class DateJoinedUserMixin(models.Model):
# date_joined = models.DateTimeField(
# verbose_name=_('date joined'),
# default=timezone.now,
# editable=False,
# )
#
# class Meta:
# abstract = True
#
# class EmailUserMixin(models.Model):
# email = CIEmailField(
# verbose_name=_('Email address'),
# unique=True,
# max_length=511,
# )
# email_verified = True
#
# objects = UserManager()
#
# USERNAME_FIELD = 'email'
#
# class Meta:
# abstract = True
#
# class EmailVerifyUserMixin(EmailVerifyUserMethodsMixin, models.Model):
# is_active = models.BooleanField(_('active'), default=False)
# email_verified = models.BooleanField(
# _('Email verified?'),
# default=False,
# help_text=_('Indicates if the email address has been verified.'))
#
# objects = VerifyEmailManager()
#
# class Meta:
# abstract = True
#
# @classmethod
# def check(cls, **kwargs):
# errors = super(EmailVerifyUserMixin, cls).check(**kwargs)
# errors.extend(cls._check_manager(**kwargs))
# return errors
#
# @classmethod
# def _check_manager(cls, **kwargs):
# if isinstance(cls.objects, VerifyEmailManager):
# return []
#
# return [
# checks.Warning(
# "Manager should be an instance of 'VerifyEmailManager'",
# hint="Subclass a custom manager from 'VerifyEmailManager'",
# obj=cls,
# id='user_management.W001',
# ),
# ]
#
# class IsStaffUserMixin(models.Model):
# is_staff = models.BooleanField(_('staff status'), default=False)
#
# class Meta:
# abstract = True
#
# class NameUserMethodsMixin:
# def get_full_name(self):
# return self.name
#
# def get_short_name(self):
# return self.name
#
# def __str__(self):
# return self.name
#
# class VerifyEmailMixin(EmailVerifyUserMixin, BasicUserFieldsMixin):
# class Meta:
# abstract = True
. Output only the next line. | pass |
Predict the next line after this snippet: <|code_start|>
class User(AvatarMixin, VerifyEmailMixin, PermissionsMixin, AbstractBaseUser):
pass
class BasicUser(BasicUserFieldsMixin, AbstractBaseUser):
pass
class VerifyEmailUser(VerifyEmailMixin, AbstractBaseUser):
<|code_end|>
using the current file's imports:
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.db import models
from .notifications import CustomPasswordResetNotification
from ..mixins import (
AvatarMixin,
BasicUserFieldsMixin,
DateJoinedUserMixin,
EmailUserMixin,
EmailVerifyUserMixin,
IsStaffUserMixin,
NameUserMethodsMixin,
VerifyEmailMixin,
)
and any relevant context from other files:
# Path: user_management/models/tests/notifications.py
# class CustomPasswordResetNotification(PasswordResetNotification):
# """Test setting a custom notification to alter how we send the password reset."""
# text_email_template = 'my_custom_email.txt'
# html_email_template = None
# headers = {'test-header': 'Test'}
#
# Path: user_management/models/mixins.py
# class AvatarMixin(models.Model):
# avatar = models.ImageField(upload_to='user_avatar', null=True, blank=True)
#
# class Meta:
# abstract = True
#
# class BasicUserFieldsMixin(
# DateJoinedUserMixin, EmailUserMixin, IsStaffUserMixin, NameUserMixin):
# class Meta:
# abstract = True
#
# class DateJoinedUserMixin(models.Model):
# date_joined = models.DateTimeField(
# verbose_name=_('date joined'),
# default=timezone.now,
# editable=False,
# )
#
# class Meta:
# abstract = True
#
# class EmailUserMixin(models.Model):
# email = CIEmailField(
# verbose_name=_('Email address'),
# unique=True,
# max_length=511,
# )
# email_verified = True
#
# objects = UserManager()
#
# USERNAME_FIELD = 'email'
#
# class Meta:
# abstract = True
#
# class EmailVerifyUserMixin(EmailVerifyUserMethodsMixin, models.Model):
# is_active = models.BooleanField(_('active'), default=False)
# email_verified = models.BooleanField(
# _('Email verified?'),
# default=False,
# help_text=_('Indicates if the email address has been verified.'))
#
# objects = VerifyEmailManager()
#
# class Meta:
# abstract = True
#
# @classmethod
# def check(cls, **kwargs):
# errors = super(EmailVerifyUserMixin, cls).check(**kwargs)
# errors.extend(cls._check_manager(**kwargs))
# return errors
#
# @classmethod
# def _check_manager(cls, **kwargs):
# if isinstance(cls.objects, VerifyEmailManager):
# return []
#
# return [
# checks.Warning(
# "Manager should be an instance of 'VerifyEmailManager'",
# hint="Subclass a custom manager from 'VerifyEmailManager'",
# obj=cls,
# id='user_management.W001',
# ),
# ]
#
# class IsStaffUserMixin(models.Model):
# is_staff = models.BooleanField(_('staff status'), default=False)
#
# class Meta:
# abstract = True
#
# class NameUserMethodsMixin:
# def get_full_name(self):
# return self.name
#
# def get_short_name(self):
# return self.name
#
# def __str__(self):
# return self.name
#
# class VerifyEmailMixin(EmailVerifyUserMixin, BasicUserFieldsMixin):
# class Meta:
# abstract = True
. Output only the next line. | pass |
Given snippet: <|code_start|>
class User(AvatarMixin, VerifyEmailMixin, PermissionsMixin, AbstractBaseUser):
pass
class BasicUser(BasicUserFieldsMixin, AbstractBaseUser):
pass
class VerifyEmailUser(VerifyEmailMixin, AbstractBaseUser):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.db import models
from .notifications import CustomPasswordResetNotification
from ..mixins import (
AvatarMixin,
BasicUserFieldsMixin,
DateJoinedUserMixin,
EmailUserMixin,
EmailVerifyUserMixin,
IsStaffUserMixin,
NameUserMethodsMixin,
VerifyEmailMixin,
)
and context:
# Path: user_management/models/tests/notifications.py
# class CustomPasswordResetNotification(PasswordResetNotification):
# """Test setting a custom notification to alter how we send the password reset."""
# text_email_template = 'my_custom_email.txt'
# html_email_template = None
# headers = {'test-header': 'Test'}
#
# Path: user_management/models/mixins.py
# class AvatarMixin(models.Model):
# avatar = models.ImageField(upload_to='user_avatar', null=True, blank=True)
#
# class Meta:
# abstract = True
#
# class BasicUserFieldsMixin(
# DateJoinedUserMixin, EmailUserMixin, IsStaffUserMixin, NameUserMixin):
# class Meta:
# abstract = True
#
# class DateJoinedUserMixin(models.Model):
# date_joined = models.DateTimeField(
# verbose_name=_('date joined'),
# default=timezone.now,
# editable=False,
# )
#
# class Meta:
# abstract = True
#
# class EmailUserMixin(models.Model):
# email = CIEmailField(
# verbose_name=_('Email address'),
# unique=True,
# max_length=511,
# )
# email_verified = True
#
# objects = UserManager()
#
# USERNAME_FIELD = 'email'
#
# class Meta:
# abstract = True
#
# class EmailVerifyUserMixin(EmailVerifyUserMethodsMixin, models.Model):
# is_active = models.BooleanField(_('active'), default=False)
# email_verified = models.BooleanField(
# _('Email verified?'),
# default=False,
# help_text=_('Indicates if the email address has been verified.'))
#
# objects = VerifyEmailManager()
#
# class Meta:
# abstract = True
#
# @classmethod
# def check(cls, **kwargs):
# errors = super(EmailVerifyUserMixin, cls).check(**kwargs)
# errors.extend(cls._check_manager(**kwargs))
# return errors
#
# @classmethod
# def _check_manager(cls, **kwargs):
# if isinstance(cls.objects, VerifyEmailManager):
# return []
#
# return [
# checks.Warning(
# "Manager should be an instance of 'VerifyEmailManager'",
# hint="Subclass a custom manager from 'VerifyEmailManager'",
# obj=cls,
# id='user_management.W001',
# ),
# ]
#
# class IsStaffUserMixin(models.Model):
# is_staff = models.BooleanField(_('staff status'), default=False)
#
# class Meta:
# abstract = True
#
# class NameUserMethodsMixin:
# def get_full_name(self):
# return self.name
#
# def get_short_name(self):
# return self.name
#
# def __str__(self):
# return self.name
#
# class VerifyEmailMixin(EmailVerifyUserMixin, BasicUserFieldsMixin):
# class Meta:
# abstract = True
which might include code, classes, or functions. Output only the next line. | pass |
Using the snippet: <|code_start|>
class User(AvatarMixin, VerifyEmailMixin, PermissionsMixin, AbstractBaseUser):
pass
class BasicUser(BasicUserFieldsMixin, AbstractBaseUser):
<|code_end|>
, determine the next line of code. You have imports:
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.db import models
from .notifications import CustomPasswordResetNotification
from ..mixins import (
AvatarMixin,
BasicUserFieldsMixin,
DateJoinedUserMixin,
EmailUserMixin,
EmailVerifyUserMixin,
IsStaffUserMixin,
NameUserMethodsMixin,
VerifyEmailMixin,
)
and context (class names, function names, or code) available:
# Path: user_management/models/tests/notifications.py
# class CustomPasswordResetNotification(PasswordResetNotification):
# """Test setting a custom notification to alter how we send the password reset."""
# text_email_template = 'my_custom_email.txt'
# html_email_template = None
# headers = {'test-header': 'Test'}
#
# Path: user_management/models/mixins.py
# class AvatarMixin(models.Model):
# avatar = models.ImageField(upload_to='user_avatar', null=True, blank=True)
#
# class Meta:
# abstract = True
#
# class BasicUserFieldsMixin(
# DateJoinedUserMixin, EmailUserMixin, IsStaffUserMixin, NameUserMixin):
# class Meta:
# abstract = True
#
# class DateJoinedUserMixin(models.Model):
# date_joined = models.DateTimeField(
# verbose_name=_('date joined'),
# default=timezone.now,
# editable=False,
# )
#
# class Meta:
# abstract = True
#
# class EmailUserMixin(models.Model):
# email = CIEmailField(
# verbose_name=_('Email address'),
# unique=True,
# max_length=511,
# )
# email_verified = True
#
# objects = UserManager()
#
# USERNAME_FIELD = 'email'
#
# class Meta:
# abstract = True
#
# class EmailVerifyUserMixin(EmailVerifyUserMethodsMixin, models.Model):
# is_active = models.BooleanField(_('active'), default=False)
# email_verified = models.BooleanField(
# _('Email verified?'),
# default=False,
# help_text=_('Indicates if the email address has been verified.'))
#
# objects = VerifyEmailManager()
#
# class Meta:
# abstract = True
#
# @classmethod
# def check(cls, **kwargs):
# errors = super(EmailVerifyUserMixin, cls).check(**kwargs)
# errors.extend(cls._check_manager(**kwargs))
# return errors
#
# @classmethod
# def _check_manager(cls, **kwargs):
# if isinstance(cls.objects, VerifyEmailManager):
# return []
#
# return [
# checks.Warning(
# "Manager should be an instance of 'VerifyEmailManager'",
# hint="Subclass a custom manager from 'VerifyEmailManager'",
# obj=cls,
# id='user_management.W001',
# ),
# ]
#
# class IsStaffUserMixin(models.Model):
# is_staff = models.BooleanField(_('staff status'), default=False)
#
# class Meta:
# abstract = True
#
# class NameUserMethodsMixin:
# def get_full_name(self):
# return self.name
#
# def get_short_name(self):
# return self.name
#
# def __str__(self):
# return self.name
#
# class VerifyEmailMixin(EmailVerifyUserMixin, BasicUserFieldsMixin):
# class Meta:
# abstract = True
. Output only the next line. | pass |
Predict the next line after this snippet: <|code_start|>
class User(AvatarMixin, VerifyEmailMixin, PermissionsMixin, AbstractBaseUser):
pass
class BasicUser(BasicUserFieldsMixin, AbstractBaseUser):
pass
class VerifyEmailUser(VerifyEmailMixin, AbstractBaseUser):
<|code_end|>
using the current file's imports:
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.db import models
from .notifications import CustomPasswordResetNotification
from ..mixins import (
AvatarMixin,
BasicUserFieldsMixin,
DateJoinedUserMixin,
EmailUserMixin,
EmailVerifyUserMixin,
IsStaffUserMixin,
NameUserMethodsMixin,
VerifyEmailMixin,
)
and any relevant context from other files:
# Path: user_management/models/tests/notifications.py
# class CustomPasswordResetNotification(PasswordResetNotification):
# """Test setting a custom notification to alter how we send the password reset."""
# text_email_template = 'my_custom_email.txt'
# html_email_template = None
# headers = {'test-header': 'Test'}
#
# Path: user_management/models/mixins.py
# class AvatarMixin(models.Model):
# avatar = models.ImageField(upload_to='user_avatar', null=True, blank=True)
#
# class Meta:
# abstract = True
#
# class BasicUserFieldsMixin(
# DateJoinedUserMixin, EmailUserMixin, IsStaffUserMixin, NameUserMixin):
# class Meta:
# abstract = True
#
# class DateJoinedUserMixin(models.Model):
# date_joined = models.DateTimeField(
# verbose_name=_('date joined'),
# default=timezone.now,
# editable=False,
# )
#
# class Meta:
# abstract = True
#
# class EmailUserMixin(models.Model):
# email = CIEmailField(
# verbose_name=_('Email address'),
# unique=True,
# max_length=511,
# )
# email_verified = True
#
# objects = UserManager()
#
# USERNAME_FIELD = 'email'
#
# class Meta:
# abstract = True
#
# class EmailVerifyUserMixin(EmailVerifyUserMethodsMixin, models.Model):
# is_active = models.BooleanField(_('active'), default=False)
# email_verified = models.BooleanField(
# _('Email verified?'),
# default=False,
# help_text=_('Indicates if the email address has been verified.'))
#
# objects = VerifyEmailManager()
#
# class Meta:
# abstract = True
#
# @classmethod
# def check(cls, **kwargs):
# errors = super(EmailVerifyUserMixin, cls).check(**kwargs)
# errors.extend(cls._check_manager(**kwargs))
# return errors
#
# @classmethod
# def _check_manager(cls, **kwargs):
# if isinstance(cls.objects, VerifyEmailManager):
# return []
#
# return [
# checks.Warning(
# "Manager should be an instance of 'VerifyEmailManager'",
# hint="Subclass a custom manager from 'VerifyEmailManager'",
# obj=cls,
# id='user_management.W001',
# ),
# ]
#
# class IsStaffUserMixin(models.Model):
# is_staff = models.BooleanField(_('staff status'), default=False)
#
# class Meta:
# abstract = True
#
# class NameUserMethodsMixin:
# def get_full_name(self):
# return self.name
#
# def get_short_name(self):
# return self.name
#
# def __str__(self):
# return self.name
#
# class VerifyEmailMixin(EmailVerifyUserMixin, BasicUserFieldsMixin):
# class Meta:
# abstract = True
. Output only the next line. | pass |
Continue the code snippet: <|code_start|>
class User(AvatarMixin, VerifyEmailMixin, PermissionsMixin, AbstractBaseUser):
pass
class BasicUser(BasicUserFieldsMixin, AbstractBaseUser):
pass
class VerifyEmailUser(VerifyEmailMixin, AbstractBaseUser):
<|code_end|>
. Use current file imports:
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.db import models
from .notifications import CustomPasswordResetNotification
from ..mixins import (
AvatarMixin,
BasicUserFieldsMixin,
DateJoinedUserMixin,
EmailUserMixin,
EmailVerifyUserMixin,
IsStaffUserMixin,
NameUserMethodsMixin,
VerifyEmailMixin,
)
and context (classes, functions, or code) from other files:
# Path: user_management/models/tests/notifications.py
# class CustomPasswordResetNotification(PasswordResetNotification):
# """Test setting a custom notification to alter how we send the password reset."""
# text_email_template = 'my_custom_email.txt'
# html_email_template = None
# headers = {'test-header': 'Test'}
#
# Path: user_management/models/mixins.py
# class AvatarMixin(models.Model):
# avatar = models.ImageField(upload_to='user_avatar', null=True, blank=True)
#
# class Meta:
# abstract = True
#
# class BasicUserFieldsMixin(
# DateJoinedUserMixin, EmailUserMixin, IsStaffUserMixin, NameUserMixin):
# class Meta:
# abstract = True
#
# class DateJoinedUserMixin(models.Model):
# date_joined = models.DateTimeField(
# verbose_name=_('date joined'),
# default=timezone.now,
# editable=False,
# )
#
# class Meta:
# abstract = True
#
# class EmailUserMixin(models.Model):
# email = CIEmailField(
# verbose_name=_('Email address'),
# unique=True,
# max_length=511,
# )
# email_verified = True
#
# objects = UserManager()
#
# USERNAME_FIELD = 'email'
#
# class Meta:
# abstract = True
#
# class EmailVerifyUserMixin(EmailVerifyUserMethodsMixin, models.Model):
# is_active = models.BooleanField(_('active'), default=False)
# email_verified = models.BooleanField(
# _('Email verified?'),
# default=False,
# help_text=_('Indicates if the email address has been verified.'))
#
# objects = VerifyEmailManager()
#
# class Meta:
# abstract = True
#
# @classmethod
# def check(cls, **kwargs):
# errors = super(EmailVerifyUserMixin, cls).check(**kwargs)
# errors.extend(cls._check_manager(**kwargs))
# return errors
#
# @classmethod
# def _check_manager(cls, **kwargs):
# if isinstance(cls.objects, VerifyEmailManager):
# return []
#
# return [
# checks.Warning(
# "Manager should be an instance of 'VerifyEmailManager'",
# hint="Subclass a custom manager from 'VerifyEmailManager'",
# obj=cls,
# id='user_management.W001',
# ),
# ]
#
# class IsStaffUserMixin(models.Model):
# is_staff = models.BooleanField(_('staff status'), default=False)
#
# class Meta:
# abstract = True
#
# class NameUserMethodsMixin:
# def get_full_name(self):
# return self.name
#
# def get_short_name(self):
# return self.name
#
# def __str__(self):
# return self.name
#
# class VerifyEmailMixin(EmailVerifyUserMixin, BasicUserFieldsMixin):
# class Meta:
# abstract = True
. Output only the next line. | pass |
Next line prediction: <|code_start|>
class User(AvatarMixin, VerifyEmailMixin, PermissionsMixin, AbstractBaseUser):
pass
class BasicUser(BasicUserFieldsMixin, AbstractBaseUser):
<|code_end|>
. Use current file imports:
(from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.db import models
from .notifications import CustomPasswordResetNotification
from ..mixins import (
AvatarMixin,
BasicUserFieldsMixin,
DateJoinedUserMixin,
EmailUserMixin,
EmailVerifyUserMixin,
IsStaffUserMixin,
NameUserMethodsMixin,
VerifyEmailMixin,
))
and context including class names, function names, or small code snippets from other files:
# Path: user_management/models/tests/notifications.py
# class CustomPasswordResetNotification(PasswordResetNotification):
# """Test setting a custom notification to alter how we send the password reset."""
# text_email_template = 'my_custom_email.txt'
# html_email_template = None
# headers = {'test-header': 'Test'}
#
# Path: user_management/models/mixins.py
# class AvatarMixin(models.Model):
# avatar = models.ImageField(upload_to='user_avatar', null=True, blank=True)
#
# class Meta:
# abstract = True
#
# class BasicUserFieldsMixin(
# DateJoinedUserMixin, EmailUserMixin, IsStaffUserMixin, NameUserMixin):
# class Meta:
# abstract = True
#
# class DateJoinedUserMixin(models.Model):
# date_joined = models.DateTimeField(
# verbose_name=_('date joined'),
# default=timezone.now,
# editable=False,
# )
#
# class Meta:
# abstract = True
#
# class EmailUserMixin(models.Model):
# email = CIEmailField(
# verbose_name=_('Email address'),
# unique=True,
# max_length=511,
# )
# email_verified = True
#
# objects = UserManager()
#
# USERNAME_FIELD = 'email'
#
# class Meta:
# abstract = True
#
# class EmailVerifyUserMixin(EmailVerifyUserMethodsMixin, models.Model):
# is_active = models.BooleanField(_('active'), default=False)
# email_verified = models.BooleanField(
# _('Email verified?'),
# default=False,
# help_text=_('Indicates if the email address has been verified.'))
#
# objects = VerifyEmailManager()
#
# class Meta:
# abstract = True
#
# @classmethod
# def check(cls, **kwargs):
# errors = super(EmailVerifyUserMixin, cls).check(**kwargs)
# errors.extend(cls._check_manager(**kwargs))
# return errors
#
# @classmethod
# def _check_manager(cls, **kwargs):
# if isinstance(cls.objects, VerifyEmailManager):
# return []
#
# return [
# checks.Warning(
# "Manager should be an instance of 'VerifyEmailManager'",
# hint="Subclass a custom manager from 'VerifyEmailManager'",
# obj=cls,
# id='user_management.W001',
# ),
# ]
#
# class IsStaffUserMixin(models.Model):
# is_staff = models.BooleanField(_('staff status'), default=False)
#
# class Meta:
# abstract = True
#
# class NameUserMethodsMixin:
# def get_full_name(self):
# return self.name
#
# def get_short_name(self):
# return self.name
#
# def __str__(self):
# return self.name
#
# class VerifyEmailMixin(EmailVerifyUserMixin, BasicUserFieldsMixin):
# class Meta:
# abstract = True
. Output only the next line. | pass |
Continue the code snippet: <|code_start|>
@override_settings(AUTH_USER_MODEL='tests.VerifyEmailUser')
class TestVerifyUserEmailView(RequestTestCase):
view_class = views.VerifyUserEmailView
<|code_end|>
. Use current file imports:
from django.test import override_settings
from user_management.models.tests.factories import VerifyEmailUserFactory
from user_management.models.tests.models import VerifyEmailUser
from user_management.models.tests.utils import RequestTestCase
from .. import views
and context (classes, functions, or code) from other files:
# Path: user_management/models/tests/factories.py
# class VerifyEmailUserFactory(UserFactory):
# email_verified = False
#
# class Meta:
# model = VerifyEmailUser
#
# Path: user_management/models/tests/models.py
# class VerifyEmailUser(VerifyEmailMixin, AbstractBaseUser):
# pass
#
# Path: user_management/models/tests/utils.py
# class RequestTestCase(Python2AssertMixin, BaseRequestTestCase):
# user_factory = UserFactory
. Output only the next line. | def test_get(self): |
Based on the snippet: <|code_start|>
@override_settings(AUTH_USER_MODEL='tests.VerifyEmailUser')
class TestVerifyUserEmailView(RequestTestCase):
view_class = views.VerifyUserEmailView
<|code_end|>
, predict the immediate next line with the help of imports:
from django.test import override_settings
from user_management.models.tests.factories import VerifyEmailUserFactory
from user_management.models.tests.models import VerifyEmailUser
from user_management.models.tests.utils import RequestTestCase
from .. import views
and context (classes, functions, sometimes code) from other files:
# Path: user_management/models/tests/factories.py
# class VerifyEmailUserFactory(UserFactory):
# email_verified = False
#
# class Meta:
# model = VerifyEmailUser
#
# Path: user_management/models/tests/models.py
# class VerifyEmailUser(VerifyEmailMixin, AbstractBaseUser):
# pass
#
# Path: user_management/models/tests/utils.py
# class RequestTestCase(Python2AssertMixin, BaseRequestTestCase):
# user_factory = UserFactory
. Output only the next line. | def test_get(self): |
Predict the next line for this snippet: <|code_start|>
@override_settings(AUTH_USER_MODEL='tests.VerifyEmailUser')
class TestVerifyUserEmailView(RequestTestCase):
view_class = views.VerifyUserEmailView
<|code_end|>
with the help of current file imports:
from django.test import override_settings
from user_management.models.tests.factories import VerifyEmailUserFactory
from user_management.models.tests.models import VerifyEmailUser
from user_management.models.tests.utils import RequestTestCase
from .. import views
and context from other files:
# Path: user_management/models/tests/factories.py
# class VerifyEmailUserFactory(UserFactory):
# email_verified = False
#
# class Meta:
# model = VerifyEmailUser
#
# Path: user_management/models/tests/models.py
# class VerifyEmailUser(VerifyEmailMixin, AbstractBaseUser):
# pass
#
# Path: user_management/models/tests/utils.py
# class RequestTestCase(Python2AssertMixin, BaseRequestTestCase):
# user_factory = UserFactory
, which may contain function names, class names, or code. Output only the next line. | def test_get(self): |
Next line prediction: <|code_start|>
User = get_user_model()
TEST_SERVER = 'http://testserver'
SEND_METHOD = 'user_management.utils.notifications.incuna_mail.send'
EMAIL_CONTEXT = 'user_management.utils.notifications.password_reset_email_context'
REGISTRATION_SERIALIZER_META_MODEL = (
'user_management.api.serializers.RegistrationSerializer.Meta.model'
)
class GetAuthTokenTest(APIRequestTestCase):
model = models.AuthToken
view_class = views.GetAuthToken
def setUp(self):
self.username = 'Test@example.com'
self.password = 'myepicstrongpassword'
self.data = {'username': self.username, 'password': self.password}
def tearDown(self):
<|code_end|>
. Use current file imports:
(import datetime
import re
from collections import OrderedDict
from django.contrib.auth import get_user_model, signals
from django.contrib.auth.hashers import check_password
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.models import Site
from django.core import mail
from django.core.cache import cache
from django.test import override_settings
from django.urls import reverse
from django.utils import timezone
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from mock import MagicMock, patch
from rest_framework import status
from rest_framework.test import APIRequestFactory
from user_management.api import models, views
from user_management.api.tests.test_throttling import THROTTLE_RATE_PATH
from user_management.models.tests.factories import AuthTokenFactory, UserFactory
from user_management.models.tests.models import BasicUser
from user_management.models.tests.utils import APIRequestTestCase
from user_management.tests.utils import iso_8601)
and context including class names, function names, or small code snippets from other files:
# Path: user_management/api/models.py
# MINUTE = 60
# HOUR = 60 * MINUTE
# DAY = 24 * HOUR
# DEFAULT_AUTH_TOKEN_MAX_AGE = 200 * DAY
# DEFAULT_AUTH_TOKEN_MAX_INACTIVITY = 12 * HOUR
# def update_expiry(created=None):
# def __str__(self):
# def save(self, *args, **kwargs):
# def generate_key(self):
# def update_expiry(self, commit=True):
# class AuthToken(models.Model):
#
# Path: user_management/api/views.py
# class GetAuthToken(ObtainAuthToken):
# class UserRegister(generics.CreateAPIView):
# class PasswordResetEmail(generics.GenericAPIView):
# class OneTimeUseAPIMixin(object):
# class PasswordReset(OneTimeUseAPIMixin, generics.UpdateAPIView):
# class PasswordChange(generics.UpdateAPIView):
# class VerifyAccountView(VerifyAccountViewMixin, views.APIView):
# class ProfileDetail(generics.RetrieveUpdateDestroyAPIView):
# class UserList(generics.ListCreateAPIView):
# class UserDetail(generics.RetrieveUpdateDestroyAPIView):
# class ResendConfirmationEmail(generics.GenericAPIView):
# def post(self, request):
# def delete(self, request, *args, **kwargs):
# def create(self, request, *args, **kwargs):
# def is_invalid(self, serializer):
# def is_valid(self, serializer):
# def post(self, request, *args, **kwargs):
# def initial(self, request, *args, **kwargs):
# def get_object(self):
# def get_object(self):
# def initial(self, request, *args, **kwargs):
# def post(self, request, *args, **kwargs):
# def get_object(self):
# def initial(self, request, *args, **kwargs):
# def post(self, request, *args, **kwargs):
#
# Path: user_management/api/tests/test_throttling.py
# THROTTLE_RATE_PATH = 'rest_framework.throttling.ScopedRateThrottle.THROTTLE_RATES'
#
# Path: user_management/models/tests/factories.py
# class AuthTokenFactory(factory.DjangoModelFactory):
# key = factory.Sequence('key{}'.format)
# user = factory.SubFactory(UserFactory)
#
# class Meta:
# model = AuthToken
#
# class UserFactory(factory.DjangoModelFactory):
# name = factory.Sequence('Test User {}'.format)
# email = factory.Sequence('email{}@example.com'.format)
# is_active = True
#
# class Meta:
# model = get_user_model()
#
# @factory.post_generation
# def password(self, create, extracted='default password', **kwargs):
# self.raw_password = extracted
# self.set_password(self.raw_password)
# if create:
# self.save()
#
# Path: user_management/models/tests/models.py
# class BasicUser(BasicUserFieldsMixin, AbstractBaseUser):
# pass
#
# Path: user_management/models/tests/utils.py
# class APIRequestTestCase(Python2AssertMixin, BaseAPIRequestTestCase):
# user_factory = UserFactory
#
# Path: user_management/tests/utils.py
# def iso_8601(datetime):
# """Convert a datetime into an iso 8601 string."""
# if datetime is None:
# return datetime
# value = datetime.isoformat()
# if value.endswith('+00:00'):
# value = value[:-6] + 'Z'
# return value
. Output only the next line. | cache.clear() |
Given the code snippet: <|code_start|>
User = get_user_model()
TEST_SERVER = 'http://testserver'
SEND_METHOD = 'user_management.utils.notifications.incuna_mail.send'
<|code_end|>
, generate the next line using the imports in this file:
import datetime
import re
from collections import OrderedDict
from django.contrib.auth import get_user_model, signals
from django.contrib.auth.hashers import check_password
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.models import Site
from django.core import mail
from django.core.cache import cache
from django.test import override_settings
from django.urls import reverse
from django.utils import timezone
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from mock import MagicMock, patch
from rest_framework import status
from rest_framework.test import APIRequestFactory
from user_management.api import models, views
from user_management.api.tests.test_throttling import THROTTLE_RATE_PATH
from user_management.models.tests.factories import AuthTokenFactory, UserFactory
from user_management.models.tests.models import BasicUser
from user_management.models.tests.utils import APIRequestTestCase
from user_management.tests.utils import iso_8601
and context (functions, classes, or occasionally code) from other files:
# Path: user_management/api/models.py
# MINUTE = 60
# HOUR = 60 * MINUTE
# DAY = 24 * HOUR
# DEFAULT_AUTH_TOKEN_MAX_AGE = 200 * DAY
# DEFAULT_AUTH_TOKEN_MAX_INACTIVITY = 12 * HOUR
# def update_expiry(created=None):
# def __str__(self):
# def save(self, *args, **kwargs):
# def generate_key(self):
# def update_expiry(self, commit=True):
# class AuthToken(models.Model):
#
# Path: user_management/api/views.py
# class GetAuthToken(ObtainAuthToken):
# class UserRegister(generics.CreateAPIView):
# class PasswordResetEmail(generics.GenericAPIView):
# class OneTimeUseAPIMixin(object):
# class PasswordReset(OneTimeUseAPIMixin, generics.UpdateAPIView):
# class PasswordChange(generics.UpdateAPIView):
# class VerifyAccountView(VerifyAccountViewMixin, views.APIView):
# class ProfileDetail(generics.RetrieveUpdateDestroyAPIView):
# class UserList(generics.ListCreateAPIView):
# class UserDetail(generics.RetrieveUpdateDestroyAPIView):
# class ResendConfirmationEmail(generics.GenericAPIView):
# def post(self, request):
# def delete(self, request, *args, **kwargs):
# def create(self, request, *args, **kwargs):
# def is_invalid(self, serializer):
# def is_valid(self, serializer):
# def post(self, request, *args, **kwargs):
# def initial(self, request, *args, **kwargs):
# def get_object(self):
# def get_object(self):
# def initial(self, request, *args, **kwargs):
# def post(self, request, *args, **kwargs):
# def get_object(self):
# def initial(self, request, *args, **kwargs):
# def post(self, request, *args, **kwargs):
#
# Path: user_management/api/tests/test_throttling.py
# THROTTLE_RATE_PATH = 'rest_framework.throttling.ScopedRateThrottle.THROTTLE_RATES'
#
# Path: user_management/models/tests/factories.py
# class AuthTokenFactory(factory.DjangoModelFactory):
# key = factory.Sequence('key{}'.format)
# user = factory.SubFactory(UserFactory)
#
# class Meta:
# model = AuthToken
#
# class UserFactory(factory.DjangoModelFactory):
# name = factory.Sequence('Test User {}'.format)
# email = factory.Sequence('email{}@example.com'.format)
# is_active = True
#
# class Meta:
# model = get_user_model()
#
# @factory.post_generation
# def password(self, create, extracted='default password', **kwargs):
# self.raw_password = extracted
# self.set_password(self.raw_password)
# if create:
# self.save()
#
# Path: user_management/models/tests/models.py
# class BasicUser(BasicUserFieldsMixin, AbstractBaseUser):
# pass
#
# Path: user_management/models/tests/utils.py
# class APIRequestTestCase(Python2AssertMixin, BaseAPIRequestTestCase):
# user_factory = UserFactory
#
# Path: user_management/tests/utils.py
# def iso_8601(datetime):
# """Convert a datetime into an iso 8601 string."""
# if datetime is None:
# return datetime
# value = datetime.isoformat()
# if value.endswith('+00:00'):
# value = value[:-6] + 'Z'
# return value
. Output only the next line. | EMAIL_CONTEXT = 'user_management.utils.notifications.password_reset_email_context' |
Given the code snippet: <|code_start|>
User = get_user_model()
TEST_SERVER = 'http://testserver'
SEND_METHOD = 'user_management.utils.notifications.incuna_mail.send'
EMAIL_CONTEXT = 'user_management.utils.notifications.password_reset_email_context'
REGISTRATION_SERIALIZER_META_MODEL = (
'user_management.api.serializers.RegistrationSerializer.Meta.model'
)
class GetAuthTokenTest(APIRequestTestCase):
model = models.AuthToken
view_class = views.GetAuthToken
def setUp(self):
self.username = 'Test@example.com'
self.password = 'myepicstrongpassword'
<|code_end|>
, generate the next line using the imports in this file:
import datetime
import re
from collections import OrderedDict
from django.contrib.auth import get_user_model, signals
from django.contrib.auth.hashers import check_password
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.models import Site
from django.core import mail
from django.core.cache import cache
from django.test import override_settings
from django.urls import reverse
from django.utils import timezone
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from mock import MagicMock, patch
from rest_framework import status
from rest_framework.test import APIRequestFactory
from user_management.api import models, views
from user_management.api.tests.test_throttling import THROTTLE_RATE_PATH
from user_management.models.tests.factories import AuthTokenFactory, UserFactory
from user_management.models.tests.models import BasicUser
from user_management.models.tests.utils import APIRequestTestCase
from user_management.tests.utils import iso_8601
and context (functions, classes, or occasionally code) from other files:
# Path: user_management/api/models.py
# MINUTE = 60
# HOUR = 60 * MINUTE
# DAY = 24 * HOUR
# DEFAULT_AUTH_TOKEN_MAX_AGE = 200 * DAY
# DEFAULT_AUTH_TOKEN_MAX_INACTIVITY = 12 * HOUR
# def update_expiry(created=None):
# def __str__(self):
# def save(self, *args, **kwargs):
# def generate_key(self):
# def update_expiry(self, commit=True):
# class AuthToken(models.Model):
#
# Path: user_management/api/views.py
# class GetAuthToken(ObtainAuthToken):
# class UserRegister(generics.CreateAPIView):
# class PasswordResetEmail(generics.GenericAPIView):
# class OneTimeUseAPIMixin(object):
# class PasswordReset(OneTimeUseAPIMixin, generics.UpdateAPIView):
# class PasswordChange(generics.UpdateAPIView):
# class VerifyAccountView(VerifyAccountViewMixin, views.APIView):
# class ProfileDetail(generics.RetrieveUpdateDestroyAPIView):
# class UserList(generics.ListCreateAPIView):
# class UserDetail(generics.RetrieveUpdateDestroyAPIView):
# class ResendConfirmationEmail(generics.GenericAPIView):
# def post(self, request):
# def delete(self, request, *args, **kwargs):
# def create(self, request, *args, **kwargs):
# def is_invalid(self, serializer):
# def is_valid(self, serializer):
# def post(self, request, *args, **kwargs):
# def initial(self, request, *args, **kwargs):
# def get_object(self):
# def get_object(self):
# def initial(self, request, *args, **kwargs):
# def post(self, request, *args, **kwargs):
# def get_object(self):
# def initial(self, request, *args, **kwargs):
# def post(self, request, *args, **kwargs):
#
# Path: user_management/api/tests/test_throttling.py
# THROTTLE_RATE_PATH = 'rest_framework.throttling.ScopedRateThrottle.THROTTLE_RATES'
#
# Path: user_management/models/tests/factories.py
# class AuthTokenFactory(factory.DjangoModelFactory):
# key = factory.Sequence('key{}'.format)
# user = factory.SubFactory(UserFactory)
#
# class Meta:
# model = AuthToken
#
# class UserFactory(factory.DjangoModelFactory):
# name = factory.Sequence('Test User {}'.format)
# email = factory.Sequence('email{}@example.com'.format)
# is_active = True
#
# class Meta:
# model = get_user_model()
#
# @factory.post_generation
# def password(self, create, extracted='default password', **kwargs):
# self.raw_password = extracted
# self.set_password(self.raw_password)
# if create:
# self.save()
#
# Path: user_management/models/tests/models.py
# class BasicUser(BasicUserFieldsMixin, AbstractBaseUser):
# pass
#
# Path: user_management/models/tests/utils.py
# class APIRequestTestCase(Python2AssertMixin, BaseAPIRequestTestCase):
# user_factory = UserFactory
#
# Path: user_management/tests/utils.py
# def iso_8601(datetime):
# """Convert a datetime into an iso 8601 string."""
# if datetime is None:
# return datetime
# value = datetime.isoformat()
# if value.endswith('+00:00'):
# value = value[:-6] + 'Z'
# return value
. Output only the next line. | self.data = {'username': self.username, 'password': self.password} |
Using the snippet: <|code_start|>
User = get_user_model()
TEST_SERVER = 'http://testserver'
SEND_METHOD = 'user_management.utils.notifications.incuna_mail.send'
EMAIL_CONTEXT = 'user_management.utils.notifications.password_reset_email_context'
REGISTRATION_SERIALIZER_META_MODEL = (
'user_management.api.serializers.RegistrationSerializer.Meta.model'
)
class GetAuthTokenTest(APIRequestTestCase):
model = models.AuthToken
view_class = views.GetAuthToken
def setUp(self):
self.username = 'Test@example.com'
self.password = 'myepicstrongpassword'
self.data = {'username': self.username, 'password': self.password}
def tearDown(self):
<|code_end|>
, determine the next line of code. You have imports:
import datetime
import re
from collections import OrderedDict
from django.contrib.auth import get_user_model, signals
from django.contrib.auth.hashers import check_password
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.models import Site
from django.core import mail
from django.core.cache import cache
from django.test import override_settings
from django.urls import reverse
from django.utils import timezone
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from mock import MagicMock, patch
from rest_framework import status
from rest_framework.test import APIRequestFactory
from user_management.api import models, views
from user_management.api.tests.test_throttling import THROTTLE_RATE_PATH
from user_management.models.tests.factories import AuthTokenFactory, UserFactory
from user_management.models.tests.models import BasicUser
from user_management.models.tests.utils import APIRequestTestCase
from user_management.tests.utils import iso_8601
and context (class names, function names, or code) available:
# Path: user_management/api/models.py
# MINUTE = 60
# HOUR = 60 * MINUTE
# DAY = 24 * HOUR
# DEFAULT_AUTH_TOKEN_MAX_AGE = 200 * DAY
# DEFAULT_AUTH_TOKEN_MAX_INACTIVITY = 12 * HOUR
# def update_expiry(created=None):
# def __str__(self):
# def save(self, *args, **kwargs):
# def generate_key(self):
# def update_expiry(self, commit=True):
# class AuthToken(models.Model):
#
# Path: user_management/api/views.py
# class GetAuthToken(ObtainAuthToken):
# class UserRegister(generics.CreateAPIView):
# class PasswordResetEmail(generics.GenericAPIView):
# class OneTimeUseAPIMixin(object):
# class PasswordReset(OneTimeUseAPIMixin, generics.UpdateAPIView):
# class PasswordChange(generics.UpdateAPIView):
# class VerifyAccountView(VerifyAccountViewMixin, views.APIView):
# class ProfileDetail(generics.RetrieveUpdateDestroyAPIView):
# class UserList(generics.ListCreateAPIView):
# class UserDetail(generics.RetrieveUpdateDestroyAPIView):
# class ResendConfirmationEmail(generics.GenericAPIView):
# def post(self, request):
# def delete(self, request, *args, **kwargs):
# def create(self, request, *args, **kwargs):
# def is_invalid(self, serializer):
# def is_valid(self, serializer):
# def post(self, request, *args, **kwargs):
# def initial(self, request, *args, **kwargs):
# def get_object(self):
# def get_object(self):
# def initial(self, request, *args, **kwargs):
# def post(self, request, *args, **kwargs):
# def get_object(self):
# def initial(self, request, *args, **kwargs):
# def post(self, request, *args, **kwargs):
#
# Path: user_management/api/tests/test_throttling.py
# THROTTLE_RATE_PATH = 'rest_framework.throttling.ScopedRateThrottle.THROTTLE_RATES'
#
# Path: user_management/models/tests/factories.py
# class AuthTokenFactory(factory.DjangoModelFactory):
# key = factory.Sequence('key{}'.format)
# user = factory.SubFactory(UserFactory)
#
# class Meta:
# model = AuthToken
#
# class UserFactory(factory.DjangoModelFactory):
# name = factory.Sequence('Test User {}'.format)
# email = factory.Sequence('email{}@example.com'.format)
# is_active = True
#
# class Meta:
# model = get_user_model()
#
# @factory.post_generation
# def password(self, create, extracted='default password', **kwargs):
# self.raw_password = extracted
# self.set_password(self.raw_password)
# if create:
# self.save()
#
# Path: user_management/models/tests/models.py
# class BasicUser(BasicUserFieldsMixin, AbstractBaseUser):
# pass
#
# Path: user_management/models/tests/utils.py
# class APIRequestTestCase(Python2AssertMixin, BaseAPIRequestTestCase):
# user_factory = UserFactory
#
# Path: user_management/tests/utils.py
# def iso_8601(datetime):
# """Convert a datetime into an iso 8601 string."""
# if datetime is None:
# return datetime
# value = datetime.isoformat()
# if value.endswith('+00:00'):
# value = value[:-6] + 'Z'
# return value
. Output only the next line. | cache.clear() |
Given snippet: <|code_start|>
User = get_user_model()
TEST_SERVER = 'http://testserver'
SEND_METHOD = 'user_management.utils.notifications.incuna_mail.send'
EMAIL_CONTEXT = 'user_management.utils.notifications.password_reset_email_context'
REGISTRATION_SERIALIZER_META_MODEL = (
'user_management.api.serializers.RegistrationSerializer.Meta.model'
)
class GetAuthTokenTest(APIRequestTestCase):
model = models.AuthToken
view_class = views.GetAuthToken
def setUp(self):
self.username = 'Test@example.com'
self.password = 'myepicstrongpassword'
self.data = {'username': self.username, 'password': self.password}
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import datetime
import re
from collections import OrderedDict
from django.contrib.auth import get_user_model, signals
from django.contrib.auth.hashers import check_password
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.models import Site
from django.core import mail
from django.core.cache import cache
from django.test import override_settings
from django.urls import reverse
from django.utils import timezone
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from mock import MagicMock, patch
from rest_framework import status
from rest_framework.test import APIRequestFactory
from user_management.api import models, views
from user_management.api.tests.test_throttling import THROTTLE_RATE_PATH
from user_management.models.tests.factories import AuthTokenFactory, UserFactory
from user_management.models.tests.models import BasicUser
from user_management.models.tests.utils import APIRequestTestCase
from user_management.tests.utils import iso_8601
and context:
# Path: user_management/api/models.py
# MINUTE = 60
# HOUR = 60 * MINUTE
# DAY = 24 * HOUR
# DEFAULT_AUTH_TOKEN_MAX_AGE = 200 * DAY
# DEFAULT_AUTH_TOKEN_MAX_INACTIVITY = 12 * HOUR
# def update_expiry(created=None):
# def __str__(self):
# def save(self, *args, **kwargs):
# def generate_key(self):
# def update_expiry(self, commit=True):
# class AuthToken(models.Model):
#
# Path: user_management/api/views.py
# class GetAuthToken(ObtainAuthToken):
# class UserRegister(generics.CreateAPIView):
# class PasswordResetEmail(generics.GenericAPIView):
# class OneTimeUseAPIMixin(object):
# class PasswordReset(OneTimeUseAPIMixin, generics.UpdateAPIView):
# class PasswordChange(generics.UpdateAPIView):
# class VerifyAccountView(VerifyAccountViewMixin, views.APIView):
# class ProfileDetail(generics.RetrieveUpdateDestroyAPIView):
# class UserList(generics.ListCreateAPIView):
# class UserDetail(generics.RetrieveUpdateDestroyAPIView):
# class ResendConfirmationEmail(generics.GenericAPIView):
# def post(self, request):
# def delete(self, request, *args, **kwargs):
# def create(self, request, *args, **kwargs):
# def is_invalid(self, serializer):
# def is_valid(self, serializer):
# def post(self, request, *args, **kwargs):
# def initial(self, request, *args, **kwargs):
# def get_object(self):
# def get_object(self):
# def initial(self, request, *args, **kwargs):
# def post(self, request, *args, **kwargs):
# def get_object(self):
# def initial(self, request, *args, **kwargs):
# def post(self, request, *args, **kwargs):
#
# Path: user_management/api/tests/test_throttling.py
# THROTTLE_RATE_PATH = 'rest_framework.throttling.ScopedRateThrottle.THROTTLE_RATES'
#
# Path: user_management/models/tests/factories.py
# class AuthTokenFactory(factory.DjangoModelFactory):
# key = factory.Sequence('key{}'.format)
# user = factory.SubFactory(UserFactory)
#
# class Meta:
# model = AuthToken
#
# class UserFactory(factory.DjangoModelFactory):
# name = factory.Sequence('Test User {}'.format)
# email = factory.Sequence('email{}@example.com'.format)
# is_active = True
#
# class Meta:
# model = get_user_model()
#
# @factory.post_generation
# def password(self, create, extracted='default password', **kwargs):
# self.raw_password = extracted
# self.set_password(self.raw_password)
# if create:
# self.save()
#
# Path: user_management/models/tests/models.py
# class BasicUser(BasicUserFieldsMixin, AbstractBaseUser):
# pass
#
# Path: user_management/models/tests/utils.py
# class APIRequestTestCase(Python2AssertMixin, BaseAPIRequestTestCase):
# user_factory = UserFactory
#
# Path: user_management/tests/utils.py
# def iso_8601(datetime):
# """Convert a datetime into an iso 8601 string."""
# if datetime is None:
# return datetime
# value = datetime.isoformat()
# if value.endswith('+00:00'):
# value = value[:-6] + 'Z'
# return value
which might include code, classes, or functions. Output only the next line. | def tearDown(self): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.