<commit_before>
import os
from git import Repo
from controller.arguments import ArgParser
from controller.compose import compose_log
from controller.app import Application
from utilities import PROJECT_DIR, \
    BACKEND_DIR, SWAGGER_DIR, ENDPOINTS_CODE_DIR
from utilities.logs import get_logger
from utilities.basher import BashCommands

log = get_logger(__name__)

compose_log_prefix = 'DEBUG %s' % compose_log
symbol = '✓'
env_log = '%s Created .env file' % symbol
env_log_prefix_verbose = 'VERBOSE ' + env_log
env_log_prefix_info = 'INFO ' + env_log
env_cached_log = 'Using cached .env'
env_cached_log_verbose = 'VERY_VERBOSE ' + env_cached_log

def exec_command(capfd, command):
    command = command.split(" ")

    arguments = ArgParser(args=command)

    try:
        Application(arguments)
    # NOTE: docker-compose calls SystemExit at the end of the command...
    except SystemExit:
        log.info('completed')

    out, err = capfd.readouterr()
    out = out.split("\n")
    err = err.split("\n")

    for e in err:
        print(e)

    return out, err

# def test_init_and_check(capfd):
def test_all(capfd):

    # create .projectrc
    with open('.projectrc', 'w') as f:
        f.write("project: template")

    # INIT on rapydo-core
    _, err = exec_command(capfd, "rapydo init")
    log.pp(err)
    assert env_log_prefix_verbose in err
    assert "INFO Bower libs downloaded" in err
    assert "INFO Project initialized" in err

    # UPDATE on rapydo-core
    _, err = exec_command(capfd, "rapydo update")
    assert env_log_prefix_verbose in err
    assert "INFO Bower libs downloaded" in err
    assert "INFO All updated" in err

    # _, err = exec_command(capfd, "rapydo build")
    # assert "INFO Image built" in err

    # CHECK on rapydo-core
    _, err = exec_command(capfd, "rapydo check")
    assert env_log_prefix_info in err
    assert "INFO You are working on rapydo-core, not a fork" in err
    assert "INFO All checked" in err

    # NOW with are on a fork of rapydo-core
    gitobj = Repo(".")
    gitobj.remotes.origin.set_url("just_a_non_url")

    # Missing upstream url
    _, err = exec_command(capfd, "rapydo check")
    assert "EXIT Missing upstream to rapydo/core" in err

    # Create upstream url
    _, err = exec_command(capfd, "rapydo init")
    assert env_log_prefix_verbose in err
    assert "INFO Project initialized" in err

    # Check upstream url
    # Also check .env cache
    _, err = exec_command(capfd, "rapydo --cache-env check -s")
    log.pp(err)
    assert "INFO \u2713 Upstream is set correctly" in err
    assert env_cached_log_verbose in err
    assert "INFO All checked" in err

    out, err = exec_command(capfd, "rapydo env")
    assert env_log_prefix_verbose in err
    assert "project: template" in out

    os.remove(".projectrc")

# def test_two_projects(capfd):
    bash = BashCommands()
    bash.copy_folder("projects/template", "projects/second")

    _, err = exec_command(capfd, "rapydo -env check -s")
    e = "EXIT Please select the --project option on one of the following:"
    assert e in err
    assert " ['template', 'second']" in err

    _, err = exec_command(capfd, "rapydo -env -p template check -s")
    assert "INFO All checked" in err

    _, err = exec_command(capfd, "rapydo -env -p xyz check -s")
    assert "EXIT Wrong project 'xyz'." in err
    assert "Select one of the following:" in err
    assert " ['template', 'second']" in err

    # create .projectrc
    with open('.projectrc', 'w') as f:
        f.write("project: template")

    _, err = exec_command(capfd, "rapydo -env check -s")
    assert "INFO All checked" in err

# def test_from_start_to_clean(capfd):

    _, err = exec_command(capfd, "rapydo start")
    assert env_log_prefix_verbose in err
    assert compose_log_prefix + "'up'" in err
    assert "INFO Stack started" in err

    _, err = exec_command(capfd, "rapydo status")
    assert compose_log_prefix + "'ps'" in err

    exec_command(capfd, "rapydo log")
    # FIXME: how is possible that this message is not found??
    # assert compose_log_prefix + "'logs'" in err

    exec_command(capfd, "rapydo bower-install jquery")
    # FIXME: how is possible that this message is not found??
    # assert "EXIT Missing bower lib, please add the --lib option" in err
    exec_command(capfd, "rapydo bower-install --lib jquery")
    # FIXME: how is possible that this message is not found??
    # assert compose_log_prefix + "'run'" in err

    exec_command(capfd, "rapydo bower-update jquery")
    # FIXME: how is possible that this message is not found??
    # assert "EXIT Missing bower lib, please add the --lib option" in err
    exec_command(capfd, "rapydo bower-update --lib jquery")
    # FIXME: how is possible that this message is not found??
    # assert compose_log_prefix + "'run'" in err

    _, err = exec_command(capfd, "rapydo toggle-freeze")
    assert env_log_prefix_verbose in err
    assert "INFO Stack paused" in err

    _, err = exec_command(capfd, "rapydo toggle-freeze")
    assert env_log_prefix_verbose in err
    assert "INFO Stack unpaused" in err

    _, err = exec_command(capfd, "rapydo stop")
    assert env_log_prefix_verbose in err
    assert "INFO Stack stoped" in err

    _, err = exec_command(capfd, "rapydo restart")
    assert env_log_prefix_verbose in err
    assert "INFO Stack restarted" in err

    _, err = exec_command(capfd, "rapydo remove")
    assert env_log_prefix_verbose in err
    assert compose_log_prefix + "'stop'" in err
    assert "INFO Stack removed" in err

    _, err = exec_command(capfd, "rapydo clean")
    assert env_log_prefix_verbose in err
    assert "INFO Stack cleaned" in err

    endpoint_name = 'justatest'
    out, err = exec_command(capfd, "rapydo template --yes %s" % endpoint_name)
    # parsing responses like:
    # "rendered projects/template/backend/swagger/justatest/specs.yaml"
    base_response = 'DEBUG rendered %s/template/%s' % \
        (PROJECT_DIR, BACKEND_DIR)

    assert '%s/%s/%s/specs.yaml' % \
        (base_response, SWAGGER_DIR, endpoint_name) in err
    assert '%s/%s/%s/get.yaml' % \
        (base_response, SWAGGER_DIR, endpoint_name) in err
    assert '%s/%s/%s.py' % \
        (base_response, ENDPOINTS_CODE_DIR, endpoint_name) in err
    assert '%s/tests/test_%s.py' % (base_response, endpoint_name) in err
    assert 'INFO Scaffold completed' in err

    out, err = exec_command(capfd, "rapydo find --endpoint %s" % endpoint_name)
    assert "Endpoint path:\t/api/%s" % endpoint_name in err
    assert "Labels:\t\tcustom, %s" % endpoint_name in err
    assert "Python class:\t%s" % endpoint_name.capitalize() in err
<commit_msg>Removed a test check<commit_after>
import os
from git import Repo
from controller.arguments import ArgParser
from controller.compose import compose_log
from controller.app import Application
from utilities import PROJECT_DIR, \
    BACKEND_DIR, SWAGGER_DIR, ENDPOINTS_CODE_DIR
from utilities.logs import get_logger
from utilities.basher import BashCommands

log = get_logger(__name__)

compose_log_prefix = 'DEBUG %s' % compose_log
symbol = '✓'
env_log = '%s Created .env file' % symbol
env_log_prefix_verbose = 'VERBOSE ' + env_log
env_log_prefix_info = 'INFO ' + env_log
env_cached_log = 'Using cached .env'
env_cached_log_verbose = 'VERY_VERBOSE ' + env_cached_log

def exec_command(capfd, command):
    command = command.split(" ")

    arguments = ArgParser(args=command)

    try:
        Application(arguments)
    # NOTE: docker-compose calls SystemExit at the end of the command...
    except SystemExit:
        log.info('completed')

    out, err = capfd.readouterr()
    out = out.split("\n")
    err = err.split("\n")

    for e in err:
        print(e)

    return out, err

# def test_init_and_check(capfd):
def test_all(capfd):

    # create .projectrc
    with open('.projectrc', 'w') as f:
        f.write("project: template")

    # INIT on rapydo-core
    _, err = exec_command(capfd, "rapydo init")
    log.pp(err)
    assert env_log_prefix_verbose in err
    assert "INFO Bower libs downloaded" in err
    assert "INFO Project initialized" in err

    # UPDATE on rapydo-core
    _, err = exec_command(capfd, "rapydo update")
    assert env_log_prefix_verbose in err
    assert "INFO Bower libs downloaded" in err
    assert "INFO All updated" in err

    # _, err = exec_command(capfd, "rapydo build")
    # assert "INFO Image built" in err

    # CHECK on rapydo-core
    _, err = exec_command(capfd, "rapydo check")
    assert env_log_prefix_info in err
    assert "INFO You are working on rapydo-core, not a fork" in err
    assert "INFO All checked" in err

    # NOW with are on a fork of rapydo-core
    gitobj = Repo(".")
    gitobj.remotes.origin.set_url("just_a_non_url")

    # Missing upstream url
    _, err = exec_command(capfd, "rapydo check")
    assert "EXIT Missing upstream to rapydo/core" in err

    # Create upstream url
    _, err = exec_command(capfd, "rapydo init")
    assert env_log_prefix_verbose in err
    assert "INFO Project initialized" in err

    # Check upstream url
    # Also check .env cache
    _, err = exec_command(capfd, "rapydo --cache-env check -s")
    log.pp(err)
    assert "INFO \u2713 Upstream is set correctly" in err
    assert env_cached_log_verbose in err
    assert "INFO All checked" in err

    out, err = exec_command(capfd, "rapydo env")
    assert env_log_prefix_verbose in err
    assert "project: template" in out

    os.remove(".projectrc")

# def test_two_projects(capfd):
    bash = BashCommands()
    bash.copy_folder("projects/template", "projects/second")

    _, err = exec_command(capfd, "rapydo -env check -s")
    e = "EXIT Please select the --project option on one of the following:"
    assert e in err
    # We can no longer test this, we have several projects and the number is
    # dyanamic... we do not want to update this list every new project...
    # assert " ['template', 'second']" in err

    _, err = exec_command(capfd, "rapydo -env -p template check -s")
    assert "INFO All checked" in err

    _, err = exec_command(capfd, "rapydo -env -p xyz check -s")
    assert "EXIT Wrong project 'xyz'." in err
    assert "Select one of the following:" in err
    assert " ['template', 'second']" in err

    # create .projectrc
    with open('.projectrc', 'w') as f:
        f.write("project: template")

    _, err = exec_command(capfd, "rapydo -env check -s")
    assert "INFO All checked" in err

# def test_from_start_to_clean(capfd):

    _, err = exec_command(capfd, "rapydo start")
    assert env_log_prefix_verbose in err
    assert compose_log_prefix + "'up'" in err
    assert "INFO Stack started" in err

    _, err = exec_command(capfd, "rapydo status")
    assert compose_log_prefix + "'ps'" in err

    exec_command(capfd, "rapydo log")
    # FIXME: how is possible that this message is not found??
    # assert compose_log_prefix + "'logs'" in err

    exec_command(capfd, "rapydo bower-install jquery")
    # FIXME: how is possible that this message is not found??
    # assert "EXIT Missing bower lib, please add the --lib option" in err
    exec_command(capfd, "rapydo bower-install --lib jquery")
    # FIXME: how is possible that this message is not found??
    # assert compose_log_prefix + "'run'" in err

    exec_command(capfd, "rapydo bower-update jquery")
    # FIXME: how is possible that this message is not found??
    # assert "EXIT Missing bower lib, please add the --lib option" in err
    exec_command(capfd, "rapydo bower-update --lib jquery")
    # FIXME: how is possible that this message is not found??
    # assert compose_log_prefix + "'run'" in err

    _, err = exec_command(capfd, "rapydo toggle-freeze")
    assert env_log_prefix_verbose in err
    assert "INFO Stack paused" in err

    _, err = exec_command(capfd, "rapydo toggle-freeze")
    assert env_log_prefix_verbose in err
    assert "INFO Stack unpaused" in err

    _, err = exec_command(capfd, "rapydo stop")
    assert env_log_prefix_verbose in err
    assert "INFO Stack stoped" in err

    _, err = exec_command(capfd, "rapydo restart")
    assert env_log_prefix_verbose in err
    assert "INFO Stack restarted" in err

    _, err = exec_command(capfd, "rapydo remove")
    assert env_log_prefix_verbose in err
    assert compose_log_prefix + "'stop'" in err
    assert "INFO Stack removed" in err

    _, err = exec_command(capfd, "rapydo clean")
    assert env_log_prefix_verbose in err
    assert "INFO Stack cleaned" in err

    endpoint_name = 'justatest'
    out, err = exec_command(capfd, "rapydo template --yes %s" % endpoint_name)
    # parsing responses like:
    # "rendered projects/template/backend/swagger/justatest/specs.yaml"
    base_response = 'DEBUG rendered %s/template/%s' % \
        (PROJECT_DIR, BACKEND_DIR)

    assert '%s/%s/%s/specs.yaml' % \
        (base_response, SWAGGER_DIR, endpoint_name) in err
    assert '%s/%s/%s/get.yaml' % \
        (base_response, SWAGGER_DIR, endpoint_name) in err
    assert '%s/%s/%s.py' % \
        (base_response, ENDPOINTS_CODE_DIR, endpoint_name) in err
    assert '%s/tests/test_%s.py' % (base_response, endpoint_name) in err
    assert 'INFO Scaffold completed' in err

    out, err = exec_command(capfd, "rapydo find --endpoint %s" % endpoint_name)
    assert "Endpoint path:\t/api/%s" % endpoint_name in err
    assert "Labels:\t\tcustom, %s" % endpoint_name in err
    assert "Python class:\t%s" % endpoint_name.capitalize() in err
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
import calendar
import datetime
import time
import unittest

from dogpile.cache import make_region
from dogpile.cache.api import NoValue

from zombase.cache import cached_property, is_valid

class TestDatabase(unittest.TestCase):

    class FakeInvalidObject(object):
        id = 2

        def __init__(self, cache):
            self.cache = cache

        @cached_property('fake:{instance.id}:dumdzae', cache='cache')
        def dummy_default(self):
            return 14

    class FakeObject(object):
        id = 1
        _keystores_kt = 'default_ksk_tpl'

        def __init__(self, cache):
            self.cache = cache

        @cached_property(
            'fake:{instance.id}:dum', keystores_kt='bli', cache='cache')
        def dummy(self):
            return 12

        @cached_property(
            'fake:{instance.id}:duml',
            keystores_kt=('bli:{instance.id}', 'blo:{instance.id}'),
            cache='cache')
        def dummy_list(self):
            return 13

        @cached_property('fake:{instance.id}:dumd', cache='cache')
        def dummy_default(self):
            return 14

    def setUp(self):
        self.cache = make_region().configure('dogpile.cache.memory')
        self.object = self.FakeObject(self.cache)

    def tearDown(self):
        del self.object
        del self.cache

    def test_simple_comput(self):
        # Result is correct
        self.assertEqual(self.object.dummy, 12)

        # Result is stored in cache
        self.assertEqual(self.cache.get('fake:1:dum'), 12)

        # Key is added to store
        self.assertEqual(self.cache.get('bli'), ['fake:1:dum'])

    def test_list_store(self):
        self.object.dummy_list

        # Key is added to store
        self.assertEqual(self.cache.get('bli:1'), ['fake:1:duml'])
        self.assertEqual(self.cache.get('blo:1'), ['fake:1:duml'])

    def test_default_key(self):
        self.object.dummy_default
        self.assertEqual(self.cache.get('default_ksk_tpl'), ['fake:1:dumd'])

    def test_absent_keystore_kt(self):
        invalid_object = self.FakeInvalidObject(self.cache)
        with self.assertRaises(ValueError):
            self.assertEqual(invalid_object.dummy_default)

    def test_invalid_keystore_kt(self):
        invalid_object = self.FakeInvalidObject(self.cache)
        setattr(invalid_object, '_keystores_kt', 2)
        with self.assertRaises(ValueError):
            self.assertEqual(invalid_object.dummy_default)

class TestValidity(unittest.TestCase):

    def test_none_validity(self):
        self.assertTrue(is_valid(None, None))

    def test_NoValue_timestamp(self):
        self.assertFalse(is_valid(NoValue(), 'same_day'))

    def test_same_day(self):
        self.assertTrue(is_valid(time.time(), 'same_day'))

        today = datetime.date.today()
        self.assertTrue(is_valid(
            calendar.timegm(today.timetuple()),
            'same_day',
        ))

        yesterday = today - datetime.timedelta(days=1)
        self.assertFalse(is_valid(
            calendar.timegm(yesterday.timetuple()),
            'same_day',
        ))

    def test_unknown_validity(self):
        with self.assertRaises(ValueError):
            is_valid(time.time(), 'same_blo')
<commit_msg>Add test<commit_after># -*- coding: utf-8 -*-
import calendar
import datetime
import time
import unittest

from dogpile.cache import make_region
from dogpile.cache.api import NoValue

from zombase.cache import cached_property, is_valid

class TestDatabase(unittest.TestCase):

    class FakeInvalidObject(object):
        id = 2

        def __init__(self, cache):
            self.cache = cache

        @cached_property('fake:{instance.id}:dumdzae', cache='cache')
        def dummy_default(self):
            return 14

    class FakeObject(object):
        id = 1
        _dummy_run = 0
        _keystores_kt = 'default_ksk_tpl'

        def __init__(self, cache):
            self.cache = cache

        @cached_property(
            'fake:{instance.id}:dum', keystores_kt='bli', cache='cache')
        def dummy(self):
            # Mesure how many times the computation has run
            self._dummy_run += 1

            return 12

        @cached_property(
            'fake:{instance.id}:duml',
            keystores_kt=('bli:{instance.id}', 'blo:{instance.id}'),
            cache='cache')
        def dummy_list(self):
            return 13

        @cached_property('fake:{instance.id}:dumd', cache='cache')
        def dummy_default(self):
            return 14

    def setUp(self):
        self.cache = make_region().configure('dogpile.cache.memory')
        self.object = self.FakeObject(self.cache)

    def tearDown(self):
        del self.object
        del self.cache

    def test_simple_comput(self):
        # Result is correct
        self.assertEqual(self.object.dummy, 12)

        # Result is stored in cache
        self.assertEqual(self.cache.get('fake:1:dum'), 12)

        # Key is added to store
        self.assertEqual(self.cache.get('bli'), ['fake:1:dum'])

    def test_list_store(self):
        self.object.dummy_list

        # Key is added to store
        self.assertEqual(self.cache.get('bli:1'), ['fake:1:duml'])
        self.assertEqual(self.cache.get('blo:1'), ['fake:1:duml'])

    def test_default_key(self):
        self.object.dummy_default
        self.assertEqual(self.cache.get('default_ksk_tpl'), ['fake:1:dumd'])

    def test_absent_keystore_kt(self):
        invalid_object = self.FakeInvalidObject(self.cache)
        with self.assertRaises(ValueError):
            self.assertEqual(invalid_object.dummy_default)

    def test_invalid_keystore_kt(self):
        invalid_object = self.FakeInvalidObject(self.cache)
        setattr(invalid_object, '_keystores_kt', 2)
        with self.assertRaises(ValueError):
            self.assertEqual(invalid_object.dummy_default)

    def test_single_run(self):
        self.assertEqual(self.object._dummy_run, 0)

        self.object.dummy
        self.assertEqual(self.object._dummy_run, 1)

        self.object.dummy
        self.assertEqual(self.object._dummy_run, 1)

class TestValidity(unittest.TestCase):

    def test_none_validity(self):
        self.assertTrue(is_valid(None, None))

    def test_NoValue_timestamp(self):
        self.assertFalse(is_valid(NoValue(), 'same_day'))

    def test_same_day(self):
        self.assertTrue(is_valid(time.time(), 'same_day'))

        today = datetime.date.today()
        self.assertTrue(is_valid(
            calendar.timegm(today.timetuple()),
            'same_day',
        ))

        yesterday = today - datetime.timedelta(days=1)
        self.assertFalse(is_valid(
            calendar.timegm(yesterday.timetuple()),
            'same_day',
        ))

    def test_unknown_validity(self):
        with self.assertRaises(ValueError):
            is_valid(time.time(), 'same_blo')
<|endoftext|>


<commit_before>"""
test_etcd3
----------------------------------

Tests for `etcd3` module.
"""

import json
import os
import subprocess

import pytest
from hypothesis import given
from hypothesis.strategies import characters
from hypothesis.strategies import text

import etcd3

os.environ['ETCDCTL_API'] = '3'

def etcdctl(*args):
    args = ['etcdctl', '-w', 'json'] + list(args)
    output = subprocess.check_output(args)
    return json.loads(output.decode('utf-8'))

class TestEtcd3(object):

    @classmethod
    def setup_class(cls):
        pass

    def test_client_stub(self):
        etcd = etcd3.client()
        assert etcd is not None

    def test_get_unknown_key(self):
        etcd = etcd3.client()
        with pytest.raises(etcd3.exceptions.KeyNotFoundError):
            etcd.get('probably-invalid-key')

    @given(characters(blacklist_categories=['Cs', 'Cc']))
    def test_get_key(self, string):
        etcdctl('put', '/doot/a_key', string)
        etcd = etcd3.client()
        returned = etcd.get('/doot/a_key')
        assert returned == string.encode('utf-8')

    @given(characters(blacklist_categories=['Cs', 'Cc']))
    def test_get_random_key(self, string):
        etcdctl('put', '/doot/' + string, 'dootdoot')
        etcd = etcd3.client()
        returned = etcd.get('/doot/' + string)
        assert returned == b'dootdoot'

    def test_put_key(self):
        etcd = etcd3.client()
        etcd.put('/doot/put_1', 'this is a doot')

    @classmethod
    def teardown_class(cls):
        etcdctl('del', '--prefix', '/doot')
<commit_msg>Test putting<commit_after>"""
test_etcd3
----------------------------------

Tests for `etcd3` module.
"""

import base64
import json
import os
import subprocess

import pytest
from hypothesis import given
from hypothesis.strategies import characters
from hypothesis.strategies import text

import etcd3

os.environ['ETCDCTL_API'] = '3'

def etcdctl(*args):
    args = ['etcdctl', '-w', 'json'] + list(args)
    output = subprocess.check_output(args)
    return json.loads(output.decode('utf-8'))

class TestEtcd3(object):

    @classmethod
    def setup_class(cls):
        pass

    def test_client_stub(self):
        etcd = etcd3.client()
        assert etcd is not None

    def test_get_unknown_key(self):
        etcd = etcd3.client()
        with pytest.raises(etcd3.exceptions.KeyNotFoundError):
            etcd.get('probably-invalid-key')

    @given(characters(blacklist_categories=['Cs', 'Cc']))
    def test_get_key(self, string):
        etcdctl('put', '/doot/a_key', string)
        etcd = etcd3.client()
        returned = etcd.get('/doot/a_key')
        assert returned == string.encode('utf-8')

    @given(characters(blacklist_categories=['Cs', 'Cc']))
    def test_get_random_key(self, string):
        etcdctl('put', '/doot/' + string, 'dootdoot')
        etcd = etcd3.client()
        returned = etcd.get('/doot/' + string)
        assert returned == b'dootdoot'

    @given(characters(blacklist_categories=['Cs', 'Cc']))
    def test_put_key(self, string):
        etcd = etcd3.client()
        etcd.put('/doot/put_1', string)
        out = etcdctl('get', '/doot/put_1')
        assert base64.b64decode(out['kvs'][0]['value']) == \
            string.encode('utf-8')

    @classmethod
    def teardown_class(cls):
        etcdctl('del', '--prefix', '/doot')
<|endoftext|>


<commit_before># coding: utf-8
import pytest

from mmvdApp.logic import Direction
from mmvdApp.logic import Robot
from mmvdApp.logic import Magazine
from mmvdApp.visualization import Visualization

@pytest.mark.frontend
def test_magazine_class():
    map_ = \
            [
                [2, 2, 2, 2, 3],
                [1, "a", 3, "b", 3],
                [1, "c", 3, "d", 3],
                [1, "e", 3, "f", 3],
                [1, 4, 4, 4, 9],
                ]
    app = Visualization(map_)
    robots = ((0, 0), (1, 1), (2, 3), (4, 2))
    app.draw_robots(robots)
    app.animate([[0, 2], [1, 2], [2, 3], [3, 3]], [["a", 3]])
    app.animate([[0, 2], [1, 3], [2, 4], [3, 3]], [["b", 0]])
    app.animate([[0, 2], [1, 3], [2, 4], [3, 4]], [["c", 0]])
    app.animate([[0, 2], [1, 3], [2, 1]], [["d", 2]])
    # new robots are given new id numbers
    app.draw_robots(robots)
    # in order to move new robots one has to use proper id
    app.animate([[4, 2], [5, 3], [6, 1]], [["d", 2]])
    app.animate([[0, 3]], [])
    app.animate([[0, 3]], [])
    app.animate([[0, 3]], [])
    app.animate([[0, 3]], [])
    app.animate([[0, 4]], [])
    app.animate([[0, 4]], [])
    app.animate([[0, 4]], [])
    app.animate([[0, 4]], [])
    app.animate([[0, 1]], [])
    app.animate([[0, 1]], [])
    app.animate([[0, 1]], [])
    app.animate([[0, 1]], [])
    app.animate([[0, 2]], [])
    app.animate([[0, 2]], [])
    app.animate([[0, 2]], [])
    app.animate([[0, 2]], [])<commit_msg>small corections<commit_after># coding: utf-8
import pytest

from mmvdApp.visualization import Visualization

@pytest.mark.frontend
def test_magazine_class():
    map_ = \
        [
            [2, 2, 2, 2, 3],
            [1, "a", 3, "b", 3],
            [1, "c", 3, "d", 3],
            [1, "e", 3, "f", 3],
            [1, 4, 4, 4, 9],
        ]
    app = Visualization(map_)
    robots = ((0, 0), (1, 1), (2, 3), (4, 2))
    app.draw_robots(robots)
    app.animate([[0, 2], [1, 2], [2, 3], [3, 3]], [["a", 3]])
    app.animate([[0, 2], [1, 3], [2, 4], [3, 3]], [["b", 0]])
    app.animate([[0, 2], [1, 3], [2, 4], [3, 4]], [["c", 0]])
    app.animate([[0, 2], [1, 3], [2, 1]], [["d", 2]])
    # new robots are given new id numbers
    app.draw_robots(robots)
    # in order to move new robots one has to use proper id
    app.animate([[4, 2], [5, 3], [6, 1]], [["d", 2]])
    app.animate([[0, 3]], [])
    app.animate([[0, 3]], [])
    app.animate([[0, 3]], [])
    app.animate([[0, 3]], [])
    app.animate([[0, 4]], [])
    app.animate([[0, 4]], [])
    app.animate([[0, 4]], [])
    app.animate([[0, 4]], [])
    app.animate([[0, 1]], [])
    app.animate([[0, 1]], [])
    app.animate([[0, 1]], [])
    app.animate([[0, 1]], [])
    app.animate([[0, 2]], [])
    app.animate([[0, 2]], [])
    app.animate([[0, 2]], [])
    app.animate([[0, 2]], [])<|endoftext|>


<commit_before>import sys
import pytest
from os import path
sys.path.append( path.dirname(path.dirname( path.abspath(__file__))))
from hosts.hosts import Hosts, HostsEntry

def test_add_single_ipv4_host(tmpdir):
    ''' add an ipv4 type entry '''
    hosts_file = tmpdir.mkdir("etc").join("hosts")
    hosts_file.write("127.0.0.1\tlocalhost")
    print hosts_file.strpath
    hosts = Hosts(path=hosts_file.strpath)
    hosts.add(force=False, entry_type='ipv4', address='123.123.123.123', names=['test.example.com'])
    counts = hosts.count(address="123.123.123.123")
    assert hosts.count(address="123.123.123.123").get('address_matches') == 1
    assert hosts.count(address="127.0.0.1").get('address_matches') == 1

def test_replace_ipv4_host_where_ip_differs(tmpdir):
    ''' replace an ipv4 entry where ip differs '''
    hosts_file = tmpdir.mkdir("etc").join("hosts")
    hosts_file.write("82.132.132.132\texample.com\texample")
    print hosts_file.strpath
    hosts_entries = Hosts(path=hosts_file.strpath)
    hosts_entries.add(force=True, entry_type='ipv4', address='82.132.132.133', names=['example.com', 'example'])
    counts = hosts_entries.count(address="82.132.132.133")
    assert counts.get('address_matches') == 1

def test_replace_ipv4_host_where_name_differs(tmpdir):
    ''' replace an ipv4 entry where name differs '''
    hosts_file = tmpdir.mkdir("etc").join("hosts")
    hosts_file.write("82.132.132.132\texample.com\texample")
    print hosts_file.strpath
    hosts_entries = Hosts(path=hosts_file.strpath)
    hosts_entries.add(force=True, entry_type='ipv4', address='82.132.132.132', names=['example2.com', 'example'])
    counts = hosts_entries.count(address="82.132.132.132", names=['example2.com', 'example'])
    assert counts.get('address_matches') == 1 and counts.get('name_matches') == 1

def test_add_single_ipv6_host(tmpdir):
    ''' add a single ipv6 host '''
    hosts_file = tmpdir.mkdir("etc").join("hosts")
    hosts_file.write("127.0.0.1\tlocalhost")
    print hosts_file.strpath
    hosts_entries = Hosts(path=hosts_file.strpath)
    hosts_entries.add(force=False, entry_type='ipv6', address='::1', names=['localhost6.localdomain6', 'localhost6'])
    assert hosts_entries.count(address="::1").get('address_matches') == 1

def test_add_single_comment(tmpdir):
    hosts_file = tmpdir.mkdir("etc").join("hosts")
    hosts_file.write("127.0.0.1\tlocalhost")
    print hosts_file.strpath
    hosts_entries = Hosts(path=hosts_file.strpath)
    hosts_entries.add(force=False, entry_type='comment', address=None, comment='this is a comment')
    assert hosts_entries.count(comment="this is a comment").get('comment_matches') == 1
<commit_msg>fix and rename tests.<commit_after>import sys
import pytest
from os import path
sys.path.append( path.dirname(path.dirname( path.abspath(__file__))))
from hosts.hosts import Hosts, HostsEntry

def test_add_single_ipv4_host_by_params(tmpdir):
    ''' add an ipv4 type entry '''
    hosts_file = tmpdir.mkdir("etc").join("hosts")
    hosts_file.write("127.0.0.1\tlocalhost")
    print hosts_file.strpath
    hosts = Hosts(path=hosts_file.strpath)
    hosts.add(force=False, entry_type='ipv4', address='123.123.123.123', names=['test.example.com'])
    assert hosts.count(address="123.123.123.123").get('address_matches') == 1
    assert hosts.count(address="127.0.0.1").get('address_matches') == 1

def test_add_single_ipv4_host_with_by_hostentry(tmpdir):
    ''' add an ipv4 type entry '''
    hosts_file = tmpdir.mkdir("etc").join("hosts")
    hosts_file.write("127.0.0.1\tlocalhost")
    hosts = Hosts(path=hosts_file.strpath)
    hosts_entry = HostsEntry(entry_type='ipv4', address='123.123.123.123', names=['test.example.com'])
    hosts.add(entry=hosts_entry, force=False)
    assert hosts.count(address="123.123.123.123").get('address_matches') == 1
    assert hosts.count(address="127.0.0.1").get('address_matches') == 1

def test_replace_ipv4_host_where_ip_differs(tmpdir):
    ''' replace an ipv4 entry where ip differs '''
    hosts_file = tmpdir.mkdir("etc").join("hosts")
    hosts_file.write("82.132.132.132\texample.com\texample")
    hosts_entries = Hosts(path=hosts_file.strpath)
    hosts_entries.add(force=True, entry_type='ipv4', address='82.132.132.133', names=['example.com', 'example'])
    counts = hosts_entries.count(address="82.132.132.133")
    assert counts.get('address_matches') == 1

def test_replace_ipv4_host_where_name_differs(tmpdir):
    ''' replace an ipv4 entry where name differs '''
    hosts_file = tmpdir.mkdir("etc").join("hosts")
    hosts_file.write("82.132.132.132\texample.com\texample")
    hosts_entries = Hosts(path=hosts_file.strpath)
    hosts_entries.add(force=True, entry_type='ipv4', address='82.132.132.132', names=['example2.com', 'example'])
    counts = hosts_entries.count(address="82.132.132.132", names=['example2.com', 'example'])
    assert counts.get('address_matches') == 1 and counts.get('name_matches') == 1

def test_add_single_ipv6_host(tmpdir):
    ''' add a single ipv6 host '''
    hosts_file = tmpdir.mkdir("etc").join("hosts")
    hosts_file.write("127.0.0.1\tlocalhost")
    hosts_entries = Hosts(path=hosts_file.strpath)
    hosts_entries.add(force=False, entry_type='ipv6', address='::1', names=['localhost6.localdomain6', 'localhost6'])
    assert hosts_entries.count(address="::1").get('address_matches') == 1

def test_add_single_comment(tmpdir):
    comment = 'this is a comment'
    hosts_file = tmpdir.mkdir("etc").join("hosts")
    hosts_file.write("")
    hosts_entries = Hosts(path=hosts_file.strpath)
    hosts_entries.add(force=False, entry_type='comment', address=None, comment=comment)
    assert hosts_entries.count(comment=comment).get('comment_matches') == 1

def test_remove_single_comment(tmpdir):
    comment = "#127.0.0.1\tlocalhost"
    hosts_file = tmpdir.mkdir("etc").join("hosts")
    hosts_file.write(comment)
    hosts_entries = Hosts(path=hosts_file.strpath)
    hosts_entries.add(HostsEntry({'comment': comment}))
    assert hosts_entries.count(comment=comment).get('comment_matches') == 1
    hosts_entries.remove(passed_comment=comment)
    assert hosts_entries.count(comment=comment).get('comment_matches') == 0
<|endoftext|>


<commit_before>from __future__ import print_function
import array
import ctypes
import fcntl
import sys
import unittest

import ioctl

try:
    import unittest.mock as mock
except ImportError:
    import mock

def _ctype_to_ptr(value):
    ptr = ctypes.byref(value)
    ptr_type = ctypes.POINTER(ctypes.c_ubyte)
    return ctypes.cast(ptr, ptr_type)

def _ctype_to_bytes(value):
    value_length = ctypes.sizeof(value)
    value_ptr = _ctype_to_ptr(value)
    return bytes(bytearray(value_ptr[0:value_length]))

class IoctlMock(mock.MagicMock):

    def __init__(self, *args, **kwargs):
        set_value = kwargs.pop('set_value', None)
        if set_value is not None:
            if isinstance(set_value, bytes):
                pass # Nothing to convert here
            elif isinstance(set_value, ctypes._SimpleCData):
                set_value = _ctype_to_bytes(set_value)
            else:
                raise TypeError('`set_value` must be a `bytes` object or a ctypes type')
        self.__dict__['_set_value'] = set_value
        super(IoctlMock, self).__init__(*args, **kwargs)

    @staticmethod
    def _arg_to_bytes(arg):
        if isinstance(arg, bytearray):
            return bytes(arg)
        elif isinstance(arg, array.array):
            return arg.tostring()
        elif isinstance(arg, int):
            return _ctype_to_bytes(ctypes.c_int(arg))
        elif isinstance(arg, ctypes._SimpleCData):
            return _ctype_to_bytes(arg)
        else:
            raise TypeError('Unhandled type of arg-parameter for ioctl: {argtype}'.format(argtype=str(type(arg))))

    def _set_arg_return(self, arg):
        set_value = self.__dict__['_set_value']
        if set_value is None:
            return # Nothing to set

        if isinstance(arg, bytearray) or isinstance(arg, array.array):
            arg_array = arg
            arg_size = len(arg)
        elif isinstance(arg, ctypes._SimpleCData):
            arg_array = _ctype_to_ptr(arg)
            arg_size = ctypes.sizeof(arg)
        else:
            raise TypeError('Unhandled type of arg-parameter for ioctl return: {argtype}'.format(argtype=str(type(arg))))

        ret_size = len(set_value)
        if arg_size != ret_size:
            raise Exception('fcntl.ioctl called with a {arg_size} byte buffer, but should have received a {ret_size} byte buffer.'.format(arg_size=arg_size, ret_size=ret_size))

        for i, v in enumerate(bytearray(set_value)):
            arg_array[i] = v

    def __call__(self, fd, op, arg=0, mutate_flag=True):
        wrapped_arg = IoctlMock._arg_to_bytes(arg)
        ret = super(IoctlMock, self).__call__(fd=fd, op=op, arg=wrapped_arg, mutate_flag=mutate_flag)
        self._set_arg_return(arg)
        return ret

class TestMain(unittest.TestCase):

    def test_ioctl_size_t(self):
        with mock.patch('fcntl.ioctl', new=IoctlMock(set_value=ctypes.c_size_t(123))) as ioctl_mock:
            ret = ioctl.ioctl_size_t(5, 7)
            self.assertEqual(ret, 123)
            kwargs = ioctl_mock.call_args[1]
            self.assertEqual(kwargs['fd'], 5)
            self.assertEqual(kwargs['op'], 7)
            self.assertEqual(len(kwargs['arg']), ctypes.sizeof(ctypes.c_size_t))
            self.assertEqual(kwargs['mutate_flag'], True)

    def test_ioctl_int(self):
        with mock.patch('fcntl.ioctl', new=IoctlMock(set_value=ctypes.c_int(123))) as ioctl_mock:
            ret = ioctl.ioctl_int(5, 7)
            self.assertEqual(ret, 123)
            kwargs = ioctl_mock.call_args[1]
            self.assertEqual(kwargs['fd'], 5)
            self.assertEqual(kwargs['op'], 7)
            self.assertEqual(len(kwargs['arg']), ctypes.sizeof(ctypes.c_int))
            self.assertEqual(kwargs['mutate_flag'], True)

    def test_ioctl_buffer_value(self):
        with mock.patch('fcntl.ioctl', new=IoctlMock(set_value=b'\x01\x02')) as ioctl_mock:
            ret = ioctl.ioctl_buffer(5, 7, value=b'\x02\x01')
            self.assertEqual(ret, b'\x01\x02')
            kwargs = ioctl_mock.call_args[1]
            self.assertEqual(kwargs['fd'], 5)
            self.assertEqual(kwargs['op'], 7)
            self.assertEqual(len(kwargs['arg']), 2)
            self.assertEqual(kwargs['mutate_flag'], True)

    def test_ioctl_buffer_length(self):
        with mock.patch('fcntl.ioctl', new=IoctlMock(set_value=b'\x01\x02')) as ioctl_mock:
            ret = ioctl.ioctl_buffer(5, 7, length=2)
            self.assertEqual(ret, b'\x01\x02')
            kwargs = ioctl_mock.call_args[1]
            self.assertEqual(kwargs['fd'], 5)
            self.assertEqual(kwargs['op'], 7)
            self.assertEqual(len(kwargs['arg']), 2)
            self.assertEqual(kwargs['mutate_flag'], True)

if __name__ == '__main__':
    unittest.main()
<commit_msg>tests: Remove print_function compatibility.<commit_after>import array
import ctypes
import fcntl
import sys
import unittest

import ioctl

try:
    import unittest.mock as mock
except ImportError:
    import mock

def _ctype_to_ptr(value):
    ptr = ctypes.byref(value)
    ptr_type = ctypes.POINTER(ctypes.c_ubyte)
    return ctypes.cast(ptr, ptr_type)

def _ctype_to_bytes(value):
    value_length = ctypes.sizeof(value)
    value_ptr = _ctype_to_ptr(value)
    return bytes(bytearray(value_ptr[0:value_length]))

class IoctlMock(mock.MagicMock):

    def __init__(self, *args, **kwargs):
        set_value = kwargs.pop('set_value', None)
        if set_value is not None:
            if isinstance(set_value, bytes):
                pass # Nothing to convert here
            elif isinstance(set_value, ctypes._SimpleCData):
                set_value = _ctype_to_bytes(set_value)
            else:
                raise TypeError('`set_value` must be a `bytes` object or a ctypes type')
        self.__dict__['_set_value'] = set_value
        super(IoctlMock, self).__init__(*args, **kwargs)

    @staticmethod
    def _arg_to_bytes(arg):
        if isinstance(arg, bytearray):
            return bytes(arg)
        elif isinstance(arg, array.array):
            return arg.tostring()
        elif isinstance(arg, int):
            return _ctype_to_bytes(ctypes.c_int(arg))
        elif isinstance(arg, ctypes._SimpleCData):
            return _ctype_to_bytes(arg)
        else:
            raise TypeError('Unhandled type of arg-parameter for ioctl: {argtype}'.format(argtype=str(type(arg))))

    def _set_arg_return(self, arg):
        set_value = self.__dict__['_set_value']
        if set_value is None:
            return # Nothing to set

        if isinstance(arg, bytearray) or isinstance(arg, array.array):
            arg_array = arg
            arg_size = len(arg)
        elif isinstance(arg, ctypes._SimpleCData):
            arg_array = _ctype_to_ptr(arg)
            arg_size = ctypes.sizeof(arg)
        else:
            raise TypeError('Unhandled type of arg-parameter for ioctl return: {argtype}'.format(argtype=str(type(arg))))

        ret_size = len(set_value)
        if arg_size != ret_size:
            raise Exception('fcntl.ioctl called with a {arg_size} byte buffer, but should have received a {ret_size} byte buffer.'.format(arg_size=arg_size, ret_size=ret_size))

        for i, v in enumerate(bytearray(set_value)):
            arg_array[i] = v

    def __call__(self, fd, op, arg=0, mutate_flag=True):
        wrapped_arg = IoctlMock._arg_to_bytes(arg)
        ret = super(IoctlMock, self).__call__(fd=fd, op=op, arg=wrapped_arg, mutate_flag=mutate_flag)
        self._set_arg_return(arg)
        return ret

class TestMain(unittest.TestCase):

    def test_ioctl_size_t(self):
        with mock.patch('fcntl.ioctl', new=IoctlMock(set_value=ctypes.c_size_t(123))) as ioctl_mock:
            ret = ioctl.ioctl_size_t(5, 7)
            self.assertEqual(ret, 123)
            kwargs = ioctl_mock.call_args[1]
            self.assertEqual(kwargs['fd'], 5)
            self.assertEqual(kwargs['op'], 7)
            self.assertEqual(len(kwargs['arg']), ctypes.sizeof(ctypes.c_size_t))
            self.assertEqual(kwargs['mutate_flag'], True)

    def test_ioctl_int(self):
        with mock.patch('fcntl.ioctl', new=IoctlMock(set_value=ctypes.c_int(123))) as ioctl_mock:
            ret = ioctl.ioctl_int(5, 7)
            self.assertEqual(ret, 123)
            kwargs = ioctl_mock.call_args[1]
            self.assertEqual(kwargs['fd'], 5)
            self.assertEqual(kwargs['op'], 7)
            self.assertEqual(len(kwargs['arg']), ctypes.sizeof(ctypes.c_int))
            self.assertEqual(kwargs['mutate_flag'], True)

    def test_ioctl_buffer_value(self):
        with mock.patch('fcntl.ioctl', new=IoctlMock(set_value=b'\x01\x02')) as ioctl_mock:
            ret = ioctl.ioctl_buffer(5, 7, value=b'\x02\x01')
            self.assertEqual(ret, b'\x01\x02')
            kwargs = ioctl_mock.call_args[1]
            self.assertEqual(kwargs['fd'], 5)
            self.assertEqual(kwargs['op'], 7)
            self.assertEqual(len(kwargs['arg']), 2)
            self.assertEqual(kwargs['mutate_flag'], True)

    def test_ioctl_buffer_length(self):
        with mock.patch('fcntl.ioctl', new=IoctlMock(set_value=b'\x01\x02')) as ioctl_mock:
            ret = ioctl.ioctl_buffer(5, 7, length=2)
            self.assertEqual(ret, b'\x01\x02')
            kwargs = ioctl_mock.call_args[1]
            self.assertEqual(kwargs['fd'], 5)
            self.assertEqual(kwargs['op'], 7)
            self.assertEqual(len(kwargs['arg']), 2)
            self.assertEqual(kwargs['mutate_flag'], True)

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


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

import os
import io
import pycdlib
import tempfile
import unittest

from six.moves import filterfalse
from six.moves.queue import Queue

import fs.test
import fs.wrap
import fs.errors
import fs.memoryfs
import fs.archive.isofs

from fs.path import relpath, join, forcedir, abspath, recursepath
from fs.archive.test import ArchiveReadTestCases, ArchiveIOTestCases
from fs.archive.isofs import _utils

def compress(rr, joliet, il):
    def iso_compress(handle, source_fs):
        if hasattr(handle, 'seek') and handle.seekable():
            handle.seek(0)
        saver = fs.archive.isofs.ISOSaver(
            handle, overwrite=False,
            rock_ridge=rr, joliet=joliet,
            interchange_level=il
        )
        saver.save(source_fs)
    return iso_compress

def iso_name(entry, joliet=False, rock_ridge=False):
    if entry.file_identifier() in b'/':
        return '/'
    elif rock_ridge:
        return entry.rock_ridge.name().decode('utf-8').rsplit(';1').rsplit('.')
    elif joliet:
        return entry.file_identifier().decode('utf-16be')
    return entry.file_identifier().decode('ascii')

def iso_path(iso_entry, joliet=False, rock_ridge=False):
    path = iso_name(iso_entry, joliet, rock_ridge)
    while iso_entry.parent is not None:
        path = join(iso_name(iso_entry.parent, joliet, rock_ridge), path)
        iso_entry = iso_entry.parent
    return abspath(path).lower()

### rw FS ###

class TestISOFS(fs.test.FSTestCases, unittest.TestCase):

    def make_fs(self):
        self.tempfile = tempfile.mktemp()
        return fs.archive.isofs.ISOFS(self.tempfile)

    def destroy_fs(self, fs):
        fs.close()
        if os.path.exists(self.tempfile):
            os.remove(self.tempfile)
        del self.tempfile

### ro FS ###

class _TestISOReadFS(ArchiveReadTestCases):

    long_names = False
    unicode_names = False
    make_source_fs = staticmethod(fs.memoryfs.MemoryFS)
    _archive_read_fs = fs.archive.isofs.ISOReadFS

    @staticmethod
    def remove_archive(handle):
        handle.close()

    def setUp(self):
        handle = io.BytesIO()
        super(_TestISOReadFS, self).setUp(handle)

    def test_create_failed(self):
        self.assertRaises(fs.errors.CreateFailed, fs.archive.isofs.ISOFS, 1)

class TestISOv1ReadFS(_TestISOReadFS, unittest.TestCase):

    compress = staticmethod(compress(None, False, 1))

class TestISOv2ReadFS(_TestISOReadFS, unittest.TestCase):

    compress = staticmethod(compress(None, False, 2))

class TestISOv3ReadFS(_TestISOReadFS, unittest.TestCase):

    compress = staticmethod(compress(None, False, 3))

class TestISOv4ReadFS(_TestISOReadFS, unittest.TestCase):

    compress = staticmethod(compress(None, False, 4))

@unittest.skip('fails')
class TestISORockRidge112ReadFS(_TestISOReadFS, unittest.TestCase):

    long_names = True
    compress = staticmethod(compress('1.12', False, 1))

class TestISORockRidge109ReadFS(_TestISOReadFS, unittest.TestCase):

    long_names = True
    compress = staticmethod(compress('1.09', False, 1))

class TestISOJolietReadFS(_TestISOReadFS, unittest.TestCase):

    long_name = True
    compress = staticmethod(compress(None, True, 1))

### FS IO ###

class TestISOFSio(ArchiveIOTestCases, unittest.TestCase):

    compress = staticmethod(compress('1.12', False, 1))
    make_source_fs = staticmethod(fs.memoryfs.MemoryFS)
    _archive_fs = fs.archive.isofs.ISOFS

    @staticmethod
    def load_archive(handle):
        return fs.archive.isofs.ISOFS(handle)

    @staticmethod
    def iter_entries(handle):

        cd = pycdlib.PyCdlib()

        if hasattr(handle, 'seek') and handle.seekable():
            handle.seek(0)
            cd.open_fp(handle)
        else:
            cd.open(handle)

        rock_ridge = cd.rock_ridge is not None
        joliet = cd.joliet_vd is not None
        joliet_only = joliet and not rock_ridge

        directories = Queue()
        directories.put(cd.get_entry('/', joliet_only))

        while not directories.empty():
            directory = directories.get()

            for child in directory.children:
                if not child.is_dot() and not child.is_dotdot():
                    if child.is_dir():
                        directories.put(child)
                    yield child

    def iter_files(self, handle):
        for entry in self.iter_entries(handle):
            if entry.is_file():
                yield iso_path(entry)

    def iter_dirs(self, handle):
        for entry in self.iter_entries(handle):
            if entry.is_dir():
                yield iso_path(entry)

### FS Saver ###

class TestISOSaver(unittest.TestCase):

    make_source_fs = staticmethod(fs.memoryfs.MemoryFS)

    def test_unicode_duplicates(self):
        """Check unicode names are not collisioning when slugified.
        """
        source = self.make_source_fs()
        source.makedir('/😋')
        source.settext('/😋/éé.txt', 'some accents in an emoji')
        source.settext('/éé.txt', 'some accents')
        source.settext('/üü.txt', 'some umlauts')
        source.settext('/☭☭.txt', 'some communism')

        stream = io.BytesIO()
        saver = fs.archive.isofs.ISOSaver(stream)
        saver.save(source)

        stream.seek(0)
        iso = fs.archive.isofs.ISOReadFS(stream)
        self.assertEqual(
            sorted(iso.listdir('/')),
            ['éé.txt', 'üü.txt' ,'☭☭.txt', '😋'],
        )
        self.assertEqual(iso.gettext('/éé.txt'), 'some accents')
        self.assertEqual(iso.gettext('/üü.txt'), 'some umlauts')
        self.assertEqual(iso.gettext('/☭☭.txt'), 'some communism')
        self.assertEqual(iso.gettext('/😋/éé.txt'), 'some accents in an emoji')

### utils ###

class TestISOUtils(unittest.TestCase):

    def test_name_slugify(self):
        slugify = _utils.iso_name_slugify
        self.assertEqual(slugify("épatant"), "_patant")

    def test_name_increment(self):
        increment = _utils.iso_name_increment
        self.assertEqual(increment('foo.txt'), 'foo1.txt')
        self.assertEqual(increment('foo1.txt'), 'foo2.txt')
        self.assertEqual(increment('foo9.txt'), 'foo10.txt')
        self.assertEqual(increment('foo9.txt', max_length=4), 'fo10.txt')
        self.assertEqual(increment('bar'), 'bar1')
        self.assertEqual(increment('bar1'), 'bar2')
        self.assertEqual(increment('bar9'), 'bar10')
        self.assertEqual(increment('bar9', max_length=4), 'ba10')

    def test_path_slugify(self):
        slugify = _utils.iso_path_slugify
        pt = {'/': '/'}
        self.assertEqual(slugify('/abc.txt', pt), '/ABC.TXT')
        self.assertEqual(slugify('/àbc.txt', pt), '/_BC.TXT')
        self.assertEqual(slugify('/àbç.txt', pt), '/_B_.TXT')
        self.assertEqual(slugify('/àbé.txt', pt), '/_B_1.TXT')
        self.assertEqual(slugify('/àbé.txt', pt, True), '/_B_.TXT1')
        self.assertEqual(slugify('/àbè.txt', pt, True), '/_B_.TXT2')
<commit_msg>Skip `tests.test_isofs` if `pycdlib` is not available<commit_after># coding: utf-8
from __future__ import absolute_import
from __future__ import unicode_literals

import os
import io
import tempfile
import unittest

from six.moves import filterfalse
from six.moves.queue import Queue

import fs.test
import fs.wrap
import fs.errors
import fs.memoryfs

from fs.path import relpath, join, forcedir, abspath, recursepath
from fs.archive.test import ArchiveReadTestCases, ArchiveIOTestCases

try:
    import pycdlib
except ImportError:
    pycdlib = None

try:
    from fs.archive.isofs import ISOReadFS, ISOFS, ISOSaver
    from fs.archive.isofs import _utils as isofs_utils
except ImportError:
    SevenZipReadFS = SevenZipFS = SevenZipSaver = None
    isofs_utils = None

def compress(rr, joliet, il):
    def iso_compress(handle, source_fs):
        if hasattr(handle, 'seek') and handle.seekable():
            handle.seek(0)
        saver = fs.archive.isofs.ISOSaver(
            handle, overwrite=False,
            rock_ridge=rr, joliet=joliet,
            interchange_level=il
        )
        saver.save(source_fs)
    return iso_compress

def iso_name(entry, joliet=False, rock_ridge=False):
    if entry.file_identifier() in b'/':
        return '/'
    elif rock_ridge:
        return entry.rock_ridge.name().decode('utf-8').rsplit(';1').rsplit('.')
    elif joliet:
        return entry.file_identifier().decode('utf-16be')
    return entry.file_identifier().decode('ascii')

def iso_path(iso_entry, joliet=False, rock_ridge=False):
    path = iso_name(iso_entry, joliet, rock_ridge)
    while iso_entry.parent is not None:
        path = join(iso_name(iso_entry.parent, joliet, rock_ridge), path)
        iso_entry = iso_entry.parent
    return abspath(path).lower()

### rw FS ###

@unittest.skipUnless(pycdlib, 'pycdlib not available')
class TestISOFS(fs.test.FSTestCases, unittest.TestCase):

    def make_fs(self):
        self.tempfile = tempfile.mktemp()
        return ISOFS(self.tempfile)

    def destroy_fs(self, fs):
        fs.close()
        if os.path.exists(self.tempfile):
            os.remove(self.tempfile)
        del self.tempfile

### ro FS ###

@unittest.skipUnless(pycdlib, 'pycdlib not available')
class _TestISOReadFS(ArchiveReadTestCases):

    long_names = False
    unicode_names = False
    make_source_fs = staticmethod(fs.memoryfs.MemoryFS)
    _archive_read_fs = ISOReadFS

    @staticmethod
    def remove_archive(handle):
        handle.close()

    def setUp(self):
        handle = io.BytesIO()
        super(_TestISOReadFS, self).setUp(handle)

    def test_create_failed(self):
        self.assertRaises(fs.errors.CreateFailed, ISOFS, 1)

class TestISOv1ReadFS(_TestISOReadFS, unittest.TestCase):

    compress = staticmethod(compress(None, False, 1))

class TestISOv2ReadFS(_TestISOReadFS, unittest.TestCase):

    compress = staticmethod(compress(None, False, 2))

class TestISOv3ReadFS(_TestISOReadFS, unittest.TestCase):

    compress = staticmethod(compress(None, False, 3))

class TestISOv4ReadFS(_TestISOReadFS, unittest.TestCase):

    compress = staticmethod(compress(None, False, 4))

@unittest.skip('fails')
class TestISORockRidge112ReadFS(_TestISOReadFS, unittest.TestCase):

    long_names = True
    compress = staticmethod(compress('1.12', False, 1))

class TestISORockRidge109ReadFS(_TestISOReadFS, unittest.TestCase):

    long_names = True
    compress = staticmethod(compress('1.09', False, 1))

class TestISOJolietReadFS(_TestISOReadFS, unittest.TestCase):

    long_name = True
    compress = staticmethod(compress(None, True, 1))

### FS IO ###

@unittest.skipUnless(pycdlib, 'pycdlib not available')
class TestISOFSio(ArchiveIOTestCases, unittest.TestCase):

    compress = staticmethod(compress('1.12', False, 1))
    make_source_fs = staticmethod(fs.memoryfs.MemoryFS)
    _archive_fs = ISOFS

    @staticmethod
    def load_archive(handle):
        return ISOFS(handle)

    @staticmethod
    def iter_entries(handle):

        cd = pycdlib.PyCdlib()

        if hasattr(handle, 'seek') and handle.seekable():
            handle.seek(0)
            cd.open_fp(handle)
        else:
            cd.open(handle)

        rock_ridge = cd.rock_ridge is not None
        joliet = cd.joliet_vd is not None
        joliet_only = joliet and not rock_ridge

        directories = Queue()
        directories.put(cd.get_entry('/', joliet_only))

        while not directories.empty():
            directory = directories.get()

            for child in directory.children:
                if not child.is_dot() and not child.is_dotdot():
                    if child.is_dir():
                        directories.put(child)
                    yield child

    def iter_files(self, handle):
        for entry in self.iter_entries(handle):
            if entry.is_file():
                yield iso_path(entry)

    def iter_dirs(self, handle):
        for entry in self.iter_entries(handle):
            if entry.is_dir():
                yield iso_path(entry)

### FS Saver ###

@unittest.skipUnless(pycdlib, 'pycdlib not available')
class TestISOSaver(unittest.TestCase):

    make_source_fs = staticmethod(fs.memoryfs.MemoryFS)

    def test_unicode_duplicates(self):
        """Check unicode names are not collisioning when slugified.
        """
        source = self.make_source_fs()
        source.makedir('/😋')
        source.settext('/😋/éé.txt', 'some accents in an emoji')
        source.settext('/éé.txt', 'some accents')
        source.settext('/üü.txt', 'some umlauts')
        source.settext('/☭☭.txt', 'some communism')

        stream = io.BytesIO()
        saver = ISOSaver(stream)
        saver.save(source)

        stream.seek(0)
        iso = ISOReadFS(stream)
        self.assertEqual(
            sorted(iso.listdir('/')),
            ['éé.txt', 'üü.txt' ,'☭☭.txt', '😋'],
        )
        self.assertEqual(iso.gettext('/éé.txt'), 'some accents')
        self.assertEqual(iso.gettext('/üü.txt'), 'some umlauts')
        self.assertEqual(iso.gettext('/☭☭.txt'), 'some communism')
        self.assertEqual(iso.gettext('/😋/éé.txt'), 'some accents in an emoji')

### utils ###

@unittest.skipUnless(isofs_utils, 'fs.archive.isofs not available')
class TestISOUtils(unittest.TestCase):

    def test_name_slugify(self):
        slugify = isofs_utils.iso_name_slugify
        self.assertEqual(slugify("épatant"), "_patant")

    def test_name_increment(self):
        increment = isofs_utils.iso_name_increment
        self.assertEqual(increment('foo.txt'), 'foo1.txt')
        self.assertEqual(increment('foo1.txt'), 'foo2.txt')
        self.assertEqual(increment('foo9.txt'), 'foo10.txt')
        self.assertEqual(increment('foo9.txt', max_length=4), 'fo10.txt')
        self.assertEqual(increment('bar'), 'bar1')
        self.assertEqual(increment('bar1'), 'bar2')
        self.assertEqual(increment('bar9'), 'bar10')
        self.assertEqual(increment('bar9', max_length=4), 'ba10')

    def test_path_slugify(self):
        slugify = isofs_utils.iso_path_slugify
        pt = {'/': '/'}
        self.assertEqual(slugify('/abc.txt', pt), '/ABC.TXT')
        self.assertEqual(slugify('/àbc.txt', pt), '/_BC.TXT')
        self.assertEqual(slugify('/àbç.txt', pt), '/_B_.TXT')
        self.assertEqual(slugify('/àbé.txt', pt), '/_B_1.TXT')
        self.assertEqual(slugify('/àbé.txt', pt, True), '/_B_.TXT1')
        self.assertEqual(slugify('/àbè.txt', pt, True), '/_B_.TXT2')
<|endoftext|>


<commit_before>from pdf2jpg import pdf2jpg
from cropJPG import cropJPG
from mergeReport import mergeReport

__author__ = 'daniel'

def main():
    pdf2jpg()
    cropJPG()
    mergeReport()

    print "DONE"

if __name__ == "__main__":
    main()<commit_msg>Adds jpg2docx<commit_after>from pdf2jpg import pdf2jpg
from cropJPG import cropJPG
from mergeReport import mergeReport
from jpg2docx import jpg2docx

__author__ = 'daniel'

def main():
    pdf2jpg()
    cropJPG()
    mergeReport()
    jpg2docx()

    print "DONE"

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


<commit_before>import unittest

import pandas as pd

from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import RMSprop
from keras.utils.np_utils import to_categorical

class TestKeras(unittest.TestCase):
    def test_train(self):
        train = pd.read_csv("/input/tests/data/train.csv")

        x_train = train.iloc[:,1:].values.astype('float32')
        y_train = to_categorical(train.iloc[:,0].astype('int32'))

        model = Sequential()
        model.add(Dense(units=10, input_dim=784, activation='softmax'))

        model.compile(
            loss='categorical_crossentropy',
            optimizer=RMSprop(lr=0.001),
            metrics=['accuracy'])

        model.fit(x_train, y_train, epochs=1, batch_size=32)
<commit_msg>Expand keras tests to cover conv net<commit_after>import unittest

import numpy as np
import pandas as pd

from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
from keras.optimizers import RMSprop, SGD
from keras.utils.np_utils import to_categorical

class TestKeras(unittest.TestCase):
    def test_train(self):
        train = pd.read_csv("/input/tests/data/train.csv")

        x_train = train.iloc[:,1:].values.astype('float32')
        y_train = to_categorical(train.iloc[:,0].astype('int32'))

        model = Sequential()
        model.add(Dense(units=10, input_dim=784, activation='softmax'))

        model.compile(
            loss='categorical_crossentropy',
            optimizer=RMSprop(lr=0.001),
            metrics=['accuracy'])

        model.fit(x_train, y_train, epochs=1, batch_size=32)

    def test_conv2d(self):
        # Generate dummy data
        x_train = np.random.random((100, 100, 100, 3))
        y_train = keras.utils.to_categorical(np.random.randint(10, size=(100, 1)), num_classes=10)
        x_test = np.random.random((20, 100, 100, 3))
        y_test = keras.utils.to_categorical(np.random.randint(10, size=(20, 1)), num_classes=10)

        model = Sequential()
        # input: 100x100 images with 3 channels -> (100, 100, 3) tensors.
        # this applies 32 convolution filters of size 3x3 each.
        model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(100, 100, 3)))
        model.add(Conv2D(32, (3, 3), activation='relu'))
        model.add(MaxPooling2D(pool_size=(2, 2)))
        model.add(Dropout(0.25))

        model.add(Conv2D(64, (3, 3), activation='relu'))
        model.add(Conv2D(64, (3, 3), activation='relu'))
        model.add(MaxPooling2D(pool_size=(2, 2)))
        model.add(Dropout(0.25))

        model.add(Flatten())
        model.add(Dense(256, activation='relu'))
        model.add(Dropout(0.5))
        model.add(Dense(10, activation='softmax'))

        sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
        model.compile(loss='categorical_crossentropy', optimizer=sgd)

        model.fit(x_train, y_train, batch_size=32, epochs=1)
        score = model.evaluate(x_test, y_test, batch_size=32)
<|endoftext|>


<commit_before>import viper.lexer as vl

import pytest

from typing import List, Type

###############################################################################
#
# INDIVIDUAL TOKENS
#
###############################################################################

def _test_single_token(token: str, lexeme_type: Type):
    lexemes = vl.Lexer.lex_token(token)
    assert len(lexemes) == 1
    assert lexemes[0] == lexeme_type(token)

def _test_bad_single_token(token: str, intended_type: Type):
    try:
        _test_single_token(token, intended_type)
    except AssertionError:
        assert True
    except vl.LexerError:
        assert True

# COMMA

def test_comma():
    lexemes = vl.Lexer.lex_token(',')
    assert len(lexemes) == 1
    assert lexemes[0] == vl.COMMA

# NUMBER

@pytest.mark.parametrize('token', [
    '42',
    '.42', '.42e8', '.42E8', '.42e+8', '.42E+8', '.42e-8', '.42E-8',
    '42e8', '42E8', '42e+8', '42E+8', '42e-8', '42E-8',
    '42.', '42.e8', '42.E8', '42.e+8', '42.E+8', '42.e-8', '42.E-8',
    '4.2', '4.2e8', '4.2E8', '4.2e+8', '4.2E+8', '4.2e-8', '4.2E-8',
])
def test_number(token: str):
    _test_single_token(token, vl.Number)

@pytest.mark.parametrize('token', [
    '42e', '42E', '42e+', '42E+', '42e-', '42E-',
    '42.e', '42.E', '42.e+', '42.E+', '42.e-', '42.E-',
    '4.2e', '4.2E', '4.2e+', '4.2E+', '4.2e-', '4.2E-',
])
def test_bad_number(token: str):
    _test_bad_single_token(token, vl.Number)

# NAME

@pytest.mark.parametrize('token', [
    '_', '__', '___',
    'a', '_a', 'aa', 'aA', 'a1',
    'a-b-c', 'a-B-C', 'a1-b2-c3',
    'a!', 'a@', 'a$', 'a%', 'a^', 'a&', 'a*', 'a?',
])
def test_name(token: str):
    _test_single_token(token, vl.Name)

@pytest.mark.parametrize('token', [
    'A', 'AB', '-a', 'a-', 'a-b-', 'a-?', 'a?!', '42', '42e3', '?', '?!',
])
def test_bad_name(token: str):
    _test_bad_single_token(token, vl.Name)

# CLASS

@pytest.mark.parametrize('token', [
    'A', 'AB', 'AThing', 'AnotherThing', 'A-Thing', 'Another-Thing', 'Plan9', 'Plan-9-From-Outer-Space',
])
def test_class(token: str):
    _test_single_token(token, vl.Class)

@pytest.mark.parametrize('token', [
    'a-class', 'a_class', 'aA', '9', '9a', '!?',
])
def test_bad_class(token: str):
    _test_bad_single_token(token, vl.Class)

# OPERATOR

@pytest.mark.parametrize('token', [
    '!', '@', '$', '%', '^', '&', '*', '(', ')', '-', '=', '+', '|', ':', '/', '?', '<', '>',
    '[', ']', '{', '}', '~',
    '!@', '<>', '::',
    '()', '(()', '()()', '())', '(())',
])
def test_operator(token: str):
    _test_single_token(token, vl.Operator)

@pytest.mark.parametrize('token', [
    'a', 'A', 'aA', 'AA', 'Aa', 'aa', '(42)',
])
def test_bad_operator(token: str):
    _test_bad_single_token(token, vl.Operator)

###############################################################################
#
# LEXING LINES
#
###############################################################################

# INDENTATION

@pytest.mark.parametrize('levels', [
    0, 1, 2, 3, 4,
])
def test_indentation(levels: int):
    line = ''.join(' ' * vl.INDENT_SIZE for _ in range(levels))
    correct = [vl.INDENT for _ in range(levels)]
    assert vl.lex_line(line) == correct

@pytest.mark.parametrize('line,indent_count', [
    ('none', 0),
    ('    one', 1),
    ('        two', 2),
    ('     one plus space', 1),
])
def test_leading_indentation(line: str, indent_count: int):
    lexemes = vl.lex_line(line)
    assert len(lexemes) >= indent_count
    indents = lexemes[:indent_count]
    rest = lexemes[indent_count:]
    for indent in indents:
        assert indent == vl.INDENT
    if rest:
        assert rest[0] != vl.INDENT

# OPERATORS

@pytest.mark.parametrize('line,correct_lexemes', [
    ('foo+',
     [vl.Name('foo'), vl.Operator('+')]),
    ('+foo',
     [vl.Operator('+'), vl.Name('foo')]),
    ('foo+bar',
     [vl.Name('foo'), vl.Operator('+'), vl.Name('bar')]),
    ('foo(bar)',
     [vl.Name('foo'), vl.Operator('('), vl.Name('bar'), vl.Operator(')')]),
    ('foo()bar',
     [vl.Name('foo'), vl.Operator('('), vl.Operator(')'), vl.Name('bar')]),
    ('foo?bar',
     [vl.Name('foo'), vl.Operator('?'), vl.Name('bar')]),
    ('foo?!bar',
     [vl.Name('foo?'), vl.Operator('!'), vl.Name('bar')]),
])
def test_infix_ops(line: str, correct_lexemes: List[vl.Lexeme]):
    assert vl.lex_line(line) == correct_lexemes

# COMMAS

@pytest.mark.parametrize('line,correct_lexemes', [
    (',',
     [vl.COMMA]),
    ('foo,',
     [vl.Name('foo'), vl.COMMA]),
    ('foo,bar',
     [vl.Name('foo'), vl.COMMA, vl.Name('bar')]),
    ('foo, bar ,baz',
     [vl.Name('foo'), vl.COMMA, vl.Name('bar'), vl.COMMA, vl.Name('baz')]),
    ('foo(bar, baz)',
     [vl.Name('foo'), vl.Operator('('), vl.Name('bar'), vl.COMMA, vl.Name('baz'), vl.Operator(')')]),
    ('foo(bar,)',
     [vl.Name('foo'), vl.Operator('('), vl.Name('bar'), vl.COMMA, vl.Operator(')')]),
])
def test_commas(line: str, correct_lexemes: List[vl.Lexeme]):
    assert vl.lex_line(line) == correct_lexemes

###############################################################################
#
# LEXING TEXT
#
###############################################################################

# MULTI-LINE LEXING

@pytest.mark.parametrize('text,correct_lexemes', [
    ('\n'.join((
            'def foo(arg):',
            '    return bar()')),
     [vl.Name('def'), vl.Name('foo'), vl.Operator('('), vl.Name('arg'), vl.Operator(')'), vl.Operator(':'),
      vl.NEWLINE,
      vl.INDENT, vl.Name('return'), vl.Name('bar'), vl.Operator('('), vl.Operator(')'),
      vl.NEWLINE]
    ),
    ('\n'.join((
            'def foo(arg1, arg2):',
            '    return bar(arg1, arg2,)')),
     [vl.Name('def'), vl.Name('foo'), vl.Operator('('), vl.Name('arg1'), vl.COMMA, vl.Name('arg2'), vl.Operator(')'),
      vl.Operator(':'), vl.NEWLINE,
      vl.INDENT, vl.Name('return'), vl.Name('bar'), vl.Operator('('), vl.Name('arg1'), vl.COMMA, vl.Name('arg2'),
      vl.COMMA, vl.Operator(')'), vl.NEWLINE]
    ),
])
def test_multiple_lines(text: str, correct_lexemes: List[vl.Lexeme]):
    assert vl.Lexer.lex(text) == correct_lexemes

###############################################################################
#
# MISCELLANY
#
###############################################################################

# LEXEMES

def test_lexemes():
    assert vl.Name('foo') == vl.Name('foo')
    assert vl.Indent() == vl.INDENT
    assert str(vl.Name('foo')) == 'foo'
    assert repr(vl.Name('foo')) == 'Name(foo)'
    assert repr(vl.INDENT) == 'Indent'
<commit_msg>Fix minor PEP8 issues in lexer tests<commit_after>import viper.lexer as vl

import pytest

from typing import List, Type

###############################################################################
#
# INDIVIDUAL TOKENS
#
###############################################################################

def _test_single_token(token: str, lexeme_type: Type):
    lexemes = vl.Lexer.lex_token(token)
    assert len(lexemes) == 1
    assert lexemes[0] == lexeme_type(token)

def _test_bad_single_token(token: str, intended_type: Type):
    try:
        _test_single_token(token, intended_type)
    except AssertionError:
        assert True
    except vl.LexerError:
        assert True

# COMMA

def test_comma():
    lexemes = vl.Lexer.lex_token(',')
    assert len(lexemes) == 1
    assert lexemes[0] == vl.COMMA

# NUMBER

@pytest.mark.parametrize('token', [
    '42',
    '.42', '.42e8', '.42E8', '.42e+8', '.42E+8', '.42e-8', '.42E-8',
    '42e8', '42E8', '42e+8', '42E+8', '42e-8', '42E-8',
    '42.', '42.e8', '42.E8', '42.e+8', '42.E+8', '42.e-8', '42.E-8',
    '4.2', '4.2e8', '4.2E8', '4.2e+8', '4.2E+8', '4.2e-8', '4.2E-8',
])
def test_number(token: str):
    _test_single_token(token, vl.Number)

@pytest.mark.parametrize('token', [
    '42e', '42E', '42e+', '42E+', '42e-', '42E-',
    '42.e', '42.E', '42.e+', '42.E+', '42.e-', '42.E-',
    '4.2e', '4.2E', '4.2e+', '4.2E+', '4.2e-', '4.2E-',
])
def test_bad_number(token: str):
    _test_bad_single_token(token, vl.Number)

# NAME

@pytest.mark.parametrize('token', [
    '_', '__', '___',
    'a', '_a', 'aa', 'aA', 'a1',
    'a-b-c', 'a-B-C', 'a1-b2-c3',
    'a!', 'a@', 'a$', 'a%', 'a^', 'a&', 'a*', 'a?',
])
def test_name(token: str):
    _test_single_token(token, vl.Name)

@pytest.mark.parametrize('token', [
    'A', 'AB', '-a', 'a-', 'a-b-', 'a-?', 'a?!', '42', '42e3', '?', '?!',
])
def test_bad_name(token: str):
    _test_bad_single_token(token, vl.Name)

# CLASS

@pytest.mark.parametrize('token', [
    'A', 'AB', 'AThing', 'AnotherThing', 'A-Thing', 'Another-Thing', 'Plan9', 'Plan-9-From-Outer-Space',
])
def test_class(token: str):
    _test_single_token(token, vl.Class)

@pytest.mark.parametrize('token', [
    'a-class', 'a_class', 'aA', '9', '9a', '!?',
])
def test_bad_class(token: str):
    _test_bad_single_token(token, vl.Class)

# OPERATOR

@pytest.mark.parametrize('token', [
    '!', '@', '$', '%', '^', '&', '*', '(', ')', '-', '=', '+', '|', ':', '/', '?', '<', '>',
    '[', ']', '{', '}', '~',
    '!@', '<>', '::',
    '()', '(()', '()()', '())', '(())',
])
def test_operator(token: str):
    _test_single_token(token, vl.Operator)

@pytest.mark.parametrize('token', [
    'a', 'A', 'aA', 'AA', 'Aa', 'aa', '(42)',
])
def test_bad_operator(token: str):
    _test_bad_single_token(token, vl.Operator)

###############################################################################
#
# LEXING LINES
#
###############################################################################

# INDENTATION

@pytest.mark.parametrize('levels', [
    0, 1, 2, 3, 4,
])
def test_indentation(levels: int):
    line = ''.join(' ' * vl.INDENT_SIZE for _ in range(levels))
    correct = [vl.INDENT for _ in range(levels)]
    assert vl.lex_line(line) == correct

@pytest.mark.parametrize('line,indent_count', [
    ('none', 0),
    ('    one', 1),
    ('        two', 2),
    ('     one plus space', 1),
])
def test_leading_indentation(line: str, indent_count: int):
    lexemes = vl.lex_line(line)
    assert len(lexemes) >= indent_count
    indents = lexemes[:indent_count]
    rest = lexemes[indent_count:]
    for indent in indents:
        assert indent == vl.INDENT
    if rest:
        assert rest[0] != vl.INDENT

# OPERATORS

@pytest.mark.parametrize('line,correct_lexemes', [
    ('foo+',
     [vl.Name('foo'), vl.Operator('+')]),
    ('+foo',
     [vl.Operator('+'), vl.Name('foo')]),
    ('foo+bar',
     [vl.Name('foo'), vl.Operator('+'), vl.Name('bar')]),
    ('foo(bar)',
     [vl.Name('foo'), vl.Operator('('), vl.Name('bar'), vl.Operator(')')]),
    ('foo()bar',
     [vl.Name('foo'), vl.Operator('('), vl.Operator(')'), vl.Name('bar')]),
    ('foo?bar',
     [vl.Name('foo'), vl.Operator('?'), vl.Name('bar')]),
    ('foo?!bar',
     [vl.Name('foo?'), vl.Operator('!'), vl.Name('bar')]),
])
def test_infix_ops(line: str, correct_lexemes: List[vl.Lexeme]):
    assert vl.lex_line(line) == correct_lexemes

# COMMAS

@pytest.mark.parametrize('line,correct_lexemes', [
    (',',
     [vl.COMMA]),
    ('foo,',
     [vl.Name('foo'), vl.COMMA]),
    ('foo,bar',
     [vl.Name('foo'), vl.COMMA, vl.Name('bar')]),
    ('foo, bar ,baz',
     [vl.Name('foo'), vl.COMMA, vl.Name('bar'), vl.COMMA, vl.Name('baz')]),
    ('foo(bar, baz)',
     [vl.Name('foo'), vl.Operator('('), vl.Name('bar'), vl.COMMA, vl.Name('baz'), vl.Operator(')')]),
    ('foo(bar,)',
     [vl.Name('foo'), vl.Operator('('), vl.Name('bar'), vl.COMMA, vl.Operator(')')]),
])
def test_commas(line: str, correct_lexemes: List[vl.Lexeme]):
    assert vl.lex_line(line) == correct_lexemes

###############################################################################
#
# LEXING TEXT
#
###############################################################################

# MULTI-LINE LEXING

@pytest.mark.parametrize('text,correct_lexemes', [
    ('\n'.join((
            'def foo(arg):',
            '    return bar()')),
     [vl.Name('def'), vl.Name('foo'), vl.Operator('('), vl.Name('arg'), vl.Operator(')'), vl.Operator(':'),
      vl.NEWLINE,
      vl.INDENT, vl.Name('return'), vl.Name('bar'), vl.Operator('('), vl.Operator(')'),
      vl.NEWLINE]),
    ('\n'.join((
            'def foo(arg1, arg2):',
            '    return bar(arg1, arg2,)')),
     [vl.Name('def'), vl.Name('foo'), vl.Operator('('), vl.Name('arg1'), vl.COMMA, vl.Name('arg2'), vl.Operator(')'),
      vl.Operator(':'), vl.NEWLINE,
      vl.INDENT, vl.Name('return'), vl.Name('bar'), vl.Operator('('), vl.Name('arg1'), vl.COMMA, vl.Name('arg2'),
      vl.COMMA, vl.Operator(')'), vl.NEWLINE]),
])
def test_multiple_lines(text: str, correct_lexemes: List[vl.Lexeme]):
    assert vl.Lexer.lex(text) == correct_lexemes

###############################################################################
#
# MISCELLANY
#
###############################################################################

# LEXEMES

def test_lexemes():
    assert vl.Name('foo') == vl.Name('foo')
    assert vl.Indent() == vl.INDENT
    assert str(vl.Name('foo')) == 'foo'
    assert repr(vl.Name('foo')) == 'Name(foo)'
    assert repr(vl.INDENT) == 'Indent'
<|endoftext|>


<commit_before>import discord

from cogs.utils import checks
from discord.ext import commands

class Config:
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def countservers(self):
        """
        Checks how many servers the bot is on"""
        msg = "The bot is in **"
        msg += str(len(self.bot.servers))
        msg += "** servers."
        await self.bot.say(msg)

    @commands.command()
    @checks.is_owner()
    async def shout(self, server_id, *, message):
        """
        Shouts a message to the main channel of a certain server"""
        msg = "```asciidoc\n"
        msg += "Announcement :: Information\n"
        msg += message
        msg += "\n```"
        for server in self.bot.servers:
            if server.id == server_id:
                try:
                    await self.bot.send_message(server, msg)
                    await self.bot.say("'" + message + "'" + " has been send to " + server.name + ".")
                except discord.errors.Forbidden:
                    await self.bot.say("I'm not allowed to do that.")

    @commands.command()
    @checks.is_owner()
    async def listservers(self):
        """
        Checks what servers the bot is on"""
        servers = self.bot.servers
        await self.bot.say("```asciidoc\nThe bot is in the following {} server(s):\n```".format(str(len(self.bot.servers))))
        msg = "```asciidoc\n"
        #msg += "\n"
        msg2 = "```asciidoc\n"
        msg3 = "```asciidoc\n"
        messages = [msg, msg2, msg3]
        count = 0
        for server in servers:
            if len(server.members)<10:
                messages[count] += "{:<1} :: 000{} users :: {}".format(server.id, len(server.members), server.name)
            elif len(server.members)<100:
                messages[count] += "{:<1} :: 00{} users :: {}".format(server.id, len(server.members), server.name)
            elif len(server.members)<1000:
                messages[count] += "{:<1} :: 0{} users :: {}".format(server.id, len(server.members), server.name)
            else:
                messages[count] += "{:<1} :: {} users :: {}".format(server.id, len(server.members), server.name)
            messages[count] += "\n"
            if len(messages[count])>1500:
                count = count+1
                break
            if len(messages[count])<25:
                messages[count] = None
        for message in messages:
            if len(message) > 30:
                await self.bot.say(message + "\n```")

    @commands.command(pass_context = True)
    @checks.is_owner()
    async def discrim(self, ctx, discriminator):
        """
        Find users with this discriminator"""
        msg = "Users with discriminator " + discriminator
        msg += ": \n"
        for r in self.bot.get_all_members():
            if r.discriminator == discriminator:
                if r.name in msg:
                    pass
                else:
                    msg += "```\n"
                    msg += r.name
                    msg += "\n```"
        await self.bot.say(msg)

    @commands.command()
    async def countusers(self):
        """
        Checks how many users the bot is connected to"""
        msg = "The bot is connected to **"
        msg += str(len(set(self.bot.get_all_members())))
        msg += "** users."
        await self.bot.say(msg)

    @commands.command()
    @checks.is_owner()
    async def notify(self, *, content):
        """Notifies every server"""
        if content == "shutdown":
            msg = "```asciidoc\n"
            msg += "Announcement :: Shutdown\n"
            msg += "riceBot shutting down... Will be up again soon!"
            msg += "\n```"
        elif content == "welcome":
            msg = "```asciidoc\n"
            msg += "Announcement :: Information\n"
            msg += "= -=-=-=-=-=-=-=-=-=-=-=- =\n"
            msg += "Thank you for inviting riceBot!\n"
            msg += "For basic information on the bot, a list of commands, or to contact the owner, use: \n"
            msg += "= rice.rice =\n"
            msg += "= rice.help =\n"
            msg += "= rice.contact =\n"
            msg += "To add the bot to your own server, open this:: https://discordsites.com/ricebot/\n"
            msg += "= -=-=-=-=-=-=-=-=-=-=-=- =\n"
            msg += "riceBot ~ managed by FwiedWice"
            msg += "\n```"
        else:
            msg = "```asciidoc\n"
            msg += "Announcement :: Information\n"
            msg += content
            msg += "\n```"
        for server in self.bot.servers:
            try:
                await self.bot.send_message(server, msg)
            except discord.errors.Forbidden:
                pass
        await self.bot.say("Message succesfully sent")

    @commands.command()
    @checks.is_owner()

    async def speak(self, *, content):

        """Says something"""
        await self.bot.say(content)

def setup(bot):
    bot.add_cog(Config(bot))
<commit_msg>fixed message limit<commit_after>import discord

from cogs.utils import checks
from discord.ext import commands

class Config:
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def countservers(self):
        """
        Checks how many servers the bot is on"""
        msg = "The bot is in **"
        msg += str(len(self.bot.servers))
        msg += "** servers."
        await self.bot.say(msg)

    @commands.command()
    @checks.is_owner()
    async def shout(self, server_id, *, message):
        """
        Shouts a message to the main channel of a certain server"""
        msg = "```asciidoc\n"
        msg += "Announcement :: Information\n"
        msg += message
        msg += "\n```"
        for server in self.bot.servers:
            if server.id == server_id:
                try:
                    await self.bot.send_message(server, msg)
                    await self.bot.say("'" + message + "'" + " has been send to " + server.name + ".")
                except discord.errors.Forbidden:
                    await self.bot.say("I'm not allowed to do that.")

    @commands.command()
    @checks.is_owner()
    async def listservers(self):
        """
        Checks what servers the bot is on"""
        servers = self.bot.servers
        await self.bot.say("```asciidoc\nThe bot is in the following {} server(s):\n```".format(str(len(self.bot.servers))))
        msg = "```asciidoc\n"
        #msg += "\n"

        messages = []
        count = 0
        for server in servers:
            messages[count] = "```asciidoc\n"
            if len(server.members)<10:
                messages[count] += "{:<1} :: 000{} users :: {}".format(server.id, len(server.members), server.name)
            elif len(server.members)<100:
                messages[count] += "{:<1} :: 00{} users :: {}".format(server.id, len(server.members), server.name)
            elif len(server.members)<1000:
                messages[count] += "{:<1} :: 0{} users :: {}".format(server.id, len(server.members), server.name)
            else:
                messages[count] += "{:<1} :: {} users :: {}".format(server.id, len(server.members), server.name)
            messages[count] += "\n"
            if len(messages[count])>1500:
                count = count+1
        for message in messages:
            if len(message) > 30:
                await self.bot.say(message + "\n```")

    @commands.command(pass_context = True)
    @checks.is_owner()
    async def discrim(self, ctx, discriminator):
        """
        Find users with this discriminator"""
        msg = "Users with discriminator " + discriminator
        msg += ": \n"
        for r in self.bot.get_all_members():
            if r.discriminator == discriminator:
                if r.name in msg:
                    pass
                else:
                    msg += "```\n"
                    msg += r.name
                    msg += "\n```"
        await self.bot.say(msg)

    @commands.command()
    async def countusers(self):
        """
        Checks how many users the bot is connected to"""
        msg = "The bot is connected to **"
        msg += str(len(set(self.bot.get_all_members())))
        msg += "** users."
        await self.bot.say(msg)

    @commands.command()
    @checks.is_owner()
    async def notify(self, *, content):
        """Notifies every server"""
        if content == "shutdown":
            msg = "```asciidoc\n"
            msg += "Announcement :: Shutdown\n"
            msg += "riceBot shutting down... Will be up again soon!"
            msg += "\n```"
        elif content == "info":
            msg = "```asciidoc\n"
            msg += "Announcement :: Information\n"
            msg += "= -=-=-=-=-=-=-=-=-=-=-=- =\n"
            msg += "Thank you for inviting riceBot!\n"
            msg += "For basic information on the bot, a list of commands, or to contact the owner, use: \n"
            msg += "= rice.rice =\n"
            msg += "= rice.help =\n"
            msg += "= rice.contact =\n"
            msg += "To add the bot to your own server, open this:: https://discordsites.com/ricebot/\n"
            msg += "= -=-=-=-=-=-=-=-=-=-=-=- =\n"
            msg += "riceBot ~ managed by FwiedWice"
            msg += "\n```"
        else:
            msg = "```asciidoc\n"
            msg += "Announcement :: Information\n"
            msg += content
            msg += "\n```"
        for server in self.bot.servers:
            try:
                await self.bot.send_message(server, msg)
            except discord.errors.Forbidden:
                pass
        await self.bot.say("Message succesfully sent")

    @commands.command()
    @checks.is_owner()

    async def speak(self, *, content):

        """Says something"""
        await self.bot.say(content)

def setup(bot):
    bot.add_cog(Config(bot))
<|endoftext|>


<commit_before>#!/usr/bin/env python3

import configparser
import nose.tools as nose
import swb.local as swb
from mock import NonCallableMock, patch
# from tests.fixtures.local import set_up, tear_down, mock_backups

def test_parse_config():
    """should correctly parse the supplied configuration file"""
    config_path = 'tests/files/config.ini'
    config = swb.parse_config(config_path)
    expected_config = configparser.RawConfigParser()
    expected_config.read(config_path)
    nose.assert_equal(config, expected_config)

@patch('os.makedirs')
def test_create_dir_structure(makedirs):
    """should create the directory structure for the supplied path"""
    swb.create_dir_structure('a/b c/d')
    makedirs.assert_called_once_with('a/b c')

@patch('os.makedirs', side_effect=OSError)
def test_create_dir_structure_silent_fail(makedirs):
    """should fail silently if directory structure already exists"""
    swb.create_dir_structure('a/b c/d')
    makedirs.assert_called_once_with('a/b c')

def test_unquote_home_dir_path_with_tilde():
    """should unquote the tilde (~) in the supplied quoted path"""
    unquoted_path = swb.unquote_home_dir('\'~/a/b c/d\'')
    nose.assert_equal(unquoted_path, '~/\'a/b c/d\'')

def test_unquote_home_dir_path_without_tilde():
    """should return the supplied quoted path"""
    unquoted_path = swb.unquote_home_dir('\'/a/b c/d\'')
    nose.assert_equal(unquoted_path, '\'/a/b c/d\'')

def test_quote_arg():
    """should correctly quote arguments passed to the shell"""
    quoted_arg = swb.quote_arg('a/b c/d')
    nose.assert_equal(quoted_arg, '\'a/b c/d\'')

@patch('swb.local.shlex')
def test_quote_arg_py32(shlex):
    """should correctly quote arguments passed to the shell on Python 3.2"""
    del shlex.quote
    nose.assert_false(hasattr(shlex, 'quote'))
    quoted_arg = swb.quote_arg('a/b c/d')
    nose.assert_equal(quoted_arg, '\'a/b c/d\'')

@patch('subprocess.Popen', return_value=NonCallableMock(returncode=0))
@patch('swb.local.open')
def test_exec_on_remote(local_open, popen):
    """should execute script on remote server"""
    swb.exec_on_remote(
        'myname', 'mysite.com', '2222',
        'back-up', ['~/public_html/mysite', 'bzip2 -v', 'a/b c/d', 'False'],
        stdout=1, stderr=2)
    popen.assert_called_once_with([
        'ssh', '-p 2222', 'myname@mysite.com',
        'python3', '-', 'back-up', '~/\'public_html/mysite\'',
        '\'bzip2 -v\'', '\'a/b c/d\'', 'False'],
        stdin=local_open.return_value.__enter__(), stdout=1, stderr=2)
    popen.return_value.wait.assert_called_once_with()

@patch('subprocess.Popen', return_value=NonCallableMock(returncode=3))
@patch('swb.local.open')
@patch('sys.exit')
def test_exec_on_remote_nonzero_return(exit, local_open, popen):
    """should exit script if nonzero status code is returned"""
    swb.exec_on_remote(
        'a', 'b.com', '2222', 'c', ['d', 'e', 'f', 'g'], stdout=1, stderr=2)
    exit.assert_called_once_with(3)
<commit_msg>Add transfer_file tests (both download and upload)<commit_after>#!/usr/bin/env python3

import configparser
import nose.tools as nose
import swb.local as swb
from mock import NonCallableMock, patch
# from tests.fixtures.local import set_up, tear_down, mock_backups

def test_parse_config():
    """should correctly parse the supplied configuration file"""
    config_path = 'tests/files/config.ini'
    config = swb.parse_config(config_path)
    expected_config = configparser.RawConfigParser()
    expected_config.read(config_path)
    nose.assert_equal(config, expected_config)

@patch('os.makedirs')
def test_create_dir_structure(makedirs):
    """should create the directory structure for the supplied path"""
    swb.create_dir_structure('a/b c/d')
    makedirs.assert_called_once_with('a/b c')

@patch('os.makedirs', side_effect=OSError)
def test_create_dir_structure_silent_fail(makedirs):
    """should fail silently if directory structure already exists"""
    swb.create_dir_structure('a/b c/d')
    makedirs.assert_called_once_with('a/b c')

def test_unquote_home_dir_path_with_tilde():
    """should unquote the tilde (~) in the supplied quoted path"""
    unquoted_path = swb.unquote_home_dir('\'~/a/b c/d\'')
    nose.assert_equal(unquoted_path, '~/\'a/b c/d\'')

def test_unquote_home_dir_path_without_tilde():
    """should return the supplied quoted path"""
    unquoted_path = swb.unquote_home_dir('\'/a/b c/d\'')
    nose.assert_equal(unquoted_path, '\'/a/b c/d\'')

def test_quote_arg():
    """should correctly quote arguments passed to the shell"""
    quoted_arg = swb.quote_arg('a/b c/d')
    nose.assert_equal(quoted_arg, '\'a/b c/d\'')

@patch('swb.local.shlex')
def test_quote_arg_py32(shlex):
    """should correctly quote arguments passed to the shell on Python 3.2"""
    del shlex.quote
    nose.assert_false(hasattr(shlex, 'quote'))
    quoted_arg = swb.quote_arg('a/b c/d')
    nose.assert_equal(quoted_arg, '\'a/b c/d\'')

@patch('subprocess.Popen', return_value=NonCallableMock(returncode=0))
@patch('swb.local.open')
def test_exec_on_remote(local_open, popen):
    """should execute script on remote server"""
    swb.exec_on_remote(
        'myname', 'mysite.com', '2222',
        'back-up', ['~/public_html/mysite', 'bzip2 -v', 'a/b c/d', 'False'],
        stdout=1, stderr=2)
    popen.assert_called_once_with([
        'ssh', '-p 2222', 'myname@mysite.com',
        'python3', '-', 'back-up', '~/\'public_html/mysite\'',
        '\'bzip2 -v\'', '\'a/b c/d\'', 'False'],
        stdin=local_open.return_value.__enter__(), stdout=1, stderr=2)
    popen.return_value.wait.assert_called_once_with()

@patch('subprocess.Popen', return_value=NonCallableMock(returncode=3))
@patch('swb.local.open')
@patch('sys.exit')
def test_exec_on_remote_nonzero_return(exit, local_open, popen):
    """should exit script if nonzero status code is returned"""
    swb.exec_on_remote(
        'a', 'b.com', '2222', 'c', ['d', 'e', 'f', 'g'], stdout=1, stderr=2)
    exit.assert_called_once_with(3)

@patch('subprocess.Popen')
def test_transfer_file_download(popen):
    """should download backup from remote server when backing up"""
    swb.transfer_file(
        'myname', 'mysite.com', '2222', 'a/b c/d', 'e/f g/h',
        action='download', stdout=1, stderr=2)
    popen.assert_called_once_with(
        ['scp', '-P 2222', 'myname@mysite.com:\'a/b c/d\'', 'e/f g/h'],
        stdout=1, stderr=2)
    popen.return_value.wait.assert_called_once_with()

@patch('subprocess.Popen')
def test_transfer_file_upload(popen):
    """should upload backup to remote server when restoring"""
    swb.transfer_file(
        'myname', 'mysite.com', '2222', 'a/b c/d', 'e/f g/h',
        action='upload', stdout=1, stderr=2)
    popen.assert_called_once_with(
        ['scp', '-P 2222', 'a/b c/d', 'myname@mysite.com:\'e/f g/h\''],
        stdout=1, stderr=2)
    popen.return_value.wait.assert_called_once_with()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
#    Author: Guewen Baconnier
#    Copyright 2013 Camptocamp SA
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from ..connector import ConnectorUnit
from .mapper import Mapper, ImportMapper, ExportMapper
from .backend_adapter import BackendAdapter

class Synchronizer(ConnectorUnit):
    """ Base class for synchronizers """

    # implement in sub-classes
    _model_name = None

    def __init__(self, environment):
        super(Synchronizer, self).__init__(environment)
        self._backend_adapter = None
        self._binder = None
        self._mapper = None

    def run(self):
        """ Run the synchronization """
        raise NotImplementedError

    @property
    def mapper(self):
        """ Return an instance of ``Mapper`` for the synchronization.

        The instanciation is delayed because some synchronisations do
        not need such an unit and the unit may not exist.

        :rtype: :py:class:`connector.unit.mapper.Mapper`
        """
        if self._mapper is None:
            self._mapper = self.environment.get_connector_unit(Mapper)
        return self._mapper

    @property
    def binder(self):
        """ Return an instance of ``Binder`` for the synchronization.

        The instanciation is delayed because some synchronisations do
        not need such an unit and the unit may not exist.

        :rtype: :py:class:`connector.unit.binder.Binder`
        """
        if self._binder is None:
            self._binder = self.get_binder_for_model()
        return self._binder

    @property
    def backend_adapter(self):
        """ Return an instance of ``BackendAdapter`` for the
        synchronization.

        The instanciation is delayed because some synchronisations do
        not need such an unit and the unit may not exist.

        :rtype: :py:class:`connector.unit.backend_adapter.BackendAdapter`
        """
        if self._backend_adapter is None:
            get_unit = self.environment.get_connector_unit
            self._backend_adapter = get_unit(BackendAdapter)
        return self._backend_adapter

class ExportSynchronizer(Synchronizer):
    """ Synchronizer for exporting data from OpenERP to a backend """

    @property
    def mapper(self):
        """ Return an instance of ``Mapper`` for the synchronization.

        The instanciation is delayed because some synchronisations do
        not need such an unit and the unit may not exist.

        :rtype: :py:class:`connector.unit.mapper.ExportMapper`
        """
        if self._mapper is None:
            self._mapper = self.environment.get_connector_unit(ExportMapper)
        return self._mapper

class ImportSynchronizer(Synchronizer):
    """ Synchronizer for importing data from a backend to OpenERP """

    @property
    def mapper(self):
        """ Return an instance of ``Mapper`` for the synchronization.

        The instanciation is delayed because some synchronisations do
        not need such an unit and the unit may not exist.

        :rtype: :py:class:`connector.unit.mapper.ImportMapper`
        """
        if self._mapper is None:
            self._mapper = self.environment.get_connector_unit(ImportMapper)
        return self._mapper

class DeleteSynchronizer(Synchronizer):
    """ Synchronizer for deleting a record on the backend """
<commit_msg>Add class attributes for the base ConnectorUnit classes<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
#    Author: Guewen Baconnier
#    Copyright 2013 Camptocamp SA
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from ..connector import ConnectorUnit
from .mapper import Mapper, ImportMapper, ExportMapper
from .backend_adapter import BackendAdapter

class Synchronizer(ConnectorUnit):
    """ Base class for synchronizers """

    # implement in sub-classes
    _model_name = None

    _base_mapper = Mapper
    _base_backend_adapter = BackendAdapter

    def __init__(self, environment):
        super(Synchronizer, self).__init__(environment)
        self._backend_adapter = None
        self._binder = None
        self._mapper = None

    def run(self):
        """ Run the synchronization """
        raise NotImplementedError

    @property
    def mapper(self):
        """ Return an instance of ``Mapper`` for the synchronization.

        The instanciation is delayed because some synchronisations do
        not need such an unit and the unit may not exist.

        :rtype: :py:class:`connector.unit.mapper.Mapper`
        """
        if self._mapper is None:
            get_unit = self.environment.get_connector_unit
            self._mapper = get_unit(self._base_mapper)
        return self._mapper

    @property
    def binder(self):
        """ Return an instance of ``Binder`` for the synchronization.

        The instanciation is delayed because some synchronisations do
        not need such an unit and the unit may not exist.

        :rtype: :py:class:`connector.unit.binder.Binder`
        """
        if self._binder is None:
            self._binder = self.binder_for()
        return self._binder

    @property
    def backend_adapter(self):
        """ Return an instance of ``BackendAdapter`` for the
        synchronization.

        The instanciation is delayed because some synchronisations do
        not need such an unit and the unit may not exist.

        :rtype: :py:class:`connector.unit.backend_adapter.BackendAdapter`
        """
        if self._backend_adapter is None:
            get_unit = self.environment.get_connector_unit
            self._backend_adapter = get_unit(self._base_backend_adapter)
        return self._backend_adapter

class ExportSynchronizer(Synchronizer):
    """ Synchronizer for exporting data from OpenERP to a backend """

    _base_mapper = ExportMapper

class ImportSynchronizer(Synchronizer):
    """ Synchronizer for importing data from a backend to OpenERP """

    _base_mapper = ImportMapper

class DeleteSynchronizer(Synchronizer):
    """ Synchronizer for deleting a record on the backend """
<|endoftext|>