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))
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))
def test_printingSmokeTest(self): """ None of the print* methods fail when called. """ f = getDivisionFailure() out = NativeStringIO() f.printDetailedTraceback(out) self.assertStartsWith(out.getvalue(), '*--- Failure') out = NativeStringIO() f.printBriefTraceback(out) self.assertStartsWith(out.getvalue(), 'Traceback') out = NativeStringIO() f.printTraceback(out) self.assertStartsWith(out.getvalue(), 'Traceback')
def test_printingNoVars(self): """ Calling C{Failure()} with no arguments does not capture any locals or globals, so L{printDetailedTraceback} cannot show them in its output. """ out = NativeStringIO() f = getDivisionFailure() f.printDetailedTraceback(out) # There should be no variables in the detailed output. Variables are # printed on lines with 2 leading spaces. linesWithVars = [line for line in out.getvalue().splitlines() if line.startswith(' ')] self.assertEqual([], linesWithVars) self.assertIn( 'Capture of Locals and Globals disabled', out.getvalue())
def linkList(lst): io = StringIO() io.write("<ul>\n") for hr, el in lst: io.write('<li> <a href="%s">%s</a></li>\n' % (hr, el)) io.write("</ul>") return io.getvalue()
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())
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)
def test_emitPrefix(self): """ FileLogObserver.emit() will add a timestamp and system prefix to its file output. """ output = StringIO() flo = log.FileLogObserver(output) events = [] def observer(event): # Capture the event for reference and pass it along to flo events.append(event) flo.emit(event) publisher = log.LogPublisher() publisher.addObserver(observer) publisher.msg("Hello!") self.assertEqual(len(events), 1) event = events[0] result = output.getvalue() prefix = "{time} [{system}] ".format( time=flo.formatTime(event["time"]), system=event["system"], ) self.assertTrue( result.startswith(prefix), "{0!r} does not start with {1!r}".format(result, prefix) )
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())
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
def UL(lst): io = StringIO() io.write("<ul>\n") for el in lst: io.write("<li> %s</li>\n" % el) io.write("</ul>") return io.getvalue()
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" """)
def test_printingNoVars(self): """ Calling C{Failure()} with no arguments does not capture any locals or globals, so L{printDetailedTraceback} cannot show them in its output. """ out = NativeStringIO() f = getDivisionFailure() f.printDetailedTraceback(out) # There should be no variables in the detailed output. Variables are # printed on lines with 2 leading spaces. linesWithVars = [ line for line in out.getvalue().splitlines() if line.startswith(' ') ] self.assertEqual([], linesWithVars) self.assertIn('Capture of Locals and Globals disabled', out.getvalue())
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
class StdoutAssertionsMixin(object): """ Mix this in to be able to assert on stdout during the test """ def setUpStdoutAssertions(self): self.stdout = NativeStringIO() self.patch(sys, 'stdout', self.stdout) def assertWasQuiet(self): self.assertEqual(self.stdout.getvalue(), '') def assertInStdout(self, exp): self.assertIn(exp, self.stdout.getvalue()) def getStdout(self): return self.stdout.getvalue().strip()
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" """)
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)
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())
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())
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 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 test_nativeStringIO(self): """ L{NativeStringIO} is a file-like object that stores native strings in memory. """ f = NativeStringIO() f.write("hello") f.write(" there") self.assertEqual(f.getvalue(), "hello there")
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(), "")
def test_printingCapturedVarsSmokeTest(self): """ None of the print* methods fail when called on a L{Failure} constructed with C{captureVars=True}. Local variables on the stack can be seen in the detailed traceback. """ exampleLocalVar = 'xyzzy' f = getDivisionFailure(captureVars=True) out = NativeStringIO() f.printDetailedTraceback(out) self.assertStartsWith(out.getvalue(), '*--- Failure') self.assertNotEqual(None, re.search('exampleLocalVar.*xyzzy', out.getvalue())) out = NativeStringIO() f.printBriefTraceback(out) self.assertStartsWith(out.getvalue(), 'Traceback') out = NativeStringIO() f.printTraceback(out) self.assertStartsWith(out.getvalue(), 'Traceback')
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_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())
def test_printingCapturedVarsSmokeTest(self): """ None of the print* methods fail when called on a L{Failure} constructed with C{captureVars=True}. Local variables on the stack can be seen in the detailed traceback. """ exampleLocalVar = 'xyzzy' f = getDivisionFailure(captureVars=True) out = NativeStringIO() f.printDetailedTraceback(out) self.assertStartsWith(out.getvalue(), '*--- Failure') self.assertNotEqual( None, re.search('exampleLocalVar.*xyzzy', out.getvalue())) out = NativeStringIO() f.printBriefTraceback(out) self.assertStartsWith(out.getvalue(), 'Traceback') out = NativeStringIO() f.printTraceback(out) self.assertStartsWith(out.getvalue(), 'Traceback')
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())
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()
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")
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_printingCapturedVarsCleanedSmokeTest(self): """ C{printDetailedTraceback} includes information about local variables on the stack after C{cleanFailure} has been called. """ exampleLocalVar = 'xyzzy' f = getDivisionFailure(captureVars=True) f.cleanFailure() out = NativeStringIO() f.printDetailedTraceback(out) self.assertNotEqual(None, re.search('exampleLocalVar.*xyzzy', out.getvalue()))
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_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_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 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()
def test_printingCapturedVarsCleanedSmokeTest(self): """ C{printDetailedTraceback} includes information about local variables on the stack after C{cleanFailure} has been called. """ exampleLocalVar = 'xyzzy' f = getDivisionFailure(captureVars=True) f.cleanFailure() out = NativeStringIO() f.printDetailedTraceback(out) self.assertNotEqual( None, re.search('exampleLocalVar.*xyzzy', out.getvalue()))
def test_printingCaptureVars(self): """ Calling C{Failure(captureVars=True)} captures the locals and globals for its stack frames, so L{printDetailedTraceback} will show them in its output. """ out = NativeStringIO() f = getDivisionFailure(captureVars=True) f.printDetailedTraceback(out) # Variables are printed on lines with 2 leading spaces. linesWithVars = [line for line in out.getvalue().splitlines() if line.startswith(' ')] self.assertNotEqual([], linesWithVars)
def _safeFormat(formatter, o): """ Helper function for L{safe_repr} and L{safe_str}. """ try: return formatter(o) except: io = NativeStringIO() traceback.print_exc(file=io) className = _determineClassName(o) tbValue = io.getvalue() return "<%s instance at 0x%x with %s error:\n %s>" % ( className, unsignedID(o), formatter.__name__, tbValue)
def _safeFormat(formatter, o): """ Helper function for L{safe_repr} and L{safe_str}. """ try: return formatter(o) except: io = NativeStringIO() traceback.print_exc(file=io) className = _determineClassName(o) tbValue = io.getvalue() return "<%s instance at 0x%x with %s error:\n %s>" % ( className, id(o), formatter.__name__, tbValue)
def test_startLoggingOverridesWarning(self): """ startLogging() overrides global C{warnings.showwarning} such that warnings go to Twisted log observers. """ self._startLoggingCleanup() # Ugggh, pretend we're starting from newly imported module: log._oldshowwarning = None fakeFile = StringIO() observer = log.startLogging(fakeFile) self.addCleanup(observer.stop) warnings.warn("hello!") output = fakeFile.getvalue() self.assertIn("UserWarning: hello!", output)
def test_startLoggingOverridesWarning(self): """ startLogging() overrides global C{warnings.showwarning} such that warnings go to Twisted log observers. """ self._startLoggingCleanup() newPublisher = NewLogPublisher() class SysModule(object): stdout = object() stderr = object() tempLogPublisher = LogPublisher( newPublisher, newPublisher, logBeginner=LogBeginner(newPublisher, StringIO(), SysModule, warnings) ) # Trial reports warnings in two ways. First, it intercepts the global # 'showwarning' function *itself*, after starting logging (by way of # the '_collectWarnings' function which collects all warnings as a # around the test's 'run' method). Second, it has a log observer which # immediately reports warnings when they're propagated into the log # system (which, in normal operation, happens only at the end of the # test case). In order to avoid printing a spurious warning in this # test, we first replace the global log publisher's 'showwarning' in # the module with our own. self.patch(log, "theLogPublisher", tempLogPublisher) # And, one last thing, pretend we're starting from a fresh import, or # warnings.warn won't be patched at all. log._oldshowwarning = None # Global mutable state is bad, kids. Stay in school. fakeFile = StringIO() # We didn't previously save log messages, so let's make sure we don't # save them any more. evt = {"pre-start": "event"} received = [] def preStartObserver(x): if 'pre-start' in x.keys(): received.append(x) newPublisher(evt) newPublisher.addObserver(preStartObserver) log.startLogging(fakeFile, setStdout=False) self.addCleanup(tempLogPublisher._stopLogging) self.assertEqual(received, []) warnings.warn("hello!") output = fakeFile.getvalue() self.assertIn("UserWarning: hello!", output)