本文整理汇总了Python中twisted.python.compat.NativeStringIO类的典型用法代码示例。如果您正苦于以下问题:Python NativeStringIO类的具体用法?Python NativeStringIO怎么用?Python NativeStringIO使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了NativeStringIO类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_removeSafelyRemoveFailsMoveSucceeds
def test_removeSafelyRemoveFailsMoveSucceeds(self):
"""
If an L{OSError} is raised while removing a path in
L{util._removeSafely}, an attempt is made to move the path to a new
name.
"""
def dummyRemove():
"""
Raise an C{OSError} to emulate the branch of L{util._removeSafely}
in which path removal fails.
"""
raise OSError()
# Patch stdout so we can check the print statements in _removeSafely
out = NativeStringIO()
self.patch(sys, 'stdout', out)
# Set up a trial directory with a _trial_marker
directory = self.mktemp().encode("utf-8")
os.mkdir(directory)
dirPath = filepath.FilePath(directory)
dirPath.child(b'_trial_marker').touch()
# Ensure that path.remove() raises an OSError
dirPath.remove = dummyRemove
util._removeSafely(dirPath)
self.assertIn("could not remove FilePath", out.getvalue())
示例2: test_insufficient_args
def test_insufficient_args(self):
"""
Calling run() with no args will cause it to print help.
"""
stringio = NativeStringIO()
self.patch(sys, 'stdout', stringio)
self.patch(os, 'getcwd', self.getcwd)
self.patch(datetime, 'date', self.date)
with self.assertRaises(SystemExit) as e:
run(["inctestpkg", "--rc"])
self.assertEqual(e.exception.args[0], 0)
self.assertIn("Updating codebase", stringio.getvalue())
self.assertEqual(self.packagedir.child("_version.py").getContent(),
b'''"""
Provides inctestpkg version information.
"""
# This file is auto-generated! Do not edit!
# Use `python -m incremental.update inctestpkg` to change this file.
from incremental import Version
__version__ = Version('inctestpkg', 16, 8, 0, release_candidate=1)
__all__ = ["__version__"]
''')
self.assertEqual(self.packagedir.child("__init__.py").getContent(),
b"""
from incremental import Version
introduced_in = Version('inctestpkg', 16, 8, 0, release_candidate=1).short()
next_released_version = "inctestpkg 16.8.0rc1"
""")
示例3: test_reporter
def test_reporter(self):
"""
Test for LimitedReporter.
Use test file of indentation to test
whether limited messages are returned when using LimitedReporter.
Complete run on the test file will return two warnings:
W0311 and W0312, but with limited report it returns only one.
"""
moduleTestIndentation = "twistedchecker.functionaltests.indentation"
pathTestIndentation = os.path.join(twistedchecker.abspath,
"functionaltests", "indentation.py")
# assert the test file exists
self.assertTrue(os.path.exists(pathTestIndentation))
streamTestResult = NativeStringIO()
runner = Runner()
runner.setOutput(streamTestResult)
# defaultly, runner will use LimitedReporter as its output reporter
# set allowed messages for it
runner.linter.reporter.messagesAllowed = set(["W0311"])
exitResult = self.assertRaises(
SystemExit, runner.run, [moduleTestIndentation])
# check the results to see only W0311 is reported
resultTest = streamTestResult.getvalue()
self.assertTrue("W0311" in resultTest)
self.assertTrue("W0312" not in resultTest)
self.assertEqual(4, exitResult.code)
示例4: setUp
def setUp(self):
"""
Add our example directory to the path and record which modules are
currently loaded.
"""
self.originalPath = sys.path[:]
self.originalModules = sys.modules.copy()
# Python usually expects native strs to be written to sys.stdout/stderr
self.fakeErr = NativeStringIO()
self.patch(sys, 'stderr', self.fakeErr)
self.fakeOut = NativeStringIO()
self.patch(sys, 'stdout', self.fakeOut)
# Get documentation root
here = (
FilePath(__file__)
.parent().parent().parent().parent()
.child('docs')
)
# Find the example script within this branch
for childName in self.exampleRelativePath.split('/'):
here = here.child(childName)
if not here.exists():
raise SkipTest(
"Examples (%s) not found - cannot test" % (here.path,))
self.examplePath = here
# Add the example parent folder to the Python path
sys.path.append(self.examplePath.parent().path)
# Import the example as a module
moduleName = self.examplePath.basename().split('.')[0]
self.example = __import__(moduleName)
示例5: render
def render(self, request):
"""
Render me to a web client.
Load my file, execute it in a special namespace (with 'request' and
'__file__' global vars) and finish the request. Output to the web-page
will NOT be handled with print - standard output goes to the log - but
with request.write.
"""
request.setHeader(b"x-powered-by", networkString("Twisted/%s" % copyright.version))
namespace = {'request': request,
'__file__': _coerceToFilesystemEncoding("", self.filename),
'registry': self.registry}
try:
execfile(self.filename, namespace, namespace)
except IOError as e:
if e.errno == 2: #file not found
request.setResponseCode(http.NOT_FOUND)
request.write(resource.NoResource("File not found.").render(request))
except:
io = NativeStringIO()
traceback.print_exc(file=io)
output = util._PRE(io.getvalue())
if _PY3:
output = output.encode("utf8")
request.write(output)
request.finish()
return server.NOT_DONE_YET
示例6: setUp
def setUp(self):
"""
Redirect stdout to a temp C{StringIO} stream.
"""
self.outputStream = NativeStringIO()
self.patch(sys, "stdout", self.outputStream)
self.errorStream = NativeStringIO()
self.patch(sys, "stderr", self.errorStream)
示例7: dump
def dump():
if not self._passed:
dump = NativeStringIO()
print("FAILED! dumping build db for debug", file=dump)
builds = yield self.master.data.get(("builds",))
for build in builds:
yield self.printBuild(build, dump, withLogs=True)
raise self.failureException(dump.getvalue())
示例8: mocked_open
def mocked_open(*args, **kwargs):
"""
Mock for the open call to prevent actually opening a log file.
"""
open_calls.append((args, kwargs))
io = NativeStringIO()
io.name = args[0]
open_rvalues.append(io)
return io
示例9: test_run_bad
def test_run_bad(self):
self.patch(sys, 'argv', ['buildbot', 'my', '-l'])
stdout = NativeStringIO()
self.patch(sys, 'stdout', stdout)
try:
runner.run()
except SystemExit as e:
self.assertEqual(e.args[0], 1)
else:
self.fail("didn't exit")
self.assertIn('THIS IS ME', stdout.getvalue())
示例10: test_run
def test_run(self):
"""
Calling run() with no args will cause it to print help.
"""
stringio = NativeStringIO()
self.patch(sys, 'stdout', stringio)
with self.assertRaises(SystemExit) as e:
run(["--help"])
self.assertEqual(e.exception.args[0], 0)
self.assertIn("Show this message and exit", stringio.getvalue())
示例11: test_exitMessageZero
def test_exitMessageZero(self):
"""
L{exit} given a status code of zero (C{0}) writes the given message to
standard output.
"""
out = NativeStringIO()
self.patch(_exit, "stdout", out)
message = "Hello, world."
exit(0, message)
self.assertEqual(out.getvalue(), message + "\n")
示例12: test_startLogging
def test_startLogging(self):
"""
startLogging() installs FileLogObserver and overrides sys.stdout and
sys.stderr.
"""
origStdout, origStderr = sys.stdout, sys.stderr
self._startLoggingCleanup()
# When done with test, reset stdout and stderr to current values:
fakeFile = StringIO()
observer = log.startLogging(fakeFile)
self.addCleanup(observer.stop)
log.msg("Hello!")
self.assertIn("Hello!", fakeFile.getvalue())
self.assertIsInstance(sys.stdout, log.StdioOnnaStick)
self.assertEqual(sys.stdout.isError, False)
encoding = getattr(origStdout, "encoding", None)
if not encoding:
encoding = sys.getdefaultencoding()
self.assertEqual(sys.stdout.encoding, encoding)
self.assertIsInstance(sys.stderr, log.StdioOnnaStick)
self.assertEqual(sys.stderr.isError, True)
encoding = getattr(origStderr, "encoding", None)
if not encoding:
encoding = sys.getdefaultencoding()
self.assertEqual(sys.stderr.encoding, encoding)
示例13: test_warningToFile
def test_warningToFile(self):
"""
L{twisted.python.log.showwarning} passes warnings with an explicit file
target on to the underlying Python warning system.
"""
# log.showwarning depends on _oldshowwarning being set, which only
# happens in startLogging(), which doesn't happen if you're not
# running under trial. So this test only passes by accident of runner
# environment.
if log._oldshowwarning is None:
raise unittest.SkipTest("Currently this test only runs under trial.")
message = "another unique message"
category = FakeWarning
filename = "warning-filename.py"
lineno = 31
output = StringIO()
log.showwarning(message, category, filename, lineno, file=output)
self.assertEqual(
output.getvalue(),
warnings.formatwarning(message, category, filename, lineno))
# In Python 2.6, warnings.showwarning accepts a "line" argument which
# gives the source line the warning message is to include.
if sys.version_info >= (2, 6):
line = "hello world"
output = StringIO()
log.showwarning(message, category, filename, lineno, file=output,
line=line)
self.assertEqual(
output.getvalue(),
warnings.formatwarning(message, category, filename, lineno,
line))
示例14: test_startLogging
def test_startLogging(self):
"""
startLogging() installs FileLogObserver and overrides sys.stdout and
sys.stderr.
"""
origStdout, origStderr = sys.stdout, sys.stderr
self._startLoggingCleanup()
# When done with test, reset stdout and stderr to current values:
fakeFile = StringIO()
observer = log.startLogging(fakeFile)
self.addCleanup(observer.stop)
log.msg("Hello!")
self.assertIn("Hello!", fakeFile.getvalue())
self.assertIsInstance(sys.stdout, LoggingFile)
self.assertEqual(sys.stdout.level, NewLogLevel.info)
encoding = getattr(origStdout, "encoding", None)
if not encoding:
encoding = sys.getdefaultencoding()
self.assertEqual(sys.stdout.encoding.upper(), encoding.upper())
self.assertIsInstance(sys.stderr, LoggingFile)
self.assertEqual(sys.stderr.level, NewLogLevel.error)
encoding = getattr(origStderr, "encoding", None)
if not encoding:
encoding = sys.getdefaultencoding()
self.assertEqual(sys.stderr.encoding.upper(), encoding.upper())
示例15: test_warningToFile
def test_warningToFile(self):
"""
L{twisted.python.log.showwarning} passes warnings with an explicit file
target on to the underlying Python warning system.
"""
message = "another unique message"
category = FakeWarning
filename = "warning-filename.py"
lineno = 31
output = StringIO()
log.showwarning(message, category, filename, lineno, file=output)
self.assertEqual(
output.getvalue(),
warnings.formatwarning(message, category, filename, lineno))
# In Python 2.6 and higher, warnings.showwarning accepts
# a "line" argument which gives the source line the warning
# message is to include.
line = "hello world"
output = StringIO()
log.showwarning(message, category, filename, lineno, file=output,
line=line)
self.assertEqual(
output.getvalue(),
warnings.formatwarning(message, category, filename, lineno,
line))