buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_permissions(self): call_command('collectstatic', **self.command_params) test_file = os.path.join(settings.STATIC_ROOT, "test.txt") test_dir = os.path.join(settings.STATIC_ROOT, "subdir") file_mod...
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_permissions(self): call_command('collectstatic', **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / 'test.txt' file_mode = test_file.stat().st_mode & 0o777 ...
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_default_permissions(self): call_command('collectstatic', **self.command_params) test_file = os.path.join(settings.STATIC_ROOT, "test.txt") test_dir = os.path.join(settings.STATIC_ROOT, "subdir") ...
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_default_permissions(self): call_command('collectstatic', **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / 'test.txt' file_mode = test_file.stat().st_mode ...
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_subclass_of_static_storage(self): call_command('collectstatic', **self.command_params) test_file = os.path.join(settings.STATIC_ROOT, "test.txt") test_dir = os.path.join(settings.STATIC_ROOT, "subdir") ...
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_subclass_of_static_storage(self): call_command('collectstatic', **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / 'test.txt' file_mode = test_file.stat().s...
} def reset_format_cache(): """Clear any cached formats.
} FORMAT_SETTINGS = frozenset([ 'DECIMAL_SEPARATOR', 'THOUSAND_SEPARATOR', 'NUMBER_GROUPING', 'FIRST_DAY_OF_WEEK', 'MONTH_DAY_FORMAT', 'TIME_FORMAT', 'DATE_FORMAT', 'DATETIME_FORMAT', 'SHORT_DATE_FORMAT', 'SHORT_DATETIME_FORMAT', 'YEAR_MONTH_FORMAT', 'DATE_INPUT_FORMATS...
def get_format(format_type, lang=None, use_l10n=None): be localized (or not), overriding the value of settings.USE_L10N. """ format_type = force_str(format_type) if use_l10n or (use_l10n is None and settings.USE_L10N): if lang is None: lang = get_language()
def get_format(format_type, lang=None, use_l10n=None): be localized (or not), overriding the value of settings.USE_L10N. """ format_type = force_str(format_type) if format_type not in FORMAT_SETTINGS: return format_type if use_l10n or (use_l10n is None and settings.USE_L10N): if lang...
def test_localized_as_text_as_hidden_input(self): '<input id="id_cents_paid" name="cents_paid" type="hidden" value="59,47" />' ) class MiscTests(SimpleTestCase):
def test_localized_as_text_as_hidden_input(self): '<input id="id_cents_paid" name="cents_paid" type="hidden" value="59,47" />' ) def test_format_arbitrary_settings(self): self.assertEqual(get_format('DEBUG'), 'DEBUG') class MiscTests(SimpleTestCase):
class DataFrame(NDFrame): if is_transposed: data = data.T result = data._data.quantile( qs=q, axis=1, interpolation=interpolation, transposed=is_transposed )
class DataFrame(NDFrame): if is_transposed: data = data.T if len(data.columns) == 0: # GH#23925 _get_numeric_data may have dropped all columns cols = Index([], name=self.columns.name) if is_list_like(q): return self._constructor([], index=...
class TestDataFrameQuantile: ) tm.assert_frame_equal(res, exp) def test_quantile_empty(self): # floats df = DataFrame(columns=["a", "b"], dtype="float64")
class TestDataFrameQuantile: ) tm.assert_frame_equal(res, exp) def test_quantile_empty_no_rows(self): # floats df = DataFrame(columns=["a", "b"], dtype="float64")
class TestDataFrameQuantile: # FIXME (gives NaNs instead of NaT in 0.18.1 or 0.19.0) # res = df.quantile(0.5, numeric_only=False)
class TestDataFrameQuantile: # FIXME (gives NaNs instead of NaT in 0.18.1 or 0.19.0) # res = df.quantile(0.5, numeric_only=False) def test_quantile_empty_no_columns(self): # GH#23925 _get_numeric_data may drop all columns df = pd.DataFrame(pd.date_range("1/1/18", periods=5)) ...
def read_file(cls, file_path, config_name): with open(file_path) as file_stream: return file_stream.read() def read_templates( self, filenames: List[str], custom_template_directory: Optional[str] = None, autoescape: bool = False, ) -> List[jinja2.Template]: ...
def read_file(cls, file_path, config_name): with open(file_path) as file_stream: return file_stream.read() def read_template(self, filename: str) -> jinja2.Template: """Load a template file from disk. This function will attempt to load the given template from the default Synaps...
def read_templates( template directory. If `custom_template_directory` is supplied, that directory is tried first. Files read are treated as Jinja templates. These templates are not rendered yet. Args: filenames: A list of template filenames to read.
def read_templates( template directory. If `custom_template_directory` is supplied, that directory is tried first. Files read are treated as Jinja templates. The templates are not rendered yet and have autoescape enabled. Args: filenames: A list of template filename...
def read_templates( custom_template_directory: A directory to try to look for the templates before using the default Synapse template directory instead. autoescape: Whether to autoescape variables before inserting them into the template. Raises: ...
def read_templates( custom_template_directory: A directory to try to look for the templates before using the default Synapse template directory instead. Raises: ConfigError: if the file's path is incorrect or otherwise cannot be read. Returns: A list...
def read_templates( search_directories.insert(0, custom_template_directory) loader = jinja2.FileSystemLoader(search_directories) env = jinja2.Environment(loader=loader, autoescape=autoescape) # Update the environment with our custom filters env.filters.update(
def read_templates( search_directories.insert(0, custom_template_directory) loader = jinja2.FileSystemLoader(search_directories) env = jinja2.Environment(loader=loader, autoescape=jinja2.select_autoescape(),) # Update the environment with our custom filters env.filters.upda...
def read_templates( } ) for filename in filenames: # Load the template template = env.get_template(filename) templates.append(template) return templates def _format_ts_filter(value: int, format: str):
def read_templates( } ) # Load the templates return [env.get_template(filename) for filename in filenames] def _format_ts_filter(value: int, format: str):
def read_config(self, config, **kwargs): "recaptcha_siteverify_api", "https://www.recaptcha.net/recaptcha/api/siteverify", ) self.recaptcha_template = self.read_templates( ["recaptcha.html"], autoescape=True )[0] def generate_config_section(self, **kwargs...
def read_config(self, config, **kwargs): "recaptcha_siteverify_api", "https://www.recaptcha.net/recaptcha/api/siteverify", ) self.recaptcha_template = self.read_template("recaptcha.html") def generate_config_section(self, **kwargs): return """\
def __init__(self, *args): def read_config(self, config, **kwargs): consent_config = config.get("user_consent") self.terms_template = self.read_templates(["terms.html"], autoescape=True)[0] if consent_config is None: return
def __init__(self, *args): def read_config(self, config, **kwargs): consent_config = config.get("user_consent") self.terms_template = self.read_template("terms.html") if consent_config is None: return
def read_config(self, config, **kwargs): self.session_lifetime = session_lifetime # The success template used during fallback auth. self.fallback_success_template = self.read_templates( ["auth_success.html"], autoescape=True )[0] def generate_config_section(self, genera...
def read_config(self, config, **kwargs): self.session_lifetime = session_lifetime # The success template used during fallback auth. self.fallback_success_template = self.read_template("auth_success.html") def generate_config_section(self, generate_secrets=False, **kwargs): if gener...
def make_unsubscribe_link( def safe_markup(raw_html: str) -> jinja2.Markup: return jinja2.Markup( bleach.linkify( bleach.clean(
def make_unsubscribe_link( def safe_markup(raw_html: str) -> jinja2.Markup: """ Sanitise a raw HTML string to a set of allowed tags and attributes, and linkify any bare URLs. Args raw_html: Unsafe HTML. Returns: A Markup object ready to safely use in a Jinja template. """ ret...
def safe_markup(raw_html: str) -> jinja2.Markup: def safe_text(raw_text: str) -> jinja2.Markup: """ Process text: treat it as HTML but escape any tags (ie. just escape the HTML) then linkify it. """ return jinja2.Markup( bleach.linkify(bleach.clean(raw_text, tags=[], attributes={}, strip=Fa...
def safe_markup(raw_html: str) -> jinja2.Markup: def safe_text(raw_text: str) -> jinja2.Markup: """ Sanitise text (escape any HTML tags), and then linkify any bare URLs. Args raw_text: Unsafe text which might include HTML markup. Returns: A Markup object ready to safely use in a Jinja...
def readString(self): pass def skip(self, type): if type == TType.STOP: return elif type == TType.BOOL: self.readBool() elif type == TType.BYTE: self.readByte()
def readString(self): pass def skip(self, type): if type == TType.BOOL: self.readBool() elif type == TType.BYTE: self.readByte()
def skip(self, type): for _ in range(size): self.skip(etype) self.readListEnd() def readIntegral(self, type): if type == TType.BOOL:
def skip(self, type): for _ in range(size): self.skip(etype) self.readListEnd() else: raise TProtocolException( TProtocolException.INVALID_DATA, "Unexpected type for skipping {}".format(type) ) def readIntegral(...
def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]: for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = get_schema_compatible_field(field=f) required = any(True for f in flat_dependant.body_params if f.required) if any(isinstance(f.schema, params.File) for f in...
def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]: for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = get_schema_compatible_field(field=f) required = any(True for f in flat_dependant.body_params if f.required) BodySchema_kwargs: Dict[str, Any] = dict(default...
def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]: else: BodySchema = params.Body field = Field( name="body", type_=BodyModel,
def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]: else: BodySchema = params.Body body_param_media_types = [ getattr(f.schema, "media_type") for f in flat_dependant.body_params if isinstance(f.schema, params.Body) ] if len(...
def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]: model_config=BaseConfig, class_validators={}, alias="body", schema=BodySchema(None), ) return field
def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]: model_config=BaseConfig, class_validators={}, alias="body", schema=BodySchema(**BodySchema_kwargs), ) return field
def split_line( return line_str = str(line).strip("\n") if not line.should_explode and is_line_short_enough( line, line_length=line_length, line_str=line_str ): yield line return
def split_line( return line_str = str(line).strip("\n") # we don't want to split special comments like type annotations # https://github.com/python/typing/issues/186 has_special_comment = False for leaf in line.leaves: for comment in line.comments_after(leaf): if leaf.t...
def is_import(leaf: Leaf) -> bool: ) def normalize_prefix(leaf: Leaf, *, inside_brackets: bool) -> None: """Leave existing extra newlines if not `inside_brackets`. Remove everything else.
def is_import(leaf: Leaf) -> bool: ) def is_special_comment(leaf: Leaf) -> bool: """Return True if the given leaf is a special comment. Only returns true for type comments for now.""" t = leaf.type v = leaf.value return bool( (t == token.COMMENT or t == STANDALONE_COMMENT) and (v.start...
def ensure_visible(leaf: Leaf) -> None: def should_explode(line: Line, opening_bracket: Leaf) -> bool: """Should `line` immediately be split with `delimiter_split()` after RHS?""" if not ( opening_bracket.parent and opening_bracket.parent.type in {syms.atom, syms.import_from}
def ensure_visible(leaf: Leaf) -> None: def should_explode(line: Line, opening_bracket: Leaf) -> bool: """Should `line` immediately be split with `delimiter_split()` after RHS?""" if not ( opening_bracket.parent and opening_bracket.parent.type in {syms.atom, syms.import_from}
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_comments6(self) -> None: source, expected = read_data("comments6") actual = fs(source) ...
from scrapy.exceptions import DontCloseSpider from scrapy.http import Response, Request from scrapy.utils.misc import load_object from scrapy.utils.reactor import CallLaterOnce from scrapy.utils.log import logformatter_adapter logger = logging.getLogger(__name__)
from scrapy.exceptions import DontCloseSpider from scrapy.http import Response, Request from scrapy.utils.misc import load_object from scrapy.utils.reactor import CallLaterOnce from scrapy.utils.log import logformatter_adapter, failure_to_exc_info logger = logging.getLogger(__name__)
class ExecutionEngine(object): d = self._download(request, spider) d.addBoth(self._handle_downloader_output, request, spider) d.addErrback(lambda f: logger.info('Error while handling downloader output', extra={'spider': spider, 'failure': f})) d...
class ExecutionEngine(object): d = self._download(request, spider) d.addBoth(self._handle_downloader_output, request, spider) d.addErrback(lambda f: logger.info('Error while handling downloader output', exc_info=failure_to_exc_info(f), ...
class ExecutionEngine(object): # response is a Response or Failure d = self.scraper.enqueue_scrape(response, request, spider) d.addErrback(lambda f: logger.error('Error while enqueuing downloader output', extra={'spider': spider, 'failure': f})) ...
class ExecutionEngine(object): # response is a Response or Failure d = self.scraper.enqueue_scrape(response, request, spider) d.addErrback(lambda f: logger.error('Error while enqueuing downloader output', exc_info=failure_to_exc_info(f), ...
class ExecutionEngine(object): def log_failure(msg): def errback(failure): logger.error(msg, extra={'spider': spider, 'failure': failure}) return errback dfd.addBoth(lambda _: self.downloader.close())
class ExecutionEngine(object): def log_failure(msg): def errback(failure): logger.error( msg, exc_info=failure_to_exc_info(failure), extra={'spider': spider} ) return errback dfd.addBoth...
from twisted.internet import defer from scrapy.utils.defer import defer_result, defer_succeed, parallel, iter_errback from scrapy.utils.spider import iterate_spider_output from scrapy.utils.misc import load_object from scrapy.utils.log import logformatter_adapter from scrapy.exceptions import CloseSpider, DropItem, Ign...
from twisted.internet import defer from scrapy.utils.defer import defer_result, defer_succeed, parallel, iter_errback from scrapy.utils.spider import iterate_spider_output from scrapy.utils.misc import load_object from scrapy.utils.log import logformatter_adapter, failure_to_exc_info from scrapy.exceptions import Close...
class Scraper(object): dfd.addErrback( lambda f: logger.error('Scraper bug processing %(request)s', {'request': request}, extra={'spider': spider, 'failure': f})) self._scrape_next(spider, slot) return dfd
class Scraper(object): dfd.addErrback( lambda f: logger.error('Scraper bug processing %(request)s', {'request': request}, exc_info=failure_to_exc_info(f), extra={'spider': spider})) self....
class Scraper(object): logger.error( "Spider error processing %(request)s (referer: %(referer)s)", {'request': request, 'referer': referer}, extra={'spider': spider, 'failure': _failure} ) self.signals.send_catch_log( signal=signals.spider_error,
class Scraper(object): logger.error( "Spider error processing %(request)s (referer: %(referer)s)", {'request': request, 'referer': referer}, exc_info=failure_to_exc_info(_failure), extra={'spider': spider} ) self.signals.send_catch_log( ...
class Scraper(object): if download_failure.frames: logger.error('Error downloading %(request)s', {'request': request}, extra={'spider': spider, 'failure': download_failure}) else: errmsg = download_failure....
class Scraper(object): if download_failure.frames: logger.error('Error downloading %(request)s', {'request': request}, exc_info=failure_to_exc_info(download_failure), extra={'spider': spider}) ...
class Scraper(object): spider=spider, exception=output.value) else: logger.error('Error processing %(item)s', {'item': item}, extra={'spider': spider, 'failure': output}) else: logkws = self.logformatter.scraped(output, res...
class Scraper(object): spider=spider, exception=output.value) else: logger.error('Error processing %(item)s', {'item': item}, exc_info=failure_to_exc_info(output), extra={'spider': spider}) else: ...
from six.moves.urllib import robotparser from scrapy.exceptions import NotConfigured, IgnoreRequest from scrapy.http import Request from scrapy.utils.httpobj import urlparse_cached logger = logging.getLogger(__name__)
from six.moves.urllib import robotparser from scrapy.exceptions import NotConfigured, IgnoreRequest from scrapy.http import Request from scrapy.utils.httpobj import urlparse_cached from scrapy.utils.log import failure_to_exc_info logger = logging.getLogger(__name__)
class RobotsTxtMiddleware(object): if failure.type is not IgnoreRequest: logger.error("Error downloading %(request)s: %(f_exception)s", {'request': request, 'f_exception': failure.value}, extra={'spider': spider, 'failure': failure}) def _parse_...
class RobotsTxtMiddleware(object): if failure.type is not IgnoreRequest: logger.error("Error downloading %(request)s: %(f_exception)s", {'request': request, 'f_exception': failure.value}, exc_info=failure_to_exc_info(failure), ...
from scrapy.utils.ftp import ftp_makedirs_cwd from scrapy.exceptions import NotConfigured from scrapy.utils.misc import load_object from scrapy.utils.python import get_func_args logger = logging.getLogger(__name__)
from scrapy.utils.ftp import ftp_makedirs_cwd from scrapy.exceptions import NotConfigured from scrapy.utils.misc import load_object from scrapy.utils.python import get_func_args from scrapy.utils.log import failure_to_exc_info logger = logging.getLogger(__name__)
class FeedExporter(object): d.addCallback(lambda _: logger.info(logfmt % "Stored", log_args, extra={'spider': spider})) d.addErrback(lambda f: logger.error(logfmt % "Error storing", log_args, extra={'spider': spider,...
class FeedExporter(object): d.addCallback(lambda _: logger.info(logfmt % "Stored", log_args, extra={'spider': spider})) d.addErrback(lambda f: logger.error(logfmt % "Error storing", log_args, exc_info=failure_to_exc_...
import warnings from twisted.python.failure import Failure from scrapy.exceptions import ScrapyDeprecationWarning logger = logging.getLogger(__name__)
import warnings from twisted.python.failure import Failure from scrapy.exceptions import ScrapyDeprecationWarning from scrapy.utils.log import failure_to_exc_info logger = logging.getLogger(__name__)
def err(_stuff=None, _why=None, **kw): level = kw.pop('level', logging.ERROR) failure = kw.pop('failure', _stuff) or Failure() message = kw.pop('why', _why) or failure.value logger.log(level, message, *[kw] if kw else [], extra={'failure': failure})
def err(_stuff=None, _why=None, **kw): level = kw.pop('level', logging.ERROR) failure = kw.pop('failure', _stuff) or Failure() message = kw.pop('why', _why) or failure.value logger.log(level, message, *[kw] if kw else [], exc_info=failure_to_exc_info(failure))
from scrapy.pipelines.media import MediaPipeline from scrapy.exceptions import NotConfigured, IgnoreRequest from scrapy.http import Request from scrapy.utils.misc import md5sum logger = logging.getLogger(__name__)
from scrapy.pipelines.media import MediaPipeline from scrapy.exceptions import NotConfigured, IgnoreRequest from scrapy.http import Request from scrapy.utils.misc import md5sum from scrapy.utils.log import failure_to_exc_info logger = logging.getLogger(__name__)
class FilesPipeline(MediaPipeline): dfd.addErrback( lambda f: logger.error(self.__class__.__name__ + '.store.stat_file', extra={'spider': info.spider, 'failure': f}) ) return dfd
class FilesPipeline(MediaPipeline): dfd.addErrback( lambda f: logger.error(self.__class__.__name__ + '.store.stat_file', exc_info=failure_to_exc_info(f), extra={'spider': info.spider}) ) return dfd
from twisted.python.failure import Failure from scrapy.utils.defer import mustbe_deferred, defer_result from scrapy.utils.request import request_fingerprint from scrapy.utils.misc import arg_to_iter logger = logging.getLogger(__name__)
from twisted.python.failure import Failure from scrapy.utils.defer import mustbe_deferred, defer_result from scrapy.utils.request import request_fingerprint from scrapy.utils.misc import arg_to_iter from scrapy.utils.log import failure_to_exc_info logger = logging.getLogger(__name__)
class MediaPipeline(object): dfd.addCallback(self._check_media_to_download, request, info) dfd.addBoth(self._cache_result_and_execute_waiters, fp, info) dfd.addErrback(lambda f: logger.error( f.value, extra={'spider': info.spider, 'failure': f}) ) return dfd.addBoth(l...
class MediaPipeline(object): dfd.addCallback(self._check_media_to_download, request, info) dfd.addBoth(self._cache_result_and_execute_waiters, fp, info) dfd.addErrback(lambda f: logger.error( f.value, exc_info=failure_to_exc_info(f), extra={'spider': info.spider}) ) r...
class MediaPipeline(object): logger.error( '%(class)s found errors processing %(item)s', {'class': self.__class__.__name__, 'item': item}, extra={'spider': info.spider, 'failure': value} ) return item
class MediaPipeline(object): logger.error( '%(class)s found errors processing %(item)s', {'class': self.__class__.__name__, 'item': item}, exc_info=failure_to_exc_info(value), extra={'spider': info.spider...
# -*- coding: utf-8 -*- import os import sys import logging import warnings
# -*- coding: utf-8 -*- import sys import logging import warnings
from scrapy.exceptions import ScrapyDeprecationWarning logger = logging.getLogger(__name__) class FailureFormatter(logging.Filter): """Extract exc_info from Failure instances provided as contextual data This filter mimics Twisted log.err formatting for its first `_stuff` argument, which means that reprs ...
from scrapy.exceptions import ScrapyDeprecationWarning logger = logging.getLogger(__name__) def failure_to_exc_info(failure): """Extract exc_info from Failure instances""" if isinstance(failure, Failure): return (failure.type, failure.value, failure.tb) class TopLevelFormatter(logging.Filter):
class TopLevelFormatter(logging.Filter): DEFAULT_LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'failure_formatter': { '()': 'scrapy.utils.log.FailureFormatter', }, }, 'loggers': { 'scrapy': { 'level': 'DEBUG', 'f...
class TopLevelFormatter(logging.Filter): DEFAULT_LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'loggers': { 'scrapy': { 'level': 'DEBUG', }, 'twisted': { 'level': 'ERROR',
from twisted.python.failure import Failure from scrapy.xlib.pydispatch.dispatcher import Any, Anonymous, liveReceivers, \ getAllReceivers, disconnect from scrapy.xlib.pydispatch.robustapply import robustApply logger = logging.getLogger(__name__)
from twisted.python.failure import Failure from scrapy.xlib.pydispatch.dispatcher import Any, Anonymous, liveReceivers, \ getAllReceivers, disconnect from scrapy.xlib.pydispatch.robustapply import robustApply from scrapy.utils.log import failure_to_exc_info logger = logging.getLogger(__name__)
def send_catch_log_deferred(signal=Any, sender=Anonymous, *arguments, **named): if dont_log is None or not isinstance(failure.value, dont_log): logger.error("Error caught on signal handler: %(receiver)s", {'receiver': recv}, extra={'spider': spider, ...
def send_catch_log_deferred(signal=Any, sender=Anonymous, *arguments, **named): if dont_log is None or not isinstance(failure.value, dont_log): logger.error("Error caught on signal handler: %(receiver)s", {'receiver': recv}, exc_info=failure_to_exc_i...
from scrapy.http import Request, Response from scrapy.spiders import Spider from scrapy.utils.request import request_fingerprint from scrapy.pipelines.media import MediaPipeline from scrapy.utils.signal import disconnect_all from scrapy import signals
from scrapy.http import Request, Response from scrapy.spiders import Spider from scrapy.utils.request import request_fingerprint from scrapy.pipelines.media import MediaPipeline from scrapy.utils.log import failure_to_exc_info from scrapy.utils.signal import disconnect_all from scrapy import signals
class BaseMediaPipelineTestCase(unittest.TestCase): assert len(l.records) == 1 record = l.records[0] assert record.levelname == 'ERROR' assert record.failure is fail # disable failure logging and check again self.pipe.LOG_FAILED_RESULTS = False
class BaseMediaPipelineTestCase(unittest.TestCase): assert len(l.records) == 1 record = l.records[0] assert record.levelname == 'ERROR' self.assertTupleEqual(record.exc_info, failure_to_exc_info(fail)) # disable failure logging and check again self.pipe.LOG_FAILED_RESULT...
# -*- coding: utf-8 -*- from __future__ import print_function import os import sys import logging import unittest
# -*- coding: utf-8 -*- from __future__ import print_function import sys import logging import unittest
import unittest from testfixtures import LogCapture from twisted.python.failure import Failure from scrapy.utils.log import (FailureFormatter, TopLevelFormatter, LogCounterHandler, StreamLogger) from scrapy.utils.test import get_crawler class FailureFormatterTest(unittest.TestCase): ...
import unittest from testfixtures import LogCapture from twisted.python.failure import Failure from scrapy.utils.log import (failure_to_exc_info, TopLevelFormatter, LogCounterHandler, StreamLogger) from scrapy.utils.test import get_crawler class FailureToExcInfoTest(unittest.TestCase): ...
def parse_uri(self, uri): "like so: " "swift+http://user:pass@authurl.com/v1/container/obj" ) LOG.error(_("Invalid store uri %(uri)s: %(reason)s") % locals()) raise exception.BadStoreUri(message=reason) pieces = urlparse.urlpar...
def parse_uri(self, uri): "like so: " "swift+http://user:pass@authurl.com/v1/container/obj" ) LOG.error(_("Invalid store URI: %(reason)s") % locals()) raise exception.BadStoreUri(message=reason) pieces = urlparse.urlparse(uri)
def parse_uri(self, uri): if creds: cred_parts = creds.split(':') if len(cred_parts) != 2: reason = (_("Badly formed credentials '%(creds)s' in Swift " "URI") % locals()) LOG.error(reason) raise exception.BadStor...
def parse_uri(self, uri): if creds: cred_parts = creds.split(':') if len(cred_parts) != 2: reason = (_("Badly formed credentials in Swift URI.")) LOG.error(reason) raise exception.BadStoreUri() user, key = cred_parts
def parse_uri(self, uri): path_parts.insert(0, netloc) self.auth_or_store_url = '/'.join(path_parts) except IndexError: reason = _("Badly formed Swift URI: %s") % uri LOG.error(reason) raise exception.BadStoreUri()
def parse_uri(self, uri): path_parts.insert(0, netloc) self.auth_or_store_url = '/'.join(path_parts) except IndexError: reason = _("Badly formed Swift URI.") LOG.error(reason) raise exception.BadStoreUri()
def get(self, location): except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_store_uri() raise exception.NotFound(_("Swift could not find image at " "uri %(uri)s") % locals()) ...
def get(self, location): except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_store_uri() msg = _("Swift could not find image at URI.") raise exception.NotFound(msg) else: raise
def add(self, image_id, image_file, image_size): except swiftclient.ClientException, e: if e.http_status == httplib.CONFLICT: raise exception.Duplicate(_("Swift already has an image at " "location %s") % location.get_uri()) msg = ...
def add(self, image_id, image_file, image_size): except swiftclient.ClientException, e: if e.http_status == httplib.CONFLICT: raise exception.Duplicate(_("Swift already has an image at " "this location.")) msg = (_("Failed to add ...
def delete(self, location): except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_store_uri() raise exception.NotFound(_("Swift could not find image at " "uri %(uri)s") % locals()) ...
def delete(self, location): except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_store_uri() msg = _("Swift could not find image at URI.") raise exception.NotFound(msg) else: raise...
def set_acls(self, location, public=False, read_tenants=[], except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_store_uri() raise exception.NotFound(_("Swift could not find image at " ...
def set_acls(self, location, public=False, read_tenants=[], except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_store_uri() msg = _("Swift could not find image at URI.") raise exception.N...
class SparkSubmitTask(luigi.Task): command = [] if value and isinstance(value, dict): for prop, value in value.items(): command += [name, '"{0}={1}"'.format(prop, value)] return command def _flag_arg(self, name, value):
class SparkSubmitTask(luigi.Task): command = [] if value and isinstance(value, dict): for prop, value in value.items(): command += [name, '{0}={1}'.format(prop, value)] return command def _flag_arg(self, name, value):
class SparkSubmitTaskTest(unittest.TestCase): self.assertEqual(proc.call_args[0][0], ['ss-stub', '--master', 'yarn-client', '--deploy-mode', 'client', '--name', 'AppName', '--class', 'org.test.MyClass', '--jars', 'jars/my.jar', '--py-files', 'file1.py,file2.py'...
class SparkSubmitTaskTest(unittest.TestCase): self.assertEqual(proc.call_args[0][0], ['ss-stub', '--master', 'yarn-client', '--deploy-mode', 'client', '--name', 'AppName', '--class', 'org.test.MyClass', '--jars', 'jars/my.jar', '--py-files', 'file1.py,file2.py'...
class SparkSubmitTaskTest(unittest.TestCase): self.assertEqual(proc.call_args[0][0], ['ss-stub', '--master', 'spark://host:7077', '--jars', 'jar1.jar,jar2.jar', '--py-files', 'file1.py,file2.py', '--files', 'file1,file2', '--archives', 'archive1', ...
class SparkSubmitTaskTest(unittest.TestCase): self.assertEqual(proc.call_args[0][0], ['ss-stub', '--master', 'spark://host:7077', '--jars', 'jar1.jar,jar2.jar', '--py-files', 'file1.py,file2.py', '--files', 'file1,file2', '--archives', 'archive1', ...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import random import shlex
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import errno import fcntl import os import random import shlex
import subprocess import sys import tempfile import warnings from binascii import hexlify from binascii import unhexlify from binascii import Error as BinasciiError
import subprocess import sys import tempfile import warnings from binascii import hexlify from binascii import unhexlify from binascii import Error as BinasciiError
class VaultEditor: os.remove(tmp_path) def _edit_file_helper(self, filename, secret, existing_data=None, force_save=False, vault_id=None): # Create a tempfile root, ext = os.path.splitext(os.path.realpath(filename)) fd, tmp_path = tempfile.mkstemp(suffix=...
class VaultEditor: os.remove(tmp_path) def _edit_file_helper(self, filename, secret, existing_data=None, force_save=False, vault_id=None): # Create a tempfile root, ext = os.path.splitext(os.path.realpath(filename)) fd, tmp_path = tempfile.mkstemp(suffix=ext, dir=C.DEFAULT_LOCAL_T...
class VaultEditor: # Figure out the vault id from the file, to select the right secret to re-encrypt it # (duplicates parts of decrypt, but alas...) dummy, dummy, cipher_name, vault_id = parse_vaulttext_envelope(b_vaulttext, ...
class VaultEditor: # Figure out the vault id from the file, to select the right secret to re-encrypt it # (duplicates parts of decrypt, but alas...) dummy, dummy, cipher_name, vault_id = parse_vaulttext_envelope(b_vaulttext, filename=filename) # vault id here may not be the vault id ac...
class VaultEditor: return data # TODO: add docstrings for arg types since this code is picky about that def write_data(self, data, filename, shred=True): """Write the data bytes to given path This is used to write a byte string to a file or stdout. It is used for
class VaultEditor: return data def write_data(self, data, thefile, shred=True, mode=0o600): # TODO: add docstrings for arg types since this code is picky about that """Write the data bytes to given path This is used to write a byte string to a file or stdout. It is used for
class VaultEditor: should be a byte string and not a text type. :arg data: the byte string (bytes) data :arg filename: filename to save 'data' to. :arg shred: if shred==True, make sure that the original data is first shredded so that is cannot be recovered. :returns: None ...
class VaultEditor: should be a byte string and not a text type. :arg data: the byte string (bytes) data :arg thefile: file descriptor or filename to save 'data' to. :arg shred: if shred==True, make sure that the original data is first shredded so that is cannot be recovered. :re...
class HTTP1Connection(httputil.HTTPConnection): return connection_header != "close" elif ("Content-Length" in headers or headers.get("Transfer-Encoding", "").lower() == "chunked" or start_line.method in ("HEAD", "GET")): return connection_header == "keep-alive...
class HTTP1Connection(httputil.HTTPConnection): return connection_header != "close" elif ("Content-Length" in headers or headers.get("Transfer-Encoding", "").lower() == "chunked" or getattr(start_line, 'method', None) in ("HEAD", "GET")): # start_line may be a...
TEST_MODULES = [ 'tornado.test.curl_httpclient_test', 'tornado.test.escape_test', 'tornado.test.gen_test', 'tornado.test.httpclient_test', 'tornado.test.httpserver_test', 'tornado.test.httputil_test',
TEST_MODULES = [ 'tornado.test.curl_httpclient_test', 'tornado.test.escape_test', 'tornado.test.gen_test', 'tornado.test.http1connection_test', 'tornado.test.httpclient_test', 'tornado.test.httpserver_test', 'tornado.test.httputil_test',
def SHA244(self,data:str): hash = str(sha.digest()) return self.__Salt(hash,salt=self.salt) def MD5(self,data:str): sha = hashlib.md5(bytes(data.encode())) hash = str(sha.digest()) return self.__Salt(hash,salt=self.salt) def SHA384(self,data:str): sha = hashlib....
def SHA244(self,data:str): hash = str(sha.digest()) return self.__Salt(hash,salt=self.salt) def SHA384(self,data:str): sha = hashlib.sha384(bytes(data.encode())) hash = str(sha.digest())
setup(name='gym', if package.startswith('gym')], zip_safe=False, install_requires=[ 'scipy', 'numpy>=1.10.4', 'pyglet>=1.4.0,<=1.5.0', 'Pillow<=7.2.0', 'cloudpickle>=1.2.0,<1.7.0', ], extras_require=extras, package_data={'gym': [
setup(name='gym', if package.startswith('gym')], zip_safe=False, install_requires=[ 'scipy', 'numpy>=1.10.4', 'pyglet>=1.4.0,<=1.5.15', 'Pillow<=8.2.0', 'cloudpickle>=1.2.0,<1.7.0', ], extras_require=extras, package_data={'gym': [
except ImportError: from ordereddict import OrderedDict from luigi import six class TaskClassException(Exception):
except ImportError: from ordereddict import OrderedDict from luigi import six import logging logger = logging.getLogger('luigi-interface') class TaskClassException(Exception):
from helpers import unittest import luigi import luigi.date_interval import luigi.notifications
from helpers import unittest import luigi import luigi.worker import luigi.date_interval import luigi.notifications
class InstanceTest(unittest.TestCase): self.assertNotEqual(dummy_1, dummy_2) self.assertEqual(dummy_1, dummy_1b) if __name__ == '__main__': unittest.main()
class InstanceTest(unittest.TestCase): self.assertNotEqual(dummy_1, dummy_2) self.assertEqual(dummy_1, dummy_1b) def test_unhashable_type(self): # See #857 class DummyTask(luigi.Task): x = luigi.Parameter() dummy = DummyTask(x={}) if __name__ == '__main__': ...
class WorkerProcess(multiprocessing_context.Process): self._variable_manager = variable_manager self._shared_loader_obj = shared_loader_obj def _save_stdin(self): self._new_stdin = os.devnull try:
class WorkerProcess(multiprocessing_context.Process): self._variable_manager = variable_manager self._shared_loader_obj = shared_loader_obj # NOTE: this works due to fork, if switching to threads this should change to per thread storage of temp files # clear var to ensure we only delete...
class WorkerProcess(multiprocessing_context.Process): except Exception: display.debug(u"WORKER EXCEPTION: %s" % to_text(e)) display.debug(u"WORKER TRACEBACK: %s" % to_text(traceback.format_exc())) display.debug("WORKER PROCESS EXITING")
class WorkerProcess(multiprocessing_context.Process): except Exception: display.debug(u"WORKER EXCEPTION: %s" % to_text(e)) display.debug(u"WORKER TRACEBACK: %s" % to_text(traceback.format_exc())) finally: self._clean_up() ...
class WorkerProcess(multiprocessing_context.Process): # ps.print_stats() # with open('worker_%06d.stats' % os.getpid(), 'w') as f: # f.write(s.getvalue())
class WorkerProcess(multiprocessing_context.Process): # ps.print_stats() # with open('worker_%06d.stats' % os.getpid(), 'w') as f: # f.write(s.getvalue()) def _clean_up(self): # NOTE: see note in init about forks # ensure we cleanup all temp files for this worker ...
class DataLoader: ''' def __init__(self): self._basedir = '.' self._FILE_CACHE = dict() self._tempfiles = set() # initialize the vault stuff with an empty password
class DataLoader: ''' def __init__(self): self._basedir = '.' # NOTE: not effective with forks as the main copy does not get updated. # avoids rereading files self._FILE_CACHE = dict() # NOTE: not thread safe, also issues with forks not returning data to main proc ...
class DataLoader: def _create_content_tempfile(self, content): ''' Create a tempfile containing defined content ''' fd, content_tempfile = tempfile.mkstemp() f = os.fdopen(fd, 'wb') content = to_bytes(content) try:
class DataLoader: def _create_content_tempfile(self, content): ''' Create a tempfile containing defined content ''' fd, content_tempfile = tempfile.mkstemp(dir=C.DEFAULT_LOCAL_TMP) f = os.fdopen(fd, 'wb') content = to_bytes(content) try:
class DataLoader: self._tempfiles.remove(file_path) def cleanup_all_tmp_files(self): for f in self._tempfiles: try: self.cleanup_tmp_file(f)
class DataLoader: self._tempfiles.remove(file_path) def cleanup_all_tmp_files(self): """ Removes all temporary files that DataLoader has created NOTE: not thread safe, forks also need special handling see __init__ for details. """ for f in self._tempfiles: ...
class VaultEditor: # Create a tempfile root, ext = os.path.splitext(os.path.realpath(filename)) fd, tmp_path = tempfile.mkstemp(suffix=ext) os.close(fd) cmd = self._editor_shell_command(tmp_path)
class VaultEditor: # Create a tempfile root, ext = os.path.splitext(os.path.realpath(filename)) fd, tmp_path = tempfile.mkstemp(suffix=ext, dir=C.DEFAULT_LOCAL_TMP) os.close(fd) cmd = self._editor_shell_command(tmp_path)
ASCTIME_DATE = _lazy_re_compile(r"^\w{3} %s %s %s %s$" % (__M, __D2, __T, __Y)) RFC3986_GENDELIMS = ":/?#[]@" RFC3986_SUBDELIMS = "!$&'()*+,;=" def urlencode(query, doseq=False): """
ASCTIME_DATE = _lazy_re_compile(r"^\w{3} %s %s %s %s$" % (__M, __D2, __T, __Y)) RFC3986_GENDELIMS = ":/?#[]@" RFC3986_SUBDELIMS = "!$&'()*+,;=" # TODO: Remove when dropping support for PY38. # Unsafe bytes to be removed per WHATWG spec. _UNSAFE_URL_BYTES_TO_REMOVE = ["\t", "\r", "\n"] def urlencode(query, doseq=Fals...
def url_has_allowed_host_and_scheme(url, allowed_hosts, require_https=False): ) # Copied from urllib.parse.urlparse() but uses fixed urlsplit() function. def _urlparse(url, scheme="", allow_fragments=True): """Parse a URL into 6 components:
def url_has_allowed_host_and_scheme(url, allowed_hosts, require_https=False): ) # TODO: Remove when dropping support for PY38. # Copied from urllib.parse.urlparse() but uses fixed urlsplit() function. def _urlparse(url, scheme="", allow_fragments=True): """Parse a URL into 6 components:
def _urlparse(url, scheme="", allow_fragments=True): return _coerce_result(result) # Copied from urllib.parse.urlsplit() with # https://github.com/python/cpython/pull/661 applied. def _urlsplit(url, scheme="", allow_fragments=True): """Parse a URL into 5 components: <scheme>://<netloc>/<path>?<query>#<fra...
def _urlparse(url, scheme="", allow_fragments=True): return _coerce_result(result) # TODO: Remove when dropping support for PY38. def _remove_unsafe_bytes_from_url(url): for b in _UNSAFE_URL_BYTES_TO_REMOVE: url = url.replace(b, "") return url # TODO: Remove when dropping support for PY38. # Bac...
def _urlsplit(url, scheme="", allow_fragments=True): Note that we don't break the components up in smaller bits (e.g. netloc is a single string) and we don't expand % escapes.""" url, scheme, _coerce_result = _coerce_args(url, scheme) netloc = query = fragment = "" i = url.find(":") if i > 0:
def _urlsplit(url, scheme="", allow_fragments=True): Note that we don't break the components up in smaller bits (e.g. netloc is a single string) and we don't expand % escapes.""" url, scheme, _coerce_result = _coerce_args(url, scheme) url = _remove_unsafe_bytes_from_url(url) scheme = _remove_unsafe_...
class URLHasAllowedHostAndSchemeTests(unittest.TestCase): r"http:/\example.com", 'javascript:alert("XSS")', "\njavascript:alert(x)", "\x08//example.com", r"http://otherserver\@example.com", r"http:\\testserver\@example.com",
class URLHasAllowedHostAndSchemeTests(unittest.TestCase): r"http:/\example.com", 'javascript:alert("XSS")', "\njavascript:alert(x)", "java\nscript:alert(x)", "\x08//example.com", r"http://otherserver\@example.com", r"http:\\testserver\@...
class LocalFileSystem(FileSystem): raise RuntimeError('Destination exists: %s' % new_path) d = os.path.dirname(new_path) if d and not os.path.exists(d): self.fs.mkdir(d) os.rename(old_path, new_path)
class LocalFileSystem(FileSystem): raise RuntimeError('Destination exists: %s' % new_path) d = os.path.dirname(new_path) if d and not os.path.exists(d): self.mkdir(d) os.rename(old_path, new_path)
class FileSystemTest(unittest.TestCase): pass self.assertTrue([self.path + '/file'], list(self.fs.listdir(self.path + '/'))) class TestImportFile(unittest.TestCase):
class FileSystemTest(unittest.TestCase): pass self.assertTrue([self.path + '/file'], list(self.fs.listdir(self.path + '/'))) def test_move_to_new_dir(self): # Regression test for a bug in LocalFileSystem.move src = os.path.join(self.path, 'src.txt') dest = os.path.join(s...
from thefuck.rules.git_diff_staged import match, get_new_command from tests.utils import Command @pytest.mark.parametrize('command', [Command(script='git diff')]) def test_match(command): assert match(command, None)
from thefuck.rules.git_diff_staged import match, get_new_command from tests.utils import Command @pytest.mark.parametrize('command', [ Command(script='git diff foo'), Command(script='git diff')]) def test_match(command): assert match(command, None)
def test_not_match(command): @pytest.mark.parametrize('command, new_command', [ (Command('git diff'), 'git diff --staged')]) def test_get_new_command(command, new_command): assert get_new_command(command, None) == new_command
def test_not_match(command): @pytest.mark.parametrize('command, new_command', [ (Command('git diff'), 'git diff --staged'), (Command('git diff foo'), 'git diff --staged foo')]) def test_get_new_command(command, new_command): assert get_new_command(command, None) == new_command
def match(command, settings): @utils.git_support def get_new_command(command, settings): return '{} --staged'.format(command.script)
def match(command, settings): @utils.git_support def get_new_command(command, settings): return command.script.replace(' diff', ' diff --staged')
class _AtIndexer(_ScalarAccessIndexer): "can only have integer indexers" ) else: if is_integer(i) and not ax.holds_integer(): raise ValueError( "At based indexing on an non-integer " ...
class _AtIndexer(_ScalarAccessIndexer): "can only have integer indexers" ) else: if is_integer(i) and not (ax.holds_integer() or ax.is_floating()): raise ValueError( "At based indexing on an non-integer "...
class TestFloat64Index(Numeric): ) def test_lookups_datetimelike_values(self, vals): # If we have datetime64 or timedelta64 values, make sure they are # wrappped correctly ser = pd.Series(vals, index=range(3, 6)) ser.index = ser.index.astype("float64")
class TestFloat64Index(Numeric): ) def test_lookups_datetimelike_values(self, vals): # If we have datetime64 or timedelta64 values, make sure they are # wrappped correctly GH#31163 ser = pd.Series(vals, index=range(3, 6)) ser.index = ser.index.astype("float64")
class TestFloat64Index(Numeric): result = ser.at[4.0] assert isinstance(result, type(expected)) and result == expected # Note: ser.at[4] raises ValueError; TODO: should we make this match loc? result = ser.iloc[1] assert isinstance(result, type(expected)) and result == expected
class TestFloat64Index(Numeric): result = ser.at[4.0] assert isinstance(result, type(expected)) and result == expected # GH#31329 .at[4] should cast to 4.0, matching .loc behavior result = ser.at[4] assert isinstance(result, type(expected)) and result == expected result...