本文整理汇总了Python中scripttest.TestFileEnvironment类的典型用法代码示例。如果您正苦于以下问题:Python TestFileEnvironment类的具体用法?Python TestFileEnvironment怎么用?Python TestFileEnvironment使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了TestFileEnvironment类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_env
def get_env(self, check_help_version=True):
#import tempfile
#env = TestFileEnvironment(tempfile.mkdtemp(suffix='', prefix='test_' + script))
env = TestFileEnvironment()
# Use Agg backend for plots.
#env.writefile("matplotlibrc", "backend: Agg")
#with open(os.path.join(env.base_path, "matplotlibrc"), "wt") as fh:
# fh.write("backend: Agg\n")
if check_help_version:
# Start with --help. If this does not work...
r = env.run(self.script, "--help", expect_stderr=self.expect_stderr)
assert r.returncode == 0
# Script must provide a version option
r = env.run(self.script, "--version", expect_stderr=self.expect_stderr)
assert r.returncode == 0
print("stderr", r.stderr)
print("stdout", r.stdout)
verstr = r.stdout.strip()
# deprecation warnings break --version
#if not verstr: verstr = r.stdout.strip() # py3k
#assert str(verstr) == str(abilab.__version__)
return env
示例2: main
def main():
""" Main method
Returns 0 on success, 1 on failure
"""
start = timer()
script = 'bin/csv2ofx --help'
env = TestFileEnvironment('.scripttest')
tmpfile = NamedTemporaryFile(dir=parent_dir, delete=False)
tmpname = tmpfile.name
tests = [
(2, 'default.csv', 'default.qif', 'oq'),
(3, 'default.csv', 'default_w_splits.qif', 'oqS Category'),
(4, 'xero.csv', 'xero.qif', 'oqc Description -m xero'),
(5, 'mint.csv', 'mint.qif', 'oqS Category -m mint'),
(
6, 'mint.csv', 'mint_alt.qif',
'oqs20150613 -e20150614 -S Category -m mint'
),
(7, 'default.csv', 'default.ofx', 'oe 20150908'),
(8, 'default.csv', 'default_w_splits.ofx', 'oS Category'),
(9, 'mint.csv', 'mint.ofx', 'oS Category -m mint'),
]
try:
env.run(script, cwd=parent_dir)
print('\nScripttest #1: %s ... ok' % script)
for test_num, example_filename, check_filename, opts in tests:
example = p.join(example_dir, example_filename)
check = p.join(check_dir, check_filename)
checkfile = open(check)
script = 'bin/csv2ofx -%s %s %s' % (opts, example, tmpname)
env.run(script, cwd=parent_dir)
args = [checkfile.readlines(), open(tmpname).readlines()]
kwargs = {'fromfile': 'expected', 'tofile': 'got'}
diffs = list(unified_diff(*args, **kwargs))
if diffs:
loc = ' '.join(script.split(' ')[:-1])
msg = "ERROR from test #%i! Output:\n\t%s\n" % (test_num, loc)
msg += "doesn't match hash of\n\t%s\n" % check
sys.stderr.write(msg)
sys.exit(''.join(diffs))
else:
short_script = 'csv2ofx -%s %s %s' % (
opts, example_filename, check_filename)
print('Scripttest #%i: %s ... ok' % (test_num, short_script))
except Exception as e:
sys.exit(e)
else:
time = timer() - start
print('%s' % '-' * 70)
print('Ran %i scripttests in %0.3fs\n\nOK' % (test_num, time))
sys.exit(0)
finally:
checkfile.close
os.unlink(tmpname)
示例3: TestBasicCommands
class TestBasicCommands(TestCase):
"""Test basic command-line invoke of the program"""
def setUp(self):
self.env = TestFileEnvironment('./test-output')
def test_default(self):
res = self.env.run('../run.py', '-s', '1')
assert 'Timeout' in res.stdout
self.assertEqual(res.returncode, 0)
def test_collect(self):
res = self.env.run('../run.py', '-s', '1', '-c')
assert 'Collecting' in res.stdout
self.assertEqual(res.returncode, 0)
def test_log(self):
res = self.env.run('../run.py', '-s', '1', '--log', 'log.txt')
assert 'Timeout' in res.stdout
assert 'log.txt' in res.files_created
self.assertEqual(res.returncode, 0)
def test_segment(self):
res = self.env.run('../run.py', '-s', '1', '--segment', '0.2')
assert 'Timeout' in res.stdout
self.assertEqual(res.returncode, 0)
def tearDown(self):
pass
示例4: CLITest
class CLITest(unittest.TestCase):
def setUp(self):
import githook
self.githook = githook
self.githook.app.config['TESTING'] = True
self.tempdir = tempfile.mkdtemp()
self.env = TestFileEnvironment(
os.path.join(self.tempdir,'test-output'),
ignore_hidden=False)
@unittest.skipIf(*is_travis)
def test_no_config(self):
result = self.env.run('bin/python %s' % os.path.join(here, "..", "__init__.py"),
expect_error=True,
cwd=os.path.join(here, '../', '../')
)
self.assertEqual(result.returncode, 1)
self.assertEqual(result.stderr, u'CRITICAL:root:Configuration file not found. Please specify one.\n')
# TODO This loops. :D Need another way of testing daemons.
@unittest.skipIf(True, 'It loops')
def test_ok_config(self):
self.env.run('bin/python -m githook -c githook/tests/config/okconfig.ini',
cwd=os.path.join(here, '../', '../')
)
示例5: PhonebookTestCase
class PhonebookTestCase(unittest.TestCase):
def setUp(self):
self.env = TestFileEnvironment('./scratch')
self.prefix = os.getcwd()
# load phonebook fixture. Need to use separate name to prevent
# overwriting actual file.
with open('phonebook_fixture.txt') as f:
with open('phonebook_fixture.pb', 'wb') as phonebook_fixture:
for line in f:
phonebook_fixture.write(line)
def tearDown(self):
os.remove('phonebook_fixture.pb')
# helper methods for ensuring things were/weren't added to files.
def assert_not_added(self, entry_fields):
result = self.env.run('cat %s/phonebook_fixture.pb' % self.prefix)
for value in entry_fields:
nose.tools.assert_not_in(value, result.stdout)
def assert_added(self, entry_fields):
result = self.env.run('cat %s/phonebook_fixture.pb' % self.prefix)
for value in entry_fields:
nose.tools.assert_in(value, result.stdout)
示例6: main
def main(script, tests, verbose=False, stop=True):
""" Main method
Returns 0 on success, 1 on failure
"""
failures = 0
logger = gogo.Gogo(__name__, verbose=verbose).logger
short_script = p.basename(script)
env = TestFileEnvironment('.scripttest')
start = timer()
for pos, test in enumerate(tests):
num = pos + 1
opts, arguments, expected = test
joined_opts = ' '.join(opts) if opts else ''
joined_args = '"%s"' % '" "'.join(arguments) if arguments else ''
command = "%s %s %s" % (script, joined_opts, joined_args)
short_command = "%s %s %s" % (short_script, joined_opts, joined_args)
result = env.run(command, cwd=p.abspath(p.dirname(p.dirname(__file__))))
output = result.stdout
if isinstance(expected, bool):
text = StringIO(output).read()
outlines = [str(bool(text))]
checklines = StringIO(str(expected)).readlines()
elif p.isfile(expected):
outlines = StringIO(output).readlines()
with open(expected, encoding='utf-8') as f:
checklines = f.readlines()
else:
outlines = StringIO(output).readlines()
checklines = StringIO(expected).readlines()
args = [checklines, outlines]
kwargs = {'fromfile': 'expected', 'tofile': 'got'}
diffs = ''.join(unified_diff(*args, **kwargs))
passed = not diffs
if not passed:
failures += 1
msg = "ERROR! Output from test #%i:\n %s\n" % (num, short_command)
msg += "doesn't match:\n %s\n" % expected
msg += diffs if diffs else ''
else:
logger.debug(output)
msg = 'Scripttest #%i: %s ... ok' % (num, short_command)
logger.info(msg)
if stop and failures:
break
time = timer() - start
logger.info('%s' % '-' * 70)
end = 'FAILED (failures=%i)' % failures if failures else 'OK'
logger.info('Ran %i scripttests in %0.3fs\n\n%s' % (num, time, end))
sys.exit(failures)
示例7: test_script
def test_script(self):
with HTTMock(mock_TwitterK):
env = TestFileEnvironment('myria_upload')
res = env.run('''myria_upload --relation TwitterK --program test
--overwrite --hostname localhost
--port 12345 --dry''', stdin='foo,bar\n1,b\n3,c',
expect_stderr=True)
eq_(res.stdout, '''1,b\n3,c\n''')
示例8: TestIntegration
class TestIntegration(unittest.TestCase):
def setUp(self):
self.env = TestFileEnvironment(test_path, template_path=template_path)
def test_init(self):
result = self.env.run("gpc", "init", expect_stderr=True)
created_filenames = result.files_created.keys()
self.assertTrue("log" in created_filenames)
self.assertTrue("log/data" in created_filenames)
self.assertTrue("log/schema.sql" in created_filenames)
self.assertTrue("storage" in created_filenames)
def test_make_target(self):
self.env.run("gpc", "init", expect_stderr=True)
self.env.writefile("gpc.yaml", frompath="simple.yaml")
result = self.env.run("gpc", "make", "c", expect_stderr=True)
created_filenames = list(result.files_created.keys())
self.assertTrue("c" in created_filenames)
created_filenames.remove("c")
self.assertTrue(any([s.startswith("storage/") for s in created_filenames]))
self.assertTrue(any([s.startswith("log/data/") for s in created_filenames]))
def test_make_target_cached(self):
call(["cp", "-r", template_path + "/.gpc", test_path])
call(["cp", "-r", template_path + "/log", test_path])
call(["cp", "-r", template_path + "/storage", test_path])
self.env.writefile("gpc.yaml", frompath="simple.yaml")
result = self.env.run("gpc", "make", "c", expect_stderr=True)
created_filenames = result.files_created.keys()
self.assertTrue("c" in created_filenames)
self.assertTrue(len(created_filenames) == 1)
示例9: test_bad_symlink
def test_bad_symlink(tmpdir):
"""
symlinks only work in UNIX
"""
if sys.platform == 'win32':
return
env = TestFileEnvironment(str(tmpdir), start_clear=False)
res = env.run(sys.executable, '-c', '''\
import os
os.symlink(os.path.join('does', 'not', 'exist.txt'), "does-not-exist.txt")
''')
assert 'does-not-exist.txt' in res.files_created, res.files_created
assert res.files_created['does-not-exist.txt'].invalid
# Just make sure there's no error:
str(res)
示例10: get_env
def get_env(self):
#import tempfile
#env = TestFileEnvironment(tempfile.mkdtemp(suffix='', prefix='test_' + script))
env = TestFileEnvironment()
# Use Agg backend for plots.
#env.writefile("matplotlibrc", "backend : Agg")
# Start with --help. If this does not work...
env.run(self.script, "--help")
# Script must provide a version option
#r = env.run(self.script, "--version", expect_stderr=True)
#assert r.stderr.strip() == "%s version %s" % (os.path.basename(self.script), abilab.__version__)
return env
示例11: TestSpec
class TestSpec(object):
td_dir = "{0}/test_data/".format(tests_dir)
bin_dir = os.path.split(tests_dir)[0] + "/"
exe = "python {0}mybin.py".format(bin_dir)
def setup_method(self, method):
self.env = TestFileEnvironment("{0}/test_output/".format(tests_dir))
@pytest.mark.parametrize(
("package", "options", "expected"),
[
("Jinja2", "", "python-Jinja2.spec"),
("Jinja2", "-b3", "python-Jinja2_base.spec"),
("Jinja2", "-t epel7", "python-Jinja2_epel7.spec"),
("Jinja2", "-t epel6", "python-Jinja2_epel6.spec"),
("buildkit", "-b2", "python-buildkit.spec"),
("StructArray", "-b2", "python-StructArray.spec"),
("Sphinx", "-r python-sphinx", "python-sphinx.spec"),
],
)
@pytest.mark.spectest
def test_spec(self, package, options, expected):
with open(self.td_dir + expected) as fi:
self.spec_content = fi.read()
res = self.env.run("{0} {1} {2}".format(self.exe, package, options))
# changelog have to be cut from spec files
assert set(res.stdout.split("\n")[1:-4]) == set(self.spec_content.split("\n")[1:-4])
示例12: BaseTemplateTest
class BaseTemplateTest(unittest.TestCase):
"""Base class for all spirit.bob test cases."""
def setUp(self):
self.tempdir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, self.tempdir)
# docs http://pythonpaste.org/scripttest/
self.env = TestFileEnvironment(
os.path.join(self.tempdir, 'test-output'),
ignore_hidden=False,
)
def create_template(self):
"""Run mr.bob to create your template."""
options = {
'dir': os.path.join(os.path.dirname(__file__)),
'template': self.template,
'answers_file': self.answers_file,
}
return self.env.run(
'{dir}/bin/mrbob --config '
'{dir}/{answers_file} {dir}/src/spirit/bob/{template}'.format(
**options
)
)
示例13: TestSpec
class TestSpec(object):
td_dir = '{0}/test_data/'.format(tests_dir)
bin_dir = os.path.split(tests_dir)[0] + '/'
exe = 'python {0}mybin.py'.format(bin_dir)
def setup_method(self, method):
self.env = TestFileEnvironment('{0}/test_output/'.format(tests_dir))
@pytest.mark.parametrize(('package', 'options', 'expected'), [
('Jinja2', '-v2.8', 'python-Jinja2.spec'),
('Jinja2', '-v2.8 -b3', 'python-Jinja2_base.spec'),
('Jinja2', '-v2.8 -t epel7', 'python-Jinja2_epel7.spec'),
('Jinja2', '-v2.8 -t epel6', 'python-Jinja2_epel6.spec'),
('buildkit', '-v0.2.2 -b2', 'python-buildkit.spec'),
('StructArray', '-v0.1 -b2', 'python-StructArray.spec'),
('Sphinx', '-v1.5 -r python-sphinx', 'python-sphinx.spec'),
])
@pytest.mark.webtest
def test_spec(self, package, options, expected):
with open(self.td_dir + expected) as fi:
self.spec_content = fi.read()
res = self.env.run('{0} {1} {2}'.format(self.exe, package, options),
expect_stderr=True)
# changelog have to be cut from spec files
assert set(res.stdout.split('\n')[1:-4]) == set(self.spec_content.split('\n')[1:-4])
示例14: test_setting_ansible_container_envar
def test_setting_ansible_container_envar():
env = ScriptTestEnvironment()
result = env.run('ansible-container', '--debug', 'build',
cwd=project_dir('environment'), expect_stderr=True)
assert "web MYVAR=foo ANSIBLE_CONTAINER=1" in result.stdout
assert "db MYVAR=foo ANSIBLE_CONTAINER=1" in result.stdout
assert "mw ANSIBLE_CONTAINER=1" in result.stdout
示例15: test_stop_service_minimal_docker_container
def test_stop_service_minimal_docker_container():
env = ScriptTestEnvironment()
env.run('ansible-container', 'run', '--detached', cwd=project_dir('minimal_sleep'), expect_stderr=True)
result = env.run('ansible-container', 'stop', 'minimal1',
cwd=project_dir('minimal_sleep'), expect_stderr=True)
assert "Stopping ansible_minimal1_1 ... done" in result.stderr
assert "Stopping ansible_minimal2_1 ... done" not in result.stderr