本文整理汇总了Python中tempdir.TempDir.dissolve方法的典型用法代码示例。如果您正苦于以下问题:Python TempDir.dissolve方法的具体用法?Python TempDir.dissolve怎么用?Python TempDir.dissolve使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tempdir.TempDir
的用法示例。
在下文中一共展示了TempDir.dissolve方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: SearchEngineTest
# 需要导入模块: from tempdir import TempDir [as 别名]
# 或者: from tempdir.TempDir import dissolve [as 别名]
class SearchEngineTest(unittest.TestCase):
def setUp(self):
self.tempdir = TempDir()
self.agent_home = self.tempdir.name
def tearDown(self):
self.tempdir.dissolve()
def test_encoding(self):
# given
se = SearchEngine(INDEX_KEY, self.agent_home)
headers = {
'From': '[email protected]',
'To': '=?utf-8?b?IsOEw7zDtiDDlsO8w6QiIDxmb2xrZXJAcGl4ZWxhdGVkLXByb2plY3Qub3Jn?=\n =?utf-8?b?PiwgRsO2bGtlciA8Zm9sa2VyQHBpeGVsYXRlZC1wcm9qZWN0Lm9yZz4=?=',
'Cc': '=?utf-8?b?IsOEw7zDtiDDlsO8w6QiIDxmb2xrZXJAcGl4ZWxhdGVkLXByb2plY3Qub3Jn?=\n =?utf-8?b?PiwgRsO2bGtlciA8Zm9sa2VyQHBpeGVsYXRlZC1wcm9qZWN0Lm9yZz4=?=',
'Subject': 'Some test mail',
}
# when
se.index_mail(LeapMail('mailid', 'INBOX', headers=headers)) # test_helper.pixelated_mail(extra_headers=headers, chash='mailid'))
result = se.search('folker')
self.assertEqual((['mailid'], 1), result)
示例2: SearchEngineTest
# 需要导入模块: from tempdir import TempDir [as 别名]
# 或者: from tempdir.TempDir import dissolve [as 别名]
class SearchEngineTest(unittest.TestCase):
def setUp(self):
self.tempdir = TempDir()
self.agent_home = self.tempdir.name
def tearDown(self):
self.tempdir.dissolve()
def test_encoding(self):
# given
se = SearchEngine(INDEX_KEY, self.agent_home)
headers = {
"From": "[email protected]",
"To": "=?utf-8?b?IsOEw7zDtiDDlsO8w6QiIDxmb2xrZXJAcGl4ZWxhdGVkLXByb2plY3Qub3Jn?=\n =?utf-8?b?PiwgRsO2bGtlciA8Zm9sa2VyQHBpeGVsYXRlZC1wcm9qZWN0Lm9yZz4=?=",
"Cc": "=?utf-8?b?IsOEw7zDtiDDlsO8w6QiIDxmb2xrZXJAcGl4ZWxhdGVkLXByb2plY3Qub3Jn?=\n =?utf-8?b?PiwgRsO2bGtlciA8Zm9sa2VyQHBpeGVsYXRlZC1wcm9qZWN0Lm9yZz4=?=",
"Subject": "Some test mail",
}
# when
se.index_mail(test_helper.pixelated_mail(extra_headers=headers, chash="mailid"))
result = se.search("folker")
self.assertEqual((["mailid"], 1), result)
示例3: test_use_build_script_instead_of_docker_file_if_available
# 需要导入模块: from tempdir import TempDir [as 别名]
# 或者: from tempdir.TempDir import dissolve [as 别名]
def test_use_build_script_instead_of_docker_file_if_available(self, docker_mock, res_mock, tempDir_mock):
# given
provider = DockerProvider(self._adapter, 'leap_provider', self._leap_provider_x509)
tempBuildDir = TempDir()
try:
tempDir_mock.return_value = tempBuildDir
tempBuildDir_name = tempBuildDir.name
with NamedTemporaryFile() as file:
res_mock.resource_exists.return_value = True
res_mock.resource_string.return_value = '#!/bin/bash\necho %s $PWD > %s' % (file.name, file.name)
# when
provider.initialize()
# then
res_mock.resource_exists.assert_called_with('pixelated.resources', 'init-pixelated-docker-context.sh')
res_mock.resource_string.assert_called_with('pixelated.resources', 'init-pixelated-docker-context.sh')
with open(file.name, "r") as input:
data = input.read().replace('\n', '')
self.assertEqual('%s %s' % (file.name, os.path.realpath(tempBuildDir_name)), data)
docker_mock.return_value.build.assert_called_once_with(path=tempBuildDir_name, tag='pixelated:latest', fileobj=None)
finally:
tempBuildDir.dissolve()
示例4: SearchEngineTest
# 需要导入模块: from tempdir import TempDir [as 别名]
# 或者: from tempdir.TempDir import dissolve [as 别名]
class SearchEngineTest(unittest.TestCase):
def setUp(self):
self.tempdir = TempDir()
self.agent_home = self.tempdir.name
def tearDown(self):
self.tempdir.dissolve()
def test_index_mail_secured_by_lock(self):
# given
soledad_querier = mock()
lock_stub = LockStub()
when(soledad_querier).get_index_masterkey().thenReturn(INDEX_KEY)
self.assertEqual(INDEX_KEY, soledad_querier.get_index_masterkey())
se = SearchEngine(soledad_querier, self.agent_home)
se._write_lock = lock_stub
headers = {
'From': '[email protected]',
'To': '[email protected]',
'Subject': 'Some test mail',
}
# when
se.index_mail(test_helper.pixelated_mail(extra_headers=headers))
# then
self.assertTrue(lock_stub.called)
def test_encoding(self):
# given
soledad_querier = mock()
when(soledad_querier).get_index_masterkey().thenReturn(INDEX_KEY)
se = SearchEngine(soledad_querier, self.agent_home)
headers = {
'From': '[email protected]',
'To': '=?utf-8?b?IsOEw7zDtiDDlsO8w6QiIDxmb2xrZXJAcGl4ZWxhdGVkLXByb2plY3Qub3Jn?=\n =?utf-8?b?PiwgRsO2bGtlciA8Zm9sa2VyQHBpeGVsYXRlZC1wcm9qZWN0Lm9yZz4=?=',
'Cc': '=?utf-8?b?IsOEw7zDtiDDlsO8w6QiIDxmb2xrZXJAcGl4ZWxhdGVkLXByb2plY3Qub3Jn?=\n =?utf-8?b?PiwgRsO2bGtlciA8Zm9sa2VyQHBpeGVsYXRlZC1wcm9qZWN0Lm9yZz4=?=',
'Subject': 'Some test mail',
}
# when
se.index_mail(test_helper.pixelated_mail(extra_headers=headers, chash='mailid'))
result = se.search('folker')
self.assertEqual((['mailid'], 1), result)
示例5: AppTestClient
# 需要导入模块: from tempdir import TempDir [as 别名]
# 或者: from tempdir.TempDir import dissolve [as 别名]
class AppTestClient(object):
INDEX_KEY = (
"\xde3?\x87\xff\xd9\xd3\x14\xf0\xa7>\x1f%C{\x16.\\\xae\x8c\x13\xa7\xfb\x04\xd4]+\x8d_\xed\xd1\x8d\x0bI"
"\x8a\x0e\xa4tm\xab\xbf\xb4\xa5\x99\x00d\xd5w\x9f\x18\xbc\x1d\xd4_W\xd2\xb6\xe8H\x83\x1b\xd8\x9d\xad"
)
ACCOUNT = "test"
MAIL_ADDRESS = "[email protected]"
def _initialize(self):
self._tmp_dir = TempDir()
self.accounts = {}
@defer.inlineCallbacks
def start_client(self, mode=UserAgentMode(is_single_user=True)):
self._initialize()
self._mode = mode
self._test_account = AppTestAccount(self.ACCOUNT, self._tmp_dir.name)
yield self._test_account.start()
self.cleanup = lambda: self._tmp_dir.dissolve()
# copy fields for single user tests
self.soledad = self._test_account.soledad
self.search_engine = self._test_account.search_engine
self.keymanager = self._test_account.keymanager
self.mail_sender = self._test_account.mail_sender
self.mail_store = self._test_account.mail_store
self.attachment_store = self._test_account.attachment_store
self.draft_service = self._test_account.draft_service
self.leap_session = self._test_account.leap_session
self.feedback_service = self._test_account.feedback_service
self.mail_service = self._test_account.mail_service
self.account = self._test_account.account
if mode.is_single_user:
self.service_factory = SingleUserServicesFactory(mode)
services = self._test_account.services
self.service_factory.add_session("someuserid", services)
self.resource = RootResource(self.service_factory)
self.resource.initialize()
else:
self.service_factory = StubServicesFactory(self.accounts, mode)
provider = mock()
provider.config = LeapConfig(self._tmp_dir.name)
self.resource = set_up_protected_resources(
RootResource(self.service_factory), provider, self.service_factory, checker=StubSRPChecker(provider)
)
@defer.inlineCallbacks
def create_user(self, account_name):
if self._mode.is_single_user:
raise Exception("Not supported in single user mode")
account = AppTestAccount(account_name, self._tmp_dir.name)
yield account.start()
self.accounts[account_name] = account
def _render(self, request, as_json=True):
def get_str(_str):
return json.loads(_str) if as_json else _str
def get_request_written_data(_=None):
written_data = request.getWrittenData()
if written_data:
return get_str(written_data)
resource = getChildForRequest(self.resource, request)
result = resource.render(request)
if isinstance(result, basestring):
return get_str(result), request
# result is NOT_DONE_YET
d = succeed(request) if request.finished else request.notifyFinish()
d.addCallback(get_request_written_data)
return d, request
def listenTCP(self, port=4567, host="127.0.0.1"):
reactor.listenTCP(port, PixelatedSite(self.resource), interface=host)
def run_on_a_thread(self, logfile="/tmp/app_test_client.log", port=4567, host="127.0.0.1"):
def _start():
self.listenTCP(port, host)
reactor.run()
process = multiprocessing.Process(target=_start)
process.start()
time.sleep(1)
return lambda: process.terminate()
def stop(self):
reactor.stop()
def get(self, path, get_args="", as_json=True, ajax=True, csrf="token"):
request = request_mock(path, ajax=ajax, csrf=csrf)
request.args = get_args
#.........这里部分代码省略.........
示例6: TestCli
# 需要导入模块: from tempdir import TempDir [as 别名]
# 或者: from tempdir.TempDir import dissolve [as 别名]
class TestCli(unittest.TestCase):
key = '0b660492d98c54412d3d91818de5a2ae0b3110850a12010768b80fb277f55aa6'.decode('hex')
iv = '9059d464b93397a2a98e8e1f00b596c6'.decode('hex')
length = 5
characters = 'abc'
domain = 'domain'
username = 'username'
password = 'password'
pin = '1234'
def setUp(self):
self.d = TempDir()
self.k = os.path.join(self.d.name, 'keyfile')
d = os.path.join(self.d.name, 'database')
cli.main(('init %s %s' % (self.k, d)).split(' '))
self.keyfile = Keyfile.load(self.k)
def tearDown(self):
self.d.dissolve()
@not_raises(AttributeError)
def test_init_defaults(self):
with TempDir() as d:
k = os.path.join(d.name, 'keyfile')
d = os.path.join(d.name, 'database')
cli.main(('init %s %s' % (k, d)).split(' '))
keyfile = Keyfile.load(k)
self.assertEqual(k, keyfile.path)
self.assertEqual(d, keyfile.database_path)
self.assertEqual(Keyfile.LENGTH, keyfile.length)
self.assertEqual(Keyfile.CHARACTERS, keyfile.characters)
keyfile.key
keyfile.iv
def test_init_override(self):
with TempDir() as d:
k = os.path.join(d.name, 'keyfile')
d = os.path.join(d.name, 'database')
cli.main(('init %s %s --key %s --iv %s --length %d --characters %s' % (k, d, self.key, self.iv, self.length, self.characters)).split(' '))
keyfile = Keyfile.load(k)
self.assertEqual(k, keyfile.path)
self.assertEqual(d, keyfile.database_path)
self.assertEqual(self.length, keyfile.length)
self.assertEqual(self.characters, keyfile.characters)
self.assertEqual(self.key, keyfile.key)
self.assertEqual(self.iv, keyfile.iv)
def test_add_defaults(self):
results = cli.main(
('add %s --domain %s --username %s --pin %s'
% (self.k, self.domain, self.username, self.pin)).split(' '))
with Database(self.keyfile) as d:
c = d.find(domain=self.domain, username=self.username)[0]
c.unlock(self.pin)
self.assertEqual(results, '\n'.join([c.domain, c.username, c.plainpassword]))
def test_add_override(self):
results = cli.main(
('add %s --domain %s --username %s --pin %s --length %d --characters %s'
% (self.k, self.domain, self.username, self.pin, self.length, self.characters)).split(' '))
parts = results.split('\n')
self.assertEqual(self.length, len(parts[2]))
for c in parts[2]:
self.assertIn(c, self.characters)
def test_add_provide_password(self):
results = cli.main(
('add %s --domain %s --username %s --pin %s --password %s'
% (self.k, self.domain, self.username, self.pin, self.password)).split(' '))
parts = results.split('\n')
self.assertEqual(self.password, parts[2])
def test_find_single_keyfile_single_result(self):
cli.main(
('add %s --domain %s --username %s --pin %s --password %s'
% (self.k, self.domain, self.username, self.pin, self.password)).split(' '))
results = cli.main(
('find %s --domain %s --username %s --pin %s'
% (self.k, self.domain, self.username, self.pin)).split(' '))
self.assertEqual(results, '\n'.join([self.domain, self.username, self.password]))
def test_find_single_keyfile_multiple_results(self):
cli.main(
('add %s --domain %s --username %s --pin %s --password %s'
% (self.k, self.domain, self.username, self.pin, self.password)).split(' '))
cli.main(
('add %s --domain %s --username %s --pin %s --password %s'
% (self.k, self.domain + '2', self.username, self.pin, self.password)).split(' '))
results = cli.main(
('find %s --domain %s --username %s --pin %s'
% (self.k, self.domain, self.username, self.pin)).split(' '))
self.assertEqual(results, '\n'.join([self.domain, self.username, '', self.domain + '2', self.username]))
def test_find_multiple_keyfiles_single_result(self):
k2 = os.path.join(self.d.name, 'keyfile2')
d2 = os.path.join(self.d.name, 'database2')
cli.main(('init %s %s' % (k2, d2)).split(' '))
cli.main(
('add %s --domain %s --username %s --pin %s --password %s'
#.........这里部分代码省略.........
示例7: ForkProviderTest
# 需要导入模块: from tempdir import TempDir [as 别名]
# 或者: from tempdir.TempDir import dissolve [as 别名]
class ForkProviderTest(unittest.TestCase):
def setUp(self):
self._tmpdir = TempDir()
self.root_path = self._tmpdir.name
self.runner = MagicMock(spec=Adapter)
self.provider = ForkProvider(self.root_path, self.runner)
self.provider.initialize()
def tearDown(self):
self._tmpdir.dissolve()
@patch('random.getrandbits')
def test_new_instance_can_be_added(self, randmock):
hashed_password = '1298e6969236f8efe078c2718acc793c6459b6d94720eb2443a9d04820ac68faacc0d79ba28c7b323be13a69d30bf19340cfcadab79c9f11f8b7388436409de9'
hex_salt = 31
randmock.return_value = 1
self.provider.add('test', 'password')
instance_path = join(self.root_path, 'test')
cfg_path = join(instance_path, 'agent.cfg')
data_path = join(instance_path, 'data')
gnupg_path = join(instance_path, 'gnupg')
self.assertTrue(isfile(cfg_path), 'No config file created')
self.assertTrue(isdir(instance_path), 'No folder for user has been created')
self.assertTrue(isdir(data_path), 'No maipile folder for user has been created')
self.assertTrue(isdir(gnupg_path), 'No gnupg folder for user has been created')
self.assert_config_file(cfg_path, 'test', hashed_password, hex_salt)
self.assertEqual(stat.S_IFDIR | stat.S_IRWXU, os.stat(instance_path).st_mode)
self.assertEqual(stat.S_IFDIR | stat.S_IRWXU, os.stat(data_path).st_mode)
self.assertEqual(stat.S_IFDIR | stat.S_IRWXU, os.stat(gnupg_path).st_mode)
@patch('random.getrandbits')
def test_random_salt_is_used(self, randmock):
hashed_password = 'ecb5c3382726fd831a54bc888d46c8813a18750220c2067cd7bc3fe4f7791261099426cabc6ad07220080943de2c331afddd75210d3ecdd7c5742c85146ace3c'
salt = 2
hex_salt = 32
randmock.return_value = salt
instance_path = join(self.root_path, 'test')
cfg_path = join(instance_path, 'agent.cfg')
self.provider.add('test', 'password')
self.assert_config_file(cfg_path, 'test', hashed_password, hex_salt)
def test_multiple_instances_can_be_added(self):
self.provider.add('first', 'password')
self.provider.add('second', 'password')
self.assertEqual(['first', 'second'], self.provider.list())
def test_instances_can_not_be_added_twice(self):
self.provider.add('test', 'password')
self.assertRaises(InstanceAlreadyExistsError, self.provider.add, 'test', 'password')
def test_remove_raises_exception_if_instance_does_not_exist(self):
self.assertRaises(ValueError, self.provider.remove, 'test')
def test_instances_can_be_removed(self):
self.provider.add('test', 'password')
self.provider.remove('test')
def test_that_non_existing_instance_cannot_be_started(self):
self.assertRaises(InstanceNotFoundError, self.provider.start, 'test')
def test_that_instance_can_be_started_and_gets_initialized(self):
self.provider.add('test', 'password')
self.provider.start('test')
self.runner.initialize.assert_called_with('test')
self.runner.start.assert_called_with('test')
def test_that_instance_cannot_be_started_twice(self):
self.provider.add('test', 'password')
self.provider.start('test')
self.assertRaises(InstanceAlreadyRunningError, self.provider.start, 'test')
def test_that_running_instances_are_in_runnig_list(self):
self._init_runner_memory_usage()
for name in ['one', 'two', 'three']:
self.provider.add(name, 'password')
self.provider.start(name)
self.provider.add('not-started', 'password')
self.assertEqual({'one', 'two', 'three'}, set(self.provider.list_running()))
def test_that_non_existing_instance_cannot_be_stopped(self):
self.assertRaises(InstanceNotRunningError, self.provider.stop, 'test')
def test_that_non_started_instance_cannot_be_stopped(self):
self.provider.add('test', 'password')
self.assertRaises(InstanceNotRunningError, self.provider.stop, 'test')
def test_that_running_instance_can_be_stopped(self):
#.........这里部分代码省略.........
示例8: SearchEngineTest
# 需要导入模块: from tempdir import TempDir [as 别名]
# 或者: from tempdir.TempDir import dissolve [as 别名]
class SearchEngineTest(unittest.TestCase):
def setUp(self):
self.tempdir = TempDir()
self.user_home = self.tempdir.name
def tearDown(self):
self.tempdir.dissolve()
def test_headers_encoding(self):
# given
se = SearchEngine(INDEX_KEY, self.user_home)
headers = {
'From': '[email protected]',
'To': '=?utf-8?b?IsOEw7zDtiDDlsO8w6QiIDxmb2xrZXJAcGl4ZWxhdGVkLXByb2plY3Qub3Jn?=\n =?utf-8?b?PiwgRsO2bGtlciA8Zm9sa2VyQHBpeGVsYXRlZC1wcm9qZWN0Lm9yZz4=?=',
'Cc': '=?utf-8?b?IsOEw7zDtiDDlsO8w6QiIDxmb2xrZXJAcGl4ZWxhdGVkLXByb2plY3Qub3Jn?=\n =?utf-8?b?PiwgRsO2bGtlciA8Zm9sa2VyQHBpeGVsYXRlZC1wcm9qZWN0Lm9yZz4=?=',
'Subject': 'Some test mail',
}
# when
se.index_mail(LeapMail('mailid', 'INBOX', headers=headers)) # test_helper.pixelated_mail(extra_headers=headers, chash='mailid'))
result = se.search('folker')
self.assertEqual((['mailid'], 1), result)
def test_contents_encoding_accents(self):
# given
se = SearchEngine(INDEX_KEY, self.user_home)
headers = {
'From': '[email protected]',
'To': '=?utf-8?b?IsOEw7zDtiDDlsO8w6QiIDxmb2xrZXJAcGl4ZWxhdGVkLXByb2plY3Qub3Jn?=\n =?utf-8?b?PiwgRsO2bGtlciA8Zm9sa2VyQHBpeGVsYXRlZC1wcm9qZWN0Lm9yZz4=?=',
'Cc': '=?utf-8?b?IsOEw7zDtiDDlsO8w6QiIDxmb2xrZXJAcGl4ZWxhdGVkLXByb2plY3Qub3Jn?=\n =?utf-8?b?PiwgRsO2bGtlciA8Zm9sa2VyQHBpeGVsYXRlZC1wcm9qZWN0Lm9yZz4=?=',
'Subject': 'Some test mail',
}
body = "When doing the search, it's not possible to find words with graphical accents, e.g.: 'coração', 'é', 'Fièvre', La Pluie d'été, 'não'."
# when
se.index_mail(LeapMail('mailid', 'INBOX', headers=headers, body=body)) # test_helper.pixelated_mail(extra_headers=headers, chash='mailid'))
result = se.search(u"'coração', 'é',")
self.assertEqual((['mailid'], 1), result)
result = se.search(u"Fièvre")
self.assertEqual((['mailid'], 1), result)
result = se.search(u"été")
self.assertEqual((['mailid'], 1), result)
def test_contents_encoding_special_characters(self):
# given
se = SearchEngine(INDEX_KEY, self.user_home)
headers = {
'From': '[email protected]',
'To': '=?utf-8?b?IsOEw7zDtiDDlsO8w6QiIDxmb2xrZXJAcGl4ZWxhdGVkLXByb2plY3Qub3Jn?=\n =?utf-8?b?PiwgRsO2bGtlciA8Zm9sa2VyQHBpeGVsYXRlZC1wcm9qZWN0Lm9yZz4=?=',
'Cc': '=?utf-8?b?IsOEw7zDtiDDlsO8w6QiIDxmb2xrZXJAcGl4ZWxhdGVkLXByb2plY3Qub3Jn?=\n =?utf-8?b?PiwgRsO2bGtlciA8Zm9sa2VyQHBpeGVsYXRlZC1wcm9qZWN0Lm9yZz4=?=',
'Subject': 'Some test mail',
}
body = "When doing the search, 您好 أهلا"
# when
se.index_mail(LeapMail('mailid', 'INBOX', headers=headers, body=body)) # test_helper.pixelated_mail(extra_headers=headers, chash='mailid'))
result = se.search(u"您好")
self.assertEqual((['mailid'], 1), result)
result = se.search(u"أهلا")
self.assertEqual((['mailid'], 1), result)
示例9: SmokeTest
# 需要导入模块: from tempdir import TempDir [as 别名]
# 或者: from tempdir.TempDir import dissolve [as 别名]
class SmokeTest(unittest.TestCase):
__slots__ = ('_run_method', '_shutdown_method', '_thread_name', '_thread')
class Server(object):
def __init__(self, run_method, shutdown_method, thread_name=None):
self._run_method = run_method
self._shutdown_method = shutdown_method
self._thread_name = thread_name
self._thread = None
def _start_server(self):
self._thread = threading.Thread(target=self._run_method)
self._thread.setDaemon(True)
if self._thread_name:
self._thread.setName(self._thread_name)
self._thread.start()
def __enter__(self):
self._start_server()
time.sleep(0.3) # let server start
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self._shutdown_method()
self._thread.join()
self._kill_subprocesses()
def _kill_subprocesses(self):
for child in psutil.Process(os.getpid()).children():
try:
p = psutil.Process(child.pid)
p.kill()
except psutil.Error:
pass
def setUp(self):
self._tmpdir = TempDir()
self.ssl_request = requests.Session()
self.ssl_request.mount('https://', EnforceTLSv1Adapter())
def tearDown(self):
self._tmpdir.dissolve()
def _dispatcher_manager(self):
fake_mailpile = os.path.join(os.path.dirname(__file__), 'fake_mailpile.py')
ssl_config = SSLConfig(certfile(), keyfile())
provider_ca = None
server = DispatcherManager(self._tmpdir.name, fake_mailpile, ssl_config, 'leap provider hostname', provider_ca, mailpile_virtualenv=INHERIT)
return SmokeTest.Server(server.serve_forever, server.shutdown, thread_name='PixelatedServerManager')
def _dispatcher_proxy(self):
dispatcher = DispatcherProxy(PixelatedDispatcherClient('localhost', DEFAULT_PORT, cacert=cafile(), assert_hostname=False), port=12345, certfile=certfile(),
keyfile=keyfile())
return SmokeTest.Server(dispatcher.serve_forever, dispatcher.shutdown, thread_name='PixelatedDispatcherProxy')
def _method(self, method, url, form_data=None, json_data=None, timeout=2.0):
if json_data:
headers = {'content-type': 'application/json'}
data = json.dumps(json_data)
cookies = None
else:
cookies = {'_xsrf': '2|7586b241|47c876d965112a2f547c63c95cbc44b1|1402910163'}
headers = None
data = form_data.copy()
data['_xsrf'] = '2|7586b241|47c876d965112a2f547c63c95cbc44b1|1402910163'
return method(url, data=data, headers=headers, cookies=cookies, timeout=timeout, verify=cafile())
def get(self, url):
return self.ssl_request.get(url, verify=cafile())
def put(self, url, form_data=None, json_data=None):
return self._method(self.ssl_request.put, url, form_data=form_data, json_data=json_data)
def post(self, url, form_data=None, json_data=None):
return self._method(self.ssl_request.post, url, form_data=form_data, json_data=json_data)
def test_dispatcher_run(self):
with self._dispatcher_manager():
self.assertSuccess(
self.post('https://localhost:4443/agents', json_data={'name': 'test', 'password': 'some password'}))
self.assertSuccess(self.get('https://localhost:4443/agents'), json_body={
'agents': [{'name': 'test', 'state': 'stopped', 'uri': 'http://localhost:4443/agents/test'}]})
self.assertSuccess(
self.put('https://localhost:4443/agents/test/state', json_data={'state': 'running'}))
self.assertSuccess(self.get('https://localhost:4443/agents/test/runtime'),
json_body={'state': 'running', 'port': 5000})
time.sleep(2) # let mailpile start
self.assertSuccess(self.get('http://localhost:5000/'))
self.assertSuccess(
self.put('https://localhost:4443/agents/test/state', json_data={'state': 'stopped'}))
def test_dispatcher_starts(self):
with self._dispatcher_proxy():
self.assertSuccess(self.get('https://localhost:12345/auth/login'))
def test_server_dispatcher_combination(self):
with self._dispatcher_manager():
with self._dispatcher_proxy():
#.........这里部分代码省略.........
示例10: DockerProviderTest
# 需要导入模块: from tempdir import TempDir [as 别名]
# 或者: from tempdir.TempDir import dissolve [as 别名]
class DockerProviderTest(unittest.TestCase):
def setUp(self):
self._provider_hostname = 'example.org'
self.users = MagicMock(spec=Users)
self._tmpdir = TempDir()
self.root_path = self._tmpdir.name
self._adapter = MagicMock(wraps=PixelatedDockerAdapter(self._provider_hostname))
self._adapter.docker_image_name.return_value = 'pixelated'
self._leap_provider_x509 = LeapProviderX509Info()
def tearDown(self):
self._tmpdir.dissolve()
def test_that_docker_api_version_is_pinned_to_v1_14(self):
self.assertEqual('1.14', DOCKER_API_VERSION)
@patch('pixelated.provider.docker.docker.Client')
def test_constructor_expects_docker_url(self, docker_mock):
DockerProvider(self.root_path, self._adapter, self._leap_provider_x509, 'some docker url')
@patch('pixelated.provider.docker.docker.Client')
def test_initialize_builds_docker_image(self, docker_mock):
# given
client = docker_mock.return_value
client.images.return_value = []
dockerfile = pkg_resources.resource_string('pixelated.resources', 'Dockerfile.pixelated')
# when
DockerProvider(self._adapter, 'leap_provider', self._leap_provider_x509, 'some docker url').initialize()
# then
docker_mock.assert_called_once_with(base_url="some docker url", version=DOCKER_API_VERSION)
client.build.assert_called_once_with(path=None, fileobj=StringIOMatcher(dockerfile), tag='pixelated:latest')
@patch('pixelated.provider.docker.docker.Client')
def test_initialize_downloads_docker_image_if_image_name_contains_slash(self, docker_mock):
# given
client = docker_mock.return_value
client.images.return_value = []
self._adapter.docker_image_name.return_value = 'pixelated/pixelated-user-agent'
# when
DockerProvider(self._adapter, 'leap_provider', self._leap_provider_x509, 'some docker url').initialize()
# then
docker_mock.assert_called_once_with(base_url='some docker url', version=DOCKER_API_VERSION)
client.pull.assert_called_with(tag='latest', repository='pixelated/pixelated-user-agent', stream=True)
@patch('pixelated.provider.docker.docker.Client')
def test_initialize_downloads_and_starts_logger_docker_image_if_not_yet_available(self, docker_mock):
# given
client = docker_mock.return_value
client.images.return_value = []
container = {'Id': 'some id'}
client.create_container.return_value = container
expected_syslog_tag = '.user_agent'
# when
DockerProvider(self._adapter, 'leap_provider', self._leap_provider_x509, 'some docker url').initialize()
# then
docker_mock.assert_called_once_with(base_url='some docker url', version=DOCKER_API_VERSION)
client.pull.assert_called_with(tag='latest', repository='pixelated/logspout', stream=True)
client.create_container.assert_called_once_with(
image='pixelated/logspout:latest',
command='syslog://localhost:514?append_tag=%s' % expected_syslog_tag,
volumes='/tmp/docker.sock',
environment={'HTTP_PORT': '51957'})
client.start.assert_called_once_with(
container='some id',
network_mode='host',
binds={'/var/run/docker.sock': {'bind': '/tmp/docker.sock', 'ro': False}})
@patch('pixelated.provider.docker.docker.Client')
def test_initialize_skips_image_build_or_download_if_already_available(self, docker_mock):
# given
client = docker_mock.return_value
client.images.return_value = [
{'Created': 1404833111,
'VirtualSize': 297017244,
'ParentId': '57885511c8444c2b89743bef8b89eccb65f302b2a95daa95dfcc9b972807b6db',
'RepoTags': ['pixelated:latest'],
'Id': 'b4f10a2395ab8dfc5e1c0fae26fa56c7f5d2541debe54263105fe5af1d263189',
'Size': 181956643}]
provider = DockerProvider(self._adapter, 'leap_provider', self._leap_provider_x509)
# when
provider.initialize()
# then
self.assertFalse(client.build.called)
self.assertFalse(provider.initializing)
@patch('pixelated.provider.docker.docker.Client')
def test_initialize_doesnt_download_logger_image_if_already_available(self, docker_mock):
# given
client = docker_mock.return_value
client.images.return_value = [
{'Created': 1404833111,
'VirtualSize': 297017244,
'ParentId': '57885511c8444c2b89743bef8b89eccb65f302b2a95daa95dfcc9b972807b6db',
#.........这里部分代码省略.........
示例11: RESTfulServerTest
# 需要导入模块: from tempdir import TempDir [as 别名]
# 或者: from tempdir.TempDir import dissolve [as 别名]
class RESTfulServerTest(unittest.TestCase):
mock_provider = None
ssl_config = None
server = None
@classmethod
def setUpClass(cls):
RESTfulServerTest.mock_provider = MagicMock(spec=Provider)
RESTfulServerTest.mock_users = MagicMock(spec=Users)
RESTfulServerTest.mock_authenticator = MagicMock(spec=Authenticator)
RESTfulServerTest.ssl_config = SSLConfig(certfile(),
keyfile())
RESTfulServerTest.server = RESTfulServer(RESTfulServerTest.ssl_config, RESTfulServerTest.mock_users, RESTfulServerTest.mock_authenticator, RESTfulServerTest.mock_provider)
RESTfulServerTest.server.server_forever_in_backgroud()
time.sleep(1) # let it get up to speed
@classmethod
def tearDownClass(cls):
RESTfulServerTest.server.shutdown()
print 'Stopped test server'
def setUp(self):
self.mock_provider = RESTfulServerTest.mock_provider
self.mock_provider.reset_mock()
self.mock_users.reset_mock()
self.mock_authenticator.reset_mock()
self.ssl_request = requests.Session()
self.ssl_request.mount('https://', EnforceTLSv1Adapter())
self._tmpdir = TempDir()
self._root_path = self._tmpdir.name
def tearDown(self):
self._tmpdir.dissolve()
def get(self, url):
return self.ssl_request.get(url, verify=cafile())
def put(self, url, data=None):
if data:
data = json.dumps(data)
return self.ssl_request.put(url, data=data, headers={'content-type': 'application/json'}, verify=cafile())
def post(self, url, data=None):
if data:
data = json.dumps(data)
return self.ssl_request.post(url, data=data, headers={'content-type': 'application/json'}, verify=cafile())
def delete(self, url):
return self.ssl_request.delete(url, verify=cafile())
def assertSuccessJson(self, dict, response):
self.assertEqual(200, response.status_code)
self.assertEquals('application/json', response.headers['content-type'])
self.assertEqual(dict, response.json())
def assertInternalError(self, response):
self.assertEqual(500, response.status_code)
def test_list_empty_agents(self):
# given
self.mock_provider.status.return_value = {'state': 'stopped'}
self.mock_users.list.return_value = []
# when
r = self.get('https://localhost:4443/agents')
# then
self.assertSuccessJson({'agents': []}, r)
def test_list_agents(self):
# given
self.mock_provider.status.return_value = {'state': 'stopped'}
self.mock_provider.status.side_effect = None
self.mock_users.list.return_value = ['first', 'second']
# when
r = self.get('https://localhost:4443/agents')
# then
self.assertSuccessJson(
{'agents': [
{'name': 'first', 'state': 'stopped', 'uri': 'http://localhost:4443/agents/first'},
{'name': 'second', 'state': 'stopped', 'uri': 'http://localhost:4443/agents/second'}
]}, r)
def test_add_agent(self):
# given
self.mock_provider.status.return_value = {'state': 'stopped'}
payload = {'name': 'first', 'password': 'some password'}
# when
r = self.post('https://localhost:4443/agents', data=payload)
# then
#.........这里部分代码省略.........
示例12: ForkProviderTest
# 需要导入模块: from tempdir import TempDir [as 别名]
# 或者: from tempdir.TempDir import dissolve [as 别名]
class ForkProviderTest(unittest.TestCase):
def setUp(self):
self._tmpdir = TempDir()
self.root_path = self._tmpdir.name
self.runner = MagicMock(spec=Adapter)
self.provider = ForkProvider(self.runner)
self.provider.initialize()
def tearDown(self):
self._tmpdir.dissolve()
def test_instances_can_be_removed(self):
user_config = UserConfig('test', join(self.root_path, 'test'))
os.makedirs(join(user_config.path, 'data'))
self.provider.remove(user_config)
def test_that_instance_can_be_started_and_gets_initialized(self):
self.provider.start(self._user_config('test'))
self.runner.initialize.assert_called_with('test')
self.runner.start.assert_called_with('test')
def test_that_instance_cannot_be_started_twice(self):
user_config = self._user_config('test')
self.provider.start(user_config)
self.assertRaises(InstanceAlreadyRunningError, self.provider.start, user_config)
def test_that_running_instances_are_in_runnig_list(self):
self._init_runner_memory_usage()
for name in ['one', 'two', 'three']:
self.provider.start(self._user_config(name))
self.assertEqual({'one', 'two', 'three'}, set(self.provider.list_running()))
def test_that_non_existing_instance_cannot_be_stopped(self):
self.assertRaises(InstanceNotRunningError, self.provider.stop, 'test')
def test_that_non_started_instance_cannot_be_stopped(self):
self.assertRaises(InstanceNotRunningError, self.provider.stop, UserConfig('not-started', None))
def test_that_running_instance_can_be_stopped(self):
process = MagicMock(spec=ForkedProcess)
self.runner.start.return_value = process
user_config = self._user_config('test')
self.provider.start(user_config)
self.provider.stop(user_config.username)
process.terminate.assert_called_once_with()
def test_that_instance_cannot_be_stopped_twice(self):
self.provider.start(self._user_config('test'))
self.provider.stop('test')
self.assertRaises(InstanceNotRunningError, self.provider.stop, 'test')
def test_that_status_returns_current_port(self):
process = MagicMock(spec=ForkedProcess(None, 1234))
process.port = 1234
self.runner.start.return_value = process
self.provider.start(self._user_config('test'))
status = self.provider.status('test')
self.assertEqual({'port': 1234, 'state': 'running'}, status)
def assert_config_file(self, filename, name, hashed_password, salt):
with open(filename, 'r') as file:
content = file.read()
self.assertEqual('[agent]\nname = %s\nhashed_password = %s\nsalt = %s\n\n' % (name, hashed_password, salt),
content)
def test_memory_usage_zero_if_no_processes(self):
self.assertEqual({'total_usage': 0, 'average_usage': 0, 'agents': []}, self.provider.memory_usage())
def test_memory_usage_with_process(self):
# given
process = MagicMock(spec=ForkedProcess(None, 1234))
process.port = 1234
process.memory_usage.return_value = 1024
self.runner.start.return_value = process
self.provider.start(self._user_config('test'))
# when
usage = self.provider.memory_usage()
# then
self.assertEqual({'total_usage': 1024,
'average_usage': 1024,
'agents': [
{'name': 'test', 'memory_usage': 1024}
]}, usage)
@patch('pixelated.provider.fork.psutil.virtual_memory')
def test_that_instance_cannot_be_started_with_too_little_memory_left(self, vm_mock):
# given
svmem = namedtuple('svmem', ['free'])
free_memory = 1024 * 1024
vm_mock.return_value = svmem(free_memory)
#.........这里部分代码省略.........
示例13: TestDatabase
# 需要导入模块: from tempdir import TempDir [as 别名]
# 或者: from tempdir.TempDir import dissolve [as 别名]
class TestDatabase(unittest.TestCase):
domain = 'domain'
username = 'username'
plainpassword = 'password'
cipherpassword = '69e00ec7020a4d22'.decode('hex')
pin = '1234'
key = hashlib.sha256(domain + username + pin).digest()
iv = 'a3206f4194d1d7a252a9fe24b7b063b9'.decode('hex')
def setUp(self):
self.d = TempDir()
self.keyfile_path = os.path.join(self.d.name, 'keyfile')
self.database_path = os.path.join(self.d.name, 'database')
self.keyfile = K.create(
self.keyfile_path,
self.database_path)
D.create(self.keyfile)
def tearDown(self):
self.d.dissolve()
@raises(IOError)
def test_create_database_exists(self):
D.create(self.keyfile)
@raises(AttributeError)
def test_enter_missing_key(self):
del self.keyfile.key
with D(self.keyfile):
pass
@raises(ValueError)
def test_enter_invalid_key(self):
self.keyfile.key = 'not a key'
with D(self.keyfile):
pass
@raises(ValueError)
def test_enter_incorrect_key(self):
self.keyfile.key = '1b660492d98c54412d3d91818de5a2ae0b3110850a12010768b80fb277f55aa5'.decode('hex')
with D(self.keyfile):
pass
@raises(AttributeError)
def test_enter_missing_iv(self):
del self.keyfile.iv
with D(self.keyfile):
pass
@raises(ValueError)
def test_enter_invalid_iv(self):
self.keyfile.iv = 'not an iv'
with D(self.keyfile):
pass
@raises(ValueError)
def test_enter_incorrect_iv(self):
self.keyfile.iv = 'a059d464b93397a2a98e8e1f00b596c7'.decode('hex')
with D(self.keyfile):
pass
@raises(AttributeError)
def test_enter_missing_path(self):
del self.keyfile.database_path
with D(self.keyfile):
pass
@raises(IOError)
def test_enter_unreadable_path(self):
self.keyfile.database_path = '/nopermission'
with D(self.keyfile):
pass
@raises(ValueError)
def test_enter_not_a_database_path(self):
self.keyfile.database_path = os.path.join(self.d.name, 'database')
with open(self.keyfile.database_path, 'wb') as f:
f.write(Random.new().read(10))
with D(self.keyfile):
pass
def test_exit_saves_changes(self):
c = C(self.domain, self.username, cipherpassword=self.cipherpassword, iv=self.iv)
with D(self.keyfile) as d:
d.add(c, self.pin)
with D(self.keyfile) as d:
self.assertEqual(
[c],
d.find(self.domain, self.username))
def test_add(self):
c1 = C(self.domain, self.username, cipherpassword=self.cipherpassword, iv=self.iv)
with D(self.keyfile) as d:
d.add(c1, self.pin)
c2 = d.find(self.domain, self.username)[0]
print c1
print c2
self.assertEqual(self.plainpassword, c2.unlock(self.pin))
#.........这里部分代码省略.........
示例14: UsersTest
# 需要导入模块: from tempdir import TempDir [as 别名]
# 或者: from tempdir.TempDir import dissolve [as 别名]
class UsersTest(unittest.TestCase):
def setUp(self):
self._tmpdir = TempDir()
self.root_path = self._tmpdir.name
self.users = Users(self.root_path)
def test_that_constructor_throws_exception_if_root_path_does_not_exist(self):
self.assertRaises(ValueError, Users, '/does/not/exist')
def tearDown(self):
self._tmpdir.dissolve()
def test_add_user(self):
self.users.add('name')
def test_user_cannot_be_added_twice(self):
self.users.add('name')
self.assertRaises(UserAlreadyExistsError, self.users.add, 'name')
def test_list_empty(self):
self.assertEqual([], self.users.list())
def test_list_single_user(self):
self.users.add('name')
self.assertEqual(['name'], self.users.list())
def test_get_user_config_throws_exception_if_user_not_exists(self):
self.assertRaises(UserNotExistError, self.users.config, 'name')
def test_add_user_creates_data_folder_and_config(self):
self.users.add('name')
data_path = join(self.root_path, 'name')
config_file = join(data_path, 'user.cfg')
self.assertTrue(exists(data_path))
self.assertTrue(exists(config_file))
def test_add_user_does_not_override_existing_config(self):
data_path = join(self.root_path, 'name')
config_file = join(data_path, 'user.cfg')
mkdir(data_path)
with open(config_file, 'w') as fd:
fd.write('[section]\none = first value\ntwo = second value\n\n')
self.users.add('name')
data_path = join(self.root_path, 'name')
config_file = join(data_path, 'user.cfg')
with open(config_file, 'r') as fd:
self.assertEqual('[section]\none = first value\ntwo = second value\n\n', fd.read())
def test_add_validates_username(self):
self.users.add('a_name.with-valid-chars')
with self.assertRaises(ValueError):
self.users.add('CapitalLetters')
with self.assertRaises(ValueError):
self.users.add('some/name/with/slashes')
with self.assertRaises(ValueError):
self.users.add('name with spaces')
with self.assertRaises(ValueError):
self.users.add('name=with%&')
def test_loads_all_existing_users_on_startup(self):
user1_data_path = join(self.root_path, 'user1')
mkdir(user1_data_path)
user1_config_path = join(self.root_path, 'user1', 'user.cfg')
with open(user1_config_path, 'w') as fd:
fd.write('[section]\none = first value\ntwo = second value\n\n')
users = Users(self.root_path)
self.assertEqual(['user1'], users.list())
self.assertEqual('first value', users.config('user1')['section.one'])
def test_update_user_config(self):
self.users.add('name')
config = self.users.config('name')
config['foo.bar'] = 'some value'
self.users.update_config(config)
config = self.users.config('name')
self.assertEqual('some value', config['foo.bar'])
def test_has_user(self):
self.users.add('name')
self.assertTrue(self.users.has_user('name'))
self.assertFalse(self.users.has_user('other'))
示例15: DockerProviderTest
# 需要导入模块: from tempdir import TempDir [as 别名]
# 或者: from tempdir.TempDir import dissolve [as 别名]
class DockerProviderTest(unittest.TestCase):
def setUp(self):
self._tmpdir = TempDir()
self.root_path = self._tmpdir.name
self._adapter = PixelatedDockerAdapter()
def tearDown(self):
self._tmpdir.dissolve()
def test_constructor_expects_docker_url(self):
DockerProvider(self.root_path, self._adapter, 'leap_provider', 'some docker url')
@patch('pixelated.provider.docker.docker.Client')
def test_initialize_builds_docker_image(self, docker_mock):
# given
client = docker_mock.return_value
client.images.return_value = []
dockerfile = pkg_resources.resource_string('pixelated.resources', 'Dockerfile.pixelated')
# when
DockerProvider(self.root_path, self._adapter, 'leap_provider', 'some leap ca', 'some docker url').initialize()
# then
docker_mock.assert_called_once_with(base_url="some docker url")
client.build.assert_called_once_with(path=None, fileobj=StringIOMatcher(dockerfile), tag='pixelated:latest')
@patch('pixelated.provider.docker.docker.Client')
def test_initialize_skips_image_build_if_available(self, docker_mock):
# given
client = docker_mock.return_value
client.images.return_value = [{'Created': 1404833111, 'VirtualSize': 297017244, 'ParentId': '57885511c8444c2b89743bef8b89eccb65f302b2a95daa95dfcc9b972807b6db', 'RepoTags': ['pixelated:latest'], 'Id': 'b4f10a2395ab8dfc5e1c0fae26fa56c7f5d2541debe54263105fe5af1d263189', 'Size': 181956643}]
# when
DockerProvider(self.root_path, self._adapter, 'leap_provider', 'some docker url').initialize()
# then
self.assertFalse(client.build.called)
@patch('pixelated.provider.docker.docker.Client')
def test_reports_initializing_while_initialize_is_running(self, docker_mock):
# given
client = docker_mock.return_value
client.images.return_value = []
def build(path, fileobj, tag):
sleep(0.2)
return []
client.build.side_effect = build
provider = DockerProvider(self.root_path, self._adapter, 'some provider', 'some provider ca', 'some docker url')
self.assertTrue(provider.initializing)
# when
t = Thread(target=provider.initialize) # move to thread so that initializing behaviour is observable
t.start()
# then
sleep(0.1)
self.assertTrue(provider.initializing)
t.join()
self.assertFalse(provider.initializing)
@patch('pixelated.provider.docker.LeapProvider')
@patch('pixelated.provider.docker.LeapSecureRemotePassword')
def test_throws_initializing_exception_while_initializing(self, leap_provider_mock, leap_srp_mock):
# given
provider = DockerProvider(self.root_path, self._adapter, 'provider url', 'provider ca', 'some docker url')
# when/then
self.assertRaises(ProviderInitializingException, provider.start, 'test')
self.assertRaises(ProviderInitializingException, provider.add, 'test', 'password')
self.assertRaises(ProviderInitializingException, provider.remove, 'test')
self.assertRaises(ProviderInitializingException, provider.list)
self.assertRaises(ProviderInitializingException, provider.list_running)
self.assertRaises(ProviderInitializingException, provider.stop, 'test')
self.assertRaises(ProviderInitializingException, provider.status, 'test')
self.assertRaises(ProviderInitializingException, provider.authenticate, 'test', 'password')
self.assertRaises(ProviderInitializingException, provider.memory_usage)
def test_add(self):
self._create_initialized_provider(self.root_path, self._adapter, 'some docker url').add('test', 'password')
instance_path = join(self.root_path, 'test')
data_dir = join(instance_path, 'data')
cfg_file = join(instance_path, BaseProvider.CFG_FILE_NAME)
self.assertTrue(isdir(instance_path), 'No folder for user has been created')
self.assertTrue(isdir(data_dir), 'No folder for pixelated has been created')
self.assertTrue(isfile(cfg_file), 'No config file had been created')
@patch('pixelated.provider.docker.docker.Client')
def test_that_non_existing_instance_cannot_be_started(self, docker_mock):
provider = self._create_initialized_provider(self.root_path, self._adapter, 'some docker url')
self.assertRaises(InstanceNotFoundError, provider.start, 'test')
@patch('pixelated.provider.docker.docker.Client')
def test_that_instance_can_be_started(self, docker_mock):
client = docker_mock.return_value
#.........这里部分代码省略.........