buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
def main():
download_list.sort(key=lambda pkg: pkg.name)
if opts.urls:
for pkg in download_list:
remote = pkg.returnSimple('relativepath')
local = os.path.join(local_repo_path, remote)
if not (os.path.exists(local) and my.verifyPkg(local, pkg, ... | def main():
download_list.sort(key=lambda pkg: pkg.name)
if opts.urls:
for pkg in download_list:
local = os.path.join(local_repo_path, pkg.remote_path)
if not (os.path.exists(local) and my.verifyPkg(local, pkg, False)):
print urljoin(pkg.re... |
def main():
# set localpaths
for pkg in download_list:
rpmfn = pkg.remote_path
pkg.localpath = os.path.join(local_repo_path, rpmfn)
pkg.repo.copy_local = True
pkg.repo.cache = 0
localdir = os.path.dirname(pkg.localpath) | def main():
# set localpaths
for pkg in download_list:
pkg.localpath = os.path.join(local_repo_path, pkg.remote_path)
pkg.repo.copy_local = True
pkg.repo.cache = 0
localdir = os.path.dirname(pkg.localpath) |
def _recursively_freeze(value):
"""
if isinstance(value, Mapping):
return _FrozenOrderedDict(((k, _recursively_freeze(v)) for k, v in value.items()))
elif isinstance(value, list):
return tuple(_recursively_freeze(v) for v in value)
return value
class DictParameter(Parameter):
"""
... | def _recursively_freeze(value):
"""
if isinstance(value, Mapping):
return _FrozenOrderedDict(((k, _recursively_freeze(v)) for k, v in value.items()))
elif isinstance(value, list) or isinstance(value, tuple):
return tuple(_recursively_freeze(v) for v in value)
return value
class _DictPa... |
class DictParameter(Parameter):
tags, that are dynamically constructed outside Luigi), or you have a complex parameter containing logically related
values (like a database connection config).
"""
class _DictParamEncoder(JSONEncoder):
"""
JSON encoder for :py:class:`~DictParameter`, whic... | class DictParameter(Parameter):
tags, that are dynamically constructed outside Luigi), or you have a complex parameter containing logically related
values (like a database connection config).
"""
def normalize(self, value):
"""
Ensure that dictionary parameter is converted to a _FrozenOr... |
class DictParameter(Parameter):
return json.loads(s, object_pairs_hook=_FrozenOrderedDict)
def serialize(self, x):
return json.dumps(x, cls=DictParameter._DictParamEncoder)
class ListParameter(Parameter): | class DictParameter(Parameter):
return json.loads(s, object_pairs_hook=_FrozenOrderedDict)
def serialize(self, x):
return json.dumps(x, cls=_DictParamEncoder)
class ListParameter(Parameter): |
class ListParameter(Parameter):
"""
def normalize(self, x):
"""
Ensure that list parameter is converted to a tuple so it can be hashed.
:param str x: the value to parse.
:return: the normalized (hashable/immutable) value. | class ListParameter(Parameter):
"""
def normalize(self, x):
"""
Ensure that struct is recursively converted to a tuple so it can be hashed.
:param str x: the value to parse.
:return: the normalized (hashable/immutable) value. |
class ListParameter(Parameter):
:param str x: the value to parse.
:return: the parsed value.
"""
return list(json.loads(x))
def serialize(self, x):
""" | class ListParameter(Parameter):
:param str x: the value to parse.
:return: the parsed value.
"""
return list(json.loads(x, object_pairs_hook=_FrozenOrderedDict))
def serialize(self, x):
""" |
class ListParameter(Parameter):
:param x: the value to serialize.
"""
return json.dumps(x)
class TupleParameter(Parameter):
"""
Parameter whose value is a ``tuple`` or ``tuple`` of tuples.
| class ListParameter(Parameter):
:param x: the value to serialize.
"""
return json.dumps(x, cls=_DictParamEncoder)
class TupleParameter(ListParameter):
"""
Parameter whose value is a ``tuple`` or ``tuple`` of tuples.
|
class TupleParameter(Parameter):
$ luigi --module my_tasks MyTask --book_locations '((12,3),(4,15),(52,1))'
"""
def parse(self, x):
"""
Parse an individual value from the input. | class TupleParameter(Parameter):
$ luigi --module my_tasks MyTask --book_locations '((12,3),(4,15),(52,1))'
"""
def parse(self, x):
"""
Parse an individual value from the input. |
class TupleParameter(Parameter):
# Therefore, if json.loads(x) returns a ValueError, try ast.literal_eval(x).
# ast.literal_eval(t_str) == t
try:
return tuple(tuple(x) for x in json.loads(x)) # loop required to parse tuple of tuples
except ValueError:
return lite... | class TupleParameter(Parameter):
# Therefore, if json.loads(x) returns a ValueError, try ast.literal_eval(x).
# ast.literal_eval(t_str) == t
try:
# loop required to parse tuple of tuples
return tuple(tuple(x) for x in json.loads(x, object_pairs_hook=_FrozenOrderedDict))
... |
class TestParametersHashability(LuigiTestCase):
p = luigi.parameter.ListParameter()
self.assertEqual(hash(Foo(args=[1, "hello"]).args), hash(p.normalize(p.parse('[1,"hello"]'))))
def test_tuple(self):
class Foo(luigi.Task):
args = luigi.parameter.TupleParameter() | class TestParametersHashability(LuigiTestCase):
p = luigi.parameter.ListParameter()
self.assertEqual(hash(Foo(args=[1, "hello"]).args), hash(p.normalize(p.parse('[1,"hello"]'))))
def test_list_dict(self):
class Foo(luigi.Task):
args = luigi.parameter.ListParameter()
p =... |
class TestParametersHashability(LuigiTestCase):
p = luigi.parameter.TupleParameter()
self.assertEqual(hash(Foo(args=(1, "hello")).args), hash(p.parse('(1,"hello")')))
def test_task(self):
class Bar(luigi.Task):
pass | class TestParametersHashability(LuigiTestCase):
p = luigi.parameter.TupleParameter()
self.assertEqual(hash(Foo(args=(1, "hello")).args), hash(p.parse('(1,"hello")')))
def test_tuple_dict(self):
class Foo(luigi.Task):
args = luigi.parameter.TupleParameter()
p = luigi.par... |
import base64
import binascii
import hashlib
import importlib
from collections import OrderedDict
from django.conf import settings | import base64
import binascii
import hashlib
import importlib
import warnings
from collections import OrderedDict
from django.conf import settings |
def check_password(password, encoded, setter=None, preferred='default'):
preferred = get_hasher(preferred)
hasher = identify_hasher(encoded)
must_update = hasher.algorithm != preferred.algorithm
if not must_update:
must_update = preferred.must_update(encoded)
is_correct = hasher.verify(pass... | def check_password(password, encoded, setter=None, preferred='default'):
preferred = get_hasher(preferred)
hasher = identify_hasher(encoded)
hasher_changed = hasher.algorithm != preferred.algorithm
must_update = hasher_changed or preferred.must_update(encoded)
is_correct = hasher.verify(password, e... |
class BasePasswordHasher(object):
def must_update(self, encoded):
return False
class PBKDF2PasswordHasher(BasePasswordHasher):
""" | class BasePasswordHasher(object):
def must_update(self, encoded):
return False
def harden_runtime(self, password, encoded):
"""
Bridge the runtime gap between the work factor supplied in `encoded`
and the work factor suggested by this hasher.
Taking PBKDF2 as an example... |
class PBKDF2PasswordHasher(BasePasswordHasher):
algorithm, iterations, salt, hash = encoded.split('$', 3)
return int(iterations) != self.iterations
class PBKDF2SHA1PasswordHasher(PBKDF2PasswordHasher):
""" | class PBKDF2PasswordHasher(BasePasswordHasher):
algorithm, iterations, salt, hash = encoded.split('$', 3)
return int(iterations) != self.iterations
def harden_runtime(self, password, encoded):
algorithm, iterations, salt, hash = encoded.split('$', 3)
extra_iterations = self.iteratio... |
class BCryptSHA256PasswordHasher(BasePasswordHasher):
def verify(self, password, encoded):
algorithm, data = encoded.split('$', 1)
assert algorithm == self.algorithm
bcrypt = self._load_library()
# Hash the password prior to using bcrypt to prevent password
# truncation as d... | class BCryptSHA256PasswordHasher(BasePasswordHasher):
def verify(self, password, encoded):
algorithm, data = encoded.split('$', 1)
assert algorithm == self.algorithm
encoded_2 = self.encode(password, force_bytes(data))
return constant_time_compare(encoded, encoded_2)
def safe_su... |
class BCryptSHA256PasswordHasher(BasePasswordHasher):
algorithm, empty, algostr, rounds, data = encoded.split('$', 4)
return int(rounds) != self.rounds
class BCryptPasswordHasher(BCryptSHA256PasswordHasher):
""" | class BCryptSHA256PasswordHasher(BasePasswordHasher):
algorithm, empty, algostr, rounds, data = encoded.split('$', 4)
return int(rounds) != self.rounds
def harden_runtime(self, password, encoded):
_, data = encoded.split('$', 1)
salt = data[:29] # Length of the salt in bcrypt.
... |
class SHA1PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(hash)),
])
class MD5PasswordHasher(BasePasswordHasher):
""" | class SHA1PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(hash)),
])
def harden_runtime(self, password, encoded):
pass
class MD5PasswordHasher(BasePasswordHasher):
""" |
class MD5PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(hash)),
])
class UnsaltedSHA1PasswordHasher(BasePasswordHasher):
""" | class MD5PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(hash)),
])
def harden_runtime(self, password, encoded):
pass
class UnsaltedSHA1PasswordHasher(BasePasswordHasher):
""" |
class UnsaltedSHA1PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(hash)),
])
class UnsaltedMD5PasswordHasher(BasePasswordHasher):
""" | class UnsaltedSHA1PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(hash)),
])
def harden_runtime(self, password, encoded):
pass
class UnsaltedMD5PasswordHasher(BasePasswordHasher):
""" |
class UnsaltedMD5PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(encoded, show=3)),
])
class CryptPasswordHasher(BasePasswordHasher):
""" | class UnsaltedMD5PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(encoded, show=3)),
])
def harden_runtime(self, password, encoded):
pass
class CryptPasswordHasher(BasePasswordHasher):
""" |
class CryptPasswordHasher(BasePasswordHasher):
(_('salt'), salt),
(_('hash'), mask_hash(data, show=3)),
]) | class CryptPasswordHasher(BasePasswordHasher):
(_('salt'), salt),
(_('hash'), mask_hash(data, show=3)),
])
def harden_runtime(self, password, encoded):
pass |
from django.contrib.auth.hashers import (
check_password, get_hasher, identify_hasher, is_password_usable,
make_password,
)
from django.test import SimpleTestCase
from django.test.utils import override_settings
from django.utils import six
try:
import crypt | from django.contrib.auth.hashers import (
check_password, get_hasher, identify_hasher, is_password_usable,
make_password,
)
from django.test import SimpleTestCase, mock
from django.test.utils import override_settings
from django.utils import six
from django.utils.encoding import force_bytes
try:
import cry... |
class TestUtilsHashPass(SimpleTestCase):
finally:
hasher.rounds = old_rounds
def test_unusable(self):
encoded = make_password(None)
self.assertEqual(len(encoded), len(UNUSABLE_PASSWORD_PREFIX) + UNUSABLE_PASSWORD_SUFFIX_LENGTH) | class TestUtilsHashPass(SimpleTestCase):
finally:
hasher.rounds = old_rounds
@skipUnless(bcrypt, "bcrypt not installed")
def test_bcrypt_harden_runtime(self):
hasher = get_hasher('bcrypt')
self.assertEqual('bcrypt', hasher.algorithm)
with mock.patch.object(hasher, '... |
class TestUtilsHashPass(SimpleTestCase):
finally:
hasher.iterations = old_iterations
def test_pbkdf2_upgrade_new_hasher(self):
hasher = get_hasher('default')
self.assertEqual('pbkdf2_sha256', hasher.algorithm) | class TestUtilsHashPass(SimpleTestCase):
finally:
hasher.iterations = old_iterations
def test_pbkdf2_harden_runtime(self):
hasher = get_hasher('default')
self.assertEqual('pbkdf2_sha256', hasher.algorithm)
with mock.patch.object(hasher, 'iterations', 1):
enc... |
class TestUtilsHashPass(SimpleTestCase):
self.assertTrue(check_password('letmein', encoded, setter))
self.assertTrue(state['upgraded'])
def test_load_library_no_algorithm(self):
with self.assertRaises(ValueError) as e:
BasePasswordHasher()._load_library() | class TestUtilsHashPass(SimpleTestCase):
self.assertTrue(check_password('letmein', encoded, setter))
self.assertTrue(state['upgraded'])
def test_check_password_calls_harden_runtime(self):
hasher = get_hasher('default')
encoded = make_password('letmein')
with mock.pa... |
class IcnsFile:
i = HEADERSIZE
while i < filesize:
sig, blocksize = nextheader(fobj)
i = i + HEADERSIZE
blocksize = blocksize - HEADERSIZE
dct[sig] = (i, blocksize) | class IcnsFile:
i = HEADERSIZE
while i < filesize:
sig, blocksize = nextheader(fobj)
if blocksize <= 0:
raise SyntaxError('invalid block header')
i = i + HEADERSIZE
blocksize = blocksize - HEADERSIZE
dct[sig] = (i, blocksize) |
def main():
# request makes further api requests
app.run(host='0.0.0.0',
port=settings.config.api_port,
debug=True,
threaded=True,
use_reloader=False,
ssl_context=context) | def main():
# request makes further api requests
app.run(host='0.0.0.0',
port=settings.config.api_port,
debug=settings.config.debug,
use_evalex=False,
threaded=True,
use_reloader=False,
ssl_context=context) |
class PamdRule(PamdLine):
valid_control_actions = ['ignore', 'bad', 'die', 'ok', 'done', 'reset']
def __init__(self, rule_type, rule_control, rule_path, rule_args=None):
self._control = None
self._args = None
self.rule_type = rule_type | class PamdRule(PamdLine):
valid_control_actions = ['ignore', 'bad', 'die', 'ok', 'done', 'reset']
def __init__(self, rule_type, rule_control, rule_path, rule_args=None):
self.prev = None
self.next = None
self._control = None
self._args = None
self.rule_type = rule_type |
class PamdService(object):
if current_line.matches(rule_type, rule_control, rule_path):
if current_line.prev is not None:
current_line.prev.next = current_line.next
current_line.next.prev = current_line.prev
else:
se... | class PamdService(object):
if current_line.matches(rule_type, rule_control, rule_path):
if current_line.prev is not None:
current_line.prev.next = current_line.next
if current_line.next is not None:
current_line.next.prev = curr... |
session required pam_unix.so"""
auth required pam_env.so
"""
self.pamd = PamdService(self.system_auth_string)
def test_properly_parsed(self): | session required pam_unix.so"""
auth required pam_env.so
"""
self.no_header_system_auth_string = """auth required pam_env.so
auth sufficient pam_unix.so nullok try_first_pass
auth requisite pam_succeed_if.so uid
auth required pam_deny.so
"""
self.pamd = PamdSer... |
session required pam_unix.so"""
self.assertFalse(self.pamd.remove('account', 'required', 'pam_unix.so'))
test_rule = PamdRule('account', 'required', 'pam_unix.so')
self.assertNotIn(str(test_rule), str(self.pamd)) | session required pam_unix.so"""
self.assertFalse(self.pamd.remove('account', 'required', 'pam_unix.so'))
test_rule = PamdRule('account', 'required', 'pam_unix.so')
self.assertNotIn(str(test_rule), str(self.pamd))
def test_remove_first_rule(self):
no_header_service = PamdService(s... |
"""Basic WSGI Application object for REST server."""
import re
import logging
from base64 import b64decode | """Basic WSGI Application object for REST server."""
import re
import hmac
import logging
from base64 import b64decode |
class Middleware:
credentials = b64decode(request.auth[6:]).decode('utf-8')
username, password = credentials.split(':', 1)
if (username == config.webservice.admin_user and
password == config.webservice.admin_pass):
authorized = True
if not ... | class Middleware:
credentials = b64decode(request.auth[6:]).decode('utf-8')
username, password = credentials.split(':', 1)
if (username == config.webservice.admin_user and
hmac.compare_digest(
password, config.webservice.admin_pass)):
... |
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):
... |
class TestFormatSelection(unittest.TestCase):
self.assertEqual(downloaded['format_id'], '137+141')
self.assertEqual(downloaded['ext'], 'mp4')
info_dict = _make_result(list(formats_order), extractor='youtube')
ydl = YDL({'format': '(bestvideo[ext=mp4],bestvideo[ext=webm])+bestaudio'})
... | class TestFormatSelection(unittest.TestCase):
self.assertEqual(downloaded['format_id'], '137+141')
self.assertEqual(downloaded['ext'], 'mp4')
info_dict = _make_result(list(formats_order), extractor='youtube')
ydl = YDL({'format': 'bestvideo[height>=999999]+bestaudio/best'})
yie ... |
class YoutubeDL(object):
else:
filter_parts.append(string)
def _parse_format_selection(tokens, endwith=[]):
selectors = []
current_selector = None
for type, string, start, _, _ in tokens: | class YoutubeDL(object):
else:
filter_parts.append(string)
def _parse_format_selection(tokens, inside_merge=False, inside_choice=False, inside_group=False):
selectors = []
current_selector = None
for type, string, start, _, _ in tokens: |
class YoutubeDL(object):
elif type in [tokenize.NAME, tokenize.NUMBER]:
current_selector = FormatSelector(SINGLE, string, [])
elif type == tokenize.OP:
if string in endwith:
break
elif string == ')':
... | class YoutubeDL(object):
elif type in [tokenize.NAME, tokenize.NUMBER]:
current_selector = FormatSelector(SINGLE, string, [])
elif type == tokenize.OP:
if string == ')':
if not inside_group:
# ')'... |
class YoutubeDL(object):
elif string == '(':
if current_selector:
raise syntax_error('Unexpected "("', start)
current_selector = FormatSelector(GROUP, _parse_format_selection(tokens, [')']), [])
elif stri... | class YoutubeDL(object):
elif string == '(':
if current_selector:
raise syntax_error('Unexpected "("', start)
group = _parse_format_selection(tokens, inside_group=True)
current_selector = FormatSelect... |
from __future__ import division
import os
import re
import sys
import mimetypes
import threading
from time import sleep, time | from __future__ import division
import os
import re
import sys
import errno
import mimetypes
import threading
from time import sleep, time |
def filename_from_url(url, content_type):
return fn
def get_unique_filename(filename, exists=os.path.exists):
attempt = 0
while True:
suffix = '-' + str(attempt) if attempt > 0 else ''
if not exists(filename + suffix):
return filename + suffix
attempt += 1
| def filename_from_url(url, content_type):
return fn
def trim_filename(filename, max_len):
if len(filename) > max_len:
trim_by = len(filename) - max_len
name, ext = os.path.splitext(filename)
if trim_by >= len(name):
filename = filename[:-trim_by]
else:
f... |
import os
import time
import pytest
from requests.structures import CaseInsensitiveDict
from httpie.compat import urlopen | import os
import time
import pytest
import mock
from requests.structures import CaseInsensitiveDict
from httpie.compat import urlopen |
class TestDownloadUtils:
content_type='x-foo/bar'
)
def test_unique_filename(self):
def attempts(unique_on_attempt=0):
# noinspection PyUnresolvedReferences,PyUnusedLocal
def exists(filename): | class TestDownloadUtils:
content_type='x-foo/bar'
)
@pytest.mark.parametrize(
'orig_name, unique_on_attempt, expected',
[
# Simple
('foo.bar', 0, 'foo.bar'),
('foo.bar', 1, 'foo.bar-1'),
('foo.bar', 10, 'foo.bar-10'),
#... |
class TestDownloadUtils:
exists.attempt = 0
return exists
assert 'foo.bar' == get_unique_filename('foo.bar', attempts(0))
assert 'foo.bar-1' == get_unique_filename('foo.bar', attempts(1))
assert 'foo.bar-10' == get_unique_filename('foo.bar', attempts(10))
class TestDow... | class TestDownloadUtils:
exists.attempt = 0
return exists
get_filename_max_length.return_value = 10
actual = get_unique_filename(orig_name, attempts(unique_on_attempt))
assert expected == actual
class TestDownloads: |
class CentralPlannerScheduler(Scheduler):
tasks.sort(key=self._rank(), reverse=True)
for task in tasks:
in_workers = assistant or worker in task.workers
if task.status == 'RUNNING' and in_workers:
# Return a list of currently running tasks to the client,
... | class CentralPlannerScheduler(Scheduler):
tasks.sort(key=self._rank(), reverse=True)
for task in tasks:
in_workers = (assistant and task.workers) or worker in task.workers
if task.status == 'RUNNING' and in_workers:
# Return a list of currently running tasks to t... |
class CentralPlannerTest(unittest.TestCase):
self.assertEqual(list(running_tasks.keys()), ['A'])
self.assertEqual(running_tasks['A']['worker_running'], 'Y')
def test_task_fails_when_assistant_dies(self):
self.setTime(0)
self.sch.add_task(worker='X', task_id='A') | class CentralPlannerTest(unittest.TestCase):
self.assertEqual(list(running_tasks.keys()), ['A'])
self.assertEqual(running_tasks['A']['worker_running'], 'Y')
def test_assistant_get_work_external_task(self):
self.sch.add_task('X', task_id='A', runnable=False)
self.assertTrue(self.sch.... |
'usemap',
# Not standard:
'dynsrc', 'lowsrc',
])
# Not in the HTML 4 spec: | 'usemap',
# Not standard:
'dynsrc', 'lowsrc',
# HTML5 formaction
'formaction'
])
# Not in the HTML 4 spec: |
def test_sneaky_js_in_math_style(self):
b'<math><style>/* deleted */</style></math>',
lxml.html.tostring(clean_html(s)))
def test_suite():
suite = unittest.TestSuite() | def test_sneaky_js_in_math_style(self):
b'<math><style>/* deleted */</style></math>',
lxml.html.tostring(clean_html(s)))
def test_formaction_attribute_in_button_input(self):
# The formaction attribute overrides the form's action and should be
# treated as a malicious link at... |
class TestAllURLsMatching(unittest.TestCase):
def test_facebook_matching(self):
self.assertTrue(FacebookIE.suitable('https://www.facebook.com/Shiniknoh#!/photo.php?v=10153317450565268'))
def test_no_duplicates(self):
ies = gen_extractors() | class TestAllURLsMatching(unittest.TestCase):
def test_facebook_matching(self):
self.assertTrue(FacebookIE.suitable('https://www.facebook.com/Shiniknoh#!/photo.php?v=10153317450565268'))
self.assertTrue(FacebookIE.suitable('https://www.facebook.com/cindyweather?fref=ts#!/photo.php?v=101521839989457... |
from ..utils import (
class FacebookIE(InfoExtractor):
_VALID_URL = r'''(?x)
https?://(?:\w+\.)?facebook\.com/
(?:[^#?]*\#!/)?
(?:video/video\.php|photo\.php|video/embed)\?(?:.*?)
(?:v|video_id)=(?P<id>[0-9]+)
(?:.*)''' | from ..utils import (
class FacebookIE(InfoExtractor):
_VALID_URL = r'''(?x)
https?://(?:\w+\.)?facebook\.com/
(?:[^#]*?\#!/)?
(?:video/video\.php|photo\.php|video/embed)\?(?:.*?)
(?:v|video_id)=(?P<id>[0-9]+)
(?:.*)''' |
class Client(object):
xs.rawDataOutFn = self.rawDataOut
def disconnected(self, xs):
print('Disconnected.')
self.finished.callback(None)
| class Client(object):
xs.rawDataOutFn = self.rawDataOut
def disconnected(self, reason):
print('Disconnected.')
print(reason)
self.finished.callback(None)
|
class BasicAuthenticator(xmlstream.ConnectAuthenticator):
xs.version = (0, 0)
xmlstream.ConnectAuthenticator.associateWithStream(self, xs)
inits = [ (xmlstream.TLSInitiatingInitializer, False),
(IQAuthInitializer, True),
]
for initClass, required in in... | class BasicAuthenticator(xmlstream.ConnectAuthenticator):
xs.version = (0, 0)
xmlstream.ConnectAuthenticator.associateWithStream(self, xs)
xs.initializers = [
xmlstream.TLSInitiatingInitializer(xs, required=False),
IQAuthInitializer(xs),
]
# TODO: move regis... |
class SessionInitializer(xmlstream.BaseFeatureInitiatingInitializer):
def XMPPClientFactory(jid, password):
"""
Client factory for XMPP 1.0 (only).
| class SessionInitializer(xmlstream.BaseFeatureInitiatingInitializer):
def XMPPClientFactory(jid, password, configurationForTLS=None):
"""
Client factory for XMPP 1.0 (only).
|
def XMPPClientFactory(jid, password):
@param jid: Jabber ID to connect with.
@type jid: L{jid.JID}
@param password: password to authenticate with.
@type password: L{unicode}
@return: XML stream factory.
@rtype: L{xmlstream.XmlStreamFactory}
"""
a = XMPPAuthenticator(jid, password)
r... | def XMPPClientFactory(jid, password):
@param jid: Jabber ID to connect with.
@type jid: L{jid.JID}
@param password: password to authenticate with.
@type password: L{unicode}
@param configurationForTLS: An object which creates appropriately
configured TLS connections. This is passed to C{s... |
class XMPPAuthenticator(xmlstream.ConnectAuthenticator):
resource binding step, and this is stored in this instance
variable.
@type jid: L{jid.JID}
@ivar password: password to be used during SASL authentication.
@type password: L{unicode}
"""
namespace = 'jabber:client... | class XMPPAuthenticator(xmlstream.ConnectAuthenticator):
resource binding step, and this is stored in this instance
variable.
@type jid: L{jid.JID}
@ivar password: password to be used during SASL authentication.
@type password: L{unicode}
"""
namespace = 'jabber:clien... |
class XMPPAuthenticator(xmlstream.ConnectAuthenticator):
"""
xmlstream.ConnectAuthenticator.associateWithStream(self, xs)
xs.initializers = [CheckVersionInitializer(xs)]
inits = [ (xmlstream.TLSInitiatingInitializer, False),
(sasl.SASLInitiatingInitializer, True),
... | class XMPPAuthenticator(xmlstream.ConnectAuthenticator):
"""
xmlstream.ConnectAuthenticator.associateWithStream(self, xs)
xs.initializers = [
CheckVersionInitializer(xs),
xmlstream.TLSInitiatingInitializer(
xs, required=True,
... |
class BaseFeatureInitiatingInitializer(object):
@cvar feature: tuple of (uri, name) of the stream feature root element.
@type feature: tuple of (C{str}, C{str})
@ivar required: whether the stream feature is required to be advertized
by the receiving entity.
@type required: C{bool}
... | class BaseFeatureInitiatingInitializer(object):
@cvar feature: tuple of (uri, name) of the stream feature root element.
@type feature: tuple of (C{str}, C{str})
@ivar required: whether the stream feature is required to be advertized
by the receiving entity.
@type required: C{bool}
... |
class TLSInitiatingInitializer(BaseFeatureInitiatingInitializer):
set the C{wanted} attribute to False instead of removing it from the list
of initializers, so a proper exception L{TLSRequired} can be raised.
@cvar wanted: indicates if TLS negotiation is wanted.
@type wanted: C{bool}
"""
featu... | class TLSInitiatingInitializer(BaseFeatureInitiatingInitializer):
set the C{wanted} attribute to False instead of removing it from the list
of initializers, so a proper exception L{TLSRequired} can be raised.
@ivar wanted: indicates if TLS negotiation is wanted.
@type wanted: C{bool}
"""
featu... |
class TLSInitiatingInitializer(BaseFeatureInitiatingInitializer):
"""
self.xmlstream.removeObserver('/failure', self.onFailure)
ctx = ssl.CertificateOptions()
self.xmlstream.transport.startTLS(ctx)
self.xmlstream.reset()
self.xmlstream.sendHeader() | class TLSInitiatingInitializer(BaseFeatureInitiatingInitializer):
"""
self.xmlstream.removeObserver('/failure', self.onFailure)
if self._configurationForTLS:
ctx = self._configurationForTLS
else:
ctx = ssl.optionsForClientTLS(self.xmlstream.otherEntity.host)
... |
from twisted.words.protocols.jabber import client, error, jid, xmlstream
from twisted.words.protocols.jabber.sasl import SASLInitiatingInitializer
from twisted.words.xish import utility
IQ_AUTH_GET = '/iq[@type="get"]/query[@xmlns="jabber:iq:auth"]'
IQ_AUTH_SET = '/iq[@type="set"]/query[@xmlns="jabber:iq:auth"]'
NS_BI... | from twisted.words.protocols.jabber import client, error, jid, xmlstream
from twisted.words.protocols.jabber.sasl import SASLInitiatingInitializer
from twisted.words.xish import utility
try:
from twisted.internet import ssl
except ImportError:
ssl = None
skipWhenNoSSL = "SSL not available"
else:
skipWh... |
class SessionInitializerTests(InitiatingInitializerHarness, unittest.TestCase):
class XMPPAuthenticatorTests(unittest.TestCase):
"""
Test for both XMPPAuthenticator and XMPPClientFactory.
"""
def testBasic(self):
"""
Test basic operations.
| class SessionInitializerTests(InitiatingInitializerHarness, unittest.TestCase):
class BasicAuthenticatorTests(unittest.TestCase):
"""
Test for both BasicAuthenticator and basicClientFactory.
"""
def test_basic(self):
"""
Authenticator and stream are properly constructed by the factor... |
class XMPPAuthenticatorTests(unittest.TestCase):
self.assertIsInstance(bind, client.BindInitializer)
self.assertIsInstance(session, client.SessionInitializer)
self.assertFalse(tls.required)
self.assertTrue(sasl.required)
self.assertFalse(bind.required)
self.assertFalse(s... | class XMPPAuthenticatorTests(unittest.TestCase):
self.assertIsInstance(bind, client.BindInitializer)
self.assertIsInstance(session, client.SessionInitializer)
self.assertTrue(tls.required)
self.assertTrue(sasl.required)
self.assertTrue(bind.required)
self.assertFalse(ses... |
from twisted.words.test.test_xmlstream import GenericXmlStreamFactoryTestsMixin
from twisted.words.xish import domish
from twisted.words.protocols.jabber import error, ijabber, jid, xmlstream
NS_XMPP_TLS = 'urn:ietf:params:xml:ns:xmpp-tls'
| from twisted.words.test.test_xmlstream import GenericXmlStreamFactoryTestsMixin
from twisted.words.xish import domish
from twisted.words.protocols.jabber import error, ijabber, jid, xmlstream
try:
from twisted.internet import ssl
except ImportError:
ssl = None
skipWhenNoSSL = "SSL not available"
else:
... |
class TLSInitiatingInitializerTests(unittest.TestCase):
self.savedSSL = xmlstream.ssl
self.authenticator = xmlstream.Authenticator()
self.xmlstream = xmlstream.XmlStream(self.authenticator)
self.xmlstream.send = self.output.append
self.xmlstream.connectionMade() | class TLSInitiatingInitializerTests(unittest.TestCase):
self.savedSSL = xmlstream.ssl
self.authenticator = xmlstream.ConnectAuthenticator(u'example.com')
self.xmlstream = xmlstream.XmlStream(self.authenticator)
self.xmlstream.send = self.output.append
self.xmlstream.connectionM... |
class TLSInitiatingInitializerTests(unittest.TestCase):
xmlstream.ssl = self.savedSSL
def testWantedSupported(self):
"""
Test start when TLS is wanted and the SSL library available.
"""
self.xmlstream.transport = proto_helpers.StringTransport()
self.xmlstream.transp... | class TLSInitiatingInitializerTests(unittest.TestCase):
xmlstream.ssl = self.savedSSL
def test_initRequired(self):
"""
Passing required sets the instance variable.
"""
self.init = xmlstream.TLSInitiatingInitializer(self.xmlstream,
... |
class TLSInitiatingInitializerTests(unittest.TestCase):
d = self.init.start()
d.addCallback(self.assertEqual, xmlstream.Reset)
starttls = self.output[0]
self.assertEqual('starttls', starttls.name)
self.assertEqual(NS_XMPP_TLS, starttls.uri)
self.xmlstream.dataReceived("<... | class TLSInitiatingInitializerTests(unittest.TestCase):
d = self.init.start()
d.addCallback(self.assertEqual, xmlstream.Reset)
self.assertEqual(2, len(self.output))
starttls = self.output[1]
self.assertEqual('starttls', starttls.name)
self.assertEqual(NS_XMPP_TLS, startt... |
class TLSInitiatingInitializerTests(unittest.TestCase):
return d
if not xmlstream.ssl:
testWantedSupported.skip = "SSL not available"
def testWantedNotSupportedNotRequired(self):
"""
Test start when TLS is wanted and the SSL library available.
"""
xmlstream.ss... | class TLSInitiatingInitializerTests(unittest.TestCase):
return d
test_wantedSupported.skip = skipWhenNoSSL
def test_certificateVerify(self):
"""
The server certificate will be verified.
"""
def fakeStartTLS(contextFactory):
self.assertIsInstance(contextFa... |
class TLSInitiatingInitializerTests(unittest.TestCase):
self.init.wanted = False
d = self.init.start()
self.assertEqual([], self.output)
self.assertFailure(d, xmlstream.TLSRequired)
return d
def testNotWantedNotRequired(self):
"""
Test start when TLS is no... | class TLSInitiatingInitializerTests(unittest.TestCase):
self.init.wanted = False
d = self.init.start()
self.assertEqual(1, len(self.output))
self.assertFailure(d, xmlstream.TLSRequired)
return d
def test_notWantedNotRequired(self):
"""
No StartTLS is initi... |
from pandas.errors import AbstractMethodError
from pandas import DataFrame, get_option
from pandas.io.common import get_filepath_or_buffer, is_s3_url
def get_engine(engine): | from pandas.errors import AbstractMethodError
from pandas import DataFrame, get_option
from pandas.io.common import get_filepath_or_buffer, is_gcs_url, is_s3_url
def get_engine(engine): |
class FastParquetImpl(BaseImpl):
if partition_cols is not None:
kwargs["file_scheme"] = "hive"
if is_s3_url(path):
# path is s3:// so we need to open the s3file in 'wb' mode.
# TODO: Support 'ab'
path, _, _, _ = get_filepath_or_buffer(path, mode="wb")
... | class FastParquetImpl(BaseImpl):
if partition_cols is not None:
kwargs["file_scheme"] = "hive"
if is_s3_url(path) or is_gcs_url(path):
# if path is s3:// or gs:// we need to open the file in 'wb' mode.
# TODO: Support 'ab'
path, _, _, _ = get_filepath_or... |
from io import StringIO
import numpy as np
import pytest | from io import StringIO
import os
import numpy as np
import pytest |
def test_to_csv_gcs(monkeypatch):
assert_frame_equal(df1, df2)
@td.skip_if_no("gcsfs")
def test_gcs_get_filepath_or_buffer(monkeypatch):
df1 = DataFrame( | def test_to_csv_gcs(monkeypatch):
assert_frame_equal(df1, df2)
@td.skip_if_no("fastparquet")
@td.skip_if_no("gcsfs")
def test_to_parquet_gcs_new_file(monkeypatch, tmpdir):
"""Regression test for writing to a not-yet-existent GCS Parquet file."""
df1 = DataFrame(
{
"int": [1, 3],
... |
def _create_instance(self, context, instance_type,
LOG.debug(_("Going to run %s instances...") % num_instances)
if create_instance_here:
instance = self.create_db_entry_for_new_instance(
context, instance_type, image, base_options, | def _create_instance(self, context, instance_type,
LOG.debug(_("Going to run %s instances...") % num_instances)
# Validate the correct devices have been specified
for bdm in block_device_mapping:
# NOTE(vish): For now, just make sure the volumes are accessible.
snapshot... |
class InstanceInvalidState(Invalid):
"%(method)s while the instance is in this state.")
class InstanceNotRunning(Invalid):
message = _("Instance %(instance_id)s is not running.")
| class InstanceInvalidState(Invalid):
"%(method)s while the instance is in this state.")
class InvalidBDM(Invalid):
message = _("Block Device Mapping is Invalid.")
class InvalidBDMSnapshot(InvalidBDM):
message = _("Block Device Mapping is Invalid: "
"failed to get snapshot %(i... |
class LightSource:
.format(lookup.keys)) from err
# Only apply result where hillshade intensity isn't masked
if hasattr(intensity, 'mask'):
mask = intensity.mask[..., 0]
for i in range(3):
blend[..., i][mask] = rgb[..., i][mask] | class LightSource:
.format(lookup.keys)) from err
# Only apply result where hillshade intensity isn't masked
if np.ma.is_masked(intensity):
mask = intensity.mask[..., 0]
for i in range(3):
blend[..., i][mask] = rgb[..., i][mask] |
def test_light_source_shading_default():
assert_array_almost_equal(rgb, expect, decimal=2)
# Numpy 1.9.1 fixed a bug in masked arrays which resulted in
# additional elements being masked when calculating the gradient thus
# the output is different with earlier numpy versions. | def test_light_source_shading_default():
assert_array_almost_equal(rgb, expect, decimal=2)
def test_light_source_shading_empty_mask():
y, x = np.mgrid[-1.2:1.2:8j, -1.2:1.2:8j]
z0 = 10 * np.cos(x**2 + y**2)
z1 = np.ma.array(z0)
cmap = plt.cm.copper
ls = mcolors.LightSource(315, 45)
rgb0 =... |
def test_overrun(self):
except IOError as e:
self.assertEqual(str(e), "buffer overrun when reading image file")
class MockEncoder(object):
pass | def test_overrun(self):
except IOError as e:
self.assertEqual(str(e), "buffer overrun when reading image file")
with Image.open("Tests/images/fli_overrun2.bin") as im:
try:
im.seek(1)
self.assertFail()
except IOError as e:
... |
class FileBasedCache(BaseCache):
self._delete(fname)
def _createdir(self):
os.makedirs(self._dir, 0o700, exist_ok=True)
def _key_to_file(self, key, version=None):
""" | class FileBasedCache(BaseCache):
self._delete(fname)
def _createdir(self):
# Set the umask because os.makedirs() doesn't apply the "mode" argument
# to intermediate-level directories.
old_umask = os.umask(0o077)
try:
os.makedirs(self._dir, 0o700, exist_ok=Tru... |
import os
import pickle
import re
import shutil
import tempfile
import threading
import time
import unittest
from unittest import mock
from django.conf import settings
from django.core import management, signals | import os
import pickle
import re
import shutil
import sys
import tempfile
import threading
import time
import unittest
from pathlib import Path
from unittest import mock, skipIf
from django.conf import settings
from django.core import management, signals |
class FileBasedCacheTests(BaseCacheTests, TestCase):
# Returns the default instead of erroring.
self.assertEqual(cache.get('foo', 'baz'), 'baz')
def test_get_does_not_ignore_non_filenotfound_exceptions(self):
with mock.patch('builtins.open', side_effect=OSError):
with self.asser... | class FileBasedCacheTests(BaseCacheTests, TestCase):
# Returns the default instead of erroring.
self.assertEqual(cache.get('foo', 'baz'), 'baz')
@skipIf(
sys.platform == 'win32',
'Windows only partially supports umasks and chmod.',
)
def test_cache_dir_permissions(self):
... |
class Path:
if not args:
return Path(np.empty([0, 2], dtype=np.float32))
vertices = np.concatenate([x.vertices for x in args])
codes = np.empty(len(vertices), dtype=cls.code_type)
i = 0 | class Path:
if not args:
return Path(np.empty([0, 2], dtype=np.float32))
# concatenate paths
vertices = np.concatenate([x.vertices for x in args])
codes = np.empty(len(vertices), dtype=cls.code_type)
i = 0 |
class Path:
codes[i:i + len(path.codes)] = path.codes
i += len(path.vertices)
return cls(vertices, codes)
def __repr__(self): | class Path:
codes[i:i + len(path.codes)] = path.codes
i += len(path.vertices)
# remove internal STOP's, replace kinal stop if present
last_vert = None
if codes.size > 0 and codes[-1] == cls.STOP:
last_vert = vertices[-1]
vertices = vertices[codes ... |
def test_make_compound_path_empty():
assert r.vertices.shape == (0, 2)
@image_comparison(['xkcd.png'], remove_text=True)
def test_xkcd():
np.random.seed(0) | def test_make_compound_path_empty():
assert r.vertices.shape == (0, 2)
def test_make_compound_path_stops():
zero = [0, 0]
paths = 3*[Path([zero, zero], [Path.MOVETO, Path.STOP])]
compound_path = Path.make_compound_path(*paths)
assert np.sum(compound_path.codes == Path.STOP) == 1
@image_compariso... |
class StaticFileTest(WebTestCase):
self.assertEqual(response.headers.get("Content-Length"), "4")
self.assertEqual(response.headers.get("Content-Range"), "bytes 22-25/26")
def test_static_invalid_range(self):
response = self.get_and_head("/static/robots.txt", headers={"Range": "asdf"})
... | class StaticFileTest(WebTestCase):
self.assertEqual(response.headers.get("Content-Length"), "4")
self.assertEqual(response.headers.get("Content-Range"), "bytes 22-25/26")
def test_static_with_range_neg_past_start(self):
response = self.get_and_head(
"/static/robots.txt", headers... |
class StaticFileTest(WebTestCase):
self.assertEqual(response.code, 416)
self.assertEqual(response.headers.get("Content-Range"), "bytes */26")
def test_static_head(self):
response = self.fetch("/static/robots.txt", method="HEAD")
self.assertEqual(response.code, 200) | class StaticFileTest(WebTestCase):
self.assertEqual(response.code, 416)
self.assertEqual(response.headers.get("Content-Range"), "bytes */26")
def test_static_unsatisfiable_range_end_less_than_start(self):
response = self.get_and_head(
"/static/robots.txt", headers={"Range": "byt... |
class StaticFileHandler(RequestHandler):
size = self.get_content_size()
if request_range:
start, end = request_range
if (start is not None and start >= size) or end == 0:
# As per RFC 2616 14.35.1, a range is not satisfiable only: if
# the first re... | class StaticFileHandler(RequestHandler):
size = self.get_content_size()
if request_range:
start, end = request_range
if start is not None and start < 0:
start += size
if start < 0:
start = 0
if (
star... |
def aesEncrypt(data, key):
except ImportError:
from Crypto.Cipher import AES
def aesEncrypt(data, key):
cipher = AES.new(key)
data = data + (" " * (16 - (len(data) % 16)))
return cipher.encrypt(data)
def aesDecrypt(data, key):
cipher = AES.new(key)
return cipher.... | def aesEncrypt(data, key):
except ImportError:
from Crypto.Cipher import AES
from Crypto.Util import Counter
def aesEncrypt(data, key):
cipher = AES.new(key, AES.MODE_CTR,
counter=Counter.new(128, initial_value=0))
return cipher.encrypt(data)
def aesDecrypt(d... |
from django.utils.encoding import force_bytes, force_str, force_text
from django.utils.functional import allow_lazy
from django.utils.six.moves.urllib.parse import (
quote, quote_plus, unquote, unquote_plus, urlencode as original_urlencode,
urlparse,
)
ETAG_MATCH = re.compile(r'(?:W/)?"((?:\\.|[^"])*)"')
MONT... | from django.utils.encoding import force_bytes, force_str, force_text
from django.utils.functional import allow_lazy
from django.utils.six.moves.urllib.parse import (
quote, quote_plus, unquote, unquote_plus, urlencode as original_urlencode,
)
if six.PY2:
from urlparse import (
ParseResult, SplitResult,... |
def is_safe_url(url, host=None):
return _is_safe_url(url, host) and _is_safe_url(url.replace('\\', '/'), host)
def _is_safe_url(url, host):
# Chrome considers any URL with more than two slashes to be absolute, but
# urlparse is not so flexible. Treat any url with three slashes as unsafe.
if url.starts... | def is_safe_url(url, host=None):
return _is_safe_url(url, host) and _is_safe_url(url.replace('\\', '/'), host)
# Copied from urllib.parse.urlparse() but uses fixed urlsplit() function.
def _urlparse(url, scheme='', allow_fragments=True):
"""Parse a URL into 6 components:
<scheme>://<netloc>/<path>;<params... |
class TestUtilsHttp(unittest.TestCase):
r'http://testserver\me:pass@example.com',
r'http://testserver\@example.com',
r'http:\\testserver\confirm\me@example.com',
'\n'):
self.assertFalse(http.is_safe_url(bad_url, ... | class TestUtilsHttp(unittest.TestCase):
r'http://testserver\me:pass@example.com',
r'http://testserver\@example.com',
r'http:\\testserver\confirm\me@example.com',
'http:999999999',
'ftp:9999999999',
... |
class TestUtilsHttp(unittest.TestCase):
'HTTPS://testserver/',
'//testserver/',
'http://testserver/confirm?email=me@example.com',
'/url%20with%20spaces/'):
self.assertTrue(http.is_safe_url(good_url, host='testserver'), "%s s... | class TestUtilsHttp(unittest.TestCase):
'HTTPS://testserver/',
'//testserver/',
'http://testserver/confirm?email=me@example.com',
'/url%20with%20spaces/',
'path/http:2222222222'):
self.assertTrue(http.is... |
class FileSystemStorage(Storage):
if not os.path.exists(directory):
try:
if self.directory_permissions_mode is not None:
# os.makedirs applies the global umask, so we reset it,
# for consistency with file_permissions_mode behavior.
... | class FileSystemStorage(Storage):
if not os.path.exists(directory):
try:
if self.directory_permissions_mode is not None:
# Set the umask because os.makedirs() doesn't apply the "mode"
# argument to intermediate-level directories.
... |
import time
import unittest
from datetime import datetime, timedelta
from io import StringIO
from urllib.request import urlopen
from django.core.cache import cache | import time
import unittest
from datetime import datetime, timedelta
from io import StringIO
from pathlib import Path
from urllib.request import urlopen
from django.core.cache import cache |
class FileStoragePermissions(unittest.TestCase):
@override_settings(FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765)
def test_file_upload_directory_permissions(self):
self.storage = FileSystemStorage(self.storage_dir)
name = self.storage.save("the_directory/the_file", ContentFile("data"))
dir_mo... | class FileStoragePermissions(unittest.TestCase):
@override_settings(FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765)
def test_file_upload_directory_permissions(self):
self.storage = FileSystemStorage(self.storage_dir)
name = self.storage.save('the_directory/subdir/the_file', ContentFile('data'))
... |
import sys
import tempfile
import unittest
from io import StringIO
from django.conf import settings
from django.contrib.staticfiles import finders, storage | import sys
import tempfile
import unittest
from io import StringIO
from pathlib import Path
from django.conf import settings
from django.contrib.staticfiles import finders, storage |
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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.