<commit_before># Copyright (c) 2017 The Regents of the University of Michigan
# All rights reserved.
# This software is licensed under the BSD 3-Clause License.
import os
import json
import unittest
import subprocess

import signac
from signac.common import six

if six.PY2:
    from tempdir import TemporaryDirectory
else:
    from tempfile import TemporaryDirectory

class DummyFile(object):
    "We redirect sys stdout into this file during console tests."

    def __init__(self):
        self._x = ''

    def write(self, x):
        self._x += x

    def flush(self): pass

    def read(self):
        x = self._x
        self._x = ''
        return x

class ExitCodeError(RuntimeError):
    pass

class BasicShellTest(unittest.TestCase):

    def setUp(self):
        pythonpath=os.environ.get('PYTHONPATH')
        if pythonpath is None:
            pythonpath = [os.getcwd()]
        else:
            pythonpath = [os.getcwd()] + pythonpath.split(':')
        os.environ['PYTHONPATH'] = ':'.join(pythonpath)
        self.tmpdir = TemporaryDirectory(prefix='signac_')
        self.addCleanup(self.tmpdir.cleanup)
        self.cwd = os.getcwd()
        self.addCleanup(self.return_to_cwd)
        os.chdir(self.tmpdir.name)

    def return_to_cwd(self):
        os.chdir(self.cwd)

    def call(self, command, input=None):
        p = subprocess.Popen(
            command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = p.communicate(input=input)
        if p.returncode != 0:
            raise ExitCodeError("STDOUT='{}' STDERR='{}'".format(out, err))
        if six.PY2:
            return str(out)
        else:
            return out.decode()

    def test_init_project(self):
        self.call('python -m signac init my_project'.split())
        assert str(signac.get_project()) == 'my_project'

    def test_init_project_in_project_root(self):
        self.call('python -m signac init my_project'.split())
        assert str(signac.get_project()) == 'my_project'
        with self.assertRaises(ExitCodeError):
            self.call('python -m signac init second_project'.split())

    def test_project_id(self):
        self.call('python -m signac init my_project'.split())
        self.assertEqual(str(signac.get_project()), 'my_project')
        self.assertEqual(
            self.call('python -m signac project'.split()).strip(),
            'my_project')

    def test_project_workspace(self):
        self.call('python -m signac init my_project'.split())
        self.assertEqual(str(signac.get_project()), 'my_project')
        self.assertEqual(
            os.path.realpath(
                self.call('python -m signac project --workspace'.split()).strip()),
            os.path.realpath(os.path.join(self.tmpdir.name, 'workspace')))

    def test_job_with_argument(self):
        self.call('python -m signac init my_project'.split())
        self.assertEqual(
            self.call(['python', '-m', 'signac', 'job', '{"a": 0}']).strip(),
            '9bfd29df07674bc4aa960cf661b5acd2')

    def test_job_with_argument_workspace(self):
        self.call('python -m signac init my_project'.split())
        wd_path = os.path.join(self.tmpdir.name, 'workspace',
                               '9bfd29df07674bc4aa960cf661b5acd2')
        self.assertEqual(
            os.path.realpath(
                self.call(['python', '-m', 'signac', 'job', '--workspace', '{"a": 0}']).strip()),
            os.path.realpath(wd_path))

    def test_job_with_argument_create_workspace(self):
        self.call('python -m signac init my_project'.split())
        wd_path = os.path.join(self.tmpdir.name, 'workspace',
                               '9bfd29df07674bc4aa960cf661b5acd2')
        self.assertFalse(os.path.isdir(wd_path))
        self.call(['python', '-m', 'signac', 'job', '--create', '{"a": 0}'])
        self.assertTrue(os.path.isdir(wd_path))

    def test_index(self):
        self.call('python -m signac init my_project'.split())
        project = signac.Project()
        project.open_job({'a': 0}).init()
        doc = json.loads(self.call('python -m signac index'.split()))
        self.assertIn('statepoint', doc)
        self.assertEqual(doc['statepoint'], {'a': 0})
        project.open_job({'a': 0}).document['b'] = 0
        doc = json.loads(self.call('python -m signac index'.split()))
        self.assertIn('statepoint', doc)
        self.assertEqual(doc['statepoint'], {'a': 0})
        self.assertIn('b', doc)
        self.assertEqual(doc['b'], 0)

    def test_view(self):
        self.call('python -m signac init my_project'.split())
        project = signac.Project()
        sps = [{'a': i} for i in range(3)]
        for sp in sps:
            project.open_job(sp).init()
        os.mkdir('view')
        self.call('python -m signac view'.split())
        for sp in sps:
            self.assertTrue(os.path.isdir('view/a_{}'.format(sp['a'])))
            self.assertTrue(os.path.isdir('view/a_{}/job'.format(sp['a'])))
            self.assertEqual(
                os.path.realpath('view/a_{}/job'.format(sp['a'])),
                os.path.realpath(project.open_job(sp).workspace()))

    def test_find(self):
        self.call('python -m signac init my_project'.split())
        project = signac.Project()
        sps = [{'a': i} for i in range(3)]
        for sp in sps:
            project.open_job(sp).init()
        out = self.call('python -m signac find'.split())
        job_ids = out.split('\n')[:-1]
        self.assertEqual(set(job_ids), set(project.find_job_ids()))
        self.assertEqual(
            self.call('python -m signac find'.split() + ['{"a": 0}']).strip(),
            list(project.find_job_ids({'a': 0}))[0])

        # Test the doc_filter
        for job in project.find_jobs():
            job.document['a'] = job.statepoint()['a']

        for i in range(3):
            self.assertEqual(
                self.call('python -m signac find --doc-filter'.split() + ['{"a": ' + str(i) + '}']).strip(),
                list(project.find_job_ids(doc_filter={'a': i}))[0])

if __name__ == '__main__':
    unittest.main()
<commit_msg>Add unit test for signac statepoint command.<commit_after># Copyright (c) 2017 The Regents of the University of Michigan
# All rights reserved.
# This software is licensed under the BSD 3-Clause License.
import os
import json
import unittest
import subprocess

import signac
from signac.common import six

if six.PY2:
    from tempdir import TemporaryDirectory
else:
    from tempfile import TemporaryDirectory

class DummyFile(object):
    "We redirect sys stdout into this file during console tests."

    def __init__(self):
        self._x = ''

    def write(self, x):
        self._x += x

    def flush(self): pass

    def read(self):
        x = self._x
        self._x = ''
        return x

class ExitCodeError(RuntimeError):
    pass

class BasicShellTest(unittest.TestCase):

    def setUp(self):
        pythonpath=os.environ.get('PYTHONPATH')
        if pythonpath is None:
            pythonpath = [os.getcwd()]
        else:
            pythonpath = [os.getcwd()] + pythonpath.split(':')
        os.environ['PYTHONPATH'] = ':'.join(pythonpath)
        self.tmpdir = TemporaryDirectory(prefix='signac_')
        self.addCleanup(self.tmpdir.cleanup)
        self.cwd = os.getcwd()
        self.addCleanup(self.return_to_cwd)
        os.chdir(self.tmpdir.name)

    def return_to_cwd(self):
        os.chdir(self.cwd)

    def call(self, command, input=None):
        p = subprocess.Popen(
            command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = p.communicate(input=input)
        if p.returncode != 0:
            raise ExitCodeError("STDOUT='{}' STDERR='{}'".format(out, err))
        if six.PY2:
            return str(out)
        else:
            return out.decode()

    def test_init_project(self):
        self.call('python -m signac init my_project'.split())
        assert str(signac.get_project()) == 'my_project'

    def test_init_project_in_project_root(self):
        self.call('python -m signac init my_project'.split())
        assert str(signac.get_project()) == 'my_project'
        with self.assertRaises(ExitCodeError):
            self.call('python -m signac init second_project'.split())

    def test_project_id(self):
        self.call('python -m signac init my_project'.split())
        self.assertEqual(str(signac.get_project()), 'my_project')
        self.assertEqual(
            self.call('python -m signac project'.split()).strip(),
            'my_project')

    def test_project_workspace(self):
        self.call('python -m signac init my_project'.split())
        self.assertEqual(str(signac.get_project()), 'my_project')
        self.assertEqual(
            os.path.realpath(
                self.call('python -m signac project --workspace'.split()).strip()),
            os.path.realpath(os.path.join(self.tmpdir.name, 'workspace')))

    def test_job_with_argument(self):
        self.call('python -m signac init my_project'.split())
        self.assertEqual(
            self.call(['python', '-m', 'signac', 'job', '{"a": 0}']).strip(),
            '9bfd29df07674bc4aa960cf661b5acd2')

    def test_job_with_argument_workspace(self):
        self.call('python -m signac init my_project'.split())
        wd_path = os.path.join(self.tmpdir.name, 'workspace',
                               '9bfd29df07674bc4aa960cf661b5acd2')
        self.assertEqual(
            os.path.realpath(
                self.call(['python', '-m', 'signac', 'job', '--workspace', '{"a": 0}']).strip()),
            os.path.realpath(wd_path))

    def test_job_with_argument_create_workspace(self):
        self.call('python -m signac init my_project'.split())
        wd_path = os.path.join(self.tmpdir.name, 'workspace',
                               '9bfd29df07674bc4aa960cf661b5acd2')
        self.assertFalse(os.path.isdir(wd_path))
        self.call(['python', '-m', 'signac', 'job', '--create', '{"a": 0}'])
        self.assertTrue(os.path.isdir(wd_path))

    def test_statepoint(self):
        self.call('python -m signac init my_project'.split())
        self.call(['python', '-m', 'signac', 'job', '--create', '{"a": 0}'])
        project = signac.Project()
        for job in project:
            sp = self.call('python -m signac statepoint {}'.format(job).split())
            self.assertEqual(project.open_job(json.loads(sp)), job)

    def test_index(self):
        self.call('python -m signac init my_project'.split())
        project = signac.Project()
        project.open_job({'a': 0}).init()
        doc = json.loads(self.call('python -m signac index'.split()))
        self.assertIn('statepoint', doc)
        self.assertEqual(doc['statepoint'], {'a': 0})
        project.open_job({'a': 0}).document['b'] = 0
        doc = json.loads(self.call('python -m signac index'.split()))
        self.assertIn('statepoint', doc)
        self.assertEqual(doc['statepoint'], {'a': 0})
        self.assertIn('b', doc)
        self.assertEqual(doc['b'], 0)

    def test_view(self):
        self.call('python -m signac init my_project'.split())
        project = signac.Project()
        sps = [{'a': i} for i in range(3)]
        for sp in sps:
            project.open_job(sp).init()
        os.mkdir('view')
        self.call('python -m signac view'.split())
        for sp in sps:
            self.assertTrue(os.path.isdir('view/a_{}'.format(sp['a'])))
            self.assertTrue(os.path.isdir('view/a_{}/job'.format(sp['a'])))
            self.assertEqual(
                os.path.realpath('view/a_{}/job'.format(sp['a'])),
                os.path.realpath(project.open_job(sp).workspace()))

    def test_find(self):
        self.call('python -m signac init my_project'.split())
        project = signac.Project()
        sps = [{'a': i} for i in range(3)]
        for sp in sps:
            project.open_job(sp).init()
        out = self.call('python -m signac find'.split())
        job_ids = out.split('\n')[:-1]
        self.assertEqual(set(job_ids), set(project.find_job_ids()))
        self.assertEqual(
            self.call('python -m signac find'.split() + ['{"a": 0}']).strip(),
            list(project.find_job_ids({'a': 0}))[0])

        # Test the doc_filter
        for job in project.find_jobs():
            job.document['a'] = job.statepoint()['a']

        for i in range(3):
            self.assertEqual(
                self.call('python -m signac find --doc-filter'.split() + ['{"a": ' + str(i) + '}']).strip(),
                list(project.find_job_ids(doc_filter={'a': i}))[0])

if __name__ == '__main__':
    unittest.main()
<|endoftext|>


<commit_before>import pytest
import rfpipe.state

class TestClass_create:

    def test_create0(self):
        state = rfpipe.state.State()
        assert 'version' in state.defined

<commit_msg>import of rfpipe.state not ok?<commit_after>import pytest
import rfpipe

class TestClass_create:

    def test_state0(self):
        st = rfpipe.state.State()
        assert 'version' in st.defined

<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
import click
import click.testing
import distutils.spawn
import pytest
import zazu.cli
import zazu.plugins.clang_format_styler
import zazu.plugins.astyle_styler
import zazu.plugins.autopep8_styler
import zazu.plugins.docformatter_styler
import zazu.style
import zazu.util

def write_c_file_with_bad_style(file):
    with open(file, 'w') as f:
        f.write('void main(){\n\n}\n \n')

def write_py_file_with_bad_style(file):
    with open(file, 'w') as f:
        f.write('def main():\tpass\n\n\n \n')

@pytest.fixture()
def repo_with_style_errors(repo_with_style):
    dir = repo_with_style.working_tree_dir
    with zazu.util.cd(dir):
        write_c_file_with_bad_style('temp.c')
        write_c_file_with_bad_style('temp.cc')
        write_c_file_with_bad_style('temp.cpp')
        write_c_file_with_bad_style('temp.hpp')
        write_c_file_with_bad_style('temp.h')
        write_py_file_with_bad_style('temp.py')
    return repo_with_style

@pytest.mark.skipif(not distutils.spawn.find_executable('astyle'),
                    reason="requires astyle")
def test_astyle():
    styler = zazu.plugins.astyle_styler.AstyleStyler(options=['-U'])
    ret = styler.style_string('void main ( ) {}')
    assert ret == 'void main() {}'
    assert styler.default_extensions()

def test_autopep8():
    styler = zazu.plugins.autopep8_styler.Autopep8Styler()
    ret = styler.style_string('def foo ():\n  pass')
    assert ret == 'def foo():\n    pass\n'
    assert ['*.py'] == styler.default_extensions()

def test_docformatter():
    styler = zazu.plugins.docformatter_styler.DocformatterStyler()
    ret = styler.style_string('def foo ():\n"""doc"""\n  pass')
    assert ret == 'def foo ():\n"""doc"""\n  pass'
    assert ['*.py'] == styler.default_extensions()

def test_docformatter():
    styler = zazu.plugins.docformatter_styler.DocformatterStyler()
    ret = styler.style_string('def foo ():\n"""doc"""\n  pass')
    assert ret == 'def foo ():\n"""doc"""\n  pass'
    assert ['*.py'] == styler.default_extensions()

def test_goimports(mocker):
    mocker.patch('zazu.util.check_popen', return_value='bar')
    styler = zazu.plugins.goimports_styler.GoimportsStyler(options=['-U'])
    ret = styler.style_string('foo')
    zazu.util.check_popen.assert_called_once_with(args=['goimports', '-U'], stdin_str='foo')
    assert ret == 'bar'
    assert styler.default_extensions() == ['*.go']

def test_esformatter(mocker):
    mocker.patch('zazu.util.check_popen', return_value='bar')
    styler = zazu.plugins.esformatter_styler.EsformatterStyler(options=['-U'])
    ret = styler.style_string('foo')
    zazu.util.check_popen.assert_called_once_with(args=['esformatter', '-U'], stdin_str='foo')
    assert ret == 'bar'
    assert styler.default_extensions() == ['*.js', '*.es', '*.es6']

@pytest.mark.skipif(not distutils.spawn.find_executable('clang-format'),
                    reason="requires clang-format")
def test_clang_format():
    styler = zazu.plugins.clang_format_styler.ClangFormatStyler(options=['-style=google'])
    ret = styler.style_string('void  main ( ) { }')
    assert ret == 'void main() {}'
    assert styler.default_extensions()

@pytest.mark.skipif(not distutils.spawn.find_executable('clang-format'),
                    reason="requires clang-format")
def test_bad_style(repo_with_style_errors):
    dir = repo_with_style_errors.working_tree_dir
    with zazu.util.cd(dir):
        runner = click.testing.CliRunner()
        result = runner.invoke(zazu.cli.cli, ['style', '--check', '-v'])
        assert result.exit_code
        assert result.output.endswith('6 files with violations in 6 files\n')
        result = runner.invoke(zazu.cli.cli, ['style', '-v'])
        assert result.exit_code == 0
        assert result.output.endswith('6 files fixed in 6 files\n')
        result = runner.invoke(zazu.cli.cli, ['style', '--check'])
        assert result.exit_code == 0

@pytest.mark.skipif(not distutils.spawn.find_executable('clang-format'),
                    reason="requires clang-format")
def test_dirty_style(repo_with_style_errors):
    dir = repo_with_style_errors.working_tree_dir
    with zazu.util.cd(dir):
        runner = click.testing.CliRunner()
        result = runner.invoke(zazu.cli.cli, ['style', '--check', '--cached', '-v'])
        assert result.exit_code == 0
        assert result.output == '0 files with violations in 0 files\n'
        repo_with_style_errors.git.add('temp.c')
        result = runner.invoke(zazu.cli.cli, ['style', '--check', '--cached', '-v'])
        assert result.exit_code
        assert result.output.endswith('1 files with violations in 1 files\n')
        result = runner.invoke(zazu.cli.cli, ['style', '--cached', '-v'])
        assert result.output.endswith('1 files fixed in 1 files\n')
        result = runner.invoke(zazu.cli.cli, ['style', '--check', '--cached', '-v'])
        assert not result.exit_code
        assert result.output.endswith('0 files with violations in 1 files\n')
        repo_with_style_errors.git.add('temp.cpp')
        with open('temp.cpp', 'a') as f:
            f.write('//comment\n')
        result = runner.invoke(zazu.cli.cli, ['style', '--cached', '-v'])
        assert result.output.endswith('1 files fixed in 2 files\n')
        # File with missing newline at end of file.
        with open('temp.h', 'a') as f:
            f.write('//comment')
        repo_with_style_errors.git.add('temp.h')
        with open('temp.h', 'a') as f:
            f.write('//another')
        result = runner.invoke(zazu.cli.cli, ['style', '--cached'])
        assert result.output.endswith('File "temp.h" must have a trailing newline\n')

def test_style_no_config(repo_with_missing_style):
    dir = repo_with_missing_style.working_tree_dir
    with zazu.util.cd(dir):
        runner = click.testing.CliRunner()
        result = runner.invoke(zazu.cli.cli, ['style'])
        assert result.output == 'no style settings found\n'
        assert result.exit_code == 0

def test_styler():
    uut = zazu.styler.Styler()
    with pytest.raises(NotImplementedError):
        uut.style_string('')
<commit_msg>Update astyle test<commit_after># -*- coding: utf-8 -*-
import click
import click.testing
import distutils.spawn
import pytest
import zazu.cli
import zazu.plugins.clang_format_styler
import zazu.plugins.astyle_styler
import zazu.plugins.autopep8_styler
import zazu.plugins.docformatter_styler
import zazu.style
import zazu.util

def write_c_file_with_bad_style(file):
    with open(file, 'w') as f:
        f.write('void main(){\n\n}\n \n')

def write_py_file_with_bad_style(file):
    with open(file, 'w') as f:
        f.write('def main():\tpass\n\n\n \n')

@pytest.fixture()
def repo_with_style_errors(repo_with_style):
    dir = repo_with_style.working_tree_dir
    with zazu.util.cd(dir):
        write_c_file_with_bad_style('temp.c')
        write_c_file_with_bad_style('temp.cc')
        write_c_file_with_bad_style('temp.cpp')
        write_c_file_with_bad_style('temp.hpp')
        write_c_file_with_bad_style('temp.h')
        write_py_file_with_bad_style('temp.py')
    return repo_with_style

def test_astyle(mocker):
    mocker.patch('zazu.util.check_popen', return_value='bar')
    styler = zazu.plugins.astyle_styler.AstyleStyler(options=['-U'])
    ret = styler.style_string('foo')
    zazu.util.check_popen.assert_called_once_with(args=['astyle', '-U'], stdin_str='foo')
    assert ret == 'bar'
    assert styler.default_extensions() == ['*.c',
                                           '*.cc',
                                           '*.cs',
                                           '*.cpp',
                                           '*.h',
                                           '*.hpp',
                                           '*.java']

def test_autopep8():
    styler = zazu.plugins.autopep8_styler.Autopep8Styler()
    ret = styler.style_string('def foo ():\n  pass')
    assert ret == 'def foo():\n    pass\n'
    assert ['*.py'] == styler.default_extensions()

def test_docformatter():
    styler = zazu.plugins.docformatter_styler.DocformatterStyler()
    ret = styler.style_string('def foo ():\n"""doc"""\n  pass')
    assert ret == 'def foo ():\n"""doc"""\n  pass'
    assert ['*.py'] == styler.default_extensions()

def test_docformatter():
    styler = zazu.plugins.docformatter_styler.DocformatterStyler()
    ret = styler.style_string('def foo ():\n"""doc"""\n  pass')
    assert ret == 'def foo ():\n"""doc"""\n  pass'
    assert ['*.py'] == styler.default_extensions()

def test_goimports(mocker):
    mocker.patch('zazu.util.check_popen', return_value='bar')
    styler = zazu.plugins.goimports_styler.GoimportsStyler(options=['-U'])
    ret = styler.style_string('foo')
    zazu.util.check_popen.assert_called_once_with(args=['goimports', '-U'], stdin_str='foo')
    assert ret == 'bar'
    assert styler.default_extensions() == ['*.go']

def test_esformatter(mocker):
    mocker.patch('zazu.util.check_popen', return_value='bar')
    styler = zazu.plugins.esformatter_styler.EsformatterStyler(options=['-U'])
    ret = styler.style_string('foo')
    zazu.util.check_popen.assert_called_once_with(args=['esformatter', '-U'], stdin_str='foo')
    assert ret == 'bar'
    assert styler.default_extensions() == ['*.js', '*.es', '*.es6']

@pytest.mark.skipif(not distutils.spawn.find_executable('clang-format'),
                    reason="requires clang-format")
def test_clang_format():
    styler = zazu.plugins.clang_format_styler.ClangFormatStyler(options=['-style=google'])
    ret = styler.style_string('void  main ( ) { }')
    assert ret == 'void main() {}'
    assert styler.default_extensions()

@pytest.mark.skipif(not distutils.spawn.find_executable('clang-format'),
                    reason="requires clang-format")
def test_bad_style(repo_with_style_errors):
    dir = repo_with_style_errors.working_tree_dir
    with zazu.util.cd(dir):
        runner = click.testing.CliRunner()
        result = runner.invoke(zazu.cli.cli, ['style', '--check', '-v'])
        assert result.exit_code
        assert result.output.endswith('6 files with violations in 6 files\n')
        result = runner.invoke(zazu.cli.cli, ['style', '-v'])
        assert result.exit_code == 0
        assert result.output.endswith('6 files fixed in 6 files\n')
        result = runner.invoke(zazu.cli.cli, ['style', '--check'])
        assert result.exit_code == 0

@pytest.mark.skipif(not distutils.spawn.find_executable('clang-format'),
                    reason="requires clang-format")
def test_dirty_style(repo_with_style_errors):
    dir = repo_with_style_errors.working_tree_dir
    with zazu.util.cd(dir):
        runner = click.testing.CliRunner()
        result = runner.invoke(zazu.cli.cli, ['style', '--check', '--cached', '-v'])
        assert result.exit_code == 0
        assert result.output == '0 files with violations in 0 files\n'
        repo_with_style_errors.git.add('temp.c')
        result = runner.invoke(zazu.cli.cli, ['style', '--check', '--cached', '-v'])
        assert result.exit_code
        assert result.output.endswith('1 files with violations in 1 files\n')
        result = runner.invoke(zazu.cli.cli, ['style', '--cached', '-v'])
        assert result.output.endswith('1 files fixed in 1 files\n')
        result = runner.invoke(zazu.cli.cli, ['style', '--check', '--cached', '-v'])
        assert not result.exit_code
        assert result.output.endswith('0 files with violations in 1 files\n')
        repo_with_style_errors.git.add('temp.cpp')
        with open('temp.cpp', 'a') as f:
            f.write('//comment\n')
        result = runner.invoke(zazu.cli.cli, ['style', '--cached', '-v'])
        assert result.output.endswith('1 files fixed in 2 files\n')
        # File with missing newline at end of file.
        with open('temp.h', 'a') as f:
            f.write('//comment')
        repo_with_style_errors.git.add('temp.h')
        with open('temp.h', 'a') as f:
            f.write('//another')
        result = runner.invoke(zazu.cli.cli, ['style', '--cached'])
        assert result.output.endswith('File "temp.h" must have a trailing newline\n')

def test_style_no_config(repo_with_missing_style):
    dir = repo_with_missing_style.working_tree_dir
    with zazu.util.cd(dir):
        runner = click.testing.CliRunner()
        result = runner.invoke(zazu.cli.cli, ['style'])
        assert result.output == 'no style settings found\n'
        assert result.exit_code == 0

def test_styler():
    uut = zazu.styler.Styler()
    with pytest.raises(NotImplementedError):
        uut.style_string('')
<|endoftext|>


<commit_before>"""
OpenCL nodes supported by ctree.
"""

from ctree.nodes import *

class OclNode(CtreeNode):
    """Base class for all OpenCL nodes supported by ctree."""

    def codegen(self, indent=0):
        """generate ocl code for this node"""
        from ctree.ocl.codegen import OclCodeGen

        return OclCodeGen(indent).visit(self)

    def label(self, indent=0):
        """generate dot element for this node"""
        from ctree.ocl.dotgen import OclDotLabeller

        return OclDotLabeller().visit(self)

class OclFile(OclNode, File):
    """Represents a .cl file."""
    _ext = "cl"

    def __init__(self, name="generated", body=None):
        if not body:
            body = []
        #TODO: Inspect complains about 2 args to __init__
        super(OclFile, self).__init__(name, body)

    def _compile(self, program_text, compilation_dir):
        """
        write the ocl program to a text file and compile it
        """
        import os
        cl_src_file = os.path.join(compilation_dir, self.get_filename())
        log.info("file for generated OpenCL: %s" % cl_src_file)
        log.info("generated OpenCL code: (((\n%s\n)))" % program_text)

        # write program text to C file
        with open(cl_src_file, 'w') as cl_file:
            cl_file.write(program_text)

        import llvm.core

        return llvm.core.Module.new("empty cl module")
<commit_msg>made similar filecaching changes to oclFile<commit_after>"""
OpenCL nodes supported by ctree.
"""

from ctree.nodes import *

class OclNode(CtreeNode):
    """Base class for all OpenCL nodes supported by ctree."""

    def codegen(self, indent=0):
        """generate ocl code for this node"""
        from ctree.ocl.codegen import OclCodeGen

        return OclCodeGen(indent).visit(self)

    def label(self, indent=0):
        """generate dot element for this node"""
        from ctree.ocl.dotgen import OclDotLabeller

        return OclDotLabeller().visit(self)

class OclFile(OclNode, File):
    """Represents a .cl file."""
    _ext = "cl"

    def __init__(self, name="generated", body=None):
        if not body:
            body = []
        #TODO: Inspect complains about 2 args to __init__
        super(OclFile, self).__init__(name, body)

    def _compile(self, program_text, compilation_dir):
        """
        write the ocl program to a text file and compile it
        """
        import os
        cl_src_file = os.path.join(compilation_dir, self.get_filename())
        if not os.path.exists(cl_src_file):
            log.info("file for generated OpenCL: %s" % cl_src_file)
            log.info("generated OpenCL code: (((\n%s\n)))" % program_text)

            # write program text to C file
            with open(cl_src_file, 'w') as cl_file:
                cl_file.write(program_text)
        else:
            log.info("OpenCL file already generated")
        import llvm.core

        return llvm.core.Module.new("empty cl module")
<|endoftext|>


<commit_before># Copyright (c) 2016 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

from __future__ import absolute_import

import mock
import tornado.gen
import pytest

from tchannel import TChannel, thrift
from tchannel.tcurl import _catch_errors
from tchannel.tcurl import main
from tchannel.tcurl import parse_args
import six

service = thrift.load('tests/data/idls/ThriftTest.thrift')

@pytest.mark.parametrize('input, expectations', [
    (
        [
            '-p', 'localhost:54496',
            '-s', 'larry',
            '--headers', '{"req": "header"}',
            '--body', '{"req": "body"}',
            '--endpoint', 'foo',
        ],
        dict(
            host='localhost:54496',
            headers={'req': 'header'},
            body={"req": "body"},
        )
    ),
    (
        [
            '--service', 'larry',
            '--thrift', 'tests/data/idls/ThriftTest.thrift',
            '--endpoint', 'foo::bar',
        ],
        dict(
            service="larry",
            thrift=mock.ANY,
            endpoint='foo::bar',
        ),
    ),
    (
        [
            '-p', 'localhost:54496',
            '-s', 'larry',
            '--headers', '{"req": "header"}',
            '--body', '{"req": "body"',
            '--raw',
        ],
        dict(
            service="larry",
            headers='{"req": "header"}',
            body='{"req": "body"',
        ),
    ),
])
def test_parse_valid_args(input, expectations):
    args = parse_args(input)

    for key, expected in six.iteritems(expectations):
        assert expected == getattr(args, key)

@pytest.mark.parametrize('input, message', [
    (
        [''],
        'argument --service/-s is required'
    ),
    (
        ['--service', 'larry', '--thrift'],
        '--thrift/-t: expected one argument',
    ),
    (
        ['--service', 'larry', '--thrift', 'foo.thrift'],
        'No such file or directory',
    ),
    (
        [
            '--service', 'larry',
            '--thrift', 'tests/data/idls/ThriftTest.thrift',
        ],
        "--thrift must be used with --endpoint",
    ),
    (
        [
            '--service', 'larry',
            '--thrift', 'tests/data/idls/ThriftTest.thrift',
            '--endpoint',
        ],
        '--endpoint/-1: expected one argument',
    ),
    (
        [
            '--service', 'larry',
            '--thrift', 'tests/data/idls/ThriftTest.thrift',
            '--endpoint', 'foo',
        ],
        '--endpoint should be of the form'
    ),
    (
        [
            '-p', 'localhost:54496',
            '-s', 'larry',
            '--headers', '{"req": "header"}',
            '--body', '{"req": "body"',
        ],
        "--body isn't valid JSON",
    ),
    (
        [
            '-p', 'localhost:54496',
            '-s', 'larry',
            '--headers', '{"req": "header"',
            '--body', '{"req": "body"}',
        ],
        "--headers isn't valid JSON",
    ),
    (
        [
            '--service', 'larry',
            '--thrift', 'tests/data/idls/ThriftTest.thrift',
            '--endpoint', 'foo::bar',
            '--raw',
        ],
        "can't use --thrift and --raw together",
    ),
])
def test_parse_invalid_args(input, message, capsys):
    with pytest.raises(SystemExit) as e:
        parse_args(input)

    # Arg parse always dies with an error code of 2.
    if six.PY2:
        assert e.value.message == 2
    if six.PY3:
        print(dir(e))
        assert int(str(e)) == 2

    out, err = capsys.readouterr()
    assert message in err

@pytest.mark.gen_test
def test_tcurl_health():
    server = TChannel(name='server')
    server.listen()

    response = yield main([
        '-s', 'server',
        '--host', server.hostport,
        '--health',
    ])

    assert response.body.ok

@pytest.mark.gen_test
def test_tcurl_thrift():
    server = TChannel(name='server')

    @server.thrift.register(service.ThriftTest)
    def testString(request):
        return request.body.thing

    server.listen()

    response = yield main([
        '-s', 'server',
        '--host', server.hostport,
        '--thrift', 'tests/data/idls/ThriftTest.thrift',
        '--body', '{"thing": "foo"}',
        '--endpoint', 'ThriftTest::testString',
    ])

    assert response.body == 'foo'

@pytest.mark.gen_test
def test_tcurl_json():
    server = TChannel(name='server')

    @server.json.register
    def test(request):
        return request.body

    server.listen()

    response = yield main([
        '-s', 'server',
        '--host', server.hostport,
        '--body', '{"thing": "foo"}',
        '--endpoint', 'test',
    ])

    assert response.body == {"thing": "foo"}

@pytest.mark.gen_test
def test_catch_errors(capsys):

    class Exit(Exception):
        pass

    def exit(ret):
        raise Exit(ret)

    f = tornado.gen.Future()
    f.set_exception(Exception("Foobar"))

    with pytest.raises(Exit):
        yield _catch_errors(f, verbose=False, exit=exit)

    out, err = capsys.readouterr()

    assert err == "Foobar\n"

@pytest.mark.gen_test
def test_catch_errors_verbose(capsys):

    class Exit(Exception):
        pass

    def exit(ret):
        raise Exit(ret)

    f = tornado.gen.Future()
    f.set_exception(Exception("Foobar"))

    with pytest.raises(Exit):
        yield _catch_errors(f, verbose=True, exit=exit)

    out, err = capsys.readouterr()

    assert 'Traceback' in err
<commit_msg>Moving print statement elsewhere to help debug<commit_after># Copyright (c) 2016 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

from __future__ import absolute_import

import mock
import tornado.gen
import pytest

from tchannel import TChannel, thrift
from tchannel.tcurl import _catch_errors
from tchannel.tcurl import main
from tchannel.tcurl import parse_args
import six

service = thrift.load('tests/data/idls/ThriftTest.thrift')

@pytest.mark.parametrize('input, expectations', [
    (
        [
            '-p', 'localhost:54496',
            '-s', 'larry',
            '--headers', '{"req": "header"}',
            '--body', '{"req": "body"}',
            '--endpoint', 'foo',
        ],
        dict(
            host='localhost:54496',
            headers={'req': 'header'},
            body={"req": "body"},
        )
    ),
    (
        [
            '--service', 'larry',
            '--thrift', 'tests/data/idls/ThriftTest.thrift',
            '--endpoint', 'foo::bar',
        ],
        dict(
            service="larry",
            thrift=mock.ANY,
            endpoint='foo::bar',
        ),
    ),
    (
        [
            '-p', 'localhost:54496',
            '-s', 'larry',
            '--headers', '{"req": "header"}',
            '--body', '{"req": "body"',
            '--raw',
        ],
        dict(
            service="larry",
            headers='{"req": "header"}',
            body='{"req": "body"',
        ),
    ),
])
def test_parse_valid_args(input, expectations):
    args = parse_args(input)

    for key, expected in six.iteritems(expectations):
        assert expected == getattr(args, key)

@pytest.mark.parametrize('input, message', [
    (
        [''],
        'argument --service/-s is required'
    ),
    (
        ['--service', 'larry', '--thrift'],
        '--thrift/-t: expected one argument',
    ),
    (
        ['--service', 'larry', '--thrift', 'foo.thrift'],
        'No such file or directory',
    ),
    (
        [
            '--service', 'larry',
            '--thrift', 'tests/data/idls/ThriftTest.thrift',
        ],
        "--thrift must be used with --endpoint",
    ),
    (
        [
            '--service', 'larry',
            '--thrift', 'tests/data/idls/ThriftTest.thrift',
            '--endpoint',
        ],
        '--endpoint/-1: expected one argument',
    ),
    (
        [
            '--service', 'larry',
            '--thrift', 'tests/data/idls/ThriftTest.thrift',
            '--endpoint', 'foo',
        ],
        '--endpoint should be of the form'
    ),
    (
        [
            '-p', 'localhost:54496',
            '-s', 'larry',
            '--headers', '{"req": "header"}',
            '--body', '{"req": "body"',
        ],
        "--body isn't valid JSON",
    ),
    (
        [
            '-p', 'localhost:54496',
            '-s', 'larry',
            '--headers', '{"req": "header"',
            '--body', '{"req": "body"}',
        ],
        "--headers isn't valid JSON",
    ),
    (
        [
            '--service', 'larry',
            '--thrift', 'tests/data/idls/ThriftTest.thrift',
            '--endpoint', 'foo::bar',
            '--raw',
        ],
        "can't use --thrift and --raw together",
    ),
])
def test_parse_invalid_args(input, message, capsys):
    with pytest.raises(SystemExit) as e:
        parse_args(input)

    # Arg parse always dies with an error code of 2.
    if six.PY2:
        assert e.value.message == 2
    if six.PY3:
        print('FIND_ME', dir(e.value))
        assert int(str(e)) == 2

    out, err = capsys.readouterr()
    assert message in err

@pytest.mark.gen_test
def test_tcurl_health():
    server = TChannel(name='server')
    server.listen()

    response = yield main([
        '-s', 'server',
        '--host', server.hostport,
        '--health',
    ])

    assert response.body.ok

@pytest.mark.gen_test
def test_tcurl_thrift():
    server = TChannel(name='server')

    @server.thrift.register(service.ThriftTest)
    def testString(request):
        return request.body.thing

    server.listen()

    response = yield main([
        '-s', 'server',
        '--host', server.hostport,
        '--thrift', 'tests/data/idls/ThriftTest.thrift',
        '--body', '{"thing": "foo"}',
        '--endpoint', 'ThriftTest::testString',
    ])

    assert response.body == 'foo'

@pytest.mark.gen_test
def test_tcurl_json():
    server = TChannel(name='server')

    @server.json.register
    def test(request):
        return request.body

    server.listen()

    response = yield main([
        '-s', 'server',
        '--host', server.hostport,
        '--body', '{"thing": "foo"}',
        '--endpoint', 'test',
    ])

    assert response.body == {"thing": "foo"}

@pytest.mark.gen_test
def test_catch_errors(capsys):

    class Exit(Exception):
        pass

    def exit(ret):
        raise Exit(ret)

    f = tornado.gen.Future()
    f.set_exception(Exception("Foobar"))

    with pytest.raises(Exit):
        yield _catch_errors(f, verbose=False, exit=exit)

    out, err = capsys.readouterr()

    assert err == "Foobar\n"

@pytest.mark.gen_test
def test_catch_errors_verbose(capsys):

    class Exit(Exception):
        pass

    def exit(ret):
        raise Exit(ret)

    f = tornado.gen.Future()
    f.set_exception(Exception("Foobar"))

    with pytest.raises(Exit):
        yield _catch_errors(f, verbose=True, exit=exit)

    out, err = capsys.readouterr()

    assert 'Traceback' in err
<|endoftext|>


<commit_before>import dedupe
import unittest

class ParsingTest(unittest.TestCase) :
    def setUp(self) :
        self.index = dedupe.tfidf.TfIdfIndex('foo')

    def test_keywords(self) :
        print self.index._parseTerms(u'`AND OR NOT ( ) ATOM \\EOF')
        assert self.index._parseTerms(u'`AND OR NOT ( ) ATOM \\EOF') ==\
            ['\AND', '\OR', '\NOT', '\ATOM', '\EOF']

        self.index.index(1, 'AND OR EOF NOT')
        assert self.index.search('AND OR EOF NOT')[0] == 1

    def test_keywords_title(self) :
        assert self.index._parseTerms(u'`And Or Not ( ) Atom \\Eof') ==\
            ['\AND', '\OR', '\NOT', '\ATOM', '\EOF']

        self.index.index(1, 'And Or Eof Not')
        assert self.index.search('And Or Eof Not')[0] == 1

    def test_empty_search(self) :
        assert self.index.search('') == []

    def test_wildcards(self) :
        self.index.index(1, 'f\o')
        self.index.index(2, 'f*')
        assert len(self.index.search('f*')) == 1

if __name__ == "__main__":
    unittest.main()
<commit_msg>added test for globbing<commit_after>import dedupe
import unittest

class ParsingTest(unittest.TestCase) :
    def setUp(self) :
        self.index = dedupe.tfidf.TfIdfIndex('foo')

    def test_keywords(self) :
        assert self.index._parseTerms(u'`AND OR NOT ( ) ATOM \\EOF') ==\
            ['\AND', '\OR', '\NOT', '\ATOM', '\EOF']

        self.index.index(1, 'AND OR EOF NOT')
        assert self.index.search('AND OR EOF NOT')[0] == 1

    def test_keywords_title(self) :
        assert self.index._parseTerms(u'`And Or Not ( ) Atom \\Eof') ==\
            ['\AND', '\OR', '\NOT', '\ATOM', '\EOF']

        self.index.index(1, 'And Or Eof Not')
        assert self.index.search('And Or Eof Not')[0] == 1

    def test_empty_search(self) :
        assert self.index.search('') == []

    def test_wildcards(self) :
        self.index.index(1, 'f\o')
        self.index.index(2, 'f*')
        assert len(self.index.search('f*')) == 1
        assert self.index._parseTerms('f*o') == ['f*o']

if __name__ == "__main__":
    unittest.main()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

"""Test the functions in the tools file."""

import bibpy.parser
import bibpy.tools
import pytest

def test_version_format():
    assert bibpy.tools.version_format().format('0.1.0') == '%(prog)s v0.1.0'

    program_name = dict(prog='tool_name')
    assert (bibpy.tools.version_format() % program_name).format('2.3') ==\
        'tool_name v2.3'

# TODO: Expand grammar tests with failures
def test_key_grammar():
    assert bibpy.parser.parse_query('SomeKey', 'bibkey') ==\
        ('key', (None, 'SomeKey'))
    assert bibpy.parser.parse_query('^SomeKey', 'bibkey') ==\
        ('key', ('^', 'SomeKey'))
    assert bibpy.parser.parse_query('~SomeKey', 'bibkey') ==\
        ('key', ('~', 'SomeKey'))

def test_entry_grammar():
    assert bibpy.parser.parse_query('article', 'bibtype') ==\
        ('bibtype', (None, 'article'))
    assert bibpy.parser.parse_query('^book', 'bibtype') ==\
        ('bibtype', ('^', 'book'))
    assert bibpy.parser.parse_query('~conference', 'bibtype') ==\
        ('bibtype', ('~', 'conference'))

# NOTE: We also test the numeric grammar here as it is part of the field query
# grammar
def test_field_grammar():
    assert bibpy.parser.parse_query('year<2000', 'field') ==\
        ('comparison', (None, 'year', '<', '2000'))
    assert bibpy.parser.parse_query('^year>2000', 'field') ==\
        ('comparison', ('^', 'year', '>', '2000'))
    assert bibpy.parser.parse_query('issue<=10', 'field') ==\
        ('comparison', (None, 'issue', '<=', '10'))
    assert bibpy.parser.parse_query('volume>100', 'field') ==\
        ('comparison', (None, 'volume', '>', '100'))
    assert bibpy.parser.parse_query('month>=9', 'field') ==\
        ('comparison', (None, 'month', '>=', '9'))
    assert bibpy.parser.parse_query('year=1990-2000', 'field') ==\
        ('interval', (None, 'year', '1990', '2000'))
    assert bibpy.parser.parse_query('1900 < year <= 2000', 'field') ==\
        ('range', (None, '1900', '<', 'year', '<=', '2000'))

    # Test invalid queries
    invalid_queries = [
        # '!author .',         # Extra characters at the end
        'volume/1900-2000',  # '=' replaces by forward slash
        'author<>10',        # Invalid comparison operator
        'institution~'       # No value following '~'
    ]

    for query in invalid_queries:
        with pytest.raises(bibpy.error.ParseException):
            bibpy.parser.parse_query(query, 'field')

def test_predicate_composition():
    at = bibpy.tools.always_true
    af = bibpy.tools.always_false

    pred1 = bibpy.tools.compose_predicates([af, at, af], any)
    pred2 = bibpy.tools.compose_predicates([af, af, af], any)
    pred3 = bibpy.tools.compose_predicates([af, at], all)
    pred4 = bibpy.tools.compose_predicates([at, at], all)

    assert pred1(1)
    assert not pred2(1)
    assert not pred3(1)
    assert pred4(1)
<commit_msg>Remove tests that do not make sense<commit_after># -*- coding: utf-8 -*-

"""Test the functions in the tools file."""

import bibpy.parser
import bibpy.tools
import pytest

def test_version_format():
    assert bibpy.tools.version_format().format('0.1.0') == '%(prog)s v0.1.0'

    program_name = dict(prog='tool_name')
    assert (bibpy.tools.version_format() % program_name).format('2.3') ==\
        'tool_name v2.3'

# TODO: Expand grammar tests with failures
def test_key_grammar():
    assert bibpy.parser.parse_query('SomeKey', 'bibkey') ==\
        ('key', (None, 'SomeKey'))
    assert bibpy.parser.parse_query('^SomeKey', 'bibkey') ==\
        ('key', ('^', 'SomeKey'))

def test_entry_grammar():
    assert bibpy.parser.parse_query('article', 'bibtype') ==\
        ('bibtype', (None, 'article'))
    assert bibpy.parser.parse_query('^book', 'bibtype') ==\
        ('bibtype', ('^', 'book'))

# NOTE: We also test the numeric grammar here as it is part of the field query
# grammar
def test_field_grammar():
    assert bibpy.parser.parse_query('year<2000', 'field') ==\
        ('comparison', (None, 'year', '<', '2000'))
    assert bibpy.parser.parse_query('^year>2000', 'field') ==\
        ('comparison', ('^', 'year', '>', '2000'))
    assert bibpy.parser.parse_query('issue<=10', 'field') ==\
        ('comparison', (None, 'issue', '<=', '10'))
    assert bibpy.parser.parse_query('volume>100', 'field') ==\
        ('comparison', (None, 'volume', '>', '100'))
    assert bibpy.parser.parse_query('month>=9', 'field') ==\
        ('comparison', (None, 'month', '>=', '9'))
    assert bibpy.parser.parse_query('year=1990-2000', 'field') ==\
        ('interval', (None, 'year', '1990', '2000'))
    assert bibpy.parser.parse_query('1900 < year <= 2000', 'field') ==\
        ('range', (None, '1900', '<', 'year', '<=', '2000'))

    # Test invalid queries
    invalid_queries = [
        # '!author .',         # Extra characters at the end
        'volume/1900-2000',  # '=' replaces by forward slash
        'author<>10',        # Invalid comparison operator
        'institution~'       # No value following '~'
    ]

    for query in invalid_queries:
        with pytest.raises(bibpy.error.ParseException):
            bibpy.parser.parse_query(query, 'field')

def test_predicate_composition():
    at = bibpy.tools.always_true
    af = bibpy.tools.always_false

    pred1 = bibpy.tools.compose_predicates([af, at, af], any)
    pred2 = bibpy.tools.compose_predicates([af, af, af], any)
    pred3 = bibpy.tools.compose_predicates([af, at], all)
    pred4 = bibpy.tools.compose_predicates([at, at], all)

    assert pred1(1)
    assert not pred2(1)
    assert not pred3(1)
    assert pred4(1)
<|endoftext|>


<commit_before>from __future__ import unicode_literals
import difflib
from future import standard_library
standard_library.install_aliases()
import fnmatch
import os
import re
import io
import zipfile

import requests

from xml.etree.ElementTree import ElementTree

CUMULUSCI_PATH = os.path.realpath(
    os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')
)

def findReplace(find, replace, directory, filePattern, logger=None, max=None):
    for path, dirs, files in os.walk(os.path.abspath(directory)):
        for filename in fnmatch.filter(files, filePattern):
            filepath = os.path.join(path, filename)
            with open(filepath) as f:
                s = f.read()
            if max:
                s_updated = s.replace(find, replace, max)
            else:
                s_updated = s.replace(find, replace)
            if s != s_updated:
                if logger:
                    logger.info('Updating {}'.format(filepath))
                with open(filepath, "w") as f:
                    f.write(s_updated)

def findReplaceRegex(find, replace, directory, filePattern, logger=None):
    for path, dirs, files in os.walk(os.path.abspath(directory)):
        for filename in fnmatch.filter(files, filePattern):
            filepath = os.path.join(path, filename)
            with open(filepath) as f:
                s = f.read()
            s_updated = re.sub(find, replace, s)
            if s != s_updated:
                if logger:
                    logger.info('Updating {}'.format(filepath))
                with open(filepath, "w") as f:
                    f.write(s_updated)

def findRename(find, replace, directory, logger=None):
    for path, dirs, files in os.walk(os.path.abspath(directory)):
        for filename in files:
            filepath = os.path.join(path, filename)
            if logger:
                logger.info('Renaming {}'.format(filepath))
            os.rename(filepath, os.path.join(
                path,
                filename.replace(find, replace),
            ))

def removeXmlElement(name, directory, file_pattern, logger=None):
    for path, dirs, files in os.walk(os.path.abspath(directory)):
        for filename in fnmatch.filter(files, file_pattern):
            filepath = os.path.join(path, filename)
            tree = ElementTree()
            tree.parse(filepath)
            root = tree.getroot()
            remove = root.findall(
                './/{{http://soap.sforce.com/2006/04/metadata}}{}'.format(name)
            )
            if not remove:
                continue

            if logger:
                logger.info(
                    'Modifying {} to remove <{}> elements'.format(
                        filepath,
                        name,
                    )
                )

            parent_map = {c: p for p in tree.iter() for c in p}

            for elem in remove:
                parent = parent_map[elem]
                parent.remove(elem)

            tree.write(
                filepath,
                encoding="UTF-8",
                default_namespace='http://soap.sforce.com/2006/04/metadata',
            )

def download_extract_zip(url, target=None, subfolder=None):
    resp = requests.get(url)
    zip_content = io.BytesIO(resp.content)
    zip_file = zipfile.ZipFile(zip_content)
    if subfolder:
        zip_file = zip_subfolder(zip_file, subfolder)
    if target:
        zip_file.extractall(target)
        return
    return zip_file

def zip_subfolder(zip_src, path):
    if not path.endswith('/'):
        path = path + '/'

    zip_dest = zipfile.ZipFile(io.BytesIO(), 'w', zipfile.ZIP_DEFLATED)
    for name in zip_src.namelist():
        if not name.startswith(path):
            continue

        content = zip_src.read(name)
        rel_name = name.replace(path, '', 1)

        if rel_name:
            zip_dest.writestr(rel_name, content)

    return zip_dest

def zip_inject_namespace(zip_src, namespace=None, managed=None, filename_token=None, namespace_token=None, namespaced_org=None, logger=None):
    """ Replaces %%%NAMESPACE%%% for all files and ___NAMESPACE___ in all
        filenames in the zip with the either '' if no namespace is provided
        or 'namespace__' if provided.
    """
    # Handle token %%%NAMESPACE_OR_C%%% for lightning components
    namespace_or_c_token = '%%%NAMESPACE_OR_C%%%'
    namespace_or_c = namespace if namespace else 'c'

    # Handle namespace and filename tokens
    if not filename_token:
        filename_token = '___NAMESPACE___'
    if not namespace_token:
        namespace_token = '%%%NAMESPACE%%%'
    if managed is True and namespace:
        namespace = namespace + '__'
    else:
        namespace = ''

    # Handle tokens %%%NAMESPACED_ORG%%% and ___NAMESPACED_ORG___
    namespaced_org_token = '%%%NAMESPACED_ORG%%%'
    namespaced_org_file_token = '___NAMESPACED_ORG___'
    namespaced_org = namespace if namespaced_org else ''

    zip_dest = zipfile.ZipFile(io.BytesIO(), 'w', zipfile.ZIP_DEFLATED)

    differ = difflib.Differ()

    for name in zip_src.namelist():
        orig_name = unicode(name)
        try:
            content = zip_src.read(name)
            orig_content = unicode(content)
            content = content.replace(namespace_token, namespace)
            if logger and content != orig_content:
                logger.info('  {}: Replaced %%%NAMESPACE%%% with {}'.format(name, namespace))

            prev_content = unicode(content)
            content = content.replace(namespace_or_c_token, namespace_or_c)
            if logger and content != prev_content:
                logger.info('  {}: Replaced %%%NAMESPACE_OR_C%%% with {}'.format(name, namespace_or_c))

            prev_content = unicode(content)
            content = content.replace(namespaced_org_token, namespaced_org)
            if logger and content != prev_content:
                logger.info('  {}: Replaced %%%NAMESPACED_ORG%%% with {}'.format(name, namespaced_org))

        except UnicodeDecodeError:
            # if we cannot decode the content, don't try and replace it.
            pass

        # Replace namespace token in file name
        name = name.replace(filename_token, namespace)
        name = name.replace(namespaced_org_file_token, namespaced_org)
        if logger and name != orig_name:
            logger.info('  {}: renamed to {}'.format(orig_name, name))
        zip_dest.writestr(name, content)

    return zip_dest

def zip_strip_namespace(zip_src, namespace, logger=None):
    """ Given a namespace, strips 'namespace__' from all files and filenames
        in the zip
    """
    namespace_prefix = '{}__'.format(namespace)
    lightning_namespace = '{}:'.format(namespace)
    zip_dest = zipfile.ZipFile(io.BytesIO(), 'w', zipfile.ZIP_DEFLATED)
    for name in zip_src.namelist():
        try:
            content = zip_src.read(name).replace(namespace_prefix, '')
            content = content.replace(lightning_namespace, 'c')
            name = name.replace(namespace_prefix, '')
            zip_dest.writestr(name, content)
        except UnicodeDecodeError:
            # if we cannot decode the content, don't try and replace it.
            pass
    return zip_dest

def zip_tokenize_namespace(zip_src, namespace, logger=None):
    """ Given a namespace, replaces 'namespace__' with %%%NAMESPACE%%% for all
        files and ___NAMESPACE___ in all filenames in the zip
    """
    if not namespace:
        return zip_src

    namespace_prefix = '{}__'.format(namespace)
    lightning_namespace = '{}:'.format(namespace)
    zip_dest = zipfile.ZipFile(io.BytesIO(), 'w', zipfile.ZIP_DEFLATED)
    for name in zip_src.namelist():
        try:
            content = zip_src.read(name).replace(namespace_prefix, '%%%NAMESPACE%%%')
            content = content.replace(lightning_namespace, '%%%NAMESPACE_OR_C%%%')
            name = name.replace(namespace_prefix, '___NAMESPACE___')
            zip_dest.writestr(name, content)
        except UnicodeDecodeError:
            # if we cannot decode the content, don't try and replace it.
            pass
    return zip_dest

def doc_task(task_name, task_config, project_config=None, org_config=None):
    """ Document a (project specific) task configuration in RST format. """
    from cumulusci.core.utils import import_class
    doc = []
    doc.append(
        '{}\n==========================================\n'.format(task_name))
    doc.append('**Description:** {}\n'.format(task_config.description))
    doc.append('**Class::** {}\n'.format(task_config.class_path))

    task_class = import_class(task_config.class_path)
    if task_class.task_options:
        doc.append('Options:\n------------------------------------------\n')
        defaults = task_config.options
        if not defaults:
            defaults = {}
        for name, option in list(task_class.task_options.items()):
            default = defaults.get(name)
            if default:
                default = ' **Default: {}**'.format(default)
            else:
                default = ''
            if option.get('required'):
                doc.append('* **{}** *(required)*: {}{}'.format(
                    name,
                    option.get('description'),
                    default))
            else:
                doc.append('* **{}**: {}{}'.format(
                    name,
                    option.get('description'),
                    default))

    return '\n'.join(doc)

def package_xml_from_dict(items, api_version, package_name=None):
    lines = []

    # Print header
    lines.append(u'<?xml version="1.0" encoding="UTF-8"?>')
    lines.append(u'<Package xmlns="http://soap.sforce.com/2006/04/metadata">')

    # Include package name if specified
    if package_name:
        lines.append('    <fullName>{}</fullName'.format(package_name))

    # Print types sections
    md_types = list(items.keys())
    md_types.sort()
    for md_type in md_types:
        members = items[md_type]
        members.sort()
        lines.append('    <types>')
        for member in members:
            lines.append('        <members>{}</members>'.format(member))
        lines.append('        <name>{}</name>'.format(md_type))
        lines.append('    </types>')

    # Print footer
    lines.append(u'    <version>{0}</version>'.format(api_version))
    lines.append(u'</Package>')

    return u'\n'.join(lines)
<commit_msg>Add support for %%%NAMESPACED_ORG_OR_C%%% token<commit_after>from __future__ import unicode_literals
import difflib
from future import standard_library
standard_library.install_aliases()
import fnmatch
import os
import re
import io
import zipfile

import requests

from xml.etree.ElementTree import ElementTree

CUMULUSCI_PATH = os.path.realpath(
    os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')
)

def findReplace(find, replace, directory, filePattern, logger=None, max=None):
    for path, dirs, files in os.walk(os.path.abspath(directory)):
        for filename in fnmatch.filter(files, filePattern):
            filepath = os.path.join(path, filename)
            with open(filepath) as f:
                s = f.read()
            if max:
                s_updated = s.replace(find, replace, max)
            else:
                s_updated = s.replace(find, replace)
            if s != s_updated:
                if logger:
                    logger.info('Updating {}'.format(filepath))
                with open(filepath, "w") as f:
                    f.write(s_updated)

def findReplaceRegex(find, replace, directory, filePattern, logger=None):
    for path, dirs, files in os.walk(os.path.abspath(directory)):
        for filename in fnmatch.filter(files, filePattern):
            filepath = os.path.join(path, filename)
            with open(filepath) as f:
                s = f.read()
            s_updated = re.sub(find, replace, s)
            if s != s_updated:
                if logger:
                    logger.info('Updating {}'.format(filepath))
                with open(filepath, "w") as f:
                    f.write(s_updated)

def findRename(find, replace, directory, logger=None):
    for path, dirs, files in os.walk(os.path.abspath(directory)):
        for filename in files:
            filepath = os.path.join(path, filename)
            if logger:
                logger.info('Renaming {}'.format(filepath))
            os.rename(filepath, os.path.join(
                path,
                filename.replace(find, replace),
            ))

def removeXmlElement(name, directory, file_pattern, logger=None):
    for path, dirs, files in os.walk(os.path.abspath(directory)):
        for filename in fnmatch.filter(files, file_pattern):
            filepath = os.path.join(path, filename)
            tree = ElementTree()
            tree.parse(filepath)
            root = tree.getroot()
            remove = root.findall(
                './/{{http://soap.sforce.com/2006/04/metadata}}{}'.format(name)
            )
            if not remove:
                continue

            if logger:
                logger.info(
                    'Modifying {} to remove <{}> elements'.format(
                        filepath,
                        name,
                    )
                )

            parent_map = {c: p for p in tree.iter() for c in p}

            for elem in remove:
                parent = parent_map[elem]
                parent.remove(elem)

            tree.write(
                filepath,
                encoding="UTF-8",
                default_namespace='http://soap.sforce.com/2006/04/metadata',
            )

def download_extract_zip(url, target=None, subfolder=None):
    resp = requests.get(url)
    zip_content = io.BytesIO(resp.content)
    zip_file = zipfile.ZipFile(zip_content)
    if subfolder:
        zip_file = zip_subfolder(zip_file, subfolder)
    if target:
        zip_file.extractall(target)
        return
    return zip_file

def zip_subfolder(zip_src, path):
    if not path.endswith('/'):
        path = path + '/'

    zip_dest = zipfile.ZipFile(io.BytesIO(), 'w', zipfile.ZIP_DEFLATED)
    for name in zip_src.namelist():
        if not name.startswith(path):
            continue

        content = zip_src.read(name)
        rel_name = name.replace(path, '', 1)

        if rel_name:
            zip_dest.writestr(rel_name, content)

    return zip_dest

def zip_inject_namespace(zip_src, namespace=None, managed=None, filename_token=None, namespace_token=None, namespaced_org=None, logger=None):
    """ Replaces %%%NAMESPACE%%% for all files and ___NAMESPACE___ in all
        filenames in the zip with the either '' if no namespace is provided
        or 'namespace__' if provided.
    """

    # Handle namespace and filename tokens
    if not filename_token:
        filename_token = '___NAMESPACE___'
    if not namespace_token:
        namespace_token = '%%%NAMESPACE%%%'
    if managed is True and namespace:
        namespace_prefix = namespace + '__'
    else:
        namespace_prefix = ''

    # Handle tokens %%%NAMESPACED_ORG%%% and ___NAMESPACED_ORG___
    namespaced_org_token = '%%%NAMESPACED_ORG%%%'
    namespaced_org_file_token = '___NAMESPACED_ORG___'
    namespaced_org = namespace_prefix if namespaced_org else ''

    # Handle token %%%NAMESPACE_OR_C%%% for lightning components
    namespace_or_c_token = '%%%NAMESPACE_OR_C%%%'
    namespace_or_c = namespace if managed and namespace else 'c'

    # Handle token %%%NAMESPACED_ORG_OR_C%%%
    namespaced_org_or_c_token = '%%%NAMESPACE_OR_C%%%'
    namespaced_org_or_c = namespace if namespaced_org else 'c'

    zip_dest = zipfile.ZipFile(io.BytesIO(), 'w', zipfile.ZIP_DEFLATED)

    differ = difflib.Differ()

    for name in zip_src.namelist():
        orig_name = unicode(name)
        try:
            content = zip_src.read(name)
            orig_content = unicode(content)
            content = content.replace(namespace_token, namespace_prefix)
            if logger and content != orig_content:
                logger.info('  {}: Replaced %%%NAMESPACE%%% with {}'.format(name, namespace))

            prev_content = unicode(content)
            content = content.replace(namespace_or_c_token, namespace_or_c)
            if logger and content != prev_content:
                logger.info('  {}: Replaced %%%NAMESPACE_OR_C%%% with {}'.format(name, namespace_or_c))

            prev_content = unicode(content)
            content = content.replace(namespaced_org_token, namespaced_org)
            if logger and content != prev_content:
                logger.info('  {}: Replaced %%%NAMESPACED_ORG%%% with {}'.format(name, namespaced_org))

            prev_content = unicode(content)
            content = content.replace(namespaced_org_or_c_token, namespaced_org_or_c)
            if logger and content != prev_content:
                logger.info('  {}: Replaced %%%NAMESPACE_OR_C%%% with {}'.format(name, namespaced_org_or_c))

        except UnicodeDecodeError:
            # if we cannot decode the content, don't try and replace it.
            pass

        # Replace namespace token in file name
        name = name.replace(filename_token, namespace_prefix)
        name = name.replace(namespaced_org_file_token, namespaced_org)
        if logger and name != orig_name:
            logger.info('  {}: renamed to {}'.format(orig_name, name))
        zip_dest.writestr(name, content)

    return zip_dest

def zip_strip_namespace(zip_src, namespace, logger=None):
    """ Given a namespace, strips 'namespace__' from all files and filenames
        in the zip
    """
    namespace_prefix = '{}__'.format(namespace)
    lightning_namespace = '{}:'.format(namespace)
    zip_dest = zipfile.ZipFile(io.BytesIO(), 'w', zipfile.ZIP_DEFLATED)
    for name in zip_src.namelist():
        try:
            content = zip_src.read(name).replace(namespace_prefix, '')
            content = content.replace(lightning_namespace, 'c')
            name = name.replace(namespace_prefix, '')
            zip_dest.writestr(name, content)
        except UnicodeDecodeError:
            # if we cannot decode the content, don't try and replace it.
            pass
    return zip_dest

def zip_tokenize_namespace(zip_src, namespace, logger=None):
    """ Given a namespace, replaces 'namespace__' with %%%NAMESPACE%%% for all
        files and ___NAMESPACE___ in all filenames in the zip
    """
    if not namespace:
        return zip_src

    namespace_prefix = '{}__'.format(namespace)
    lightning_namespace = '{}:'.format(namespace)
    zip_dest = zipfile.ZipFile(io.BytesIO(), 'w', zipfile.ZIP_DEFLATED)
    for name in zip_src.namelist():
        try:
            content = zip_src.read(name).replace(namespace_prefix, '%%%NAMESPACE%%%')
            content = content.replace(lightning_namespace, '%%%NAMESPACE_OR_C%%%')
            name = name.replace(namespace_prefix, '___NAMESPACE___')
            zip_dest.writestr(name, content)
        except UnicodeDecodeError:
            # if we cannot decode the content, don't try and replace it.
            pass
    return zip_dest

def doc_task(task_name, task_config, project_config=None, org_config=None):
    """ Document a (project specific) task configuration in RST format. """
    from cumulusci.core.utils import import_class
    doc = []
    doc.append(
        '{}\n==========================================\n'.format(task_name))
    doc.append('**Description:** {}\n'.format(task_config.description))
    doc.append('**Class::** {}\n'.format(task_config.class_path))

    task_class = import_class(task_config.class_path)
    if task_class.task_options:
        doc.append('Options:\n------------------------------------------\n')
        defaults = task_config.options
        if not defaults:
            defaults = {}
        for name, option in list(task_class.task_options.items()):
            default = defaults.get(name)
            if default:
                default = ' **Default: {}**'.format(default)
            else:
                default = ''
            if option.get('required'):
                doc.append('* **{}** *(required)*: {}{}'.format(
                    name,
                    option.get('description'),
                    default))
            else:
                doc.append('* **{}**: {}{}'.format(
                    name,
                    option.get('description'),
                    default))

    return '\n'.join(doc)

def package_xml_from_dict(items, api_version, package_name=None):
    lines = []

    # Print header
    lines.append(u'<?xml version="1.0" encoding="UTF-8"?>')
    lines.append(u'<Package xmlns="http://soap.sforce.com/2006/04/metadata">')

    # Include package name if specified
    if package_name:
        lines.append('    <fullName>{}</fullName'.format(package_name))

    # Print types sections
    md_types = list(items.keys())
    md_types.sort()
    for md_type in md_types:
        members = items[md_type]
        members.sort()
        lines.append('    <types>')
        for member in members:
            lines.append('        <members>{}</members>'.format(member))
        lines.append('        <name>{}</name>'.format(md_type))
        lines.append('    </types>')

    # Print footer
    lines.append(u'    <version>{0}</version>'.format(api_version))
    lines.append(u'</Package>')

    return u'\n'.join(lines)
<|endoftext|>


<commit_before>from classes.office import Office
from classes.living_space import LivingSpace
from classes.fellow import Fellow
from classes.staff import Staff
from random import randint

class Dojo(object):
    """
    This class imports Office, LivingSpace, Fellow and Staff.

    It creates instances of each in its methods.
    """

    def __init__(self):
        self.all_rooms = []
        self.allocated_persons = []
        self.unallocated_persons = []
        self.all_persons = []
        self.offices = []
        self.living_spaces = []

    def create_room(self, room_type, room_name):
        if not isinstance(room_name, str) or not isinstance(room_type, str):
            raise ValueError('Invalid: Please input a string as room_name or room_type')
        else:
            room_type = room_type.lower()
            room_name = room_name.lower()
        if room_type != "office" and room_type != "living_space":
            raise ValueError("Invalid room type: Your room type should be 'office' or 'living_space'")
        existing_rooms = []
        for room in self.all_rooms:
            if room.room_name == room_name and room.room_type == room_type:
                existing_rooms.append({room_name: room_type})
        if {room_name: room_type} in existing_rooms:
            print (room_type.title() + " " + room_name.title() + " already exists")
        else:
            if room_type == 'office':
                room = Office(room_name)
                self.offices.append(room)
            elif room_type == 'living_space':
                room = LivingSpace(room_name)
                self.living_spaces.append(room)
            self.all_rooms.append(room)
            print ("An " + room.room_type + " called " + room.room_name.title() + " has been successfully created!")

    def add_person(self, person_type, person_name, person_surname, wants_accommodation="N"):
        if wants_accommodation:
            wants_accommodation = wants_accommodation.lower()
            if wants_accommodation != "y" and wants_accommodation != "n":
                raise ValueError("Please input Y or N for wants_accommodation")
        if not isinstance(person_type, str) or not isinstance(person_name, str) or not isinstance(person_surname, str):
            raise ValueError('Only strings are allowed as input')
        else:
            person_type = person_type.lower()
            person_name = person_name.lower()
            person_surname = person_surname.lower()
            if person_type != 'staff' and person_type != 'fellow':
                raise ValueError("Invalid person_type: Your person type should be either 'fellow' or 'staff'")
            if person_type == 'staff':
                person = Staff(person_name, person_surname)
            elif person_type == 'fellow':
                person = Fellow(person_name, person_surname, wants_accommodation)
            existing_persons = []
            if self.all_persons:
                for item in self.all_persons:
                    if item.person_name == person.person_name and item.person_surname == person.person_surname:
                        existing_persons.append(person)
            if person in existing_persons:
                print (person.person_name.title() + " " + person.person_surname.title() + " already exists")
            else:
                self.all_persons.append(person)
                print (person.person_type.title() + " " + person.person_name.title() + " " + person.person_surname.title() + " has been successfully added!")

    def allocate_rooms(self):
        if not self.all_persons:
            print ("There are no persons to allocate rooms")
        else:
            for person in self.all_persons:
                if person not in self.allocated_persons:
                    self.unallocated_persons.append(person)
                    if not self.living_spaces:
                        print ("There are no living_spaces to allocate " + person.person_name.title())
                    if not self.offices:
                        print ("There are no offices to allocate " + person.person_name.title())
                    if person.person_type == "fellow":
                        if person.wants_accommodation == "y":
                            random_living_space_number = randint(0, len(self.living_spaces) - 1)
                            random_office_number = randint(0, len(self.offices) - 1)
                            living_space_allocation = self.living_spaces[random_living_space_number]
                            office_allocation = self.offices[random_office_number]
                            try:
                                living_space_allocation.add_occupant(person)
                                office_allocation.add_occupant(person)
                            except Exception as e:
                                print (e)
                            self.allocated_persons.append(person)
                        else:
                            random_office_number = randint(0, len(self.offices) - 1)
                            office_allocation = self.offices[random_office_number]
                            try:
                                office_allocation.add_occupant(person)
                            except Exception as e:
                                print (e)
                            self.allocated_persons.append(person)
                    elif person.person_type == "staff":
                        random_office_number = randint(0, len(self.offices) - 1)
                        office_allocation = self.offices[random_office_number]
                        try:
                            office_allocation.add_occupant(person)
                        except Exception as e:
                            print (e)
                        self.allocated_persons.append(person)
<commit_msg>Fix bug that raises error with randint implementation<commit_after>from classes.office import Office
from classes.living_space import LivingSpace
from classes.fellow import Fellow
from classes.staff import Staff
from random import randint

class Dojo(object):
    """
    This class imports Office, LivingSpace, Fellow and Staff.

    It creates instances of each in its methods.
    """

    def __init__(self):
        self.all_rooms = []
        self.allocated_persons = []
        self.unallocated_persons = []
        self.all_persons = []
        self.offices = []
        self.living_spaces = []

    def create_room(self, room_type, room_name):
        if not isinstance(room_name, str) or not isinstance(room_type, str):
            raise ValueError('Invalid: Please input a string as room_name or room_type')
        else:
            room_type = room_type.lower()
            room_name = room_name.lower()
        if room_type != "office" and room_type != "living_space":
            raise ValueError("Invalid room type: Your room type should be 'office' or 'living_space'")
        else:
            if room_type == 'office':
                room = Office(room_name)
            elif room_type == 'living_space':
                room = LivingSpace(room_name)
            try:
                for item in self.all_rooms:
                    if item.room_name == room_name and item.room_type == room_type:
                        raise Exception(room_type.title() + " " + room_name.title() + " already exists")
            except Exception as e:
                print (e)
            else:
                if room.room_type == 'office':
                    self.offices.append(room)
                elif room.room_type == 'living_space':
                    self.living_spaces.append(room)
                self.all_rooms.append(room)
                print ("An " + room.room_type + " called " + room.room_name.title() + " has been successfully created!")

    def add_person(self, person_type, person_name, person_surname, wants_accommodation="N"):
        if wants_accommodation:
            wants_accommodation = wants_accommodation.lower()
            if wants_accommodation != "y" and wants_accommodation != "n":
                raise ValueError("Please input Y or N for wants_accommodation")
        if not isinstance(person_type, str) or not isinstance(person_name, str) or not isinstance(person_surname, str):
            raise ValueError('Only strings are allowed as input')
        else:
            person_type = person_type.lower()
            person_name = person_name.lower()
            person_surname = person_surname.lower()
            if person_type != 'staff' and person_type != 'fellow':
                raise ValueError("Invalid person_type: Your person type should be either 'fellow' or 'staff'")
            if person_type == 'staff':
                person = Staff(person_name, person_surname)
            elif person_type == 'fellow':
                person = Fellow(person_name, person_surname, wants_accommodation)
            try:
                for item in self.all_persons:
                    if item.person_name == person_name and item.person_surname == person_surname:
                        raise Exception(person_type.title() + " " + person_name.title() + " already exists")
            except Exception as e:
                print (e)
            else:
                self.all_persons.append(person)
                print (person.person_type.title() + " " + person.person_name.title() + " " + person.person_surname.title() + " has been successfully added!")

    def allocate_rooms(self):
        if not self.all_persons:
            print ("There are no persons to allocate rooms")
        else:
            for person in self.all_persons:
                if person not in self.allocated_persons:
                    self.unallocated_persons.append(person)
                    if person.person_type == "fellow":
                        if person.wants_accommodation == "y":
                            if self.living_spaces:
                                random_living_space_number = randint(0, len(self.living_spaces) - 1)
                                living_space_allocation = self.living_spaces[random_living_space_number]
                                try:
                                    living_space_allocation.add_occupant(person)
                                except Exception as e:
                                    print (e)
                                self.allocated_persons.append(person)
                            else:
                                print ("There are no living_spaces to allocate " + person.person_name.title() + " " + person.person_surname.title())
                            if self.offices:
                                random_office_number = randint(0, len(self.offices) - 1)
                                office_allocation = self.offices[random_office_number]
                                try:
                                    office_allocation.add_occupant(person)
                                except Exception as e:
                                    print (e)
                                if person not in self.allocated_persons:
                                    self.allocated_persons.append(person)
                            else:
                                print ("There are no offices to allocate " + person.person_name.title() + " " + person.person_surname.title())
                        else:
                            if self.offices:
                                random_office_number = randint(0, len(self.offices) - 1)
                                office_allocation = self.offices[random_office_number]
                                try:
                                    office_allocation.add_occupant(person)
                                except Exception as e:
                                    print (e)
                                self.allocated_persons.append(person)
                            else:
                                print ("There are no offices to allocate " + person.person_name.title() + " " + person.person_surname.title())
                    elif person.person_type == "staff":
                        if self.offices:
                            random_office_number = randint(0, len(self.offices) - 1)
                            office_allocation = self.offices[random_office_number]
                            try:
                                office_allocation.add_occupant(person)
                            except Exception as e:
                                print (e)
                            self.allocated_persons.append(person)
                        else:
                            print ("There are no offices to allocate " + person.person_name.title() + " " + person.person_surname.title())
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals

from collections import OrderedDict
from rakuten_ws.utils import xml2dict, dict2xml, sorted_dict, camelize_dict

def test_sorted_dict():
    test_dict = {
        "thirdKey": 3,
        "myDict": {
            "c": 2,
            "b": 2,
            "a": "one"
        },
        "firstKey": [
            "simple_value",
            {
                "twoValue": 2,
                "oneKey": "one"
            }
        ],
        "zzzz": 2,
        "aaaa": 1
    }
    expected_dict = OrderedDict([
        ('aaaa', 1),
        ('firstKey', ["simple_value", OrderedDict([('oneKey', 'one'), ('twoValue', 2)])]),
        ('myDict', OrderedDict([('a', 'one'), ('b', 2), ('c', 2)])),
        ('thirdKey', 3),
        ('zzzz', 2)
    ])
    assert sorted_dict(test_dict) == expected_dict

def test_camelize_dict():
    test_dict = {
        "my_list": [{"one_key": "one", "Two_key": 2, "NGKeyword": 3}, 2, "three"],
        "my_dict": {"one_key": "one", "Two_key": 2, "NGKeyword": 3},
        "first_key": 1,
        "SecondKey": 2,
        "thirdKey": 3,
    }
    expected_dict = {
        "thirdKey": 3,
        "myDict": {
            "Two_key": 2,
            "NGKeyword": 3,
            "oneKey": "one"
        },
        "myList": [
            {
                "Two_key": 2,
                "NGKeyword": 3,
                "oneKey": "one"
            }
        ],
        "SecondKey": 2,
        "firstKey": 1
    }
    assert camelize_dict(test_dict) == expected_dict

def test_xml2dict():
    xml_string = """<request>
    <cast>
        <actor>
            <firstname>Rami</firstname>
            <lastname>Malek</lastname>
            <age>35</age>
        </actor>
        <actor>
            <firstname>Carly</firstname>
            <lastname>Chaikin</lastname>
            <age>26</age>
        </actor>
    </cast>
</request>"""
    data = xml2dict(xml_string)
    assert data['cast']['actor'][1]['firstname'] == 'Carly'
    assert data['cast']['actor'][0]['age'] == 35

    class MyDictClass(dict):
        pass

    data = xml2dict(xml_string, dict_type=MyDictClass)
    assert isinstance(data, MyDictClass)

def test_dict2xml():
    expected_xml_string = """<?xml version='1.0' encoding='utf-8'?>
<request>
  <itemUpdateRequest>
    <item>
      <itemPrice>198000</itemPrice>
      <categories>
        <categoryInfo>
          <categoryId>123</categoryId>
        </categoryInfo>
      </categories>
      <itemUrl>test123</itemUrl>
    </item>
  </itemUpdateRequest>
</request>"""
    categories = OrderedDict([('categoryInfo', OrderedDict([('categoryId', 123)]))])
    item = OrderedDict([('item', OrderedDict([('itemPrice', 198000),
                                              ('categories', categories),
                                              ('itemUrl', 'test123')]))])
    data = OrderedDict([('itemUpdateRequest', item)])

    xml_string = dict2xml(data, root="request", pretty_print=True)
    assert expected_xml_string == xml_string.strip()
    expected_no_pretty_xml_string = expected_xml_string.replace('  ', '')\
                                                       .replace('\n', '')\
                                                       .replace('?>', '?>\n')
    assert expected_no_pretty_xml_string == dict2xml(data, root="request", pretty_print=False)
<commit_msg>Tested to_unicode helpers<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals

from collections import OrderedDict
from rakuten_ws.utils import xml2dict, dict2xml, sorted_dict, camelize_dict
from rakuten_ws.compat import to_unicode

def test_sorted_dict():
    test_dict = {
        "thirdKey": 3,
        "myDict": {
            "c": 2,
            "b": 2,
            "a": "one"
        },
        "firstKey": [
            "simple_value",
            {
                "twoValue": 2,
                "oneKey": "one"
            }
        ],
        "zzzz": 2,
        "aaaa": 1
    }
    expected_dict = OrderedDict([
        ('aaaa', 1),
        ('firstKey', ["simple_value", OrderedDict([('oneKey', 'one'), ('twoValue', 2)])]),
        ('myDict', OrderedDict([('a', 'one'), ('b', 2), ('c', 2)])),
        ('thirdKey', 3),
        ('zzzz', 2)
    ])
    assert sorted_dict(test_dict) == expected_dict

def test_camelize_dict():
    test_dict = {
        "my_list": [{"one_key": "one", "Two_key": 2, "NGKeyword": 3}, 2, "three"],
        "my_dict": {"one_key": "one", "Two_key": 2, "NGKeyword": 3},
        "first_key": 1,
        "SecondKey": 2,
        "thirdKey": 3,
    }
    expected_dict = {
        "thirdKey": 3,
        "myDict": {
            "Two_key": 2,
            "NGKeyword": 3,
            "oneKey": "one"
        },
        "myList": [
            {
                "Two_key": 2,
                "NGKeyword": 3,
                "oneKey": "one"
            }
        ],
        "SecondKey": 2,
        "firstKey": 1
    }
    assert camelize_dict(test_dict) == expected_dict

def test_xml2dict():
    xml_string = """<request>
    <cast>
        <actor>
            <firstname>Rami</firstname>
            <lastname>Malek</lastname>
            <age>35</age>
        </actor>
        <actor>
            <firstname>Carly</firstname>
            <lastname>Chaikin</lastname>
            <age>26</age>
        </actor>
    </cast>
</request>"""
    data = xml2dict(xml_string)
    assert data['cast']['actor'][1]['firstname'] == 'Carly'
    assert data['cast']['actor'][0]['age'] == 35

    class MyDictClass(dict):
        pass

    data = xml2dict(xml_string, dict_type=MyDictClass)
    assert isinstance(data, MyDictClass)

def test_dict2xml():
    expected_xml_string = """<?xml version='1.0' encoding='utf-8'?>
<request>
  <itemUpdateRequest>
    <item>
      <itemPrice>198000</itemPrice>
      <categories>
        <categoryInfo>
          <categoryId>123</categoryId>
        </categoryInfo>
      </categories>
      <itemUrl>test123</itemUrl>
    </item>
  </itemUpdateRequest>
</request>"""
    categories = OrderedDict([('categoryInfo', OrderedDict([('categoryId', 123)]))])
    item = OrderedDict([('item', OrderedDict([('itemPrice', 198000),
                                              ('categories', categories),
                                              ('itemUrl', 'test123')]))])
    data = OrderedDict([('itemUpdateRequest', item)])

    xml_string = dict2xml(data, root="request", pretty_print=True)
    assert expected_xml_string == xml_string.strip()
    expected_no_pretty_xml_string = expected_xml_string.replace('  ', '')\
                                                       .replace('\n', '')\
                                                       .replace('?>', '?>\n')
    assert expected_no_pretty_xml_string == dict2xml(data, root="request", pretty_print=False)

def test_to_unicode():
    assert to_unicode('à tester') == 'à tester'
    assert to_unicode('à tester'.encode('utf-8')) == 'à tester'
    assert to_unicode('à tester'.encode('iso-8859-1'), encoding='iso-8859-1') == 'à tester'
    assert to_unicode(352) == '352'
<|endoftext|>


<commit_before><commit_msg>BaseTools: use set instead of list for a variable to be used with in<commit_after><|endoftext|>


<commit_before>from piece import piece
from tkinter import *

class tour(piece):

    def __init__(self, color):
        super(tour, self).__init__(color)

    def move(self, pos_x, pos_y, tableau, array):
        curColor = tableau.getPion(pos_x, pos_y).getColor()
        curX = pos_x + 1
        curY = pos_y
        while (tableau.getPion(curX, curY) == None and curX <= 7):
           tableau.setPossible(curX, curY, 0, array)
           curX = curX + 1
        tableau.setPossible(curX, curY, curColor, array)
        curX = pos_x - 1
        curY = pos_y
        while (tableau.getPion(curX, curY) == None and curX >=0):
           tableau.setPossible(curX, curY, 0, array)
           curX = curX - 1
        tableau.setPossible(curX, curY, curColor, array)
        curX = pos_x
        curY = pos_y + 1
        while (tableau.getPion(curX, curY) == None and curY <= 7):
           tableau.setPossible(curX, curY, 0, array)
           curY = curY + 1
        tableau.setPossible(curX, curY, curColor, array)
        curX = pos_x
        curY = pos_y - 1
        while (tableau.getPion(curX, curY) == None and curY >= 0):
           tableau.setPossible(curX, curY, 0, array)
           curY = curY - 1
        tableau.setPossible(curX, curY, curColor, array)

    def getLetter(self):
        return "T"

    def getImage(self):
        if self.getColor() == piece._players['NOIR']:
            return PhotoImage(file="tour_n.png")
        else:
            return PhotoImage(file="tour_b.png")
<commit_msg>Update tour.py<commit_after>from piece import piece

class tour(piece):

    def __init__(self, color):
        super(tour, self).__init__(color)

    def move(self, pos_x, pos_y, tableau, array):
        curColor = tableau.getPion(pos_x, pos_y).getColor()
        curX = pos_x + 1
        curY = pos_y
        while (tableau.getPion(curX, curY) == None and curX <= 7):
           tableau.setPossible(curX, curY, 0, array)
           curX = curX + 1
        tableau.setPossible(curX, curY, curColor, array)
        curX = pos_x - 1
        curY = pos_y
        while (tableau.getPion(curX, curY) == None and curX >=0):
           tableau.setPossible(curX, curY, 0, array)
           curX = curX - 1
        tableau.setPossible(curX, curY, curColor, array)
        curX = pos_x
        curY = pos_y + 1
        while (tableau.getPion(curX, curY) == None and curY <= 7):
           tableau.setPossible(curX, curY, 0, array)
           curY = curY + 1
        tableau.setPossible(curX, curY, curColor, array)
        curX = pos_x
        curY = pos_y - 1
        while (tableau.getPion(curX, curY) == None and curY >= 0):
           tableau.setPossible(curX, curY, 0, array)
           curY = curY - 1
        tableau.setPossible(curX, curY, curColor, array)

    def getLetter(self):
        return "T"
<|endoftext|>