<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

from os import path
import unittest
import tempfile

from poor_smime_sign import smime_sign, smime_verify

def _read_file(abs_path):
        with file(abs_path, 'r') as f:
            return f.read()

class PoorSmimeSignTest(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.signer_cert_path = path.join(path.dirname(__file__), "files/signer.cert")
        cls.signer_key_path = path.join(path.dirname(__file__), "files/signer.pem")
        cls.recipient_cert_path = path.join(path.dirname(__file__), "files/recipient.cert")
        cls.manifest_json_path = path.join(path.dirname(__file__), "files/manifest.json")

        cls.signature_smime_path = path.join(path.dirname(__file__), "files/signature.smime")
        cls.signature_pem_path = path.join(path.dirname(__file__), "files/signature.pem")
        cls.signature_der_path = path.join(path.dirname(__file__), "files/signature.der")

        cls.signature_smime = _read_file(cls.signature_smime_path)
        cls.signature_pem = _read_file(cls.signature_pem_path)
        cls.signature_der = _read_file(cls.signature_der_path)

        cls.maniphest_json = _read_file(cls.manifest_json_path)

    def test_smime_fixture(self):
        self.assertTrue(
            smime_verify(
                signer_cert_path=self.signer_cert_path,
                content_path=self.manifest_json_path,
                signature_path=self.signature_smime_path,
                signature_format='SMIME',
            )
        )

    def test_pem_fixture(self):
        self.assertTrue(
            smime_verify(
                signer_cert_path=self.signer_cert_path,
                content_path=self.manifest_json_path,
                signature_path=self.signature_pem_path,
                signature_format='PEM',
            )
        )

    def test_der_fixture(self):
        self.assertTrue(
            smime_verify(
                signer_cert_path=self.signer_cert_path,
                content_path=self.manifest_json_path,
                signature_path=self.signature_der_path,
                signature_format='DER',
            )
        )

    def test_smime_format(self):
        actual_smime = smime_sign(
            signer_cert_path=self.signer_cert_path,
            signer_key_path=self.signer_key_path,
            recipient_cert_path=self.recipient_cert_path,
            content=self.maniphest_json,
            output_format='SMIME',
        )

        with tempfile.NamedTemporaryFile(delete=True) as temp:
            temp.write(actual_smime)
            temp.flush()

            self.assertTrue(
                smime_verify(
                    signer_cert_path=self.signer_cert_path,
                    content_path=self.manifest_json_path,
                    signature_path=path.abspath(temp.name),
                    signature_format='SMIME',
                )
            )

    def test_pem_format(self):
        actual_smime = smime_sign(
            signer_cert_path=self.signer_cert_path,
            signer_key_path=self.signer_key_path,
            recipient_cert_path=self.recipient_cert_path,
            content=self.maniphest_json,
            output_format='PEM',
        )

        with tempfile.NamedTemporaryFile(delete=True) as temp:
            temp.write(actual_smime)
            temp.flush()

            self.assertTrue(
                smime_verify(
                    signer_cert_path=self.signer_cert_path,
                    content_path=self.manifest_json_path,
                    signature_path=path.abspath(temp.name),
                    signature_format='PEM',
                )
            )

    def test_der_format(self):
        actual_smime = smime_sign(
            signer_cert_path=self.signer_cert_path,
            signer_key_path=self.signer_key_path,
            recipient_cert_path=self.recipient_cert_path,
            content=self.maniphest_json,
            output_format='DER',
        )

        with tempfile.NamedTemporaryFile(delete=True) as temp:
            temp.write(actual_smime)
            temp.flush()

            self.assertTrue(
                smime_verify(
                    signer_cert_path=self.signer_cert_path,
                    content_path=self.manifest_json_path,
                    signature_path=path.abspath(temp.name),
                    signature_format='DER',
                )
            )

    def test_inconsistent_check(self):
        actual_smime = smime_sign(
            signer_cert_path=self.signer_cert_path,
            signer_key_path=self.signer_key_path,
            recipient_cert_path=self.recipient_cert_path,
            content=self.maniphest_json,
            output_format='SMIME',
        )

        with tempfile.NamedTemporaryFile(delete=True) as temp:
            temp.write(actual_smime)
            temp.flush()

            self.assertFalse(
                smime_verify(
                    signer_cert_path=self.signer_cert_path,
                    content_path=self.manifest_json_path,
                    signature_path=path.abspath(temp.name),
                    signature_format='PEM',
                )
            )

    def test_relative_signer_cert_error(self):
        relative_signer_cert = "files/signer.cert"

        with self.assertRaises(ValueError) as ctx:
            smime_sign(
                signer_cert_path=relative_signer_cert,
                signer_key_path=self.signer_key_path,
                recipient_cert_path=self.recipient_cert_path,
                content=self.maniphest_json,
                output_format='SMIME',
            )

        self.assertEqual(
            ctx.exception.message,
            "{file_list} must be absolute paths to existing files".format(
                file_list=", ".join([
                    relative_signer_cert,
                    self.signer_key_path,
                    self.recipient_cert_path,
                ]),
            )
        )

    def test_relative_signer_key_error(self):
        relative_signer_key = "files/signer.pem"

        with self.assertRaises(ValueError) as ctx:
            smime_sign(
                signer_cert_path=self.signer_cert_path,
                signer_key_path=relative_signer_key,
                recipient_cert_path=self.recipient_cert_path,
                content=self.maniphest_json,
                output_format='SMIME',
            )

        self.assertEqual(
            ctx.exception.message,
            "{file_list} must be absolute paths to existing files".format(
                file_list=", ".join([
                    self.signer_cert_path,
                    relative_signer_key,
                    self.recipient_cert_path,
                ]),
            )
        )

    def test_relative_recipient_cert_error(self):
        relative_recipient_cert = "files/recipient.pem"

        with self.assertRaises(ValueError) as ctx:
            smime_sign(
                signer_cert_path=self.signer_cert_path,
                signer_key_path=self.signer_key_path,
                recipient_cert_path=relative_recipient_cert,
                content=self.maniphest_json,
                output_format='SMIME',
            )

        self.assertEqual(
            ctx.exception.message,
            "{file_list} must be absolute paths to existing files".format(
                file_list=", ".join([
                    self.signer_cert_path,
                    self.signer_key_path,
                    relative_recipient_cert,
                ]),
            )
        )

    def test_incorrect_format_error(self):
        with self.assertRaises(ValueError) as ctx:
            smime_sign(
                signer_cert_path=self.signer_cert_path,
                signer_key_path=self.signer_key_path,
                recipient_cert_path=self.recipient_cert_path,
                content=self.maniphest_json,
                output_format='INCORRECT',
            )

        self.assertEqual(
            ctx.exception.message,
            ("{output_format}' not found in the set of supported "
             "formats: {supported_formats}").format(
                 output_format='INCORRECT',
                 supported_formats=", ".join(('SMIME', 'PEM', 'DER')),
            )
        )

    def test_runtime_error(self):
        with self.assertRaises(RuntimeError) as ctx:
            smime_sign(
                signer_cert_path=self.signer_key_path,
                signer_key_path=self.recipient_cert_path,
                recipient_cert_path=self.signer_key_path,
                content=self.maniphest_json,
                output_format='PEM',
            )

        self.assertRegexpMatches(ctx.exception.message, r'OpenSSL failed with #[\d]+: .*')

if __name__ == '__main__':
    import sys
    sys.exit(unittest.main())
<commit_msg>Quite embarrasing. I'll say it's a typo.<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

from os import path
import unittest
import tempfile

from poor_smime_sign import smime_sign, smime_verify

def _read_file(abs_path):
        with open(abs_path, 'r') as f:
            return f.read()

class PoorSmimeSignTest(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.signer_cert_path = path.join(path.dirname(__file__), "files/signer.cert")
        cls.signer_key_path = path.join(path.dirname(__file__), "files/signer.pem")
        cls.recipient_cert_path = path.join(path.dirname(__file__), "files/recipient.cert")
        cls.manifest_json_path = path.join(path.dirname(__file__), "files/manifest.json")

        cls.signature_smime_path = path.join(path.dirname(__file__), "files/signature.smime")
        cls.signature_pem_path = path.join(path.dirname(__file__), "files/signature.pem")
        cls.signature_der_path = path.join(path.dirname(__file__), "files/signature.der")

        cls.signature_smime = _read_file(cls.signature_smime_path)
        cls.signature_pem = _read_file(cls.signature_pem_path)
        cls.signature_der = _read_file(cls.signature_der_path)

        cls.maniphest_json = _read_file(cls.manifest_json_path)

    def test_smime_fixture(self):
        self.assertTrue(
            smime_verify(
                signer_cert_path=self.signer_cert_path,
                content_path=self.manifest_json_path,
                signature_path=self.signature_smime_path,
                signature_format='SMIME',
            )
        )

    def test_pem_fixture(self):
        self.assertTrue(
            smime_verify(
                signer_cert_path=self.signer_cert_path,
                content_path=self.manifest_json_path,
                signature_path=self.signature_pem_path,
                signature_format='PEM',
            )
        )

    def test_der_fixture(self):
        self.assertTrue(
            smime_verify(
                signer_cert_path=self.signer_cert_path,
                content_path=self.manifest_json_path,
                signature_path=self.signature_der_path,
                signature_format='DER',
            )
        )

    def test_smime_format(self):
        actual_smime = smime_sign(
            signer_cert_path=self.signer_cert_path,
            signer_key_path=self.signer_key_path,
            recipient_cert_path=self.recipient_cert_path,
            content=self.maniphest_json,
            output_format='SMIME',
        )

        with tempfile.NamedTemporaryFile(delete=True) as temp:
            temp.write(actual_smime)
            temp.flush()

            self.assertTrue(
                smime_verify(
                    signer_cert_path=self.signer_cert_path,
                    content_path=self.manifest_json_path,
                    signature_path=path.abspath(temp.name),
                    signature_format='SMIME',
                )
            )

    def test_pem_format(self):
        actual_smime = smime_sign(
            signer_cert_path=self.signer_cert_path,
            signer_key_path=self.signer_key_path,
            recipient_cert_path=self.recipient_cert_path,
            content=self.maniphest_json,
            output_format='PEM',
        )

        with tempfile.NamedTemporaryFile(delete=True) as temp:
            temp.write(actual_smime)
            temp.flush()

            self.assertTrue(
                smime_verify(
                    signer_cert_path=self.signer_cert_path,
                    content_path=self.manifest_json_path,
                    signature_path=path.abspath(temp.name),
                    signature_format='PEM',
                )
            )

    def test_der_format(self):
        actual_smime = smime_sign(
            signer_cert_path=self.signer_cert_path,
            signer_key_path=self.signer_key_path,
            recipient_cert_path=self.recipient_cert_path,
            content=self.maniphest_json,
            output_format='DER',
        )

        with tempfile.NamedTemporaryFile(delete=True) as temp:
            temp.write(actual_smime)
            temp.flush()

            self.assertTrue(
                smime_verify(
                    signer_cert_path=self.signer_cert_path,
                    content_path=self.manifest_json_path,
                    signature_path=path.abspath(temp.name),
                    signature_format='DER',
                )
            )

    def test_inconsistent_check(self):
        actual_smime = smime_sign(
            signer_cert_path=self.signer_cert_path,
            signer_key_path=self.signer_key_path,
            recipient_cert_path=self.recipient_cert_path,
            content=self.maniphest_json,
            output_format='SMIME',
        )

        with tempfile.NamedTemporaryFile(delete=True) as temp:
            temp.write(actual_smime)
            temp.flush()

            self.assertFalse(
                smime_verify(
                    signer_cert_path=self.signer_cert_path,
                    content_path=self.manifest_json_path,
                    signature_path=path.abspath(temp.name),
                    signature_format='PEM',
                )
            )

    def test_relative_signer_cert_error(self):
        relative_signer_cert = "files/signer.cert"

        with self.assertRaises(ValueError) as ctx:
            smime_sign(
                signer_cert_path=relative_signer_cert,
                signer_key_path=self.signer_key_path,
                recipient_cert_path=self.recipient_cert_path,
                content=self.maniphest_json,
                output_format='SMIME',
            )

        self.assertEqual(
            ctx.exception.message,
            "{file_list} must be absolute paths to existing files".format(
                file_list=", ".join([
                    relative_signer_cert,
                    self.signer_key_path,
                    self.recipient_cert_path,
                ]),
            )
        )

    def test_relative_signer_key_error(self):
        relative_signer_key = "files/signer.pem"

        with self.assertRaises(ValueError) as ctx:
            smime_sign(
                signer_cert_path=self.signer_cert_path,
                signer_key_path=relative_signer_key,
                recipient_cert_path=self.recipient_cert_path,
                content=self.maniphest_json,
                output_format='SMIME',
            )

        self.assertEqual(
            ctx.exception.message,
            "{file_list} must be absolute paths to existing files".format(
                file_list=", ".join([
                    self.signer_cert_path,
                    relative_signer_key,
                    self.recipient_cert_path,
                ]),
            )
        )

    def test_relative_recipient_cert_error(self):
        relative_recipient_cert = "files/recipient.pem"

        with self.assertRaises(ValueError) as ctx:
            smime_sign(
                signer_cert_path=self.signer_cert_path,
                signer_key_path=self.signer_key_path,
                recipient_cert_path=relative_recipient_cert,
                content=self.maniphest_json,
                output_format='SMIME',
            )

        self.assertEqual(
            ctx.exception.message,
            "{file_list} must be absolute paths to existing files".format(
                file_list=", ".join([
                    self.signer_cert_path,
                    self.signer_key_path,
                    relative_recipient_cert,
                ]),
            )
        )

    def test_incorrect_format_error(self):
        with self.assertRaises(ValueError) as ctx:
            smime_sign(
                signer_cert_path=self.signer_cert_path,
                signer_key_path=self.signer_key_path,
                recipient_cert_path=self.recipient_cert_path,
                content=self.maniphest_json,
                output_format='INCORRECT',
            )

        self.assertEqual(
            ctx.exception.message,
            ("{output_format}' not found in the set of supported "
             "formats: {supported_formats}").format(
                 output_format='INCORRECT',
                 supported_formats=", ".join(('SMIME', 'PEM', 'DER')),
            )
        )

    def test_runtime_error(self):
        with self.assertRaises(RuntimeError) as ctx:
            smime_sign(
                signer_cert_path=self.signer_key_path,
                signer_key_path=self.recipient_cert_path,
                recipient_cert_path=self.signer_key_path,
                content=self.maniphest_json,
                output_format='PEM',
            )

        self.assertRegexpMatches(ctx.exception.message, r'OpenSSL failed with #[\d]+: .*')

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


<commit_before>"""Test flask_celery.single_instance()."""

import pytest

from flask.ext.celery import _LockManagerRedis, OtherInstanceError, _select_manager
from redis.exceptions import LockError

from tests.instances import app, celery

PARAMS = [('tests.instances.add', 8), ('tests.instances.mul', 16), ('tests.instances.sub', 0)]

@pytest.mark.parametrize('task_name,expected', PARAMS)
def test_basic(task_name, expected):
    task = celery.tasks[task_name]
    assert expected == task.apply_async(args=(4, 4)).get()

@pytest.mark.parametrize('task_name,expected', PARAMS)
def test_collision(task_name, expected):
    manager_class = _select_manager(celery.backend.__class__.__name__)
    manager_instance = list()
    task = celery.tasks[task_name]

    # First run the task and prevent it from removing the lock.
    def new_exit(self, *_):
        manager_instance.append(self)
        return None
    original_exit = manager_class.__exit__
    setattr(manager_class, '__exit__', new_exit)
    assert expected == task.apply_async(args=(4, 4)).get()
    setattr(manager_class, '__exit__', original_exit)
    assert manager_instance[0].is_already_running is True

    # Now run it again.
    with pytest.raises(OtherInstanceError) as e:
        task.apply_async(args=(4, 4)).get()
    if manager_instance[0].include_args:
        assert str(e.value).startswith('Failed to acquire lock, {0}.args.'.format(task_name))
    else:
        assert 'Failed to acquire lock, {0} already running.'.format(task_name) == str(e.value)

    # Clean up.
    manager_instance[0].reset_lock()
    assert manager_instance[0].is_already_running is False

    # Once more.
    assert expected == task.apply_async(args=(4, 4)).get()

def test_instance():
    """Test for exception to be raised."""
    # Prepare.
    add_task = celery.tasks['tests.instances.add']
    redis = app.extensions['redis'].redis
    redis_key = _LockManagerRedis.CELERY_LOCK.format(task_id='tests.instances.add')
    lock = redis.lock(redis_key, timeout=1)
    have_lock = lock.acquire(blocking=False)
    assert have_lock is True
    # Test.
    with pytest.raises(OtherInstanceError) as e:
        add_task.apply_async(args=(4, 4)).get()
    assert 'Failed to acquire lock, tests.instances.add already running.' == str(e.value)
    lock.release()

def test_instance_include_args():
    """Same as test_instance() but with single_instance(include_args=True)."""
    # Prepare.
    mul_task = celery.tasks['tests.instances.mul']
    redis = app.extensions['redis'].redis
    redis_key = _LockManagerRedis.CELERY_LOCK.format(
        task_id='tests.instances.mul.args.3d6442056c1bdf824b13ee277b62050c'
    )
    lock = redis.lock(redis_key, timeout=1)
    have_lock = lock.acquire(blocking=False)
    assert have_lock is True
    # Test with different args.
    assert 12 == mul_task.apply_async(args=(4, 3)).get()
    # Test with matching.
    with pytest.raises(OtherInstanceError) as e:
        mul_task.apply_async(args=(4, 4)).get()
    assert str(e.value).startswith('Failed to acquire lock, tests.instances.mul.args.')
    try:
        lock.release()
    except LockError:
        pass
<commit_msg>Testing include_args more thoroughly.<commit_after>"""Test flask_celery.single_instance()."""

import pytest

from flask.ext.celery import OtherInstanceError, _select_manager

from tests.instances import celery

PARAMS = [('tests.instances.add', 8), ('tests.instances.mul', 16), ('tests.instances.sub', 0)]

@pytest.mark.parametrize('task_name,expected', PARAMS)
def test_basic(task_name, expected):
    task = celery.tasks[task_name]
    assert expected == task.apply_async(args=(4, 4)).get()

@pytest.mark.parametrize('task_name,expected', PARAMS)
def test_collision(task_name, expected):
    manager_class = _select_manager(celery.backend.__class__.__name__)
    manager_instance = list()
    task = celery.tasks[task_name]

    # First run the task and prevent it from removing the lock.
    def new_exit(self, *_):
        manager_instance.append(self)
        return None
    original_exit = manager_class.__exit__
    setattr(manager_class, '__exit__', new_exit)
    assert expected == task.apply_async(args=(4, 4)).get()
    setattr(manager_class, '__exit__', original_exit)
    assert manager_instance[0].is_already_running is True

    # Now run it again.
    with pytest.raises(OtherInstanceError) as e:
        task.apply_async(args=(4, 4)).get()
    if manager_instance[0].include_args:
        assert str(e.value).startswith('Failed to acquire lock, {0}.args.'.format(task_name))
    else:
        assert 'Failed to acquire lock, {0} already running.'.format(task_name) == str(e.value)

    # Clean up.
    manager_instance[0].reset_lock()
    assert manager_instance[0].is_already_running is False

    # Once more.
    assert expected == task.apply_async(args=(4, 4)).get()

def test_include_args():
    manager_class = _select_manager(celery.backend.__class__.__name__)
    manager_instance = list()
    task = celery.tasks['tests.instances.mul']

    # First run the tasks and prevent them from removing the locks.
    def new_exit(self, *_):
        """Expected to be run twice."""
        manager_instance.append(self)
        return None
    original_exit = manager_class.__exit__
    setattr(manager_class, '__exit__', new_exit)
    assert 16 == task.apply_async(args=(4, 4)).get()
    assert 20 == task.apply_async(args=(5, 4)).get()
    setattr(manager_class, '__exit__', original_exit)
    assert manager_instance[0].is_already_running is True
    assert manager_instance[1].is_already_running is True

    # Now run them again.
    with pytest.raises(OtherInstanceError) as e:
        task.apply_async(args=(4, 4)).get()
    assert str(e.value).startswith('Failed to acquire lock, tests.instances.mul.args.')
    with pytest.raises(OtherInstanceError) as e:
        task.apply_async(args=(5, 4)).get()
    assert str(e.value).startswith('Failed to acquire lock, tests.instances.mul.args.')

    # Clean up.
    manager_instance[0].reset_lock()
    assert manager_instance[0].is_already_running is False
    manager_instance[1].reset_lock()
    assert manager_instance[1].is_already_running is False

    # Once more.
    assert 16 == task.apply_async(args=(4, 4)).get()
    assert 20 == task.apply_async(args=(5, 4)).get()
<|endoftext|>


<commit_before>import abc
import json
import unittest
import warnings

import billboard
import six
from billboard import UnsupportedYearWarning

@six.add_metaclass(abc.ABCMeta)
class Base:
    @classmethod
    @abc.abstractmethod
    def setUpClass(cls):
        pass

    def testYear(self):
        self.assertIsNotNone(self.chart.year)

    def testNextYear(self):
        next_year = str(int(self.chart.year) + 1)
        self.assertEqual(self.chart.nextYear, next_year)

    def testPreviousYear(self):
        previous_year = str(int(self.chart.year) - 1)
        self.assertEqual(self.chart.previousYear, previous_year)

    def testTitle(self):
        self.assertEqual(self.chart.title, self.expectedTitle)

    def testRanks(self):
        ranks = list(entry.rank for entry in self.chart)
        self.assertEqual(ranks, sorted(ranks))

    def testEntriesValidity(self, skipTitleCheck=False):
        self.assertEqual(len(self.chart), self.expectedNumEntries)
        for entry in self.chart:
            if not skipTitleCheck:
                self.assertGreater(len(entry.title), 0)
            self.assertGreater(len(entry.artist), 0)

    def testJson(self):
        self.assertTrue(json.loads(self.chart.json()))
        for entry in self.chart:
            self.assertTrue(json.loads(entry.json()))

class TestHot100Songs2019(Base, unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.chart = billboard.ChartData("hot-100-songs", year="2019")
        cls.expectedTitle = "Hot 100 Songs - Year-End"
        cls.expectedNumEntries = 100

    def testNextYear(self):
        self.assertIsNone(self.chart.nextYear)

class TestHotCountrySongs1970(Base, unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        name = "hot-country-songs"
        year = 1970
        warnings.filterwarnings(action="always", category=UnsupportedYearWarning)
        with warnings.catch_warnings(record=True) as w:
            cls.chart = billboard.ChartData(name, year=year)
            cls.warning = w[0] if w else None

        cls.expectedTitle = "Hot Country Songs - Year-End"
        cls.expectedNumEntries = 34

    def testUnsupportedYearWarning(self):
        self.assertEquals(self.warning.category, UnsupportedYearWarning)

    def testNextYear(self):
        self.assertIsNone(self.chart.nextYear)

    def testPreviousYear(self):
        self.assertIsNone(self.chart.previousYear)

class TestJazzAlbumsImprints2006(Base, unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.chart = billboard.ChartData("jazz-imprints", year="2006")
        cls.expectedTitle = "Jazz Albums Imprints - Year-End"
        cls.expectedNumEntries = 9

    def testEntriesValidity(self):
        super(TestJazzAlbumsImprints2006, self).testEntriesValidity(skipTitleCheck=True)
        for entry in self.chart:
            self.assertEqual(entry.title, "")  # This chart has no titles

    def testPreviousYear(self):
        self.assertIsNone(self.chart.previousYear)
<commit_msg>Fix failing test for year-end chart (new chart came out?)<commit_after>import abc
import json
import unittest
import warnings

import billboard
import six
from billboard import UnsupportedYearWarning

@six.add_metaclass(abc.ABCMeta)
class Base:
    @classmethod
    @abc.abstractmethod
    def setUpClass(cls):
        pass

    def testYear(self):
        self.assertIsNotNone(self.chart.year)

    def testNextYear(self):
        next_year = str(int(self.chart.year) + 1)
        self.assertEqual(self.chart.nextYear, next_year)

    def testPreviousYear(self):
        previous_year = str(int(self.chart.year) - 1)
        self.assertEqual(self.chart.previousYear, previous_year)

    def testTitle(self):
        self.assertEqual(self.chart.title, self.expectedTitle)

    def testRanks(self):
        ranks = list(entry.rank for entry in self.chart)
        self.assertEqual(ranks, sorted(ranks))

    def testEntriesValidity(self, skipTitleCheck=False):
        self.assertEqual(len(self.chart), self.expectedNumEntries)
        for entry in self.chart:
            if not skipTitleCheck:
                self.assertGreater(len(entry.title), 0)
            self.assertGreater(len(entry.artist), 0)

    def testJson(self):
        self.assertTrue(json.loads(self.chart.json()))
        for entry in self.chart:
            self.assertTrue(json.loads(entry.json()))

class TestHot100Songs2019(Base, unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.chart = billboard.ChartData("hot-100-songs", year="2019")
        cls.expectedTitle = "Hot 100 Songs - Year-End"
        cls.expectedNumEntries = 100

class TestHotCountrySongs1970(Base, unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        name = "hot-country-songs"
        year = 1970
        warnings.filterwarnings(action="always", category=UnsupportedYearWarning)
        with warnings.catch_warnings(record=True) as w:
            cls.chart = billboard.ChartData(name, year=year)
            cls.warning = w[0] if w else None

        cls.expectedTitle = "Hot Country Songs - Year-End"
        cls.expectedNumEntries = 34

    def testUnsupportedYearWarning(self):
        self.assertEquals(self.warning.category, UnsupportedYearWarning)

    def testNextYear(self):
        self.assertIsNone(self.chart.nextYear)

    def testPreviousYear(self):
        self.assertIsNone(self.chart.previousYear)

class TestJazzAlbumsImprints2006(Base, unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.chart = billboard.ChartData("jazz-imprints", year="2006")
        cls.expectedTitle = "Jazz Albums Imprints - Year-End"
        cls.expectedNumEntries = 9

    def testEntriesValidity(self):
        super(TestJazzAlbumsImprints2006, self).testEntriesValidity(skipTitleCheck=True)
        for entry in self.chart:
            self.assertEqual(entry.title, "")  # This chart has no titles

    def testPreviousYear(self):
        self.assertIsNone(self.chart.previousYear)
<|endoftext|>


<commit_before>import os
import unittest
from splinter.browser import Browser
from base import BaseBrowserTests
from fake_webapp import EXAMPLE_APP
from nose.tools import raises

class ZopeTestBrowserDriverTest(BaseBrowserTests, unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.browser = Browser('zope.testbrowser')

    def setUp(self):
        self.browser.visit(EXAMPLE_APP)

    @classmethod
    def tearDownClass(self):
        self.browser.quit()

    def test_attach_file(self):
        "should provide a way to change file field value"
        file_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'mockfile.txt')
        self.browser.attach_file('file', file_path)
        self.browser.find_by_name('upload').first.click()

        html = self.browser.html
        assert 'text/plain' in html
        assert open(file_path).read() in html

    @raises(NotImplementedError)
    def test_cant_switch_to_frame(self):
        "zope.testbrowser should not be able to switch to frames"
        self.browser.switch_to_frame('frame_123')
<commit_msg>Fixed zope.testbrowser test<commit_after>import os
import unittest
from splinter.browser import Browser
from base import BaseBrowserTests
from fake_webapp import EXAMPLE_APP
from nose.tools import raises

class ZopeTestBrowserDriverTest(BaseBrowserTests, unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.browser = Browser('zope.testbrowser')

    def setUp(self):
        self.browser.visit(EXAMPLE_APP)

    @classmethod
    def tearDownClass(self):
        self.browser.quit()

    def test_attach_file(self):
        "should provide a way to change file field value"
        file_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'mockfile.txt')
        self.browser.attach_file('file', file_path)
        self.browser.find_by_name('upload').first.click()

        html = self.browser.html
        assert 'text/plain' in html
        assert open(file_path).read() in html

    @raises(NotImplementedError)
    def test_cant_switch_to_frame(self):
        "zope.testbrowser should not be able to switch to frames"
        self.browser.get_iframe('frame_123')
<|endoftext|>


<commit_before>"""
Tests for pika.heartbeat

"""
try:
    import mock
except ImportError:
    from unittest import mock

try:
    import unittest2 as unittest
except ImportError:
    import unittest

from pika import connection
from pika import frame
from pika import heartbeat

class HeartbeatTests(unittest.TestCase):

    INTERVAL = 5

    def setUp(self):
        self.mock_conn = mock.Mock(spec=connection.Connection)
        self.mock_conn.bytes_received = 100
        self.mock_conn.bytes_sent = 100
        self.mock_conn.heartbeat = mock.Mock(spec=heartbeat.HeartbeatChecker)
        self.obj = heartbeat.HeartbeatChecker(self.mock_conn, self.INTERVAL)

    def tearDown(self):
        del self.obj
        del self.mock_conn

    def test_default_initialization_max_idle_count(self):
        self.assertEqual(self.obj._max_idle_count, self.obj.MAX_IDLE_COUNT)

    def test_constructor_assignment_connection(self):
        self.assertEqual(self.obj._connection, self.mock_conn)

    def test_constructor_assignment_heartbeat_interval(self):
        self.assertEqual(self.obj._interval, self.INTERVAL)

    def test_constructor_initial_bytes_received(self):
        self.assertEqual(self.obj._bytes_received, 0)

    def test_constructor_initial_bytes_sent(self):
        self.assertEqual(self.obj._bytes_received, 0)

    def test_constructor_initial_heartbeat_frames_received(self):
        self.assertEqual(self.obj._heartbeat_frames_received, 0)

    def test_constructor_initial_heartbeat_frames_sent(self):
        self.assertEqual(self.obj._heartbeat_frames_sent, 0)

    def test_constructor_initial_idle_byte_intervals(self):
        self.assertEqual(self.obj._idle_byte_intervals, 0)

    @mock.patch('pika.heartbeat.HeartbeatChecker._setup_timer')
    def test_constructor_called_setup_timer(self, timer):
        obj = heartbeat.HeartbeatChecker(self.mock_conn, self.INTERVAL)
        timer.assert_called_once_with()

    def test_active_true(self):
        self.mock_conn.heartbeat = self.obj
        self.assertTrue(self.obj.active)

    def test_active_false(self):
        self.mock_conn.heartbeat = mock.Mock()
        self.assertFalse(self.obj.active)

    def test_bytes_received_on_connection(self):
        self.mock_conn.bytes_received = 128
        self.assertEqual(self.obj.bytes_received_on_connection, 128)

    def test_connection_is_idle_false(self):
        self.assertFalse(self.obj.connection_is_idle)

    def test_connection_is_idle_true(self):
        self.obj._idle_byte_intervals = self.INTERVAL
        self.assertTrue(self.obj.connection_is_idle)

    def test_received(self):
        self.obj.received()
        self.assertTrue(self.obj._heartbeat_frames_received, 1)

    @mock.patch('pika.heartbeat.HeartbeatChecker._close_connection')
    def test_send_and_check_not_closed(self, close_connection):
        obj = heartbeat.HeartbeatChecker(self.mock_conn, self.INTERVAL)
        obj.send_and_check()
        close_connection.assert_not_called()

    @mock.patch('pika.heartbeat.HeartbeatChecker._close_connection')
    def test_send_and_check_missed_bytes(self, close_connection):
        obj = heartbeat.HeartbeatChecker(self.mock_conn, self.INTERVAL)
        obj._idle_byte_intervals = self.INTERVAL
        obj.send_and_check()
        close_connection.assert_called_once_with()

    def test_send_and_check_increment_no_bytes(self):
        self.mock_conn.bytes_received = 100
        self.obj._bytes_received = 100
        self.obj.send_and_check()
        self.assertEqual(self.obj._idle_byte_intervals, 1)

    def test_send_and_check_increment_bytes(self):
        self.mock_conn.bytes_received = 100
        self.obj._bytes_received = 128
        self.obj.send_and_check()
        self.assertEqual(self.obj._idle_byte_intervals, 0)

    @mock.patch('pika.heartbeat.HeartbeatChecker._update_counters')
    def test_send_and_check_update_counters(self, update_counters):
        obj = heartbeat.HeartbeatChecker(self.mock_conn, self.INTERVAL)
        obj.send_and_check()
        update_counters.assert_called_once_with()

    @mock.patch('pika.heartbeat.HeartbeatChecker._send_heartbeat_frame')
    def test_send_and_check_send_heartbeat_frame(self, send_heartbeat_frame):
        obj = heartbeat.HeartbeatChecker(self.mock_conn, self.INTERVAL)
        obj.send_and_check()
        send_heartbeat_frame.assert_called_once_with()

    @mock.patch('pika.heartbeat.HeartbeatChecker._start_timer')
    def test_send_and_check_start_timer(self, start_timer):
        obj = heartbeat.HeartbeatChecker(self.mock_conn, self.INTERVAL)
        obj.send_and_check()
        start_timer.assert_called_once_with()

    def test_connection_close(self):
        self.obj._idle_byte_intervals = 3
        self.obj._idle_heartbeat_intervals = 4
        self.obj._close_connection()
        reason = self.obj._STALE_CONNECTION % (self.obj._max_idle_count *
                                               self.obj._interval)
        self.mock_conn.close.assert_called_once_with(
            self.obj._CONNECTION_FORCED, reason)
        self.mock_conn._on_disconnect.assert_called_once_with(
            self.obj._CONNECTION_FORCED, reason)
        self.mock_conn._adapter_disconnect.assert_called_once_with()

    def test_has_received_data_false(self):
        self.obj._bytes_received = 100
        self.assertFalse(self.obj._has_received_data)

    def test_has_received_data_true(self):
        self.mock_conn.bytes_received = 128
        self.obj._bytes_received = 100
        self.assertTrue(self.obj._has_received_data)

    def test_new_heartbeat_frame(self):
        self.assertIsInstance(self.obj._new_heartbeat_frame(), frame.Heartbeat)

    def test_send_heartbeat_send_frame_called(self):
        self.obj._send_heartbeat_frame()
        self.mock_conn._send_frame.assert_called_once()

    def test_send_heartbeat_counter_incremented(self):
        self.obj._send_heartbeat_frame()
        self.assertEqual(self.obj._heartbeat_frames_sent, 1)

    def test_setup_timer_called(self):
        self.obj._setup_timer()
        self.mock_conn.add_timeout.called_once_with(self.INTERVAL,
                                                    self.obj.send_and_check)

    @mock.patch('pika.heartbeat.HeartbeatChecker._setup_timer')
    def test_start_timer_not_active(self, setup_timer):
        self.obj._start_timer()
        setup_timer.assert_not_called()

    @mock.patch('pika.heartbeat.HeartbeatChecker._setup_timer')
    def test_start_timer_active(self, setup_timer):
        self.mock_conn.heartbeat = self.obj
        self.obj._start_timer()
        self.assertTrue(setup_timer.called)

    def test_update_counters_bytes_received(self):
        self.mock_conn.bytes_received = 256
        self.obj._update_counters()
        self.assertEqual(self.obj._bytes_received, 256)

    def test_update_counters_bytes_sent(self):
        self.mock_conn.bytes_sent = 256
        self.obj._update_counters()
        self.assertEqual(self.obj._bytes_sent, 256)
<commit_msg>Make the test more reliable in Python 3.5<commit_after>"""
Tests for pika.heartbeat

"""
try:
    import mock
except ImportError:
    from unittest import mock

try:
    import unittest2 as unittest
except ImportError:
    import unittest

from pika import connection
from pika import frame
from pika import heartbeat

class HeartbeatTests(unittest.TestCase):

    INTERVAL = 5

    def setUp(self):
        self.mock_conn = mock.Mock(spec=connection.Connection)
        self.mock_conn.bytes_received = 100
        self.mock_conn.bytes_sent = 100
        self.mock_conn.heartbeat = mock.Mock(spec=heartbeat.HeartbeatChecker)
        self.obj = heartbeat.HeartbeatChecker(self.mock_conn, self.INTERVAL)

    def tearDown(self):
        del self.obj
        del self.mock_conn

    def test_default_initialization_max_idle_count(self):
        self.assertEqual(self.obj._max_idle_count, self.obj.MAX_IDLE_COUNT)

    def test_constructor_assignment_connection(self):
        self.assertEqual(self.obj._connection, self.mock_conn)

    def test_constructor_assignment_heartbeat_interval(self):
        self.assertEqual(self.obj._interval, self.INTERVAL)

    def test_constructor_initial_bytes_received(self):
        self.assertEqual(self.obj._bytes_received, 0)

    def test_constructor_initial_bytes_sent(self):
        self.assertEqual(self.obj._bytes_received, 0)

    def test_constructor_initial_heartbeat_frames_received(self):
        self.assertEqual(self.obj._heartbeat_frames_received, 0)

    def test_constructor_initial_heartbeat_frames_sent(self):
        self.assertEqual(self.obj._heartbeat_frames_sent, 0)

    def test_constructor_initial_idle_byte_intervals(self):
        self.assertEqual(self.obj._idle_byte_intervals, 0)

    @mock.patch('pika.heartbeat.HeartbeatChecker._setup_timer')
    def test_constructor_called_setup_timer(self, timer):
        obj = heartbeat.HeartbeatChecker(self.mock_conn, self.INTERVAL)
        timer.assert_called_once_with()

    def test_active_true(self):
        self.mock_conn.heartbeat = self.obj
        self.assertTrue(self.obj.active)

    def test_active_false(self):
        self.mock_conn.heartbeat = mock.Mock()
        self.assertFalse(self.obj.active)

    def test_bytes_received_on_connection(self):
        self.mock_conn.bytes_received = 128
        self.assertEqual(self.obj.bytes_received_on_connection, 128)

    def test_connection_is_idle_false(self):
        self.assertFalse(self.obj.connection_is_idle)

    def test_connection_is_idle_true(self):
        self.obj._idle_byte_intervals = self.INTERVAL
        self.assertTrue(self.obj.connection_is_idle)

    def test_received(self):
        self.obj.received()
        self.assertTrue(self.obj._heartbeat_frames_received, 1)

    @mock.patch('pika.heartbeat.HeartbeatChecker._close_connection')
    def test_send_and_check_not_closed(self, close_connection):
        obj = heartbeat.HeartbeatChecker(self.mock_conn, self.INTERVAL)
        obj.send_and_check()
        close_connection.assert_not_called()

    @mock.patch('pika.heartbeat.HeartbeatChecker._close_connection')
    def test_send_and_check_missed_bytes(self, close_connection):
        obj = heartbeat.HeartbeatChecker(self.mock_conn, self.INTERVAL)
        obj._idle_byte_intervals = self.INTERVAL
        obj.send_and_check()
        close_connection.assert_called_once_with()

    def test_send_and_check_increment_no_bytes(self):
        self.mock_conn.bytes_received = 100
        self.obj._bytes_received = 100
        self.obj.send_and_check()
        self.assertEqual(self.obj._idle_byte_intervals, 1)

    def test_send_and_check_increment_bytes(self):
        self.mock_conn.bytes_received = 100
        self.obj._bytes_received = 128
        self.obj.send_and_check()
        self.assertEqual(self.obj._idle_byte_intervals, 0)

    @mock.patch('pika.heartbeat.HeartbeatChecker._update_counters')
    def test_send_and_check_update_counters(self, update_counters):
        obj = heartbeat.HeartbeatChecker(self.mock_conn, self.INTERVAL)
        obj.send_and_check()
        update_counters.assert_called_once_with()

    @mock.patch('pika.heartbeat.HeartbeatChecker._send_heartbeat_frame')
    def test_send_and_check_send_heartbeat_frame(self, send_heartbeat_frame):
        obj = heartbeat.HeartbeatChecker(self.mock_conn, self.INTERVAL)
        obj.send_and_check()
        send_heartbeat_frame.assert_called_once_with()

    @mock.patch('pika.heartbeat.HeartbeatChecker._start_timer')
    def test_send_and_check_start_timer(self, start_timer):
        obj = heartbeat.HeartbeatChecker(self.mock_conn, self.INTERVAL)
        obj.send_and_check()
        start_timer.assert_called_once_with()

    def test_connection_close(self):
        self.obj._idle_byte_intervals = 3
        self.obj._idle_heartbeat_intervals = 4
        self.obj._close_connection()
        reason = self.obj._STALE_CONNECTION % (self.obj._max_idle_count *
                                               self.obj._interval)
        self.mock_conn.close.assert_called_once_with(
            self.obj._CONNECTION_FORCED, reason)
        self.mock_conn._on_disconnect.assert_called_once_with(
            self.obj._CONNECTION_FORCED, reason)
        self.mock_conn._adapter_disconnect.assert_called_once_with()

    def test_has_received_data_false(self):
        self.obj._bytes_received = 100
        self.assertFalse(self.obj._has_received_data)

    def test_has_received_data_true(self):
        self.mock_conn.bytes_received = 128
        self.obj._bytes_received = 100
        self.assertTrue(self.obj._has_received_data)

    def test_new_heartbeat_frame(self):
        self.assertIsInstance(self.obj._new_heartbeat_frame(), frame.Heartbeat)

    def test_send_heartbeat_send_frame_called(self):
        frame_value = self.obj._new_heartbeat_frame()
        with mock.patch.object(self.obj, '_new_heartbeat_frame') as new_frame:
            new_frame.return_value = frame_value
            self.obj._send_heartbeat_frame()
            self.mock_conn._send_frame.assert_called_once_with(frame_value)

    def test_send_heartbeat_counter_incremented(self):
        self.obj._send_heartbeat_frame()
        self.assertEqual(self.obj._heartbeat_frames_sent, 1)

    def test_setup_timer_called(self):
        self.obj._setup_timer()
        self.mock_conn.add_timeout.called_once_with(self.INTERVAL,
                                                    self.obj.send_and_check)

    @mock.patch('pika.heartbeat.HeartbeatChecker._setup_timer')
    def test_start_timer_not_active(self, setup_timer):
        self.obj._start_timer()
        setup_timer.assert_not_called()

    @mock.patch('pika.heartbeat.HeartbeatChecker._setup_timer')
    def test_start_timer_active(self, setup_timer):
        self.mock_conn.heartbeat = self.obj
        self.obj._start_timer()
        self.assertTrue(setup_timer.called)

    def test_update_counters_bytes_received(self):
        self.mock_conn.bytes_received = 256
        self.obj._update_counters()
        self.assertEqual(self.obj._bytes_received, 256)

    def test_update_counters_bytes_sent(self):
        self.mock_conn.bytes_sent = 256
        self.obj._update_counters()
        self.assertEqual(self.obj._bytes_sent, 256)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
'''
    :codeauthor: :email:`Bo Maryniuk <bo@suse.de>`
'''

from __future__ import absolute_import, print_function, unicode_literals
from tests.support.unit import TestCase, skipIf
from tests.support.mock import (
    NO_MOCK,
    NO_MOCK_REASON,
    MagicMock,
    patch)

# Import Salt libs
import salt.exceptions
import salt.state
from salt.utils import ssdp
import datetime

try:
    import pytest
except ImportError as err:
    pytest = None

class Mocks(object):
    def get_socket_mock(self, expected_ip, expected_hostname):
        '''
        Get a mock of a socket
        :return:
        '''
        sck = MagicMock()
        sck.getsockname = MagicMock(return_value=(expected_ip, 123456))

        sock_mock = MagicMock()
        sock_mock.socket = MagicMock(return_value=sck)
        sock_mock.gethostbyname = MagicMock(return_value=expected_hostname)

        return sock_mock

@skipIf(NO_MOCK, NO_MOCK_REASON)
@skipIf(pytest is None, 'PyTest is missing')
class SSDPBaseTestCase(TestCase, Mocks):
    '''
    TestCase for SSDP-related parts.
    '''

    @staticmethod
    def exception_generic(*args, **kwargs):
        '''
        Side effect
        :return:
        '''
        raise Exception('some network error')

    @staticmethod
    def exception_attr_error(*args, **kwargs):
        '''
        Side effect
        :return:
        '''
        raise AttributeError('attribute error: {0}. {1}'.format(args, kwargs))

    @patch('salt.utils.ssdp._json', None)
    @patch('salt.utils.ssdp.asyncio', None)
    def test_base_avail(self):
        '''
        Test SSDP base class availability method.
        :return:
        '''
        base = ssdp.SSDPBase()
        assert not base._is_available()

        with patch('salt.utils.ssdp._json', True):
            assert not base._is_available()

        with patch('salt.utils.ssdp.asyncio', True):
            assert not base._is_available()

        with patch('salt.utils.ssdp._json', True), patch('salt.utils.ssdp.asyncio', True):
            assert base._is_available()

    def test_base_protocol_settings(self):
        '''
        Tests default constants data.
        :return:
        '''
        base = ssdp.SSDPBase()
        v_keys = ['signature', 'answer', 'port', 'listen_ip', 'timeout']
        v_vals = ['__salt_master_service', {}, 4520, '0.0.0.0', 3]
        for key in v_keys:
            assert key in base.DEFAULTS

        for key in base.DEFAULTS.keys():
            assert key in v_keys

        for key, value in zip(v_keys, v_vals):
            assert base.DEFAULTS[key] == value

    def test_base_self_ip(self):
        '''
        Test getting self IP method.

        :return:
        '''
        base = ssdp.SSDPBase()
        expected_ip = '192.168.1.10'
        expected_host = 'oxygen'
        sock_mock = self.get_socket_mock(expected_ip, expected_host)

        with patch('salt.utils.ssdp.socket', sock_mock):
            assert base.get_self_ip() == expected_ip

        sock_mock.socket().getsockname.side_effect = SSDPBaseTestCase.exception_generic
        with patch('salt.utils.ssdp.socket', sock_mock):
            assert base.get_self_ip() == expected_host

@skipIf(NO_MOCK, NO_MOCK_REASON)
@skipIf(pytest is None, 'PyTest is missing')
class SSDPFactoryTestCase(TestCase):
    '''
    Test socket protocol
    '''
    @patch('salt.utils.ssdp.socket.gethostbyname', MagicMock(return_value='10.10.10.10'))
    def test_attr_check(self):
        '''
        Tests attributes are set to the base class

        :return:
        '''
        config = {
            ssdp.SSDPBase.SIGNATURE: '-signature-',
            ssdp.SSDPBase.ANSWER: {'this-is': 'the-answer'}
        }
        factory = ssdp.SSDPFactory(**config)
        for attr in [ssdp.SSDPBase.SIGNATURE, ssdp.SSDPBase.ANSWER]:
            assert hasattr(factory, attr)
            assert getattr(factory, attr) == config[attr]
        assert not factory.disable_hidden
        assert factory.my_ip == '10.10.10.10'

    def test_transport_sendto_success(self):
        '''
        Test transport send_to.

        :return:
        '''
        transport = MagicMock()
        log = MagicMock()
        factory = ssdp.SSDPFactory()
        with patch.object(factory, 'transport', transport), patch.object(factory, 'log', log):
            data = {'some': 'data'}
            addr = '10.10.10.10'
            factory._sendto(data=data, addr=addr)
            assert factory.transport.sendto.called
            assert factory.transport.sendto.mock_calls[0][1][0]['some'] == 'data'
            assert factory.transport.sendto.mock_calls[0][2]['addr'] == '10.10.10.10'
            assert factory.log.debug.called
            assert factory.log.debug.mock_calls[0][1][0] == 'Sent successfully'

    @patch('salt.utils.ssdp.time.sleep', MagicMock())
    def test_transport_sendto_retry(self):
        '''
        Test transport send_to.

        :return:
        '''
        transport = MagicMock()
        transport.sendto = MagicMock(side_effect=SSDPBaseTestCase.exception_attr_error)
        log = MagicMock()
        factory = ssdp.SSDPFactory()
        with patch.object(factory, 'transport', transport), patch.object(factory, 'log', log):
            data = {'some': 'data'}
            addr = '10.10.10.10'
            factory._sendto(data=data, addr=addr)
            assert factory.transport.sendto.called
            assert ssdp.time.sleep.called
            assert ssdp.time.sleep.call_args[0][0] > 0 and ssdp.time.sleep.call_args[0][0] < 0.5
            assert factory.log.debug.called
            assert 'Permission error' in factory.log.debug.mock_calls[0][1][0]

    def test_datagram_signature_bad(self):
        '''
        Test datagram_received on bad signature

        :return:
        '''
        factory = ssdp.SSDPFactory()
        data = 'nonsense'
        addr = '10.10.10.10', 'foo.suse.de'

        with patch.object(factory, 'log', MagicMock()):
            factory.datagram_received(data=data, addr=addr)
            assert factory.log.debug.called
            assert 'Received bad signature from' in factory.log.debug.call_args[0][0]
            assert factory.log.debug.call_args[0][1] == addr[0]
            assert factory.log.debug.call_args[0][2] == addr[1]

    def test_datagram_signature_wrong_timestamp_quiet(self):
        '''
        Test datagram receives a wrong timestamp (no reply).

        :return:
        '''
        factory = ssdp.SSDPFactory()
        data = '{}nonsense'.format(ssdp.SSDPBase.DEFAULTS[ssdp.SSDPBase.SIGNATURE])
        addr = '10.10.10.10', 'foo.suse.de'
        with patch.object(factory, 'log', MagicMock()), patch.object(factory, '_sendto', MagicMock()):
            factory.datagram_received(data=data, addr=addr)
            assert factory.log.debug.called
            assert 'Received invalid timestamp in package' in factory.log.debug.call_args[0][0]
            assert not factory._sendto.called

    def test_datagram_signature_wrong_timestamp_reply(self):
        '''
        Test datagram receives a wrong timestamp.

        :return:
        '''
        factory = ssdp.SSDPFactory()
        factory.disable_hidden = True
        signature = ssdp.SSDPBase.DEFAULTS[ssdp.SSDPBase.SIGNATURE]
        data = '{}nonsense'.format(signature)
        addr = '10.10.10.10', 'foo.suse.de'
        with patch.object(factory, 'log', MagicMock()), patch.object(factory, '_sendto', MagicMock()):
            factory.datagram_received(data=data, addr=addr)
            assert factory.log.debug.called
            assert 'Received invalid timestamp in package' in factory.log.debug.call_args[0][0]
            assert factory._sendto.called
            assert '{}:E:Invalid timestamp'.format(signature) == factory._sendto.call_args[0][0]

    def test_datagram_signature_outdated_timestamp_quiet(self):
        '''
        Test if datagram processing reacts on outdated message (more than 20 seconds). Quiet mode.
        :return:
        '''
        factory = ssdp.SSDPFactory()
        signature = ssdp.SSDPBase.DEFAULTS[ssdp.SSDPBase.SIGNATURE]
        data = '{}{}'.format(signature, '1516623820')
        addr = '10.10.10.10', 'foo.suse.de'

        ahead_dt = datetime.datetime.fromtimestamp(1516623841)
        curnt_dt = datetime.datetime.fromtimestamp(1516623820)
        delta = datetime.timedelta(0, 20)
        with patch.object(factory, 'log', MagicMock()), patch.object(factory, '_sendto'), \
             patch('salt.utils.ssdp.datetime.datetime', MagicMock()), \
             patch('salt.utils.ssdp.datetime.datetime.now', MagicMock(return_value=ahead_dt)), \
             patch('salt.utils.ssdp.datetime.datetime.fromtimestamp', MagicMock(return_value=curnt_dt)), \
             patch('salt.utils.ssdp.datetime.timedelta', MagicMock(return_value=delta)):
            factory.datagram_received(data=data, addr=addr)
            assert factory.log.debug.called
            assert not factory.disable_hidden
            assert not factory._sendto.called
            assert 'Received outdated package' in factory.log.debug.call_args[0][0]

    def test_datagram_signature_outdated_timestamp_reply(self):
        '''
        Test if datagram processing reacts on outdated message (more than 20 seconds). Reply mode.
        :return:
        '''
        factory = ssdp.SSDPFactory()
        factory.disable_hidden = True
        signature = ssdp.SSDPBase.DEFAULTS[ssdp.SSDPBase.SIGNATURE]
        data = '{}{}'.format(signature, '1516623820')
        addr = '10.10.10.10', 'foo.suse.de'

        ahead_dt = datetime.datetime.fromtimestamp(1516623841)
        curnt_dt = datetime.datetime.fromtimestamp(1516623820)
        delta = datetime.timedelta(0, 20)
        with patch.object(factory, 'log', MagicMock()), patch.object(factory, '_sendto'), \
             patch('salt.utils.ssdp.datetime.datetime', MagicMock()), \
             patch('salt.utils.ssdp.datetime.datetime.now', MagicMock(return_value=ahead_dt)), \
             patch('salt.utils.ssdp.datetime.datetime.fromtimestamp', MagicMock(return_value=curnt_dt)), \
             patch('salt.utils.ssdp.datetime.timedelta', MagicMock(return_value=delta)):
            factory.datagram_received(data=data, addr=addr)
            assert factory.log.debug.called
            assert factory.disable_hidden
            assert factory._sendto.called
            assert 'Received outdated package' in factory.log.debug.call_args[0][0]

<commit_msg>Lintfix: too much empty lines<commit_after># -*- coding: utf-8 -*-
'''
    :codeauthor: :email:`Bo Maryniuk <bo@suse.de>`
'''

from __future__ import absolute_import, print_function, unicode_literals
from tests.support.unit import TestCase, skipIf
from tests.support.mock import (
    NO_MOCK,
    NO_MOCK_REASON,
    MagicMock,
    patch)

# Import Salt libs
import salt.exceptions
import salt.state
from salt.utils import ssdp
import datetime

try:
    import pytest
except ImportError as err:
    pytest = None

class Mocks(object):
    def get_socket_mock(self, expected_ip, expected_hostname):
        '''
        Get a mock of a socket
        :return:
        '''
        sck = MagicMock()
        sck.getsockname = MagicMock(return_value=(expected_ip, 123456))

        sock_mock = MagicMock()
        sock_mock.socket = MagicMock(return_value=sck)
        sock_mock.gethostbyname = MagicMock(return_value=expected_hostname)

        return sock_mock

@skipIf(NO_MOCK, NO_MOCK_REASON)
@skipIf(pytest is None, 'PyTest is missing')
class SSDPBaseTestCase(TestCase, Mocks):
    '''
    TestCase for SSDP-related parts.
    '''

    @staticmethod
    def exception_generic(*args, **kwargs):
        '''
        Side effect
        :return:
        '''
        raise Exception('some network error')

    @staticmethod
    def exception_attr_error(*args, **kwargs):
        '''
        Side effect
        :return:
        '''
        raise AttributeError('attribute error: {0}. {1}'.format(args, kwargs))

    @patch('salt.utils.ssdp._json', None)
    @patch('salt.utils.ssdp.asyncio', None)
    def test_base_avail(self):
        '''
        Test SSDP base class availability method.
        :return:
        '''
        base = ssdp.SSDPBase()
        assert not base._is_available()

        with patch('salt.utils.ssdp._json', True):
            assert not base._is_available()

        with patch('salt.utils.ssdp.asyncio', True):
            assert not base._is_available()

        with patch('salt.utils.ssdp._json', True), patch('salt.utils.ssdp.asyncio', True):
            assert base._is_available()

    def test_base_protocol_settings(self):
        '''
        Tests default constants data.
        :return:
        '''
        base = ssdp.SSDPBase()
        v_keys = ['signature', 'answer', 'port', 'listen_ip', 'timeout']
        v_vals = ['__salt_master_service', {}, 4520, '0.0.0.0', 3]
        for key in v_keys:
            assert key in base.DEFAULTS

        for key in base.DEFAULTS.keys():
            assert key in v_keys

        for key, value in zip(v_keys, v_vals):
            assert base.DEFAULTS[key] == value

    def test_base_self_ip(self):
        '''
        Test getting self IP method.

        :return:
        '''
        base = ssdp.SSDPBase()
        expected_ip = '192.168.1.10'
        expected_host = 'oxygen'
        sock_mock = self.get_socket_mock(expected_ip, expected_host)

        with patch('salt.utils.ssdp.socket', sock_mock):
            assert base.get_self_ip() == expected_ip

        sock_mock.socket().getsockname.side_effect = SSDPBaseTestCase.exception_generic
        with patch('salt.utils.ssdp.socket', sock_mock):
            assert base.get_self_ip() == expected_host

@skipIf(NO_MOCK, NO_MOCK_REASON)
@skipIf(pytest is None, 'PyTest is missing')
class SSDPFactoryTestCase(TestCase):
    '''
    Test socket protocol
    '''
    @patch('salt.utils.ssdp.socket.gethostbyname', MagicMock(return_value='10.10.10.10'))
    def test_attr_check(self):
        '''
        Tests attributes are set to the base class

        :return:
        '''
        config = {
            ssdp.SSDPBase.SIGNATURE: '-signature-',
            ssdp.SSDPBase.ANSWER: {'this-is': 'the-answer'}
        }
        factory = ssdp.SSDPFactory(**config)
        for attr in [ssdp.SSDPBase.SIGNATURE, ssdp.SSDPBase.ANSWER]:
            assert hasattr(factory, attr)
            assert getattr(factory, attr) == config[attr]
        assert not factory.disable_hidden
        assert factory.my_ip == '10.10.10.10'

    def test_transport_sendto_success(self):
        '''
        Test transport send_to.

        :return:
        '''
        transport = MagicMock()
        log = MagicMock()
        factory = ssdp.SSDPFactory()
        with patch.object(factory, 'transport', transport), patch.object(factory, 'log', log):
            data = {'some': 'data'}
            addr = '10.10.10.10'
            factory._sendto(data=data, addr=addr)
            assert factory.transport.sendto.called
            assert factory.transport.sendto.mock_calls[0][1][0]['some'] == 'data'
            assert factory.transport.sendto.mock_calls[0][2]['addr'] == '10.10.10.10'
            assert factory.log.debug.called
            assert factory.log.debug.mock_calls[0][1][0] == 'Sent successfully'

    @patch('salt.utils.ssdp.time.sleep', MagicMock())
    def test_transport_sendto_retry(self):
        '''
        Test transport send_to.

        :return:
        '''
        transport = MagicMock()
        transport.sendto = MagicMock(side_effect=SSDPBaseTestCase.exception_attr_error)
        log = MagicMock()
        factory = ssdp.SSDPFactory()
        with patch.object(factory, 'transport', transport), patch.object(factory, 'log', log):
            data = {'some': 'data'}
            addr = '10.10.10.10'
            factory._sendto(data=data, addr=addr)
            assert factory.transport.sendto.called
            assert ssdp.time.sleep.called
            assert ssdp.time.sleep.call_args[0][0] > 0 and ssdp.time.sleep.call_args[0][0] < 0.5
            assert factory.log.debug.called
            assert 'Permission error' in factory.log.debug.mock_calls[0][1][0]

    def test_datagram_signature_bad(self):
        '''
        Test datagram_received on bad signature

        :return:
        '''
        factory = ssdp.SSDPFactory()
        data = 'nonsense'
        addr = '10.10.10.10', 'foo.suse.de'

        with patch.object(factory, 'log', MagicMock()):
            factory.datagram_received(data=data, addr=addr)
            assert factory.log.debug.called
            assert 'Received bad signature from' in factory.log.debug.call_args[0][0]
            assert factory.log.debug.call_args[0][1] == addr[0]
            assert factory.log.debug.call_args[0][2] == addr[1]

    def test_datagram_signature_wrong_timestamp_quiet(self):
        '''
        Test datagram receives a wrong timestamp (no reply).

        :return:
        '''
        factory = ssdp.SSDPFactory()
        data = '{}nonsense'.format(ssdp.SSDPBase.DEFAULTS[ssdp.SSDPBase.SIGNATURE])
        addr = '10.10.10.10', 'foo.suse.de'
        with patch.object(factory, 'log', MagicMock()), patch.object(factory, '_sendto', MagicMock()):
            factory.datagram_received(data=data, addr=addr)
            assert factory.log.debug.called
            assert 'Received invalid timestamp in package' in factory.log.debug.call_args[0][0]
            assert not factory._sendto.called

    def test_datagram_signature_wrong_timestamp_reply(self):
        '''
        Test datagram receives a wrong timestamp.

        :return:
        '''
        factory = ssdp.SSDPFactory()
        factory.disable_hidden = True
        signature = ssdp.SSDPBase.DEFAULTS[ssdp.SSDPBase.SIGNATURE]
        data = '{}nonsense'.format(signature)
        addr = '10.10.10.10', 'foo.suse.de'
        with patch.object(factory, 'log', MagicMock()), patch.object(factory, '_sendto', MagicMock()):
            factory.datagram_received(data=data, addr=addr)
            assert factory.log.debug.called
            assert 'Received invalid timestamp in package' in factory.log.debug.call_args[0][0]
            assert factory._sendto.called
            assert '{}:E:Invalid timestamp'.format(signature) == factory._sendto.call_args[0][0]

    def test_datagram_signature_outdated_timestamp_quiet(self):
        '''
        Test if datagram processing reacts on outdated message (more than 20 seconds). Quiet mode.
        :return:
        '''
        factory = ssdp.SSDPFactory()
        signature = ssdp.SSDPBase.DEFAULTS[ssdp.SSDPBase.SIGNATURE]
        data = '{}{}'.format(signature, '1516623820')
        addr = '10.10.10.10', 'foo.suse.de'

        ahead_dt = datetime.datetime.fromtimestamp(1516623841)
        curnt_dt = datetime.datetime.fromtimestamp(1516623820)
        delta = datetime.timedelta(0, 20)
        with patch.object(factory, 'log', MagicMock()), patch.object(factory, '_sendto'), \
             patch('salt.utils.ssdp.datetime.datetime', MagicMock()), \
             patch('salt.utils.ssdp.datetime.datetime.now', MagicMock(return_value=ahead_dt)), \
             patch('salt.utils.ssdp.datetime.datetime.fromtimestamp', MagicMock(return_value=curnt_dt)), \
             patch('salt.utils.ssdp.datetime.timedelta', MagicMock(return_value=delta)):
            factory.datagram_received(data=data, addr=addr)
            assert factory.log.debug.called
            assert not factory.disable_hidden
            assert not factory._sendto.called
            assert 'Received outdated package' in factory.log.debug.call_args[0][0]

    def test_datagram_signature_outdated_timestamp_reply(self):
        '''
        Test if datagram processing reacts on outdated message (more than 20 seconds). Reply mode.
        :return:
        '''
        factory = ssdp.SSDPFactory()
        factory.disable_hidden = True
        signature = ssdp.SSDPBase.DEFAULTS[ssdp.SSDPBase.SIGNATURE]
        data = '{}{}'.format(signature, '1516623820')
        addr = '10.10.10.10', 'foo.suse.de'

        ahead_dt = datetime.datetime.fromtimestamp(1516623841)
        curnt_dt = datetime.datetime.fromtimestamp(1516623820)
        delta = datetime.timedelta(0, 20)
        with patch.object(factory, 'log', MagicMock()), patch.object(factory, '_sendto'), \
             patch('salt.utils.ssdp.datetime.datetime', MagicMock()), \
             patch('salt.utils.ssdp.datetime.datetime.now', MagicMock(return_value=ahead_dt)), \
             patch('salt.utils.ssdp.datetime.datetime.fromtimestamp', MagicMock(return_value=curnt_dt)), \
             patch('salt.utils.ssdp.datetime.timedelta', MagicMock(return_value=delta)):
            factory.datagram_received(data=data, addr=addr)
            assert factory.log.debug.called
            assert factory.disable_hidden
            assert factory._sendto.called
            assert 'Received outdated package' in factory.log.debug.call_args[0][0]
<|endoftext|>


<commit_before>import unittest
import mock
import pyglet.clock

class ClockTestCase(unittest.TestCase):
    """Test clock using dummy time keeper

    not tested:
      positional and named arguments
    """

    def setUp(self):
        self.interval = .001
        self.time = 0
        self.callback_a = mock.Mock()
        self.callback_b = mock.Mock()
        self.callback_c = mock.Mock()
        self.callback_d = mock.Mock()
        self.clock = pyglet.clock.Clock(time_function=lambda: self.time)
        #import pyglet.clock_
        #self.clock = pyglet.clock_.Clock(time_function=lambda: self.time)

    def advance_clock(self, dt=1):
        """simulate the passage of time like a real clock would"""
        frames = 0
        end = self.time + dt
        while self.time < end:
            frames += 1
            self.time += self.interval
            self.clock.tick()
        self.time = round(self.time, 0)
        return frames

    def test_schedule(self):
        self.clock.schedule(self.callback_a)
        frames = self.advance_clock()
        self.assertEqual(self.callback_a.call_count, frames)

    def test_schedule_once(self):
        self.clock.schedule_once(self.callback_a, 1)
        self.advance_clock(2)
        self.assertEqual(self.callback_a.call_count, 1)

    def test_schedule_once_multiple(self):
        self.clock.schedule_once(self.callback_a, 1)
        self.clock.schedule_once(self.callback_b, 2)
        self.advance_clock(2)
        self.assertEqual(self.callback_a.call_count, 1)
        self.assertEqual(self.callback_b.call_count, 1)

    def test_schedule_interval(self):
        self.clock.schedule_interval(self.callback_a, 1)
        self.advance_clock(2)
        self.assertEqual(self.callback_a.call_count, 2)

    def test_schedule_interval_multiple(self):
        self.clock.schedule_interval(self.callback_a, 1)
        self.clock.schedule_interval(self.callback_b, 1)
        self.advance_clock(2)
        self.assertEqual(self.callback_a.call_count, 2)
        self.assertEqual(self.callback_b.call_count, 2)

    def test_schedule_interval_soft(self):
        self.clock.schedule_interval_soft(self.callback_a, 1)
        self.advance_clock(2)
        self.assertEqual(self.callback_a.call_count, 2)

    def test_schedule_interval_soft_multiple(self):
        self.clock.schedule_interval(self.callback_a, 1)
        self.clock.schedule_interval_soft(self.callback_b, 1)
        self.clock.schedule_interval_soft(self.callback_b, 1)
        next_ts = set(i.next_ts for i in self.clock._scheduled_items)
        self.assertEqual(len(next_ts), 3)
        self.advance_clock()
        self.assertEqual(self.callback_a.call_count, 1)
        self.assertEqual(self.callback_b.call_count, 2)

    def test_schedule_unschedule(self):
        self.clock.schedule(self.callback_a)
        self.clock.unschedule(self.callback_a)
        self.advance_clock()
        self.assertEqual(self.callback_a.call_count, 0)

    def test_schedule_once_unschedule(self):
        self.clock.schedule_once(self.callback_a, 1)
        self.clock.unschedule(self.callback_a)
        self.advance_clock()
        self.assertEqual(self.callback_a.call_count, 0)

    def test_schedule_interval_unschedule(self):
        self.clock.schedule_interval(self.callback_a, 1)
        self.clock.unschedule(self.callback_a)
        self.advance_clock()
        self.assertEqual(self.callback_a.call_count, 0)

    def test_schedule_interval_soft_unschedule(self):
        self.clock.schedule_interval_soft(self.callback_a, 1)
        self.clock.unschedule(self.callback_a)
        self.advance_clock()
        self.assertEqual(self.callback_a.call_count, 0)

    def test_unschedule_removes_all(self):
        self.clock.schedule(self.callback_a)
        self.clock.schedule_once(self.callback_a, 1)
        self.clock.schedule_interval(self.callback_a, 1)
        self.clock.schedule_interval_soft(self.callback_a, 1)
        self.clock.schedule(self.callback_a)
        self.clock.schedule(self.callback_b)
        self.clock.unschedule(self.callback_a)
        frames = self.advance_clock(10)
        self.assertEqual(self.callback_a.call_count, 0)
        self.assertEqual(self.callback_b.call_count, frames)

    def test_schedule_will_not_call_function(self):
        self.clock.schedule(self.callback_a)
        self.assertEqual(self.callback_a.call_count, 0)
        self.clock.schedule_once(self.callback_a, 0)
        self.assertEqual(self.callback_a.call_count, 0)
        self.clock.schedule_interval(self.callback_a, 1)
        self.assertEqual(self.callback_a.call_count, 0)
        self.clock.schedule_interval_soft(self.callback_a, 1)
        self.assertEqual(self.callback_a.call_count, 0)

    def test_unschedule_will_not_call_function(self):
        self.clock.schedule(self.callback_a)
        self.clock.unschedule(self.callback_a)
        self.assertEqual(self.callback_a.call_count, 0)
        self.clock.schedule_once(self.callback_a, 0)
        self.clock.unschedule(self.callback_a)
        self.assertEqual(self.callback_a.call_count, 0)
        self.clock.schedule_interval(self.callback_a, 1)
        self.clock.unschedule(self.callback_a)
        self.assertEqual(self.callback_a.call_count, 0)
        self.clock.schedule_interval_soft(self.callback_a, 1)
        self.clock.unschedule(self.callback_a)
        self.assertEqual(self.callback_a.call_count, 0)

    def test_unschedule_will_not_fail_if_already_unscheduled(self):
        self.clock.schedule(self.callback_a)
        self.clock.unschedule(self.callback_a)
        self.clock.unschedule(self.callback_a)
        self.clock.schedule_once(self.callback_a, 0)
        self.clock.unschedule(self.callback_a)
        self.clock.unschedule(self.callback_a)
        self.clock.schedule_interval(self.callback_a, 1)
        self.clock.unschedule(self.callback_a)
        self.clock.unschedule(self.callback_a)
        self.clock.schedule_interval_soft(self.callback_a, 1)
        self.clock.unschedule(self.callback_a)
        self.clock.unschedule(self.callback_a)

    def test_call_sched_return_True_if_called_functions(self):
        self.clock.schedule(self.callback_a)
        self.assertTrue(self.clock.call_scheduled_functions(0))

    def test_call_sched_return_True_if_called_functions_interval(self):
        self.clock.schedule_once(self.callback_a, 1)
        self.assertFalse(self.clock.call_scheduled_functions(0))
        self.clock.set_time(1)
        self.assertTrue(self.clock.call_scheduled_functions(0))

    def test_call_sched_return_False_if_no_called_functions(self):
        self.assertFalse(self.clock.call_scheduled_functions(0))

    def test_tick_return_last_delta(self):
        self.assertEqual(self.clock.tick(), 0)
        self.time = 1
        self.assertEqual(self.clock.tick(), 1)
        self.time = 3
        self.assertEqual(self.clock.tick(), 2)

    def test_get_sleep_time_None_if_no_items(self):
        self.assertIsNone(self.clock.get_sleep_time())

    def test_get_sleep_time_can_sleep(self):
        self.clock.schedule_once(self.callback_a, 3)
        self.clock.schedule_once(self.callback_b, 1)
        self.clock.schedule_once(self.callback_c, 6)
        self.clock.schedule_once(self.callback_d, 7)
        self.assertEqual(self.clock.get_sleep_time(), 1)
        self.advance_clock()
        self.assertEqual(self.clock.get_sleep_time(), 2)
        self.advance_clock(2)
        self.assertEqual(self.clock.get_sleep_time(), 3)
        self.advance_clock(3)
        self.assertEqual(self.clock.get_sleep_time(), 1)

    def test_get_sleep_time_cannot_sleep(self):
        self.clock.schedule(self.callback_a)
        self.clock.schedule_once(self.callback_b, 1)
        self.assertEqual(self.clock.get_sleep_time(), 0)

    def test_remove_item_during_processing_tasks(self):
        def suicidal_event(dt, sock):
            sock()
            self.clock.unschedule(suicidal_event)

        sock = mock.Mock()
        self.clock.schedule(suicidal_event, sock)
        self.advance_clock()
        self.assertEqual(sock.call_count, 1)

    def test_slow_clock(self):
        """pyglet's clock will not make up for lost time.  in this case, the
        interval scheduled for callback_[bcd] is 1, and 2 seconds have passed.
        since pyglet won't make up for lost time, they are only called once.
        """
        self.clock.schedule(self.callback_a)
        self.clock.schedule_once(self.callback_b, 1)
        self.clock.schedule_interval(self.callback_c, 1)
        self.clock.schedule_interval_soft(self.callback_d, 1)
        self.time = 2
        self.clock.tick()
        self.assertEqual(self.callback_a.call_count, 1)
        self.assertEqual(self.callback_b.call_count, 1)
        self.assertEqual(self.callback_c.call_count, 1)
        self.assertEqual(self.callback_d.call_count, 1)

    def test_get_interval(self):
        self.assertEqual(self.clock.get_interval(), 0)
        self.advance_clock(100)
        self.assertEqual(round(self.clock.get_interval(), 10), self.interval)
<commit_msg>test another corner case with the clock (slow/lagged time)<commit_after>import unittest
import mock
import pyglet.clock

class ClockTestCase(unittest.TestCase):
    """Test clock using dummy time keeper

    not tested:
      positional and named arguments
    """

    def setUp(self):
        self.interval = .001
        self.time = 0
        self.callback_a = mock.Mock()
        self.callback_b = mock.Mock()
        self.callback_c = mock.Mock()
        self.callback_d = mock.Mock()
        self.clock = pyglet.clock.Clock(time_function=lambda: self.time)

    def advance_clock(self, dt=1):
        """simulate the passage of time like a real clock would"""
        frames = 0
        end = self.time + dt
        while self.time < end:
            frames += 1
            self.time += self.interval
            self.clock.tick()
        self.time = round(self.time, 0)
        return frames

    def test_schedule(self):
        self.clock.schedule(self.callback_a)
        frames = self.advance_clock()
        self.assertEqual(self.callback_a.call_count, frames)

    def test_schedule_once(self):
        self.clock.schedule_once(self.callback_a, 1)
        self.advance_clock(2)
        self.assertEqual(self.callback_a.call_count, 1)

    def test_schedule_once_multiple(self):
        self.clock.schedule_once(self.callback_a, 1)
        self.clock.schedule_once(self.callback_b, 2)
        self.advance_clock(2)
        self.assertEqual(self.callback_a.call_count, 1)
        self.assertEqual(self.callback_b.call_count, 1)

    def test_schedule_interval(self):
        self.clock.schedule_interval(self.callback_a, 1)
        self.advance_clock(2)
        self.assertEqual(self.callback_a.call_count, 2)

    def test_schedule_interval_multiple(self):
        self.clock.schedule_interval(self.callback_a, 1)
        self.clock.schedule_interval(self.callback_b, 1)
        self.advance_clock(2)
        self.assertEqual(self.callback_a.call_count, 2)
        self.assertEqual(self.callback_b.call_count, 2)

    def test_schedule_interval_soft(self):
        self.clock.schedule_interval_soft(self.callback_a, 1)
        self.advance_clock(2)
        self.assertEqual(self.callback_a.call_count, 2)

    def test_schedule_interval_soft_multiple(self):
        self.clock.schedule_interval(self.callback_a, 1)
        self.clock.schedule_interval_soft(self.callback_b, 1)
        self.clock.schedule_interval_soft(self.callback_b, 1)
        next_ts = set(i.next_ts for i in self.clock._scheduled_items)
        self.assertEqual(len(next_ts), 3)
        self.advance_clock()
        self.assertEqual(self.callback_a.call_count, 1)
        self.assertEqual(self.callback_b.call_count, 2)

    def test_schedule_unschedule(self):
        self.clock.schedule(self.callback_a)
        self.clock.unschedule(self.callback_a)
        self.advance_clock()
        self.assertEqual(self.callback_a.call_count, 0)

    def test_schedule_once_unschedule(self):
        self.clock.schedule_once(self.callback_a, 1)
        self.clock.unschedule(self.callback_a)
        self.advance_clock()
        self.assertEqual(self.callback_a.call_count, 0)

    def test_schedule_interval_unschedule(self):
        self.clock.schedule_interval(self.callback_a, 1)
        self.clock.unschedule(self.callback_a)
        self.advance_clock()
        self.assertEqual(self.callback_a.call_count, 0)

    def test_schedule_interval_soft_unschedule(self):
        self.clock.schedule_interval_soft(self.callback_a, 1)
        self.clock.unschedule(self.callback_a)
        self.advance_clock()
        self.assertEqual(self.callback_a.call_count, 0)

    def test_unschedule_removes_all(self):
        self.clock.schedule(self.callback_a)
        self.clock.schedule_once(self.callback_a, 1)
        self.clock.schedule_interval(self.callback_a, 1)
        self.clock.schedule_interval_soft(self.callback_a, 1)
        self.clock.schedule(self.callback_a)
        self.clock.schedule(self.callback_b)
        self.clock.unschedule(self.callback_a)
        frames = self.advance_clock(10)
        self.assertEqual(self.callback_a.call_count, 0)
        self.assertEqual(self.callback_b.call_count, frames)

    def test_schedule_will_not_call_function(self):
        self.clock.schedule(self.callback_a)
        self.assertEqual(self.callback_a.call_count, 0)
        self.clock.schedule_once(self.callback_a, 0)
        self.assertEqual(self.callback_a.call_count, 0)
        self.clock.schedule_interval(self.callback_a, 1)
        self.assertEqual(self.callback_a.call_count, 0)
        self.clock.schedule_interval_soft(self.callback_a, 1)
        self.assertEqual(self.callback_a.call_count, 0)

    def test_unschedule_will_not_call_function(self):
        self.clock.schedule(self.callback_a)
        self.clock.unschedule(self.callback_a)
        self.assertEqual(self.callback_a.call_count, 0)
        self.clock.schedule_once(self.callback_a, 0)
        self.clock.unschedule(self.callback_a)
        self.assertEqual(self.callback_a.call_count, 0)
        self.clock.schedule_interval(self.callback_a, 1)
        self.clock.unschedule(self.callback_a)
        self.assertEqual(self.callback_a.call_count, 0)
        self.clock.schedule_interval_soft(self.callback_a, 1)
        self.clock.unschedule(self.callback_a)
        self.assertEqual(self.callback_a.call_count, 0)

    def test_unschedule_will_not_fail_if_already_unscheduled(self):
        self.clock.schedule(self.callback_a)
        self.clock.unschedule(self.callback_a)
        self.clock.unschedule(self.callback_a)
        self.clock.schedule_once(self.callback_a, 0)
        self.clock.unschedule(self.callback_a)
        self.clock.unschedule(self.callback_a)
        self.clock.schedule_interval(self.callback_a, 1)
        self.clock.unschedule(self.callback_a)
        self.clock.unschedule(self.callback_a)
        self.clock.schedule_interval_soft(self.callback_a, 1)
        self.clock.unschedule(self.callback_a)
        self.clock.unschedule(self.callback_a)

    def test_call_sched_return_True_if_called_functions(self):
        self.clock.schedule(self.callback_a)
        self.assertTrue(self.clock.call_scheduled_functions(0))

    def test_call_sched_return_True_if_called_functions_interval(self):
        self.clock.schedule_once(self.callback_a, 1)
        self.assertFalse(self.clock.call_scheduled_functions(0))
        self.clock.set_time(1)
        self.assertTrue(self.clock.call_scheduled_functions(0))

    def test_call_sched_return_False_if_no_called_functions(self):
        self.assertFalse(self.clock.call_scheduled_functions(0))

    def test_tick_return_last_delta(self):
        self.assertEqual(self.clock.tick(), 0)
        self.time = 1
        self.assertEqual(self.clock.tick(), 1)
        self.time = 3
        self.assertEqual(self.clock.tick(), 2)

    def test_get_sleep_time_None_if_no_items(self):
        self.assertIsNone(self.clock.get_sleep_time())

    def test_get_sleep_time_can_sleep(self):
        self.clock.schedule_once(self.callback_a, 3)
        self.clock.schedule_once(self.callback_b, 1)
        self.clock.schedule_once(self.callback_c, 6)
        self.clock.schedule_once(self.callback_d, 7)
        self.assertEqual(self.clock.get_sleep_time(), 1)
        self.advance_clock()
        self.assertEqual(self.clock.get_sleep_time(), 2)
        self.advance_clock(2)
        self.assertEqual(self.clock.get_sleep_time(), 3)
        self.advance_clock(3)
        self.assertEqual(self.clock.get_sleep_time(), 1)

    def test_get_sleep_time_cannot_sleep(self):
        self.clock.schedule(self.callback_a)
        self.clock.schedule_once(self.callback_b, 1)
        self.assertEqual(self.clock.get_sleep_time(), 0)

    def test_remove_item_during_processing_tasks(self):
        def suicidal_event(dt, sock):
            sock()
            self.clock.unschedule(suicidal_event)

        sock = mock.Mock()
        self.clock.schedule(suicidal_event, sock)
        self.advance_clock()
        self.assertEqual(sock.call_count, 1)

    def test_slow_clock_doesnt_repeat_calls(self):
        """pyglet's clock will not make up for lost time.  in this case, the
        interval scheduled for callback_[bcd] is 1, and 2 seconds have passed.
        since pyglet won't make up for lost time, they are only called once.
        """
        self.clock.schedule(self.callback_a)
        self.clock.schedule_once(self.callback_b, 1)
        self.clock.schedule_interval(self.callback_c, 1)
        self.clock.schedule_interval_soft(self.callback_d, 1)

        # simulate slow clock
        self.time = 2
        self.clock.tick()

        self.assertEqual(self.callback_a.call_count, 1)
        self.assertEqual(self.callback_b.call_count, 1)
        self.assertEqual(self.callback_c.call_count, 1)
        self.assertEqual(self.callback_d.call_count, 1)

    def test_slow_clock_reschedules(self):
        """pyglet's clock will not make up for lost time.  in this case, the
        interval scheduled for callback_[bcd] is 1, and 2 seconds have passed.
        since pyglet won't make up for lost time, they are only called once.
        this test verifies that missed events are rescheduled and executed later
        """
        self.clock.schedule(self.callback_a)
        self.clock.schedule_once(self.callback_b, 1)
        self.clock.schedule_interval(self.callback_c, 1)
        self.clock.schedule_interval_soft(self.callback_d, 1)

        # simulate slow clock
        self.time = 2
        self.clock.tick()

        # simulate a proper clock
        frames = self.advance_clock()

        # make sure our clock is at 3 seconds
        self.assertEqual(self.time, 3)

        # the +1 is the call during the slow clock period
        self.assertEqual(self.callback_a.call_count, frames + 1)

        # only scheduled to happen once
        self.assertEqual(self.callback_b.call_count, 1)

        # 2 because they 'missed' a call when the clock lagged
        # with a good clock, this would be 3
        self.assertEqual(self.callback_c.call_count, 2)
        self.assertEqual(self.callback_d.call_count, 2)

    def test_get_interval(self):
        self.assertEqual(self.clock.get_interval(), 0)
        self.advance_clock(100)
        self.assertEqual(round(self.clock.get_interval(), 10), self.interval)
<|endoftext|>


<commit_before>from flask import make_response
from flask import jsonify
from flask import Blueprint
from flask import request
from pymongo import MongoClient
from bson.objectid import ObjectId
import sender

client = MongoClient()
db = client.menudb
menu_items = db.menu_items
order = Blueprint('order', __name__, template_folder = 'templates')
print('dog')
@order.route('',methods = ['POST'])
def index():
 #destination_num = data.get(destination)
  msg = ""
  phone_num = request.form.get('number')
  print('cat')
  food_id = request.form.get('item_id')
  try:
     side_id = request.form.get('side_id')
  except:
     pass
  special_requests = request.form.get('special')
  print('crunch time')
  for items in menu_items.find():
    print('d')
    if food_id == str(items['_id']):
      msg = items['item']
  for dog in menu_items.find():
    if side_id == str(items['_id']):
      side = items['item']
      msg = side + msg
  if(len(msg)<=0):
    return jsonify({'ERROR':"ID not found"})
    to_send = msg + special
    rtn = sender.send_text(phone_num, phone_num,to_send)
    if (rtn != 'success'):
      return jonify({'ERROR':'a serious error has occurred, please inform creators of flaw'})
    else:
      return jsonify({'success':'expect your food shortly!'})
<commit_msg>fixes to orders<commit_after>from flask import make_response
from flask import jsonify
from flask import Blueprint
from flask import request
from pymongo import MongoClient
from bson.objectid import ObjectId
import sender

client = MongoClient()
db = client.menudb
menu_items = db.menu_items
order = Blueprint('order', __name__, template_folder = 'templates')
print('dog')
@order.route('',methods = ['POST'])
def index():
 #destination_num = data.get(destination)
  msg = ""
  phone_num = request.form.get('number')
  print('cat')
  food_id = request.form.get('item_id')
  try:
     side_id = request.form.get('side_id')
  except:
     pass
  special_requests = request.form.get('special')
  print('crunch time')
  for items in menu_items.find():
    print('d')
    if food_id == str(items['_id']):
      msg = items['item']
  for dog in menu_items.find():
    if side_id == str(items['_id']):
      side = items['item']
      msg = side + msg
  if(len(msg)<=0):
    return jsonify({'ERROR':"ID not found"})
  to_send = msg + special_requests
  rtn = sender.send_text(phone_num, phone_num,to_send)
  if (rtn != 'success'):
    return jsonify({'ERROR':'a serious error has occurred, please inform creators of flaw'})
  else:
    return jsonify({'success':'expect your food shortly!'})
<|endoftext|>


<commit_before>"""Test core functions."""

import numpy as np
from tetrahydra.core import closure, perturb, power

def test_closure():
    """Test closure operator."""
    # Given
    data = np.random.random([2, 3])
    expected = np.ones(2)
    # When
    output = np.sum(closure(data), axis=1)
    # Then
    assert output == pytest.approx(expected)

def test_perturb():
    """Test perturbation operator."""
    # Given
    data = np.random.random([2, 3])
    p_vals = np.array([1., 2., 3.])  # perturbation values
    expected = data * p_vals
    # When
    output = perturb(data, p_vals, reclose=False)
    # Then
    assert np.all(output == expected)

def test_power():
    """Test powering operator."""
    # Given
    data = np.random.random([2, 3])
    expected = data**np.pi
    # When
    output = power(data, np.pi, reclose=False)
    # Then
    assert np.all(output == expected)
<commit_msg>Revert prev commit in this file.<commit_after>"""Test core functions."""

import pytest
import numpy as np
from tetrahydra.core import closure, perturb, power

def test_closure():
    """Test closure operator."""
    # Given
    data = np.random.random([2, 3])
    expected = np.ones(2)
    # When
    output = np.sum(closure(data), axis=1)
    # Then
    assert output == pytest.approx(expected)

def test_perturb():
    """Test perturbation operator."""
    # Given
    data = np.random.random([2, 3])
    p_vals = np.array([1., 2., 3.])  # perturbation values
    expected = data * p_vals
    # When
    output = perturb(data, p_vals, reclose=False)
    # Then
    assert np.all(output == expected)

def test_power():
    """Test powering operator."""
    # Given
    data = np.random.random([2, 3])
    expected = data**np.pi
    # When
    output = power(data, np.pi, reclose=False)
    # Then
    assert np.all(output == expected)
<|endoftext|>