本文整理汇总了Python中twisted.internet.task.Clock.seconds方法的典型用法代码示例。如果您正苦于以下问题:Python Clock.seconds方法的具体用法?Python Clock.seconds怎么用?Python Clock.seconds使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twisted.internet.task.Clock
的用法示例。
在下文中一共展示了Clock.seconds方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_rewriteCss
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import seconds [as 别名]
def test_rewriteCss(self):
"""
Test that CSS processing works, and verify the header.
"""
clock = Clock()
fc = FileCache(lambda: clock.seconds(), 1)
temp = FilePath(self.mktemp() + '.css')
with temp.open('wb') as f:
f.write("p { color: red; }\n")
# BetterFile(temp.path) would not work because the processing happens
# in getChild. So, create a BetterFile for the .css file's parent dir.
bf = BetterFile(temp.parent().path, fileCache=fc, rewriteCss=True)
d = self._requestPostpathAndRender(bf, [temp.basename()])
headerRe = re.compile(r"/\* CSSResource processed ([0-9a-f]{32}?) \*/")
def assertProcessedContent((request, child)):
out = "".join(request.written)
lines = out.split("\n")
self.assertTrue(re.match(headerRe, lines[0]), lines[0])
self.assertEqual("p { color: red; }", lines[1])
self.assertEqual("", lines[2])
self.assertEqual(3, len(lines))
d.addCallback(assertProcessedContent)
return d
示例2: test_cssRewriterFixesUrls
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import seconds [as 别名]
def test_cssRewriterFixesUrls(self):
"""
The CSS rewriter appends ?cachebreakers to the url(...)s inside
the .css file. If a file mentioned by a url(...) is modified, the
processed .css is updated.
"""
clock = Clock()
fc = FileCache(lambda: clock.seconds(), 1)
parent, t = self._makeTree()
root = BetterFile(parent.path, fileCache=fc, rewriteCss=True)
site = server.Site(root)
def requestStyleCss():
return self._requestPostpathAndRender(
root, ['sub', 'style.css'], path='/sub/style.css', site=site)
d = requestStyleCss()
expect = """\
/* CSSResource processed %(md5original)s */
div { background-image: url(http://127.0.0.1/not-modified.png); }
td { background-image: url(https://127.0.0.1/not-modified.png); }
p { background-image: url(../one.png?cb=%(md5one)s); }
q { background-image: url(two.png?cb=%(md5two)s); }
b { background-image: url(sub%%20sub/three.png?cb=%(md5three)s); }
i { background-image: url(/sub/sub%%20sub/three.png?cb=%(md5three)s); }
"""
def assertCacheBrokenLinks((request, child)):
out = "".join(request.written)
self.assertEqual(expect % t, out,
"\nExpected:\n\n%s\n\nGot:\n\n%s" % (expect % t, out))
expectedBreaker = hashlib.md5(expect % t).hexdigest()
self.assertEqual(expectedBreaker, child.getCacheBreaker())
d.addCallback(assertCacheBrokenLinks)
def modifyThreePngAndMakeRequest(_):
parent.child('sub').child('sub sub').child('three.png').setContent("replacement")
return requestStyleCss()
d.addCallback(modifyThreePngAndMakeRequest)
def assertNotUpdatedLinks((request, child)):
out = "".join(request.written)
# Still the same links, because we didn't advance the clock.
self.assertEqual(expect % t, out)
d.addCallback(assertNotUpdatedLinks)
def advanceClockAndMakeRequest(_):
clock.advance(1)
return requestStyleCss()
d.addCallback(advanceClockAndMakeRequest)
def assertUpdatedLinks((request, child)):
out = "".join(request.written)
t2 = t.copy()
t2['md5three'] = t['md5replacement']
self.assertEqual(expect % t2, out)
d.addCallback(assertUpdatedLinks)
return d
示例3: test_periodic_client_enquire_link
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import seconds [as 别名]
def test_periodic_client_enquire_link(self):
request_body_a = (
"<ENQRequest>"
"<requestId>0</requestId>"
"<enqCmd>ENQUIRELINK</enqCmd>"
"</ENQRequest>")
expected_request_packet_a = utils.mk_packet('0', request_body_a)
response_body_a = (
"<ENQResponse>"
"<requestId>0</requestId>"
"<enqCmd>ENQUIRELINKRSP</enqCmd>"
"</ENQResponse>")
response_packet_a = utils.mk_packet('0', response_body_a)
self.server.responses[expected_request_packet_a] = response_packet_a
request_body_b = (
"<ENQRequest>"
"<requestId>1</requestId>"
"<enqCmd>ENQUIRELINK</enqCmd>"
"</ENQRequest>")
expected_request_packet_b = utils.mk_packet('1', request_body_b)
response_body_b = (
"<ENQResponse>"
"<requestId>1</requestId>"
"<enqCmd>ENQUIRELINKRSP</enqCmd>"
"</ENQResponse>")
response_packet_b = utils.mk_packet('1', response_body_b)
self.server.responses[expected_request_packet_b] = response_packet_b
clock = Clock()
t0 = clock.seconds()
self.client.clock = clock
self.client.enquire_link_interval = 120
self.client.timeout_period = 20
self.client.authenticated = True
self.client.start_periodic_enquire_link()
# advance to just after the first enquire link request
clock.advance(0.01)
self.assert_next_timeout(t0 + 20)
# wait for the first enquire link response
yield self.client.wait_for_data()
self.assert_timeout_cancelled()
# advance to just after the second enquire link request
clock.advance(120.01)
self.assert_next_timeout(t0 + 140)
# wait for the second enquire link response
yield self.client.wait_for_data()
self.assert_timeout_cancelled()
示例4: test_httpRequest
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import seconds [as 别名]
def test_httpRequest(self):
clock = Clock()
rco = ResponseCacheOptions(
cacheTime=3600, httpCachePublic=False, httpsCachePublic=True)
request = DummyRequest([])
setCachingHeadersOnRequest(request, rco, getTime=lambda: clock.seconds())
self.assertEqual({
'Cache-Control': ['max-age=3600, private'],
'Date': ['Thu, 01 Jan 1970 00:00:00 GMT'],
'Expires': ['Thu, 01 Jan 1970 01:00:00 GMT']},
dict(request.responseHeaders.getAllRawHeaders()))
示例5: test_noCache
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import seconds [as 别名]
def test_noCache(self):
"""
If C{cacheTime} is 0, appropriate headers are set.
"""
clock = Clock()
# Even though these are both public=True, it correctly sets ", private".
rco = ResponseCacheOptions(
cacheTime=0, httpCachePublic=True, httpsCachePublic=True)
request = DummyRequest([])
setCachingHeadersOnRequest(request, rco, getTime=lambda: clock.seconds())
self.assertEqual({
'Cache-Control': ['max-age=0, private'],
# A Date header is set even in this case.
'Date': ['Thu, 01 Jan 1970 00:00:00 GMT'],
'Expires': ['-1']},
dict(request.responseHeaders.getAllRawHeaders()))
示例6: test_cssCached
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import seconds [as 别名]
def test_cssCached(self):
"""
The processed CSS file is cached, and updated when the underlying
file changes.
"""
clock = Clock()
fc = FileCache(lambda: clock.seconds(), 1)
temp = FilePath(self.mktemp() + '.css')
temp.setContent("p { color: red; }\n")
bf = BetterFile(temp.parent().path, fileCache=fc, rewriteCss=True)
d = self._requestPostpathAndRender(bf, [temp.basename()])
def assertColorRed((request, child)):
lines = "".join(request.written).split("\n")
self.assertEqual(["p { color: red; }", ""], lines[1:])
d.addCallback(assertColorRed)
def modifyUnderlyingAndMakeRequest(_):
with temp.open('wb') as f:
f.write("p { color: green; }\n")
d = self._requestPostpathAndRender(bf, [temp.basename()])
return d
d.addCallback(modifyUnderlyingAndMakeRequest)
def assertStillColorRed((request, child)):
lines = "".join(request.written).split("\n")
self.assertEqual(["p { color: red; }", ""], lines[1:])
d.addCallback(assertStillColorRed)
def advanceClockAndMakeRequest(_):
clock.advance(1)
d = self._requestPostpathAndRender(bf, [temp.basename()])
return d
d.addCallback(advanceClockAndMakeRequest)
def assertColorGreen((request, child)):
lines = "".join(request.written).split("\n")
self.assertEqual(["p { color: green; }", ""], lines[1:])
d.addCallback(assertColorGreen)
return d
示例7: ret
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import seconds [as 别名]
def ret():
error = [None]
clock = Clock()
d = f(clock)
@d.addErrback
def on_error(f):
error[0] = f
while True:
time_to_wait = max([0] + [call.getTime() - clock.seconds() for call in clock.getDelayedCalls()])
if time_to_wait == 0:
break
else:
clock.advance(time_to_wait)
if error[0]:
error[0].raiseException()
示例8: test_requestAlreadyHasHeaders
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import seconds [as 别名]
def test_requestAlreadyHasHeaders(self):
"""
If the request passed to L{setCachingHeadersOnRequest} already has headers,
existing Date/Expires/Cache-Control headers are replaced, and
irrelevant ones are kept.
"""
clock = Clock()
rco = ResponseCacheOptions(
cacheTime=3600, httpCachePublic=False, httpsCachePublic=True)
request = DummyRequest([])
request.responseHeaders.setRawHeaders('cache-control', ['X', 'Y'])
request.responseHeaders.setRawHeaders('date', ['whenever'])
request.responseHeaders.setRawHeaders('expires', ['sometime'])
request.responseHeaders.setRawHeaders('extra', ['one', 'two'])
setCachingHeadersOnRequest(request, rco, getTime=lambda: clock.seconds())
self.assertEqual({
'Cache-Control': ['max-age=3600, private'],
'Date': ['Thu, 01 Jan 1970 00:00:00 GMT'],
'Expires': ['Thu, 01 Jan 1970 01:00:00 GMT'],
'Extra': ['one', 'two']},
dict(request.responseHeaders.getAllRawHeaders()))
示例9: APITestsMixin
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import seconds [as 别名]
#.........这里部分代码省略.........
"""
name = u"thename"
# Create a dataset out-of-band with matching dataset ID and name
# which the docker plugin won't be able to see.
def create_after_list():
# Clean up the patched version:
del self.flocker_client.list_datasets_configuration
# But first time we're called, we create dataset and lie about
# its existence:
d = self.flocker_client.create_dataset(
self.NODE_A, DEFAULT_SIZE,
metadata={u"name": name},
dataset_id=UUID(dataset_id_from_name(name)))
d.addCallback(lambda _: [])
return d
self.flocker_client.list_datasets_configuration = create_after_list
return self.create(name)
def _flush_volume_plugin_reactor_on_endpoint_render(self):
"""
This method patches ``self.app`` so that after any endpoint is
rendered, the reactor used by the volume plugin is advanced repeatedly
until there are no more ``delayedCalls`` pending on the reactor.
"""
real_execute_endpoint = self.app.execute_endpoint
def patched_execute_endpoint(*args, **kwargs):
val = real_execute_endpoint(*args, **kwargs)
while self.volume_plugin_reactor.getDelayedCalls():
pending_calls = self.volume_plugin_reactor.getDelayedCalls()
next_expiration = min(t.getTime() for t in pending_calls)
now = self.volume_plugin_reactor.seconds()
self.volume_plugin_reactor.advance(
max(0.0, next_expiration - now))
return val
self.patch(self.app, 'execute_endpoint', patched_execute_endpoint)
def test_mount(self):
"""
``/VolumeDriver.Mount`` sets the primary of the dataset with matching
name to the current node and then waits for the dataset to
actually arrive.
"""
name = u"myvol"
dataset_id = UUID(dataset_id_from_name(name))
# Create dataset on a different node:
d = self.flocker_client.create_dataset(
self.NODE_B, DEFAULT_SIZE, metadata={u"name": name},
dataset_id=dataset_id)
self._flush_volume_plugin_reactor_on_endpoint_render()
# Pretend that it takes 5 seconds for the dataset to get established on
# Node A.
self.volume_plugin_reactor.callLater(
5.0, self.flocker_client.synchronize_state)
d.addCallback(lambda _:
self.assertResult(
b"POST", b"/VolumeDriver.Mount",
{u"Name": name}, OK,
{u"Err": None,
u"Mountpoint": u"/flocker/{}".format(dataset_id)}))
d.addCallback(lambda _: self.flocker_client.list_datasets_state())
示例10: LeasesTests
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import seconds [as 别名]
class LeasesTests(AsyncTestCase):
"""
Tests for ``LeaseService`` and ``update_leases``.
"""
def setUp(self):
super(LeasesTests, self).setUp()
self.clock = Clock()
self.persistence_service = ConfigurationPersistenceService(
self.clock, FilePath(self.mktemp()))
self.persistence_service.startService()
self.addCleanup(self.persistence_service.stopService)
def test_update_leases_saves_changed_leases(self):
"""
``update_leases`` only changes the leases stored in the configuration.
"""
node_id = uuid4()
dataset_id = uuid4()
original_leases = Leases().acquire(
datetime.fromtimestamp(0, UTC), uuid4(), node_id)
def update(leases):
return leases.acquire(
datetime.fromtimestamp(1000, UTC), dataset_id, node_id)
d = self.persistence_service.save(
LATEST_TEST_DEPLOYMENT.set(leases=original_leases))
d.addCallback(
lambda _: update_leases(update, self.persistence_service))
def updated(_):
self.assertEqual(
self.persistence_service.get(),
LATEST_TEST_DEPLOYMENT.set(leases=update(original_leases)))
d.addCallback(updated)
return d
def test_update_leases_result(self):
"""
``update_leases`` returns a ``Deferred`` firing with the updated
``Leases`` instance.
"""
node_id = uuid4()
dataset_id = uuid4()
original_leases = Leases()
def update(leases):
return leases.acquire(
datetime.fromtimestamp(1000, UTC), dataset_id, node_id)
d = update_leases(update, self.persistence_service)
def updated(updated_leases):
self.assertEqual(updated_leases, update(original_leases))
d.addCallback(updated)
return d
def test_expired_lease_removed(self):
"""
A lease that has expired is removed from the persisted
configuration.
"""
timestep = 100
node_id = uuid4()
ids = uuid4(), uuid4()
# First dataset lease expires at timestep:
now = self.clock.seconds()
leases = Leases().acquire(
datetime.fromtimestamp(now, UTC), ids[0], node_id, timestep)
# Second dataset lease expires at timestep * 2:
leases = leases.acquire(
datetime.fromtimestamp(now, UTC), ids[1], node_id, timestep * 2)
new_config = Deployment(leases=leases)
d = self.persistence_service.save(new_config)
def saved(_):
self.clock.advance(timestep - 1) # 99
before_first_expire = self.persistence_service.get().leases
self.clock.advance(2) # 101
after_first_expire = self.persistence_service.get().leases
self.clock.advance(timestep - 2) # 199
before_second_expire = self.persistence_service.get().leases
self.clock.advance(2) # 201
after_second_expire = self.persistence_service.get().leases
self.assertTupleEqual(
(before_first_expire, after_first_expire,
before_second_expire, after_second_expire),
(leases, leases.remove(ids[0]), leases.remove(ids[0]),
leases.remove(ids[0]).remove(ids[1])))
d.addCallback(saved)
return d
@capture_logging(None)
def test_expire_lease_logging(self, logger):
"""
An expired lease is logged.
"""
node_id = uuid4()
dataset_id = uuid4()
#.........这里部分代码省略.........
示例11: MemCacheTestCase
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import seconds [as 别名]
#.........这里部分代码省略.........
d1 = self.proto.stats()
d2 = Deferred()
self.proto.connectionLost = d2.callback
self.proto.dataReceived("STAT foo bar\r\n")
self.clock.advance(self.proto.persistentTimeOut)
self.assertFailure(d1, TimeoutError)
return gatherResults([d1, d2])
def test_timeoutPipelining(self):
"""
When two requests are sent, a timeout call remains around for the
second request, and its timeout time is correct.
"""
d1 = self.proto.get("foo")
d2 = self.proto.get("bar")
d3 = Deferred()
self.proto.connectionLost = d3.callback
self.clock.advance(self.proto.persistentTimeOut - 1)
self.proto.dataReceived("VALUE foo 0 3\r\nbar\r\nEND\r\n")
def check(result):
self.assertEquals(result, (0, "bar"))
self.assertEquals(len(self.clock.calls), 1)
for i in range(self.proto.persistentTimeOut):
self.clock.advance(1)
return self.assertFailure(d2, TimeoutError).addCallback(checkTime)
def checkTime(ignored):
# Check that the timeout happened C{self.proto.persistentTimeOut}
# after the last response
self.assertEquals(
self.clock.seconds(), 2 * self.proto.persistentTimeOut - 1)
d1.addCallback(check)
return d1
def test_timeoutNotReset(self):
"""
Check that timeout is not resetted for every command, but keep the
timeout from the first command without response.
"""
d1 = self.proto.get("foo")
d3 = Deferred()
self.proto.connectionLost = d3.callback
self.clock.advance(self.proto.persistentTimeOut - 1)
d2 = self.proto.get("bar")
self.clock.advance(1)
self.assertFailure(d1, TimeoutError)
self.assertFailure(d2, TimeoutError)
return gatherResults([d1, d2, d3])
def test_timeoutCleanDeferreds(self):
"""
C{timeoutConnection} cleans the list of commands that it fires with
C{TimeoutError}: C{connectionLost} doesn't try to fire them again, but
sets the disconnected state so that future commands fail with a
C{RuntimeError}.
"""
d1 = self.proto.get("foo")
self.clock.advance(self.proto.persistentTimeOut)
self.assertFailure(d1, TimeoutError)
d2 = self.proto.get("bar")
示例12: MemCacheTestCase
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import seconds [as 别名]
#.........这里部分代码省略.........
"""
d1 = self.proto.stats()
d2 = Deferred()
self.proto.connectionLost = d2.callback
self.proto.dataReceived("STAT foo bar\r\n")
self.clock.advance(self.proto.persistentTimeOut)
self.assertFailure(d1, TimeoutError)
return gatherResults([d1, d2])
def test_timeoutPipelining(self):
"""
When two requests are sent, a timeout call should remain around for the
second request, and its timeout time should be correct.
"""
d1 = self.proto.get("foo")
d2 = self.proto.get("bar")
d3 = Deferred()
self.proto.connectionLost = d3.callback
self.clock.advance(self.proto.persistentTimeOut - 1)
self.proto.dataReceived("VALUE foo 0 3\r\nbar\r\nEND\r\n")
def check(result):
self.assertEquals(result, (0, "bar"))
self.assertEquals(len(self.clock.calls), 1)
for i in range(self.proto.persistentTimeOut):
self.clock.advance(1)
return self.assertFailure(d2, TimeoutError).addCallback(checkTime)
def checkTime(ignored):
# Check that the timeout happened C{self.proto.persistentTimeOut}
# after the last response
self.assertEquals(self.clock.seconds(),
2 * self.proto.persistentTimeOut - 1)
d1.addCallback(check)
return d1
def test_timeoutNotReset(self):
"""
Check that timeout is not resetted for every command, but keep the
timeout from the first command without response.
"""
d1 = self.proto.get("foo")
d3 = Deferred()
self.proto.connectionLost = d3.callback
self.clock.advance(self.proto.persistentTimeOut - 1)
d2 = self.proto.get("bar")
self.clock.advance(1)
self.assertFailure(d1, TimeoutError)
self.assertFailure(d2, TimeoutError)
return gatherResults([d1, d2, d3])
def test_tooLongKey(self):
"""
Test that an error is raised when trying to use a too long key: the
called command should return a L{Deferred} which fail with a
L{ClientError}.
"""
d1 = self.assertFailure(self.proto.set("a" * 500, "bar"), ClientError)
d2 = self.assertFailure(self.proto.increment("a" * 500), ClientError)
d3 = self.assertFailure(self.proto.get("a" * 500), ClientError)
d4 = self.assertFailure(self.proto.append("a" * 500, "bar"), ClientError)
示例13: ClusterStateServiceTests
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import seconds [as 别名]
#.........这里部分代码省略.........
self.assertEqual(service.as_deployment(),
DeploymentState(nodes=[
NodeState(
hostname=u"host1",
applications=frozenset([APP1])),
NodeState(
hostname=u"host2",
applications=frozenset([APP2])),
]))
def test_manifestation_path(self):
"""
``manifestation_path`` returns the path on the filesystem where the
given dataset exists.
"""
identifier = uuid4()
service = self.service()
service.apply_changes([
NodeState(hostname=u"host1", uuid=identifier,
manifestations={
MANIFESTATION.dataset_id:
MANIFESTATION},
paths={MANIFESTATION.dataset_id:
FilePath(b"/xxx/yyy")},
devices={})
])
self.assertEqual(
service.manifestation_path(identifier, MANIFESTATION.dataset_id),
FilePath(b"/xxx/yyy"))
def test_expiration(self):
"""
Information updates that are more than the hard-coded expiration period
(in seconds) old are wiped.
"""
service = self.service()
service.apply_changes([self.WITH_APPS])
advance_rest(self.clock)
before_wipe_state = service.as_deployment()
advance_some(self.clock)
after_wipe_state = service.as_deployment()
self.assertEqual(
[before_wipe_state, after_wipe_state],
[DeploymentState(nodes=[self.WITH_APPS]), DeploymentState()],
)
def test_expiration_from_inactivity(self):
"""
Information updates from a source with no activity for more than the
hard-coded expiration period are wiped.
"""
service = self.service()
source = ChangeSource()
# Apply some changes at T1
source.set_last_activity(self.clock.seconds())
service.apply_changes_from_source(source, [self.WITH_APPS])
# A little bit of time passes (T2) and there is some activity.
advance_some(self.clock)
source.set_last_activity(self.clock.seconds())
# Enough more time passes (T3) to reach EXPIRATION_TIME from T1
advance_rest(self.clock)
before_wipe_state = service.as_deployment()
示例14: EINVALTestCase
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import seconds [as 别名]
class EINVALTestCase(TestCase):
"""
Sometimes, L{os.listdir} will raise C{EINVAL}. This is a transient error,
and L{CachingFilePath.listdir} should work around it by retrying the
C{listdir} operation until it succeeds.
"""
def setUp(self):
"""
Create a L{CachingFilePath} for the test to use.
"""
self.cfp = CachingFilePath(self.mktemp())
self.clock = Clock()
self.cfp._sleep = self.clock.advance
def test_testValidity(self):
"""
If C{listdir} is replaced on a L{CachingFilePath}, we should be able to
observe exceptions raised by the replacement. This verifies that the
test patching done here is actually testing something.
"""
class CustomException(Exception): "Just for testing."
def blowUp(dirname):
raise CustomException()
self.cfp._listdir = blowUp
self.assertRaises(CustomException, self.cfp.listdir)
self.assertRaises(CustomException, self.cfp.children)
def test_retryLoop(self):
"""
L{CachingFilePath} should catch C{EINVAL} and respond by retrying the
C{listdir} operation until it succeeds.
"""
calls = []
def raiseEINVAL(dirname):
calls.append(dirname)
if len(calls) < 5:
raise OSError(EINVAL, "This should be caught by the test.")
return ['a', 'b', 'c']
self.cfp._listdir = raiseEINVAL
self.assertEquals(self.cfp.listdir(), ['a', 'b', 'c'])
self.assertEquals(self.cfp.children(), [
CachingFilePath(pathjoin(self.cfp.path, 'a')),
CachingFilePath(pathjoin(self.cfp.path, 'b')),
CachingFilePath(pathjoin(self.cfp.path, 'c')),])
def requireTimePassed(self, filenames):
"""
Create a replacement for listdir() which only fires after a certain
amount of time.
"""
self.calls = []
def thunk(dirname):
now = self.clock.seconds()
if now < 20.0:
self.calls.append(now)
raise OSError(EINVAL, "Not enough time has passed yet.")
else:
return filenames
self.cfp._listdir = thunk
def assertRequiredTimePassed(self):
"""
Assert that calls to the simulated time.sleep() installed by
C{requireTimePassed} have been invoked the required number of times.
"""
# Waiting should be growing by *2 each time until the additional wait
# exceeds BACKOFF_MAX (5), at which point we should wait for 5s each
# time.
def cumulative(values):
current = 0.0
for value in values:
current += value
yield current
self.assertEquals(self.calls,
list(cumulative(
[0.0, 0.1, 0.2, 0.4, 0.8, 1.6, 3.2, 5.0, 5.0])))
def test_backoff(self):
"""
L{CachingFilePath} will wait for an increasing interval up to
C{BACKOFF_MAX} between calls to listdir().
"""
self.requireTimePassed(['a', 'b', 'c'])
self.assertEquals(self.cfp.listdir(), ['a', 'b', 'c'])
def test_siblingExtensionSearch(self):
"""
L{FilePath.siblingExtensionSearch} is unfortunately not implemented in
terms of L{FilePath.listdir}, so we need to verify that it will also
retry.
"""
filenames = [self.cfp.basename()+'.a',
#.........这里部分代码省略.........
示例15: TransportTestCase
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import seconds [as 别名]
class TransportTestCase(object):
"""PT client and server connect over a string transport.
We bypass the communication between client and server and intercept the
messages sent over the string transport.
"""
def setUp(self):
"""Set the reactor's callLater to our clock's callLater function
and build the protocols.
"""
self.clock = Clock()
reactor.callLater = self.clock.callLater
self.dump = []
self.proto_client = self._build_protocol(const.CLIENT)
self.proto_server = self._build_protocol(const.SERVER)
self.pt_client = self.proto_client.circuit.transport
self.pt_server = self.proto_server.circuit.transport
self._proxy(self.proto_client, self.proto_server)
self._bypass_connection(self.proto_client, self.proto_server)
def _proxy(self, client, server):
"""Proxy the communication between client and server and dump
intercepted data into a dictionary.
"""
def decorate_intercept(end):
old_rcv_f = end.circuit.transport.receivedDownstream
old_snd_f = end.circuit.transport.sendDownstream
def intercept(old_f, direction):
def new_f(data):
msgs = old_f(data)
end.history[direction].append((self.clock.seconds(), msgs))
return new_f
end.circuit.transport.receivedDownstream = intercept(old_rcv_f, 'rcv')
end.circuit.transport.sendDownstream = intercept(old_snd_f, 'snd')
decorate_intercept(client)
decorate_intercept(server)
def _bypass_connection(self, client, server):
"""Instead of requiring TCP connections between client and server
transports, we directly pass the data written from one end to the
received function at the other.
"""
def curry_bypass_connection(up, down, direction):
old_write = up.circuit.downstream.write
def write(data):
old_write(data)
down.dataReceived(data)
self.dump.append((self.clock.seconds(), direction * len(data)))
return write
client.circuit.downstream.write = curry_bypass_connection(client, server, const.OUT)
server.circuit.downstream.write = curry_bypass_connection(server, client, const.IN)
def _build_protocol(self, mode):
"""Build client and server protocols for an end point."""
addr_tuple = (HOST, str(PORT))
address = IPv4Address('TCP', HOST, PORT)
pt_config = self._build_transport_configuration(mode)
transport_class = self._configure_transport_class(mode, pt_config)
f_server = net.StaticDestinationServerFactory(addr_tuple, mode, transport_class, pt_config)
protocol_server = self._set_protocol(f_server, address)
f_client = net.StaticDestinationClientFactory(protocol_server.circuit, const.CLIENT)
protocol_client = self._set_protocol(f_client, address)
if mode == const.CLIENT:
return protocol_client
elif mode == const.SERVER:
return protocol_server
else:
raise ValueError("Transport mode '%s' not recognized." % mode)
def _set_protocol(self, factory, address):
"""Make protocol connection with a Twisted string transport."""
protocol = factory.buildProtocol(address)
protocol.makeConnection(proto_helpers.StringTransport())
protocol.history = {'rcv': [], 'snd': []}
return protocol
def _build_transport_configuration(self, mode):
"""Configure transport as a managed transport."""
pt_config = transport_config.TransportConfig()
pt_config.setStateLocation(const.TEMP_DIR)
pt_config.setObfsproxyMode("managed")
pt_config.setListenerMode(mode)
return pt_config
def _configure_transport_class(self, mode, pt_config):
"""Use the global arguments to configure the trasnport."""
transport_args = [mode, ADDR, "--dest=%s" % ADDR] + self.args
sys.argv = [sys.argv[0],
"--log-file", join(const.TEMP_DIR, "%s.log" % mode),
"--log-min-severity", "debug"]
sys.argv.append("wfpad") # use wfpad transport
sys.argv += transport_args
parser = set_up_cli_parsing()
consider_cli_args(parser.parse_args())
transport_class = get_transport_class(self.transport, mode)
transport_class.setup(pt_config)
p = ArgumentParser()
transport_class.register_external_mode_cli(p)
args = p.parse_args(transport_args)
#.........这里部分代码省略.........