Пример #1
0
    def test_embed_data_AssertEqualFiles(self, embed_data):
        CreateFile(embed_data.GetDataFilename('equal.txt'),
                   'This is alpha.txt')
        embed_data.AssertEqualFiles('alpha.txt', 'equal.txt')

        CreateFile(embed_data.GetDataFilename('different.txt'),
                   'This is different.txt')
        with pytest.raises(AssertionError) as e:
            embed_data.AssertEqualFiles('alpha.txt', 'different.txt')
        assert str(e.value) == Dedent('''
            *** FILENAME: data_fixtures__test_embed_data_AssertEqualFiles/alpha.txt
            ***\w

            ---\w

            ***************

            *** 1 ****

            ! This is alpha.txt
            --- 1 ----

            ! This is different.txt
            '''.replace('\w', ' '))

        with pytest.raises(MultipleFilesNotFound) as e:
            embed_data.AssertEqualFiles('alpha.txt', 'missing.txt')

        assert (
            str(e.value) == 'Files not found: '
            'missing.txt,data_fixtures__test_embed_data_AssertEqualFiles/missing.txt'
        )
Пример #2
0
    def testGetDirtyFiles(self, git, embed_data):
        assert git.GetDirtyFiles(git.cloned_remote) == []

        # New files and directories are not considered dirty
        CreateFile(embed_data['cloned_remote/some_file'], contents='')
        CreateDirectory(embed_data['cloned_remote/some_dir'])
        assert git.GetDirtyFiles(git.cloned_remote) == []

        # Modify alpha.txt
        CreateFile(embed_data['cloned_remote/alpha.txt'], contents='')
        assert set(git.GetDirtyFiles(git.cloned_remote)) == set([
            ('M', 'alpha.txt')
        ])
Пример #3
0
    def testIsDirty(self, git, embed_data):
        assert git.IsDirty(git.cloned_remote) == False

        # Creating a new file should not leave the repo dirty
        new_file = embed_data['cloned_remote/some_new_file.txt']
        CreateFile(new_file, contents='new_file')
        assert git.IsDirty(git.cloned_remote) == False
        DeleteFile(new_file)

        # Modifying a file should
        CreateFile(embed_data['cloned_remote/alpha.txt'],
                   contents='modified alpha')
        assert git.IsDirty(git.cloned_remote) == True
Пример #4
0
    def testPrintEnvironment(self, embed_data):
        # Create a fake environment
        environment = {
            'var1' : 'value1',
            'var2' : 'value2',
            'PATH' : os.pathsep.join(['path1', 'path2']),
            'PYTHONPATH' : os.pathsep.join(['pythonpath1', 'pythonpath2']),

        }

        # Prepare a controled text output
        stream = StringIO()
        output = TextOutput(stream)

        # Print environment
        PrintEnvironment(environment, output)

        # Save output to temp file
        obtained = embed_data.GetDataFilename('testPrintEnvironment.txt')
        CreateFile(obtained, contents=stream.getvalue())

        # Compare file contents
        embed_data.AssertEqualFiles(
            obtained,
            'testPrintEnvironment.expected.txt'
        )
Пример #5
0
    def CreateHookFile(
        self,
        repo_path,
        filename,
        content,
    ):
        '''
        Create a hook-file.

        :param str repo_path:
            Path to the repository (local)

        :param str filename:
            The hook filename.
            Just the base name.
            Ex.
                pre-commit
                post-commit
                hook_lib.py

        :param str content:
            The hook file content.

        :return str:
            Returns the hook *full* filename.
        '''
        from ben10.filesystem import CreateFile, EOL_STYLE_UNIX

        r_filename = '%(repo_path)s/.git/hooks/%(filename)s' % locals()
        CreateFile(r_filename, content, eol_style=EOL_STYLE_UNIX)
        return r_filename
Пример #6
0
    def testClean(self, git, embed_data):
        # Create some file and see that they are cleaned
        echo = embed_data['cloned_remote/echo.txt']
        foxtrot = embed_data['cloned_remote/foxtrot.txt']

        CreateFile(echo, contents='echo')
        CreateFile(foxtrot, contents='foxtrot')

        # Create .gitignore
        CreateFile(embed_data['cloned_remote/.gitignore'], contents='echo.txt')

        removed_files = git.Clean(git.cloned_remote)
        assert removed_files == ['echo.txt']

        assert not os.path.isfile(echo)
        assert os.path.isfile(foxtrot)
Пример #7
0
    def test_embed_data_ExistingDataDir(self, embed_data):
        # Create the directory manually (we must not use any embed_data functions or else the
        # directory is created)
        extra_txt = 'data_fixtures__test_embed_data_ExistingDataDir/extra.txt'
        CreateFile(extra_txt, 'This file will perish')
        assert os.path.isfile(extra_txt)

        # Calling CreateDataDir again will recreate the directory, deleting the old file
        embed_data.CreateDataDir()
        assert not os.path.isfile(extra_txt)
Пример #8
0
    def testStatus(self, git):
        working_dir = git.cloned_remote

        r = git.Status(working_dir)
        assert r == '## master...origin/master'

        CreateFile(working_dir + '/zulu.txt', 'zulu')

        r = git.Status(working_dir)
        assert r == '## master...origin/master\n?? zulu.txt'
Пример #9
0
    def testDownloadRemote(self, embed_data):
        '''
        Tests the method DownloadRemote with a normal directory as the remote.
        '''
        dir_cache = DirCache(
            embed_data['remotes/alpha'],
            embed_data['local/zulu'],
            embed_data['cache_dir'],
        )
        assert dir_cache.GetFilename() == 'alpha'
        assert dir_cache.GetName() == 'alpha'

        assert dir_cache.RemoteExists()
        assert not dir_cache.CacheExists()
        assert not dir_cache.LocalExists()

        dir_cache.CreateCache()
        # DownloadRemote extracts the archive contents into a directory with the same basename of
        # the archive.
        assert os.path.isdir(embed_data['cache_dir/alpha'])
        assert os.path.isfile(embed_data['cache_dir/alpha/file.txt'])

        assert dir_cache.RemoteExists()
        assert dir_cache.CacheExists()
        assert not dir_cache.LocalExists()

        # Calling it twice does nothing.
        CreateFile(embed_data['cache_dir/alpha/new_file.txt'], 'This is new')
        assert IsFile(embed_data['cache_dir/alpha/new_file.txt'])
        dir_cache.CreateCache()
        assert IsFile(embed_data['cache_dir/alpha/new_file.txt'])
        assert dir_cache.RemoteExists()
        assert dir_cache.CacheExists()
        assert not dir_cache.LocalExists()

        # Forcing cache download will override new created file.
        CreateFile(embed_data['cache_dir/alpha/new_file.txt'], 'This is new')
        assert IsFile(embed_data['cache_dir/alpha/new_file.txt'])
        dir_cache.CreateCache(force=True)
        assert not IsFile(embed_data['cache_dir/alpha/new_file.txt'])
Пример #10
0
    def testReset(self, git):
        working_dir = git.cloned_remote

        r = git.Status(working_dir)
        assert r == '## master...origin/master'

        CreateFile(working_dir + '/alpha.txt', 'Changed!')

        r = git.Status(working_dir)
        assert r == '## master...origin/master\n M alpha.txt'

        git.Reset(working_dir)

        r = git.Status(working_dir)
        assert r == '## master...origin/master'
Пример #11
0
    def testStash(self, git):
        assert not git.IsDirty(git.cloned_remote)

        # Modify alpha.txt
        alpha_txt = git.cloned_remote + '/alpha.txt'
        CreateFile(alpha_txt, 'Changing alpha.txt\n')
        assert git.IsDirty(git.cloned_remote)

        # Stash changes so we have alpha.txt with its original content.
        git.Stash(git.cloned_remote)
        assert not git.IsDirty(git.cloned_remote)
        assert GetFileContents(alpha_txt) == 'alpha\n'

        # Pop changes so we have alpha.txt with our modification
        git.StashPop(git.cloned_remote)
        assert git.IsDirty(git.cloned_remote)
        assert GetFileContents(alpha_txt) == 'Changing alpha.txt\n'
Пример #12
0
    def testAddCommitPush(self, git, embed_data):
        # We start out with 2 commits
        assert git.GetCommitCount(git.cloned_remote) == 3

        # Add something and check the new count
        test_file = embed_data['cloned_remote/test_file']
        CreateFile(test_file, contents='test_file')

        git.Add(git.cloned_remote, 'test_file')
        git.Commit(git.cloned_remote, commit_message='Added test_file')
        git.Push(git.cloned_remote)

        assert git.GetCommitCount(git.cloned_remote) == 4

        assert (git.GetCommitRepr(git.cloned_remote,
                                  commit_hash=False,
                                  summary=True) == 'Added test_file')
Пример #13
0
def license_headers(console_, directory, header='HEADER.txt'):
    '''
    Check and fix license headers in all source files.

    :param directory: The base directory perform the operation.
    :param header: Filename containing the header information.
    '''

    def MatchHeader(lines, header_lines):
        '''
        Returns whether the given filename lines (lines) match the header lines (header_lines).
        '''
        if len(lines) < len(header_lines):
            return False
        lines = lines[:len(header_lines)]
        for i, j in zip(lines, header_lines):
            if i != j.strip():
                return False
        return True

    header_lines = GetFileLines(header)
    filenames = FindFiles(directory, in_filters=['*.py'])
    for i_filename in filenames:
        console_.Progress(i_filename + '... ')

        # Get filename lines.
        lines = GetFileLines(i_filename)

        # Check if we already have the proper header.
        if MatchHeader(lines, header_lines):
            console_.ProgressWarning('skip')
            continue

        # Add/replace header with our header.
        content = []
        for i_line in lines:
            if not content and i_line.startswith('#'):
                continue
            content.append(i_line)
        content = header_lines + content

        # Rewrite the file.
        CreateFile(i_filename, '\n'.join(content))
        console_.ProgressOk('done')
Пример #14
0
    def testExceptions(self, embed_data):
        from archivist import Archivist
        from ben10.filesystem import CreateDirectory, CreateFile
        import os
        import pytest

        CreateFile(embed_data['alpha.INVALID'], '')
        CreateDirectory(embed_data['CREATE/root_dir/empty_dir'])

        archive = Archivist()

        with pytest.raises(NotImplementedError):
            archive.ExtractZip(embed_data['alpha.INVALID'],
                               embed_data.GetDataDirectory())

        with pytest.raises(RuntimeError):
            # Unknown format
            archive.CreateArchive(embed_data['alpha.UNKNOWN'],
                                  embed_data.GetDataDirectory())

        with pytest.raises(FileAlreadyExistsError):
            # File already exists
            # File is kept
            archive.CreateArchive(embed_data['alpha.INVALID'],
                                  embed_data.GetDataDirectory(),
                                  overwrite=False)
        assert os.path.isfile(embed_data['alpha.INVALID'])

        with pytest.raises(RuntimeError):
            archive.ExtractArchive(embed_data['alpha.INVALID'],
                                   embed_data.GetDataDirectory())

        with pytest.raises(RuntimeError):
            # Unknown format
            # File is deleted: this may not be a good default behavior, but it is what we have now.
            archive.CreateArchive(
                embed_data['alpha.INVALID'],
                embed_data.GetDataDirectory(),
            )
        assert not os.path.isfile(embed_data['alpha.INVALID'])
Пример #15
0
    def testLocalBranch(self, git, embed_data):
        # Initial test
        assert git.GetCurrentBranch(git.cloned_remote) == 'master'

        # Create a new branch and check again
        git.CreateLocalBranch(git.cloned_remote, 'new_branch')
        assert git.GetCurrentBranch(git.cloned_remote) == 'new_branch'

        # Try to create a branch that already exists
        with pytest.raises(BranchAlreadyExistsError):
            git.CreateLocalBranch(git.cloned_remote, 'new_branch')

        # Try to create a branch while dirty
        CreateFile(embed_data['cloned_remote/alpha.txt'], contents='')
        with pytest.raises(DirtyRepositoryError):
            git.CreateLocalBranch(git.cloned_remote, 'other_new_branch')

        # We are still in new_branch, but we should be able to delete it
        git.DeleteLocalBranch(git.cloned_remote, 'new_branch')

        # We can't go back to it
        with pytest.raises(GitRefDoesNotExistError):
            git.Checkout(git.cloned_remote, 'new_branch')
Пример #16
0
    def __ExtractArchive(self, archive_filename, target_dir):
        '''
        Generic implementation of Extract Archive. Handles .rar and .zip files.

        :param str archive_filename:
            The name of the archive.

        :param str target_dir:
            The target directory to extract the archive contents.
        '''
        # Get archive wrapper
        from _archive_wrapper import CreateArchiveWrapper
        archive = CreateArchiveWrapper(archive_filename)

        # Create directories needed for target
        target_dir = os.path.normpath(target_dir)
        if not target_dir.endswith(':'):
            CreateDirectory(target_dir)

        # Create archive structure
        for sub_dir in archive.ListDirs():
            curdir = os.path.join(target_dir, sub_dir)
            CreateDirectory(curdir)

        # Extract archive
        for i_name in archive.ListFilenames():
            target_filename = os.path.normpath(os.path.join(
                target_dir, i_name))
            if os.path.isdir(target_filename):
                continue

            CreateFile(
                target_filename,
                archive.ReadFile(i_name),
                eol_style=EOL_STYLE_NONE,
            )