本文整理汇总了Python中six.StringIO.getvalue方法的典型用法代码示例。如果您正苦于以下问题:Python StringIO.getvalue方法的具体用法?Python StringIO.getvalue怎么用?Python StringIO.getvalue使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six.StringIO
的用法示例。
在下文中一共展示了StringIO.getvalue方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_any_sequence_to_fasta
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import getvalue [as 别名]
def test_any_sequence_to_fasta(self):
# store writer function, sequence object to write, expected
# fasta filepath for default parameters, expected fasta filepath for
# non-defaults, and expected qual filepath for non-defaults
id_ = 'f o o'
desc = 'b\na\nr'
test_data = (
(_biological_sequence_to_fasta,
Sequence('ACGT', id=id_, description=desc,
quality=range(1, 5)),
('fasta_single_bio_seq_defaults',
'fasta_single_bio_seq_non_defaults',
'qual_single_bio_seq_non_defaults')),
(_dna_sequence_to_fasta,
DNA('TACG', id=id_, description=desc, quality=range(4)),
('fasta_single_dna_seq_defaults',
'fasta_single_dna_seq_non_defaults',
'qual_single_dna_seq_non_defaults')),
(_rna_sequence_to_fasta,
RNA('UACG', id=id_, description=desc, quality=range(2, 6)),
('fasta_single_rna_seq_defaults',
'fasta_single_rna_seq_non_defaults',
'qual_single_rna_seq_non_defaults')),
(_protein_sequence_to_fasta,
Protein('PQQ', id=id_, description=desc, quality=[42, 41, 40]),
('fasta_single_prot_seq_defaults',
'fasta_single_prot_seq_non_defaults',
'qual_single_prot_seq_non_defaults')))
for fn, obj, fps in test_data:
defaults_fp, non_defaults_fasta_fp, non_defaults_qual_fp = fps
# test writing with default parameters
fh = StringIO()
fn(obj, fh)
obs = fh.getvalue()
fh.close()
with open(get_data_path(defaults_fp), 'U') as fh:
exp = fh.read()
self.assertEqual(obs, exp)
# test writing with non-defaults
fasta_fh = StringIO()
qual_fh = StringIO()
fn(obj, fasta_fh, id_whitespace_replacement='-',
description_newline_replacement='_', max_width=1, qual=qual_fh)
obs_fasta = fasta_fh.getvalue()
obs_qual = qual_fh.getvalue()
fasta_fh.close()
qual_fh.close()
with open(get_data_path(non_defaults_fasta_fp), 'U') as fh:
exp_fasta = fh.read()
with open(get_data_path(non_defaults_qual_fp), 'U') as fh:
exp_qual = fh.read()
self.assertEqual(obs_fasta, exp_fasta)
self.assertEqual(obs_qual, exp_qual)
示例2: _Buffer
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import getvalue [as 别名]
class _Buffer(object):
def __init__(self, stream):
self._stream = stream
self._buffer = StringIO()
def fileno(self):
return self._stream.fileno()
def __getattr__(self, attr):
# this happens on unpickling
if attr == '_buffer':
raise AttributeError("No _buffer yet")
return getattr(self._buffer, attr)
def __le__(self, obj):
return self._buffer.getvalue() == obj
def __eq__(self, obj):
return self._buffer.getvalue() == obj
def __str__(self):
return self._buffer.getvalue()
def __repr__(self):
return repr(self._buffer.getvalue())
示例3: test_packed_workflow_execution
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import getvalue [as 别名]
def test_packed_workflow_execution(wf_path, job_path, namespaced, tmpdir):
load_tool.loaders = {}
document_loader, workflowobj, uri = fetch_document(
get_data(wf_path), resolver=tool_resolver)
document_loader, _, processobj, metadata, uri = validate_document(
document_loader, workflowobj, uri, [], {})
packed = json.loads(print_pack(document_loader, processobj, uri, metadata))
assert not namespaced or "$namespaces" in packed
wf_packed_handle, wf_packed_path = tempfile.mkstemp()
with open(wf_packed_path, 'w') as temp_file:
json.dump(packed, temp_file)
normal_output = StringIO()
packed_output = StringIO()
normal_params = ['--outdir', str(tmpdir), get_data(wf_path), get_data(job_path)]
packed_params = ['--outdir', str(tmpdir), '--debug', get_data(wf_packed_path), get_data(job_path)]
assert main(normal_params, stdout=normal_output) == 0
assert main(packed_params, stdout=packed_output) == 0
assert json.loads(packed_output.getvalue()) == json.loads(normal_output.getvalue())
os.close(wf_packed_handle)
os.remove(wf_packed_path)
示例4: _in_process_execute
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import getvalue [as 别名]
def _in_process_execute(self, cli_ctx, command, expect_failure=False):
from six import StringIO
from vcr.errors import CannotOverwriteExistingCassetteException
if command.startswith('az '):
command = command[3:]
stdout_buf = StringIO()
logging_buf = StringIO()
try:
# issue: stderr cannot be redirect in this form, as a result some failure information
# is lost when command fails.
self.exit_code = cli_ctx.invoke(shlex.split(command), out_file=stdout_buf) or 0
self.output = stdout_buf.getvalue()
self.applog = logging_buf.getvalue()
except CannotOverwriteExistingCassetteException as ex:
raise AssertionError(ex)
except CliExecutionError as ex:
if expect_failure:
self.exit_code = 1
self.output = stdout_buf.getvalue()
self.applog = logging_buf.getvalue()
elif ex.exception:
raise ex.exception
else:
raise ex
except Exception as ex: # pylint: disable=broad-except
self.exit_code = 1
self.output = stdout_buf.getvalue()
self.process_error = ex
finally:
stdout_buf.close()
logging_buf.close()
示例5: test_invalid_project_name
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import getvalue [as 别名]
def test_invalid_project_name(self):
#with patch('sys.stdout', self.stdout):
stderr_tmp = StringIO()
with patch('sys.stderr', stderr_tmp):
with self.assertRaises(SystemExit) as error:
conf_data = config.parse([
'-q',
'--db=postgres://user:[email protected]/dbname',
'-p'+self.project_dir,
'test'])
self.assertTrue(stderr_tmp.getvalue().find("Project name 'test' is not valid") > -1)
stderr_tmp = StringIO()
with patch('sys.stderr', stderr_tmp):
with self.assertRaises(SystemExit) as error:
conf_data = config.parse([
'-q',
'--db=postgres://user:[email protected]/dbname',
'-p'+self.project_dir,
'assert'])
self.assertTrue(stderr_tmp.getvalue().find("Project name 'assert' is not valid") > -1)
stderr_tmp = StringIO()
with patch('sys.stderr', stderr_tmp):
with self.assertRaises(SystemExit) as error:
conf_data = config.parse([
'-q',
'--db=postgres://user:[email protected]/dbname',
'-p'+self.project_dir,
'values'])
self.assertTrue(stderr_tmp.getvalue().find("Project name 'values' is not valid") > -1)
示例6: write_to_db
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import getvalue [as 别名]
def write_to_db(self, db, transaction=None, commit=True):
if transaction is None:
transaction = db
fp = StringIO()
if len(self) < Timeseries.MAX_ALL_BOTTOM:
top = ''
middle = None
self.write(fp)
bottom = fp.getvalue()
else:
dates = sorted(self.keys())
self.write(fp, end=dates[Timeseries.ROWS_IN_TOP_BOTTOM - 1])
top = fp.getvalue()
fp.truncate(0)
fp.seek(0)
self.write(fp, start=dates[Timeseries.ROWS_IN_TOP_BOTTOM],
end=dates[-(Timeseries.ROWS_IN_TOP_BOTTOM + 1)])
middle = self.blob_create(
zlib.compress(fp.getvalue().encode('ascii')))
fp.truncate(0)
fp.seek(0)
self.write(fp, start=dates[-Timeseries.ROWS_IN_TOP_BOTTOM])
bottom = fp.getvalue()
fp.close()
c = db.cursor()
c.execute("DELETE FROM ts_records WHERE id=%d" % (self.id))
c.execute("""INSERT INTO ts_records (id, top, middle, bottom)
VALUES (%s, %s, %s, %s)""", (self.id, top, middle,
bottom))
c.close()
if commit:
transaction.commit()
示例7: test_roundtrip_generators
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import getvalue [as 别名]
def test_roundtrip_generators(self):
# test that fasta and qual files can be streamed into memory and back
# out to disk using generator reader and writer
fps = list(map(lambda e: list(map(get_data_path, e)),
[('empty', 'empty'),
('fasta_multi_seq_roundtrip',
'qual_multi_seq_roundtrip')]))
for fasta_fp, qual_fp in fps:
with open(fasta_fp, 'U') as fh:
exp_fasta = fh.read()
with open(qual_fp, 'U') as fh:
exp_qual = fh.read()
fasta_fh = StringIO()
qual_fh = StringIO()
_generator_to_fasta(_fasta_to_generator(fasta_fp, qual=qual_fp),
fasta_fh, qual=qual_fh)
obs_fasta = fasta_fh.getvalue()
obs_qual = qual_fh.getvalue()
fasta_fh.close()
qual_fh.close()
self.assertEqual(obs_fasta, exp_fasta)
self.assertEqual(obs_qual, exp_qual)
示例8: test_trap_output
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import getvalue [as 别名]
def test_trap_output(self):
class BorkedOutput(outputs.ListOutput):
def _write(self, x):
raise RuntimeError("BORK")
out = BorkedOutput(close_atexit=False)
sio = StringIO()
def cleanup(stderr, output):
sys.stderr = stderr
sio.close()
self.log.output = output
out.close()
self.addCleanup(cleanup, sys.stderr, self.log.output)
sys.stderr = sio
self.log.output = out
self.log.fields().info('hi')
assert "BORK" in sio.getvalue()
assert "Offending message: <twiggy.message.Message object" in sio.getvalue()
assert "Error in twiggy internal log! Something is seriously broken." in sio.getvalue()
assert "Traceback" in sio.getvalue()
示例9: test_declared
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import getvalue [as 别名]
def test_declared(self):
b = PySPConfigBlock()
safe_register_common_option(b, "verbose")
b.display()
b.display()
out = StringIO()
b.display(ostream=out)
self.assertEqual(out.getvalue(),
"verbose: false\n")
self.assertEqual(b.check_usage(), True)
self.assertEqual(b.check_usage(error=False), True)
b.verbose = True
out = StringIO()
b.display(ostream=out)
self.assertEqual(out.getvalue(),
"verbose: true\n")
with self.assertRaises(ValueError):
b.check_usage()
with self.assertRaises(ValueError):
b.check_usage()
self.assertEqual(b.check_usage(error=False), False)
b.verbose
self.assertEqual(b.check_usage(), True)
self.assertEqual(b.check_usage(error=False), True)
verbose_about = \
"""PySPConfigValue: verbose
- type: <%s 'bool'>
- default: False
- doc: Generate verbose output for both initialization and
execution.""" % ('class' if six.PY3 else 'type')
self.assertEqual(b.about("verbose"),
verbose_about)
示例10: TestBuild
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import getvalue [as 别名]
class TestBuild(unittest.TestCase):
def setUp(self):
self.out = StringIO()
os.mkdir('/tmp/resu') # Append uuid
os.chdir('/tmp/resu')
def test_basic(self):
resu.cli.run(args=['-g'], out=self.out)
resu.cli.run(args=[], out=self.out)
assert os.path.isfile('resu.pdf')
self.assertEquals(self.out.getvalue(), '')
def test_specify_output_file(self):
resu.cli.run(args=['-g'], out=self.out)
resu.cli.run(args=['-o', 'other.html'], out=self.out)
assert os.path.isfile('other.html')
self.assertEquals(self.out.getvalue(), '')
def test_non_existant_parser(self):
resu.cli.run(args=['-g'], out=self.out)
with self.assertRaises(FeatureNotFound):
resu.cli.run(args=['-p', 'gibberish'], out=self.out)
assert not os.path.isfile('resu.pdf')
def tearDown(self):
shutil.rmtree('/tmp/resu')
示例11: understand_buffer_usage_and_performance
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import getvalue [as 别名]
def understand_buffer_usage_and_performance():
multiplier = 1000 * 100
big_data = data * multiplier
# no buffer
st = time.time()
big_data_json = json.dumps(big_data)
elapse = time.time() - st
print("%.6f" % elapse)
# write to text, then create buffer
st = time.time()
buffer = StringIO()
big_data_json = json.dumps(big_data)
buffer = StringIO(big_data_json)
value = buffer.getvalue()
elapse = time.time() - st
print("%.6f" % elapse)
# write to buffer
st = time.time()
buffer = StringIO()
json.dump(big_data, buffer)
value = buffer.getvalue()
elapse = time.time() - st
print("%.6f" % elapse)
print("%s KB" % sys.getsizeof(big_data_json))
示例12: test_invalid_project_name
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import getvalue [as 别名]
def test_invalid_project_name(self):
with patch("sys.stdout", self.stdout):
stderr_tmp = StringIO()
with patch("sys.stderr", stderr_tmp):
with self.assertRaises(SystemExit) as error:
conf_data = config.parse(
["-q", "--db=postgres://user:[email protected]/dbname", "-p" + self.project_dir, "test"]
)
self.assertTrue(stderr_tmp.getvalue().find('Project name "test" is not a valid app name') > -1)
stderr_tmp = StringIO()
with patch("sys.stderr", stderr_tmp):
with self.assertRaises(SystemExit) as error:
conf_data = config.parse(
["-q", "--db=postgres://user:[email protected]/dbname", "-p" + self.project_dir, "assert"]
)
self.assertTrue(stderr_tmp.getvalue().find('Project name "assert" is not a valid app name') > -1)
stderr_tmp = StringIO()
with patch("sys.stderr", stderr_tmp):
with self.assertRaises(SystemExit) as error:
conf_data = config.parse(
["-q", "--db=postgres://user:[email protected]/dbname", "-p" + self.project_dir, "values"]
)
self.assertTrue(stderr_tmp.getvalue().find('Project name "values" is not a valid app name') > -1)
stderr_tmp = StringIO()
with patch("sys.stderr", stderr_tmp):
with self.assertRaises(SystemExit) as error:
conf_data = config.parse(
["-q", "--db=postgres://user:[email protected]/dbname", "-p" + self.project_dir, "project-name"]
)
self.assertTrue(stderr_tmp.getvalue().find('Project name "project-name" is not a valid app name') > -1)
示例13: test_display
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import getvalue [as 别名]
def test_display(self):
model = ConcreteModel()
model.e = Expression()
with capture_output() as out:
model.e.display()
self.assertEqual(out.getvalue().strip(), """
e : Size=1
Key : Value
None : Undefined
""".strip())
model.e.set_value(1.0)
with capture_output() as out:
model.e.display()
self.assertEqual(out.getvalue().strip(), """
e : Size=1
Key : Value
None : 1.0
""".strip())
out = StringIO()
with capture_output() as no_out:
model.e.display(ostream=out)
self.assertEqual(no_out.getvalue(), "")
self.assertEqual(out.getvalue().strip(), """
e : Size=1
Key : Value
None : 1.0
""".strip())
model.E = Expression([1,2])
with capture_output() as out:
model.E.display()
self.assertEqual(out.getvalue().strip(), """
E : Size=2
Key : Value
1 : Undefined
2 : Undefined
""".strip())
model.E[1].set_value(1.0)
with capture_output() as out:
model.E.display()
self.assertEqual(out.getvalue().strip(), """
E : Size=2
Key : Value
1 : 1.0
2 : Undefined
""".strip())
out = StringIO()
with capture_output() as no_out:
model.E.display(ostream=out)
self.assertEqual(no_out.getvalue(), "")
self.assertEqual(out.getvalue().strip(), """
E : Size=2
Key : Value
1 : 1.0
2 : Undefined
""".strip())
示例14: test_info_unicode
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import getvalue [as 别名]
def test_info_unicode(self, depfile):
output = StringIO()
task = Task("t1", [], file_dep=[six.u("tests/data/dependency1")])
cmd = CmdFactory(Info, outstream=output, dep_file=depfile.name, task_list=[task])
cmd._execute(["t1"])
assert """t1""" in output.getvalue()
assert """tests/data/dependency1""" in output.getvalue()
示例15: test_commands
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import getvalue [as 别名]
def test_commands(self):
out = StringIO()
call_command('billing_check', stdout=out)
self.assertEqual(out.getvalue(), '')
self.add_project()
self.add_project()
out = StringIO()
call_command('billing_check', stdout=out)
self.assertEqual(
out.getvalue(),
'Following billings are over limit:\n'
' * test0, test1 (test)\n'
)
out = StringIO()
call_command('billing_check', '--valid', stdout=out)
self.assertEqual(out.getvalue(), '')
self.invoice.delete()
out = StringIO()
call_command('billing_check', stdout=out)
self.assertEqual(
out.getvalue(),
'Following billings are over limit:\n'
' * test0, test1 (test)\n'
'Following billings are past due date:\n'
' * test0, test1 (test)\n'
)
call_command('billing_check', '--notify', stdout=out)
self.assertEqual(len(mail.outbox), 1)