Пример #1
0
class test_env_var_property(unit_test):
    class fruit(object):
        def __init__(self, color, flavor):
            self._color = color
            self._flavor = flavor

        @env_var_property
        def color(self):
            return self._color

        @env_var_property
        def flavor(self):
            return self._flavor

    def test_env_var_no_var(self):
        f = self.fruit('yellow', 'tart')
        self.assertEqual('yellow', f.color)
        self.assertEqual('tart', f.flavor)

    def test_env_var_one_var(self):
        f = self.fruit('${COLOR}', 'tart')
        with env_override({'COLOR': 'yellow'}) as env:
            self.assertEqual('yellow', f.color)
            self.assertEqual('tart', f.flavor)

    def test_env_var_two_vars(self):
        f = self.fruit('${MODIFIER}${COLOR}', 'tart')
        with env_override({'COLOR': 'yellow', 'MODIFIER': 'nice'}) as env:
            self.assertEqual('niceyellow', f.color)
            self.assertEqual('tart', f.flavor)

    def test_env_var_multiple_vars(self):
        f = self.fruit('${COLOR}', '${FLAVOR}')
        with env_override({'COLOR': 'yellow', 'FLAVOR': 'tart'}) as env:
            self.assertEqual('yellow', f.color)
            self.assertEqual('tart', f.flavor)

    @unit_test_function_skip.skip_if(not host.is_unix(), 'not unix')
    def test_env_var_tilde(self):
        f = self.fruit('yellow', '~/tart')
        with env_override({'HOME': '/tmp/foo'}) as env:
            self.assertEqual('yellow', f.color)
            self.assertEqual('/tmp/foo/tart', f.flavor)

    @unit_test_function_skip.skip_if(not host.is_unix(), 'not unix')
    def test_env_var_tilde_and_var(self):
        f = self.fruit('yellow', '~/${FLAVOR}')
        with env_override({'HOME': '/tmp/foo', 'FLAVOR': 'tart'}) as env:
            self.assertEqual('yellow', f.color)
            self.assertEqual('/tmp/foo/tart', f.flavor)
Пример #2
0
  def test_one_script_with_dry_run(self):
    r = git_temp_repo(debug = self.DEBUG)
    if host.is_windows():
      script = self.native_filename('fruits/kiwi.bat')
      content = '''\
@echo off
echo {} %*
exit 0
'''.format(script)
    elif host.is_unix():
      script = self.native_filename('fruits/kiwi.sh')
      content = '''\
#!/bin/bash
echo {} ${{1+"$@"}}
exit 0
'''.format(script)
    else:
      assert False
    xp_script = self.native_filename(script)
    r.add_file(self.native_filename(xp_script), content, mode = 0o0755)
    r.push('origin', 'master')
    r.tag('1.0.0')
    r.push_tag('1.0.0')
    options = git_repo_script_options(dry_run = True)
    scripts = [
      git_util.script(xp_script, [ 'arg1', 'arg2' ]),
    ]
    rv = git_util.repo_run_scripts(r.address, scripts, options = options)
    self.assertEqual( [ None ], rv.results )
Пример #3
0
 def xp_filename(clazz, p, sep=None):
     if host.is_windows():
         return clazz._xp_filename_windows(p, sep=sep)
     elif host.is_unix():
         return clazz._xp_filename_unix(p, sep=sep)
     else:
         host.raise_unsupported_system()
Пример #4
0
class test_python_exe(unit_test):

  def test_full_version(self):
    fake_exe = python_testing.make_temp_fake_python('python', '2.7.666', debug = self.DEBUG)
    self.assertEqual( '2.7.666', str(python_exe.full_version(fake_exe)) )

  def test_version(self):
    fake_exe = python_testing.make_temp_fake_python('python', '2.7.666', debug = self.DEBUG)
    self.assertEqual( '2.7', str(python_exe.version(fake_exe)) )

  def test_check_exe_success(self):
    fake_exe = python_testing.make_temp_fake_python('python6.7', '6.7.666', debug = self.DEBUG)
    self.assertEqual( '6.7.666', python_exe.check_exe(fake_exe) )

  @unit_test_function_skip.skip_if(not host.is_unix(), 'not unix')
  def test_check_exe_not_executable(self):
    fake_exe = python_testing.make_temp_fake_python('python6.7', '6.7.666', mode = 0o0600, debug = self.DEBUG)
    with self.assertRaises(python_error) as ctx:
      python_exe.check_exe(fake_exe)
    self.assertTrue( 'not a valid executable' in str(ctx.exception) )
    
  def test_check_exe_not_abs(self):
    with self.assertRaises(python_error) as ctx:
      python_exe.check_exe('python6.7')
    self.assertTrue( 'not an absolute path' in str(ctx.exception) )
Пример #5
0
class test_which(unit_test):
    @unit_test_function_skip.skip_if(not host.is_unix(), 'not unix')
    def test_which_unix(self):
        'Test which() in unix.'
        tmp_dir = self.make_temp_dir()
        bin_dir = path.join(tmp_dir, 'bin')
        content = '!#/bin/bash\nechoecho kiwi\nexit 0\n'
        temp_exe = file_util.save(path.join(bin_dir, 'fruit_kiwi_tool'),
                                  content=content,
                                  mode=0o0755)
        self.assertEqual(None, which.which('fruit_kiwi_tool'))
        with env_override.path_append(bin_dir) as env:
            expected_path = path.join(bin_dir, 'fruit_kiwi_tool')
            self.assertEqual(expected_path, which.which('fruit_kiwi_tool'))

    @unit_test_function_skip.skip_if(not host.is_windows(), 'not windows')
    def test_which_windows(self):
        'Test which() in unix.'
        tmp_dir = self.make_temp_dir()
        bin_dir = path.join(tmp_dir, 'bin')
        content = '@echo off\n\recho kiwi\n\rexit 0\n\r'
        temp_bat = file_util.save(path.join(bin_dir, 'fruit_kiwi_tool.bat'),
                                  content=content,
                                  mode=0o0755)
        self.assertEqual(None, which.which('fruit_kiwi_tool.bat'))
        with env_override.path_append(bin_dir) as env:
            expected_path = path.join(bin_dir, 'fruit_kiwi_tool.bat')
            self.assertEqual(expected_path, which.which('fruit_kiwi_tool.bat'))
            self.assertEqual(expected_path, which.which('fruit_kiwi_tool'))
Пример #6
0
 def _git_exe_name(clazz):
     'Return the platform specific name of the git exe.'
     if host.is_unix():
         return 'git'
     elif host.is_windows():
         return 'git.exe'
     else:
         host.raise_unsupported_system()
Пример #7
0
 def bin_dir(self):
   if host.is_windows():
     bin_dir = path.join(self.user_base_install_dir, 'Scripts')
   elif host.is_unix():
     bin_dir = path.join(self.user_base_install_dir, 'bin')
   else:
     host.raise_unsupported_system()
   return bin_dir
Пример #8
0
 def site_packages_dir(self):
   if host.is_windows():
     site_packages_dir = path.join(self.user_base_install_dir, 'site-packages')
   elif host.is_unix():
     site_packages_dir = path.join(self.user_base_install_dir, 'lib/python/site-packages')
   else:
     host.raise_unsupported_system()
   return site_packages_dir
Пример #9
0
  def find_exe_for_python(clazz, python_exe):
    'Find pip executable for a specific python exe'
    bes_python_exe.check_exe(python_exe)

    if host.is_windows():
      result = clazz._find_exe_for_python_windows(python_exe)
    elif host.is_unix():
      result = clazz._find_exe_for_python_unix(python_exe)
    else:
      host.raise_unsupported_system()
    return result
Пример #10
0
  def test_many_scripts_with_push(self):
    r1 = git_temp_repo(debug = self.DEBUG)
    if host.is_windows():
      script1 = self.native_filename('scripts/script1.bat')
      script2 = self.native_filename('scripts/script2.bat')
      content1 = '''\
@echo off
echo %1% > color.txt
git add color.txt
git commit -madd color.txt
exit 0
'''
      content2 = '''\
@echo off
echo %1% > fruit.txt
git add fruit.txt
git commit -madd fruit.txt
exit 0
'''
    elif host.is_unix():
      script1 = self.native_filename('scripts/script1.sh')
      script2 = self.native_filename('scripts/script2.sh')
      content1 = '''\
#!/bin/bash
echo ${1} > color.txt
git add color.txt
git commit -madd color.txt
exit 0
'''
      content2 = '''\
#!/bin/bash
echo ${1} > fruit.txt
git add fruit.txt
git commit -madd fruit.txt
exit 0
'''
    else:
      assert False
    r1.add_file(script1, content1, mode = 0o0755)
    r1.add_file(script2, content2, mode = 0o0755)
    r1.push('origin', 'master')
    r1.tag('1.0.0')
    r1.push_tag('1.0.0')
    scripts = [
      git_util.script(script1, [ 'yellow' ]),
      git_util.script(script2, [ 'kiwi' ]),
    ]
    options = git_repo_script_options(push = True)
    rv = git_util.repo_run_scripts(r1.address, scripts, options = options)

    r2 = r1.make_temp_cloned_repo()
    self.assertEqual( 'yellow', r2.read_file('color.txt').strip() )
    self.assertEqual( 'kiwi', r2.read_file('fruit.txt').strip() )
Пример #11
0
  def test_push_conflict(self):
    r1 = git_temp_repo(debug = self.DEBUG)
    if host.is_windows():
      script = self.native_filename('fruits/kiwi.bat')
      content = '''\
@echo off
echo %1 > %1
git add %1
git commit -m"add %1" %1
exit 0
'''
    elif host.is_unix():
      script = self.native_filename('fruits/kiwi.sh')
      content = '''\
#!/bin/bash
echo ${1} > ${1}
git add ${1}
git commit -m"add ${1}" ${1}
exit 0
'''
    else:
      assert False
    xp_script = self.native_filename(script)
    r1.add_file(self.native_filename(xp_script), content, mode = 0o0755)
    r1.push('origin', 'master')

    jobs = []
    for fruit in self._FRUITS:
      p = multiprocessing.Process(target = self._worker_test_push_conflict, args = ( fruit, r1.address, xp_script ) )
      jobs.append(p)
      p.start()

    for job in jobs:
      job.join()

    r2 = git_repo(self.make_temp_dir(), address = r1.address)
    r2.clone_or_pull()

    self.assertEqual( {
      xp_script, 
      'apple',
      'blueberry',
      'kiwi',
      'lemon',
      'melon',
      'orange',
      'papaya',
      'pineapple',
      'watermelon',
    }, set(r2.find_all_files()) )

    '''
Пример #12
0
 def _ensure_versioned_python_exe(clazz, root_dir, exe):
     'On some unix systems with certain python versions (3.7) the venv exe with major.minor version is missing.'
     if not host.is_unix():
         return
     version = python_exe.version(exe)
     versioned_exe = python_source.versioned_python_exe(root_dir, version)
     if not path.isfile(versioned_exe):
         exe = python_source.python_exe(root_dir, version)
         file_symlink.symlink(path.basename(exe), versioned_exe)
         if not path.isfile(versioned_exe):
             raise python_error(
                 'Failed to create versioned python exe symlink: "{}"'.
                 format(versioned_exe))
Пример #13
0
class test_python_exe_filename(unit_test):
    @unit_test_function_skip.skip_if(not host.is_unix(), 'not unix')
    def test_name_unix(self):
        self.assertEqual('python', python_exe_filename.name('/usr/bin/python'))
        self.assertEqual('python2',
                         python_exe_filename.name('/usr/bin/python2'))
        self.assertEqual('python2.7',
                         python_exe_filename.name('/usr/bin/python2.7'))

    @unit_test_function_skip.skip_if(not host.is_windows(), 'not windows')
    def test_name_windows(self):
        self.assertEqual(
            'python',
            python_exe_filename.name(r'C:\Program Files\Python38\python.exe'))
Пример #14
0
class best_cli(cli):
    def __init__(self):
        super(best_cli, self).__init__('best')

    from bes.system.host import host

    COMMAND_GROUPS = []

    if host.is_macos():
        from .best_cli_macos import MACOS_COMMAND_GROUPS
        COMMAND_GROUPS.extend(MACOS_COMMAND_GROUPS)

    if host.is_unix():
        from .best_cli_unix import UNIX_COMMAND_GROUPS
        COMMAND_GROUPS.extend(UNIX_COMMAND_GROUPS)

    if host.is_windows():
        from .best_cli_windows import WINDOWS_COMMAND_GROUPS
        COMMAND_GROUPS.extend(WINDOWS_COMMAND_GROUPS)

    from .best_cli_common import COMMON_COMMAND_GROUPS
    COMMAND_GROUPS.extend(COMMON_COMMAND_GROUPS)

    #@abstractmethod
    def command_group_list(self):
        'Return a list of command groups for this cli.'
        return self.COMMAND_GROUPS

    from bes.cli.cli_env_cli_args import cli_env_cli_args
    from bes.cli.cli_version_cli_args import cli_version_cli_args
    from bes.cli.cli_help_cli_args import cli_help_cli_args
    cli_version_cli_args.version_module_name = 'bes'
    cli_version_cli_args.version_dependencies = None
    COMMANDS = [
        cli_command('env', 'env_add_args', 'Print env information',
                    cli_env_cli_args),
        cli_command('help', 'help_add_args', 'Print help', cli_help_cli_args),
        cli_command('version', 'version_add_args', 'Print version information',
                    cli_version_cli_args),
    ]

    #@abstractmethod
    def command_list(self):
        'Return a list of commands for this cli.'
        return self.COMMANDS

    @classmethod
    def run(clazz):
        raise SystemExit(best_cli().main())
Пример #15
0
 def _make_read_only_temp_file(self):
     from bes.fs.file_util import file_util
     tmp = self._make_temp_file('this is foo\n')
     print('B4: tmp={} mode={}'.format(tmp, file_util.mode(tmp)))
     import os
     #      os.chmod(tmp, stat.S_IREAD)
     os.chmod(tmp, 0o0400)
     print('AF: tmp={} mode={}'.format(tmp, file_util.mode(tmp)))
     return tmp
     if host.is_unix():
         return file_symlink.resolve('/bin/sh')
     elif host.is_windows():
         return r'C:\Windows\System32\cmd.exe'
     else:
         host.raise_unsupported_system()
Пример #16
0
class test_program_unit_test_true(program_unit_test):

    if host.is_unix():
        _program = program_unit_test.file_path(__file__, 'true.sh')
    elif host.is_windows():
        _program = program_unit_test.file_path(__file__, 'true.bat')
    else:
        host.raise_unsupported_system()

    def test_true(self):
        rv = self.run_program(self._program, ['foo', 'bar'])
        self.assertEqual(0, rv.exit_code)
        self.assert_string_equal_strip('foo bar', rv.output)

    def test_true_raw(self):
        rv = self.run_program_raw(self._program, ['foo', 'bar'])
        self.assertEqual(0, rv.exit_code)
        self.assert_string_equal_strip(b'foo bar', rv.output)
Пример #17
0
class line_break(object):
    'Deal with line breaks.'

    # str.splitlines() uses these as line break delimiters
    LINE_BREAKS = [
        '\r\n',  # Carriage Return + Line Feed
        '\n',  # Line Feed
        '\r',  # Carriage Return
        '\v',  # or \x0b	Line Tabulation
        '\f',  # or \x0c	Form Feed
        '\x1c',  # File Separator
        '\x1d',  # Group Separator
        '\x1e',  # Record Separator
        #    '\x85',   # Next Line (C1 Control Code)
        '\u2028',  # Line Separator
        '\u2029',  # Paragraph Separator
    ]

    LINE_BREAKS_SET = set(LINE_BREAKS)

    if host.is_unix():
        DEFAULT_LINE_BREAK = '\n'
        DEFAULT_LINE_BREAK_RAW = r'\n'
    else:
        DEFAULT_LINE_BREAK = '\r\n'
        DEFAULT_LINE_BREAK_RAW = r'\r\n'

    @classmethod
    def is_line_break(clazz, c):
        'return true if c is a line break'
        return c in clazz.LINE_BREAKS_SET

    @classmethod
    def ends_with_line_break(clazz, s):
        'Return True if s ends with a line break'
        return clazz.is_line_break(s[-1])

    @classmethod
    def guess_line_break(clazz, s):
        'Guess the line break for a multi line string or None if not multi line.'
        for lb in clazz.LINE_BREAKS:
            if lb in s:
                return lb
        return None
Пример #18
0
 def _make_test_program(self):
     tmp_dir = self.make_temp_dir()
     file_util.save(path.join(tmp_dir, 'farm_cli.py'),
                    content=self._FARM_CLI_DOT_PY)
     file_util.save(path.join(tmp_dir, 'fruit_cli_args.py'),
                    content=self._FRUIT_CLI_ARGS_DOT_PY)
     file_util.save(path.join(tmp_dir, 'cheese_cli_args.py'),
                    content=self._CHEESE_CLI_ARGS_DOT_PY)
     unix_program = file_util.save(path.join(tmp_dir, 'farm.py'),
                                   content=self._FARM_DOT_PY)
     if host.is_unix():
         program = unix_program
     elif host.is_windows():
         content = self._FARM_DOT_BAT.format(executable=sys.executable)
         program = file_util.save(path.join(tmp_dir, 'farm.bat'),
                                  content=content)
     else:
         host.raise_unsupported_system()
     return program
Пример #19
0
  def test_one_script_with_bump_tag(self):
    r1 = git_temp_repo(debug = self.DEBUG)
    if host.is_windows():
      script = 'nothing.bat'
      content = '''\
@echo off
exit 0
'''.format(script)
    elif host.is_unix():
      script = './nothing.sh'
      content = '''\
#!/bin/bash
exit 0
'''.format(script)
    else:
      assert False
    xp_script = self.native_filename(script)
    r1.add_file(xp_script, content, mode = 0o0755)
    r1.push('origin', 'master')
    r1.tag('1.0.0')
    r1.push_tag('1.0.0')
    options = git_repo_script_options(bump_tag_component = 'revision')
    scripts = [
      git_util.script(xp_script, []),
    ]
    rv = git_util.repo_run_scripts(r1.address, scripts, options = options)
    self.assertEqual( 1, len(rv.results) )

    r2 = r1.make_temp_cloned_repo()
    self.assertEqual( '1.0.1', r2.greatest_local_tag().name )

    options = git_repo_script_options(bump_tag_component = 'major')
    scripts = [
      git_util.script(xp_script, []),
    ]
    rv = git_util.repo_run_scripts(r1.address, scripts, options = options)
    self.assertEqual( 1, len(rv.results) )
    self.assertEqual( '2.0.1', r2.greatest_remote_tag().name )
Пример #20
0
  def test_one_script_with_push(self):
    r1 = git_temp_repo(debug = self.DEBUG)
    if host.is_windows():
      script = self.native_filename('fruits/kiwi.bat')
      content = '''\
@echo off
echo yellow > color.txt
git add color.txt
git commit -madd color.txt
exit 0
'''
    elif host.is_unix():
      script = self.native_filename('fruits/kiwi.sh')
      content = '''\
#!/bin/bash
echo yellow > color.txt
git add color.txt
git commit -madd color.txt
exit 0
'''
    else:
      assert False
    xp_script = self.native_filename(script)
    r1.add_file(xp_script, content, mode = 0o0755)
    r1.push('origin', 'master')
    r1.tag('1.0.0')
    r1.push_tag('1.0.0')
    options = git_repo_script_options(push = True)
    scripts = [
      git_util.script(xp_script, [ 'arg1', 'arg2' ]),
    ]
    rv = git_util.repo_run_scripts(r1.address, scripts, options = options)
    self.assertEqual( 1, len(rv.results) )

    r2 = r1.make_temp_cloned_repo()
    self.assertEqual( 'yellow', r2.read_file('color.txt').strip() )
Пример #21
0
 def raise_skip_if_not_unix(clazz):
     clazz.raise_skip_if_not(host.is_unix(),
                             'system is not unix: {}'.format(host.SYSTEM))
Пример #22
0
class test_execute(unit_test):
    @unit_test_function_skip.skip_if(not host.is_windows(), 'not windows')
    def test_windows_batch_file_success(self):
        script = '''\
@echo off
echo %*
exit 0
'''
        bat = self.make_temp_file(content=script, suffix='.bat')
        cmd = [bat, 'foo', 'bar']
        rv = execute.execute(cmd, shell=False)
        self.assertEqual(0, rv.exit_code)
        self.assertEqual('foo bar', rv.stdout.strip())

    @unit_test_function_skip.skip_if(not host.is_windows(), 'not windows')
    def test_windows_batch_file_success_flat(self):
        script = '''\
@echo off
echo %*
exit 0
'''
        bat = self.make_temp_file(content=script, suffix='.bat')
        cmd = f'{bat} foo bar'
        rv = execute.execute(cmd, shell=False)
        self.assertEqual(0, rv.exit_code)
        self.assertEqual('foo bar', rv.stdout.strip())

    @unit_test_function_skip.skip_if(not host.is_windows(), 'not windows')
    def test_windows_batch_file_success_shell(self):
        script = '''\
@echo off
echo %*
exit 0
'''
        bat = self.make_temp_file(content=script, suffix='.bat')
        cmd = [bat, 'foo', 'bar']
        rv = execute.execute(cmd, shell=True, quote=True)
        self.assertEqual(0, rv.exit_code)
        self.assertEqual('foo bar', rv.stdout.strip())

    @unit_test_function_skip.skip_if(not host.is_windows(), 'not windows')
    def test_windows_batch_file_success_flat_shell(self):
        script = '''\
@echo off
echo %*
exit 0
'''
        bat = self.make_temp_file(content=script, suffix='.bat')
        cmd = f'"{bat}" foo bar'
        rv = execute.execute(cmd, shell=True, quote=True)
        self.assertEqual(0, rv.exit_code)
        self.assertEqual('foo bar', rv.stdout.strip())

    @unit_test_function_skip.skip_if(not host.is_windows(), 'not windows')
    def test_windows_batch_file_failure(self):
        script = '''\
@echo off
echo %*
exit 1
'''
        bat = self.make_temp_file(content=script, suffix='.bat')
        cmd = [bat, 'foo', 'bar']
        rv = execute.execute(cmd, shell=False, raise_error=False)
        self.assertEqual(1, rv.exit_code)

    @unit_test_function_skip.skip_if(not host.is_windows(), 'not windows')
    def test_windows_batch_file_failure_flat(self):
        script = '''\
@echo off
echo %*
exit 1
'''
        bat = self.make_temp_file(content=script, suffix='.bat')
        cmd = f'"{bat}" foo bar'
        rv = execute.execute(cmd, shell=False, raise_error=False)
        self.assertEqual(1, rv.exit_code)
        self.assertEqual('foo bar', rv.stdout.strip())

    @unit_test_function_skip.skip_if(not host.is_windows(), 'not windows')
    def test_windows_batch_file_failure_shell(self):
        script = '''\
@echo off
echo %*
exit 1
'''
        bat = self.make_temp_file(content=script, suffix='.bat')
        cmd = [bat, 'foo', 'bar']
        rv = execute.execute(cmd, shell=True, raise_error=False, quote=True)
        self.assertEqual(1, rv.exit_code)

    @unit_test_function_skip.skip_if(not host.is_windows(), 'not windows')
    def test_windows_batch_file_failure_flat_shell(self):
        script = '''\
@echo off
echo %*
exit 1
'''
        bat = self.make_temp_file(content=script, suffix='.bat')
        cmd = f'"{bat}" foo bar'
        rv = execute.execute(cmd, shell=True, raise_error=False, quote=True)
        self.assertEqual(1, rv.exit_code)

    @unit_test_function_skip.skip_if(not host.is_unix(), 'not unix')
    def test_unix_shell_script_success(self):
        script = '''\
#!/bin/sh
echo "$@"
exit 0
'''
        bat = self.make_temp_file(content=script, perm=0o0755, suffix='.sh')
        cmd = [bat, 'foo', 'bar']
        rv = execute.execute(cmd, shell=False)
        self.assertEqual(0, rv.exit_code)
        self.assertEqual('foo bar', rv.stdout.strip())

    @unit_test_function_skip.skip_if(not host.is_unix(), 'not unix')
    def test_unix_shell_script_success_flat(self):
        script = '''\
#!/bin/sh
echo "$@"
exit 0
'''
        bat = self.make_temp_file(content=script, perm=0o0755, suffix='.sh')
        cmd = f'"{bat}" foo bar'
        rv = execute.execute(cmd, shell=False)
        self.assertEqual(0, rv.exit_code)
        self.assertEqual('foo bar', rv.stdout.strip())

    @unit_test_function_skip.skip_if(not host.is_unix(), 'not unix')
    def test_unix_shell_script_success_shell(self):
        script = '''\
#!/bin/sh
echo "$@"
exit 0
'''
        bat = self.make_temp_file(content=script, perm=0o0755, suffix='.sh')
        cmd = [bat, 'foo', 'bar']
        rv = execute.execute(cmd, shell=True, quote=True)
        self.assertEqual(0, rv.exit_code)
        self.assertEqual('foo bar', rv.stdout.strip())

    @unit_test_function_skip.skip_if(not host.is_unix(), 'not unix')
    def test_unix_shell_script_success_flat_shell(self):
        script = '''\
#!/bin/sh
echo "$@"
exit 0
'''
        bat = self.make_temp_file(content=script, perm=0o0755, suffix='.sh')
        cmd = f'"{bat}" foo bar'
        rv = execute.execute(cmd, shell=True, quote=True)
        self.assertEqual(0, rv.exit_code)
        self.assertEqual('foo bar', rv.stdout.strip())

    @unit_test_function_skip.skip_if(not host.is_unix(), 'not unix')
    def test_unix_shell_script_failure(self):
        script = '''\
#!/bin/sh
echo "$@"
exit 1
'''
        bat = self.make_temp_file(content=script, perm=0o0755, suffix='.sh')
        cmd = [bat, 'foo', 'bar']
        rv = execute.execute(cmd, shell=False, raise_error=False)
        self.assertEqual(1, rv.exit_code)

    @unit_test_function_skip.skip_if(not host.is_unix(), 'not unix')
    def test_unix_shell_script_failure_flat(self):
        script = '''\
#!/bin/sh
echo "$@"
exit 1
'''
        bat = self.make_temp_file(content=script, perm=0o0755, suffix='.sh')
        cmd = f'"{bat}" foo bar'
        rv = execute.execute(cmd, shell=False, raise_error=False)
        self.assertEqual(1, rv.exit_code)
        self.assertEqual('foo bar', rv.stdout.strip())

    @unit_test_function_skip.skip_if(not host.is_unix(), 'not unix')
    def test_unix_shell_script_failure_shell(self):
        script = '''\
#!/bin/sh
echo "$@"
exit 1
'''
        bat = self.make_temp_file(content=script, perm=0o0755, suffix='.sh')
        cmd = [f'"{bat}"', 'foo', 'bar']
        rv = execute.execute(cmd, shell=True, raise_error=False, quote=True)
        self.assertEqual(1, rv.exit_code)

    @unit_test_function_skip.skip_if(not host.is_unix(), 'not unix')
    def test_unix_shell_script_failure_flat_shell(self):
        script = '''\
#!/bin/sh
echo "$@"
exit 1
'''
        bat = self.make_temp_file(content=script, perm=0o0755, suffix='.sh')
        cmd = f'"{bat}" foo bar'
        rv = execute.execute(cmd, shell=True, raise_error=False, quote=True)
        self.assertEqual(1, rv.exit_code)

    def test_python_script_success(self):
        content = '''\
import sys
print(f'success:{sys.argv[1]}')
raise SystemExit(0)
'''
        script = self.make_temp_file(content=content,
                                     perm=0o0755,
                                     suffix='.py')
        cmd = [script, 'foo']
        rv = execute.execute(cmd, shell=True, raise_error=False, quote=True)
        self.assertEqual(0, rv.exit_code)
        self.assertEqual('success:foo', rv.stdout.strip())

    def test_python_script_failure(self):
        content = '''\
import sys
print(f'failure:{sys.argv[1]}')
raise SystemExit(1)
'''
        script = self.make_temp_file(content=content,
                                     perm=0o0755,
                                     suffix='.py')
        cmd = [script, 'foo']
        rv = execute.execute(cmd, shell=True, raise_error=False, quote=True)
        self.assertEqual(1, rv.exit_code)

    def test_python_script_uppercase_extension(self):
        content = '''\
import sys
print(f'success:{sys.argv[1]}')
raise SystemExit(0)
'''
        script = self.make_temp_file(content=content,
                                     perm=0o0755,
                                     suffix='.PY')
        cmd = [script, 'foo']
        rv = execute.execute(cmd, shell=True, raise_error=False, quote=True)
        self.assertEqual(0, rv.exit_code)
        self.assertEqual('success:foo', rv.stdout.strip())

    @unit_test_function_skip.skip_if(not host.is_unix(), 'not unix')
    def test_execute_stdout_stderr(self):
        script = '''\
#!/bin/sh
echo "this_is_stderr 1" >&2
echo "this_is_stdout 1" >&1
echo "this_is_stderr 2" >&2
echo "this_is_stdout 2" >&1
echo "this_is_stdout 3" >&1
echo "this_is_stdout 4" >&1
echo "this_is_stderr 3" >&2
echo "this_is_stderr 4" >&2
exit 0
'''
        bat = self.make_temp_file(content=script, perm=0o0755)
        rv = execute.execute(bat, shell=False, raise_error=False)
        self.assertEqual(0, rv.exit_code)
        self.assert_string_equal_fuzzy(
            r'''
this_is_stdout 1
this_is_stdout 2
this_is_stdout 3
this_is_stdout 4
''', rv.stdout)

        self.assert_string_equal_fuzzy(
            r'''
this_is_stderr 1
this_is_stderr 2
this_is_stderr 3
this_is_stderr 4
''', rv.stderr)

    @unit_test_function_skip.skip_if(not host.is_unix(), 'not unix')
    def test_execute_stdout_stderr_non_blocking(self):
        script = '''\
#!/bin/sh
echo "this_is_stderr 1" >&2
echo "this_is_stdout 1" >&1
echo "this_is_stderr 2" >&2
echo "this_is_stdout 2" >&1
echo "this_is_stdout 3" >&1
echo "this_is_stdout 4" >&1
echo "this_is_stderr 3" >&2
echo "this_is_stderr 4" >&2
exit 0
'''
        bat = self.make_temp_file(content=script, perm=0o0755)
        rv = execute.execute(bat,
                             shell=False,
                             raise_error=False,
                             non_blocking=True)
        self.assertEqual(0, rv.exit_code)
        self.assert_string_equal_fuzzy(
            r'''
this_is_stdout 1
this_is_stdout 2
this_is_stdout 3
this_is_stdout 4
''', rv.stdout)

        self.assert_string_equal_fuzzy(
            r'''
this_is_stderr 1
this_is_stderr 2
this_is_stderr 3
this_is_stderr 4
''', rv.stderr)

    @unit_test_function_skip.skip_if(not host.is_unix(), 'not unix')
    def test_execute_stderr_to_stdout_non_blocking(self):
        script = '''\
#!/bin/sh
echo "this_is_stderr 1" >&2
echo "this_is_stdout 1" >&1
echo "this_is_stderr 2" >&2
echo "this_is_stdout 2" >&1
echo "this_is_stdout 3" >&1
echo "this_is_stdout 4" >&1
echo "this_is_stderr 3" >&2
echo "this_is_stderr 4" >&2
exit 0
'''
        bat = self.make_temp_file(content=script, perm=0o0755)
        rv = execute.execute(bat,
                             shell=False,
                             raise_error=False,
                             non_blocking=True,
                             stderr_to_stdout=True)
        self.assertEqual(0, rv.exit_code)
        self.assert_string_equal_fuzzy(
            r'''
this_is_stderr 1
this_is_stdout 1
this_is_stderr 2
this_is_stdout 2
this_is_stdout 3
this_is_stdout 4
this_is_stderr 3
this_is_stderr 4
''', rv.stdout)

        self.assert_string_equal_fuzzy('', rv.stderr)

    @unit_test_function_skip.skip_if(not host.is_unix(), 'not unix')
    def test_execute_output_function_non_blocking(self):
        script = '''\
#!/bin/sh
echo "this_is_stderr 1" >&2
echo "this_is_stdout 1" >&1
echo "this_is_stderr 2" >&2
echo "this_is_stdout 2" >&1
echo "this_is_stdout 3" >&1
echo "this_is_stdout 4" >&1
echo "this_is_stderr 3" >&2
echo "this_is_stderr 4" >&2
exit 0
'''
        stdout_lines = []
        stderr_lines = []

        def _func(output):
            stdout_lines.append(output.stdout)
            stderr_lines.append(output.stderr)

        bat = self.make_temp_file(content=script, perm=0o0755)
        rv = execute.execute(bat,
                             shell=False,
                             raise_error=False,
                             non_blocking=True,
                             output_function=_func)
        self.assertEqual(0, rv.exit_code)
        self.assert_string_equal_fuzzy(
            r'''
this_is_stdout 1
this_is_stdout 2
this_is_stdout 3
this_is_stdout 4
''', rv.stdout)

        self.assert_string_equal_fuzzy(
            r'''
this_is_stderr 1
this_is_stderr 2
this_is_stderr 3
this_is_stderr 4
''', rv.stderr)

        self.assert_string_equal_fuzzy(
            r'''
this_is_stdout 1
this_is_stdout 2
this_is_stdout 3
this_is_stdout 4
''', os.linesep.join(stdout_lines))

        self.assert_string_equal_fuzzy(
            r'''
this_is_stderr 1
this_is_stderr 2
this_is_stderr 3
this_is_stderr 4
''', os.linesep.join(stderr_lines))

    @unit_test_function_skip.skip_if(not host.is_unix(), 'not unix')
    def test_execute_output_function_non_blocking_with_stderr_to_stdout(self):
        script = '''\
#!/bin/sh
echo "this_is_stderr 1" >&2
echo "this_is_stdout 1" >&1
echo "this_is_stderr 2" >&2
echo "this_is_stdout 2" >&1
echo "this_is_stdout 3" >&1
echo "this_is_stdout 4" >&1
echo "this_is_stderr 3" >&2
echo "this_is_stderr 4" >&2
exit 0
'''
        stdout_lines = []
        stderr_lines = []

        def _func(output):
            if output.stdout:
                stdout_lines.append(output.stdout)
            if output.stderr:
                stderr_lines.append(output.stderr)

        bat = self.make_temp_file(content=script, perm=0o0755)
        rv = execute.execute(bat,
                             shell=False,
                             raise_error=False,
                             non_blocking=True,
                             output_function=_func,
                             stderr_to_stdout=True)
        self.assertEqual(0, rv.exit_code)
        self.assert_string_equal_fuzzy(
            r'''
this_is_stderr 1
this_is_stdout 1
this_is_stderr 2
this_is_stdout 2
this_is_stdout 3
this_is_stdout 4
this_is_stderr 3
this_is_stderr 4
''', rv.stdout)

        self.assert_string_equal_fuzzy('', rv.stderr)

        self.assert_string_equal_fuzzy(
            r'''
this_is_stderr 1
this_is_stdout 1
this_is_stderr 2
this_is_stdout 2
this_is_stdout 3
this_is_stdout 4
this_is_stderr 3
this_is_stderr 4
''', os.linesep.join(stdout_lines))

        self.assert_string_equal_fuzzy('', os.linesep.join(stderr_lines))
Пример #23
0
 def skip_if_not_unix(warning = False):
   return unit_test_function_skip.skip_if(not host.is_unix(), 'not unix', warning = warning)
 def is_supported(clazz):
     'Return True if this class is supported on the current platform.'
     return host.is_unix() and which.which('file') != None
Пример #25
0
class test_file_find(unit_test):

  @classmethod
  def _make_temp_content(clazz, items):
    return temp_content.write_items_to_temp_dir(items, delete = not clazz.DEBUG)

  def test_file_sync_basic(self):
    tmp_src_dir = self._make_temp_content([
      'file foo.txt "foo.txt\n"',
      'file subdir/bar.txt "bar.txt\n"',
      'file subdir/subberdir/baz.txt "baz.txt\n"',
      'file emptyfile.txt',
      'dir emptydir',
    ])
    tmp_dst_dir = temp_file.make_temp_dir()
    file_sync.sync(tmp_src_dir, tmp_dst_dir)
    expected = [
      self.native_filename('emptyfile.txt'),
      self.native_filename('foo.txt'),
      self.native_filename('subdir/bar.txt'),
      self.native_filename('subdir/subberdir/baz.txt'),
    ]
    self.assertEqual( expected, file_find.find(tmp_dst_dir, relative = True) )

  def test_file_sync_remove_one(self):
    tmp_src_dir1 = self._make_temp_content([
      'file foo.txt "foo.txt\n"',
      'file subdir/bar.txt "bar.txt\n"',
      'file subdir/subberdir/baz.txt "baz.txt\n"',
      'file emptyfile.txt',
      'dir emptydir',
    ])
    tmp_src_dir2 = self._make_temp_content([
      'file subdir/bar.txt "bar.txt\n"',
      'file subdir/subberdir/baz.txt "baz.txt\n"',
      'file emptyfile.txt',
      'dir emptydir',
    ])
    tmp_dst_dir = temp_file.make_temp_dir()
    file_sync.sync(tmp_src_dir1, tmp_dst_dir)
    file_sync.sync(tmp_src_dir2, tmp_dst_dir)
    expected = [
      self.native_filename('emptyfile.txt'),
      self.native_filename('subdir/bar.txt'),
      self.native_filename('subdir/subberdir/baz.txt'),
    ]
    self.assertEqual( expected, file_find.find(tmp_dst_dir, relative = True) )

  def test_file_sync_change_one(self):
    tmp_src_dir1 = self._make_temp_content([
      'file foo.txt "first foo.txt\n"',
      'file subdir/bar.txt "bar.txt\n"',
      'file subdir/subberdir/baz.txt "baz.txt\n"',
      'file emptyfile.txt',
      'dir emptydir',
    ])
    tmp_src_dir2 = self._make_temp_content([
      'file foo.txt "second foo.txt\n"',
      'file subdir/bar.txt "bar.txt\n"',
      'file subdir/subberdir/baz.txt "baz.txt\n"',
      'file emptyfile.txt',
      'dir emptydir',
    ])
    tmp_dst_dir = temp_file.make_temp_dir()
    file_sync.sync(tmp_src_dir1, tmp_dst_dir)
    file_sync.sync(tmp_src_dir2, tmp_dst_dir)
    expected = [
      self.native_filename('emptyfile.txt'),
      self.native_filename('foo.txt'),
      self.native_filename('subdir/bar.txt'),
      self.native_filename('subdir/subberdir/baz.txt'),
    ]
    self.assertEqual( expected, file_find.find(tmp_dst_dir, relative = True) )
    self.assertEqual( 'second foo.txt\n', file_util.read(path.join(tmp_dst_dir, 'foo.txt'), codec = 'utf8') )

  def test_file_sync_with_exclude(self):
    tmp_src_dir = self._make_temp_content([
      'file foo.txt "foo.txt\n"',
      'file subdir/bar.txt "bar.txt\n"',
      'file subdir/subberdir/baz.txt "baz.txt\n"',
      'file emptyfile.txt',
      'dir emptydir',
    ])
    tmp_dst_dir = temp_file.make_temp_dir()
    file_sync.sync(tmp_src_dir, tmp_dst_dir, exclude = [
      self.native_filename('foo.txt'),
      self.native_filename('subdir/subberdir/baz.txt'),
    ])
    expected = [
      self.native_filename('emptyfile.txt'),
      self.native_filename('subdir/bar.txt'),
    ]
    self.assertEqual( expected, file_find.find(tmp_dst_dir, relative = True) )

  @unit_test_function_skip.skip_if(not host.is_unix(), 'not unix')
  def test_file_sync_with_mode(self):
    tmp_src_dir = self._make_temp_content([
      'file foo.txt "foo.txt\n" 644',
      'file bar.sh "#!/bin/bash\necho bar\n" 755',
    ])
    tmp_dst_dir = temp_file.make_temp_dir()
    file_sync.sync(tmp_src_dir, tmp_dst_dir)
    self.assertEqual( 0o0755, file_util.mode(path.join(tmp_dst_dir, 'bar.sh')) )
    self.assertEqual( 0o0644, file_util.mode(path.join(tmp_dst_dir, 'foo.txt')) )
    
  @unit_test_function_skip.skip_if(not host.is_unix(), 'not unix')
  def test_file_sync_with_mode_change(self):
    tmp_src_dir = self._make_temp_content([
      'file foo.txt "foo.txt\n" 644',
      'file bar.sh "#!/bin/bash\necho bar\n" 755',
    ])
    tmp_dst_dir = temp_file.make_temp_dir()
    file_sync.sync(tmp_src_dir, tmp_dst_dir)
    self.assertEqual( 0o0755, file_util.mode(path.join(tmp_dst_dir, 'bar.sh')) )
    self.assertEqual( 0o0644, file_util.mode(path.join(tmp_dst_dir, 'foo.txt')) )

    os.chmod(path.join(tmp_src_dir, 'foo.txt'), 0o0755)
    os.chmod(path.join(tmp_src_dir, 'bar.sh'), 0o0644)
    file_sync.sync(tmp_src_dir, tmp_dst_dir)
    self.assertEqual( 0o0644, file_util.mode(path.join(tmp_dst_dir, 'bar.sh')) )
    self.assertEqual( 0o0755, file_util.mode(path.join(tmp_dst_dir, 'foo.txt')) )
Пример #26
0
    def test_vm_builder_ssh_setup(self):

        git_access_ssh_public_key_content = r'''
ssh-rsa test_public_bitbucket_key fred@bedrock
'''
        git_access_ssh_private_key_content = r'''
-----BEGIN RSA PRIVATE KEY-----
test_private_bitbucket_key
-----END RSA PRIVATE KEY-----
'''
        git_access_ssh_public_key = self.make_temp_file(
            content=git_access_ssh_public_key_content)
        git_access_ssh_private_key = self.make_temp_file(
            content=git_access_ssh_private_key_content)

        vm_builder_access_ssh_public_key_content = r'''
ssh-rsa test_public_access_key sally@bedrock
'''
        vm_builder_access_ssh_private_key_content = r'''
-----BEGIN RSA PRIVATE KEY-----
test_private_access_key
-----END RSA PRIVATE KEY-----
'''
        vm_builder_access_ssh_public_key = self.make_temp_file(
            content=vm_builder_access_ssh_public_key_content)

        tmp_dir = self.make_temp_dir(suffix='.ssh')

        args = [
            'vm_builder',
            'vm_builder_ssh_setup',
            '--dont-include-ip-address',
            '--dont-include-comment',
            tmp_dir,
            'fred',
            git_access_ssh_public_key,
            git_access_ssh_private_key,
            'bitbucket.org',
            vm_builder_access_ssh_public_key,
        ]

        rv = self.run_program(self._program, args)
        self.assertEqual(0, rv.exit_code)
        files = file_find.find(tmp_dir)
        self.assertEqual([
            'authorized_keys',
            'config',
            'id_rsa_bitbucket_org',
            'id_rsa_bitbucket_org.pub',
            'known_hosts',
            'vm_builder_access_key.pub',
        ], files)

        private_key = path.join(tmp_dir, 'id_rsa_bitbucket_org')
        config_text = file_util.read(path.join(tmp_dir, 'config'),
                                     codec='utf-8').strip()
        expected_config = '''
Host bitbucket.org
  Hostname bitbucket.org
  IdentityFile {private_key}
  User fred
'''.format(private_key=private_key)
        self.assert_string_equal(expected_config,
                                 config_text,
                                 strip=True,
                                 multi_line=True,
                                 native_line_breaks=True)

        known_hosts_text = file_util.read(path.join(tmp_dir, 'known_hosts'),
                                          codec='utf-8').strip()
        expected_known_hosts = '''
bitbucket.org ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAubiN81eDcafrgMeLzaFPsw2kNvEcqTKl/VqLat/MaB33pZy0y3rJZtnqwR2qOOvbwKZYKiEO1O6VqNEBxKvJJelCq0dTXWT5pbO2gDXC6h6QDXCaHo6pOHGPUy+YBaGQRGuSusMEASYiWunYN0vCAI8QaXnWMXNMdFP3jHAJH0eDsoiGnLPBlBp4TNm6rYI74nMzgz3B9IikW4WVK+dc8KZJZWYjAuORU3jc1c/NPskD2ASinf8v3xnfXeukU0sJ5N6m5E8VLjObPEO+mN2t/FZTMZLiFqPWc/ALSqnMnnhwrNi2rbfg/rd/IpL8Le3pSBne8+seeFVBoGqzHM9yXw==
'''
        self.assert_string_equal(expected_known_hosts,
                                 known_hosts_text,
                                 strip=True,
                                 multi_line=True,
                                 native_line_breaks=True)

        abs_files = [path.join(tmp_dir, f) for f in files]
        if host.is_unix():
            for filename in abs_files:
                self.assertEqual(0o0600, file_util.mode(filename))
Пример #27
0
 def copy_tree(clazz, src_dir, dst_dir, excludes=None):
     'Copy src_dir to dst_dir recursively, preserving permissions and optionally excluding excludes.'
     if host.is_unix():
         tar_util.copy_tree(src_dir, dst_dir, excludes=excludes)
     else:
         xcopy.copy_tree(src_dir, dst_dir, excludes=excludes)
Пример #28
0
class test_simple_config_files(unit_test):
    def test_section(self):
        tmp_dir = self._make_temp_configs()
        s = SCL(tmp_dir, '*.config')
        s.load()
        files = [
            'animal.config',
            'bacteria.config',
            'bird.config',
            'cat.config',
            'dog.config',
            'mammal.config',
            'organism.config',
            'virus.config',
        ]
        self.assertTrue(s.has_unique_section('dog'))
        self.assertTrue(s.has_unique_section('cat'))
        self.assertFalse(s.has_unique_section('notthere'))

        self.assertEqual('false', s.section('dog').find_by_key('food'))
        self.assertEqual('true', s.section('dog').find_by_key('pet'))
        self.assertEqual('warm', s.section('dog').find_by_key('blood'))
        self.assertEqual('aerobic',
                         s.section('dog').find_by_key('respiration'))

        self.assertEqual('true', s.section('cat').find_by_key('food'))
        self.assertEqual('true', s.section('cat').find_by_key('pet'))
        self.assertEqual('warm', s.section('cat').find_by_key('blood'))
        self.assertEqual('aerobic',
                         s.section('cat').find_by_key('respiration'))

        self.assertEqual('true', s.section('bird').find_by_key('food'))
        self.assertEqual('false', s.section('bird').find_by_key('pet'))
        self.assertEqual('cold', s.section('bird').find_by_key('blood'))
        self.assertEqual('aerobic',
                         s.section('bird').find_by_key('respiration'))

    def test_section_one_config_file(self):
        tmp_file = self._make_one_temp_config()
        s = SCL(path.dirname(tmp_file), '*.config')
        s.load()
        self.assertEqual('false', s.section('dog').find_by_key('food'))
        self.assertEqual('true', s.section('dog').find_by_key('pet'))
        self.assertEqual('warm', s.section('dog').find_by_key('blood'))
        self.assertEqual('aerobic',
                         s.section('dog').find_by_key('respiration'))

        self.assertEqual('true', s.section('cat').find_by_key('food'))
        self.assertEqual('true', s.section('cat').find_by_key('pet'))
        self.assertEqual('warm', s.section('cat').find_by_key('blood'))
        self.assertEqual('aerobic',
                         s.section('cat').find_by_key('respiration'))

        self.assertEqual('true', s.section('bird').find_by_key('food'))
        self.assertEqual('false', s.section('bird').find_by_key('pet'))
        self.assertEqual('cold', s.section('bird').find_by_key('blood'))
        self.assertEqual('aerobic',
                         s.section('bird').find_by_key('respiration'))

    def test_files(self):
        tmp_dir = self._make_temp_configs()
        s = SCL(tmp_dir, '*.config')
        s.load()
        files = [
            'animal.config',
            'bacteria.config',
            'bird.config',
            'cat.config',
            'dog.config',
            'mammal.config',
            'organism.config',
            'virus.config',
        ]
        self.assertEqual([path.join(tmp_dir, f) for f in files], s.files)

    def test_files_one_config_file(self):
        tmp_file = self._make_one_temp_config()
        s = SCL(path.dirname(tmp_file), '*.config')
        s.load()
        self.assertEqual([tmp_file], s.files)

    def _make_temp_configs(self):
        organism = '''\
organism
  respiration: unknown
  food: false
'''
        animal = '''\
animal extends organism
  respiration: aerobic
  food: false
  pet: false
'''
        bacteria = '''\
bacteria extends organism
  respiration: anaerobic
'''
        virus = '''\
virus extends organism
  respiration: parasitic
'''
        bird = '''\
bird extends animal
  blood: cold
  food: true
'''
        mammal = '''\
mammal extends animal
  blood: warm
  food: maybe
'''
        dog = '''\
dog extends mammal
  food: false
  pet: true

shepherd extends dog
  food: false
  pet: false
  worker: true
  name: rin tin tin
'''
        cat = '''\
cat extends mammal
  food: true
  pet: true
'''
        tmp_dir = temp_content.write_items_to_temp_dir([
            'file organism.config "{}" 644'.format(organism),
            'file animal.config "{}" 644'.format(animal),
            'file bacteria.config "{}" 644'.format(bacteria),
            'file virus.config "{}" 644'.format(virus),
            'file bird.config "{}" 644'.format(bird),
            'file mammal.config "{}" 644'.format(mammal),
            'file dog.config "{}" 644'.format(dog),
            'file cat.config "{}" 644'.format(cat),
        ])
        return tmp_dir

    def _make_one_temp_config(self):
        content = '''\
organism
  respiration: unknown
  food: false

animal extends organism
  respiration: aerobic
  food: false
  pet: false

bacteria extends organism
  respiration: anaerobic

virus extends organism
  respiration: parasitic

bird extends animal
  blood: cold
  food: true

mammal extends animal
  blood: warm
  food: maybe

dog extends mammal
  food: false
  pet: true

cat extends mammal
  food: true
  pet: true
'''
        tmp_dir = self.make_temp_dir()
        tmp_file = path.join(tmp_dir, 'organisms.config')
        file_util.save(tmp_file, content=content)
        return tmp_file

    def test_duplicate_section(self):
        content = '''\
organism
  respiration: unknown
  food: false

organism
  respiration: unknown
  food: true
'''
        tmp_dir = self.make_temp_dir()
        tmp_file = path.join(tmp_dir, 'organisms.config')
        file_util.save(tmp_file, content=content)
        s = SCL(tmp_dir, '*.config')
        with self.assertRaises(ERROR) as ctx:
            s.load()
            self.assertTrue(
                'Duplicate config section' in ctx.exception.message)

    def test_missing_dependency(self):
        content = '''\
ape extends missing_link
  something: yes
'''
        tmp_dir = self.make_temp_dir()
        tmp_file = path.join(tmp_dir, 'apes.config')
        file_util.save(tmp_file, content=content)
        s = SCL(tmp_dir, '*.config')
        s.load()
        with self.assertRaises(ERROR) as ctx:
            s.section('ape')
            self.assertTrue('Missing dependency for ape: missing_link' in
                            ctx.exception.message)

    def test_cyclic_dependency(self):
        content = '''\
ape extends bonobo
  something: yes

bonobo extends ape
  something: yes
'''
        tmp_dir = self.make_temp_dir()
        tmp_file = path.join(tmp_dir, 'apes.config')
        file_util.save(tmp_file, content=content)
        s = SCL(tmp_dir, '*.config')
        s.load()
        with self.assertRaises(ERROR) as ctx:
            s.section('ape')
            self.assertTrue('Cyclic dependencies found: ape bonobo' in
                            ctx.exception.message)

    def test_self_dependency(self):
        content = '''\
ape extends ape
  something: yes
'''
        tmp_dir = self.make_temp_dir()
        tmp_file = path.join(tmp_dir, 'apes.config')
        file_util.save(tmp_file, content=content)
        s = SCL(tmp_dir, '*.config')
        with self.assertRaises(ERROR) as ctx:
            s.load()
            self.assertTrue(
                'Self dependency for "ape"' in ctx.exception.message)

    def test_env_vars(self):
        content = '''\
ape
  activity: ${_CONFIG_ACTIVITY}
  snack: leaves

bonobo extends ape
  activity: loving
  snack: ${_CONFIG_SNACK}

chimp extends ape
  activity: fighting
  snack: eggs
'''
        tmp_dir = self.make_temp_dir()
        tmp_file = path.join(tmp_dir, 'apes.config')
        file_util.save(tmp_file, content=content)
        with env_override(env={
                '_CONFIG_ACTIVITY': 'resting',
                '_CONFIG_SNACK': 'kiwi'
        }) as tmp_env:
            s = SCL(tmp_dir, '*.config')
            s.load()
            self.assertEqual('fighting',
                             s.section('chimp').find_by_key('activity'))
            self.assertEqual('loving',
                             s.section('bonobo').find_by_key('activity'))
            self.assertEqual('eggs', s.section('chimp').find_by_key('snack'))
            self.assertEqual('kiwi', s.section('bonobo').find_by_key('snack'))

    @unit_test_function_skip.skip_if(not host.is_unix(), 'not unix')
    def test_search_path_expanduser(self):
        content = '''\
ape
  activity: resting
  snack: leaves

bonobo extends ape
  activity: loving
  snack: kiwi

chimp extends ape
  activity: fighting
  snack: eggs
'''
        with env_override.temp_home() as tmp_env:
            file_util.save(path.join(os.environ['HOME'], '.config',
                                     'apes.config'),
                           content=content)
            s = SCL('~/.config', '*.config')
            s.load()
            self.assertEqual('fighting',
                             s.section('chimp').find_by_key('activity'))
            self.assertEqual('loving',
                             s.section('bonobo').find_by_key('activity'))
            self.assertEqual('eggs', s.section('chimp').find_by_key('snack'))
            self.assertEqual('kiwi', s.section('bonobo').find_by_key('snack'))

    def test_search_path_env_var(self):
        content = '''\
ape
  activity: resting
  snack: leaves

bonobo extends ape
  activity: loving
  snack: kiwi

chimp extends ape
  activity: fighting
  snack: eggs
'''
        tmp_file = self.make_named_temp_file('apes.config', content=content)
        with env_override(
                env={'_CONFIG_DIR': path.dirname(tmp_file)}) as tmp_env:
            s = SCL('${_CONFIG_DIR}', '*.config')
            s.load()
            self.assertEqual('fighting',
                             s.section('chimp').find_by_key('activity'))
            self.assertEqual('loving',
                             s.section('bonobo').find_by_key('activity'))
            self.assertEqual('eggs', s.section('chimp').find_by_key('snack'))
            self.assertEqual('kiwi', s.section('bonobo').find_by_key('snack'))

    def test_empty_section(self):
        content = '''\
ape
  activity: resting
  snack: leaves

bonobo extends ape

chimp extends ape
  activity: fighting
  snack: eggs
'''
        tmp_file = self.make_named_temp_file('apes.config', content=content)
        with env_override(
                env={'_CONFIG_DIR': path.dirname(tmp_file)}) as tmp_env:
            s = SCL('${_CONFIG_DIR}', '*.config')
            s.load()
            self.assertEqual('fighting',
                             s.section('chimp').find_by_key('activity'))
            self.assertEqual('resting',
                             s.section('bonobo').find_by_key('activity'))
            self.assertEqual('eggs', s.section('chimp').find_by_key('snack'))
            self.assertEqual('leaves',
                             s.section('bonobo').find_by_key('snack'))

    def test_load_and_find_section(self):
        tmp_dir = self._make_temp_configs()
        section = SCL.load_and_find_section(tmp_dir, 'mammal', 'config')
        self.assertEqual(
            {
                'food': 'maybe',
                'blood': 'warm',
                'pet': 'false',
                'respiration': 'aerobic',
            }, section.to_dict())

    def test_load_config_without_section(self):
        tmp_dir = self._make_temp_configs()
        tmp_config = path.join(tmp_dir, 'mammal.config')
        values = SCL.load_config(tmp_config)
        self.assertEqual(
            {
                'food': 'maybe',
                'blood': 'warm',
                'pet': 'false',
                'respiration': 'aerobic',
            }, values)

    def test_load_config_with_section(self):
        tmp_dir = self._make_temp_configs()
        tmp_config = path.join(tmp_dir, 'mammal.config') + ':shepherd'
        values = SCL.load_config(tmp_config)
        self.assertEqual(
            {
                'food': 'false',
                'blood': 'warm',
                'pet': 'false',
                'worker': 'true',
                'respiration': 'aerobic',
                'name': 'rin tin tin',
            }, values)

    def test_load_config_with_none(self):
        self.assertEqual({}, SCL.load_config(None))
#!/usr/bin/env python
#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-

from bes.testing.unit_test import unit_test
from bes.testing.unit_test_class_skip import unit_test_class_skip
from bes.system.host import host

from _file_mime_type_detector_tester import make_test_case

if host.is_unix():
    from bes.fs._detail._file_mime_type_detector_file_exe import _file_mime_type_detector_file_exe

    class test__file_mime_type_detector_file_exe(
            make_test_case(_file_mime_type_detector_file_exe)):
        @classmethod
        def setUpClass(clazz):
            unit_test_class_skip.raise_skip_if_not_unix()


if __name__ == '__main__':
    unit_test.main()