当前位置: 首页>>代码示例>>Python>>正文


Python tempdir.TempDir类代码示例

本文整理汇总了Python中tempdir.TempDir的典型用法代码示例。如果您正苦于以下问题:Python TempDir类的具体用法?Python TempDir怎么用?Python TempDir使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了TempDir类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_use_build_script_instead_of_docker_file_if_available

    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()
开发者ID:Meistache,项目名称:pixelated-dispatcher,代码行数:25,代码来源:docker_provider_test.py

示例2: SearchEngineTest

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)
开发者ID:EderRoger,项目名称:pixelated-user-agent,代码行数:25,代码来源:test_search.py

示例3: SearchEngineTest

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)
开发者ID:rdoh,项目名称:pixelated-user-agent,代码行数:25,代码来源:test_search.py

示例4: SearchEngineTest

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)
开发者ID:amukiza,项目名称:pixelated-user-agent,代码行数:50,代码来源:test_search.py

示例5: setUp

 def setUp(self):
     self.users = MagicMock(spec=Users)
     self._tmpdir = TempDir()
     self.root_path = self._tmpdir.name
     self._adapter = MagicMock(wraps=PixelatedDockerAdapter())
     self._adapter.docker_image_name.return_value = 'pixelated'
     self._leap_provider_x509 = LeapProviderX509Info()
开发者ID:xenobyte,项目名称:pixelated-dispatcher,代码行数:7,代码来源:docker_provider_test.py

示例6: setUp

 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)
开发者ID:WilliamMayor,项目名称:pinscher,代码行数:8,代码来源:test_database.py

示例7: setUp

    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
开发者ID:Meistache,项目名称:pixelated-dispatcher,代码行数:11,代码来源:manager_test.py

示例8: __enter__

    def __enter__(self):
        self.tempdir_obj = TempDir()
        tempdir = self.tempdir_obj.__enter__()
        logfile = join(tempdir, self.description + "out")
        os.mkfifo(logfile)
        bash_command = "{} 2>&1 | tee -i --output-error=warn {} | tee -i --output-error=warn {}_log.txt".format(
            self.spawn_cmd, pipes.quote(logfile), self.description)

        self.pane = check_output([
            'tmux', 'split-window', '-hdP',
            '-F', '#{pane_id}', '-t', pane,
            'bash', '-c', bash_command]).strip()

        self.proc = Expect(os.open(logfile, os.O_RDONLY | os.O_NONBLOCK), quiet=True)
        self.proc.expect("(rr) ")
        return self
开发者ID:mewbak,项目名称:panda,代码行数:16,代码来源:diverge.py

示例9: ForkProviderTest

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):
#.........这里部分代码省略.........
开发者ID:mmircea16,项目名称:pixelated-dispatcher,代码行数:101,代码来源:provider_test.py

示例10: RRInstance

class RRInstance(object):
    def __init__(self, description, rr_replay, source_pane):
        self.description = description
        self.spawn_cmd = "{} replay {}".format(
            pipes.quote(cli_args.rr), pipes.quote(rr_replay))
        self.source_pane = source_pane

        self.breakpoints = {}
        self.watches_set = 0

    def __repr__(self):
        return "RRInstance({!r})".format(self.description)

    # Runs in child process.
    def sendline(self, msg):
        check_call(['tmux', 'send-keys', '-t', self.pane, '-l', msg])
        check_call(['tmux', 'send-keys', '-t', self.pane, 'ENTER'])

    # Runs in child process.
    def kill(self):
        check_call(['tmux', 'kill-pane', '-t', self.pane])

    def __enter__(self):
        self.tempdir_obj = TempDir()
        tempdir = self.tempdir_obj.__enter__()
        logfile = join(tempdir, self.description + "out")
        os.mkfifo(logfile)
        bash_command = "{} 2>&1 | tee -i --output-error=warn {} | tee -i --output-error=warn {}_log.txt".format(
            self.spawn_cmd, pipes.quote(logfile), self.description)

        self.pane = check_output([
            'tmux', 'split-window', '-hdP',
            '-F', '#{pane_id}', '-t', pane,
            'bash', '-c', bash_command]).strip()

        self.proc = Expect(os.open(logfile, os.O_RDONLY | os.O_NONBLOCK), quiet=True)
        self.proc.expect("(rr) ")
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type:
            self.kill()
        self.tempdir_obj.__exit__(exc_type, exc_value, traceback)

    def gdb(self, *args, **kwargs):
        timeout = kwargs.get('timeout', None)
        cmd = " ".join(map(str, args))
        print "(rr-{}) {}".format(self.description, cmd)
        sys.stdout.flush()

        while True:
            try:
                os.read(self.proc.fd, 1024)
            except OSError as e:
                if e.errno in [EAGAIN, EWOULDBLOCK]:
                    break
                else:
                    raise
        self.sendline(cmd)

        try:
            output = self.proc.expect("(rr) ", timeout=timeout)
        except TimeoutExpired:
            print self.proc.sofar
            print "EXCEPTION!"
            sys.stdout.flush()

        return output

    def quit(self):
        self.gdb("set confirm off")
        self.sendline("quit")

    def breakpoint(self, break_arg):
        result = self.gdb("break", break_arg)
        bp_num = int(re.search(r"Breakpoint ([0-9]+) at", result).group(1))
        self.breakpoints[break_arg] = bp_num

    def disable_all(self):
        self.gdb("disable")

    def enable(self, break_arg):
        self.gdb("enable", self.breakpoints[break_arg])

    def condition(self, break_arg, cond):
        self.gdb("condition", self.breakpoints[break_arg], cond)

    def condition_instr(self, break_arg, op, instr):
        if not hasattr(self, 'instr_count_ptr'):
            self.instr_count_ptr = self.get_value(
                "&cpus->tqh_first->rr_guest_instr_count")
        self.condition(
            break_arg, "*(uint64_t *){} {} {}".format(self.instr_count_ptr, op, instr))

    def get_value(self, value_str):
        result = self.gdb("print/u", value_str)
        re_result = re.search(r"\$[0-9]+ = ([0-9]+)", result)
        if re_result:
            return long(re_result.group(1))
        else:
#.........这里部分代码省略.........
开发者ID:mewbak,项目名称:panda,代码行数:101,代码来源:diverge.py

示例11: setUp

 def setUp(self):
     self._tmpdir = TempDir()
     self.root_path = self._tmpdir.name
     self._adapter = PixelatedDockerAdapter()
开发者ID:mmircea16,项目名称:pixelated-dispatcher,代码行数:4,代码来源:docker_provider_test.py

示例12: setUp

 def setUp(self):
     self._tmpdir = TempDir()
     self.ssl_request = requests.Session()
     self.ssl_request.mount('https://', EnforceTLSv1Adapter())
开发者ID:mmircea16,项目名称:pixelated-dispatcher,代码行数:4,代码来源:smoke_test.py

示例13: setUp

 def setUp(self):
     self._tmpdir = TempDir()
     self.root_path = self._tmpdir.name
     self.users = Users(self.root_path)
开发者ID:vivekbsable,项目名称:pixelated-dispatcher,代码行数:4,代码来源:users_test.py

示例14: AppTestClient

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
#.........这里部分代码省略.........
开发者ID:akjones,项目名称:pixelated-user-agent,代码行数:101,代码来源:app_test_client.py

示例15: setUp

 def setUp(self):
     self.tempdir = TempDir()
     self.user_home = self.tempdir.name
开发者ID:carriercomm,项目名称:pixelated-user-agent,代码行数:3,代码来源:test_search.py


注:本文中的tempdir.TempDir类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。