Here are the examples of the python api twisted.python.compat.NativeStringIO taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
90 Examples
3
Source : test_update.py
with MIT License
from autofelix
with MIT License
from autofelix
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())
def test_insufficient_args(self):
3
Source : test_exit.py
with MIT License
from autofelix
with MIT License
from autofelix
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")
def test_exitMessageNonZero(self):
3
Source : test_exit.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_exitMessageNonZero(self):
"""
L{exit} given a non-zero status code writes the given message to
standard error.
"""
out = NativeStringIO()
self.patch(_exit, "stderr", out)
message = "Hello, world."
exit(64, message)
self.assertEqual(out.getvalue(), message + "\n")
class DummyExit(object):
3
Source : test_strcred.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_warnWithBadFilename(self):
"""
When the file auth plugin is given a file that doesn't exist, it
should produce a warning.
"""
oldOutput = cred_file.theFileCheckerFactory.errorOutput
newOutput = NativeStringIO()
cred_file.theFileCheckerFactory.errorOutput = newOutput
strcred.makeChecker('file:' + self._fakeFilename())
cred_file.theFileCheckerFactory.errorOutput = oldOutput
self.assertIn(cred_file.invalidFileWarning, newOutput.getvalue())
class SSHCheckerTests(unittest.TestCase):
3
Source : test_strcred.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_displaysListCorrectly(self):
"""
The C{--help-auth} argument correctly displays all
available authentication plugins, then exits.
"""
newStdout = NativeStringIO()
options = DummyOptions()
options.authOutput = newStdout
self.assertRaises(SystemExit, options.parseOptions, ['--help-auth'])
for checkerFactory in strcred.findCheckerFactories():
self.assertIn(checkerFactory.authType, newStdout.getvalue())
def test_displaysHelpCorrectly(self):
3
Source : test_strcred.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_displaysHelpCorrectly(self):
"""
The C{--help-auth-for} argument will correctly display the help file for a
particular authentication plugin.
"""
newStdout = NativeStringIO()
options = DummyOptions()
options.authOutput = newStdout
self.assertRaises(
SystemExit, options.parseOptions, ['--help-auth-type', 'file'])
for line in cred_file.theFileCheckerFactory.authHelp:
if line.strip():
self.assertIn(line.strip(), newStdout.getvalue())
def test_unexpectedException(self):
3
Source : mailmail.py
with MIT License
from autofelix
with MIT License
from autofelix
def senderror(failure, options):
recipient = [options.sender]
sender = '"Internally Generated Message ({})" < postmaster@{}>'.format(
sys.argv[0], smtp.DNSNAME.decode("ascii"))
error = NativeStringIO()
failure.printTraceback(file=error)
body = NativeStringIO(ERROR_FMT % error.getvalue())
d = smtp.sendmail('localhost', sender, recipient, body)
d.addBoth(lambda _: reactor.stop())
def deny(conf):
3
Source : test_mailmail.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_unspecifiedRecipients(self):
"""
If no recipients are given in the argument list and there is no
recipient header in the message text, L{parseOptions} raises
L{SystemExit} with a string describing the problem.
"""
self.patch(sys, 'stdin', NativeStringIO(
'Subject: foo\n'
'\n'
'Hello, goodbye.\n'))
exc = self.assertRaises(SystemExit, parseOptions, [])
self.assertEqual(exc.args, ('No recipients specified.',))
def test_listQueueInformation(self):
3
Source : test_mailmail.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_version(self):
"""
The I{--version} option displays the version and raises
L{SystemExit} with L{None} as the exit code.
"""
out = NativeStringIO()
self.patch(sys, 'stdout', out)
systemExitCode = self.assertRaises(SystemExit, parseOptions,
'--version')
# SystemExit.code is None on success
self.assertEqual(systemExitCode.code, None)
data = out.getvalue()
self.assertEqual(data, "mailmail version: {}\n".format(version))
def test_backgroundDelivery(self):
3
Source : test_mailmail.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_backgroundDelivery(self):
"""
The I{-odb} flag specifies background delivery.
"""
stdin = NativeStringIO('\n')
self.patch(sys, 'stdin', stdin)
o = parseOptions("-odb")
self.assertTrue(o.background)
def test_foregroundDelivery(self):
3
Source : test_mailmail.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_foregroundDelivery(self):
"""
The I{-odf} flags specifies foreground delivery.
"""
stdin = NativeStringIO('\n')
self.patch(sys, 'stdin', stdin)
o = parseOptions("-odf")
self.assertFalse(o.background)
def test_recipientsFromHeaders(self):
3
Source : test_mailmail.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_recipientsFromHeaders(self):
"""
The I{-t} flags specifies that recipients should be obtained
from headers.
"""
stdin = NativeStringIO(
'To: Curly < [email protected]>\n'
'Cc: Larry < [email protected]>\n'
'Bcc: Moe < [email protected]>\n'
'\n'
'Oh, a wise guy?\n')
self.patch(sys, 'stdin', stdin)
o = parseOptions("-t")
self.assertEqual(len(o.to), 3)
def test_setFrom(self):
3
Source : test_mailmail.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_setFrom(self):
"""
When a message has no I{From:} header, a I{From:} value can be
specified with the I{-F} flag.
"""
stdin = NativeStringIO(
'To: [email protected]\n'
'Subject: A wise guy?\n\n')
self.patch(sys, 'stdin', stdin)
o = parseOptions(["-F", "Larry < [email protected]>", "-t"])
self.assertEqual(o.sender, "Larry < [email protected]>")
def test_overrideFromFlagByFromHeader(self):
3
Source : test_mailmail.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_overrideFromFlagByFromHeader(self):
"""
The I{-F} flag specifies the From: value. However, I{-F} flag is
overriden by the value of From: in the e-mail header.
"""
stdin = NativeStringIO(
'To: Curly < [email protected]>\n'
'From: Shemp < [email protected]>\n')
self.patch(sys, 'stdin', stdin)
o = parseOptions(["-F", "Groucho < [email protected]>", "-t"])
self.assertEqual(o.sender, "[email protected]")
def test_runErrorsToStderr(self):
3
Source : test_mailmail.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_runErrorsToStderr(self):
"""
Call L{mailmail.run}, and specify I{-oep} to print errors
to stderr. The sender, to, and printErrors options should be
set and there should be no failure.
"""
argv = ("test_mailmail.py", "[email protected]", "-oep")
stdin = NativeStringIO('\n')
self.patch(sys, 'argv', argv)
self.patch(sys, 'stdin', stdin)
mailmail.run()
self.assertEqual(self.options.sender, mailmail.getlogin())
self.assertEqual(self.options.to, ["[email protected]"])
# We should have printErrors set because we specified "-oep"
self.assertTrue(self.options.printErrors)
# We should not have any failures.
self.assertIsNone(mailmail.failed)
if platformType == "win32":
3
Source : components.py
with MIT License
from autofelix
with MIT License
from autofelix
def __repr__(self):
from pprint import pprint
sio = NativeStringIO()
pprint(self._adapterCache, sio)
return sio.getvalue()
def proxyForInterface(iface, originalAttribute='original'):
3
Source : test_pbfailure.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_printTracebackIncludesValue(self):
"""
When L{CopiedFailure.printTraceback} is used to print a copied failure
which was unjellied from a L{CopyableFailure} with C{unsafeTracebacks}
set to C{False}, the string representation of the exception value is
included in the output.
"""
original = pb.CopyableFailure(Exception("some reason"))
copied = jelly.unjelly(jelly.jelly(original, invoker=DummyInvoker()))
output = NativeStringIO()
copied.printTraceback(output)
exception = qual(Exception)
expectedOutput = ("Traceback from remote host -- "
"{}: some reason\n".format(exception))
self.assertEqual(expectedOutput, output.getvalue())
3
Source : test_application.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_reactorSelectionMixinNonExistent(self):
"""
Test that the usage mixin exits when trying to use a non existent
reactor (the name not matching to any reactor), giving an error
message.
"""
class ReactorSelectionOptions(usage.Options, app.ReactorSelectionMixin):
pass
self.pluginResults = []
options = ReactorSelectionOptions()
options.messageOutput = NativeStringIO()
e = self.assertRaises(usage.UsageError, options.parseOptions,
['--reactor', 'fakereactortest', 'subcommand'])
self.assertIn("fakereactortest", e.args[0])
self.assertIn("help-reactors", e.args[0])
def test_reactorSelectionMixinNotAvailable(self):
3
Source : test_application.py
with MIT License
from autofelix
with MIT License
from autofelix
def setUp(self):
"""
Get the text from --help-reactors
"""
self.options = app.ReactorSelectionMixin()
self.options.messageOutput = NativeStringIO()
self.assertRaises(SystemExit, self.options.opt_help_reactors)
self.message = self.options.messageOutput.getvalue()
def test_lacksAsyncIO(self):
3
Source : test_application.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_onlySupportedReactors(self):
"""
--help-reactors with only supported reactors
"""
def getReactorTypes():
yield twisted_reactors.default
options = app.ReactorSelectionMixin()
options._getReactorTypes = getReactorTypes
options.messageOutput = NativeStringIO()
self.assertRaises(SystemExit, options.opt_help_reactors)
message = options.messageOutput.getvalue()
self.assertNotIn("reactors not available", message)
class BackoffPolicyTests(unittest.TestCase):
3
Source : test_ident.py
with MIT License
from autofelix
with MIT License
from autofelix
def testLookupProcNetTcp(self):
"""
L{ident.ProcServerMixin.lookup} uses the Linux TCP process table.
"""
open_calls = []
def mocked_open(*args, **kwargs):
"""
Mock for the open call to prevent actually opening /proc/net/tcp.
"""
open_calls.append((args, kwargs))
return NativeStringIO(self.sampleFile)
self.patch(builtins, 'open', mocked_open)
p = ident.ProcServerMixin()
self.assertRaises(ident.NoUser, p.lookup, ('127.0.0.1', 26),
('1.2.3.4', 762))
self.assertEqual([(('/proc/net/tcp',), {})], open_calls)
3
Source : test_main.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_twisted_import(self):
"""Importing twisted.__main__ does not execute twist."""
output = StringIO()
monkey = self.patch(sys, 'stdout', output)
import twisted.__main__
self.assertTrue(twisted.__main__) # Appease pyflakes
monkey.restore()
self.assertEqual(output.getvalue(), "")
3
Source : test_policies.py
with MIT License
from autofelix
with MIT License
from autofelix
def open(self, name):
assert self.openFile is None, "open() called too many times"
self.openFile = NativeStringIO()
return self.openFile
class LoggingFactoryTests(unittest.TestCase):
3
Source : test_twistd.py
with MIT License
from autofelix
with MIT License
from autofelix
def _testStats(self, statsClass, profile):
out = NativeStringIO()
# Patch before creating the pstats, because pstats binds self.stream to
# sys.stdout early in 2.5 and newer.
stdout = self.patch(sys, 'stdout', out)
# If pstats.Stats can load the data and then reformat it, then the
# right thing probably happened.
stats = statsClass(profile)
stats.print_stats()
stdout.restore()
data = out.getvalue()
self.assertIn("function calls", data)
self.assertIn("(run)", data)
def test_profileSaveStats(self):
3
Source : test_keyboard.py
with MIT License
from autofelix
with MIT License
from autofelix
def setUp(self):
self.output = NativeStringIO()
self.reporter = reporter.TestResult()
self.loader = runner.TestLoader()
class InterruptInTestTests(TrialTest):
3
Source : test_output.py
with MIT License
from autofelix
with MIT License
from autofelix
def runTrial(*args):
from twisted.trial import reporter
config = trial.Options()
config.parseOptions(args)
output = NativeStringIO()
myRunner = runner.TrialRunner(
reporter.VerboseTextReporter,
stream=output,
workingDirectory=config['temp-directory'])
suite = trial._getSuite(config)
myRunner.run(suite)
return output.getvalue()
class ImportErrorsTests(packages.SysPathManglingTest):
3
Source : test_reporter.py
with MIT License
from autofelix
with MIT License
from autofelix
def setUp(self):
output = NativeStringIO()
self.result = reporter.Reporter(output, realtime=True)
class ErrorReportingTests(StringTest):
3
Source : test_reporter.py
with MIT License
from autofelix
with MIT License
from autofelix
def setUp(self):
self.loader = runner.TestLoader()
self.output = NativeStringIO()
self.result = reporter.Reporter(self.output)
def getOutput(self, suite):
3
Source : test_reporter.py
with MIT License
from autofelix
with MIT License
from autofelix
def setUp(self):
self.loader = runner.TestLoader()
self.output = NativeStringIO()
self.result = UncleanWarningsReporterWrapper(
reporter.Reporter(self.output))
class TracebackHandlingTests(unittest.SynchronousTestCase):
3
Source : test_reporter.py
with MIT License
from autofelix
with MIT License
from autofelix
def getErrorFrames(self, test):
"""
Run the given C{test}, make sure it fails and return the trimmed
frames.
@param test: The test case to run.
@return: The C{list} of frames trimmed.
"""
stream = NativeStringIO()
result = reporter.Reporter(stream)
test.run(result)
bads = result.failures + result.errors
self.assertEqual(len(bads), 1)
self.assertEqual(bads[0][0], test)
return result._trimFrames(bads[0][1].frames)
def checkFrames(self, observedFrames, expectedFrames):
3
Source : test_reporter.py
with MIT License
from autofelix
with MIT License
from autofelix
def setUp(self):
try:
raise RuntimeError('foo')
except RuntimeError:
self.f = Failure()
self.f.frames = [
['foo', 'foo/bar.py', 5, [('x', 5)], [('y', 'orange')]],
['qux', 'foo/bar.py', 10, [('a', 'two')], [('b', 'MCMXCIX')]]
]
self.stream = NativeStringIO()
self.result = reporter.Reporter(self.stream)
def test_formatDefault(self):
3
Source : test_reporter.py
with MIT License
from autofelix
with MIT License
from autofelix
def setUp(self):
self.dirtyError = Failure(
util.DirtyReactorAggregateError(['foo'], ['bar']))
self.output = NativeStringIO()
self.test = DirtyReactorTests('test_errorByDefault')
def test_errorByDefault(self):
3
Source : test_reporter.py
with MIT License
from autofelix
with MIT License
from autofelix
def setUp(self):
self.stream = NativeStringIO()
self.result = reporter.Reporter(self.stream)
self.test = sample.FooTest('test_foo')
def _getSkips(self, result):
3
Source : test_reporter.py
with MIT License
from autofelix
with MIT License
from autofelix
def setUp(self):
self.stream = NativeStringIO()
self.result = reporter.Reporter(self.stream)
self.test = sample.FooTest('test_foo')
def _getTodos(self, result):
3
Source : test_reporter.py
with MIT License
from autofelix
with MIT License
from autofelix
def setUp(self):
self.test = sample.FooTest('test_foo')
self.stream = NativeStringIO()
self.result = reporter.TreeReporter(self.stream)
self.result._colorizer = MockColorizer(self.stream)
self.log = self.result._colorizer.log
def makeError(self):
3
Source : test_reporter.py
with MIT License
from autofelix
with MIT License
from autofelix
def setUp(self):
self.test = sample.FooTest('test_foo')
self.stream = NativeStringIO()
self.publisher = log.LogPublisher()
self.result = self.resultFactory(self.stream, publisher=self.publisher)
def test_shouldStopInitiallyFalse(self):
3
Source : test_reporter.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_safe(self):
"""
Test that L{reporter.SafeStream} successfully write to its original
stream even if an interrupt happens during the write.
"""
stream = NativeStringIO()
broken = BrokenStream(stream)
safe = reporter.SafeStream(broken)
safe.write("Hello")
self.assertEqual(stream.getvalue(), "Hello")
class SubunitReporterTests(ReporterInterfaceTests):
3
Source : test_reporter.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_subunitNotInstalled(self):
"""
If subunit is not installed, TestProtocolClient will be None, and
SubunitReporter will raise an error when you try to construct it.
"""
stream = NativeStringIO()
self.patch(reporter, 'TestProtocolClient', None)
e = self.assertRaises(Exception, reporter.SubunitReporter, stream)
self.assertEqual("Subunit not available", str(e))
class TimingReporterTests(ReporterTests):
3
Source : test_runner.py
with MIT License
from autofelix
with MIT License
from autofelix
def setUp(self):
self.stream = NativeStringIO()
self.runner = runner.TrialRunner(CapturingReporter, stream=self.stream)
self.test = TrialRunnerTests('test_empty')
def test_publisher(self):
3
Source : test_runner.py
with MIT License
from autofelix
with MIT License
from autofelix
def setUp(self):
self.stream = NativeStringIO()
self.runner = runner.TrialRunner(CapturingReporter, stream=self.stream,
uncleanWarnings=True)
self.test = TrialRunnerTests('test_empty')
class DryRunMixin(object):
3
Source : test_runner.py
with MIT License
from autofelix
with MIT License
from autofelix
def setUp(self):
self.log = []
self.stream = NativeStringIO()
self.runner = runner.TrialRunner(CapturingReporter,
runner.TrialRunner.DRY_RUN,
stream=self.stream)
self.makeTestFixtures()
def makeTestFixtures(self):
3
Source : test_runner.py
with MIT License
from autofelix
with MIT License
from autofelix
def getRunner(self):
r = trial._makeRunner(self.config)
r.stream = NativeStringIO()
# XXX The runner should always take care of cleaning this up itself.
# It's not clear why this is necessary. The runner always tears down
# its log file.
self.addCleanup(r._tearDownLogFile)
# XXX The runner should always take care of cleaning this up itself as
# well. It's necessary because TrialRunner._setUpTestdir might raise
# an exception preventing Reporter.done from being run, leaving the
# observer added by Reporter.__init__ still present in the system.
# Something better needs to happen inside
# TrialRunner._runWithoutDecoration to remove the need for this cludge.
r._log = log.LogPublisher()
return r
def test_runner_can_get_reporter(self):
3
Source : test_runner.py
with MIT License
from autofelix
with MIT License
from autofelix
def setUp(self):
UntilFailureTests.FailAfter.count = []
self.test = UntilFailureTests.FailAfter('test_foo')
self.stream = NativeStringIO()
self.runner = runner.TrialRunner(reporter.Reporter, stream=self.stream)
def test_runUntilFailure(self):
3
Source : test_runner.py
with MIT License
from autofelix
with MIT License
from autofelix
def _test(self, method):
"""
Wrapper for one of the test method of L{ContainMalformed}.
"""
stream = NativeStringIO()
trialRunner = runner.TrialRunner(reporter.Reporter, stream=stream)
test = MalformedMethodTests.ContainMalformed(method)
result = trialRunner.run(test)
self.assertEqual(result.testsRun, 1)
self.assertFalse(result.wasSuccessful())
self.assertEqual(len(result.errors), 1)
def test_extraArg(self):
3
Source : test_script.py
with MIT License
from autofelix
with MIT License
from autofelix
def makeRunner(self):
"""
Return a L{TrialRunner} object that is safe to use in tests.
"""
runner = trial._makeRunner(self.config)
runner.stream = NativeStringIO()
return runner
def test_forceGc(self):
3
Source : test_script.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_testmoduleOnNonexistentFile(self):
"""
Check that --testmodule displays a meaningful error message when
passed a non-existent filename.
"""
buffy = NativeStringIO()
stderr, sys.stderr = sys.stderr, buffy
filename = 'test_thisbetternoteverexist.py'
try:
self.config.opt_testmodule(filename)
self.assertEqual(0, len(self.config['tests']))
self.assertEqual("File %r doesn't exist\n" % (filename,),
buffy.getvalue())
finally:
sys.stderr = stderr
def test_testmoduleOnEmptyVars(self):
3
Source : test_script.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_testmoduleOnModuleName(self):
"""
Check that --testmodule does *not* support module names as arguments
and that it displays a meaningful error message.
"""
buffy = NativeStringIO()
stderr, sys.stderr = sys.stderr, buffy
moduleName = 'twisted.trial.test.test_script'
try:
self.config.opt_testmodule(moduleName)
self.assertEqual(0, len(self.config['tests']))
self.assertEqual("File %r doesn't exist\n" % (moduleName,),
buffy.getvalue())
finally:
sys.stderr = stderr
def test_parseLocalVariable(self):
3
Source : test_tests.py
with MIT License
from autofelix
with MIT License
from autofelix
def setUp(self):
"""
Setup our test case
"""
self.result = reporter.Reporter(NativeStringIO())
self.loader = runner.TestLoader()
def test_leftoverSockets(self):
3
Source : test_warning.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_flushed(self):
"""
Any warnings emitted by a test which are flushed are not emitted to the
Python warning system.
"""
result = TestResult()
case = Mask.MockTests('test_flushed')
output = StringIO()
monkey = self.patch(sys, 'stdout', output)
case.run(result)
monkey.restore()
self.assertEqual(output.getvalue(), "")
def test_warningsConfiguredAsErrors(self):
3
Source : test_warning.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_suppresses(self):
"""
Any warnings emitted by a call to a function passed to
L{_collectWarnings} are not actually emitted to the warning system.
"""
output = StringIO()
self.patch(sys, 'stdout', output)
_collectWarnings(lambda x: None, warnings.warn, "text")
self.assertEqual(output.getvalue(), "")
def test_callsFunction(self):
See More Examples