<commit_before>import sys
import unittest
from datetime import datetime
try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO

from botocore.client import ClientError
from botocore.auth import NoCredentialsError
from botocore.retryhandler import EndpointConnectionError

from termcolor import colored

try:
    from mock import patch, Mock, call
except ImportError:
    from unittest.mock import patch, Mock, call

from awslogs import AWSLogs
from awslogs.exceptions import UnknownDateError, ConnectionError
from awslogs.bin import main

class TestAWSLogs(unittest.TestCase):

    def _stream(self, name, start=0, end=sys.maxsize):
        return {'logStreamName': name,
                'firstEventTimestamp': start,
                'lastEventTimestamp': end}

    @patch('boto3.client')
    @patch('awslogs.core.datetime')
    def test_parse_datetime(self, datetime_mock, botoclient):

        awslogs = AWSLogs()
        datetime_mock.now.return_value = datetime(2015, 1, 1, 3, 0, 0, 0)

        def epoch(dt):
            return int(dt.strftime("%s")) * 1000

        self.assertEqual(awslogs.parse_datetime(''), None)
        self.assertEqual(awslogs.parse_datetime(None), None)

        self.assertEqual(awslogs.parse_datetime('1m'),
                         epoch(datetime(2015, 1, 1, 2, 59, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1m ago'),
                         epoch(datetime(2015, 1, 1, 2, 59, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1minute'),
                         epoch(datetime(2015, 1, 1, 2, 59, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1minute ago'),
                         epoch(datetime(2015, 1, 1, 2, 59, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1minutes'),
                         epoch(datetime(2015, 1, 1, 2, 59, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1minutes ago'),
                         epoch(datetime(2015, 1, 1, 2, 59, 0, 0)))

        self.assertEqual(awslogs.parse_datetime('1h'),
                         epoch(datetime(2015, 1, 1, 2, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1h ago'),
                         epoch(datetime(2015, 1, 1, 2, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1hour'),
                         epoch(datetime(2015, 1, 1, 2, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1hour ago'),
                         epoch(datetime(2015, 1, 1, 2, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1hours'),
                         epoch(datetime(2015, 1, 1, 2, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1hours ago'),
                         epoch(datetime(2015, 1, 1, 2, 0, 0, 0)))

        self.assertEqual(awslogs.parse_datetime('1d'),
                         epoch(datetime(2014, 12, 31, 3, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1d ago'),
                         epoch(datetime(2014, 12, 31, 3, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1day'),
                         epoch(datetime(2014, 12, 31, 3, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1day ago'),
                         epoch(datetime(2014, 12, 31, 3, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1days'),
                         epoch(datetime(2014, 12, 31, 3, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1days ago'),
                         epoch(datetime(2014, 12, 31, 3, 0, 0, 0)))

        self.assertEqual(awslogs.parse_datetime('1w'),
                         epoch(datetime(2014, 12, 25, 3, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1w ago'),
                         epoch(datetime(2014, 12, 25, 3, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1week'),
                         epoch(datetime(2014, 12, 25, 3, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1week ago'),
                         epoch(datetime(2014, 12, 25, 3, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1weeks'),
                         epoch(datetime(2014, 12, 25, 3, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1weeks ago'),
                         epoch(datetime(2014, 12, 25, 3, 0, 0, 0)))

        self.assertEqual(awslogs.parse_datetime('1/1/2013'),
                         epoch(datetime(2013, 1, 1, 0, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1/1/2012 12:34'),
                         epoch(datetime(2012, 1, 1, 12, 34, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1/1/2011 12:34:56'),
                         epoch(datetime(2011, 1, 1, 12, 34, 56, 0)))

        self.assertRaises(UnknownDateError, awslogs.parse_datetime, '???')

    @patch('boto3.client')
    def test_get_groups(self, botoclient):
        client = Mock()
        botoclient.return_value = client
        client.describe_log_groups.side_effect = [
            {'logGroups': [{'logGroupName': 'A'},
                           {'logGroupName': 'B'},
                           {'logGroupName': 'C'}],
             'nextToken': 1},
            {'logGroups': [{'logGroupName': 'D'},
                           {'logGroupName': 'E'},
                           {'logGroupName': 'F'}],
             'nextToken': 2},
            {'logGroups': [{'logGroupName': 'G'}]},
        ]

        awslogs = AWSLogs()
        self.assertEqual([g for g in awslogs.get_groups()], ['A', 'B', 'C', 'D', 'E', 'F', 'G'])

        expected = [call(),
                    call(nextToken=1),
                    call(nextToken=2)]
        self.assertEqual(client.describe_log_groups.call_args_list, expected)

    @patch('boto3.client')
    def test_get_streams(self, botoclient):
        client = Mock()
        botoclient.return_value = client
        client.describe_log_streams.side_effect = [
            {'logStreams': [self._stream('A'),
                            self._stream('B'),
                            self._stream('C')],
             'nextToken': 1},
            {'logStreams': [self._stream('D'),
                            self._stream('E'),
                            self._stream('F')],
             'nextToken': 2},
            {'logStreams': [self._stream('G')]},
        ]

        awslogs = AWSLogs(log_group_name='group')
        self.assertEqual([g for g in awslogs.get_streams()], ['A', 'B', 'C', 'D', 'E', 'F', 'G'])

        expected = [call(logGroupName="group"),
                    call(logGroupName="group", nextToken=1),
                    call(logGroupName="group", nextToken=2)]

        self.assertEqual(client.describe_log_streams.call_args_list, expected)

    @patch('boto3.client')
    @patch('awslogs.core.AWSLogs.parse_datetime')
    def test_get_streams_filtered_by_date(self, parse_datetime, botoclient):
        client = Mock()
        botoclient.return_value = client
        client.describe_log_streams.side_effect = [
            {'logStreams': [self._stream('A', 0, 1),
                            self._stream('B', 0, 6),
                            self._stream('C'),
                            self._stream('D', sys.maxsize - 1, sys.maxsize)],
            }
        ]
        parse_datetime.side_effect = [5, 7]
        awslogs = AWSLogs(log_group_name='group', start='5', end='7')
        self.assertEqual([g for g in awslogs.get_streams()], ['B', 'C'])
        self.assertEqual(client.describe_log_streams.call_args_list, [call(logGroupName="group")])

    @patch('boto3.client')
    def test_get_streams_from_pattern(self, botoclient):
        client = Mock()
        botoclient.return_value = client

        side_effect = [
            {'logStreams': [self._stream('AAA'),
                            self._stream('ABA'),
                            self._stream('ACA')],
             'nextToken': 1},
            {'logStreams': [self._stream('BAA'),
                            self._stream('BBA'),
                            self._stream('BBB')],
             'nextToken': 2},
            {'logStreams': [self._stream('CAC')]},
        ]

        awslogs = AWSLogs()

        client.describe_log_streams.side_effect = side_effect
        expected = ['AAA', 'ABA', 'ACA', 'BAA', 'BBA', 'BBB', 'CAC']
        actual = [s for s in awslogs._get_streams_from_pattern('X', 'ALL')]
        self.assertEqual(actual, expected)

        client.describe_log_streams.side_effect = side_effect
        expected = ['AAA', 'ABA', 'ACA']
        actual = [s for s in awslogs._get_streams_from_pattern('X', 'A')]
        self.assertEqual(actual, expected)

        client.describe_log_streams.side_effect = side_effect
        expected = ['AAA', 'ACA']
        actual = [s for s in awslogs._get_streams_from_pattern('X', 'A[AC]A')]
        self.assertEqual(actual, expected)

    @patch('boto3.client')
    @patch('sys.stdout', new_callable=StringIO)
    def test_main_get(self, mock_stdout, botoclient):
        client = Mock()
        botoclient.return_value = client
        awslogs = AWSLogs()

        logs = [
            {'events': [{'timestamp': 1, 'message': 'Hello 1', 'logStreamName': 'DDD'},
                        {'timestamp': 2, 'message': 'Hello 2', 'logStreamName': 'EEE'},
                        {'timestamp': 3, 'message': 'Hello 3', 'logStreamName': 'DDD'}],
             'nextToken': 'token'},
            {'events': [{'timestamp': 4, 'message': 'Hello 4', 'logStreamName': 'EEE'},
                        {'timestamp': 5, 'message': 'Hello 5', 'logStreamName': 'DDD'},
                        {'timestamp': 6, 'message': 'Hello 6', 'logStreamName': 'EEE'}],
             'nextToken': 'token'},
            {'events': []}
        ]

        groups = [
            {'logGroups': [{'logGroupName': 'AAA'},
                           {'logGroupName': 'BBB'},
                           {'logGroupName': 'CCC'}]},
        ]

        streams = [
            {'logStreams': [self._stream('DDD'),
                            self._stream('EEE')]}
        ]

        client.filter_log_events.side_effect = logs
        client.describe_log_groups.side_effect = groups
        client.describe_log_streams.side_effect = streams

        main("awslogs get AAA DDD --no-color".split())

        self.assertEqual(
            mock_stdout.getvalue(),
            ("AAA DDD Hello 1\n"
             "AAA EEE Hello 2\n"
             "AAA DDD Hello 3\n"
             "AAA EEE Hello 4\n"
             "AAA DDD Hello 5\n"
             "AAA EEE Hello 6\n")
        )

    @patch('boto3.client')
    @patch('sys.stdout', new_callable=StringIO)
    def test_main_groups(self, mock_stdout, botoclient):
        client = Mock()
        botoclient.return_value = client
        awslogs = AWSLogs()

        groups = [
            {'logGroups': [{'logGroupName': 'AAA'},
                           {'logGroupName': 'BBB'},
                           {'logGroupName': 'CCC'}]},
        ]

        client.describe_log_groups.side_effect = groups

        main("awslogs groups".split())
        self.assertEqual(
            mock_stdout.getvalue(),
            ("AAA\n"
             "BBB\n"
             "CCC\n")
        )

    @patch('boto3.client')
    @patch('sys.stdout', new_callable=StringIO)
    def test_main_streams(self, mock_stdout, botoclient):
        client = Mock()
        botoclient.return_value = client
        awslogs = AWSLogs()

        groups = [
            {'logGroups': [{'logGroupName': 'AAA'},
                           {'logGroupName': 'BBB'},
                           {'logGroupName': 'CCC'}]},
        ]

        streams = [
            {'logStreams': [self._stream('DDD'),
                            self._stream('EEE')]}
        ]

        client.describe_log_groups.side_effect = groups
        client.describe_log_streams.side_effect = streams

        main("awslogs streams AAA".split())
        self.assertEqual(
            mock_stdout.getvalue(),
            ("DDD\n"
             "EEE\n")
        )

    @patch('sys.stderr', new_callable=StringIO)
    def test_unknown_date_error(self, mock_stderr):
        code = main("awslogs get AAA BBB -sX".split())
        self.assertEqual(code, 3)
        self.assertEqual(mock_stderr.getvalue(),
                         colored("awslogs doesn't understand 'X' as a date.\n", "red"))

    @patch('awslogs.bin.AWSLogs')
    @patch('sys.stderr', new_callable=StringIO)
    def test_unknown_error(self, mock_stderr, mock_awslogs):
        mock_awslogs.side_effect = Exception("Error!")
        code = main("awslogs get AAA BBB".split())
        output = mock_stderr.getvalue()
        self.assertEqual(code, 1)
        self.assertTrue("You've found a bug!" in output)
        self.assertTrue("Exception: Error!" in output)

    @patch('boto3.client')
    @patch('sys.stderr', new_callable=StringIO)
    def test_connection_error(self, mock_stderr, botoclient):
        client = Mock()
        botoclient.return_value = client

        exc = EndpointConnectionError(endpoint_url="url")
        client.describe_log_groups.side_effect = exc

        code = main("awslogs groups --aws-region=eu-west-1".split())
        self.assertEqual(code, 2)
        self.assertEqual(mock_stderr.getvalue(), colored("Could not connect to the endpoint URL: \"url\"\n", "red"))

    @patch('boto3.client')
    @patch('sys.stderr', new_callable=StringIO)
    def test_access_denied_error(self, mock_stderr, botoclient):
        client = Mock()
        botoclient.return_value = client

        exc = ClientError(error_response={'Error': {'Code': 'AccessDeniedException', 'Message': 'User XXX...'}}, operation_name="operation")
        client.describe_log_groups.side_effect = exc

        code = main("awslogs groups --aws-region=eu-west-1".split())
        self.assertEqual(code, 4)
        self.assertEqual(mock_stderr.getvalue(), colored("User XXX...\n", "red"))

    @patch('boto3.client')
    @patch('sys.stderr', new_callable=StringIO)
    def test_no_credentials_error(self, mock_stderr, botoclient):
        client = Mock()
        botoclient.return_value = client

        exc = NoCredentialsError()
        client.describe_log_groups.side_effect = exc

        code = main("awslogs groups --aws-region=eu-west-1".split())
        self.assertEqual(code, 5)
        self.assertEqual(mock_stderr.getvalue(), colored("""Unable to locate credentials
Check that you have provided valid credentials in one of the following ways:
* AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables.
* ~/.aws/credentials
* Instance profile credentials\n""", "red"))
<commit_msg>Fix tests<commit_after>import sys
import unittest
from datetime import datetime
try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO

from botocore.client import ClientError
from botocore.auth import NoCredentialsError
from botocore.retryhandler import EndpointConnectionError

from termcolor import colored

try:
    from mock import patch, Mock, call
except ImportError:
    from unittest.mock import patch, Mock, call

from awslogs import AWSLogs
from awslogs.exceptions import UnknownDateError, ConnectionError
from awslogs.bin import main

class TestAWSLogs(unittest.TestCase):

    def _stream(self, name, start=0, end=sys.maxsize):
        return {'logStreamName': name,
                'firstEventTimestamp': start,
                'lastEventTimestamp': end}

    @patch('boto3.client')
    @patch('awslogs.core.datetime')
    def test_parse_datetime(self, datetime_mock, botoclient):

        awslogs = AWSLogs()
        datetime_mock.utcnow.return_value = datetime(2015, 1, 1, 3, 0, 0, 0)
        datetime_mock.return_value = datetime(1970, 1, 1)

        def epoch(dt):
            return int((dt - datetime(1970, 1, 1)).total_seconds() * 1000)

        self.assertEqual(awslogs.parse_datetime(''), None)
        self.assertEqual(awslogs.parse_datetime(None), None)

        self.assertEqual(awslogs.parse_datetime('1m'),
                         epoch(datetime(2015, 1, 1, 2, 59, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1m ago'),
                         epoch(datetime(2015, 1, 1, 2, 59, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1minute'),
                         epoch(datetime(2015, 1, 1, 2, 59, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1minute ago'),
                         epoch(datetime(2015, 1, 1, 2, 59, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1minutes'),
                         epoch(datetime(2015, 1, 1, 2, 59, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1minutes ago'),
                         epoch(datetime(2015, 1, 1, 2, 59, 0, 0)))

        self.assertEqual(awslogs.parse_datetime('1h'),
                         epoch(datetime(2015, 1, 1, 2, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1h ago'),
                         epoch(datetime(2015, 1, 1, 2, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1hour'),
                         epoch(datetime(2015, 1, 1, 2, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1hour ago'),
                         epoch(datetime(2015, 1, 1, 2, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1hours'),
                         epoch(datetime(2015, 1, 1, 2, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1hours ago'),
                         epoch(datetime(2015, 1, 1, 2, 0, 0, 0)))

        self.assertEqual(awslogs.parse_datetime('1d'),
                         epoch(datetime(2014, 12, 31, 3, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1d ago'),
                         epoch(datetime(2014, 12, 31, 3, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1day'),
                         epoch(datetime(2014, 12, 31, 3, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1day ago'),
                         epoch(datetime(2014, 12, 31, 3, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1days'),
                         epoch(datetime(2014, 12, 31, 3, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1days ago'),
                         epoch(datetime(2014, 12, 31, 3, 0, 0, 0)))

        self.assertEqual(awslogs.parse_datetime('1w'),
                         epoch(datetime(2014, 12, 25, 3, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1w ago'),
                         epoch(datetime(2014, 12, 25, 3, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1week'),
                         epoch(datetime(2014, 12, 25, 3, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1week ago'),
                         epoch(datetime(2014, 12, 25, 3, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1weeks'),
                         epoch(datetime(2014, 12, 25, 3, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1weeks ago'),
                         epoch(datetime(2014, 12, 25, 3, 0, 0, 0)))

        self.assertEqual(awslogs.parse_datetime('1/1/2013'),
                         epoch(datetime(2013, 1, 1, 0, 0, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1/1/2012 12:34'),
                         epoch(datetime(2012, 1, 1, 12, 34, 0, 0)))
        self.assertEqual(awslogs.parse_datetime('1/1/2011 12:34:56'),
                         epoch(datetime(2011, 1, 1, 12, 34, 56, 0)))

        self.assertRaises(UnknownDateError, awslogs.parse_datetime, '???')

    @patch('boto3.client')
    def test_get_groups(self, botoclient):
        client = Mock()
        botoclient.return_value = client
        client.get_paginator.return_value.paginate.return_value = [
            {'logGroups': [{'logGroupName': 'A'},
                           {'logGroupName': 'B'},
                           {'logGroupName': 'C'}],
             'nextToken': 1},
            {'logGroups': [{'logGroupName': 'D'},
                           {'logGroupName': 'E'},
                           {'logGroupName': 'F'}],
             'nextToken': 2},
            {'logGroups': [{'logGroupName': 'G'}]},
        ]

        awslogs = AWSLogs()
        self.assertEqual([g for g in awslogs.get_groups()], ['A', 'B', 'C', 'D', 'E', 'F', 'G'])

    @patch('boto3.client')
    def test_get_streams(self, botoclient):
        client = Mock()
        botoclient.return_value = client
        client.get_paginator.return_value.paginate.return_value = [
            {'logStreams': [self._stream('A'),
                            self._stream('B'),
                            self._stream('C')],
             'nextToken': 1},
            {'logStreams': [self._stream('D'),
                            self._stream('E'),
                            self._stream('F')],
             'nextToken': 2},
            {'logStreams': [self._stream('G')]},
        ]

        awslogs = AWSLogs(log_group_name='group')
        self.assertEqual([g for g in awslogs.get_streams()], ['A', 'B', 'C', 'D', 'E', 'F', 'G'])

    @patch('boto3.client')
    @patch('awslogs.core.AWSLogs.parse_datetime')
    def test_get_streams_filtered_by_date(self, parse_datetime, botoclient):
        client = Mock()
        botoclient.return_value = client
        client.get_paginator.return_value.paginate.return_value = [
            {'logStreams': [self._stream('A', 0, 1),
                            self._stream('B', 0, 6),
                            self._stream('C'),
                            self._stream('D', sys.maxsize - 1, sys.maxsize)],
            }
        ]
        parse_datetime.side_effect = [5, 7]
        awslogs = AWSLogs(log_group_name='group', start='5', end='7')
        self.assertEqual([g for g in awslogs.get_streams()], ['B', 'C'])

    @patch('boto3.client')
    def test_get_streams_from_pattern(self, botoclient):
        client = Mock()
        botoclient.return_value = client

        side_effect = [
            {'logStreams': [self._stream('AAA'),
                            self._stream('ABA'),
                            self._stream('ACA')],
             'nextToken': 1},
            {'logStreams': [self._stream('BAA'),
                            self._stream('BBA'),
                            self._stream('BBB')],
             'nextToken': 2},
            {'logStreams': [self._stream('CAC')]},
        ]

        awslogs = AWSLogs()

        client.get_paginator.return_value.paginate.return_value = side_effect
        expected = ['AAA', 'ABA', 'ACA', 'BAA', 'BBA', 'BBB', 'CAC']
        actual = [s for s in awslogs._get_streams_from_pattern('X', 'ALL')]
        self.assertEqual(actual, expected)

        client.get_paginator.return_value.paginate.return_value = side_effect
        expected = ['AAA', 'ABA', 'ACA']
        actual = [s for s in awslogs._get_streams_from_pattern('X', 'A')]
        self.assertEqual(actual, expected)

        client.get_paginator.return_value.paginate.return_value = side_effect
        expected = ['AAA', 'ACA']
        actual = [s for s in awslogs._get_streams_from_pattern('X', 'A[AC]A')]
        self.assertEqual(actual, expected)

    @patch('boto3.client')
    @patch('sys.stdout', new_callable=StringIO)
    def test_main_get(self, mock_stdout, botoclient):
        client = Mock()
        botoclient.return_value = client
        awslogs = AWSLogs()

        logs = [
            {'events': [{'timestamp': 1, 'message': 'Hello 1', 'logStreamName': 'DDD'},
                        {'timestamp': 2, 'message': 'Hello 2', 'logStreamName': 'EEE'},
                        {'timestamp': 3, 'message': 'Hello 3', 'logStreamName': 'DDD'}],
             'nextToken': 'token'},
            {'events': [{'timestamp': 4, 'message': 'Hello 4', 'logStreamName': 'EEE'},
                        {'timestamp': 5, 'message': 'Hello 5', 'logStreamName': 'DDD'},
                        {'timestamp': 6, 'message': 'Hello 6', 'logStreamName': 'EEE'}],
             'nextToken': 'token'},
            {'events': []}
        ]

        groups = [
            {'logGroups': [{'logGroupName': 'AAA'},
                           {'logGroupName': 'BBB'},
                           {'logGroupName': 'CCC'}]},
        ]

        streams = [
            {'logStreams': [self._stream('DDD'),
                            self._stream('EEE')]}
        ]

        def paginator(value):
            mock = Mock()
            mock.paginate.return_value = {
                'filter_log_events': logs,
                'describe_log_groups': groups,
                'describe_log_streams': streams
            }.get(value)
            return mock

        client.get_paginator.side_effect = paginator

        main("awslogs get AAA DDD --no-color".split())

        self.assertEqual(
            mock_stdout.getvalue(),
            ("AAA DDD Hello 1\n"
             "AAA EEE Hello 2\n"
             "AAA DDD Hello 3\n"
             "AAA EEE Hello 4\n"
             "AAA DDD Hello 5\n"
             "AAA EEE Hello 6\n")
        )

    @patch('boto3.client')
    @patch('sys.stdout', new_callable=StringIO)
    def test_main_groups(self, mock_stdout, botoclient):
        client = Mock()
        botoclient.return_value = client
        awslogs = AWSLogs()

        groups = [
            {'logGroups': [{'logGroupName': 'AAA'},
                           {'logGroupName': 'BBB'},
                           {'logGroupName': 'CCC'}]},
        ]

        client.get_paginator.return_value.paginate.return_value = groups

        main("awslogs groups".split())
        self.assertEqual(
            mock_stdout.getvalue(),
            ("AAA\n"
             "BBB\n"
             "CCC\n")
        )

    @patch('boto3.client')
    @patch('sys.stdout', new_callable=StringIO)
    def test_main_streams(self, mock_stdout, botoclient):
        client = Mock()
        botoclient.return_value = client
        awslogs = AWSLogs()

        groups = [
            {'logGroups': [{'logGroupName': 'AAA'},
                           {'logGroupName': 'BBB'},
                           {'logGroupName': 'CCC'}]},
        ]

        streams = [
            {'logStreams': [self._stream('DDD'),
                            self._stream('EEE')]}
        ]

        def paginator(value):
            mock = Mock()
            mock.paginate.return_value = {
                'describe_log_groups': groups,
                'describe_log_streams': streams
            }.get(value)
            return mock

        client.get_paginator.side_effect = paginator

        main("awslogs streams AAA".split())
        self.assertEqual(
            mock_stdout.getvalue(),
            ("DDD\n"
             "EEE\n")
        )

    @patch('sys.stderr', new_callable=StringIO)
    def test_unknown_date_error(self, mock_stderr):
        code = main("awslogs get AAA BBB -sX".split())
        self.assertEqual(code, 3)
        self.assertEqual(mock_stderr.getvalue(),
                         colored("awslogs doesn't understand 'X' as a date.\n", "red"))

    @patch('awslogs.bin.AWSLogs')
    @patch('sys.stderr', new_callable=StringIO)
    def test_unknown_error(self, mock_stderr, mock_awslogs):
        mock_awslogs.side_effect = Exception("Error!")
        code = main("awslogs get AAA BBB".split())
        output = mock_stderr.getvalue()
        self.assertEqual(code, 1)
        self.assertTrue("You've found a bug!" in output)
        self.assertTrue("Exception: Error!" in output)

    @patch('boto3.client')
    @patch('sys.stderr', new_callable=StringIO)
    def test_connection_error(self, mock_stderr, botoclient):
        client = Mock()
        botoclient.return_value = client

        exc = EndpointConnectionError(endpoint_url="url")
        client.get_paginator.side_effect = exc

        code = main("awslogs groups --aws-region=eu-west-1".split())
        self.assertEqual(code, 2)
        self.assertEqual(mock_stderr.getvalue(), colored("Could not connect to the endpoint URL: \"url\"\n", "red"))

    @patch('boto3.client')
    @patch('sys.stderr', new_callable=StringIO)
    def test_access_denied_error(self, mock_stderr, botoclient):
        client = Mock()
        botoclient.return_value = client

        exc = ClientError(error_response={'Error': {'Code': 'AccessDeniedException', 'Message': 'User XXX...'}}, operation_name="operation")
        client.get_paginator.side_effect = exc

        code = main("awslogs groups --aws-region=eu-west-1".split())
        self.assertEqual(code, 4)
        self.assertEqual(mock_stderr.getvalue(), colored("User XXX...\n", "red"))

    @patch('boto3.client')
    @patch('sys.stderr', new_callable=StringIO)
    def test_no_credentials_error(self, mock_stderr, botoclient):
        client = Mock()
        botoclient.return_value = client

        exc = NoCredentialsError()
        client.get_paginator.side_effect = exc

        code = main("awslogs groups --aws-region=eu-west-1".split())
        self.assertEqual(code, 5)
        self.assertEqual(mock_stderr.getvalue(), colored("""Unable to locate credentials
Check that you have provided valid credentials in one of the following ways:
* AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables.
* ~/.aws/credentials
* Instance profile credentials\n""", "red"))
<|endoftext|>


<commit_before>import logging
import unittest

from StringIO import StringIO

class TestArgParsing(unittest.TestCase):

    def setUp(self):
        unittest.TestCase.setUp(self)
        from script import parseargs

        self.parseargs = parseargs

    def test_parseargs(self):
        opts, args = self.parseargs(["foo"])

        self.assertEqual(opts.silent, False)
        self.assertEqual(args, [])

class TestMain(unittest.TestCase):

    def setUp(self):
        unittest.TestCase.setUp(self)

        root = logging.getLogger()
        buffer = logging.handlers.BufferingHandler(100)
        root.addHandler(buffer)
        self.buffer = buffer.buffer
        self.out = StringIO()
        self.err = StringIO()

    def main(self, *args, **kwargs):
        from script import main

        _kwargs = {
            "out": self.out,
            "err": self.err,
        }
        _kwargs.update(kwargs)
        return main(*args, **_kwargs)

    def test_main(self):
        result = self.main(["foo"])

        self.assertEqual(result, None)
        self.assertEqual(self.buffer, [])

    def test_main_verbose(self):
        result = self.main(["foo", "-vv"])

        self.assertEqual(result, None)
        self.assertEqual(len(self.buffer), 1)
        self.assertEqual(self.buffer[0].msg, "Ready to run")
<commit_msg>Test that log messages go to stderr.<commit_after>import logging
import unittest

from StringIO import StringIO

class TestArgParsing(unittest.TestCase):

    def setUp(self):
        unittest.TestCase.setUp(self)
        from script import parseargs

        self.parseargs = parseargs

    def test_parseargs(self):
        opts, args = self.parseargs(["foo"])

        self.assertEqual(opts.silent, False)
        self.assertEqual(args, [])

class TestMain(unittest.TestCase):

    def setUp(self):
        unittest.TestCase.setUp(self)

        root = logging.getLogger()
        buffer = logging.handlers.BufferingHandler(100)
        root.addHandler(buffer)
        self.buffer = buffer.buffer
        self.out = StringIO()
        self.err = StringIO()

    def main(self, *args, **kwargs):
        from script import main

        _kwargs = {
            "out": self.out,
            "err": self.err,
        }
        _kwargs.update(kwargs)
        return main(*args, **_kwargs)

    def test_main(self):
        result = self.main(["foo"])

        self.assertEqual(result, None)
        self.assertEqual(self.buffer, [])

    def test_main_verbose(self):
        result = self.main(["foo", "-vv"])

        self.assertEqual(result, None)
        self.assertEqual(len(self.buffer), 1)
        self.assertEqual(self.buffer[0].msg, "Ready to run")
        self.assertTrue("Ready to run" in self.err.getvalue())
<|endoftext|>


<commit_before>import unittest, requests, json, os

from app import *
from factories import OrganizationFactory, ProjectFactory, EventFactory, StoryFactory

class ApiTest(unittest.TestCase):

    def setUp(self):
        # Set up the database settings
        app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://postgres@localhost/civic_json_worker_test'
        db.create_all()
        self.app = app.test_client()

    def tearDown(self):
        db.drop_all()

    # Test API -----------------------

    def test_recent_events(self):
        '''
        Test that only the two most recent events are being returned
        '''
        organization = OrganizationFactory(name='Collective of Ericas')
        db.session.flush()
        # Create multiple events with different times
        oldest_event = EventFactory(organization_name=organization.name, name="Oldest event", start_time="2014-01-01T00:01:00")
        second_most_recent_event = EventFactory(organization_name=organization.name, name="Second most recent event", start_time="2014-01-01T01:01:00")
        most_recent_event = EventFactory(organization_name=organization.name, name="Most recent event", start_time="2014-01-02T01:00:00")
        old_event = EventFactory(organization_name=organization.name, name="Old event", start_time="2014-01-01T01:00:00")

        db.session.flush()
        response = self.app.get('/api/organizations/Collective%20of%20Ericas')
        response_json = json.loads(response.data)
        self.assertEqual(len(response_json['recent_events']), 2)
        self.assertEqual(response_json['recent_events'][0]['name'], "Most recent event")
        self.assertEqual(response_json['recent_events'][1]['name'], "Second most recent event")
        self.assertEqual(response_json['recent_events'][0]['organization_name'], "Collective of Ericas")

    def test_recent_stories(self):
        '''
        Test that only the two most recent stories are being returned
        '''
        organization = OrganizationFactory(name='Collective of Ericas')
        db.session.flush()

        StoryFactory(organization_name='Collective of Ericas', title='First Story')
        StoryFactory(organization_name='Collective of Ericas', title='Second Story')
        db.session.flush()

        response = self.app.get('/api/organizations/Collective%20of%20Ericas')
        response_json = json.loads(response.data)
        self.assertEqual(response_json['recent_stories'][0]['title'], 'First Story')
        self.assertEqual(response_json['recent_stories'][1]['title'], 'Second Story')

    def test_headers(self):
        OrganizationFactory()
        db.session.flush()

        response = self.app.get('/api/organizations')
        assert response.headers['Access-Control-Allow-Origin']  == '*'
        assert response.headers['Content-Type']  == 'application/json'

    def test_brigade_name_request(self):
        OrganizationFactory(name='Code for San Francisco')
        db.session.flush()

        response = self.app.get('/api/organizations/Code for San Francisco')
        response = json.loads(response.data)
        assert isinstance(response, dict)
        assert isinstance(response['city'], unicode)
        assert isinstance(response['recent_events'], list)
        assert isinstance(response['latitude'], float)
        assert isinstance(response['longitude'], float)
        assert isinstance(response['name'], unicode)
        assert isinstance(response['recent_projects'], list)
        assert isinstance(response['projects_list_url'], unicode)
        assert isinstance(response['rss'], unicode)
        assert isinstance(response['recent_stories'], list)
        assert isinstance(response['type'], unicode)
        assert isinstance(response['website'], unicode)

    def test_organizations(self):
        OrganizationFactory()
        db.session.flush()

        response = self.app.get('/api/organizations')
        response = json.loads(response.data)
        assert isinstance(response, dict)
        assert isinstance(response['objects'], list)
        assert isinstance(response['objects'][0]['city'], unicode)
        assert isinstance(response['objects'][0]['recent_events'], list)
        assert isinstance(response['objects'][0]['latitude'], float)
        assert isinstance(response['objects'][0]['longitude'], float)
        assert isinstance(response['objects'][0]['name'], unicode)
        assert isinstance(response['objects'][0]['recent_projects'], list)
        assert isinstance(response['objects'][0]['projects_list_url'], unicode)
        assert isinstance(response['objects'][0]['rss'], unicode)
        assert isinstance(response['objects'][0]['recent_stories'], list)
        assert isinstance(response['objects'][0]['type'], unicode)
        assert isinstance(response['objects'][0]['website'], unicode)

    def test_projects(self):
        ProjectFactory()
        db.session.flush()

        response = self.app.get('/api/projects')
        response = json.loads(response.data)
        assert isinstance(response, dict)
        assert isinstance(response['objects'], list)
        assert isinstance(response['objects'][0]['categories'], unicode)
        assert isinstance(response['objects'][0]['code_url'], unicode)
        assert isinstance(response['objects'][0]['description'], unicode)
        assert isinstance(response['objects'][0]['github_details'], dict)
        assert isinstance(response['objects'][0]['id'], int)
        assert isinstance(response['objects'][0]['link_url'], unicode)
        assert isinstance(response['objects'][0]['name'], unicode)
        assert isinstance(response['objects'][0]['organization'], dict)
        assert isinstance(response['objects'][0]['organization_name'], unicode)
        assert isinstance(response['objects'][0]['type'], unicode)

    def test_stories(self):
        StoryFactory()
        db.session.flush()

        response = self.app.get('/api/stories')
        response = json.loads(response.data)
        assert isinstance(response, dict)
        assert isinstance(response['objects'], list)
        assert isinstance(response['objects'][0]['id'], int)
        assert isinstance(response['objects'][0]['link'], unicode)
        assert isinstance(response['objects'][0]['organization'], dict)
        assert isinstance(response['objects'][0]['organization_name'], unicode)
        assert isinstance(response['objects'][0]['title'], unicode)
        assert isinstance(response['objects'][0]['type'], unicode)

    def test_events(self):
        EventFactory()
        db.session.flush()

        response = self.app.get('/api/events')
        response = json.loads(response.data)
        assert isinstance(response, dict)
        assert isinstance(response['objects'], list)
        assert isinstance(response['objects'][0]['description'], unicode)
        assert isinstance(response['objects'][0]['end_time'], unicode)
        assert isinstance(response['objects'][0]['event_url'], unicode)
        assert isinstance(response['objects'][0]['id'], int)
        assert isinstance(response['objects'][0]['location'], unicode)
        assert isinstance(response['objects'][0]['name'], unicode)
        assert isinstance(response['objects'][0]['organization'], dict)
        assert isinstance(response['objects'][0]['organization_name'], unicode)
        assert isinstance(response['objects'][0]['start_time'], unicode)

if __name__ == '__main__':
    unittest.main()
    <commit_msg>Tests for underscores.<commit_after>import unittest, requests, json, os
from urlparse import urlparse

from app import *
from factories import OrganizationFactory, ProjectFactory, EventFactory, StoryFactory

class ApiTest(unittest.TestCase):

    def setUp(self):
        # Set up the database settings
        app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://postgres@localhost/civic_json_worker_test'
        db.create_all()
        self.app = app.test_client()

    def tearDown(self):
        db.drop_all()

    # Test API -----------------------

    def test_recent_events(self):
        '''
        Test that only the two most recent events are being returned
        '''
        organization = OrganizationFactory(name='Collective of Ericas')
        db.session.flush()
        # Create multiple events with different times
        oldest_event = EventFactory(organization_name=organization.name, name="Oldest event", start_time="2014-01-01T00:01:00")
        second_most_recent_event = EventFactory(organization_name=organization.name, name="Second most recent event", start_time="2014-01-01T01:01:00")
        most_recent_event = EventFactory(organization_name=organization.name, name="Most recent event", start_time="2014-01-02T01:00:00")
        old_event = EventFactory(organization_name=organization.name, name="Old event", start_time="2014-01-01T01:00:00")

        db.session.flush()
        response = self.app.get('/api/organizations/Collective%20of%20Ericas')
        response_json = json.loads(response.data)
        self.assertEqual(len(response_json['recent_events']), 2)
        self.assertEqual(response_json['recent_events'][0]['name'], "Most recent event")
        self.assertEqual(response_json['recent_events'][1]['name'], "Second most recent event")
        self.assertEqual(response_json['recent_events'][0]['organization_name'], "Collective of Ericas")

    def test_recent_stories(self):
        '''
        Test that only the two most recent stories are being returned
        '''
        organization = OrganizationFactory(name='Collective of Ericas')
        db.session.flush()

        StoryFactory(organization_name='Collective of Ericas', title='First Story')
        StoryFactory(organization_name='Collective of Ericas', title='Second Story')
        db.session.flush()

        response = self.app.get('/api/organizations/Collective%20of%20Ericas')
        response_json = json.loads(response.data)
        self.assertEqual(response_json['recent_stories'][0]['title'], 'First Story')
        self.assertEqual(response_json['recent_stories'][1]['title'], 'Second Story')

    def test_headers(self):
        OrganizationFactory()
        db.session.flush()

        response = self.app.get('/api/organizations')
        assert response.headers['Access-Control-Allow-Origin']  == '*'
        assert response.headers['Content-Type']  == 'application/json'

    def test_brigade_name_request(self):
        OrganizationFactory(name='Code for San Francisco')
        db.session.flush()

        response = self.app.get('/api/organizations/Code for San Francisco')
        response = json.loads(response.data)
        assert isinstance(response, dict)
        assert isinstance(response['city'], unicode)
        assert isinstance(response['recent_events'], list)
        assert isinstance(response['latitude'], float)
        assert isinstance(response['longitude'], float)
        assert isinstance(response['name'], unicode)
        assert isinstance(response['recent_projects'], list)
        assert isinstance(response['projects_list_url'], unicode)
        assert isinstance(response['rss'], unicode)
        assert isinstance(response['recent_stories'], list)
        assert isinstance(response['type'], unicode)
        assert isinstance(response['website'], unicode)

    def test_organizations(self):
        OrganizationFactory()
        db.session.flush()

        response = self.app.get('/api/organizations')
        response = json.loads(response.data)
        assert isinstance(response, dict)
        assert isinstance(response['objects'], list)
        assert isinstance(response['objects'][0]['city'], unicode)
        assert isinstance(response['objects'][0]['recent_events'], list)
        assert isinstance(response['objects'][0]['latitude'], float)
        assert isinstance(response['objects'][0]['longitude'], float)
        assert isinstance(response['objects'][0]['name'], unicode)
        assert isinstance(response['objects'][0]['recent_projects'], list)
        assert isinstance(response['objects'][0]['projects_list_url'], unicode)
        assert isinstance(response['objects'][0]['rss'], unicode)
        assert isinstance(response['objects'][0]['recent_stories'], list)
        assert isinstance(response['objects'][0]['type'], unicode)
        assert isinstance(response['objects'][0]['website'], unicode)

    def test_projects(self):
        ProjectFactory()
        db.session.flush()

        response = self.app.get('/api/projects')
        response = json.loads(response.data)
        assert isinstance(response, dict)
        assert isinstance(response['objects'], list)
        assert isinstance(response['objects'][0]['categories'], unicode)
        assert isinstance(response['objects'][0]['code_url'], unicode)
        assert isinstance(response['objects'][0]['description'], unicode)
        assert isinstance(response['objects'][0]['github_details'], dict)
        assert isinstance(response['objects'][0]['id'], int)
        assert isinstance(response['objects'][0]['link_url'], unicode)
        assert isinstance(response['objects'][0]['name'], unicode)
        assert isinstance(response['objects'][0]['organization'], dict)
        assert isinstance(response['objects'][0]['organization_name'], unicode)
        assert isinstance(response['objects'][0]['type'], unicode)

    def test_stories(self):
        StoryFactory()
        db.session.flush()

        response = self.app.get('/api/stories')
        response = json.loads(response.data)
        assert isinstance(response, dict)
        assert isinstance(response['objects'], list)
        assert isinstance(response['objects'][0]['id'], int)
        assert isinstance(response['objects'][0]['link'], unicode)
        assert isinstance(response['objects'][0]['organization'], dict)
        assert isinstance(response['objects'][0]['organization_name'], unicode)
        assert isinstance(response['objects'][0]['title'], unicode)
        assert isinstance(response['objects'][0]['type'], unicode)

    def test_events(self):
        EventFactory()
        db.session.flush()

        response = self.app.get('/api/events')
        response = json.loads(response.data)
        assert isinstance(response, dict)
        assert isinstance(response['objects'], list)
        assert isinstance(response['objects'][0]['description'], unicode)
        assert isinstance(response['objects'][0]['end_time'], unicode)
        assert isinstance(response['objects'][0]['event_url'], unicode)
        assert isinstance(response['objects'][0]['id'], int)
        assert isinstance(response['objects'][0]['location'], unicode)
        assert isinstance(response['objects'][0]['name'], unicode)
        assert isinstance(response['objects'][0]['organization'], dict)
        assert isinstance(response['objects'][0]['organization_name'], unicode)
        assert isinstance(response['objects'][0]['start_time'], unicode)

    def test_underscores_and_spaces(self):
        organization = OrganizationFactory(name="Code for America")
        db.session.add(organization)
        db.session.commit()

        response = self.app.get('/api/organizations/Code for America')
        self.assertEqual(response.status_code,200)
        response = json.loads(response.data)
        scheme, netloc, path, _, _, _  = urlparse(response["all_events"])
        self.assertTrue("_" in path)
        self.assertFalse(" " in path)
        scheme, netloc, path, _, _, _  = urlparse(response["all_stories"])
        self.assertTrue("_" in path)
        self.assertFalse(" " in path)
        scheme, netloc, path, _, _, _  = urlparse(response["all_projects"])
        self.assertTrue("_" in path)
        self.assertFalse(" " in path)

        response = self.app.get('/api/organizations/Code_for_America')
        self.assertEqual(response.status_code,200)
        response = json.loads(response.data)
        self.assertEqual(response["name"], "Code for America")

        project = ProjectFactory(organization_name="Code for America")
        db.session.add(project)
        db.session.commit()

        response = self.app.get('/api/organizations/Code for America/projects')
        self.assertEqual(response.status_code,200)
        response = json.loads(response.data)
        self.assertEqual(response["objects"][0]["organization_name"], "Code for America")

        response = self.app.get('/api/organizations/Code_for_America/projects')
        self.assertEqual(response.status_code,200)
        response = json.loads(response.data)
        self.assertEqual(response["objects"][0]["organization_name"], "Code for America")

        event = EventFactory(organization_name="Code for America")
        db.session.add(event)
        db.session.commit()

        response = self.app.get('/api/organizations/Code for America/events')
        self.assertEqual(response.status_code,200)
        response = json.loads(response.data)
        self.assertEqual(response["objects"][0]["organization_name"], "Code for America")

        response = self.app.get('/api/organizations/Code_for_America/events')
        self.assertEqual(response.status_code,200)
        response = json.loads(response.data)
        self.assertEqual(response["objects"][0]["organization_name"], "Code for America")

        story = StoryFactory(organization_name="Code for America")
        db.session.add(story)
        db.session.commit()

        response = self.app.get('/api/organizations/Code for America/stories')
        self.assertEqual(response.status_code,200)
        response = json.loads(response.data)
        self.assertEqual(response["objects"][0]["organization_name"], "Code for America")

        response = self.app.get('/api/organizations/Code_for_America/stories')
        self.assertEqual(response.status_code,200)
        response = json.loads(response.data)
        self.assertEqual(response["objects"][0]["organization_name"], "Code for America")

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


<commit_before>from osv import fields, osv
from datetime import datetime as dt

'''
Class for holding the data
'''
class bsm_data(osv.osv_memory):
    _name = 'bsm.data'

    _columns={
        'bsm_imei_code': fields.char('IMEI Code', size=15),
        'bsm_product_code': fields.char('Product code', size=64),
        'bsm_date': fields.datetime('Import date'),
        'bsm_used': fields.boolean('Used')
        # TODO needs a relative field pointing to lot serials?
    }

    _defaults = {
        'bsm_used': False
    }

bsm_data()

class prodlot_bsm(osv.osv_memory):
    _name = 'stock.production.lot'
    _inherit = 'stock.production.lot'

    _columns = {
        'bsm_id': fields.many2one('bsm.data', 'BSM data', select=True),
        'bsm_imei_code': fields.related('bsm_id','bsm_imei_code',type='char', relation="bsm.data", string="IMEI"),
        'bsm_product_code': fields.related('bsm_id','bsm_product_code',type='char', relation="bsm.data", string="Product code")
    }

prodlot_bsm()

class stock_move_split_bsm(osv.osv_memory):
    _name = 'stock.move.split'
    _inherit = 'stock.move.split'

    selectedId = ""

    def split_lot(self, cr, uid, ids, context=None):
        print 'bsm split_lot'
        # Call super class
        if context:
            print str(context)
        super(stock_move_split_bsm, self).split_lot(cr, uid, ids, context=context)
        print 'selected id: ' + str(self.selectedId)
        if self.selectedId != "":
            print 'saving bsm id ' + str(self.selectedId) + ' to move'
            moves = self.pool.get('stock.move').browse(cr, uid, ids, context)
            bsm = self.pool.get('bsm.data').browse(cr, uid, self.selectedId, context)
            if moves and bsm:
                print 'move and bsm found'
                if moves[0].prodlot_id:
                    print 'production lot found'
                    moves[0].prodlot_id.write(cr, uid, {'bsm_id': bsm})
                else:
                    print 'saving to move'
                    moves[0].write(cr, uid, {'bsm_id':bsm})
                print 'done'
        return True

    def selected_bsm_on_change(self, cr, uid, ids, bsm_id, context=None):
        print 'select_bsm_on_change'

        value = {}
        if bsm_id:
            #bsm_ids = self.pool.get('bsm.data').search(cr, uid, [('id', '=', bsm_id)])
            print 'context: ' + str(context)
            print 'selected: ' + str(bsm_id) + ' move id: ' + str(ids)
            self.selectedId = bsm_id
            move = self.pool.get('stock.move').browse(cr, uid, ids)
            if move:
                #move.prodlot_id.bsm_id = self.pool.get('bsm_data').browse(cr, uid, context['selected_bsm'], context) # get selected value
                print 'saving bsm id'
                print 'move prodlot: ' + str(move.prodlot_id)
                bsm = self.pool.get('bsm_data').browse(cr, uid, bsm_id, context)
                move.write(cr, uid, {'bsm_id':bsm})
            #print 'selected: ' + str(bsm_ids)
            #value['bsm_id': bsm_ids]
        return True

    _columns = {
        'bsm_id': fields.many2one('bsm.data', 'Select BSM')#fields.related('line_ids','prodlot_id','bsm_id',type='char', relation="bsm.data", string="BSM")
        #
        #fields.related('line_ids','prodlot_id','bsm_id',type='char', relation="bsm.data", string="BSM")
    }

stock_move_split_bsm()

class stock_move_bsm(osv.osv_memory):
    _name = 'stock.move'
    _inherit = 'stock.move'

    _columns = {
        'bsm_id': fields.related('prodlot_id','bsm_id',type='char', relation="bsm.data", string="BSM"),

        #'bsm_product_code': fields.related('prodlot_id','bsm_id',type='char', relation="bsm.data", string="Product Code")

    }

stock_move_bsm()

'''
BSM file importer UI methods and data deserialization
'''
class bsm_importer(osv.osv_memory):

    LOCALFILEPATH = '/home/parallels/bsm/bsm.txt'

    _name='bsm.importer'
    #_inherit='mrp.product.produce'

    def _get_selection(self, cr, uid, context=None):
        print 'bsm.importer._get_selection'
        obj = self.pool.get('bsm.data')
        ids = obj.search(cr, uid, [])
        res = obj.read(cr, uid, ids, ['bsm_imei_code', 'bsm_product_code'], context)
        res = [(r['bsm_product_code'], r['bsm_imei_code']) for r in res]
        return res

    def getSerials(self, cr, uid, context=None):
        print 'getSerials()'
        # Read local file from the file system
        '''
        try:
            f = open(self.LOCALFILEPATH, 'r')
            for line in f:
                if line is not '' and line[0] is not '#':
                    params = line.split(';')
                    if len(params) == 3:
                        # read date
                        vals = {
                            'bsm_date': dt.strptime(params[0], "%d-%m-%Y %H:%M.%S")
                            'bsm_imei_code': params[1]
                            'bsm_product_code': params[2]
                        }

                        # create object
                        bsm_obj = self.pool.get('bsm.data')
                        existing = bsm_obj.search(cr, uid, [('bsm_imei_code','=',vals['bsm_imei_code'])], context=context)
                        if len(existing) == 0:
                            print 'Creating BSM serial'
                            new_device = bsm_obj.create(cr, uid, vals, context=context)
                        else:
                            print 'IMEI code exists already'
                    else:
                        raise ValueError("Line format not recognized")
            f.close()
        except IOError as ioe:
            print "I/O error({0}): {1}".format(ioe.errno, ioe.strerror)
        except ValueError as fe:
            print fe.strerror
        except:
            print 'lol random error'
        '''
        return True

    def addBSM(self, cr, uid, context=None):
        print 'addBSM'

        return {
            'view_id': 'bsm_data_view',
            'views': 'form',
            'type': 'ir.actions.act_window',
            'view_type': 'form',
            'res_model': 'bsm.data',
            #'res_id': prod.move_created_ids2[len(prod.move_created_ids2)-1].id,
            'view_mode': 'form',
            'target': 'new',
            'context': context,
       }

    _columns={
        'imei_selection' : fields.many2one('bsm.data', 'Select IMEI code', selection=_get_selection)
    }

bsm_importer()

<commit_msg>implementing lot split with bsm<commit_after>from osv import fields, osv
from datetime import datetime as dt

'''
Class for holding the data
'''
class bsm_data(osv.osv_memory):
    _name = 'bsm.data'

    _columns={
        'bsm_imei_code': fields.char('IMEI Code', size=15),
        'bsm_product_code': fields.char('Product code', size=64),
        'bsm_date': fields.datetime('Import date'),
        'bsm_used': fields.boolean('Used')
        # TODO needs a relative field pointing to lot serials?
    }

    _defaults = {
        'bsm_used': False
    }

bsm_data()

class prodlot_bsm(osv.osv_memory):
    _name = 'stock.production.lot'
    _inherit = 'stock.production.lot'

    _columns = {
        'bsm_id': fields.many2one('bsm.data', 'BSM data', select=True),
        'bsm_imei_code': fields.related('bsm_id','bsm_imei_code',type='char', relation="bsm.data", string="IMEI"),
        'bsm_product_code': fields.related('bsm_id','bsm_product_code',type='char', relation="bsm.data", string="Product code")
    }

prodlot_bsm()

class stock_move_split_bsm(osv.osv_memory):
    _name = 'stock.move.split'
    _inherit = 'stock.move.split'

    selectedId = ""

    def split_lot(self, cr, uid, ids, context=None):
        print 'bsm split_lot'
        # Call super class
        if context:
            print str(context)
        super(stock_move_split_bsm, self).split_lot(cr, uid, ids, context=context)
        print 'selected id: ' + str(self.selectedId)
        if self.selectedId != "":
            print 'saving bsm id ' + str(self.selectedId) + ' to move'
            moves = self.pool.get('stock.move').browse(cr, uid, ids, context)
            bsm = self.pool.get('bsm.data').browse(cr, uid, self.selectedId, context)
            if moves and bsm:
                print 'move and bsm found'
                print 'moves: ' + str(len(moves))
                if moves[0].prodlot_id:
                    print 'production lot found'
                    moves[0].prodlot_id.write(cr, uid, {'bsm_id': bsm})
                else:
                    print 'saving to move'
                    moves[0].write(cr, uid, {'bsm_id':bsm})
                print 'done'
        return True

    def selected_bsm_on_change(self, cr, uid, ids, bsm_id, context=None):
        print 'select_bsm_on_change'

        value = {}
        if bsm_id:
            #bsm_ids = self.pool.get('bsm.data').search(cr, uid, [('id', '=', bsm_id)])
            print 'context: ' + str(context)
            print 'selected: ' + str(bsm_id) + ' move id: ' + str(ids)
            self.selectedId = bsm_id
            move = self.pool.get('stock.move').browse(cr, uid, ids)
            if move:
                #move.prodlot_id.bsm_id = self.pool.get('bsm_data').browse(cr, uid, context['selected_bsm'], context) # get selected value
                print 'saving bsm id'
                print 'move prodlot: ' + str(move.prodlot_id)
                bsm = self.pool.get('bsm_data').browse(cr, uid, bsm_id, context)
                move.write(cr, uid, {'bsm_id':bsm})
            #print 'selected: ' + str(bsm_ids)
            #value['bsm_id': bsm_ids]
        return True

    _columns = {
        'bsm_id': fields.many2one('bsm.data', 'Select BSM')#fields.related('line_ids','prodlot_id','bsm_id',type='char', relation="bsm.data", string="BSM")
        #
        #fields.related('line_ids','prodlot_id','bsm_id',type='char', relation="bsm.data", string="BSM")
    }

stock_move_split_bsm()

class stock_move_bsm(osv.osv_memory):
    _name = 'stock.move'
    _inherit = 'stock.move'

    _columns = {
        'bsm_id': fields.related('prodlot_id','bsm_id',type='char', relation="bsm.data", string="BSM"),

        #'bsm_product_code': fields.related('prodlot_id','bsm_id',type='char', relation="bsm.data", string="Product Code")

    }

stock_move_bsm()

'''
BSM file importer UI methods and data deserialization
'''
class bsm_importer(osv.osv_memory):

    LOCALFILEPATH = '/home/parallels/bsm/bsm.txt'

    _name='bsm.importer'
    #_inherit='mrp.product.produce'

    def _get_selection(self, cr, uid, context=None):
        print 'bsm.importer._get_selection'
        obj = self.pool.get('bsm.data')
        ids = obj.search(cr, uid, [])
        res = obj.read(cr, uid, ids, ['bsm_imei_code', 'bsm_product_code'], context)
        res = [(r['bsm_product_code'], r['bsm_imei_code']) for r in res]
        return res

    def getSerials(self, cr, uid, context=None):
        print 'getSerials()'
        # Read local file from the file system
        '''
        try:
            f = open(self.LOCALFILEPATH, 'r')
            for line in f:
                if line is not '' and line[0] is not '#':
                    params = line.split(';')
                    if len(params) == 3:
                        # read date
                        vals = {
                            'bsm_date': dt.strptime(params[0], "%d-%m-%Y %H:%M.%S")
                            'bsm_imei_code': params[1]
                            'bsm_product_code': params[2]
                        }

                        # create object
                        bsm_obj = self.pool.get('bsm.data')
                        existing = bsm_obj.search(cr, uid, [('bsm_imei_code','=',vals['bsm_imei_code'])], context=context)
                        if len(existing) == 0:
                            print 'Creating BSM serial'
                            new_device = bsm_obj.create(cr, uid, vals, context=context)
                        else:
                            print 'IMEI code exists already'
                    else:
                        raise ValueError("Line format not recognized")
            f.close()
        except IOError as ioe:
            print "I/O error({0}): {1}".format(ioe.errno, ioe.strerror)
        except ValueError as fe:
            print fe.strerror
        except:
            print 'lol random error'
        '''
        return True

    def addBSM(self, cr, uid, context=None):
        print 'addBSM'

        return {
            'view_id': 'bsm_data_view',
            'views': 'form',
            'type': 'ir.actions.act_window',
            'view_type': 'form',
            'res_model': 'bsm.data',
            #'res_id': prod.move_created_ids2[len(prod.move_created_ids2)-1].id,
            'view_mode': 'form',
            'target': 'new',
            'context': context,
       }

    _columns={
        'imei_selection' : fields.many2one('bsm.data', 'Select IMEI code', selection=_get_selection)
    }

bsm_importer()

<|endoftext|>


<commit_before>import cufflinks as cf
import pandas as pd
import unittest
from nose.tools import assert_equals

##
## nosetests -xv tests.py --with-coverage --cover-package=cufflinks
##

class TestIPlot(unittest.TestCase):
	def setUp(self):
		self.df = pd.DataFrame(dict(x=[1, 2, 3], y=[4, 2, 1], c=[3, 1, 5]))

	def _iplot(self, df, **kwargs):
		return df.iplot(asFigure=True, **kwargs)

	def _ta(self, df, study, **kwargs):
		# print(study,kwargs)
		return df.ta_figure(study,**kwargs)

	def test_scatter_matrix(self):
		self.df.scatter_matrix(asFigure=True)

def test_irregular_subplots():
	df = cf.datagen.bubble(10, 50, mode='stocks')
	figs = cf.figures(df, [
		dict(kind='histogram', keys='x', color='blue'),
		dict(kind='scatter', mode='markers', x='x', y='y', size=5),
		dict(kind='scatter', mode='markers', x='x', y='y',
			 size=5, color='teal')],asList=True)
	figs.append(cf.datagen.lines(1).figure(bestfit=False, colors=['blue'],
										   bestfit_colors=['pink']))
	base_layout = cf.tools.get_base_layout(figs)
	sp = cf.subplots(figs, shape=(3, 2), base_layout=base_layout,
					 vertical_spacing=.15, horizontal_spacing=.03,
					 specs=[[{'rowspan': 2}, {}], [None, {}],
							[{'colspan': 2}, None]],
					 subplot_titles=['Histogram', 'Scatter 1',
									 'Scatter 2', 'Bestfit Line'])
	sp['layout'].update(showlegend=False)
	return sp

def bar_input_argument_tests():
	options = {
		'kind': ['bar', 'barh'],
		'barmode': ['stack', 'overlay', 'group'],
		'bargap': [0.1],
		'subplots': [True]
	}

	def bar_test(self, **kwargs):
		self._iplot(self.df, **kwargs)

	_generate_tests(TestIPlot, bar_test, 'bar', options)

def bar_row_input_argument_tests():
	options = {
		'kind': ['bar', 'barh'],
		'barmode': ['stack', 'overlay', 'group'],
		'bargap': [0.1],
		'subplots': [True]
	}

	def bar_row_test(self, **kwargs):
		self._iplot(self.df.ix[1], **kwargs)

	_generate_tests(TestIPlot, bar_row_test, 'bar_row', options)

def histogram_input_argument_tests():
	options = {
		'barmode': ['stack'],
		'bins': [20],
		'orientation': ['h', 'v', 'horizontal', 'vertical'],
		'histnorm': ['probability','percent','density'],
		'subplots': [True],
		'line_color':['blue','#fa0']
	}

	def histogram_test(self, **kwargs):
		self._iplot(self.df, kind='histogram', **kwargs)

	_generate_tests(TestIPlot, histogram_test, 'histogram', options)

def heatmap_input_argument_tests():
	options = {}

	def heatmap_test(self, **kwargs):
		self._iplot(self.df, kind='heatmap', **kwargs)
		df=cf.datagen.heatmap()
		df.index=cf.pd.period_range('1/1/2016',periods=5)
		df.iplot(kind='heatmap')

	_generate_tests(TestIPlot, heatmap_test, 'heatmap', options)

def box_input_argument_tests():
	options = {}

	def box_test(self, **kwargs):
		self._iplot(self.df, kind='box', **kwargs)

	_generate_tests(TestIPlot, box_test, 'box', options)

def area_plot_input_argument_tests():
	options = {
		'fill': [True],
		'opacity': [1],
		'kind': ['area']
	}

	def area_test(self, **kwargs):
		self._iplot(self.df, **kwargs)

	_generate_tests(TestIPlot, area_test, 'area', options)

def scatter_plot_input_argument_tests():
	options = {
		'x': ['x'],
		'y': ['y'],
		'mode': ['markers'],
		'symbol': ['dot'],
		'colors': [['orange', 'teal']],
		'size': [10]
	}

	def scatter_test(self, **kwargs):
		self._iplot(self.df, **kwargs)

	_generate_tests(TestIPlot, scatter_test, 'scatter', options)

def bubble_chart_argument_tests():
	options = {
		'x': ['x'], 'y': ['y'], 'size': ['c']
	}

	def bubble_test(self, **kwargs):
		self._iplot(self.df, **kwargs)

	_generate_tests(TestIPlot, bubble_test, 'bubble', options)

def subplot_input_argument_tests():
	options = {
		'shape': [(3, 1)],
		'shared_xaxes': [True],
		'vertical_spacing': [0.02],
		'fill': [True],
		'subplot_titles': [True],
		'legend': [False]
	}

	def subplot_test(self, **kwargs):
		self._iplot(self.df, subplots=True, **kwargs)

	_generate_tests(TestIPlot, subplot_test, 'subplots', options)

def shape_input_argument_tests():
	df = cf.datagen.lines(3, columns=['a', 'b', 'c'])
	options = {
		'hline': [
			[2, 4],
			[dict(y=-1, color='blue', width=3),
			 dict(y=1, color='pink', dash='dash')]],
		'vline': [['2015-02-10']],
		'hspan': [[(-1, 1), (2, 5)]],
		'vspan': [{
			'x0': '2015-02-15', 'x1': '2015-03-15',
			'color': 'teal', 'fill': True, 'opacity': .4}]
	}

	def shape_tests(self, **kwargs):
		self._iplot(df, **kwargs)

	_generate_tests(TestIPlot, shape_tests, 'shape', options)

# colors

def color_normalize_tests():
	c=dict([(k.lower(),v.upper()) for k,v in list(cf.cnames.items())])
	d={}
	for k,v in list(c.items()):
		assert_equals(v,cf.normalize(k).upper())
	return 2

# technical analysis

def ta_tests():
	df=cf.datagen.lines(1,500)
	studies=['sma']
	options = {
		'periods' : [14]
	}

	def ta_tests(self, studies, **kwargs):
		for study in studies:
			self._ta(df, study, **kwargs)

	_generate_tests(TestIPlot, ta_tests, 'ta', options)

# test generators

def _generate_tests(test_class, test_func, test_name, options):
	from itertools import chain, combinations, product

	def powerset(iterable):
		"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
		s = list(iterable)
		return chain.from_iterable(combinations(s, r)
								   for r in range(len(s) + 1))
	key_value_tuple = {}
	for option, values in list(options.items()):
		key_value_tuple[option] = [(option, i) for i in values]

	for option_groups in powerset(key_value_tuple.values()):
		for input_kwargs in product(*option_groups):
			kwargs = {i[0]: i[1] for i in input_kwargs}
			setattr(
				test_class,
				'test_{}_{}'.format(test_name, '__'.join([
					'_'.join([str(s) for s in i])
					for i in kwargs.items()])),
				_generate_test(test_func, **kwargs))

def _generate_test(test_func, **kwargs):
	def test(self):
		test_func(self, **kwargs)

	return test

bar_input_argument_tests()
bar_row_input_argument_tests()
histogram_input_argument_tests()
box_input_argument_tests()
heatmap_input_argument_tests()
area_plot_input_argument_tests()
scatter_plot_input_argument_tests()
bubble_chart_argument_tests()
subplot_input_argument_tests()
shape_input_argument_tests()
test_irregular_subplots()
color_normalize_tests()
# ta_tests()

if __name__ == '__main__':
	unittest.main()
<commit_msg>update tests<commit_after>import cufflinks as cf
import pandas as pd
import unittest
from nose.tools import assert_equals

##
## nosetests -xv tests.py --with-coverage --cover-package=cufflinks
##

class TestIPlot(unittest.TestCase):
	def setUp(self):
		self.df = pd.DataFrame(dict(x=[1, 2, 3], y=[4, 2, 1], c=[3, 1, 5]))

	def _iplot(self, df, **kwargs):
		return df.iplot(asFigure=True, **kwargs)

	def _ta(self, df, study, **kwargs):
		# print(study,kwargs)
		return df.ta_figure(study,**kwargs)

	def test_scatter_matrix(self):
		self.df.scatter_matrix(asFigure=True)

def test_irregular_subplots():
	df = cf.datagen.bubble(10, 50, mode='stocks')
	figs = cf.figures(df, [
		dict(kind='histogram', keys='x', color='blue'),
		dict(kind='scatter', mode='markers', x='x', y='y', size=5),
		dict(kind='scatter', mode='markers', x='x', y='y',
			 size=5, color='teal')],asList=True)
	figs.append(cf.datagen.lines(1).figure(bestfit=False, colors=['blue'],
										   bestfit_colors=['pink']))
	base_layout = cf.tools.get_base_layout(figs)
	sp = cf.subplots(figs, shape=(3, 2), base_layout=base_layout,
					 vertical_spacing=.15, horizontal_spacing=.03,
					 specs=[[{'rowspan': 2}, {}], [None, {}],
							[{'colspan': 2}, None]],
					 subplot_titles=['Histogram', 'Scatter 1',
									 'Scatter 2', 'Bestfit Line'])
	sp['layout'].update(showlegend=False)
	return sp

def bar_input_argument_tests():
	options = {
		'kind': ['bar', 'barh'],
		'barmode': ['stack', 'overlay', 'group'],
		'bargap': [0.1],
		'subplots': [True]
	}

	def bar_test(self, **kwargs):
		self._iplot(self.df, **kwargs)

	_generate_tests(TestIPlot, bar_test, 'bar', options)

def bar_row_input_argument_tests():
	options = {
		'kind': ['bar', 'barh'],
		'barmode': ['stack', 'overlay', 'group'],
		'bargap': [0.1],
		'subplots': [True]
	}

	def bar_row_test(self, **kwargs):
		self._iplot(self.df.ix[1], **kwargs)

	_generate_tests(TestIPlot, bar_row_test, 'bar_row', options)

def histogram_input_argument_tests():
	options = {
		'barmode': ['stack'],
		'bins': [20],
		'orientation': ['h', 'v', 'horizontal', 'vertical'],
		'histnorm': ['probability','percent','density'],
		'subplots': [True],
		'line_color':['blue','#fa0']
	}

	def histogram_test(self, **kwargs):
		self._iplot(self.df, kind='histogram', **kwargs)

	_generate_tests(TestIPlot, histogram_test, 'histogram', options)

def heatmap_input_argument_tests():
	options = {}

	def heatmap_test(self, **kwargs):
		self._iplot(self.df, kind='heatmap', **kwargs)
		df=cf.datagen.heatmap()
		df.index=cf.pd.period_range('1/1/2016',periods=5)
		self._iplot(df,kind='heatmap', **kwargs)
		# df.iplot(kind='heatmap')

	_generate_tests(TestIPlot, heatmap_test, 'heatmap', options)

def box_input_argument_tests():
	options = {}

	def box_test(self, **kwargs):
		self._iplot(self.df, kind='box', **kwargs)

	_generate_tests(TestIPlot, box_test, 'box', options)

def area_plot_input_argument_tests():
	options = {
		'fill': [True],
		'opacity': [1],
		'kind': ['area']
	}

	def area_test(self, **kwargs):
		self._iplot(self.df, **kwargs)

	_generate_tests(TestIPlot, area_test, 'area', options)

def scatter_plot_input_argument_tests():
	options = {
		'x': ['x'],
		'y': ['y'],
		'mode': ['markers'],
		'symbol': ['dot'],
		'colors': [['orange', 'teal']],
		'size': [10]
	}

	def scatter_test(self, **kwargs):
		self._iplot(self.df, **kwargs)

	_generate_tests(TestIPlot, scatter_test, 'scatter', options)

def bubble_chart_argument_tests():
	options = {
		'x': ['x'], 'y': ['y'], 'size': ['c']
	}

	def bubble_test(self, **kwargs):
		self._iplot(self.df, **kwargs)

	_generate_tests(TestIPlot, bubble_test, 'bubble', options)

def subplot_input_argument_tests():
	options = {
		'shape': [(3, 1)],
		'shared_xaxes': [True],
		'vertical_spacing': [0.02],
		'fill': [True],
		'subplot_titles': [True],
		'legend': [False]
	}

	def subplot_test(self, **kwargs):
		self._iplot(self.df, subplots=True, **kwargs)

	_generate_tests(TestIPlot, subplot_test, 'subplots', options)

def shape_input_argument_tests():
	df = cf.datagen.lines(3, columns=['a', 'b', 'c'])
	options = {
		'hline': [
			[2, 4],
			[dict(y=-1, color='blue', width=3),
			 dict(y=1, color='pink', dash='dash')]],
		'vline': [['2015-02-10']],
		'hspan': [[(-1, 1), (2, 5)]],
		'vspan': [{
			'x0': '2015-02-15', 'x1': '2015-03-15',
			'color': 'teal', 'fill': True, 'opacity': .4}]
	}

	def shape_tests(self, **kwargs):
		self._iplot(df, **kwargs)

	_generate_tests(TestIPlot, shape_tests, 'shape', options)

# colors

def color_normalize_tests():
	c=dict([(k.lower(),v.upper()) for k,v in list(cf.cnames.items())])
	d={}
	for k,v in list(c.items()):
		assert_equals(v,cf.normalize(k).upper())
	return 2

# technical analysis

def ta_tests():
	df=cf.datagen.lines(1,500)
	studies=['sma']
	options = {
		'periods' : [14]
	}

	def ta_tests(self, studies, **kwargs):
		for study in studies:
			self._ta(df, study, **kwargs)

	_generate_tests(TestIPlot, ta_tests, 'ta', options)

# test generators

def _generate_tests(test_class, test_func, test_name, options):
	from itertools import chain, combinations, product

	def powerset(iterable):
		"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
		s = list(iterable)
		return chain.from_iterable(combinations(s, r)
								   for r in range(len(s) + 1))
	key_value_tuple = {}
	for option, values in list(options.items()):
		key_value_tuple[option] = [(option, i) for i in values]

	for option_groups in powerset(key_value_tuple.values()):
		for input_kwargs in product(*option_groups):
			kwargs = {i[0]: i[1] for i in input_kwargs}
			setattr(
				test_class,
				'test_{}_{}'.format(test_name, '__'.join([
					'_'.join([str(s) for s in i])
					for i in kwargs.items()])),
				_generate_test(test_func, **kwargs))

def _generate_test(test_func, **kwargs):
	def test(self):
		test_func(self, **kwargs)

	return test

bar_input_argument_tests()
bar_row_input_argument_tests()
histogram_input_argument_tests()
box_input_argument_tests()
heatmap_input_argument_tests()
area_plot_input_argument_tests()
scatter_plot_input_argument_tests()
bubble_chart_argument_tests()
subplot_input_argument_tests()
shape_input_argument_tests()
test_irregular_subplots()
color_normalize_tests()
# ta_tests()

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


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

import unittest

from hot_redis import List, Set

class ListTests(unittest.TestCase):

    def test_value(self):
        a = [4, 2, 0]
        self.assertEquals(List(a), a)

    def test_iter(self):
        a = [4, 2, 0]
        for i, x in enumerate(List(a)):
            self.assertEquals(x, a[i])

    def test_add(self):
        a = [4, 2, 0]
        b = [6, 6, 6]
        self.assertEquals(a + b, List(a) + List(b))
        self.assertEquals(a + b, List(a) + b)
        self.assertRaises(TypeError, lambda: List(a) + ["wulgus"])

    def test_iadd(self):
        a = [4, 2, 0]
        b = [6, 6, 6]
        c = List(a)
        d = List(b)
        d += c
        c += b
        self.assertEquals(a + b, c)
        self.assertEquals(b + a, d)
        def iadd_other_type(l):
            l += ["wulgus"]
        self.assertRaises(TypeError, iadd_other_type, c)

    def test_mul(self):
        a = [4, 2, 0]
        i = 9000
        self.assertEquals(a * i, List(a) * i)

    def test_imul(self):
        a = [4, 2, 0]
        b = List(a)
        i = 9000
        b *= i
        self.assertEquals(a * i, b)

    def test_len(self):
        a = [4, 2, 0]
        self.assertEquals(len(a), len(List(a)))

    def test_get(self):
        a = [4, 2, 0] * 10
        b = List(a)
        self.assertEquals(a[4], b[4])
        self.assertEquals(a[3:12], b[3:12])
        self.assertEquals(a[:-5], b[:-5])
        self.assertRaises(IndexError, lambda: b[len(b)])

    def test_set(self):
        a = [4, 2, 0]
        b = List(a)
        i = 9000
        a[1] = i
        self.assertNotEquals(a, b)
        b[1] = i
        self.assertEquals(a, b)
        def set_other_type(l):
            l[1] = "wulgus"
        self.assertRaises(TypeError, set_other_type, b)
        # todo: slice

    def test_del(self):
        a = [4, 2, 0]
        b = List(a)
        del a[1]
        self.assertNotEquals(a, b)
        del b[1]
        self.assertEquals(a, b)
        # todo: slice?

    def test_extend(self):
        a = [4, 2, 0]
        b = [6, 6, 6]
        c = List(a)
        a.extend(b)
        c.extend(b)
        self.assertEquals(a, c)
        self.assertRaises(TypeError, lambda: c.extend(["wulgus"]))

    def test_append(self):
        a = [4, 2, 0]
        b = List(a)
        i = 9000
        a.append(i)
        b.append(i)
        self.assertEquals(a, b)
        self.assertRaises(TypeError, lambda: b.append("wulgus"))

    def test_insert(self):
        a = [4, 2, 0]
        b = List(a)
        i = 9000
        a.insert(1, i)
        b.insert(1, i)
        self.assertEquals(a, b)
        self.assertRaises(TypeError, lambda: b.insert(1, "wulgus"))

    def test_pop(self):
        a = [4, 2, 0] * 10
        b = List(a)
        a.pop()
        b.pop()
        self.assertEquals(a, b)
        a.pop(0)
        b.pop(0)
        self.assertEquals(a, b)
        a.pop(-1)
        b.pop(-1)
        self.assertEquals(a, b)
        a.pop(20)
        b.pop(20)
        self.assertEquals(a, b)

    def test_reverse(self):
        a = [4, 2, 0]
        b = List(a)
        a.reverse()
        b.reverse()
        self.assertEquals(a, b)

    def test_index(self):
        a = [4, 2, 0] * 10
        b = List(a)
        self.assertEquals(a.index(2), b.index(2))
        self.assertRaises(ValueError, lambda: b.index(9000))

    def test_count(self):
        a = [4, 2, 0] * 10
        b = List(a)
        self.assertEquals(a.count(2), b.count(2))
        self.assertEquals(a.count(9000), b.count(9000))

    def test_sort(self):
        a = [4, 2, 0] * 10
        b = List(a)
        a.sort()
        b.sort()
        self.assertEquals(a, b)
        a.sort(reverse=True)
        b.sort(reverse=True)
        self.assertEquals(a, b)

class SetTests(unittest.TestCase):

    def test_value(self):
        a = set([4, 2, 0])
        self.assertEquals(Set(a), a)

    def test_add(self):
        a = set([4, 2, 0])
        b = Set(a)
        i = 9000
        a.add(i)
        b.add(i)
        self.assertEquals(b, a)
        self.assertRaises(TypeError, lambda: b.add("wulgus"))

    def test_update(self):
        a = set([4, 2, 0])
        b = set([6, 6, 6])
        c = set([0, 6, 9])
        d = Set(a)
        a.update(b, c)
        d.update(b, c)
        self.assertEquals(d, a)
        self.assertRaises(TypeError, lambda: d.update(set(["wulgus"])))

    def test_pop(self):
        a = Set([4, 2, 0])
        i = len(a)
        b = a.pop()
        self.assertEquals(len(a), i - 1)
        self.assertNotIn(b, a)

    def test_clear(self):
        a = Set([4, 2, 0])
        a.clear()
        self.assertEquals(len(a), 0)

    def test_remove(self):
        a = Set([4, 2, 0])
        i = len(a)
        b = 4
        a.remove(b)
        self.assertEquals(len(a), i - 1)
        self.assertNotIn(b, a)
        self.assertRaises(TypeError, lambda: a.remove("wulgus"))
        self.assertRaises(KeyError, lambda: a.remove(9000))

    def test_discard(self):
        a = Set([4, 2, 0])
        i = len(a)
        b = 4
        a.discard(b)
        self.assertEquals(len(a), i - 1)
        self.assertNotIn(b, a)
        self.assertRaises(TypeError, lambda: a.discard("wulgus"))
        self.assertEquals(a.discard(9000), None)

    def test_len(self):
        a = set([4, 2, 0])
        b = Set(a)
        self.assertEquals(len(a), len(b))

    def test_contains(self):
        a = Set([4, 2, 0])
        self.assertIn(4, a)
        self.assertNotIn(9000, a)

    def test_and(self):
        a = set([4, 2, 0])
        b = set([4, 2, 1])
        self.assertEquals(a & b, Set(a) & b)

    def test_iand(self):
        a = set([4, 2, 0])
        b = set([4, 2, 1])
        c = Set(a)
        a &= b
        c &= b
        self.assertEquals(c, a)

    def test_rand(self):
        a = set([4, 2, 0])
        b = set([4, 2, 1])
        self.assertEquals(b & a, b & Set(a))
        self.assertEquals(b & a, Set(b) & Set(a))

    def test_intersection(self):
        a = set([4, 2, 0])
        b = set([4, 2, 1])
        c = set([4, 2, 2])
        d = Set(a)
        e = a.intersection(b, c)
        self.assertEquals(a.intersection(b), d.intersection(b))
        self.assertEquals(e, d.intersection(b, c))
        self.assertEquals(e, d.intersection(Set(b), c))
        self.assertEquals(e, d.intersection(b, Set(c)))
        self.assertEquals(e, d.intersection(Set(b), Set(c)))

    def test_intersection_update(self):
        a = set([4, 2, 0])
        b = set([4, 2, 1])
        c = set([4, 2, 2])
        d = a.copy()
        d.intersection_update(b)
        e = Set(a)
        e.intersection_update(b)
        self.assertEquals(e, d)
        d = a.copy()
        d.intersection_update(b, c)
        e = Set(a)
        e.intersection_update(b, c)
        self.assertEquals(e, d)
        e = Set(a)
        e.intersection_update(Set(b), c)
        self.assertEquals(e, d)
        e = Set(a)
        e.intersection_update(b, Set(c))
        self.assertEquals(e, d)
        e = Set(a)
        e.intersection_update(Set(b), Set(c))
        self.assertEquals(e, d)

    def test_disjoint(self):
        a = set([4, 2, 0])
        b = Set(a)
        c = Set([4, 2, 1])
        d = set([6, 6, 6])
        e = Set(d)
        self.assertFalse(b.isdisjoint(a))
        self.assertFalse(b.isdisjoint(c))
        self.assertTrue(b.isdisjoint(d))
        self.assertTrue(b.isdisjoint(e))

    def test_cmp(self):
        a = set([4, 2, 0])
        b = set([6, 6, 6])
        c = Set(a)
        d = Set(b)
        self.assertEquals(a > b, c > d)
        self.assertEquals(a < b, c < d)
        self.assertEquals(a > b, c > b)
        self.assertEquals(a < b, c < b)
        self.assertEquals(a >= b, c >= d)
        self.assertEquals(a <= b, c <= d)
        self.assertEquals(a >= b, c >= b)
        self.assertEquals(a <= b, c <= b)

if __name__ == "__main__":
    unittest.main()
<commit_msg>set superset/subset tests<commit_after>#!/usr/bin/env python

import unittest

from hot_redis import List, Set

class ListTests(unittest.TestCase):

    def test_value(self):
        a = [4, 2, 0]
        self.assertEquals(List(a), a)

    def test_iter(self):
        a = [4, 2, 0]
        for i, x in enumerate(List(a)):
            self.assertEquals(x, a[i])

    def test_add(self):
        a = [4, 2, 0]
        b = [6, 6, 6]
        self.assertEquals(a + b, List(a) + List(b))
        self.assertEquals(a + b, List(a) + b)
        self.assertRaises(TypeError, lambda: List(a) + ["wulgus"])

    def test_iadd(self):
        a = [4, 2, 0]
        b = [6, 6, 6]
        c = List(a)
        d = List(b)
        d += c
        c += b
        self.assertEquals(a + b, c)
        self.assertEquals(b + a, d)
        def iadd_other_type(l):
            l += ["wulgus"]
        self.assertRaises(TypeError, iadd_other_type, c)

    def test_mul(self):
        a = [4, 2, 0]
        i = 9000
        self.assertEquals(a * i, List(a) * i)

    def test_imul(self):
        a = [4, 2, 0]
        b = List(a)
        i = 9000
        b *= i
        self.assertEquals(a * i, b)

    def test_len(self):
        a = [4, 2, 0]
        self.assertEquals(len(a), len(List(a)))

    def test_get(self):
        a = [4, 2, 0] * 10
        b = List(a)
        self.assertEquals(a[4], b[4])
        self.assertEquals(a[3:12], b[3:12])
        self.assertEquals(a[:-5], b[:-5])
        self.assertRaises(IndexError, lambda: b[len(b)])

    def test_set(self):
        a = [4, 2, 0]
        b = List(a)
        i = 9000
        a[1] = i
        self.assertNotEquals(a, b)
        b[1] = i
        self.assertEquals(a, b)
        def set_other_type(l):
            l[1] = "wulgus"
        self.assertRaises(TypeError, set_other_type, b)
        # todo: slice

    def test_del(self):
        a = [4, 2, 0]
        b = List(a)
        del a[1]
        self.assertNotEquals(a, b)
        del b[1]
        self.assertEquals(a, b)
        # todo: slice?

    def test_extend(self):
        a = [4, 2, 0]
        b = [6, 6, 6]
        c = List(a)
        a.extend(b)
        c.extend(b)
        self.assertEquals(a, c)
        self.assertRaises(TypeError, lambda: c.extend(["wulgus"]))

    def test_append(self):
        a = [4, 2, 0]
        b = List(a)
        i = 9000
        a.append(i)
        b.append(i)
        self.assertEquals(a, b)
        self.assertRaises(TypeError, lambda: b.append("wulgus"))

    def test_insert(self):
        a = [4, 2, 0]
        b = List(a)
        i = 9000
        a.insert(1, i)
        b.insert(1, i)
        self.assertEquals(a, b)
        self.assertRaises(TypeError, lambda: b.insert(1, "wulgus"))

    def test_pop(self):
        a = [4, 2, 0] * 10
        b = List(a)
        a.pop()
        b.pop()
        self.assertEquals(a, b)
        a.pop(0)
        b.pop(0)
        self.assertEquals(a, b)
        a.pop(-1)
        b.pop(-1)
        self.assertEquals(a, b)
        a.pop(20)
        b.pop(20)
        self.assertEquals(a, b)

    def test_reverse(self):
        a = [4, 2, 0]
        b = List(a)
        a.reverse()
        b.reverse()
        self.assertEquals(a, b)

    def test_index(self):
        a = [4, 2, 0] * 10
        b = List(a)
        self.assertEquals(a.index(2), b.index(2))
        self.assertRaises(ValueError, lambda: b.index(9000))

    def test_count(self):
        a = [4, 2, 0] * 10
        b = List(a)
        self.assertEquals(a.count(2), b.count(2))
        self.assertEquals(a.count(9000), b.count(9000))

    def test_sort(self):
        a = [4, 2, 0] * 10
        b = List(a)
        a.sort()
        b.sort()
        self.assertEquals(a, b)
        a.sort(reverse=True)
        b.sort(reverse=True)
        self.assertEquals(a, b)

class SetTests(unittest.TestCase):

    def test_value(self):
        a = set([4, 2, 0])
        self.assertEquals(Set(a), a)

    def test_add(self):
        a = set([4, 2, 0])
        b = Set(a)
        i = 9000
        a.add(i)
        b.add(i)
        self.assertEquals(b, a)
        self.assertRaises(TypeError, lambda: b.add("wulgus"))

    def test_update(self):
        a = set([4, 2, 0])
        b = set([6, 6, 6])
        c = set([0, 6, 9])
        d = Set(a)
        a.update(b, c)
        d.update(b, c)
        self.assertEquals(d, a)
        self.assertRaises(TypeError, lambda: d.update(set(["wulgus"])))

    def test_pop(self):
        a = Set([4, 2, 0])
        i = len(a)
        b = a.pop()
        self.assertEquals(len(a), i - 1)
        self.assertNotIn(b, a)

    def test_clear(self):
        a = Set([4, 2, 0])
        a.clear()
        self.assertEquals(len(a), 0)

    def test_remove(self):
        a = Set([4, 2, 0])
        i = len(a)
        b = 4
        a.remove(b)
        self.assertEquals(len(a), i - 1)
        self.assertNotIn(b, a)
        self.assertRaises(TypeError, lambda: a.remove("wulgus"))
        self.assertRaises(KeyError, lambda: a.remove(9000))

    def test_discard(self):
        a = Set([4, 2, 0])
        i = len(a)
        b = 4
        a.discard(b)
        self.assertEquals(len(a), i - 1)
        self.assertNotIn(b, a)
        self.assertRaises(TypeError, lambda: a.discard("wulgus"))
        self.assertEquals(a.discard(9000), None)

    def test_len(self):
        a = set([4, 2, 0])
        b = Set(a)
        self.assertEquals(len(a), len(b))

    def test_contains(self):
        a = Set([4, 2, 0])
        self.assertIn(4, a)
        self.assertNotIn(9000, a)

    def test_and(self):
        a = set([4, 2, 0])
        b = set([4, 2, 1])
        self.assertEquals(a & b, Set(a) & b)

    def test_iand(self):
        a = set([4, 2, 0])
        b = set([4, 2, 1])
        c = Set(a)
        a &= b
        c &= b
        self.assertEquals(c, a)

    def test_rand(self):
        a = set([4, 2, 0])
        b = set([4, 2, 1])
        self.assertEquals(b & a, b & Set(a))
        self.assertEquals(b & a, Set(b) & Set(a))

    def test_intersection(self):
        a = set([4, 2, 0])
        b = set([4, 2, 1])
        c = set([4, 2, 2])
        d = Set(a)
        e = a.intersection(b, c)
        self.assertEquals(a.intersection(b), d.intersection(b))
        self.assertEquals(e, d.intersection(b, c))
        self.assertEquals(e, d.intersection(Set(b), c))
        self.assertEquals(e, d.intersection(b, Set(c)))
        self.assertEquals(e, d.intersection(Set(b), Set(c)))

    def test_intersection_update(self):
        a = set([4, 2, 0])
        b = set([4, 2, 1])
        c = set([4, 2, 2])
        d = a.copy()
        d.intersection_update(b)
        e = Set(a)
        e.intersection_update(b)
        self.assertEquals(e, d)
        d = a.copy()
        d.intersection_update(b, c)
        e = Set(a)
        e.intersection_update(b, c)
        self.assertEquals(e, d)
        e = Set(a)
        e.intersection_update(Set(b), c)
        self.assertEquals(e, d)
        e = Set(a)
        e.intersection_update(b, Set(c))
        self.assertEquals(e, d)
        e = Set(a)
        e.intersection_update(Set(b), Set(c))
        self.assertEquals(e, d)

    def test_disjoint(self):
        a = set([4, 2, 0])
        b = Set(a)
        c = Set([4, 2, 1])
        d = set([6, 6, 6])
        e = Set(d)
        self.assertFalse(b.isdisjoint(a))
        self.assertFalse(b.isdisjoint(c))
        self.assertTrue(b.isdisjoint(d))
        self.assertTrue(b.isdisjoint(e))

    def test_cmp(self):
        a = set([4, 2, 0])
        b = set([6, 6, 6])
        c = Set(a)
        d = Set(b)
        self.assertEquals(a > b, c > d)
        self.assertEquals(a < b, c < d)
        self.assertEquals(a > b, c > b)
        self.assertEquals(a < b, c < b)
        self.assertEquals(a >= b, c >= d)
        self.assertEquals(a <= b, c <= d)
        self.assertEquals(a >= b, c >= b)
        self.assertEquals(a <= b, c <= b)
        self.assertEquals(a.issubset(b), c.issubset(d))
        self.assertEquals(a.issuperset(b), c.issuperset(d))
        self.assertEquals(a.issubset(b), c.issubset(b))
        self.assertEquals(a.issuperset(b), c.issuperset(b))

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