Python unittest 模块,main() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用unittest.main()。
def testHelpMessageForSQLitePlugin(self):
"""test the --help option for SQLite"""
helper = end_to_end_test_helper.EndToEndTestHelper('not needed',
'not needed')
if platform.system() in ['Linux']:
message_help = (
'Usage: main.py sqlite [OPTIONS]\r\n\r\n'
'Options:\r\n '
'--path TEXT The path to plaso\r\n '
'--name TEXT The plugin name\r\n '
'--testfile TEXT The testfile path\r\n '
'--sql / --no-sql The output example flag for the SQL Query for the '
'plugin.\r\n '
'--help Show this message and exit.')
command = 'python {0} sqlite --help'.format(helper.MAIN_PATH)
child = pexpect.spawn(command)
child.expect_exact(message_help)
else:
raise NotImplementedError("test only implemented for linux platform")
def helper_test_dismiss_dialog_twice(self, app):
"""
If by some choice the dismiss event of a dialog created with
Controller.create_dialog_helper() is fired twice, it should be
handled gracefully, refs #89.
"""
Controller = main.Controller
title = "title"
body = "body"
# makes sure the controller has no dialog
self.assertEqual(Controller.dialogs, [])
# creates one and verifies it was created
dialog = Controller.create_dialog_helper(title, body)
self.assertEqual(len(Controller.dialogs), 1)
# dimisses it once and verifies it was handled
dialog.dispatch('on_dismiss')
self.assertEqual(Controller.dialogs, [])
# then a second time and it should not crash
dialog.dispatch('on_dismiss')
self.assertEqual(Controller.dialogs, [])
def testHelpMessage(self):
"""test the universal --help Option"""
helper = end_to_end_test_helper.EndToEndTestHelper('not needed',
'not needed')
if platform.system() in ['Linux']:
message_help = ('Usage: main.py [OPTIONS] COMMAND [ARGS]...\r\n\r\n'
'Options:\r\n'
' --help Show this message and exit.\r\n\r\n'
'Commands:\r\n'
' sqlite')
command = 'python {0} --help'.format(helper.MAIN_PATH)
child = pexpect.spawn(command)
child.expect_exact(message_help)
else:
raise NotImplementedError("test only implemented for linux platform")
def testSQLiteHelp(self):
"""testing the main of the sqlite"""
runner = CliRunner()
result = runner.invoke(main.entry_point, ['sqlite', '--help'])
expected_output = ('Usage: entry_point sqlite [OPTIONS]\n'
'\n'
'Options:\n'
' --path TEXT The path to plaso\n'
' --name TEXT The plugin name\n'
' --testfile TEXT The testfile path\n'
' --sql / --no-sql The output example flag for the '
'SQL Query for the plugin.\n'
' --help Show this message and exit.\n')
self.assertEqual(expected_output, str(result.output))
self.assertEqual(0, result.exit_code)
def todo_test_pump(self):
# __doc__ (as of 2008-08-02) for pygame.fastevent.pump:
# pygame.fastevent.pump() -> None
# update the internal messages
#
# For each frame of your game, you will need to make some sort
# of call to the event queue. This ensures your program can internally
# interact with the rest of the operating system. If you are not using
# other event functions in your game, you should call pump() to allow
# pygame to handle internal actions.
#
# There are important things that must be dealt with internally in the
# event queue. The main window may need to be repainted. Certain joysticks
# must be polled for their values. If you fail to make a call to the event
# queue for too long, the system may decide your program has locked up.
self.fail()
def run_tests(self):
import unittest
# Purge modules under test from sys.modules. The test loader will
# re-import them from the build location. Required when 2to3 is used
# with namespace packages.
if sys.version_info >= (3,) and getattr(self.distribution, 'use_2to3', False):
module = self.test_args[-1].split('.')[0]
if module in _namespace_packages:
del_modules = []
if module in sys.modules:
del_modules.append(module)
module += '.'
for name in sys.modules:
if name.startswith(module):
del_modules.append(name)
list(map(sys.modules.__delitem__, del_modules))
loader_ep = EntryPoint.parse("x="+self.test_loader)
loader_class = loader_ep.load(require=False)
cks = loader_class()
unittest.main(
None, None, [unittest.__file__]+self.test_args,
testLoader = cks
)
def transition_function(P):
"""
The main principle on building the transition function is to think about
the fact that every time we scan a new character from the input sequence
the suffix should match with the prefix of the pattern. If that is not
possible for every length of the suffix, the next state need to be the
initial, otherwise the length of the suffix that matches properly will be
exactly the next state.
"""
alphabet = st.ascii_letters+st.punctuation+st.digits+st.whitespace
m = len(P)
trans = [{c:0 for c in alphabet} for i in range(m)]
for s in range(m):
for c in alphabet:
k = min(m, s+1)
while (P[:s]+c)[-k:] != P[:k]:
k-=1
trans[s][c]=k
return trans
def _test_checkin_with_handoff(my):
search_type = "unittest/person"
code = "joe"
search_key = my.server.build_search_key(search_type, code)
# copy file to handoff dir
path = "%s/test/miso_ramen.jpg" % my.client_lib_dir
handoff_dir = my.server.get_handoff_dir()
shutil.copy(path, handoff_dir)
# check the file in
snapshot = my.server.simple_checkin(search_key, "publish", path, use_handoff_dir=True)
snapshot_code = snapshot.get("code")
# get the filename
file_type = "main"
path = my.server.get_path_from_snapshot(snapshot_code, file_type)
exists = os.path.exists(path)
my.assertEquals(True, exists)
# check that the file name is correct
filename = os.path.basename(path)
# changed naming.. adds "publish"
my.assertEquals("miso_ramen_publish_v001.jpg", filename)
def testCatchBreakInstallsHandler(self):
module = sys.modules['unittest.main']
original = module.installHandler
def restore():
module.installHandler = original
self.addCleanup(restore)
self.installed = False
def fakeInstallHandler():
self.installed = True
module.installHandler = fakeInstallHandler
program = self.program
program.catchbreak = True
program.testRunner = FakeRunner
program.runTests()
self.assertTrue(self.installed)
def test_violations(self):
"Test error determination in CollectionValidator.why_bad"
obj = vv.Validator()
# main & where clause, both fail
q = vv.MongoQuery()
q.add_clause(vv.MongoClause(vv.Constraint('foo', 'size>', 2)))
q.add_clause(vv.MongoClause(vv.Constraint('bar', '>', 1)))
rec = {'foo': [0], 'bar': 0}
reasons = obj._get_violations(q, rec)
self.failUnlessEqual(len(reasons), 2)
for r in reasons:
if r.field == 'bar':
self.failUnless(r.op == '>' and r.got_value == 0 and r.expected_value == 1)
# all pass
q = vv.MongoQuery()
q.add_clause(vv.MongoClause(vv.Constraint('foo', 'size>', 2)))
q.add_clause(vv.MongoClause(vv.Constraint('bar', '>', 1)))
rec = {'foo': [0, 1, 2], 'bar': 9}
reasons = obj._get_violations(q, rec)
rtuples = [r.as_tuple() for r in reasons]
print('\n'.join(map(str, rtuples)))
self.failUnlessEqual(len(reasons), 0)
def test_one_detection(self):
input_file = StringIO(self.image_name + ' 1:1')
output_filename = os.path.join(self.temp_dir, 'empty_file.json')
main(input_file, output_filename)
self.assertTrue(os.path.exists(output_filename))
with open(output_filename, 'r') as output_file:
obj = json.load(output_file)
self.assertEqual(1, len(obj['requests']))
self.assertIn('image', obj['requests'][0])
self.assertIn('content', obj['requests'][0]['image'])
self.assertIn('features', obj['requests'][0])
self.assertEqual(1, len(obj['requests'][0]['features']))
self.assertEqual(
'FACE_DETECTION', obj['requests'][0]['features'][0]['type'])
self.assertEqual(
1, obj['requests'][0]['features'][0]['maxResults'])
def test_multiple_detections(self):
input_file = StringIO(self.image_name + ' 1:1 2:3')
output_filename = os.path.join(self.temp_dir, 'empty_file.json')
main(input_file, output_filename)
self.assertTrue(os.path.exists(output_filename))
with open(output_filename, 'r') as output_file:
obj = json.load(output_file)
self.assertEqual(1, len(obj['requests']))
self.assertIn('image', obj['requests'][0])
self.assertIn('content', obj['requests'][0]['image'])
self.assertIn('features', obj['requests'][0])
self.assertEqual(2, len(obj['requests'][0]['features']))
self.assertEqual(
'FACE_DETECTION', obj['requests'][0]['features'][0]['type'])
self.assertEqual(
1, obj['requests'][0]['features'][0]['maxResults'])
self.assertEqual(
'LANDMARK_DETECTION', obj['requests'][0]['features'][1]['type'])
self.assertEqual(
3, obj['requests'][0]['features'][1]['maxResults'])
def test_bad_detection_type(self):
input_file = StringIO(self.image_name + ' 125:1')
output_filename = os.path.join(self.temp_dir, 'empty_file.json')
main(input_file, output_filename)
self.assertTrue(os.path.exists(output_filename))
with open(output_filename, 'r') as output_file:
obj = json.load(output_file)
self.assertEqual(1, len(obj['requests']))
self.assertIn('image', obj['requests'][0])
self.assertIn('content', obj['requests'][0]['image'])
self.assertIn('features', obj['requests'][0])
self.assertEqual(1, len(obj['requests'][0]['features']))
self.assertEqual(
'TYPE_UNSPECIFIED', obj['requests'][0]['features'][0]['type'])
self.assertEqual(
1, obj['requests'][0]['features'][0]['maxResults'])
def test_expressions(self):
e1 = '''int k = (r + 10.0) >> 6 + 8 << (3 & 0x14);'''
self.assert_all_Constants(e1, ['10.0', '6', '8', '3', '0x14'])
e2 = r'''char n = '\n', *prefix = "st_";'''
self.assert_all_Constants(e2, [r"'\n'", '"st_"'])
s1 = r'''int main() {
int i = 5, j = 6, k = 1;
if ((i=j && k == 1) || k > j)
printf("Hello, world\n");
return 0;
}'''
ps1 = self.parse(s1)
self.assert_all_Constants(ps1,
['5', '6', '1', '1', '"Hello, world\\n"', '0'])
self.assert_num_ID_refs(ps1, 'i', 1)
self.assert_num_ID_refs(ps1, 'j', 2)
def test_switchcase(self):
self._assert_ctoc_correct(r'''
int main() {
switch (myvar) {
case 10:
{
k = 10;
p = k + 1;
break;
}
case 20:
case 30:
return 20;
default:
break;
}
}
''')
def test(*args):
"""
Run unit tests. Only works inside source repo, not when installed.
"""
# unittest.main doesn't work because this isn't a module
# so we'll do it ourselves
print("-" * 79)
for clsname, cls in sorted(globals().items()):
if clsname.startswith("Test") and isinstance(cls, type):
o = cls()
for fnname in sorted(dir(o)):
if fnname.startswith("test"):
fn = getattr(o, fnname)
if callable(fn):
fn()
print()
print(tests_run, "tests passed.")
def setUp(self):
"""Stores a BeautifulSoup in self.soup."""
html = """
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>
Héllø World
</title>
<link href="styles/main.css" rel="stylesheet"/>
<meta content="Hello World" name="name"/>
</head>
<body>
<h1>
Hello, Wo®ld!
</h1>
</body>
</html>"""
self.soup = bs4.BeautifulSoup(html)
def setUp(self):
"""Stores a BeautifulSoup in self.soup."""
html = """
<!DOCTYPE html>
<html>
<head>
<title>
Hello Wó®ld
</title>
<link href="styles/main.css" rel="stylesheet"/>
</head>
<body>
<h1>
Héllo, World! ÚÑÍ¢ÓÐÉ
</h1>
</body>
</html>"""
self.soup = bs4.BeautifulSoup(html)
def test_no_duplicate_metas(self):
"""Tests that existing meta tags aren't duplicated."""
chrome_app_manifest = {'description': 'a déscription'}
root_path = 'path'
html = """
<!DOCTYPE html>
<html>
<head>
<title>
Hello Wó®ld
</title>
<meta name="description" content="tést description"/>
<link href="styles/main.css" rel="stylesheet"/>
</head>
<body>
<h1>
Héllo, World! ÚÑÍ¢ÓÐÉ
</h1>
</body>
</html>"""
soup = bs4.BeautifulSoup(html)
caterpillar.inject_misc_tags(soup, chrome_app_manifest, root_path, '')
metas = soup.findAll('meta', {'name': 'description'})
self.assertEqual(len(metas), 1)
self.assertEqual(metas[0]['content'], 'tést description')
def test_main(self):
out_dir = "clue/functional_tests/527ef1c3"
# Delete out_dir if it exists already
if os.path.exists(out_dir):
shutil.rmtree(out_dir)
config_path = "https://s3.amazonaws.com/data.clue.io/psp/examples/example_user_input.yml"
second_config_path = "clue/functional_tests/test_prot_query_alt_psp_on_clue.yml"
args_string = "-u {} -o {} -p {}".format(
config_path, out_dir, second_config_path).split()
args = prot_query.build_parser().parse_args(args_string)
prot_query.main(args)
self.assertTrue(os.path.exists(os.path.join(out_dir, "INTROSPECT_CONN.gct")))
self.assertTrue(os.path.exists(os.path.join(out_dir, "CONCATED_CONN.gct")))
self.assertTrue(os.path.exists(os.path.join(out_dir, "success.txt")))
# Alt config file only specified 2 cell lines (excludes YAPC)
self.assertFalse(os.path.exists(os.path.join(out_dir, "YAPC_CONN.gct")))
# Clean up
shutil.rmtree(out_dir)
def test_main1(self):
input_gct_path = os.path.join(FUNCTIONAL_TESTS_DIR,
"test_introspect_main.gct")
output_gct_path = os.path.join(FUNCTIONAL_TESTS_DIR,
"test_introspect_main_out.gct")
expected_gct_path = os.path.join(FUNCTIONAL_TESTS_DIR,
"test_introspect_main_expected.gct")
args_string = "-i {} -o {} -fa chd1".format(input_gct_path, output_gct_path)
args = introspect.build_parser().parse_args(args_string.split())
introspect.main(args)
# Read in output and expected gcts and confirm that they're equal
output_gct = parse(output_gct_path)
expected_gct = parse(expected_gct_path)
pd.util.testing.assert_almost_equal(expected_gct.data_df, output_gct.data_df, check_less_precise=2)
pd.testing.assert_frame_equal(expected_gct.row_metadata_df, output_gct.row_metadata_df)
pd.testing.assert_frame_equal(expected_gct.col_metadata_df, output_gct.col_metadata_df)
# Clean up
os.remove(output_gct_path)
def test_main2(self):
input_gct_path = os.path.join(FUNCTIONAL_TESTS_DIR,
"test_introspect_main.gct")
output_gct_path = os.path.join(FUNCTIONAL_TESTS_DIR,
"test_introspect_main_out2.gct")
expected_gct_path = os.path.join(FUNCTIONAL_TESTS_DIR,
"test_introspect_main_expected2.gct")
args_string = "-i {} -o {} -fa moa".format(input_gct_path, output_gct_path)
args = introspect.build_parser().parse_args(args_string.split())
introspect.main(args)
# Read in output and expected gcts and confirm that they're equal
output_gct = parse(output_gct_path)
expected_gct = parse(expected_gct_path)
pd.util.testing.assert_almost_equal(expected_gct.data_df, output_gct.data_df, check_less_precise=True)
pd.util.testing.assert_frame_equal(expected_gct.row_metadata_df, output_gct.row_metadata_df)
pd.util.testing.assert_frame_equal(expected_gct.col_metadata_df, output_gct.col_metadata_df)
# Clean up
os.remove(output_gct_path)
def test_main(self):
gct_path = os.path.join(functional_tests_dir, "test_annotate_gct_from_mapping_in.gct")
mapping_path = os.path.join(functional_tests_dir, "test_annotate_gct_from_mapping.tsv")
expected_gct_path = os.path.join(functional_tests_dir, "test_annotate_gct_from_mapping_expected.gct")
out_path = os.path.join(functional_tests_dir, "test_annotate_gct_from_mapping_out.gct")
args_string = "-i {} -m {} -o {} -f {}".format(
gct_path, mapping_path, out_path, "pert_iname")
args = agfm.build_parser().parse_args(args_string.split())
agfm.main(args)
# Read in expected and actual outputs
e_gct = parse(expected_gct_path)
out_gct = parse(out_path)
pd.util.testing.assert_frame_equal(e_gct.data_df, out_gct.data_df)
pd.util.testing.assert_frame_equal(e_gct.row_metadata_df, out_gct.row_metadata_df)
pd.util.testing.assert_frame_equal(e_gct.col_metadata_df, out_gct.col_metadata_df)
# Clean up
os.remove(out_path)
def test_main(self):
in_gct_path = os.path.join(FUNCTIONAL_TESTS_DIR, "test_tear_main.gct")
out_name = os.path.join(FUNCTIONAL_TESTS_DIR, "test_tear_out.gct")
args_string = ("-i {} -o {} -dm -p {}").format(
in_gct_path, out_name, "psp_production.cfg")
args = tear.build_parser().parse_args(args_string.split())
tear.main(args)
# Read in result
out_gct = parse(out_name)
e_values = np.array(
[[0., 4.07, -1.48, -10.71, 0.],
[4.43, -3.26, -0.23, 0., 1.48],
[0., 2.49, 2.50, -1.48, -0.86]])
self.assertTrue(np.allclose(e_values, out_gct.data_df, atol=1e-2))
# Clean up
os.remove(out_name)
def testDownload(self):
self.SetUpWorkdir(populate_bucket=True)
with _MockedInput('y'):
status = update.main([
'download',
'--dry-run',
'--bucket', self.paths.bucket,
'--config', self.paths.config_file,
'--sdk-root', self.paths.gms.sdk_root,
])
self.assertEqual(status, 0, 'the command should have succeeded.')
# sdk_root should contain zip contents, zip sha1, license
self.assertTrue(os.path.isfile(self.paths.gms.client_paths[0]))
self.assertTrue(os.path.isfile(self.paths.gms.lib_zip_sha1))
self.assertTrue(os.path.isfile(self.paths.gms.license))
self.assertEquals(_GetFileContent(self.paths.gms.license),
self.DEFAULT_LICENSE)
def testDownloadBot(self):
self.SetUpWorkdir(populate_bucket=True, bot_env=True)
# No need to type 'y' on bots
status = update.main([
'download',
'--dry-run',
'--bucket', self.paths.bucket,
'--config', self.paths.config_file,
'--sdk-root', self.paths.gms.sdk_root,
])
self.assertEqual(status, 0, 'the command should have succeeded.')
# sdk_root should contain zip contents, zip sha1, license
self.assertTrue(os.path.isfile(self.paths.gms.client_paths[0]))
self.assertTrue(os.path.isfile(self.paths.gms.lib_zip_sha1))
self.assertTrue(os.path.isfile(self.paths.gms.license))
self.assertEquals(_GetFileContent(self.paths.gms.license),
self.DEFAULT_LICENSE)
def testDownloadAlreadyUpToDate(self):
self.SetUpWorkdir(
populate_bucket=True,
existing_zip_sha1=self.DEFAULT_ZIP_SHA1)
status = update.main([
'download',
'--dry-run',
'--bucket', self.paths.bucket,
'--config', self.paths.config_file,
'--sdk-root', self.paths.gms.sdk_root,
])
self.assertEqual(status, 0, 'the command should have succeeded.')
# there should not be new files downloaded to sdk_root
self.assertFalse(os.path.isfile(os.path.join(self.paths.gms.client_paths[0],
'dummy_file')))
self.assertFalse(os.path.isfile(self.paths.gms.license))
def testDownloadAcceptedLicense(self):
self.SetUpWorkdir(
populate_bucket=True,
existing_license=self.DEFAULT_LICENSE)
# License already accepted, no need to type
status = update.main([
'download',
'--dry-run',
'--bucket', self.paths.bucket,
'--config', self.paths.config_file,
'--sdk-root', self.paths.gms.sdk_root,
])
self.assertEqual(status, 0, 'the command should have succeeded.')
# sdk_root should contain zip contents, zip sha1, license
self.assertTrue(os.path.isfile(self.paths.gms.client_paths[0]))
self.assertTrue(os.path.isfile(self.paths.gms.lib_zip_sha1))
self.assertTrue(os.path.isfile(self.paths.gms.license))
self.assertEquals(_GetFileContent(self.paths.gms.license),
self.DEFAULT_LICENSE)
def testDownloadRefusedLicense(self):
self.SetUpWorkdir(
populate_bucket=True,
existing_license='Old license')
with _MockedInput('n'):
status = update.main([
'download',
'--dry-run',
'--bucket', self.paths.bucket,
'--config', self.paths.config_file,
'--sdk-root', self.paths.gms.sdk_root,
])
self.assertEqual(status, 0, 'the command should have succeeded.')
# there should not be new files downloaded to sdk_root
self.assertFalse(os.path.isfile(os.path.join(self.paths.gms.client_paths[0],
'dummy_file')))
self.assertEquals(_GetFileContent(self.paths.gms.license),
'Old license')
def testDownloadNoAndroidSDK(self):
self.SetUpWorkdir(
populate_bucket=True,
existing_license='Old license')
non_existing_sdk_root = os.path.join(self.workdir, 'non_existing_sdk_root')
# Should not run, no typing needed
status = update.main([
'download',
'--dry-run',
'--bucket', self.paths.bucket,
'--config', self.paths.config_file,
'--sdk-root', non_existing_sdk_root,
])
self.assertEqual(status, 0, 'the command should have succeeded.')
self.assertFalse(os.path.isdir(non_existing_sdk_root))
def test_odin_init(self):
# Create a test file.
path = "./test_portfolio_id/"
main = path + IOFiles.main_file.value
handlers = path + IOFiles.handlers_file.value
settings = path + IOFiles.settings_file.value
strategy = path + IOFiles.strategy_file.value
fund = path + IOFiles.fund_file.value
odin_init(path)
# Assert that all of the requisite files exist.
self.assertTrue(os.path.isdir(path))
self.assertTrue(os.path.isfile(main))
self.assertTrue(os.path.isfile(handlers))
self.assertTrue(os.path.isfile(settings))
self.assertTrue(os.path.isfile(strategy))
self.assertTrue(os.path.isfile(fund))
shutil.rmtree(path)
def _set_up_config(self, domain, custom_archive):
# TODO: maybe provide NamespaceConfig.make_dirs?
# TODO: main() should create those dirs, c.f. #902
os.makedirs(os.path.join(self.config.live_dir, domain))
config_file = configobj.ConfigObj()
if custom_archive is not None:
os.makedirs(custom_archive)
config_file["archive_dir"] = custom_archive
else:
os.makedirs(os.path.join(self.config.default_archive_dir, domain))
for kind in ALL_FOUR:
config_file[kind] = os.path.join(self.config.live_dir, domain,
kind + ".pem")
config_file.filename = os.path.join(self.config.renewal_configs_dir,
domain + ".conf")
config_file.write()
return config_file
def setUp(self):
self.domain = 'example.org'
self.patches = [
mock.patch('certbot.main._get_and_save_cert'),
mock.patch('certbot.main.display_ops.success_installation'),
mock.patch('certbot.main.display_ops.success_renewal'),
mock.patch('certbot.main._init_le_client'),
mock.patch('certbot.main._suggest_donation_if_appropriate'),
mock.patch('certbot.main._report_new_cert'),
mock.patch('certbot.main._find_cert')]
self.mock_auth = self.patches[0].start()
self.mock_success_installation = self.patches[1].start()
self.mock_success_renewal = self.patches[2].start()
self.mock_init = self.patches[3].start()
self.mock_suggest_donation = self.patches[4].start()
self.mock_report_cert = self.patches[5].start()
self.mock_find_cert = self.patches[6].start()
def test_certonly_abspath(self):
cert = 'cert'
key = 'key'
chain = 'chain'
fullchain = 'fullchain'
with mock.patch('certbot.main.certonly') as mock_certonly:
self._call(['certonly', '--cert-path', cert, '--key-path', 'key',
'--chain-path', 'chain',
'--fullchain-path', 'fullchain'])
config, unused_plugins = mock_certonly.call_args[0]
self.assertEqual(config.cert_path, os.path.abspath(cert))
self.assertEqual(config.key_path, os.path.abspath(key))
self.assertEqual(config.chain_path, os.path.abspath(chain))
self.assertEqual(config.fullchain_path, os.path.abspath(fullchain))
def _test_renew_common(self, renewalparams=None, names=None,
assert_oc_called=None, **kwargs):
self._make_dummy_renewal_config()
with mock.patch('certbot.storage.RenewableCert') as mock_rc:
mock_lineage = mock.MagicMock()
mock_lineage.fullchain = "somepath/fullchain.pem"
if renewalparams is not None:
mock_lineage.configuration = {'renewalparams': renewalparams}
if names is not None:
mock_lineage.names.return_value = names
mock_rc.return_value = mock_lineage
with mock.patch('certbot.main.renew_cert') as mock_renew_cert:
kwargs.setdefault('args', ['renew'])
self._test_renewal_common(True, None, should_renew=False, **kwargs)
if assert_oc_called is not None:
if assert_oc_called:
self.assertTrue(mock_renew_cert.called)
else:
self.assertFalse(mock_renew_cert.called)
def test_unregister(self):
mocked_storage = mock.MagicMock()
mocked_storage.find_all.return_value = ["an account"]
self.mocks['account'].AccountFileStorage.return_value = mocked_storage
self.mocks['_determine_account'].return_value = (mock.MagicMock(), "foo")
cb_client = mock.MagicMock()
self.mocks['client'].Client.return_value = cb_client
config = mock.MagicMock()
unused_plugins = mock.MagicMock()
res = main.unregister(config, unused_plugins)
self.assertTrue(res is None)
self.assertTrue(cb_client.acme.deactivate_registration.called)
m = "Account deactivated."
self.assertTrue(m in self.mocks['get_utility']().add_message.call_args[0][0])
def test_perform1(self, mock_save):
self.sni.add_chall(self.achalls[0])
response = self.achalls[0].response(self.account_key)
mock_setup_cert = mock.MagicMock(return_value=response)
# pylint: disable=protected-access
self.sni._setup_challenge_cert = mock_setup_cert
responses = self.sni.perform()
mock_setup_cert.assert_called_once_with(self.achalls[0])
self.assertEqual([response], responses)
self.assertEqual(mock_save.call_count, 1)
# Make sure challenge config is included in main config
http = self.sni.configurator.parser.parsed[
self.sni.configurator.parser.config_root][-1]
self.assertTrue(
util.contains_at_depth(http, ['include', self.sni.challenge_conf], 1))
def test_is_site_enabled(self):
"""Test if site is enabled.
.. note:: This test currently fails for hard links
(which may happen if you move dirs incorrectly)
.. warning:: This test does not work when running using the
unittest.main() function. It incorrectly copies symlinks.
"""
self.assertTrue(self.config.is_site_enabled(self.vh_truth[0].filep))
self.assertFalse(self.config.is_site_enabled(self.vh_truth[1].filep))
self.assertTrue(self.config.is_site_enabled(self.vh_truth[2].filep))
self.assertTrue(self.config.is_site_enabled(self.vh_truth[3].filep))
with mock.patch("os.path.isdir") as mock_isdir:
mock_isdir.return_value = False
self.assertRaises(errors.ConfigurationError,
self.config.is_site_enabled,
"irrelevant")
def setUp(self):
self.ter1 = Terrain(100, 100) # all black
self.ter2 = Terrain(200, 200) # all white
for x in range(self.ter2.width):
for y in range(self.ter2.length):
self.ter2[x, y] = 1
self.ter3 = Terrain(100, 100) # main diagonal is increasing brightness downwards
for x in range(self.ter3.width):
for y in range(self.ter3.length):
if x == y:
self.ter3[x, y] = float(y) / self.ter3.length
self.ter4 = Terrain(200, 100) # checkerboard pattern
for x in range(self.ter4.width):
for y in range(self.ter4.length):
self.ter4[x, y] = 1 if (x + y) % 2 == 0 else 0
def unittest_main(*args, **kwargs):
if 'testRunner' in kwargs and kwargs['testRunner'] is None:
kwargs['testRunner'] = unittest.TextTestRunner
return unittest.main(*args, **kwargs)
def helper_setup(self, app):
main.SCREEN_SWITCH_DELAY = 0.001
def helper_load_switch_account(self, app):
"""
Helper method for loading the switch account screen and returning
the class handling this view.
"""
controller = app.controller
# TODO: use dispatch('on_release') on navigation drawer
controller.load_switch_account()
self.advance_frames(1)
switch_account = controller.switch_account
self.assertEqual(switch_account.__class__, main.SwitchAccount)
return switch_account
def helper_test_delete_last_account(self, app):
"""
Trying to delete the last account, should not crash the app,
refs #120.
"""
controller = app.controller
pywalib = controller.pywalib
manage_existing = controller.manage_existing
# makes sure there's only one account left
self.assertEqual(
len(pywalib.get_account_list()), 1)
# deletes it
delete_button_id = manage_existing.ids.delete_button_id
delete_button_id.dispatch('on_release')
# a confirmation popup should show
dialogs = controller.dialogs
self.assertEqual(len(dialogs), 1)
dialog = dialogs[0]
self.assertEqual(dialog.title, 'Are you sure?')
# confirm it
manage_existing.on_delete_account_yes(dialog)
# account was deleted dialog message
dialogs = controller.dialogs
self.assertEqual(len(dialogs), 1)
dialog = dialogs[0]
self.assertEqual(dialog.title, 'Account deleted, redirecting...')
controller.dismiss_all_dialogs()
self.advance_frames(1)
# verifies the account was deleted
self.assertEqual(len(pywalib.get_account_list()), 0)
# this should be done by the events, but doesn't seem to happen
# so we have to trigger it manually
controller.history.current_account = None
self.advance_frames(1)
# main test function
def unittest_main(*args, **kwargs):
if 'testRunner' in kwargs and kwargs['testRunner'] is None:
kwargs['testRunner'] = unittest.TextTestRunner
return unittest.main(*args, **kwargs)
def testMainHelp(self):
"""testing the help of the main"""
runner = CliRunner()
result = runner.invoke(main.entry_point, ['--help'])
expected_output = ('Usage: entry_point [OPTIONS] COMMAND [ARGS]...\n'
'\n'
'Options:\n'
' --help Show this message and exit.\n'
'\n'
'Commands:''\n'
' sqlite\n')
self.assertEqual(expected_output, str(result.output))
self.assertEqual(0, result.exit_code)
def testSQLiteRun(self, sqlite): #pylint: disable=unused-argument
"""testing the interaction with main and sqlite"""
runner = CliRunner()
result = runner.invoke(main.entry_point, ['sqlite'])
self.assertEqual(0, result.exit_code)
self.assertIsNone(result.exception)
self.assertIsNone(result.exc_info)
def call(arguments):
output = six.StringIO()
with mock.patch("sys.stdout", output):
with mock.patch("sys.argv", arguments):
main.main()
return str(output.getvalue())
def testArgumentInvalidFormat(self):
self.assertEqual('', main.argument_name(''))
self.assertEqual('', main.argument_name('arg=val'))
self.assertEqual('', main.argument_name('-arg=val'))
self.assertEqual('', main.argument_name('--argval'))
self.assertEqual('', main.argument_name('--=val'))
self.assertEqual('', main.argument_name('--='))