buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
import asyncio from asyncio.base_events import BaseEventLoop from concurrent.futures import Executor, ProcessPoolExecutor from functools import partial import keyword import os from pathlib import Path import tokenize import sys from typing import ( Dict, Generic, Iterable, Iterator, List, Optional, Set, Tuple, Typ...
import asyncio from asyncio.base_events import BaseEventLoop from concurrent.futures import Executor, ProcessPoolExecutor from functools import partial, wraps import keyword import os from pathlib import Path import tokenize import sys from typing import ( Callable, Dict, Generic, Iterable, Iterator...
Depth = int NodeType = int LeafID = int Priority = int LN = Union[Leaf, Node] out = partial(click.secho, bold=True, err=True) err = partial(click.secho, fg='red', err=True)
Depth = int NodeType = int LeafID = int Priority = int Index = int LN = Union[Leaf, Node] SplitFunc = Callable[['Line', bool], Iterator['Line']] out = partial(click.secho, bold=True, err=True) err = partial(click.secho, fg='red', err=True)
class Line: depth: int = 0 leaves: List[Leaf] = Factory(list) comments: Dict[LeafID, Leaf] = Factory(dict) bracket_tracker: BracketTracker = Factory(BracketTracker) inside_brackets: bool = False has_for: bool = False
class Line: depth: int = 0 leaves: List[Leaf] = Factory(list) comments: List[Tuple[Index, Leaf]] = Factory(list) bracket_tracker: BracketTracker = Factory(BracketTracker) inside_brackets: bool = False has_for: bool = False
class Line: self.bracket_tracker.mark(leaf) self.maybe_remove_trailing_comma(leaf) self.maybe_increment_for_loop_variable(leaf) if self.maybe_adapt_standalone_comment(leaf): return if not self.append_comment(leaf): self.leaves.append(l...
class Line: self.bracket_tracker.mark(leaf) self.maybe_remove_trailing_comma(leaf) self.maybe_increment_for_loop_variable(leaf) if not self.append_comment(leaf): self.leaves.append(leaf) def append_safe(self, leaf: Leaf, preformatted: bool = False) -> None: ...
class Line: and self.leaves[0].value == 'yield' ) def maybe_remove_trailing_comma(self, closing: Leaf) -> bool: """Remove trailing comma if there is one and it's safe.""" if not (
class Line: and self.leaves[0].value == 'yield' ) @property def contains_standalone_comments(self) -> bool: """If so, needs to be split before emitting.""" for leaf in self.leaves: if leaf.type == STANDALONE_COMMENT: return True return Fa...
class Line: return False if closing.type == token.RBRACE: self.leaves.pop() return True if closing.type == token.RSQB: comma = self.leaves[-1] if comma.parent and comma.parent.type == syms.listmaker: self.leaves.pop() ...
class Line: return False if closing.type == token.RBRACE: self.remove_trailing_comma() return True if closing.type == token.RSQB: comma = self.leaves[-1] if comma.parent and comma.parent.type == syms.listmaker: self.remove_tra...
class Line: break if commas > 1: self.leaves.pop() return True return False
class Line: break if commas > 1: self.remove_trailing_comma() return True return False
class Line: return False def maybe_adapt_standalone_comment(self, comment: Leaf) -> bool: """Hack a standalone comment to act as a trailing comment for line splitting. If this line has brackets and a standalone `comment`, we need to adapt it to be able to still reformat the line. ...
class Line: return False def append_comment(self, comment: Leaf) -> bool: """Add an inline or standalone comment to the line.""" if ( comment.type == STANDALONE_COMMENT and self.bracket_tracker.any_open_brackets() ): comment.prefix = '' ...
class Line: res = f'{first.prefix}{indent}{first.value}' for leaf in leaves: res += str(leaf) for comment in self.comments.values(): res += str(comment) return res + '\n'
class Line: res = f'{first.prefix}{indent}{first.value}' for leaf in leaves: res += str(leaf) for _, comment in self.comments: res += str(comment) return res + '\n'
class UnformattedLines(Line): """Does nothing and returns False.""" return False def maybe_adapt_standalone_comment(self, comment: Leaf) -> bool: """Does nothing and returns False.""" return False @dataclass class EmptyLineTracker:
class UnformattedLines(Line): """Does nothing and returns False.""" return False @dataclass class EmptyLineTracker:
def split_line( If `py36` is True, splitting may generate syntax that is only compatible with Python 3.6 and later. """ if isinstance(line, UnformattedLines): yield line return line_str = str(line).strip('\n') if len(line_str) <= line_length and '\n' not in line_str: yie...
def split_line( If `py36` is True, splitting may generate syntax that is only compatible with Python 3.6 and later. """ if isinstance(line, UnformattedLines) or line.is_comment: yield line return line_str = str(line).strip('\n') if ( len(line_str) <= line_length ...
def split_line( # split altogether. result: List[Line] = [] try: for l in split_func(line, py36=py36): if str(l).strip('\n') == line_str: raise CannotSplit("Split function returned an unchanged result")
def split_line( # split altogether. result: List[Line] = [] try: for l in split_func(line, py36): if str(l).strip('\n') == line_str: raise CannotSplit("Split function returned an unchanged result")
def left_hand_split(line: Line, py36: bool = False) -> Iterator[Line]: ): for leaf in leaves: result.append(leaf, preformatted=True) comment_after = line.comments.get(id(leaf)) if comment_after: result.append(comment_after, preformatted=True) bracket_s...
def left_hand_split(line: Line, py36: bool = False) -> Iterator[Line]: ): for leaf in leaves: result.append(leaf, preformatted=True) for comment_after in line.comments_after(leaf): result.append(comment_after, preformatted=True) bracket_split_succeeded_or_raise(he...
def right_hand_split(line: Line, py36: bool = False) -> Iterator[Line]: ): for leaf in leaves: result.append(leaf, preformatted=True) comment_after = line.comments.get(id(leaf)) if comment_after: result.append(comment_after, preformatted=True) bracket_...
def right_hand_split(line: Line, py36: bool = False) -> Iterator[Line]: ): for leaf in leaves: result.append(leaf, preformatted=True) for comment_after in line.comments_after(leaf): result.append(comment_after, preformatted=True) bracket_split_succeeded_or_raise(h...
def bracket_split_succeeded_or_raise(head: Line, body: Line, tail: Line) -> None ) def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]: """Split according to delimiters of the highest priority. This kind of split doesn't increase indentation. If `py36` is True, the split wil...
def bracket_split_succeeded_or_raise(head: Line, body: Line, tail: Line) -> None ) def dont_increase_indentation(split_func: SplitFunc) -> SplitFunc: """Normalize prefix of the first leaf in every line returned by `split_func`. This is a decorator over relevant split functions. """ @wrap...
def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]: current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets) lowest_depth = sys.maxsize trailing_comma_safe = True for leaf in line.leaves: current_line.append(leaf, preformatted=True) comment_after = l...
def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]: current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets) lowest_depth = sys.maxsize trailing_comma_safe = True def append_to_line(leaf: Leaf) -> Iterator[Line]: """Append `leaf` to current line or to new l...
def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]: trailing_comma_safe = trailing_comma_safe and py36 leaf_priority = delimiters.get(id(leaf)) if leaf_priority == delimiter_priority: normalize_prefix(current_line.leaves[0], inside_brackets=True) yi...
def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]: trailing_comma_safe = trailing_comma_safe and py36 leaf_priority = delimiters.get(id(leaf)) if leaf_priority == delimiter_priority: yield current_line current_line = Line(depth=line.depth, inside_...
def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]: and trailing_comma_safe ): current_line.append(Leaf(token.COMMA, ',')) normalize_prefix(current_line.leaves[0], inside_brackets=True) yield current_line
def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]: and trailing_comma_safe ): current_line.append(Leaf(token.COMMA, ',')) yield current_line @dont_increase_indentation def standalone_comment_split(line: Line, py36: bool = False) -> Iterator[Line]: """Spl...
class BlackTestCase(unittest.TestCase): black.assert_equivalent(source, actual) black.assert_stable(source, actual, line_length=ll) @patch("black.dump_to_file", dump_to_stderr) def test_cantfit(self) -> None: source, expected = read_data('cantfit')
class BlackTestCase(unittest.TestCase): black.assert_equivalent(source, actual) black.assert_stable(source, actual, line_length=ll) @patch("black.dump_to_file", dump_to_stderr) def test_comments3(self) -> None: source, expected = read_data('comments3') actual = fs(source) ...
from django.contrib.gis.db.models.fields import ( ExtentField, GeometryCollectionField, GeometryField, LineStringField, ) from django.db.models import Aggregate from django.utils.functional import cached_property __all__ = ['Collect', 'Extent', 'Extent3D', 'MakeLine', 'Union']
from django.contrib.gis.db.models.fields import ( ExtentField, GeometryCollectionField, GeometryField, LineStringField, ) from django.db.models import Aggregate, Value from django.utils.functional import cached_property __all__ = ['Collect', 'Extent', 'Extent3D', 'MakeLine', 'Union']
class GeoAggregate(Aggregate): ) def as_oracle(self, compiler, connection, **extra_context): tolerance = self.extra.get('tolerance') or getattr(self, 'tolerance', 0.05) template = None if self.is_extent else '%(function)s(SDOAGGRTYPE(%(expressions)s,%(tolerance)s))' return self.as_s...
class GeoAggregate(Aggregate): ) def as_oracle(self, compiler, connection, **extra_context): if not self.is_extent: tolerance = self.extra.get('tolerance') or getattr(self, 'tolerance', 0.05) clone = self.copy() clone.set_source_expressions([ *sel...
class OracleToleranceMixin: tolerance = 0.05 def as_oracle(self, compiler, connection, **extra_context): tol = self.extra.get('tolerance', self.tolerance) return self.as_sql( compiler, connection, template="%%(function)s(%%(expressions)s, %s)" % tol, **extra_...
class OracleToleranceMixin: tolerance = 0.05 def as_oracle(self, compiler, connection, **extra_context): tolerance = Value(self._handle_param( self.extra.get('tolerance', self.tolerance), 'tolerance', NUMERIC_TYPES, )) clone = self.copy() clon...
class DistanceFunctionsTests(FuncTestMixin, TestCase): ).filter(d=D(m=1)) self.assertTrue(qs.exists()) @skipIfDBFeature("supports_distance_geodetic") @skipUnlessDBFeature("has_Distance_function") def test_distance_function_raw_result_d_lookup(self):
class DistanceFunctionsTests(FuncTestMixin, TestCase): ).filter(d=D(m=1)) self.assertTrue(qs.exists()) @unittest.skipUnless( connection.vendor == 'oracle', 'Oracle supports tolerance paremeter.', ) def test_distance_function_tolerance_escaping(self): qs = Interstate....
from django.contrib.gis.geos import ( MultiPoint, MultiPolygon, Point, Polygon, fromstr, ) from django.core.management import call_command from django.db import NotSupportedError, connection from django.db.models import F, OuterRef, Subquery from django.test import TestCase, skipUnlessDBFeature
from django.contrib.gis.geos import ( MultiPoint, MultiPolygon, Point, Polygon, fromstr, ) from django.core.management import call_command from django.db import DatabaseError, NotSupportedError, connection from django.db.models import F, OuterRef, Subquery from django.test import TestCase, skipUnlessDBFeature
class GeoQuerySetTest(TestCase): qs = City.objects.filter(name='NotACity') self.assertIsNone(qs.aggregate(Union('point'))['point__union']) def test_within_subquery(self): """ Using a queryset inside a geo lookup is working (using a subquery)
class GeoQuerySetTest(TestCase): qs = City.objects.filter(name='NotACity') self.assertIsNone(qs.aggregate(Union('point'))['point__union']) @unittest.skipUnless( connection.vendor == 'oracle', 'Oracle supports tolerance paremeter.', ) def test_unionagg_tolerance(self): ...
class SplunkHTTPCollectorSource(object): else: ansible_role = None data = {} data['uuid'] = result._task._uuid data['session'] = self.session
class SplunkHTTPCollectorSource(object): else: ansible_role = None if 'args' in result._task_fields: del result._task_fields['args'] data = {} data['uuid'] = result._task._uuid data['session'] = self.session
class SumologicHTTPCollectorSource(object): else: ansible_role = None data = {} data['uuid'] = result._task._uuid data['session'] = self.session
class SumologicHTTPCollectorSource(object): else: ansible_role = None if 'args' in result._task_fields: del result._task_fields['args'] data = {} data['uuid'] = result._task._uuid data['session'] = self.session
class TimeGrouper(Grouper): # because replace() will swallow the nanosecond part # thus last bin maybe slightly before the end if the end contains # nanosecond part and lead to `Values falls after last bin` error binner = labels = date_range( freq=self.freq, start...
class TimeGrouper(Grouper): # because replace() will swallow the nanosecond part # thus last bin maybe slightly before the end if the end contains # nanosecond part and lead to `Values falls after last bin` error # GH 25758: If DST lands at midnight (e.g. 'America/Havana'), user feedback...
def test_downsample_across_dst_weekly(): tm.assert_series_equal(result, expected) def test_resample_with_nat(): # GH 13020 index = DatetimeIndex(
def test_downsample_across_dst_weekly(): tm.assert_series_equal(result, expected) def test_downsample_dst_at_midnight(): # GH 25758 start = datetime(2018, 11, 3, 12) end = datetime(2018, 11, 5, 12) index = pd.date_range(start, end, freq="1H") index = index.tz_localize("UTC").tz_convert("Americ...
import copy from django import forms from django.core.exceptions import ValidationError from django.db.models.deletion import CASCADE from django.urls import reverse from django.urls.exceptions import NoReverseMatch
import copy from django import forms from django.core.exceptions import ValidationError from django.core.validators import URLValidator from django.db.models.deletion import CASCADE from django.urls import reverse from django.urls.exceptions import NoReverseMatch
class AdminEmailInputWidget(forms.EmailInput): class AdminURLFieldWidget(forms.URLInput): template_name = 'admin/widgets/url.html' def __init__(self, attrs=None): final_attrs = {'class': 'vURLField'} if attrs is not None: final_attrs.update(attrs) super(AdminURLFieldWidget, ...
class AdminEmailInputWidget(forms.EmailInput): class AdminURLFieldWidget(forms.URLInput): template_name = 'admin/widgets/url.html' def __init__(self, attrs=None, validator_class=URLValidator): final_attrs = {'class': 'vURLField'} if attrs is not None: final_attrs.update(attrs) ...
class AdminSplitDateTimeWidgetTest(SimpleTestCase): class AdminURLWidgetTest(SimpleTestCase): def test_render(self): w = widgets.AdminURLFieldWidget() self.assertHTMLEqual(
class AdminSplitDateTimeWidgetTest(SimpleTestCase): class AdminURLWidgetTest(SimpleTestCase): def test_get_context_validates_url(self): w = widgets.AdminURLFieldWidget() for invalid in ['', '/not/a/full/url/', 'javascript:alert("Danger XSS!")']: self.assertFalse(w.get_context('name', i...
class AdminURLWidgetTest(SimpleTestCase): VALUE_RE = re.compile('value="([^"]+)"') TEXT_RE = re.compile('<a[^>]+>([^>]+)</a>') w = widgets.AdminURLFieldWidget() output = w.render('test', 'http://example.com/<sometag>some text</sometag>') self.assertEqual( HREF_RE.sear...
class AdminURLWidgetTest(SimpleTestCase): VALUE_RE = re.compile('value="([^"]+)"') TEXT_RE = re.compile('<a[^>]+>([^>]+)</a>') w = widgets.AdminURLFieldWidget() output = w.render('test', 'http://example.com/<sometag>some-text</sometag>') self.assertEqual( HREF_RE.sear...
class MarkerStyle: self._snap_threshold = None self._joinstyle = 'round' self._capstyle = 'butt' self._filled = True self._marker_function() def __bool__(self):
class MarkerStyle: self._snap_threshold = None self._joinstyle = 'round' self._capstyle = 'butt' # Initial guess: Assume the marker is filled unless the fillstyle is # set to 'none'. The marker function will override this for unfilled # markers. self._filled = sel...
from matplotlib.testing.decorators import check_figures_equal import pytest def test_markers_valid(): marker_style = markers.MarkerStyle() mrk_array = np.array([[-0.5, 0],
from matplotlib.testing.decorators import check_figures_equal import pytest def test_marker_fillstyle(): marker_style = markers.MarkerStyle(marker='o', fillstyle='none') assert marker_style.get_fillstyle() == 'none' assert not marker_style.is_filled() def test_markers_valid(): marker_style = markers...
class MultiPartParser: remaining = len(stripped_chunk) % 4 while remaining != 0: over_chunk = field_stream.read(4 - remaining) stripped_chunk += b"".join(over_chunk.split()) ...
class MultiPartParser: remaining = len(stripped_chunk) % 4 while remaining != 0: over_chunk = field_stream.read(4 - remaining) if not over_chunk: ...
class FileUploadTests(TestCase): def test_big_base64_newlines_upload(self): self._test_base64_upload("Big data" * 68000, encode=base64.encodebytes) def test_unicode_file_name(self): with sys_tempfile.TemporaryDirectory() as temp_dir: # This file contains Chinese symbols and an accen...
class FileUploadTests(TestCase): def test_big_base64_newlines_upload(self): self._test_base64_upload("Big data" * 68000, encode=base64.encodebytes) def test_base64_invalid_upload(self): payload = client.FakePayload('\r\n'.join([ '--' + client.BOUNDARY, 'Content-Dispositi...
def write(data, path, saltenv="base", index=0): ) roots_dir = __opts__["pillar_roots"][saltenv][index] dest = os.path.join(roots_dir, path) if not salt.utils.verify.clean_path(roots_dir, dest): return "Invalid path" dest = os.path.join(__opts__["pillar_roots"][saltenv][index], path) ...
def write(data, path, saltenv="base", index=0): ) roots_dir = __opts__["pillar_roots"][saltenv][index] dest = os.path.join(roots_dir, path) if not salt.utils.verify.clean_path(roots_dir, dest, subdir=True): return "Invalid path" dest = os.path.join(__opts__["pillar_roots"][saltenv][index...
class WheelPillarRootsTest(TestCase, AdaptedConfigurationTestCaseMixin): assert os.path.exists(os.path.join(self.pillar_dir, "foo")) assert ret.find("Wrote data to file") != -1 def test_cvr_2021_25282(self): ret = self.wheel.cmd( "pillar_roots.write", kwarg={"data": "foo", "path...
class WheelPillarRootsTest(TestCase, AdaptedConfigurationTestCaseMixin): assert os.path.exists(os.path.join(self.pillar_dir, "foo")) assert ret.find("Wrote data to file") != -1 def test_write_subdir(self): ret = self.wheel.cmd( "pillar_roots.write", kwarg={"data": "foo: bar", "p...
from blib2to3 import pygram, pytree from blib2to3.pgen2 import driver, token from blib2to3.pgen2.grammar import Grammar from blib2to3.pgen2.parse import ParseError __version__ = "19.3b0"
from blib2to3 import pygram, pytree from blib2to3.pgen2 import driver, token from blib2to3.pgen2.grammar import Grammar from blib2to3.pgen2.parse import ParseError from blib2to3.pgen2.tokenize import TokenizerConfig __version__ = "19.3b0"
class Feature(Enum): NUMERIC_UNDERSCORES = 3 TRAILING_COMMA_IN_CALL = 4 TRAILING_COMMA_IN_DEF = 5 VERSION_TO_FEATURES: Dict[TargetVersion, Set[Feature]] = { TargetVersion.PY27: set(), TargetVersion.PY33: {Feature.UNICODE_LITERALS}, TargetVersion.PY34: {Feature.UNICODE_LITERALS}, TargetVers...
class Feature(Enum): NUMERIC_UNDERSCORES = 3 TRAILING_COMMA_IN_CALL = 4 TRAILING_COMMA_IN_DEF = 5 # The following two feature-flags are mutually exclusive, and exactly one should be # set for every version of python. ASYNC_IS_VALID_IDENTIFIER = 6 ASYNC_IS_RESERVED_KEYWORD = 7 VERSION_TO_FE...
VERSION_TO_FEATURES: Dict[TargetVersion, Set[Feature]] = { Feature.NUMERIC_UNDERSCORES, Feature.TRAILING_COMMA_IN_CALL, Feature.TRAILING_COMMA_IN_DEF, }, TargetVersion.PY38: { Feature.UNICODE_LITERALS,
VERSION_TO_FEATURES: Dict[TargetVersion, Set[Feature]] = { Feature.NUMERIC_UNDERSCORES, Feature.TRAILING_COMMA_IN_CALL, Feature.TRAILING_COMMA_IN_DEF, Feature.ASYNC_IS_RESERVED_KEYWORD, }, TargetVersion.PY38: { Feature.UNICODE_LITERALS,
VERSION_TO_FEATURES: Dict[TargetVersion, Set[Feature]] = { Feature.NUMERIC_UNDERSCORES, Feature.TRAILING_COMMA_IN_CALL, Feature.TRAILING_COMMA_IN_DEF, }, }
VERSION_TO_FEATURES: Dict[TargetVersion, Set[Feature]] = { Feature.NUMERIC_UNDERSCORES, Feature.TRAILING_COMMA_IN_CALL, Feature.TRAILING_COMMA_IN_DEF, Feature.ASYNC_IS_RESERVED_KEYWORD, }, }
def decode_bytes(src: bytes) -> Tuple[FileContent, Encoding, NewLine]: return tiow.read(), encoding, newline def get_grammars(target_versions: Set[TargetVersion]) -> List[Grammar]: if not target_versions: # No target_version specified, so try all grammars. return [ pygram.pytho...
def decode_bytes(src: bytes) -> Tuple[FileContent, Encoding, NewLine]: return tiow.read(), encoding, newline @dataclass(frozen=True) class ParserConfig: grammar: Grammar tokenizer_config: TokenizerConfig = TokenizerConfig() def get_parser_configs(target_versions: Set[TargetVersion]) -> List[ParserCo...
def lib2to3_parse(src_txt: str, target_versions: Iterable[TargetVersion] = ()) - if src_txt[-1:] != "\n": src_txt += "\n" for grammar in get_grammars(set(target_versions)): drv = driver.Driver(grammar, pytree.convert) try: result = drv.parse_string(src_txt, True) ...
def lib2to3_parse(src_txt: str, target_versions: Iterable[TargetVersion] = ()) - if src_txt[-1:] != "\n": src_txt += "\n" for parser_config in get_parser_configs(set(target_versions)): drv = driver.Driver( parser_config.grammar, pytree.convert, tokenizer_conf...
from . import grammar, parse, token, tokenize, pgen class Driver(object): def __init__(self, grammar, convert=None, logger=None): self.grammar = grammar if logger is None: logger = logging.getLogger(__name__) self.logger = logger self.convert = convert def parse_to...
from . import grammar, parse, token, tokenize, pgen class Driver(object): def __init__( self, grammar, convert=None, logger=None, tokenizer_config=tokenize.TokenizerConfig(), ): self.grammar = grammar if logger is None: logger = logging.getLo...
class Driver(object): def parse_stream_raw(self, stream, debug=False): """Parse a stream and return the syntax tree.""" tokens = tokenize.generate_tokens(stream.readline) return self.parse_tokens(tokens, debug) def parse_stream(self, stream, debug=False):
class Driver(object): def parse_stream_raw(self, stream, debug=False): """Parse a stream and return the syntax tree.""" tokens = tokenize.generate_tokens(stream.readline, config=self.tokenizer_config) return self.parse_tokens(tokens, debug) def parse_stream(self, stream, debug=False):
class Driver(object): def parse_string(self, text, debug=False): """Parse a string and return the syntax tree.""" tokens = tokenize.generate_tokens(io.StringIO(text).readline) return self.parse_tokens(tokens, debug) def _partially_consume_prefix(self, prefix, column):
class Driver(object): def parse_string(self, text, debug=False): """Parse a string and return the syntax tree.""" tokens = tokenize.generate_tokens( io.StringIO(text).readline, config=self.tokenizer_config, ) return self.parse_tokens(tokens, debug) def _...
__credits__ = \ import re from codecs import BOM_UTF8, lookup from blib2to3.pgen2.token import * from . import token
__credits__ = \ import re from codecs import BOM_UTF8, lookup from attr import dataclass from blib2to3.pgen2.token import * from . import token
single_quoted = ( tabsize = 8 class TokenError(Exception): pass class StopTokenizing(Exception): pass
single_quoted = ( tabsize = 8 @dataclass(frozen=True) class TokenizerConfig: async_is_reserved_keyword: bool = False class TokenError(Exception): pass class StopTokenizing(Exception): pass
def untokenize(iterable): ut = Untokenizer() return ut.untokenize(iterable) def generate_tokens(readline): """ The generate_tokens() generator requires one argument, readline, which must be a callable object which provides the same interface as the
def untokenize(iterable): ut = Untokenizer() return ut.untokenize(iterable) def generate_tokens(readline, config: TokenizerConfig = TokenizerConfig()): """ The generate_tokens() generator requires one argument, readline, which must be a callable object which provides the same interface as the
def generate_tokens(readline): contline = None indents = [0] # 'stashed' and 'async_*' are used for async/await parsing stashed = None async_def = False
def generate_tokens(readline): contline = None indents = [0] # If we know we're parsing 3.7+, we can unconditionally parse `async` and # `await` as keywords. async_is_reserved_keyword = config.async_is_reserved_keyword # 'stashed' and 'async_*' are used for async/await parsing stashed = Non...
def generate_tokens(readline): yield (STRING, token, spos, epos, line) elif initial.isidentifier(): # ordinary name if token in ('async', 'await'): if async_def: yield (ASYNC if token == 'async'...
def generate_tokens(readline): yield (STRING, token, spos, epos, line) elif initial.isidentifier(): # ordinary name if token in ('async', 'await'): if async_is_reserved_keyword or async_def: yie...
async def func(): self.async_inc, arange(8), batch_size=3 ) ] # output
async def func(): self.async_inc, arange(8), batch_size=3 ) ] def awaited_generator_value(n): return (await awaitable for awaitable in awaitable_list) def make_arange(n): return (i * 2 for i in range(n) if await wrap(i)) # output
async def func(): self.async_inc, arange(8), batch_size=3 ) ]
async def func(): self.async_inc, arange(8), batch_size=3 ) ] def awaited_generator_value(n): return (await awaitable for awaitable in awaitable_list) def make_arange(n): return (i * 2 for i in range(n) if await wrap(i))
class BlackTestCase(unittest.TestCase): self.assertFormatEqual(expected, actual) black.assert_stable(source, actual, mode) @patch("black.dump_to_file", dump_to_stderr) def test_python37(self) -> None: source, expected = read_data("python37") actual = fs(source) self.asse...
class BlackTestCase(unittest.TestCase): self.assertFormatEqual(expected, actual) black.assert_stable(source, actual, mode) @patch("black.dump_to_file", dump_to_stderr) def test_async_as_identifier(self) -> None: source_path = (THIS_DIR / "data" / "async_as_identifier.py").resolve() ...
class BlackTestCase(unittest.TestCase): if major > 3 or (major == 3 and minor >= 7): black.assert_equivalent(source, actual) black.assert_stable(source, actual, black.FileMode()) @patch("black.dump_to_file", dump_to_stderr) def test_fmtonoff(self) -> None:
class BlackTestCase(unittest.TestCase): if major > 3 or (major == 3 and minor >= 7): black.assert_equivalent(source, actual) black.assert_stable(source, actual, black.FileMode()) # ensure black can parse this when the target is 3.7 self.invokeBlack([str(source_path), "--targe...
from AccessControl import ClassSecurityInfo, Unauthorized from Products.CMFPlone.PloneBaseTool import PloneBaseTool from Products.CMFPlone.PloneTool import EMAIL_RE # - remove '1', 'l', and 'I' to avoid confusion # - remove '0', 'O', and 'Q' to avoid confusion # - remove vowels to avoid spelling words
from AccessControl import ClassSecurityInfo, Unauthorized from Products.CMFPlone.PloneBaseTool import PloneBaseTool from Products.CMFPlone.PloneTool import EMAIL_RE from Products.PluggableAuthService.interfaces.authservice \ import IPluggableAuthService # - remove '1', 'l', and 'I' to avoid confusion # - remo...
class RegistrationTool(PloneBaseTool, BaseTool): return self.mail_password_response( self, self.REQUEST ) RegistrationTool.__doc__ = BaseTool.__doc__
class RegistrationTool(PloneBaseTool, BaseTool): return self.mail_password_response( self, self.REQUEST ) def isMemberIdAllowed(self, id): if len(id) < 1 or id == 'Anonymous User': return 0 if not self._ALLOWED_MEMBER_ID_PATTERN.match( id ): return 0 pas = ...
class TestRegistrationTool(PloneTestCase.PloneTestCase): def afterSetUp(self): self.registration = self.portal.portal_registration def testJoinCreatesUser(self): self.registration.addMember(member_id, 'secret',
class TestRegistrationTool(PloneTestCase.PloneTestCase): def afterSetUp(self): self.registration = self.portal.portal_registration self.portal.acl_users.userFolderAddUser("userid", "password", (), (), ()) self.portal.acl_users._doAddGroup("groupid", ()) def testJoinCrea...
class TestRegistrationTool(PloneTestCase.PloneTestCase): def testInvalidCMFDefaultEmailFailsValidation(self): # http://dev.plone.org/plone/ticket/3910 self.failIf(self.registration.isValidEmail('bogus@127.0.0.1')) class TestPasswordGeneration(PloneTestCase.PloneTestCase):
class TestRegistrationTool(PloneTestCase.PloneTestCase): def testInvalidCMFDefaultEmailFailsValidation(self): # http://dev.plone.org/plone/ticket/3910 self.failIf(self.registration.isValidEmail('bogus@127.0.0.1')) def testNewIdAllowed(self): self.assertEqual(self.registration.isMemberId...
class XMLRPCHandlerTests(unittest.TestCase): self.assertEqual(request._error, 500) class TraverseTests(unittest.TestCase): def test_underscore(self): from supervisor import xmlrpc self.assertRaises(xmlrpc.RPCError, xmlrpc.traverse, None, '_', None) def test_notfound(self): from...
class XMLRPCHandlerTests(unittest.TestCase): self.assertEqual(request._error, 500) class TraverseTests(unittest.TestCase): def test_security_disallows_underscore_methods(self): from supervisor import xmlrpc class Root: pass class A: def _danger(self): ...
class supervisor_xmlrpc_handler(xmlrpc_handler): return traverse(self.rpcinterface, method, params) def traverse(ob, method, params): path = method.split('.') for name in path: if name.startswith('_'): # security (don't allow things that start with an underscore to # be ...
class supervisor_xmlrpc_handler(xmlrpc_handler): return traverse(self.rpcinterface, method, params) def traverse(ob, method, params): dotted_parts = method.split('.') # security (CVE-2017-11610, don't allow object traversal) if len(dotted_parts) != 2: raise RPCError(Faults.UNKNOWN_METHOD) ...
import re from setuptools import setup, find_packages # Requirements REQUIREMENTS = ["marshmallow>=2.15.0"] def find_version(fname):
import re from setuptools import setup, find_packages # Requirements REQUIREMENTS = ["marshmallow>=2.15.2"] def find_version(fname):
class TestFormatSelection(unittest.TestCase): downloaded = ydl.downloaded_info_dicts[0] self.assertEqual(downloaded['format_id'], '38') info_dict = _make_result(list(formats_order), extractor='youtube') ydl = YDL({'format': '(bestvideo[ext=mp4],bestvideo[ext=webm])+bestaudio'}) ...
class TestFormatSelection(unittest.TestCase): downloaded = ydl.downloaded_info_dicts[0] self.assertEqual(downloaded['format_id'], '38') info_dict = _make_result(list(formats_order), extractor='youtube') ydl = YDL({'format': 'bestvideo/best,bestaudio'}) yie = YoutubeIE(ydl) ...
class YoutubeDL(object): elif string == '/': first_choice = current_selector second_choice = _parse_format_selection(tokens, inside_choice=True) current_selector = None selectors.append(FormatSelector(PIC...
class YoutubeDL(object): elif string == '/': first_choice = current_selector second_choice = _parse_format_selection(tokens, inside_choice=True) current_selector = FormatSelector(PICKFIRST, (first_choice, second_choice), []) ...
class HttpRequest: def scheme(self): if settings.SECURE_PROXY_SSL_HEADER: try: header, value = settings.SECURE_PROXY_SSL_HEADER except ValueError: raise ImproperlyConfigured( 'The SECURE_PROXY_SSL_HEADER setting must be a tuple cont...
class HttpRequest: def scheme(self): if settings.SECURE_PROXY_SSL_HEADER: try: header, secure_value = settings.SECURE_PROXY_SSL_HEADER except ValueError: raise ImproperlyConfigured( 'The SECURE_PROXY_SSL_HEADER setting must be a tup...
class SecureProxySslHeaderTest(SimpleTestCase): req.META['HTTP_X_FORWARDED_PROTOCOL'] = 'https' self.assertIs(req.is_secure(), True) class IsOverriddenTest(SimpleTestCase): def test_configure(self):
class SecureProxySslHeaderTest(SimpleTestCase): req.META['HTTP_X_FORWARDED_PROTOCOL'] = 'https' self.assertIs(req.is_secure(), True) @override_settings(SECURE_PROXY_SSL_HEADER=('HTTP_X_FORWARDED_PROTOCOL', 'https')) def test_xheader_preferred_to_underlying_request(self): class ProxyRequ...
async def get_file( try: length = await make_deferred_yieldable( readBodyToFile(response, output_stream, max_size) ) except SynapseError: # This can happen e.g. because the body is too large. raise except Exception as e: ...
async def get_file( try: length = await make_deferred_yieldable( read_body_with_max_size(response, output_stream, max_size) ) except BodyExceededMaxSize: SynapseError( 502, "Requested file is too large > %r bytes" % (ma...
def _timeout_to_request_timed_out_error(f: Failure): return f class _ReadBodyToFileProtocol(protocol.Protocol): def __init__( self, stream: BinaryIO, deferred: defer.Deferred, max_size: Optional[int] ):
def _timeout_to_request_timed_out_error(f: Failure): return f class BodyExceededMaxSize(Exception): """The maximum allowed size of the HTTP body was exceeded.""" class _ReadBodyWithMaxSizeProtocol(protocol.Protocol): def __init__( self, stream: BinaryIO, deferred: defer.Deferred, max_size: Optio...
def dataReceived(self, data: bytes) -> None: self.stream.write(data) self.length += len(data) if self.max_size is not None and self.length >= self.max_size: self.deferred.errback( SynapseError( 502, "Requested file is too large ...
def dataReceived(self, data: bytes) -> None: self.stream.write(data) self.length += len(data) if self.max_size is not None and self.length >= self.max_size: self.deferred.errback(BodyExceededMaxSize()) self.deferred = defer.Deferred() self.transport.loseConnec...
def connectionLost(self, reason: Failure) -> None: self.deferred.errback(reason) def readBodyToFile( response: IResponse, stream: BinaryIO, max_size: Optional[int] ) -> defer.Deferred: """ Read a HTTP response body to a file-object. Optionally enforcing a maximum file size. Args: ...
def connectionLost(self, reason: Failure) -> None: self.deferred.errback(reason) def read_body_with_max_size( response: IResponse, stream: BinaryIO, max_size: Optional[int] ) -> defer.Deferred: """ Read a HTTP response body to a file-object. Optionally enforcing a maximum file size. If th...
def readBodyToFile( """ d = defer.Deferred() response.deliverBody(_ReadBodyToFileProtocol(stream, d, max_size)) return d
def readBodyToFile( """ d = defer.Deferred() response.deliverBody(_ReadBodyWithMaxSizeProtocol(stream, d, max_size)) return d
import logging import random import time from typing import Callable, Dict, Optional, Tuple import attr from twisted.internet import defer from twisted.internet.interfaces import IReactorTime from twisted.web.client import RedirectAgent, readBody from twisted.web.http import stringToDatetime from twisted.web.http_hea...
import logging import random import time from io import BytesIO from typing import Callable, Dict, Optional, Tuple import attr from twisted.internet import defer from twisted.internet.interfaces import IReactorTime from twisted.web.client import RedirectAgent from twisted.web.http import stringToDatetime from twisted...
# lower bound for .well-known cache period WELL_KNOWN_MIN_CACHE_PERIOD = 5 * 60 # Attempt to refetch a cached well-known N% of the TTL before it expires. # e.g. if set to 0.2 and we have a cached entry with a TTL of 5mins, then # we'll start trying to refetch 1 minute before it expires.
# lower bound for .well-known cache period WELL_KNOWN_MIN_CACHE_PERIOD = 5 * 60 # The maximum size (in bytes) to allow a well-known file to be. WELL_KNOWN_MAX_SIZE = 50 * 1024 # 50 KiB # Attempt to refetch a cached well-known N% of the TTL before it expires. # e.g. if set to 0.2 and we have a cached entry with a TTL...
async def _make_well_known_request( server_name: name of the server, from the requested url retry: Whether to retry the request if it fails. Returns: Returns the response object and body. Response may be a non-200 response. """
async def _make_well_known_request( server_name: name of the server, from the requested url retry: Whether to retry the request if it fails. Raises: _FetchWellKnownFailure if we fail to lookup a result Returns: Returns the response object and body. Respo...
async def _make_well_known_request( b"GET", uri, headers=Headers(headers) ) ) body = await make_deferred_yieldable(readBody(response)) if 500 <= response.code < 600: raise Exception("Non-200 response %s" % (...
async def _make_well_known_request( b"GET", uri, headers=Headers(headers) ) ) body_stream = BytesIO() await make_deferred_yieldable( read_body_with_max_size(response, body_stream, WELL_KNOWN_MAX_SIZE) ...
async def _make_well_known_request( except defer.CancelledError: # Bail if we've been cancelled raise except Exception as e: if not retry or i >= WELL_KNOWN_RETRY_ATTEMPTS: logger.info("Error fetching %s: %s", uri_str, e)
async def _make_well_known_request( except defer.CancelledError: # Bail if we've been cancelled raise except BodyExceededMaxSize: # If the well-known file was too large, do not keep attempting # to download it, but consider it a tem...
import synapse.metrics import synapse.util.retryutils from synapse.api.errors import ( FederationDeniedError, HttpResponseException, RequestSendFailed, ) from synapse.http import QuieterFileBodyProducer from synapse.http.client import ( BlacklistingAgentWrapper, BlacklistingReactorWrapper, encod...
import synapse.metrics import synapse.util.retryutils from synapse.api.errors import ( Codes, FederationDeniedError, HttpResponseException, RequestSendFailed, SynapseError, ) from synapse.http import QuieterFileBodyProducer from synapse.http.client import ( BlacklistingAgentWrapper, Blacklis...
async def get_file( headers = dict(response.headers.getAllRawHeaders()) try: d = readBodyToFile(response, output_stream, max_size) d.addTimeout(self.default_timeout, self.reactor) length = await make_deferred_yieldable(d) except Exception as e: lo...
async def get_file( headers = dict(response.headers.getAllRawHeaders()) try: d = read_body_with_max_size(response, output_stream, max_size) d.addTimeout(self.default_timeout, self.reactor) length = await make_deferred_yieldable(d) except BodyExceededMaxSize: ...
from synapse.http.federation.matrix_federation_agent import MatrixFederationAgent from synapse.http.federation.srv_resolver import Server from synapse.http.federation.well_known_resolver import ( WellKnownResolver, _cache_period_from_headers, )
from synapse.http.federation.matrix_federation_agent import MatrixFederationAgent from synapse.http.federation.srv_resolver import Server from synapse.http.federation.well_known_resolver import ( WELL_KNOWN_MAX_SIZE, WellKnownResolver, _cache_period_from_headers, )
def test_well_known_cache_with_temp_failure(self): r = self.successResultOf(fetch_d) self.assertEqual(r.delegated_server, None) def test_srv_fallbacks(self): """Test that other SRV results are tried if the first one fails. """
def test_well_known_cache_with_temp_failure(self): r = self.successResultOf(fetch_d) self.assertEqual(r.delegated_server, None) def test_well_known_too_large(self): """A well-known query that returns a result which is too large should be rejected.""" self.reactor.lookups["testserv"]...
part 3</font></u> self.assertEqual(get_element_by_attribute('class', 'foo', html), None) self.assertEqual(get_element_by_attribute('class', 'no-such-foo', html), None) def test_get_elements_by_class(self): html = ''' <span class="foo bar">nice</span><span class="foo bar">also ni...
part 3</font></u> self.assertEqual(get_element_by_attribute('class', 'foo', html), None) self.assertEqual(get_element_by_attribute('class', 'no-such-foo', html), None) html = ''' <div itemprop="author" itemscope>foo</div> ''' self.assertEqual(get_element_by_attribut...
def get_elements_by_attribute(attribute, value, html, escape_value=True): retlist = [] for m in re.finditer(r'''(?xs) <([a-zA-Z0-9:._-]+) (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'))*? \s+%s=['"]?%s['"]? (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[...
def get_elements_by_attribute(attribute, value, html, escape_value=True): retlist = [] for m in re.finditer(r'''(?xs) <([a-zA-Z0-9:._-]+) (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'|))*? \s+%s=['"]?%s['"]? (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='...
class Register(abc.ABCMeta): # We return this in a topologically sorted list of inheritance: this is useful in some cases (#822) reg = OrderedDict() for cls in cls._reg: if cls.run == NotImplemented: continue name = cls.task_family if name in ...
class Register(abc.ABCMeta): # We return this in a topologically sorted list of inheritance: this is useful in some cases (#822) reg = OrderedDict() for cls in cls._reg: name = cls.task_family if name in reg and reg[name] != cls and \
class AmbiguousClass(luigi.Task): pass class NonAmbiguousClass(luigi.ExternalTask): pass class NonAmbiguousClass(luigi.Task): def run(self): NonAmbiguousClass.has_run = True class TaskWithSameName(luigi.Task): def run(self):
class AmbiguousClass(luigi.Task): pass class TaskWithSameName(luigi.Task): def run(self):
class CmdlineTest(unittest.TestCase): def test_cmdline_ambiguous_class(self, logger): self.assertRaises(Exception, luigi.run, ['--local-scheduler', '--no-lock', 'AmbiguousClass']) @mock.patch("logging.getLogger") @mock.patch("warnings.warn") def test_cmdline_non_ambiguous_class(self, warn, logg...
class CmdlineTest(unittest.TestCase): def test_cmdline_ambiguous_class(self, logger): self.assertRaises(Exception, luigi.run, ['--local-scheduler', '--no-lock', 'AmbiguousClass']) @mock.patch("logging.getLogger") @mock.patch("logging.StreamHandler") def test_setup_interface_logging(self, handle...
from datetime import datetime, timedelta import luigi import luigi.task class DummyTask(luigi.Task):
from datetime import datetime, timedelta import luigi import luigi.task from luigi.task_register import load_task class DummyTask(luigi.Task):
class TaskTest(unittest.TestCase): other = DummyTask.from_str_params(original.to_str_params()) self.assertEqual(original, other) def test_id_to_name_and_params(self): task_id = "InputText(date=2014-12-29)" (name, params) = luigi.task.id_to_name_and_params(task_id)
class TaskTest(unittest.TestCase): other = DummyTask.from_str_params(original.to_str_params()) self.assertEqual(original, other) def test_external_tasks_loadable(self): task = load_task("luigi", "ExternalTask", {}) assert(isinstance(task, luigi.ExternalTask)) def test_id_to_nam...
def serialize_response( errors.extend(errors_) if errors: raise ValidationError(errors) return jsonable_encoder( value, include=include,
def serialize_response( errors.extend(errors_) if errors: raise ValidationError(errors) if skip_defaults and isinstance(response, BaseModel): value = response.dict(skip_defaults=skip_defaults) return jsonable_encoder( value, include=inc...
from django.utils.translation import gettext, gettext_lazy as _ UserModel = get_user_model() class ReadOnlyPasswordHashWidget(forms.Widget): template_name = 'auth/widgets/read_only_password_hash.html' read_only = True
from django.utils.translation import gettext, gettext_lazy as _ UserModel = get_user_model() def _unicode_ci_compare(s1, s2): """ Perform case-insensitive comparison of two identifiers, using the recommended algorithm from Unicode Technical Report 36, section 2.11.2(B)(2). """ return unicodeda...
class PasswordResetForm(forms.Form): that prevent inactive users and users with unusable passwords from resetting their password. """ active_users = UserModel._default_manager.filter(**{ '%s__iexact' % UserModel.get_email_field_name(): email, 'is_active': True, ...
class PasswordResetForm(forms.Form): that prevent inactive users and users with unusable passwords from resetting their password. """ email_field_name = UserModel.get_email_field_name() active_users = UserModel._default_manager.filter(**{ '%s__iexact' % email_field_na...
class PasswordResetForm(forms.Form): user. """ email = self.cleaned_data["email"] for user in self.get_users(email): if not domain_override: current_site = get_current_site(request)
class PasswordResetForm(forms.Form): user. """ email = self.cleaned_data["email"] email_field_name = UserModel.get_email_field_name() for user in self.get_users(email): if not domain_override: current_site = get_current_site(request)
class PasswordResetForm(forms.Form): domain = current_site.domain else: site_name = domain = domain_override context = { 'email': email, 'domain': domain, 'site_name': site_name, 'uid': urlsafe_base64...
class PasswordResetForm(forms.Form): domain = current_site.domain else: site_name = domain = domain_override user_email = getattr(user, email_field_name) context = { 'email': user_email, 'domain': domain, ...
class PasswordResetForm(forms.Form): } self.send_mail( subject_template_name, email_template_name, context, from_email, email, html_email_template_name=html_email_template_name, )
class PasswordResetForm(forms.Form): } self.send_mail( subject_template_name, email_template_name, context, from_email, user_email, html_email_template_name=html_email_template_name, )
class PasswordResetFormTest(TestDataMixin, TestCase): self.assertFalse(form.is_valid()) self.assertEqual(form['email'].errors, [_('Enter a valid email address.')]) def test_nonexistent_email(self): """ Test nonexistent email address. This should not fail because it would
class PasswordResetFormTest(TestDataMixin, TestCase): self.assertFalse(form.is_valid()) self.assertEqual(form['email'].errors, [_('Enter a valid email address.')]) def test_user_email_unicode_collision(self): User.objects.create_user('mike123', 'mike@example.org', 'test123') User.ob...
import time from django.conf import settings from django.db.backends.base.creation import BaseDatabaseCreation from django.db.utils import DatabaseError from django.utils.six.moves import input TEST_DATABASE_PREFIX = 'test_' PASSWORD = 'Im_a_lumberjack' class DatabaseCreation(BaseDatabaseCreation):
import time from django.conf import settings from django.db.backends.base.creation import BaseDatabaseCreation from django.db.utils import DatabaseError from django.utils.crypto import get_random_string from django.utils.six.moves import input TEST_DATABASE_PREFIX = 'test_' class DatabaseCreation(BaseDatabaseCreatio...
class DatabaseCreation(BaseDatabaseCreation): ] # Ignore "user already exists" error when keepdb is on acceptable_ora_err = 'ORA-01920' if keepdb else None self._execute_allow_fail_statements(cursor, statements, parameters, verbosity, acceptable_ora_err) # Most test-suites can be...
class DatabaseCreation(BaseDatabaseCreation): ] # Ignore "user already exists" error when keepdb is on acceptable_ora_err = 'ORA-01920' if keepdb else None success = self._execute_allow_fail_statements(cursor, statements, parameters, verbosity, acceptable_ora_err) # If the passwo...
class DatabaseCreation(BaseDatabaseCreation): """ settings_dict = self.connection.settings_dict val = settings_dict['TEST'].get(key, default) if val is None: val = TEST_DATABASE_PREFIX + settings_dict[prefixed] return val
class DatabaseCreation(BaseDatabaseCreation): """ settings_dict = self.connection.settings_dict val = settings_dict['TEST'].get(key, default) if val is None and prefixed: val = TEST_DATABASE_PREFIX + settings_dict[prefixed] return val
class DatabaseCreation(BaseDatabaseCreation): return self._test_settings_get('USER', prefixed='USER') def _test_database_passwd(self): return self._test_settings_get('PASSWORD', default=PASSWORD) def _test_database_tblspace(self): return self._test_settings_get('TBLSPACE', prefixed='US...
class DatabaseCreation(BaseDatabaseCreation): return self._test_settings_get('USER', prefixed='USER') def _test_database_passwd(self): password = self._test_settings_get('PASSWORD') if password is None and self._test_user_create(): # Oracle passwords are limited to 30 chars and ...