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


Python TempDirectory.makedir方法代码示例

本文整理汇总了Python中testfixtures.TempDirectory.makedir方法的典型用法代码示例。如果您正苦于以下问题:Python TempDirectory.makedir方法的具体用法?Python TempDirectory.makedir怎么用?Python TempDirectory.makedir使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在testfixtures.TempDirectory的用法示例。

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

示例1: GitHelper

# 需要导入模块: from testfixtures import TempDirectory [as 别名]
# 或者: from testfixtures.TempDirectory import makedir [as 别名]
class GitHelper(object):

    repo = 'local/'

    def setUp(self):
        self.dir = TempDirectory()
        self.addCleanup(self.dir.cleanup)

    def git(self, command, repo=None):
        repo_path = self.dir.getpath(repo or self.repo)
        try:
            return check_output(['git'] + command.split(), cwd=repo_path, stderr=STDOUT)
        except CalledProcessError as e:
            self.fail(e.output)

    def git_rev_parse(self, label, repo=None):
        return self.git('rev-parse --verify -q --short '+label, repo).strip()

    def check_tags(self, expected, repo=None):
        actual = {}
        for tag in self.git('tag', repo).split():
            actual[tag] = self.git_rev_parse(tag, repo)
        compare(expected, actual=actual)

    def make_repo_with_content(self, repo):
        if not os.path.exists(self.dir.getpath(repo)):
            self.dir.makedir(repo)
        self.git('init', repo)
        self.dir.write(repo + 'a', 'some content')
        self.dir.write(repo + 'b', 'other content')
        self.dir.write(repo + 'c', 'more content')
        self.git('add .', repo)
        self.git('commit -m initial', repo)
开发者ID:cjw296,项目名称:ansible-role-createtag,代码行数:35,代码来源:git.py


示例2: Test_archivepgsql_backup_invocation

# 需要导入模块: from testfixtures import TempDirectory [as 别名]
# 或者: from testfixtures.TempDirectory import makedir [as 别名]
class Test_archivepgsql_backup_invocation(TestCase):
    ARCHIVEPGSQL_PATH = os.path.join('bbpgsql', 'cmdline_scripts')
    CONFIG_FILE = 'config.ini'
    exe_script = 'archivepgsql'

    def setUp(self):
        self.setup_environment()
        self.setup_config()
        self.execution_sequence = 0

    def setup_environment(self):
        self.env = deepcopy(os.environ)
        self.env['PATH'] = ''.join([
            self.env['PATH'],
            ':',
            self.ARCHIVEPGSQL_PATH])
        self.tempdir = TempDirectory()
        self.data_dir = self.tempdir.makedir('pgsql_data')
        self.archive_dir = self.tempdir.makedir('pgsql_archive')

    def setup_config(self):
        self.config_path = os.path.join(self.tempdir.path, self.CONFIG_FILE)
        self.config_dict = {
            'General': {
                'pgsql_data_directory': self.data_dir,
            },
            'Snapshot': {
                'driver': 'memory',
            },
        }
        write_config_to_filename(self.config_dict, self.config_path)
        self.config = get_config_from_filename_and_set_up_logging(
            self.config_path
        )

    def tearDown(self):
        self.tempdir.cleanup()

    @patch('bbpgsql.archive_pgsql.commit_snapshot_to_repository')
    @patch('bbpgsql.archive_pgsql.create_archive')
    @patch('bbpgsql.archive_pgsql.pg_stop_backup')
    @patch('bbpgsql.archive_pgsql.pg_start_backup')
    def test_perform_backup(self, mock_pg_start_backup, mock_pg_stop_backup,
        mock_create_archive, mock_commit_snapshot_to_repository):
        first_WAL = '000000D0'
        second_WAL = '000000D1'
        mock_pg_start_backup.return_value = first_WAL
        mock_pg_stop_backup.return_value = second_WAL
        archiveFile = os.path.join(self.archive_dir, 'pgsql.snapshot.tar')
        tag = bbpgsql.archive_pgsql.generate_tag()
        repo = get_Snapshot_repository(self.config)
        bbpgsql.archive_pgsql.perform_backup(self.data_dir,
            archiveFile, tag, repo)
        mock_pg_start_backup.assert_called_once_with(tag)
        mock_create_archive.assert_called_once_with(self.data_dir, archiveFile)
        self.assertEqual(mock_pg_stop_backup.called, True)
        self.assertEqual(mock_pg_stop_backup.call_count, 1)
        mock_commit_snapshot_to_repository.assert_called_once_with(
            repo, archiveFile, tag, first_WAL, second_WAL)
开发者ID:nbarendt,项目名称:PgsqlBackup,代码行数:61,代码来源:test_cmdline.py


示例3: test_create_monitor_with_watch_path

# 需要导入模块: from testfixtures import TempDirectory [as 别名]
# 或者: from testfixtures.TempDirectory import makedir [as 别名]
    def test_create_monitor_with_watch_path(self):
        wd = TempDirectory()
        source_path = wd.makedir('source')
        wd.makedir('build')

        with chdir(wd.path):
            m = create_monitor(source_path)
        assert len(m.reporters) == 1
        reporter = m.reporters[0]
        assert reporter.watch_path == source_path
        assert reporter.build_path == '{}-build'.format(os.path.realpath(source_path)) # noqa
开发者ID:yerejm,项目名称:ttt,代码行数:13,代码来源:test_monitor.py


示例4: test_testlist

# 需要导入模块: from testfixtures import TempDirectory [as 别名]
# 或者: from testfixtures.TempDirectory import makedir [as 别名]
    def test_testlist(self):
        import stat

        work_directory = TempDirectory()
        work_directory.makedir('test')
        work_directory.write(['test', 'test_dummy.c'], b'')
        build_directory = TempDirectory()
        testbin_path = build_directory.write(['test_dummy'], b'')
        st = os.stat(testbin_path)
        os.chmod(testbin_path, st.st_mode | stat.S_IEXEC)

        w = Watcher(work_directory.path, build_directory.path)
        w.poll()

        exefile = testbin_path + watcher.EXE_SUFFIX
        testlist = [(g.source(), g.executable()) for g in w.testlist()]
        assert testlist == [(os.path.join('test', 'test_dummy.c'), exefile)]
开发者ID:yerejm,项目名称:ttt,代码行数:19,代码来源:test_watcher.py


示例5: setUp

# 需要导入模块: from testfixtures import TempDirectory [as 别名]
# 或者: from testfixtures.TempDirectory import makedir [as 别名]
 def setUp(self):
     self.app = Flask(__name__)
     self.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
     self.app.config['USER_LIST'] = ['Test Admin']
     db.init_app(self.app)
     d = TempDirectory()
     d.makedir('dataset')
     d.write('dataset/files/testfile.jpg', 'abc')
     d.write('dataset/testfile2.jpg', 'abc')
     self.directory = d
     self.app.config['DATASET_ROOT'] = d.path
     with self.app.app_context(), TempDirectory() as d:
         db.create_all()
         lib.models.buildDB()
         dataset = lib.models.Datasets()
         dataset.name = 'Test'
         dataset.path = "dataset"
         db.session.add(dataset)
         db.session.commit()
开发者ID:Kungbib,项目名称:data.kb.se,代码行数:21,代码来源:test_torrents.py


示例6: test_default_watcher_gets_all_files

# 需要导入模块: from testfixtures import TempDirectory [as 别名]
# 或者: from testfixtures.TempDirectory import makedir [as 别名]
    def test_default_watcher_gets_all_files(self):
        work_directory = TempDirectory()
        work_directory.write('a.h', b'')
        work_directory.write('a.c', b'')
        work_directory.write('a.cc', b'')
        work_directory.write('CMakeLists.txt', b'')
        work_directory.write('blah.txt', b'')
        work_directory.makedir('.git')
        work_directory.makedir('.hg')
        wd_len = len(work_directory.path) + 1

        w = Watcher(work_directory.path, None)
        watchstate = w.poll()
        filelist = [f[wd_len:] for f in watchstate.inserts]
        filelist.sort()
        assert filelist == [
            'CMakeLists.txt',
            'a.c',
            'a.cc',
            'a.h',
            'blah.txt'
        ]
开发者ID:yerejm,项目名称:ttt,代码行数:24,代码来源:test_watcher.py


示例7: test_use_configuration_from_root_path_when_no_other_was_found

# 需要导入模块: from testfixtures import TempDirectory [as 别名]
# 或者: from testfixtures.TempDirectory import makedir [as 别名]
    def test_use_configuration_from_root_path_when_no_other_was_found(self):
        root_dir = TempDirectory()
        self.tmpdirs.append(root_dir)

        start_path = root_dir.makedir('some/directories/to/start/looking/for/settings')
        test_file = os.path.realpath(os.path.join(root_dir.path, 'settings.ini'))
        with open(test_file, 'a') as file_:
            file_.write('[settings]')
        self.files.append(test_file)  # Required to removed it at tearDown

        discovery = ConfigurationDiscovery(start_path, root_path=root_dir.path)
        filenames = [cfg.filename for cfg in discovery.config_files]
        self.assertEqual([test_file], filenames)
开发者ID:erickwilder,项目名称:prettyconf,代码行数:15,代码来源:test_filediscover.py


示例8: TestXMLExporter

# 需要导入模块: from testfixtures import TempDirectory [as 别名]
# 或者: from testfixtures.TempDirectory import makedir [as 别名]
class TestXMLExporter(unittest.TestCase):
    def setUp(self):
        self.tmp = TempDirectory()
        self.dir = self.tmp.makedir('foobar/')
        self.exp = XMLExporter(self.dir)
    def tearDown(self):
        TempDirectory.cleanup_all()

    #not responsible for creation
    def DISABLEDtest_creation_of_meta_info_file(self):
        filename = 'barfoo.xml'
        status = self.exp._exportMetaInformationToXML('', '', filename)
        self.assertTrue(os.path.isfile(self.dir+'metainformation.xml'))
        self.assertTrue(status)
    #not responsible for creation;
    # TODO: fix
    def DISABLEDtest_content_of_meta_info_file(self):
        filename = 'barfoo.xml'
        status = self.exp._exportMetaInformationToXML('01', '02', filename)
        tree = et.parse(self.dir + 'metainformation.xml')
        xml = tree.getroot()
        session = xml.find('Session')
        exercise = xml.find('Exercise')
        annotation = xml.find('Annotationfile')
        self.assertEquals('01', session.text)
        self.assertEquals('02', exercise.text)
        self.assertEquals(self.dir + filename, annotation.text)
    def DISABLEDtest_content_of_xml_export_file(self):
        src = lib.Sourcefile._make(['', '', '', '', lib.Orientation.left])
        input = lib.Validationfile._make([src, 'Gold', [['Foo', 'Bar']], 
            [{ 'Fu': '1', 'Baz': '2'}, {'Fu': '3', 'Baz': '4'}]])
        self.assertTrue(self.exp.export(input))
        tree = et.parse(self.dir + 'annotation.xml')
        xml = tree.getroot()
        validation = xml.find('Validation')
        self.assertEquals(validation.attrib, {'Type': 'Gold'})
        sensor = validation.find('Sensor')
        self.assertEquals(sensor.attrib, {'Orientation': 'left'})
        meta = sensor.find('Meta')
        self.assertEquals(meta[0].tag, 'Foo')
        self.assertEquals(meta[0].text, 'Bar')
        content = sensor.find('Content')
        self.assertEquals(content[0].tag,     'No1')
        self.assertEquals(content[0][0].tag,  'Fu')
        self.assertEquals(content[0][0].text, '1')
        self.assertEquals(content[0][1].tag,  'Baz')
        self.assertEquals(content[0][1].text, '2')
        self.assertEquals(content[1][0].tag,  'Fu')
        self.assertEquals(content[1][0].text, '3')
        self.assertEquals(content[1][1].tag,  'Baz')
        self.assertEquals(content[1][1].text, '4')
开发者ID:nce,项目名称:sedater,代码行数:53,代码来源:test_exporter.py


示例9: Test_FilesystemCommitStorage

# 需要导入模块: from testfixtures import TempDirectory [as 别名]
# 或者: from testfixtures.TempDirectory import makedir [as 别名]
class Test_FilesystemCommitStorage(TestCase):
    def setUp(self):
        self.tempdir = TempDirectory()
        self.commit_storage_path = self.tempdir.makedir('commit_storage')
        self.config = config()
        self.config.set('WAL', 'driver', 'filesystem')
        self.config.set('WAL', 'path', self.commit_storage_path)

    def tearDown(self):
        self.tempdir.cleanup()

    def test_will_build_storage_from_config(self):
        self.assertEqual(FilesystemCommitStorage,
            type(get_repository_storage_from_config(self.config, 'WAL')))
开发者ID:nbarendt,项目名称:PgsqlBackup,代码行数:16,代码来源:test_storage_configuration.py


示例10: setUp

# 需要导入模块: from testfixtures import TempDirectory [as 别名]
# 或者: from testfixtures.TempDirectory import makedir [as 别名]
 def setUp(self):
     data.app.config['TESTING'] = True
     data.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
     data.app.config['USER_LIST'] = ['Test Admin']
     db.init_app(data.app)
     d = TempDirectory()
     d.makedir('dataset')
     d.write('dataset/files/testfile.jpg', 'abc')
     d.write('dataset/testfile2.jpg', 'abc')
     self.directory = d
     data.app.config['DATASET_ROOT'] = d.path
     with data.app.app_context(), TempDirectory() as d:
         db.create_all()
         lib.models.buildDB()
         license = lib.models.License.query.first()
         provider = lib.models.Provider.query.first()
         dataset = lib.models.Datasets()
         dataset.name = 'Test'
         dataset.license = [license]
         dataset.provider = [provider]
         dataset.path = "dataset"
         db.session.add(dataset)
         db.session.commit()
     self.app = data.app.test_client()
开发者ID:Kungbib,项目名称:data.kb.se,代码行数:26,代码来源:test_rdf.py


示例11: test_lookup_should_stop_at_root_path

# 需要导入模块: from testfixtures import TempDirectory [as 别名]
# 或者: from testfixtures.TempDirectory import makedir [as 别名]
    def test_lookup_should_stop_at_root_path(self):
        test_dir = TempDirectory()
        self.tmpdirs.append(test_dir)  # Cleanup dir at tearDown

        start_path = test_dir.makedir('some/dirs/without/config')

        # create a file in the test_dir
        test_file = os.path.realpath(os.path.join(test_dir.path, 'settings.ini'))
        with open(test_file, 'a') as file_:
            file_.write('[settings]')
        self.files.append(test_file)  # Required to removed it at tearDown

        root_dir = os.path.join(test_dir.path, 'some', 'dirs')  # No settings here

        discovery = ConfigurationDiscovery(start_path, root_path=root_dir)
        self.assertEqual(discovery.config_files, [])
开发者ID:erickwilder,项目名称:prettyconf,代码行数:18,代码来源:test_filediscover.py


示例12: Test_archivepgsql_BasicCommandLineOperation

# 需要导入模块: from testfixtures import TempDirectory [as 别名]
# 或者: from testfixtures.TempDirectory import makedir [as 别名]
class Test_archivepgsql_BasicCommandLineOperation(TestCase):
    ARCHIVEPGSQL_PATH = os.path.join('bbpgsql', 'cmdline_scripts')
    CONFIG_FILE = 'config.ini'
    exe_script = 'archivepgsql'

    def setUp(self):
        self.setup_environment()
        self.setup_config()
        self.cmd = [self.exe_script, '--dry-run', '--config', self.config_path]

    def setup_environment(self):
        self.env = deepcopy(os.environ)
        self.env['PATH'] = ''.join([
            self.env['PATH'],
            ':',
            self.ARCHIVEPGSQL_PATH])
        self.tempdir = TempDirectory()
        self.data_dir = self.tempdir.makedir('pgsql_data')

    def setup_config(self):
        self.config_path = os.path.join(self.tempdir.path, self.CONFIG_FILE)
        self.config_dict = {
            'General': {
                'pgsql_data_directory': self.data_dir,
            },
            'Snapshot': {
                'driver': 'memory',
            },
        }
        write_config_to_filename(self.config_dict, self.config_path)
        self.config = get_config_from_filename_and_set_up_logging(
            self.config_path
        )

    def tearDown(self):
        self.tempdir.cleanup()

    def test_can_execute_archivepgsql(self):
        check_call(self.cmd, env=self.env, stdout=PIPE)

    def test_obeys_dry_run_option(self):
        proc = Popen(self.cmd, env=self.env, stdout=PIPE)
        stdoutdata, stderrdata = proc.communicate()
        self.assertEqual("Dry Run\n", stdoutdata)
开发者ID:nbarendt,项目名称:PgsqlBackup,代码行数:46,代码来源:test_cmdline.py


示例13: TestCSVExporter

# 需要导入模块: from testfixtures import TempDirectory [as 别名]
# 或者: from testfixtures.TempDirectory import makedir [as 别名]
class TestCSVExporter(unittest.TestCase):
    def setUp(self):
        self.tmp = TempDirectory()
        self.dir = self.tmp.makedir('foobar')
        self.exp = CSVExporter()
    def tearDown(self):
        TempDirectory.cleanup_all()
    def test_creation_of_export_file(self):
        filename = 'foobar.csv'
        values = [lib.Sensorsegment._make([0] * 6)]
        status = self.exp.export(values, self.dir+filename)
        self.assertTrue(os.path.isfile(self.dir+filename))
        self.assertTrue(status)
    def test_content_of_export_file(self):
        filename = 'foobar.csv'
        values = [lib.Sensorsegment._make([0] * 6),
                lib.Sensorsegment._make([1] * 6)
                ]
        self.exp.export(values, self.dir+filename, False, False)
        res = self.tmp.read(self.dir+filename)
        ref = b'0,0,0,0,0,0\r\n1,1,1,1,1,1\r\n'
        self.assertEqual(ref, res)
    def test_content_with_header_with_indices(self):
        filename = 'foobar.csv'
        values = [lib.Sensorsegment._make([0] * 6)]
        self.exp.export(values, self.dir+filename, True, True)
        res = self.tmp.read(self.dir+filename)
        ref = b'Index,accelX,accelY,accelZ,gyroX,gyroY,gyroZ\r\n1,0,0,0,0,0,0\r\n'
        self.assertEqual(ref, res)
    def test_content_with_header_without_indices(self):
        filename = 'foobar.csv'
        values = [lib.Sensorsegment._make([0] * 6)]
        self.exp.export(values, self.dir+filename, True, False)
        res = self.tmp.read(self.dir+filename)
        ref = b'accelX,accelY,accelZ,gyroX,gyroY,gyroZ\r\n0,0,0,0,0,0\r\n'
        self.assertEqual(ref, res)
    def test_content_without_header_with_indices(self):
        filename = 'foobar.csv'
        values = [lib.Sensorsegment._make([0] * 6)]
        self.exp.export(values, self.dir+filename, False, True)
        res = self.tmp.read(self.dir+filename)
        ref = b'1,0,0,0,0,0,0\r\n'
        self.assertEqual(ref, res)
开发者ID:nce,项目名称:sedater,代码行数:45,代码来源:test_exporter.py


示例14: DocumentServiceWriterTestCases

# 需要导入模块: from testfixtures import TempDirectory [as 别名]
# 或者: from testfixtures.TempDirectory import makedir [as 别名]
class DocumentServiceWriterTestCases(SegueApiTestCase):
    def setUp(self):
        super(DocumentServiceWriterTestCases, self).setUp()
        self.tmp_dir   = TempDirectory()
        self.out_dir   = self.tmp_dir.makedir("output")
        self.templates = os.path.join(os.path.dirname(__file__), 'fixtures')

        self.service = DocumentService(override_root=self.out_dir, template_root=self.templates, tmp_dir=self.tmp_dir.path)

    def tearDown(self):
        self.tmp_dir.cleanup()

    @skipIf("SNAP_CI" in os.environ, "inkscape is not available in CI")
    def test_svg_to_pdf(self):
        result = self.service.svg_to_pdf('templates/dummy.svg', 'certificate', "ABCD", { 'XONGA': 'bir<osca' })

        self.tmp_dir.check_dir('','certificate-ABCD.svg', 'output')
        self.tmp_dir.check_dir('output/certificate/AB', 'certificate-ABCD.pdf')

        contents_of_temp = self.tmp_dir.read("certificate-ABCD.svg")
        self.assertIn("bir&lt;osca da silva", contents_of_temp)

        self.assertEquals(result, 'certificate-ABCD.pdf')
开发者ID:Bindambc,项目名称:segue,代码行数:25,代码来源:service_tests.py


示例15: PluginWithTempDirTests

# 需要导入模块: from testfixtures import TempDirectory [as 别名]
# 或者: from testfixtures.TempDirectory import makedir [as 别名]
class PluginWithTempDirTests(TestCase):
    def setUp(self):
        self.dir = TempDirectory()
        self.addCleanup(self.dir.cleanup)

    def run_actions(self, path=None, **kw):
        with LogCapture() as log:
            plugin = make_git_repo(path=path or self.dir.path, **kw)
            with Replacer() as r:
                r.replace("archivist.repos.git.datetime", test_datetime())
                plugin.actions()
        return log

    def git(self, command, repo_path=None):
        return run(["git"] + command.split(), cwd=repo_path or self.dir.path)

    def make_repo_with_content(self, repo=""):
        repo_path = self.dir.getpath(repo) if repo else None
        self.git("init", repo_path)
        self.dir.write(repo + "a", "some content")
        self.dir.write(repo + "b", "other content")
        self.dir.write(repo + "c", "more content")
        self.git("add .", repo_path)
        self.git("commit -m initial", repo_path)
        return repo

    def make_local_changes(self, repo=""):
        self.dir.write(repo + "b", "changed content")
        os.remove(self.dir.getpath(repo + "c"))
        self.dir.write(repo + "d", "new content")

    def status_log_entry(self, lines, repo_path=None):
        return (
            "archivist.repos.git",
            "INFO",
            "\n".join(l.format(repo=repo_path or self.dir.path) for l in lines) + "\n",
        )

    def check_git_log(self, lines, repo_path=None):
        compare("\n".join(lines) + "\n", self.git("log --pretty=format:%s --stat", repo_path))

    def get_dummy_source(self, name):
        class DummySource(Source):
            schema = Schema({})

            def __init__(self, type, name, repo):
                super(DummySource, self).__init__(type, name, repo)

            def process(self, path):
                pass

        return DummySource("dummy", name, "repo")

    def test_path_for_with_name(self):
        compare(
            self.dir.getpath("dummy/the_name"),
            make_git_repo(path=self.dir.path).path_for(self.get_dummy_source("the_name")),
        )
        self.assertTrue(os.path.exists(self.dir.getpath("dummy/the_name")))

    def test_path_for_no_name(self):
        compare(self.dir.getpath("dummy"), make_git_repo(path=self.dir.path).path_for(self.get_dummy_source(name=None)))
        self.assertTrue(os.path.exists(self.dir.getpath("dummy")))

    def test_not_there(self):
        repo_path = self.dir.getpath("var")
        log = self.run_actions(repo_path)
        log.check(("archivist.repos.git", "INFO", "creating git repo at " + repo_path))
        self.assertTrue(self.dir.getpath("var/.git"))

    def test_there_not_git(self):
        repo_path = self.dir.makedir("var")
        log = self.run_actions(repo_path)
        log.check(("archivist.repos.git", "INFO", "creating git repo at " + repo_path))
        self.assertTrue(self.dir.getpath("var/.git"))

    def test_no_changes(self):
        self.git("init")
        log = self.run_actions()
        log.check()  # no logging

    def test_just_log_changes(self):
        self.make_repo_with_content()
        self.make_local_changes()
        log = self.run_actions(commit=False)
        log.check(self.status_log_entry(["changes found in git repo at {repo}:", " M b", " D c", "?? d"]))
        self.check_git_log(["initial", " a | 1 +", " b | 1 +", " c | 1 +", " 3 files changed, 3 insertions(+)"])

    def test_commit_changes(self):
        self.make_repo_with_content()
        self.make_local_changes()
        log = self.run_actions(commit=True)
        log.check(
            self.status_log_entry(["changes found in git repo at {repo}:", " M b", " D c", "?? d"]),
            ("archivist.repos.git", "INFO", "changes committed"),
        )
        compare("", self.git("status --porcelain"))
        self.check_git_log(
            [
                "Recorded by archivist at 2001-01-01 00:00",
#.........这里部分代码省略.........
开发者ID:Simplistix,项目名称:archivist,代码行数:103,代码来源:test_repo_git.py


示例16: test_watcher_with_file_filter

# 需要导入模块: from testfixtures import TempDirectory [as 别名]
# 或者: from testfixtures.TempDirectory import makedir [as 别名]
    def test_watcher_with_file_filter(self):
        work_directory = TempDirectory()
        work_directory.write('a.h', b'')
        work_directory.write('a.c', b'')
        work_directory.write('a.cc', b'')
        work_directory.write('CMakeLists.txt', b'')
        work_directory.write('blah.txt', b'')
        work_directory.makedir('blah')
        work_directory.write(['blah', 'test_dummy.c'], b'')
        wd_len = len(work_directory.path) + 1

        w = Watcher(work_directory.path, None, [])
        watchstate = w.poll()
        filelist = [f[wd_len:] for f in watchstate.inserts]
        filelist.sort()
        assert filelist == [
            'CMakeLists.txt',
            'a.c',
            'a.cc',
            'a.h',
            'blah.txt',
            'blah/test_dummy.c'
        ]

        w = Watcher(work_directory.path, None,
                    source_patterns=['CMakeLists.txt'])
        watchstate = w.poll()
        filelist = [f[wd_len:] for f in watchstate.inserts]
        filelist.sort()
        assert filelist == ['CMakeLists.txt']

        w = Watcher(work_directory.path, None, source_patterns=['*.txt'])
        watchstate = w.poll()
        filelist = [f[wd_len:] for f in watchstate.inserts]
        filelist.sort()
        assert filelist == ['CMakeLists.txt', 'blah.txt']

        w = Watcher(work_directory.path, None, source_patterns=['?.cc'])
        watchstate = w.poll()
        filelist = [f[wd_len:] for f in watchstate.inserts]
        filelist.sort()
        assert filelist == ['a.cc']

        w = Watcher(work_directory.path, None, source_patterns=['blah'])
        watchstate = w.poll()
        filelist = [f[wd_len:] for f in watchstate.inserts]
        filelist.sort()
        assert filelist == ['blah.txt', 'blah/test_dummy.c']

        w = Watcher(work_directory.path, None, source_patterns=['blah/'])
        watchstate = w.poll()
        filelist = [f[wd_len:] for f in watchstate.inserts]
        filelist.sort()
        assert filelist == ['blah/test_dummy.c']

        w = Watcher(work_directory.path, None, source_patterns=['*.txt'],
                    source_exclusions=['blah.txt'])
        watchstate = w.poll()
        filelist = [f[wd_len:] for f in watchstate.inserts]
        filelist.sort()
        assert filelist == ['CMakeLists.txt']

        w = Watcher(work_directory.path, None, source_patterns=['*.txt'],
                    source_exclusions=['blah.*'])
        watchstate = w.poll()
        filelist = [f[wd_len:] for f in watchstate.inserts]
        filelist.sort()
        assert filelist == ['CMakeLists.txt']

        w = Watcher(work_directory.path, None, None,
                    source_exclusions=['*.txt', 'blah'])
        watchstate = w.poll()
        filelist = [f[wd_len:] for f in watchstate.inserts]
        filelist.sort()
        assert filelist == ['a.c', 'a.cc', 'a.h']
开发者ID:yerejm,项目名称:ttt,代码行数:77,代码来源:test_watcher.py


示例17: Test_Logging_setup

# 需要导入模块: from testfixtures import TempDirectory [as 别名]
# 或者: from testfixtures.TempDirectory import makedir [as 别名]
class Test_Logging_setup(TestCase):
    def setUp(self):
        self.default_config = bbpgsql.configuration.config()
        self.td = TempDirectory()
        self.logdir = self.td.makedir('log')
        self.logfilepath = os.path.join(self.logdir, 'bbpgsql')
        self.config_path = self.td.write('bbpgsql', config_text)
        self.full_config = bbpgsql.configuration.config([self.config_path])
        self.full_config.set('Logging', 'logfile', self.logfilepath)
        self.config_path = self.td.write('bad_level', config_bad_values)
        self.bad_config = bbpgsql.configuration.config([self.config_path])
        self.config_path = self.td.write('section_only', config_only_section)
        self.section_only = bbpgsql.configuration.config([self.config_path])

    def tearDown(self):
        self.td.cleanup()

    def test_default_config_lacks_logging(self):
        self.assertFalse(self.default_config.has_section('Logger'))

    def test_section_only_does_no_logging(self):
        log_config = bbpgsql.configuration.set_up_logging(self.section_only)
        # assert only null handler
        self.assertEqual(1, len(log_config['handlers']))

    @patch('logging.config.dictConfig')
    def test_logger_sets_up_default_config(self, mock_dictConfig):
        mock_dictConfig.return_value = None
        bbpgsql.configuration.set_up_logging(self.default_config)
        self.assertTrue(mock_dictConfig.called)
        expected = ((default_log_config, ), {})
        self.assertEqual(expected, mock_dictConfig.call_args)

    def test_logger_sets_log_level_from_configfile(self):
        log_config = bbpgsql.configuration.set_up_logging(self.full_config)
        self.assertEqual(DEBUG,
            log_config['loggers']['bbpgsql']['level'])

    def test_logger_rejects_bad_level_name(self):
        self.assertRaises(Exception, bbpgsql.configuration.set_up_logging,
            (self.bad_config))

    def test_logger_gets_filename_from_config(self):
        handlers, formatters = \
            bbpgsql.configuration.set_up_logger_file_handler(self.full_config)
        self.assertEqual(handlers,
            {'file': {
                'class': 'logging.handlers.TimedRotatingFileHandler',
                'formatter': 'file_formatter',
                'filename': self.logfilepath,
                'when': 'd',
                'interval': 1,
                'backupCount': 14
                }
            }
        )
        self.assertEqual(formatters,
            {
                'file_formatter': {
                'format': "%(asctime)s - %(levelname)s - %(message)s",
                }
            }
        )

    def test_logger_does_nothing_if_section_is_missing(self):
        handlers, formatters = \
            bbpgsql.configuration.set_up_logger_file_handler(
                self.default_config)
        self.assertEqual({}, handlers)
        self.assertEqual({}, formatters)

    def test_logger_gets_hostname_port_from_config(self):
        handlers, formatters = \
            bbpgsql.configuration.set_up_logger_syslog_handler(
                self.full_config)
        self.assertEqual(handlers['syslog']['address'],
            ('localhost', 514))

    def test_logger_does_nothing_if_syslog_host_not_defined(self):
        conf = SafeConfigParser()
        conf.add_section('Logging')
        conf.set('Logging', 'logport', '514')
        handlers, formatters = \
            bbpgsql.configuration.set_up_logger_syslog_handler(conf)
        self.assertEqual({}, handlers)
        self.assertEqual({}, formatters)

    def test_logger_does_nothing_if_syslog_port_not_defined(self):
        conf = SafeConfigParser()
        conf.add_section('Logging')
        conf.set('Logging', 'loghost', 'localhost')
        handlers, formatters = \
            bbpgsql.configuration.set_up_logger_syslog_handler(conf)
        self.assertEqual({}, handlers)
        self.assertEqual({}, formatters)

    def test_logger_uses_UDP_by_default(self):
        conf = SafeConfigParser()
        conf.add_section('Logging')
        conf.set('Logging', 'loghost', 'localhost')
#.........这里部分代码省略.........
开发者ID:nbarendt,项目名称:PgsqlBackup,代码行数:103,代码来源:test_logging_configuration.py


示例18: TestFilesystemCrawler

# 需要导入模块: from testfixtures import TempDirectory [as 别名]
# 或者: from testfixtures.TempDirectory import makedir [as 别名]
class TestFilesystemCrawler(unittest.TestCase):
    filename = 'foobar.txt'
    dirname  = 'barfoo/'
    file = ''
    dir = ''

    def setUp(self):
        self.tmp = TempDirectory()
        self.dir = self.tmp.makedir(self.dirname)
        self.file = self.tmp.write(self.filename, b'foo')
    def tearDown(self):
        TempDirectory.cleanup_all()
    def dummyFile(self, filename, expected):
        f = self.tmp.write(filename, b'EOF')
        crawler = Crawler()
        ref = Sourcefile._make(
                ['', '', expected[0], expected[1], expected[2]])
        res = crawler._parseFileName(f)
        self.assertEquals(ref[2], res[2])
        self.assertEquals(ref[3], res[3])
        self.assertEquals(ref[4], res[4])

    #silent skip of all non readable dirs
    def DISABLEDtest_input_type(self):
        crawler = Crawler()
        self.assertRaises(AttributeError, crawler.crawl, '404')

    #silent skip of all non readable dirs
    def DISABLEtest_input_file_permissions(self):
        os.chmod(self.file, 0)
        crawler = Crawler()
        self.assertRaises(PermissionError, crawler._parseFileName, self.file)

    def test_empty_pairing(self):
        crawler = Crawler()
        self.assertRaises(ValueError, crawler.pair)

    # Pxx_Eyy_right|left (eGaitDatabase)
    def test_S_E_O_format(self):
        self.dummyFile('P01_E2_right.dat', ['01', '2', Orientation.right])

    # GAxxEyy_right|left (eGaitDatabase3/Controls)
    def test_SE_O_format(self):
        self.dummyFile('GA112030E3_left.txt', ['112030', '3', Orientation.left])

    # PxxEyy_right|left (eGaitDatabase3/Geriatrics)
    def test_SE_O_format2(self):
        self.dummyFile('P50E6_left.txt', ['50', '6', Orientation.left])

    # PatxxWald(left|right)Foot_Sensor_Date (eGaitDatabase3/GeriatricsGSTD/4MW)
    def test_SO_format(self):
        self.dummyFile('Pat1WaldrightFoot_1eea_20140325133006.dat', 
                ['1Wald', '', Orientation.right])

    # GAxx_(Left|Right)Foot_Sensor_Date (eGaitDatabase3/Controls/4MW)
    def test_SO_format2(self):
        self.dummyFile('GA214026LeftFoot_1eea_20140428110132.dat', 
                ['214026', '', Orientation.left])

    # GAstdxx_(Left|Right)Foot_Sensor_Date (eGaitDatabase3/Controls/4MW)
    def test_SO_format3(self):
        self.dummyFile('GAstd45jwRightFoot_1d68_20140506123332.dat', 
                ['45jw', '', Orientation.right])

    def test_correct_pairing(self):
        left  = self.tmp.write(self.dir + 'P01_E2_left.txt', b'')
        right = self.tmp.write(self.dir + 'P01_E2_right.txt', b'')
        crawler = Crawler()
        crawler.crawl(self.dir)
        crawler.pair()
        self.assertEquals(crawler.pairedFiles[0][0].filename, 'P01_E2_left.txt')
        self.assertEquals(crawler.pairedFiles[0][1].filename, 'P01_E2_right.txt')

    def test_one_partner_missing_pairing(self):
        left = self.tmp.write(self.dir + 'P01_E2_left.txt', b'')
        crawler = Crawler()
        crawler.crawl(self.dir)
        try:
            crawler.pair()
        except ValueError:
            pass
        self.assertEquals(crawler.pairedFiles[0][0].filename, 
                crawler.pairedFiles[0][1].filename)
开发者ID:nce,项目名称:sedater,代码行数:85,代码来源:test_filesystem.py


示例19: TestPathSource

# 需要导入模块: from testfixtures import TempDirectory [as 别名]
# 或者: from testfixtures.TempDirectory import makedir [as 别名]
class TestPathSource(TestCase):

    def setUp(self):
        self.dir = TempDirectory()
        self.addCleanup(self.dir.cleanup)

    def test_abc(self):
        self.assertTrue(issubclass(Plugin, Source))

    def test_schema_ok(self):
        p1 = self.dir.write('foo', b'f')
        p2 = self.dir.write('bar', b'b')
        compare(
            dict(type='paths', values=[p1, p2], repo='config'),
            Plugin.schema(
                dict(type='paths', values=[p1, p2], repo='config')
            ))

    def test_schema_wrong_type(self):
        text = "not a valid value for dictionary value @ data['type']"
        with ShouldFailSchemaWith(text):
            Plugin.schema(dict(type='bar', values=['/']))

    def test_schema_extra_keys(self):
        with ShouldFailSchemaWith("extra keys not allowed @ data['foo']"):
            Plugin.schema(dict(type='paths', foo='bar'))

    def test_name_supplied(self):
        text = "not a valid value for dictionary value @ data['name']"
        with ShouldFailSchemaWith(text):
            Plugin.schema(dict(type='paths', name='foo'))

    def test_no_paths(self):
        text = "length of value must be at least 1 for dictionary value " \
               "@ data['values']"
        with ShouldFailSchemaWith(text):
            Plugin.schema(dict(type='paths', values=[]))

    def test_path_not_string(self):
        text = "expected str @ data['values'][0]"
        with ShouldFailSchemaWith(text):
            Plugin.schema(dict(type='paths', values=[1]))

    def test_path_not_starting_with_slash(self):
        text = "'foo' is not an absolute path @ data['values'][0]"
        try:
            cwd = os.getcwd()
            os.chdir(self.dir.path)
            self.dir.makedir('foo')
            with ShouldFailSchemaWith(text):
                Plugin.schema(dict(type='paths', values=['foo']))
        finally:
            os.chdir(cwd)


    def test_path_not_there(self):
        bad_path = self.dir.getpath('bad')
        text = "'%s' does not exist @ data['values'][0]" % bad_path
        with ShouldFailSchemaWith(text):
            Plugin.schema(dict(type='paths', values=[bad_path]))

    def test_interface(self):
        plugin = Plugin('source', name=None, repo='config',
                        values=['/foo/bar'])
        compare(plugin.type, 'source')
        compare(plugin.name, None)
        compare(plugin.repo, 'config')
        compare(plugin.source_paths, ['/foo/bar'])
开发者ID:Simplistix,项目名称:archivist,代码行数:70,代码来源:test_source_paths.py



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