code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
194
| url
stringlengths 46
254
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def test_equality(self):
"""
L{DefaultFormattingState}s are always equal to other
L{DefaultFormattingState}s.
"""
self.assertEqual(
DefaultFormattingState(),
DefaultFormattingState())
self.assertNotEqual(
DefaultFormattingState(),
'hello') | L{DefaultFormattingState}s are always equal to other
L{DefaultFormattingState}s. | test_equality | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_textattributes.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_textattributes.py | MIT |
def test_partsAreBytes(self):
"""
All of the attributes of L{urlpath.URLPath} should be L{bytes}.
"""
self.assertIsInstance(self.path.scheme, bytes)
self.assertIsInstance(self.path.netloc, bytes)
self.assertIsInstance(self.path.path, bytes)
self.assertIsInstance(self.path.query, bytes)
self.assertIsInstance(self.path.fragment, bytes) | All of the attributes of L{urlpath.URLPath} should be L{bytes}. | test_partsAreBytes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | MIT |
def test_strReturnsStr(self):
"""
Calling C{str()} with a L{URLPath} will always return a L{str}.
"""
self.assertEqual(type(self.path.__str__()), str) | Calling C{str()} with a L{URLPath} will always return a L{str}. | test_strReturnsStr | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | MIT |
def test_mutabilityWithText(self, stringType=type(u"")):
"""
Setting attributes on L{urlpath.URLPath} should change the value
returned by L{str}.
@param stringType: a callable to parameterize this test for different
text types.
@type stringType: 1-argument callable taking L{unicode} and returning
L{str} or L{bytes}.
"""
self.path.scheme = stringType(u"https")
self.assertEqual(
str(self.path),
"https://example.com/foo/bar?yes=no&no=yes#footer")
self.path.netloc = stringType(u"another.example.invalid")
self.assertEqual(
str(self.path),
"https://another.example.invalid/foo/bar?yes=no&no=yes#footer")
self.path.path = stringType(u"/hello")
self.assertEqual(
str(self.path),
"https://another.example.invalid/hello?yes=no&no=yes#footer")
self.path.query = stringType(u"alpha=omega&opposites=same")
self.assertEqual(
str(self.path),
"https://another.example.invalid/hello?alpha=omega&opposites=same"
"#footer")
self.path.fragment = stringType(u"header")
self.assertEqual(
str(self.path),
"https://another.example.invalid/hello?alpha=omega&opposites=same"
"#header") | Setting attributes on L{urlpath.URLPath} should change the value
returned by L{str}.
@param stringType: a callable to parameterize this test for different
text types.
@type stringType: 1-argument callable taking L{unicode} and returning
L{str} or L{bytes}. | test_mutabilityWithText | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | MIT |
def test_mutabilityWithBytes(self):
"""
Same as L{test_mutabilityWithText} but for bytes.
"""
self.test_mutabilityWithText(lambda x: x.encode("ascii")) | Same as L{test_mutabilityWithText} but for bytes. | test_mutabilityWithBytes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | MIT |
def test_allAttributesAreBytes(self):
"""
A created L{URLPath} has bytes attributes.
"""
self.assertIsInstance(self.path.scheme, bytes)
self.assertIsInstance(self.path.netloc, bytes)
self.assertIsInstance(self.path.path, bytes)
self.assertIsInstance(self.path.query, bytes)
self.assertIsInstance(self.path.fragment, bytes) | A created L{URLPath} has bytes attributes. | test_allAttributesAreBytes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | MIT |
def test_stringConversion(self):
"""
Calling C{str()} with a L{URLPath} will return the same URL that it was
constructed with.
"""
self.assertEqual(str(self.path),
"http://example.com/foo/bar?yes=no&no=yes#footer") | Calling C{str()} with a L{URLPath} will return the same URL that it was
constructed with. | test_stringConversion | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | MIT |
def test_childString(self):
"""
Calling C{str()} with a C{URLPath.child()} will return a URL which is
the child of the URL it was instantiated with.
"""
self.assertEqual(str(self.path.child(b'hello')),
"http://example.com/foo/bar/hello")
self.assertEqual(str(self.path.child(b'hello').child(b'')),
"http://example.com/foo/bar/hello/")
self.assertEqual(str(self.path.child(b'hello', keepQuery=True)),
"http://example.com/foo/bar/hello?yes=no&no=yes") | Calling C{str()} with a C{URLPath.child()} will return a URL which is
the child of the URL it was instantiated with. | test_childString | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | MIT |
def test_siblingString(self):
"""
Calling C{str()} with a C{URLPath.sibling()} will return a URL which is
the sibling of the URL it was instantiated with.
"""
self.assertEqual(str(self.path.sibling(b'baz')),
'http://example.com/foo/baz')
self.assertEqual(str(self.path.sibling(b'baz', keepQuery=True)),
"http://example.com/foo/baz?yes=no&no=yes")
# The sibling of http://example.com/foo/bar/
# is http://example.comf/foo/bar/baz
# because really we are constructing a sibling of
# http://example.com/foo/bar/index.html
self.assertEqual(str(self.path.child(b'').sibling(b'baz')),
'http://example.com/foo/bar/baz') | Calling C{str()} with a C{URLPath.sibling()} will return a URL which is
the sibling of the URL it was instantiated with. | test_siblingString | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | MIT |
def test_parentString(self):
"""
Calling C{str()} with a C{URLPath.parent()} will return a URL which is
the parent of the URL it was instantiated with.
"""
# .parent() should be equivalent to '..'
# 'foo' is the current directory, '/' is the parent directory
self.assertEqual(str(self.path.parent()),
'http://example.com/')
self.assertEqual(str(self.path.parent(keepQuery=True)),
'http://example.com/?yes=no&no=yes')
self.assertEqual(str(self.path.child(b'').parent()),
'http://example.com/foo/')
self.assertEqual(str(self.path.child(b'baz').parent()),
'http://example.com/foo/')
self.assertEqual(
str(self.path.parent().parent().parent().parent().parent()),
'http://example.com/') | Calling C{str()} with a C{URLPath.parent()} will return a URL which is
the parent of the URL it was instantiated with. | test_parentString | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | MIT |
def test_hereString(self):
"""
Calling C{str()} with a C{URLPath.here()} will return a URL which is
the URL that it was instantiated with, without any file, query, or
fragment.
"""
# .here() should be equivalent to '.'
self.assertEqual(str(self.path.here()), 'http://example.com/foo/')
self.assertEqual(str(self.path.here(keepQuery=True)),
'http://example.com/foo/?yes=no&no=yes')
self.assertEqual(str(self.path.child(b'').here()),
'http://example.com/foo/bar/') | Calling C{str()} with a C{URLPath.here()} will return a URL which is
the URL that it was instantiated with, without any file, query, or
fragment. | test_hereString | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | MIT |
def test_doubleSlash(self):
"""
Calling L{urlpath.URLPath.click} on a L{urlpath.URLPath} with a
trailing slash with a relative URL containing a leading slash will
result in a URL with a single slash at the start of the path portion.
"""
self.assertEqual(
str(self.path.click(b"/hello/world")).encode("ascii"),
b"http://example.com/hello/world"
) | Calling L{urlpath.URLPath.click} on a L{urlpath.URLPath} with a
trailing slash with a relative URL containing a leading slash will
result in a URL with a single slash at the start of the path portion. | test_doubleSlash | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | MIT |
def test_pathList(self):
"""
L{urlpath.URLPath.pathList} returns a L{list} of L{bytes}.
"""
self.assertEqual(
self.path.child(b"%00%01%02").pathList(),
[b"", b"foo", b"bar", b"%00%01%02"]
)
# Just testing that the 'copy' argument exists for compatibility; it
# was originally provided for performance reasons, and its behavioral
# contract is kind of nonsense (where is the state shared? who with?)
# so it doesn't actually *do* anything any more.
self.assertEqual(
self.path.child(b"%00%01%02").pathList(copy=False),
[b"", b"foo", b"bar", b"%00%01%02"]
)
self.assertEqual(
self.path.child(b"%00%01%02").pathList(unquote=True),
[b"", b"foo", b"bar", b"\x00\x01\x02"]
) | L{urlpath.URLPath.pathList} returns a L{list} of L{bytes}. | test_pathList | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | MIT |
def test_mustBeBytes(self):
"""
L{URLPath.fromBytes} must take a L{bytes} argument.
"""
with self.assertRaises(ValueError):
urlpath.URLPath.fromBytes(None)
with self.assertRaises(ValueError):
urlpath.URLPath.fromBytes(u"someurl") | L{URLPath.fromBytes} must take a L{bytes} argument. | test_mustBeBytes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | MIT |
def test_withoutArguments(self):
"""
An instantiation with no arguments creates a usable L{URLPath} with
default arguments.
"""
url = urlpath.URLPath()
self.assertEqual(str(url), "http://localhost/") | An instantiation with no arguments creates a usable L{URLPath} with
default arguments. | test_withoutArguments | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | MIT |
def test_partialArguments(self):
"""
Leaving some optional arguments unfilled makes a L{URLPath} with those
optional arguments filled with defaults.
"""
# Not a "full" URL given to fromBytes, no /
# / is filled in
url = urlpath.URLPath.fromBytes(b"http://google.com")
self.assertEqual(url.scheme, b"http")
self.assertEqual(url.netloc, b"google.com")
self.assertEqual(url.path, b"/")
self.assertEqual(url.fragment, b"")
self.assertEqual(url.query, b"")
self.assertEqual(str(url), "http://google.com/") | Leaving some optional arguments unfilled makes a L{URLPath} with those
optional arguments filled with defaults. | test_partialArguments | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | MIT |
def test_nonASCIIBytes(self):
"""
L{URLPath.fromBytes} can interpret non-ASCII bytes as percent-encoded
"""
url = urlpath.URLPath.fromBytes(b"http://example.com/\xff\x00")
self.assertEqual(str(url), "http://example.com/%FF%00") | L{URLPath.fromBytes} can interpret non-ASCII bytes as percent-encoded | test_nonASCIIBytes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | MIT |
def test_mustBeStr(self):
"""
C{URLPath.fromString} must take a L{str} or L{unicode} argument.
"""
with self.assertRaises(ValueError):
urlpath.URLPath.fromString(None)
if _PY3:
with self.assertRaises(ValueError):
urlpath.URLPath.fromString(b"someurl") | C{URLPath.fromString} must take a L{str} or L{unicode} argument. | test_mustBeStr | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | MIT |
def test_nonASCIICharacters(self):
"""
L{URLPath.fromString} can load non-ASCII characters.
"""
url = urlpath.URLPath.fromString(u"http://example.com/\xff\x00")
self.assertEqual(str(url), "http://example.com/%C3%BF%00") | L{URLPath.fromString} can load non-ASCII characters. | test_nonASCIICharacters | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_urlpath.py | MIT |
def test_moduleName(self):
"""
Calling L{appdirs.getDataDirectory} will return a user data directory
in the system convention, with the module of the caller as the
subdirectory.
"""
res = _appdirs.getDataDirectory()
self.assertTrue(res.endswith("twisted.python.test.test_appdirs")) | Calling L{appdirs.getDataDirectory} will return a user data directory
in the system convention, with the module of the caller as the
subdirectory. | test_moduleName | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_appdirs.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_appdirs.py | MIT |
def test_manual(self):
"""
Calling L{appdirs.getDataDirectory} with a C{moduleName} argument will
make a data directory with that name instead.
"""
res = _appdirs.getDataDirectory("foo.bar.baz")
self.assertTrue(res.endswith("foo.bar.baz")) | Calling L{appdirs.getDataDirectory} with a C{moduleName} argument will
make a data directory with that name instead. | test_manual | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_appdirs.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_appdirs.py | MIT |
def findInvalidUID():
"""
By convention, UIDs less than 1000 are reserved for the system. A system
which allocated every single one of those UIDs would likely have practical
problems with allocating new ones, so let's assume that we'll be able to
find one. (If we don't, this will wrap around to negative values and
I{eventually} find something.)
@return: a user ID which does not exist on the local system. Or, on
systems without a L{pwd} module, return C{SYSTEM_UID_MAX}.
"""
guess = SYSTEM_UID_MAX
if pwd is not None:
while True:
try:
pwd.getpwuid(guess)
except KeyError:
break
else:
guess -= 1
return guess | By convention, UIDs less than 1000 are reserved for the system. A system
which allocated every single one of those UIDs would likely have practical
problems with allocating new ones, so let's assume that we'll be able to
find one. (If we don't, this will wrap around to negative values and
I{eventually} find something.)
@return: a user ID which does not exist on the local system. Or, on
systems without a L{pwd} module, return C{SYSTEM_UID_MAX}. | findInvalidUID | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | MIT |
def test_getpwuid(self):
"""
I{getpwuid} accepts a uid and returns the user record associated with
it.
"""
for i in range(2):
# Get some user which exists in the database.
username, password, uid, gid, gecos, dir, shell = self.getExistingUserInfo()
# Now try to look it up and make sure the result is correct.
entry = self.database.getpwuid(uid)
self.assertEqual(entry.pw_name, username)
self.assertEqual(entry.pw_passwd, password)
self.assertEqual(entry.pw_uid, uid)
self.assertEqual(entry.pw_gid, gid)
self.assertEqual(entry.pw_gecos, gecos)
self.assertEqual(entry.pw_dir, dir)
self.assertEqual(entry.pw_shell, shell) | I{getpwuid} accepts a uid and returns the user record associated with
it. | test_getpwuid | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | MIT |
def test_noSuchUID(self):
"""
I{getpwuid} raises L{KeyError} when passed a uid which does not exist
in the user database.
"""
self.assertRaises(KeyError, self.database.getpwuid, INVALID_UID) | I{getpwuid} raises L{KeyError} when passed a uid which does not exist
in the user database. | test_noSuchUID | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | MIT |
def test_getpwnam(self):
"""
I{getpwnam} accepts a username and returns the user record associated
with it.
"""
for i in range(2):
# Get some user which exists in the database.
username, password, uid, gid, gecos, dir, shell = self.getExistingUserInfo()
# Now try to look it up and make sure the result is correct.
entry = self.database.getpwnam(username)
self.assertEqual(entry.pw_name, username)
self.assertEqual(entry.pw_passwd, password)
self.assertEqual(entry.pw_uid, uid)
self.assertEqual(entry.pw_gid, gid)
self.assertEqual(entry.pw_gecos, gecos)
self.assertEqual(entry.pw_dir, dir)
self.assertEqual(entry.pw_shell, shell) | I{getpwnam} accepts a username and returns the user record associated
with it. | test_getpwnam | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | MIT |
def test_noSuchName(self):
"""
I{getpwnam} raises L{KeyError} when passed a username which does not
exist in the user database.
"""
self.assertRaises(
KeyError, self.database.getpwnam,
'no' 'such' 'user' 'exists' 'the' 'name' 'is' 'too' 'long' 'and' 'has'
'\1' 'in' 'it' 'too') | I{getpwnam} raises L{KeyError} when passed a username which does not
exist in the user database. | test_noSuchName | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | MIT |
def test_recordLength(self):
"""
The user record returned by I{getpwuid}, I{getpwnam}, and I{getpwall}
has a length.
"""
db = self.database
username, password, uid, gid, gecos, dir, shell = self.getExistingUserInfo()
for entry in [db.getpwuid(uid), db.getpwnam(username), db.getpwall()[0]]:
self.assertIsInstance(len(entry), int)
self.assertEqual(len(entry), 7) | The user record returned by I{getpwuid}, I{getpwnam}, and I{getpwall}
has a length. | test_recordLength | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | MIT |
def test_recordIndexable(self):
"""
The user record returned by I{getpwuid}, I{getpwnam}, and I{getpwall}
is indexable, with successive indexes starting from 0 corresponding to
the values of the C{pw_name}, C{pw_passwd}, C{pw_uid}, C{pw_gid},
C{pw_gecos}, C{pw_dir}, and C{pw_shell} attributes, respectively.
"""
db = self.database
username, password, uid, gid, gecos, dir, shell = self.getExistingUserInfo()
for entry in [db.getpwuid(uid), db.getpwnam(username), db.getpwall()[0]]:
self.assertEqual(entry[0], username)
self.assertEqual(entry[1], password)
self.assertEqual(entry[2], uid)
self.assertEqual(entry[3], gid)
self.assertEqual(entry[4], gecos)
self.assertEqual(entry[5], dir)
self.assertEqual(entry[6], shell)
self.assertEqual(len(entry), len(list(entry)))
self.assertRaises(IndexError, getitem, entry, 7) | The user record returned by I{getpwuid}, I{getpwnam}, and I{getpwall}
is indexable, with successive indexes starting from 0 corresponding to
the values of the C{pw_name}, C{pw_passwd}, C{pw_uid}, C{pw_gid},
C{pw_gecos}, C{pw_dir}, and C{pw_shell} attributes, respectively. | test_recordIndexable | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | MIT |
def setUp(self):
"""
Create a L{UserDatabase} with no user data in it.
"""
self.database = UserDatabase()
self._counter = SYSTEM_UID_MAX + 1 | Create a L{UserDatabase} with no user data in it. | setUp | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | MIT |
def getExistingUserInfo(self):
"""
Add a new user to C{self.database} and return its information.
"""
self._counter += 1
suffix = '_' + str(self._counter)
username = 'username' + suffix
password = 'password' + suffix
uid = self._counter
gid = self._counter + 1000
gecos = 'gecos' + suffix
dir = 'dir' + suffix
shell = 'shell' + suffix
self.database.addUser(username, password, uid, gid, gecos, dir, shell)
return (username, password, uid, gid, gecos, dir, shell) | Add a new user to C{self.database} and return its information. | getExistingUserInfo | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | MIT |
def test_addUser(self):
"""
L{UserDatabase.addUser} accepts seven arguments, one for each field of
a L{pwd.struct_passwd}, and makes the new record available via
L{UserDatabase.getpwuid}, L{UserDatabase.getpwnam}, and
L{UserDatabase.getpwall}.
"""
username = 'alice'
password = 'secr3t'
uid = 123
gid = 456
gecos = 'Alice,,,'
home = '/users/alice'
shell = '/usr/bin/foosh'
db = self.database
db.addUser(username, password, uid, gid, gecos, home, shell)
for [entry] in [[db.getpwuid(uid)], [db.getpwnam(username)],
db.getpwall()]:
self.assertEqual(entry.pw_name, username)
self.assertEqual(entry.pw_passwd, password)
self.assertEqual(entry.pw_uid, uid)
self.assertEqual(entry.pw_gid, gid)
self.assertEqual(entry.pw_gecos, gecos)
self.assertEqual(entry.pw_dir, home)
self.assertEqual(entry.pw_shell, shell) | L{UserDatabase.addUser} accepts seven arguments, one for each field of
a L{pwd.struct_passwd}, and makes the new record available via
L{UserDatabase.getpwuid}, L{UserDatabase.getpwnam}, and
L{UserDatabase.getpwall}. | test_addUser | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | MIT |
def getExistingUserInfo(self):
"""
Read and return the next record from C{self._users}, filtering out
any records with previously seen uid values (as these cannot be
found with C{getpwuid} and only cause trouble).
"""
while True:
entry = next(self._users)
uid = entry.pw_uid
if uid not in self._uids:
self._uids.add(uid)
return entry | Read and return the next record from C{self._users}, filtering out
any records with previously seen uid values (as these cannot be
found with C{getpwuid} and only cause trouble). | getExistingUserInfo | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | MIT |
def test_getspnam(self):
"""
L{getspnam} accepts a username and returns the user record associated
with it.
"""
for i in range(2):
# Get some user which exists in the database.
(username, password, lastChange, min, max, warn, inact, expire,
flag) = self.getExistingUserInfo()
entry = self.database.getspnam(username)
self.assertEqual(entry.sp_nam, username)
self.assertEqual(entry.sp_pwd, password)
self.assertEqual(entry.sp_lstchg, lastChange)
self.assertEqual(entry.sp_min, min)
self.assertEqual(entry.sp_max, max)
self.assertEqual(entry.sp_warn, warn)
self.assertEqual(entry.sp_inact, inact)
self.assertEqual(entry.sp_expire, expire)
self.assertEqual(entry.sp_flag, flag) | L{getspnam} accepts a username and returns the user record associated
with it. | test_getspnam | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | MIT |
def test_noSuchName(self):
"""
I{getspnam} raises L{KeyError} when passed a username which does not
exist in the user database.
"""
self.assertRaises(KeyError, self.database.getspnam, "alice") | I{getspnam} raises L{KeyError} when passed a username which does not
exist in the user database. | test_noSuchName | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | MIT |
def test_recordLength(self):
"""
The shadow user record returned by I{getspnam} and I{getspall} has a
length.
"""
db = self.database
username = self.getExistingUserInfo()[0]
for entry in [db.getspnam(username), db.getspall()[0]]:
self.assertIsInstance(len(entry), int)
self.assertEqual(len(entry), 9) | The shadow user record returned by I{getspnam} and I{getspall} has a
length. | test_recordLength | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | MIT |
def test_recordIndexable(self):
"""
The shadow user record returned by I{getpwnam} and I{getspall} is
indexable, with successive indexes starting from 0 corresponding to the
values of the C{sp_nam}, C{sp_pwd}, C{sp_lstchg}, C{sp_min}, C{sp_max},
C{sp_warn}, C{sp_inact}, C{sp_expire}, and C{sp_flag} attributes,
respectively.
"""
db = self.database
(username, password, lastChange, min, max, warn, inact, expire,
flag) = self.getExistingUserInfo()
for entry in [db.getspnam(username), db.getspall()[0]]:
self.assertEqual(entry[0], username)
self.assertEqual(entry[1], password)
self.assertEqual(entry[2], lastChange)
self.assertEqual(entry[3], min)
self.assertEqual(entry[4], max)
self.assertEqual(entry[5], warn)
self.assertEqual(entry[6], inact)
self.assertEqual(entry[7], expire)
self.assertEqual(entry[8], flag)
self.assertEqual(len(entry), len(list(entry)))
self.assertRaises(IndexError, getitem, entry, 9) | The shadow user record returned by I{getpwnam} and I{getspall} is
indexable, with successive indexes starting from 0 corresponding to the
values of the C{sp_nam}, C{sp_pwd}, C{sp_lstchg}, C{sp_min}, C{sp_max},
C{sp_warn}, C{sp_inact}, C{sp_expire}, and C{sp_flag} attributes,
respectively. | test_recordIndexable | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | MIT |
def setUp(self):
"""
Create a L{ShadowDatabase} with no user data in it.
"""
self.database = ShadowDatabase()
self._counter = 0 | Create a L{ShadowDatabase} with no user data in it. | setUp | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | MIT |
def getExistingUserInfo(self):
"""
Add a new user to C{self.database} and return its information.
"""
self._counter += 1
suffix = '_' + str(self._counter)
username = 'username' + suffix
password = 'password' + suffix
lastChange = self._counter + 1
min = self._counter + 2
max = self._counter + 3
warn = self._counter + 4
inact = self._counter + 5
expire = self._counter + 6
flag = self._counter + 7
self.database.addUser(username, password, lastChange, min, max, warn,
inact, expire, flag)
return (username, password, lastChange, min, max, warn, inact,
expire, flag) | Add a new user to C{self.database} and return its information. | getExistingUserInfo | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | MIT |
def test_addUser(self):
"""
L{UserDatabase.addUser} accepts seven arguments, one for each field of
a L{pwd.struct_passwd}, and makes the new record available via
L{UserDatabase.getpwuid}, L{UserDatabase.getpwnam}, and
L{UserDatabase.getpwall}.
"""
username = 'alice'
password = 'secr3t'
lastChange = 17
min = 42
max = 105
warn = 12
inact = 3
expire = 400
flag = 3
db = self.database
db.addUser(username, password, lastChange, min, max, warn, inact,
expire, flag)
for [entry] in [[db.getspnam(username)], db.getspall()]:
self.assertEqual(entry.sp_nam, username)
self.assertEqual(entry.sp_pwd, password)
self.assertEqual(entry.sp_lstchg, lastChange)
self.assertEqual(entry.sp_min, min)
self.assertEqual(entry.sp_max, max)
self.assertEqual(entry.sp_warn, warn)
self.assertEqual(entry.sp_inact, inact)
self.assertEqual(entry.sp_expire, expire)
self.assertEqual(entry.sp_flag, flag) | L{UserDatabase.addUser} accepts seven arguments, one for each field of
a L{pwd.struct_passwd}, and makes the new record available via
L{UserDatabase.getpwuid}, L{UserDatabase.getpwnam}, and
L{UserDatabase.getpwall}. | test_addUser | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | MIT |
def getExistingUserInfo(self):
"""
Read and return the next record from C{self._users}.
"""
return next(self._users) | Read and return the next record from C{self._users}. | getExistingUserInfo | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_fakepwd.py | MIT |
def test_versionComparison(self):
"""
Versions can be compared for equality and order.
"""
va = Version("dummy", 1, 0, 0)
vb = Version("dummy", 0, 1, 0)
self.assertTrue(va > vb)
self.assertTrue(vb < va)
self.assertTrue(va >= vb)
self.assertTrue(vb <= va)
self.assertTrue(va != vb)
self.assertTrue(vb == Version("dummy", 0, 1, 0))
self.assertTrue(vb == vb) | Versions can be compared for equality and order. | test_versionComparison | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | MIT |
def test_versionComparisonCaseInsensitive(self):
"""
Version packages are compared case insensitively.
"""
va = Version("twisted", 1, 0, 0)
vb = Version("Twisted", 0, 1, 0)
self.assertTrue(va > vb)
self.assertTrue(vb < va)
self.assertTrue(va >= vb)
self.assertTrue(vb <= va)
self.assertTrue(va != vb)
self.assertTrue(vb == Version("twisted", 0, 1, 0))
self.assertTrue(vb == Version("TWISted", 0, 1, 0))
self.assertTrue(vb == vb) | Version packages are compared case insensitively. | test_versionComparisonCaseInsensitive | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | MIT |
def test_comparingPrereleasesWithReleases(self):
"""
Prereleases are always less than versions without prereleases.
"""
va = Version("whatever", 1, 0, 0, prerelease=1)
vb = Version("whatever", 1, 0, 0)
self.assertTrue(va < vb)
self.assertFalse(va > vb)
self.assertNotEqual(vb, va) | Prereleases are always less than versions without prereleases. | test_comparingPrereleasesWithReleases | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | MIT |
def test_comparingPrereleases(self):
"""
The value specified as the prerelease is used in version comparisons.
"""
va = Version("whatever", 1, 0, 0, prerelease=1)
vb = Version("whatever", 1, 0, 0, prerelease=2)
self.assertTrue(va < vb)
self.assertTrue(vb > va)
self.assertTrue(va <= vb)
self.assertTrue(vb >= va)
self.assertTrue(va != vb)
self.assertTrue(vb == Version("whatever", 1, 0, 0, prerelease=2))
self.assertTrue(va == va) | The value specified as the prerelease is used in version comparisons. | test_comparingPrereleases | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | MIT |
def test_infComparison(self):
"""
L{_inf} is equal to L{_inf}.
This is a regression test.
"""
self.assertEqual(_inf, _inf) | L{_inf} is equal to L{_inf}.
This is a regression test. | test_infComparison | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | MIT |
def test_disallowBuggyComparisons(self):
"""
The package names of the Version objects need to be the same,
"""
self.assertRaises(IncomparableVersions,
operator.eq,
Version("dummy", 1, 0, 0),
Version("dumym", 1, 0, 0)) | The package names of the Version objects need to be the same, | test_disallowBuggyComparisons | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | MIT |
def test_notImplementedComparisons(self):
"""
Comparing a L{Version} to some other object type results in
C{NotImplemented}.
"""
va = Version("dummy", 1, 0, 0)
vb = ("dummy", 1, 0, 0) # a tuple is not a Version object
self.assertEqual(va.__cmp__(vb), NotImplemented) | Comparing a L{Version} to some other object type results in
C{NotImplemented}. | test_notImplementedComparisons | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | MIT |
def test_repr(self):
"""
Calling C{repr} on a version returns a human-readable string
representation of the version.
"""
self.assertEqual(repr(Version("dummy", 1, 2, 3)),
"Version('dummy', 1, 2, 3)") | Calling C{repr} on a version returns a human-readable string
representation of the version. | test_repr | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | MIT |
def test_reprWithPrerelease(self):
"""
Calling C{repr} on a version with a prerelease returns a human-readable
string representation of the version including the prerelease.
"""
self.assertEqual(repr(Version("dummy", 1, 2, 3, prerelease=4)),
"Version('dummy', 1, 2, 3, release_candidate=4)") | Calling C{repr} on a version with a prerelease returns a human-readable
string representation of the version including the prerelease. | test_reprWithPrerelease | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | MIT |
def test_str(self):
"""
Calling C{str} on a version returns a human-readable string
representation of the version.
"""
self.assertEqual(str(Version("dummy", 1, 2, 3)),
"[dummy, version 1.2.3]") | Calling C{str} on a version returns a human-readable string
representation of the version. | test_str | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | MIT |
def test_strWithPrerelease(self):
"""
Calling C{str} on a version with a prerelease includes the prerelease.
"""
self.assertEqual(str(Version("dummy", 1, 0, 0, prerelease=1)),
"[dummy, version 1.0.0rc1]") | Calling C{str} on a version with a prerelease includes the prerelease. | test_strWithPrerelease | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | MIT |
def test_getVersionString(self):
"""
L{getVersionString} returns a string with the package name and the
short version number.
"""
self.assertEqual(
'Twisted 8.0.0', getVersionString(Version('Twisted', 8, 0, 0))) | L{getVersionString} returns a string with the package name and the
short version number. | test_getVersionString | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | MIT |
def test_getVersionStringWithPrerelease(self):
"""
L{getVersionString} includes the prerelease, if any.
"""
self.assertEqual(
getVersionString(Version("whatever", 8, 0, 0, prerelease=1)),
"whatever 8.0.0rc1") | L{getVersionString} includes the prerelease, if any. | test_getVersionStringWithPrerelease | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | MIT |
def test_base(self):
"""
The L{base} method returns a very simple representation of the version.
"""
self.assertEqual(Version("foo", 1, 0, 0).base(), "1.0.0") | The L{base} method returns a very simple representation of the version. | test_base | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | MIT |
def test_baseWithPrerelease(self):
"""
The base version includes 'preX' for versions with prereleases.
"""
self.assertEqual(Version("foo", 1, 0, 0, prerelease=8).base(),
"1.0.0rc8") | The base version includes 'preX' for versions with prereleases. | test_baseWithPrerelease | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_versions.py | MIT |
def getFileEntry(self, contents):
"""
Return an appropriate zip file entry
"""
filename = self.mktemp()
with zipfile.ZipFile(filename, 'w', self.compression) as z:
z.writestr('content', contents)
z = zipstream.ChunkingZipFile(filename, 'r')
return z.readfile('content') | Return an appropriate zip file entry | getFileEntry | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | MIT |
def test_isatty(self):
"""
zip files should not be ttys, so isatty() should be false
"""
with self.getFileEntry('') as fileEntry:
self.assertFalse(fileEntry.isatty()) | zip files should not be ttys, so isatty() should be false | test_isatty | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | MIT |
def test_closed(self):
"""
The C{closed} attribute should reflect whether C{close()} has been
called.
"""
with self.getFileEntry('') as fileEntry:
self.assertFalse(fileEntry.closed)
self.assertTrue(fileEntry.closed) | The C{closed} attribute should reflect whether C{close()} has been
called. | test_closed | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | MIT |
def test_readline(self):
"""
C{readline()} should mirror L{file.readline} and return up to a single
delimiter.
"""
with self.getFileEntry(b'hoho\nho') as fileEntry:
self.assertEqual(fileEntry.readline(), b'hoho\n')
self.assertEqual(fileEntry.readline(), b'ho')
self.assertEqual(fileEntry.readline(), b'') | C{readline()} should mirror L{file.readline} and return up to a single
delimiter. | test_readline | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | MIT |
def test_next(self):
"""
Zip file entries should implement the iterator protocol as files do.
"""
with self.getFileEntry(b'ho\nhoho') as fileEntry:
self.assertEqual(fileEntry.next(), b'ho\n')
self.assertEqual(fileEntry.next(), b'hoho')
self.assertRaises(StopIteration, fileEntry.next) | Zip file entries should implement the iterator protocol as files do. | test_next | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | MIT |
def test_readlines(self):
"""
C{readlines()} should return a list of all the lines.
"""
with self.getFileEntry(b'ho\nho\nho') as fileEntry:
self.assertEqual(fileEntry.readlines(), [b'ho\n', b'ho\n', b'ho']) | C{readlines()} should return a list of all the lines. | test_readlines | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | MIT |
def test_iteration(self):
"""
C{__iter__()} and C{xreadlines()} should return C{self}.
"""
with self.getFileEntry('') as fileEntry:
self.assertIs(iter(fileEntry), fileEntry)
self.assertIs(fileEntry.xreadlines(), fileEntry) | C{__iter__()} and C{xreadlines()} should return C{self}. | test_iteration | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | MIT |
def test_readWhole(self):
"""
C{.read()} should read the entire file.
"""
contents = b"Hello, world!"
with self.getFileEntry(contents) as entry:
self.assertEqual(entry.read(), contents) | C{.read()} should read the entire file. | test_readWhole | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | MIT |
def test_readPartial(self):
"""
C{.read(num)} should read num bytes from the file.
"""
contents = "0123456789"
with self.getFileEntry(contents) as entry:
one = entry.read(4)
two = entry.read(200)
self.assertEqual(one, b"0123")
self.assertEqual(two, b"456789") | C{.read(num)} should read num bytes from the file. | test_readPartial | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | MIT |
def test_tell(self):
"""
C{.tell()} should return the number of bytes that have been read so
far.
"""
contents = "x" * 100
with self.getFileEntry(contents) as entry:
entry.read(2)
self.assertEqual(entry.tell(), 2)
entry.read(4)
self.assertEqual(entry.tell(), 6) | C{.tell()} should return the number of bytes that have been read so
far. | test_tell | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | MIT |
def setUp(self):
"""
Creates junk data that can be compressed and a test directory for any
files that will be created
"""
self.testdir = filepath.FilePath(self.mktemp())
self.testdir.makedirs()
self.unzipdir = self.testdir.child('unzipped')
self.unzipdir.makedirs() | Creates junk data that can be compressed and a test directory for any
files that will be created | setUp | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | MIT |
def makeZipFile(self, contents, directory=''):
"""
Makes a zip file archive containing len(contents) files. Contents
should be a list of strings, each string being the content of one file.
"""
zpfilename = self.testdir.child('zipfile.zip').path
with zipfile.ZipFile(zpfilename, 'w') as zpfile:
for i, content in enumerate(contents):
filename = str(i)
if directory:
filename = directory + "/" + filename
zpfile.writestr(filename, content)
return zpfilename | Makes a zip file archive containing len(contents) files. Contents
should be a list of strings, each string being the content of one file. | makeZipFile | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | MIT |
def test_invalidMode(self):
"""
A ChunkingZipFile opened in write-mode should not allow .readfile(),
and raise a RuntimeError instead.
"""
with zipstream.ChunkingZipFile(self.mktemp(), "w") as czf:
self.assertRaises(RuntimeError, czf.readfile, "something") | A ChunkingZipFile opened in write-mode should not allow .readfile(),
and raise a RuntimeError instead. | test_invalidMode | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | MIT |
def test_closedArchive(self):
"""
A closed ChunkingZipFile should raise a L{RuntimeError} when
.readfile() is invoked.
"""
czf = zipstream.ChunkingZipFile(self.makeZipFile(["something"]), "r")
czf.close()
self.assertRaises(RuntimeError, czf.readfile, "something") | A closed ChunkingZipFile should raise a L{RuntimeError} when
.readfile() is invoked. | test_closedArchive | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | MIT |
def test_invalidHeader(self):
"""
A zipfile entry with the wrong magic number should raise BadZipfile for
readfile(), but that should not affect other files in the archive.
"""
fn = self.makeZipFile(["test contents",
"more contents"])
with zipfile.ZipFile(fn, "r") as zf:
zeroOffset = zf.getinfo("0").header_offset
# Zero out just the one header.
with open(fn, "r+b") as scribble:
scribble.seek(zeroOffset, 0)
scribble.write(b'0' * 4)
with zipstream.ChunkingZipFile(fn) as czf:
self.assertRaises(zipfile.BadZipfile, czf.readfile, "0")
with czf.readfile("1") as zfe:
self.assertEqual(zfe.read(), b"more contents") | A zipfile entry with the wrong magic number should raise BadZipfile for
readfile(), but that should not affect other files in the archive. | test_invalidHeader | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | MIT |
def test_filenameMismatch(self):
"""
A zipfile entry with a different filename than is found in the central
directory should raise BadZipfile.
"""
fn = self.makeZipFile([b"test contents",
b"more contents"])
with zipfile.ZipFile(fn, "r") as zf:
info = zf.getinfo("0")
info.filename = "not zero"
with open(fn, "r+b") as scribble:
scribble.seek(info.header_offset, 0)
scribble.write(info.FileHeader())
with zipstream.ChunkingZipFile(fn) as czf:
self.assertRaises(zipfile.BadZipfile, czf.readfile, "0")
with czf.readfile("1") as zfe:
self.assertEqual(zfe.read(), b"more contents") | A zipfile entry with a different filename than is found in the central
directory should raise BadZipfile. | test_filenameMismatch | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | MIT |
def test_unsupportedCompression(self):
"""
A zipfile which describes an unsupported compression mechanism should
raise BadZipfile.
"""
fn = self.mktemp()
with zipfile.ZipFile(fn, "w") as zf:
zi = zipfile.ZipInfo("0")
zf.writestr(zi, "some data")
# Mangle its compression type in the central directory; can't do
# this before the writestr call or zipfile will (correctly) tell us
# not to pass bad compression types :)
zi.compress_type = 1234
with zipstream.ChunkingZipFile(fn) as czf:
self.assertRaises(zipfile.BadZipfile, czf.readfile, "0") | A zipfile which describes an unsupported compression mechanism should
raise BadZipfile. | test_unsupportedCompression | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | MIT |
def test_extraData(self):
"""
readfile() should skip over 'extra' data present in the zip metadata.
"""
fn = self.mktemp()
with zipfile.ZipFile(fn, 'w') as zf:
zi = zipfile.ZipInfo("0")
extra_data = b"hello, extra"
zi.extra = (
struct.pack('<hh', 42, len(extra_data))
+ extra_data
)
zf.writestr(zi, b"the real data")
with zipstream.ChunkingZipFile(fn) as czf, czf.readfile("0") as zfe:
self.assertEqual(zfe.read(), b"the real data") | readfile() should skip over 'extra' data present in the zip metadata. | test_extraData | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | MIT |
def test_unzipIterChunky(self):
"""
L{twisted.python.zipstream.unzipIterChunky} returns an iterator which
must be exhausted to completely unzip the input archive.
"""
numfiles = 10
contents = ['This is test file %d!' % i for i in range(numfiles)]
contents = [i.encode("ascii") for i in contents]
zpfilename = self.makeZipFile(contents)
list(zipstream.unzipIterChunky(zpfilename, self.unzipdir.path))
self.assertEqual(
set(self.unzipdir.listdir()),
set(map(str, range(numfiles))))
for child in self.unzipdir.children():
num = int(child.basename())
self.assertEqual(child.getContent(), contents[num]) | L{twisted.python.zipstream.unzipIterChunky} returns an iterator which
must be exhausted to completely unzip the input archive. | test_unzipIterChunky | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | MIT |
def test_unzipIterChunkyDirectory(self):
"""
The path to which a file is extracted by L{zipstream.unzipIterChunky}
is determined by joining the C{directory} argument to C{unzip} with the
path within the archive of the file being extracted.
"""
numfiles = 10
contents = ['This is test file %d!' % i for i in range(numfiles)]
contents = [i.encode("ascii") for i in contents]
zpfilename = self.makeZipFile(contents, 'foo')
list(zipstream.unzipIterChunky(zpfilename, self.unzipdir.path))
fileContents = {str(num).encode("ascii") for num in range(numfiles)}
self.assertEqual(
set(self.unzipdir.child(b'foo').listdir()),
fileContents)
for child in self.unzipdir.child(b'foo').children():
num = int(child.basename())
self.assertEqual(child.getContent(), contents[num]) | The path to which a file is extracted by L{zipstream.unzipIterChunky}
is determined by joining the C{directory} argument to C{unzip} with the
path within the archive of the file being extracted. | test_unzipIterChunkyDirectory | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | MIT |
def _unzipIterChunkyTest(self, compression, chunksize, lower, upper):
"""
unzipIterChunky should unzip the given number of bytes per iteration.
"""
junk = b''
for n in range(1000):
num = round(random.random(), 12)
numEncoded = str(num).encode("ascii")
junk += b' '+numEncoded
junkmd5 = md5(junk).hexdigest()
tempdir = filepath.FilePath(self.mktemp())
tempdir.makedirs()
zfpath = tempdir.child('bigfile.zip').path
self._makebigfile(zfpath, compression, junk)
uziter = zipstream.unzipIterChunky(zfpath, tempdir.path,
chunksize=chunksize)
r = next(uziter)
# test that the number of chunks is in the right ballpark;
# this could theoretically be any number but statistically it
# should always be in this range
approx = lower < r < upper
self.assertTrue(approx)
for r in uziter:
pass
self.assertEqual(r, 0)
with tempdir.child("zipstreamjunk").open() as f:
newmd5 = md5(f.read()).hexdigest()
self.assertEqual(newmd5, junkmd5) | unzipIterChunky should unzip the given number of bytes per iteration. | _unzipIterChunkyTest | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | MIT |
def test_unzipIterChunkyStored(self):
"""
unzipIterChunky should unzip the given number of bytes per iteration on
a stored archive.
"""
self._unzipIterChunkyTest(zipfile.ZIP_STORED, 500, 35, 45) | unzipIterChunky should unzip the given number of bytes per iteration on
a stored archive. | test_unzipIterChunkyStored | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | MIT |
def test_chunkyDeflated(self):
"""
unzipIterChunky should unzip the given number of bytes per iteration on
a deflated archive.
"""
self._unzipIterChunkyTest(zipfile.ZIP_DEFLATED, 972, 23, 27) | unzipIterChunky should unzip the given number of bytes per iteration on
a deflated archive. | test_chunkyDeflated | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | MIT |
def _makebigfile(self, filename, compression, junk):
"""
Create a zip file with the given file name and compression scheme.
"""
with zipfile.ZipFile(filename, 'w', compression) as zf:
for i in range(10):
fn = 'zipstream%d' % i
zf.writestr(fn, "")
zf.writestr('zipstreamjunk', junk) | Create a zip file with the given file name and compression scheme. | _makebigfile | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_zipstream.py | MIT |
def test_emitWithoutMessage(self):
"""
L{SyslogObserver.emit} ignores events with an empty value for the
C{'message'} key.
"""
self.observer.emit({'message': (), 'isError': False, 'system': '-'})
self.assertEqual(self.events, []) | L{SyslogObserver.emit} ignores events with an empty value for the
C{'message'} key. | test_emitWithoutMessage | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_syslog.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_syslog.py | MIT |
def test_emitCustomPriority(self):
"""
L{SyslogObserver.emit} uses the value of the C{'syslogPriority'} as the
syslog priority, if that key is present in the event dictionary.
"""
self.observer.emit({
'message': ('hello, world',), 'isError': False, 'system': '-',
'syslogPriority': stdsyslog.LOG_DEBUG})
self.assertEqual(
self.events,
[(stdsyslog.LOG_DEBUG, '[-] hello, world')]) | L{SyslogObserver.emit} uses the value of the C{'syslogPriority'} as the
syslog priority, if that key is present in the event dictionary. | test_emitCustomPriority | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_syslog.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_syslog.py | MIT |
def test_emitErrorPriority(self):
"""
L{SyslogObserver.emit} uses C{LOG_ALERT} if the event represents an
error.
"""
self.observer.emit({
'message': ('hello, world',), 'isError': True, 'system': '-',
'failure': Failure(Exception("foo"))})
self.assertEqual(
self.events,
[(stdsyslog.LOG_ALERT, '[-] hello, world')]) | L{SyslogObserver.emit} uses C{LOG_ALERT} if the event represents an
error. | test_emitErrorPriority | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_syslog.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_syslog.py | MIT |
def test_emitCustomPriorityOverridesError(self):
"""
L{SyslogObserver.emit} uses the value of the C{'syslogPriority'} key if
it is specified even if the event dictionary represents an error.
"""
self.observer.emit({
'message': ('hello, world',), 'isError': True, 'system': '-',
'syslogPriority': stdsyslog.LOG_NOTICE,
'failure': Failure(Exception("bar"))})
self.assertEqual(
self.events,
[(stdsyslog.LOG_NOTICE, '[-] hello, world')]) | L{SyslogObserver.emit} uses the value of the C{'syslogPriority'} key if
it is specified even if the event dictionary represents an error. | test_emitCustomPriorityOverridesError | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_syslog.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_syslog.py | MIT |
def test_emitCustomFacility(self):
"""
L{SyslogObserver.emit} uses the value of the C{'syslogPriority'} as the
syslog priority, if that key is present in the event dictionary.
"""
self.observer.emit({
'message': ('hello, world',), 'isError': False, 'system': '-',
'syslogFacility': stdsyslog.LOG_CRON})
self.assertEqual(
self.events,
[(stdsyslog.LOG_INFO | stdsyslog.LOG_CRON, '[-] hello, world')]) | L{SyslogObserver.emit} uses the value of the C{'syslogPriority'} as the
syslog priority, if that key is present in the event dictionary. | test_emitCustomFacility | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_syslog.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_syslog.py | MIT |
def test_emitCustomSystem(self):
"""
L{SyslogObserver.emit} uses the value of the C{'system'} key to prefix
the logged message.
"""
self.observer.emit({'message': ('hello, world',), 'isError': False,
'system': 'nonDefaultSystem'})
self.assertEqual(
self.events,
[(stdsyslog.LOG_INFO, "[nonDefaultSystem] hello, world")]) | L{SyslogObserver.emit} uses the value of the C{'system'} key to prefix
the logged message. | test_emitCustomSystem | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_syslog.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_syslog.py | MIT |
def test_emitMessage(self):
"""
L{SyslogObserver.emit} logs the value of the C{'message'} key of the
event dictionary it is passed to the syslog.
"""
self.observer.emit({
'message': ('hello, world',), 'isError': False,
'system': '-'})
self.assertEqual(
self.events,
[(stdsyslog.LOG_INFO, "[-] hello, world")]) | L{SyslogObserver.emit} logs the value of the C{'message'} key of the
event dictionary it is passed to the syslog. | test_emitMessage | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_syslog.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_syslog.py | MIT |
def test_emitMultilineMessage(self):
"""
Each line of a multiline message is emitted separately to the syslog.
"""
self.observer.emit({
'message': ('hello,\nworld',), 'isError': False,
'system': '-'})
self.assertEqual(
self.events,
[(stdsyslog.LOG_INFO, '[-] hello,'),
(stdsyslog.LOG_INFO, '[-] \tworld')]) | Each line of a multiline message is emitted separately to the syslog. | test_emitMultilineMessage | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_syslog.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_syslog.py | MIT |
def test_emitStripsTrailingEmptyLines(self):
"""
Trailing empty lines of a multiline message are omitted from the
messages sent to the syslog.
"""
self.observer.emit({
'message': ('hello,\nworld\n\n',), 'isError': False,
'system': '-'})
self.assertEqual(
self.events,
[(stdsyslog.LOG_INFO, '[-] hello,'),
(stdsyslog.LOG_INFO, '[-] \tworld')]) | Trailing empty lines of a multiline message are omitted from the
messages sent to the syslog. | test_emitStripsTrailingEmptyLines | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_syslog.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_syslog.py | MIT |
def mktime(t9):
"""
Call L{mktime_real}, and if it raises L{OverflowError}, catch it and raise
SkipTest instead.
@param t9: A time as a 9-item tuple.
@type t9: L{tuple}
@return: A timestamp.
@rtype: L{float}
"""
try:
return mktime_real(t9)
except OverflowError:
raise SkipTest(
"Platform cannot construct time zone for {0!r}"
.format(t9)
) | Call L{mktime_real}, and if it raises L{OverflowError}, catch it and raise
SkipTest instead.
@param t9: A time as a 9-item tuple.
@type t9: L{tuple}
@return: A timestamp.
@rtype: L{float} | mktime | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_tzhelper.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_tzhelper.py | MIT |
def setTZ(name):
"""
Set time zone.
@param name: a time zone name
@type name: L{str}
"""
if tzset is None:
return
if name is None:
try:
del environ["TZ"]
except KeyError:
pass
else:
environ["TZ"] = name
tzset() | Set time zone.
@param name: a time zone name
@type name: L{str} | setTZ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_tzhelper.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_tzhelper.py | MIT |
def addTZCleanup(testCase):
"""
Add cleanup hooks to a test case to reset timezone to original value.
@param testCase: the test case to add the cleanup to.
@type testCase: L{unittest.TestCase}
"""
tzIn = environ.get("TZ", None)
@testCase.addCleanup
def resetTZ():
setTZ(tzIn) | Add cleanup hooks to a test case to reset timezone to original value.
@param testCase: the test case to add the cleanup to.
@type testCase: L{unittest.TestCase} | addTZCleanup | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_tzhelper.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_tzhelper.py | MIT |
def test_tzinfo(self):
"""
Test that timezone attributes respect the timezone as set by the
standard C{TZ} environment variable and L{tzset} API.
"""
if tzset is None:
raise SkipTest(
"Platform cannot change timezone; unable to verify offsets."
)
def testForTimeZone(name, expectedOffsetDST, expectedOffsetSTD):
setTZ(name)
localDST = mktime((2006, 6, 30, 0, 0, 0, 4, 181, 1))
localSTD = mktime((2007, 1, 31, 0, 0, 0, 2, 31, 0))
tzDST = FixedOffsetTimeZone.fromLocalTimeStamp(localDST)
tzSTD = FixedOffsetTimeZone.fromLocalTimeStamp(localSTD)
self.assertEqual(
tzDST.tzname(localDST),
"UTC{0}".format(expectedOffsetDST)
)
self.assertEqual(
tzSTD.tzname(localSTD),
"UTC{0}".format(expectedOffsetSTD)
)
self.assertEqual(tzDST.dst(localDST), timedelta(0))
self.assertEqual(tzSTD.dst(localSTD), timedelta(0))
def timeDeltaFromOffset(offset):
assert len(offset) == 5
sign = offset[0]
hours = int(offset[1:3])
minutes = int(offset[3:5])
if sign == "-":
hours = -hours
minutes = -minutes
else:
assert sign == "+"
return timedelta(hours=hours, minutes=minutes)
self.assertEqual(
tzDST.utcoffset(localDST),
timeDeltaFromOffset(expectedOffsetDST)
)
self.assertEqual(
tzSTD.utcoffset(localSTD),
timeDeltaFromOffset(expectedOffsetSTD)
)
addTZCleanup(self)
# UTC
testForTimeZone("UTC+00", "+0000", "+0000")
# West of UTC
testForTimeZone("EST+05EDT,M4.1.0,M10.5.0", "-0400", "-0500")
# East of UTC
testForTimeZone("CEST-01CEDT,M4.1.0,M10.5.0", "+0200", "+0100")
# No DST
testForTimeZone("CST+06", "-0600", "-0600") | Test that timezone attributes respect the timezone as set by the
standard C{TZ} environment variable and L{tzset} API. | test_tzinfo | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_tzhelper.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_tzhelper.py | MIT |
def fileno(self):
"""
Return the fileno of this FD.
"""
return self._fd | Return the fileno of this FD. | fileno | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_sendmsg.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_sendmsg.py | MIT |
def close(self):
"""
Close the FD. If it's already been closed, do nothing.
"""
if self._fd:
close(self._fd)
self._fd = None | Close the FD. If it's already been closed, do nothing. | close | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_sendmsg.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_sendmsg.py | MIT |
def __del__(self):
"""
If C{self._fd} is unclosed, raise a warning.
"""
if self._fd:
if not _PY3:
ResourceWarning = Warning
warnings.warn("FD %s was not closed!" % (self._fd,),
ResourceWarning)
self.close() | If C{self._fd} is unclosed, raise a warning. | __del__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_sendmsg.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_sendmsg.py | MIT |
def _makePipe():
"""
Create a pipe, and return the two FDs wrapped in L{_FDHolders}.
"""
r, w = pipe()
return (_FDHolder(r), _FDHolder(w)) | Create a pipe, and return the two FDs wrapped in L{_FDHolders}. | _makePipe | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_sendmsg.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_sendmsg.py | MIT |
def __str__(self):
"""
Dump the errors in a pretty way in the event of a subprocess traceback.
"""
result = b'\n'.join([b''] + list(self.args))
if _PY3:
result = repr(result)
return result | Dump the errors in a pretty way in the event of a subprocess traceback. | __str__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_sendmsg.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_sendmsg.py | MIT |
def _spawn(script, outputFD):
"""
Start a script that is a peer of this test as a subprocess.
@param script: the module name of the script in this directory (no
package prefix, no '.py')
@type script: C{str}
@rtype: L{StartStopProcessProtocol}
"""
pyExe = FilePath(sys.executable).asBytesMode().path
env = bytesEnviron()
env[b"PYTHONPATH"] = FilePath(
pathsep.join(sys.path)).asBytesMode().path
sspp = StartStopProcessProtocol()
reactor.spawnProcess(
sspp, pyExe, [
pyExe,
FilePath(__file__).sibling(script + ".py").asBytesMode().path,
intToBytes(outputFD),
],
env=env,
childFDs={0: "w", 1: "r", 2: "r", outputFD: outputFD}
)
return sspp | Start a script that is a peer of this test as a subprocess.
@param script: the module name of the script in this directory (no
package prefix, no '.py')
@type script: C{str}
@rtype: L{StartStopProcessProtocol} | _spawn | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_sendmsg.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_sendmsg.py | MIT |
def __iter__(self):
"""
Allow normal list iteration, or raise an exception.
If C{self.iterate} is C{True}, it will be flipped to C{False} and then
normal iteration will proceed. If C{self.iterate} is C{False},
L{RuntimeError} is raised instead.
"""
if self.iterate:
self.iterate = False
return super(BadList, self).__iter__()
raise RuntimeError("Something bad happened") | Allow normal list iteration, or raise an exception.
If C{self.iterate} is C{True}, it will be flipped to C{False} and then
normal iteration will proceed. If C{self.iterate} is C{False},
L{RuntimeError} is raised instead. | __iter__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_sendmsg.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_sendmsg.py | MIT |
def __iter__(self):
"""
Return an iterator which will raise an exception as soon as C{next} is
called on it.
"""
class BadIterator(object):
def next(self):
raise RuntimeError("This is a really bad case.")
return BadIterator() | Return an iterator which will raise an exception as soon as C{next} is
called on it. | __iter__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_sendmsg.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_sendmsg.py | MIT |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.