Here are the examples of the python api sys.stdout.getvalue taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
137 Examples
3
Example 51
Project: numba Source File: test_print.py
@tag('important')
def test_print_multiple_values(self):
pyfunc = print_values
cr = compile_isolated(pyfunc, (types.int32,) * 3)
cfunc = cr.entry_point
with captured_stdout():
cfunc(1, 2, 3)
self.assertEqual(sys.stdout.getvalue(), '1 2 3\n')
3
Example 52
@mock.patch('sys.argv', ['nova'])
@mock.patch('sys.stdout', six.StringIO())
@mock.patch('sys.stderr', six.StringIO())
def test_main_noargs(self):
# Ensure that main works with no command-line arguments
try:
novaclient.shell.main()
except SystemExit:
self.fail('Unexpected SystemExit')
# We expect the normal usage as a result
self.assertIn('Command-line interface to the OpenStack Nova API',
sys.stdout.getvalue())
3
Example 53
Project: ansible Source File: test_exit_json.py
def test_exit_json_removes_values(self):
self.maxDiff = None
for args, return_val, expected in self.dataset:
params = dict(ANSIBLE_MODULE_ARGS=args)
params = json.dumps(params)
with swap_stdin_and_argv(stdin_data=params):
with swap_stdout():
basic._ANSIBLE_ARGS = None
module = basic.AnsibleModule(
argument_spec = dict(
username=dict(),
password=dict(no_log=True),
token=dict(no_log=True),
),
)
with self.assertRaises(SystemExit) as ctx:
self.assertEquals(module.exit_json(**return_val), expected)
self.assertEquals(json.loads(sys.stdout.getvalue()), expected)
3
Example 54
Project: inselect Source File: test_save_crops.py
def test_save_crops_with_existing(self):
"Attempt to save crops over an existing directory"
with temp_directory_with_files(TESTDATA / 'shapes.inselect',
TESTDATA / 'shapes.png') as tempdir:
# Create crops dir
crops = tempdir / 'shapes_crops'
crops.mkdir()
main([unicode(tempdir)])
# nose hooks up stdout to a file-like object
stdout = sys.stdout.getvalue()
self.assertIn('exists - skipping', stdout)
3
Example 55
Project: expyre Source File: test_main.py
def test_correct_invocation_get_scheduled_jobs(self):
with mock.patch('expyre.__main__.get_scheduled_jobs', return_value={'/path/to/file':self.dummy_job}) as mocked:
main(['--list'])
self.assertTrue(mocked.called)
self.assertSequenceEqual('/path/to/file scheduled to expire at {0:%F %R} \n'.format(self.dummy_job.timestamp),
sys.stdout.getvalue())
3
Example 56
@mock.patch('sys.argv', ['magnum'])
@mock.patch('sys.stdout', six.StringIO())
@mock.patch('sys.stderr', six.StringIO())
def test_main_noargs(self):
# Ensure that main works with no command-line arguments
try:
magnumclient.shell.main()
except SystemExit:
self.fail('Unexpected SystemExit')
# We expect the normal usage as a result
self.assertIn('Command-line interface to the OpenStack Magnum API',
sys.stdout.getvalue())
3
Example 57
Project: packstack Source File: test_sequences.py
def test_run(self):
"""
Test packstack.instaler.core.sequences.Step run.
"""
def func(config, messages):
if 'test' not in config:
raise AssertionError('Missing config value.')
step = Step('test', func, title='Running test')
step.run(config={'test': 'test'})
contents = sys.stdout.getvalue()
state = '[ %s ]\n' % utils.color_text('DONE', 'green')
if(not contents.startswith('Running test') or
not contents.endswith(state)):
raise AssertionError('Step run test failed: %s' % contents)
3
Example 58
Project: cyg-apt Source File: test_ob.py
def makeOn(self):
txt = "TestOb.makeOn ";
print(txt, end="");
value = sys.stdout.getvalue();
self.assertTrue(value.endswith(txt));
self.assertTrue(self.obj._state);
3
Example 59
Project: python-novaclient Source File: test_utils.py
@mock.patch('sys.stdout', six.StringIO())
def test_print_list_sort_by_integer(self):
objs = [_FakeResult("k1", 1),
_FakeResult("k3", 2),
_FakeResult("k2", 3)]
utils.print_list(objs, ["Name", "Value"], sortby_index=1)
self.assertEqual('+------+-------+\n'
'| Name | Value |\n'
'+------+-------+\n'
'| k1 | 1 |\n'
'| k3 | 2 |\n'
'| k2 | 3 |\n'
'+------+-------+\n',
sys.stdout.getvalue())
3
Example 60
Project: simple-db-migrate Source File: run_test.py
def test_it_should_print_error_message_and_exit_when_required_info_is_not_valid(self):
try:
simple_db_migrate.run_from_argv(["--info", "not_valid", "-c", os.path.abspath('sample.conf')])
except SystemExit as e:
self.assertEqual(1, e.code)
self.assertEqual("[ERROR] The 'not_valid' is a wrong parameter for info\n\n", sys.stdout.getvalue())
3
Example 61
def test_runs(self):
# lame test...does it run?
n = Name(name='Gabriel')
n.save()
call_command('dumpscript', 'tests')
self.assertTrue('Gabriel' in sys.stdout.getvalue())
3
Example 62
Project: pyscard Source File: test_ATR.py
def test_ATR1(self):
atr = [0x3F, 0x65, 0x25, 0x00, 0x2C, 0x09, 0x69, 0x90, 0x00]
data_out = """TB1: 25
TC1: 0
supported protocols T=0
T=0 supported: True
T=1 supported: False
clock rate conversion factor: 372
bit rate adjustment factor: 1
maximum programming current: 50
programming voltage: 30
guard time: 0
nb of interface bytes: 2
nb of historical bytes: 5
"""
a = ATR(atr)
a.dump()
output = sys.stdout.getvalue()
self.assertEqual(output, data_out)
3
Example 63
Project: gsync Source File: test_output.py
def test_exception_as_object(self):
channel = Debug()
channel.enable()
self.assertTrue(channel.enabled())
import re
pat = re.compile(
r'''^DEBUG: Exception\('Test exception',\): ''',
re.M | re.S
)
try:
raise Exception("Test exception")
except Exception, e:
channel.exception(e)
self.assertIsNotNone(pat.search(sys.stdout.getvalue()))
self.assertEqual("", sys.stderr.getvalue())
3
Example 64
def test_print(self):
"""
Test re-implementing print() for a custom type with @overload.
"""
cfunc = jit(nopython=True)(print_usecase)
with captured_stdout():
cfunc(MyDummy())
self.assertEqual(sys.stdout.getvalue(), "hello!\n")
3
Example 65
Project: gsync Source File: test_output.py
def test_exception_as_default(self):
channel = Debug()
channel.enable()
self.assertTrue(channel.enabled())
import re
pat = re.compile(
r'''^DEBUG: 'Exception': ''',
re.M | re.S
)
try:
raise Exception("Test exception")
except Exception, e:
channel.exception()
self.assertIsNotNone(pat.search(sys.stdout.getvalue()))
self.assertEqual("", sys.stderr.getvalue())
3
Example 66
Project: osprofiler Source File: test_shell.py
@mock.patch("sys.stdout", six.StringIO())
@mock.patch("osprofiler.cmd.shell.OSProfilerShell")
def test_shell_main(self, mock_shell):
mock_shell.side_effect = exc.CommandError("some_message")
shell.main()
self.assertEqual("some_message\n", sys.stdout.getvalue())
3
Example 67
Project: django-jenkins Source File: runner.py
def stopTest(self, test):
if self.buffer:
output = sys.stdout.getvalue() if hasattr(sys.stdout, 'getvalue') else ''
if output:
sysout = ET.SubElement(self.testcase, 'system-out')
sysout.text = smart_text(output, errors='ignore')
error = sys.stderr.getvalue() if hasattr(sys.stderr, 'getvalue') else ''
if error:
syserr = ET.SubElement(self.testcase, 'system-err')
syserr.text = smart_text(error, errors='ignore')
super(EXMLTestResult, self).stopTest(test)
3
Example 68
Project: python-glanceclient Source File: test_shell.py
@mock.patch('sys.argv', ['glance'])
@mock.patch('sys.stdout', six.StringIO())
@mock.patch('sys.stderr', six.StringIO())
def test_main_noargs(self):
# Ensure that main works with no command-line arguments
try:
openstack_shell.main()
except SystemExit:
self.fail('Unexpected SystemExit')
# We expect the normal v2 usage as a result
expected = ['Command-line interface to the OpenStack Images API',
'image-list',
'image-deactivate',
'location-add']
for output in expected:
self.assertIn(output,
sys.stdout.getvalue())
3
Example 69
Project: Surveilr Source File: test_admin.py
def test_unauthorized_error(self):
self._replace_stdout_with_stringio()
self._define_test_cmd()
ret = admin.main(['Foo', '-r'])
self.assertFalse(ret)
self.assertEquals(sys.stdout.getvalue(),
'Action not permitted\n')
3
Example 70
Project: python-novaclient Source File: test_utils.py
@mock.patch('sys.stdout', six.StringIO())
def test_print_dict_wrap(self):
dict = {'key1': 'not wrapped',
'key2': 'this will be wrapped'}
utils.print_dict(dict, wrap=16)
self.assertEqual('+----------+--------------+\n'
'| Property | Value |\n'
'+----------+--------------+\n'
'| key1 | not wrapped |\n'
'| key2 | this will be |\n'
'| | wrapped |\n'
'+----------+--------------+\n',
sys.stdout.getvalue())
3
Example 71
Project: Surveilr Source File: test_admin.py
def test_cmd_list_if_invalid_command_given(self):
self._replace_stdout_with_stringio()
ret = admin.main(['this is not a valid command'])
self.assertEquals(ret, False)
stdout = sys.stdout.getvalue()
self._check_cmd_list(stdout)
3
Example 72
Project: expyre Source File: test_main.py
def test_correct_invocation_remove_from_schedule_multiple_paths(self):
with mock.patch('expyre.__main__.remove_from_schedule', return_value=[['/path/to/file1'], ['/path/to/file2']]) as mocked:
main('--reset /path/to/file1 /path/to/file2'.split())
mocked.assert_called_with(['/path/to/file1', '/path/to/file2'])
self.assertSequenceEqual('Successfully removed these paths from expiry list:\n'
'/path/to/file1\n'
'Failed to remove these paths from expiry list:\n'
'/path/to/file2\n',
sys.stdout.getvalue())
3
Example 73
Project: python-novaclient Source File: test_utils.py
@mock.patch('sys.stdout', six.StringIO())
def test_print_dict(self):
dict = {'key': 'value'}
utils.print_dict(dict)
self.assertEqual('+----------+-------+\n'
'| Property | Value |\n'
'+----------+-------+\n'
'| key | value |\n'
'+----------+-------+\n',
sys.stdout.getvalue())
3
Example 74
Project: expyre Source File: test_main.py
def test_correct_invocation_get_scheduled_jobs_multiple(self):
now = datetime.now()
later = datetime.now()+timedelta(hours=2)
earlier = datetime.now()-timedelta(hours=2)
jobs = {'/path/to/second': JobSpec(0, '/path/to/second', now, ''),
'/path/to/last': JobSpec(1, '/path/to/last', later, ''),
'/path/to/first': JobSpec(2, '/path/to/first', earlier, '')
}
self.maxDiff = None
with mock.patch('expyre.__main__.get_scheduled_jobs', return_value=jobs) as mocked:
main(['--list'])
self.assertTrue(mocked.called)
self.assertSequenceEqual(
('/path/to/first scheduled to expire at {0:%F %R} \n'
'/path/to/second scheduled to expire at {1:%F %R} \n'
'/path/to/last scheduled to expire at {2:%F %R} \n').format(earlier, now, later),
sys.stdout.getvalue())
3
Example 75
def test_input(self):
player = Player("julie", "f")
with WrappedConsoleIO(None) as io:
pc = PlayerConnection(player, io)
player.tell("first this text")
player.store_input_line(" input text \n")
x = pc.input_direct("inputprompt")
self.assertEqual("input text", x)
self.assertEqual(" first this text\ninputprompt ", sys.stdout.getvalue()) # should have outputted the buffered text
3
Example 76
Project: pyscard Source File: test_ATR.py
def test_ATR4(self):
atr = [0x3B, 0x65, 0x00, 0x00, 0x9C, 0x11, 0x01, 0x01, 0x03]
data_out = """TB1: 0
TC1: 0
supported protocols T=0
T=0 supported: True
T=1 supported: False
clock rate conversion factor: 372
bit rate adjustment factor: 1
maximum programming current: 25
programming voltage: 5
guard time: 0
nb of interface bytes: 2
nb of historical bytes: 5
"""
a = ATR(atr)
a.dump()
output = sys.stdout.getvalue()
self.assertEqual(output, data_out)
3
Example 77
Project: pyscard Source File: test_ATR.py
def test_ATR2(self):
atr = [0x3F, 0x65, 0x25, 0x08, 0x93, 0x04, 0x6C, 0x90, 0x00]
data_out = """TB1: 25
TC1: 8
supported protocols T=0
T=0 supported: True
T=1 supported: False
clock rate conversion factor: 372
bit rate adjustment factor: 1
maximum programming current: 50
programming voltage: 30
guard time: 8
nb of interface bytes: 2
nb of historical bytes: 5
"""
a = ATR(atr)
a.dump()
output = sys.stdout.getvalue()
self.assertEqual(output, data_out)
3
Example 78
Project: gsync Source File: test_output.py
def test_output_when_enabled(self):
channel = Channel()
channel.enable()
self.assertTrue(channel.enabled())
channel("Hello World")
self.assertEqual("Hello World\n", sys.stdout.getvalue())
self.assertEqual("", sys.stderr.getvalue())
3
Example 79
Project: inselect Source File: test_export_metadata.py
def test_export_csv_with_template(self):
"Export metadata to CSV using a metadata template"
with temp_directory_with_files(TESTDATA / 'shapes.inselect',
TESTDATA / 'shapes.png') as tempdir:
main([unicode(tempdir),
u'--template={0}'.format(TESTDATA / 'test.inselect_template')])
# nose hooks up stdout to a file-like object
stdout = sys.stdout.getvalue()
self.assertIn('because there are validation problems', stdout)
self.assertIn('Box [1] [0001] lacks mandatory field [Taxonomy]', stdout)
self.assertIn('Box [1] [0001] lacks mandatory field [Location]', stdout)
self.assertIn(
'Could not parse value of [catalogNumber] [1] for box [1] [0001]',
stdout
)
csv = tempdir / 'shapes.csv'
self.assertFalse(csv.is_file())
3
Example 80
Project: Surveilr Source File: test_admin.py
def test_cmd_list_if_no_command_given(self):
self._replace_stdout_with_stringio()
ret = admin.main([])
self.assertEquals(ret, False)
stdout = sys.stdout.getvalue()
self._check_cmd_list(stdout)
3
Example 81
Project: inselect Source File: test_save_crops.py
def test_save_crops_with_template(self):
"Save crops using a metadata template"
with temp_directory_with_files(TESTDATA / 'shapes.inselect',
TESTDATA / 'shapes.png') as tempdir:
main([unicode(tempdir),
u'--template={0}'.format(TESTDATA / 'test.inselect_template')])
# nose hooks up stdout to a file-like object
stdout = sys.stdout.getvalue()
self.assertIn('because there are validation problems', stdout)
self.assertIn('Box [1] [0001] lacks mandatory field [Taxonomy]', stdout)
self.assertIn('Box [1] [0001] lacks mandatory field [Location]', stdout)
self.assertIn(
'Could not parse value of [catalogNumber] [1] for box [1] [0001]',
stdout
)
crops = tempdir / 'shapes_crops'
self.assertFalse(crops.is_dir())
3
Example 82
Project: gsync Source File: test_output.py
def test_exception_as_string(self):
channel = Debug()
channel.enable()
self.assertTrue(channel.enabled())
import re
pat = re.compile(
r'''^DEBUG: 'Test exception': ''',
re.M | re.S
)
try:
raise Exception("Test exception")
except Exception, e:
channel.exception(str(e))
self.assertIsNotNone(pat.search(sys.stdout.getvalue()))
self.assertEqual("", sys.stderr.getvalue())
3
Example 83
Project: osprofiler Source File: test_shell.py
@mock.patch("sys.stdout", six.StringIO())
@mock.patch("osprofiler.drivers.ceilometer.Ceilometer.get_report")
def test_trace_show_in_json(self, mock_get):
notifications = {
"info": {
"started": 0, "finished": 0, "name": "total"}, "children": []}
mock_get.return_value = notifications
self.run_command("trace show fake_id --json")
self.assertEqual("%s\n" % json.dumps(notifications),
sys.stdout.getvalue())
3
Example 84
Project: expyre Source File: test_main.py
def test_correct_invocation_remove_from_schedule_single_path(self):
with mock.patch('expyre.__main__.remove_from_schedule', return_value=[['/path/to/file'], []]) as mocked:
main(['--reset', '/path/to/file'])
mocked.assert_called_with(['/path/to/file'])
self.assertSequenceEqual('Successfully removed these paths from expiry list:\n'
'/path/to/file\n',
sys.stdout.getvalue())
3
Example 85
Project: Tale Source File: test_player.py
def test_write_output(self):
player = Player("julie", "f")
with WrappedConsoleIO(None) as io:
pc = PlayerConnection(player, io)
player.tell("hello 1", end=True)
player.tell("hello 2", end=True)
pc.write_output()
self.assertEqual(" hello 2", pc.last_output_line)
self.assertEqual(" hello 1\n hello 2\n", sys.stdout.getvalue())
3
Example 86
Project: pyscard Source File: test_ATR.py
def test_ATR3(self):
atr = [0x3B, 0x16, 0x94, 0x7C, 0x03, 0x01, 0x00, 0x00, 0x0D]
data_out = """TA1: 94
supported protocols T=0
T=0 supported: True
T=1 supported: False
clock rate conversion factor: 512
bit rate adjustment factor: 8
maximum programming current: 50
programming voltage: 5
guard time: None
nb of interface bytes: 1
nb of historical bytes: 6
"""
a = ATR(atr)
a.dump()
output = sys.stdout.getvalue()
self.assertEqual(output, data_out)
2
Example 87
Project: numba Source File: test_print.py
@tag('important')
def test_print_values(self):
"""
Test printing a single argument value.
"""
pyfunc = print_value
def check_values(typ, values):
cr = compile_isolated(pyfunc, (typ,))
cfunc = cr.entry_point
for val in values:
with captured_stdout():
cfunc(val)
self.assertEqual(sys.stdout.getvalue(), str(val) + '\n')
# Various scalars
check_values(types.int32, (1, -234))
check_values(types.int64, (1, -234,
123456789876543210, -123456789876543210))
check_values(types.uint64, (1, 234,
123456789876543210, 2**63 + 123))
check_values(types.boolean, (True, False))
check_values(types.float64, (1.5, 100.0**10.0, float('nan')))
check_values(types.complex64, (1+1j,))
check_values(types.NPTimedelta('ms'), (np.timedelta64(100, 'ms'),))
cr = compile_isolated(pyfunc, (types.float32,))
cfunc = cr.entry_point
with captured_stdout():
cfunc(1.1)
# Float32 will lose precision
got = sys.stdout.getvalue()
expect = '1.10000002384'
self.assertTrue(got.startswith(expect))
self.assertTrue(got.endswith('\n'))
# NRT-enabled type
with self.assertNoNRTLeak():
x = [1, 3, 5, 7]
with self.assertRefCount(x):
check_values(types.List(types.int32), (x,))
# Array will have to use object mode
arraytype = types.Array(types.int32, 1, 'C')
cr = compile_isolated(pyfunc, (arraytype,), flags=enable_pyobj_flags)
cfunc = cr.entry_point
with captured_stdout():
cfunc(np.arange(10))
self.assertEqual(sys.stdout.getvalue(),
'[0 1 2 3 4 5 6 7 8 9]\n')
2
Example 88
Project: bitcurator Source File: bc_disk_access.py
def bcOperateOnFiles(self, check, exportDir):
## print(">>D: Length of fiDictList: ", len(self.fiDictList))
global g_breakout
g_breakout = False
for i in range(0, len(self.fiDictList) - 1):
path = self.fiDictList[i]['filename']
inode = self.fiDictList[i]['inode']
if self.fiDictList[i]['name_type'] == 'd':
isdir = True
else:
isdir = False
pathlist = path.split('/')
pathlen = len(pathlist)
## print("D: Path List: ", pathlist, len(pathlist))
last_elem = pathlist[pathlen-1]
if last_elem == "." or last_elem == "..":
# Ignore . and ..
continue
if isdir == False:
# First get the name of the current file
current_fileordir = pathlist[pathlen-1]
# Now using the dict of files, file_item_of, get the item for this file
unique_path = path + '-' + str(inode)
current_item = self.file_item_of[unique_path]
if check == 1:
if (current_item.checkState() == 0):
## print("D: Setting File to Checked_state ", current_fileordir)
current_item.setCheckState(2)
elif check == 0:
current_item.setCheckState(0)
elif check == 2:
if g_breakout == True:
break
# If "check" is 2, we use this routine to dump the
# contents of the specified file to the specified output file.
# If this file is "checked", download its contents.
# item.checkState has 0 if not checked, 1 if partially
# checked and 2 if checked.
# http://qt.developpez.com/doc/4.6/qt/#checkstate-enum
if current_item.checkState() == 2:
## print(">> D: File %s is Checked" %current_fileordir)
if not os.path.exists(exportDir):
os.mkdir(exportDir)
pathlist = path.split('/')
oldDir = newDir = exportDir
# Iterate through the path list and make the directories
# in the path, if they don't already exist.
for k in range(0, len(pathlist)-1):
newDir = oldDir + '/' + pathlist[k]
if not os.path.exists(newDir):
os.mkdir(newDir)
oldDir = newDir
outfile = newDir + '/'+current_fileordir
## print(">> D: Writing to Outfile: ", outfile, path)
filestr.bcCatFile(path, inode, g_image, g_dfxmlfile, True, outfile)
elif current_item.checkState() == 1:
print("Partially checked state: ",current_item.checkState())
print("File %s is NOT Checked" %current_fileordir)
# FIXME: Test the above debug print stmts
g_textEdit.setText( sys.stdout.getvalue() )
sys.stdout = x.oldstdout
elif check == 3:
# Dump the first checked File in textEdit window
if current_item.checkState() == 2:
print(">> D: File %s is Checked" %current_fileordir)
self.oldstdout = sys.stdout
sys.stdout = StringIO()
## print("D: >> Dumping the contents of the file ", path)
## FIXME: Not tested with inode yet.
filestr.bcCatFile(path, inode, g_image, g_dfxmlfile, False, None)
g_textEdit.setText( sys.stdout.getvalue() )
sys.stdout = self.oldstdout
# We list only the first checked file.
return
elif current_item.checkState() == 1:
print("Partially checked state: ",current_item.checkState())
print("File %s is NOT Checked" %current_fileordir)
g_textEdit.setText( sys.stdout.getvalue() )
sys.stdout = self.oldstdout
2
Example 89
Project: bitcurator Source File: bc_disk_access.py
def bcExtractFileStr(self, image, dfxmlfile, outdir):
x = Ui_MainWindow
### Following 4 lines added for debugging
global g_textEdit
g_textEdit.append( sys.stdout.getvalue() )
x.oldstdout = sys.stdout
sys.stdout = StringIO()
# Extract the information from dfxml file to create the
# dictionary only if it is not done before.
if len(self.fiDictList) == 0:
self.bcProcessDfxmlFileUsingSax(dfxmlfile)
## print("D: Length of dictionary fiDictList: ", len(self.fiDictList))
parent0 = image
parent0_item = QtGui.QStandardItem('Disk Image: {}'.format(image))
current_fileordir = image
parent_dir_item = parent0_item
font = QtGui.QFont("Times",12,QtGui.QFont.Bold)
parent_dir_item.setFont(font)
global g_image
global g_dfxmlfile
g_image = re.escape(image)
g_dfxmlfile = dfxmlfile
# A dictionary item_of{} is maintained which contains each file/
# directory and its corresponding " tree item" as its value.
item_of = dict()
item_of[image] = parent0_item
global g_model
g_model.appendRow(parent0_item)
for i in range(0, len(self.fiDictList) - 1):
path = self.fiDictList[i]['filename']
inode = self.fiDictList[i]['inode']
## print("D: path, inode: ", path, inode)
isdir = False
if self.fiDictList[i]['name_type'] == 'd':
isdir = True
deleted = False
if self.fiDictList[i]['alloc'] == False:
deleted = True
pathlist = path.split('/')
pathlen = len(pathlist)
## print("D: Path LiSt: ", pathlist, len(pathlist))
last_elem = pathlist[pathlen-1]
if last_elem == "." or last_elem == "..":
# Ignore . and ..
continue
if isdir == True:
## print("D: It is a Directory: Pathlen: ", pathlen)
if (pathlen < 2):
# If pathlen is < 2 it is a file/dir directly off the root.
parent_dir_item = parent0_item
else:
parent_dir_item = item_of[pathlist[pathlen-2]]
current_dir = pathlist[pathlen-1]
current_item = QtGui.QStandardItem(current_dir)
font = QtGui.QFont("Times",12,QtGui.QFont.Bold)
current_item.setFont(font)
# Add the directory item to the tree.
parent_dir_item.appendRow(current_item)
# DEBUG: Following 2 lines are added for debugging
g_textEdit.append(sys.stdout.getvalue() )
sys.stdout = x.oldstdout
# Save the item of this directory
item_of[current_dir] = current_item
else:
# File: The file could be in any level - top level is the
# child of parent0_item (disk img). The level is sensed by the
# pathlen
current_fileordir = pathlist[pathlen-1]
unique_current_file = current_fileordir + '-' + str(inode)
current_item = QtGui.QStandardItem(unique_current_file)
## print("D: Found a file: ", current_fileordir, current_item)
## print("D: Path length: ", pathlen)
# We want just the filename in the GUI - without the inode
current_item.setText(current_fileordir)
g_textEdit.append( sys.stdout.getvalue() )
sys.stdout = x.oldstdout
current_item.setCheckable(True)
current_item.setCheckState(0)
if deleted == True:
current_item.setForeground(QtGui.QColor('red'))
# Save the "item" of each file
unique_path = path + '-' + str(inode)
self.file_item_of[unique_path] = current_item
if pathlen > 1:
parent_dir_item = item_of[pathlist[pathlen-2]]
else:
parent_dir_item = parent0_item
# Add the directory item to the tree.
parent_dir_item.appendRow(current_item)
parent = parent_dir_item
# DEEBUG: The following 2 lines are added for debugging
g_textEdit.append( sys.stdout.getvalue() )
sys.stdout = x.oldstdout
2
Example 90
def test_run(self):
"""
Test packstack.instaler.core.sequences.Sequence run.
"""
self.seq.run()
contents = sys.stdout.getvalue()
self.assertEqual(contents, '')
self.seq.run(config={'test': 'test'}, step='2')
contents = sys.stdout.getvalue()
assert contents.startswith('Step 2')
output = []
self.steps.insert(0, {'title': 'Step 2'})
for i in self.steps:
output.append('%s\n' % utils.state_message(i['title'],
'DONE', 'green'))
self.seq.run(config={'test': 'test'})
contents = sys.stdout.getvalue()
self.assertEqual(contents, ''.join(output))
2
Example 91
def test_command_decorator_with_additional_options(self):
manager = Manager(self.app)
@manager.option('-n', '--name', dest='name', help='Your name')
def hello(name):
print "hello", name
assert 'hello' in manager._commands
manager.handle("manage.py", "hello", ["--name=joe"])
assert 'hello joe' in sys.stdout.getvalue()
try:
manager.handle("manage.py", "hello", ["-h"])
except SystemExit:
pass
assert "Your name" in sys.stdout.getvalue()
@manager.option('-n', '--name', dest='name', help='Your name')
@manager.option('-u', '--url', dest='url', help='Your URL')
def hello_again(name, url=None):
if url:
print "hello", name, "from", url
else:
print "hello", name
assert 'hello_again' in manager._commands
manager.handle("manage.py", "hello_again", ["--name=joe"])
assert 'hello joe' in sys.stdout.getvalue()
manager.handle("manage.py", "hello_again",
["--name=joe", "--url=reddit.com"])
assert 'hello joe from reddit.com' in sys.stdout.getvalue()
0
Example 92
def _exc_info_to_string(self, err, test):
"""Converts a sys.exc_info()-style tuple of values into a string."""
exctype, value, tb = err
# Skip test runner traceback levels
while tb and self._is_relevant_tb_level(tb):
tb = tb.tb_next
if exctype is test.failureException:
# Skip assert*() traceback levels
length = self._count_relevant_tb_levels(tb)
msgLines = traceback.format_exception(exctype, value, tb, length)
else:
msgLines = traceback.format_exception(exctype, value, tb)
if self.buffer:
output = sys.stdout.getvalue()
error = sys.stderr.getvalue()
if output:
if not output.endswith('\n'):
output += '\n'
msgLines.append(STDOUT_LINE % output)
if error:
if not error.endswith('\n'):
error += '\n'
msgLines.append(STDERR_LINE % error)
return ''.join(msgLines)
0
Example 93
def complete_run(self):
"""called when finshed running all tasks"""
# restore stdout
log_out = sys.stdout.getvalue()
sys.stdout = self._old_out
log_err = sys.stderr.getvalue()
sys.stderr = self._old_err
# add errors together with stderr output
if self.errors:
log_err += "\n".join(self.errors)
task_result_list = [
tr.to_dict() for tr in self.t_results.values()]
json_data = {'tasks': task_result_list,
'out': log_out,
'err': log_err}
# indent not available on simplejson 1.3 (debian etch)
# json.dump(json_data, sys.stdout, indent=4)
json.dump(json_data, self.outstream)
0
Example 94
def run(self, test):
"""Run the given test case or test suite."""
class_ = test.__class__
classname = class_.__module__ + "." + class_.__name__
result = _XMLTestResult(classname)
start_time = time.time()
with _fake_std_streams():
test(result)
try:
out_s = sys.stdout.getvalue()
except AttributeError:
out_s = ""
try:
err_s = sys.stderr.getvalue()
except AttributeError:
err_s = ""
time_taken = time.time() - start_time
result.print_report(self._stream, self._logs_stream, time_taken, out_s, err_s)
return result
0
Example 95
def _restoreStdout(self):
if self.buffer:
if self._mirrorOutput:
output = sys.stdout.getvalue()
error = sys.stderr.getvalue()
if output:
if not output.endswith('\n'):
output += '\n'
self._original_stdout.write(STDOUT_LINE % output)
if error:
if not error.endswith('\n'):
error += '\n'
self._original_stderr.write(STDERR_LINE % error)
sys.stdout = self._original_stdout
sys.stderr = self._original_stderr
self._stdout_buffer.seek(0)
self._stdout_buffer.truncate()
self._stderr_buffer.seek(0)
self._stderr_buffer.truncate()
0
Example 96
Project: pygogo Source File: test_main.py
def test_structured_formatter(self):
console_msg = {
'snowman': '\u2603', 'name': 'structured_formatter.base',
'level': 'INFO', 'message': 'log message', 'time': '20...',
'msecs': '...', 'set_value': [1, 2, 3]}
log_format = gogo.formatters.BASIC_FORMAT
skwargs = {'datefmt': '%Y'}
formatter = gogo.formatters.StructuredFormatter(log_format, **skwargs)
kwargs = {'low_level': 'info', 'low_formatter': formatter}
logger = gogo.Gogo('structured_formatter', **kwargs).logger
extra = {'set_value': set([1, 2, 3]), 'snowman': '\u2603'}
logger.info('log message', extra=extra)
result = loads(sys.stdout.getvalue())
result['msecs'] = str(result['msecs'])
keys = sorted(result.keys())
nt.assert_equal(sorted(console_msg.keys()), keys)
whitelist = {'msecs', 'time'}
for k in keys:
f = nt.assert_equal_ellipsis if k in whitelist else nt.assert_equal
f(console_msg[k], result[k])
0
Example 97
def stopTest(self, test):
"""Called when the given test has been run"""
if self.buffer:
if self._mirrorOutput:
output = sys.stdout.getvalue()
error = sys.stderr.getvalue()
if output:
if not output.endswith('\n'):
output += '\n'
self._original_stdout.write(STDOUT_LINE % output)
if error:
if not error.endswith('\n'):
error += '\n'
self._original_stderr.write(STDERR_LINE % error)
sys.stdout = self._original_stdout
sys.stderr = self._original_stderr
self._stdout_buffer.seek(0)
self._stdout_buffer.truncate()
self._stderr_buffer.seek(0)
self._stderr_buffer.truncate()
self._mirrorOutput = False
0
Example 98
def stopTest(self, test):
"""Called when the given test has been run"""
if self.buffer:
if self._mirrorOutput:
output = sys.stdout.getvalue()
error = sys.stderr.getvalue()
if output:
if not output.endswith('\n'):
output += '\n'
self._original_stdout.write(STDOUT_LINE % output)
if error:
if not error.endswith('\n'):
error += '\n'
self._original_stderr.write(STDERR_LINE % error)
sys.stdout = self._original_stdout
sys.stderr = self._original_stderr
self._stdout_buffer.seek(0)
self._stdout_buffer.truncate()
self._stderr_buffer.seek(0)
self._stderr_buffer.truncate()
self._mirrorOutput = False
0
Example 99
def _exc_info_to_string(self, err, test):
"""Converts a sys.exc_info()-style tuple of values into a string."""
exctype, value, tb = err
# Skip test runner traceback levels
while tb and self._is_relevant_tb_level(tb):
tb = tb.tb_next
if exctype is test.failureException:
# Skip assert*() traceback levels
length = self._count_relevant_tb_levels(tb)
msgLines = traceback.format_exception(exctype, value, tb, length)
else:
msgLines = traceback.format_exception(exctype, value, tb)
if self.buffer:
output = sys.stdout.getvalue()
error = sys.stderr.getvalue()
if output:
if not output.endswith('\n'):
output += '\n'
msgLines.append(STDOUT_LINE % output)
if error:
if not error.endswith('\n'):
error += '\n'
msgLines.append(STDERR_LINE % error)
return ''.join(msgLines)
0
Example 100
def _restore_stdout(self):
output = sys.stdout.getvalue()
sys.stdout.close()
sys.stdout = sys.__stdout__
return output