buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class TextWarningsTest(fixtures.TestBase, AssertsCompiledSQL): ) def test_where(self): self._test( select([table1.c.myid]).where, "myid == 5", "myid == 5", "SELECT mytable.myid FROM mytable WHERE myid == 5", ) def test_column(self): ...
class TextWarningsTest(fixtures.TestBase, AssertsCompiledSQL): ) def test_where(self): self._test(select([table1.c.myid]).where, "myid == 5", "myid == 5") def test_column(self): self._test(select, ["myid"], "myid") def test_having(self): self._test(select([table1.c.myid])....
class OrderByLabelResolutionTest(fixtures.TestBase, AssertsCompiledSQL): def test_unresolvable_warning_order_by(self): stmt = select([table1.c.myid]).order_by("foobar") self._test_warning( stmt, "foobar", "SELECT mytable.myid FROM mytable ORDER BY foobar" ) def test_group_b...
class OrderByLabelResolutionTest(fixtures.TestBase, AssertsCompiledSQL): def test_unresolvable_warning_order_by(self): stmt = select([table1.c.myid]).order_by("foobar") self._test_exception(stmt, "foobar") def test_group_by_label(self): stmt = select([table1.c.myid.label("foo")]).group...
class OrderByLabelResolutionTest(fixtures.TestBase, AssertsCompiledSQL): def test_unresolvable_warning_group_by(self): stmt = select([table1.c.myid]).group_by("foobar") self._test_warning( stmt, "foobar", "SELECT mytable.myid FROM mytable GROUP BY foobar" ) def test_asc(sel...
class OrderByLabelResolutionTest(fixtures.TestBase, AssertsCompiledSQL): def test_unresolvable_warning_group_by(self): stmt = select([table1.c.myid]).group_by("foobar") self._test_exception(stmt, "foobar") def test_asc(self): stmt = select([table1.c.myid]).order_by(asc("name"), "descri...
class OrderByLabelResolutionTest(fixtures.TestBase, AssertsCompiledSQL): .order_by("myid", "t1name", "x") ) def go(): # the labels here are anonymized, so label naming # can't catch these. self.assert_compile( s1, "SELECT m...
class OrderByLabelResolutionTest(fixtures.TestBase, AssertsCompiledSQL): .order_by("myid", "t1name", "x") ) assert_raises_message( exc.CompileError, r"Can't resolve label reference for ORDER BY / GROUP BY. " "Textual SQL " "expression 't1name'...
class TestUtil(unittest.TestCase): on = js_to_json('{ 0: /* " \n */ ",]" , }') self.assertEqual(json.loads(on), {'0': ',]'}) on = js_to_json(r'["<p>x<\/p>"]') self.assertEqual(json.loads(on), ['<p>x</p>'])
class TestUtil(unittest.TestCase): on = js_to_json('{ 0: /* " \n */ ",]" , }') self.assertEqual(json.loads(on), {'0': ',]'}) on = js_to_json('{ 0: // comment\n1 }') self.assertEqual(json.loads(on), {'0': 1}) on = js_to_json(r'["<p>x<\/p>"]') self.assertEqual(json.loads(...
def js_to_json(code): v = m.group(0) if v in ('true', 'false', 'null'): return v elif v.startswith('/*') or v == ',': return "" if v[0] in ("'", '"'):
def js_to_json(code): v = m.group(0) if v in ('true', 'false', 'null'): return v elif v.startswith('/*') or v.startswith('//') or v == ',': return "" if v[0] in ("'", '"'):
def js_to_json(code): return re.sub(r'''(?sx) "(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"| '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'| /\*.*?\*/|,(?=\s*[\]}])| [a-zA-Z_][.a-zA-Z_0-9]*| \b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:\s*:)?| [0-9]+(?=\s*:)
def js_to_json(code): return re.sub(r'''(?sx) "(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"| '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'| /\*.*?\*/|//[^\n]*|,(?=\s*[\]}])| [a-zA-Z_][.a-zA-Z_0-9]*| \b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:\s*:)?| [0-9]+(?=\s*:)
class tqdm(Comparable): if not _is_ascii(full_bar.charset) and _is_ascii(bar_format): bar_format = _unicode(bar_format) res = bar_format.format(bar=full_bar, **format_dict) if ncols: return disp_trim(res, ncols) elif bar_format: # ...
class tqdm(Comparable): if not _is_ascii(full_bar.charset) and _is_ascii(bar_format): bar_format = _unicode(bar_format) res = bar_format.format(bar=full_bar, **format_dict) return disp_trim(res, ncols) if ncols else res elif bar_format: # user-spe...
class tqdm(Comparable): if ncols else 10, charset=Bar.BLANK) res = bar_format.format(bar=full_bar, **format_dict) if ncols: return disp_trim(res, ncols) else: # no total: no progressbar, ETA, just progress stats retu...
class tqdm(Comparable): if ncols else 10, charset=Bar.BLANK) res = bar_format.format(bar=full_bar, **format_dict) return disp_trim(res, ncols) if ncols else res else: # no total: no progressbar, ETA, just progress stats return ((pre...
def test_format_meter(): # l_bar gets chopped # no bar # no r_bar format_meter(0, 1000, 13, ncols=10, bar_width=10, bar_format="************{bar}$$$$$$$$$$"), "**********" # 10/12 stars since ncols is 10 ) eq_(
def test_format_meter(): # l_bar gets chopped # no bar # no r_bar format_meter(0, 1000, 13, ncols=10, bar_format="************{bar:10}$$$$$$$$$$"), "**********" # 10/12 stars since ncols is 10 ) eq_(
def test_format_meter(): # l_bar displays # bar gets chopped # no r_bar format_meter(0, 1000, 13, ncols=20, bar_width=10, bar_format="************{bar}$$$$$$$$$$"), "************ " # all 12 stars and 8/10 bar parts ) eq_(
def test_format_meter(): # l_bar displays # bar gets chopped # no r_bar format_meter(0, 1000, 13, ncols=20, bar_format="************{bar:10}$$$$$$$$$$"), "************ " # all 12 stars and 8/10 bar parts ) eq_(
def test_format_meter(): # l_bar displays # bar displays # r_bar gets chopped format_meter(0, 1000, 13, ncols=30, bar_width=10, bar_format="************{bar}$$$$$$$$$$"), "************ $$$$$$$$" # all 12 stars and 10 bar parts, but only 8/10 dollar signs ) eq_( ...
def test_format_meter(): # l_bar displays # bar displays # r_bar gets chopped format_meter(0, 1000, 13, ncols=30, bar_format="************{bar:10}$$$$$$$$$$"), "************ $$$$$$$$" # all 12 stars and 10 bar parts, but only 8/10 dollar signs ) eq_( # l...
def disp_trim(data, length): if len(data) == disp_len(data): return data[:length] while disp_len(data) > length: # carefully delete one char at a time data = data[:-1] if RE_ANSI.search(data): # assume ANSI reset is required return data + "\033[0m" return data
def disp_trim(data, length): if len(data) == disp_len(data): return data[:length] ansi_present = bool(RE_ANSI.search(data)) while disp_len(data) > length: # carefully delete one char at a time data = data[:-1] if ansi_present and bool(RE_ANSI.search(data)): # assume ANSI reset ...
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 _iter_command_classes(module_name): # TODO: add `name` attribute to commands and and merge this function with # scrapy.utils.spider.iter_spider_classes for module in walk_modules(module_name): for obj in vars(module).itervalues(): if inspect.isclass(obj) and \ issubcla...
def _iter_command_classes(module_name): # TODO: add `name` attribute to commands and and merge this function with # scrapy.utils.spider.iter_spider_classes for module in walk_modules(module_name): for obj in vars(module).values(): if inspect.isclass(obj) and \ issubcl...
class TestProcessProtocol(protocol.ProcessProtocol): def __init__(self): self.deferred = defer.Deferred() self.out = '' self.err = '' self.exitcode = None def outReceived(self, data):
class TestProcessProtocol(protocol.ProcessProtocol): def __init__(self): self.deferred = defer.Deferred() self.out = b'' self.err = b'' self.exitcode = None def outReceived(self, data):
class CmdlineTest(unittest.TestCase): self.env['SCRAPY_SETTINGS_MODULE'] = 'tests.test_cmdline.settings' def _execute(self, *new_args, **kwargs): args = (sys.executable, '-m', 'scrapy.cmdline') + new_args proc = Popen(args, stdout=PIPE, stderr=PIPE, env=self.env, **kwargs) comm = pr...
class CmdlineTest(unittest.TestCase): self.env['SCRAPY_SETTINGS_MODULE'] = 'tests.test_cmdline.settings' def _execute(self, *new_args, **kwargs): encoding = getattr(sys.stdout, 'encoding') or 'utf-8' args = (sys.executable, '-m', 'scrapy.cmdline') + new_args proc = Popen(args, stdou...
from twisted.trial import unittest from twisted.internet import defer
import sys from twisted.trial import unittest from twisted.internet import defer
class VersionTest(ProcessTest, unittest.TestCase): @defer.inlineCallbacks def test_output(self): _, out, _ = yield self.execute([]) self.assertEqual(out.strip(), "Scrapy %s" % scrapy.__version__)
class VersionTest(ProcessTest, unittest.TestCase): @defer.inlineCallbacks def test_output(self): encoding = getattr(sys.stdout, 'encoding') or 'utf-8' _, out, _ = yield self.execute([]) self.assertEqual(out.strip().decode(encoding), "Scrapy %s" % scrapy.__version__)
def verify_collections(collections, search_paths, apis, validate_certs, ignore_e for search_path in search_paths: b_search_path = to_bytes(os.path.join(search_path, namespace, name), errors='surrogate_or_strict') if os.path.isdir(b_search_path): ...
def verify_collections(collections, search_paths, apis, validate_certs, ignore_e for search_path in search_paths: b_search_path = to_bytes(os.path.join(search_path, namespace, name), errors='surrogate_or_strict') if os.path.isdir(b_search_path): ...
def test_verify_identical(monkeypatch, mock_collection, manifest_info, files_man assert mock_debug.call_args_list[-1][0][0] == success_msg @patch.object(collection.CollectionRequirement, 'verify') def test_verify_collections_not_installed(mock_verify, mock_collection, monkeypatch): namespace = 'ansibl...
def test_verify_identical(monkeypatch, mock_collection, manifest_info, files_man assert mock_debug.call_args_list[-1][0][0] == success_msg @patch.object(os.path, 'isdir', return_value=True) def test_verify_collections_no_version(mock_isdir, mock_collection, monkeypatch): namespace = 'ansible_namespace...
def test_verify_collections_not_installed_ignore_errors(mock_verify, mock_collec @patch.object(os.path, 'isdir', return_value=True) @patch.object(collection.CollectionRequirement, 'verify') def test_verify_collections_no_remote(mock_verify, mock_isdir, mock_collection): namespace = 'ansible_namespace' name = '...
def test_verify_collections_not_installed_ignore_errors(mock_verify, mock_collec @patch.object(os.path, 'isdir', return_value=True) @patch.object(collection.CollectionRequirement, 'verify') def test_verify_collections_no_remote(mock_verify, mock_isdir, mock_collection, monkeypatch): namespace = 'ansible_namespace'...
def test_verify_collections_no_remote(mock_verify, mock_isdir, mock_collection): @patch.object(os.path, 'isdir', return_value=True) @patch.object(collection.CollectionRequirement, 'verify') def test_verify_collections_no_remote_ignore_errors(mock_verify, mock_isdir, mock_collection): namespace = 'ansible_namespace...
def test_verify_collections_no_remote(mock_verify, mock_isdir, mock_collection): @patch.object(os.path, 'isdir', return_value=True) @patch.object(collection.CollectionRequirement, 'verify') def test_verify_collections_no_remote_ignore_errors(mock_verify, mock_isdir, mock_collection, monkeypatch): namespace = 'ansi...
def test_verify_collections_url(monkeypatch): assert err.value.message == msg @patch.object(os.path, 'isfile', return_value=False) @patch.object(os.path, 'isdir', return_value=True) @patch.object(collection.CollectionRequirement, 'verify') def test_verify_collections_name(mock_verify, mock_isdir, mock_isfile, moc...
def test_verify_collections_url(monkeypatch): assert err.value.message == msg @patch.object(os.path, 'isdir', return_value=True) @patch.object(collection.CollectionRequirement, 'verify') def test_verify_collections_name(mock_verify, mock_isdir, mock_collection, monkeypatch): local_collection = mock_collection...
from django.utils.text import normalize_newlines from .html_parser import HTMLParseError, HTMLParser # Configuration for urlize() function. TRAILING_PUNCTUATION_RE = re.compile( '^' # Beginning of word '(.*?)' # The URL in word '([.,:;!]+)' # Allowed non-wrapping, trailing punctuation ...
from django.utils.text import normalize_newlines from .html_parser import HTMLParseError, HTMLParser # Configuration for urlize() function. TRAILING_PUNCTUATION_CHARS = '.,:;!' WRAPPING_PUNCTUATION = [('(', ')'), ('<', '>'), ('[', ']'), ('&lt;', '&gt;'), ('"', '"'), ('\'', '\'')] # List of possible strings used for b...
unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)') word_split_re = re.compile(r'''([\s<>"']+)''') simple_url_re = re.compile(r'^https?://\[?\w', re.IGNORECASE) simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)($|/.*)$', re.IGNORECASE) simple_email_re = re.compile(r'^\S+@\S+\.\...
unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)') word_split_re = re.compile(r'''([\s<>"']+)''') simple_url_re = re.compile(r'^https?://\[?\w', re.IGNORECASE) simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)($|/.*)$', re.IGNORECASE) @keep_lazy(six.text_type, SafeText)
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): trimmed_something = False # Trim trailing punctuation. match = TRAILING_PUNCTUATION_RE.match(middle) if match: middle = match.group(1) trail = match.group(2) + trail ...
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): trimmed_something = False # Trim trailing punctuation. stripped = middle.rstrip(TRAILING_PUNCTUATION_CHARS) if middle != stripped: trail = middle[len(stripped):] + trail ...
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): trimmed_something = True return lead, middle, trail words = word_split_re.split(force_text(text)) for i, word in enumerate(words): if '.' in word or '@' in word or ':' in word:
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): trimmed_something = True return lead, middle, trail def is_email_simple(value): """Return True if value looks like an email address.""" # An @ must be in the middle of the value. if '@' not ...
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): elif simple_url_2_re.match(middle): middle, middle_unescaped, trail = unescape(middle, trail) url = smart_urlquote('http://%s' % middle_unescaped) elif ':' not in middle and simple_email_re.m...
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): elif simple_url_2_re.match(middle): middle, middle_unescaped, trail = unescape(middle, trail) url = smart_urlquote('http://%s' % middle_unescaped) elif ':' not in middle and is_email_simple(m...
class TestUtilsHtml(SimpleTestCase): @html.html_safe class HtmlClass(object): pass
class TestUtilsHtml(SimpleTestCase): @html.html_safe class HtmlClass(object): pass def test_urlize_unchanged_inputs(self): tests = ( ('a' + '@a' * 50000) + 'a', # simple_email_re catastrophic test ('a' + '.' * 1000000) + 'a', # trailing_punc...
import asyncio import enum import inspect import json
import asyncio import email.message import enum import inspect import json
) from pydantic import BaseModel from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import ModelField from starlette import routing from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException
) from pydantic import BaseModel from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import ModelField, Undefined from starlette import routing from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException
def get_request_handler( async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if b...
def get_request_handler( async def app(request: Request) -> Response: try: body: Any = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() ...
def test_post_body(path, body, expected_status, expected_response): def test_post_broken_body(): response = client.post("/items/", data={"name": "Foo", "price": 50.5}) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "ctx": { ...
def test_post_body(path, body, expected_status, expected_response): def test_post_broken_body(): response = client.post( "/items/", headers={"content-type": "application/json"}, data="{some broken json}", ) assert response.status_code == 422, response.text assert response.json(...
def test_gzip_request(compress): if compress: data = gzip.compress(data) headers["Content-Encoding"] = "gzip" response = client.post("/sum", data=data, headers=headers) assert response.json() == {"sum": n}
def test_gzip_request(compress): if compress: data = gzip.compress(data) headers["Content-Encoding"] = "gzip" headers["Content-Type"] = "application/json" response = client.post("/sum", data=data, headers=headers) assert response.json() == {"sum": n}
class HadoopJarJobRunner(luigi.contrib.hadoop.JobRunner): arglist.append('{}@{}'.format(username, host)) else: arglist = [] if not job.jar() or not os.path.exists(job.jar()): logger.error("Can't find jar: %s, full path %s", job.jar(), os.path.abspath(job.jar()...
class HadoopJarJobRunner(luigi.contrib.hadoop.JobRunner): arglist.append('{}@{}'.format(username, host)) else: arglist = [] if not job.jar(): raise HadoopJarJobError("Jar not defined") if not os.path.exists(job.jar()): logger.error(...
class Network(Layer): unprocessed_nodes = {} def add_unprocessed_node(layer, node_data): if layer not in unprocessed_nodes: unprocessed_nodes[layer] = [node_data] else: unprocessed_nodes[layer].append(node_data) def process_node(layer, no...
class Network(Layer): unprocessed_nodes = {} def add_unprocessed_node(layer, node_data): """Add node to layer list Args: layer: layer object node_data: Node data specifying layer call """ if layer not in unprocessed_nodes:...
class Network(Layer): else: raise ValueError('Improperly formatted model config.') inbound_layer = created_layers[inbound_layer_name] if len(inbound_layer._inbound_nodes) <= inbound_node_index: add_unprocessed_node(layer, node_data)...
class Network(Layer): else: raise ValueError('Improperly formatted model config.') inbound_layer = created_layers[inbound_layer_name] # Raise an error if the corresponding layer node # has not yet been created if len(inb...
class Network(Layer): # First, we create all layers and enqueue nodes to be processed for layer_data in config['layers']: process_layer(layer_data) # Then we process nodes in order of layer depth. # Nodes that cannot yet be processed (if the inbound node # does not ye...
class Network(Layer): # First, we create all layers and enqueue nodes to be processed for layer_data in config['layers']: process_layer(layer_data) # Then we process nodes in order of layer depth. # Nodes that cannot yet be processed (if the inbound node # does not y...
class Network(Layer): while unprocessed_nodes: for layer_data in config['layers']: layer = created_layers[layer_data['name']] if layer in unprocessed_nodes: for node_data in unprocessed_nodes.pop(layer): process_node(layer, ...
class Network(Layer): while unprocessed_nodes: for layer_data in config['layers']: layer = created_layers[layer_data['name']] # Process all nodes in layer, if not yet processed if layer in unprocessed_nodes: node_data_list = unproc...
def test_layer_sharing_at_heterogeneous_depth_with_concat(): np.testing.assert_allclose(output_val, output_val_2, atol=1e-6) def test_multi_output_mask(): """Fixes #7589""" class TestMultiOutputLayer(Layer):
def test_layer_sharing_at_heterogeneous_depth_with_concat(): np.testing.assert_allclose(output_val, output_val_2, atol=1e-6) def test_layer_sharing_at_heterogeneous_depth_order(): # This tests for the bug in this issue # https://github.com/keras-team/keras/issues/11159 # It occurs with layer sharing a...
class URLValidator(RegexValidator): r'\Z', re.IGNORECASE) message = _('Enter a valid URL.') schemes = ['http', 'https', 'ftp', 'ftps'] def __init__(self, schemes=None, **kwargs): super().__init__(**kwargs)
class URLValidator(RegexValidator): r'\Z', re.IGNORECASE) message = _('Enter a valid URL.') schemes = ['http', 'https', 'ftp', 'ftps'] unsafe_chars = frozenset('\t\r\n') def __init__(self, schemes=None, **kwargs): super().__init__(**kwargs)
class URLValidator(RegexValidator): def __call__(self, value): if not isinstance(value, str): raise ValidationError(self.message, code=self.code, params={'value': value}) # Check if the scheme is valid. scheme = value.split('://')[0].lower() if scheme not in self.schemes:
class URLValidator(RegexValidator): def __call__(self, value): if not isinstance(value, str): raise ValidationError(self.message, code=self.code, params={'value': value}) if self.unsafe_chars.intersection(value): raise ValidationError(self.message, code=self.code, params={'va...
TEST_DATA = [ (URLValidator(), None, ValidationError), (URLValidator(), 56, ValidationError), (URLValidator(), 'no_scheme', ValidationError), # Trailing newlines not accepted (URLValidator(), 'http://www.djangoproject.com/\n', ValidationError), (URLValidator(), 'http://[::ffff:192.9.5.5]\n', Val...
TEST_DATA = [ (URLValidator(), None, ValidationError), (URLValidator(), 56, ValidationError), (URLValidator(), 'no_scheme', ValidationError), # Newlines and tabs are not accepted. (URLValidator(), 'http://www.djangoproject.com/\n', ValidationError), (URLValidator(), 'http://[::ffff:192.9.5.5]\n'...
class DatabaseFeatures(BaseDatabaseFeatures): only_supports_unbounded_with_preceding_and_following = True supports_aggregate_filter_clause = True supported_explain_formats = {"JSON", "TEXT", "XML", "YAML"} validates_explain_options = False # A query will error on invalid options. supports_deferrabl...
class DatabaseFeatures(BaseDatabaseFeatures): only_supports_unbounded_with_preceding_and_following = True supports_aggregate_filter_clause = True supported_explain_formats = {"JSON", "TEXT", "XML", "YAML"} supports_deferrable_unique_constraints = True has_json_operators = True json_key_contains_...
from django.db.backends.utils import split_tzname_delta class DatabaseOperations(BaseDatabaseOperations): cast_char_field_without_max_length = "varchar" explain_prefix = "EXPLAIN" cast_data_types = { "AutoField": "integer", "BigAutoField": "bigint",
from django.db.backends.utils import split_tzname_delta class DatabaseOperations(BaseDatabaseOperations): cast_char_field_without_max_length = "varchar" explain_prefix = "EXPLAIN" explain_options = frozenset( [ "ANALYZE", "BUFFERS", "COSTS", "SETTINGS"...
class DatabaseOperations(BaseDatabaseOperations): return super().subtract_temporals(internal_type, lhs, rhs) def explain_query_prefix(self, format=None, **options): prefix = super().explain_query_prefix(format) extra = {} if format: extra["FORMAT"] = format if op...
class DatabaseOperations(BaseDatabaseOperations): return super().subtract_temporals(internal_type, lhs, rhs) def explain_query_prefix(self, format=None, **options): extra = {} # Normalize options. if options: options = { name.upper(): "true" if value else...
__all__ = ["Query", "RawQuery"] # SQL comments are forbidden in column aliases. FORBIDDEN_ALIAS_PATTERN = _lazy_re_compile(r"['`\"\]\[;\s]|--|/\*|\*/") def get_field_names_from_opts(opts): return set(
__all__ = ["Query", "RawQuery"] # SQL comments are forbidden in column aliases. FORBIDDEN_ALIAS_PATTERN = _lazy_re_compile(r"['`\"\]\[;\s]|--|/\*|\*/") # Inspired from # https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS EXPLAIN_OPTIONS_PATTERN = _lazy_re_compile(r"[\w\-]+") def g...
class Query(BaseExpression): def explain(self, using, format=None, **options): q = self.clone() q.explain_info = ExplainInfo(format, options) compiler = q.get_compiler(using=using) return "\n".join(compiler.explain_query())
class Query(BaseExpression): def explain(self, using, format=None, **options): q = self.clone() for option_name in options: if ( not EXPLAIN_OPTIONS_PATTERN.fullmatch(option_name) or "--" in option_name ): raise ValueError(f"In...
class ExplainTests(TestCase): @skipUnlessDBFeature("validates_explain_options") def test_unknown_options(self): with self.assertRaisesMessage(ValueError, "Unknown options: test, test2"): Tag.objects.all().explain(test=1, test2=1) def test_unknown_format(self): msg = "DOES NOT E...
class ExplainTests(TestCase): @skipUnlessDBFeature("validates_explain_options") def test_unknown_options(self): with self.assertRaisesMessage(ValueError, "Unknown options: TEST, TEST2"): Tag.objects.all().explain(**{"TEST": 1, "TEST2": 1}) def test_unknown_format(self): msg = "...
class ExplainTests(TestCase): option = "{} {}".format(name.upper(), "true" if value else "false") self.assertIn(option, captured_queries[0]["sql"]) @unittest.skipUnless(connection.vendor == "mysql", "MySQL specific") def test_mysql_text_to_traditional(self): # En...
class ExplainTests(TestCase): option = "{} {}".format(name.upper(), "true" if value else "false") self.assertIn(option, captured_queries[0]["sql"]) def test_option_sql_injection(self): qs = Tag.objects.filter(name="test") options = {"SUMMARY true) SELECT 1; -...
import traceback # Import 3rd-party libs import jinja2 import jinja2.ext # Import Salt libs import salt.utils.data
import traceback # Import 3rd-party libs import jinja2 import jinja2.ext import jinja2.sandbox # Import Salt libs import salt.utils.data
def render_jinja_tmpl(tmplstr, context, tmplpath=None): opt_jinja_env_helper(opt_jinja_env, "jinja_env") if opts.get("allow_undefined", False): jinja_env = jinja2.Environment(**env_args) else: jinja_env = jinja2.Environment(undefined=jinja2.StrictUndefined, **env_args) tojson_filte...
def render_jinja_tmpl(tmplstr, context, tmplpath=None): opt_jinja_env_helper(opt_jinja_env, "jinja_env") if opts.get("allow_undefined", False): jinja_env = jinja2.sandbox.SandboxedEnvironment(**env_args) else: jinja_env = jinja2.sandbox.SandboxedEnvironment( undefined=jinja2...
def render_jinja_tmpl(tmplstr, context, tmplpath=None): except ( jinja2.exceptions.TemplateRuntimeError, jinja2.exceptions.TemplateSyntaxError, ) as exc: trace = traceback.extract_tb(sys.exc_info()[2]) line, out = _get_jinja_error(trace, context=decoded_context)
def render_jinja_tmpl(tmplstr, context, tmplpath=None): except ( jinja2.exceptions.TemplateRuntimeError, jinja2.exceptions.TemplateSyntaxError, jinja2.exceptions.SecurityError, ) as exc: trace = traceback.extract_tb(sys.exc_info()[2]) line, out = _get_jinja_error(trace, c...
import logging import os import sys import salt.utils.files # Import Salt libs
import logging import os import sys import pytest import salt.utils.files # Import Salt libs
class RenderTestCase(TestCase): res = salt.utils.templates.render_cheetah_tmpl(tmpl, ctx) self.assertEqual(res.strip(), "OK") class MockRender(object): def __call__(self, tplstr, context, tmplpath=None):
class RenderTestCase(TestCase): res = salt.utils.templates.render_cheetah_tmpl(tmpl, ctx) self.assertEqual(res.strip(), "OK") def test_render_jinja_cve_2021_25283(self): tmpl = """{{ [].__class__ }}""" ctx = dict(self.context) ctx["var"] = "OK" with pytest.raises(sal...
from django.contrib.gis.db.models.fields import ( ExtentField, GeometryCollectionField, GeometryField, LineStringField, ) from django.db.models.aggregates import Aggregate from django.utils.functional import cached_property
from django.contrib.gis.db.models.fields import ( ExtentField, GeometryCollectionField, GeometryField, LineStringField, ) from django.db.models import Value from django.db.models.aggregates import Aggregate from django.utils.functional import cached_property
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.test import TestCase, skipUnlessDBFeature from ..utils import (
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.test import TestCase, skipUnlessDBFeature from ..utils import (
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): ...
from django import http from django.template import Context, Engine, TemplateDoesNotExist, loader from django.utils import six from django.utils.encoding import force_text from django.views.decorators.csrf import requires_csrf_token ERROR_404_TEMPLATE_NAME = '404.html'
from django import http from django.template import Context, Engine, TemplateDoesNotExist, loader from django.utils import six from django.utils.encoding import force_text from django.utils.http import urlquote from django.views.decorators.csrf import requires_csrf_token ERROR_404_TEMPLATE_NAME = '404.html'
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/') exception The message from the exception which triggered the 404 (if one was ...
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/'). It's quoted to prevent a content injection attack. exception The ...
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): if isinstance(message, six.text_type): exception_repr = message context = { 'request_path': request.path, 'exception': exception_repr, } try:
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): if isinstance(message, six.text_type): exception_repr = message context = { 'request_path': urlquote(request.path), 'exception': exception_repr, } try:
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): raise template = Engine().from_string( '<h1>Not Found</h1>' '<p>The requested URL {{ request_path }} was not found on this server.</p>') body = template.render(Context(context)) con...
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): raise template = Engine().from_string( '<h1>Not Found</h1>' '<p>The requested resource was not found on this server.</p>') body = template.render(Context(context)) content_type = 't...
from __future__ import unicode_literals import unittest from django.core.exceptions import ImproperlyConfigured
from __future__ import unicode_literals import sys import unittest from django.core.exceptions import ImproperlyConfigured
try: except ImportError: # Python < 3.5 HTTPStatus = None class HandlerTests(SimpleTestCase):
try: except ImportError: # Python < 3.5 HTTPStatus = None PY37 = sys.version_info >= (3, 7, 0) class HandlerTests(SimpleTestCase):
class HandlerRequestTests(SimpleTestCase): def test_invalid_urls(self): response = self.client.get('~%A9helloworld') self.assertContains(response, '~%A9helloworld', status_code=404) response = self.client.get('d%aao%aaw%aan%aal%aao%aaa%aad%aa/') self.assertContains(response, 'd%AAo...
class HandlerRequestTests(SimpleTestCase): def test_invalid_urls(self): response = self.client.get('~%A9helloworld') self.assertEqual(response.status_code, 404) self.assertEqual(response.context['request_path'], '/~%25A9helloworld' if PY37 else '/%7E%25A9helloworld') response = sel...
class TaskProcess(AbstractTaskProcess): self.task.trigger_event(Event.START, self.task) t0 = time.time() status = None try: new_deps = self._run_get_new_deps() if new_deps is None: status = RUNNING else: ...
class TaskProcess(AbstractTaskProcess): self.task.trigger_event(Event.START, self.task) t0 = time.time() status = None new_deps = self._run_get_new_deps() if new_deps is None: status = DONE self.task.trigger_event( ...
class TestEventCallbacks(unittest.TestCase): build([t], local_scheduler=True) self.assertEqual(saved_tasks, [t]) def test_success_handler(self): saved_tasks = [] @EmptyTask.event_handler(Event.SUCCESS) def save_task(task): print("Saving task...") sav...
class TestEventCallbacks(unittest.TestCase): build([t], local_scheduler=True) self.assertEqual(saved_tasks, [t]) def _run_empty_task(self, fail): successes = [] failures = [] exceptions = [] @EmptyTask.event_handler(Event.SUCCESS) def success(task): ...
class TestEventCallbacks(unittest.TestCase): build([t], local_scheduler=True) self.assertEqual(dummies[0], "foo") def test_processing_time_handler(self): @EmptyTask.event_handler(Event.PROCESSING_TIME) def save_task(task, processing_time): self.result = task, processing_...
class TestEventCallbacks(unittest.TestCase): build([t], local_scheduler=True) self.assertEqual(dummies[0], "foo") def _run_processing_time_handler(self, fail): result = [] @EmptyTask.event_handler(Event.PROCESSING_TIME) def save_task(task, processing_time): resu...
class RedirectMiddleware(BaseRedirectMiddleware): def process_response(self, request, response, spider): if (request.meta.get('dont_redirect', False) or response.status in getattr(spider, 'handle_httpstatus_list', [])): return response if request.method == 'HEAD':
class RedirectMiddleware(BaseRedirectMiddleware): def process_response(self, request, response, spider): if (request.meta.get('dont_redirect', False) or response.status in getattr(spider, 'handle_httpstatus_list', []) or response.status in request.meta.get('handle_httpstatus_l...
class RedirectMiddlewareTest(unittest.TestCase): r = self.mw.process_response(req, rsp, smartspider) self.assertIs(r, rsp) class MetaRefreshMiddlewareTest(unittest.TestCase):
class RedirectMiddlewareTest(unittest.TestCase): r = self.mw.process_response(req, rsp, smartspider) self.assertIs(r, rsp) def test_request_meta_handling(self): url = 'http://www.example.com/301' url2 = 'http://www.example.com/redirected' def _test_passthrough(req): ...
def act(fp): self.assertFalse(fp.closed) def test_overrun(self): for file in ["fli_overrun.bin", "sgi_overrun.bin", "pcx_overrun.bin"]: im = Image.open(os.path.join("Tests/images", file)) try: im.load()
def act(fp): self.assertFalse(fp.closed) def test_overrun(self): for file in [ "fli_overrun.bin", "sgi_overrun.bin", "pcx_overrun.bin", "pcx_overrun2.bin", ]: im = Image.open(os.path.join("Tests/images", file)) try:...
class S3CopyToTable(rdbms.CopyToTable): if not (self.table): raise Exception("table need to be specified") path = self.s3_load_path() connection = self.output().connect() if not self.does_table_exist(connection): # try creating table
class S3CopyToTable(rdbms.CopyToTable): if not (self.table): raise Exception("table need to be specified") path = self.s3_load_path connection = self.output().connect() if not self.does_table_exist(connection): # try creating table
def login(): login_user(form.user, remember=remember_me, authn_via=["password"]) after_this_request(_commit) if not _security._want_json(request): return redirect(get_post_login_redirect()) if _security._want_json(request): if current_user.is_authenticated: ...
def login(): login_user(form.user, remember=remember_me, authn_via=["password"]) after_this_request(_commit) if _security._want_json(request): return base_render_json(form, include_auth_token=True) return redirect(get_post_login_redirect()) if _security._want_json(reque...
def change_password(): if form.validate_on_submit(): after_this_request(_commit) change_user_password(current_user._get_current_object(), form.new_password.data) if not _security._want_json(request): do_flash(*get_message("PASSWORD_CHANGE")) return redirect( ...
def change_password(): if form.validate_on_submit(): after_this_request(_commit) change_user_password(current_user._get_current_object(), form.new_password.data) if _security._want_json(request): form.user = current_user return base_render_json(form, include_auth_toke...
version = re.search(r'__version__ = "(.*?)"', f.read()).group(1) tests_require = [ "Flask-Mongoengine>=0.9.5", "peewee>=3.11.2", "Flask-SQLAlchemy>=2.3", "argon2_cffi>=19.1.0",
version = re.search(r'__version__ = "(.*?)"', f.read()).group(1) tests_require = [ "Flask-Mongoengine~=0.9.5", "peewee>=3.11.2", "Flask-SQLAlchemy>=2.3", "argon2_cffi>=19.1.0",
"cryptography>=2.3.1", "isort>=4.2.2", "mock>=1.3.0", "mongoengine>=0.15.3", "mongomock>=3.14.0", "msgcheck>=2.9", "pony>=0.7.11", "phonenumberslite>=8.11.1",
"cryptography>=2.3.1", "isort>=4.2.2", "mock>=1.3.0", "mongoengine~=0.19.1", "mongomock~=3.19.0", "msgcheck>=2.9", "pony>=0.7.11", "phonenumberslite>=8.11.1",
def test_session_query(in_app_context): assert response.status_code == 200 end_nqueries = get_num_queries(app.security.datastore) assert current_nqueries is None or end_nqueries == (current_nqueries + 2)
def test_session_query(in_app_context): assert response.status_code == 200 end_nqueries = get_num_queries(app.security.datastore) assert current_nqueries is None or end_nqueries == (current_nqueries + 2) @pytest.mark.changeable() def test_no_get_auth_token(app, client): # Test that GETs don't return a...
class TestUtil(unittest.TestCase): "1":{"src":"skipped", "type": "application/vnd.apple.mpegURL"} }''') def test_js_to_json_edgecases(self): on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}") self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
class TestUtil(unittest.TestCase): "1":{"src":"skipped", "type": "application/vnd.apple.mpegURL"} }''') inp = '''{"foo":101}''' self.assertEqual(js_to_json(inp), '''{"foo":101}''') def test_js_to_json_edgecases(self): on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}") ...
def js_to_json(code): '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'| /\*.*?\*/|,(?=\s*[\]}])| [a-zA-Z_][.a-zA-Z_0-9]*| (?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:\s*:)?| [0-9]+(?=\s*:) ''', fix_kv, code)
def js_to_json(code): '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'| /\*.*?\*/|,(?=\s*[\]}])| [a-zA-Z_][.a-zA-Z_0-9]*| \b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:\s*:)?| [0-9]+(?=\s*:) ''', fix_kv, code)
class SparseDataFrame(DataFrame): this, other = self.align(other, join="outer", axis=0, level=level, copy=False) new_data = {} for col, series in this.items(): new_data[col] = func(series.values, other.values) fill_value = self._get_op_result_fill_value(other, func)
class SparseDataFrame(DataFrame): this, other = self.align(other, join="outer", axis=0, level=level, copy=False) new_data = {} for col in this.columns: new_data[col] = func(this[col], other) fill_value = self._get_op_result_fill_value(other, func)
class SparseDataFrame(DataFrame): new_data = {} for col in left.columns: new_data[col] = func(left[col], float(right[col])) return self._constructor( new_data,
class SparseDataFrame(DataFrame): new_data = {} for col in left.columns: new_data[col] = func(left[col], right[col]) return self._constructor( new_data,
class TestSparseDataFrameArithmetic: assert isinstance(res, pd.SparseDataFrame) tm.assert_frame_equal(res.to_dense(), df != 0) @pytest.mark.filterwarnings("ignore:Sparse:FutureWarning") @pytest.mark.filterwarnings("ignore:DataFrame.to_sparse:FutureWarning")
class TestSparseDataFrameArithmetic: assert isinstance(res, pd.SparseDataFrame) tm.assert_frame_equal(res.to_dense(), df != 0) def test_add_series_retains_dtype(self): # SparseDataFrame._combine_match_columns used to incorrectly cast # to float d = {0: [2j, 3j], 1: [0, 1]} ...
import logging import salt.utils.files import salt.utils.path import salt.payload from salt.ext import six
import logging import salt.utils.files import salt.utils.path import salt.utils.verify import salt.payload from salt.ext import six
def get_token(opts, tok): :returns: Token data if successful. Empty dict if failed. ''' t_path = os.path.join(opts['token_dir'], tok) if not os.path.isfile(t_path): return {} serial = salt.payload.Serial(opts)
def get_token(opts, tok): :returns: Token data if successful. Empty dict if failed. ''' t_path = os.path.join(opts['token_dir'], tok) if not salt.utils.verify.clean_path(opts['token_dir'], t_path): return {} if not os.path.isfile(t_path): return {} serial = salt.payload.Serial(op...
import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.user log = logging.getLogger(__name__)
import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.user import salt.ext.six log = logging.getLogger(__name__)
def check_max_open_files(opts): log.log(level=level, msg=msg) def clean_path(root, path, subdir=False): ''' Accepts the root the path needs to be under and verifies that the path is under said root. Pass in subdir=True if the path can result in a subdirectory of the root instead of having to resid...
def check_max_open_files(opts): log.log(level=level, msg=msg) def _realpath_darwin(path): base = '' for part in path.split(os.path.sep)[1:]: if base != '': if os.path.islink(os.path.sep.join([base, part])): base = os.readlink(os.path.sep.join([base, part])) ...
def update_config(file_name, yaml_contents): dir_path = os.path.join(__opts__['config_dir'], os.path.dirname(__opts__['default_include'])) try: yaml_out = salt.utils.yaml.safe_dump(yaml_contents, default_flow_style=False) if not os.path.exists(dir_path): ...
def update_config(file_name, yaml_contents): dir_path = os.path.join(__opts__['config_dir'], os.path.dirname(__opts__['default_include'])) try: yaml_out = salt.utils.yaml.safe_dump( yaml_contents, default_flow_style=False, ) if not os....
def find(path, saltenv='base'): return ret for root in __opts__['file_roots'][saltenv]: full = os.path.join(root, path) if os.path.isfile(full): # Add it to the dict with salt.utils.files.fopen(full, 'rb') as fp_:
def find(path, saltenv='base'): return ret for root in __opts__['file_roots'][saltenv]: full = os.path.join(root, path) if not salt.utils.verify.clean_path(root, full): continue if os.path.isfile(full): # Add it to the dict with salt.utils.files.fo...
def write(data, path, saltenv='base', index=0): if os.path.isabs(path): return ('The path passed in {0} is not relative to the environment ' '{1}').format(path, saltenv) dest = os.path.join(__opts__['file_roots'][saltenv][index], path) dest_dir = os.path.dirname(dest) if not os.p...
def write(data, path, saltenv='base', index=0): if os.path.isabs(path): return ('The path passed in {0} is not relative to the environment ' '{1}').format(path, saltenv) root = __opts__['file_roots'][saltenv][index] dest = os.path.join(root, path) if not salt.utils.verify.clean_p...
class ClearFuncsPubTestCase(TestCase): ret_evt = raw break assert not os.path.exists(self.tmpfile), 'Evil file created'
class ClearFuncsPubTestCase(TestCase): ret_evt = raw break assert not os.path.exists(self.tmpfile), 'Evil file created' class ClearFuncsConfigTest(TestCase): def setUp(self): master_opts = AdaptedConfigurationTestCaseMixin.get_config('master') self.conf_dir...
class BadTestModuleNamesTestCase(TestCase): 'integration.loader.test_ext_modules', 'integration.logging.test_jid_logging', 'integration.master.test_event_return', 'integration.minion.test_blackout', 'integration.minion.test_pillar', 'integration.mi...
class BadTestModuleNamesTestCase(TestCase): 'integration.loader.test_ext_modules', 'integration.logging.test_jid_logging', 'integration.master.test_event_return', 'integration.master.test_clear_funcs', 'integration.minion.test_blackout', 'integrati...
import stat import shutil import tempfile import socket # Import third party libs if sys.platform.startswith('win'):
import stat import shutil import tempfile import socket import ctypes # Import third party libs if sys.platform.startswith('win'):
from salt.utils.verify import ( verify_log, verify_logs_filter, verify_log_files, ) # Import 3rd-party libs
from salt.utils.verify import ( verify_log, verify_logs_filter, verify_log_files, clean_path ) # Import 3rd-party libs
class TestVerifyLog(TestCase): self.assertFalse(os.path.exists(path)) verify_log_files([path], getpass.getuser()) self.assertTrue(os.path.exists(path))
class TestVerifyLog(TestCase): self.assertFalse(os.path.exists(path)) verify_log_files([path], getpass.getuser()) self.assertTrue(os.path.exists(path)) class TestCleanPath(TestCase): ''' salt.utils.clean_path works as expected ''' def setUp(self): self.tmpdir = tempfil...